Skip to content

Instantly share code, notes, and snippets.

@wolfdancer
Created November 25, 2014 06:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wolfdancer/9daffeaf4abc803780bb to your computer and use it in GitHub Desktop.
Save wolfdancer/9daffeaf4abc803780bb to your computer and use it in GitHub Desktop.
import monitornig configuration
#!/usr/bin/env python3
"""
This script will load the monitoring configuration yaml file for the server-side configuratino,
hit the monitoring API to create the checks and alarms
To use:
./import.py --user <username> --api-key <api key> --entity <entity-id> --file <yaml file>
"""
import argparse
from urllib.request import urlopen, Request, HTTPError
import sys
import re
from datetime import datetime
import requests
import json
import yaml
from collections import OrderedDict
class literal(str): pass
def literal_presenter(dumper, data):
return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|')
yaml.add_representer(literal, literal_presenter)
def ordered_dict_presenter(dumper, data):
return dumper.represent_dict(data.items())
yaml.add_representer(OrderedDict, ordered_dict_presenter)
monitoring_api = 'https://monitoring.api.rackspacecloud.com/v1.0/'
def login(user, key):
auth_payload = {
'auth':{
'RAX-KSKEY:apiKeyCredentials':{
'username': user,
'apiKey': key
}
}
}
try:
auth_req = Request(args.auth_uri)
auth_req.add_header('Content-type', 'application/json')
auth_resp = json.loads(urlopen(auth_req, json.dumps(auth_payload).encode("utf8")).read().decode("utf8"))
except HTTPError:
print('status err Unable to authenticate user {0}'.format(args.user))
sys.exit(1)
else:
auth_token = auth_resp['access']['token']['id']
tenant_id = auth_resp['access']['token']['tenant']['id']
return auth_token, tenant_id
def to_json(data):
return json.dumps(data, sort_keys="True", indent=2, separators=(',', ': '))
def call_api(api, auth_token, tenant_id, payload):
url = "{}{}/{}".format(monitoring_api, tenant_id, api)
request = Request(url)
request.add_header('X-Auth-Token', auth_token)
request.add_header('Content-Type', 'application/json')
print("post {}".format(url))
json_data = to_json(payload)
try:
response = urlopen(request, json_data.encode('utf8'))
return response.info().get("X-Object-ID")
except HTTPError as err:
print("{}:{}".format(err.code, err.reason))
print(err.read().decode('utf8'))
sys.exit(1)
def to_yaml(content):
return yaml.dump(content, default_flow_style=False)
def main():
auth_token, tenant_id = login(args.user, args.api_key)
print("X-Auth-Token {}".format(auth_token))
entity_id = args.entity_id
filename = args.file
content = yaml.load(open(filename, 'r'))
alarms = content.pop('alarms')
check_id = call_api("entities/{}/checks".format(entity_id), auth_token, tenant_id, content)
print("check created: {}".format(check_id))
for key, alarm in alarms.items():
alarm["check_id"] = check_id
print("alarm created: {}".format(call_api("entities/{}/alarms".format(entity_id), auth_token, tenant_id, alarm)))
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Monitornig host info')
parser.add_argument('--user', dest='user', action='store',
required=True, help='The Rackspace user')
parser.add_argument('--api-key', dest='api_key', action='store',
required=True, help='The Rackspace API key')
parser.add_argument('--entity-id', dest='entity_id', action='store',
required=True, help='The entity ID')
parser.add_argument('--file', dest='file', action='store',
required=True, help='The yaml file')
parser.add_argument('--auth-uri', dest='auth_uri', action='store',
default='https://identity.api.rackspacecloud.com/v2.0/tokens',
help='The Rackspace Identity token endpoint')
args = parser.parse_args()
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment