Search code examples
gradlegroovyartifactory

Gradle task retry on failure


This is the task which fails intermittently and when it is manually rerun then it usually passes, I want to retry this task 3 times programmatically with a 5 second delay between each retry until declaring it as a genuine failure:-

uploadWildFlyWar {
    dependsOn createAndCopySasJar
    description 'Uploads the Wild-fly war'
    group 'publishing'
    repositories {
        mavenDeployer {
            repository(url: repoProps["remoteRepoUrlVal"]) {
                authentication(userName: repoProps["remoteRepoUsernameVal"], password: repoProps["remoteRepoPasswordVal"])
            }
        }
    }
}

Failure reason:-

What went wrong: Execution failed for task ':commons:src:uploadWildFlyWar'. Could not publish configuration 'wildFlyWar' Failed to deploy artifacts: Could not transfer artifact common:wildfly-startup:war:Branch-8.8.3.5c8e849b5 from/to remote (https://artifactory.abc.com/artifactory/cprms-build-branch): Failed to transfer file: https://artifactory.abc.com/artifactory/cprms-build-branch/com/ideas/cpro/common/wildfly-startup/Branch-8.8.3.5c8e849b5/wildfly-startup-Branch-8.8.3.5c8e849b5.war. Return code is: 502, ReasonPhrase: Bad Gateway.


Solution

  • Assuming you are not after a "clean" solution, you can hack-around it like this:

    // configure the uploadWildFlyWar task
    uploadWildFlyWar { task ->
        // remember the original task actions, copying them to a new list as the  returned list is a live view
        def actions = [*task.actions]
        // replace the original task actions with one own task action that does the error handling
        task.actions = [{
            // remembered exceptions from first two runs
            def exceptions = []
            // try up to three times
            for (i in 1..3) {
                try {
                    // execute the original actions
                    actions.each { it.execute(task) }
                    // if the original actions executed successfully, break the loop
                    break
                } catch (e) {
                    // on the third try if still throwing an exception
                    if (i == 3) {
                        // add the first two exceptions as "suppressed" ones
                        exceptions.each { e.addSuppressed(it) }
                        // rethrow the exception
                        throw e
                    } else {
                        // remember the first two exceptions
                        exceptions.add(e)
                        // wait 5 seconds before retrying
                        sleep 5000
                    }
                }
            }
        } as Action]
    }