All Downloads are FREE. Search and download functionalities are using the official Maven repository.

nl.topicus.jdbc.shaded.com.google.cloud.MetadataConfig Maven / Gradle / Ivy

There is a newer version: 1.1.6
Show newest version
/*
 * Copyright 2017 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in nl.topicus.jdbc.shaded.com.liance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.nl.topicus.jdbc.shaded.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 nl.topicus.jdbc.shaded.com.google.cloud;

import static java.nio.charset.StandardCharsets.UTF_8;

import java.nl.topicus.jdbc.shaded.io.BufferedReader;
import java.nl.topicus.jdbc.shaded.io.IOException;
import java.nl.topicus.jdbc.shaded.io.InputStream;
import java.nl.topicus.jdbc.shaded.io.InputStreamReader;
import java.nl.topicus.jdbc.shaded.net.HttpURLConnection;
import java.nl.topicus.jdbc.shaded.net.URL;

/**
 * Retrieves Google Cloud project-id and a limited set of instance attributes from Metadata server.
 * @see 
 *   https://cloud.google.nl.topicus.jdbc.shaded.com.nl.topicus.jdbc.shaded.com.ute/docs/storing-retrieving-metadata
 */
public class MetadataConfig {

  private static final String METADATA_URL = "http://metadata/nl.topicus.jdbc.shaded.com.uteMetadata/v1/";

  private MetadataConfig() {
  }

  public static String getProjectId() {
    return getAttribute("project/project-id");
  }

  public static String getZone() {
    String zoneId = getAttribute("instance/zone");
    if (zoneId.contains("/")) {
      return zoneId.substring(zoneId.lastIndexOf('/') + 1);
    }
    return zoneId;
  }

  public static String getInstanceId() {
    return getAttribute("instance/id");
  }

  public static String getClusterName() {
    return getAttribute("instance/cluster-name");
  }

  private static String getAttribute(String attributeName) {
    try {
      URL url = new URL(METADATA_URL + attributeName);
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
      connection.setRequestProperty("Metadata-Flavor", "Google");
      InputStream input = connection.getInputStream();
      if (connection.getResponseCode() == 200) {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(input, UTF_8))) {
          return reader.readLine();
        }
      }
    } catch (IOException ignore) {
      // ignore
    }
    return null;
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy