com.microsoft.azure.management.network.NetworkInterface Java Examples

The following examples show how to use com.microsoft.azure.management.network.NetworkInterface. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AzureVmPublicIpProvider.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
String getPublicIp(AzureClient azureClient, AzureUtils azureUtils, NetworkInterface networkInterface, String resourceGroup) {
    PublicIPAddress publicIpAddress = networkInterface.primaryIPConfiguration().getPublicIPAddress();

    List<LoadBalancerBackend> backends = networkInterface.primaryIPConfiguration().listAssociatedLoadBalancerBackends();
    List<LoadBalancerInboundNatRule> inboundNatRules = networkInterface.primaryIPConfiguration().listAssociatedLoadBalancerInboundNatRules();
    String publicIp = null;
    if (!backends.isEmpty() || !inboundNatRules.isEmpty()) {
        publicIp = azureClient.getLoadBalancerIps(resourceGroup, azureUtils.getLoadBalancerId(resourceGroup)).get(0);
    }

    if (publicIpAddress != null && publicIpAddress.ipAddress() != null) {
        publicIp = publicIpAddress.ipAddress();
    }

    return publicIp;
}
 
Example #2
Source File: ApplicationGatewayBackendServerHealthImpl.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
@Override
public NicIPConfiguration getNetworkInterfaceIPConfiguration() {
    if (this.inner().ipConfiguration() == null) {
        return null;
    }
    String nicIPConfigId = this.inner().ipConfiguration().id();
    if (nicIPConfigId == null) {
        return null;
    }

    String nicIPConfigName = ResourceUtils.nameFromResourceId(nicIPConfigId);
    String nicId = ResourceUtils.parentResourceIdFromResourceId(nicIPConfigId);
    NetworkInterface nic = this.parent().parent().parent().manager().networkInterfaces().getById(nicId);
    if (nic == null) {
        return null;
    } else {
        return nic.ipConfigurations().get(nicIPConfigName);
    }
}
 
Example #3
Source File: LoadBalancerBackendImpl.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
@Override
public Set<String> getVirtualMachineIds() {
    Set<String> vmIds = new HashSet<>();
    Map<String, String> nicConfigs = this.backendNicIPConfigurationNames();
    if (nicConfigs != null) {
        for (String nicId : nicConfigs.keySet()) {
            try {
                NetworkInterface nic = this.parent().manager().networkInterfaces().getById(nicId);
                if (nic == null || nic.virtualMachineId() == null) {
                    continue;
                } else {
                    vmIds.add(nic.virtualMachineId());
                }
            } catch (CloudException | IllegalArgumentException e) {
                continue;
            }
        }
    }

    return vmIds;
}
 
Example #4
Source File: VirtualMachineImpl.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
@Override
public VirtualMachineImpl withNewPrimaryPublicIPAddress(String leafDnsLabel) {
    PublicIPAddress.DefinitionStages.WithGroup definitionWithGroup = this.networkManager.publicIPAddresses()
            .define(this.namer.randomName("pip", 15))
            .withRegion(this.regionName());
    PublicIPAddress.DefinitionStages.WithCreate definitionAfterGroup;
    if (this.creatableGroup != null) {
        definitionAfterGroup = definitionWithGroup.withNewResourceGroup(this.creatableGroup);
    } else {
        definitionAfterGroup = definitionWithGroup.withExistingResourceGroup(this.resourceGroupName());
    }
    this.implicitPipCreatable = definitionAfterGroup.withLeafDomainLabel(leafDnsLabel);
    // Create NIC with creatable PIP
    //
    Creatable<NetworkInterface> nicCreatable = this.nicDefinitionWithCreate
            .withNewPrimaryPublicIPAddress(this.implicitPipCreatable);
    this.creatablePrimaryNetworkInterfaceKey = this.addDependency(nicCreatable);
    return this;
}
 
Example #5
Source File: NetworkSecurityGroupsImpl.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
@Override
public Completable deleteByResourceGroupAsync(String groupName, String name) {
    // Clear NIC references if any
    NetworkSecurityGroupImpl nsg = (NetworkSecurityGroupImpl) getByResourceGroup(groupName, name);
    if (nsg != null) {
        Set<String> nicIds = nsg.networkInterfaceIds();
        if (nicIds != null) {
            for (String nicRef : nsg.networkInterfaceIds()) {
                NetworkInterface nic = this.manager().networkInterfaces().getById(nicRef);
                if (nic == null) {
                    continue;
                } else if (!nsg.id().equalsIgnoreCase(nic.networkSecurityGroupId())) {
                    continue;
                } else {
                    nic.update().withoutNetworkSecurityGroup().apply();
                }
            }
        }
    }

    return this.deleteInnerAsync(groupName, name);
}
 
