Search in sources :

Example 1 with NetworkInterface

use of io.micronaut.discovery.cloud.NetworkInterface in project micronaut-core by micronaut-projects.

the class DigitalOceanMetadataResolver method resolve.

@Override
public Optional<ComputeInstanceMetadata> resolve(Environment environment) {
    if (!configuration.isEnabled()) {
        return Optional.empty();
    }
    if (cachedMetadata != null) {
        cachedMetadata.setCached(true);
        return Optional.of(cachedMetadata);
    }
    DigitalOceanInstanceMetadata instanceMetadata = new DigitalOceanInstanceMetadata();
    try {
        String metadataUrl = configuration.getUrl();
        JsonNode metadataJson = readMetadataUrl(new URL(metadataUrl), CONNECTION_TIMEOUT_IN_MILLS, READ_TIMEOUT_IN_MILLS, JsonNodeTreeCodec.getInstance().withConfig(jsonStreamConfig), jsonFactory, new HashMap<>());
        if (metadataJson != null) {
            instanceMetadata.setInstanceId(textValue(metadataJson, DROPLET_ID));
            instanceMetadata.setName(textValue(metadataJson, HOSTNAME));
            instanceMetadata.setVendorData(textValue(metadataJson, VENDOR_DATA));
            instanceMetadata.setUserData(textValue(metadataJson, USER_DATA));
            instanceMetadata.setRegion(textValue(metadataJson, REGION));
            JsonNode networkInterfaces = metadataJson.get(INTERFACES.getName());
            List<NetworkInterface> privateInterfaces = processJsonInterfaces(networkInterfaces.get(PRIVATE_INTERFACES.getName()), instanceMetadata::setPrivateIpV4, instanceMetadata::setPrivateIpV6);
            List<NetworkInterface> publicInterfaces = processJsonInterfaces(networkInterfaces.get(PUBLIC_INTERFACES.getName()), instanceMetadata::setPublicIpV4, instanceMetadata::setPublicIpV6);
            List<NetworkInterface> allInterfaces = new ArrayList<>();
            allInterfaces.addAll(publicInterfaces);
            allInterfaces.addAll(privateInterfaces);
            instanceMetadata.setInterfaces(allInterfaces);
            populateMetadata(instanceMetadata, metadataJson);
            cachedMetadata = instanceMetadata;
            return Optional.of(instanceMetadata);
        }
    } catch (MalformedURLException mue) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Digital Ocean metadataUrl value is invalid!: " + configuration.getUrl(), mue);
        }
    } catch (IOException ioe) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Error connecting to" + configuration.getUrl() + "reading instance metadata", ioe);
        }
    }
    return Optional.empty();
}
Also used : MalformedURLException(java.net.MalformedURLException) ArrayList(java.util.ArrayList) NetworkInterface(io.micronaut.discovery.cloud.NetworkInterface) JsonNode(io.micronaut.json.tree.JsonNode) IOException(java.io.IOException) URL(java.net.URL)

Example 2 with NetworkInterface

use of io.micronaut.discovery.cloud.NetworkInterface in project micronaut-gcp by micronaut-projects.

the class GoogleComputeInstanceMetadataResolver method resolve.

