Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Move probes in common over to context manager and python3 #89

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 23 additions & 21 deletions common/check_expired_dids
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#!/usr/bin/env python
#!/usr/bin/env python3
# Copyright European Organization for Nuclear Research (CERN) 2013
#
# Licensed under the Apache License, Version 2.0 (the "License");
Expand All @@ -8,7 +8,7 @@
# Authors:
# - Vincent Garonne, <[email protected]>, 2013
# - Thomas Beermann, <[email protected]>, 2019
# - Eric Vaandering <[email protected]>, 2020-2021
# - Eric Vaandering <[email protected]>, 2020-2022

"""
Probe to check the backlog of expired dids.
Expand All @@ -17,42 +17,44 @@ from __future__ import print_function

import sys
import traceback


from datetime import datetime
from rucio.core import monitor

from prometheus_client import CollectorRegistry, Gauge, push_to_gateway
from rucio.common.config import config_get

from rucio.db.sqla import models
from rucio.db.sqla.session import get_session
from rucio.db.sqla.util import get_count


PrometheusPusher = common.PrometheusPusher

from utils.common import probe_metrics


# Exit statuses
OK, WARNING, CRITICAL, UNKNOWN = 0, 1, 2, 3

PROM_SERVERS = config_get('monitor', 'prometheus_servers', raise_exception=False, default='')
if PROM_SERVERS != '':
PROM_SERVERS = PROM_SERVERS.split(',')

if __name__ == "__main__":
try:
registry = CollectorRegistry()
session = get_session()
query = session.query(models.DataIdentifier.scope).filter(models.DataIdentifier.expired_at.isnot(None),
models.DataIdentifier.expired_at < datetime.utcnow())
result = get_count(query)
# Possible check against a threshold. If result > max_value then sys.exit(CRITICAL)
probe_metrics.gauge(name='undertaker.expired_dids').set(result)
Gauge('undertaker_expired_dids', '', registry=registry).set(result)

if len(PROM_SERVERS):
for server in PROM_SERVERS:
try:
push_to_gateway(server.strip(), job='check_expired_dids', registry=registry)
except:
continue

print(result)
with PrometheusPusher(registry, job_name='check_expired_dids') as prometheus_config:
prefix: str = prometheus_config['prefix']
query = (session.query(models.DataIdentifier.scope)
.filter(models.DataIdentifier.expired_at.isnot(None),
models.DataIdentifier.expired_at < datetime.utcnow()))
result = get_count(query)
# Possible check against a threshold. If result > max_value then sys.exit(CRITICAL)

monitor.record_gauge('undertaker.expired_dids', value=result)
Gauge(prefix + 'undertaker_expired_dids', '', registry=registry).set(result)

print(result)

except:
print(traceback.format_exc())
sys.exit(UNKNOWN)
Expand Down
178 changes: 87 additions & 91 deletions common/check_fts_backlog
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#!/usr/bin/env python
#!/usr/bin/env python3
"""
Copyright European Organization for Nuclear Research (CERN) 2013

