當前位置: 首頁>>代碼示例>>Python>>正文


Python monitoring_v3.MetricServiceClient方法代碼示例

本文整理匯總了Python中google.cloud.monitoring_v3.MetricServiceClient方法的典型用法代碼示例。如果您正苦於以下問題:Python monitoring_v3.MetricServiceClient方法的具體用法?Python monitoring_v3.MetricServiceClient怎麽用?Python monitoring_v3.MetricServiceClient使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在google.cloud.monitoring_v3的用法示例。


在下文中一共展示了monitoring_v3.MetricServiceClient方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: setup_metrics

# 需要導入模塊: from google.cloud import monitoring_v3 [as 別名]
# 或者: from google.cloud.monitoring_v3 import MetricServiceClient [as 別名]
def setup_metrics(non_dry_run):
  """Set up metrics."""
  client = monitoring_v3.MetricServiceClient()
  project_name = utils.get_application_id()
  project_path = client.project_path(project_name)

  for name in dir(monitoring_metrics):
    metric = getattr(monitoring_metrics, name)
    if not isinstance(metric, monitor.Metric):
      continue

    descriptor = monitoring_v3.types.MetricDescriptor()
    metric.monitoring_v3_metric_descriptor(descriptor)

    if non_dry_run:
      print('Creating metric', descriptor)
      client.create_metric_descriptor(project_path, descriptor)
    else:
      print('Skip creating metric', descriptor, '(dry-run mode)') 
開發者ID:google,項目名稱:clusterfuzz,代碼行數:21,代碼來源:setup.py

示例2: initialize

# 需要導入模塊: from google.cloud import monitoring_v3 [as 別名]
# 或者: from google.cloud.monitoring_v3 import MetricServiceClient [as 別名]
def initialize():
  """Initialize if monitoring is enabled for this bot."""
  global _monitoring_v3_client
  global _flusher_thread

  if environment.get_value('LOCAL_DEVELOPMENT'):
    return

  if not local_config.ProjectConfig().get('monitoring.enabled'):
    return

  if check_module_loaded(monitoring_v3):
    _initialize_monitored_resource()
    _monitoring_v3_client = monitoring_v3.MetricServiceClient(
        credentials=credentials.get_default()[0])
    _flusher_thread = _FlusherThread()
    _flusher_thread.start() 
開發者ID:google,項目名稱:clusterfuzz,代碼行數:19,代碼來源:monitor.py

示例3: get_cpu_load

# 需要導入模塊: from google.cloud import monitoring_v3 [as 別名]
# 或者: from google.cloud.monitoring_v3 import MetricServiceClient [as 別名]
def get_cpu_load():
    """Returns the most recent Cloud Bigtable CPU load measurement.

    Returns:
          float: The most recent Cloud Bigtable CPU usage metric
    """
    # [START bigtable_cpu]
    client = monitoring_v3.MetricServiceClient()
    cpu_query = query.Query(client,
                            project=PROJECT,
                            metric_type='bigtable.googleapis.com/'
                                        'cluster/cpu_load',
                            minutes=5)
    cpu = next(cpu_query.iter())
    return cpu.points[0].value.double_value
    # [END bigtable_cpu] 
開發者ID:GoogleCloudPlatform,項目名稱:python-docs-samples,代碼行數:18,代碼來源:metricscaler.py

示例4: get_storage_utilization

# 需要導入模塊: from google.cloud import monitoring_v3 [as 別名]
# 或者: from google.cloud.monitoring_v3 import MetricServiceClient [as 別名]
def get_storage_utilization():
    """Returns the most recent Cloud Bigtable storage utilization measurement.

    Returns:
          float: The most recent Cloud Bigtable storage utilization metric
    """
    # [START bigtable_metric_scaler_storage_utilization]
    client = monitoring_v3.MetricServiceClient()
    utilization_query = query.Query(client,
                                    project=PROJECT,
                                    metric_type='bigtable.googleapis.com/'
                                                'cluster/storage_utilization',
                                    minutes=5)
    utilization = next(utilization_query.iter())
    return utilization.points[0].value.double_value
    # [END bigtable_metric_scaler_storage_utilization] 
開發者ID:GoogleCloudPlatform,項目名稱:python-docs-samples,代碼行數:18,代碼來源:metricscaler.py

示例5: run_quickstart

