SLA plugin: template integration with SLA Dashboard
[myslice.git] / sla / slaclient / restclient.py
index cdada8a..4b8614b 100755 (executable)
@@ -3,6 +3,7 @@
 import requests
 
 from requests.auth import HTTPBasicAuth
+from myslice.settings import logger
 
 import xmlconverter
 import wsag_model
@@ -12,13 +13,13 @@ from django.conf import settings
 
 """REST client to SLA Manager.
 
-Contains a generic rest client and wrappers over this generic client 
+Contains a generic rest client and wrappers over this generic client
 for each resource.
 
 Each resource client implements business-like() functions, but
 returns a tuple (output, requests.Response)
 
-The resource clients are initialized with the rooturl and a path, which 
+The resource clients are initialized with the rooturl and a path, which
 are combined to build the resource url. The path is defaulted to the known
 resource path. So, for example, to create a agreements client:
 
@@ -32,21 +33,19 @@ c = restclient.Factory.agreements()
 
 """
 
-_PROVIDERS_PATH = "providerso"
-_AGREEMENTS_PATH = "agreementso"
-_TEMPLATES_PATH = "templateso"
-_VIOLATIONS_PATH = "violationso"
+_PROVIDERS_PATH = "providers"
+_AGREEMENTS_PATH = "agreements"
+_TEMPLATES_PATH = "templates"
+_VIOLATIONS_PATH = "violations"
 _ENFORCEMENTJOBS_PATH = "enforcements"
 
-rooturl = settings.SLA_MANAGER_URL
+rooturl = settings.SLA_COLLECTOR_URL
 
-# SLA_MANAGER_USER = "normal_user"
-# SLA_MANAGER_PASSWORD = "password"
 
 class Factory(object):
     @staticmethod
     def agreements():
-        """Returns aREST client for Agreements
+        """Returns a REST client for Agreements
 
         :rtype : Agreements
          """
@@ -54,7 +53,7 @@ class Factory(object):
 
     @staticmethod
     def providers():
-        """Returns aREST client for Providers
+        """Returns a REST client for Providers
 
         :rtype : Providers
         """
@@ -62,7 +61,7 @@ class Factory(object):
 
     @staticmethod
     def violations():
-        """Returns aREST client for Violations
+        """Returns a REST client for Violations
 
         :rtype : Violations
         """
@@ -70,7 +69,7 @@ class Factory(object):
 
     @staticmethod
     def templates():
-        """Returns aREST client for Violations
+        """Returns a REST client for Violations
 
         :rtype : Violations
         """
@@ -78,12 +77,13 @@ class Factory(object):
 
     @staticmethod
     def enforcements():
-        """Returns aREST client for Enforcements jobs
+        """Returns a REST client for Enforcements jobs
 
         :rtype : Enforcements
         """
         return Enforcements(rooturl)
 
+
 class Client(object):
 
     def __init__(self, root_url):
@@ -104,21 +104,36 @@ class Client(object):
         Returns a requests.Response
 
         :rtype : request.Response
-        :param str path: remaining path from root url; 
+        :param str path: remaining path from root url;
             empty if desired path equal to rooturl.
         :param kwargs: arguments to requests.get
-        
-        Example: 
+
+        Example:
             c = Client("http://localhost:8080/service")
             c.get("/resource", headers = { "accept": "application/json" })
         """
-        url = _buildpath_(self.rooturl, path)
-        kwargs["auth"] = HTTPBasicAuth(settings.SLA_MANAGER_USER, settings.SLA_MANAGER_PASSWORD)
-        result = requests.get(url, **kwargs)
-        print "GET {} {} {}".format(
-            result.url, result.status_code, result.text[0:70])
+        url = _buildpath(self.rooturl, path)
+        if "testbed" in kwargs:
+            url = url + "?testbed=" + kwargs["testbed"]
+
+        if "headers" not in kwargs:
+            kwargs["headers"] = {"accept": "application/xml"}
+
+
+        kwargs["auth"] = HTTPBasicAuth(settings.SLA_COLLECTOR_USER,
+                                       settings.SLA_COLLECTOR_PASSWORD)
+
+        # for key, values in kwargs.iteritems():
+        #     print key, values
+
+        result = requests.get(url, verify=False, **kwargs)
+        logger.debug('SLA GET {} - result: {}'.format(result.url, result.status_code))
+        # print "GET {} {} {}".format(
+        #     result.url, result.status_code, result.text[0:70])
+        # print result.encoding
+
         return result
