summaryrefslogtreecommitdiffstats
path: root/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/aai/AaiService.java
blob: 289fedfded109704478807fd4ddc9bf8e1382ee0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
/*******************************************************************************
 *  ============LICENSE_START=======================================================
 *  slice-analysis-ms
 *  ================================================================================
 *   Copyright (C) 2021-2022 Wipro Limited.
 *   Copyright (C) 2022 Huawei Canada Limited.
 *   ==============================================================================
 *     Licensed under the Apache License, Version 2.0 (the "License");
 *     you may not use this file except in compliance with the License.
 *     You may obtain a copy of the License at
 *
 *          http://www.apache.org/licenses/LICENSE-2.0
 *
 *     Unless required by applicable law or agreed to in writing, software
 *     distributed under the License is distributed on an "AS IS" BASIS,
 *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *     See the License for the specific language governing permissions and
 *     limitations under the License.
 *     ============LICENSE_END=========================================================
 *
 *******************************************************************************/

package org.onap.slice.analysis.ms.aai;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import org.json.JSONArray;
import org.json.JSONObject;
import org.onap.slice.analysis.ms.models.Configuration;
import org.onap.slice.analysis.ms.models.aai.ServiceInstance;
import org.onap.slice.analysis.ms.restclients.AaiRestClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

/**
 *
 * Service for AAI interfaces
 *
 */
@Service
public class AaiService implements AaiInterface {

    private static Logger log = LoggerFactory.getLogger(Configuration.class);

    @Autowired
    AaiRestClient restclient;

    private static ObjectMapper objectMapper = new ObjectMapper();
    private static String globalSubscriberId;
    private static String subscriptionServiceType;
    private static String aaiBaseUrl = Configuration.getInstance().getAaiUrl();

    /**
     * Fetches the details of a service
     *
     * @param snssai SNSSAI ID
     * @return responseMap contains service details
     */
    public Map<String, String> fetchServiceDetails(String snssai) {
        Map<String, String> responseMap = fetchSubscriberAndSubscriptionServiceType();
        String serviceReqUrl = aaiBaseUrl + "/business/customers/customer/" + globalSubscriberId
                + "/service-subscriptions/service-subscription/" + subscriptionServiceType + "/service-instances";
        log.info("serviceReqUrl {}", serviceReqUrl);
        String serviceRole = "AN-NF";
        try {
            String serviceInstance =
                    restclient.sendGetRequest(serviceReqUrl, new ParameterizedTypeReference<String>() {}).getBody();
            JSONObject serviceInstanceJson = new JSONObject(serviceInstance);
            JSONArray serviceInstanceList = serviceInstanceJson.getJSONArray("service-instance");
            for (int i = 0; i < serviceInstanceList.length(); i++) {
                JSONObject serviceObj = serviceInstanceList.getJSONObject(i);
                if (serviceObj.has("environment-context") && serviceObj.getString("environment-context").equalsIgnoreCase(snssai)) {
                    responseMap.put("sliceProfileId", serviceObj.getString("service-instance-id"));
                }
            }

            String serviceRoleReqUrl = aaiBaseUrl + "/business/customers/customer/" + globalSubscriberId
                    + "/service-subscriptions/service-subscription/" + subscriptionServiceType
                    + "/service-instances/?service-role=nssi&depth=2";
            log.info("serviceRoleReqUrl {}", serviceRoleReqUrl);
            String serviceInstanceForServiceRole =
                    restclient.sendGetRequest(serviceRoleReqUrl, new ParameterizedTypeReference<String>() {}).getBody();
            JSONObject serviceInstanceForServiceRoleJson = new JSONObject(serviceInstanceForServiceRole);
            JSONArray serviceInstanceListForServiceRole =
                    serviceInstanceForServiceRoleJson.getJSONArray("service-instance");
            for (int i = 0; i < serviceInstanceListForServiceRole.length(); i++) {
                JSONObject serviceObj = serviceInstanceListForServiceRole.getJSONObject(i);
                if (serviceObj.has("workload-context") && serviceObj.getString("workload-context").trim().equalsIgnoreCase(serviceRole)) {
                    responseMap.put("ranNFNSSIId", serviceObj.getString("service-instance-id"));
                }
            }
        } catch (Exception e) {
            log.info("Exception while fetching serviceDetails: " + e);
        }
        responseMap.put("sNSSAI", snssai);
        log.info("subscriber details: " + responseMap);
        return responseMap;
    }

