desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Get a part of a pod config from the kubernetes API'
| def get_kube_config(self, c_id, key):
| for pod in self.kube_pods:
c_statuses = pod.get('status', {}).get('containerStatuses', [])
for status in c_statuses:
if (c_id == status.get('containerID', '').split('//')[(-1)]):
return pod.get(key, {})
return {}
|
'Get the list of checks applied to a container from the identifier_to_checks cache in the config store.
Use the DATADOG_ID label or the image.'
| def _get_checks_to_refresh(self, state, c_id):
| inspect = state.inspect_container(c_id)
if ((not inspect) or ((not inspect.get('State', {}).get('Running')) and Platform.is_k8s() and (not self.agentConfig.get('sd_config_backend')))):
self.reload_check_configs = True
return
labels = inspect.get('Config', {}).get('Labels', {})
identifier... |
'Extract the host-namespace pid of the container pid 0'
| def _get_container_pid(self, state, cid, tpl_var):
| pid = state.inspect_container(cid).get('State', {}).get('Pid')
if (not pid):
return None
return str(pid)
|
'Extract the container IP from a docker inspect object, or the kubelet API.'
| def _get_host_address(self, state, c_id, tpl_var):
| c_inspect = state.inspect_container(c_id)
(c_id, c_img) = (c_inspect.get('Id', ''), c_inspect.get('Config', {}).get('Image', ''))
networks = (c_inspect.get('NetworkSettings', {}).get('Networks') or {})
ip_dict = {}
for (net_name, net_desc) in networks.iteritems():
ip = net_desc.get('IPAddres... |
'Extract a single IP from a dictionary made of network names and IPs.'
| def _extract_ip_from_networks(self, ip_dict, tpl_var):
| if (not ip_dict):
return None
tpl_parts = tpl_var.split('_', 1)
if (len(tpl_parts) < 2):
log.debug(('No key was passed for template variable %s.' % tpl_var))
return self._get_fallback_ip(ip_dict)
else:
res = ip_dict.get(tpl_parts[(-1)])
if (re... |
'try to pick the bridge key, falls back to the value of the last key'
| def _get_fallback_ip(self, ip_dict):
| if ('bridge' in ip_dict):
log.debug('Using the bridge network.')
return ip_dict['bridge']
else:
last_key = sorted(ip_dict.iterkeys())[(-1)]
log.debug(("Trying with the last (sorted) network: '%s'." % last_key))
return ip_dict[last_key]
|
'Extract a port from a container_inspect or the k8s API given a template variable.'
| def _get_port(self, state, c_id, tpl_var):
| container_inspect = state.inspect_container(c_id)
try:
ports = map((lambda x: x.split('/')[0]), container_inspect['NetworkSettings']['Ports'].keys())
if (len(ports) == 0):
raise IndexError
except (IndexError, KeyError, AttributeError):
ports = map((lambda x: x.split('/')[... |
'Extract useful tags from docker or platform APIs. These are collected by default.'
| def get_tags(self, state, c_id):
| c_inspect = state.inspect_container(c_id)
tags = self.dockerutil.extract_container_tags(c_inspect)
if Platform.is_k8s():
pod_metadata = state.get_kube_config(c_id, 'metadata')
if (pod_metadata is None):
log.warning(('Failed to fetch pod metadata for container ... |
'Get the config for all docker containers running on the host.'
| def get_configs(self):
| configs = {}
state = self._make_fetch_state()
containers = [(self.dockerutil.image_name_extractor(container), container.get('Id'), container.get('Labels')) for container in self.docker_client.containers()]
for (image, cid, labels) in containers:
try:
identifier = self.get_config_id(i... |
'Look for a DATADOG_ID label, return its value or the image name if missing'
| def get_config_id(self, image, labels):
| return (labels.get(DATADOG_ID) or image)
|
'Retrieve configuration templates and fill them with data pulled from docker and tags.'
| def _get_check_configs(self, state, c_id, identifier, labels=None):
| platform_kwargs = {}
if Platform.is_k8s():
kube_metadata = (state.get_kube_config(c_id, 'metadata') or {})
platform_kwargs = {'kube_container_name': state.get_kube_container_name(c_id), 'kube_annotations': kube_metadata.get('annotations')}
if labels:
platform_kwargs['docker_labels'] ... |
'Extract config templates for an identifier from a K/V store and returns it as a dict object.'
| def _get_config_templates(self, identifier, **platform_kwargs):
| config_backend = self.agentConfig.get('sd_config_backend')
templates = []
if (config_backend is None):
auto_conf = True
else:
auto_conf = False
raw_tpls = self.config_store.get_check_tpls(identifier, auto_conf=auto_conf, **platform_kwargs)
for tpl in raw_tpls:
try:
... |
'Add container tags to instance templates and build a
dict from template variable names and their values.'
| def _fill_tpl(self, state, c_id, instance_tpl, variables, tags=None):
| var_values = {}
c_image = state.inspect_container(c_id).get('Config', {}).get('Image', '')
if tags:
tpl_tags = instance_tpl.get('tags', [])
if isinstance(tpl_tags, dict):
for (key, val) in tpl_tags.iteritems():
tags.append('{}:{}'.format(key, val))
else:
... |
'Extract settings from a config object'
| def _extract_settings(self, config):
| settings = {'host': config.get('sd_backend_host', DEFAULT_CONSUL_HOST), 'port': int(config.get('sd_backend_port', DEFAULT_CONSUL_PORT)), 'token': config.get('consul_token', None), 'scheme': config.get('consul_scheme', DEFAULT_CONSUL_SCHEME), 'consistency': config.get('consul_consistency', DEFAULT_CONSUL_CONSISTENCY... |
'Return a consul client, create it if needed'
| def get_client(self, reset=False):
| if ((self.client is None) or (reset is True)):
self.client = Consul(host=self.settings.get('host'), port=self.settings.get('port'), token=self.settings.get('token'), scheme=self.settings.get('scheme'), consistency=self.settings.get('consistency'), verify=self.settings.get('verify'))
return self.client
|
'Retrieve a value from a consul key.'
| def client_read(self, path, **kwargs):
| recurse = (kwargs.get('recursive') or kwargs.get('all', False))
res = self.client.kv.get(path, recurse=recurse)
if kwargs.get('watch', False):
return res[0]
elif (res[1] is not None):
return (res[1].get('Value') if (not recurse) else res[1])
else:
raise KeyNotFound(('The k... |
'Return a dict made of all image names and their corresponding check info'
| def dump_directory(self, path, **kwargs):
| templates = {}
path = path.lstrip('/')
try:
directory = self.client_read(path, recursive=True)
except KeyNotFound:
raise KeyNotFound(('The key %s was not found in consul' % path))
for leaf in directory:
image = leaf.get('Key').split('/')[(-2)]
par... |
'Get the config for all docker containers running on the host.'
| def get_configs(self):
| raise NotImplementedError()
|
'Replace placeholders in a template with the proper values.
Return a tuple made of `init_config` and `instances`.'
| def _render_template(self, init_config_tpl, instance_tpl, variables):
| config = (init_config_tpl, instance_tpl)
for tpl in config:
for key in tpl:
for var in self.PLACEHOLDER_REGEX.findall(str(tpl[key])):
var_value = variables.get(var.strip('%'))
if (var_value is not None):
if isinstance(tpl[key], list):
... |
'Extract settings from a config object'
| def _extract_settings(self, config):
| settings = {'host': config.get('sd_backend_host', DEFAULT_ETCD_HOST), 'port': int(config.get('sd_backend_port', (-1))), 'username': config.get('sd_backend_username', None), 'password': config.get('sd_backend_password', None), 'allow_reconnect': config.get('etcd_allow_reconnect', DEFAULT_RECO), 'protocol': config.ge... |
'Retrieve a value from a etcd key.'
| def client_read(self, path, **kwargs):
| try:
res = self.client.read(path, timeout=kwargs.get('timeout', DEFAULT_TIMEOUT), recursive=(kwargs.get('recursive') or kwargs.get('all', False)))
if kwargs.get('watch', False):
modified_indices = ((res.modifiedIndex,) + tuple((leaf.modifiedIndex for leaf in res.leaves)))
ret... |
'Return a dict made of all image names and their corresponding check info'
| def dump_directory(self, path, **kwargs):
| templates = {}
try:
directory = self.client.read(path, recursive=True, timeout=kwargs.get('timeout', DEFAULT_TIMEOUT))
except EtcdKeyNotFound:
raise KeyNotFound(('The key %s was not found in etcd' % path))
except TimeoutError as e:
raise e
for leaf in dir... |
'Initialize TLS settings for connection to apiserver and kubelet.'
| def _init_tls_settings(self, instance):
| tls_settings = {}
client_crt = instance.get('apiserver_client_crt')
client_key = instance.get('apiserver_client_key')
apiserver_cacert = instance.get('apiserver_ca_cert')
if (client_crt and client_key and os.path.exists(client_crt) and os.path.exists(client_key)):
tls_settings['apiserver_cli... |
'Kubelet may or may not accept un-authenticated http requests.
If it doesn\'t we need to use its HTTPS API that may or may not
require auth.'
| def _locate_kubelet(self, instance):
| host = (os.environ.get('KUBERNETES_KUBELET_HOST') or instance.get('host'))
if (not host):
docker_hostname = self.docker_util.get_hostname(should_resolve=True)
if self.tls_settings.get('kubelet_verify'):
try:
k8s_hostname = self.get_node_hostname(docker_hostname)
... |
'Query the API server for the kubernetes hostname of the node
using the docker hostname as a filter.'
| def get_node_hostname(self, host):
| node_filter = {'labelSelector': ('kubernetes.io/hostname=%s' % host)}
node = self.retrieve_json_auth((self.kubernetes_api_url + ('/nodes?%s' % urlencode(node_filter))))
if (len(node['items']) != 1):
log.error(('Error while getting node hostname: expected 1 node, got %s.' %... |
'Gets pods\' labels as tags + creator and service tags.
Returns a dict{namespace/podname: [tags]}'
| def get_kube_pod_tags(self, excluded_keys=None):
| pods = self.retrieve_pods_list()
return self.extract_kube_pod_tags(pods, excluded_keys=excluded_keys)
|
'Extract labels + creator and service tags from a list of
pods coming from the kubelet API.
:param excluded_keys: labels to skip
:param label_prefix: prefix for label->tag conversion, None defaults
to the configuration option label_to_tag_prefix
Returns a dict{namespace/podname: [tags]}'
| def extract_kube_pod_tags(self, pods_list, excluded_keys=None, label_prefix=None):
| excluded_keys = (excluded_keys or [])
kube_labels = defaultdict(list)
pod_items = (pods_list.get('items') or [])
label_prefix = (label_prefix or self.kube_label_prefix)
for pod in pod_items:
metadata = pod.get('metadata', {})
name = metadata.get('name')
namespace = metadata.g... |
'Retrieve the list of pods for this cluster querying the kubelet API.
TODO: the list of pods could be cached with some policy to be decided.'
| def retrieve_pods_list(self):
| return self.perform_kubelet_query(self.pods_list_url).json()
|
'Retrieve machine info from Cadvisor.'
| def retrieve_machine_info(self):
| return retrieve_json(self.machine_info_url)
|
'Retrieve metrics from Cadvisor.'
| def retrieve_metrics(self):
| return retrieve_json(self.metrics_url)
|
'Get the deployment name for a given replicaset name
For now, the rs name\'s first part always is the deployment\'s name, see
https://github.com/kubernetes/kubernetes/blob/release-1.6/pkg/controller/deployment/sync.go#L299
But it might change in a future k8s version. The other way to match RS and deployments is
to pars... | def get_deployment_for_replicaset(self, rs_name):
| end = rs_name.rfind('-')
if ((end > 0) and rs_name[(end + 1):].isdigit()):
return rs_name[0:end]
else:
return None
|
'Perform and return a GET request against kubelet. Support auth and TLS validation.'
| def perform_kubelet_query(self, url, verbose=True, timeout=10):
| tls_context = self.tls_settings
headers = None
cert = tls_context.get('kubelet_client_cert')
verify = tls_context.get('kubelet_verify', DEFAULT_TLS_VERIFY)
if ((not cert) and url.lower().startswith('https') and ('bearer_token' in self.tls_settings)):
headers = {'Authorization': 'Bearer {}... |
'Kubernetes API requires authentication using a token available in
every pod, or with a client X509 cert/key pair.
We authenticate using the service account token by default
and replace this behavior with cert authentication if the user provided
a cert/key pair in the instance.
We try to verify the server TLS cert if t... | def retrieve_json_auth(self, url, timeout=10, verify=None, params=None):
| verify = self.tls_settings.get('apiserver_cacert')
if (not verify):
verify = (self.CA_CRT_PATH if os.path.exists(self.CA_CRT_PATH) else False)
log.debug('tls validation: {}'.format(verify))
cert = self.tls_settings.get('apiserver_client_cert')
bearer_token = (self.tls_settings.get('bea... |
'Return the IP address and the hostname of the node where the pod is running.'
| def get_node_info(self):
| if (None in (self._node_ip, self._node_name)):
self._fetch_host_data()
return (self._node_ip, self._node_name)
|
'Retrieve host name and IP address from the payload returned by the listing
pods endpoints from kubelet.
The host IP address is different from the default router for the pod.'
| def _fetch_host_data(self):
| try:
pod_items = (self.retrieve_pods_list().get('items') or [])
except Exception as e:
log.warning('Unable to retrieve pod list %s. Not fetching host data', str(e))
return
for pod in pod_items:
metadata = pod.get('metadata', {})
name = metad... |
'Return a list of tags extracted from an event object'
| def extract_event_tags(self, event):
| tags = []
if ('reason' in event):
tags.append(('reason:%s' % event.get('reason', '').lower()))
if ('namespace' in event.get('metadata', {})):
tags.append(('namespace:%s' % event['metadata']['namespace']))
if ('host' in event.get('source', {})):
tags.append(('node_name:%s' % event... |
'Because it is a pain to call it from the kubernetes check otherwise.'
| def are_tags_filtered(self, tags):
| return self.docker_util.are_tags_filtered(tags)
|
'Return a string containing the authorization token for the pod.'
| @classmethod
def get_auth_token(cls, instance):
| token_path = instance.get('bearer_token_path', cls.AUTH_TOKEN_PATH)
try:
with open(token_path) as f:
return f.read().strip()
except IOError as e:
log.error('Unable to read token from {}: {}'.format(token_path, e))
return None
|
'Match the pods labels with services\' label selectors to determine the list
of services that point to that pod. Returns an array of service names.
Pass refresh=True if you want to bypass the cached cid->services mapping (after a service change)'
| def match_services_for_pod(self, pod_metadata, refresh=False):
| s = self._service_mapper.match_services_for_pod(pod_metadata, refresh, names=True)
return s
|
'Returns a KubeEventRetriever object ready for action'
| def get_event_retriever(self, namespaces=None, kinds=None, delay=None):
| return KubeEventRetriever(self, namespaces, kinds, delay)
|
'Reads a set of pod uids and returns the set of docker
container ids they manage
podlist should be a recent self.retrieve_pods_list return value,
if not given that method will be called'
| def match_containers_for_pods(self, pod_uids, podlist=None):
| cids = set()
if ((not isinstance(pod_uids, set)) or (len(pod_uids) < 1)):
return cids
if (podlist is None):
podlist = self.retrieve_pods_list()
for pod in podlist.get('items', {}):
uid = pod.get('metadata', {}).get('uid', None)
if (uid in pod_uids):
for contai... |
'Get the pod\'s creator from its metadata and returns a
tuple (creator_kind, creator_name)
This allows for consitency across code path'
| def get_pod_creator(self, pod_metadata):
| try:
created_by = json.loads(pod_metadata['annotations']['kubernetes.io/created-by'])
creator_kind = created_by.get('reference', {}).get('kind')
creator_name = created_by.get('reference', {}).get('name')
return (creator_kind, creator_name)
except Exception:
log.debug(('Co... |
'Get the pod\'s creator from its metadata and returns a list of tags
in the form kube_$kind:$name, ready to add to the metrics'
| def get_pod_creator_tags(self, pod_metadata, legacy_rep_controller_tag=False):
| try:
tags = []
(creator_kind, creator_name) = self.get_pod_creator(pod_metadata)
if ((creator_kind in CREATOR_KIND_TO_TAG) and creator_name):
tags.append(('%s:%s' % (CREATOR_KIND_TO_TAG[creator_kind], creator_name)))
if (creator_kind == 'ReplicaSet'):
... |
'Reads a list of kube events, invalidates caches and and computes a set
of containers impacted by the changes, to refresh service discovery
Pod creation/deletion events are ignored for now, as docker_daemon already
sends container creation/deletion events to SD
Pod->containers matching is done using match_containers_fo... | def process_events(self, event_array, podlist=None):
| try:
pods = set()
if self._service_mapper:
pods.update(self._service_mapper.process_events(event_array))
return self.match_containers_for_pods(pods, podlist)
except Exception as e:
log.warning(('Error processing events %s: %s' % (str(event_array), e)))
... |
':param kubeutil_object: valid, initialised KubeUtil objet to route requests through
:param namespaces: namespace(s) to watch (string or list)
:param kinds: kinds(s) to watch (string or list)
:param delay: minimum time (in seconds) between two apiserver requests, return [] in the meantime'
| def __init__(self, kubeutil_object, namespaces=None, kinds=None, delay=None):
| self.kubeutil = kubeutil_object
self.last_resversion = (-1)
self.set_namespaces(namespaces)
self.set_kinds(kinds)
self._request_interval = delay
self._last_lookup_timestamp = (-1)
|
'Fetch latest events from the apiserver for the namespaces and kinds set on init
and returns an array of event objects'
| def get_event_array(self):
| if self._request_interval:
if ((time.time() - self._last_lookup_timestamp) < self._request_interval):
return []
else:
self._last_lookup_timestamp = time.time()
lastest_resversion = None
filtered_events = []
events = self.kubeutil.retrieve_json_auth(self.request_ur... |
'Create a new service PodServiceMapper
The apiserver requests are routed through the given KubeUtil instance'
| def __init__(self, kubeutil_object):
| self.kube = kubeutil_object
self._service_cache_selectors = defaultdict(dict)
self._service_cache_names = {}
self._service_cache_invalidated = True
self._pod_labels_cache = defaultdict(dict)
self._pod_services_mapping = defaultdict(list)
self._403_errors = 0
self._403_disable = False
|
'Get the list of services from the kubelet API and store the label selector dicts.
The cache is to be invalidated by the user class by calling process_events'
| def _fill_services_cache(self):
| if self._403_disable:
return
try:
reply = self.kube.retrieve_json_auth((self.kube.kubernetes_api_url + '/services'))
self._service_cache_selectors = defaultdict(dict)
self._service_cache_names = {}
for service in reply.get('items', []):
uid = service.get('meta... |
'Match the pods labels with services\' label selectors to determine the list
of services that point to that pod. Returns an array of service uids or names.
Pass names=True if you want the service name instead of the uids
Pass refresh=True if you want to bypass the cached cid->services mapping (after a service change)'
| def match_services_for_pod(self, pod_metadata, refresh=False, names=False):
| matches = []
if self._403_disable:
return matches
try:
pod_id = pod_metadata['uid']
pod_labels = pod_metadata.get('labels', {})
self._pod_labels_cache[pod_id] = pod_labels
if ((refresh is False) and (pod_id in self._pod_services_mapping)):
matches = self._... |
'Allows to check if a pod fulfills the label_selectors for a service by
iterating over the dictionnary.
If the pod\'s label or label_selectors are empty, the match is assumed false
Note: Job, Deployment, ReplicaSet and DaemonSet introduce matchExpressions
that are not handled by this method'
| @classmethod
def _does_pod_fulfill_selectors(cls, pod_labels, label_selectors):
| if ((len(pod_labels) == 0) or (len(label_selectors) == 0)):
return False
for (label, value) in label_selectors.iteritems():
if (pod_labels.get(label, '') != value):
return False
return True
|
'Returns the [pod_uid] list matching a service uid.
Uses the service selector and pod labels caches, but not _pod_services_mapping'
| def search_pods_for_service(self, service_uid):
| matches = []
if self._403_disable:
return matches
try:
if (self._service_cache_invalidated is True):
self._fill_services_cache()
if (service_uid not in self._service_cache_selectors):
log.debug('No selectors cached for service %s, skipping ... |
'Reads a list of kube events, invalidates caches and and computes a set
of pods impacted by the changes, to refresh service discovery'
| def process_events(self, event_array):
| pod_uids = set()
service_cache_checked = False
if self._403_disable:
return pod_uids
for event in event_array:
kind = event.get('involvedObject', {}).get('kind', None)
reason = event.get('reason', None)
if ((kind == 'Pod') and (reason == 'Killing')):
pod_id = ... |
'The Mesos agent runs on every node and listens to http port 5051
See https://mesos.apache.org/documentation/latest/endpoints/
We\'ll use the unauthenticated endpoint /version
The DCOS agent runs on every node and listens to ports 61001 or 61002
See https://dcos.io/docs/1.9/api/agent-routes/
We\'ll use the unauthentica... | def _detect_agents(self):
| mesos_urls = []
dcos_urls = []
for var in MESOS_AGENT_IP_ENV:
if (var in os.environ):
mesos_urls.append((MESOS_VERSION_URL_TEMPLATE % (os.environ.get(var), MESOS_AGENT_HTTP_PORT)))
dcos_urls.append((DCOS_HEALTH_URL_TEMPLATE % (os.environ.get(var), DCOS_AGENT_HTTP_PORT)))
... |
'Trigger a new autodetection and reset underlying util classes'
| def reset(self):
| self._utils = []
if DockerUtilProxy.is_detected():
util = DockerUtilProxy()
util.reset_cache()
self._utils.append(util)
else:
self._has_detected = False
return
if KubeUtilProxy.is_detected():
util = KubeUtilProxy()
util.reset_cache()
self._... |
'Returns whether the tagger has detected orchestrators it handles
If false, calling get_container_tags will return an empty list'
| def has_detected(self):
| return self._has_detected
|
'Returns container tags for the given container, inspecting the container if needed
:param container: either the container id or container dict returned by docker-py
:return: tags as list<string>, cached'
| def get_container_tags(self, cid=None, co=None):
| if ((cid is not None) and (co is not None)):
self.log.error('Can only pass either a container id or object, not both, returning empty tags')
return []
if ((cid is None) and (co is None)):
self.log.error('Need one container id or conta... |
'Allows cache invalidation when containers die
:param events from self.get_events'
| def invalidate_cache(self, events):
| try:
for ev in events:
if ((ev.get('status') == 'die') and (ev.get('id') in self._container_tags_cache)):
del self._container_tags_cache[ev.get('id')]
except Exception as e:
self.log.warning(('Error when invalidating tag cache: ' + str(e)))
|
'Empties all caches to reset the singleton to initial state'
| def reset_cache(self):
| self._container_tags_cache = {}
|
'When detecting orchestrator agents, one might need to try several IPs
before finding the good one.
The first url returning a 200 and validating the lambda will be returned.
If no lambda is provided, the first url to return a 200 is returned.
:param urls: list of urls to try
:param validation_lambda: lambda to return a... | def _try_urls(self, urls, validation_lambda=None, timeout=1):
| if (not urls):
return None
for url in urls:
try:
response = requests.get(url, timeout=timeout)
if (response.status_code is not requests.codes.ok):
continue
if (validation_lambda and (not validation_lambda(response))):
continue
... |
'The ECS agent runs on a container and listens to port 51678
We\'ll test the response on / for detection'
| def _detect_agent(self):
| urls = []
ecs_config = self.docker_util.inspect_container('ecs-agent')
ip = ecs_config.get('NetworkSettings', {}).get('IPAddress')
if ip:
ports = ecs_config.get('NetworkSettings', {}).get('Ports')
port = (ports.keys()[0].split('/')[0] if ports else str(ECS_AGENT_DEFAULT_PORT))
ur... |
'Populate the cache of ecs tags. Can be called with skip_known=True
If we just want to update new containers quickly (single task api call)
(because we detected that a new task started for example)'
| def _populate_ecs_tags(self, skip_known=False):
| if (self.agent_url is None):
self.log.warning('ecs-agent not found, skipping task tagging')
return
try:
tasks = requests.get((self.agent_url + ECS_AGENT_TASKS_PATH), timeout=1).json()
for task in tasks.get('Tasks', []):
for container in task.get('Contai... |
'The Nomad agent runs on every node and listens to http port 4646
See https://www.nomadproject.io/docs/http/agent-self.html
We\'ll use the unauthenticated endpoint /v1/agent/self
We don\'t have any envvars or downwards API to help us, so we try
default gw (network=bridge) and localhost (network=host), but can\'t
auto-d... | def _detect_agent(self):
| urls = []
gw = self.docker_util.get_gateway()
if gw:
urls.append((NOMAD_AGENT_URL % gw))
urls.append((NOMAD_AGENT_URL % '127.0.0.1'))
nomad_url = self._try_urls(urls, validation_lambda=NomadUtil.nomad_agent_validation)
if nomad_url:
self.log.debug(('Found Nomad agent at ... |
'Retrieve the actual pid'
| def get_pid(self):
| try:
pf = open(self.get_path())
pid_s = pf.read()
pf.close()
return int(pid_s.strip())
except Exception:
return None
|
'Read the config from docker_daemon.yaml'
| def get_check_config(self):
| from util import check_yaml
from utils.checkfiles import get_conf_path
(init_config, instances) = ({}, [])
try:
conf_path = get_conf_path(CHECK_NAME)
except IOError:
log.debug("Couldn't find docker settings, trying with defaults.")
return (init_config, {})
... |
'Return the `Name` param from `docker info` to use as the hostname
Falls back to the default route.'
| def get_hostname(self, use_default_gw=True, should_resolve=False):
| is_resolvable = (lambda host: socket.gethostbyname(host))
if (self.hostname is not None):
try:
if ((not should_resolve) or is_resolvable(self.hostname)):
return self.hostname
except Exception:
log.debug(("Couldn't resolve cached hostname %s, ... |
'Update docker settings'
| def set_docker_settings(self, init_config, instance):
| self._docker_root = init_config.get('docker_root', '/')
self.settings = {'version': init_config.get('api_version', DEFAULT_VERSION), 'base_url': instance.get('url', ''), 'timeout': int(init_config.get('timeout', DEFAULT_TIMEOUT))}
if init_config.get('tls', False):
client_cert_path = init_config.get(... |
'Find the mount point for a specified cgroup hierarchy.
Works with old style and new style mounts.
An example of what the output of /proc/mounts looks like:
cgroup /sys/fs/cgroup/cpuset cgroup rw,relatime,cpuset 0 0
cgroup /sys/fs/cgroup/cpu cgroup rw,relatime,cpu 0 0
cgroup /sys/fs/cgroup/cpuacct cgroup rw,relatime,cp... | def find_cgroup(self, hierarchy):
| with open(os.path.join(self._docker_root, '/proc/mounts'), 'r') as fp:
mounts = map((lambda x: x.split()), fp.read().splitlines())
cgroup_mounts = filter((lambda x: (x[2] == 'cgroup')), mounts)
if (len(cgroup_mounts) == 0):
raise Exception("Can't find mounted cgroups. If you ... |
'Build sets of include/exclude patters and of all filtered tag names based on these'
| def build_filters(self):
| if (not self._exclude):
return
filtered_tag_names = []
exclude_patterns = []
include_patterns = []
for rule in self._exclude:
exclude_patterns.append(re.compile(rule))
filtered_tag_names.append(rule.split(':')[0])
for rule in self._include:
include_patterns.append... |
'Parse cgroup path.
- If the path is a slice (see https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/Resource_Management_Guide/sec-Default_Cgroup_Hierarchies.html)
we return the path as-is (we still strip out any leading \'/\')
- If \'docker\' is in the path, it can be there once or twice:
/d... | @classmethod
def _parse_subsystem(cls, line):
| if ('.slice' in line[2]):
return line[2].lstrip('/')
i = line[2].rfind('docker')
if (i != (-1)):
return line[2][i:]
elif (line[2][0] == '/'):
return line[2][1:]
else:
return line[2]
|
'Retrives docker_image, image_name and image_tag tags as a list for a
container. If the container or image is invalid, will gracefully
return an empty list'
| def extract_container_tags(self, co):
| tags = []
docker_image = self.image_name_extractor(co)
image_name_array = self.image_tag_extractor(co, 0)
image_tag_array = self.image_tag_extractor(co, 1)
if docker_image:
tags.append(('docker_image:%s' % docker_image))
if (image_name_array and (len(image_name_array) > 0)):
tags... |
'Returns the image name for a container, either directly from the
container\'s Image property or by inspecting the image entity if
the reference is its sha256 sum and not its name.
Result is cached for performance, no invalidation planned as image
churn is low on typical hosts.'
| def image_name_extractor(self, co):
| if ('Image' in co):
image = co.get('Image', '')
if image.startswith('sha256:'):
try:
if (image in self._image_sha_to_name_mapping):
return self._image_sha_to_name_mapping[image]
else:
image_spec = self.client.inspect... |
'Matches /proc/$PID/net/route and docker inspect to map interface names to docker network name.
Raises an exception on error (dict lookup or file parsing), to be caught by the using method'
| @classmethod
def get_container_network_mapping(cls, container):
| try:
proc_net_route_file = os.path.join(container['_proc_root'], 'net/route')
docker_gateways = {}
for (netname, netconf) in container['NetworkSettings']['Networks'].iteritems():
if ((netname == 'host') or (netconf.get(u'Gateway') == '')):
log.debug(('Empty net... |
'Requests docker inspect for one container. This is a costly operation!
:param co_id: container id
:return: dict from docker-py'
| def inspect_container(self, co_id):
| return self.client.inspect_container(co_id)
|
'Kill the process. It will be eventually restarted.'
| @staticmethod
def self_destruct(signum, frame):
| try:
log.error('Self-destructing...')
log.error(traceback.format_exc())
finally:
os.kill(os.getpid(), signal.SIGKILL)
|
'Detect suspicious high activity, i.e. the number of resets exceeds the maximum limit set
on the watchdog timeframe.
Flush old activity history'
| def _is_frenetic(self):
| now = time.time()
while (self._restarts and (self._restarts[0] < (now - self._RESTART_TIMEFRAME))):
self._restarts.popleft()
return (len(self._restarts) > self._max_resets)
|
'Reset the watchdog state, i.e.
* re-arm alarm signal
* (optional) save reset history, flush old entries and check frequency'
| def reset(self):
| if self._max_resets:
self._restarts.append(time.time())
if self._is_frenetic():
self.destruct()
log.debug('Resetting watchdog for %d', self._duration)
signal.alarm(self._duration)
|
'Retrieve instance\'s IAM role.
Raise `NoIAMRole` when unavailable.'
| @staticmethod
def get_iam_role():
| try:
r = requests.get((EC2.METADATA_URL_BASE + '/iam/security-credentials/'))
r.raise_for_status()
return r.content.strip()
except requests.exceptions.HTTPError as e:
log.debug('Collecting IAM Role failed %s', str(e))
if (e.response.status_code == 404):
... |
'Retrieve AWS EC2 tags.'
| @staticmethod
def get_tags(agentConfig):
| if (not agentConfig['collect_instance_metadata']):
log.info('Instance metadata collection is disabled. Not collecting it.')
return []
EC2_tags = []
try:
iam_role = EC2.get_iam_role()
iam_url = ((EC2.METADATA_URL_BASE + '/iam/security-credentials/') + unic... |
'Use the ec2 http service to introspect the instance. This adds latency if not running on EC2'
| @staticmethod
def get_metadata(agentConfig):
| if (not agentConfig['collect_instance_metadata']):
log.info('Instance metadata collection is disabled. Not collecting it.')
return {}
for k in ('instance-id', 'hostname', 'local-hostname', 'public-hostname', 'ami-id', 'local-ipv4', 'public-keys/', 'public-ipv4', 'reservation... |
'Create a \'special\' file, which acts as a trigger to exit JMXFetch.
Note: Windows only'
| @classmethod
def write_exit_file(cls):
| open(os.path.join(cls._get_dir(), cls._JMX_EXIT_FILE), 'a').close()
|
'Removes JMX status files'
| @classmethod
def clean_status_file(cls):
| try:
os.remove(os.path.join(cls._get_dir(), cls._STATUS_FILE))
except OSError:
pass
try:
os.remove(os.path.join(cls._get_dir(), cls._PYTHON_STATUS_FILE))
except OSError:
pass
|
'Remove exit file trigger -may not exist-.
Note: Windows only'
| @classmethod
def clean_exit_file(cls):
| try:
os.remove(os.path.join(cls._get_dir(), cls._JMX_EXIT_FILE))
except OSError:
pass
|
'Retrieves the running JMX checks based on the {tmp}/jmx_status.yaml file
updated by JMXFetch (and the only communication channel between JMXFetch
and the collector since JMXFetch).'
| @classmethod
def get_jmx_appnames(cls):
| check_names = []
jmx_status_path = os.path.join(cls._get_dir(), cls._STATUS_FILE)
if os.path.exists(jmx_status_path):
jmx_checks = yaml.load(file(jmx_status_path)).get('checks', {})
check_names = [name for name in jmx_checks.get('initialized_checks', {}).iterkeys()]
return check_names
|
'Return true if this is a BSD like operating system.'
| @staticmethod
def is_bsd(name=None):
| name = (name or sys.platform)
return (Platform.is_darwin(name) or Platform.is_freebsd(name))
|
'Return true if the platform is a unix, False otherwise.'
| @staticmethod
def is_unix(name=None):
| name = (name or sys.platform)
return (Platform.is_darwin() or Platform.is_linux() or Platform.is_freebsd())
|
'Initial Setup'
| def setUp(self):
| if (not self.prepared):
Object.objects.all().delete()
User.objects.all().delete()
try:
self.group = Group.objects.get(name='test')
except Group.DoesNotExist:
Group.objects.all().delete()
self.group = Group(name='test')
self.group.save()... |
'Test index page at /api/finance/currencies'
| def test_unauthenticated_access(self):
| response = self.client.get('/api/finance/currencies')
self.assertEquals(response.status_code, 401)
|
'Test index page api/finance/currencies'
| def test_get_currencies_list(self):
| response = self.client.get(path=reverse('api_finance_currencies'), **self.authentication_headers)
self.assertEquals(response.status_code, 200)
|
'Test index page api/finance/taxes'
| def test_get_taxes_list(self):
| response = self.client.get(path=reverse('api_finance_taxes'), **self.authentication_headers)
self.assertEquals(response.status_code, 200)
|
'Test index page api/finance/categories'
| def test_get_categories_list(self):
| response = self.client.get(path=reverse('api_finance_categories'), **self.authentication_headers)
self.assertEquals(response.status_code, 200)
|
'Test index page api/finance/assets'
| def test_get_assets_list(self):
| response = self.client.get(path=reverse('api_finance_assets'), **self.authentication_headers)
self.assertEquals(response.status_code, 200)
|
'Test index page api/finance/accounts'
| def test_get_accounts_list(self):
| response = self.client.get(path=reverse('api_finance_accounts'), **self.authentication_headers)
self.assertEquals(response.status_code, 200)
|
'Test index page api/finance/equities'
| def test_get_equities_list(self):
| response = self.client.get(path=reverse('api_finance_equities'), **self.authentication_headers)
self.assertEquals(response.status_code, 200)
|
'Test index page api/finance/liabilities'
| def test_get_liabilities_list(self):
| response = self.client.get(path=reverse('api_finance_liabilities'), **self.authentication_headers)
self.assertEquals(response.status_code, 200)
|
'Test index page api/finance/transactions'
| def test_get_transactions_list(self):
| response = self.client.get(path=reverse('api_finance_transactions'), **self.authentication_headers)
self.assertEquals(response.status_code, 200)
|
'Check Depreciate'
| def check_depreciate(self):
| if (self.purchase_date and (self.endlife_value is not None) and self.initial_value and self.lifetime):
return True
else:
return False
|
'Get Depreciation'
| def get_depreciation(self):
| if self.check_depreciate():
self.set_rate()
from_purchase = (datetime.date(datetime.now()) - self.purchase_date)
days_from_purchase = from_purchase.days
if (days_from_purchase >= (self.lifetime * 365)):
return (self.initial_value - self.endlife_value).quantize(Decimal('.0... |
'Set Rate'
| def set_rate(self):
| if (self.depreciation_type == 'straight'):
if self.lifetime:
self.depreciation_rate = (100 / self.lifetime).quantize(Decimal('00.01'), rounding=ROUND_UP)
elif (self.depreciation_type == 'reducing'):
if (not self.check_depreciate()):
return Decimal('0.00')
self.dep... |
'Set current value'
| def set_current_value(self):
| if (not self.check_depreciate()):
return self.initial_value
self.current_value = (self.initial_value - self.get_depreciation())
self.save()
return self.current_value
|
'Returns absolute URL'
| def get_absolute_url(self):
| try:
return reverse('finance_asset_view', args=[self.id])
except Exception:
return ''
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.