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