0721b3fd9348e949517d81b3d94d81db0b8a20b5
[so.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.so.adapters.appc.orchestrator.client;
22
23 import java.lang.reflect.InvocationTargetException;
24 import java.lang.reflect.Method;
25 import java.time.Instant;
26 import java.util.Optional;
27 import java.util.Properties;
28 import java.util.UUID;
29 import java.util.concurrent.ConcurrentHashMap;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32 import org.springframework.beans.factory.annotation.Autowired;
33 import org.springframework.core.env.Environment;
34 import org.springframework.stereotype.Component;
35 import org.onap.appc.client.lcm.api.AppcClientServiceFactoryProvider;
36 import org.onap.appc.client.lcm.api.AppcLifeCycleManagerServiceFactory;
37 import org.onap.appc.client.lcm.api.ApplicationContext;
38 import org.onap.appc.client.lcm.api.LifeCycleManagerStateful;
39 import org.onap.appc.client.lcm.exceptions.AppcClientException;
40 import org.onap.appc.client.lcm.model.Action;
41 import org.onap.appc.client.lcm.model.ActionIdentifiers;
42 import org.onap.appc.client.lcm.model.CommonHeader;
43 import org.onap.appc.client.lcm.model.Flags;
44 import org.onap.appc.client.lcm.model.Flags.Force;
45 import org.onap.appc.client.lcm.model.Flags.Mode;
46 import org.onap.appc.client.lcm.model.Payload;
47 import org.onap.appc.client.lcm.model.Status;
48 import org.onap.appc.client.lcm.model.ZULU;
49
50 @Component
51 public class ApplicationControllerClient {
52     @Autowired
53     public Environment env;
54
55     public static final String DEFAULT_CONTROLLER_TYPE = "APPC";
56
57     private static final String CLIENT_NAME = "MSO";
58
59     protected static final String API_VER = "2.00";
60     protected static final String ORIGINATOR_ID = "MSO";
61     protected static final int FLAGS_TTL = 65000;
62     private static Logger logger = LoggerFactory.getLogger(ApplicationControllerClient.class);
63
64     @Autowired
65     private ApplicationControllerSupport appCSupport;
66
67     // APPC gave us an API where the controllerType is configured in the
68     // client object, which is not what we asked for. We asked for an API
69     // in which the client would have additional methods that could take
70     // the controllerType as a parameter, so that we would not need to
71     // maintain multiple client objects. This map should be removed when
72     // the (hopefully short-term) controllerType becomes obsolete.
73
74     private String controllerType = DEFAULT_CONTROLLER_TYPE;
75
76     private static ConcurrentHashMap<String, LifeCycleManagerStateful> appCClients = new ConcurrentHashMap<>();
77
78     /**
79      * Creates an ApplicationControllerClient for the specified controller type.
80      *
81      * @param controllerType the controller type: "appc" or "sdnc".
82      */
83     public void setControllerType(String controllerType) {
84         if (controllerType == null) {
85             controllerType = DEFAULT_CONTROLLER_TYPE;
86         }
87         this.controllerType = controllerType.toUpperCase();
88     }
89
90     /**
91      * Gets the controller type.
92      *
93      * @return the controllertype
94      */
95     public String getControllerType() {
96         return controllerType;
97     }
98
99     /**
100      * Returns the AppC client object associated with this ApplicationControllerClient. AppC client objects are shared
101      * objects. One is created if it does not exist.
102      *
103      * @return the client object, or null if creation failed
104      */
105     public LifeCycleManagerStateful getAppCClient() {
106         return appCClients.computeIfAbsent(controllerType, k -> createAppCClient(k));
107     }
108
109     protected LifeCycleManagerStateful createAppCClient(String controllerType) {
110
111         try {
112             if (controllerType == null) {
113                 controllerType = DEFAULT_CONTROLLER_TYPE;
114             }
115             controllerType = controllerType.toUpperCase();
116
117             return AppcClientServiceFactoryProvider.getFactory(AppcLifeCycleManagerServiceFactory.class)
118                     .createLifeCycleManagerStateful(new ApplicationContext(), getLCMProperties(controllerType));
119         } catch (AppcClientException e) {
120             logger.error("Error in getting LifeCycleManagerStateful: {}", e.getMessage(), e);
121             // This null value will cause NullPointerException when used later.
122             // Error handling could certainly be improved here.
123             return null;
124         }
125     }
126
127     public Status vnfCommand(Action action, String requestId, String vnfId, Optional<String> vserverId,
128             Optional<String> request, String controllerType, ApplicationControllerCallback listener, String requestorId)
129             throws ApplicationControllerOrchestratorException {
130         this.setControllerType(controllerType);
131         Status status;
132         ActionIdentifiers actionIdentifiers = new ActionIdentifiers();
133         actionIdentifiers.setVnfId(vnfId);
134         if (vserverId.isPresent()) {
135             actionIdentifiers.setVserverId(vserverId.get());
136         }
137         Payload payload = null;
138         if (request.isPresent()) {
139             payload = new Payload(request.get());
140
141         }
142         status = runCommand(action, actionIdentifiers, payload, requestId, listener, requestorId);
143         if (appCSupport.getCategoryOf(status).equals(StatusCategory.ERROR)) {
144             throw new ApplicationControllerOrchestratorException(status.getMessage(), status.getCode());
145         } else {
146             return status;
147         }
148     }
149
150
151     public Status runCommand(Action action, org.onap.appc.client.lcm.model.ActionIdentifiers actionIdentifiers,
152             org.onap.appc.client.lcm.model.Payload payload, String requestID, ApplicationControllerCallback listener,
153             String requestorId) throws ApplicationControllerOrchestratorException {
154         Object requestObject;
155         requestObject = createRequest(action, actionIdentifiers, payload, requestID, requestorId);
156         appCSupport.logLCMMessage(requestObject);
157         LifeCycleManagerStateful client = getAppCClient();
158         Method lcmMethod = appCSupport.getAPIMethod(action.name(), client, true);
159         try {
160             Object response = lcmMethod.invoke(client, requestObject, listener);
161             if (response != null) {
162                 return appCSupport.getStatusFromGenericResponse(response);
163             } else {
164                 return new Status();
165             }
166         } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
167             throw new RuntimeException(String.format("%s : %s", "Unable to invoke action", action.toString()), e);
168         }
169     }
170
171     protected Properties getLCMProperties() {
172         return getLCMProperties("appc");
173     }
174
175     protected Properties getLCMProperties(String controllerType) {
176         Properties properties = new Properties();
177
178         properties.put("topic.read", this.env.getProperty("appc.client.topic.read.name"));
179         properties.put("topic.write", this.env.getProperty("appc.client.topic.write"));
180         properties.put("SDNC-topic.read", this.env.getProperty("appc.client.topic.sdnc.read"));
181         properties.put("SDNC-topic.write", this.env.getProperty("appc.client.topic.sdnc.write"));
182         properties.put("topic.read.timeout", this.env.getProperty("appc.client.topic.read.timeout"));
183         properties.put("client.response.timeout", this.env.getProperty("appc.client.response.timeout"));
184         properties.put("poolMembers", this.env.getProperty("appc.client.poolMembers"));
185         properties.put("controllerType", controllerType);
186         properties.put("client.key", this.env.getProperty("appc.client.key"));
187         properties.put("client.secret", this.env.getProperty("appc.client.secret"));
188         properties.put("client.name", CLIENT_NAME);
189         properties.put("service", this.env.getProperty("appc.client.service"));
190         return properties;
191     }
192
193     public Object createRequest(Action action, ActionIdentifiers identifier, Payload payload, String requestId,
194             String requestorId) {
195         Object requestObject = appCSupport.getInput(action.name());
196
197
198         try {
199             CommonHeader commonHeader = buildCommonHeader(requestId, requestorId);
200             requestObject.getClass().getDeclaredMethod("setCommonHeader", CommonHeader.class).invoke(requestObject,
201                     commonHeader);
202             requestObject.getClass().getDeclaredMethod("setAction", Action.class).invoke(requestObject, action);
203             requestObject.getClass().getDeclaredMethod("setActionIdentifiers", ActionIdentifiers.class)
204                     .invoke(requestObject, identifier);
205             if (payload != null) {
206                 logger.info("payload in RunCommand: " + payload.getValue());
207                 requestObject.getClass().getDeclaredMethod("setPayload", Payload.class).invoke(requestObject, payload);
208             }
209         } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
210             logger.error("Error building Appc request", e);
211         }
212         return requestObject;
213     }
214
215     protected CommonHeader buildCommonHeader(String requestId, String requestorId) {
216         CommonHeader commonHeader = new CommonHeader();
217         commonHeader.setApiVer(API_VER);
218         commonHeader.setOriginatorId(ORIGINATOR_ID);
219         commonHeader.setRequestId(requestId == null ? UUID.randomUUID().toString() : requestId);
220         commonHeader.setSubRequestId(UUID.randomUUID().toString());
221         Flags flags = new Flags();
222         String flagsMode = "NORMAL";
223         Mode mode = Mode.valueOf(flagsMode);
224         flags.setMode(mode);
225         String flagsForce = "FALSE";
226         Force force = Force.valueOf(flagsForce);
227         flags.setForce(force);
228         flags.setTtl(FLAGS_TTL);
229         commonHeader.setFlags(flags);
230         Instant timestamp = Instant.now();
231         ZULU zulu = new ZULU(timestamp.toString());
232         commonHeader.setTimestamp(zulu);
233         return commonHeader;
234     }
235
236     public Flags createRequestFlags() {
237         Flags flags = new Flags();
238         flags.setTtl(6000);
239         return flags;
240     }
241 }