    /**
     * Fetches the current configuration of a Slice from AAI
     *
     * @param snssai SNSSAI ID
     * @return responseMap contains slice configuration
     */
    public Map<String, Integer> fetchCurrentConfigurationOfSlice(String snssai) {
        log.info("AAI fetch config Slice: " + aaiBaseUrl);
        String serviceInstaneId = null;
        String serviceReqUrl = aaiBaseUrl + "/business/customers/customer/" + globalSubscriberId
                + "/service-subscriptions/service-subscription/" + subscriptionServiceType + "/service-instances";
        log.info("serviceReqUrl {}", serviceReqUrl);
        Map<String, Integer> responseMap = new HashMap<String, Integer>();
        try {
            String serviceInstance =
                    restclient.sendGetRequest(serviceReqUrl, new ParameterizedTypeReference<String>() {}).getBody();
            JSONObject serviceInstanceJson = new JSONObject(serviceInstance);

            JSONArray serviceInstanceList = serviceInstanceJson.getJSONArray("service-instance");
            for (int i = 0; i < serviceInstanceList.length(); i++) {
                JSONObject serviceObj = serviceInstanceList.getJSONObject(i);
                if (serviceObj.has("environment-context") && serviceObj.getString("environment-context").equalsIgnoreCase(snssai)) {
                    serviceInstaneId = serviceObj.getString("service-instance-id");
                }
            }

            String sliceProfileReqUrl = aaiBaseUrl + "/business/customers/customer/" + globalSubscriberId
                    + "/service-subscriptions/service-subscription/" + subscriptionServiceType
                    + "/service-instances/service-instance/" + serviceInstaneId + "/slice-profiles";
            log.info("sliceProfileReqUrl {}", sliceProfileReqUrl);
            String sliceProfile = restclient
                    .sendGetRequest(sliceProfileReqUrl, new ParameterizedTypeReference<String>() {}).getBody();
            JSONObject sliceProfileJson = new JSONObject(sliceProfile);
            JSONArray sliceProfileList = sliceProfileJson.getJSONArray("slice-profile");
            for (int i = 0; i < sliceProfileList.length(); i++) {
                JSONObject sliceProfileObj = sliceProfileList.getJSONObject(i);
                responseMap.put("dLThptPerSlice", sliceProfileObj.getInt("exp-data-rate-UL"));
                responseMap.put("uLThptPerSlice", sliceProfileObj.getInt("exp-data-rate-DL"));
                break;
            }
            log.info("Slice configuration: " + responseMap);
        } catch (Exception e) {
            log.info("AAI Slice: " + e);
        }
        return responseMap;
    }

    /**
     * Fetches the details of a subscriber and subscription Service
     *
     * @return responseMap contains details of subscriber and subscription service
     */
    public Map<String, String> fetchSubscriberAndSubscriptionServiceType() {

        Map<String, String> responseMap = new HashMap<String, String>();

        log.info("Get GlobalSubscriberId");
        String subscriberReqUrl = aaiBaseUrl + "/business/customers";
        log.info("subscriberReqUrl {}", subscriberReqUrl);
        try {
            String subscriberReq =
                    restclient.sendGetRequest(subscriberReqUrl, new ParameterizedTypeReference<String>() {}).getBody();
            JSONObject subscriberReqJson = new JSONObject(subscriberReq);
            JSONArray subscriberReqJsonList = subscriberReqJson.getJSONArray("customer");
            for (int i = 0; i < subscriberReqJsonList.length(); i++) {
                JSONObject subscriberReqObj = subscriberReqJsonList.getJSONObject(i);
                globalSubscriberId = subscriberReqObj.getString("global-customer-id");
                responseMap.put("globalSubscriberId", globalSubscriberId);
                break;
            }

            log.info("Get subscriptionServiceType");
            String subscriptionServiceReqUrl =
                    aaiBaseUrl + "/business/customers/customer/" + globalSubscriberId + "/service-subscriptions";
            log.info("subscriptionServiceReqUrl: {}", subscriptionServiceReqUrl);
            String subscriptionService = restclient
                    .sendGetRequest(subscriptionServiceReqUrl, new ParameterizedTypeReference<String>() {}).getBody();
            JSONObject subscriptionServiceJson = new JSONObject(subscriptionService);
            JSONArray subscriptionServiceListJson = subscriptionServiceJson.getJSONArray("service-subscription");
            for (int i = 0; i < subscriptionServiceListJson.length(); i++) {
                JSONObject subscriptionServiceObj = subscriptionServiceListJson.getJSONObject(i);
                subscriptionServiceType = subscriptionServiceObj.getString("service-type");
                responseMap.put("subscriptionServiceType", subscriptionServiceType);
                break;
            }
        } catch (Exception e) {
            log.info("Exception while fetching subscriber and subscription: " + e);
        }

        log.info("responseMap: " + responseMap);
        return responseMap;

    }