Expand All @@ -9,27 +9,26 @@
Authors:
- Cedric Serfon, <[email protected]>, 2014-2018
- Mario Lassnig, <[email protected]>, 2015
- Eric Vaandering, <[email protected]>, 2019-2021
- Eric Vaandering, <[email protected]>, 2019-2022
- Thomas Beermann, <[email protected]>, 2019
"""
from __future__ import print_function

import os
import sys
from urllib.parse import urlparse

import requests
import urllib3
try:
from urlparse import urlparse
except ImportError:
from urllib.parse import urlparse

from prometheus_client import CollectorRegistry, Gauge, push_to_gateway
from prometheus_client import CollectorRegistry, Gauge
from rucio.common.config import config_get, config_get_bool
from rucio.core import monitor
from rucio.core.distance import update_distances
from rucio.db.sqla.session import BASE, get_session

from utils.common import probe_metrics
from utils import common

PrometheusPusher = common.PrometheusPusher


OK, WARNING, CRITICAL, UNKNOWN = 0, 1, 2, 3

Expand All @@ -40,10 +39,6 @@ if BASE.metadata.schema:
else:
schema = ''

PROM_SERVERS = config_get('monitor', 'prometheus_servers', raise_exception=False, default='')
if PROM_SERVERS != '':
PROM_SERVERS = PROM_SERVERS.split(',')

if __name__ == "__main__":

se_matrix = {}
Expand Down Expand Up @@ -83,86 +78,87 @@ if __name__ == "__main__":
UPDATE_DIST = True

registry = CollectorRegistry()
g = Gauge('fts_submitted', '', labelnames=('hostname',), registry=registry)
errmsg = ''
for ftshost in FTSHOSTS.split(','):
print("=== %s ===" % ftshost)
parsed_url = urlparse(ftshost)
scheme, hostname, port = parsed_url.scheme, parsed_url.hostname, parsed_url.port
retvalue = CRITICAL
url = '%s/fts3/ftsmon/overview?dest_se=&source_se=&time_window=1&vo=%s' % (ftshost, VO)
busy_channels = []
busylimit = 5000
for attempt in range(0, 5):
result = None
try:
result = requests.get(url, verify=False, cert=(PROXY, PROXY))
res = result.json()
for channel in res['overview']['items']:
src = channel['source_se']
dst = channel['dest_se']
if (src, dst) not in se_matrix:
se_matrix[(src, dst)] = {'active': 0, 'submitted': 0, 'finished': 0, 'failed': 0,
'transfer_speed': 0, 'mbps_link': 0}
for state in ['submitted', 'active', 'finished', 'failed']:
with PrometheusPusher(registry, job_name='check_fts_backlog') as prometheus_config:
prefix: str = prometheus_config['prefix']
extra_prom_labels = prometheus_config['labels']
labelnames = ['hostname']
labelnames.extend(extra_prom_labels.keys())
g = Gauge(prefix + 'fts_submitted', '', labelnames=labelnames, registry=registry)

errmsg = ''
for ftshost in FTSHOSTS.split(','):
print("=== %s ===" % ftshost)
parsed_url = urlparse(ftshost)
scheme, hostname, port = parsed_url.scheme, parsed_url.hostname, parsed_url.port
retvalue = CRITICAL
url = '%s/fts3/ftsmon/overview?dest_se=&source_se=&time_window=1&vo=%s' % (ftshost, VO)
busy_channels = []
busylimit = 5000
for attempt in range(0, 5):
result = None
try:
result = requests.get(url, verify=False, cert=(PROXY, PROXY))
res = result.json()
for channel in res['overview']['items']:
src = channel['source_se']
dst = channel['dest_se']
if (src, dst) not in se_matrix:
se_matrix[(src, dst)] = {'active': 0, 'submitted': 0, 'finished': 0, 'failed': 0,
'transfer_speed': 0, 'mbps_link': 0}
for state in ['submitted', 'active', 'finished', 'failed']:
try:
se_matrix[(src, dst)][state] += channel[state]
except Exception:
pass
try:
se_matrix[(src, dst)][state] += channel[state]
se_matrix[(src, dst)]['transfer_speed'] += channel['current']
se_matrix[(src, dst)]['mbps_link'] += channel['current']
except Exception:
pass
try:
se_matrix[(src, dst)]['transfer_speed'] += channel['current']
se_matrix[(src, dst)]['mbps_link'] += channel['current']
except Exception:
pass
if CHECK_BUSY and 'submitted' in channel and channel['submitted'] >= busylimit:
url_activities = '%s/fts3/ftsmon/config/activities/%s?source_se=%s&dest_se=%s' % (ftshost, VO,
src, dst)
activities = {}
try:
s = requests.get(url_activities, verify=False, cert=(PROXY, PROXY))
for key, val in s.json().items():
activities[key] = val['SUBMITTED']
except Exception as error:
pass
busy_channels.append({'src': src, 'dst': dst, 'submitted': channel['submitted'],
'activities': activities})
summary = res['summary']
hostname = hostname.replace('.', '_')
print('%s : Submitted : %s' % (hostname, summary['submitted']))
print('%s : Active : %s' % (hostname, summary['active']))
print('%s : Staging : %s' % (hostname, summary['staging']))
print('%s : Started : %s' % (hostname, summary['started']))
if busy_channels != []:
print('Busy channels (>%s submitted):' % busylimit)
for bc in busy_channels:
activities_str = ", ".join([("%s: %s" % (key, val)) for key, val in bc['activities'].items()])
print(' %s to %s : %s submitted jobs (%s)' % (bc['src'], bc['dst'], bc['submitted'],
str(activities_str)))
probe_metrics.gauge('fts3.{hostname}.submitted').labels(hostname=hostname).set(summary['submitted']
+ summary['active']
+ summary['staging']
+ summary['started'])

g.labels(**{'hostname': hostname}).set((summary['submitted'] + summary['active'] + summary['staging'] + summary['started']))
retvalue = OK
break
except Exception as error:
retvalue = CRITICAL
if result and result.status_code:
errmsg = 'Error when trying to get info from %s : HTTP status code %s. [%s]' % (
ftshost, str(result.status_code), str(error))
else:
errmsg = 'Error when trying to get info from %s. %s' % (ftshost, str(error))
if retvalue == CRITICAL:
print("All attempts failed. %s" % errmsg)
WORST_RETVALUE = max(retvalue, WORST_RETVALUE)

if len(PROM_SERVERS):
for server in PROM_SERVERS:
try:
push_to_gateway(server.strip(), job='check_fts_backlog', registry=registry)
except:
continue

if CHECK_BUSY and 'submitted' in channel and channel['submitted'] >= busylimit:
url_activities = '%s/fts3/ftsmon/config/activities/%s?source_se=%s&dest_se=%s' % (
ftshost, VO,
src, dst)
activities = {}
try:
s = requests.get(url_activities, verify=False, cert=(PROXY, PROXY))
for key, val in s.json().items():
activities[key] = val['SUBMITTED']
except Exception as error:
pass
busy_channels.append({'src': src, 'dst': dst, 'submitted': channel['submitted'],
'activities': activities})
summary = res['summary']
hostname = hostname.replace('.', '_')
print('%s : Submitted : %s' % (hostname, summary['submitted']))
print('%s : Active : %s' % (hostname, summary['active']))
print('%s : Staging : %s' % (hostname, summary['staging']))
print('%s : Started : %s' % (hostname, summary['started']))
if busy_channels != []:
print('Busy channels (>%s submitted):' % busylimit)
for bc in busy_channels:
activities_str = ", ".join([("%s: %s" % (key, val)) for key, val in bc['activities'].items()])
print(' %s to %s : %s submitted jobs (%s)' % (bc['src'], bc['dst'], bc['submitted'],
str(activities_str)))
monitor.record_gauge('fts3.%s.submitted' % hostname,
value=(summary['submitted'] + summary['active']
+ summary['staging'] + summary['started']))
g.labels(**{'hostname': hostname}).set(
(summary['submitted'] + summary['active'] + summary['staging'] + summary['started']))
retvalue = OK
break
except Exception as error:
retvalue = CRITICAL
if result and result.status_code:
errmsg = 'Error when trying to get info from %s : HTTP status code %s. [%s]' % (
ftshost, str(result.status_code), str(error))
else:
errmsg = 'Error when trying to get info from %s. %s' % (ftshost, str(error))
if retvalue == CRITICAL:
print("All attempts failed. %s" % errmsg)
WORST_RETVALUE = max(retvalue, WORST_RETVALUE)


if not UPDATE_DIST:
sys.exit(WORST_RETVALUE)
Expand Down
36 changes: 16 additions & 20 deletions common/check_messages_to_submit
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#!/usr/bin/env python
#!/usr/bin/env python3
# Copyright European Organization for Nuclear Research (CERN) 2013
#
# Licensed under the Apache License, Version 2.0 (the "License");
Expand All @@ -8,19 +8,23 @@
# Authors:
# - Mario Lassnig, <[email protected]>, 2013-2014
# - Thomas Beermann, <[email protected]>, 2019
# - Eric Vaandering <[email protected]>, 2022

"""
Probe to check the queues of messages to submit by Hermes to the broker
"""
from __future__ import print_function

import sys

from prometheus_client import CollectorRegistry, Gauge, push_to_gateway
from rucio.common.config import config_get

from prometheus_client import CollectorRegistry, Gauge
from rucio.core import monitor
from rucio.db.sqla.session import BASE, get_session

from utils.common import probe_metrics
from utils import common

PrometheusPusher = common.PrometheusPusher


# Exit statuses
OK, WARNING, CRITICAL, UNKNOWN = 0, 1, 2, 3
Expand All @@ -32,25 +36,17 @@ else:

queue_sql = """SELECT COUNT(*) FROM {schema}messages""".format(schema=schema)

PROM_SERVERS = config_get('monitor', 'prometheus_servers', raise_exception=False, default='')
if PROM_SERVERS != '':
PROM_SERVERS = PROM_SERVERS.split(',')

if __name__ == "__main__":
try:
registry = CollectorRegistry()
session = get_session()
result = session.execute(queue_sql).fetchall()
print('queues.messages %s' % result[0][0])
probe_metrics.gauge(name='queues.messages').set(result[0][0])
Gauge('hermes_queues_messages', '', registry=registry).set(result[0][0])

if len(PROM_SERVERS):
for server in PROM_SERVERS:
try:
push_to_gateway(server.strip(), job='check_messages_to_submit', registry=registry)
except:
continue
with PrometheusPusher(registry, job_name='check_messages_to_submit') as prometheus_config:
prefix: str = prometheus_config['prefix']
result = session.execute(queue_sql).fetchall()
print('queues.messages %s' % result[0][0])
monitor.record_gauge(stat='queues.messages', value=result[0][0])
Gauge(prefix + 'hermes_queues_messages', '', registry=registry).set(result[0][0])


if result[0][0] > 100000:
sys.exit(WARNING)
Expand Down
Loading