feat:Add file transfer function
[usecase-ui/server.git] / server / src / main / java / org / onap / usecaseui / server / service / intent / impl / IntentInstanceServiceImpl.java
1 /*
2  * Copyright (C) 2021 CTC, Inc. and others. All rights reserved.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package org.onap.usecaseui.server.service.intent.impl;
17
18 import com.alibaba.fastjson.JSON;
19 import com.alibaba.fastjson.JSONArray;
20 import com.alibaba.fastjson.JSONObject;
21 import org.hibernate.Query;
22 import org.hibernate.Session;
23 import org.hibernate.SessionFactory;
24 import org.hibernate.Transaction;
25 import org.onap.usecaseui.server.bean.intent.InstancePerformance;
26 import org.onap.usecaseui.server.bean.intent.IntentInstance;
27 import org.onap.usecaseui.server.service.intent.IntentApiService;
28 import org.onap.usecaseui.server.service.intent.IntentInstanceService;
29 import org.onap.usecaseui.server.service.lcm.domain.so.SOService;
30 import org.onap.usecaseui.server.service.lcm.domain.so.bean.OperationProgressInformation;
31 import org.onap.usecaseui.server.util.Page;
32 import org.onap.usecaseui.server.util.RestfulServices;
33 import org.onap.usecaseui.server.util.UuiCommonUtil;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36 import org.springframework.beans.factory.annotation.Autowired;
37 import org.springframework.context.annotation.EnableAspectJAutoProxy;
38 import org.springframework.stereotype.Service;
39 import retrofit2.Response;
40
41 import javax.transaction.Transactional;
42 import java.io.IOException;
43 import java.text.SimpleDateFormat;
44 import java.util.*;
45
46 @Service("IntentInstanceService")
47 @Transactional
48 @org.springframework.context.annotation.Configuration
49 @EnableAspectJAutoProxy
50 public class IntentInstanceServiceImpl implements IntentInstanceService {
51     private static final Logger logger = LoggerFactory.getLogger(IntentInstanceServiceImpl.class);
52
53     @Autowired
54     private SessionFactory sessionFactory;
55
56
57     private IntentApiService intentApiService;
58
59     private SOService soService;
60
61     public IntentInstanceServiceImpl() {
62         this(RestfulServices.create(IntentApiService.class),RestfulServices.create(SOService.class));
63     }
64     public IntentInstanceServiceImpl(IntentApiService intentApiService, SOService soService) {
65         this.intentApiService = intentApiService;
66         this.soService = soService;
67     }
68
69     private Session getSession() {
70         return sessionFactory.openSession();
71     }
72
73     @Override
74     public Page<IntentInstance> queryIntentInstance(IntentInstance intentInstance, int currentPage, int pageSize) {
75         Page<IntentInstance> page = new Page<IntentInstance>();
76         int allRow =this.getAllCount(intentInstance,currentPage,pageSize);
77         int offset = page.countOffset(currentPage, pageSize);
78         Session session = getSession();
79         try{
80             StringBuffer hql =new StringBuffer("from IntentInstance a where deleteState = 0");
81             if (null != intentInstance) {
82                 if(UuiCommonUtil.isNotNullOrEmpty(intentInstance.getInstanceId())) {
83                     String ver =intentInstance.getInstanceId();
84                     hql.append(" and a.instance_id = '"+ver+"'");
85                 }
86                 if(UuiCommonUtil.isNotNullOrEmpty(intentInstance.getJobId())) {
87                     String ver =intentInstance.getJobId();
88                     hql.append(" and a.job_id = '"+ver+"'");
89                 }
90                 if(UuiCommonUtil.isNotNullOrEmpty(intentInstance.getStatus())) {
91                     String ver =intentInstance.getStatus();
92                     hql.append(" and a.status = '"+ver+"'");
93                 }
94             }
95             hql.append(" order by id");
96             logger.info("AlarmsHeaderServiceImpl queryIntentInstance: intentInstance={}", intentInstance);
97             Query query = session.createQuery(hql.toString());
98             query.setFirstResult(offset);
99             query.setMaxResults(pageSize);
100             List<IntentInstance> list= query.list();
101             page.setPageNo(currentPage);
102             page.setPageSize(pageSize);
103             page.setTotalRecords(allRow);
104             page.setList(list);
105             return page;
106         } catch (Exception e) {
107             logger.error("exception occurred while performing AlarmsHeaderServiceImpl queryAlarmsHeader. Details:" + e.getMessage());
108             return null;
109         }
110     }
111
112
113     public int getAllCount(IntentInstance intentInstance,int currentPage,int pageSize) {
114         Session session = getSession();
115         try{
116             StringBuffer count=new StringBuffer("select count(*) from IntentInstance a where deleteState = 0");
117             if (null != intentInstance) {
118                 if(UuiCommonUtil.isNotNullOrEmpty(intentInstance.getInstanceId())) {
119                     String ver =intentInstance.getInstanceId();
120                     count.append(" and a.instance_id = '"+ver+"'");
121                 }
122                 if(UuiCommonUtil.isNotNullOrEmpty(intentInstance.getJobId())) {
123                     String ver =intentInstance.getJobId();
124                     count.append(" and a.job_id = '"+ver+"'");
125                 }
126                 if(UuiCommonUtil.isNotNullOrEmpty(intentInstance.getStatus())) {
127                     String ver =intentInstance.getStatus();
128                     count.append(" and a.status = '"+ver+"'");
129                 }
130             }
131             Query query = session.createQuery(count.toString());
132             long q=(long)query.uniqueResult();
133             return (int)q;
134         } catch (Exception e) {
135             logger.error("exception occurred while performing IntentInstanceServiceImpl getAllCount. Details:" + e.getMessage());
136             return -1;
137         }
138     }
139
140     @Override
141     public int createIntentInstance(IntentInstance intentInstance) {
142         try{
143
144             if (null == intentInstance){
145                 logger.error("intentInstance is null!");
146                 return 0;
147             }
148             String jobId = createIntentInstanceToSO(intentInstance);
149             intentInstance.setJobId(jobId);
150             intentInstance.setResourceInstanceId("cll-"+intentInstance.getInstanceId());
151             Session session = getSession();
152             Transaction tx = session.beginTransaction();
153             session.save(intentInstance);
154             tx.commit();
155 //            session.flush();
156             return 1;
157         } catch (Exception e) {
158             logger.error("Details:" + e.getMessage());
159             return 0;
160         }
161     }
162
163     private String createIntentInstanceToSO(IntentInstance intentInstance) throws IOException {
164         Map<String, Object> params = new HashMap<>();
165         params.put("name", intentInstance.getName());
166         params.put("modelInvariantUuid", "6790ab0e-034f-11eb-adc1-0242ac120002");
167         params.put("modelUuid", "6790ab0e-034f-11eb-adc1-0242ac120002");
168         params.put("globalSubscriberId", "IBNCustomer");
169         params.put("subscriptionServiceType", "IBN");
170         params.put("serviceType", "CLL");
171         Map<String, Object> additionalProperties = new HashMap<>();
172         additionalProperties.put("enableSdnc", "false");
173         additionalProperties.put("serviceInstanceID", "cll-" + intentInstance.getInstanceId());
174         List<Map<String, Object>> transportNetworks = new ArrayList<>();
175         Map<String, Object> transportNetwork = new HashMap<>();
176         transportNetwork.put("id", "");
177         Map<String, Object> sla = new HashMap<>();
178         sla.put("latency", "2");
179         sla.put("maxBandwidth", intentInstance.getAccessPointOneBandWidth());
180         List<Map<String, Object>> connectionLinks = new ArrayList<>();
181         Map<String, Object> connectionLink = new HashMap<>();
182         connectionLink.put("name", "");
183         connectionLink.put("transportEndpointA", intentInstance.getAccessPointOneName());
184         connectionLink.put("transportEndpointB", intentInstance.getCloudPointName());
185         connectionLinks.add(connectionLink);
186         transportNetwork.put("sla", sla);
187         transportNetwork.put("connectionLinks", connectionLinks);
188         transportNetworks.add(transportNetwork);
189         additionalProperties.put("transportNetworks", transportNetworks);
190         params.put("additionalProperties",additionalProperties);
191
192         okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(okhttp3.MediaType.parse("application/json"), JSON.toJSONString(params));
193         Response<JSONObject> response = intentApiService.createIntentInstance(requestBody).execute();
194         if (response.isSuccessful()) {
195             return response.body().getString("jobId");
196         }
197         return null;
198     }
199
200     @Override
201     public void getIntentInstanceProgress() {
202         List<IntentInstance> instanceList = getInstanceByFinishedFlag("0");
203         for (IntentInstance instance: instanceList) {
204             try {
205
206                 int progress = getProgressByJobId(instance);
207                 if (progress >=100) {
208                     instance.setStatus("1");
209                 }
210                 instance.setProgress(progress);
211             }
212             catch (Exception e) {
213                 logger.info("get progress exception:"+e);
214             }
215         }
216         saveProgress(instanceList);
217
218     }
219
220     private void saveProgress(List<IntentInstance> instanceList) {
221         Transaction tx = null;
222         if(instanceList == null || instanceList.isEmpty()) {
223             return;
224         }
225         try(Session session = getSession()) {
226             tx = session.beginTransaction();
227             for (IntentInstance instance : instanceList) {
228                 session.save(instance);
229             }
230             tx.commit();
231             logger.info("update progress ok");
232
233         } catch (Exception e) {
234             if(tx!=null){
235                 tx.rollback();
236             }
237             logger.error("update progress exception:"+e);
238
239         }
240     }
241
242     private int getProgressByJobId(IntentInstance instance) throws IOException {
243         Response<OperationProgressInformation> response = soService.queryOperationProgress(instance.getResourceInstanceId(), instance.getJobId()).execute();
244         return response.body().getOperationStatus().getProgress();
245     }
246
247     private List<IntentInstance> getInstanceByFinishedFlag(String flag) {
248         Session session = getSession();
249         try{
250             StringBuffer sql=new StringBuffer("from IntentInstance where deleteState = 0 and status = '" + flag + "'");
251
252             Query query = session.createQuery(sql.toString());
253             List<IntentInstance> q=(List<IntentInstance>) query.list();
254             logger.debug(q.toString());
255             return q;
256         } catch (Exception e) {
257             logger.error("exception occurred while performing IntentInstanceServiceImpl getNotFinishedJobId. Details:" + e.getMessage());
258             return null;
259         }
260     }
261
262
263     @Override
264     public List<IntentInstance> getFinishedInstanceInfo() {
265         Session session = getSession();
266         try{
267             StringBuffer count=new StringBuffer("from IntentInstance where status = '1' and deleteState = 0");
268
269             Query query = session.createQuery(count.toString());
270             List<IntentInstance> q=(List<IntentInstance>) query.list();
271             logger.debug(q.toString());
272             return q;
273         } catch (Exception e) {
274             logger.error("exception occurred while performing IntentInstanceServiceImpl getNotFinishedJobId. Details:" + e.getMessage());
275             return null;
276         }
277     }
278
279     @Override
280     public void getIntentInstanceBandwidth() throws IOException {
281         List<IntentInstance> instanceList = getInstanceByFinishedFlag("1");
282         for (IntentInstance instance : instanceList) {
283             String serviceInstanceId = instance.getResourceInstanceId();
284             Response<JSONObject> response = intentApiService.getInstanceNetworkInfo(serviceInstanceId).execute();
285             JSONObject responseBody = response.body();
286             JSONObject allottedResource = responseBody.getJSONObject("allotted-resources").getJSONArray("allotted-resource").getJSONObject(0);
287             JSONArray relationshipList = allottedResource.getJSONObject("relationship-list").getJSONArray("relationship");
288             String networkPolicyId = null;
289             for (int i = 0; i<relationshipList.size();i++) {
290                 if ("network-policy".equals(relationshipList.getJSONObject(i).getString("related-to"))) {
291                     JSONArray datas = relationshipList.getJSONObject(i).getJSONArray("relationship-data");
292                     for (int j = 0; j<relationshipList.size();j++) {
293                         if ("network-policy.network-policy-id".equals(datas.getJSONObject(j).getString("relationship-key"))) {
294                             networkPolicyId = datas.getJSONObject(j).getString("relationship-value");
295                             break;
296                         }
297                     }
298                     break;
299                 }
300             }
301             if (networkPolicyId== null) {
302                 logger.error("get network Policy Id exception. serviceInstanceId:" + instance.getResourceInstanceId());
303                 continue;
304             }
305             JSONObject networkPolicyInfo = intentApiService.getInstanceNetworkPolicyInfo(networkPolicyId).execute().body();
306             String maxBandwidth =  networkPolicyInfo.getString("max-bandwidth");
307             InstancePerformance instancePerformance = new InstancePerformance();
308             instancePerformance.setMaxBandwidth(maxBandwidth);
309             instancePerformance.setResourceInstanceId(instance.getResourceInstanceId());
310             instancePerformance.setJobId(instance.getJobId());
311             instancePerformance.setDate(new Date());
312
313             JSONObject metadatum = intentApiService.getInstanceBandwidth(serviceInstanceId).execute().body();
314             String metaval = metadatum.getJSONArray("metadatum").getJSONObject(0).getString("metaval");
315             instancePerformance.setBandwidth(metaval);
316
317             try{
318                 Session session = getSession();
319                 Transaction tx = session.beginTransaction();
320                 session.save(instancePerformance);
321                 tx.commit();
322             } catch (Exception e) {
323                 logger.error("Details:" + e.getMessage());
324             }
325
326
327         }
328     }
329
330     @Override
331     public void deleteIntentInstance(String instanceId) {
332         IntentInstance result = null;
333
334         try(Session session = getSession()) {
335
336             result = (IntentInstance)session.createQuery("from IntentInstance where deleteState = 0 and instanceId = :instanceId")
337                     .setParameter("instanceId", instanceId).uniqueResult();
338             logger.info("get IntentInstance OK, id=" + instanceId);
339
340         } catch (Exception e) {
341             logger.error("getodel occur exception:"+e);
342
343         }
344         try {
345             String serviceInstanceId = result.getResourceInstanceId();
346             deleteInstanceToSO(serviceInstanceId);
347             deleteInstance(serviceInstanceId);
348         }catch (Exception e) {
349             logger.error("delete instance to SO error :" + e);
350         }
351     }
352
353
354     private void deleteInstanceToSO(String serviceInstanceId) throws IOException {
355         JSONObject params = new JSONObject();
356         params.put("serviceInstanceID", serviceInstanceId);
357         params.put("globalSubscriberId", "IBNCustomer");
358         params.put("subscriptionServiceType", "IBN");
359         params.put("serviceType", "CLL");
360         JSONObject additionalProperties = new JSONObject();
361         additionalProperties.put("enableSdnc", "false");
362         params.put("additionalProperties", additionalProperties);
363         okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(okhttp3.MediaType.parse("application/json"), JSON.toJSONString(params));
364         intentApiService.deleteIntentInstance(requestBody).execute();
365     }
366     private String deleteInstance(String serviceInstanceId) {
367         Transaction tx = null;
368         String result="0";
369         if(serviceInstanceId==null || serviceInstanceId.trim().equals(""))
370             return  result;
371
372         try(Session session = getSession()) {
373             tx = session.beginTransaction();
374
375             IntentInstance instance = new IntentInstance();
376             instance.setInstanceId(serviceInstanceId);
377             session.delete(instance);
378             tx.commit();
379             logger.info("delete instance OK, id=" + serviceInstanceId);
380
381             result="1";
382         } catch (Exception e) {
383             if(tx!=null){
384                 tx.rollback();
385             }
386             logger.error("delete instance occur exception:"+e);
387
388         }
389         return result;
390     }
391
392     @Override
393     public void activeIntentInstance(String instanceId) {
394         IntentInstance instance = null;
395
396         try(Session session = getSession()) {
397
398             instance = (IntentInstance)session.createQuery("from IntentInstance where deleteState = 0 and instanceId = :instanceId and status = :status")
399                     .setParameter("instanceId", instanceId).setParameter("status", "3").uniqueResult();
400             logger.info("get instance OK, id=" + instanceId);
401
402         } catch (Exception e) {
403             logger.error("getodel occur exception:"+e);
404
405         }
406         if (null == instance) {
407             logger.error("intentInstance is null!");
408             return;
409         }
410         try {
411             String jobId = createIntentInstanceToSO(instance);
412             instance.setStatus("0");
413             instance.setJobId(jobId);
414             Session session = getSession();
415             Transaction tx = session.beginTransaction();
416             session.save(instance);
417             tx.commit();
418
419         }catch (Exception e) {
420             logger.error("active instance to SO error :" + e);
421         }
422     }
423
424     public void invalidIntentInstance(String instanceId) {
425         IntentInstance instance = null;
426
427         try(Session session = getSession()) {
428             instance = (IntentInstance)session.createQuery("from IntentInstance where deleteState = 0 and instanceId = :instanceId")
429                     .setParameter("instanceId", instanceId).uniqueResult();
430             logger.info("get instance OK, id=" + instanceId);
431
432         } catch (Exception e) {
433             logger.error("get instance occur exception:"+e);
434
435         }
436         if (null == instance) {
437             logger.error("intentInstance is null!");
438             return;
439         }
440         try {
441             deleteInstanceToSO(instance.getInstanceId());
442             instance.setStatus("3");
443             Session session = getSession();
444             Transaction tx = session.beginTransaction();
445             session.save(instance);
446             tx.commit();
447
448         }catch (Exception e) {
449             logger.error("invalid instance to SO error :" + e);
450         }
451     }
452
453     @Override
454     public Map<String, Object> queryInstancePerformanceData(String instanceId) {
455         try(Session session = getSession()) {
456             String hql = "from IntentInstance i, InstancePerformance p where i.resourceInstanceId = p.resourceInstanceId and  i.instanceId = :instanceId and i.deleteState = 0 order by p.date";
457             Query query = session.createQuery(hql).setParameter("instanceId", instanceId);
458             List<Object[]> queryResult= query.list();
459             List<String> date = new ArrayList<>();
460             List<String> bandwidth = new ArrayList<>();
461             List<String> maxBandwidth = new ArrayList<>();
462             SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
463             for (Object[] o : queryResult) {
464                 InstancePerformance performance = (InstancePerformance) o[1];
465                 date.add(ft.format(performance.getDate()));
466                 bandwidth.add(performance.getBandwidth());
467                 maxBandwidth.add(performance.getMaxBandwidth());
468             }
469             Map<String, Object> xAxis = new HashMap<>();
470             xAxis.put("data",date);
471             Map<String, Object> bandwidthData = new HashMap<>();
472             bandwidthData.put("data",bandwidth);
473             Map<String, Object> maxBandwidthData = new HashMap<>();
474             maxBandwidthData.put("data",maxBandwidth);
475             List<Map<String, Object>> series = new ArrayList<>();
476             series.add(bandwidthData);
477             series.add(maxBandwidthData);
478
479             Map<String, Object> result = new HashMap<>();
480             result.put("xAxis", xAxis);
481             result.put("series", series);
482
483             return result;
484         }catch (Exception e) {
485             logger.error("invalid instance to SO error :" + e);
486             throw e;
487         }
488     }
489
490     @Override
491     public Object queryAccessNodeInfo() throws IOException {
492         Map<String, Object> result = new HashMap<>();
493         List<String> accessNodeList = new ArrayList<>();
494         List<String> cloudAccessNodeList = new ArrayList<>();
495         JSONObject body = intentApiService.queryNetworkRoute().execute().body();
496         JSONArray data = body.getJSONArray("data");
497         for (int i = 0; i<data.size(); i++) {
498             JSONObject nodeInfo = data.getJSONObject(i);
499             if ("ROOT".equals(nodeInfo.getString("type"))) {
500                 cloudAccessNodeList.add(nodeInfo.getString("route-id"));
501             }
502             else {
503                 accessNodeList.add(nodeInfo.getString("route-id"));
504             }
505         }
506         result.put("accessNodeList",accessNodeList);
507         result.put("cloudAccessNodeList",cloudAccessNodeList);
508         return result;
509     }
510 }