aboutsummaryrefslogtreecommitdiffstats
path: root/appc-adapters/appc-ansible-adapter/appc-ansible-adapter-bundle/src/main/java/org/openecomp/appc/adapter/ansible/model/AnsibleMessageParser.java
blob: e9b889930394de6a4038f8b1dc8a124f30617238 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
/*-
 * ============LICENSE_START=======================================================
 * APPC
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * Copyright (C) 2017 Amdocs
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
 */

package org.openecomp.appc.adapter.ansible.model;

/**
 * This module imples the APP-C/Ansible Server interface
 * based on the REST API specifications
 */

import java.lang.NumberFormatException ;
import java.util.*;
import com.google.common.base.Strings;

import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;
import org.openecomp.appc.exceptions.APPCException;
import org.openecomp.appc.adapter.ansible.model.AnsibleResult;


/**
 * Class that validates and constructs requests sent/received from 
 * Ansible Server
 *
 */
public class AnsibleMessageParser {




    // Accepts a map of strings and
    // a) validates if all parameters are appropriate (else, throws an exception)
    // and b) if correct returns a JSON object with appropriate key-value
    // pairs to send to the server. 
    public JSONObject ReqMessage(Map <String, String> params) throws APPCException, NumberFormatException, JSONException{

	// Mandatory  parameters, that must be in the supplied information to the Ansible Adapter
	// 1. URL to connect to
	// 2. credentials for URL (assume username password for now)
	// 3. Playbook name
	String[] mandatoryTestParams = {"AgentUrl", "PlaybookName", "User", "Password"};

	// Optional testService parameters that may be provided in the request
	String[] optionalTestParams = {"EnvParameters", "NodeList", "LocalParameters", "Timeout", "Version", "FileParameters", "Action"};

	JSONObject JsonPayload = new JSONObject();
	String payload = "";
	JSONObject paramsJson;

  
	// Verify all the mandatory parameters are there 
	for (String key: mandatoryTestParams){
	    if (! params.containsKey(key)){
		throw new APPCException(String.format("Ansible: Mandatory AnsibleAdapter key %s not found in parameters provided by calling agent !", key));
	    }
	    payload = params.get(key);
	    if (Strings.isNullOrEmpty(payload)){
		throw new APPCException(String.format("Ansible: Mandatory AnsibleAdapter key % value is Null or Emtpy", key));
	    }
	    
	    JsonPayload.put(key, payload);
	}

	// Iterate through optional parameters
	// If null or empty omit it 
	for (String key : optionalTestParams){
	    if (params.containsKey(key)){
		payload = params.get(key);
		if(!Strings.isNullOrEmpty(payload)){
		    
		    // different cases require different treatment
		    switch (key){
		    case "Timeout": 
			int Timeout = Integer.parseInt(payload);
			if (Timeout < 0){
			    throw new NumberFormatException(" : specified negative integer for timeout = " +  payload);
			}
			JsonPayload.put(key, payload);
			break;

		    case "Version": 
			JsonPayload.put(key, payload);
			break;

		    case "LocalParameters":  
			paramsJson = new JSONObject(payload);
			JsonPayload.put(key, paramsJson);
			break;
			
		    case "EnvParameters":  
			paramsJson = new JSONObject(payload);
			JsonPayload.put(key, paramsJson);
			break;
			
		    case "NodeList":  
			JSONArray paramsArray = new JSONArray(payload);
			JsonPayload.put(key, paramsArray);
			break;
			
		    case "FileParameters":
			// Files may have strings with newlines. Escape them as appropriate
			String formattedPayload = payload.replace("\n", "\\n").replace("\r", "\\r");
			JSONObject fileParams = new JSONObject(formattedPayload);
			JsonPayload.put(key, fileParams);
			break;
			
		    }
		}
	    }
	}
	

	// Generate a unique uuid for the test
	String ReqId = UUID.randomUUID().toString();
	JsonPayload.put("Id", ReqId);

	return JsonPayload;
	
    }