Example #6
Source File: VirtualMachineImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
private NetworkInterface.DefinitionStages.WithPrimaryPublicIPAddress prepareNetworkInterface(String name) {
    NetworkInterface.DefinitionStages.WithGroup definitionWithGroup = this.networkManager
            .networkInterfaces()
            .define(name)
            .withRegion(this.regionName());
    NetworkInterface.DefinitionStages.WithPrimaryNetwork definitionWithNetwork;
    if (this.creatableGroup != null) {
        definitionWithNetwork = definitionWithGroup.withNewResourceGroup(this.creatableGroup);
    } else {
        definitionWithNetwork = definitionWithGroup.withExistingResourceGroup(this.resourceGroupName());
    }
    return definitionWithNetwork
            .withNewPrimaryNetwork("vnet" + name)
            .withPrimaryPrivateIPAddressDynamic();
}
 
Example #7
Source File: NetworkInterfaceInventoryCollector.java    From pacbot with Apache License 2.0 5 votes vote down vote up
public List<NetworkInterfaceVH> fetchNetworkInterfaceDetails(SubscriptionVH subscription,
		Map<String, Map<String, String>> tagMap) {
	List<NetworkInterfaceVH> networkInterfaceList = new ArrayList<NetworkInterfaceVH>();

	Azure azure = azureCredentialProvider.getClient(subscription.getTenant(),subscription.getSubscriptionId());
	PagedList<NetworkInterface> networkInterfaces = azure.networkInterfaces().list();

	for (NetworkInterface networkInterface : networkInterfaces) {
		NetworkInterfaceVH networkInterfaceVH = new NetworkInterfaceVH();
		networkInterfaceVH.setAppliedDnsServers(networkInterface.appliedDnsServers());
		networkInterfaceVH.setDnsServers(networkInterface.dnsServers());
		networkInterfaceVH.setId(networkInterface.id());
		networkInterfaceVH.setInternalDnsNameLabel(networkInterface.internalDnsNameLabel());
		networkInterfaceVH.setInternalDomainNameSuffix(networkInterface.internalDomainNameSuffix());
		networkInterfaceVH.setInternalFqdn(networkInterface.internalFqdn());
		networkInterfaceVH.setAcceleratedNetworkingEnabled(networkInterface.isAcceleratedNetworkingEnabled());
		networkInterfaceVH.setKey(networkInterface.key());
		networkInterfaceVH.setMacAddress(networkInterface.macAddress());
		networkInterfaceVH.setName(networkInterface.name());
		networkInterfaceVH.setNetworkSecurityGroupId(networkInterface.networkSecurityGroupId());
		networkInterfaceVH.setPrimaryPrivateIP(networkInterface.primaryPrivateIP());
		networkInterfaceVH
				.setTags(Util.tagsList(tagMap, networkInterface.resourceGroupName(), networkInterface.tags()));
		networkInterfaceVH.setVirtualMachineId(networkInterface.virtualMachineId());
		networkInterfaceVH.setSubscription(subscription.getSubscriptionId());
		networkInterfaceVH.setSubscriptionName(subscription.getSubscriptionName());
		networkInterfaceVH.setIPForwardingEnabled(networkInterface.isIPForwardingEnabled());
		setipConfigurations(networkInterface.ipConfigurations(), networkInterfaceVH);
		networkInterfaceList.add(networkInterfaceVH);

	}
	log.info("Target Type : {}  Total: {} ","Networkinterface",networkInterfaceList.size());
	return networkInterfaceList;
}
 
Example #8
Source File: VirtualMachineImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
private NetworkInterface.DefinitionStages.WithPrimaryNetwork preparePrimaryNetworkInterface(String name) {
    NetworkInterface.DefinitionStages.WithGroup definitionWithGroup = this.networkManager.networkInterfaces()
            .define(name)
            .withRegion(this.regionName());
    NetworkInterface.DefinitionStages.WithPrimaryNetwork definitionAfterGroup;
    if (this.creatableGroup != null) {
        definitionAfterGroup = definitionWithGroup.withNewResourceGroup(this.creatableGroup);
    } else {
        definitionAfterGroup = definitionWithGroup.withExistingResourceGroup(this.resourceGroupName());
    }
    return definitionAfterGroup;
}
 
