Prefacio
Jenkins es una popular herramienta de integración continua de código abierto que se usa ampliamente en el desarrollo de proyectos y tiene funciones como construcción automatizada, pruebas e implementación.
Recientemente, participé en el desarrollo de la plataforma de prueba integrada de la compañía y encontré muchos problemas en el desarrollo. La iteración de dos semanas está a punto de completarse. Usaré este blog para grabar los problemas en el desarrollo de la referencia de los lectores.
La compañía tiene muchas aplicaciones, por lo que necesitamos comprender cómo construir estas aplicaciones en Jenkins. He participado en dos tipos de aplicaciones de comandantes, uno es la clase Big Data, y la otra es la aplicación Scala de nuestro grupo de arquitectura de servidor.
1. Aplicación de big data
La configuración es la siguiente:
El archivo XML correspondiente al archivo de configuración: obtenga el archivo de configuración XML a través de crul: http: //host/job/tar_py_dwx_dev/config.xml
<Estre> <Actions/> <Description/> <KeepDependencies> False </KeepDependences> <Properties> <com.dabsquared.gitlabjenkins.connection.gitlabconnectionProperty plugin = "[email protected]"> <gitlabconnection/</com.dabsquared.gitlabjenkins.connection.gitlabconnectionproperty> <hudson.plugins.pomoted__builds.jobpertyImpl pluginmin Dev </string> </activoprocessnames> </hudson.plugins.promoted__builds.jobpropertyimpl> </propiies> <scm plugin = "[email protected]"> <configVersion> 2 </configVersion> <Serremoteconfigs> <hudson.plugins.git.userrem Oteconfig> <URL> ssh: //[email protected]: 10022/bigData/dwx.git </sl> <CredentialSid> 84F4BE19-EA8D-4271 -8CFB-42AF8F507285 </CredentialSid> </Hudson.plugins.git.userremoteconfig> </serReMoteconfigs> <Randsons> <Hudson.plugins.git.Branchspec> ES> <DogenerAdSubModuleConfigurations> False </dogenerAsAbModuleconfigurations> <Submodulecfg/> <Extensions/</scm> <signedNode>! Macmini </aguednode> <Canroam> falso </canroam> <diaced> Falso </sishaam </siSa DisaAd bled><blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding><blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding><triggers><hudson.triggers.SCMTrigger><spec>H/5 * * * * *</spec> <ignorepostCommitooks> false </ignorepostCommitooks> </hudson.triggers.scmtrigger> </triggers> <cresentBuild> false </concurrentBuild> <constructores> <hudson.tasks.shell> <sandem> Proyecto = DWX1 CD $ {Workspace} Tar ZCVF $}. * AWS S3 CP $ {Project} .tar.gz s3: // lattebank-jenkins-build-dev/$ {job_base_name}/$ {build_number}/--region cn-north-1 rm -rf $ {Project} .tar.gz </comando> </hudson.tasks.shell> </structores> <publishers/> <buildwrappers/> <jecter>
La información obtenida del XML no corresponde al archivo de configuración en la figura.
Los scripts de promoción no se pueden obtener en el archivo de configuración XML. En este momento, hay un problema. Esta API no puede obtener los scripts de promoción. Al mismo tiempo, esto también trae grandes desafíos a nuestro trabajo. También significa que la implementación de la aplicación Commander no se puede realizar a través de este método y la configuración de Jenkins a través del método de la plataforma se puede operar directamente.
Sin embargo, después de consultar las API relevantes, no podemos encontrar el contenido relevante. Después de esfuerzos incontables, finalmente encontramos la API relacionada con el complemento de promoción de la construcción
Consulta: http: //host/job/jobname/promotion/process/promotionname/config.xml
Esta interfaz puede obtener su archivo XML, pero no puede agregar o modificar el archivo de configuración.
He encapsulado algunos métodos para esto:
/** * @Author Chenlang * Fecha 2018/5/7 */ @SLF4JPublic Class JenkinspromotionUtils {String final estático privado Sub_Path_Promotion_CoomMand = "/hudson.plugins.Promoted__Builds.promotionProcess"; cadena final estática privada sub_path_build = "/buildsteps"; Cadena final estática privada sub_path_builder_shell_command = "/hudson.tasks.shell/command"; cadena final estática privada path_promotion_command = sub_path_promotion_coommand + sub_path_build + sub_path_builder_shell_command; cadena estática privada create_promotion_json = "" {'Propiedades': {'stapler-class-bag': 'True', 'hudson-plugins-promoted_builds-jobpropertyImpl': {'promotiones': {'activoitems': {'nombre': '%s ',' isVisible ':' ',' icon ':' Star-Gold ',' HasSassignedLabel ': false,' AsignedLabelString ':' ',' Condiciones ': {' Stapler-Class-Bag ':' True '}}}}} "; static final static privado content_type = "aplicación/x-www-form-urlencoded"; public static void UpdatePromotionShell (document JobConfigDocument, String JobName, JenkinspromotionClient JenkinspromotionClient, String PromotionShell, String Path) lanza ioexception, documentException {if (stringUtils.isblank (promocionshell) {return; } String promotionName = getPromotionName (JobConfigDocument, Path); Documento documento = jenkinspromotionClient.getJobpromotionxml (JobName, PromotionName); document.selectsinglenode (Path_promotion_command) .settext (promoción); jenkinspromotionClient.updateJob (JobName, PromotionName, document.asxml ()); } public static void CreatePromotionShell (document JobConfigDocument, String tmpJobName, String JobName, String PromotionShell, String Path, JenkinspromotionClient JenkinspromotionClient) lanza IOException, DocumentException {if (StringUtils.isblank (promotionShell) {return; } String promotionName = getPromotionName (JobConfigDocument, Path); Documento documento = jenkinspromotionClient.getJobpromotionxml (tmpJobName, promocionname); document.selectsinglenode (Path_promotion_command) .settext (promoción); Map <string, string> map = maps.newhashmap (); map.put ("Content-type", content_type); map.put ("json", string.format (create_promotion_json, promotionName)); intente {jenkinspromotionClient.createJob (JobName, map); } catch (excepción e) {log.error ("falló al comenzar una promoción" + e); } jenkinspromotionClient.CreateJob (JobName, PromotionName, document.asxml ()); } public static string getPromotionName (document JobConfigDocument, String Path) {return JobConfigDocument.SelectsingLenode (ruta) .gettext (); }} paquete cn.caijiajia.phoenix.service.jenkins; import com.offbytwo.jenkins.client.jenkinshttpclient; import org.dom4j.documentHelper; import org.springframework.beans.factory.annotation.autowired; import org.springframework.stereotype.component; import java.io.ioexception; import java.util.map; /** * @author Chenlang * Fecha 2018/5/4 */ @ComponentPublic Class JenkinspromotionClient {@aUtowired private jenkinhttpclient jenkinshttpclient; public jenkinspromotionClient () {} / *** Obtenga el archivo de configuración de promoción del trabajo** @param JobName Nombre de trabajo* @param Nombre de promoción de promoción* @return* @throws ioException* / public document getJobPromotionxml (String JobName, String String PromotionName) tira IoException, documentException {regreso {regreso {regreso {regreso {regreso {regreso {regreso {regreso {regreso {regreso {regreso {regreso {regreso {regreso {regreso {regreso {regreso {regreso {regreso {regreso {regreso {regreso { Documenthelper.parsetext (this.getJobxml (JobName, PromotionName)); } /** * Update job * * @param jobName * @param promotionName * @param jobXml * @throws IOException */ public void updateJob(String jobName, String promotionName, String jobXml) throws IOException { this.jenkinsHttpClient.post_xml(this.toJobBaseUrl(jobName, promotionName) + "/Config.xml", Jobxml, true); }/** * Agregar script de trabajo * * @param JobName * @param Jobxml * @throws ioException */public void createJob (String JobName, String PromotionName, String JobXml) lanza ioexception {this.jenkinshttpclient.post_xml (this.tojobbaseurl (jobname, promocion JOBXML, verdadero); }/** * Agregue un trabajo de promoción * * @param JobName * @param map * @throws ioexception */public void createJob (String JobName, Map Map) lanza IOException {this.jenkinshttpclient.post_form ("/Job/" + encodingutiliS.Code (JobName) + "/configSubMit?", Mape, False); } cadena privada getJobxml (String JobName, String PromotionName) lanza ioexception {return this.jenkinshttpclient.get (this.tojobbaseurl (JobName, promocionname) + "/config.xml"); } private String toJobBaseUrl (String JobName, String PromotionName) {return "/Job/" + encodingUtilss.encode (JobName) + "/Promotion/Process/" + PromotionName; } / ** * Construcción de scripts de promoción * @param JobName * @param PromotionName * @param versión * @param isFirstBuild * @throws ioexception * / public void construye (string jobName, string promotionName, versión entera, boolean isfirstBuild) tira ioexception {if (isFirstBuild) this.jenkinshttpclient.post ("/job/"+encodingutils.encode (JobName)+"/"+versión+"/promoción/forcePromotion? name ="+promocionname+"& json =%7b%7d & subt = force promotion"); } else {this.jenkinshttpclient.post ("/job/"+encodingutils.enDode (JobName)+"/"+versión+"/promoción/"+promoción Name+"/build? json =%7b%7d & submit = re-Eexcutut promotion"); }}}El método encapsula la adición de configuración, eliminación, modificación y consulta del complemento de promoción de compilación, así como la construcción del script de promoción.
Resumir
Lo anterior es todo el contenido de este artículo. Espero que el contenido de este artículo tenga cierto valor de referencia para el estudio o el trabajo de todos. Si tiene alguna pregunta, puede dejar un mensaje para comunicarse. Gracias por su apoyo a Wulin.com.