    /**
     * Fetches the SNSSIs of a serviceInstanceId
     *
     * @param serviceInstanceId service instance ID
     * @return snssaiList contains list of SNSSAIs
     */
    public List<String> getSnssaiList(String sliceInstanceId) {
        fetchSubscriberAndSubscriptionServiceType();
        List<String> allotedResource = new ArrayList<>();
        List<String> sliceProfileList = new ArrayList<>();
        List<String> snssaiList = new ArrayList<>();

        log.info("fetch slice instance details");
        String serviceReqUrl = aaiBaseUrl + "/business/customers/customer/" + globalSubscriberId
                + "/service-subscriptions/service-subscription/" + subscriptionServiceType
                + "/service-instances/service-instance/" + sliceInstanceId;
        log.info("serviceReqUrl {}", serviceReqUrl);
        try {
            String serviceInstanceString =
                    restclient.sendGetRequest(serviceReqUrl, new ParameterizedTypeReference<String>() {}).getBody();
            ServiceInstance serviceInstance = objectMapper.readValue(serviceInstanceString, ServiceInstance.class);
            if (serviceInstance.getServiceRole().equalsIgnoreCase("nsi")) {
                serviceInstance.getRelationshipList().getRelationship().forEach(relationship -> {
                    if (Objects.nonNull(relationship.getRelatedTo()) && relationship.getRelatedTo().equalsIgnoreCase("allotted-resource")) {
                        relationship.getRelationshipData().forEach(data -> {
                            if (data.get("relationship-key").equalsIgnoreCase("service-instance.service-instance-id")) {
                                allotedResource.add(data.get("relationship-value"));
                            }

                        });
                    }
                });

                return fetchSnssaiOfSliceProfile(fetchSliceProfilesOfAllotedResourceData(allotedResource));

            }
            if (serviceInstance.getServiceRole().equalsIgnoreCase("nssi")) {
                serviceInstance.getRelationshipList().getRelationship().forEach(relationship -> {
                    if (Objects.nonNull(relationship.getRelatedToProperty())) {
                        relationship.getRelatedToProperty().forEach(property -> {
                            if (property.get("property-value").contains("sliceprofile")) {
                                relationship.getRelationshipData().forEach(data -> {
                                    if (data.get("relationship-key")
                                            .equalsIgnoreCase("service-instance.service-instance-id")) {
                                        sliceProfileList.add(data.get("relationship-value"));
                                    }

                                });

                            }

                        });
                    }
                });
                return fetchSnssaiOfSliceProfile(sliceProfileList);
            }

        } catch (Exception e) {
            log.info("Exception while fetching snssaiList: " + e);
        }

        return snssaiList;

    }