Example #9
Source File: TestPublicIPAddress.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
public static void printPIP(PublicIPAddress resource) {
    StringBuilder info = new StringBuilder().append("Public IP Address: ").append(resource.id())
            .append("\n\tName: ").append(resource.name())
            .append("\n\tResource group: ").append(resource.resourceGroupName())
            .append("\n\tRegion: ").append(resource.region())
            .append("\n\tTags: ").append(resource.tags())
            .append("\n\tIP Address: ").append(resource.ipAddress())
            .append("\n\tLeaf domain label: ").append(resource.leafDomainLabel())
            .append("\n\tFQDN: ").append(resource.fqdn())
            .append("\n\tReverse FQDN: ").append(resource.reverseFqdn())
            .append("\n\tIdle timeout (minutes): ").append(resource.idleTimeoutInMinutes())
            .append("\n\tIP allocation method: ").append(resource.ipAllocationMethod().toString())
            .append("\n\tIP version: ").append(resource.version().toString());

    // Show the associated load balancer if any
    info.append("\n\tLoad balancer association: ");
    if (resource.hasAssignedLoadBalancer()) {
        final LoadBalancerPublicFrontend frontend = resource.getAssignedLoadBalancerFrontend();
        final LoadBalancer lb = frontend.parent();
        info.append("\n\t\tLoad balancer ID: ").append(lb.id())
            .append("\n\t\tFrontend name: ").append(frontend.name());
    } else {
        info.append("(None)");
    }

    // Show the associated NIC if any
    info.append("\n\tNetwork interface association: ");
    if (resource.hasAssignedNetworkInterface()) {
        final NicIPConfiguration nicIp = resource.getAssignedNetworkInterfaceIPConfiguration();
        final NetworkInterface nic = nicIp.parent();
        info.append("\n\t\tNetwork interface ID: ").append(nic.id())
            .append("\n\t\tIP config name: ").append(nicIp.name());
    } else {
        info.append("(None)");
    }

    System.out.println(info.toString());
}
 
Example #10
Source File: TestNetworkInterface.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public NetworkInterface updateResource(NetworkInterface resource) throws Exception {
    resource =  resource.update()
            .withoutIPForwarding()
            .withoutAcceleratedNetworking()
            .withSubnet("subnet2")
            .updateIPConfiguration("primary")  // Updating the primary IP configuration
                .withPrivateIPAddressDynamic() // Equivalent to ..update().withPrimaryPrivateIPAddressDynamic()
                .withoutPublicIPAddress()      // Equivalent to ..update().withoutPrimaryPublicIPAddress()
                .parent()
            .withTag("tag1", "value1")
            .withTag("tag2", "value2")
            .apply();

    // Verifications
    Assert.assertFalse(resource.isAcceleratedNetworkingEnabled());
    Assert.assertFalse(resource.isIPForwardingEnabled());
    NicIPConfiguration primaryIpConfig = resource.primaryIPConfiguration();
    Assert.assertNotNull(primaryIpConfig);
    Assert.assertTrue(primaryIpConfig.isPrimary());
    Assert.assertTrue("subnet2".equalsIgnoreCase(primaryIpConfig.subnetName()));
    Assert.assertNull(primaryIpConfig.publicIPAddressId());
    Assert.assertTrue(resource.tags().containsKey("tag1"));

    Assert.assertEquals(1,  resource.ipConfigurations().size());

    resource.updateTags()
            .withoutTag("tag1")
            .withTag("tag3", "value3")
            .applyTags();
    Assert.assertFalse(resource.tags().containsKey("tag1"));
    Assert.assertEquals("value3", resource.tags().get("tag3"));
    return resource;
}
 
Example #11
Source File: Utils.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
/**
 * Print network interface.
 *
 * @param resource a network interface
 */