    // method that validates that the Map has  enough information
    // to query Ansible server for a result . If so, it
    // returns the appropriate url, else an empty string
    public String ReqUri_Result(Map <String, String> params) throws APPCException, NumberFormatException{
	
	// Mandatory  parameters, that must be in the request
	String[] mandatoryTestParams = {"AgentUrl", "Id", "User", "Password" };
	
	// Verify all the mandatory parameters are there
	String payload = "";
	String Uri = "";
	
	for (String key: mandatoryTestParams){
	    if (! params.containsKey(key)){
		throw new APPCException(String.format("Ansible: Mandatory AnsibleAdapter key %s not found in parameters provided by calling agent !", key));		    
	    }

	    payload = params.get(key);
	    if (Strings.isNullOrEmpty(payload)){
		throw new APPCException(String.format("Ansible: Mandatory AnsibleAdapter key %s not found in parameters provided by calling agent !", key));		    
	    }

	}

	Uri = params.get("AgentUrl") + "?Id=" + params.get("Id") + "&Type=GetResult";

	return Uri;
      
    }



    // method that validates that the Map has  enough information
    // to query Ansible server for logs. If so, it populates the appropriate
    // returns the appropriate url, else an empty string
    public String ReqUri_Output(Map <String, String> params) throws APPCException, NumberFormatException{
	
	
	// Mandatory  parameters, that must be in the request
	String[] mandatoryTestParams = {"AgentUrl", "Id", "User", "Password" };
	
	// Verify all the mandatory parameters are there
	String payload = "";
	String Uri = "";
	
	for (String key: mandatoryTestParams){
	    if (! params.containsKey(key)){
		throw new APPCException(String.format("Ansible: Mandatory AnsibleAdapter key %s not found in parameters provided by calling agent !", key));		    
	    }
	    payload = params.get(key);
	    if (Strings.isNullOrEmpty(payload)){
		throw new APPCException(String.format("Ansible: Mandatory AnsibleAdapter key %s not found in parameters provided by calling agent !", key));		    
	    }

	}

	Uri = params.get("AgentUrl") + "?Id=" + params.get("Id") + "&Type=GetOutput";
	return Uri;
      
    }

    // method that validates that the Map has  enough information
    // to query Ansible server for logs. If so, it populates the appropriate
    // returns the appropriate url, else an empty string
    public String ReqUri_Log(Map <String, String> params) throws APPCException, NumberFormatException{
	
	
	// Mandatory  parameters, that must be in the request
	String[] mandatoryTestParams = {"AgentUrl", "Id", "User", "Password" };
	
	// Verify all the mandatory parameters are there
	String payload = "";
	String Uri = "";
	
	for (String key: mandatoryTestParams){
	    if (! params.containsKey(key)){
		throw new APPCException(String.format("Ansible: Mandatory AnsibleAdapter key %s not found in parameters provided by calling agent !", key));		    
	    }
	    payload = params.get(key);
	    if (Strings.isNullOrEmpty(payload)){
		throw new APPCException(String.format("Ansible: Mandatory AnsibleAdapter key %s not found in parameters provided by calling agent !", key));		    
	    }

	}

	Uri = params.get("AgentUrl") + "?Id=" + params.get("Id") + "&Type=GetLog";
	return Uri;
      
    }

   
    /** 
	This method parses response from the 
	Ansible Server when we do a post 
	and returns an AnsibleResult object
    **/
    
