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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
|
/*-
* ============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. 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.
*/
package org.onap.so.heatbridge;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.WebApplicationException;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.validator.routines.InetAddressValidator;
import org.onap.aai.domain.yang.Flavor;
import org.onap.aai.domain.yang.Image;
import org.onap.aai.domain.yang.L3InterfaceIpv4AddressList;
import org.onap.aai.domain.yang.L3InterfaceIpv6AddressList;
import org.onap.aai.domain.yang.L3Network;
import org.onap.aai.domain.yang.LInterface;
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.RelationshipList;
import org.onap.aai.domain.yang.SriovPf;
import org.onap.aai.domain.yang.SriovPfs;
import org.onap.aai.domain.yang.Subnets;
import org.onap.aai.domain.yang.SriovVf;
import org.onap.aai.domain.yang.VfModule;
import org.onap.aai.domain.yang.Vlan;
import org.onap.aai.domain.yang.Vserver;
import org.onap.aaiclient.client.aai.AAIDSLQueryClient;
import org.onap.aaiclient.client.aai.AAIResourcesClient;
import org.onap.aaiclient.client.aai.AAISingleTransactionClient;
import org.onap.aaiclient.client.aai.entities.AAIResultWrapper;
import org.onap.aaiclient.client.aai.entities.Relationships;
import org.onap.aaiclient.client.aai.entities.Results;
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.graphinventory.Format;
import org.onap.aaiclient.client.graphinventory.entities.DSLQuery;
import org.onap.aaiclient.client.graphinventory.entities.DSLQueryBuilder;
import org.onap.aaiclient.client.graphinventory.entities.DSLStartNode;
import org.onap.aaiclient.client.graphinventory.entities.Node;
import org.onap.aaiclient.client.graphinventory.entities.Start;
import org.onap.aaiclient.client.graphinventory.entities.TraversalBuilder;
import org.onap.aaiclient.client.graphinventory.entities.__;
import org.onap.aaiclient.client.graphinventory.entities.uri.Depth;
import org.onap.aaiclient.client.graphinventory.exceptions.BulkProcessFailed;
import org.onap.logging.filter.base.ErrorCode;
import org.onap.so.cloud.resource.beans.NodeType;
import org.onap.so.db.catalog.beans.CloudIdentity;
import org.onap.so.db.catalog.beans.ServerType;
import org.onap.so.heatbridge.constants.HeatBridgeConstants;
import org.onap.so.heatbridge.factory.MsoCloudClientFactoryImpl;
import org.onap.so.heatbridge.helpers.AaiHelper;
import org.onap.so.heatbridge.openstack.api.OpenstackClient;
import org.onap.so.heatbridge.openstack.factory.OpenstackClientFactoryImpl;
import org.onap.so.heatbridge.utils.HeatBridgeUtils;
import org.onap.so.logger.LoggingAnchor;
import org.onap.so.logger.MessageEnum;
import org.onap.so.spring.SpringContextHelper;
import org.openstack4j.model.compute.Server;
import org.openstack4j.model.heat.Resource;
import org.openstack4j.model.network.IP;
import org.openstack4j.model.network.Network;
import org.openstack4j.model.network.NetworkType;
import org.openstack4j.model.network.Port;
import org.openstack4j.model.network.Subnet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import inet.ipaddr.IPAddressString;
/**
* This class provides an implementation of {@link HeatBridgeApi}
*/
public class HeatBridgeImpl implements HeatBridgeApi {
private static final Logger logger = LoggerFactory.getLogger(HeatBridgeImpl.class);
private static final String ERR_MSG_NULL_OS_CLIENT =
"Initialization error: Null openstack client. Authenticate with Keystone first.";
private static final String OOB_MGT_NETWORK_IDENTIFIER = "Management";
protected static final String DIRECT = "direct";
protected static final String PCI_SLOT = "pci_slot";
protected static final String OVSNET = "ovsnet";
protected static final String SRIOV = "SRIOV";
protected static final String RESOURCE_LINK = "resource-link";
protected static final Object PRIVATE_VLANS = "private_vlans";
protected static final Object PUBLIC_VLANS = "public_vlans";
protected ObjectMapper mapper = new ObjectMapper();
private OpenstackClient osClient;
private AAIResourcesClient resourcesClient;
private AAIDSLQueryClient aaiDSLClient;
private AAISingleTransactionClient transaction;
private String cloudOwner;
private String cloudRegionId;
private String regionId;
private String tenantId;
private NodeType nodeType;
private AaiHelper aaiHelper = new AaiHelper();
private CloudIdentity cloudIdentity;
private Environment env;
public HeatBridgeImpl(AAIResourcesClient resourcesClient, final CloudIdentity cloudIdentity,
@Nonnull final String cloudOwner, @Nonnull final String cloudRegionId, @Nonnull final String regionId,
@Nonnull final String tenantId, @Nonnull final NodeType nodeType) {
Objects.requireNonNull(cloudOwner, "Null cloud-owner value!");
Objects.requireNonNull(cloudRegionId, "Null cloud-region identifier!");
Objects.requireNonNull(tenantId, "Null tenant identifier!");
Objects.requireNonNull(regionId, "Null regionId identifier!");
this.cloudIdentity = cloudIdentity;
this.cloudOwner = cloudOwner;
this.cloudRegionId = cloudRegionId;
this.regionId = regionId;
this.tenantId = tenantId;
this.resourcesClient = resourcesClient;
this.nodeType = nodeType;
if (resourcesClient != null)
this.transaction = resourcesClient.beginSingleTransaction();
if (SpringContextHelper.getAppContext() != null)
this.env = SpringContextHelper.getAppContext().getEnvironment();
}
public HeatBridgeImpl() {
this.resourcesClient = new AAIResourcesClient();
this.transaction = resourcesClient.beginSingleTransaction();
}
@Override
public OpenstackClient authenticate() throws HeatBridgeException {
String keystoneVersion = "";
if (ServerType.KEYSTONE.equals(cloudIdentity.getIdentityServerType()))
keystoneVersion = "v2.0";
else if (ServerType.KEYSTONE_V3.equals(cloudIdentity.getIdentityServerType())) {
keystoneVersion = "v3";
} else {
keystoneVersion = "UNKNOWN";
}
logger.trace("Keystone Version: {} ", keystoneVersion);
this.osClient = new MsoCloudClientFactoryImpl(new OpenstackClientFactoryImpl()).getOpenstackClient(
cloudIdentity.getIdentityUrl(), cloudIdentity.getMsoId(), cloudIdentity.getMsoPass(), regionId,
tenantId, keystoneVersion, cloudIdentity.getUserDomainName(), cloudIdentity.getProjectDomainName());
logger.trace("Successfully authenticated with keystone for tenant: {} and region: {}", tenantId, regionId);
return osClient;
}
@Override
public List<Resource> queryNestedHeatStackResources(final String heatStackId) {
Objects.requireNonNull(osClient, ERR_MSG_NULL_OS_CLIENT);
Preconditions.checkState(!Strings.isNullOrEmpty(heatStackId), "Invalid heatStackId!");
List<Resource> stackBasedResources =
osClient.getStackBasedResources(heatStackId, HeatBridgeConstants.OS_DEFAULT_HEAT_NESTING);
logger.debug(stackBasedResources.size() + " heat stack resources are extracted for stack: " + heatStackId);
return stackBasedResources;
}
@Override
public List<String> extractStackResourceIdsByResourceType(final List<Resource> stackResources,
final String resourceType) {
return stackResources.stream().filter(stackResource -> stackResource.getType().equals(resourceType))
.map(Resource::getPhysicalResourceId).collect(Collectors.toList());
}
@Override
public List<String> extractNetworkIds(final List<String> networkNameList) {
Objects.requireNonNull(osClient, ERR_MSG_NULL_OS_CLIENT);
return networkNameList.stream()
.map(netName -> osClient
.listNetworksByFilter(ImmutableMap.of(HeatBridgeConstants.OS_NAME_KEY, netName)))
.filter(nets -> nets != null && nets.size() == 1) // extract network-id only if network-name is unique
.map(nets -> nets.get(0).getId()).collect(Collectors.toList());
}
@Override
public List<Server> getAllOpenstackServers(final List<Resource> stackResources) {
Objects.requireNonNull(osClient, ERR_MSG_NULL_OS_CLIENT);
// Filter Openstack Compute resources
List<String> serverIds =
extractStackResourceIdsByResourceType(stackResources, HeatBridgeConstants.OS_SERVER_RESOURCE_TYPE);
return serverIds.stream().map(serverId -> osClient.getServerById(serverId)).collect(Collectors.toList());
}
protected Server getOpenstackServerById(String deviceId) {
return osClient.getServerById(deviceId);
}
@Override
public List<Network> getAllOpenstackProviderNetworks(final List<Resource> stackResources) {
Objects.requireNonNull(osClient, ERR_MSG_NULL_OS_CLIENT);
// Filter Openstack Compute resources
List<String> providerNetworkIds =
extractStackResourceIdsByResourceType(stackResources, HeatBridgeConstants.OS_NEUTRON_PROVIDERNET);
return providerNetworkIds.stream().map(providerNetworkId -> osClient.getNetworkById(providerNetworkId))
.collect(Collectors.toList());
}
@Override
public List<org.openstack4j.model.compute.Image> extractOpenstackImagesFromServers(final List<Server> servers) {
Objects.requireNonNull(osClient, ERR_MSG_NULL_OS_CLIENT);
return servers.stream().map(Server::getImage)
.filter(distinctByProperty(org.openstack4j.model.compute.Image::getId)).collect(Collectors.toList());
}
@Override
public List<org.openstack4j.model.compute.Flavor> extractOpenstackFlavorsFromServers(final List<Server> servers) {
Objects.requireNonNull(osClient, ERR_MSG_NULL_OS_CLIENT);
return servers.stream().map(Server::getFlavor)
.filter(distinctByProperty(org.openstack4j.model.compute.Flavor::getId)).collect(Collectors.toList());
}
public void buildAddNetworksToAaiAction(final String genericVnfId, final String vfModuleId,
List<Network> networks) {
networks.forEach(network -> {
L3Network l3Network = aaiHelper.buildNetwork(network);
if (l3Network != null) {
l3Network.setSubnets(buildSunets(network));
RelationshipList relationshipList = new RelationshipList();
List<Relationship> relationships = relationshipList.getRelationship();
relationships.add(aaiHelper.getRelationshipToVfModule(genericVnfId, vfModuleId));
relationships.add(aaiHelper.getRelationshipToTenant(cloudOwner, cloudRegionId, tenantId));
l3Network.setRelationshipList(relationshipList);
transaction.createIfNotExists(
AAIUriFactory
.createResourceUri(AAIFluentTypeBuilder.network().l3Network(l3Network.getNetworkId())),
Optional.of(l3Network));
}
});
}
@Override
public void buildAddImagesToAaiAction(final List<org.openstack4j.model.compute.Image> images)
throws HeatBridgeException {
for (org.openstack4j.model.compute.Image image : images) {
Image aaiImage = aaiHelper.buildImage(image);
try {
AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure()
.cloudRegion(cloudOwner, cloudRegionId).image(aaiImage.getImageId()));
if (!resourcesClient.exists(uri)) {
transaction.create(uri, aaiImage);
logger.debug("Queuing AAI command to add image: " + aaiImage.getImageId());
} else {
logger.debug("Nothing to add since image: " + aaiImage.getImageId() + "already exists in AAI.");
}
} catch (WebApplicationException e) {
throw new HeatBridgeException(
"Failed to update image to AAI: " + aaiImage.getImageId() + ". Error" + " cause: " + e, e);
}
}
}
@Override
public void buildAddFlavorsToAaiAction(final List<org.openstack4j.model.compute.Flavor> flavors)
throws HeatBridgeException {
for (org.openstack4j.model.compute.Flavor flavor : flavors) {
Flavor aaiFlavor = aaiHelper.buildFlavor(flavor);
try {
AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure()
.cloudRegion(cloudOwner, cloudRegionId).flavor(aaiFlavor.getFlavorId()));
transaction.createIfNotExists(uri, Optional.of(aaiFlavor));
} catch (WebApplicationException e) {
throw new HeatBridgeException(
"Failed to update flavor to AAI: " + aaiFlavor.getFlavorId() + ". Error" + " cause: " + e, e);
}
}
}
@Override
public void buildAddVserversToAaiAction(final String genericVnfId, final String vfModuleId,
final List<Server> servers) {
servers.forEach(server -> {
Vserver vserver = aaiHelper.buildVserver(server.getId(), server);
// Build vserver relationships to: image, flavor, pserver, vf-module
vserver.setRelationshipList(
aaiHelper.getVserverRelationshipList(cloudOwner, cloudRegionId, genericVnfId, vfModuleId, server));
transaction.createIfNotExists(
AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure()
.cloudRegion(cloudOwner, cloudRegionId).tenant(tenantId).vserver(vserver.getVserverId())),
Optional.of(vserver));
});
}
@Override
public void buildAddVserverLInterfacesToAaiAction(final List<Resource> stackResources,
final List<String> oobMgtNetIds, String cloudOwner) throws HeatBridgeException {
Objects.requireNonNull(osClient, ERR_MSG_NULL_OS_CLIENT);
List<String> portIds =
extractStackResourceIdsByResourceType(stackResources, HeatBridgeConstants.OS_PORT_RESOURCE_TYPE);
if (portIds == null)
return;
for (String portId : portIds) {
boolean isL2Multicast = false;
Port port = osClient.getPortById(portId);
Network network = osClient.getNetworkById(port.getNetworkId());
LInterface lIf = new LInterface();
lIf.setInterfaceId(port.getId());
lIf.setInterfaceName(port.getName());
lIf.setMacaddr(port.getMacAddress());
lIf.setNetworkName(network.getName());
lIf.setIsPortMirrored(false);
lIf.setIsIpUnnumbered(false);
lIf.setInMaint(false);
if (port.getProfile() != null && port.getProfile().get("trusted") != null) {
String trusted = port.getProfile().get("trusted").toString();
if (Boolean.parseBoolean(trusted)) {
isL2Multicast = true;
}
}
lIf.setL2Multicasting(isL2Multicast);
lIf.setInterfaceType(getInterfaceType(nodeType, port.getvNicType()));
lIf.setRelationshipList(new RelationshipList());
if (oobMgtNetIds != null && oobMgtNetIds.contains(port.getNetworkId())) {
lIf.setInterfaceRole(OOB_MGT_NETWORK_IDENTIFIER);
} else {
lIf.setInterfaceRole(port.getvNicType());
}
// Update l-interface to the vserver
transaction.createIfNotExists(
AAIUriFactory.createResourceUri(
AAIFluentTypeBuilder.cloudInfrastructure().cloudRegion(cloudOwner, cloudRegionId)
.tenant(tenantId).vserver(port.getDeviceId()).lInterface(lIf.getInterfaceName())),
Optional.of(lIf));
updateLInterfaceIps(port, lIf);
if (cloudOwner.equals(env.getProperty("mso.cloudOwner.included", ""))) {
Server server = getOpenstackServerById(port.getDeviceId());
updateLInterfaceVlan(port, lIf, server.getHypervisorHostname());
}
updateSriovPfToPserver(port, lIf);
}
}
protected String getInterfaceType(NodeType nodeType, String nicType) {
logger.debug("nicType: " + nicType + "nodeType: " + nodeType);
if (DIRECT.equalsIgnoreCase(nicType)) {
return SRIOV;
} else {
if (nodeType == NodeType.GREENFIELD) {
return NodeType.GREENFIELD.getNetworkTechnologyName();
} else {
return NodeType.BROWNFIELD.getNetworkTechnologyName();
}
}
}
@Override
public void createPserversAndPinterfacesIfNotPresentInAai(final List<Resource> stackResources)
throws HeatBridgeException {
if (stackResources == null) {
return;
}
Map<String, Pserver> serverHostnames = getPserverMapping(stackResources);
createPServerIfNotExists(serverHostnames);
List<String> portIds =
extractStackResourceIdsByResourceType(stackResources, HeatBridgeConstants.OS_PORT_RESOURCE_TYPE);
for (String portId : portIds) {
Port port = osClient.getPortById(portId);
if (port.getvNicType().equalsIgnoreCase(HeatBridgeConstants.OS_SRIOV_PORT_TYPE)) {
Pserver foundServer = serverHostnames.get(port.getHostId());
if (foundServer != null) {
createPServerPInterfaceIfNotExists(foundServer.getHostname(), aaiHelper.buildPInterface(port));
}
}
}
}
private Map<String, Pserver> getPserverMapping(final List<Resource> stackResources) {
List<Server> osServers = getAllOpenstackServers(stackResources);
Map<String, Pserver> pserverMap = new HashMap<>();
if (osServers != null) {
for (Server server : osServers) {
Pserver pserver = aaiHelper.buildPserver(server);
if (pserver != null) {
logger.debug("Adding Pserver: " + server.getHost());
pserverMap.put(server.getHost(), pserver);
}
}
}
return pserverMap;
}
private Subnets buildSunets(Network network) {
Subnets aaiSubnets = new Subnets();
List<String> subnetIds = network.getSubnets();
subnetIds.forEach(subnetId -> {
Subnet subnet = osClient.getSubnetById(subnetId);
org.onap.aai.domain.yang.Subnet aaiSubnet = aaiHelper.buildSubnet(subnet);
if (aaiSubnet != null) {
aaiSubnets.getSubnet().add(aaiSubnet);
}
});
return aaiSubnets;
}
private void createPServerIfNotExists(Map<String, Pserver> serverHostnames) {
for (Pserver pserver : serverHostnames.values()) {
AAIResourceUri uri = AAIUriFactory
.createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure().pserver(pserver.getHostname()));
resourcesClient.createIfNotExists(uri, Optional.of(pserver));
}
}
private void createPServerPInterfaceIfNotExists(String pserverHostname, PInterface pInterface) {
AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure()
.pserver(pserverHostname).pInterface(pInterface.getInterfaceName()));
resourcesClient.createIfNotExists(uri, Optional.of(pInterface));
}
protected void updateLInterfaceVlan(final Port port, final LInterface lIf, final String hostName)
throws HeatBridgeException {
// add back all vlan logic
Vlan vlan = new Vlan();
Network network = osClient.getNetworkById(port.getNetworkId());
if (network.getNetworkType() != null && network.getNetworkType().equals(NetworkType.VLAN)) {
vlan.setVlanInterface(port.getName() + network.getProviderSegID());
vlan.setVlanIdOuter(Long.parseLong(network.getProviderSegID()));
vlan.setVlanIdInner(0L);
vlan.setInMaint(false);
vlan.setIsIpUnnumbered(false);
vlan.setIsPrivate(false);
transaction
.createIfNotExists(
AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure()
.cloudRegion(cloudOwner, cloudRegionId).tenant(tenantId).vserver(port.getDeviceId())
.lInterface(lIf.getInterfaceName()).vlan(vlan.getVlanInterface())),
Optional.of(vlan));
}
if (!lIf.getInterfaceType().equals(SRIOV)) {
if (nodeType == NodeType.GREENFIELD) {
validatePhysicalNetwork(port, network);
processOVS(lIf, hostName, NodeType.GREENFIELD.getInterfaceName());
} else {
processOVS(lIf, hostName, NodeType.BROWNFIELD.getInterfaceName());
}
}
List<String> privateVlans = (ArrayList<String>) port.getProfile().get(PRIVATE_VLANS);
List<String> publicVlans = (ArrayList<String>) port.getProfile().get(PUBLIC_VLANS);
List<String> vlans = null;
if (publicVlans != null && !publicVlans.isEmpty()) {
vlans = publicVlans.stream().filter(publicVlan -> !Strings.isNullOrEmpty(publicVlan))
.collect(Collectors.toList());
} else {
vlans = new ArrayList<>();
}
if (privateVlans != null && !privateVlans.isEmpty()) {
List<String> temp = privateVlans.stream().filter(privateVlan -> !Strings.isNullOrEmpty(privateVlan))
.collect(Collectors.toList());
vlans.addAll(temp);
}
vlans.stream().forEach(vlanLocal -> logger.debug("Vlan Id: {}", vlanLocal));
processVlanTag(lIf, vlans);
if (port.getvNicType() != null && port.getvNicType().equalsIgnoreCase(HeatBridgeConstants.OS_SRIOV_PORT_TYPE)) {
SriovVf sriovVf = new SriovVf();
sriovVf.setPciId(port.getProfile().get(HeatBridgeConstants.OS_PCI_SLOT_KEY).toString());
sriovVf.setNeutronNetworkId(port.getNetworkId());
sriovVf.setVfVlanFilter("0");
sriovVf.setVfVlanAntiSpoofCheck(false);
sriovVf.setVfMacAntiSpoofCheck(false);
transaction
.createIfNotExists(
AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure()
.cloudRegion(cloudOwner, cloudRegionId).tenant(tenantId).vserver(port.getDeviceId())
.lInterface(lIf.getInterfaceName()).sriovVf(sriovVf.getPciId())),
Optional.of(sriovVf));
}
}
protected String createVlanTagUri(String vlanIdOuter) throws HeatBridgeException {
int vlanOuterInt = Integer.parseInt(vlanIdOuter);
DSLQueryBuilder<Start, Node> builder = TraversalBuilder
.fragment(new DSLStartNode(Types.CLOUD_REGION, __.key("cloud-owner", cloudOwner),
__.key("cloud-region-id", cloudRegionId)))
.to(__.node(Types.VLAN_RANGE))
.to(__.node(Types.VLAN_TAG, __.key("vlan-id-outer", vlanOuterInt)).output());
String results = getAAIDSLClient().query(Format.PATHED, new DSLQuery(builder.build()));
Optional<String> vlanTagURI = findLinkedURI(results);
if (vlanTagURI.isPresent())
return vlanTagURI.get();
else
throw new HeatBridgeException("Cannot find VlanTag Related Link " + vlanIdOuter);
}
protected void processVlanTag(LInterface lInterface, List<String> vlanTags) throws HeatBridgeException {
for (String vlanTag : vlanTags) {
Relationship vlanTagRelationship = new Relationship();
vlanTagRelationship.setRelatedLink(createVlanTagUri(vlanTag));
lInterface.getRelationshipList().getRelationship().add(vlanTagRelationship);
}
}
protected void validatePhysicalNetwork(Port neutronPort, Network network) throws HeatBridgeException {
String physicalNetworkType = network.getProviderPhyNet();
if (!OVSNET.equalsIgnoreCase(physicalNetworkType)) {
String exceptionMessage = String.format(
"The OVS-DPDK port is expected to have a physical network of type ovsnet but was found to have %s instead.",
physicalNetworkType);
throw new HeatBridgeException(exceptionMessage);
}
}
protected void processOVS(LInterface lInterface, String hostName, String interfaceName) {
Relationship lagRelationship = new Relationship();
lagRelationship.setRelatedLink(AAIUriFactory
.createResourceUri(
AAIFluentTypeBuilder.cloudInfrastructure().pserver(hostName).lagInterface(interfaceName))
.build().toString());
lInterface.getRelationshipList().getRelationship().add(lagRelationship);
}
/**
* Needs to be corrected according to the specification that is in draft If pserver/p-interface does not have a
* SRIOV-PF object matching the PCI-ID of the Openstack port object, then create it in AAI. Openstack SRIOV Port
* object has pci-id (to match sriov-pf on pserver/p-interface), physical-network ID (that matches the p-interface
* name).
*
* @param port Openstack port object
* @param lIf AAI l-interface object
*/
private void updateSriovPfToPserver(final Port port, final LInterface lIf) {
if (port.getvNicType().equalsIgnoreCase(HeatBridgeConstants.OS_SRIOV_PORT_TYPE)) {
if (port.getProfile() == null || Strings
.isNullOrEmpty(port.getProfile().get(HeatBridgeConstants.OS_PHYSICAL_NETWORK_KEY).toString())) {
logger.debug("The SRIOV port:" + port.getName() + " is missing physical-network-id, cannot update "
+ "sriov-pf object for host pserver: " + port.getHostId());
return;
}
Optional<String> matchingPifName = HeatBridgeUtils.getMatchingPserverPifName(
port.getProfile().get(HeatBridgeConstants.OS_PHYSICAL_NETWORK_KEY).toString());
if (matchingPifName.isPresent()) {
// Update l-interface description
String pserverHostName = port.getHostId();
lIf.setInterfaceDescription(
"Attached to SR-IOV port: " + pserverHostName + "::" + matchingPifName.get());
try {
AAIResourceUri pInterfaceUri =
AAIUriFactory
.createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure()
.pserver(pserverHostName).pInterface(matchingPifName.get()))
.depth(Depth.ONE);
if (resourcesClient.exists(pInterfaceUri)) {
PInterface matchingPIf = resourcesClient.get(PInterface.class, pInterfaceUri).get();
String pfPciId = port.getProfile().get(HeatBridgeConstants.OS_PCI_SLOT_KEY).toString();
if (matchingPIf.getSriovPfs() == null
|| CollectionUtils.isEmpty(matchingPIf.getSriovPfs().getSriovPf())
|| matchingPIf.getSriovPfs().getSriovPf().stream()
.noneMatch(existingSriovPf -> existingSriovPf.getPfPciId().equals(pfPciId))) {
SriovPf sriovPf = new SriovPf();
sriovPf.setPfPciId(pfPciId);
AAIResourceUri sriovPfUri = AAIUriFactory.createResourceUri(
AAIFluentTypeBuilder.cloudInfrastructure().pserver(pserverHostName)
.pInterface(matchingPifName.get()).sriovPf(sriovPf.getPfPciId()));
// TODO if it does exist, should check if relationship is there, if not then create?
if (!resourcesClient.exists(sriovPfUri)) {
transaction.create(sriovPfUri, sriovPf);
AAIResourceUri sriovVfUri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder
.cloudInfrastructure().cloudRegion(cloudOwner, cloudRegionId).tenant(tenantId)
.vserver(port.getDeviceId()).lInterface(lIf.getInterfaceName()).sriovVf(
port.getProfile().get(HeatBridgeConstants.OS_PCI_SLOT_KEY).toString()));
transaction.connect(sriovPfUri, sriovVfUri);
}
}
} else {
logger.warn(
"PInterface {} does not exist in AAI. Unable to build sriov-vf to sriov-pf relationship.",
matchingPifName.get());
}
} catch (WebApplicationException e) {
// Silently log that we failed to update the Pserver p-interface with PCI-ID
logger.error(LoggingAnchor.NINE, MessageEnum.GENERAL_EXCEPTION, pserverHostName,
matchingPifName.get(), cloudOwner, tenantId, "OpenStack", "Heatbridge",
ErrorCode.DataError.getValue(), "Exception - Failed to add sriov-pf object to pserver", e);
}
}
}
}
protected void updateLInterfaceIps(final Port port, final LInterface lIf) {
for (IP ip : port.getFixedIps()) {
String ipAddress = ip.getIpAddress();
if (InetAddressValidator.getInstance().isValidInet4Address(ipAddress)) {
Subnet subnet = osClient.getSubnetById(ip.getSubnetId());
IPAddressString cidr = new IPAddressString(subnet.getCidr());
L3InterfaceIpv4AddressList lInterfaceIp = new L3InterfaceIpv4AddressList();
lInterfaceIp.setIsFloating(false);
lInterfaceIp.setL3InterfaceIpv4Address(ipAddress);
lInterfaceIp.setNeutronNetworkId(port.getNetworkId());
lInterfaceIp.setNeutronSubnetId(ip.getSubnetId());
lInterfaceIp.setL3InterfaceIpv4PrefixLength(Long.parseLong(cidr.getNetworkPrefixLength().toString()));
transaction.createIfNotExists(
AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure()
.cloudRegion(cloudOwner, cloudRegionId).tenant(tenantId).vserver(port.getDeviceId())
.lInterface(lIf.getInterfaceName()).l3InterfaceIpv4AddressList(ipAddress)),
Optional.of(lInterfaceIp));
} else if (InetAddressValidator.getInstance().isValidInet6Address(ipAddress)) {
Subnet subnet = osClient.getSubnetById(ip.getSubnetId());
IPAddressString cidr = new IPAddressString(subnet.getCidr());
L3InterfaceIpv6AddressList ipv6 = new L3InterfaceIpv6AddressList();
ipv6.setIsFloating(false);
ipv6.setL3InterfaceIpv6Address(ipAddress);
ipv6.setNeutronNetworkId(port.getNetworkId());
ipv6.setNeutronSubnetId(ip.getSubnetId());
ipv6.setL3InterfaceIpv6PrefixLength(Long.parseLong(cidr.getNetworkPrefixLength().toString()));
transaction.createIfNotExists(
AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure()
.cloudRegion(cloudOwner, cloudRegionId).tenant(tenantId).vserver(port.getDeviceId())
.lInterface(lIf.getInterfaceName()).l3InterfaceIpv6AddressList(ipAddress)),
Optional.of(ipv6));
}
}
}
@Override
public void submitToAai(boolean dryrun) throws HeatBridgeException {
try {
transaction.execute(dryrun);
} catch (BulkProcessFailed e) {
String msg = "Failed to commit transaction";
logger.debug(msg + " with error: " + e);
throw new HeatBridgeException(msg, e);
}
}
@Override
public void deleteVfModuleData(@Nonnull final String vnfId, @Nonnull final String vfModuleId)
throws HeatBridgeException {
Objects.requireNonNull(vnfId, "Null vnf-id!");
Objects.requireNonNull(vfModuleId, "Null vf-module-id!");
try {
Optional<VfModule> vfModule = resourcesClient.get(AAIUriFactory
.createResourceUri(AAIFluentTypeBuilder.network().genericVnf(vnfId).vfModule(vfModuleId))
.depth(Depth.ONE), NotFoundException.class).asBean(VfModule.class);
AAIResultWrapper resultWrapper = new AAIResultWrapper(vfModule.get());
Optional<Relationships> relationships = resultWrapper.getRelationships();
logger.debug("VfModule contains relationships in AAI: {}", relationships.isPresent());
if (relationships.isPresent()) {
List<AAIResourceUri> l3NetworkUris = relationships.get().getRelatedUris(Types.L3_NETWORK);
logger.debug("L3Network contains {} relationships in AAI", l3NetworkUris.size());
if (!l3NetworkUris.isEmpty()) {
for (AAIResourceUri l3NetworkUri : l3NetworkUris) {
if (env.getProperty("heatBridgeDryrun", Boolean.class, true)) {
logger.debug("Would delete L3Network: {}", l3NetworkUri.build().toString());
} else {
resourcesClient.delete(l3NetworkUri);
}
}
}
List<AAIResourceUri> vserverUris = relationships.get().getRelatedUris(Types.VSERVER);
logger.debug("VServer contains {} relationships in AAI", vserverUris.size());
createTransactionToDeleteSriovPfFromPserver(vserverUris);
if (!vserverUris.isEmpty()) {
for (AAIResourceUri vserverUri : vserverUris) {
if (env.getProperty("heatBridgeDryrun", Boolean.class, false)) {
logger.debug("Would delete Vserver: {}", vserverUri.build().toString());
} else {
resourcesClient.delete(vserverUri);
}
}
}
}
} catch (NotFoundException e) {
String msg = "Failed to commit delete heatbridge data transaction";
logger.debug(msg + " with error: " + e);
throw new HeatBridgeException(msg, e);
} catch (Exception e) {
String msg = "Failed to commit delete heatbridge data transaction";
logger.debug(msg + " with error: " + e);
throw new HeatBridgeException(msg, e);
}
}
private void createTransactionToDeleteSriovPfFromPserver(List<AAIResourceUri> vserverUris) {
Map<String, List<String>> pserverToPciIdMap = getPserverToPciIdMap(vserverUris);
for (Map.Entry<String, List<String>> entry : pserverToPciIdMap.entrySet()) {
String pserverName = entry.getKey();
List<String> pciIds = entry.getValue();
Optional<Pserver> pserver = resourcesClient.get(Pserver.class,
AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure().pserver(pserverName))
.depth(Depth.TWO));
if (pserver.isPresent()) {
// For each pserver/p-interface match sriov-vfs by pic-id and delete them.
pserver.get().getPInterfaces().getPInterface().stream().filter(
pIf -> pIf.getSriovPfs() != null && CollectionUtils.isNotEmpty(pIf.getSriovPfs().getSriovPf()))
.forEach(pIf -> pIf.getSriovPfs().getSriovPf().forEach(sriovPf -> {
if (pciIds.contains(sriovPf.getPfPciId())) {
logger.debug("creating transaction to delete SR-IOV PF: " + pIf.getInterfaceName()
+ " from PServer: " + pserverName);
if (env.getProperty("heatBridgeDryrun", Boolean.class, false)) {
logger.debug("Would delete Sriov Pf: {}",
AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.cloudInfrastructure()
.pserver(pserverName).pInterface(pIf.getInterfaceName())
.sriovPf(sriovPf.getPfPciId())).build());
} else {
resourcesClient.delete(AAIUriFactory.createResourceUri(
AAIFluentTypeBuilder.cloudInfrastructure().pserver(pserverName)
.pInterface(pIf.getInterfaceName()).sriovPf(sriovPf.getPfPciId())));
}
}
}));
}
}
}
private Map<String, List<String>> getPserverToPciIdMap(List<AAIResourceUri> vserverUris) {
Map<String, List<String>> pserverToPciIdMap = new HashMap<>();
for (AAIResourceUri vserverUri : vserverUris) {
AAIResultWrapper vserverWrapper = resourcesClient.get(vserverUri.depth(Depth.TWO));
Optional<Relationships> vserverRelationships = vserverWrapper.getRelationships();
if (vserverRelationships.isPresent()
&& CollectionUtils.isNotEmpty(vserverRelationships.get().getRelatedLinks(Types.PSERVER))) {
Vserver vserver = vserverWrapper.asBean(Vserver.class).get();
List<String> pciIds = HeatBridgeUtils.extractPciIdsFromVServer(vserver);
if (CollectionUtils.isNotEmpty(pciIds)) {
List<AAIResourceUri> matchingPservers = vserverRelationships.get().getRelatedUris(Types.PSERVER);
if (matchingPservers != null && matchingPservers.size() == 1) {
pserverToPciIdMap.put(matchingPservers.get(0).getURIKeys().get("hostname"), pciIds);
}
}
}
}
return pserverToPciIdMap;
}
private <T> Predicate<T> distinctByProperty(Function<? super T, Object> keyExtractor) {
Map<Object, Boolean> map = new ConcurrentHashMap<>();
return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
protected Optional<String> findLinkedURI(String jsonResultsString) {
Results<Map<String, String>> results;
try {
results = mapper.readValue(jsonResultsString, new TypeReference<Results<Map<String, String>>>() {});
if (results.getResult().size() == 1) {
return Optional.of(results.getResult().get(0).get(RESOURCE_LINK));
} else if (results.getResult().isEmpty()) {
return Optional.empty();
} else {
throw new IllegalStateException("more than one result returned");
}
} catch (IOException e) {
logger.error("Error retrieving URI from Results JSON", e);
return Optional.empty();
}
}
protected AAIDSLQueryClient getAAIDSLClient() {
if (aaiDSLClient == null) {
aaiDSLClient = new AAIDSLQueryClient();
}
return aaiDSLClient;
}
}
|