Merge "Reorder modifiers"
[so.git] / adapters / mso-adapter-utils / src / main / java / org / openecomp / mso / aria / AriaVduPlugin.java
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 package org.openecomp.mso.aria;
21
22 import com.gigaspaces.aria.rest.client.AriaClient;
23 import com.gigaspaces.aria.rest.client.AriaClientFactory;
24 import com.gigaspaces.aria.rest.client.ExecutionDetails;
25 import com.gigaspaces.aria.rest.client.Input;
26 import com.gigaspaces.aria.rest.client.InputImpl;
27 import com.gigaspaces.aria.rest.client.Output;
28 import com.gigaspaces.aria.rest.client.Service;
29 import com.gigaspaces.aria.rest.client.ServiceTemplate;
30 import com.gigaspaces.aria.rest.client.ServiceTemplateImpl;
31 import java.util.ArrayList;
32 import java.util.HashMap;
33 import java.util.List;
34 import java.util.Map;
35 import org.openecomp.mso.adapters.vdu.CloudInfo;
36 import org.openecomp.mso.adapters.vdu.VduException;
37 import org.openecomp.mso.adapters.vdu.VduInstance;
38 import org.openecomp.mso.adapters.vdu.VduModelInfo;
39 import org.openecomp.mso.adapters.vdu.VduPlugin;
40 import org.openecomp.mso.adapters.vdu.VduStateType;
41 import org.openecomp.mso.adapters.vdu.VduStatus;
42 import org.openecomp.mso.logger.MessageEnum;
43 import org.openecomp.mso.logger.MsoLogger;
44
45 /**
46  * ARIA VDU Plugin. Pluggable interface for the ARIA REST API to support TOSCA orchestration.
47  *
48  * @author DeWayne
49  */
50 public class AriaVduPlugin implements VduPlugin {
51     private static final String API_VERSION = "0.1";
52     private static final MsoLogger logger = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA);
53     private AriaClient client = null;
54     private Map<String, Integer> templateIds = new HashMap<>();
55     private Map<String, Integer> serviceIds = new HashMap<>();
56     private Map<String, Map<String, Object>> inputsCache = new HashMap<>();
57
58     public AriaVduPlugin() {
59         super();
60     }
61
62     public AriaVduPlugin(String host, int port) {
63         try {
64             client = new AriaClientFactory().createRestClient("http", host, port, API_VERSION);
65         } catch (Exception e) {
66             logger.error(
67                     MessageEnum.RA_CREATE_VNF_ERR,
68                     "",
69                     "",
70                     "",
71                     "",
72                     "aria",
73                     MsoLogger.ErrorCode.AvailabilityError,
74                     "Connection to ARIA REST API failed",
75                     e);
76             throw e;
77         }
78     }
79
80     /**
81      * Instantiate VDU in ARIA. <code>instanceName</code> is used for both service template name and
82      * service name.
83      */
84     @SuppressWarnings("unchecked")
85     @Override
86     public VduInstance instantiateVdu(
87             CloudInfo cloudInfo,
88             String instanceName,
89             Map<String, Object> inputs,
90             VduModelInfo vduModel,
91             boolean rollbackOnFailure)
92             throws VduException {
93
94         String cloudSiteId = cloudInfo.getCloudSiteId();
95         String tenantId = cloudInfo.getTenantId();
96
97         // Currently only support simple CSAR with single main template
98         byte[] csar = new CSAR(vduModel).create();
99
100         ServiceTemplate template = new ServiceTemplateImpl(instanceName, csar);
101         try {
102             client.install_service_template(template);
103         } catch (Exception e) {
104             logger.error(
105                     MessageEnum.RA_CREATE_VNF_ERR,
106                     "",
107                     "",
108                     "",
109                     "",
110                     instanceName,
111                     MsoLogger.ErrorCode.BusinessProcesssError,
112                     "instantiate vdu via csar failed",
113                     e);
114             throw new VduException(e.getMessage());
115         }
116
117         /** Create a service */
118         try {
119             int templateId = -1;
120             for (ServiceTemplate stemplate :
121                     (List<ServiceTemplate>) client.list_service_templates()) {
122                 if (stemplate.getName().equals(instanceName)) {
123                     templateId = stemplate.getId();
124                 }
125             }
126             List<Input> sinputs = new ArrayList<>();
127             for (Map.Entry<String, ? extends Object> entry : inputs.entrySet()) {
128                 Input inp = new InputImpl(entry.getKey(), entry.getValue().toString(), "");
129                 sinputs.add(inp);
130             }
131             client.create_service(templateId, instanceName, sinputs);
132         } catch (Exception e) {
133             logger.error(
134                     MessageEnum.RA_CREATE_VNF_ERR,
135                     "",
136                     "",
137                     "",
138                     "",
139                     instanceName,
140                     MsoLogger.ErrorCode.BusinessProcesssError,
141                     "aria service creation failed",
142                     e);
143             throw new VduException(e.getMessage());
144         }
145
146         // Get the service ID and cache it
147         int sid = getServiceId(instanceName);
148         serviceIds.put(instanceName, sid);
149
150         /** Run install */
151         try {
152             client.start_execution(sid, "install", new ExecutionDetails());
153         } catch (Exception e) {
154             logger.error(
155                     MessageEnum.RA_CREATE_VNF_ERR,
156                     "",
157                     "",
158                     "",
159                     "",
160                     instanceName,
161                     MsoLogger.ErrorCode.BusinessProcesssError,
162                     "aria install workflow failed",
163                     e);
164             throw new VduException(e.getMessage());
165         }
166
167         /** Get the outputs and return */
168         try {
169             Map<String, Object> voutputs = getOutputs(sid);
170
171             VduInstance vi = new VduInstance();
172             vi.setVduInstanceName(instanceName);
173             vi.setInputs((Map<String, Object>) inputs);
174             inputsCache.put(instanceName, vi.getInputs());
175             vi.setOutputs(voutputs);
176             vi.setStatus(new VduStatus(VduStateType.INSTANTIATED));
177             return vi;
178         } catch (Exception e) {
179             logger.error(
180                     MessageEnum.RA_CREATE_VNF_ERR,
181                     "",
182                     "",
183                     "",
184                     "",
185                     instanceName,
186                     MsoLogger.ErrorCode.BusinessProcesssError,
187                     "aria service output fetch failed",
188                     e);
189             throw new VduException(e.getMessage());
190         }
191     }
192
193     /**
194      * Queries ARIA for VDU status. instanceId used as template and service name in ARIA (by
195      * convention).
196      */
197     @Override
198     public VduInstance queryVdu(CloudInfo cloudInfo, String instanceId) throws VduException {
199         if (client == null) {
200             throw new VduException("Internal error: no ARIA connection found");
201         }
202
203         VduInstance vif = new VduInstance();
204         vif.setVduInstanceId(instanceId);
205         Integer sid = serviceIds.get(instanceId);
206         if (sid == null) {
207             // service doesn't exist
208             vif.setStatus(new VduStatus(VduStateType.NOTFOUND));
209             return vif;
210         }
211         Service service = client.get_service(sid);
212         if (service == null) {
213             throw new VduException(
214                     String.format("Internal error: cached service id %s not found in ARIA", sid));
215         }
216         Map<String, Object> voutputs = getOutputs(sid);
217         vif.setOutputs(voutputs);
218         vif.setInputs(inputsCache.get(instanceId));
219         vif.setStatus(new VduStatus(VduStateType.INSTANTIATED));
220         return vif;
221     }
222
223     @Override
224     public VduInstance deleteVdu(CloudInfo cloudInfo, String instanceId, int timeoutMinutes)
225             throws VduException {
226         VduInstance vif = new VduInstance();
227         vif.setVduInstanceId(instanceId);
228
229         if (client == null) {
230             throw new VduException("Internal error: no ARIA connection found");
231         }
232         Integer sid = serviceIds.get(instanceId);
233         if (sid == null) {
234             // service doesn't exist
235             vif.setStatus(new VduStatus(VduStateType.NOTFOUND));
236             return vif;
237         }
238
239         /** Run uninstall */
240         try {
241             client.start_execution(sid, "uninstall", new ExecutionDetails());
242         } catch (Exception e) {
243             logger.error(
244                     MessageEnum.RA_CREATE_VNF_ERR,
245                     "",
246                     "",
247                     "",
248                     "",
249                     instanceId,
250                     MsoLogger.ErrorCode.BusinessProcesssError,
251                     "aria uninstall workflow failed",
252                     e);
253             throw new VduException(e.getMessage());
254         }
255
256         /** Delete the service */
257         try {
258             client.delete_service(sid);
259         } catch (Exception e) {
260             logger.error(
261                     MessageEnum.RA_CREATE_VNF_ERR,
262                     "",
263                     "",
264                     "",
265                     "",
266                     instanceId,
267                     MsoLogger.ErrorCode.BusinessProcesssError,
268                     String.format("aria service delete failed. Service id: %d", sid),
269                     e);
270             throw new VduException(e.getMessage());
271         }
272
273         /** Delete the blueprint */
274         try {
275             client.delete_service_template(templateIds.get(instanceId));
276         } catch (Exception e) {
277             logger.error(
278                     MessageEnum.RA_CREATE_VNF_ERR,
279                     "",
280                     "",
281                     "",
282                     "",
283                     instanceId,
284                     MsoLogger.ErrorCode.BusinessProcesssError,
285                     "aria template delete failed",
286                     e);
287             throw new VduException(e.getMessage());
288         }
289
290         vif.setStatus(new VduStatus(VduStateType.DELETED));
291         return vif;
292     }
293
294     /** Deployment update not possible with ARIA */
295     @Override
296     public VduInstance updateVdu(
297             CloudInfo cloudInfo,
298             String instanceId,
299             Map<String, Object> inputs,
300             VduModelInfo vduModel,
301             boolean rollbackOnFailure)
302             throws VduException {
303         throw new VduException("NOT IMPLEMENTED");
304     }
305
306     /** Private */
307
308     /**
309      * p Gets and repacks service outputs for internal use
310      *
311      * @param sid the service id (ARIA service id)
312      * @return
313      */
314     private Map<String, Object> getOutputs(int sid) {
315         @SuppressWarnings("unchecked")
316         List<Output> outputs = (List<Output>) client.list_service_outputs(sid);
317         Map<String, Object> voutputs = new HashMap<>();
318         for (Output output : outputs) {
319             voutputs.put(output.getName(), output.getValue());
320         }
321         return voutputs;
322     }
323
324     @SuppressWarnings("unchecked")
325     private int getServiceId(String service_name) throws VduException {
326         int sid = -1;
327         List<Service> services = (List<Service>) client.list_services();
328         for (Service service : services) {
329             if (service.getName().equals(service_name)) {
330                 sid = service.getId();
331             }
332         }
333         if (sid == -1) {
334             throw new VduException(
335                     String.format(
336                             "Internal error: just created service not found: %s", service_name));
337         }
338         return sid;
339     }
340 }