# 需要導入模塊: from google.cloud import monitoring_v3 [as 別名]
# 或者: from google.cloud.monitoring_v3 import MetricServiceClient [as 別名]
def run_quickstart():
    # [START monitoring_quickstart]
    from google.cloud import monitoring_v3

    import time

    client = monitoring_v3.MetricServiceClient()
    project = 'my-project'  # TODO: Update to your project ID.
    project_name = client.project_path(project)

    series = monitoring_v3.types.TimeSeries()
    series.metric.type = 'custom.googleapis.com/my_metric'
    series.resource.type = 'gce_instance'
    series.resource.labels['instance_id'] = '1234567890123456789'
    series.resource.labels['zone'] = 'us-central1-f'
    point = series.points.add()
    point.value.double_value = 3.14
    now = time.time()
    point.interval.end_time.seconds = int(now)
    point.interval.end_time.nanos = int(
        (now - point.interval.end_time.seconds) * 10**9)
    client.create_time_series(project_name, [series])
    print('Successfully wrote time series.')
    # [END monitoring_quickstart] 
開發者ID:GoogleCloudPlatform,項目名稱:python-docs-samples,代碼行數:26,代碼來源:quickstart.py

示例6: list_time_series

# 需要導入模塊: from google.cloud import monitoring_v3 [as 別名]
# 或者: from google.cloud.monitoring_v3 import MetricServiceClient [as 別名]
def list_time_series(project_id):
    # [START monitoring_read_timeseries_simple]
    client = monitoring_v3.MetricServiceClient()
    project_name = client.project_path(project_id)
    interval = monitoring_v3.types.TimeInterval()
    now = time.time()
    interval.end_time.seconds = int(now)
    interval.end_time.nanos = int(
        (now - interval.end_time.seconds) * 10**9)
    interval.start_time.seconds = int(now - 1200)
    interval.start_time.nanos = interval.end_time.nanos
    results = client.list_time_series(
        project_name,
        'metric.type = "compute.googleapis.com/instance/cpu/utilization"',
        interval,
        monitoring_v3.enums.ListTimeSeriesRequest.TimeSeriesView.FULL)
    for result in results:
        print(result)
    # [END monitoring_read_timeseries_simple] 
開發者ID:GoogleCloudPlatform,項目名稱:python-docs-samples,代碼行數:21,代碼來源:snippets.py

示例7: list_time_series_header

# 需要導入模塊: from google.cloud import monitoring_v3 [as 別名]
# 或者: from google.cloud.monitoring_v3 import MetricServiceClient [as 別名]
def list_time_series_header(project_id):
    # [START monitoring_read_timeseries_fields]
    client = monitoring_v3.MetricServiceClient()
    project_name = client.project_path(project_id)
    interval = monitoring_v3.types.TimeInterval()
    now = time.time()
    interval.end_time.seconds = int(now)
    interval.end_time.nanos = int(
        (now - interval.end_time.seconds) * 10**9)
    interval.start_time.seconds = int(now - 1200)
    interval.start_time.nanos = interval.end_time.nanos
    results = client.list_time_series(
        project_name,
        'metric.type = "compute.googleapis.com/instance/cpu/utilization"',
        interval,
        monitoring_v3.enums.ListTimeSeriesRequest.TimeSeriesView.HEADERS)
    for result in results:
        print(result)
    # [END monitoring_read_timeseries_fields] 
開發者ID:GoogleCloudPlatform,項目名稱:python-docs-samples,代碼行數:21,代碼來源:snippets.py

示例8: list_time_series_aggregate

# 需要導入模塊: from google.cloud import monitoring_v3 [as 別名]
# 或者: from google.cloud.monitoring_v3 import MetricServiceClient [as 別名]
def list_time_series_aggregate(project_id):
    # [START monitoring_read_timeseries_align]
    client = monitoring_v3.MetricServiceClient()
    project_name = client.project_path(project_id)
    interval = monitoring_v3.types.TimeInterval()
    now = time.time()
    interval.end_time.seconds = int(now)
    interval.end_time.nanos = int(
        (now - interval.end_time.seconds) * 10**9)
    interval.start_time.seconds = int(now - 3600)
    interval.start_time.nanos = interval.end_time.nanos
    aggregation = monitoring_v3.types.Aggregation()
    aggregation.alignment_period.seconds = 1200  # 20 minutes
    aggregation.per_series_aligner = (
        monitoring_v3.enums.Aggregation.Aligner.ALIGN_MEAN)

    results = client.list_time_series(
        project_name,
        'metric.type = "compute.googleapis.com/instance/cpu/utilization"',
        interval,
        monitoring_v3.enums.ListTimeSeriesRequest.TimeSeriesView.FULL,
        aggregation)
    for result in results:
        print(result)
    # [END monitoring_read_timeseries_align] 