public static void print(NetworkInterface resource) {
    StringBuilder info = new StringBuilder();
    info.append("NetworkInterface: ").append(resource.id())
            .append("Name: ").append(resource.name())
            .append("\n\tResource group: ").append(resource.resourceGroupName())
            .append("\n\tRegion: ").append(resource.region())
            .append("\n\tTags: ").append(resource.tags())
            .append("\n\tInternal DNS name label: ").append(resource.internalDnsNameLabel())
            .append("\n\tInternal FQDN: ").append(resource.internalFqdn())
            .append("\n\tInternal domain name suffix: ").append(resource.internalDomainNameSuffix())
            .append("\n\tNetwork security group: ").append(resource.networkSecurityGroupId())
            .append("\n\tApplied DNS servers: ").append(resource.appliedDnsServers().toString())
            .append("\n\tDNS server IPs: ");

    // Output dns servers
    for (String dnsServerIp : resource.dnsServers()) {
        info.append("\n\t\t").append(dnsServerIp);
    }

    info.append("\n\tIP forwarding enabled? ").append(resource.isIPForwardingEnabled())
            .append("\n\tAccelerated networking enabled? ").append(resource.isAcceleratedNetworkingEnabled())
            .append("\n\tMAC Address:").append(resource.macAddress())
            .append("\n\tPrivate IP:").append(resource.primaryPrivateIP())
            .append("\n\tPrivate allocation method:").append(resource.primaryPrivateIPAllocationMethod())
            .append("\n\tPrimary virtual network ID: ").append(resource.primaryIPConfiguration().networkId())
            .append("\n\tPrimary subnet name:").append(resource.primaryIPConfiguration().subnetName());

    System.out.println(info.toString());
}
 
Example #12
Source File: PublicIPAddressImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public NicIPConfiguration getAssignedNetworkInterfaceIPConfiguration() {
    if (this.hasAssignedNetworkInterface()) {
        final String refId = this.inner().ipConfiguration().id();
        final String parentId = ResourceUtils.parentResourceIdFromResourceId(refId);
        final NetworkInterface nic = this.myManager.networkInterfaces().getById(parentId);
        final String childName = ResourceUtils.nameFromResourceId(refId);
        return nic.ipConfigurations().get(childName);
    } else {
        return null;
    }
}
 
Example #13
Source File: SubnetImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public Collection<NicIPConfiguration> listNetworkInterfaceIPConfigurations() {
    Collection<NicIPConfiguration> ipConfigs = new ArrayList<>();
    Map<String, NetworkInterface> nics = new TreeMap<>();
    List<IPConfiguration> ipConfigRefs = this.inner().ipConfigurations();
    if (ipConfigRefs == null) {
        return ipConfigs;
    }

    for (IPConfiguration ipConfigRef : ipConfigRefs) {
        String nicID = ResourceUtils.parentResourceIdFromResourceId(ipConfigRef.id());
        String ipConfigName = ResourceUtils.nameFromResourceId(ipConfigRef.id());
        // Check if NIC already cached
        NetworkInterface nic = nics.get(nicID.toLowerCase());
        if (nic == null) {
            //  NIC not previously found, so ask Azure for it
            nic = this.parent().manager().networkInterfaces().getById(nicID);
        }

        if (nic == null) {
            // NIC doesn't exist so ignore this bad reference
            continue;
        }

        // Cache the NIC
        nics.put(nic.id().toLowerCase(), nic);

        // Get the IP config
        NicIPConfiguration ipConfig = nic.ipConfigurations().get(ipConfigName);
        if (ipConfig == null) {
            // IP config not found, so ignore this bad reference
            continue;
        }

        ipConfigs.add(ipConfig);
    }

    return Collections.unmodifiableCollection(ipConfigs);
}
 
Example #14
Source File: LoadBalancerImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
protected void afterCreating() {
    if (this.nicsInBackends != null) {
        List<Exception> nicExceptions = new ArrayList<>();

        // Update the NICs to point to the backend pool
        for (Entry<String, String> nicInBackend : this.nicsInBackends.entrySet()) {
            String nicId = nicInBackend.getKey();
            String backendName = nicInBackend.getValue();
            try {
                NetworkInterface nic = this.manager().networkInterfaces().getById(nicId);
                NicIPConfiguration nicIP = nic.primaryIPConfiguration();
                nic.update()
                    .updateIPConfiguration(nicIP.name())
                        .withExistingLoadBalancerBackend(this, backendName)
                        .parent()
                    .apply();
            } catch (Exception e) {
                nicExceptions.add(e);
            }
        }

        if (!nicExceptions.isEmpty()) {
            throw new CompositeException(nicExceptions);
        }

        this.nicsInBackends.clear();
        this.refresh();
    }
}
 