@Override
public Optional<ComputeInstanceMetadata> resolve(Environment environment) {
    if (!configuration.isEnabled()) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Resolving of Google Compute Instance metadata is disabled");
        }
        return Optional.empty();
    }
    if (cachedMetadata != null) {
        cachedMetadata.setCached(true);
        return Optional.of(cachedMetadata);
    }
    GoogleComputeInstanceMetadata instanceMetadata = null;
    try {
        int connectionTimeoutMs = (int) configuration.getConnectTimeout().toMillis();
        int readTimeoutMs = (int) configuration.getReadTimeout().toMillis();
        Map<String, String> requestProperties = new HashMap<>();
        requestProperties.put(HEADER_METADATA_FLAVOR, "Google");
        JsonNode projectResultJson = null;
        try {
            projectResultJson = readMetadataUrl(new URL(configuration.getProjectMetadataUrl() + "?recursive=true"), connectionTimeoutMs, readTimeoutMs, objectMapper, requestProperties);
        } catch (MalformedURLException me) {
            if (LOG.isErrorEnabled()) {
                LOG.error("Google compute project metadataUrl value is invalid!: " + configuration.getProjectMetadataUrl(), me);
            }
        } catch (FileNotFoundException fnfe) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("No project metadata found at: " + configuration.getProjectMetadataUrl() + "?recursive=true", fnfe);
            }
        } catch (IOException ioe) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Error connecting to" + configuration.getProjectMetadataUrl() + "?recursive=true reading project metadata. Not a Google environment?", ioe);
            }
        }
        JsonNode instanceMetadataJson = readMetadataUrl(new URL(configuration.getMetadataUrl() + "?recursive=true"), connectionTimeoutMs, readTimeoutMs, objectMapper, requestProperties);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Read compute instance metadata from URL [{}]. Resulting JSON: {}", configuration.getMetadataUrl(), instanceMetadataJson);
        }
        if (environment.getActiveNames().contains(Environment.GAE)) {
            instanceMetadata = new GoogleComputeInstanceMetadata();
            instanceMetadata.setInstanceId(System.getenv("GAE_INSTANCE"));
            instanceMetadata.setAccount(System.getenv("GOOGLE_CLOUD_PROJECT"));
        }
        if (instanceMetadataJson != null) {
            if (instanceMetadata == null) {
                instanceMetadata = new GoogleComputeInstanceMetadata();
            }
            stringValue(instanceMetadataJson, GoogleComputeMetadataKeys.ID.getName()).ifPresent(instanceMetadata::setInstanceId);
            if (projectResultJson != null) {
                stringValue(projectResultJson, GoogleComputeMetadataKeys.PROJECT_ID.getName()).ifPresent(instanceMetadata::setAccount);
            } else {
                stringValue(instanceMetadataJson, GoogleComputeMetadataKeys.PROJECT_ID.getName()).ifPresent(instanceMetadata::setAccount);
            }
            stringValue(instanceMetadataJson, GoogleComputeMetadataKeys.ZONE.getName()).ifPresent(instanceMetadata::setAvailabilityZone);
            stringValue(instanceMetadataJson, GoogleComputeMetadataKeys.MACHINE_TYPE.getName()).ifPresent(instanceMetadata::setMachineType);
            stringValue(instanceMetadataJson, GoogleComputeMetadataKeys.DESCRIPTION.getName()).ifPresent(instanceMetadata::setDescription);
            stringValue(instanceMetadataJson, GoogleComputeMetadataKeys.IMAGE.getName()).ifPresent(instanceMetadata::setImageId);
            stringValue(instanceMetadataJson, GoogleComputeMetadataKeys.HOSTNAME.getName()).ifPresent(instanceMetadata::setLocalHostname);
            stringValue(instanceMetadataJson, GoogleComputeMetadataKeys.NAME.getName()).ifPresent(instanceMetadata::setName);
            JsonNode networkInterfaces = instanceMetadataJson.findValue(GoogleComputeMetadataKeys.NETWORK_INTERFACES.getName());
            if (networkInterfaces != null) {
                List<NetworkInterface> interfaces = new ArrayList<>();
                AtomicInteger networkCounter = new AtomicInteger(0);
                GoogleComputeInstanceMetadata finalInstanceMetadata = instanceMetadata;
                networkInterfaces.elements().forEachRemaining(jsonNode -> {
                    GoogleComputeNetworkInterface networkInterface = new GoogleComputeNetworkInterface();
                    networkInterface.setId(String.valueOf(networkCounter.getAndIncrement()));
                    if (jsonNode.findValue(GoogleComputeMetadataKeys.ACCESS_CONFIGS.getName()) != null) {
                        JsonNode accessConfigs = jsonNode.findValue(GoogleComputeMetadataKeys.ACCESS_CONFIGS.getName());
                        // we just grab the first one
                        finalInstanceMetadata.setPublicIpV4(accessConfigs.get(0).findValue("externalIp").textValue());
                    }
                    stringValue(jsonNode, GoogleComputeMetadataKeys.IP.getName()).ifPresent(finalInstanceMetadata::setPrivateIpV4);
                    stringValue(jsonNode, GoogleComputeMetadataKeys.IP.getName()).ifPresent(networkInterface::setIpv4);
                    stringValue(jsonNode, GoogleComputeMetadataKeys.MAC.getName()).ifPresent(networkInterface::setMac);
                    stringValue(jsonNode, GoogleComputeMetadataKeys.NETWORK.getName()).ifPresent(networkInterface::setNetwork);
                    stringValue(jsonNode, GoogleComputeMetadataKeys.NETMASK.getName()).ifPresent(networkInterface::setNetmask);
                    stringValue(jsonNode, GoogleComputeMetadataKeys.GATEWAY.getName()).ifPresent(networkInterface::setGateway);
                    interfaces.add(networkInterface);
                });
                instanceMetadata.setInterfaces(interfaces);
            }
            final Map<?, ?> metadata = objectMapper.convertValue(instanceMetadata, Map.class);
            populateMetadata(instanceMetadata, metadata);
            cachedMetadata = instanceMetadata;
            return Optional.of(instanceMetadata);
        }
    } catch (MalformedURLException me) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Google compute metadataUrl value is invalid!: " + configuration.getMetadataUrl(), me);
        }
    } catch (FileNotFoundException fnfe) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("No metadata found at: " + configuration.getMetadataUrl() + "?recursive=true", fnfe);
        }
    } catch (IOException ioe) {
        if (LOG.isErrorEnabled()) {
            LOG.debug("Error connecting to" + configuration.getMetadataUrl() + "?recursive=true reading instance metadata", ioe);
        }
    }
    return Optional.ofNullable(instanceMetadata);
}
Also used : MalformedURLException(java.net.MalformedURLException) FileNotFoundException(java.io.FileNotFoundException) NetworkInterface(io.micronaut.discovery.cloud.NetworkInterface) JsonNode(com.fasterxml.jackson.databind.JsonNode) IOException(java.io.IOException) URL(java.net.URL) AtomicInteger(java.util.concurrent.atomic.AtomicInteger)