開發者ID:GoogleCloudPlatform,項目名稱:python-docs-samples,代碼行數:27,代碼來源:snippets.py

示例9: _get_resource_values

# 需要導入模塊: from google.cloud import monitoring_v3 [as 別名]
# 或者: from google.cloud.monitoring_v3 import MetricServiceClient [as 別名]
def _get_resource_values():
    """Get Resources Values

    :return:
    """
    # Get instance information
    data = requests.get('{}zone'.format(METADATA_SERVER),
                        headers=METADATA_FLAVOR).text
    instance_id = requests.get(
        '{}id'.format(METADATA_SERVER), headers=METADATA_FLAVOR).text
    client = monitoring_v3.MetricServiceClient()
    # Collect zone
    zone = data.split('/')[3]
    # Collect project id
    project_id = data.split('/')[1]
    resource_values = {
        'client': client,
        'instance_id': instance_id,
        'zone': zone,
        'project_id': project_id
    }
    return resource_values 
開發者ID:GoogleCloudPlatform,項目名稱:ml-on-gcp,代碼行數:24,代碼來源:report_gpu_metrics.py

示例10: __init__

# 需要導入模塊: from google.cloud import monitoring_v3 [as 別名]
# 或者: from google.cloud.monitoring_v3 import MetricServiceClient [as 別名]
def __init__(
        self, project_id=None, client=None, add_unique_identifier=False
    ):
        self.client = client or MetricServiceClient()
        if not project_id:
            _, self.project_id = google.auth.default()
        else:
            self.project_id = project_id
        self.project_name = self.client.project_path(self.project_id)
        self._metric_descriptors = {}
        self._last_updated = {}
        self.unique_identifier = None
        if add_unique_identifier:
            self.unique_identifier = "{:08x}".format(
                random.randint(0, 16 ** 8)
            ) 
開發者ID:open-telemetry,項目名稱:opentelemetry-python,代碼行數:18,代碼來源:__init__.py

示例11: _add_series

# 需要導入模塊: from google.cloud import monitoring_v3 [as 別名]
# 或者: from google.cloud.monitoring_v3 import MetricServiceClient [as 別名]
def _add_series(project_id, series, client=None):
  """Write metrics series to Stackdriver.

  Args:
    project_id: series will be written to this project id's account
    series: the time series to be written, as a list of
        monitoring_v3.types.TimeSeries instances
    client: optional monitoring_v3.MetricServiceClient will be used
        instead of obtaining a new one
  """
  client = client or monitoring_v3.MetricServiceClient()
  project_name = client.project_path(project_id)
  if isinstance(series, monitoring_v3.types.TimeSeries):
    series = [series]
  try:
    client.create_time_series(project_name, series)
  except GoogleAPIError as e:
    raise Error('Error from monitoring API: %s' % e) 
開發者ID:GoogleCloudPlatform,項目名稱:professional-services,代碼行數:20,代碼來源:gce-quota-sync.py

示例12: main

# 需要導入模塊: from google.cloud import monitoring_v3 [as 別名]
# 或者: from google.cloud.monitoring_v3 import MetricServiceClient [as 別名]
def main(project=None, gce_regions=None, verbose=False, **kw):
  "Fetch, convert, and write quotas for project and optional regions."
  _configure_logging(verbose=verbose)
  regions = ['global']
  if gce_regions:
    regions += gce_regions.split(',')
  quotas = []
  try:
    compute = googleapiclient.discovery.build(
        'compute', 'v1', cache_discovery=False)
    # Fetch quotas for global + defined regions.
    for region in regions:
      _LOGGER.debug('fetching project quota for %s %s', project, region)
      for quota in _fetch_quotas(project, region, compute=compute):
        quotas.append((region, quota))
    # Convert quotas to series, write to Stackdriver using naive batching.
    client, i = monitoring_v3.MetricServiceClient(), 0
    while i < len(quotas):
      series = [_quota_to_series(project, *q)
                for q in quotas[i:i + _BATCH_SIZE]]
      _add_series(project, series, client)
      i += _BATCH_SIZE
  except Error as e:
    _LOGGER.critical(e.message) 