Example #15
Source File: NetworkInterfaceImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public Observable<NetworkInterface> refreshAsync() {
    return super.refreshAsync().map(new Func1<NetworkInterface, NetworkInterface>() {
        @Override
        public NetworkInterface call(NetworkInterface networkInterface) {
            NetworkInterfaceImpl impl = (NetworkInterfaceImpl) networkInterface;
            impl.clearCachedRelatedResources();
            impl.initializeChildrenFromInner();
            return impl;
        }
    });
}
 
Example #16
Source File: AzureClient.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
public List<NetworkInterface> getNetworkInterfaceListByNames(String resourceGroup, Collection<String> attachedNetworkInterfaces) {
    PagedList<NetworkInterface> networkInterfaces = getNetworkInterfaces(resourceGroup);
    networkInterfaces.loadAll();
    return networkInterfaces.stream()
            .filter(networkInterface -> attachedNetworkInterfaces
                    .contains(networkInterface.name()))
            .collect(Collectors.toList());
}
 
Example #17
Source File: NetworkInterfaceDetachChecker.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Override
protected Boolean doCall() {
    LOGGER.info("Waiting for network interfaces to be detached: {}", attachedNetworkInterfaces);

    AzureClient azureClient = context.getAzureClient();
    String resourceGroupName = context.getResourceGroupName();
    List<NetworkInterface> filteredNetworkInterfaces = azureClient.getNetworkInterfaceListByNames(resourceGroupName, attachedNetworkInterfaces);

    attachedNetworkInterfaces = filteredNetworkInterfaces
            .stream()
            .filter(ni -> ni.virtualMachineId() != null)
            .map(NetworkInterface::name)
            .collect(Collectors.toSet());
    return attachedNetworkInterfaces.isEmpty();
}
 
Example #18
Source File: AzureMetadataCollectorTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private VirtualMachine createVirtualMachine(String name) {
    VirtualMachine virtualMachine = mock(VirtualMachine.class);
    NetworkInterface networkInterface = mock(NetworkInterface.class);
    NicIPConfiguration nicIPConfiguration = mock(NicIPConfiguration.class);
    when(virtualMachine.name()).thenReturn(name);
    when(virtualMachine.getPrimaryNetworkInterface()).thenReturn(networkInterface);
    when(networkInterface.primaryIPConfiguration()).thenReturn(nicIPConfiguration);
    when(networkInterface.primaryPrivateIP()).thenReturn(PRIVATE_IP);
    when(nicIPConfiguration.subnetName()).thenReturn(SUBNET_NAME);
    return virtualMachine;
}
 
Example #19
Source File: VirtualMachineImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public VirtualMachineImpl withNewPrimaryPublicIPAddress(Creatable<PublicIPAddress> creatable) {
    Creatable<NetworkInterface> nicCreatable = this.nicDefinitionWithCreate
            .withNewPrimaryPublicIPAddress(creatable);
    this.creatablePrimaryNetworkInterfaceKey = this.addDependency(nicCreatable);
    return this;
}
 
Example #20
Source File: VirtualMachineImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public VirtualMachineImpl withExistingPrimaryPublicIPAddress(PublicIPAddress publicIPAddress) {
    Creatable<NetworkInterface> nicCreatable = this.nicDefinitionWithCreate
            .withExistingPrimaryPublicIPAddress(publicIPAddress);
    this.creatablePrimaryNetworkInterfaceKey = this.addDependency(nicCreatable);
    return this;
}
 
Example #21
Source File: VirtualMachineImpl.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
@Override
public VirtualMachineImpl withoutPrimaryPublicIPAddress() {
    Creatable<NetworkInterface> nicCreatable = this.nicDefinitionWithCreate;
    this.creatablePrimaryNetworkInterfaceKey = this.addDependency(nicCreatable);
    return this;
}
 