Example 3 with NetworkInterface

use of io.micronaut.discovery.cloud.NetworkInterface in project micronaut-core by micronaut-projects.

the class DigitalOceanMetadataResolver method processJsonInterfaces.

private List<NetworkInterface> processJsonInterfaces(JsonNode interfaces, Consumer<String> ipv4Setter, Consumer<String> ipv6Setter) {
    List<NetworkInterface> networkInterfaces = new ArrayList<>();
    if (interfaces != null) {
        AtomicReference<Integer> networkCounter = new AtomicReference<>(0);
        interfaces.values().forEach(jsonNode -> {
            DigitalOceanNetworkInterface networkInterface = new DigitalOceanNetworkInterface();
            networkInterface.setId(networkCounter.toString());
            JsonNode ipv4 = jsonNode.get(IPV4.getName());
            if (ipv4 != null) {
                networkInterface.setIpv4(textValue(ipv4, IP_ADDRESS));
                networkInterface.setNetmask(textValue(ipv4, NETMASK));
                networkInterface.setGateway(textValue(ipv4, GATEWAY));
            }
            JsonNode ipv6 = jsonNode.get(IPV6.getName());
            if (ipv6 != null) {
                networkInterface.setIpv6(textValue(ipv6, IP_ADDRESS));
                networkInterface.setIpv6Gateway(textValue(ipv6, GATEWAY));
                networkInterface.setCidr(ipv6.get(CIDR.getName()).getIntValue());
            }
            networkInterface.setMac(textValue(jsonNode, MAC));
            networkCounter.getAndSet(networkCounter.get() + 1);
            networkInterfaces.add(networkInterface);
        });
        JsonNode firstIpv4 = interfaces.get(0).get(IPV4.getName());
        ipv4Setter.accept(textValue(firstIpv4, IP_ADDRESS));
        JsonNode firstIpv6 = interfaces.get(0).get(IPV6.getName());
        if (firstIpv6 != null) {
            ipv6Setter.accept(textValue(firstIpv6, IP_ADDRESS));
        }
    }
    return networkInterfaces;
}
Also used : ArrayList(java.util.ArrayList) NetworkInterface(io.micronaut.discovery.cloud.NetworkInterface) AtomicReference(java.util.concurrent.atomic.AtomicReference) JsonNode(io.micronaut.json.tree.JsonNode)

Aggregations

NetworkInterface (io.micronaut.discovery.cloud.NetworkInterface)3 JsonNode (io.micronaut.json.tree.JsonNode)2 IOException (java.io.IOException)2 MalformedURLException (java.net.MalformedURLException)2 URL (java.net.URL)2 ArrayList (java.util.ArrayList)2 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 FileNotFoundException (java.io.FileNotFoundException)1 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)1 AtomicReference (java.util.concurrent.atomic.AtomicReference)1