Esempio n. 1
0
def main():
  # Define three parameters--color, size, count--each time you run the script"
  parser = argparse.ArgumentParser(description="Write a labeled custom metric.")
  parser.add_argument("--color", required=True)
  parser.add_argument("--size", required=True)
  parser.add_argument("--count", required=True)
  args = parser.parse_args()

  # Assign some values that will be used repeatedly.
  project_id = GetProjectId()
  now_rfc3339 = GetNowRfc3339()

  # Create a cloudmonitoring service object. Use OAuth2 credentials.
  credentials = AppAssertionCredentials(
      scope="https://www.googleapis.com/auth/monitoring")
  http = credentials.authorize(httplib2.Http())
  service = build(serviceName="cloudmonitoring", version="v2beta2", http=http)

  try:
    print "Labels: color: %s, size: %s." % (args.color, args.size)
    print "Creating custom metric..."
    CreateCustomMetric(service, project_id)
    time.sleep(2)
    print "Writing new data to custom metric timeseries..."
    WriteCustomMetric(service, project_id, now_rfc3339,
                      args.color, args.size, args.count)
    print "Reading data from custom metric timeseries..."
    ReadCustomMetric(service, project_id, now_rfc3339, args.color, args.size)
  except Exception as e:
    print "Failed to complete operations on custom metric: exception=%s" % e
def main():
  project_id = GetProjectId()

  # Create a cloudmonitoring service to call. Use OAuth2 credentials.
  credentials = AppAssertionCredentials(
      scope="https://www.googleapis.com/auth/monitoring")
  http = credentials.authorize(httplib2.Http())
  service = build(serviceName="cloudmonitoring", version="v2beta2", http=http)

  # Set up the write request.
  now = GetNowRfc3339()
  desc = {"project": project_id,
          "metric": CUSTOM_METRIC_NAME}
  point = {"start": now,
           "end": now,
           "doubleValue": os.getpid()}
  print "Writing %d at %s" % (point["doubleValue"], now)

  # Write a new data point.
  try:
    write_request = service.timeseries().write(
        project=project_id,
        body={"timeseries": [{"timeseriesDesc": desc, "point": point}]})
    _ = write_request.execute()  # Ignore the response.
  except Exception as e:
    print "Failed to write custom metric data: exception=%s" % e
    raise  # propagate exception

  # Read all data points from the time series.
  # When a custom metric is created, it may take a few seconds
  # to propagate throughout the system. Retry a few times.
  print "Reading data from custom metric timeseries..."
  read_request = service.timeseries().list(
      project=project_id,
      metric=CUSTOM_METRIC_NAME,
      youngest=now)
  start = time.time()
  while True:
    try:
      read_response = read_request.execute()
      for point in read_response["timeseries"][0]["points"]:
        print "  %s: %s" % (point["end"], point["doubleValue"])
      break
    except Exception as e:
      if time.time() < start + 20:
        print "Failed to read custom metric data, retrying..."
        time.sleep(3)
      else:
        print "Failed to read custom metric data, aborting: exception=%s" % e
        raise  # propagate exception
Esempio n. 3
0
def main(argv):
  # Parse the command-line flags.
  flags = parser.parse_args(argv[1:])

  # Obtain service account credentials from virtual machine environment.
  credentials = AppAssertionCredentials(['https://www.googleapis.com/auth/datastore'])

  # Create an httplib2.Http object to handle our HTTP requests and authorize
  # it with our good Credentials.
  http = httplib2.Http()
  http = credentials.authorize(http)

  # Construct the service object for the interacting with the Compute Engine
  # API.
  service = discovery.build(API_NAME, API_VERSION, http=http)

  for (title, year, peak) in DATA:
    commit(service.datasets(), title, year, peak)
Esempio n. 4
0
def GetService():
    """Create a cloudmonitoring service to call. Use OAuth2 credentials."""
    credentials = AppAssertionCredentials(
        scope="https://www.googleapis.com/auth/monitoring")
    http = credentials.authorize(httplib2.Http())
    return build(serviceName="cloudmonitoring", version="v2beta2", http=http)
def GetService():
  """Create a cloudmonitoring service to call. Use OAuth2 credentials."""
  credentials = AppAssertionCredentials(
      scope="https://www.googleapis.com/auth/monitoring")
  http = credentials.authorize(httplib2.Http())
  return build(serviceName="cloudmonitoring", version="v2beta2", http=http)
