Actor redesign.
[policy/models.git] / models-interactions / model-actors / actor.so / src / main / java / org / onap / policy / controlloop / actor / so / SoActorServiceProvider.java
1 /*
2  * ============LICENSE_START=======================================================
3  * SOActorServiceProvider
4  * ================================================================================
5  * Copyright (C) 2017-2020 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.aai.domain.yang.CloudRegion;
32 import org.onap.aai.domain.yang.GenericVnf;
33 import org.onap.aai.domain.yang.ServiceInstance;
34 import org.onap.aai.domain.yang.Tenant;
35 import org.onap.policy.aai.AaiCqResponse;
36 import org.onap.policy.controlloop.ControlLoopOperation;
37 import org.onap.policy.controlloop.VirtualControlLoopEvent;
38 import org.onap.policy.controlloop.actorserviceprovider.impl.ActorImpl;
39 import org.onap.policy.controlloop.policy.Policy;
40 import org.onap.policy.so.SoCloudConfiguration;
41 import org.onap.policy.so.SoManager;
42 import org.onap.policy.so.SoModelInfo;
43 import org.onap.policy.so.SoOperationType;
44 import org.onap.policy.so.SoRelatedInstance;
45 import org.onap.policy.so.SoRelatedInstanceListElement;
46 import org.onap.policy.so.SoRequest;
47 import org.onap.policy.so.SoRequestDetails;
48 import org.onap.policy.so.SoRequestInfo;
49 import org.onap.policy.so.SoRequestParameters;
50 import org.onap.policy.so.util.Serialization;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53
54 public class SoActorServiceProvider extends ActorImpl {
55     private static final Logger logger = LoggerFactory.getLogger(SoActorServiceProvider.class);
56
57     private static final String TENANT_NOT_FOUND = "Tenant Item not found in AAI response {}";
58     private static final String CONSTRUCTED_SO_MSG = "Constructed SO request: {}";
59
60     // Strings for SO Actor
61     private static final String SO_ACTOR = "SO";
62
63     // Strings for targets
64     private static final String TARGET_VFC = "VFC";
65
66     // Strings for recipes
67     private static final String RECIPE_VF_MODULE_CREATE = "VF Module Create";
68     private static final String RECIPE_VF_MODULE_DELETE = "VF Module Delete";
69
70     private static final ImmutableList<String> recipes =
71             ImmutableList.of(RECIPE_VF_MODULE_CREATE, RECIPE_VF_MODULE_DELETE);
72     private static final ImmutableMap<String, List<String>> targets =
73             new ImmutableMap.Builder<String, List<String>>().put(RECIPE_VF_MODULE_CREATE, ImmutableList.of(TARGET_VFC))
74                     .put(RECIPE_VF_MODULE_DELETE, ImmutableList.of(TARGET_VFC)).build();
75
76     // name of request parameters within policy payload
77     public static final String REQ_PARAM_NM = "requestParameters";
78
79     // name of configuration parameters within policy payload
80     public static final String CONFIG_PARAM_NM = "configurationParameters";
81
82     // used to decode configuration parameters via gson
83     private static final Type CONFIG_TYPE = new TypeToken<List<Map<String, String>>>() {}.getType();
84
85     // Static variables required to hold the IDs of the last service item, VNF item and VF Module.
86     // Note that in
87     // a multithreaded deployment this WILL break
88     private static String lastVNFItemVnfId;
89     private static String lastServiceItemServiceInstanceId;
90     private static String lastVfModuleItemVfModuleInstanceId;
91
92     public SoActorServiceProvider() {
93         super(SO_ACTOR);
94     }
95
96     @Override
97     public String actor() {
98         return SO_ACTOR;
99     }
100
101     @Override
102     public List<String> recipes() {
103         return ImmutableList.copyOf(recipes);
104     }
105
106     @Override
107     public List<String> recipeTargets(String recipe) {
108         return ImmutableList.copyOf(targets.getOrDefault(recipe, Collections.emptyList()));
109     }
110
111     @Override
112     public List<String> recipePayloads(String recipe) {
113         return Collections.emptyList();
114     }
115
116     private SoModelInfo prepareSoModelInfo(Policy policy) {
117
118         if (policy.getTarget() == null || policy.getTarget().getModelCustomizationId() == null
119                         || policy.getTarget().getModelInvariantId() == null) {
120             return null;
121         }
122
123         if (policy.getTarget().getModelName() == null || policy.getTarget().getModelVersion() == null
124                         || policy.getTarget().getModelVersionId() == null) {
125             return null;
126         }
127
128         SoModelInfo soModelInfo = new SoModelInfo();
129         soModelInfo.setModelCustomizationId(policy.getTarget().getModelCustomizationId());
130         soModelInfo.setModelInvariantId(policy.getTarget().getModelInvariantId());
131         soModelInfo.setModelName(policy.getTarget().getModelName());
132         soModelInfo.setModelVersion(policy.getTarget().getModelVersion());
133         soModelInfo.setModelVersionId(policy.getTarget().getModelVersionId());
134         soModelInfo.setModelType("vfModule");
135         return soModelInfo;
136     }
137
138     /**
139      * Construct requestInfo for the SO requestDetails.
140      *
141      * @return SO request information
142      */
143     private SoRequestInfo constructRequestInfo() {
144         SoRequestInfo soRequestInfo = new SoRequestInfo();
145         soRequestInfo.setSource("POLICY");
146         soRequestInfo.setSuppressRollback(false);
147         soRequestInfo.setRequestorId("policy");
148         return soRequestInfo;
149     }
150
151     /**
152      * This method is needed to get the serviceInstanceId and vnfInstanceId which is used in the asyncSORestCall.
153      *
154      * @param requestId the request Id
155      * @param callback callback method
156      * @param request the request
157      * @param url SO REST URL
158      * @param user username
159      * @param password password
160      */
161     public static void sendRequest(String requestId, SoManager.SoCallback callback, Object request, String url,
162             String user, String password) {
163         SoManager soManager = new SoManager(url, user, password);
164         soManager.asyncSoRestCall(requestId, callback, lastServiceItemServiceInstanceId, lastVNFItemVnfId,
165                 lastVfModuleItemVfModuleInstanceId, (SoRequest) request);
166     }
167
168
169     /**
170      * Builds the request parameters from the policy payload.
171      *
172      * @param policy the policy
173      * @param request request into which to stick the request parameters
174      */
175     private void buildRequestParameters(Policy policy, SoRequestDetails request) {
176         // assume null until proven otherwise
177         request.setRequestParameters(null);
178
179         if (policy.getPayload() == null) {
180             return;
181         }
182
183         String json = policy.getPayload().get(REQ_PARAM_NM);
184         if (json == null) {
185             return;
186         }
187
188         request.setRequestParameters(Serialization.gsonPretty.fromJson(json, SoRequestParameters.class));
189     }
190
191     /**
192      * Builds the configuration parameters from the policy payload.
193      *
194      * @param policy the policy
195      * @param request request into which to stick the configuration parameters
196      */
197     private void buildConfigurationParameters(Policy policy, SoRequestDetails request) {
198         // assume null until proven otherwise
199         request.setConfigurationParameters(null);
200
201         if (policy.getPayload() == null) {
202             return;
203         }
204
205         String json = policy.getPayload().get(CONFIG_PARAM_NM);
206         if (json == null) {
207             return;
208         }
209
210         request.setConfigurationParameters(Serialization.gsonPretty.fromJson(json, CONFIG_TYPE));
211     }
212
213     /**
214      * This method is called to remember the last service instance ID, VNF Item VNF ID and vf module ID. Note these
215      * fields are static, beware for multithreaded deployments
216      *
217      * @param vnfInstanceId update the last VNF instance ID to this value
218      * @param serviceInstanceId update the last service instance ID to this value
219      * @param vfModuleId update the vfModule instance ID to this value
220      */
221     private static void preserveInstanceIds(final String vnfInstanceId, final String serviceInstanceId,
222             final String vfModuleId) {
223         lastVNFItemVnfId = vnfInstanceId;
224         lastServiceItemServiceInstanceId = serviceInstanceId;
225         lastVfModuleItemVfModuleInstanceId = vfModuleId;
226     }
227
228     /**
229      * Constructs a SO request conforming to the lcm API. The actual request is constructed and then placed in a wrapper
230      * object used to send through DMAAP.
231      *
232      * @param onset the event that is reporting the alert for policy to perform an action
233      * @param operation the control loop operation specifying the actor, operation, target, etc.
234      * @param policy the policy the was specified from the yaml generated by CLAMP or through the Policy GUI/API
235      * @param aaiCqResponse response from A&AI custom query
236      * @return a SO request conforming to the lcm API using the DMAAP wrapper
237      */
238     public SoRequest constructRequestCq(VirtualControlLoopEvent onset, ControlLoopOperation operation, Policy policy,
239             AaiCqResponse aaiCqResponse) {
240         if (!SO_ACTOR.equals(policy.getActor()) || !recipes().contains(policy.getRecipe())) {
241             return null;
242         }
243
244         // A&AI named query should have been performed by now. If not, return null
245         if (aaiCqResponse == null) {
246             return null;
247         }
248
249         SoModelInfo soModelInfo = prepareSoModelInfo(policy);
250
251         // Report the error vf module is not found
252         if (soModelInfo == null) {
253             logger.error("vf module is not found.");
254             return null;
255         }
256
257         GenericVnf vnfItem;
258         ServiceInstance vnfServiceItem;
259         Tenant tenantItem;
260         CloudRegion cloudRegionItem;
261
262         // Extract the items we're interested in from the response
263         try {
264             vnfItem = aaiCqResponse.getGenericVnfByVfModuleModelInvariantId(soModelInfo.getModelInvariantId());
265             //Report VNF not found
266             if (vnfItem == null) {
267                 logger.error("Generic Vnf is not found.");
268                 return null;
269             }
270         } catch (Exception e) {
271             logger.error("VNF Item not found in AAI response {}", Serialization.gsonPretty.toJson(aaiCqResponse), e);
272             return null;
273         }
274
275         try {
276             vnfServiceItem = aaiCqResponse.getServiceInstance();
277         } catch (Exception e) {
278             logger.error("VNF Service Item not found in AAI response {}",
279                     Serialization.gsonPretty.toJson(aaiCqResponse), e);
280             return null;
281         }
282
283         try {
284             tenantItem = aaiCqResponse.getDefaultTenant();
285         } catch (Exception e) {
286             logger.error(TENANT_NOT_FOUND, Serialization.gsonPretty.toJson(aaiCqResponse), e);
287             return null;
288         }
289
290         try {
291             cloudRegionItem = aaiCqResponse.getDefaultCloudRegion();
292         } catch (Exception e) {
293             logger.error(TENANT_NOT_FOUND, Serialization.gsonPretty.toJson(aaiCqResponse), e);
294             return null;
295         }
296
297
298
299         // Construct SO Request for a policy's recipe
300         if (RECIPE_VF_MODULE_CREATE.equals(policy.getRecipe())) {
301             return constructCreateRequestCq(aaiCqResponse, policy, tenantItem, vnfItem, vnfServiceItem, soModelInfo,
302                     cloudRegionItem);
303         } else if (RECIPE_VF_MODULE_DELETE.equals(policy.getRecipe())) {
304             return constructDeleteRequestCq(tenantItem, vnfItem, vnfServiceItem, policy, cloudRegionItem);
305         } else {
306             return null;
307         }
308     }
309
310     /**
311      * Construct the So request, based on Custom Query response from A&AI.
312      *
313      * @param aaiCqResponse Custom query response from A&AI
314      * @param policy policy information
315      * @param tenantItem Tenant from CQ response
316      * @param vnfItem Generic VNF from CQ response
317      * @param vnfServiceItem Service Instance from CQ response
318      * @param vfModuleItem VF Module from CustomQuery response
319      * @param cloudRegionItem Cloud Region from Custom query response
320      * @return SoRequest well formed So Request
321      */
322     private SoRequest constructCreateRequestCq(AaiCqResponse aaiCqResponse, Policy policy, Tenant tenantItem,
323             GenericVnf vnfItem, ServiceInstance vnfServiceItem, SoModelInfo vfModuleItem, CloudRegion cloudRegionItem) {
324         SoRequest request = new SoRequest();
325         request.setOperationType(SoOperationType.SCALE_OUT);
326         //
327         //
328         // Do NOT send So the requestId, they do not support this field
329         //
330         request.setRequestDetails(new SoRequestDetails());
331         request.getRequestDetails().setRequestParameters(new SoRequestParameters());
332         request.getRequestDetails().getRequestParameters().setUserParams(null);
333
334         // cloudConfiguration
335         request.getRequestDetails().setCloudConfiguration(constructCloudConfigurationCq(tenantItem, cloudRegionItem));
336         // modelInfo
337         request.getRequestDetails().setModelInfo(vfModuleItem);
338
339
340         // requestInfo
341         request.getRequestDetails().setRequestInfo(constructRequestInfo());
342         request.getRequestDetails().getRequestInfo().setInstanceName("vfModuleName");
343
344         // relatedInstanceList
345         SoRelatedInstanceListElement relatedInstanceListElement1 = new SoRelatedInstanceListElement();
346         SoRelatedInstanceListElement relatedInstanceListElement2 = new SoRelatedInstanceListElement();
347         relatedInstanceListElement1.setRelatedInstance(new SoRelatedInstance());
348         relatedInstanceListElement2.setRelatedInstance(new SoRelatedInstance());
349
350         // Service Item
351         relatedInstanceListElement1.getRelatedInstance().setInstanceId(vnfServiceItem.getServiceInstanceId());
352         relatedInstanceListElement1.getRelatedInstance().setModelInfo(new SoModelInfo());
353         relatedInstanceListElement1.getRelatedInstance().getModelInfo().setModelType("service");
354         relatedInstanceListElement1.getRelatedInstance().getModelInfo()
355                 .setModelInvariantId(vnfServiceItem.getModelInvariantId());
356         relatedInstanceListElement1.getRelatedInstance().getModelInfo()
357                 .setModelVersionId(vnfServiceItem.getModelVersionId());
358         relatedInstanceListElement1.getRelatedInstance().getModelInfo()
359                 .setModelName(aaiCqResponse.getModelVerByVersionId(vnfServiceItem.getModelVersionId()).getModelName());
360         relatedInstanceListElement1.getRelatedInstance().getModelInfo().setModelVersion(
361                 aaiCqResponse.getModelVerByVersionId(vnfServiceItem.getModelVersionId()).getModelVersion());
362
363
364         // VNF Item
365         relatedInstanceListElement2.getRelatedInstance().setInstanceId(vnfItem.getVnfId());
366         relatedInstanceListElement2.getRelatedInstance().setModelInfo(new SoModelInfo());
367         relatedInstanceListElement2.getRelatedInstance().getModelInfo().setModelType("vnf");
368         relatedInstanceListElement2.getRelatedInstance().getModelInfo()
369                 .setModelInvariantId(vnfItem.getModelInvariantId());
370         relatedInstanceListElement2.getRelatedInstance().getModelInfo().setModelVersionId(vnfItem.getModelVersionId());
371
372         relatedInstanceListElement2.getRelatedInstance().getModelInfo()
373                 .setModelName(aaiCqResponse.getModelVerByVersionId(vnfItem.getModelVersionId()).getModelName());
374         relatedInstanceListElement2.getRelatedInstance().getModelInfo().setModelVersion(
375                 aaiCqResponse.getModelVerByVersionId(vnfItem.getModelVersionId()).getModelVersion());
376
377
378         relatedInstanceListElement2.getRelatedInstance().getModelInfo()
379                 .setModelCustomizationId(vnfItem.getModelCustomizationId());
380
381
382         // Insert the Service Item and VNF Item
383         request.getRequestDetails().getRelatedInstanceList().add(relatedInstanceListElement1);
384         request.getRequestDetails().getRelatedInstanceList().add(relatedInstanceListElement2);
385
386         // Request Parameters
387         buildRequestParameters(policy, request.getRequestDetails());
388
389         // Configuration Parameters
390         buildConfigurationParameters(policy, request.getRequestDetails());
391         // Save the instance IDs for the VNF and service to static fields
392         // vfModuleId is not required for the create vf-module
393         preserveInstanceIds(vnfItem.getVnfId(), vnfServiceItem.getServiceInstanceId(), null);
394         if (logger.isDebugEnabled()) {
395             logger.debug(CONSTRUCTED_SO_MSG, Serialization.gsonPretty.toJson(request));
396         }
397         return request;
398     }
399
400     /**
401      * constructs delete request for So.
402      *
403      * @param tenantItem Tenant from A&AI CQ request
404      * @param vnfItem Generic VNF from A&AI CQ request
405      * @param vnfServiceItem ServiceInstance from A&AI CQ request
406      * @param policy policy information
407      * @param cloudRegionItem CloudRegion from A&AI CQ request
408      * @return SoRequest deleted
409      */
410     private SoRequest constructDeleteRequestCq(Tenant tenantItem, GenericVnf vnfItem, ServiceInstance vnfServiceItem,
411             Policy policy, CloudRegion cloudRegionItem) {
412         SoRequest request = new SoRequest();
413         request.setOperationType(SoOperationType.DELETE_VF_MODULE);
414         request.setRequestDetails(new SoRequestDetails());
415         request.getRequestDetails().setRelatedInstanceList(null);
416         request.getRequestDetails().setConfigurationParameters(null);
417
418         // cloudConfiguration
419         request.getRequestDetails().setCloudConfiguration(constructCloudConfigurationCq(tenantItem, cloudRegionItem));
420         // modelInfo
421         request.getRequestDetails().setModelInfo(prepareSoModelInfo(policy));
422         // requestInfo
423         request.getRequestDetails().setRequestInfo(constructRequestInfo());
424         // Save the instance IDs for the VNF, service and vfModule to static fields
425         preserveInstanceIds(vnfItem.getVnfId(), vnfServiceItem.getServiceInstanceId(), null);
426
427         if (logger.isDebugEnabled()) {
428             logger.debug(CONSTRUCTED_SO_MSG, Serialization.gsonPretty.toJson(request));
429         }
430         return request;
431     }
432
433
434     /**
435      * Construct cloudConfiguration for the SO requestDetails. Overridden for custom query.
436      *
437      * @param tenantItem tenant item from A&AI named-query response
438      * @return SO cloud configuration
439      */
440     private SoCloudConfiguration constructCloudConfigurationCq(Tenant tenantItem, CloudRegion cloudRegionItem) {
441         SoCloudConfiguration cloudConfiguration = new SoCloudConfiguration();
442         cloudConfiguration.setTenantId(tenantItem.getTenantId());
443         cloudConfiguration.setLcpCloudRegionId(cloudRegionItem.getCloudRegionId());
444         return cloudConfiguration;
445     }
446
447 }