File: //usr/lib/python2.7/site-packages/lap/reseller_ips.py
import yaml
import httplib
import urllib
import urllib2
import json
import time
class CASHandler(urllib2.HTTPHandler):
# this is an auth handler, do it first
handler_order = 1
ticket_url = "/v1/tickets"
def __init__(self, cas_endpoint, username, password, service):
urllib2.HTTPHandler.__init__(self)
self.cas_endpoint = cas_endpoint
self.service = service
self.http_handler = urllib2.HTTPHandler()
params = urllib.urlencode({"username": username,
"password": password})
self.headers = {"Accept": "*/*",
"Content-type": "application/x-www-form-urlencoded",}
conn = httplib.HTTPSConnection(cas_endpoint)
conn.request("POST", CASHandler.ticket_url, params, self.headers)
resp = conn.getresponse()
if resp.status != 201:
raise Exception("{0}: {1}".format(resp.status, resp.reason))
self.location = resp.getheader('location')
self.tgt = self.location.split("/")[-1]
def http_open(self, req):
# logging.error("{}".format(req.get_selector()))
conn = httplib.HTTPSConnection(self.cas_endpoint)
conn.request("POST",
CASHandler.ticket_url + '/' + self.tgt,
"service=" + self.service,
self.headers)
resp = conn.getresponse()
st = resp.read()
# logging.error("ST: {}".format(st))
req.add_header("Service-Ticket", st)
req.timeout = 5
return self.do_open(httplib.HTTPConnection, req)
def copen(opener, site, path):
retries = 3
url = site + path
for _ in range(0, retries):
try:
ret = opener.open(url)
return json.load(ret)
except Exception, e:
print url, str(e)
time.sleep(1)
raise Exception("Number of retries({0}) exceed".format(retries))
def getconfigs():
configfile = "/var/www/reseller-provisioning/config/cegonha.yml"
config = yaml.load(open(configfile))
cegonha = config["production"]["connection_url"]
cas = config["production"]["cas_url"].replace("https://", '')
service = config["production"]["service"]
username = config["production"]["auth"]["user"]
password = config["production"]["auth"]["pass"]
confcegonha = "/var/www/reseller-provisioning/config/cegonha_openstack.yml"
config_cegonha = yaml.load(open(confcegonha))
vlan_id = config_cegonha["production"]["vlan_name"]
range_cidr = config_cegonha["production"]["range_cidr"]
return (cegonha, cas, username, password, service, vlan_id, range_cidr)
def getnumberofavaliableips(cegonha, cas, username, password, service, vlan_id, range_cidr):
handler = CASHandler(cas, username, password, service)
opener = urllib2.build_opener(handler)
ranges = copen(opener, cegonha, "/vlans/{0}/ip_ranges.json".format(vlan_id))
for i in ranges:
if i["ip_range"]["name"] == range_cidr:
range_id = i["ip_range"]["id"]
break
path = "/vlans/{0}/ip_ranges/{1}.json".format(vlan_id, range_id)
_range = copen(opener, cegonha, path)
return int(_range["ip_range"]["total_available_ips"])
if __name__ == "__main__":
confs = getconfigs()
ips = getnumberofavaliableips(*confs)
print ips
def __run__(params):
confs = getconfigs()
try:
ips = getnumberofavaliableips(*confs)
if ips < int(params.get("error")):
return [2, "CRITICAL: {0} ips disponiveis. Seguir procedimento {1}".format(ips, params.get("url"))]
elif ips < int(params.get("warning")):
return [1, "WARNING: {0} ips disponiveis. Seguir procedimento {1}".format(ips, params.get("url"))]
else:
return [0, "OK: {0} ips disponiveis".format(ips)]
except Exception as e:
return [2, "CRITICAL: {0}".format(str(e).replace('\n', ' '))]
return [2, "CRITICAL: This alarm is broken, shouldn't reach here"]