View Javadoc
1   package fr.paris.lutece.plugins.releaser.service;
2   
3   import java.io.IOException;
4   import java.util.HashMap;
5   import com.fasterxml.jackson.databind.JsonNode;
6   import com.fasterxml.jackson.databind.ObjectMapper;
7   import fr.paris.lutece.plugins.releaser.business.WorkflowReleaseContext;
8   import fr.paris.lutece.plugins.releaser.util.CommandResult;
9   import fr.paris.lutece.plugins.releaser.util.ConstanteUtils;
10  import fr.paris.lutece.plugins.releaser.util.ReleaserUtils;
11  import fr.paris.lutece.portal.service.spring.SpringContextService;
12  import fr.paris.lutece.portal.service.util.AppPropertiesService;
13  import fr.paris.lutece.util.httpaccess.HttpAccess;
14  import fr.paris.lutece.util.httpaccess.HttpAccessException;
15  import fr.paris.lutece.util.signrequest.BasicAuthorizationAuthenticator;
16  import fr.paris.lutece.util.signrequest.RequestAuthenticator;
17  
18  public class JenkinsService implements IJenkinsService 
19  {
20  	/** The Constant api/json */
21      private static final String CST_API_JSON = "api/json";
22      
23  	/** The Constant json.location */
24      private static final String CST_JSON_LOCATION = "Location";
25      
26  	/** The Constant json.executable */
27      private static final String CST_JSON_EXECUTABLE = "executable";
28      
29  	/** The Constant json.result */
30      private static final String CST_JSON_RESULT = "result";
31      
32  	/** The Constant json.result */
33      private static final String CST_JSON_BUILDING = "building";
34  
35  	/** The Constant json.number */
36      private static final String CST_JSON_NUMBER = "number";
37      
38      /** The jenkins server base url. */
39      private static String JENKINS_BASE_URL;
40      
41      /** The jenkins pipeline name */
42      private static String JENKINS_PIPELINE_NAME; 
43      
44      /** The jenkins build type */
45      private static String JENKINS_BUILD_TYPE;
46  
47      /** The jenkins user login. */
48      private static String JENKINS_USER_LOGIN;
49  
50      /** The jenkins user pwd. */
51      private static String JENKINS_USER_PWD;    
52  
53      /** The instance. */ 
54      private static IJenkinsService _instance = null;
55      
56      /**
57       * Gets the service.
58       *
59       * @return the service
60       */
61      public static IJenkinsService getService( )
62      {
63          if ( _instance == null )
64          {
65              _instance = SpringContextService.getBean( ConstanteUtils.BEAN_JENKINS_SERVICE );
66              _instance.init( );
67          }
68  
69          return _instance;
70      }
71      
72  	@Override
73  	public void init() 
74  	{
75  		JENKINS_BASE_URL = AppPropertiesService.getProperty( ConstanteUtils.PROPERTY_JENKINS_BASE_URL );
76  	    JENKINS_PIPELINE_NAME = AppPropertiesService.getProperty( ConstanteUtils.PROPERTY_JENKINS_PIPELINE_NAME ); 	    
77  	    JENKINS_BUILD_TYPE = AppPropertiesService.getProperty( ConstanteUtils.PROPERTY_JENKINS_BUILD_TYPE );
78  		JENKINS_USER_LOGIN = AppPropertiesService.getProperty( ConstanteUtils.PROPERTY_JENKINS_RELEASE_ACCOUNT_LOGIN );
79  		JENKINS_USER_PWD = AppPropertiesService.getProperty( ConstanteUtils.PROPERTY_JENKINS_RELEASE_ACCOUNT_PASSWORD );
80  	}
81  
82  	@Override
83  	public String TriggerPipeline( WorkflowReleaseContext context ) 
84  	{
85  		String url;
86          boolean bBuilding = true;
87          String strStatus = null;
88      	int nBuildNumber =  -1;
89  
90          CommandResult commandResult = context.getCommandResult( );
91          ObjectMapper mapper = new ObjectMapper( );
92  
93          try
94          {
95              HttpAccess httpaccess = new HttpAccess( );
96  
97              HashMap<String, String> params = new HashMap<String, String>();
98              HashMap<String, String> headersResponse = new HashMap<String, String>();
99              params.put( "push_url", context.getReleaserResource().getScmUrl() );
100         	//params.put( "branch", context.getSite().getBranchReleaseFrom() );
101     
102         	RequestAuthenticator requestAuthenticator = new BasicAuthorizationAuthenticator( JENKINS_USER_LOGIN, JENKINS_USER_PWD );
103           
104         	url = JENKINS_BASE_URL + "/" + JENKINS_PIPELINE_NAME + "/" + JENKINS_BUILD_TYPE;
105         	httpaccess.doPost(url, params, requestAuthenticator, null, null, headersResponse);
106         	String queueUrl = headersResponse.get(CST_JSON_LOCATION);
107         	
108         	commandResult.getLog( ).append( "	Jenkins - Job waiting in pipeline...\n" );
109         	
110             while (nBuildNumber == -1) 
111             {
112                 Thread.sleep(2000);
113                 
114                 String jsonQueueItem = httpaccess.doGet(queueUrl + "/" + CST_API_JSON, requestAuthenticator, null);
115                 
116                 if ( jsonQueueItem != null && !jsonQueueItem.isEmpty() )
117             	{
118                 	JsonNode objectNodeJson = mapper.readTree(jsonQueueItem);
119                 	
120                 	if (objectNodeJson.has(CST_JSON_EXECUTABLE)) {
121                         nBuildNumber = objectNodeJson.get(CST_JSON_EXECUTABLE).get(CST_JSON_NUMBER).asInt();
122                     }    		
123             	}
124             }
125        
126             commandResult.getLog( ).append( "	Jenkins - Job #" + nBuildNumber + " launched --> Build in progress... (may take fiew minutes)\n" );
127             
128             while (bBuilding) 
129             {
130                 Thread.sleep(8000);
131                 
132                 url = JENKINS_BASE_URL + "/" + JENKINS_PIPELINE_NAME + "/" + nBuildNumber + "/" + CST_API_JSON;
133                 String jsonStatus = httpaccess.doGet(url, requestAuthenticator, null);
134 
135                 JsonNode ObjectBuildJson = mapper.readTree(jsonStatus);
136 
137                 bBuilding = ObjectBuildJson.get(CST_JSON_BUILDING).asBoolean();
138 
139                 if (!bBuilding) {
140                     strStatus = ObjectBuildJson.get(CST_JSON_RESULT).asText();
141                 }
142             }
143 
144             commandResult.getLog( ).append( "	Jenkins - Build Completed : " + strStatus + "\n\n" );
145             
146         }
147         catch( HttpAccessException e )
148         {
149             ReleaserUtils.addTechnicalError( commandResult, "Erreur lors du déclenchement de la pipeline Jenkins  : "  + e.getMessage( ), e );            
150         } 
151         catch (IOException e) 
152         {
153         	ReleaserUtils.addTechnicalError( commandResult, "Erreur lors du déclenchement de la pipeline Jenkins  : "  + e.getMessage( ), e );
154 		} 
155         catch (InterruptedException e) 
156         {
157         	ReleaserUtils.addTechnicalError( commandResult, "Erreur lors du déclenchement de la pipeline Jenkins  : "  + e.getMessage( ), e );
158 		}
159 
160         return strStatus;    
161 	}
162 }
163