2 * Copyright (C) 2021 CTC, Inc. and others. All rights reserved.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 package org.onap.usecaseui.server.service.intent.impl;
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;
41 import javax.transaction.Transactional;
42 import java.io.IOException;
43 import java.text.SimpleDateFormat;
46 @Service("IntentInstanceService")
48 @org.springframework.context.annotation.Configuration
49 @EnableAspectJAutoProxy
50 public class IntentInstanceServiceImpl implements IntentInstanceService {
51 private static final Logger logger = LoggerFactory.getLogger(IntentInstanceServiceImpl.class);
54 private SessionFactory sessionFactory;
57 private IntentApiService intentApiService;
59 private SOService soService;
61 public IntentInstanceServiceImpl() {
62 this(RestfulServices.create(IntentApiService.class),RestfulServices.create(SOService.class));
64 public IntentInstanceServiceImpl(IntentApiService intentApiService, SOService soService) {
65 this.intentApiService = intentApiService;
66 this.soService = soService;
69 private Session getSession() {
70 return sessionFactory.openSession();
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();
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+"'");
86 if(UuiCommonUtil.isNotNullOrEmpty(intentInstance.getJobId())) {
87 String ver =intentInstance.getJobId();
88 hql.append(" and a.job_id = '"+ver+"'");
90 if(UuiCommonUtil.isNotNullOrEmpty(intentInstance.getStatus())) {
91 String ver =intentInstance.getStatus();
92 hql.append(" and a.status = '"+ver+"'");
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);
106 } catch (Exception e) {
107 logger.error("exception occurred while performing AlarmsHeaderServiceImpl queryAlarmsHeader. Details:" + e.getMessage());
113 public int getAllCount(IntentInstance intentInstance,int currentPage,int pageSize) {
114 Session session = getSession();
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+"'");
122 if(UuiCommonUtil.isNotNullOrEmpty(intentInstance.getJobId())) {
123 String ver =intentInstance.getJobId();
124 count.append(" and a.job_id = '"+ver+"'");
126 if(UuiCommonUtil.isNotNullOrEmpty(intentInstance.getStatus())) {
127 String ver =intentInstance.getStatus();
128 count.append(" and a.status = '"+ver+"'");
131 Query query = session.createQuery(count.toString());
132 long q=(long)query.uniqueResult();
134 } catch (Exception e) {
135 logger.error("exception occurred while performing IntentInstanceServiceImpl getAllCount. Details:" + e.getMessage());
141 public int createIntentInstance(IntentInstance intentInstance) {
144 if (null == intentInstance){
145 logger.error("intentInstance is null!");
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);
157 } catch (Exception e) {
158 logger.error("Details:" + e.getMessage());
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);
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");
201 public void getIntentInstanceProgress() {
202 List<IntentInstance> instanceList = getInstanceByFinishedFlag("0");
203 for (IntentInstance instance: instanceList) {
206 int progress = getProgressByJobId(instance);
207 if (progress >=100) {
208 instance.setStatus("1");
210 instance.setProgress(progress);
212 catch (Exception e) {
213 logger.info("get progress exception:"+e);
216 saveProgress(instanceList);
220 private void saveProgress(List<IntentInstance> instanceList) {
221 Transaction tx = null;
222 if(instanceList == null || instanceList.isEmpty()) {
225 try(Session session = getSession()) {
226 tx = session.beginTransaction();
227 for (IntentInstance instance : instanceList) {
228 session.save(instance);
231 logger.info("update progress ok");
233 } catch (Exception e) {
237 logger.error("update progress exception:"+e);
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();
247 private List<IntentInstance> getInstanceByFinishedFlag(String flag) {
248 Session session = getSession();
250 StringBuffer sql=new StringBuffer("from IntentInstance where deleteState = 0 and status = '" + flag + "'");
252 Query query = session.createQuery(sql.toString());
253 List<IntentInstance> q=(List<IntentInstance>) query.list();
254 logger.debug(q.toString());
256 } catch (Exception e) {
257 logger.error("exception occurred while performing IntentInstanceServiceImpl getNotFinishedJobId. Details:" + e.getMessage());
264 public List<IntentInstance> getFinishedInstanceInfo() {
265 Session session = getSession();
267 StringBuffer count=new StringBuffer("from IntentInstance where status = '1' and deleteState = 0");
269 Query query = session.createQuery(count.toString());
270 List<IntentInstance> q=(List<IntentInstance>) query.list();
271 logger.debug(q.toString());
273 } catch (Exception e) {
274 logger.error("exception occurred while performing IntentInstanceServiceImpl getNotFinishedJobId. Details:" + e.getMessage());
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");
301 if (networkPolicyId== null) {
302 logger.error("get network Policy Id exception. serviceInstanceId:" + instance.getResourceInstanceId());
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());
313 JSONObject metadatum = intentApiService.getInstanceBandwidth(serviceInstanceId).execute().body();
314 String metaval = metadatum.getJSONArray("metadatum").getJSONObject(0).getString("metaval");
315 instancePerformance.setBandwidth(metaval);
318 Session session = getSession();
319 Transaction tx = session.beginTransaction();
320 session.save(instancePerformance);
322 } catch (Exception e) {
323 logger.error("Details:" + e.getMessage());
331 public void deleteIntentInstance(String instanceId) {
332 IntentInstance result = null;
334 try(Session session = getSession()) {
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);
340 } catch (Exception e) {
341 logger.error("getodel occur exception:"+e);
345 String serviceInstanceId = result.getResourceInstanceId();
346 deleteInstanceToSO(serviceInstanceId);
347 deleteInstance(serviceInstanceId);
348 }catch (Exception e) {
349 logger.error("delete instance to SO error :" + e);
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();
366 private String deleteInstance(String serviceInstanceId) {
367 Transaction tx = null;
369 if(serviceInstanceId==null || serviceInstanceId.trim().equals(""))
372 try(Session session = getSession()) {
373 tx = session.beginTransaction();
375 IntentInstance instance = new IntentInstance();
376 instance.setInstanceId(serviceInstanceId);
377 session.delete(instance);
379 logger.info("delete instance OK, id=" + serviceInstanceId);
382 } catch (Exception e) {
386 logger.error("delete instance occur exception:"+e);
393 public void activeIntentInstance(String instanceId) {
394 IntentInstance instance = null;
396 try(Session session = getSession()) {
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);
402 } catch (Exception e) {
403 logger.error("getodel occur exception:"+e);
406 if (null == instance) {
407 logger.error("intentInstance is null!");
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);
419 }catch (Exception e) {
420 logger.error("active instance to SO error :" + e);
424 public void invalidIntentInstance(String instanceId) {
425 IntentInstance instance = null;
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);
432 } catch (Exception e) {
433 logger.error("get instance occur exception:"+e);
436 if (null == instance) {
437 logger.error("intentInstance is null!");
441 deleteInstanceToSO(instance.getInstanceId());
442 instance.setStatus("3");
443 Session session = getSession();
444 Transaction tx = session.beginTransaction();
445 session.save(instance);
448 }catch (Exception e) {
449 logger.error("invalid instance to SO error :" + e);
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());
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);
479 Map<String, Object> result = new HashMap<>();
480 result.put("xAxis", xAxis);
481 result.put("series", series);
484 }catch (Exception e) {
485 logger.error("invalid instance to SO error :" + e);
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"));
503 accessNodeList.add(nodeInfo.getString("route-id"));
506 result.put("accessNodeList",accessNodeList);
507 result.put("cloudAccessNodeList",cloudAccessNodeList);