Example #22
Source File: VMInventoryCollector.java    From pacbot with Apache License 2.0 4 votes vote down vote up
public List<VirtualMachineVH> fetchVMDetails(SubscriptionVH subscription, Map<String, Map<String, String>> tagMap) {
	List<VirtualMachineVH> vmList = new ArrayList<>();

	Azure azure = azureCredentialProvider.getClient(subscription.getTenant(),subscription.getSubscriptionId());
	
	List<NetworkInterface> networkInterfaces = azure.networkInterfaces().list();

	PagedList<VirtualMachine> vms = azure.virtualMachines().list();
	for (VirtualMachine virtualMachine : vms) {
		try {
			VirtualMachineVH vmVH = new VirtualMachineVH();

			vmVH.setComputerName(virtualMachine.computerName() == null
					? virtualMachine.instanceView().computerName() == null ? virtualMachine.name()
							: virtualMachine.instanceView().computerName()
					: virtualMachine.computerName());
			vmVH.setName(virtualMachine.name());
			vmVH.setRegion(virtualMachine.regionName());
			vmVH.setSubscription(subscription.getSubscriptionId());
			vmVH.setSubscriptionName(subscription.getSubscriptionName());

			virtualMachine.inner().networkProfile();
			vmVH.setVmSize(virtualMachine.size().toString());
			vmVH.setResourceGroupName(virtualMachine.resourceGroupName());

			vmVH.setStatus(virtualMachine.powerState() != null
					? virtualMachine.powerState().toString().replace("PowerState/", "")
					: "Unknown");
			
			if(virtualMachine.instanceView()!=null) {
				vmVH.setOs(virtualMachine.instanceView().osName());
				vmVH.setOsVersion(virtualMachine.instanceView().osVersion());
			}
			vmVH.setOsType(virtualMachine.osType()!=null?virtualMachine.osType().toString():"");

			vmVH.setNetworkInterfaceIds(virtualMachine.networkInterfaceIds());
			vmVH.setAvailabilityZones(virtualMachine.availabilityZones());

			vmVH.setVmId(virtualMachine.vmId());
			vmVH.setManagedDiskEnabled(virtualMachine.isManagedDiskEnabled());

			vmVH.setPrivateIpAddress(virtualMachine.getPrimaryNetworkInterface().primaryPrivateIP());
			vmVH.setPublicIpAddress(virtualMachine.getPrimaryPublicIPAddress() != null
					? virtualMachine.getPrimaryPublicIPAddress().ipAddress()
					: "");

			vmVH.setAvailabilitySetId(virtualMachine.availabilitySetId());
			vmVH.setProvisioningState(virtualMachine.provisioningState());
			vmVH.setLicenseType(virtualMachine.licenseType());
			vmVH.setId(virtualMachine.id());

			vmVH.setBootDiagnosticsEnabled(virtualMachine.isBootDiagnosticsEnabled());
			vmVH.setBootDiagnosticsStorageUri(virtualMachine.bootDiagnosticsStorageUri());
			vmVH.setManagedServiceIdentityEnabled(virtualMachine.isManagedServiceIdentityEnabled());
			vmVH.setSystemAssignedManagedServiceIdentityTenantId(
					virtualMachine.systemAssignedManagedServiceIdentityTenantId());
			vmVH.setSystemAssignedManagedServiceIdentityPrincipalId(
					virtualMachine.systemAssignedManagedServiceIdentityPrincipalId());
			vmVH.setUserAssignedManagedServiceIdentityIds(virtualMachine.userAssignedManagedServiceIdentityIds());
			vmVH.setTags(Util.tagsList(tagMap, virtualMachine.resourceGroupName(), virtualMachine.tags()));
			vmVH.setPrimaryNetworkIntefaceId(virtualMachine.primaryNetworkInterfaceId());
			vmVH.setPrimaryNCIMacAddress(virtualMachine.getPrimaryNetworkInterface().macAddress());
		
			setVmDisks(virtualMachine, vmVH);
			setNsgs(virtualMachine, vmVH, networkInterfaces);
			setVnetInfo(virtualMachine, vmVH);
			setOtherVnets(virtualMachine, vmVH, networkInterfaces);
			

			vmList.add(vmVH);
		}catch(Exception e) {
			e.printStackTrace();
			log.error("Error Collecting info for {} {} ",virtualMachine.computerName(),e.getMessage());
		}
	}
	log.info("Target Type : {}  Total: {} ", "virtualmachine", vmList.size());
	return vmList;
}
 
Example #23
Source File: AzureClient.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
public NetworkInterface getNetworkInterfaceById(String networkInterfaceId) {
    return handleAuthException(() -> azure.networkInterfaces().getById(networkInterfaceId));
}
 
Example #24
Source File: AzureClient.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
public PagedList<NetworkInterface> getNetworkInterfaces(String resourceGroup) {
    return handleAuthException(() -> azure.networkInterfaces().listByResourceGroup(resourceGroup));
}
 
