df5bad1a8c279617fe287435f5a93aa7a1040b10
[osm/osmclient.git] / osmclient / sol005 / pdud.py
1 # Copyright 2018 Telefonica
2 #
3 # All Rights Reserved.
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License"); you may
6 # not use this file except in compliance with the License. You may obtain
7 # a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14 # License for the specific language governing permissions and limitations
15 # under the License.
16
17 """
18 OSM pdud API handling
19 """
20
21 from osmclient.common.exceptions import NotFound
22 from osmclient.common.exceptions import ClientException
23 from osmclient.common import utils
24 import json
25 import logging
26
27
28 class Pdu(object):
29 def __init__(self, http=None, client=None):
30 self._http = http
31 self._client = client
32 self._logger = logging.getLogger("osmclient")
33 self._apiName = "/pdu"
34 self._apiVersion = "/v1"
35 self._apiResource = "/pdu_descriptors"
36 self._apiBase = "{}{}{}".format(
37 self._apiName, self._apiVersion, self._apiResource
38 )
39
40 def list(self, filter=None):
41 self._logger.debug("")
42 self._client.get_token()
43 filter_string = ""
44 if filter:
45 filter_string = "?{}".format(filter)
46 _, resp = self._http.get2_cmd("{}{}".format(self._apiBase, filter_string))
47 if resp:
48 return json.loads(resp)
49 return list()
50
51 def get(self, name):
52 self._logger.debug("")
53 self._client.get_token()
54 if utils.validate_uuid4(name):
55 for pdud in self.list():
56 if name == pdud["_id"]:
57 return pdud
58 else:
59 for pdud in self.list():
60 if "name" in pdud and name == pdud["name"]:
61 return pdud
62 raise NotFound("pdud {} not found".format(name))
63
64 def get_individual(self, name):
65 self._logger.debug("")
66 pdud = self.get(name)
67 # It is redundant, since the previous one already gets the whole pdudInfo
68 # The only difference is that a different primitive is exercised
69 try:
70 _, resp = self._http.get2_cmd("{}/{}".format(self._apiBase, pdud["_id"]))
71 except NotFound:
72 raise NotFound("pdu '{}' not found".format(name))
73 # print(yaml.safe_dump(resp))
74 if resp:
75 return json.loads(resp)
76 raise NotFound("pdu '{}' not found".format(name))
77
78 def delete(self, name, force=False):
79 self._logger.debug("")
80 pdud = self.get(name)
81 querystring = ""
82 if force:
83 querystring = "?FORCE=True"
84 http_code, resp = self._http.delete_cmd(
85 "{}/{}{}".format(self._apiBase, pdud["_id"], querystring)
86 )
87 # print('HTTP CODE: {}'.format(http_code))
88 # print('RESP: {}'.format(resp))
89 if http_code == 202:
90 print("Deletion in progress")
91 elif http_code == 204:
92 print("Deleted")
93 else:
94 msg = resp or ""
95 # if resp:
96 # try:
97 # msg = json.loads(resp)
98 # except ValueError:
99 # msg = resp
100 raise ClientException("failed to delete pdu {} - {}".format(name, msg))
101
102 def create(self, pdu, update_endpoint=None):
103 self._logger.debug("")
104 self._client.get_token()
105 headers = self._client._headers
106 headers["Content-Type"] = "application/yaml"
107 http_header = [
108 "{}: {}".format(key, val) for (key, val) in list(headers.items())
109 ]
110 self._http.set_http_header(http_header)
111 if update_endpoint:
112 http_code, resp = self._http.put_cmd(
113 endpoint=update_endpoint, postfields_dict=pdu
114 )
115 else:
116 endpoint = self._apiBase
117 # endpoint = '{}{}'.format(self._apiBase,ow_string)
118 http_code, resp = self._http.post_cmd(
119 endpoint=endpoint, postfields_dict=pdu
120 )
121 # print('HTTP CODE: {}'.format(http_code))
122 # print('RESP: {}'.format(resp))
123 # if http_code in (200, 201, 202, 204):
124 if resp:
125 resp = json.loads(resp)
126 if not resp or "id" not in resp:
127 raise ClientException("unexpected response from server: {}".format(resp))
128 print(resp["id"])
129 # else:
130 # msg = "Error {}".format(http_code)
131 # if resp:
132 # try:
133 # msg = "{} - {}".format(msg, json.loads(resp))
134 # except ValueError:
135 # msg = "{} - {}".format(msg, resp)
136 # raise ClientException("failed to create/update pdu - {}".format(msg))
137
138 def update(self, name, filename):
139 self._logger.debug("")
140 pdud = self.get(name)
141 endpoint = "{}/{}".format(self._apiBase, pdud["_id"])
142 self.create(filename=filename, update_endpoint=endpoint)