-    
+
     def post(self, path, data=None, **kwargs):
         """Just a wrapper over request.post, just in case
 
@@ -138,16 +153,26 @@ class Client(object):
                 }
             )
         """
-        url = _buildpath_(self.rooturl, path)
-        kwargs["auth"] = HTTPBasicAuth(settings.SLA_MANAGER_USER, settings.SLA_MANAGER_PASSWORD)
+        url = _buildpath(self.rooturl, path)
+
+        if "testbed" in kwargs:
+            url = url + "?testbed=" + kwargs["testbed"]
+            del kwargs["testbed"]
+
+        if "headers" not in kwargs:
+            kwargs["headers"] = {"accept": "application/xml",
+                                 "content-type": "application/xml"}
+
+        kwargs["auth"] = HTTPBasicAuth(settings.SLA_COLLECTOR_USER,
+                                      settings.SLA_COLLECTOR_PASSWORD)
+
         result = requests.post(url, data, **kwargs)
         location = result.headers["location"] \
             if "location" in result.headers else "<null>"
-        print "POST {} {} Location: {}".format(
+        print "POST {} {} Location: {}".format(
             result.url, result.status_code, location)
         return result
 
-    
 
 class _Resource(object):
 
@@ -183,7 +208,7 @@ class _Resource(object):
 
         content_type = r.headers.get('content-type', '')
 
-        print("content-type = " + content_type)
+        #print("content-type = " + content_type)
         if content_type == 'application/json':
             result = r.json()
         elif content_type == 'application/xml':
@@ -201,18 +226,19 @@ class _Resource(object):
         resources = self._processresult(r, self.listconverter)
         return resources, r
 
-    def getbyid(self, id):
+    def getbyid(self, id, params):
         """Get resource 'id'"""
-        r = self.client.get(id)
+        r = self.client.get(id, params=params)
         resource = _Resource._processresult(r, self.converter)
         return resource, r
 
-    def get(self, params):
+    def get(self, path="", params={}):
         """Generic query over resource: GET /resource?q1=v1&q2=v2...
 
         :param dict[str,str] params: values to pass as get parameters
         """
-        r = self.client.get("", params=params)
+
+        r = self.client.get(path, params=params)
         resources = self._processresult(r, self.listconverter)
         return resources, r
 
@@ -238,9 +264,9 @@ class Agreements(object):
 
         The final url to the resource is root_url + "/" + path
         """
-        resourceurl = _buildpath_(root_url, path)
-        converter = xmlconverter.AgreementConverter()
-        self.res = _Resource(resourceurl, converter)
+        self.resourceurl = _buildpath(root_url, path)
+        self.converter = xmlconverter.AgreementConverter()
+        self.res = _Resource(self.resourceurl, self.converter)
 
     def getall(self):
         """
@@ -271,25 +297,38 @@ class Agreements(object):
         """
         return self.res.get(dict(providerId=providerid))
 
-    def getstatus(self, agreementid):
+    def getstatus(self, agreementid, testbed):
         """Get guarantee status of an agreement
 
         :param str agreementid :
         :rtype : wsag_model.AgreementStatus
         """
-        path = _buildpath_(agreementid, "guaranteestatus")
-        r = self.res.client.get(path, headers={'accept': 'application/json'})
+        # path = _buildpath(_AGREEMENTS_PATH, agreementid, "guaranteestatus")
+        path = _buildpath(agreementid, "guaranteestatus")
+        r = self.res.client.get(path, headers={'accept': 'application/json'},
+                                params={'testbed': testbed})
+
         json_obj = r.json()
         status = wsag_model.AgreementStatus.json_decode(json_obj)
 
         return status, r
-    
-    def create(self, agreement):
+
+    def getbyslice(self, slicename):
+        """Get the agreements corresponding to a slice
+
+        :rtype : list[wsag_model.Agreement]
+        """
+        self.resourceurl = _buildpath(rooturl, 'slice')
+        self.res = _Resource(self.resourceurl, self.converter)
+        return self.res.get(slicename)
+
+    def create(self, agreement, testbed):
         """Create a new agreement
 
         :param str agreement: sla template in ws-agreement format.
         """
-        return self.res.create(agreement)
+        return self.res.create(agreement, params={'testbed': testbed})
+
 
 class Templates(object):
 
@@ -300,23 +339,23 @@ class Templates(object):
 
         The final url to the resource is root_url + "/" + path
         """
-        resourceurl = _buildpath_(root_url, path)
+        resourceurl = _buildpath(root_url, path)
         converter = xmlconverter.AgreementConverter()
         self.res = _Resource(resourceurl, converter)
 
-    def getall(self):
+    def getall(self, provider_id):
         """ Get all templates
 
         :rtype : list[wsag_model.Template]
         """
-        return self.res.getall()
+        return self.res.get(path="", params={"testbed": provider_id})
 
     def getbyid(self, provider_id):
         """Get a template
 
         :rtype: wsag_model.Template
         """
-        return self.res.getbyid(provider_id)
+        return self.res.getbyid(provider_id, {"testbed": provider_id})
 
     def create(self, template):
         """Create a new template
@@ -325,6 +364,7 @@ class Templates(object):
         """
         self.res.create(template)
 
+
 class Providers(object):
 
     def __init__(self, root_url, path=_PROVIDERS_PATH):
@@ -334,7 +374,7 @@ class Providers(object):
 
         The final url to the resource is root_url + "/" + path
         """
-        resourceurl = _buildpath_(root_url, path)
+        resourceurl = _buildpath(root_url, path)
         converter = xmlconverter.ProviderConverter()
         self.res = _Resource(resourceurl, converter)
 
@@ -360,6 +400,7 @@ class Providers(object):
         body = provider.to_xml()
         return self.res.create(body)
 
+
 class Violations(object):
 
     def __init__(self, root_url, path=_VIOLATIONS_PATH):
@@ -369,7 +410,7 @@ class Violations(object):
 
         The final url to the resource is root_url + "/" + path
         """
-        resourceurl = _buildpath_(root_url, path)
+        resourceurl = _buildpath(root_url, path)
         converter = xmlconverter.ViolationConverter()
         self.res = _Resource(resourceurl, converter)
 
@@ -386,7 +427,7 @@ class Violations(object):
         """
         return self.res.getbyid(violationid)
 
-    def getbyagreement(self, agreement_id, term=None):
+    def getbyagreement(self, agreement_id, testbed, term=None):
         """Get the violations of an agreement.
 
         :param str agreement_id:
@@ -394,8 +435,9 @@ class Violations(object):
             violations from all terms will be returned
         :rtype: list[wsag_model.Violation]
         """
-        return self.res.get(
-            {"agreementId": agreement_id, "guaranteeTerm": term})
+        return self.res.get("", params={"agreementId": agreement_id,
+                                        "guaranteeTerm": term,
+                                        "testbed": testbed})
 
 
 class Enforcements(object):
@@ -407,7 +449,7 @@ class Enforcements(object):
 
         The final url to the resource is root_url + "/" + path
         """
-        resourceurl = _buildpath_(root_url, path)
+        resourceurl = _buildpath(root_url, path)
         converter = xmlconverter.EnforcementConverter()
         self.res = _Resource(resourceurl, converter)
 
@@ -417,17 +459,20 @@ class Enforcements(object):
         """
         return self.res.getall()
 
-    def getbyagreement(self, agreement_id):
+    def getbyagreement(self, agreement_id, testbed):
         """Get the enforcement of an agreement.
 
         :param str agreement_id:
-        
+
         :rtype: list[wsag_model.Enforcement]
         """
-        return self.res.getbyid(agreement_id)    
+        return self.res.getbyid(agreement_id, params={"testbed": testbed})
+
 
+def _buildpath(*paths):
+    if "" in paths:
+        paths = [path for path in paths if path != ""]
 
-def _buildpath_(*paths):
     return "/".join(paths)
 
 
@@ -437,7 +482,6 @@ def main():
     #
     global rooturl
     rooturl = "http://127.0.0.1:8080/sla-service"
-    
 
     c = Factory.templates()
     #r = c.getall()
@@ -447,12 +491,9 @@ def main():
 
     #r = c.getbyconsumer('RandomClient')
     r = c.getbyid("template02")
-    
 
     print r
 
 
 if __name__ == "__main__":
     main()
-
-