Remote access API et Hudson
Hudson est un serveur d’intégration continue très riche. Parmi ses fonctionnalités, il expose l’ensemble des opérions de l’utilisateur par API. Dans un style REST, l’utilisateur va ainsi très facilement pouvoir réaliser les opérations CRUD sur un projet Hudson (nommée job Hudson), déclencher un build ou même récupérer le résultat des différents builds. Ce mécanisme est très puissant mais souvent inexploité par les utilisateurs de Hudson.
Pour connaître les opérations disponibles, il vous suffit de rajouter le path ‘api’ à votre URL Hudson dans le contexte courant comme
- http://localhost:8090/hudson/api/
- http://localhost:80980/hudson/job/test-gradle/api/
- http://localhost:8090/hudson/job/test-gradle/17/api/
Ci-dessous une suite d’exemple d’interactions, avec une implémentation Java basée sur la librairie Jakarta Commons HttpClient.
Pour s’authentifier
Utilisation de la ressource “hudsonBaseURL/j_acegi_security_check”
-
private HttpClient authenticate(String hudsonBaseURL) throws IOException, HttpException {
-
HttpClient client = new HttpClient();
-
PostMethod postMethodAuth = new PostMethod(hudsonBaseURL + “/j_acegi_security_check”);
-
NameValuePair[] postData = new NameValuePair[3];
-
postData[0] = new NameValuePair(“j_username”, “gboissinot”);
-
postData[1] = new NameValuePair(“j_password”, “zenika”);
-
postData[2] = new NameValuePair(“Login”, “login”);
-
postMethodAuth.addParameters(postData);
-
try {
-
int status= client.executeMethod(postMethodAuth);
-
System.out.println(status + “n“+ postMethodAuth.getResponseBodyAsString());
-
} finally {
-
postMethodAuth.releaseConnection();
-
}
-
return client;
-
}
Pour valider une URL Hudson
Vérification de la présence de l’entête HTTP “X-Hudson”
-
private boolean isHudsonURL (String hudsonBaseURL) throws IOException, HttpException {
-
HttpClient client= new HttpClient();
-
GetMethod getMethod = new GetMethod(hudsonBaseURL);
-
boolean isHudsonURL=false;
-
try {
-
int status = client.executeMethod(getMethod);
-
System.out.println(status + “n“+ getMethod.getResponseBodyAsString());
-
isHudsonURL=getMethod.getResponseHeader(“X-Hudson”)!=null;
-
} finally {
-
getMethod.releaseConnection();
-
}
-
return isHudsonURL;
-
}
Pour créer un job Hudson
Envoie du fichier de configuration du job config.xml à la ressource hudsonBaseURL/createItem avec le paramètre name=jobName
-
private void put(HttpClient client, String hudsonBaseURL,String jobName, File configFile) throws IOException, HttpException {
-
PostMethod postMethod = new PostMethod(hudsonBaseURL+ “/createItem?name=” + jobName);
-
postMethod.setRequestHeader(“Content-type”,“application/xml; charset=ISO-8859-1”);
-
postMethod.setRequestBody(new FileInputStream(configFile));
-
postMethod.setDoAuthentication(true);
-
try {
-
int status = client.executeMethod(postMethod);
-
System.out.println(status + “n“+ postMethod.getResponseBodyAsString());
-
} finally {
-
postMethod.releaseConnection();
-
}
-
}
Pour mettre à jour un job Hudson
Envoie à la ressource hudsonBaseURL/job/jobName/config.xml d’un nouveau fichier de configuration config.xml
-
private void update(HttpClient client, String hudsonBaseURL,String jobName, File updateFile) throws IOException, HttpException {
-
PostMethod postMethod = new PostMethod(hudsonBaseURL + “/job/”+ jobName + “/config.xml”);
-
postMethod.setRequestHeader(“Content-type”,“text/xml; charset=ISO-8859-1”);
-
postMethod.setRequestBody(new FileInputStream(updateFile));
-
try {
-
int status = client.executeMethod(postMethod);
-
System.out.println(status + “n“+ postMethod.getResponseBodyAsString());
-
} finally {
-
postMethod.releaseConnection();
-
}
-
}
Pour copier un job Hudson
Envoie d’une requête POST à la ressource hudsonBaseURL/createItem avec 3 paramètres name=newJobName, mode=copy et from=originJobName
-
private void copy(HttpClient client, String hudsonBaseURL,String originJobName, String newJobName) throws IOException, HttpException {
-
PostMethod postMethod = new PostMethod(hudsonBaseURL + “/createItem”);
-
NameValuePair n1 = new NameValuePair(“name”, newJobName);
-
NameValuePair n2 = new NameValuePair(“mode”, “copy”);
-
NameValuePair n3 = new NameValuePair(“from”, originJobName);
-
postMethod.setQueryString(new NameValuePair[] { n1, n2, n3 });
-
postMethod.setRequestHeader(“Content-type”,“text/plain; charset=ISO-8859-1”);
-
try {
-
int status = client.executeMethod(postMethod);
-
System.out.println(status + “n“+ postMethod.getResponseBodyAsString());
-
} finally {
-
postMethod.releaseConnection();
-
}
-
}
Pour supprimer un job Hudson
Envoie d’une requête POST à la ressource hudsonBaseURL/job/jobName/doDelete
-
private void delete(HttpClient client, String hudsonBaseURL, String jobName) throws IOException, HttpException {
-
PostMethod postMethod = new PostMethod(hudsonBaseURL + “/job/”+ jobName + “/doDelete”);
-
try {
-
int status = client.executeMethod(postMethod);
-
System.out.println(status + “n“+ postMethod.getResponseBodyAsString());
-
} finally {
-
postMethod.releaseConnection();
-
}
-
}
Pour activer et désactiver un job Hudson
Envoie de requêtes POST aux ressources hudsonBaseURL/job/jobName/enable et hudsonBaseURL/job/jobName/disable
-
private void enable(HttpClien t client, String hudsonBaseURL,String jobName) throws IOException, HttpException {
-
PostMethod postMethod = new PostMethod(hudsonBaseURL + “/job/”+ jobName + “/enable”);
-
try {
-
int status = client.executeMethod(postMethod);
-
System.out.println(status + “n“+ postMethod.getResponseBodyAsString());
-
} finally {
-
postMethod.releaseConnection();
-
}
-
}
-
private void disable(HttpClient client, String hudsonBaseURL, String jobName) throws IOException, HttpException {
-
PostMethod postMethod = new PostMethod(hudsonBaseURL + “/job/”+ jobName + “/disable”);
-
try {
-
int status = client.executeMethod(postMethod);
-
System.out.println(status + “n“+ postMethod.getResponseBodyAsString());
-
} finally {
-
postMethod.releaseConnection();
-
}
-
}
Pour récupérer le fichier de configuration config.xml d’un job Hudson
Récupérer la réponse d’une requête à la ressource hudsonBaseURL/job/jobName/config.xml
-
private void fetch(HttpClient client, String hudsonBaseURL, String jobName) throws IOException, HttpException {
-
GetMethod getMethod = new GetMethod(hudsonBaseURL + “/job/” + jobName+ “/config.xml”);
-
try {
-
int returnCode = client.executeMethod(getMethod);
-
System.out.print(returnCode);
-
byte[] response = getMethod.getResponseBody();
-
System.out.println(new String(response));
-
} finally {
-
getMethod.releaseConnection();
-
}
-
}
Pour lancer le build d’un job
Invoquer la ressource hudsonBaseURL/job/jobName/build
-
private void launchBuild(HttpClient client, String hudsonBaseURL, String jobName) throws IOException, HttpException {
-
GetMethod getMethod = new GetMethod(hudsonBaseURL + “/job/”+ jobName+ “/build”);
-
try {
-
int status = client.executeMethod(getMethod);
-
System.out.println(status + “n“+ getMethod.getResponseBodyAsString());
-
} finally {
-
getMethod.releaseConnection();
-
}
-
}
Pour lancer le build d’un job avec des paramètres
Invoquer la ressource hudsonBaseURL/job/jobName/buildWithParameters avec les paramètres du job
-
private void launchBuildWithParameters(HttpClient client, String hudsonBaseURL, String jobName) throws IOException, HttpException {
-
GetMethod getMethod = new GetMethod(hudsonBaseURL + “/job/”+ jobName+ “/buildWithParameters?param1=value1”);
-
try {
-
int status = client.executeMethod(getMethod);
-
System.out.println(status + “n“+ getMethod.getResponseBodyAsString());
-
} finally {
-
getMethod.releaseConnection();
-
}
-
}
Pour récupérer la date du dernier succès d’un job
Invoquer la ressource hudsonBaseURL/job/jobName/lastSuccessfulBuild/buildTimestamp avec le paramètre format contenant comme valeur le pattern de la date désiré selon l’API SimpleDateFormat
-
private void lastSuccessfulBuild(HttpClient client, String hudsonBaseURL, String jobName) throws IOException, HttpException {
-
GetMethod getMethod = new GetMethod(hudsonBaseURL + “/job/”+ jobName+ “/lastSuccessfulBuild/buildTimestamp?format=dd/MM/yyyy”);
-
try {
-
int status = client.executeMethod(getMethod);
-
System.out.println(status + “n“+ getMethod.getResponseBodyAsString());
-
} finally {
-
getMethod.releaseConnection();
-
}
-
}
Pour récupérer le status de l’ensemble des jobs d’un dashboard Hudson
Invoquer la ressource hudsonBaseURL/api/xml et traiter le résultat
-
private void read(String hudsonBaseURL) throws IOException, HttpException,DocumentException {
-
URL url = new URL(hudsonBaseURL + “/api/xml”);
-
Document dom = new SAXReader().read(url);
-
for (Element job : (List<Element>) dom.getRootElement().elements(“job”)) {
-
System.out.println(String.format(“Name:%stStatus:%s”, job.elementText(“name”), job.elementText(“color”)));
-
}
-
}
La capacité de piloter Hudson par API est très utile dans de nombreuses situations, comme dans la création d’un installateur de projets démonstrateurs ou d’un système d’orchestration qui piloterait un ensemble de jobs Hudson.
Pour avoir plus d’informations sur cette fonctionnalité, veuillez consulter la section Renote Access API du wiki de Hudson.
Merci pour le tuto, très pratique,
J’ai une question par rapport à la création d’un job Hudson,à quel fichier doit renvoyer le “configFile”. Est-ce le config.xml du job? on doit le créer avant de lancer la méthode ??
Amicalement,