Moving common polling code into HttpOperation
[policy/models.git] / models-interactions / model-actors / actor.so / src / main / java / org / onap / policy / controlloop / actor / so / VfModuleCreate.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2020 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.policy.controlloop.actor.so;
22
23 import java.util.Map;
24 import java.util.concurrent.CompletableFuture;
25 import javax.ws.rs.client.Entity;
26 import javax.ws.rs.core.MediaType;
27 import javax.ws.rs.core.Response;
28 import org.apache.commons.lang3.tuple.Pair;
29 import org.onap.aai.domain.yang.CloudRegion;
30 import org.onap.aai.domain.yang.GenericVnf;
31 import org.onap.aai.domain.yang.ServiceInstance;
32 import org.onap.aai.domain.yang.Tenant;
33 import org.onap.policy.aai.AaiConstants;
34 import org.onap.policy.aai.AaiCqResponse;
35 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
36 import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType;
37 import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome;
38 import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams;
39 import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpPollingConfig;
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.SoRequestParameters;
47 import org.onap.policy.so.SoResponse;
48
49 /**
50  * Operation to create a VF Module. This gets the VF count from the A&AI Custom Query
51  * response and stores it in the context. It also passes the count+1 to the guard. Once
52  * the "create" completes successfully, it bumps the VF count that's stored in the
53  * context.
54  */
55 public class VfModuleCreate extends SoOperation {
56     public static final String NAME = "VF Module Create";
57
58     private static final String PATH_PREFIX = "/";
59
60     /**
61      * Constructs the object.
62      *
63      * @param params operation parameters
64      * @param config configuration for this operation
65      */
66     public VfModuleCreate(ControlLoopOperationParams params, HttpPollingConfig config) {
67         super(params, config);
68
69         // ensure we have the necessary parameters
70         validateTarget();
71     }
72
73     /**
74      * Ensures that A&AI custom query has been performed, and then runs the guard.
75      */
76     @Override
77     @SuppressWarnings("unchecked")
78     protected CompletableFuture<OperationOutcome> startPreprocessorAsync() {
79
80         // need the VF count
81         ControlLoopOperationParams cqParams = params.toBuilder().actor(AaiConstants.ACTOR_NAME)
82                         .operation(AaiCqResponse.OPERATION).payload(null).retry(null).timeoutSec(null).build();
83
84         // run Custom Query, extract the VF count, and then run the Guard
85
86         // @formatter:off
87         return sequence(() -> params.getContext().obtain(AaiCqResponse.CONTEXT_KEY, cqParams),
88                         this::obtainVfCount, this::startGuardAsync);
89         // @formatter:on
90     }
91
92     @Override
93     protected Map<String, Object> makeGuardPayload() {
94         Map<String, Object> payload = super.makeGuardPayload();
95
96         // run guard with the proposed vf count
97         payload.put(PAYLOAD_KEY_VF_COUNT, getVfCount() + 1);
98
99         return payload;
100     }
101
102     @Override
103     protected CompletableFuture<OperationOutcome> startOperationAsync(int attempt, OperationOutcome outcome) {
104
105         // starting a whole new attempt - reset the count
106         resetPollCount();
107
108         Pair<String, SoRequest> pair = makeRequest();
109         String path = getPath() + pair.getLeft();
110         SoRequest request = pair.getRight();
111
112         String url = getClient().getBaseUrl() + path;
113
114         String strRequest = prettyPrint(request);
115         logMessage(EventType.OUT, CommInfrastructure.REST, url, strRequest);
116
117         Entity<String> entity = Entity.entity(strRequest, MediaType.APPLICATION_JSON);
118
119         Map<String, Object> headers = createSimpleHeaders();
120
121         return handleResponse(outcome, url, callback -> getClient().post(callback, path, entity, headers));
122     }
123
124     /**
125      * Increments the VF count that's stored in the context, if the request was
126      * successful.
127      */
128     @Override
129     protected Status detmStatus(Response rawResponse, SoResponse response) {
130         Status status = super.detmStatus(rawResponse, response);
131
132         if (status == Status.SUCCESS) {
133             setVfCount(getVfCount() + 1);
134         }
135
136         return status;
137     }
138
139     /**
140      * Makes a request.
141      *
142      * @return a pair containing the request URL and the new request
143      */
144     protected Pair<String, SoRequest> makeRequest() {
145         final AaiCqResponse aaiCqResponse = params.getContext().getProperty(AaiCqResponse.CONTEXT_KEY);
146         final SoModelInfo soModelInfo = prepareSoModelInfo();
147         final GenericVnf vnfItem = getVnfItem(aaiCqResponse, soModelInfo);
148         final ServiceInstance vnfServiceItem = getServiceInstance(aaiCqResponse);
149         final Tenant tenantItem = getDefaultTenant(aaiCqResponse);
150         final CloudRegion cloudRegionItem = getDefaultCloudRegion(aaiCqResponse);
151
152         SoRequest request = new SoRequest();
153         request.setOperationType(SoOperationType.SCALE_OUT);
154
155         //
156         //
157         // Do NOT send SO the requestId, they do not support this field
158         //
159         request.setRequestDetails(new SoRequestDetails());
160         request.getRequestDetails().setRequestParameters(new SoRequestParameters());
161         request.getRequestDetails().getRequestParameters().setUserParams(null);
162
163         // cloudConfiguration
164         request.getRequestDetails().setCloudConfiguration(constructCloudConfigurationCq(tenantItem, cloudRegionItem));
165
166         // modelInfo
167         request.getRequestDetails().setModelInfo(soModelInfo);
168
169         // requestInfo
170         request.getRequestDetails().setRequestInfo(constructRequestInfo());
171         request.getRequestDetails().getRequestInfo().setInstanceName("vfModuleName");
172
173         // relatedInstanceList
174         SoRelatedInstanceListElement relatedInstanceListElement1 = new SoRelatedInstanceListElement();
175         SoRelatedInstanceListElement relatedInstanceListElement2 = new SoRelatedInstanceListElement();
176         relatedInstanceListElement1.setRelatedInstance(new SoRelatedInstance());
177         relatedInstanceListElement2.setRelatedInstance(new SoRelatedInstance());
178
179         // Service Item
180         relatedInstanceListElement1.getRelatedInstance().setInstanceId(vnfServiceItem.getServiceInstanceId());
181         relatedInstanceListElement1.getRelatedInstance().setModelInfo(new SoModelInfo());
182         relatedInstanceListElement1.getRelatedInstance().getModelInfo().setModelType("service");
183         relatedInstanceListElement1.getRelatedInstance().getModelInfo()
184                         .setModelInvariantId(vnfServiceItem.getModelInvariantId());
185         relatedInstanceListElement1.getRelatedInstance().getModelInfo()
186                         .setModelVersionId(vnfServiceItem.getModelVersionId());
187         relatedInstanceListElement1.getRelatedInstance().getModelInfo().setModelName(
188                         aaiCqResponse.getModelVerByVersionId(vnfServiceItem.getModelVersionId()).getModelName());
189         relatedInstanceListElement1.getRelatedInstance().getModelInfo().setModelVersion(
190                         aaiCqResponse.getModelVerByVersionId(vnfServiceItem.getModelVersionId()).getModelVersion());
191
192         // VNF Item
193         relatedInstanceListElement2.getRelatedInstance().setInstanceId(vnfItem.getVnfId());
194         relatedInstanceListElement2.getRelatedInstance().setModelInfo(new SoModelInfo());
195         relatedInstanceListElement2.getRelatedInstance().getModelInfo().setModelType("vnf");
196         relatedInstanceListElement2.getRelatedInstance().getModelInfo()
197                         .setModelInvariantId(vnfItem.getModelInvariantId());
198         relatedInstanceListElement2.getRelatedInstance().getModelInfo().setModelVersionId(vnfItem.getModelVersionId());
199
200         relatedInstanceListElement2.getRelatedInstance().getModelInfo()
201                         .setModelName(aaiCqResponse.getModelVerByVersionId(vnfItem.getModelVersionId()).getModelName());
202         relatedInstanceListElement2.getRelatedInstance().getModelInfo().setModelVersion(
203                         aaiCqResponse.getModelVerByVersionId(vnfItem.getModelVersionId()).getModelVersion());
204
205         relatedInstanceListElement2.getRelatedInstance().getModelInfo()
206                         .setModelCustomizationId(vnfItem.getModelCustomizationId());
207
208         // Insert the Service Item and VNF Item
209         request.getRequestDetails().getRelatedInstanceList().add(relatedInstanceListElement1);
210         request.getRequestDetails().getRelatedInstanceList().add(relatedInstanceListElement2);
211
212         // Request Parameters
213         buildRequestParameters().ifPresent(request.getRequestDetails()::setRequestParameters);
214
215         // Configuration Parameters
216         buildConfigurationParameters().ifPresent(request.getRequestDetails()::setConfigurationParameters);
217
218         // compute the path
219         String path = PATH_PREFIX + vnfServiceItem.getServiceInstanceId() + "/vnfs/" + vnfItem.getVnfId()
220                         + "/vfModules/scaleOut";
221
222         return Pair.of(path, request);
223     }
224 }