Fix k8s artifact url for upload
[multicloud/framework.git] / artifactbroker / plugins / forwarding-plugins / src / main / java / org / onap / policy / distribution / forwarding / k8s / K8sArtifactForwarder.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2018 Ericsson. All rights reserved.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.distribution.forwarding.k8s;
22
23 import com.google.gson.Gson;
24 import com.google.gson.GsonBuilder;
25 import com.google.gson.reflect.TypeToken;
26
27 import java.io.File;
28 import java.io.IOException;
29 import java.util.ArrayList;
30 import java.util.Collection;
31 import java.util.Collections;
32 import java.util.LinkedHashMap;
33 import java.util.List;
34 import java.util.Map;
35
36
37 import org.apache.http.HttpEntity;
38 import org.apache.http.NameValuePair;
39 import org.apache.http.client.ClientProtocolException;
40 import org.apache.http.client.entity.UrlEncodedFormEntity;
41 import org.apache.http.client.methods.CloseableHttpResponse;
42 import org.apache.http.client.methods.HttpGet;
43 import org.apache.http.client.methods.HttpPost;
44 import org.apache.http.entity.FileEntity;
45 import org.apache.http.entity.StringEntity;
46 import org.apache.http.impl.client.CloseableHttpClient;
47 import org.apache.http.impl.client.HttpClients;
48 import org.apache.http.message.BasicNameValuePair;
49 import org.apache.http.util.EntityUtils;
50
51 import org.onap.policy.common.logging.flexlogger.FlexLogger;
52 import org.onap.policy.common.logging.flexlogger.Logger;
53 import org.onap.policy.common.parameters.ParameterService;
54 import org.onap.policy.distribution.forwarding.ArtifactForwarder;
55 import org.onap.policy.distribution.model.CloudArtifact;
56 import org.onap.policy.distribution.model.PolicyInput;
57 import org.onap.policy.distribution.model.VfModuleModel;
58 import org.onap.sdc.api.notification.IArtifactInfo;
59
60
61 /**
62  * Forwards policies to the XACML PDP.
63  */
64 public class K8sArtifactForwarder implements ArtifactForwarder {
65
66     private static final Logger LOGGER = FlexLogger.getLogger(K8sArtifactForwarder.class);
67     private static final String BASE_PATH = "http://localhost:9015/v1/rb/definition";
68     private static final String CLOUD_TECHNOLOGY_SPECIFIC_ARTIFACT = "CLOUD_TECHNOLOGY_SPECIFIC_ARTIFACT";
69     private Map<String, IArtifactInfo> artifactMap;
70
71     private K8sArtifactForwarderParameterGroup configurationParameters = null;
72
73
74
75     @Override
76     public void forward(PolicyInput  policyInput) {
77         if (policyInput instanceof CloudArtifact) {
78             System.out.println("get a CloudArtifact !");
79             CloudArtifact cloudArtifact = (CloudArtifact) policyInput;
80             artifactMap = cloudArtifact.getArtifactTypeMap();
81             System.out.println("the artifactMap = " + artifactMap);
82             ArrayList<VfModuleModel> vfModuleModels = cloudArtifact.getVfModulePayload();
83             System.out.println("the size of vfModule = " + vfModuleModels.size());
84
85             for (VfModuleModel vfModule : vfModuleModels) {
86                 forwardAndUpload(vfModule);
87             }
88         } else {
89             System.out.println("NOT a CloudArtifact type !");
90             return;
91         }
92     }
93
94     private void forwardAndUpload(VfModuleModel vfModule) {
95
96         System.out.println("before create type !");
97         boolean definitionCreated = createDefinition(vfModule);
98         System.out.println(" after create type !");
99         if (definitionCreated) {
100             uploadArtifact(vfModule);
101         }
102     }
103
104     private boolean createDefinition(VfModuleModel vfModule) {
105         try {
106             HttpPost httpPost = new HttpPost(BASE_PATH);
107             httpPost.addHeader("Accept", "application/json");
108             httpPost.addHeader("Content-Type", "application/json");
109
110             Gson gson = new GsonBuilder().enableComplexMapKeySerialization()
111                 .create();
112
113             Map<String, Object> map = new LinkedHashMap<String, Object>();
114             map.put("rb-name", vfModule.getVfModuleModelInvariantUUID());
115             map.put("rb-version", vfModule.getVfModuleModelUUID());
116             map.put("descritpion",vfModule.getVfModuleModelDescription());
117             Map<String, String> labelMap = new LinkedHashMap<String, String>();
118             labelMap.put("vnf_customization_uuid",vfModule.getVfModuleModelCustomizationUUID());
119             map.put("labels", labelMap);
120             String json = gson.toJson(map);
121
122             StringEntity entity = new StringEntity(json);
123             httpPost.setEntity(entity);
124             return invokeHttpPost("definition", httpPost);
125         } catch (Exception e) {
126             System.out.println("create definition error");
127             return false;
128         }
129
130     }
131
132     private boolean uploadArtifact(VfModuleModel vfModule) {
133         String url = BASE_PATH + "/" + vfModule.getVfModuleModelInvariantUUID() + "/"
134             + vfModule.getVfModuleModelUUID() + "/content";
135         HttpPost httpPost = new HttpPost(url);
136         httpPost.addHeader("content-type", "application/x-www-form-urlencoded;charset=utf-8");
137
138         List<String> artifacts = vfModule.getArtifacts();
139         System.out.println("artifacts = " + artifacts);
140
141         String vfNamePrefix = vfModule.getVfModuleModelName().toLowerCase();
142         if ( vfNamePrefix.indexOf("..") > 0 ) {
143             vfNamePrefix = vfNamePrefix.substring(vfNamePrefix.indexOf("..") + 2);
144             if ( vfNamePrefix.indexOf("..") > 0 )
145                 vfNamePrefix = vfNamePrefix.substring(0, vfNamePrefix.indexOf("..")) + "_";
146             else
147                 vfNamePrefix = "";
148         } else
149             vfNamePrefix = "";
150
151         IArtifactInfo cloudArtifact = null;
152         IArtifactInfo firstCloudArtifact = null;
153         int cloudArtifactCount = 0;
154         boolean found = false;
155
156         for (String artifact: artifacts) {
157             if ( artifactMap.get(artifact) != null
158                 && artifactMap.get(artifact).getArtifactType().equals("CLOUD_TECHNOLOGY_SPECIFIC_ARTIFACT")) {
159                 if ( cloudArtifactCount == 0 )
160                     firstCloudArtifact = artifactMap.get(artifact);
161                 cloudArtifactCount++;
162                 IArtifactInfo tmpArtifact = artifactMap.get(artifact);
163                 if ( tmpArtifact.getArtifactName().toLowerCase().startsWith(vfNamePrefix) ) {
164                     cloudArtifact = tmpArtifact;
165                     found = true;
166                     break;
167                 }
168             }
169         }
170
171         if ( found == false  ) {
172             if ( firstCloudArtifact == null ) {
173                 System.out.println(" meets error , no CLOUD_TECHNOLOGY_SPECIFIC_ARTIFACT type found ");
174                 return false;
175             } else {
176                 if ( cloudArtifactCount == 1 || vfNamePrefix == "" ) {
177                     cloudArtifact = firstCloudArtifact;
178                 } else {
179                     System.out.println(" meets error , CLOUD_TECHNOLOGY_SPECIFIC_ARTIFACT artifacts mismatch ");
180                     return false;
181                 }
182             }
183         }
184
185         String cloudArtifactPath = "/data/" + vfModule.getVfModuleModelCustomizationUUID()
186             + "/" + cloudArtifact.getArtifactName();
187         File file = new File(cloudArtifactPath);
188         FileEntity entity = new FileEntity(file);
189         httpPost.setEntity(entity);
190
191         return invokeHttpPost("uploading", httpPost);
192     }
193
194
195     @Override
196     public void configure(String parameterGroupName) {
197         configurationParameters = ParameterService.get(parameterGroupName);
198     }
199
200     protected static boolean invokeHttpPost(String action, HttpPost httpPost)  {
201         System.out.println("httpPost URI: " + httpPost);
202         boolean ret = false;
203
204         String errorMsg;
205         label1: {
206             try ( CloseableHttpClient httpClient = HttpClients.createDefault() ) {
207                 System.out.println("Execute Post Body: " + EntityUtils.toString(httpPost.getEntity()));
208                 CloseableHttpResponse closeableHttpResponse = httpClient.execute(httpPost);
209                 System.out.println("result2");
210                 String result = EntityUtils.toString(closeableHttpResponse.getEntity());
211                 System.out.println("result = {}" + result);
212                 System.out.println("status  = {}" + closeableHttpResponse.getStatusLine().getStatusCode());
213                 int status = closeableHttpResponse.getStatusLine().getStatusCode();
214                 // [200, 300] means pass
215                 if ( (status >=200) && (status <= 300) ) {
216                     ret = true;
217                 } else {
218                     System.out.println("exception: ret= " + status);
219                 }
220
221                 closeableHttpResponse.close();
222                 break label1;
223             } catch (IOException exp) {
224                 errorMsg = action + " :invokeHttpPost failed with: " + exp.getMessage();
225                 System.out.println("exception: POST FAILED : {}" + errorMsg);
226             }
227         }
228
229         System.out.println("httpPost end!");
230         return ret;
231     }
232
233 }