Esempio n. 6
0
def main(argv):
    # Parse the command-line flags.
    flags = parser.parse_args(argv[1:])

    # Obtain service account credentials from virtual machine environement.
    credentials = AppAssertionCredentials(
        ['https://www.googleapis.com/auth/compute'])

    # Create an httplib2.Http object to handle our HTTP requests and authorize
    # it with our good Credentials.
    http = httplib2.Http()
    http = credentials.authorize(http)

    # Construct the service object for the interacting with the Compute Engine
    # API.
    service = discovery.build('compute', 'v1', http=http)

    # Set project, zone, and other constants.
    URL_PREFIX = 'https://www.googleapis.com/compute'
    API_VERSION = 'v1'
    PROJECT_ID = 'your-project-id'
    PROJECT_URL = '%s/%s/projects/%s' % (URL_PREFIX, API_VERSION, PROJECT_ID)
    INSTANCE_NAME = 'test-vm-serv-acct'
    ZONE = 'us-central1-a'
    MACHINE_TYPE = 'n1-standard-1'
    IMAGE_PROJECT_ID = 'debian-cloud'
    IMAGE_PROJECT_URL = '%s/%s/projects/%s' % (URL_PREFIX, API_VERSION,
                                               IMAGE_PROJECT_ID)
    IMAGE_NAME = 'debian-7-wheezy-v20140807'

    BODY = {
        'name':
        INSTANCE_NAME,
        'tags': {
            'items': ['frontend']
        },
        'machineType':
        '%s/zones/%s/machineTypes/%s' % (PROJECT_URL, ZONE, MACHINE_TYPE),
        'disks': [{
            'boot': True,
            'type': 'PERSISTENT',
            'mode': 'READ_WRITE',
            'zone': '%s/zones/%s' % (PROJECT_URL, ZONE),
            'initializeParams': {
                'sourceImage':
                '%s/global/images/%s' % (IMAGE_PROJECT_URL, IMAGE_NAME)
            },
        }],
        'networkInterfaces': [{
            'accessConfigs': [{
                'name': 'External NAT',
                'type': 'ONE_TO_ONE_NAT'
            }],
            'network':
            PROJECT_URL + '/global/networks/default'
        }],
        'scheduling': {
            'automaticRestart': True,
            'onHostMaintenance': 'MIGRATE'
        },
        'serviceAccounts': [{
            'email':
            'default',
            'scopes': [
                'https://www.googleapis.com/auth/compute',
                'https://www.googleapis.com/auth/devstorage.full_control'
            ]
        }],
    }

    # Build and execute instance insert request.
    request = service.instances().insert(project=PROJECT_ID,
                                         zone=ZONE,
                                         body=BODY)
    try:
        response = request.execute()
    except Exception, ex:
        print 'ERROR: ' + str(ex)
        sys.exit()
Esempio n. 7
0
def main(argv):
  # Parse the command-line flags.
  flags = parser.parse_args(argv[1:])

  # Obtain service account credentials from virtual machine environement.
  credentials = AppAssertionCredentials(['https://www.googleapis.com/auth/compute'])

  # Create an httplib2.Http object to handle our HTTP requests and authorize
  # it with our good Credentials.
  http = httplib2.Http()
  http = credentials.authorize(http)

  # Construct the service object for the interacting with the Compute Engine
  # API.
  service = discovery.build('compute', 'v1', http=http)

  # Set project, zone, and other constants.
  URL_PREFIX = 'https://www.googleapis.com/compute'
  API_VERSION = 'v1'
  PROJECT_ID = 'your-project-id'
  PROJECT_URL = '%s/%s/projects/%s' % (URL_PREFIX, API_VERSION, PROJECT_ID)
  INSTANCE_NAME = 'test-vm-serv-acct'
  ZONE = 'us-central1-a'
  MACHINE_TYPE = 'n1-standard-1'
  IMAGE_PROJECT_ID = 'debian-cloud'
  IMAGE_PROJECT_URL = '%s/%s/projects/%s' % (
      URL_PREFIX, API_VERSION, IMAGE_PROJECT_ID)
  IMAGE_NAME = 'debian-7-wheezy-v20140807'

  BODY = {
    'name': INSTANCE_NAME,
    'tags': {
      'items': ['frontend']
    },
    'machineType': '%s/zones/%s/machineTypes/%s' % (
        PROJECT_URL, ZONE, MACHINE_TYPE),
    'disks': [{
      'boot': True,
      'type': 'PERSISTENT',
      'mode': 'READ_WRITE',
      'zone': '%s/zones/%s' % (PROJECT_URL, ZONE),
      'initializeParams': {
        'sourceImage': '%s/global/images/%s' % (IMAGE_PROJECT_URL, IMAGE_NAME)
      },
    }],
    'networkInterfaces': [{
      'accessConfigs': [{
        'name': 'External NAT',
        'type': 'ONE_TO_ONE_NAT'
      }],
      'network': PROJECT_URL + '/global/networks/default'
    }],
    'scheduling': {
      'automaticRestart': True,
      'onHostMaintenance': 'MIGRATE'
    },
    'serviceAccounts': [{
      'email': 'default',
      'scopes': [
        'https://www.googleapis.com/auth/compute',
        'https://www.googleapis.com/auth/devstorage.full_control'
      ]
    }],
  }

  # Build and execute instance insert request.
  request = service.instances().insert(
      project=PROJECT_ID, zone=ZONE, body=BODY)
  try:
    response = request.execute()
  except Exception, ex:
    print 'ERROR: ' + str(ex)
    sys.exit()