Example #25
Source File: AzureClient.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
public NetworkInterface getNetworkInterface(String resourceGroup, String networkInterfaceName) {
    return handleAuthException(() -> azure.networkInterfaces().getByResourceGroup(resourceGroup, networkInterfaceName));
}
 
Example #26
Source File: AzureMetadataCollector.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
@Override
@Retryable(backoff = @Backoff(delay = 1000, multiplier = 2, maxDelay = 10000), maxAttempts = 5)
public List<CloudVmMetaDataStatus> collect(AuthenticatedContext authenticatedContext, List<CloudResource> resources, List<CloudInstance> vms,
        List<CloudInstance> knownInstances) {
    LOGGER.debug("Starting to collect vm metadata.");
    List<CloudVmMetaDataStatus> results = new ArrayList<>();
    String resourceGroup = azureUtils.getTemplateResource(resources).getName();
    AzureClient azureClient = authenticatedContext.getParameter(AzureClient.class);

    Map<String, InstanceTemplate> templateMap = getTemplateMap(vms, authenticatedContext);
    Map<String, VirtualMachine> virtualMachinesByName = azureVirtualMachineService.getVirtualMachinesByName(azureClient, resourceGroup,
            templateMap.keySet());
    azureVirtualMachineService.refreshInstanceViews(virtualMachinesByName);
    try {
        for (Entry<String, InstanceTemplate> instance : templateMap.entrySet()) {
            VirtualMachine vm = virtualMachinesByName.get(instance.getKey());
            //TODO: network interface is lazy, so we will fetch it for every instances
            if (vm != null) {
                NetworkInterface networkInterface = vm.getPrimaryNetworkInterface();
                String subnetId = networkInterface.primaryIPConfiguration().subnetName();

                Integer faultDomainCount = azureClient.getFaultDomainNumber(resourceGroup, vm.name());

                String publicIp = azureVmPublicIpProvider.getPublicIp(azureClient, azureUtils, networkInterface, resourceGroup);

                String instanceId = instance.getKey();
                String localityIndicator = Optional.ofNullable(faultDomainCount)
                        .map(domainCount -> getLocalityIndicator(domainCount, authenticatedContext.getCloudContext(), instance.getValue(), resourceGroup))
                        .orElse(null);
                CloudInstanceMetaData md = new CloudInstanceMetaData(networkInterface.primaryPrivateIP(), publicIp, localityIndicator);

                InstanceTemplate template = templateMap.get(instanceId);
                if (template != null) {
                    Map<String, Object> params = new HashMap<>(1);
                    params.put(CloudInstance.SUBNET_ID, subnetId);
                    params.put(CloudInstance.INSTANCE_NAME, vm.computerName());
                    CloudInstance cloudInstance = new CloudInstance(instanceId, template, null, params);
                    CloudVmInstanceStatus status = new CloudVmInstanceStatus(cloudInstance, InstanceStatus.CREATED);
                    results.add(new CloudVmMetaDataStatus(status, md));
                }
            }
        }
    } catch (RuntimeException e) {
        LOGGER.debug("Failed to collect vm metadata due to an exception: ", e);
        throw new CloudConnectorException(e.getMessage(), e);
    }
    LOGGER.debug("Metadata collection finished");
    return results;
}
 
Example #27
Source File: VirtualMachineImpl.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
@Override
public NetworkInterface getPrimaryNetworkInterface() {
    return this.networkManager.networkInterfaces().getById(primaryNetworkInterfaceId());
}
 
Example #28
Source File: VirtualMachineImpl.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
@Override
public VirtualMachineImpl withNewPrimaryNetworkInterface(Creatable<NetworkInterface> creatable) {
    this.creatablePrimaryNetworkInterfaceKey = this.addDependency(creatable);
    return this;
}
 
Example #29
Source File: VirtualMachineImpl.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
public VirtualMachineImpl withNewPrimaryNetworkInterface(String name, String publicDnsNameLabel) {
    Creatable<NetworkInterface> definitionCreatable = prepareNetworkInterface(name)
            .withNewPrimaryPublicIPAddress(publicDnsNameLabel);
    return withNewPrimaryNetworkInterface(definitionCreatable);
}
 
Example #30
Source File: VirtualMachineImpl.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
@Override
public VirtualMachineImpl withExistingSecondaryNetworkInterface(NetworkInterface networkInterface) {
    this.existingSecondaryNetworkInterfacesToAssociate.add(networkInterface);
    return this;
}