summaryrefslogtreecommitdiffstats
path: root/so-cnf-adapter-application/src/main/java/org/onap/so/adapters/cnf/util/AaiRepository.java
blob: 2ca9e3ab0530468df94e44b4b7f84a6b66c20546 (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
/*-
 * ============LICENSE_START=======================================================
 * ONAP - SO
 * ================================================================================
 * Copyright (C) 2021 Samsung Electronics Co. Ltd. All rights reserved.
 * Modifications Copyright (C) 2021 Orange.
 * ================================================================================
 * 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.so.adapters.cnf.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.onap.aaiclient.client.aai.AAIResourcesClient;
import org.onap.aaiclient.client.aai.AAITransactionalClient;
import org.onap.aaiclient.client.aai.AAIVersion;
import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri;
import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory;
import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder;
import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder.Types;
import org.onap.aaiclient.client.generated.fluentbuilders.K8sResource;
import org.onap.aaiclient.client.graphinventory.exceptions.BulkProcessFailed;
import org.onap.so.adapters.cnf.model.instantiation.AaiRequest;
import org.onap.so.adapters.cnf.service.aai.KubernetesResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

public class AaiRepository implements IAaiRepository {
    private final static Logger logger = LoggerFactory.getLogger(IAaiRepository.class);
    private final static Gson gson = new GsonBuilder().disableHtmlEscaping().create();

    private final AAIResourcesClient aaiClient;
    private final ObjectMapper objectMapper;
    private AAITransactionalClient transaction;

    public static IAaiRepository instance() {
        return new AaiRepository();
    }

    private AaiRepository() {
        aaiClient = new AAIResourcesClient(AAIVersion.LATEST);
        this.objectMapper = new ObjectMapper();
    }

    private AAITransactionalClient getTransaction() {
        if (transaction == null)
            transaction = aaiClient.beginTransaction();
        return transaction;
    }

    @Override
    public void commit(boolean dryrun) {
        try {
            if (transaction != null)
                transaction.execute(dryrun);
            else
                logger.info("Nothing to commit in AAI");
        } catch (BulkProcessFailed bulkProcessFailed) {
            throw new RuntimeException("Failed to exectute transaction", bulkProcessFailed);
        }
    }

    @Override
    public void update(KubernetesResource resource, AaiRequest aaiRequest) {
        logger.info("updating AAI with resource {} and request {}", resource, aaiRequest);

        K8sResource k8sResource = AAIFluentTypeBuilder.cloudInfrastructure()
                .cloudRegion(aaiRequest.getCloudOwner(), aaiRequest.getCloudRegion())
                .tenant(aaiRequest.getTenantId())
                .k8sResource(resource.getId());

        AAIResourceUri k8sResourceUri =
                AAIUriFactory.createResourceUri(k8sResource.build(), aaiRequest.getCloudOwner(), aaiRequest.getCloudRegion(), aaiRequest.getTenantId(), resource.getId());

        var k8sResourceInstance = aaiClient.get(k8sResourceUri);
        boolean updateK8sResource = true;
        if (!k8sResourceInstance.isEmpty()) {
            try {
                KubernetesResource resourceReference = objectMapper.readValue(k8sResourceInstance.getJson(), KubernetesResource.class);
                updateK8sResource = !resourceReference.compare(resource);
                if (updateK8sResource)
                    resource.setResourceVersion(resourceReference.getResourceVersion());
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
        if (updateK8sResource) {
            String payload = null;
            try {
                payload = objectMapper.writeValueAsString(resource);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
            logger.debug("K8s resource URI: " + k8sResourceUri + " with payload [" + payload + "]");
            getTransaction().create(k8sResourceUri, payload);
        }

        final String genericVnfId = aaiRequest.getGenericVnfId();
        final String vfModuleId = aaiRequest.getVfModuleId();

        if (genericVnfId == null || vfModuleId == null) {
            logger.debug("No genericVnfId or vfModuleId to create relations for payload [\" + payload + \"]\");");
            return;
        }

        var vfModuleUri = AAIUriFactory.createResourceUri(
                AAIFluentTypeBuilder.network().genericVnf(genericVnfId).vfModule(vfModuleId));
        var instance = aaiClient.get(vfModuleUri);

        if (instance.isEmpty())
            logger.error("Specified VfModule [" + vfModuleId + "] does not exist in AAI");
        else if (k8sResourceInstance.isEmpty() || !k8sResourceInstance.hasRelationshipsTo(Types.VF_MODULE)) {
            getTransaction().connect(k8sResourceUri, vfModuleUri);
        }

        var genericVnfUri = AAIUriFactory.createResourceUri(
                AAIFluentTypeBuilder.network().genericVnf(genericVnfId));
        instance = aaiClient.get(genericVnfUri);

        if (instance.isEmpty())
            logger.error("Specified GenericVnf [" + genericVnfId + "] does not exist in AAI");
        else if (k8sResourceInstance.isEmpty() || !k8sResourceInstance.hasRelationshipsTo(Types.GENERIC_VNF)) {
            getTransaction().connect(k8sResourceUri, genericVnfUri);
        }
    }

    @Override
    public void delete(AaiRequest aaiRequest, List<KubernetesResource> excludedList) {
        logger.info("deleting from AAI resource {}", aaiRequest);
        final String genericVnfId = aaiRequest.getGenericVnfId();
        final String vfModuleId = aaiRequest.getVfModuleId();
        final List<String> excludedIds = excludedList == null ? List.of() :
                excludedList.stream().map(KubernetesResource::getId).collect(Collectors.toList());

        if (genericVnfId == null || vfModuleId == null) {
            logger.debug("No genericVnfId or vfModuleId to delete k8s-resources");
            return;
        }

        var vfModuleUri = AAIUriFactory.createResourceUri(
                AAIFluentTypeBuilder.network().genericVnf(genericVnfId).vfModule(vfModuleId));
        var instance = aaiClient.get(vfModuleUri);

        if (instance.hasRelationshipsTo(Types.K8S_RESOURCE) && instance.getRelationships().isPresent()) {
            List<KubernetesResource> resources = instance.getRelationships().get().getByType(Types.K8S_RESOURCE)
                    .stream()
                    .map(r -> r.asBean(KubernetesResource.class))
                    .filter(r -> r.isPresent() && !excludedIds.contains(r.get().getId()))
                    .map(Optional::get)
                    .collect(Collectors.toList());
            resources.stream().map(r -> {
                K8sResource k8sResource = AAIFluentTypeBuilder.cloudInfrastructure()
                        .cloudRegion(aaiRequest.getCloudOwner(), aaiRequest.getCloudRegion())
                        .tenant(aaiRequest.getTenantId())
                        .k8sResource(r.getId());
                return AAIUriFactory.createResourceUri(k8sResource.build(), aaiRequest.getCloudOwner(), aaiRequest.getCloudRegion(), aaiRequest.getTenantId(), r.getId());
            }).forEach(uri -> getTransaction().delete(uri));
        }
    }
}