Improvement: Return more states in the 'detailed-status' field - client side
[osm/osmclient.git] / osmclient / common / wait.py
1 # Copyright 2019 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 API handling for the '--wait' option
19 """
20
21 from osmclient.common.exceptions import ClientException
22 import json
23 from time import sleep
24 import sys
25
26 # Declare a constant for each module, to allow customizing each timeout in the future
27 TIMEOUT_GENERIC_OPERATION = 600
28 TIMEOUT_NSI_OPERATION = TIMEOUT_GENERIC_OPERATION
29 TIMEOUT_SDNC_OPERATION = TIMEOUT_GENERIC_OPERATION
30 TIMEOUT_VIM_OPERATION = TIMEOUT_GENERIC_OPERATION
31 TIMEOUT_WIM_OPERATION = TIMEOUT_GENERIC_OPERATION
32 TIMEOUT_NS_OPERATION = 3600
33 POLLING_TIME_INTERVAL = 1
34 MAX_DELETE_ATTEMPTS = 3
35
36 def _show_detailed_status(old_detailed_status, new_detailed_status):
37 if new_detailed_status is not None and new_detailed_status != old_detailed_status:
38 sys.stderr.write("detailed-status: {}\n".format(new_detailed_status))
39 return new_detailed_status
40 else:
41 return old_detailed_status
42
43 def _get_finished_states(entity):
44 # Note that the member name is either:
45 # 'operationState' (NS and NSI)
46 # '_admin.'operationalState' (other)
47 # For NS and NSI, 'operationState' may be one of:
48 # PROCESSING, COMPLETED,PARTIALLY_COMPLETED, FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
49 # For other entities, '_admin.operationalState' may be one of:
50 # operationalState: ENABLED, DISABLED, ERROR, PROCESSING
51 if entity == 'NS' or entity == 'NSI':
52 return ['COMPLETED', 'PARTIALLY_COMPLETED', 'FAILED_TEMP', 'FAILED']
53 else:
54 return ['ENABLED', 'ERROR']
55
56 def _get_operational_state(resp, entity):
57 # Note that the member name is either:
58 # 'operationState' (NS)
59 # 'operational-status' (NSI)
60 # '_admin.'operationalState' (other)
61 if entity == 'NS' or entity == 'NSI':
62 return resp.get('operationState')
63 else:
64 return resp.get('_admin', {}).get('operationalState')
65
66 def _op_has_finished(resp, entity):
67 # This function returns:
68 # 0 on success (operation has finished)
69 # 1 on pending (operation has not finished)
70 # -1 on error (bad response)
71 #
72 finished_states = _get_finished_states(entity)
73 if resp:
74 operationalState = _get_operational_state(resp, entity)
75 if operationalState:
76 if operationalState in finished_states:
77 return 0
78 return 1
79 return -1
80
81 def _get_detailed_status(resp, entity, detailed_status_deleted):
82 if detailed_status_deleted:
83 return detailed_status_deleted
84 if entity == 'NS' or entity == 'NSI':
85 # For NS and NSI, 'detailed-status' is a JSON "root" member:
86 return resp.get('detailed-status')
87 else:
88 # For other entities, 'detailed-status' a leaf node to '_admin':
89 return resp.get('_admin', {}).get('detailed-status')
90
91 def _has_delete_error(resp, entity, deleteFlag, delete_attempts_left):
92 if deleteFlag and delete_attempts_left:
93 state = _get_operational_state(resp, entity)
94 if state and state == 'ERROR':
95 return True
96 return False
97
98 def wait_for_status(entity_label, entity_id, timeout, apiUrlStatus, http_cmd, deleteFlag=False):
99 # Arguments:
100 # entity_label: String describing the entities using '--wait':
101 # 'NS', 'NSI', 'SDNC', 'VIM', 'WIM'
102 # entity_id: The ID for an existing entity, the operation ID for an entity to create.
103 # timeout: See section at top of this file for each value of TIMEOUT_<ENTITY>_OPERATION
104 # apiUrlStatus: The endpoint to get the Response including 'detailed-status'
105 # http_cmd: callback to HTTP command.
106 # Passing this callback as an argument avoids importing the 'http' module here.
107
108 # Loop here until the operation finishes, or a timeout occurs.
109 time_left = timeout
110 detailed_status = None
111 detailed_status_deleted = None
112 time_to_return = False
113 delete_attempts_left = MAX_DELETE_ATTEMPTS
114 wait_for_404 = False
115 try:
116 while True:
117 http_code, resp_unicode = http_cmd('{}/{}'.format(apiUrlStatus, entity_id))
118 resp = ''
119 if resp_unicode:
120 resp = json.loads(resp_unicode)
121 # print 'HTTP CODE: {}'.format(http_code)
122 # print 'RESP: {}'.format(resp)
123 # print 'URL: {}/{}'.format(apiUrlStatus, entity_id)
124 if deleteFlag and http_code == 404:
125 # In case of deletion, '404 Not Found' means successfully deleted
126 # Display 'detailed-status: Deleted' and return
127 time_to_return = True
128 detailed_status_deleted = 'Deleted'
129 elif deleteFlag and http_code in (200, 201, 202, 204):
130 # In case of deletion and HTTP Status = 20* OK, deletion may be PROCESSING or COMPLETED
131 # If this is the case, we should keep on polling until 404 (deleted) is returned.
132 wait_for_404 = True
133 elif http_code not in (200, 201, 202, 204):
134 raise ClientException(str(resp))
135 if not time_to_return:
136 # Get operation status
137 op_status = _op_has_finished(resp, entity_label)
138 if op_status == -1:
139 # An error occurred
140 raise ClientException('unexpected response from server - {} '.format(
141 str(resp)))
142 elif op_status == 0:
143 # If there was an error upon deletion, try again to delete the same instance
144 # If the error is the same, there is probably nothing we can do but exit with error.
145 # If the error is different (i.e. 404), the instance was probably already corrupt, that is,
146 # operation(al)State was probably ERROR before deletion.
147 # In such a case, even if the previous state was ERROR, the deletion was successful,
148 # so detailed-status should be set to Deleted.
149 if _has_delete_error(resp, entity_label, deleteFlag, delete_attempts_left):
150 delete_attempts_left -= 1
151 else:
152 # Operation has finished, either with success or error
153 if deleteFlag:
154 delete_attempts_left -= 1
155 if not wait_for_404 and delete_attempts_left < MAX_DELETE_ATTEMPTS:
156 time_to_return = True
157 else:
158 time_to_return = True
159 new_detailed_status = _get_detailed_status(resp, entity_label, detailed_status_deleted)
160 # print 'DETAILED-STATUS: {}'.format(new_detailed_status)
161 # print 'DELETE-ATTEMPTS-LEFT: {}'.format(delete_attempts_left)
162 if not new_detailed_status:
163 new_detailed_status = 'In progress'
164 # TODO: Change LCM to provide detailed-status more up to date
165 # At the moment of this writing, 'detailed-status' may return different strings
166 # from different resources:
167 # /nslcm/v1/ns_lcm_op_occs/<id> ---> ''
168 # /nslcm/v1/ns_instances_content/<id> ---> 'deleting charms'
169 detailed_status = _show_detailed_status(detailed_status, new_detailed_status)
170 if time_to_return:
171 return
172 time_left -= POLLING_TIME_INTERVAL
173 sleep(POLLING_TIME_INTERVAL)
174 if time_left <= 0:
175 # There was a timeout, so raise an exception
176 raise ClientException('operation timeout, waited for {} seconds'.format(timeout))
177 except ClientException as exc:
178 message="Operation failed for {}:\nerror:\n{}".format(
179 entity_label,
180 exc.message)
181 raise ClientException(message)