1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
|
# Copyright (c) 2021 Dell, Inc. or its subsidiaries
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from datetime import datetime
from http import client as http_client
import logging
import time
from urllib.parse import urljoin
from dateutil import parser
from sushy import exceptions
from sushy.resources.taskservice import task
LOG = logging.getLogger(__name__)
class TaskMonitor:
def __init__(self,
connector,
task_monitor_uri,
redfish_version=None,
registries=None,
response=None):
"""A class representing a task monitor
:param connector: A Connector instance
:param task_monitor_uri: The task monitor URI
:param redfish_version: The version of Redfish. Used to construct
the object according to schema of the given version.
:param registries: Dict of Redfish Message Registry objects to be
used in any resource that needs registries to parse messages.
:param response: Raw response
"""
self._connector = connector
self._task_monitor_uri = task_monitor_uri
self._redfish_version = redfish_version
self._registries = registries
self._task = None
self._response = response
if (self._response and self._response.content
and self._response.status_code == http_client.ACCEPTED):
self._task = task.Task(self._connector, self._task_monitor_uri,
redfish_version=self._redfish_version,
registries=self._registries,
json_doc=self._response.json())
else:
self.refresh()
def refresh(self):
"""Refresh the Task
Freshly retrieves/fetches the Task.
:raises: ResourceNotFoundError
:raises: ConnectionError
:raises: HTTPError
"""
self._response = self._connector.get(path=self.task_monitor_uri)
if self._response.status_code == http_client.ACCEPTED:
# A Task should have been returned, but wasn't
if not self._response.content:
self._task = None
return
# Assume that the body contains a Task since we got a 202
if not self._task:
self._task = task.Task(self._connector, self._task_monitor_uri,
redfish_version=self._redfish_version,
registries=self._registries,
json_doc=self._response.json())
else:
self._task.refresh(json_doc=self._response.json())
else:
self._task = None
@property
def task_monitor_uri(self):
"""The TaskMonitor URI
:returns: The TaskMonitor URI.
"""
return self._task_monitor_uri
@property
def is_processing(self):
"""Indicates if the task is still processing
:returns: A boolean indicating if the task is still processing.
"""
return self._response.status_code == http_client.ACCEPTED
@property
def check_is_processing(self):
"""Refreshes task and check if it is still processing
:returns: A boolean indicating if the task is still processing.
"""
if not self.is_processing:
return False
self.refresh()
return self.is_processing
@property
def sleep_for(self):
"""Seconds the client should wait before querying the operation status
Defaults to 1 second if Retry-After not specified in response.
:returns: The number of seconds to wait
"""
retry_after = self._response.headers.get('Retry-After')
if retry_after is None:
return 1
if isinstance(retry_after, int) or retry_after.isdigit():
return retry_after
return max(0, (parser.parse(retry_after)
- datetime.now().astimezone()).total_seconds())
@property
def cancellable(self):
"""The amount of time to sleep before retrying
:returns: A Boolean indicating if the Task is cancellable.
"""
allow = self._response.headers.get('Allow')
cancellable = False
if allow and allow.upper() == 'DELETE':
cancellable = True
return cancellable
@property
def task(self):
"""The executing task
:returns: The Task being executed.
"""
return self._task
@property
def response(self):
"""Unprocessed response.
Intended to be used internally.
:returns: Unprocessed response.
"""
return self._response
def get_task(self):
"""Construct Task instance from task monitor URI.
:returns: Task instance.
"""
return task.Task(self._connector, self._task_monitor_uri,
redfish_version=self._redfish_version,
registries=self._registries)
def wait(self, timeout_sec):
"""Waits until task is completed or it times out.
:param timeout_sec: Timeout to wait
:raises: ConnectionError when times out
"""
timeout_at = time.time() + timeout_sec
while self.check_is_processing:
LOG.debug('Waiting for task monitor %(url)s; sleeping for '
'%(sleep)s seconds',
{'url': self.task_monitor_uri,
'sleep': self.sleep_for})
time.sleep(self.sleep_for)
if time.time() >= timeout_at and self.check_is_processing:
m = (f'Timeout waiting for task monitor '
f'{self.task_monitor_uri} (timeout = {timeout_sec})')
raise exceptions.ConnectionError(url=self.task_monitor_uri,
error=m)
@staticmethod
def from_response(conn, response, target_uri, redfish_version=None,
registries=None):
"""Construct TaskMonitor instance from received response.
:response: Unprocessed response
:target_uri: URI used to initiate async operation
:redfish_version: Redfish version. Optional when used internally.
:registries: Redfish registries. Optional when used internally.
:returns: TaskMonitor instance
:raises: MissingHeaderError if Location is missing in response
"""
json_data = response.json() if response.content else {}
header = 'Location'
task_monitor_uri = response.headers.get(header)
task_uri_data = json_data.get('@odata.id')
if task_uri_data:
task_monitor_uri = urljoin(task_monitor_uri, task_uri_data)
if not task_monitor_uri:
raise exceptions.MissingHeaderError(target_uri=target_uri,
header=header)
return TaskMonitor(conn,
task_monitor_uri,
redfish_version=redfish_version,
registries=registries,
response=response)
|