開發者ID:GoogleCloudPlatform,項目名稱:professional-services,代碼行數:26,代碼來源:gce-quota-sync.py

示例13: gcp_create_metric_descriptor

# 需要導入模塊: from google.cloud import monitoring_v3 [as 別名]
# 或者: from google.cloud.monitoring_v3 import MetricServiceClient [as 別名]
def gcp_create_metric_descriptor(project_id: str):
    """Create metric descriptors on Stackdriver.
    
    Re-creating these with every call is fine."""
    client = monitoring_v3.MetricServiceClient()
    project_name = client.project_path(project_id)

    for desc_type, desc_desc in [
        ["buildbots_percent_failed", "Percentage of failed builds"],
        ["buildbots_builds_successful", "Number of successful builds in the last 24h."],
        ["buildbots_builds_failed", "Number of failed builds in the last 24h."],
        ["buildbots_builds_total", "Total number of builds in the last 24h."],
    ]:

        descriptor = monitoring_v3.types.MetricDescriptor()
        descriptor.type = 'custom.googleapis.com/buildbots_{}'.format(desc_type)
        descriptor.metric_kind = (
            monitoring_v3.enums.MetricDescriptor.MetricKind.GAUGE)
        descriptor.value_type = (
            monitoring_v3.enums.MetricDescriptor.ValueType.DOUBLE)
        descriptor.description = desc_desc
        descriptor = client.create_metric_descriptor(project_name, descriptor)
        print('Created {}.'.format(descriptor.name)) 
開發者ID:google,項目名稱:llvm-premerge-checks,代碼行數:25,代碼來源:buildbots.py

示例14: gcp_write_data

# 需要導入模塊: from google.cloud import monitoring_v3 [as 別名]
# 或者: from google.cloud.monitoring_v3 import MetricServiceClient [as 別名]
def gcp_write_data(project_id: str, stats: BuildStats):
    """Upload metrics to Stackdriver."""
    client = monitoring_v3.MetricServiceClient()
    project_name = client.project_path(project_id)
    now = datetime.datetime.now()

    for desc_type, value in [
        ["buildbots_percent_failed", stats.percent_failed],
        ["buildbots_builds_successful", stats.successful],
        ["buildbots_builds_failed", stats.failed],
        ["buildbots_builds_total", stats.total],
    ]:
        series = monitoring_v3.types.TimeSeries()
        series.metric.type = 'custom.googleapis.com/buildbots_{}'.format(desc_type)
        series.resource.type = 'global'
        point = series.points.add()
        point.value.double_value = value
        point.interval.end_time.seconds = int(now.timestamp())
        client.create_time_series(project_name, [series]) 
開發者ID:google,項目名稱:llvm-premerge-checks,代碼行數:21,代碼來源:buildbots.py

示例15: gcp_write_data

# 需要導入模塊: from google.cloud import monitoring_v3 [as 別名]
# 或者: from google.cloud.monitoring_v3 import MetricServiceClient [as 別名]
def gcp_write_data(project_id: str, stats: RepoStats, now:datetime.datetime):
    """Upload metrics to Stackdriver."""
    client = monitoring_v3.MetricServiceClient()
    project_name = client.project_path(project_id)

    for desc_type, value in [
        ["reverts", stats.reverts],
        ["commits", stats.commits],
        ["percent_reverted", stats.percent_reverted],
        ["reviewed", stats.reviewed],
        ["percent_reviewed", stats.percent_reviewed],
    ]:
        if value is None:
            continue

        series = monitoring_v3.types.TimeSeries()
        series.metric.type = 'custom.googleapis.com/repository_{}'.format(desc_type)
        series.resource.type = 'global'
        point = series.points.add()
        point.value.double_value = value
        point.interval.end_time.seconds = int(now.timestamp())
        client.create_time_series(project_name, [series]) 
開發者ID:google,項目名稱:llvm-premerge-checks,代碼行數:24,代碼來源:repo.py


注:本文中的google.cloud.monitoring_v3.MetricServiceClient方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。