本文整理汇总了Python中datadog.api方法的典型用法代码示例。如果您正苦于以下问题:Python datadog.api方法的具体用法?Python datadog.api怎么用?Python datadog.api使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类datadog
的用法示例。
在下文中一共展示了datadog.api方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: poke
# 需要导入模块: import datadog [as 别名]
# 或者: from datadog import api [as 别名]
def poke(self, context):
# This instantiates the hook, but doesn't need it further,
# because the API authenticates globally (unfortunately),
# but for airflow this shouldn't matter too much, because each
# task instance runs in its own process anyway.
DatadogHook(datadog_conn_id=self.datadog_conn_id)
response = api.Event.query(
start=self.from_seconds_ago,
end=self.up_to_seconds_from_now,
priority=self.priority,
sources=self.sources,
tags=self.tags)
if isinstance(response, dict) and response.get('status', 'ok') != 'ok':
self.log.error("Unexpected Datadog result: %s", response)
raise AirflowException("Datadog returned unexpected result")
if self.response_check:
# run content check on response
return self.response_check(response)
# If no check was inserted, assume any event that matched yields true.
return len(response) > 0
示例2: __init__
# 需要导入模块: import datadog [as 别名]
# 或者: from datadog import api [as 别名]
def __init__(self, datadog_conn_id='datadog_default'):
super().__init__()
conn = self.get_connection(datadog_conn_id)
self.api_key = conn.extra_dejson.get('api_key', None)
self.app_key = conn.extra_dejson.get('app_key', None)
self.source_type_name = conn.extra_dejson.get('source_type_name', None)
# If the host is populated, it will use that hostname instead.
# for all metric submissions.
self.host = conn.host
if self.api_key is None:
raise AirflowException("api_key must be specified in the "
"Datadog connection details")
self.log.info("Setting up api keys for Datadog")
initialize(api_key=self.api_key, app_key=self.app_key)
示例3: send_metric
# 需要导入模块: import datadog [as 别名]
# 或者: from datadog import api [as 别名]
def send_metric(self, metric_name, datapoint, tags=None, type_=None, interval=None):
"""
Sends a single datapoint metric to DataDog
:param metric_name: The name of the metric
:type metric_name: str
:param datapoint: A single integer or float related to the metric
:type datapoint: int or float
:param tags: A list of tags associated with the metric
:type tags: list
:param type_: Type of your metric: gauge, rate, or count
:type type_: str
:param interval: If the type of the metric is rate or count, define the corresponding interval
:type interval: int
"""
response = api.Metric.send(
metric=metric_name,
points=datapoint,
host=self.host,
tags=tags,
type=type_,
interval=interval)
self.validate_response(response)
return response
示例4: get_datadog_monitors
# 需要导入模块: import datadog [as 别名]
# 或者: from datadog import api [as 别名]
def get_datadog_monitors():
monitors = datadog.api.Monitor.get_all(with_downtimes="true")
if CONFIG['dogpush']['ignore_prefix'] is not None:
monitors = [
m for m in monitors
if not m['name'].startswith(CONFIG['dogpush']['ignore_prefix'])
]
if not _check_monitor_names_unique(monitors):
raise DogPushException(
'Duplicate names found in remote datadog monitors.')
result = {}
for m in monitors:
m = _canonical_monitor(m)
result[m['name']] = m
return result
示例5: get_hosts
# 需要导入模块: import datadog [as 别名]
# 或者: from datadog import api [as 别名]
def get_hosts(filter_string):
host_count = api.Hosts.search(filter=initial_filter_string)['total_matching']
print('%r hosts matching initial_filter_string' % host_count)
num_req = host_count // 100 + 1
print('%r number of api requests to query all matching hosts' % num_req)
matching_hosts = []
start_index = 0
for i in range(1, num_req+1):
print('api request %r of %r' % (i, num_req))
host_list = api.Hosts.search(filter=initial_filter_string, sort_field='apps', count=100, start=start_index)['host_list']
start_index += 100
for host in host_list:
matching_hosts.append(host)
return matching_hosts
# filter list returned by API by searchin on host[key]
示例6: pull_monitors
# 需要导入模块: import datadog [as 别名]
# 或者: from datadog import api [as 别名]
def pull_monitors():
path = False
count = 0
good_keys = ['tags', 'deleted', 'query', 'message', 'matching_downtimes', 'multi', 'name', 'type', 'options', 'id']
new_monitors = []
monitors = api.Monitor.get_all()
for monitor in monitors:
if monitor["type"] == "synthetics alert":
print("Skipping {} as this is a monitor belonging to a synthetic test. Synthetic monitors will be automatically re-created when you push synthetic tests.".format(monitor["name"]))
continue
count = count + 1
new_monitor = {}
for k, v in monitor.items():
if k in good_keys:
new_monitor[k] = v
if not arguments["--dry-run"]:
path = _json_to_file('monitors', str(new_monitor["id"]), new_monitor)
print("Pulling monitor: {} with id: {}, writing to file: {}".format(new_monitor["name"].encode('utf8'), new_monitor["id"], path))
print("Retrieved '{}' monitors.".format(count))
示例7: pull_synthetics_api_tests
# 需要导入模块: import datadog [as 别名]
# 或者: from datadog import api [as 别名]
def pull_synthetics_api_tests(options, tag):
path = False
count = 0
tags = [] if not tag else tag
r = requests.get('{}api/v1/synthetics/tests?api_key={}&application_key={}'.format(options["api_host"], options["api_key"], options["app_key"]))
synthetics = r.json()
for synthetic in synthetics["tests"]:
if synthetic["type"] == "api":
for tag in tags:
if tag in synthetic["tags"]:
print("Tag: {} found in synthetic test: {}".format(tag, synthetic["name"]))
count = count + 1
json_data = requests.get('{}api/v1/synthetics/tests/{}?api_key={}&application_key={}'.format(
options["api_host"],
synthetic["public_id"],
options["api_key"],
options["app_key"]
)).json()
path = _json_to_file('synthetics_api_tests', synthetic["public_id"], json_data)
print("Pulling: {} and writing to file: {}".format(synthetic["name"].encode('utf8'), path))
print("Retrieved '{}' synthetic tests.".format(count))
示例8: push_dashboards
# 需要导入模块: import datadog [as 别名]
# 或者: from datadog import api [as 别名]
def push_dashboards():
count = 0
dashboards = _files_to_json("dashboards")
if not dashboards:
exit("No dashboards are locally available. Consider pulling dashboards first.")
for dashboard in dashboards:
with open(dashboard) as f:
data = json.load(f)
count = count + 1
print("Pushing {}".format(data["title"].encode('utf8')))
if not arguments["--dry-run"]:
api.Dashboard.create(
title=data["title"],
description=data["description"],
widgets=data["widgets"],
template_variables=data["template_variables"],
layout_type=data["layout_type"],
notify_list=data["notify_list"],
is_read_only=data["is_read_only"]
)
print("Pushed '{}' dashboards".format(count))
示例9: push_synthetics_api_tests
# 需要导入模块: import datadog [as 别名]
# 或者: from datadog import api [as 别名]
def push_synthetics_api_tests(options):
count = 0
synthetics = _files_to_json("synthetics_api_tests")
if not synthetics:
exit("No synthetic tests are locally available. Consider synthetics first.")
for synthetic in synthetics:
with open(synthetic) as f:
data = json.load(f)
count = count + 1
invalid_keys = ["public_id", "monitor_id"]
list(map(data.pop, invalid_keys))
print("Pushing {}".format(data["name"].encode('utf8')))
if not arguments["--dry-run"]:
r = requests.post('{}api/v1/synthetics/tests?api_key={}&application_key={}'.format(options["api_host"], options["api_key"], options["app_key"]), json=data)
print("Pushed '{}' synthetic tests.".format(count))
示例10: push_synthetics_browser_tests
# 需要导入模块: import datadog [as 别名]
# 或者: from datadog import api [as 别名]
def push_synthetics_browser_tests(options):
count = 0
synthetics = _files_to_json("synthetics_browser_tests")
if not synthetics:
exit("No synthetic tests are locally available. Consider synthetics first.")
for synthetic in synthetics:
with open(synthetic) as f:
data = json.load(f)
count = count + 1
invalid_keys = ["public_id", "monitor_id"]
list(map(data.pop, invalid_keys))
print("Pushing {}".format(data["name"].encode('utf8')))
if not arguments["--dry-run"]:
r = requests.post('{}api/v1/synthetics/tests?api_key={}&application_key={}'.format(options["api_host"], options["api_key"], options["app_key"]), json=data)
print("Pushed '{}' synthetic tests.".format(count))
示例11: push_awsaccounts
# 需要导入模块: import datadog [as 别名]
# 或者: from datadog import api [as 别名]
def push_awsaccounts(options):
count = 0
awsaccounts = _files_to_json("awsaccounts")
if not awsaccounts:
exit("No awsaccounts are locally available. Consider pulling awsaccounts first.")
for awsaccount in awsaccounts:
with open(awsaccount) as f:
data = json.load(f)
count = count + 1
print("Pushing {}".format(data["account_id"].encode('utf8')))
if not arguments["--dry-run"]:
r = requests.post('{}api/v1/integration/aws?api_key={}&application_key={}'.format(options["api_host"], options["api_key"], options["app_key"]), json=data)
json_data = json.loads(r.text)
json_data["account_id"] = data["account_id"]
print(json.dumps(json_data))
path = _json_to_file('awsaccounts.out', data["account_id"], json_data)
print("Pushed '{}' AWS accounts.".format(count))
print("You can now use the json files in the awsaccounts.out folder to automate the AWS External ID onboarding using AWS APIs.")
示例12: push_logpipelines
# 需要导入模块: import datadog [as 别名]
# 或者: from datadog import api [as 别名]
def push_logpipelines(options):
count = 0
fJSON = _files_to_json("logpipelines")
if not fJSON:
exit("No logpipelines are locally available. Consider pulling logpipelines first.")
for item in fJSON:
with open(item) as f:
data = json.load(f)
count = count + 1
print("Pushing {}".format(data["id"].encode('utf8')))
itemId = data['id']
del data['id']
del data['is_read_only']
del data['type']
headers = {'content-type': 'application/json'}
if not arguments["--dry-run"]:
r = requests.post('{}api/v1/logs/config/pipelines?api_key={}&application_key={}'.format(options["api_host"], options["api_key"], options["app_key"]), headers=headers, json=data)
json_data = json.loads(r.text)
json_data["id"] = itemId
path = _json_to_file('logpipelines.out', itemId, json_data)
print("Pushed '{}' log pipelines.".format(count))
示例13: metric_report
# 需要导入模块: import datadog [as 别名]
# 或者: from datadog import api [as 别名]
def metric_report(ids_list, metrics_to_eval, resource):
title = ''
resp = {}
query = ''
getter = ''
for id in ids_list:
if resource == "dash":
resp = api.Dashboard.get(str(id))
query = str(resp.get("widgets"))
getter = "title"
elif resource == "monitor":
resp = api.Monitor.get(str(id))
query = str(resp.get("query"))
getter = "name"
else:
print(resource + " is an invalid resource name, exiting.")
quit()
for metric in metrics_to_eval:
if query.find(metric) != -1:
if title != resp[getter]:
title = resp[getter]
print('\n\n\tTitle: ' + resp[getter])
print('\n\t\t Metric: ' + metric)
示例14: publish_metrics
# 需要导入模块: import datadog [as 别名]
# 或者: from datadog import api [as 别名]
def publish_metrics(self, service_metrics):
"""Writes time series data to Datadog for a metric snapshot."""
points = []
spectator_client.foreach_metric_in_service_map(
service_metrics, self.__append_timeseries_point, points)
offset = 0
while offset < len(points):
last = min(offset + self.MAX_BATCH, len(points))
chunk = points[offset:last]
try:
self.api.Metric.send(chunk)
except IOError as ioerr:
logging.error('Error sending to datadog: %s', ioerr)
offset = last
return len(points)
示例15: test_metric_query_cpuIdle
# 需要导入模块: import datadog [as 别名]
# 或者: from datadog import api [as 别名]
def test_metric_query_cpuIdle(self, datadog_api):
# set start/end
import datetime as dt
from datetime import timedelta
dt_now = dt.datetime.now()
dt_1w = dt_now - timedelta(days=7)
# convert to seconds since unix epoch
# https://stackoverflow.com/a/6999787/4126114
import time
conv2sec = lambda x: time.mktime(x.timetuple())
ue_now = conv2sec(dt_now)
ue_1w = conv2sec(dt_1w)
# build query
from isitfit.utils import SECONDS_IN_ONE_DAY
query = 'system.cpu.idle{host:%s}.rollup(min,%i)'%(self.datadog_hostname, SECONDS_IN_ONE_DAY)
# query datadog
# https://docs.datadoghq.com/api/?lang=python#query-timeseries-points
m = datadog_api.Metric.query(start=ue_1w, end=ue_now, query=query)
if 'errors' in m:
print(m)
raise Exception(m['errors'])
if m['status'] != 'ok':
raise Exception(m['status'])
assert len(m['series'])>0