    /**
     * Fetches the sliceProfileList of a AllotedResource
     *
     * @param allotedResourceList contains list of allotedResource IDs
     * @return sliceProfilesList contains list of SliceProfiles
     */
    public List<String> fetchSliceProfilesOfAllotedResourceData(List<String> allotedResourceList) {

        List<String> sliceProfileList = new ArrayList<>();

        log.info("fetch Alloted Resource Data");

        allotedResourceList.forEach(serviceInstanceId -> {
            try {
                String serviceReqUrl = aaiBaseUrl + "/business/customers/customer/" + globalSubscriberId
                        + "/service-subscriptions/service-subscription/" + subscriptionServiceType
                        + "/service-instances/service-instance/" + serviceInstanceId;
                log.info("serviceReqUrl {}", serviceReqUrl);
                String serviceInstanceString =
                        restclient.sendGetRequest(serviceReqUrl, new ParameterizedTypeReference<String>() {}).getBody();
                ServiceInstance serviceInstance = objectMapper.readValue(serviceInstanceString, ServiceInstance.class);

                serviceInstance.getRelationshipList().getRelationship().forEach(relationship -> {
                    relationship.getRelatedToProperty().forEach(property -> {
                        if (property.get("property-value").contains("sliceprofile")) {
                            relationship.getRelationshipData().forEach(data -> {
                                if (data.get("relationship-key")
                                        .equalsIgnoreCase("service-instance.service-instance-id")) {
                                    sliceProfileList.add(data.get("relationship-value"));
                                }

                            });

                        }

                    });

                });
            } catch (Exception e) {
                log.info("Exception while fetching AllotedResourceData: " + e);
            }

        });

        log.info("sliceProfileList: " + sliceProfileList);

        return sliceProfileList;

    }

    /**
     * Fetches the snssaiList of a SliceProfile
     *
     * @param sliceProfileList contains list of sliceProfile IDs
     * @return snssaiList contains list of SNSSAIs
     */
    public List<String> fetchSnssaiOfSliceProfile(List<String> sliceProfileList) {
        List<String> snssaiList = new ArrayList<>();

        log.info("fetch SliceProfile");
        sliceProfileList.forEach(serviceInstanceId -> {
            String serviceReqUrl = aaiBaseUrl + "/business/customers/customer/" + globalSubscriberId
                    + "/service-subscriptions/service-subscription/" + subscriptionServiceType + "/service-instances/"
                    + "service-instance/" + serviceInstanceId;
            log.info("serviceReqUrl {}", serviceReqUrl);
            try {
                String serviceInstanceString =
                        restclient.sendGetRequest(serviceReqUrl, new ParameterizedTypeReference<String>() {}).getBody();
                ServiceInstance serviceInstance = objectMapper.readValue(serviceInstanceString, ServiceInstance.class);

                if (serviceInstance.getServiceRole().equalsIgnoreCase("slice-profile")) {
                    if (!snssaiList.contains(serviceInstance.getEnvironmentContext())) {
                        snssaiList.add(serviceInstance.getEnvironmentContext());
                    }
                }

            } catch (Exception e) {
                log.info("Exception while fetching sliceProfile data: " + e);
            }

        });
        log.info("snssaiList: " + snssaiList);

        return snssaiList;

    }

    /**
     * Get network bandwidth attribute of an ethernet service. These data is inside a network policy whose
     * etwork-policy-fqdn equals to provided service-instance-id
     * @param serviceId target service instance id
     * @return Map contains maxBandwidth value of given service-instance
     */
    public Map<String, Integer> fetchMaxBandwidthOfService(String serviceId){
        log.info("Fetching max-bandwidth from AAI network-policy");
        String networkPolicyUrl = aaiBaseUrl + "/network/network-policies" + "?network-policy-fqdn="
                + serviceId;
        Map<String, Integer> result = new HashMap<>();
        try {
            ResponseEntity<String> resp = restclient.sendGetRequest(networkPolicyUrl, new ParameterizedTypeReference<String>() {
            });
            if (resp.getStatusCodeValue() == 200){
                String networkPolicy = resp.getBody();
                JSONObject networkPolicyJson = new JSONObject(networkPolicy);
                JSONArray networkPolicyList	= networkPolicyJson.optJSONArray("network-policy");
                if (networkPolicyList != null){
                    JSONObject networkPolicyOjb = networkPolicyList.getJSONObject(0);
                    result.put("maxBandwidth", networkPolicyOjb.getInt("max-bandwidth"));
                    return result;
                }
                log.info("Successfully fetched max bandwidth {}: {}", serviceId, result);
            }
        } catch (Exception e){
            log.warn("Error encountered when fetching maxbandwidth: " + e);

        }
        return null;
    }
}