    public AnsibleResult  parsePostResponse(String Input) throws APPCException{

	AnsibleResult ansibleResult = new AnsibleResult();
	
	try{
	    //Jsonify it
	    JSONObject  postResponse = new JSONObject(Input);
		
	    // Mandatory keys required are StatusCode and StatusMessage
	    int Code = postResponse.getInt("StatusCode");
	    String Message = postResponse.getString("StatusMessage");

	    
	    // Status code must must be either 100 (accepted) or 101 (rejected)
	    boolean valCode = AnsibleResultCodes.CODE.checkValidCode(AnsibleResultCodes.INITRESPONSE.getValue(), Code);
	    if(!valCode){
		throw new APPCException("Invalid InitResponse code  = " + Code + " received. MUST be one of " + AnsibleResultCodes.CODE.getValidCodes(AnsibleResultCodes.INITRESPONSE.getValue()) );
	    }
	    
	    ansibleResult.setStatusCode(Code);
	    ansibleResult.setStatusMessage(Message);

	}
	catch(JSONException e){
	    ansibleResult = new AnsibleResult(600, "Error parsing response = " + Input + ". Error = " + e.getMessage(), "");
	}

	
	return ansibleResult;
    }


    /** This method  parses response from an Ansible server when we do a GET for a result 
	and returns an AnsibleResult object
     **/
    public AnsibleResult  parseGetResponse(String Input) throws APPCException {

	AnsibleResult ansibleResult = new AnsibleResult();
	int FinalCode = AnsibleResultCodes.FINAL_SUCCESS.getValue();


	try{
	    
	    //Jsonify it
	    JSONObject  postResponse = new JSONObject(Input);
	    
	    // Mandatory keys required are Status and Message
	    int Code = postResponse.getInt("StatusCode");
	    String Message = postResponse.getString("StatusMessage");
	    
	    // Status code must be valid
	    // Status code must must be either 100 (accepted) or 101 (rejected)
	    boolean valCode = AnsibleResultCodes.CODE.checkValidCode(AnsibleResultCodes.FINALRESPONSE.getValue(), Code);
	    
	    if(!valCode){
		throw new APPCException("Invalid FinalResponse code  = " + Code + " received. MUST be one of " + AnsibleResultCodes.CODE.getValidCodes(AnsibleResultCodes.FINALRESPONSE.getValue()));
	    }

	    
	    ansibleResult.setStatusCode(Code);
	    ansibleResult.setStatusMessage(Message);
	    System.out.println("Received response with code = " + Integer.toString(Code) + " Message = " + Message);

	    if(! postResponse.isNull("Results")){

		// Results are available. process them 
		// Results is a dictionary of the form
		// {host :{status:s, group:g, message:m, hostname:h}, ...}
		System.out.println("Processing results in response");
		JSONObject results = postResponse.getJSONObject("Results");
		System.out.println("Get JSON dictionary from Results ..");
		Iterator<String> hosts = results.keys();
		System.out.println("Iterating through hosts");
		
		while(hosts.hasNext()){
		    String host = hosts.next();
		    System.out.println("Processing host = " + host);
		    
		    try{
			JSONObject host_response = results.getJSONObject(host);
			int subCode = host_response.getInt("StatusCode");
			String message = host_response.getString("StatusMessage");

			System.out.println("Code = " + Integer.toString(subCode) + " Message = " + message);
			
			if(subCode != 200 || ! message.equals("SUCCESS")){
			    FinalCode = AnsibleResultCodes.REQ_FAILURE.getValue();
			}
		    }
		    catch(JSONException e){
			ansibleResult.setStatusCode(AnsibleResultCodes.INVALID_RESPONSE.getValue());
			ansibleResult.setStatusMessage(String.format("Error processing response message = %s from host %s", results.getString(host), host));
			break;
		    }
		}

		ansibleResult.setStatusCode(FinalCode);

		// We return entire Results object as message
		ansibleResult.setResults(results.toString());

	    }
	    else{
		ansibleResult.setStatusCode(AnsibleResultCodes.INVALID_RESPONSE.getValue());
		ansibleResult.setStatusMessage("Results not found in GET for response");
	    }
	    
	    
	}
	catch(JSONException e){
	    ansibleResult = new AnsibleResult(AnsibleResultCodes.INVALID_PAYLOAD.getValue(), "Error parsing response = " + Input + ". Error = " + e.getMessage(), "");
	}


	return ansibleResult;
    }



};