本文整理汇总了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)')
示例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()
示例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]
示例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]
示例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]
示例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]
示例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]
示例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]
示例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
示例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)
)
示例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)
示例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)
示例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))
示例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])
示例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])