Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Created a trigger for jenkins to automaticaly build example-apps #199

Merged
merged 4 commits into from
Jun 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 0 additions & 8 deletions scripts/jenkins/jenkins-REST-client.sh
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,6 @@ function createJob() {
exit $EXIT_STATUS
fi

# Call "Scan now", triggering initialization of Job folder from SCMM Namespace
SCAN_STATUS=$(curlJenkins --fail -L -o /dev/null --write-out '%{http_code}' \
-X POST "${JENKINS_URL}/job/${JOB_NAME}/build?delay=0") && EXIT_STATUS=$? || EXIT_STATUS=$?
if [ $EXIT_STATUS != 0 ]
then
echo "WARNING: Initializing Jenkins Jobs failed with status code ${SCAN_STATUS}. Job folders might be empty."
fi

printStatus "${STATUS}"
}

Expand Down
4 changes: 4 additions & 0 deletions src/main/groovy/com/cloudogu/gitops/features/Jenkins.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -124,5 +124,9 @@ class Jenkins extends Feature {
'credentials for accessing the docker-registry')
}
}

// Once everything is set up, start the jobs.
jobManger.startJob('example-apps')

}
}
8 changes: 6 additions & 2 deletions src/main/groovy/com/cloudogu/gitops/jenkins/ApiClient.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -35,21 +35,25 @@ class ApiClient {

String runScript(String code) {
log.trace("Running groovy script in Jenkins: {}", code)
def response = sendRequestWithCrumb("scriptText", new FormBody.Builder().add("script", code).build())
def response = postRequestWithCrumb("scriptText", new FormBody.Builder().add("script", code).build())
if (response.code() != 200) {
throw new RuntimeException("Could not run script. Status code ${response.code()}")
}

return response.body().string()
}

Response sendRequestWithCrumb(String url, FormBody postData) {
Response postRequestWithCrumb(String url, RequestBody postData = null) {
return sendRequestWithRetries {
Request.Builder request = buildRequest(url)
.header("Jenkins-Crumb", getCrumb())

if (postData != null) {
request.method("POST", postData)
} else {
// Explicitly set empty body. Otherwise okhttp sends GET
RequestBody emptyBody = RequestBody.create("", null)
request.method("POST", emptyBody)
}

request.build()
Expand Down
14 changes: 12 additions & 2 deletions src/main/groovy/com/cloudogu/gitops/jenkins/JobManager.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ class JobManager {
}

void createCredential(String jobName, String id, String username, String password, String description) {
def response = apiClient.sendRequestWithCrumb(
def response = apiClient.postRequestWithCrumb(
"job/$jobName/credentials/store/folder/domain/_/createCredentials",
new FormBody.Builder()
.add("json", JsonOutput.toJson([
Expand All @@ -31,7 +31,7 @@ class JobManager {
)

if (response.code() != 200) {
throw new RuntimeException("Could not create credential. StatusCode: ${response.code()}")
throw new RuntimeException("Could not create credential id=$id,job=$jobName. StatusCode: ${response.code()}")
}
}

Expand All @@ -48,4 +48,14 @@ class JobManager {
throw new RuntimeException("Could not delete job $name")
}
}

void startJob(String jobName) {

def response= apiClient.postRequestWithCrumb(
"job/$jobName/build?delay=0sec")

if (response.code() != 200) {
throw new RuntimeException("Could not trigger build of Jenkins job: $jobName. StatusCode: ${response.code()}")
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -60,12 +60,12 @@ class ApiClientTest {
webServer.enqueue(new MockResponse())

def client = new ApiClient(webServer.url('jenkins').toString(), 'admin', 'admin', new OkHttpClient())
client.sendRequestWithCrumb("foobar", null)
client.postRequestWithCrumb("foobar")

assertThat(webServer.requestCount).isEqualTo(2)
webServer.takeRequest() // crumb
def request = webServer.takeRequest()
assertThat(request.method).isEqualTo("GET")
assertThat(request.method).isEqualTo("POST")
assertThat(request.headers.get("Jenkins-Crumb")).isEqualTo("the-crumb")
}

Expand All @@ -75,7 +75,7 @@ class ApiClientTest {
webServer.enqueue(new MockResponse())

def client = new ApiClient(webServer.url('jenkins').toString(), 'admin', 'admin', new OkHttpClient())
client.sendRequestWithCrumb("foobar", new FormBody.Builder().add('key', 'value with spaces').build())
client.postRequestWithCrumb("foobar", new FormBody.Builder().add('key', 'value with spaces').build())

assertThat(webServer.requestCount).isEqualTo(2)
webServer.takeRequest() // crumb
Expand Down
52 changes: 50 additions & 2 deletions src/test/groovy/com/cloudogu/gitops/jenkins/JobManagerTest.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -40,22 +40,70 @@ class JobManagerTest {
server.enqueue(new MockResponse().setBody('{"crumb":"the-crumb"}'))
server.enqueue(new MockResponse().setResponseCode(404))
def jobManager = new JobManager(new ApiClient(server.url("jenkins").toString(), 'admin', 'admin', new OkHttpClient()))
shouldFail(RuntimeException) {
def exception = shouldFail(RuntimeException) {
jobManager.createCredential('the-jobname', 'the-id', 'the-username', 'the-password', 'some description')
}
assertThat(exception.getMessage()).isEqualTo('Could not create credential id=the-id,job=the-jobname. StatusCode: 404')
} finally {
server.shutdown()
}
}

@Test
void 'starts job'() {
def server = new MockWebServer()
try {
server.enqueue(new MockResponse().setBody('{"crumb":"the-crumb"}'))
server.enqueue(new MockResponse().setResponseCode(200))
def jobManager = new JobManager(new ApiClient(server.url("jenkins").toString(), 'admin', 'admin', new OkHttpClient()))
jobManager.startJob('the-jobname')

assertThat(server.requestCount).isEqualTo(2)
server.takeRequest() // crumb
def request = server.takeRequest()
assertThat(request.path).isEqualTo("/jenkins/job/the-jobname/build?delay=0sec")
} finally {
server.shutdown()
}
}

@Test
void 'throw when starting job fails'() {
def server = new MockWebServer()
try {
server.enqueue(new MockResponse().setBody('{"crumb":"the-crumb"}'))
server.enqueue(new MockResponse().setResponseCode(400))
def jobManager = new JobManager(new ApiClient(server.url("jenkins").toString(), 'admin', 'admin', new OkHttpClient()))
def exception = shouldFail(RuntimeException) {
jobManager.startJob('the-jobname')
}
assertThat(exception.getMessage()).isEqualTo('Could not trigger build of Jenkins job: the-jobname. StatusCode: 400')
} finally {
server.shutdown()
}
}


@Test
void 'throws when job contains invalid characters'() {
def client = mock(ApiClient)
def jobManager = new JobManager(client)

shouldFail(RuntimeException) {
def exception = shouldFail(RuntimeException) {
jobManager.deleteJob("foo'foo")
}
assertThat(exception.getMessage()).isEqualTo('Job name cannot contain quotes.')
}

@Test
void 'throws when job deletion fails'() {
def client = mock(ApiClient)
def jobManager = new JobManager(client)

def exception = shouldFail(RuntimeException) {
jobManager.deleteJob("foo-foo")
}
assertThat(exception.getMessage()).isEqualTo('Could not delete job foo-foo')
}

@Test
Expand Down