feat:Intent instance binding 5g slice instance information
[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.csmf.ServiceCreateResult;
26 import org.onap.usecaseui.server.bean.csmf.SlicingOrder;
27 import org.onap.usecaseui.server.bean.csmf.SlicingOrderDetail;
28 import org.onap.usecaseui.server.bean.intent.InstancePerformance;
29 import org.onap.usecaseui.server.bean.intent.CCVPNInstance;
30 import org.onap.usecaseui.server.bean.intent.IntentInstance;
31 import org.onap.usecaseui.server.bean.nsmf.common.ServiceResult;
32 import org.onap.usecaseui.server.constant.IntentConstant;
33 import org.onap.usecaseui.server.service.csmf.SlicingService;
34 import org.onap.usecaseui.server.service.intent.IntentApiService;
35 import org.onap.usecaseui.server.service.intent.IntentInstanceService;
36 import org.onap.usecaseui.server.service.lcm.domain.so.SOService;
37 import org.onap.usecaseui.server.service.nsmf.ResourceMgtService;
38 import org.onap.usecaseui.server.util.Page;
39 import org.onap.usecaseui.server.util.RestfulServices;
40 import org.onap.usecaseui.server.util.UuiCommonUtil;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43 import org.springframework.beans.factory.annotation.Autowired;
44 import org.springframework.context.annotation.EnableAspectJAutoProxy;
45 import org.springframework.stereotype.Service;
46 import retrofit2.Call;
47 import retrofit2.Response;
48
49 import javax.annotation.Resource;
50 import javax.transaction.Transactional;
51 import java.io.*;
52 import java.text.SimpleDateFormat;
53 import java.util.*;
54 import java.util.regex.Matcher;
55 import java.util.regex.Pattern;
56
57 @Service("IntentInstanceService")
58 @Transactional
59 @org.springframework.context.annotation.Configuration
60 @EnableAspectJAutoProxy
61 public class IntentInstanceServiceImpl implements IntentInstanceService {
62     private static final Logger logger = LoggerFactory.getLogger(IntentInstanceServiceImpl.class);
63
64     @Autowired
65     private SessionFactory sessionFactory;
66
67     @Resource(name = "ResourceMgtService")
68     private ResourceMgtService resourceMgtService;
69
70     @Resource(name = "SlicingService")
71     private SlicingService slicingService;
72
73     private IntentApiService intentApiService;
74
75     private SOService soService;
76
77     private final static int MAX_BANDWIDTH = 6000;
78     private final static int MIN_BANDWIDTH = 100;
79
80     private final static List<String> GB_COMPANY = Arrays.asList(new String[] {"gbps", "gb"});
81     private final static List<String> MB_COMPANY = Arrays.asList(new String[] {"mbps", "mb"});
82
83     public IntentInstanceServiceImpl() {
84         this(RestfulServices.create(IntentApiService.class),RestfulServices.create(SOService.class));
85     }
86     public IntentInstanceServiceImpl(IntentApiService intentApiService, SOService soService) {
87         this.intentApiService = intentApiService;
88         this.soService = soService;
89     }
90
91     private Session getSession() {
92         return sessionFactory.openSession();
93     }
94
95     @Override
96     public Page<CCVPNInstance> queryIntentInstance(CCVPNInstance instance, int currentPage, int pageSize) {
97         Page<CCVPNInstance> page = new Page<CCVPNInstance>();
98         int allRow =this.getAllCount(instance,currentPage,pageSize);
99         int offset = page.countOffset(currentPage, pageSize);
100         Session session = getSession();
101         try{
102             StringBuffer hql =new StringBuffer("from CCVPNInstance a where deleteState = 0");
103             if (null != instance) {
104                 if(UuiCommonUtil.isNotNullOrEmpty(instance.getInstanceId())) {
105                     String ver =instance.getInstanceId();
106                     hql.append(" and a.instance_id = '"+ver+"'");
107                 }
108                 if(UuiCommonUtil.isNotNullOrEmpty(instance.getJobId())) {
109                     String ver =instance.getJobId();
110                     hql.append(" and a.job_id = '"+ver+"'");
111                 }
112                 if(UuiCommonUtil.isNotNullOrEmpty(instance.getStatus())) {
113                     String ver =instance.getStatus();
114                     hql.append(" and a.status = '"+ver+"'");
115                 }
116             }
117             hql.append(" order by id");
118             logger.info("AlarmsHeaderServiceImpl queryIntentInstance: instance={}", instance);
119             Query query = session.createQuery(hql.toString());
120             query.setFirstResult(offset);
121             query.setMaxResults(pageSize);
122             List<CCVPNInstance> list= query.list();
123             page.setPageNo(currentPage);
124             page.setPageSize(pageSize);
125             page.setTotalRecords(allRow);
126             page.setList(list);
127             return page;
128         } catch (Exception e) {
129             logger.error("exception occurred while performing AlarmsHeaderServiceImpl queryAlarmsHeader. Details:" + e.getMessage());
130             return null;
131         } finally {
132             session.close();
133         }
134     }
135
136
137     public int getAllCount(CCVPNInstance instance, int currentPage, int pageSize) {
138         Session session = getSession();
139         try{
140             StringBuffer count=new StringBuffer("select count(*) from CCVPNInstance a where deleteState = 0");
141             if (null != instance) {
142                 if(UuiCommonUtil.isNotNullOrEmpty(instance.getInstanceId())) {
143                     String ver =instance.getInstanceId();
144                     count.append(" and a.instance_id = '"+ver+"'");
145                 }
146                 if(UuiCommonUtil.isNotNullOrEmpty(instance.getJobId())) {
147                     String ver =instance.getJobId();
148                     count.append(" and a.job_id = '"+ver+"'");
149                 }
150                 if(UuiCommonUtil.isNotNullOrEmpty(instance.getStatus())) {
151                     String ver =instance.getStatus();
152                     count.append(" and a.status = '"+ver+"'");
153                 }
154             }
155             Query query = session.createQuery(count.toString());
156             long q=(long)query.uniqueResult();
157             return (int)q;
158         } catch (Exception e) {
159             logger.error("exception occurred while performing IntentInstanceServiceImpl getAllCount. Details:" + e.getMessage());
160             return -1;
161         } finally {
162             session.close();
163         }
164     }
165
166     @Override
167     public int createCCVPNInstance(CCVPNInstance instance) {
168         Session session = getSession();
169         Transaction tx = null;
170         try{
171
172             if (null == instance){
173                 logger.error("instance is null!");
174                 return 0;
175             }
176             String jobId = createIntentInstanceToSO(instance);
177             if (null == jobId){
178                 logger.error("create Instance error:jobId is null");
179                 return 0;
180             }
181             instance.setJobId(jobId);
182             instance.setResourceInstanceId("cll-"+instance.getInstanceId());
183             saveIntentInstanceToAAI(null, instance);
184
185             tx = session.beginTransaction();
186             session.save(instance);
187             tx.commit();
188             return 1;
189         } catch (Exception e) {
190             if (tx != null) {
191                 tx.rollback();
192             }
193             logger.error("Details:" + e.getMessage());
194             return 0;
195         } finally {
196             session.close();
197         }
198     }
199
200     public String createIntentInstanceToSO(CCVPNInstance instance) throws IOException {
201         Map<String, Object> params = new HashMap<>();
202         params.put("name", instance.getName());
203         params.put("modelInvariantUuid", "6790ab0e-034f-11eb-adc1-0242ac120002");
204         params.put("modelUuid", "6790ab0e-034f-11eb-adc1-0242ac120002");
205         params.put("globalSubscriberId", "IBNCustomer");
206         params.put("subscriptionServiceType", "IBN");
207         params.put("serviceType", "CLL");
208         Map<String, Object> additionalProperties = new HashMap<>();
209         additionalProperties.put("enableSdnc", "true");
210         additionalProperties.put("serviceInstanceID", "cll-" + instance.getInstanceId());
211         List<Map<String, Object>> transportNetworks = new ArrayList<>();
212         Map<String, Object> transportNetwork = new HashMap<>();
213         transportNetwork.put("id", "");
214         Map<String, Object> sla = new HashMap<>();
215         sla.put("latency", "2");
216         sla.put("maxBandwidth", instance.getAccessPointOneBandWidth());
217         List<Map<String, Object>> connectionLinks = new ArrayList<>();
218         Map<String, Object> connectionLink = new HashMap<>();
219         connectionLink.put("name", "");
220         connectionLink.put("transportEndpointA", instance.getAccessPointOneName());
221         connectionLink.put("transportEndpointB", instance.getCloudPointName());
222         connectionLinks.add(connectionLink);
223         if (instance.getProtectStatus() == 1) {
224             sla.put("protectionType", instance.getProtectionType());
225             connectionLink.put("transportEndpointBProtection", instance.getProtectionCloudPointName());
226         }
227         transportNetwork.put("sla", sla);
228         transportNetwork.put("connectionLinks", connectionLinks);
229         transportNetworks.add(transportNetwork);
230         additionalProperties.put("transportNetworks", transportNetworks);
231         params.put("additionalProperties",additionalProperties);
232
233         okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(okhttp3.MediaType.parse("application/json"), JSON.toJSONString(params));
234         Response<JSONObject> response = intentApiService.createIntentInstance(requestBody).execute();
235         if (response.isSuccessful()) {
236             return response.body().getString("jobId");
237         }
238         return null;
239     }
240
241     @Override
242     public void getIntentInstanceProgress() {
243         List<CCVPNInstance> instanceList = getInstanceByFinishedFlag("0");
244         for (CCVPNInstance instance: instanceList) {
245             try {
246
247                 int progress = getProgressByJobId(instance);
248                 instance.setProgress(progress);
249                 if (progress >=100) {
250                     instance.setStatus("1");
251                     saveIntentInstanceToAAI(IntentConstant.INTENT_INSTANCE_ID_PREFIX + "-" + instance.getInstanceId(),instance);
252                 }
253             }
254             catch (Exception e) {
255                 logger.info("get progress exception:"+e);
256             }
257         }
258         saveProgress(instanceList);
259
260     }
261     @Override
262     public void getIntentInstanceCreateStatus() {
263         List<CCVPNInstance> instanceList = getInstanceByFinishedFlag("0");
264         for (CCVPNInstance instance: instanceList) {
265             try {
266
267                 int flag = getCreateStatusByJobId(instance);
268                 if (flag > 0) {
269                     instance.setStatus(flag + "");
270                     saveIntentInstanceToAAI(IntentConstant.INTENT_INSTANCE_ID_PREFIX + "-" + instance.getInstanceId(),instance);
271                 }
272             }
273             catch (Exception e) {
274                 logger.info("get progress exception:"+e);
275             }
276         }
277         saveProgress(instanceList);
278
279     }
280
281     private void saveProgress(List<CCVPNInstance> instanceList) {
282         if(instanceList == null || instanceList.isEmpty()) {
283             return;
284         }
285         Session session = getSession();
286         Transaction tx = null;
287         try {
288             tx = session.beginTransaction();
289             for (CCVPNInstance instance : instanceList) {
290                 session.update(instance);
291                 session.flush();
292             }
293             tx.commit();
294             logger.info("update progress ok");
295
296         } catch (Exception e) {
297             if(tx!=null){
298                 tx.rollback();
299             }
300             logger.error("update progress exception:"+e);
301
302         } finally {
303             session.close();
304         }
305     }
306
307     private int getProgressByJobId(CCVPNInstance instance) throws IOException {
308         Response<JSONObject> response = intentApiService.queryOperationProgress(instance.getResourceInstanceId(), instance.getJobId()).execute();
309         logger.debug(response.toString());
310         if (response.isSuccessful()) {
311             if (response.body().containsKey("operation")) {
312                 return response.body().getJSONObject("operation").getInteger("progress");
313             }
314         }
315         return -1;
316     }
317
318     private int getCreateStatusByJobId(CCVPNInstance instance) throws IOException {
319         if (instance == null || instance.getResourceInstanceId() == null) {
320             return -1;
321         }
322         Response<JSONObject> response = intentApiService.getInstanceInfo(instance.getResourceInstanceId()).execute();
323         logger.debug(response.toString());
324         if (response.isSuccessful()) {
325             String status = response.body().getString("orchestration-status");
326             if ("created".equals(status)) {
327                 return 1;
328             }
329             return 0;
330         }
331         logger.error("getIntentInstance Create Statue Error:" + response.toString());
332         return -1;
333     }
334
335     private List<CCVPNInstance> getInstanceByFinishedFlag(String flag) {
336         Session session = getSession();
337         try{
338             StringBuffer sql=new StringBuffer("from CCVPNInstance where deleteState = 0 and status = '" + flag + "'");
339
340             Query query = session.createQuery(sql.toString());
341             List<CCVPNInstance> q=(List<CCVPNInstance>) query.list();
342             logger.debug(q.toString());
343             return q;
344         } catch (Exception e) {
345             logger.error("exception occurred while performing IntentInstanceServiceImpl getNotFinishedJobId. Details:" + e.getMessage());
346             return null;
347         } finally {
348             session.close();
349         }
350     }
351
352
353     @Override
354     public List<CCVPNInstance> getFinishedInstanceInfo() {
355         Session session = getSession();
356         try{
357             StringBuffer count=new StringBuffer("from CCVPNInstance where status = '1' and deleteState = 0");
358
359             Query query = session.createQuery(count.toString());
360             List<CCVPNInstance> q=(List<CCVPNInstance>) query.list();
361             logger.debug(q.toString());
362             return q;
363         } catch (Exception e) {
364             logger.error("exception occurred while performing IntentInstanceServiceImpl getNotFinishedJobId. Details:" + e.getMessage());
365             return null;
366         } finally {
367             session.close();
368         }
369     }
370
371     @Override
372     public void getIntentInstanceBandwidth() throws IOException {
373         List<CCVPNInstance> instanceList = getInstanceByFinishedFlag("1");
374         for (CCVPNInstance instance : instanceList) {
375             String serviceInstanceId = instance.getResourceInstanceId();
376             Response<JSONObject> response = intentApiService.getInstanceNetworkInfo(serviceInstanceId).execute();
377             if (!response.isSuccessful()) {
378                 logger.error("get Intent-Instance Bandwidth error:" + response.toString());
379                 continue;
380             }
381             JSONObject responseBody = response.body();
382             JSONObject allottedResource = responseBody.getJSONObject("allotted-resources").getJSONArray("allotted-resource").getJSONObject(0);
383             JSONArray relationshipList = allottedResource.getJSONObject("relationship-list").getJSONArray("relationship");
384             String networkPolicyId = null;
385             for (int i = 0; i<relationshipList.size();i++) {
386                 if ("network-policy".equals(relationshipList.getJSONObject(i).getString("related-to"))) {
387                     JSONArray datas = relationshipList.getJSONObject(i).getJSONArray("relationship-data");
388                     for (int j = 0; j<relationshipList.size();j++) {
389                         if ("network-policy.network-policy-id".equals(datas.getJSONObject(j).getString("relationship-key"))) {
390                             networkPolicyId = datas.getJSONObject(j).getString("relationship-value");
391                             break;
392                         }
393                     }
394                     break;
395                 }
396             }
397             if (networkPolicyId== null) {
398                 logger.error("get network Policy Id exception. serviceInstanceId:" + instance.getResourceInstanceId());
399                 continue;
400             }
401
402             Response<JSONObject> networkPolicyInfoResponse = intentApiService.getInstanceNetworkPolicyInfo(networkPolicyId).execute();
403             if (!networkPolicyInfoResponse.isSuccessful()) {
404                 logger.error("get Intent-Instance networkPolicyInfo error:" + networkPolicyInfoResponse.toString());
405                 continue;
406             }
407             JSONObject networkPolicyInfo = networkPolicyInfoResponse.body();
408             int maxBandwidth =  networkPolicyInfo.getIntValue("max-bandwidth") * 1000;
409             InstancePerformance instancePerformance = new InstancePerformance();
410             instancePerformance.setMaxBandwidth(maxBandwidth);
411             instancePerformance.setResourceInstanceId(instance.getResourceInstanceId());
412             instancePerformance.setJobId(instance.getJobId());
413             instancePerformance.setDate(new Date());
414
415             Response<JSONObject> metadatumResponse = intentApiService.getInstanceBandwidth(serviceInstanceId).execute();
416             if (!metadatumResponse.isSuccessful()) {
417                 logger.error("get Intent-Instance metadatum error:" + metadatumResponse.toString());
418                 continue;
419             }else {
420                 logger.debug("get Intent-Instance metadatum ok: instance id:" + instance.getInstanceId() + ", metadatum info:" + metadatumResponse.toString());
421             }
422             JSONObject metadatum = metadatumResponse.body();
423             JSONArray metadatumArr = metadatum.getJSONArray("metadatum");
424             int metaval = -1;
425             for (int i = 0; i < metadatumArr.size(); i++) {
426                 if (metaval == -1 || metaval > metadatumArr.getJSONObject(i).getIntValue("metaval")) {
427                     metaval = metadatumArr.getJSONObject(i).getIntValue("metaval");
428                 }
429             }
430             instancePerformance.setBandwidth(metaval);
431
432             Session session = getSession();
433             Transaction tx = null;
434             try{
435                 tx = session.beginTransaction();
436                 session.save(instancePerformance);
437                 tx.commit();
438             } catch (Exception e) {
439                 if(tx!=null){
440                     tx.rollback();
441                 }
442                 logger.error("Details:" + e.getMessage());
443             } finally {
444                 session.close();
445             }
446
447
448         }
449     }
450
451     @Override
452     public void deleteIntentInstance(String instanceId) {
453         CCVPNInstance result = null;
454         Session session = getSession();
455         try {
456
457             result = (CCVPNInstance)session.createQuery("from CCVPNInstance where deleteState = 0 and instanceId = :instanceId")
458                     .setParameter("instanceId", instanceId).uniqueResult();
459             logger.info("get CCVPNInstance OK, id=" + instanceId);
460
461         } catch (Exception e) {
462             logger.error("getodel occur exception:"+e);
463
464         } finally {
465             session.close();
466         }
467         try {
468             String serviceInstanceId = result.getResourceInstanceId();
469             deleteInstanceToSO(serviceInstanceId);
470             deleteIntentInstanceToAAI(IntentConstant.INTENT_INSTANCE_ID_PREFIX + "-"+instanceId);
471             deleteInstance(result);
472         }catch (Exception e) {
473             logger.error("delete instance to SO error :" + e);
474         }
475     }
476
477
478     private void deleteInstanceToSO(String serviceInstanceId) throws IOException {
479         JSONObject params = new JSONObject();
480         params.put("serviceInstanceID", serviceInstanceId);
481         params.put("globalSubscriberId", "IBNCustomer");
482         params.put("subscriptionServiceType", "IBN");
483         params.put("serviceType", "CLL");
484         JSONObject additionalProperties = new JSONObject();
485         additionalProperties.put("enableSdnc", "true");
486         params.put("additionalProperties", additionalProperties);
487         okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(okhttp3.MediaType.parse("application/json"), JSON.toJSONString(params));
488         intentApiService.deleteIntentInstance(requestBody).execute();
489     }
490     private String deleteInstance(CCVPNInstance instance) {
491         Transaction tx = null;
492         String result="0";
493         Session session = getSession();
494         try {
495             tx = session.beginTransaction();
496
497             session.delete(instance);
498             tx.commit();
499             logger.info("delete instance OK, id=" + instance.getInstanceId());
500
501             result="1";
502         } catch (Exception e) {
503             if(tx!=null){
504                 tx.rollback();
505             }
506             logger.error("delete instance occur exception:"+e);
507
508         } finally {
509             session.close();
510         }
511         return result;
512     }
513
514     @Override
515     public void activeIntentInstance(String instanceId) {
516         CCVPNInstance instance = null;
517         Session session = getSession();
518         Transaction tx = null;
519         try {
520
521             instance = (CCVPNInstance)session.createQuery("from CCVPNInstance where deleteState = 0 and instanceId = :instanceId and status = :status")
522                     .setParameter("instanceId", instanceId).setParameter("status", "3").uniqueResult();
523             logger.info("get instance OK, id=" + instanceId);
524
525             if (null == instance) {
526                 logger.error("instance is null!");
527                 return;
528             }
529
530             String jobId = createIntentInstanceToSO(instance);
531             instance.setStatus("0");
532             instance.setJobId(jobId);
533             tx = session.beginTransaction();
534             session.save(instance);
535             tx.commit();
536
537         }catch (Exception e) {
538             if(tx!=null){
539                 tx.rollback();
540             }
541             logger.error("active instance to SO error :" + e);
542         } finally {
543             session.close();
544         }
545     }
546
547     public void invalidIntentInstance(String instanceId) {
548         CCVPNInstance instance = null;
549         Session session = getSession();
550         Transaction tx = null;
551         try {
552             instance = (CCVPNInstance)session.createQuery("from CCVPNInstance where deleteState = 0 and instanceId = :instanceId")
553                     .setParameter("instanceId", instanceId).uniqueResult();
554             logger.info("get instance OK, id=" + instanceId);
555
556             if (null == instance) {
557                 logger.error("instance is null!");
558                 return;
559             }
560             deleteInstanceToSO(instance.getInstanceId());
561             instance.setStatus("3");
562             tx = session.beginTransaction();
563             session.save(instance);
564             session.flush();
565             tx.commit();
566
567         }catch (Exception e) {
568             if(tx!=null){
569                 tx.rollback();
570             }
571             logger.error("invalid instance to SO error :" + e);
572         } finally {
573             session.close();
574         }
575     }
576
577     @Override
578     public Map<String, Object> queryInstancePerformanceData(String instanceId) {
579         Session session = getSession();
580         try {
581             String hql = "from CCVPNInstance i, InstancePerformance p where i.resourceInstanceId = p.resourceInstanceId and  i.instanceId = :instanceId and i.deleteState = 0 order by p.date";
582             Query query = session.createQuery(hql).setParameter("instanceId", instanceId);
583             List<Object[]> queryResult= query.list();
584             List<String> date = new ArrayList<>();
585             List<Integer> bandwidth = new ArrayList<>();
586             List<Integer> maxBandwidth = new ArrayList<>();
587             SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
588             for (int i = queryResult.size() > 50? queryResult.size() - 50 : 0; i < queryResult.size(); i++) {
589                 Object[] o = queryResult.get(i);
590                 InstancePerformance performance = (InstancePerformance) o[1];
591                 date.add(ft.format(performance.getDate()));
592                 bandwidth.add(performance.getBandwidth());
593                 maxBandwidth.add(performance.getMaxBandwidth());
594             }
595             Map<String, Object> xAxis = new HashMap<>();
596             xAxis.put("data",date);
597             Map<String, Object> bandwidthData = new HashMap<>();
598             bandwidthData.put("data",bandwidth);
599             Map<String, Object> maxBandwidthData = new HashMap<>();
600             maxBandwidthData.put("data",maxBandwidth);
601             List<Map<String, Object>> series = new ArrayList<>();
602             series.add(bandwidthData);
603             series.add(maxBandwidthData);
604
605             Map<String, Object> result = new HashMap<>();
606             result.put("xAxis", xAxis);
607             result.put("series", series);
608
609             return result;
610         }catch (Exception e) {
611             logger.error("invalid instance to SO error :" + e);
612             throw e;
613         } finally {
614             session.close();
615         }
616     }
617
618     @Override
619     public Object queryAccessNodeInfo() throws IOException {
620         Map<String, Object> result = new HashMap<>();
621         List<String> accessNodeList = new ArrayList<>();
622         List<String> cloudAccessNodeList = new ArrayList<>();
623         Response<JSONObject> response = intentApiService.queryNetworkRoute().execute();
624         if (!response.isSuccessful()) {
625             logger.error(response.toString());
626             throw new RuntimeException("Query Access Node Info Error");
627         }
628         JSONObject body = response.body();
629         JSONArray data = body.getJSONArray("network-route");
630         for (int i = 0; i<data.size(); i++) {
631             JSONObject nodeInfo = data.getJSONObject(i);
632             if ("ROOT".equals(nodeInfo.getString("type"))) {
633                 cloudAccessNodeList.add(nodeInfo.getString("route-id")+"("+nodeInfo.getString("data-source")+")");
634             }
635             else {
636                 accessNodeList.add(nodeInfo.getString("route-id")+"("+nodeInfo.getString("data-source")+")");
637             }
638             IntentConstant.NetWorkNodeAlias.put(nodeInfo.getString("route-id"), nodeInfo.getString("route-id")+"("+nodeInfo.getString("data-source")+")");
639         }
640         result.put("accessNodeList",accessNodeList);
641         result.put("cloudAccessNodeList",cloudAccessNodeList);
642         return result;
643     }
644
645     @Override
646     public JSONObject getInstanceStatus(JSONArray ids) {
647         Session session = getSession();
648         try {
649             JSONObject result = new JSONObject();
650             JSONArray instanceInfos = new JSONArray();
651             String hql = "from CCVPNInstance i where i.instanceId in (:ids)";
652             Query query = session.createQuery(hql).setParameter("ids", ids);
653             List<CCVPNInstance> queryResult= query.list();
654             if (queryResult != null && queryResult.size() > 0) {
655                 for (CCVPNInstance instance : queryResult) {
656                     JSONObject instanceInfo = new JSONObject();
657                     instanceInfo.put("id", instance.getInstanceId());
658                     instanceInfo.put("status", instance.getStatus());
659                     instanceInfos.add(instanceInfo);
660                 }
661             }
662             result.put("IntentInstances",instanceInfos);
663             return result;
664
665         } catch (Exception e) {
666             logger.error("get Instance status error : " + e.getMessage());
667             throw e;
668         } finally {
669             session.close();
670         }
671     }
672
673
674     public String formatBandwidth(String strValue) {
675         String ret;
676         Pattern pattern = Pattern.compile("(\\d+)([\\w ]*)");
677         Matcher matcher = pattern.matcher(strValue);
678
679
680         int dataRate = 100;
681         if (matcher.matches()) {
682             dataRate = Integer.parseInt(matcher.group(1));
683             String company = matcher.group(2).trim().toLowerCase();
684             if (GB_COMPANY.contains(company)) {
685                 dataRate = dataRate * 1000;
686             }
687             else if (!MB_COMPANY.contains(company)) {
688                 dataRate = 100;
689             }
690             dataRate = dataRate < MIN_BANDWIDTH ? MIN_BANDWIDTH : (dataRate > MAX_BANDWIDTH ? MAX_BANDWIDTH : dataRate);
691         }
692         ret = dataRate + "";
693         return ret;
694     }
695
696
697     public String formatCloudPoint(String cloudPoint) {
698         String cloudPointAlias = "";
699         switch (cloudPoint) {
700             case "Cloud one" :
701                 cloudPointAlias = "tranportEp_dst_ID_212_1";
702                 break;
703         }
704         return cloudPointAlias;
705     }
706
707     public String formatAccessPoint(String accessPoint) {
708         String accessPointAlias = "";
709         switch (accessPoint) {
710             case "Access one" :
711                 accessPointAlias = "tranportEp_src_ID_111_1";
712                 break;
713             case "Access two" :
714                 accessPointAlias = "tranportEp_src_ID_111_2";
715                 break;
716             case "Access three" :
717                 accessPointAlias = "tranportEp_src_ID_113_1";
718                 break;
719         }
720         return accessPointAlias;
721     }
722
723     public void addCustomer() throws IOException {
724         Properties environment = getProperties();
725         String globalCustomerId = environment.getProperty("ccvpn.globalCustomerId");
726         Response<JSONObject> queryCustomerResponse = intentApiService.queryCustomer(globalCustomerId).execute();
727         if (queryCustomerResponse.isSuccessful()) {
728             return;
729         }
730         String subscriberName = environment.getProperty("ccvpn.subscriberName");
731         String subscriberType = environment.getProperty("ccvpn.subscriberType");
732         Map<String, Object> params = new HashMap<>();
733         params.put("global-customer-id", globalCustomerId);
734         params.put("subscriber-name", subscriberName);
735         params.put("subscriber-type", subscriberType);
736         okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(okhttp3.MediaType.parse("application/json"), JSON.toJSONString(params));
737         intentApiService.addCustomer(globalCustomerId, requestBody).execute();
738     }
739
740     @Override
741     public IntentInstance createIntentInstance(Object body,String businessInstanceId, String businessInstance, String type) {
742         IntentInstance instance = new IntentInstance();
743         if (IntentConstant.MODEL_TYPE_CCVPN.equals(type)) {
744             assembleIntentInstanceFormCCVPNInfo(instance, body);
745         }
746         else if (IntentConstant.MODEL_TYPE_5GS.equals(type)) {
747             assembleIntentInstanceFormSliceInfo(instance, body);
748         }
749         instance.setIntentSource(type);
750         instance.setBusinessInstanceId(businessInstanceId);
751         instance.setBusinessInstance(businessInstance);
752         Session session = getSession();
753         Transaction tx = null;
754         try{
755             tx = session.beginTransaction();
756             session.save(instance);
757             tx.commit();
758             return instance;
759         } catch (Exception e) {
760             if (tx != null) {
761                 tx.rollback();
762             }
763             logger.error("createIntentInstance Details:" + e.getMessage());
764             return null;
765         } finally {
766             session.close();
767         }
768     }
769
770     private IntentInstance assembleIntentInstanceFormCCVPNInfo(IntentInstance instance, Object body) {
771         JSONObject jsonObject = new JSONObject((Map) body);
772         String intent_content = jsonObject.getString("intentContent");
773         jsonObject.remove("intentContent");
774         instance.setIntentConfig(jsonObject.toJSONString());
775         instance.setIntentContent(intent_content);
776         instance.setIntentName(jsonObject.getString("name"));
777         return instance;
778     }
779
780     private IntentInstance assembleIntentInstanceFormSliceInfo(IntentInstance instance, Object body) {
781         JSONObject jsonObject = new JSONObject((Map) body);
782         JSONObject slicingOrderInfo = jsonObject.getJSONObject("slicing_order_info");
783         String intent_content = slicingOrderInfo.getString("intentContent");
784         slicingOrderInfo.remove("intentContent");
785         instance.setIntentConfig(slicingOrderInfo.toJSONString());
786         instance.setIntentContent(intent_content);
787         instance.setIntentName(slicingOrderInfo.getString("name"));
788         return instance;
789     }
790
791
792     @Override
793     public void deleteIntent(int id) {
794         Transaction tx = null;
795         Session session = getSession();
796         try {
797             IntentInstance intentInstance = (IntentInstance)session.createQuery("from IntentInstance where id = :id")
798                     .setParameter("id", id).uniqueResult();
799             if (IntentConstant.MODEL_TYPE_CCVPN.equals(intentInstance.getIntentSource())) {
800                 deleteIntentInstance(intentInstance.getBusinessInstanceId());
801             } else {
802                 resourceMgtService.terminateSlicingService(intentInstance.getBusinessInstanceId());
803             }
804
805
806             tx = session.beginTransaction();
807             session.delete(intentInstance);
808             tx.commit();
809             logger.info("delete IntentInstance OK, id=" + intentInstance.getId());
810         } catch (Exception e) {
811             if(tx!=null){
812                 tx.rollback();
813             }
814             logger.error("delete IntentInstance occur exception:"+e);
815
816         } finally {
817             session.close();
818         }
819     }
820
821     @Override
822     public void verifyIntent(int id) {
823         Session session = getSession();
824         IntentInstance instance = new IntentInstance();
825         try {
826             String hql = "from IntentInstance where id = :id";
827             Query query = session.createQuery(hql).setParameter("id", id);
828             instance = (IntentInstance) query.uniqueResult();
829
830         } catch (Exception e) {
831             logger.error("verifyIntentInstance error. Details:" + e.getMessage());
832         } finally {
833             session.close();
834         }
835     }
836
837     @Override
838     public Page<IntentInstance> getIntentInstanceList(int currentPage, int pageSize) {
839         Page<IntentInstance> page = new Page<IntentInstance>();
840         int allRow = getIntentInstanceAllCount();
841         int offset = page.countOffset(currentPage, pageSize);
842         Session session = getSession();
843         try{
844             String hql = "from IntentInstance order by id";
845             Query query = session.createQuery(hql);
846             query.setFirstResult(offset);
847             query.setMaxResults(pageSize);
848             List<IntentInstance> list= query.list();
849             page.setPageNo(currentPage);
850             page.setPageSize(pageSize);
851             page.setTotalRecords(allRow);
852             page.setList(list);
853             return page;
854         } catch (Exception e) {
855             logger.error("exception occurred while performing IntentInstanceServiceImpl getIntentInstanceList. Details:" + e.getMessage());
856             return null;
857         } finally {
858             session.close();
859         }
860     }
861
862     @Override
863     public ServiceResult createSlicingServiceWithIntent(Object slicingOrderBody) {
864
865         SlicingOrder slicingOrder = JSONObject.parseObject(JSONObject.toJSONString(slicingOrderBody), SlicingOrder.class);
866         ServiceResult serviceResult = slicingService.createSlicingService(slicingOrder);
867         ServiceCreateResult createResult = (ServiceCreateResult) serviceResult.getResult_body();
868         try {
869             saveSlicingServiceToAAI(createResult.getService_id(), createResult.getOperation_id(), slicingOrder);
870         } catch (IOException e) {
871             logger.error("save 5g slice to AAI fail!");
872             throw new RuntimeException("save 5g slice to AAI fail!", e);
873         }
874         createIntentInstance(slicingOrderBody,createResult.getService_id(), slicingOrder.getSlicing_order_info().getName(), IntentConstant.MODEL_TYPE_5GS);
875         return serviceResult;
876     }
877
878     @Override
879     public int updateCCVPNInstance(CCVPNInstance instance) {
880         Session session = getSession();
881         Transaction tx = null;
882         try{
883             if (null == instance){
884                 logger.error("instance is null!");
885                 return 0;
886             }
887             instance.setResourceInstanceId("cll-"+instance.getInstanceId());
888
889             CCVPNInstance ccvpnInstance = (CCVPNInstance)session.createQuery("from CCVPNInstance where instanceId = :instanceId")
890                     .setParameter("instanceId", instance.getInstanceId()).uniqueResult();
891             ccvpnInstance.setAccessPointOneBandWidth(instance.getAccessPointOneBandWidth());
892             saveIntentInstanceToAAI(IntentConstant.INTENT_INSTANCE_ID_PREFIX + "-" + ccvpnInstance.getInstanceId(), ccvpnInstance);
893
894             tx = session.beginTransaction();
895             session.update(ccvpnInstance);
896             tx.commit();
897             return 1;
898         } catch (Exception e) {
899             if (tx != null) {
900                 tx.rollback();
901             }
902             logger.error("Details:" + e.getMessage());
903             return 0;
904         } finally {
905             session.close();
906         }
907     }
908
909     public int getIntentInstanceAllCount() {
910         Session session = getSession();
911         try{
912             String count="select count(*) from IntentInstance";
913             Query query = session.createQuery(count);
914             long q=(long)query.uniqueResult();
915             return (int)q;
916         } catch (Exception e) {
917             logger.error("exception occurred while performing IntentInstanceServiceImpl getAllCount. Details:" + e.getMessage());
918             return -1;
919         } finally {
920             session.close();
921         }
922     }
923
924     public void addSubscription() throws IOException {
925         Properties environment = getProperties();
926         String globalCustomerId = environment.getProperty("ccvpn.globalCustomerId");
927         String serviceType = environment.getProperty("ccvpn.serviceType");
928         Response<JSONObject> querySubscription = intentApiService.querySubscription(globalCustomerId, serviceType).execute();
929         if (querySubscription.isSuccessful()) {
930             return;
931         }
932         Map<String, Object> params = new HashMap<>();
933         params.put("service-type", serviceType);
934         okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(okhttp3.MediaType.parse("application/json"), JSON.toJSONString(params));
935         intentApiService.addSubscription(globalCustomerId, serviceType, requestBody).execute();
936     }
937
938     public Properties getProperties() throws IOException {
939         String slicingPath = System.getProperty("user.dir") + File.separator + "config" + File.separator + "ccvpn.properties";
940         InputStream inputStream = new FileInputStream(new File(slicingPath));
941         Properties environment = new Properties();
942         environment.load(inputStream);
943         return environment;
944     }
945
946
947     public void saveIntentInstanceToAAI(String serviceInstanceId, CCVPNInstance instance) throws IOException {
948         addCustomer();
949         addSubscription();
950         Properties environment = getProperties();
951         String globalCustomerId = environment.getProperty("ccvpn.globalCustomerId");
952         String serviceType = environment.getProperty("ccvpn.serviceType");
953         String resourceVersion = null;
954         if (serviceInstanceId != null) {
955             Response<JSONObject> queryServiceInstance = intentApiService.queryServiceInstance(globalCustomerId, serviceType, serviceInstanceId).execute();
956             if (queryServiceInstance.isSuccessful()) {
957                 JSONObject body = queryServiceInstance.body();
958                 resourceVersion  = body.getString("resource-version");
959             }
960         } else {
961             serviceInstanceId = IntentConstant.INTENT_INSTANCE_ID_PREFIX + "-" + instance.getInstanceId();
962         }
963         JSONObject environmentContext = JSONObject.parseObject(JSONObject.toJSONString(instance));
964         environmentContext.put("resourceInstanceId",instance.getResourceInstanceId());
965
966         Map<String, Object> params = new HashMap<>();
967         params.put("service-instance-id", serviceInstanceId);
968         params.put("service-instance-name", instance.getName());
969         params.put("service-type", IntentConstant.MODEL_TYPE_CCVPN);
970         params.put("environment-context", environmentContext.toJSONString());
971         params.put("service-instance-location-id", instance.getResourceInstanceId());
972         params.put("bandwidth-total", instance.getAccessPointOneBandWidth());
973         params.put("data-owner", IntentConstant.INTENT_INSTANCE_DATA_OWNER);
974         if (resourceVersion != null) {
975             params.put("resource-version",resourceVersion);
976         }
977         okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(okhttp3.MediaType.parse("application/json"), JSON.toJSONString(params));
978         intentApiService.saveServiceInstance(globalCustomerId,serviceType,serviceInstanceId,requestBody).execute();
979
980     }
981     public void deleteIntentInstanceToAAI(String serviceInstanceId) throws IOException {
982         addCustomer();
983         addSubscription();
984         Properties environment = getProperties();
985         String globalCustomerId = environment.getProperty("ccvpn.globalCustomerId");
986         String serviceType = environment.getProperty("ccvpn.serviceType");
987         if (serviceInstanceId == null) {
988             return;
989         }
990         Response<JSONObject> queryServiceInstance = intentApiService.queryServiceInstance(globalCustomerId, serviceType, serviceInstanceId).execute();
991         if (queryServiceInstance.isSuccessful()) {
992             JSONObject body = queryServiceInstance.body();
993             String resourceVersion  = body.getString("resource-version");
994             intentApiService.deleteServiceInstance(globalCustomerId,serviceType,serviceInstanceId,resourceVersion).execute();
995         }
996     }
997
998     @Override
999     public void saveSlicingServiceToAAI(String serviceId, String operationId, SlicingOrder slicingOrder) throws IOException {
1000         addCustomer();
1001         addSubscription();
1002         Properties environment = getProperties();
1003         String globalCustomerId = environment.getProperty("ccvpn.globalCustomerId");
1004         String serviceType = environment.getProperty("ccvpn.serviceType");
1005         SlicingOrderDetail slicingOrderInfo = slicingOrder.getSlicing_order_info();
1006         JSONObject environmentContext = JSONObject.parseObject(JSONObject.toJSONString(slicingOrderInfo));
1007
1008         Map<String, Object> params = new HashMap<>();
1009         params.put("service-instance-id", serviceId);
1010         params.put("service-instance-name", slicingOrderInfo.getName());
1011         params.put("service-type", IntentConstant.MODEL_TYPE_5GS);
1012         params.put("environment-context", environmentContext.toJSONString());
1013         params.put("service-operation-id", operationId);
1014         params.put("data-rate-uplink", slicingOrderInfo.getExpDataRateUL());
1015         params.put("data-rate-downlink", slicingOrderInfo.getExpDataRateDL());
1016         params.put("latency", slicingOrderInfo.getLatency());
1017         params.put("max-number-of-ues", slicingOrderInfo.getMaxNumberofUEs());
1018         params.put("mobility", slicingOrderInfo.getUEMobilityLevel());
1019         params.put("resource-sharing-level", slicingOrderInfo.getResourceSharingLevel());
1020         params.put("data-owner", IntentConstant.INTENT_INSTANCE_DATA_OWNER);
1021         okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(okhttp3.MediaType.parse("application/json"), JSON.toJSONString(params));
1022         intentApiService.saveServiceInstance(globalCustomerId,serviceType,serviceId,requestBody).execute();
1023     }
1024
1025 }