summaryrefslogtreecommitdiffstats
path: root/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/helpers/AaiHelper.java
blob: 1f6c0df90f58c4c88a35bcf96cc64a8d7b321351 (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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
/*-
 * ============LICENSE_START=======================================================
 * ONAP - SO
 * ================================================================================
 * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * 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=========================================================
 */

/*
 * Copyright (C) 2018 Bell Canada.
 *
 * 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.
 */
package org.onap.so.heatbridge.helpers;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.onap.aai.domain.yang.Flavor;
import org.onap.aai.domain.yang.Image;
import org.onap.aai.domain.yang.L3Network;
import org.onap.aai.domain.yang.PInterface;
import org.onap.aai.domain.yang.Pserver;
import org.onap.aai.domain.yang.Relationship;
import org.onap.aai.domain.yang.RelationshipData;
import org.onap.aai.domain.yang.RelationshipList;
import org.onap.aai.domain.yang.SriovVf;
import org.onap.aai.domain.yang.Vserver;
import org.onap.aaiclient.client.aai.AAIResourcesClient;
import org.onap.aaiclient.client.aai.entities.AAIResultWrapper;
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.so.heatbridge.HeatBridgeException;
import org.onap.so.heatbridge.constants.HeatBridgeConstants;
import org.openstack4j.model.compute.Server;
import org.openstack4j.model.network.Network;
import org.openstack4j.model.network.Port;
import org.openstack4j.model.network.Subnet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Preconditions;

/**
 * This class provides wrapper methods to manage creation of AAI objects and extracting objects from AAI and
 * transforming into required objects.
 */
public class AaiHelper {

    private static final Logger logger = LoggerFactory.getLogger(AaiHelper.class);

    private AAIResourcesClient resourcesClient;

    public AaiHelper() {
        this.resourcesClient = new AAIResourcesClient();
    }

    /**
     * Build vserver relationship object to entities: pserver, vf-module, image, flavor
     *
     * @param cloudOwner AAI cloudOwner value
     * @param cloudRegionId AAI cloud-region identifier
     * @param genericVnfId AAI generic-vnf identifier
     * @param vfModuleId AAI vf-module identifier
     * @param server Openstack Server object
     * @throws HeatBridgeException
     */
    public RelationshipList getVserverRelationshipList(final String cloudOwner, final String cloudRegionId,
            final String genericVnfId, final String vfModuleId, final Server server) throws HeatBridgeException {
        RelationshipList relationshipList = new RelationshipList();
        List<Relationship> relationships = relationshipList.getRelationship();

        // vserver to pserver relationship
        if (!StringUtils.isEmpty(server.getHypervisorHostname())) {
            Relationship pserverRelationship = buildRelationship(AAIUriFactory.createResourceUri(
                    AAIFluentTypeBuilder.cloudInfrastructure().pserver(server.getHypervisorHostname())));
            relationships.add(pserverRelationship);
        }

        // vserver to vnfc relationship
        /*
         * if (!StringUtils.isEmpty(server.getName())) {
         * relationships.add(createVnfRelationshiptoVserver(server.getName(), genericVnfId, vfModuleId)); }
         */

        // vserver to generic-vnf relationship
        Relationship genericVnfRelationship = buildRelationship(
                AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.network().genericVnf(genericVnfId)));
        relationships.add(genericVnfRelationship);


        // vserver to vf-module relationship
        Relationship vfModuleRelationship = buildRelationship(AAIUriFactory
                .createResourceUri(AAIFluentTypeBuilder.network().genericVnf(genericVnfId).vfModule(vfModuleId)));
        relationships.add(vfModuleRelationship);

        // vserver to image relationship
        if (server.getImage() != null) {
            Relationship imageRel = buildRelationship(AAIUriFactory.createResourceUri(AAIFluentTypeBuilder
                    .cloudInfrastructure().cloudRegion(cloudOwner, cloudRegionId).image(server.getImage().getId())));
            relationships.add(imageRel);
        }

        // vserver to flavor relationship
        if (server.getFlavor() != null) {
            Relationship flavorRel = buildRelationship(AAIUriFactory.createResourceUri(AAIFluentTypeBuilder
                    .cloudInfrastructure().cloudRegion(cloudOwner, cloudRegionId).flavor(server.getFlavor().getId())));
            relationships.add(flavorRel);
        }

        return relationshipList;
    }

    public Relationship createVnfRelationshiptoVserver(String vserverName, String genericVnfId, String vfModuleId)
            throws HeatBridgeException {
        AAIResourceUri vfModuleUri = AAIUriFactory
                .createResourceUri(AAIFluentTypeBuilder.network().genericVnf(genericVnfId).vfModule(vfModuleId));
        AAIResultWrapper vfModule = resourcesClient.get(vfModuleUri);
        if (vfModule.hasRelationshipsTo(Types.VNFC)) {
            List<AAIResourceUri> vnfcUris = vfModule.getRelationships().get().getRelatedUris(Types.VNFC);
            Optional<AAIResourceUri> foundVnfcURI = vnfcUris.stream()
                    .filter(resourceUri -> resourceUri.getURIKeys().get("vnfc-name").startsWith(vserverName))
                    .findFirst();
            if (!foundVnfcURI.isPresent()) {
                throw new HeatBridgeException("Cannot Find VNFC to create edge to VServer");
            } else {
                return buildRelationship(foundVnfcURI.get());
            }
        } else {
            throw new HeatBridgeException("VF Module contains no relationships to VNFCS, cannot build edge to VServer");
        }
    }


    public RelationshipList getLInterfaceRelationshipList(final String pserverName, final String pIfName,
            final String pfPciId) {
        RelationshipList relationshipList = new RelationshipList();
        List<Relationship> relationships = relationshipList.getRelationship();

        // sriov-vf to sriov-pf relationship
        Relationship sriovPfRelationship = buildRelationship(AAIUriFactory.createResourceUri(
                AAIFluentTypeBuilder.cloudInfrastructure().pserver(pserverName).pInterface(pIfName).sriovPf(pfPciId)));
        relationships.add(sriovPfRelationship);

        return relationshipList;
    }

    public Relationship getRelationshipToVfModule(String vnfId, String vfModuleId) {
        return buildRelationship(
                AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.network().genericVnf(vnfId).vfModule(vfModuleId)));
    }

    public Relationship getRelationshipToTenant(String cloudOwner, String cloudRegionId, String tenantId) {
        return buildRelationship(AAIUriFactory.createResourceUri(
                AAIFluentTypeBuilder.cloudInfrastructure().cloudRegion(cloudOwner, cloudRegionId).tenant(tenantId)));
    }

    public org.onap.aai.domain.yang.Subnet buildSubnet(Subnet subnet) {
        org.onap.aai.domain.yang.Subnet aaiSubnet = new org.onap.aai.domain.yang.Subnet();
        aaiSubnet.setSubnetId(subnet.getId());
        aaiSubnet.setDhcpEnabled(subnet.isDHCPEnabled());

        aaiSubnet.setSubnetName(subnet.getName());
        aaiSubnet.setGatewayAddress(subnet.getGateway());
        aaiSubnet.setCidrMask(subnet.getCidr());
        aaiSubnet.setIpVersion(subnet.getIpVersion().name());
        return aaiSubnet;
    }

    public L3Network buildNetwork(Network network) {
        if (network.getId() == null) {
            return null;
        }
        L3Network l3Network = new L3Network();
        l3Network.setNetworkId(network.getId());
        l3Network.setIsBoundToVpn(true);
        l3Network.setIsProviderNetwork(true);

        // optional fields
        l3Network.setIsSharedNetwork(network.isShared());
        l3Network.setIsExternalNetwork(network.isRouterExternal());
        l3Network.setOperationalStatus(String.valueOf(network.isAdminStateUp()));
        if (network.getName() != null) {
            l3Network.setNetworkName(network.getName());
        }
        if (network.getProviderPhyNet() != null) {
            l3Network.setPhysicalNetworkName(network.getProviderPhyNet());
        }
        return l3Network;
    }

    /**
     * Transform Openstack Server object to AAI Vserver object
     *
     * @param serverId Openstack server identifier
     * @param server Openstack server object
     * @return AAI Vserver object
     */
    public Vserver buildVserver(final String serverId, final Server server) {
        Vserver vserver = new Vserver();
        vserver.setInMaint(false);
        vserver.setIsClosedLoopDisabled(false);
        vserver.setVserverId(serverId);
        vserver.setVserverName(server.getName());
        vserver.setVserverName2(server.getName());
        server.getLinks().stream().filter(link -> link.getRel().equals(HeatBridgeConstants.OS_RESOURCES_SELF_LINK_KEY))
                .findFirst().ifPresent(link -> vserver.setVserverSelflink(link.getHref()));
        return vserver;
    }

    /**
     * Transform Openstack Server object to AAI Pserver object
     *
     * @param server Openstack server object
     * @return AAI Pserver object
     */
    public Pserver buildPserver(final Server server) {
        if (server == null || server.getHypervisorHostname() == null) {
            return null;
        }
        Pserver pserver = new Pserver();
        pserver.setInMaint(false);
        pserver.setHostname(server.getHypervisorHostname());
        if (server.getId() != null) {
            pserver.setPserverId(server.getId());
        }
        if (server.getHost() != null) {
            pserver.setPserverName2(server.getHost());
        }
        return pserver;
    }

    /**
     * Transform Openstack Server object to AAI PInterface object
     *
     * @param port Openstack port object
     * @return AAI PInterface object
     */
    public PInterface buildPInterface(Port port) {
        Map<String, Object> portProfile = port.getProfile();
        PInterface pInterface = new PInterface();
        pInterface.setInterfaceName(portProfile.get(HeatBridgeConstants.OS_PHYSICAL_NETWORK_KEY).toString());
        pInterface.setInMaint(false);
        pInterface.setInterfaceRole(HeatBridgeConstants.OS_PHYSICAL_INTERFACE_KEY);
        return pInterface;
    }

    /**
     * Transform Openstack Image object to AAI Image object
     *
     * @param image Openstack Image object
     * @return AAI Image object
     */
    public Image buildImage(final org.openstack4j.model.compute.Image image) {
        Image aaiImage = new Image();
        aaiImage.setImageId(image.getId());
        aaiImage.setImageName(image.getName());
        aaiImage.setImageOsDistro(HeatBridgeConstants.OS_UNKNOWN_KEY);
        aaiImage.setImageOsVersion(HeatBridgeConstants.OS_UNKNOWN_KEY);

        // application name/vendor/version needs to be set
        if (image.getLinks() != null) {
            image.getLinks().stream()
                    .filter(link -> link.getRel().equals(HeatBridgeConstants.OS_RESOURCES_SELF_LINK_KEY)).findFirst()
                    .ifPresent(link -> aaiImage.setImageSelflink(link.getHref()));
        }
        if (aaiImage.getImageSelflink() == null || aaiImage.getImageSelflink().isEmpty()) {
            aaiImage.setImageSelflink("NA");
        }
        return aaiImage;
    }

    /**
     * Transform Openstack Flavor object to AAI Flavor object
     *
     * @param flavor Openstack Flavor object
     * @return AAI Flavor object
     */
    public Flavor buildFlavor(final org.openstack4j.model.compute.Flavor flavor) {
        Flavor aaiFlavor = new Flavor();
        aaiFlavor.setFlavorId(flavor.getId());
        aaiFlavor.setFlavorName(flavor.getName());
        aaiFlavor.setFlavorVcpus(flavor.getVcpus());
        aaiFlavor.setFlavorRam(flavor.getRam());
        aaiFlavor.setFlavorDisk(flavor.getDisk());
        aaiFlavor.setFlavorEphemeral(flavor.getEphemeral());
        aaiFlavor.setFlavorDisabled(flavor.isDisabled());
        aaiFlavor.setFlavorIsPublic(flavor.isPublic());
        aaiFlavor.setFlavorSwap(Integer.toString(flavor.getSwap()));
        flavor.getLinks().stream().filter(link -> link.getRel().equals(HeatBridgeConstants.OS_RESOURCES_SELF_LINK_KEY))
                .findFirst().ifPresent(link -> aaiFlavor.setFlavorSelflink(link.getHref()));
        return aaiFlavor;
    }

    /**
     * Extract a list of flavors URI associated with the list of vservers
     *
     * @param vservers List of vserver AAI objects
     * @return a list of related flavor related-links
     */
    public List<String> getFlavorsUriFromVserver(final List<Vserver> vservers) {
        List<String> flavorUris = new ArrayList<>();
        vservers.forEach(vserver -> flavorUris.addAll(
                filterRelatedLinksByRelatedToProperty(vserver.getRelationshipList(), HeatBridgeConstants.AAI_FLAVOR)));
        return flavorUris;
    }

    /**
     * Extract a list of images URI associated with the list of vservers
     *
     * @param vservers List of vserver AAI objects
     * @return a list of related image related-links
     */
    public List<String> getImagesUriFromVserver(final List<Vserver> vservers) {
        List<String> imageUris = new ArrayList<>();
        vservers.forEach(vserver -> imageUris.addAll(
                filterRelatedLinksByRelatedToProperty(vserver.getRelationshipList(), HeatBridgeConstants.AAI_IMAGE)));
        return imageUris;
    }

    /**
     * From the list vserver objects build a map of compute hosts's name and the PCI IDs linked to it.
     *
     * @param vservers List of vserver AAI objects
     * @return a map of compute names to the PCI ids associated with the compute
     */
    public Map<String, List<String>> getPserverToPciIdMap(final List<Vserver> vservers) {
        Map<String, List<String>> pserverToPciIdMap = new HashMap<>();
        for (Vserver vserver : vservers) {
            if (vserver.getLInterfaces() != null) {
                List<String> pciIds = vserver.getLInterfaces().getLInterface().stream()
                        .filter(lInterface -> lInterface.getSriovVfs() != null
                                && CollectionUtils.isNotEmpty(lInterface.getSriovVfs().getSriovVf()))
                        .flatMap(lInterface -> lInterface.getSriovVfs().getSriovVf().stream()).map(SriovVf::getPciId)
                        .collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(pciIds)) {
                    List<String> matchingPservers = extractRelationshipDataValue(vserver.getRelationshipList(),
                            HeatBridgeConstants.AAI_PSERVER, HeatBridgeConstants.AAI_PSERVER_HOSTNAME);
                    Preconditions.checkState(matchingPservers != null && matchingPservers.size() == 1,
                            "Invalid pserver relationships for vserver: " + vserver.getVserverName());
                    pserverToPciIdMap.put(matchingPservers.get(0), pciIds);
                }
            }
        }
        return pserverToPciIdMap;
    }

    /**
     * Extract from relationship-list object all the relationship-value that match the related-to and relationship-key
     * fields.
     *
     * @param relationshipListObj AAI relationship-list object
     * @param relatedToProperty related-to value
     * @param relationshipKey relationship-key value
     * @return relationship-value matching the key requested for the relationship object of type related-to property
     */
    private List<String> extractRelationshipDataValue(final RelationshipList relationshipListObj,
            final String relatedToProperty, final String relationshipKey) {
        if (relationshipListObj != null && relationshipListObj.getRelationship() != null) {
            return relationshipListObj.getRelationship().stream()
                    .filter(relationship -> relationship.getRelatedTo().equals(relatedToProperty))
                    .map(Relationship::getRelationshipData).flatMap(Collection::stream)
                    .filter(data -> data.getRelationshipKey() != null
                            && relationshipKey.equals(data.getRelationshipKey()))
                    .map(RelationshipData::getRelationshipValue).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    /**
     * Extract and filter the related-links to all objects that match the type specified by the filter property
     *
     * @param relationshipListObj AAI object representing relationship object
     * @param relatedToProperty Value identifying the type of AAI object for related-to field
     * @return a list of related-links filtered by the specified related-to property
     */
    private List<String> filterRelatedLinksByRelatedToProperty(final RelationshipList relationshipListObj,
            final String relatedToProperty) {
        if (relationshipListObj != null && relationshipListObj.getRelationship() != null) {
            return relationshipListObj.getRelationship().stream()
                    .filter(relationship -> relationship.getRelatedTo().equals(relatedToProperty))
                    .map(Relationship::getRelatedLink).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }

    /**
     * Build the relationship object
     *
     * @param relatedTo Related to entity value
     * @param relationshipKeyValues Key value pairs of relationship data
     * @return AAI Relationship object
     */
    private Relationship buildRelationship(final AAIResourceUri relatedLink) {
        Relationship relationship = new Relationship();
        relationship.setRelatedLink(relatedLink.build().toString());
        return relationship;
    }

    public void setAAIResourcesClient(AAIResourcesClient client) {
        this.resourcesClient = client;
    }
}