Feature 10909: Heal operation for VDU
[osm/osmclient.git] / osmclient / sol005 / pdud.py
index 3abb78c..e47dadd 100644 (file)
@@ -26,24 +26,30 @@ import logging
 
 
 class Pdu(object):
-
     def __init__(self, http=None, client=None):
         self._http = http
         self._client = client
-        self._logger = logging.getLogger('osmclient')
-        self._apiName = '/pdu'
-        self._apiVersion = '/v1'
-        self._apiResource = '/pdu_descriptors'
-        self._apiBase = '{}{}{}'.format(self._apiName,
-                                        self._apiVersion, self._apiResource)
+        self._logger = logging.getLogger("osmclient")
+        self._apiName = "/pdu"
+        self._apiVersion = "/v1"
+        self._apiResource = "/pdu_descriptors"
+        self._apiBase = "{}{}{}".format(
+            self._apiName, self._apiVersion, self._apiResource
+        )
+
+    def _get_vim_account(self, vim_account):
+        vim = self._client.vim.get(vim_account)
+        if vim is None:
+            raise NotFound("cannot find vim account '{}'".format(vim_account))
+        return vim
 
     def list(self, filter=None):
         self._logger.debug("")
         self._client.get_token()
-        filter_string = ''
+        filter_string = ""
         if filter:
-            filter_string = '?{}'.format(filter)
-        _, resp = self._http.get2_cmd('{}{}'.format(self._apiBase,filter_string))
+            filter_string = "?{}".format(filter)
+        _, resp = self._http.get2_cmd("{}{}".format(self._apiBase, filter_string))
         if resp:
             return json.loads(resp)
         return list()
@@ -53,11 +59,11 @@ class Pdu(object):
         self._client.get_token()
         if utils.validate_uuid4(name):
             for pdud in self.list():
-                if name == pdud['_id']:
+                if name == pdud["_id"]:
                     return pdud
         else:
             for pdud in self.list():
-                if 'name' in pdud and name == pdud['name']:
+                if "name" in pdud and name == pdud["name"]:
                     return pdud
         raise NotFound("pdud {} not found".format(name))
 
@@ -67,10 +73,10 @@ class Pdu(object):
         # It is redundant, since the previous one already gets the whole pdudInfo
         # The only difference is that a different primitive is exercised
         try:
-            _, resp = self._http.get2_cmd('{}/{}'.format(self._apiBase, pdud['_id']))
+            _, resp = self._http.get2_cmd("{}/{}".format(self._apiBase, pdud["_id"]))
         except NotFound:
             raise NotFound("pdu '{}' not found".format(name))
-        #print(yaml.safe_dump(resp))
+        # print(yaml.safe_dump(resp))
         if resp:
             return json.loads(resp)
         raise NotFound("pdu '{}' not found".format(name))
@@ -78,17 +84,18 @@ class Pdu(object):
     def delete(self, name, force=False):
         self._logger.debug("")
         pdud = self.get(name)
-        querystring = ''
+        querystring = ""
         if force:
-            querystring = '?FORCE=True'
-        http_code, resp = self._http.delete_cmd('{}/{}{}'.format(self._apiBase,
-                                         pdud['_id'], querystring))
-        #print('HTTP CODE: {}'.format(http_code))
-        #print('RESP: {}'.format(resp))
+            querystring = "?FORCE=True"
+        http_code, resp = self._http.delete_cmd(
+            "{}/{}{}".format(self._apiBase, pdud["_id"], querystring)
+        )
+        # print('HTTP CODE: {}'.format(http_code))
+        # print('RESP: {}'.format(resp))
         if http_code == 202:
-            print('Deletion in progress')
+            print("Deletion in progress")
         elif http_code == 204:
-            print('Deleted')
+            print("Deleted")
         else:
             msg = resp or ""
             # if resp:
@@ -100,39 +107,44 @@ class Pdu(object):
 
     def create(self, pdu, update_endpoint=None):
         self._logger.debug("")
+
+        if pdu["vim_accounts"]:
+            vim_account_list = []
+            for vim_account in pdu["vim_accounts"]:
+                vim = self._get_vim_account(vim_account)
+                vim_account_list.append(vim["_id"])
+            pdu["vim_accounts"] = vim_account_list
+
         self._client.get_token()
-        headers= self._client._headers
-        headers['Content-Type'] = 'application/yaml'
-        http_header = ['{}: {}'.format(key,val)
-                      for (key,val) in list(headers.items())]
+        headers = self._client._headers
+        headers["Content-Type"] = "application/yaml"
+        http_header = [
+            "{}: {}".format(key, val) for (key, val) in list(headers.items())
+        ]
         self._http.set_http_header(http_header)
         if update_endpoint:
-            http_code, resp = self._http.put_cmd(endpoint=update_endpoint, postfields_dict=pdu)
+            http_code, resp = self._http.patch_cmd(
+                endpoint=update_endpoint, postfields_dict=pdu
+            )
         else:
             endpoint = self._apiBase
-            #endpoint = '{}{}'.format(self._apiBase,ow_string)
-            http_code, resp = self._http.post_cmd(endpoint=endpoint, postfields_dict=pdu)
-        #print('HTTP CODE: {}'.format(http_code))
-        #print('RESP: {}'.format(resp))
-        #if http_code in (200, 201, 202, 204):
-        if resp:
-            resp = json.loads(resp)
-        if not resp or 'id' not in resp:
-            raise ClientException('unexpected response from server: '.format(
-                                  resp))
-        print(resp['id'])
-        #else:
-        #    msg = "Error {}".format(http_code)
-        #    if resp:
-        #        try:
-        #            msg = "{} - {}".format(msg, json.loads(resp))
-        #        except ValueError:
-        #            msg = "{} - {}".format(msg, resp)
-        #    raise ClientException("failed to create/update pdu - {}".format(msg))
+            # endpoint = '{}{}'.format(self._apiBase,ow_string)
+            http_code, resp = self._http.post_cmd(
+                endpoint=endpoint, postfields_dict=pdu
+            )
+        if http_code in (200, 201, 202):
+            if resp:
+                resp = json.loads(resp)
+            if not resp or "id" not in resp:
+                raise ClientException(
+                    "unexpected response from server: {}".format(resp)
+                )
+            print(resp["id"])
+        elif http_code == 204:
+            print("Updated")
 
-    def update(self, name, filename):
+    def update(self, name, pdu):
         self._logger.debug("")
         pdud = self.get(name)
-        endpoint = '{}/{}'.format(self._apiBase, pdud['_id'])
-        self.create(filename=filename, update_endpoint=endpoint)
-
+        endpoint = "{}/{}".format(self._apiBase, pdud["_id"])
+        self.create(pdu=pdu, update_endpoint=endpoint)