6d8fa4bd23f9276b0130adb044ce2f865d177536
[policy/models.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  * SOActorServiceProvider
4  * ================================================================================
5  * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2019 Nordix Foundation.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.controlloop.actor.so;
23
24 import com.google.common.collect.ImmutableList;
25 import com.google.common.collect.ImmutableMap;
26 import com.google.gson.reflect.TypeToken;
27 import java.lang.reflect.Type;
28 import java.util.Collections;
29 import java.util.List;
30 import java.util.Map;
31 import org.onap.policy.aai.AaiNqExtraProperty;
32 import org.onap.policy.aai.AaiNqInventoryResponseItem;
33 import org.onap.policy.aai.AaiNqResponseWrapper;
34 import org.onap.policy.controlloop.ControlLoopOperation;
35 import org.onap.policy.controlloop.VirtualControlLoopEvent;
36 import org.onap.policy.controlloop.actorserviceprovider.spi.Actor;
37 import org.onap.policy.controlloop.policy.Policy;
38 import org.onap.policy.so.SoCloudConfiguration;
39 import org.onap.policy.so.SoManager;
40 import org.onap.policy.so.SoModelInfo;
41 import org.onap.policy.so.SoOperationType;
42 import org.onap.policy.so.SoRelatedInstance;
43 import org.onap.policy.so.SoRelatedInstanceListElement;
44 import org.onap.policy.so.SoRequest;
45 import org.onap.policy.so.SoRequestDetails;
46 import org.onap.policy.so.SoRequestInfo;
47 import org.onap.policy.so.SoRequestParameters;
48 import org.onap.policy.so.util.Serialization;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51
52 public class SoActorServiceProvider implements Actor {
53     private static final Logger logger = LoggerFactory.getLogger(SoActorServiceProvider.class);
54
55     // Strings for SO Actor
56     private static final String SO_ACTOR = "SO";
57
58     // Strings for targets
59     private static final String TARGET_VFC = "VFC";
60
61     // Strings for recipes
62     private static final String RECIPE_VF_MODULE_CREATE = "VF Module Create";
63     private static final String RECIPE_VF_MODULE_DELETE = "VF Module Delete";
64
65     private static final ImmutableList<String> recipes = ImmutableList.of(RECIPE_VF_MODULE_CREATE,
66             RECIPE_VF_MODULE_DELETE);
67     private static final ImmutableMap<String, List<String>> targets = new ImmutableMap.Builder<String, List<String>>()
68                     .put(RECIPE_VF_MODULE_CREATE, ImmutableList.of(TARGET_VFC))
69                     .put(RECIPE_VF_MODULE_DELETE, ImmutableList.of(TARGET_VFC)).build();
70
71     // name of request parameters within policy payload
72     public static final String REQ_PARAM_NM = "requestParameters";
73
74     // name of configuration parameters within policy payload
75     public static final String CONFIG_PARAM_NM = "configurationParameters";
76
77     private static final String MODEL_NAME_PROPERTY_KEY = "model-ver.model-name";
78     private static final String MODEL_VERSION_PROPERTY_KEY = "model-ver.model-version";
79     private static final String MODEL_VERSION_ID_PROPERTY_KEY = "model-ver.model-version-id";
80
81     // used to decode configuration parameters via gson
82     private static final Type CONFIG_TYPE = new TypeToken<List<Map<String, String>>>() {}.getType();
83
84     // Static variables required to hold the IDs of the last service item, VNF item and VF Module.
85     // Note that in
86     // a multithreaded deployment this WILL break
87     private static String lastVNFItemVnfId;
88     private static String lastServiceItemServiceInstanceId;
89     private static String lastVfModuleItemVfModuleInstanceId;
90
91     @Override
92     public String actor() {
93         return SO_ACTOR;
94     }
95
96     @Override
97     public List<String> recipes() {
98         return ImmutableList.copyOf(recipes);
99     }
100
101     @Override
102     public List<String> recipeTargets(String recipe) {
103         return ImmutableList.copyOf(targets.getOrDefault(recipe, Collections.emptyList()));
104     }
105
106     @Override
107     public List<String> recipePayloads(String recipe) {
108         return Collections.emptyList();
109     }
110
111     /**
112      * Constructs a SO request conforming to the lcm API. The actual request is
113      * constructed and then placed in a wrapper object used to send through DMAAP.
114      *
115      * @param onset the event that is reporting the alert for policy to perform an action
116      * @param operation the control loop operation specifying the actor, operation,
117      *        target, etc.
118      * @param policy the policy the was specified from the yaml generated by CLAMP or
119      *        through the Policy GUI/API
120      * @param aaiResponseWrapper wrapper for AAI vserver named-query response
121      * @return a SO request conforming to the lcm API using the DMAAP wrapper
122      */
123     public SoRequest constructRequest(VirtualControlLoopEvent onset, ControlLoopOperation operation, Policy policy,
124                     AaiNqResponseWrapper aaiResponseWrapper) {
125         if (!SO_ACTOR.equals(policy.getActor()) || !recipes().contains(policy.getRecipe())) {
126             return null;
127         }
128
129         // A&AI named query should have been performed by now. If not, return null
130         if (aaiResponseWrapper == null) {
131             return null;
132         }
133
134         AaiNqInventoryResponseItem vnfItem;
135         AaiNqInventoryResponseItem vnfServiceItem;
136         AaiNqInventoryResponseItem tenantItem;
137
138         // Extract the items we're interested in from the response
139         try {
140             vnfItem = aaiResponseWrapper.getAaiNqResponse().getInventoryResponseItems().get(0).getItems()
141                             .getInventoryResponseItems().get(0);
142         } catch (Exception e) {
143             logger.error("VNF Item not found in AAI response {}", Serialization.gsonPretty.toJson(aaiResponseWrapper),
144                             e);
145             return null;
146         }
147
148         try {
149             vnfServiceItem = vnfItem.getItems().getInventoryResponseItems().get(0);
150         } catch (Exception e) {
151             logger.error("VNF Service Item not found in AAI response {}",
152                             Serialization.gsonPretty.toJson(aaiResponseWrapper), e);
153             return null;
154         }
155
156         try {
157             tenantItem = aaiResponseWrapper.getAaiNqResponse().getInventoryResponseItems().get(0).getItems()
158                             .getInventoryResponseItems().get(1);
159         } catch (Exception e) {
160             logger.error("Tenant Item not found in AAI response {}",
161                             Serialization.gsonPretty.toJson(aaiResponseWrapper), e);
162             return null;
163         }
164
165         // Find the index for base vf module and non-base vf module
166         AaiNqInventoryResponseItem baseItem = findVfModule(aaiResponseWrapper, true);
167
168         SoModelInfo soModelInfo = prepareSoModelInfo(policy);
169
170         // Report the error if either base vf module or non-base vf module is not found
171         if (baseItem == null || soModelInfo == null) {
172             logger.error("Either base or non-base vf module is not found from AAI response.");
173             return null;
174         }
175
176         // Construct SO Request for a policy's recipe
177         if (RECIPE_VF_MODULE_CREATE.equals(policy.getRecipe())) {
178             return constructCreateRequest(aaiResponseWrapper, policy, tenantItem, vnfItem, vnfServiceItem,
179                     soModelInfo);
180         } else if (RECIPE_VF_MODULE_DELETE.equals(policy.getRecipe())) {
181             return constructDeleteRequest(tenantItem, vnfItem, vnfServiceItem, soModelInfo, policy);
182         } else {
183             return null;
184         }
185     }
186
187     private SoModelInfo prepareSoModelInfo(Policy policy) {
188
189         SoModelInfo soModelInfo = new SoModelInfo();
190         if ((policy.getTarget() != null
191                 && (policy.getTarget().getModelCustomizationId() != null))
192                 && (policy.getTarget().getModelInvariantId() != null)
193                 && (policy.getTarget().getModelName() != null)
194                 && (policy.getTarget().getModelVersion() != null)
195                 && (policy.getTarget().getModelVersionId() != null)) {
196
197             soModelInfo.setModelCustomizationId(policy.getTarget().getModelCustomizationId());
198             soModelInfo.setModelInvariantId(policy.getTarget().getModelInvariantId());
199             soModelInfo.setModelName(policy.getTarget().getModelName());
200             soModelInfo.setModelVersion(policy.getTarget().getModelVersion());
201             soModelInfo.setModelVersionId(policy.getTarget().getModelVersionId());
202
203             return soModelInfo;
204         } else {
205             return null;
206         }
207     }
208
209     /**
210      * Construct SO request to create vf-module.
211      *
212      * @param aaiResponseWrapper the AAI response containing the VF modules
213      * @param policy             the policy
214      * @param tenantItem         tenant item from A&AI named-query response
215      * @param vnfItem            vnf item from A&AI named-query response
216      * @param vnfServiceItem     vnf service item from A&AI named-query response
217      * @param vfModuleItem       vf module item from A&AI named-query response
218      * @return SO create vf-module request
219      */
220     private SoRequest constructCreateRequest(AaiNqResponseWrapper aaiResponseWrapper, Policy policy,
221                                              AaiNqInventoryResponseItem tenantItem, AaiNqInventoryResponseItem vnfItem,
222                                              AaiNqInventoryResponseItem vnfServiceItem,
223                                              SoModelInfo vfModuleItem) {
224         SoRequest request = new SoRequest();
225         request.setOperationType(SoOperationType.SCALE_OUT);
226         //
227         //
228         // Do NOT send So the requestId, they do not support this field
229         //
230         request.setRequestDetails(new SoRequestDetails());
231         request.getRequestDetails().setRequestParameters(new SoRequestParameters());
232         request.getRequestDetails().getRequestParameters().setUserParams(null);
233
234         // cloudConfiguration
235         request.getRequestDetails().setCloudConfiguration(constructCloudConfiguration(tenantItem));
236         // modelInfo
237         request.getRequestDetails().setModelInfo(vfModuleItem);
238
239         // requestInfo
240         request.getRequestDetails().setRequestInfo(constructRequestInfo());
241         String vfModuleName = aaiResponseWrapper.genVfModuleName();
242         request.getRequestDetails().getRequestInfo().setInstanceName(vfModuleName);
243
244         // relatedInstanceList
245         SoRelatedInstanceListElement relatedInstanceListElement1 = new SoRelatedInstanceListElement();
246         SoRelatedInstanceListElement relatedInstanceListElement2 = new SoRelatedInstanceListElement();
247         relatedInstanceListElement1.setRelatedInstance(new SoRelatedInstance());
248         relatedInstanceListElement2.setRelatedInstance(new SoRelatedInstance());
249
250         // Service Item
251         relatedInstanceListElement1.getRelatedInstance()
252                 .setInstanceId(vnfServiceItem.getServiceInstance().getServiceInstanceId());
253         relatedInstanceListElement1.getRelatedInstance().setModelInfo(new SoModelInfo());
254         relatedInstanceListElement1.getRelatedInstance().getModelInfo().setModelType("service");
255         relatedInstanceListElement1.getRelatedInstance().getModelInfo()
256                 .setModelInvariantId(vnfServiceItem.getServiceInstance().getModelInvariantId());
257         for (AaiNqExtraProperty prop : vnfServiceItem.getExtraProperties().getExtraProperty()) {
258             if (prop.getPropertyName().equals(MODEL_NAME_PROPERTY_KEY)) {
259                 relatedInstanceListElement1.getRelatedInstance().getModelInfo().setModelName(prop.getPropertyValue());
260             } else if (prop.getPropertyName().equals(MODEL_VERSION_PROPERTY_KEY)) {
261                 relatedInstanceListElement1.getRelatedInstance().getModelInfo()
262                         .setModelVersion(prop.getPropertyValue());
263             } else if (prop.getPropertyName().equals(MODEL_VERSION_ID_PROPERTY_KEY)) {
264                 relatedInstanceListElement1.getRelatedInstance().getModelInfo()
265                         .setModelVersionId(prop.getPropertyValue());
266             }
267         }
268
269         // VNF Item
270         relatedInstanceListElement2.getRelatedInstance().setInstanceId(vnfItem.getGenericVnf().getVnfId());
271         relatedInstanceListElement2.getRelatedInstance().setModelInfo(new SoModelInfo());
272         relatedInstanceListElement2.getRelatedInstance().getModelInfo().setModelType("vnf");
273         relatedInstanceListElement2.getRelatedInstance().getModelInfo()
274                 .setModelInvariantId(vnfItem.getGenericVnf().getModelInvariantId());
275         for (AaiNqExtraProperty prop : vnfItem.getExtraProperties().getExtraProperty()) {
276             if (prop.getPropertyName().equals(MODEL_NAME_PROPERTY_KEY)) {
277                 relatedInstanceListElement2.getRelatedInstance().getModelInfo().setModelName(prop.getPropertyValue());
278             } else if (prop.getPropertyName().equals(MODEL_VERSION_PROPERTY_KEY)) {
279                 relatedInstanceListElement2.getRelatedInstance().getModelInfo()
280                         .setModelVersion(prop.getPropertyValue());
281             } else if (prop.getPropertyName().equals(MODEL_VERSION_ID_PROPERTY_KEY)) {
282                 relatedInstanceListElement2.getRelatedInstance().getModelInfo()
283                         .setModelVersionId(prop.getPropertyValue());
284             }
285         }
286         relatedInstanceListElement2.getRelatedInstance().getModelInfo()
287                 .setModelCustomizationName(vnfItem.getGenericVnf().getVnfType()
288                         .substring(vnfItem.getGenericVnf().getVnfType().lastIndexOf('/') + 1));
289         relatedInstanceListElement2.getRelatedInstance().getModelInfo()
290                 .setModelCustomizationId(vnfItem.getGenericVnf().getModelCustomizationId());
291
292         // Insert the Service Item and VNF Item
293         request.getRequestDetails().getRelatedInstanceList().add(relatedInstanceListElement1);
294         request.getRequestDetails().getRelatedInstanceList().add(relatedInstanceListElement2);
295
296         // Request Parameters
297         buildRequestParameters(policy, request.getRequestDetails());
298
299         // Configuration Parameters
300         buildConfigurationParameters(policy, request.getRequestDetails());
301         // Save the instance IDs for the VNF and service to static fields
302         // vfModuleId is not required for the create vf-module
303         preserveInstanceIds(vnfItem.getGenericVnf().getVnfId(), vnfServiceItem.getServiceInstance()
304                 .getServiceInstanceId(), null);
305         if (logger.isDebugEnabled()) {
306             logger.debug("Constructed SO request: {}", Serialization.gsonPretty.toJson(request));
307         }
308         return request;
309     }
310
311     /**
312      * Construct SO request to delete vf-module.
313      *
314      * @param tenantItem         tenant item from A&AI named-query response
315      * @param vnfItem            vnf item from A&AI named-query response
316      * @param vnfServiceItem     vnf service item from A&AI named-query response
317      * @param vfModuleItem       vf module item from A&AI named-query response
318      * @return SO delete vf-module request
319      */
320     private SoRequest constructDeleteRequest(AaiNqInventoryResponseItem tenantItem, AaiNqInventoryResponseItem
321             vnfItem, AaiNqInventoryResponseItem vnfServiceItem, SoModelInfo vfModuleItem, Policy policy) {
322         SoRequest request = new SoRequest();
323         request.setOperationType(SoOperationType.DELETE_VF_MODULE);
324         request.setRequestDetails(new SoRequestDetails());
325         request.getRequestDetails().setRelatedInstanceList(null);
326         request.getRequestDetails().setConfigurationParameters(null);
327
328         // cloudConfiguration
329         request.getRequestDetails().setCloudConfiguration(constructCloudConfiguration(tenantItem));
330         // modelInfo
331         request.getRequestDetails().setModelInfo(prepareSoModelInfo(policy));
332         // requestInfo
333         request.getRequestDetails().setRequestInfo(constructRequestInfo());
334         // Save the instance IDs for the VNF, service and vfModule to static fields
335         preserveInstanceIds(vnfItem.getGenericVnf().getVnfId(), vnfServiceItem.getServiceInstance()
336                 .getServiceInstanceId(), null);
337
338         if (logger.isDebugEnabled()) {
339             logger.debug("Constructed SO request: {}", Serialization.gsonPretty.toJson(request));
340         }
341         return request;
342     }
343
344     /**
345      * Construct requestInfo for the SO requestDetails.
346      *
347      * @return SO request information
348      */
349     private SoRequestInfo constructRequestInfo() {
350         SoRequestInfo soRequestInfo = new SoRequestInfo();
351         soRequestInfo.setSource("POLICY");
352         soRequestInfo.setSuppressRollback(false);
353         soRequestInfo.setRequestorId("policy");
354         return soRequestInfo;
355     }
356
357     /**
358      * Construct cloudConfiguration for the SO requestDetails.
359      *
360      * @param tenantItem tenant item from A&AI named-query response
361      * @return SO cloud configuration
362      */
363     private SoCloudConfiguration constructCloudConfiguration(AaiNqInventoryResponseItem tenantItem) {
364         SoCloudConfiguration cloudConfiguration = new SoCloudConfiguration();
365         cloudConfiguration.setTenantId(tenantItem.getTenant().getTenantId());
366         cloudConfiguration.setLcpCloudRegionId(tenantItem.getItems().getInventoryResponseItems().get(0)
367                 .getCloudRegion().getCloudRegionId());
368         return cloudConfiguration;
369     }
370
371     /**
372      * This method is needed to get the serviceInstanceId and vnfInstanceId which is used
373      * in the asyncSORestCall.
374      *
375      * @param requestId the request Id
376      * @param callback callback method
377      * @param request the request
378      * @param url SO REST URL
379      * @param user username
380      * @param password password
381      */
382     public static void sendRequest(String requestId, SoManager.SoCallback callback, Object request,
383             String url, String user, String password) {
384         SoManager soManager = new SoManager(url, user, password);
385         soManager.asyncSoRestCall(requestId, callback, lastServiceItemServiceInstanceId, lastVNFItemVnfId,
386                 lastVfModuleItemVfModuleInstanceId, (SoRequest) request);
387     }
388
389     /**
390      * Find the base or non base VF module item in an AAI response.
391      * If there is more than one item, then the <i>last</i> item is returned
392      *
393      * @param aaiResponseWrapper the AAI response containing the VF modules
394      * @param baseFlag true if we are searching for the base, false if we are searching
395      *        for the non base
396      * @return the base or non base VF module item or null if the module was not found
397      */
398     private AaiNqInventoryResponseItem findVfModule(AaiNqResponseWrapper aaiResponseWrapper, boolean baseFlag) {
399         List<AaiNqInventoryResponseItem> lst = aaiResponseWrapper.getVfModuleItems(baseFlag);
400         return (lst.isEmpty() ? null : lst.get(lst.size() - 1));
401     }
402
403     /**
404      * Builds the request parameters from the policy payload.
405      *
406      * @param policy the policy
407      * @param request request into which to stick the request parameters
408      */
409     private void buildRequestParameters(Policy policy, SoRequestDetails request) {
410         // assume null until proven otherwise
411         request.setRequestParameters(null);
412
413         if (policy.getPayload() == null) {
414             return;
415         }
416
417         String json = policy.getPayload().get(REQ_PARAM_NM);
418         if (json == null) {
419             return;
420         }
421
422         request.setRequestParameters(Serialization.gsonPretty.fromJson(json, SoRequestParameters.class));
423     }
424
425     /**
426      * Builds the configuration parameters from the policy payload.
427      *
428      * @param policy the policy
429      * @param request request into which to stick the configuration parameters
430      */
431     private void buildConfigurationParameters(Policy policy, SoRequestDetails request) {
432         // assume null until proven otherwise
433         request.setConfigurationParameters(null);
434
435         if (policy.getPayload() == null) {
436             return;
437         }
438
439         String json = policy.getPayload().get(CONFIG_PARAM_NM);
440         if (json == null) {
441             return;
442         }
443
444         request.setConfigurationParameters(Serialization.gsonPretty.fromJson(json, CONFIG_TYPE));
445     }
446
447     /**
448      * This method is called to remember the last service instance ID, VNF Item VNF ID and vf module ID.
449      * Note these fields are static, beware for multithreaded deployments
450      *
451      * @param vnfInstanceId update the last VNF instance ID to this value
452      * @param serviceInstanceId update the last service instance ID to this value
453      * @param vfModuleId update the vfModule instance ID to this value
454      */
455     private static void preserveInstanceIds(final String vnfInstanceId, final String serviceInstanceId,
456                                             final String vfModuleId) {
457         lastVNFItemVnfId = vnfInstanceId;
458         lastServiceItemServiceInstanceId = serviceInstanceId;
459         lastVfModuleItemVfModuleInstanceId = vfModuleId;
460     }
461 }