Apply black formatter to nfv

This commit applies the black formatter to the repository.

Note: a few black rules are conflicting with the current flake8 and
pylint rules, in which case the latter were preferred until subsequent
commits update them. This is also the reason why some imports had to be
reordered.

Test plan:
1. PASS: Build an ISO.
2. PASS: Deploy a DC system with AIO-SX and AIO-DX subclouds.
3. PASS: Successfully run sw-upgrade for the system controller and
   subclouds.
4. PASS: Successfully run kube-upgrade for the subclouds
5. PASS: Successfully run kube-rootca update for the subclouds.

Story: 2011777
Task: 54252

Change-Id: I4a8650f1b6aa10a4d019231bc556d830ad454123
Signed-off-by: Raphael <Raphael.Lima@windriver.com>
This commit is contained in:
Raphael committed 2026-05-05 08:47:38 -03:00
1 parent 3b05e987e5
commit f26d2125a1
423 files changed
+46672 -35858

No files matched your search

+2 -2
View File
@@ -6,8 +6,8 @@
class AuthTypes:
KEYSTONE = 'Keystone'
OIDC = 'oidc'
KEYSTONE = "Keystone"
OIDC = "oidc"
AUTH_TYPES = AuthTypes()
+20 -17
View File
@@ -1,5 +1,5 @@
#
# Copyright (c) 2016 Wind River Systems, Inc.
# Copyright (c) 2016, 2026 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
@@ -12,6 +12,7 @@ class Token(object):
"""
Token
"""
def __init__(self, token_data, token_id):
self._expired = False
self._data = token_data
@@ -22,7 +23,7 @@ class Token(object):
def is_expired(self, within_seconds=300):
if not self._expired:
end = iso8601.parse_date(self._data['token']['expires_at'])
end = iso8601.parse_date(self._data["token"]["expires_at"])
now = iso8601.parse_date(datetime.datetime.utcnow().isoformat())
if end <= now:
return True
@@ -40,7 +41,7 @@ class Token(object):
"""
Get the tenant identifier of the token.
"""
return self._data['token']['project']['id']
return self._data["token"]["project"]["id"]
@staticmethod
def _url_strip_version(url):
@@ -49,16 +50,16 @@ class Token(object):
"""
# Get rid of the trailing '/' if present and remove the version
# information from the URL.
url = url.rstrip('/')
url_bits = url.split('/')
url = url.rstrip("/")
url_bits = url.split("/")
# Regular-Expression to match 'v1' or 'v2.0' etc
# prefix regular expression with r to treat as raw string to
# suppress lint 'anomalous backslash' warnings
if re.match(r'v\d+\.?\d*', url_bits[-1]):
url = '/'.join(url_bits[:-1])
if re.match(r"v\d+\.?\d*", url_bits[-1]):
url = "/".join(url_bits[:-1])
elif re.match(r'v\d+\.?\d*', url_bits[-2]):
url = '/'.join(url_bits[:-2])
elif re.match(r"v\d+\.?\d*", url_bits[-2]):
url = "/".join(url_bits[:-2])
return url
@@ -66,12 +67,14 @@ class Token(object):
"""
Search the catalog of a service in a region for the url
"""
for catalog in self._data['token']['catalog']:
if catalog['type'] == service_type:
if catalog['name'] == service_name:
if 0 != len(catalog['endpoints']):
for endpoint in catalog['endpoints']:
if (endpoint['region'] == region_name and
endpoint['interface'] == interface):
return endpoint['url']
for catalog in self._data["token"]["catalog"]:
if catalog["type"] == service_type:
if catalog["name"] == service_name:
if 0 != len(catalog["endpoints"]):
for endpoint in catalog["endpoints"]:
if (
endpoint["region"] == region_name
and endpoint["interface"] == interface
):
return endpoint["url"]
return None
@@ -18,23 +18,26 @@ class OpenStackServices(object):
"""
OpenStack Services Constants
"""
VIM = 'vim'
VIM = "vim"
class OpenStackServiceTypes(object):
"""
OpenStack Service Types Constants
"""
NFV = 'nfv'
NFV = "nfv"
SERVICE = OpenStackServices()
SERVICE_TYPE = OpenStackServiceTypes()
CAFILE = os.environ.get('REQUESTS_CA_BUNDLE')
CAFILE = os.environ.get("REQUESTS_CA_BUNDLE")
def get_token(auth_uri, project_name, project_domain_name, username, password,
user_domain_name):
def get_token(
auth_uri, project_name, project_domain_name, username, password, user_domain_name
):
"""
Ask OpenStack for a token
"""
@@ -42,16 +45,14 @@ def get_token(auth_uri, project_name, project_domain_name, username, password,
ssl_context = None
try:
# handle auth_uri re-direct (300)
ssl_context = ssl.create_default_context(
ssl.Purpose.SERVER_AUTH, cafile=CAFILE
)
ssl_context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH, cafile=CAFILE)
with urllib.request.urlopen(auth_uri, context=ssl_context):
pass
except urllib.error.HTTPError as e:
if e.code == 300:
auth_uri = e.headers['location']
if auth_uri.endswith('/'):
auth_uri = e.headers["location"]
if auth_uri.endswith("/"):
auth_uri = auth_uri[:-1]
except Exception:
print("An error occurred when retrieving the token")
@@ -64,24 +65,27 @@ def get_token(auth_uri, project_name, project_domain_name, username, password,
request_info.add_header("Accept", "application/json")
request_info.add_header("User-Agent", "vim/1.0")
payload = json.dumps(
{"auth": {
"identity": {
"methods": [
"password"
],
"password": {
"user": {
"name": username,
"password": password,
"domain": {"name": user_domain_name}
{
"auth": {
"identity": {
"methods": ["password"],
"password": {
"user": {
"name": username,
"password": password,
"domain": {"name": user_domain_name},
}
},
},
"scope": {
"project": {
"name": project_name,
"domain": {"name": project_domain_name},
}
}
},
"scope": {
"project": {
"name": project_name,
"domain": {"name": project_domain_name}
}}}})
},
}
}
)
request_info.data = payload.encode()
@@ -90,7 +94,7 @@ def get_token(auth_uri, project_name, project_domain_name, username, password,
) as request:
# Identity API v3 returns token id in X-Subject-Token
# response header.
token_id = request.headers.get('X-Subject-Token')
token_id = request.headers.get("X-Subject-Token")
response = json.loads(request.read())
return Token(response, token_id)
+28 -13
View File
@@ -11,20 +11,29 @@ from nfv_client.auth_types import AUTH_TYPES
from nfv_client import sw_update
CAFILE = os.environ.get('REQUESTS_CA_BUNDLE')
STRATEGY_EXISTS = 'strategy already exists.'
CAFILE = os.environ.get("REQUESTS_CA_BUNDLE")
STRATEGY_EXISTS = "strategy already exists."
UNKNOWN_FAILURE = "Check /var/log/nfv-vim-api.log for details."
UNKNOWN_BAD_REQUEST = f"Unknown cause of bad request. {UNKNOWN_FAILURE}"
class SwRestApiException(Exception):
def __init__(self, msg, *args: object) -> None:
msg = msg.replace(sw_update.STRATEGY_NAME_SW_UPGRADE, sw_update.STRATEGY_NAME_SW_DEPLOY)
msg = msg.replace(
sw_update.STRATEGY_NAME_SW_UPGRADE, sw_update.STRATEGY_NAME_SW_DEPLOY
)
super().__init__(msg, *args)
def request(token_id, method, api_cmd, api_cmd_headers=None,
api_cmd_payload=None, timeout_in_secs=40, auth_type='keystone'):
def request(
token_id,
method,
api_cmd,
api_cmd_headers=None,
api_cmd_payload=None,
timeout_in_secs=40,
auth_type="keystone",
):
"""
Make a rest-api request
Note: Using a default timeout of 40 seconds. The VIM's internal handling
@@ -46,14 +55,18 @@ def request(token_id, method, api_cmd, api_cmd_headers=None,
api_cmd_payload = json.loads(api_cmd_payload)
try:
response = requests.request(
method, api_cmd, headers=headers, json=api_cmd_payload,
timeout=timeout_in_secs, verify=CAFILE
method,
api_cmd,
headers=headers,
json=api_cmd_payload,
timeout=timeout_in_secs,
verify=CAFILE,
)
response.raise_for_status()
# Check if the content type starts with 'application/json'
content_type = response.headers.get('content-type', '')
if content_type.startswith('application/json'):
content_type = response.headers.get("content-type", "")
if content_type.startswith("application/json"):
return response.json()
else:
return response.text
@@ -65,13 +78,15 @@ def request(token_id, method, api_cmd, api_cmd_headers=None,
elif status_code == requests.codes.bad_request: # pylint: disable=no-member
error_response = response.json()
raise SwRestApiException(
"Operation failed: Bad request.\n"
f"{error_response.get('faultstring', UNKNOWN_BAD_REQUEST)}")
"Operation failed: Bad request.\n"
f"{error_response.get('faultstring', UNKNOWN_BAD_REQUEST)}"
)
elif status_code == requests.codes.conflict: # pylint: disable=no-member
error_response = json.loads(response.text)
raise SwRestApiException(
"Operation failed: Conflict detected.\n"
f"{error_response.get('faultstring', STRATEGY_EXISTS)}")
"Operation failed: Conflict detected.\n"
f"{error_response.get('faultstring', STRATEGY_EXISTS)}"
)
elif status_code == requests.codes.forbidden: # pylint: disable=no-member
raise Exception("Authorization failed")
else:
+232 -167
View File
@@ -89,16 +89,16 @@ def _get_strategy_step_object_from_response(response):
Convert the Rest-API response into a strategy step object
"""
step = StrategyStep()
step.step_id = response['step-id']
step.step_name = response['step-name']
step.entity_type = response['entity-type']
step.entity_names = response['entity-names']
step.entity_uuids = response['entity-uuids']
step.timeout = response['timeout']
step.start_date_time = response['start-date-time']
step.end_date_time = response['end-date-time']
step.result = response['result']
step.reason = response['reason']
step.step_id = response["step-id"]
step.step_name = response["step-name"]
step.entity_type = response["entity-type"]
step.entity_names = response["entity-names"]
step.entity_uuids = response["entity-uuids"]
step.timeout = response["timeout"]
step.start_date_time = response["start-date-time"]
step.end_date_time = response["end-date-time"]
step.result = response["result"]
step.reason = response["reason"]
return step
@@ -107,19 +107,19 @@ def _get_strategy_stage_object_from_response(response):
Convert the Rest-API response into a strategy stage object
"""
stage = StrategyStage()
stage.stage_id = response['stage-id']
stage.stage_name = response['stage-name']
stage.total_steps = response['total-steps']
stage.current_step = response['current-step']
stage.timeout = response['timeout']
stage.start_date_time = response['start-date-time']
stage.end_date_time = response['end-date-time']
stage.inprogress = response['inprogress']
stage.result = response['result']
stage.reason = response['reason']
stage.stage_id = response["stage-id"]
stage.stage_name = response["stage-name"]
stage.total_steps = response["total-steps"]
stage.current_step = response["current-step"]
stage.timeout = response["timeout"]
stage.start_date_time = response["start-date-time"]
stage.end_date_time = response["end-date-time"]
stage.inprogress = response["inprogress"]
stage.result = response["result"]
stage.reason = response["reason"]
stage.steps = []
for step in response['steps']:
for step in response["steps"]:
stage.steps.append(_get_strategy_step_object_from_response(step))
return stage
@@ -130,21 +130,21 @@ def _get_strategy_phase_object_from_response(response):
Convert the Rest-API response into a strategy phase object
"""
phase = StrategyPhase()
phase.phase_name = response['phase-name']
phase.total_stages = response['total-stages']
phase.current_stage = response['current-stage']
phase.stop_at_stage = response['stop-at-stage']
phase.timeout = response['timeout']
phase.start_date_time = response['start-date-time']
phase.end_date_time = response['end-date-time']
phase.inprogress = response['inprogress']
phase.completion_percentage = response['completion-percentage']
phase.result = response['result']
phase.reason = response['reason']
phase.response = response.get('response')
phase.phase_name = response["phase-name"]
phase.total_stages = response["total-stages"]
phase.current_stage = response["current-stage"]
phase.stop_at_stage = response["stop-at-stage"]
phase.timeout = response["timeout"]
phase.start_date_time = response["start-date-time"]
phase.end_date_time = response["end-date-time"]
phase.inprogress = response["inprogress"]
phase.completion_percentage = response["completion-percentage"]
phase.result = response["result"]
phase.reason = response["reason"]
phase.response = response.get("response")
phase.stages = []
for stage in response['stages']:
for stage in response["stages"]:
phase.stages.append(_get_strategy_stage_object_from_response(stage))
return phase
@@ -154,33 +154,36 @@ def _get_strategy_object_from_response(response):
"""
Convert the Rest-API response into a strategy object
"""
strategy_data = response.get('strategy', None)
strategy_data = response.get("strategy", None)
if strategy_data is None:
return None
strategy = Strategy()
strategy.uuid = strategy_data['uuid']
strategy.name = strategy_data['name']
strategy.uuid = strategy_data["uuid"]
strategy.name = strategy_data["name"]
if strategy.name == sw_update.STRATEGY_NAME_SW_UPGRADE:
strategy.release = strategy_data['release']
strategy.controller_apply_type = strategy_data['controller-apply-type']
strategy.storage_apply_type = strategy_data['storage-apply-type']
strategy.swift_apply_type = strategy_data['swift-apply-type']
strategy.worker_apply_type = strategy_data['worker-apply-type']
strategy.max_parallel_worker_hosts = \
strategy_data['max-parallel-worker-hosts']
strategy.default_instance_action = strategy_data['default-instance-action']
strategy.alarm_restrictions = strategy_data['alarm-restrictions']
strategy.current_phase = strategy_data['current-phase']
strategy.current_phase_completion_percentage \
= strategy_data['current-phase-completion-percentage']
strategy.state = strategy_data['state']
strategy.release = strategy_data["release"]
strategy.controller_apply_type = strategy_data["controller-apply-type"]
strategy.storage_apply_type = strategy_data["storage-apply-type"]
strategy.swift_apply_type = strategy_data["swift-apply-type"]
strategy.worker_apply_type = strategy_data["worker-apply-type"]
strategy.max_parallel_worker_hosts = strategy_data["max-parallel-worker-hosts"]
strategy.default_instance_action = strategy_data["default-instance-action"]
strategy.alarm_restrictions = strategy_data["alarm-restrictions"]
strategy.current_phase = strategy_data["current-phase"]
strategy.current_phase_completion_percentage = strategy_data[
"current-phase-completion-percentage"
]
strategy.state = strategy_data["state"]
strategy.build_phase \
= _get_strategy_phase_object_from_response(strategy_data['build-phase'])
strategy.apply_phase \
= _get_strategy_phase_object_from_response(strategy_data['apply-phase'])
strategy.abort_phase \
= _get_strategy_phase_object_from_response(strategy_data['abort-phase'])
strategy.build_phase = _get_strategy_phase_object_from_response(
strategy_data["build-phase"]
)
strategy.apply_phase = _get_strategy_phase_object_from_response(
strategy_data["apply-phase"]
)
strategy.abort_phase = _get_strategy_phase_object_from_response(
strategy_data["abort-phase"]
)
return strategy
@@ -190,20 +193,26 @@ def _get_current_strategy_from_response(response):
Returns Strategy Type and State
"""
current_strategy = {}
strategy_data = response.get('strategy', None)
strategy_data = response.get("strategy", None)
if strategy_data is None:
return None
strategy = Strategy()
strategy.name = strategy_data['name']
strategy.state = strategy_data['state']
strategy.name = strategy_data["name"]
strategy.state = strategy_data["state"]
if strategy.name is not None:
current_strategy[strategy.name] = strategy.state
return current_strategy
def get_strategies(token_id, url, strategy_name, username=None,
user_domain_name=None, tenant=None,
auth_type=AUTH_TYPES.KEYSTONE):
def get_strategies(
token_id,
url,
strategy_name,
username=None,
user_domain_name=None,
tenant=None,
auth_type=AUTH_TYPES.KEYSTONE,
):
"""
Software Update - Get Strategies
"""
@@ -211,144 +220,170 @@ def get_strategies(token_id, url, strategy_name, username=None,
api_cmd_headers = dict()
if username:
api_cmd_headers['X-User'] = username
api_cmd_headers["X-User"] = username
if tenant:
api_cmd_headers['X-Tenant'] = tenant
api_cmd_headers["X-Tenant"] = tenant
if user_domain_name:
api_cmd_headers['X-User-Domain-Name'] = user_domain_name
api_cmd_headers["X-User-Domain-Name"] = user_domain_name
response = rest_api.request(token_id, "GET", api_cmd, api_cmd_headers,
auth_type=auth_type)
response = rest_api.request(
token_id, "GET", api_cmd, api_cmd_headers, auth_type=auth_type
)
if not response:
return None
return _get_strategy_object_from_response(response)
def get_strategy(token_id, url, strategy_name, strategy_uuid, username=None,
user_domain_name=None, tenant=None,
auth_type=AUTH_TYPES.KEYSTONE):
def get_strategy(
token_id,
url,
strategy_name,
strategy_uuid,
username=None,
user_domain_name=None,
tenant=None,
auth_type=AUTH_TYPES.KEYSTONE,
):
"""
Software Update - Get Strategy
"""
api_cmd = url + "/api/orchestration/%s/strategy/%s" % (strategy_name,
strategy_uuid)
api_cmd = url + "/api/orchestration/%s/strategy/%s" % (strategy_name, strategy_uuid)
api_cmd_headers = dict()
if username:
api_cmd_headers['X-User'] = username
api_cmd_headers["X-User"] = username
if tenant:
api_cmd_headers['X-Tenant'] = tenant
api_cmd_headers["X-Tenant"] = tenant
if user_domain_name:
api_cmd_headers['X-User-Domain-Name'] = user_domain_name
api_cmd_headers["X-User-Domain-Name"] = user_domain_name
response = rest_api.request(token_id, "GET", api_cmd, api_cmd_headers,
auth_type=auth_type)
response = rest_api.request(
token_id, "GET", api_cmd, api_cmd_headers, auth_type=auth_type
)
if not response:
return None
return _get_strategy_object_from_response(response)
def create_strategy(token_id,
url,
strategy_name,
controller_apply_type,
storage_apply_type,
swift_apply_type,
worker_apply_type,
max_parallel_worker_hosts,
default_instance_action,
alarm_restrictions,
username=None,
user_domain_name=None,
tenant=None,
auth_type=AUTH_TYPES.KEYSTONE,
**kwargs):
def create_strategy(
token_id,
url,
strategy_name,
controller_apply_type,
storage_apply_type,
swift_apply_type,
worker_apply_type,
max_parallel_worker_hosts,
default_instance_action,
alarm_restrictions,
username=None,
user_domain_name=None,
tenant=None,
auth_type=AUTH_TYPES.KEYSTONE,
**kwargs
):
"""
Software Update - Create Strategy
"""
api_cmd = url + "/api/orchestration/%s/strategy" % strategy_name
api_cmd_headers = dict()
api_cmd_headers['Content-Type'] = "application/json"
api_cmd_headers["Content-Type"] = "application/json"
if username:
api_cmd_headers['X-User'] = username
api_cmd_headers["X-User"] = username
if tenant:
api_cmd_headers['X-Tenant'] = tenant
api_cmd_headers["X-Tenant"] = tenant
if user_domain_name:
api_cmd_headers['X-User-Domain-Name'] = user_domain_name
api_cmd_headers["X-User-Domain-Name"] = user_domain_name
api_cmd_payload = dict()
if sw_update.STRATEGY_NAME_FW_UPDATE == strategy_name:
api_cmd_payload['controller-apply-type'] = controller_apply_type
api_cmd_payload['default-instance-action'] = default_instance_action
api_cmd_payload["controller-apply-type"] = controller_apply_type
api_cmd_payload["default-instance-action"] = default_instance_action
elif sw_update.STRATEGY_NAME_KUBE_ROOTCA_UPDATE == strategy_name:
# Note that the payload contains '-' and not '_'
if 'expiry_date' in kwargs and kwargs['expiry_date']:
api_cmd_payload['expiry-date'] = kwargs['expiry_date']
if 'subject' in kwargs and kwargs['subject']:
api_cmd_payload['subject'] = kwargs['subject']
api_cmd_payload['default-instance-action'] = default_instance_action
if "expiry_date" in kwargs and kwargs["expiry_date"]:
api_cmd_payload["expiry-date"] = kwargs["expiry_date"]
if "subject" in kwargs and kwargs["subject"]:
api_cmd_payload["subject"] = kwargs["subject"]
api_cmd_payload["default-instance-action"] = default_instance_action
elif sw_update.STRATEGY_NAME_KUBE_UPGRADE == strategy_name:
# required: 'to_version' passed to strategy as 'to-version'
api_cmd_payload['to-version'] = kwargs['to_version']
api_cmd_payload['default-instance-action'] = default_instance_action
api_cmd_payload["to-version"] = kwargs["to_version"]
api_cmd_payload["default-instance-action"] = default_instance_action
elif sw_update.STRATEGY_NAME_SYSTEM_CONFIG_UPDATE == strategy_name:
api_cmd_payload['controller-apply-type'] = controller_apply_type
api_cmd_payload['default-instance-action'] = default_instance_action
api_cmd_payload["controller-apply-type"] = controller_apply_type
api_cmd_payload["default-instance-action"] = default_instance_action
elif sw_update.STRATEGY_NAME_SW_UPGRADE == strategy_name:
# controller-apply-type and default-instance-action passed to strategy
api_cmd_payload['controller-apply-type'] = controller_apply_type
api_cmd_payload['default-instance-action'] = default_instance_action
api_cmd_payload['release'] = kwargs['release']
api_cmd_payload['rollback'] = kwargs.get('rollback')
api_cmd_payload['delete'] = kwargs.get('delete')
api_cmd_payload["controller-apply-type"] = controller_apply_type
api_cmd_payload["default-instance-action"] = default_instance_action
api_cmd_payload["release"] = kwargs["release"]
api_cmd_payload["rollback"] = kwargs.get("rollback")
api_cmd_payload["delete"] = kwargs.get("delete")
# Append snapshot if it was provided. This is to
# support API call backwards compatibility, where
# the snapshot parameter is unknown.
if kwargs.get('snapshot'):
api_cmd_payload['snapshot'] = kwargs.get('snapshot')
if kwargs.get("snapshot"):
api_cmd_payload["snapshot"] = kwargs.get("snapshot")
api_cmd_payload['storage-apply-type'] = storage_apply_type
api_cmd_payload['worker-apply-type'] = worker_apply_type
api_cmd_payload["storage-apply-type"] = storage_apply_type
api_cmd_payload["worker-apply-type"] = worker_apply_type
if max_parallel_worker_hosts is not None:
api_cmd_payload['max-parallel-worker-hosts'] = \
max_parallel_worker_hosts
api_cmd_payload['alarm-restrictions'] = alarm_restrictions
response = rest_api.request(token_id, "POST", api_cmd, api_cmd_headers,
json.dumps(api_cmd_payload),
auth_type=auth_type)
api_cmd_payload["max-parallel-worker-hosts"] = max_parallel_worker_hosts
api_cmd_payload["alarm-restrictions"] = alarm_restrictions
response = rest_api.request(
token_id,
"POST",
api_cmd,
api_cmd_headers,
json.dumps(api_cmd_payload),
auth_type=auth_type,
)
if not response:
return None
return _get_strategy_object_from_response(response)
def delete_strategy(token_id, url, strategy_name, force=False,
username=None, user_domain_name=None, tenant=None,
auth_type=AUTH_TYPES.KEYSTONE):
def delete_strategy(
token_id,
url,
strategy_name,
force=False,
username=None,
user_domain_name=None,
tenant=None,
auth_type=AUTH_TYPES.KEYSTONE,
):
"""
Software Update - Delete Strategy
"""
api_cmd = url + "/api/orchestration/%s/strategy" % strategy_name
api_cmd_headers = dict()
api_cmd_headers['Content-Type'] = "application/json"
api_cmd_headers["Content-Type"] = "application/json"
if username:
api_cmd_headers['X-User'] = username
api_cmd_headers["X-User"] = username
if tenant:
api_cmd_headers['X-Tenant'] = tenant
api_cmd_headers["X-Tenant"] = tenant
if user_domain_name:
api_cmd_headers['X-User-Domain-Name'] = user_domain_name
api_cmd_headers["X-User-Domain-Name"] = user_domain_name
api_cmd_payload = dict()
api_cmd_payload['force'] = force
api_cmd_payload["force"] = force
response = rest_api.request(token_id, "DELETE", api_cmd, api_cmd_headers,
json.dumps(api_cmd_payload),
auth_type=auth_type)
response = rest_api.request(
token_id,
"DELETE",
api_cmd,
api_cmd_headers,
json.dumps(api_cmd_payload),
auth_type=auth_type,
)
# We expect an empty response body for this request (204 NO CONTENT). If
# there is no response body it is a 404 NOT FOUND which means there was
# no strategy to delete.
@@ -358,72 +393,101 @@ def delete_strategy(token_id, url, strategy_name, force=False,
return True
def apply_strategy(token_id, url, strategy_name, stage_id=None,
username=None, user_domain_name=None, tenant=None,
auth_type=AUTH_TYPES.KEYSTONE):
def apply_strategy(
token_id,
url,
strategy_name,
stage_id=None,
username=None,
user_domain_name=None,
tenant=None,
auth_type=AUTH_TYPES.KEYSTONE,
):
"""
Software Update - Apply Strategy
"""
api_cmd = url + ("/api/orchestration/%s/strategy/actions" % strategy_name)
api_cmd_headers = dict()
api_cmd_headers['Content-Type'] = "application/json"
api_cmd_headers["Content-Type"] = "application/json"
if username:
api_cmd_headers['X-User'] = username
api_cmd_headers["X-User"] = username
if tenant:
api_cmd_headers['X-Tenant'] = tenant
api_cmd_headers["X-Tenant"] = tenant
if user_domain_name:
api_cmd_headers['X-User-Domain-Name'] = user_domain_name
api_cmd_headers["X-User-Domain-Name"] = user_domain_name
api_cmd_payload = dict()
if stage_id is None:
api_cmd_payload['action'] = 'apply-all'
api_cmd_payload["action"] = "apply-all"
else:
api_cmd_payload['action'] = 'apply-stage'
api_cmd_payload['stage-id'] = stage_id
api_cmd_payload["action"] = "apply-stage"
api_cmd_payload["stage-id"] = stage_id
response = rest_api.request(token_id, "POST", api_cmd, api_cmd_headers,
json.dumps(api_cmd_payload),
auth_type=auth_type)
response = rest_api.request(
token_id,
"POST",
api_cmd,
api_cmd_headers,
json.dumps(api_cmd_payload),
auth_type=auth_type,
)
if not response:
return None
return _get_strategy_object_from_response(response)
def abort_strategy(token_id, url, strategy_name, stage_id, username=None,
user_domain_name=None, tenant=None,
auth_type=AUTH_TYPES.KEYSTONE):
def abort_strategy(
token_id,
url,
strategy_name,
stage_id,
username=None,
user_domain_name=None,
tenant=None,
auth_type=AUTH_TYPES.KEYSTONE,
):
"""
Software Update - Abort Strategy
"""
api_cmd = url + ("/api/orchestration/%s/strategy/actions" % strategy_name)
api_cmd_headers = dict()
api_cmd_headers['Content-Type'] = "application/json"
api_cmd_headers["Content-Type"] = "application/json"
if username:
api_cmd_headers['X-User'] = username
api_cmd_headers["X-User"] = username
if tenant:
api_cmd_headers['X-Tenant'] = tenant
api_cmd_headers["X-Tenant"] = tenant
if user_domain_name:
api_cmd_headers['X-User-Domain-Name'] = user_domain_name
api_cmd_headers["X-User-Domain-Name"] = user_domain_name
api_cmd_payload = dict()
api_cmd_payload['action'] = 'abort-stage'
api_cmd_payload['stage-id'] = stage_id
api_cmd_payload["action"] = "abort-stage"
api_cmd_payload["stage-id"] = stage_id
response = rest_api.request(token_id, "POST", api_cmd, api_cmd_headers,
json.dumps(api_cmd_payload),
auth_type=auth_type)
response = rest_api.request(
token_id,
"POST",
api_cmd,
api_cmd_headers,
json.dumps(api_cmd_payload),
auth_type=auth_type,
)
if not response:
return None
return _get_strategy_object_from_response(response)
def get_current_strategy(token_id, url, username=None,
user_domain_name=None, tenant=None,
auth_type=AUTH_TYPES.KEYSTONE):
def get_current_strategy(
token_id,
url,
username=None,
user_domain_name=None,
tenant=None,
auth_type=AUTH_TYPES.KEYSTONE,
):
"""
Get The Current Active Strategy Type And State
"""
@@ -431,15 +495,16 @@ def get_current_strategy(token_id, url, username=None,
api_cmd_headers = dict()
if username:
api_cmd_headers['X-User'] = username
api_cmd_headers["X-User"] = username
if tenant:
api_cmd_headers['X-Tenant'] = tenant
api_cmd_headers["X-Tenant"] = tenant
if user_domain_name:
api_cmd_headers['X-User-Domain-Name'] = user_domain_name
api_cmd_headers["X-User-Domain-Name"] = user_domain_name
response = rest_api.request(token_id, "GET", api_cmd, api_cmd_headers,
auth_type=auth_type)
if response['strategy'] is not None:
response = rest_api.request(
token_id, "GET", api_cmd, api_cmd_headers, auth_type=auth_type
)
if response["strategy"] is not None:
return _get_current_strategy_from_response(response)
return None
+324 -273
View File
@@ -66,10 +66,10 @@ def get_extra_create_args(cmd_area, args):
elif args.rollback and args.snapshot:
raise ValueError("Cannot set both rollback and snapshot")
return {
'release': args.release,
'rollback': args.rollback,
'delete': args.delete,
'snapshot': args.snapshot
"release": args.release,
"rollback": args.rollback,
"delete": args.delete,
"snapshot": args.snapshot,
}
elif sw_update.CMD_NAME_FW_UPDATE == cmd_area:
# no additional kwargs for firmware update
@@ -79,13 +79,10 @@ def get_extra_create_args(cmd_area, args):
return {}
elif sw_update.CMD_NAME_KUBE_ROOTCA_UPDATE == cmd_area:
# kube rootca update supports expiry_date and subject
return {
'expiry_date': args.expiry_date,
'subject': args.subject
}
return {"expiry_date": args.expiry_date, "subject": args.subject}
elif sw_update.CMD_NAME_KUBE_UPGRADE == cmd_area:
# kube upgrade supports: to_version
return {'to_version': args.to_version}
return {"to_version": args.to_version}
else:
raise ValueError("Unknown command area, %s, given" % cmd_area)
@@ -101,10 +98,9 @@ def add_list_arg(some_cmd, some_arg, some_list):
The list cannot be empty. The first item in the list is the default
"""
default = some_list[0]
some_cmd.add_argument(some_arg,
default=default,
choices=some_list,
help='defaults to ' + default)
some_cmd.add_argument(
some_arg, default=default, choices=some_list, help="defaults to " + default
)
def setup_abort_cmd(parser):
@@ -115,14 +111,12 @@ def setup_abort_cmd(parser):
:param parser: the strategy parser to add the create command to.
"""
abort_cmd = parser.add_parser('abort',
help='Abort a strategy')
abort_cmd.set_defaults(cmd='abort')
abort_cmd.add_argument('--stage-id',
help='stage identifier to abort')
abort_cmd.add_argument('--yes',
action='store_true',
help='automatically confirm the action')
abort_cmd = parser.add_parser("abort", help="Abort a strategy")
abort_cmd.set_defaults(cmd="abort")
abort_cmd.add_argument("--stage-id", help="stage identifier to abort")
abort_cmd.add_argument(
"--yes", action="store_true", help="automatically confirm the action"
)
return abort_cmd
@@ -134,26 +128,25 @@ def setup_apply_cmd(parser):
:param parser: the strategy parser to register the command under
"""
apply_cmd = parser.add_parser('apply',
help='Apply a strategy')
apply_cmd.set_defaults(cmd='apply')
apply_cmd.add_argument('--stage-id',
default=None,
help='stage identifier to apply')
apply_cmd.add_argument('--yes',
action='store_true',
help='automatically confirm the action')
apply_cmd = parser.add_parser("apply", help="Apply a strategy")
apply_cmd.set_defaults(cmd="apply")
apply_cmd.add_argument("--stage-id", default=None, help="stage identifier to apply")
apply_cmd.add_argument(
"--yes", action="store_true", help="automatically confirm the action"
)
return apply_cmd
def setup_create_cmd(parser,
controller_types,
storage_types,
worker_types,
instance_actions,
alarm_restrictions,
min_parallel=1,
max_parallel=5):
def setup_create_cmd(
parser,
controller_types,
storage_types,
worker_types,
instance_actions,
alarm_restrictions,
min_parallel=1,
max_parallel=5,
):
"""
Sets up a 'create' command for a strategy command parser.
@@ -170,18 +163,20 @@ def setup_create_cmd(parser,
The lists cannot be empty. The first item in the lists is the default
"""
create_cmd = parser.add_parser('create', help='Create a strategy')
create_cmd.set_defaults(cmd='create')
create_cmd = parser.add_parser("create", help="Create a strategy")
create_cmd.set_defaults(cmd="create")
add_list_arg(create_cmd, '--controller-apply-type', controller_types)
add_list_arg(create_cmd, '--storage-apply-type', storage_types)
add_list_arg(create_cmd, '--worker-apply-type', worker_types)
add_list_arg(create_cmd, '--instance-action', instance_actions)
add_list_arg(create_cmd, '--alarm-restrictions', alarm_restrictions)
create_cmd.add_argument('--max-parallel-worker-hosts',
type=int,
choices=list(range(min_parallel, max_parallel + 1)),
help='maximum worker hosts to update in parallel')
add_list_arg(create_cmd, "--controller-apply-type", controller_types)
add_list_arg(create_cmd, "--storage-apply-type", storage_types)
add_list_arg(create_cmd, "--worker-apply-type", worker_types)
add_list_arg(create_cmd, "--instance-action", instance_actions)
add_list_arg(create_cmd, "--alarm-restrictions", alarm_restrictions)
create_cmd.add_argument(
"--max-parallel-worker-hosts",
type=int,
choices=list(range(min_parallel, max_parallel + 1)),
help="maximum worker hosts to update in parallel",
)
return create_cmd
@@ -194,11 +189,9 @@ def setup_delete_cmd(parser):
:param parser: the strategy parser to register the command under
"""
delete_cmd = parser.add_parser('delete', help='Delete a strategy')
delete_cmd.set_defaults(cmd='delete')
delete_cmd.add_argument('--force',
action='store_true',
help=argparse.SUPPRESS)
delete_cmd = parser.add_parser("delete", help="Delete a strategy")
delete_cmd.set_defaults(cmd="delete")
delete_cmd.add_argument("--force", action="store_true", help=argparse.SUPPRESS)
return delete_cmd
@@ -210,17 +203,19 @@ def setup_show_cmd(parser):
:param parser: the strategy parser to register the command under
"""
show_cmd = parser.add_parser('show', help='Show a strategy')
show_cmd.set_defaults(cmd='show')
show_cmd.add_argument('--details',
action='store_true',
help='show strategy details')
show_cmd.add_argument('--active',
action='store_true',
help='show currently active strategy step')
show_cmd.add_argument('--error-details',
action='store_true',
help='show error details of failed strategy step')
show_cmd = parser.add_parser("show", help="Show a strategy")
show_cmd.set_defaults(cmd="show")
show_cmd.add_argument(
"--details", action="store_true", help="show strategy details"
)
show_cmd.add_argument(
"--active", action="store_true", help="show currently active strategy step"
)
show_cmd.add_argument(
"--error-details",
action="store_true",
help="show error details of failed strategy step",
)
return show_cmd
@@ -229,12 +224,10 @@ def setup_fw_update_parser(commands):
cmd_area = sw_update.CMD_NAME_FW_UPDATE
register_strategy(cmd_area, sw_update.STRATEGY_NAME_FW_UPDATE)
cmd_parser = commands.add_parser(cmd_area,
help='Firmware Update Strategy')
cmd_parser = commands.add_parser(cmd_area, help="Firmware Update Strategy")
cmd_parser.set_defaults(cmd_area=cmd_area)
sub_cmds = cmd_parser.add_subparsers(title='Firmware Update Commands',
metavar='')
sub_cmds = cmd_parser.add_subparsers(title="Firmware Update Commands", metavar="")
sub_cmds.required = True
# define the create command
@@ -243,15 +236,21 @@ def setup_fw_update_parser(commands):
sub_cmds,
[sw_update.APPLY_TYPE_IGNORE], # controller supports ignore
[sw_update.APPLY_TYPE_IGNORE], # storage supports ignore
[sw_update.APPLY_TYPE_SERIAL, # worker supports serial and parallel
sw_update.APPLY_TYPE_PARALLEL,
sw_update.APPLY_TYPE_IGNORE],
[sw_update.INSTANCE_ACTION_STOP_START, # instance actions
sw_update.INSTANCE_ACTION_MIGRATE],
[sw_update.ALARM_RESTRICTIONS_STRICT, # alarm restrictions
sw_update.ALARM_RESTRICTIONS_RELAXED],
[
sw_update.APPLY_TYPE_SERIAL, # worker supports serial and parallel
sw_update.APPLY_TYPE_PARALLEL,
sw_update.APPLY_TYPE_IGNORE,
],
[
sw_update.INSTANCE_ACTION_STOP_START, # instance actions
sw_update.INSTANCE_ACTION_MIGRATE,
],
[
sw_update.ALARM_RESTRICTIONS_STRICT, # alarm restrictions
sw_update.ALARM_RESTRICTIONS_RELAXED,
],
min_parallel=2,
max_parallel=5 # fw update supports 2..5 workers in parallel
max_parallel=5, # fw update supports 2..5 workers in parallel
)
# There are no additional create options for firmware update
@@ -270,42 +269,51 @@ def setup_kube_rootca_update_parser(commands):
cmd_area = sw_update.CMD_NAME_KUBE_ROOTCA_UPDATE
register_strategy(cmd_area, sw_update.STRATEGY_NAME_KUBE_ROOTCA_UPDATE)
cmd_parser = commands.add_parser(cmd_area,
help='Kubernetes RootCA Update Strategy')
cmd_parser = commands.add_parser(cmd_area, help="Kubernetes RootCA Update Strategy")
cmd_parser.set_defaults(cmd_area=cmd_area)
sub_cmds = cmd_parser.add_subparsers(
title='Kubernetes RootCA Update Commands',
metavar='')
title="Kubernetes RootCA Update Commands", metavar=""
)
sub_cmds.required = True
# define the create command
create_strategy_cmd = setup_create_cmd(
sub_cmds,
[sw_update.APPLY_TYPE_SERIAL, # controller supports serial only
sw_update.APPLY_TYPE_IGNORE],
[sw_update.APPLY_TYPE_SERIAL, # storage supports serial only
sw_update.APPLY_TYPE_IGNORE],
[sw_update.APPLY_TYPE_SERIAL, # worker supports serial and parallel
sw_update.APPLY_TYPE_PARALLEL,
sw_update.APPLY_TYPE_IGNORE],
[sw_update.INSTANCE_ACTION_STOP_START, # instance actions
sw_update.INSTANCE_ACTION_MIGRATE],
[sw_update.ALARM_RESTRICTIONS_STRICT, # alarm restrictions
sw_update.ALARM_RESTRICTIONS_RELAXED],
[
sw_update.APPLY_TYPE_SERIAL, # controller supports serial only
sw_update.APPLY_TYPE_IGNORE,
],
[
sw_update.APPLY_TYPE_SERIAL, # storage supports serial only
sw_update.APPLY_TYPE_IGNORE,
],
[
sw_update.APPLY_TYPE_SERIAL, # worker supports serial and parallel
sw_update.APPLY_TYPE_PARALLEL,
sw_update.APPLY_TYPE_IGNORE,
],
[
sw_update.INSTANCE_ACTION_STOP_START, # instance actions
sw_update.INSTANCE_ACTION_MIGRATE,
],
[
sw_update.ALARM_RESTRICTIONS_STRICT, # alarm restrictions
sw_update.ALARM_RESTRICTIONS_RELAXED,
],
min_parallel=2,
max_parallel=10 # kube rootca update support 2..10 workers in parallel
max_parallel=10, # kube rootca update support 2..10 workers in parallel
)
# add specific arguments to the create command for kube root ca update
# The get_extra_create_args method is updated to align with these
create_strategy_cmd.add_argument(
'--expiry-date',
"--expiry-date",
required=False,
help='When the generated certificate should expire (yyyy-mm-dd)')
help="When the generated certificate should expire (yyyy-mm-dd)",
)
create_strategy_cmd.add_argument(
'--subject',
required=False,
help='Subject for the generated certificate')
"--subject", required=False, help="Subject for the generated certificate"
)
# define the delete command
_ = setup_delete_cmd(sub_cmds)
@@ -322,39 +330,48 @@ def setup_kube_upgrade_parser(commands):
cmd_area = sw_update.CMD_NAME_KUBE_UPGRADE
register_strategy(cmd_area, sw_update.STRATEGY_NAME_KUBE_UPGRADE)
cmd_parser = commands.add_parser(cmd_area,
help='Kubernetes Upgrade Strategy')
cmd_parser = commands.add_parser(cmd_area, help="Kubernetes Upgrade Strategy")
cmd_parser.set_defaults(cmd_area=cmd_area)
sub_cmds = cmd_parser.add_subparsers(title='Kubernetes Upgrade Commands',
metavar='')
sub_cmds = cmd_parser.add_subparsers(
title="Kubernetes Upgrade Commands", metavar=""
)
sub_cmds.required = True
# define the create command
create_strategy_cmd = setup_create_cmd(
sub_cmds,
[sw_update.APPLY_TYPE_SERIAL, # controller supports serial only
sw_update.APPLY_TYPE_IGNORE],
[sw_update.APPLY_TYPE_SERIAL, # storage supports serial only
sw_update.APPLY_TYPE_IGNORE],
[sw_update.APPLY_TYPE_SERIAL, # worker supports serial and parallel
sw_update.APPLY_TYPE_PARALLEL,
sw_update.APPLY_TYPE_IGNORE],
[sw_update.INSTANCE_ACTION_STOP_START, # instance actions
sw_update.INSTANCE_ACTION_MIGRATE],
[sw_update.ALARM_RESTRICTIONS_STRICT, # alarm restrictions
sw_update.ALARM_RESTRICTIONS_RELAXED],
[
sw_update.APPLY_TYPE_SERIAL, # controller supports serial only
sw_update.APPLY_TYPE_IGNORE,
],
[
sw_update.APPLY_TYPE_SERIAL, # storage supports serial only
sw_update.APPLY_TYPE_IGNORE,
],
[
sw_update.APPLY_TYPE_SERIAL, # worker supports serial and parallel
sw_update.APPLY_TYPE_PARALLEL,
sw_update.APPLY_TYPE_IGNORE,
],
[
sw_update.INSTANCE_ACTION_STOP_START, # instance actions
sw_update.INSTANCE_ACTION_MIGRATE,
],
[
sw_update.ALARM_RESTRICTIONS_STRICT, # alarm restrictions
sw_update.ALARM_RESTRICTIONS_RELAXED,
],
min_parallel=2,
max_parallel=10 # kube upgrade supports 2..10 workers in parallel
max_parallel=10, # kube upgrade supports 2..10 workers in parallel
)
# add kube specific arguments to the create command
# The get_extra_create_args method is updated to align with these
# kube upgrade create requires 'to-version'
create_strategy_cmd.add_argument(
'--to-version',
required=True,
help='The kubernetes version')
"--to-version", required=True, help="The kubernetes version"
)
# define the delete command
_ = setup_delete_cmd(sub_cmds)
@@ -371,31 +388,41 @@ def setup_system_config_update_parser(commands):
cmd_area = sw_update.CMD_NAME_SYSTEM_CONFIG_UPDATE
register_strategy(cmd_area, sw_update.STRATEGY_NAME_SYSTEM_CONFIG_UPDATE)
cmd_parser = commands.add_parser(cmd_area,
help='system config update Strategy')
cmd_parser = commands.add_parser(cmd_area, help="system config update Strategy")
cmd_parser.set_defaults(cmd_area=cmd_area)
sub_cmds = cmd_parser.add_subparsers(title='Sytem Config Update Commands',
metavar='')
sub_cmds = cmd_parser.add_subparsers(
title="Sytem Config Update Commands", metavar=""
)
sub_cmds.required = True
# define the create command
# alarm restrictions, defaults to strict
_ = setup_create_cmd(
sub_cmds,
[sw_update.APPLY_TYPE_SERIAL, # controller supports serial only
sw_update.APPLY_TYPE_IGNORE],
[sw_update.APPLY_TYPE_SERIAL, # storage supports serial only
sw_update.APPLY_TYPE_IGNORE],
[sw_update.APPLY_TYPE_SERIAL, # worker supports serial and parallel
sw_update.APPLY_TYPE_PARALLEL,
sw_update.APPLY_TYPE_IGNORE],
[sw_update.INSTANCE_ACTION_STOP_START, # instance actions
sw_update.INSTANCE_ACTION_MIGRATE],
[sw_update.ALARM_RESTRICTIONS_STRICT, # alarm restrictions
sw_update.ALARM_RESTRICTIONS_RELAXED],
[
sw_update.APPLY_TYPE_SERIAL, # controller supports serial only
sw_update.APPLY_TYPE_IGNORE,
],
[
sw_update.APPLY_TYPE_SERIAL, # storage supports serial only
sw_update.APPLY_TYPE_IGNORE,
],
[
sw_update.APPLY_TYPE_SERIAL, # worker supports serial and parallel
sw_update.APPLY_TYPE_PARALLEL,
sw_update.APPLY_TYPE_IGNORE,
],
[
sw_update.INSTANCE_ACTION_STOP_START, # instance actions
sw_update.INSTANCE_ACTION_MIGRATE,
],
[
sw_update.ALARM_RESTRICTIONS_STRICT, # alarm restrictions
sw_update.ALARM_RESTRICTIONS_RELAXED,
],
min_parallel=2,
max_parallel=100 # config update supports 2..100 workers in parallel
max_parallel=100, # config update supports 2..100 workers in parallel
)
# define the delete command
@@ -414,33 +441,40 @@ def setup_sw_deploy_parser(commands):
cmd_area = sw_update.CMD_NAME_SW_DEPLOY
# TODO(jkraitbe): Backend for sw-deploy will continue as old sw-upgrade for now
register_strategy(cmd_area, sw_update.STRATEGY_NAME_SW_UPGRADE)
cmd_parser = commands.add_parser(cmd_area,
help='Software Deploy Strategy')
cmd_parser = commands.add_parser(cmd_area, help="Software Deploy Strategy")
cmd_parser.set_defaults(cmd_area=cmd_area)
sub_cmds = cmd_parser.add_subparsers(title='Software Deploy Commands',
metavar='[create, delete, apply, abort, show]')
sub_cmds = cmd_parser.add_subparsers(
title="Software Deploy Commands", metavar="[create, delete, apply, abort, show]"
)
sub_cmds.required = True
# define the create command
# alarm restrictions, defaults to strict
create_strategy_cmd = setup_create_cmd(
sub_cmds,
[sw_update.APPLY_TYPE_SERIAL,
sw_update.APPLY_TYPE_IGNORE],
[sw_update.APPLY_TYPE_SERIAL, # storage supports serial and parallel
sw_update.APPLY_TYPE_PARALLEL,
sw_update.APPLY_TYPE_IGNORE],
[sw_update.APPLY_TYPE_SERIAL, # worker supports serial and parallel
sw_update.APPLY_TYPE_PARALLEL,
sw_update.APPLY_TYPE_IGNORE],
[sw_update.INSTANCE_ACTION_STOP_START, # instance actions
sw_update.INSTANCE_ACTION_MIGRATE],
[sw_update.ALARM_RESTRICTIONS_STRICT, # alarm restrictions
sw_update.ALARM_RESTRICTIONS_RELAXED,
sw_update.ALARM_RESTRICTIONS_PERMISSIVE],
[sw_update.APPLY_TYPE_SERIAL, sw_update.APPLY_TYPE_IGNORE],
[
sw_update.APPLY_TYPE_SERIAL, # storage supports serial and parallel
sw_update.APPLY_TYPE_PARALLEL,
sw_update.APPLY_TYPE_IGNORE,
],
[
sw_update.APPLY_TYPE_SERIAL, # worker supports serial and parallel
sw_update.APPLY_TYPE_PARALLEL,
sw_update.APPLY_TYPE_IGNORE,
],
[
sw_update.INSTANCE_ACTION_STOP_START, # instance actions
sw_update.INSTANCE_ACTION_MIGRATE,
],
[
sw_update.ALARM_RESTRICTIONS_STRICT, # alarm restrictions
sw_update.ALARM_RESTRICTIONS_RELAXED,
sw_update.ALARM_RESTRICTIONS_PERMISSIVE,
],
min_parallel=2,
max_parallel=10 # SW Deploy supports 2..10 workers in parallel
max_parallel=10, # SW Deploy supports 2..10 workers in parallel
)
# add sw-deploy specific arguments to the create command
@@ -452,28 +486,33 @@ def setup_sw_deploy_parser(commands):
# These modes are mutually exclusive.
# sw-deploy create (upgrade)
create_strategy_cmd.add_argument('release',
help='software release for deployment',
default=None,
nargs="?")
create_strategy_cmd.add_argument(
"release", help="software release for deployment", default=None, nargs="?"
)
# sw-deploy create (rollback)
create_strategy_cmd.add_argument('--rollback',
help='Perform a rollback instead of upgrade',
action=argparse.BooleanOptionalAction,
required=False)
create_strategy_cmd.add_argument(
"--rollback",
help="Perform a rollback instead of upgrade",
action=argparse.BooleanOptionalAction,
required=False,
)
# sw-deploy create (delete)
create_strategy_cmd.add_argument('--delete',
help='add delete option',
action=argparse.BooleanOptionalAction,
required=False)
create_strategy_cmd.add_argument(
"--delete",
help="add delete option",
action=argparse.BooleanOptionalAction,
required=False,
)
# sw-deploy create (snapshot)
create_strategy_cmd.add_argument('--snapshot',
help='add snapshot option',
action=argparse.BooleanOptionalAction,
required=False)
create_strategy_cmd.add_argument(
"--snapshot",
help="add snapshot option",
action=argparse.BooleanOptionalAction,
required=False,
)
# define the delete command
_ = setup_delete_cmd(sub_cmds)
@@ -505,15 +544,16 @@ def input_with_timeout(prompt, timeout):
def prompt_cli_confirmation(timeout=10):
RESET = "\033[0m"
YELLOW = '\033[93m'
BOLD = '\033[1m'
YELLOW = "\033[93m"
BOLD = "\033[1m"
confirmation = input_with_timeout(
f"{BOLD}{YELLOW}WARNING: This is a high-risk operation that may "
f"cause a service interruption or remove critical resources{RESET}\n"
f"{BOLD}{YELLOW}Do you want to continue? (yes/No): {RESET}", timeout
)
f"{BOLD}{YELLOW}WARNING: This is a high-risk operation that may "
f"cause a service interruption or remove critical resources{RESET}\n"
f"{BOLD}{YELLOW}Do you want to continue? (yes/No): {RESET}",
timeout,
)
if confirmation.lower() != 'yes':
if confirmation.lower() != "yes":
print("Operation cancelled by the user")
sys.exit(1)
@@ -524,15 +564,13 @@ def _is_service_impacting_command(command):
"fw-update-strategy",
"kube-upgrade-strategy",
"kube-rootca-update-strategy",
"system-config-update-strategy"
"system-config-update-strategy",
]
actions = ["apply", "abort"]
service_impacting_commands = {
f"{cmd} {action}"
for cmd in base_commands
for action in actions
f"{cmd} {action}" for cmd in base_commands for action in actions
}
return command in service_impacting_commands
@@ -554,22 +592,23 @@ def process_main(argv=sys.argv[1:]): # pylint: disable=dangerous-default-value
"""
try:
parser = argparse.ArgumentParser()
parser.add_argument('--debug', action='store_true')
parser.add_argument('--os-auth-url', default=None)
parser.add_argument('--os-project-name', default=None)
parser.add_argument('--os-project-domain-name', default=None)
parser.add_argument('--os-username', default=None)
parser.add_argument('--os-password', default=None)
parser.add_argument('--os-user-domain-name', default=None)
parser.add_argument('--os-region-name', default=None)
parser.add_argument('--os-interface', default=None)
parser.add_argument('--stx-auth-type',
default=os.environ.get('STX_AUTH_TYPE', "keystone").lower(),
choices=['keystone', 'oidc'],
help="Authentication type: keystone or oidc (Env: STX_AUTH_TYPE)"
)
parser.add_argument("--debug", action="store_true")
parser.add_argument("--os-auth-url", default=None)
parser.add_argument("--os-project-name", default=None)
parser.add_argument("--os-project-domain-name", default=None)
parser.add_argument("--os-username", default=None)
parser.add_argument("--os-password", default=None)
parser.add_argument("--os-user-domain-name", default=None)
parser.add_argument("--os-region-name", default=None)
parser.add_argument("--os-interface", default=None)
parser.add_argument(
"--stx-auth-type",
default=os.environ.get("STX_AUTH_TYPE", "keystone").lower(),
choices=["keystone", "oidc"],
help="Authentication type: keystone or oidc (Env: STX_AUTH_TYPE)",
)
commands = parser.add_subparsers(title='Commands', metavar='')
commands = parser.add_subparsers(title="Commands", metavar="")
commands.required = True
# Add firmware update strategy commands
@@ -599,29 +638,30 @@ def process_main(argv=sys.argv[1:]): # pylint: disable=dangerous-default-value
http_client.HTTPConnection.debuglevel = 1
if args.os_auth_url is None:
args.os_auth_url = os.environ.get('OS_AUTH_URL', None)
args.os_auth_url = os.environ.get("OS_AUTH_URL", None)
if args.os_project_name is None:
args.os_project_name = os.environ.get('OS_PROJECT_NAME', None)
args.os_project_name = os.environ.get("OS_PROJECT_NAME", None)
if args.os_project_domain_name is None:
args.os_project_domain_name \
= os.environ.get('OS_PROJECT_DOMAIN_NAME', 'Default')
args.os_project_domain_name = os.environ.get(
"OS_PROJECT_DOMAIN_NAME", "Default"
)
if args.os_username is None:
args.os_username = os.environ.get('OS_USERNAME', None)
args.os_username = os.environ.get("OS_USERNAME", None)
if args.os_password is None:
args.os_password = os.environ.get('OS_PASSWORD', None)
args.os_password = os.environ.get("OS_PASSWORD", None)
if args.os_user_domain_name is None:
args.os_user_domain_name = os.environ.get('OS_USER_DOMAIN_NAME', None)
args.os_user_domain_name = os.environ.get("OS_USER_DOMAIN_NAME", None)
if args.os_region_name is None:
args.os_region_name = os.environ.get('OS_REGION_NAME', None)
args.os_region_name = os.environ.get("OS_REGION_NAME", None)
if args.os_interface is None:
args.os_interface = os.environ.get('OS_INTERFACE', None)
args.os_interface = os.environ.get("OS_INTERFACE", None)
if args.os_auth_url is None:
print("Authentication URI not given")
@@ -660,79 +700,90 @@ def process_main(argv=sys.argv[1:]): # pylint: disable=dangerous-default-value
cli_conf_param_enabled = _is_cli_confirmation_param_enabled()
confirm_if_required(args, command, cli_conf_param_enabled)
if 'create' == args.cmd:
if "create" == args.cmd:
extra_create_args = get_extra_create_args(args.cmd_area, args)
sw_update.create_strategy(args.os_auth_url,
args.os_project_name,
args.os_project_domain_name,
args.os_username,
args.os_password,
args.os_user_domain_name,
args.os_region_name,
args.os_interface,
strategy_name,
args.controller_apply_type,
args.storage_apply_type,
sw_update.APPLY_TYPE_IGNORE,
args.worker_apply_type,
args.max_parallel_worker_hosts,
args.instance_action,
args.alarm_restrictions,
args.stx_auth_type,
**extra_create_args)
elif 'delete' == args.cmd:
sw_update.delete_strategy(args.os_auth_url,
args.os_project_name,
args.os_project_domain_name,
args.os_username,
args.os_password,
args.os_user_domain_name,
args.os_region_name,
args.os_interface,
strategy_name,
args.stx_auth_type,
force=args.force)
elif 'apply' == args.cmd:
sw_update.apply_strategy(args.os_auth_url,
args.os_project_name,
args.os_project_domain_name,
args.os_username,
args.os_password,
args.os_user_domain_name,
args.os_region_name,
args.os_interface,
strategy_name,
args.stx_auth_type,
stage_id=args.stage_id)
elif 'abort' == args.cmd:
sw_update.abort_strategy(args.os_auth_url,
args.os_project_name,
args.os_project_domain_name,
args.os_username,
args.os_password,
args.os_user_domain_name,
args.os_region_name,
args.os_interface,
strategy_name,
args.stx_auth_type,
stage_id=args.stage_id)
elif 'show' == args.cmd:
sw_update.show_strategy(args.os_auth_url,
args.os_project_name,
args.os_project_domain_name,
args.os_username,
args.os_password,
args.os_user_domain_name,
args.os_region_name,
args.os_interface,
strategy_name,
args.stx_auth_type,
details=args.details,
active=args.active,
error_details=args.error_details)
sw_update.create_strategy(
args.os_auth_url,
args.os_project_name,
args.os_project_domain_name,
args.os_username,
args.os_password,
args.os_user_domain_name,
args.os_region_name,
args.os_interface,
strategy_name,
args.controller_apply_type,
args.storage_apply_type,
sw_update.APPLY_TYPE_IGNORE,
args.worker_apply_type,
args.max_parallel_worker_hosts,
args.instance_action,
args.alarm_restrictions,
args.stx_auth_type,
**extra_create_args,
)
elif "delete" == args.cmd:
sw_update.delete_strategy(
args.os_auth_url,
args.os_project_name,
args.os_project_domain_name,
args.os_username,
args.os_password,
args.os_user_domain_name,
args.os_region_name,
args.os_interface,
strategy_name,
args.stx_auth_type,
force=args.force,
)
elif "apply" == args.cmd:
sw_update.apply_strategy(
args.os_auth_url,
args.os_project_name,
args.os_project_domain_name,
args.os_username,
args.os_password,
args.os_user_domain_name,
args.os_region_name,
args.os_interface,
strategy_name,
args.stx_auth_type,
stage_id=args.stage_id,
)
elif "abort" == args.cmd:
sw_update.abort_strategy(
args.os_auth_url,
args.os_project_name,
args.os_project_domain_name,
args.os_username,
args.os_password,
args.os_user_domain_name,
args.os_region_name,
args.os_interface,
strategy_name,
args.stx_auth_type,
stage_id=args.stage_id,
)
elif "show" == args.cmd:
sw_update.show_strategy(
args.os_auth_url,
args.os_project_name,
args.os_project_domain_name,
args.os_username,
args.os_password,
args.os_user_domain_name,
args.os_region_name,
args.os_interface,
strategy_name,
args.stx_auth_type,
details=args.details,
active=args.active,
error_details=args.error_details,
)
else:
raise ValueError("Unknown command, %s, given for %s"
% (args.cmd, args.cmd_area))
raise ValueError(
"Unknown command, %s, given for %s" % (args.cmd, args.cmd_area)
)
except KeyboardInterrupt:
print("Keyboard Interrupt received.")
+29 -25
View File
@@ -1,28 +1,32 @@
# Copyright (c) 2016-2024 Wind River Systems, Inc.
# Copyright (c) 2016-2024, 2026 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
from nfv_client.sw_update._sw_update import abort_strategy # noqa: F401
from nfv_client.sw_update._sw_update import ALARM_RESTRICTIONS_PERMISSIVE # noqa: F401
from nfv_client.sw_update._sw_update import ALARM_RESTRICTIONS_RELAXED # noqa: F401
from nfv_client.sw_update._sw_update import ALARM_RESTRICTIONS_STRICT # noqa: F401
from nfv_client.sw_update._sw_update import apply_strategy # noqa: F401
from nfv_client.sw_update._sw_update import APPLY_TYPE_IGNORE # noqa: F401
from nfv_client.sw_update._sw_update import APPLY_TYPE_PARALLEL # noqa: F401
from nfv_client.sw_update._sw_update import APPLY_TYPE_SERIAL # noqa: F401
from nfv_client.sw_update._sw_update import CMD_NAME_FW_UPDATE # noqa: F401
from nfv_client.sw_update._sw_update import CMD_NAME_KUBE_ROOTCA_UPDATE # noqa: F401
from nfv_client.sw_update._sw_update import CMD_NAME_KUBE_UPGRADE # noqa: F401
from nfv_client.sw_update._sw_update import CMD_NAME_SW_DEPLOY # noqa: F401
from nfv_client.sw_update._sw_update import CMD_NAME_SYSTEM_CONFIG_UPDATE # noqa: F401
from nfv_client.sw_update._sw_update import create_strategy # noqa: F401
from nfv_client.sw_update._sw_update import delete_strategy # noqa: F401
from nfv_client.sw_update._sw_update import INSTANCE_ACTION_MIGRATE # noqa: F401
from nfv_client.sw_update._sw_update import INSTANCE_ACTION_STOP_START # noqa: F401
from nfv_client.sw_update._sw_update import show_strategy # noqa: F401
from nfv_client.sw_update._sw_update import STRATEGY_NAME_FW_UPDATE # noqa: F401
from nfv_client.sw_update._sw_update import STRATEGY_NAME_KUBE_ROOTCA_UPDATE # noqa: F401
from nfv_client.sw_update._sw_update import STRATEGY_NAME_KUBE_UPGRADE # noqa: F401
from nfv_client.sw_update._sw_update import STRATEGY_NAME_SW_DEPLOY # noqa: F401
from nfv_client.sw_update._sw_update import STRATEGY_NAME_SW_UPGRADE # noqa: F401
from nfv_client.sw_update._sw_update import STRATEGY_NAME_SYSTEM_CONFIG_UPDATE # noqa: F401
# TODO(rlima): this disables flake8 in the whole file as there is no
# way to suppress a specific warning.
# flake8: noqa
from nfv_client.sw_update._sw_update import abort_strategy
from nfv_client.sw_update._sw_update import ALARM_RESTRICTIONS_PERMISSIVE
from nfv_client.sw_update._sw_update import ALARM_RESTRICTIONS_RELAXED
from nfv_client.sw_update._sw_update import ALARM_RESTRICTIONS_STRICT
from nfv_client.sw_update._sw_update import apply_strategy
from nfv_client.sw_update._sw_update import APPLY_TYPE_IGNORE
from nfv_client.sw_update._sw_update import APPLY_TYPE_PARALLEL
from nfv_client.sw_update._sw_update import APPLY_TYPE_SERIAL
from nfv_client.sw_update._sw_update import CMD_NAME_FW_UPDATE
from nfv_client.sw_update._sw_update import CMD_NAME_KUBE_ROOTCA_UPDATE
from nfv_client.sw_update._sw_update import CMD_NAME_KUBE_UPGRADE
from nfv_client.sw_update._sw_update import CMD_NAME_SW_DEPLOY
from nfv_client.sw_update._sw_update import CMD_NAME_SYSTEM_CONFIG_UPDATE
from nfv_client.sw_update._sw_update import create_strategy
from nfv_client.sw_update._sw_update import delete_strategy
from nfv_client.sw_update._sw_update import INSTANCE_ACTION_MIGRATE
from nfv_client.sw_update._sw_update import INSTANCE_ACTION_STOP_START
from nfv_client.sw_update._sw_update import show_strategy
from nfv_client.sw_update._sw_update import STRATEGY_NAME_FW_UPDATE
from nfv_client.sw_update._sw_update import STRATEGY_NAME_KUBE_ROOTCA_UPDATE
from nfv_client.sw_update._sw_update import STRATEGY_NAME_KUBE_UPGRADE
from nfv_client.sw_update._sw_update import STRATEGY_NAME_SW_DEPLOY
from nfv_client.sw_update._sw_update import STRATEGY_NAME_SW_UPGRADE
from nfv_client.sw_update._sw_update import STRATEGY_NAME_SYSTEM_CONFIG_UPDATE
+276 -157
View File
@@ -12,35 +12,35 @@ from nfv_client.openstack import sw_update
from platform_util.oidc import oidc_utils
from urllib.parse import urlparse
STRATEGY_NAME_SW_DEPLOY = 'sw-deploy'
STRATEGY_NAME_SW_UPGRADE = 'sw-upgrade'
STRATEGY_NAME_FW_UPDATE = 'fw-update'
STRATEGY_NAME_KUBE_ROOTCA_UPDATE = 'kube-rootca-update'
STRATEGY_NAME_KUBE_UPGRADE = 'kube-upgrade'
STRATEGY_NAME_SYSTEM_CONFIG_UPDATE = 'system-config-update'
STRATEGY_NAME_SW_DEPLOY = "sw-deploy"
STRATEGY_NAME_SW_UPGRADE = "sw-upgrade"
STRATEGY_NAME_FW_UPDATE = "fw-update"
STRATEGY_NAME_KUBE_ROOTCA_UPDATE = "kube-rootca-update"
STRATEGY_NAME_KUBE_UPGRADE = "kube-upgrade"
STRATEGY_NAME_SYSTEM_CONFIG_UPDATE = "system-config-update"
CMD_NAME_SW_DEPLOY = 'sw-deploy-strategy'
CMD_NAME_FW_UPDATE = 'fw-update-strategy'
CMD_NAME_KUBE_ROOTCA_UPDATE = 'kube-rootca-update-strategy'
CMD_NAME_KUBE_UPGRADE = 'kube-upgrade-strategy'
CMD_NAME_SYSTEM_CONFIG_UPDATE = 'system-config-update-strategy'
CMD_NAME_SW_DEPLOY = "sw-deploy-strategy"
CMD_NAME_FW_UPDATE = "fw-update-strategy"
CMD_NAME_KUBE_ROOTCA_UPDATE = "kube-rootca-update-strategy"
CMD_NAME_KUBE_UPGRADE = "kube-upgrade-strategy"
CMD_NAME_SYSTEM_CONFIG_UPDATE = "system-config-update-strategy"
APPLY_TYPE_SERIAL = 'serial'
APPLY_TYPE_PARALLEL = 'parallel'
APPLY_TYPE_IGNORE = 'ignore'
APPLY_TYPE_SERIAL = "serial"
APPLY_TYPE_PARALLEL = "parallel"
APPLY_TYPE_IGNORE = "ignore"
INSTANCE_ACTION_MIGRATE = 'migrate'
INSTANCE_ACTION_STOP_START = 'stop-start'
INSTANCE_ACTION_MIGRATE = "migrate"
INSTANCE_ACTION_STOP_START = "stop-start"
ALARM_RESTRICTIONS_STRICT = 'strict'
ALARM_RESTRICTIONS_RELAXED = 'relaxed'
ALARM_RESTRICTIONS_PERMISSIVE = 'permissive'
ALARM_RESTRICTIONS_STRICT = "strict"
ALARM_RESTRICTIONS_RELAXED = "relaxed"
ALARM_RESTRICTIONS_PERMISSIVE = "permissive"
STRATEGY_APPLYING = 'applying'
STRATEGY_READY_TO_APPLY = 'ready-to-apply'
STRATEGY_APPLYING = "applying"
STRATEGY_READY_TO_APPLY = "ready-to-apply"
def _print(indent_by, field, value, remains=''):
def _print(indent_by, field, value, remains=""):
full_field = f"{field}:"
if isinstance(value, str) and "\n" in value:
full_field = f"{full_field} |\n"
@@ -50,12 +50,19 @@ def _print(indent_by, field, value, remains=''):
full_value = f"{value} {remains}"
if not (isinstance(value, str) and "\n" in value):
print("%s%s%s%s" % (' ' * indent_by, full_field,
' ' * (42 - indent_by - len('%s' % field) - 1), full_value))
print(
"%s%s%s%s"
% (
" " * indent_by,
full_field,
" " * (42 - indent_by - len("%s" % field) - 1),
full_value,
)
)
else:
full_value = textwrap.indent(full_value, " " * (indent_by + 2))
print("%s%s%s" % (' ' * indent_by, full_field, full_value))
print("%s%s%s" % (" " * indent_by, full_field, full_value))
def _display_strategy_step(strategy_step, active=False):
@@ -66,7 +73,7 @@ def _display_strategy_step(strategy_step, active=False):
# skip steps that are not started:'initial' or completed cleanly: 'success'
# this leaves failed and in-progress states
if active:
if strategy_step.result in ['initial', 'success']:
if strategy_step.result in ["initial", "success"]:
return False
_print(12, "step-id", strategy_step.step_id)
_print(12, "step-name", strategy_step.step_name)
@@ -76,7 +83,7 @@ def _display_strategy_step(strategy_step, active=False):
_print(12, "entity-names", strategy_step.entity_names)
if 0 < len(strategy_step.entity_uuids):
_print(12, "entity-uuids", strategy_step.entity_uuids)
_print(12, "timeout", strategy_step.timeout, 'seconds')
_print(12, "timeout", strategy_step.timeout, "seconds")
if 0 < len(strategy_step.start_date_time):
_print(12, "start-date-time", strategy_step.start_date_time)
if 0 < len(strategy_step.end_date_time):
@@ -108,8 +115,8 @@ def _get_current_stage_and_step(strategy):
for step in current_stage.steps:
current_step = step
if (
step.result not in ['initial', 'timed-out', 'success'] or
step == current_stage.steps[-1]
step.result not in ["initial", "timed-out", "success"]
or step == current_stage.steps[-1]
):
break
break
@@ -129,7 +136,7 @@ def _display_strategy_stage(strategy_stage, details=False, active=False):
_print(8, "stage-name", strategy_stage.stage_name)
_print(8, "total-steps", strategy_stage.total_steps)
_print(8, "current-step", strategy_stage.current_step)
_print(8, "timeout", strategy_stage.timeout, 'seconds')
_print(8, "timeout", strategy_stage.timeout, "seconds")
_print(8, "start-date-time", strategy_stage.start_date_time)
if strategy_stage.inprogress:
_print(8, "inprogress", "true")
@@ -158,9 +165,8 @@ def _display_strategy_phase(strategy_phase, details=False, active=False):
_print(4, "total-stages", strategy_phase.total_stages)
_print(4, "current-stage", strategy_phase.current_stage)
_print(4, "stop-at-stage", strategy_phase.stop_at_stage)
_print(4, "timeout", strategy_phase.timeout, 'seconds')
_print(4, "completion-percentage",
("%s%%" % strategy_phase.completion_percentage))
_print(4, "timeout", strategy_phase.timeout, "seconds")
_print(4, "completion-percentage", ("%s%%" % strategy_phase.completion_percentage))
_print(4, "start-date-time", strategy_phase.start_date_time)
if strategy_phase.inprogress:
_print(4, "inprogress", "true")
@@ -201,8 +207,7 @@ def _display_strategy(strategy, details=False, active=False, error_details=False
_print(2, "storage-apply-type", strategy.storage_apply_type)
_print(2, "worker-apply-type", strategy.worker_apply_type)
if APPLY_TYPE_PARALLEL == strategy.worker_apply_type:
_print(2, "max-parallel-worker-hosts",
strategy.max_parallel_worker_hosts)
_print(2, "max-parallel-worker-hosts", strategy.max_parallel_worker_hosts)
_print(2, "default-instance-action", strategy.default_instance_action)
_print(2, "alarm-restrictions", strategy.alarm_restrictions)
_print(2, "current-phase", strategy.current_phase)
@@ -213,8 +218,11 @@ def _display_strategy(strategy, details=False, active=False, error_details=False
_print(2, "current-step", current_step.step_name)
if current_step.entity_type == "hosts" and current_step.entity_names:
_print(2, "entity-names", current_step.entity_names)
_print(2, "current-phase-completion",
("%s%%" % strategy.current_phase_completion_percentage))
_print(
2,
"current-phase-completion",
("%s%%" % strategy.current_phase_completion_percentage),
)
_print(2, "state", strategy.state)
if details or active:
@@ -261,10 +269,17 @@ def _display_strategy(strategy, details=False, active=False, error_details=False
_print(2, "abort-error-response", strategy.abort_phase.response)
def _get_auth_token_and_url(os_auth_uri, os_project_name,
os_project_domain_name, os_username,
os_password, os_user_domain_name,
os_region_name, os_interface, stx_auth_type):
def _get_auth_token_and_url(
os_auth_uri,
os_project_name,
os_project_domain_name,
os_username,
os_password,
os_user_domain_name,
os_region_name,
os_interface,
stx_auth_type,
):
"""Get authentication context for OIDC or Keystone"""
if stx_auth_type == AUTH_TYPES.OIDC:
@@ -277,18 +292,18 @@ def _get_auth_token_and_url(os_auth_uri, os_project_name,
# TODO(rummadis): Generalize OIDC URL construction instead of hardcoding
# ports and protocols (similar to Keystone approach)
if os_interface == 'public':
protocol = 'https'
port = '4545'
elif os_interface == 'internal':
protocol = 'http'
port = '4545'
if os_interface == "public":
protocol = "https"
port = "4545"
elif os_interface == "internal":
protocol = "http"
port = "4545"
else: # admin
protocol = 'https'
port = '4546'
protocol = "https"
port = "4546"
# Handle IPv6
if controller_ip.count(':') >= 2 and not controller_ip.startswith("["):
if controller_ip.count(":") >= 2 and not controller_ip.startswith("["):
controller_ip = f"[{controller_ip}]"
url = f"{protocol}://{controller_ip}:{port}"
@@ -296,28 +311,49 @@ def _get_auth_token_and_url(os_auth_uri, os_project_name,
return token_id, url
else:
# Keystone authentication path
token = openstack.get_token(os_auth_uri, os_project_name,
os_project_domain_name, os_username,
os_password, os_user_domain_name)
token = openstack.get_token(
os_auth_uri,
os_project_name,
os_project_domain_name,
os_username,
os_password,
os_user_domain_name,
)
if token is None:
raise ValueError("Invalid keystone token")
url = token.get_service_url(os_region_name, openstack.SERVICE.VIM,
openstack.SERVICE_TYPE.NFV, os_interface)
url = token.get_service_url(
os_region_name,
openstack.SERVICE.VIM,
openstack.SERVICE_TYPE.NFV,
os_interface,
)
if url is None:
raise ValueError("NFV-VIM URL is invalid")
return token.get_id(), url
def create_strategy(os_auth_uri, os_project_name, os_project_domain_name,
os_username, os_password, os_user_domain_name,
os_region_name, os_interface,
strategy_name, controller_apply_type,
storage_apply_type, swift_apply_type, worker_apply_type,
max_parallel_worker_hosts,
default_instance_action, alarm_restrictions, stx_auth_type,
**kwargs):
def create_strategy(
os_auth_uri,
os_project_name,
os_project_domain_name,
os_username,
os_password,
os_user_domain_name,
os_region_name,
os_interface,
strategy_name,
controller_apply_type,
storage_apply_type,
swift_apply_type,
worker_apply_type,
max_parallel_worker_hosts,
default_instance_action,
alarm_restrictions,
stx_auth_type,
**kwargs,
):
"""
Software Update - Create Strategy
"""
@@ -331,55 +367,79 @@ def create_strategy(os_auth_uri, os_project_name, os_project_domain_name,
if response != "yes":
sys.exit(1)
token_id, url = _get_auth_token_and_url(os_auth_uri,
os_project_name,
os_project_domain_name,
os_username,
os_password,
os_user_domain_name,
os_region_name,
os_interface,
stx_auth_type)
token_id, url = _get_auth_token_and_url(
os_auth_uri,
os_project_name,
os_project_domain_name,
os_username,
os_password,
os_user_domain_name,
os_region_name,
os_interface,
stx_auth_type,
)
strategy = sw_update.create_strategy(token_id, url,
strategy_name,
controller_apply_type,
storage_apply_type, swift_apply_type,
worker_apply_type,
max_parallel_worker_hosts,
default_instance_action,
alarm_restrictions,
os_username, os_user_domain_name,
os_username,
auth_type=stx_auth_type,
**kwargs)
strategy = sw_update.create_strategy(
token_id,
url,
strategy_name,
controller_apply_type,
storage_apply_type,
swift_apply_type,
worker_apply_type,
max_parallel_worker_hosts,
default_instance_action,
alarm_restrictions,
os_username,
os_user_domain_name,
os_username,
auth_type=stx_auth_type,
**kwargs,
)
if not strategy:
raise Exception("Strategy creation failed")
_display_strategy(strategy)
def delete_strategy(os_auth_uri, os_project_name, os_project_domain_name,
os_username, os_password, os_user_domain_name,
os_region_name, os_interface, strategy_name, stx_auth_type,
force=False):
def delete_strategy(
os_auth_uri,
os_project_name,
os_project_domain_name,
os_username,
os_password,
os_user_domain_name,
os_region_name,
os_interface,
strategy_name,
stx_auth_type,
force=False,
):
"""
Software Update - Delete Strategy
"""
token_id, url = _get_auth_token_and_url(os_auth_uri,
os_project_name,
os_project_domain_name,
os_username,
os_password,
os_user_domain_name,
os_region_name,
os_interface,
stx_auth_type)
token_id, url = _get_auth_token_and_url(
os_auth_uri,
os_project_name,
os_project_domain_name,
os_username,
os_password,
os_user_domain_name,
os_region_name,
os_interface,
stx_auth_type,
)
success = sw_update.delete_strategy(token_id, url,
strategy_name, force,
os_username, os_user_domain_name,
os_username, auth_type=stx_auth_type)
success = sw_update.delete_strategy(
token_id,
url,
strategy_name,
force,
os_username,
os_user_domain_name,
os_username,
auth_type=stx_auth_type,
)
if success:
print("Strategy deleted")
return
@@ -387,42 +447,65 @@ def delete_strategy(os_auth_uri, os_project_name, os_project_domain_name,
raise Exception("Nothing to delete")
def apply_strategy(os_auth_uri, os_project_name, os_project_domain_name,
os_username, os_password, os_user_domain_name,
os_region_name, os_interface, strategy_name, stx_auth_type,
stage_id=None):
def apply_strategy(
os_auth_uri,
os_project_name,
os_project_domain_name,
os_username,
os_password,
os_user_domain_name,
os_region_name,
os_interface,
strategy_name,
stx_auth_type,
stage_id=None,
):
"""
Software Update - Apply Strategy
"""
token_id, url = _get_auth_token_and_url(os_auth_uri,
os_project_name,
os_project_domain_name,
os_username,
os_password,
os_user_domain_name,
os_region_name,
os_interface,
stx_auth_type)
token_id, url = _get_auth_token_and_url(
os_auth_uri,
os_project_name,
os_project_domain_name,
os_username,
os_password,
os_user_domain_name,
os_region_name,
os_interface,
stx_auth_type,
)
strategy = sw_update.get_strategies(token_id, url, strategy_name,
os_username, os_user_domain_name,
os_username, auth_type=stx_auth_type)
strategy = sw_update.get_strategies(
token_id,
url,
strategy_name,
os_username,
os_user_domain_name,
os_username,
auth_type=stx_auth_type,
)
if not strategy:
raise Exception("No strategy available. Nothing to apply.")
else:
if strategy.state == STRATEGY_APPLYING:
raise Exception(
"Strategy already applied.")
raise Exception("Strategy already applied.")
elif strategy.state != STRATEGY_READY_TO_APPLY:
raise Exception(
"Strategy cannot be applied. %s is not a valid state." % strategy.state)
"Strategy cannot be applied. %s is not a valid state." % strategy.state
)
strategy = sw_update.apply_strategy(token_id, url,
strategy_name, stage_id,
os_username, os_user_domain_name,
os_username, auth_type=stx_auth_type)
strategy = sw_update.apply_strategy(
token_id,
url,
strategy_name,
stage_id,
os_username,
os_user_domain_name,
os_username,
auth_type=stx_auth_type,
)
if not strategy:
if stage_id is None:
raise Exception("Strategy apply failed")
@@ -432,27 +515,44 @@ def apply_strategy(os_auth_uri, os_project_name, os_project_domain_name,
_display_strategy(strategy)
def abort_strategy(os_auth_uri, os_project_name, os_project_domain_name,
os_username, os_password, os_user_domain_name,
os_region_name, os_interface, strategy_name, stx_auth_type,
stage_id=None):
def abort_strategy(
os_auth_uri,
os_project_name,
os_project_domain_name,
os_username,
os_password,
os_user_domain_name,
os_region_name,
os_interface,
strategy_name,
stx_auth_type,
stage_id=None,
):
"""
Software Update - Abort Strategy
"""
token_id, url = _get_auth_token_and_url(os_auth_uri,
os_project_name,
os_project_domain_name,
os_username,
os_password,
os_user_domain_name,
os_region_name,
os_interface,
stx_auth_type)
token_id, url = _get_auth_token_and_url(
os_auth_uri,
os_project_name,
os_project_domain_name,
os_username,
os_password,
os_user_domain_name,
os_region_name,
os_interface,
stx_auth_type,
)
strategy = sw_update.abort_strategy(token_id, url,
strategy_name, stage_id,
os_username, os_user_domain_name,
os_username, auth_type=stx_auth_type)
strategy = sw_update.abort_strategy(
token_id,
url,
strategy_name,
stage_id,
os_username,
os_user_domain_name,
os_username,
auth_type=stx_auth_type,
)
if not strategy:
if stage_id is None:
raise Exception("Strategy abort failed")
@@ -462,26 +562,45 @@ def abort_strategy(os_auth_uri, os_project_name, os_project_domain_name,
_display_strategy(strategy)
def show_strategy(os_auth_uri, os_project_name, os_project_domain_name,
os_username, os_password, os_user_domain_name, os_region_name,
os_interface, strategy_name, stx_auth_type, details=False,
active=False, error_details=False):
def show_strategy(
os_auth_uri,
os_project_name,
os_project_domain_name,
os_username,
os_password,
os_user_domain_name,
os_region_name,
os_interface,
strategy_name,
stx_auth_type,
details=False,
active=False,
error_details=False,
):
"""
Software Update - Show Strategy
"""
token_id, url = _get_auth_token_and_url(os_auth_uri,
os_project_name,
os_project_domain_name,
os_username,
os_password,
os_user_domain_name,
os_region_name,
os_interface,
stx_auth_type)
token_id, url = _get_auth_token_and_url(
os_auth_uri,
os_project_name,
os_project_domain_name,
os_username,
os_password,
os_user_domain_name,
os_region_name,
os_interface,
stx_auth_type,
)
strategy = sw_update.get_strategies(token_id, url, strategy_name,
os_username, os_user_domain_name,
os_username, auth_type=stx_auth_type)
strategy = sw_update.get_strategies(
token_id,
url,
strategy_name,
os_username,
os_user_domain_name,
os_username,
auth_type=stx_auth_type,
)
if not strategy:
print("No strategy available")
return
+10 -10
View File
@@ -1,5 +1,5 @@
#
# Copyright (c) 2016 Wind River Systems, Inc.
# Copyright (c) 2016, 2026 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
@@ -7,16 +7,16 @@ from setuptools import find_packages
from setuptools import setup
setup(
name='nfv_client',
description='NFV Client',
version='1.0.0',
license='Apache-2.0',
platforms=['any'],
provides='nfv_client',
name="nfv_client",
description="NFV Client",
version="1.0.0",
license="Apache-2.0",
platforms=["any"],
provides="nfv_client",
packages=find_packages(),
entry_points={
'console_scripts': [
'sw-manager = nfv_client.shell:process_main',
"console_scripts": [
"sw-manager = nfv_client.shell:process_main",
],
}
},
)
@@ -8,33 +8,38 @@ import stevedore
from nfv_common import debug
from nfv_common.helpers import Singleton
DLOG = debug.debug_get_logger('nfv_common.alarm.alarm_handlers')
DLOG = debug.debug_get_logger("nfv_common.alarm.alarm_handlers")
class AlarmHandlers(stevedore.enabled.EnabledExtensionManager, metaclass=Singleton):
"""
Alarm Handlers
"""
_version = '1.0.0'
_signature = 'e33d7cf6-f270-4256-893e-16266ee4dd2e'
_version = "1.0.0"
_signature = "e33d7cf6-f270-4256-893e-16266ee4dd2e"
def __init__(self, namespace, handler_names):
super(AlarmHandlers, self).__init__(namespace,
AlarmHandlers.valid_handler,
invoke_on_load=True,
invoke_args=(), invoke_kwds={})
super(AlarmHandlers, self).__init__(
namespace,
AlarmHandlers.valid_handler,
invoke_on_load=True,
invoke_args=(),
invoke_kwds={},
)
handler_list = [handler.strip() for handler in handler_names.split(',')]
handler_list = [handler.strip() for handler in handler_names.split(",")]
self._handlers = {}
for handler in self:
if handler.obj.name in handler_list:
handler_id = handler.obj.provider + ':' + handler.obj.name
handler_id = handler.obj.provider + ":" + handler.obj.name
if handler_id not in self._handlers:
self._handlers[handler_id] = handler
DLOG.info("Loaded handler %s version %s provided by %s."
% (handler.obj.name, handler.obj.version,
handler.obj.provider))
DLOG.info(
"Loaded handler %s version %s provided by %s."
% (handler.obj.name, handler.obj.version, handler.obj.provider)
)
@staticmethod
def valid_handler(handler):
@@ -44,9 +49,11 @@ class AlarmHandlers(stevedore.enabled.EnabledExtensionManager, metaclass=Singlet
if AlarmHandlers._signature == handler.obj.signature:
return True
else:
DLOG.info("Handler %s version %s from provider %s has an invalid "
"signature." % (handler.obj.name, handler.obj.version,
handler.obj.provider))
DLOG.info(
"Handler %s version %s from provider %s has an invalid "
"signature."
% (handler.obj.name, handler.obj.version, handler.obj.provider)
)
return False
def raise_alarm(self, alarm_uuid, alarm_data):
@@ -1,11 +1,11 @@
#
# Copyright (c) 2015-2016 Wind River Systems, Inc.
# Copyright (c) 2015-2016, 2026 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
from nfv_common import debug
DLOG = debug.debug_get_logger('nfv_common.alarm.alarm_module')
DLOG = debug.debug_get_logger("nfv_common.alarm.alarm_module")
def alarm_raise(alarm_uuid, alarm_data):
@@ -13,6 +13,7 @@ def alarm_raise(alarm_uuid, alarm_data):
Raise an alarm
"""
from nfv_common.alarm._alarm_thread import AlarmThread
AlarmThread().alarm_raise(alarm_uuid, alarm_data)
@@ -21,6 +22,7 @@ def alarm_clear(alarm_uuid):
Clear an alarm
"""
from nfv_common.alarm._alarm_thread import AlarmThread
AlarmThread().alarm_clear(alarm_uuid)
@@ -29,6 +31,7 @@ def alarm_subsystem_sane():
Returns true if the alarm subsystem is healthy
"""
from nfv_common.alarm._alarm_thread import AlarmThread
return 600 >= AlarmThread().stall_elapsed_secs
@@ -37,6 +40,7 @@ def alarm_initialize(config):
Initialize the alarm subsystem
"""
from nfv_common.alarm._alarm_thread import AlarmThread
AlarmThread(config).start()
@@ -45,4 +49,5 @@ def alarm_finalize():
Finalize the alarm subsystem
"""
from nfv_common.alarm._alarm_thread import AlarmThread
AlarmThread().stop(max_wait_in_seconds=5)
@@ -14,13 +14,14 @@ from nfv_common.helpers import Singleton
from nfv_common.alarm._alarm_handlers import AlarmHandlers
DLOG = debug.debug_get_logger('nfv_common.alarm.alarm_thread')
DLOG = debug.debug_get_logger("nfv_common.alarm.alarm_thread")
class AlarmWorker(thread.ThreadWorker, metaclass=Singleton):
"""
Alarm Worker
"""
def __init__(self, name, config):
super(AlarmWorker, self).__init__(name)
self._config = config
@@ -40,13 +41,17 @@ class AlarmWorker(thread.ThreadWorker, metaclass=Singleton):
"""
Initialize the Alarm Worker
"""
self._handlers = AlarmHandlers(self._config['namespace'],
self._config['handlers'])
self._handlers.initialize(self._config['config_file'])
self._handlers = AlarmHandlers(
self._config["namespace"], self._config["handlers"]
)
self._handlers.initialize(self._config["config_file"])
self._alarm_audit_timer_id = timers.timers_create_timer(
'alarm_audit', int(self._config['audit_interval']),
int(self._config['audit_interval']), self._alarm_audit)
"alarm_audit",
int(self._config["audit_interval"]),
int(self._config["audit_interval"]),
self._alarm_audit,
)
def finalize(self):
"""
@@ -63,12 +68,12 @@ class AlarmWorker(thread.ThreadWorker, metaclass=Singleton):
Do work given to the Alarm Worker
"""
if AlarmThread.ACTION_RAISE_ALARM == action:
DLOG.verbose("Raise alarm with uuid=%s" % work['alarm-uuid'])
self._handlers.raise_alarm(work['alarm-uuid'], work['alarm-data'])
DLOG.verbose("Raise alarm with uuid=%s" % work["alarm-uuid"])
self._handlers.raise_alarm(work["alarm-uuid"], work["alarm-data"])
elif AlarmThread.ACTION_CLEAR_ALARM == action:
DLOG.verbose("Clear alarm with uuid=%s" % work['alarm-uuid'])
self._handlers.clear_alarm(work['alarm-uuid'])
DLOG.verbose("Clear alarm with uuid=%s" % work["alarm-uuid"])
self._handlers.clear_alarm(work["alarm-uuid"])
else:
DLOG.debug("Unknown action %s given." % action)
@@ -78,21 +83,22 @@ class AlarmThread(thread.Thread, metaclass=Singleton):
"""
Alarm Thread
"""
ACTION_RAISE_ALARM = "thread-raise-alarm"
ACTION_CLEAR_ALARM = "thread-clear-alarm"
def __init__(self, config=None):
self._worker = AlarmWorker('Alarm', config)
super(AlarmThread, self).__init__('Alarm', self._worker)
self._worker = AlarmWorker("Alarm", config)
super(AlarmThread, self).__init__("Alarm", self._worker)
def alarm_raise(self, alarm_uuid, alarm_data):
"""
Send raise alarm to the Alarm Thread Worker
"""
work = dict()
work['alarm-uuid'] = alarm_uuid
work['alarm-data'] = alarm_data
work['alarm-change-date'] = datetime.datetime.utcnow()
work["alarm-uuid"] = alarm_uuid
work["alarm-data"] = alarm_data
work["alarm-change-date"] = datetime.datetime.utcnow()
self.send_work(AlarmThread.ACTION_RAISE_ALARM, work)
def alarm_clear(self, alarm_uuid):
@@ -100,7 +106,7 @@ class AlarmThread(thread.Thread, metaclass=Singleton):
Send clear alarm to the Alarm Thread Worker
"""
work = dict()
work['alarm-uuid'] = alarm_uuid
work['alarm-data'] = None
work['alarm-change-date'] = datetime.datetime.utcnow()
work["alarm-uuid"] = alarm_uuid
work["alarm-data"] = None
work["alarm-change-date"] = datetime.datetime.utcnow()
self.send_work(AlarmThread.ACTION_CLEAR_ALARM, work)
@@ -10,51 +10,52 @@ class AlarmHandler(object, metaclass=abc.ABCMeta):
"""
Abstract Alarm Handler Class Definition
"""
@property
@abc.abstractmethod
def name(self):
"""The name of handler """
"""The name of handler"""
pass
@property
@abc.abstractmethod
def version(self):
"""The versions of the handler """
"""The versions of the handler"""
pass
@property
@abc.abstractmethod
def provider(self):
"""Who created the handler """
"""Who created the handler"""
pass
@property
@abc.abstractmethod
def signature(self):
"""Signature of the handler """
"""Signature of the handler"""
pass
@abc.abstractmethod
def raise_alarm(self, alarm_uuid, alarm_data):
"""Raise an alarm via the handler """
"""Raise an alarm via the handler"""
pass
@abc.abstractmethod
def clear_alarm(self, alarm_uuid):
"""Clear an alarm via the handler """
"""Clear an alarm via the handler"""
pass
@abc.abstractmethod
def audit_alarms(self):
"""Audit alarms via the handler """
"""Audit alarms via the handler"""
pass
@abc.abstractmethod
def initialize(self, config_file):
"""Initialize the handler """
"""Initialize the handler"""
pass
@abc.abstractmethod
def finalize(self):
"""Finalize the handler """
"""Finalize the handler"""
pass
@@ -1,5 +1,5 @@
#
# Copyright (c) 2015-2016 Wind River Systems, Inc.
# Copyright (c) 2015-2016, 2026 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
@@ -10,6 +10,7 @@ class AlarmStateData(object):
"""
Alarm State Data
"""
def __init__(self, state):
self.state = state
@@ -21,6 +22,7 @@ class AlarmThresholdData(object):
"""
Alarm Threshold Data
"""
def __init__(self, threshold_value, observed_value):
self.threshold_value = threshold_value
self.observed_value = observed_value
@@ -34,12 +36,26 @@ class AlarmData(object):
Alarm Data
"""
def __init__(self, alarm_uuid, alarm_type, alarm_context, entity_type,
entity, event_type, probable_cause, perceived_severity,
trend_indication, specific_problem_text, proposed_repair_action,
additional_text="", state_data=None, threshold_data=None,
service_affecting=True, suppression_allowed=True,
raised_timestamp=None):
def __init__(
self,
alarm_uuid,
alarm_type,
alarm_context,
entity_type,
entity,
event_type,
probable_cause,
perceived_severity,
trend_indication,
specific_problem_text,
proposed_repair_action,
additional_text="",
state_data=None,
threshold_data=None,
service_affecting=True,
suppression_allowed=True,
raised_timestamp=None,
):
self.alarm_uuid = alarm_uuid
self.alarm_type = alarm_type
@@ -13,105 +13,123 @@ class _AlarmType(Constants, metaclass=Singleton):
"""
Alarm Type Constants
"""
UNKNOWN = Constant('unknown')
MULTI_NODE_RECOVERY_MODE = Constant('multi-node-recovery-mode')
HOST_SERVICES_FAILED = Constant('host-services-failed')
INSTANCE_FAILED = Constant('instance-failed')
INSTANCE_SCHEDULING_FAILED = Constant('instance-scheduling-failed')
INSTANCE_STOPPED = Constant('instance-stopped')
INSTANCE_REBOOTING = Constant('instance-rebooting')
INSTANCE_PAUSED = Constant('instance-paused')
INSTANCE_SUSPENDED = Constant('instance-suspended')
INSTANCE_EVACUATING = Constant('instance-evacuating')
INSTANCE_REBUILDING = Constant('instance-rebuilding')
INSTANCE_LIVE_MIGRATING = Constant('instance-live-migrating')
INSTANCE_COLD_MIGRATING = Constant('instance-cold-migrating')
INSTANCE_COLD_MIGRATED = Constant('instance-cold-migrated')
INSTANCE_COLD_MIGRATE_REVERTING = Constant('instance-cold-migrate-reverting')
INSTANCE_RESIZING = Constant('instance-resizing')
INSTANCE_RESIZED = Constant('instance-resized')
INSTANCE_RESIZE_REVERTING = Constant('instance-resize-reverting')
INSTANCE_GUEST_HEARTBEAT = Constant('instance-guest-heartbeat')
INSTANCE_GROUP_POLICY_CONFLICT = Constant('instance-group-policy-conflict')
SW_PATCH_AUTO_APPLY_INPROGRESS = Constant('sw-patch-auto-apply-inprogress')
SW_PATCH_AUTO_APPLY_ABORTING = Constant('sw-patch-auto-apply-aborting')
SW_PATCH_AUTO_APPLY_FAILED = Constant('sw-patch-auto-apply-failed')
SW_UPGRADE_AUTO_APPLY_INPROGRESS = Constant('sw-upgrade-auto-apply-inprogress')
SW_UPGRADE_AUTO_APPLY_ABORTING = Constant('sw-upgrade-auto-apply-aborting')
SW_UPGRADE_AUTO_APPLY_FAILED = Constant('sw-upgrade-auto-apply-failed')
FW_UPDATE_AUTO_APPLY_INPROGRESS = Constant('fw-update-auto-apply-inprogress')
FW_UPDATE_AUTO_APPLY_ABORTING = Constant('fw-update-auto-apply-aborting')
FW_UPDATE_AUTO_APPLY_FAILED = Constant('fw-update-auto-apply-failed')
KUBE_ROOTCA_UPDATE_AUTO_APPLY_INPROGRESS = Constant('kube-rootca-update-auto-apply-inprogress')
KUBE_ROOTCA_UPDATE_AUTO_APPLY_ABORTING = Constant('kube-rootca-update-auto-apply-aborting')
KUBE_ROOTCA_UPDATE_AUTO_APPLY_FAILED = Constant('kube-rootca-update-auto-apply-failed')
KUBE_UPGRADE_AUTO_APPLY_INPROGRESS = Constant('kube-upgrade-auto-apply-inprogress')
KUBE_UPGRADE_AUTO_APPLY_ABORTING = Constant('kube-upgrade-auto-apply-aborting')
KUBE_UPGRADE_AUTO_APPLY_FAILED = Constant('kube-upgrade-auto-apply-failed')
SYSTEM_CONFIG_UPDATE_AUTO_APPLY_INPROGRESS = Constant('system-config-update-auto-apply-inprogress')
SYSTEM_CONFIG_UPDATE_AUTO_APPLY_ABORTING = Constant('system-config-update-auto-apply-aborting')
SYSTEM_CONFIG_UPDATE_AUTO_APPLY_FAILED = Constant('system-config-update-auto-apply-failed')
UNKNOWN = Constant("unknown")
MULTI_NODE_RECOVERY_MODE = Constant("multi-node-recovery-mode")
HOST_SERVICES_FAILED = Constant("host-services-failed")
INSTANCE_FAILED = Constant("instance-failed")
INSTANCE_SCHEDULING_FAILED = Constant("instance-scheduling-failed")
INSTANCE_STOPPED = Constant("instance-stopped")
INSTANCE_REBOOTING = Constant("instance-rebooting")
INSTANCE_PAUSED = Constant("instance-paused")
INSTANCE_SUSPENDED = Constant("instance-suspended")
INSTANCE_EVACUATING = Constant("instance-evacuating")
INSTANCE_REBUILDING = Constant("instance-rebuilding")
INSTANCE_LIVE_MIGRATING = Constant("instance-live-migrating")
INSTANCE_COLD_MIGRATING = Constant("instance-cold-migrating")
INSTANCE_COLD_MIGRATED = Constant("instance-cold-migrated")
INSTANCE_COLD_MIGRATE_REVERTING = Constant("instance-cold-migrate-reverting")
INSTANCE_RESIZING = Constant("instance-resizing")
INSTANCE_RESIZED = Constant("instance-resized")
INSTANCE_RESIZE_REVERTING = Constant("instance-resize-reverting")
INSTANCE_GUEST_HEARTBEAT = Constant("instance-guest-heartbeat")
INSTANCE_GROUP_POLICY_CONFLICT = Constant("instance-group-policy-conflict")
SW_PATCH_AUTO_APPLY_INPROGRESS = Constant("sw-patch-auto-apply-inprogress")
SW_PATCH_AUTO_APPLY_ABORTING = Constant("sw-patch-auto-apply-aborting")
SW_PATCH_AUTO_APPLY_FAILED = Constant("sw-patch-auto-apply-failed")
SW_UPGRADE_AUTO_APPLY_INPROGRESS = Constant("sw-upgrade-auto-apply-inprogress")
SW_UPGRADE_AUTO_APPLY_ABORTING = Constant("sw-upgrade-auto-apply-aborting")
SW_UPGRADE_AUTO_APPLY_FAILED = Constant("sw-upgrade-auto-apply-failed")
FW_UPDATE_AUTO_APPLY_INPROGRESS = Constant("fw-update-auto-apply-inprogress")
FW_UPDATE_AUTO_APPLY_ABORTING = Constant("fw-update-auto-apply-aborting")
FW_UPDATE_AUTO_APPLY_FAILED = Constant("fw-update-auto-apply-failed")
KUBE_ROOTCA_UPDATE_AUTO_APPLY_INPROGRESS = Constant(
"kube-rootca-update-auto-apply-inprogress"
)
KUBE_ROOTCA_UPDATE_AUTO_APPLY_ABORTING = Constant(
"kube-rootca-update-auto-apply-aborting"
)
KUBE_ROOTCA_UPDATE_AUTO_APPLY_FAILED = Constant(
"kube-rootca-update-auto-apply-failed"
)
KUBE_UPGRADE_AUTO_APPLY_INPROGRESS = Constant("kube-upgrade-auto-apply-inprogress")
KUBE_UPGRADE_AUTO_APPLY_ABORTING = Constant("kube-upgrade-auto-apply-aborting")
KUBE_UPGRADE_AUTO_APPLY_FAILED = Constant("kube-upgrade-auto-apply-failed")
SYSTEM_CONFIG_UPDATE_AUTO_APPLY_INPROGRESS = Constant(
"system-config-update-auto-apply-inprogress"
)
SYSTEM_CONFIG_UPDATE_AUTO_APPLY_ABORTING = Constant(
"system-config-update-auto-apply-aborting"
)
SYSTEM_CONFIG_UPDATE_AUTO_APPLY_FAILED = Constant(
"system-config-update-auto-apply-failed"
)
class _AlarmContext(Constants, metaclass=Singleton):
"""
Alarm Context Constants
"""
ADMIN = Constant('admin')
TENANT = Constant('tenant')
ADMIN = Constant("admin")
TENANT = Constant("tenant")
class _AlarmEventType(Constants, metaclass=Singleton):
"""
Alarm Event Type Constants
"""
UNKNOWN = Constant('unknown')
COMMUNICATIONS_ALARM = Constant('communications-alarm')
PROCESSING_ERROR_ALARM = Constant('processing-error-alarm')
ENVIRONMENTAL_ALARM = Constant('environmental-alarm')
QUALITY_OF_SERVICE_ALARM = Constant('quality-of-service-alarm')
EQUIPMENT_ALARM = Constant('equipment-alarm')
INTEGRITY_VIOLATION = Constant('integrity-violation')
OPERATIONAL_VIOLATION = Constant('operational-violation')
PHYSICAL_VIOLATION = Constant('physical-violation')
SECURITY_SERVICE_VIOLATION = Constant('security-service-violation')
MECHANISM_VIOLATION = Constant('mechanism-violation')
TIME_DOMAIN_VIOLATION = Constant('time-domain-violation')
UNKNOWN = Constant("unknown")
COMMUNICATIONS_ALARM = Constant("communications-alarm")
PROCESSING_ERROR_ALARM = Constant("processing-error-alarm")
ENVIRONMENTAL_ALARM = Constant("environmental-alarm")
QUALITY_OF_SERVICE_ALARM = Constant("quality-of-service-alarm")
EQUIPMENT_ALARM = Constant("equipment-alarm")
INTEGRITY_VIOLATION = Constant("integrity-violation")
OPERATIONAL_VIOLATION = Constant("operational-violation")
PHYSICAL_VIOLATION = Constant("physical-violation")
SECURITY_SERVICE_VIOLATION = Constant("security-service-violation")
MECHANISM_VIOLATION = Constant("mechanism-violation")
TIME_DOMAIN_VIOLATION = Constant("time-domain-violation")
class _AlarmProbableCause(Constants, metaclass=Singleton):
"""
Alarm Probable Cause Constants
"""
UNKNOWN = Constant('unknown')
INDETERMINATE = Constant('indeterminate')
SOFTWARE_ERROR = Constant('software-error')
SOFTWARE_PROGRAM_ERROR = Constant('software-program-error')
UNDERLYING_RESOURCE_UNAVAILABLE = Constant('underlying-resource-unavailable')
PROCEDURAL_ERROR = Constant('procedural-error')
UNKNOWN = Constant("unknown")
INDETERMINATE = Constant("indeterminate")
SOFTWARE_ERROR = Constant("software-error")
SOFTWARE_PROGRAM_ERROR = Constant("software-program-error")
UNDERLYING_RESOURCE_UNAVAILABLE = Constant("underlying-resource-unavailable")
PROCEDURAL_ERROR = Constant("procedural-error")
class _AlarmSeverity(Constants, metaclass=Singleton):
"""
Alarm Severity Constants
"""
UNKNOWN = Constant('unknown')
CLEARED = Constant('cleared')
INDETERMINATE = Constant('indeterminate')
WARNING = Constant('warning')
MINOR = Constant('minor')
MAJOR = Constant('major')
CRITICAL = Constant('critical')
UNKNOWN = Constant("unknown")
CLEARED = Constant("cleared")
INDETERMINATE = Constant("indeterminate")
WARNING = Constant("warning")
MINOR = Constant("minor")
MAJOR = Constant("major")
CRITICAL = Constant("critical")
class _AlarmTrendIndication(Constants, metaclass=Singleton):
"""
Alarm Trend Indication Constants
"""
UNKNOWN = Constant('unknown')
LESS_SEVERE = Constant('less-severe')
NO_CHANGE = Constant('no-change')
MORE_SEVERE = Constant('more-severe')
UNKNOWN = Constant("unknown")
LESS_SEVERE = Constant("less-severe")
NO_CHANGE = Constant("no-change")
MORE_SEVERE = Constant("more-severe")
# Constant Instantiation
@@ -8,56 +8,64 @@ import stevedore
from nfv_common import debug
from nfv_common.helpers import Singleton
DLOG = debug.debug_get_logger('nfv_common.catalog.catalog_backend')
DLOG = debug.debug_get_logger("nfv_common.catalog.catalog_backend")
class CatalogBackend(stevedore.named.NamedExtensionManager, metaclass=Singleton):
"""
Catalog Backend
"""
_version = '1.0.0'
_signature = '7926ef8d-b04c-4f5b-8627-f40f59fd8d11'
_version = "1.0.0"
_signature = "7926ef8d-b04c-4f5b-8627-f40f59fd8d11"
def __init__(self, plugin_namespace, plugin_name):
super(CatalogBackend, self).__init__(plugin_namespace, plugin_name,
invoke_on_load=True,
invoke_args=(), invoke_kwds={})
super(CatalogBackend, self).__init__(
plugin_namespace,
plugin_name,
invoke_on_load=True,
invoke_args=(),
invoke_kwds={},
)
self.plugin = None
for plugin in self:
if self.valid_plugin(plugin):
self.plugin = plugin
DLOG.info("Loaded plugin %s version %s provided by %s."
% (plugin.obj.name, plugin.obj.version,
plugin.obj.provider))
DLOG.info(
"Loaded plugin %s version %s provided by %s."
% (plugin.obj.name, plugin.obj.version, plugin.obj.provider)
)
break
@staticmethod
def valid_plugin(plugin):
"""Verify signature of plugin is valid """
"""Verify signature of plugin is valid"""
if CatalogBackend._signature == plugin.obj.signature:
return True
else:
DLOG.info("Plugin %s version %s from provider %s has an invalid "
"signature." % (plugin.obj.name, plugin.obj.version,
plugin.obj.provider))
DLOG.info(
"Plugin %s version %s from provider %s has an invalid "
"signature."
% (plugin.obj.name, plugin.obj.version, plugin.obj.provider)
)
return False
def read_vnf_descriptor(self, vnfd_id, vnf_vendor, vnf_version):
"""Read a particular vnf descriptor """
"""Read a particular vnf descriptor"""
vnfd_record = None
if self.plugin is not None:
vnfd_record = self.plugin.obj.read_vnf_descriptor(vnfd_id,
vnf_vendor,
vnf_version)
vnfd_record = self.plugin.obj.read_vnf_descriptor(
vnfd_id, vnf_vendor, vnf_version
)
return vnfd_record
def initialize(self):
"""Initialize plugin """
"""Initialize plugin"""
if self.plugin is not None:
self.plugin.obj.initialize(self._version)
def finalize(self):
"""Finalize plugin """
"""Finalize plugin"""
if self.plugin is not None:
self.plugin.obj.finalize()
@@ -1,5 +1,5 @@
#
# Copyright (c) 2015-2016 Wind River Systems, Inc.
# Copyright (c) 2015-2016, 2026 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
@@ -9,20 +9,19 @@ _catalog_backend = None
def read_vnf_descriptor(vnfd_id, vnf_vendor, vnf_version):
"""Read a vnf descriptor """
"""Read a vnf descriptor"""
if _catalog_backend is not None:
return _catalog_backend.read_vnf_descriptor(vnfd_id, vnf_vendor,
vnf_version)
return _catalog_backend.read_vnf_descriptor(vnfd_id, vnf_vendor, vnf_version)
return None
def catalog_initialize(plugin_namespace, plugin_name):
"""Catalog Initialize """
"""Catalog Initialize"""
global _catalog_backend
_catalog_backend = CatalogBackend(plugin_namespace, plugin_name)
def catalog_finalize():
"""Catalog Finalize """
"""Catalog Finalize"""
global _catalog_backend
_catalog_backend = None
@@ -12,21 +12,23 @@ class ConnectionType(object, metaclass=Singleton):
"""
Connection Type Constants
"""
UNKNOWN = Constant('unknown')
VIRTUAL_PORT = Constant('virtual-port')
VIRTUAL_NIC_ADDRESS = Constant('virtual-nic-address')
PHYSICAL_PORT = Constant('physical-port')
PHYSICAL_NIC_ADDRESS = Constant('physical-nic-address')
UNKNOWN = Constant("unknown")
VIRTUAL_PORT = Constant("virtual-port")
VIRTUAL_NIC_ADDRESS = Constant("virtual-nic-address")
PHYSICAL_PORT = Constant("physical-port")
PHYSICAL_NIC_ADDRESS = Constant("physical-nic-address")
class ConnectivityType(object, metaclass=Singleton):
"""
Connectivity Type Constants
"""
UNKNOWN = Constant('unknown')
E_LINE = Constant('E-Line')
E_LAN = Constant('E-LAN')
E_TREE = Constant('E-Tree')
UNKNOWN = Constant("unknown")
E_LINE = Constant("E-Line")
E_LAN = Constant("E-LAN")
E_TREE = Constant("E-Tree")
# Constant Instantiation
@@ -1,5 +1,5 @@
#
# Copyright (c) 2015-2016 Wind River Systems, Inc.
# Copyright (c) 2015-2016, 2026 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
@@ -39,6 +39,7 @@ class VNFD(object):
manifest_file_security: a file that contains a digest of each file that
it lists as part of the vnf package
"""
def __init__(self, id):
self.id = id
self.vendor = None
@@ -63,6 +64,7 @@ class ConnectionPointVNFD(object):
identifiers
type: type of connection
"""
def __init__(self, id):
self.id = id
self.virtual_link_reference = None
@@ -81,6 +83,7 @@ class VirtualLink(object):
test_access: describes the test access facilities to be supported on
the virtual link
"""
def __init__(self, id):
self.id = id
self.connectivity_type = CONNECTIVITY_TYPE.UNKNOWN
@@ -100,6 +103,7 @@ class DeploymentFlavor(object):
constraint: zero or more deployment flavor constraints
constituent_vdu: one or more ConstituentVDU() objects
"""
def __init__(self, id):
self.id = id
self.flavor_key = None
@@ -115,6 +119,7 @@ class ConstituentVDU(object):
constituent_vnfc: one or more vnfc identifiers that should be used for
this deployment
"""
def __init__(self, vdu_reference):
self.vdu_reference = vdu_reference
self.number_of_instances = 0
@@ -142,6 +147,7 @@ class VDU(object):
monitoring_parameter: zero or more monitoring parameters which can be
tracked for a vnfc based on this vdu
"""
def __init__(self, id):
self.id = id
self.vm_image = None
@@ -162,6 +168,7 @@ class VNFC(object):
id: unique vnfc identification within the namespace of a specific vnf
connection_point: one or more network connections
"""
def __init__(self, id):
self.id = id
self.connection_point = []
@@ -174,6 +181,7 @@ class ConnectionPointVNFC(object):
virtual_link_reference: references zero or more internal virtual links
type: type of network connection
"""
def __init__(self, id):
self.id = id
self.virtual_link_reference = None
@@ -12,41 +12,42 @@ class CatalogPlugin(object, metaclass=ABCMeta):
"""
Abstract Catalog Plugin Class Definition
"""
@property
@abstractmethod
def name(self):
"""The name of plugin """
"""The name of plugin"""
pass
@property
@abstractmethod
def version(self):
"""The versions of the plugin """
"""The versions of the plugin"""
pass
@property
@abstractmethod
def provider(self):
"""Vendor created the plugin """
"""Vendor created the plugin"""
pass
@property
@abstractmethod
def signature(self):
"""Signature of the plugin """
"""Signature of the plugin"""
pass
@abstractmethod
def read_vnf_descriptor(self, vnfd_id, vnf_vendor, vnf_version):
"""Read a particular vnf descriptor """
"""Read a particular vnf descriptor"""
pass
@abstractmethod
def initialize(self, version):
"""Initialize the plugin """
"""Initialize the plugin"""
pass
@abstractmethod
def finalize(self):
"""Finalize the plugin """
"""Finalize the plugin"""
pass
+3 -2
View File
@@ -7,7 +7,7 @@ import configparser
from nfv_common import debug
DLOG = debug.debug_get_logger('nfv_common.config')
DLOG = debug.debug_get_logger("nfv_common.config")
# Configuration Global used by other modules to get access to the configuration
# specified in the ini file.
@@ -18,11 +18,12 @@ class Config(configparser.ConfigParser):
"""
Override ConfigParser class to add dictionary functionality.
"""
def as_dict(self):
d = dict(self._sections)
for key in d:
d[key] = dict(self._defaults, **d[key])
d[key].pop('__name__', None)
d[key].pop("__name__", None)
return d
+16 -11
View File
@@ -1,14 +1,19 @@
# Copyright (c) 2015-2016 Wind River Systems, Inc.
# Copyright (c) 2015-2016, 2026 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
from nfv_common.debug._debug_defs import DEBUG_LEVEL # noqa: F401
from nfv_common.debug._debug_log import debug_dump_loggers # noqa: F401
from nfv_common.debug._debug_log import debug_get_logger # noqa: F401
from nfv_common.debug._debug_log import debug_trace # noqa: F401
from nfv_common.debug._debug_module import debug_deregister_config_change_callback # noqa: F401
from nfv_common.debug._debug_module import debug_finalize # noqa: F401
from nfv_common.debug._debug_module import debug_get_config # noqa: F401
from nfv_common.debug._debug_module import debug_initialize # noqa: F401
from nfv_common.debug._debug_module import debug_register_config_change_callback # noqa: F401
from nfv_common.debug._debug_module import debug_reload_config # noqa: F401
# flake8: noqa
from nfv_common.debug._debug_defs import DEBUG_LEVEL
from nfv_common.debug._debug_log import debug_dump_loggers
from nfv_common.debug._debug_log import debug_get_logger
from nfv_common.debug._debug_log import debug_trace
from nfv_common.debug._debug_module import (
debug_deregister_config_change_callback,
)
from nfv_common.debug._debug_module import debug_finalize
from nfv_common.debug._debug_module import debug_get_config
from nfv_common.debug._debug_module import debug_initialize
from nfv_common.debug._debug_module import (
debug_register_config_change_callback,
)
from nfv_common.debug._debug_module import debug_reload_config
@@ -42,14 +42,17 @@ class DebugConfig(object, metaclass=Singleton):
"""
Debug Configuration
"""
debug_level_mapping = {'debug.level.none': DEBUG_LEVEL.NONE,
'debug.level.verbose': DEBUG_LEVEL.VERBOSE,
'debug.level.debug': DEBUG_LEVEL.DEBUG,
'debug.level.info': DEBUG_LEVEL.INFO,
'debug.level.notice': DEBUG_LEVEL.NOTICE,
'debug.level.warn': DEBUG_LEVEL.WARN,
'debug.level.error': DEBUG_LEVEL.ERROR,
'debug.level.critical': DEBUG_LEVEL.CRITICAL}
debug_level_mapping = {
"debug.level.none": DEBUG_LEVEL.NONE,
"debug.level.verbose": DEBUG_LEVEL.VERBOSE,
"debug.level.debug": DEBUG_LEVEL.DEBUG,
"debug.level.info": DEBUG_LEVEL.INFO,
"debug.level.notice": DEBUG_LEVEL.NOTICE,
"debug.level.warn": DEBUG_LEVEL.WARN,
"debug.level.error": DEBUG_LEVEL.ERROR,
"debug.level.critical": DEBUG_LEVEL.CRITICAL,
}
def __init__(self, filename):
"""
@@ -82,13 +85,14 @@ class DebugConfig(object, metaclass=Singleton):
if self._config is not None:
try:
level_str = self._config.get('debug-overall', 'debug_level')
debug_level = self.debug_level_mapping.get(level_str,
DEBUG_LEVEL.NONE)
level_str = self._config.get("debug-overall", "debug_level")
debug_level = self.debug_level_mapping.get(level_str, DEBUG_LEVEL.NONE)
except configparser.NoOptionError:
print("Debug configuration has no debug_level option in the "
"debug-overall section.")
print(
"Debug configuration has no debug_level option in the "
"debug-overall section."
)
except configparser.NoSectionError:
print("Debug configuration has no debug-overall section.")
@@ -104,13 +108,14 @@ class DebugConfig(object, metaclass=Singleton):
if self._config is not None:
try:
level_str = self._config.get('debug-overall', 'trace_level')
trace_level = self.debug_level_mapping.get(level_str,
DEBUG_LEVEL.NONE)
level_str = self._config.get("debug-overall", "trace_level")
trace_level = self.debug_level_mapping.get(level_str, DEBUG_LEVEL.NONE)
except configparser.NoOptionError:
print("Debug configuration has no trace_level option in the "
"debug-overall section.")
print(
"Debug configuration has no trace_level option in the "
"debug-overall section."
)
except configparser.NoSectionError:
print("Debug configuration has no debug-overall section.")
@@ -126,9 +131,13 @@ class DebugConfig(object, metaclass=Singleton):
if self._config is not None:
try:
for name, level_str in list(self._config.items('debug-loggers')):
debug_list.append((name, self.debug_level_mapping.get(
level_str, DEBUG_LEVEL.NONE)))
for name, level_str in list(self._config.items("debug-loggers")):
debug_list.append(
(
name,
self.debug_level_mapping.get(level_str, DEBUG_LEVEL.NONE),
)
)
except configparser.NoSectionError:
print("Debug configuration file has no debug-loggers section.")
@@ -12,6 +12,7 @@ class _DebugLevel(object, metaclass=Singleton):
"""
Debug Level Constants
"""
NONE = Constant(8000)
CRITICAL = Constant(7000)
ERROR = Constant(6000)
+49 -37
View File
@@ -22,6 +22,7 @@ class DebugLogFormatter(logging.Formatter):
"""
Debug Log Formatter
"""
def formatTime(self, record, date_format=None):
dt = datetime.datetime.fromtimestamp(record.created)
if date_format is None:
@@ -35,6 +36,7 @@ class DebugLogHandler(logging.Handler):
"""
Debug Log Handler
"""
def __init__(self):
super(DebugLogHandler, self).__init__()
self.process_name = None
@@ -49,8 +51,10 @@ class DebugLogHandler(logging.Handler):
# To keep syslog-ng happy, we need to add the who field twice. Newer
# syslog-ng removes the header formatting
fmt = (f"%(asctime)s %(who)36s[%(process)d]: %(who)36s[%(process){pid_size}d] "
"%(levelname)8s %(message)s")
fmt = (
f"%(asctime)s %(who)36s[%(process)d]: %(who)36s[%(process){pid_size}d] "
"%(levelname)8s %(message)s"
)
formatter = DebugLogFormatter(fmt)
self.setFormatter(formatter)
@@ -85,10 +89,9 @@ class DebugLogHandler(logging.Handler):
if self.process_name is not None:
if self.thread_name is not None:
log_record.who = ("%s_%s_Thread" % (self.process_name,
self.thread_name))
log_record.who = "%s_%s_Thread" % (self.process_name, self.thread_name)
else:
log_record.who = ("%s_Thread" % self.process_name)
log_record.who = "%s_Thread" % self.process_name
else:
log_record.who = "UNKNOWN"
@@ -120,17 +123,21 @@ class DebugLogger(object):
"""
Debug Logger
"""
log_level_mapping = {DEBUG_LEVEL.NONE: logging.NOTSET,
DEBUG_LEVEL.VERBOSE: logging.DEBUG,
DEBUG_LEVEL.DEBUG: logging.DEBUG,
DEBUG_LEVEL.INFO: logging.INFO,
DEBUG_LEVEL.NOTICE: logging.INFO,
DEBUG_LEVEL.WARN: logging.WARNING,
DEBUG_LEVEL.ERROR: logging.ERROR,
DEBUG_LEVEL.CRITICAL: logging.CRITICAL}
def __init__(self, name, debug_level=DEBUG_LEVEL.NONE, process_name=None,
thread_name=None):
log_level_mapping = {
DEBUG_LEVEL.NONE: logging.NOTSET,
DEBUG_LEVEL.VERBOSE: logging.DEBUG,
DEBUG_LEVEL.DEBUG: logging.DEBUG,
DEBUG_LEVEL.INFO: logging.INFO,
DEBUG_LEVEL.NOTICE: logging.INFO,
DEBUG_LEVEL.WARN: logging.WARNING,
DEBUG_LEVEL.ERROR: logging.ERROR,
DEBUG_LEVEL.CRITICAL: logging.CRITICAL,
}
def __init__(
self, name, debug_level=DEBUG_LEVEL.NONE, process_name=None, thread_name=None
):
"""
Create debug logger
"""
@@ -250,46 +257,52 @@ def debug_trace(trace_level):
"""
Decorator function used to trace entering and exiting functions
"""
def trace_wrap(func):
def trace_wrapper(*args, **kwargs):
if trace_level >= Debug().trace_level:
print(" " * Debug().trace_depth, file=Debug().output,
end='', sep='')
print("entering " + func.__name__ + ":",
file=Debug().output, end='', sep='')
print(" " * Debug().trace_depth, file=Debug().output, end="", sep="")
print(
"entering " + func.__name__ + ":",
file=Debug().output,
end="",
sep="",
)
print(" args=", file=Debug().output, end='', sep='')
print(" args=", file=Debug().output, end="", sep="")
for arg in args:
print("{0} ".format(arg), file=Debug().output,
end='', sep='')
print("{0} ".format(arg), file=Debug().output, end="", sep="")
print(" kwargs=", file=Debug().output, end='', sep='')
print(" kwargs=", file=Debug().output, end="", sep="")
for name, value in list(kwargs.items()):
print("{0}={1} ".format(name, value),
file=Debug().output, end='', sep='')
print(
"{0}={1} ".format(name, value),
file=Debug().output,
end="",
sep="",
)
try:
Debug().trace_depth += 1
result = func(*args, **kwargs)
except Exception:
print(" " * Debug().trace_depth,
file=Debug().output, end='', sep='')
print("exception", file=Debug().output,
end='\n', sep='')
print(
" " * Debug().trace_depth, file=Debug().output, end="", sep=""
)
print("exception", file=Debug().output, end="\n", sep="")
raise
finally:
Debug().trace_depth -= 1
print(" " * Debug().trace_depth, file=Debug().output,
end='\n', sep='')
print("exiting " + func.__name__, file=Debug().output,
end='\n', sep='')
print(" " * Debug().trace_depth, file=Debug().output, end="\n", sep="")
print("exiting " + func.__name__, file=Debug().output, end="\n", sep="")
return result
else:
return func(*args, **kwargs)
functools.update_wrapper(trace_wrapper, func)
return trace_wrapper
return trace_wrap
@@ -300,13 +313,12 @@ def debug_dump_loggers(directory):
if os.path.exists(directory):
program_name = os.path.basename(sys.argv[0])
with open(directory + program_name + '.dbg.conf', 'a') as f:
with open(directory + program_name + ".dbg.conf", "a") as f:
for name in _debug_loggers:
f.write(name + '\n')
f.write(name + "\n")
def debug_get_logger(name, debug_level=None, process_name=None,
thread_name=None):
def debug_get_logger(name, debug_level=None, process_name=None, thread_name=None):
"""
Create a logger if it does not already exist
"""
@@ -16,6 +16,7 @@ class Debug(object, metaclass=Singleton):
"""
Debug
"""
def __init__(self):
self._config_change_callbacks = list()
self._config = None
@@ -88,7 +89,7 @@ class Debug(object, metaclass=Singleton):
"""
if self._config is None:
self._config = config
self._debug_config = DebugConfig(config['config_file'])
self._debug_config = DebugConfig(config["config_file"])
DebugLoggingThread().send_log_config(config)
@property
@@ -17,11 +17,12 @@ class DebugLoggingThreadFormatter(logging.Formatter):
"""
Debug Log Formatter
"""
def format(self, record):
"""
Override the formatter if the record has already been formatted
"""
if hasattr(record, 'formatted_log'):
if hasattr(record, "formatted_log"):
return record.formatted_log
else:
super(DebugLoggingThreadFormatter, self).format(record)
@@ -31,6 +32,7 @@ class DebugLoggingThread(object, metaclass=Singleton):
"""
Debug Logging Thread
"""
def __init__(self):
self._handlers = list()
self._log_queue = multiprocessing.Queue()
@@ -42,13 +44,13 @@ class DebugLoggingThread(object, metaclass=Singleton):
"""
Send a log record to debug logging thread
"""
self._log_queue.put_nowait(['log-record', log_record])
self._log_queue.put_nowait(["log-record", log_record])
def send_log_config(self, config):
"""
Send log configuration to debug logging thread
"""
self._log_queue.put_nowait(['log-config', config])
self._log_queue.put_nowait(["log-config", config])
def _receive_logs(self):
"""
@@ -63,42 +65,44 @@ class DebugLoggingThread(object, metaclass=Singleton):
if log_work is not None:
action, work = log_work
if 'log-record' == action:
if "log-record" == action:
if self._handlers:
for handler in self._handlers:
if hasattr(handler, 'is_stdout'):
if hasattr(handler, "is_stdout"):
try:
date_time = work.asctime
text = str(work.formatted_log)
text = text.split('[', 1)[-1]
text = text.split(':', 1)[-1]
work.formatted_log = date_time + ' ' + text
text = text.split("[", 1)[-1]
text = text.split(":", 1)[-1]
work.formatted_log = date_time + " " + text
except Exception:
pass
handler.emit(work)
elif 'log-config' == action:
elif "log-config" == action:
if self._handlers:
for handler in self._handlers:
handler.close()
handler_names = work.get('handlers', '')
handler_list = [handler.strip()
for handler in handler_names.split(',')]
handler_names = work.get("handlers", "")
handler_list = [
handler.strip() for handler in handler_names.split(",")
]
self._handlers[:] = list()
if 'syslog' in handler_list:
address = work.get('syslog_address', '/dev/log')
facility = work.get('syslog_facility', 'user')
if "syslog" in handler_list:
address = work.get("syslog_address", "/dev/log")
facility = work.get("syslog_facility", "user")
facility = SysLogHandler.facility_names[facility]
syslog_handler = SysLogHandler(address=address,
facility=facility)
syslog_handler = SysLogHandler(
address=address, facility=facility
)
syslog_handler.setFormatter(formatter)
self._handlers.append(syslog_handler)
if 'stdout' in handler_list:
if "stdout" in handler_list:
stdout_handler = logging.StreamHandler(sys.stdout)
stdout_handler.setFormatter(formatter)
stdout_handler.is_stdout = True
+16 -13
View File
@@ -1,17 +1,20 @@
#
# Copyright (c) 2015-2016 Wind River Systems, Inc.
# Copyright (c) 2015-2016, 2026 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
from nfv_common.event_log._event_log_module import event_log # noqa: F401
from nfv_common.event_log._event_log_module import event_log_finalize # noqa: F401
from nfv_common.event_log._event_log_module import event_log_initialize # noqa: F401
from nfv_common.event_log._event_log_module import event_log_subsystem_sane # noqa: F401
from nfv_common.event_log.objects.v1 import EVENT_CONTEXT # noqa: F401
from nfv_common.event_log.objects.v1 import EVENT_ID # noqa: F401
from nfv_common.event_log.objects.v1 import EVENT_IMPORTANCE # noqa: F401
from nfv_common.event_log.objects.v1 import EVENT_INITIATED_BY # noqa: F401
from nfv_common.event_log.objects.v1 import EVENT_TYPE # noqa: F401
from nfv_common.event_log.objects.v1 import EventLogData # noqa: F401
from nfv_common.event_log.objects.v1 import EventLogStateData # noqa: F401
from nfv_common.event_log.objects.v1 import EventLogThresholdData # noqa: F401
# flake8: noqa
from nfv_common.event_log._event_log_module import event_log
from nfv_common.event_log._event_log_module import event_log_finalize
from nfv_common.event_log._event_log_module import event_log_initialize
from nfv_common.event_log._event_log_module import (
event_log_subsystem_sane,
)
from nfv_common.event_log.objects.v1 import EVENT_CONTEXT
from nfv_common.event_log.objects.v1 import EVENT_ID
from nfv_common.event_log.objects.v1 import EVENT_IMPORTANCE
from nfv_common.event_log.objects.v1 import EVENT_INITIATED_BY
from nfv_common.event_log.objects.v1 import EVENT_TYPE
from nfv_common.event_log.objects.v1 import EventLogData
from nfv_common.event_log.objects.v1 import EventLogStateData
from nfv_common.event_log.objects.v1 import EventLogThresholdData
@@ -8,33 +8,38 @@ import stevedore
from nfv_common import debug
from nfv_common.helpers import Singleton
DLOG = debug.debug_get_logger('nfv_common.event_log.event_log_handlers')
DLOG = debug.debug_get_logger("nfv_common.event_log.event_log_handlers")
class EventLogHandlers(stevedore.enabled.EnabledExtensionManager, metaclass=Singleton):
"""
Event Log Handlers
"""
_version = '1.0.0'
_signature = 'e33d7cf6-f270-4256-893e-16266ee4dd2e'
_version = "1.0.0"
_signature = "e33d7cf6-f270-4256-893e-16266ee4dd2e"
def __init__(self, namespace, handler_names):
super(EventLogHandlers, self).__init__(namespace,
EventLogHandlers.valid_handler,
invoke_on_load=True,
invoke_args=(), invoke_kwds={})
super(EventLogHandlers, self).__init__(
namespace,
EventLogHandlers.valid_handler,
invoke_on_load=True,
invoke_args=(),
invoke_kwds={},
)
handler_list = [handler.strip() for handler in handler_names.split(',')]
handler_list = [handler.strip() for handler in handler_names.split(",")]
self._handlers = {}
for handler in self:
if handler.obj.name in handler_list:
handler_id = handler.obj.provider + ':' + handler.obj.name
handler_id = handler.obj.provider + ":" + handler.obj.name
if handler_id not in self._handlers:
self._handlers[handler_id] = handler
DLOG.info("Loaded handler %s version %s provided by %s."
% (handler.obj.name, handler.obj.version,
handler.obj.provider))
DLOG.info(
"Loaded handler %s version %s provided by %s."
% (handler.obj.name, handler.obj.version, handler.obj.provider)
)
@staticmethod
def valid_handler(handler):
@@ -44,9 +49,11 @@ class EventLogHandlers(stevedore.enabled.EnabledExtensionManager, metaclass=Sing
if EventLogHandlers._signature == handler.obj.signature:
return True
else:
DLOG.info("Handler %s version %s from provider %s has an invalid "
"signature." % (handler.obj.name, handler.obj.version,
handler.obj.provider))
DLOG.info(
"Handler %s version %s from provider %s has an invalid "
"signature."
% (handler.obj.name, handler.obj.version, handler.obj.provider)
)
return False
def log(self, log_data):
@@ -1,5 +1,5 @@
#
# Copyright (c) 2015-2016 Wind River Systems, Inc.
# Copyright (c) 2015-2016, 2026 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
@@ -10,6 +10,7 @@ def event_log(log_data):
Log a particular event
"""
from nfv_common.event_log._event_log_thread import EventLogThread
EventLogThread().log(log_data)
@@ -18,6 +19,7 @@ def event_log_subsystem_sane():
Returns true if the event log subsystem is healthy
"""
from nfv_common.event_log._event_log_thread import EventLogThread
return 600 >= EventLogThread().stall_elapsed_secs
@@ -26,6 +28,7 @@ def event_log_initialize(config):
Initialize the event log subsystem
"""
from nfv_common.event_log._event_log_thread import EventLogThread
EventLogThread(config).start()
@@ -34,4 +37,5 @@ def event_log_finalize():
Finalize the event log subsystem
"""
from nfv_common.event_log._event_log_thread import EventLogThread
EventLogThread().stop(max_wait_in_seconds=5)
@@ -11,13 +11,14 @@ from nfv_common.helpers import Singleton
from nfv_common.event_log._event_log_handlers import EventLogHandlers
DLOG = debug.debug_get_logger('nfv_common.event_log.event_log_thread')
DLOG = debug.debug_get_logger("nfv_common.event_log.event_log_thread")
class EventLogWorker(thread.ThreadWorker, metaclass=Singleton):
"""
Event Log Worker
"""
def __init__(self, name, config):
super(EventLogWorker, self).__init__(name)
self._config = config
@@ -27,9 +28,10 @@ class EventLogWorker(thread.ThreadWorker, metaclass=Singleton):
"""
Initialize the Event Log Worker
"""
self._handlers = EventLogHandlers(self._config['namespace'],
self._config['handlers'])
self._handlers.initialize(self._config['config_file'])
self._handlers = EventLogHandlers(
self._config["namespace"], self._config["handlers"]
)
self._handlers.initialize(self._config["config_file"])
def finalize(self):
"""
@@ -43,23 +45,24 @@ class EventLogWorker(thread.ThreadWorker, metaclass=Singleton):
Do work given to the Event Log Worker
"""
if EventLogThread.ACTION_LOG_EVENT == action:
self._handlers.log(work['log-data'])
self._handlers.log(work["log-data"])
class EventLogThread(thread.Thread, metaclass=Singleton):
"""
Event Log Thread
"""
ACTION_LOG_EVENT = "thread-log-event"
def __init__(self, config=None):
self._worker = EventLogWorker('Event-Log', config)
super(EventLogThread, self).__init__('Event-Log', self._worker)
self._worker = EventLogWorker("Event-Log", config)
super(EventLogThread, self).__init__("Event-Log", self._worker)
def log(self, log_data):
"""
Send log data to the Event Log Thread
"""
work = dict()
work['log-data'] = log_data
work["log-data"] = log_data
self.send_work(EventLogThread.ACTION_LOG_EVENT, work)
@@ -1,6 +1,9 @@
#
# Copyright (c) 2015-2016 Wind River Systems, Inc.
# Copyright (c) 2015-2016, 2026 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
from nfv_common.event_log.handlers.v1._event_log_handler import EventLogHandler # noqa: F401
# flake8: noqa
from nfv_common.event_log.handlers.v1._event_log_handler import (
EventLogHandler,
)
@@ -10,41 +10,42 @@ class EventLogHandler(object, metaclass=abc.ABCMeta):
"""
Abstract Event Log Handler Class Definition
"""
@property
@abc.abstractmethod
def name(self):
"""The name of handler """
"""The name of handler"""
pass
@property
@abc.abstractmethod
def version(self):
"""The versions of the handler """
"""The versions of the handler"""
pass
@property
@abc.abstractmethod
def provider(self):
"""Who created the handler """
"""Who created the handler"""
pass
@property
@abc.abstractmethod
def signature(self):
"""Signature of the handler """
"""Signature of the handler"""
pass
@abc.abstractmethod
def log(self, log_data):
"""Log an event via the handler """
"""Log an event via the handler"""
pass
@abc.abstractmethod
def initialize(self, config_file):
"""Initialize the handler """
"""Initialize the handler"""
pass
@abc.abstractmethod
def finalize(self):
"""Finalize the handler """
"""Finalize the handler"""
pass
@@ -1,13 +1,22 @@
#
# Copyright (c) 2015-2016 Wind River Systems, Inc.
# Copyright (c) 2015-2016, 2026 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
from nfv_common.event_log.objects.v1._event_log_data import EventLogData # noqa: F401
from nfv_common.event_log.objects.v1._event_log_data import EventLogStateData # noqa: F401
from nfv_common.event_log.objects.v1._event_log_data import EventLogThresholdData # noqa: F401
from nfv_common.event_log.objects.v1._event_log_defs import EVENT_CONTEXT # noqa: F401
from nfv_common.event_log.objects.v1._event_log_defs import EVENT_ID # noqa: F401
from nfv_common.event_log.objects.v1._event_log_defs import EVENT_IMPORTANCE # noqa: F401
from nfv_common.event_log.objects.v1._event_log_defs import EVENT_INITIATED_BY # noqa: F401
from nfv_common.event_log.objects.v1._event_log_defs import EVENT_TYPE # noqa: F401
# flake8: noqa
from nfv_common.event_log.objects.v1._event_log_data import EventLogData
from nfv_common.event_log.objects.v1._event_log_data import (
EventLogStateData,
)
from nfv_common.event_log.objects.v1._event_log_data import (
EventLogThresholdData,
)
from nfv_common.event_log.objects.v1._event_log_defs import EVENT_CONTEXT
from nfv_common.event_log.objects.v1._event_log_defs import EVENT_ID
from nfv_common.event_log.objects.v1._event_log_defs import (
EVENT_IMPORTANCE,
)
from nfv_common.event_log.objects.v1._event_log_defs import (
EVENT_INITIATED_BY,
)
from nfv_common.event_log.objects.v1._event_log_defs import EVENT_TYPE
@@ -1,5 +1,5 @@
#
# Copyright (c) 2015-2016 Wind River Systems, Inc.
# Copyright (c) 2015-2016, 2026 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
@@ -10,6 +10,7 @@ class EventLogStateData(object):
"""
Event Log State Data
"""
def __init__(self, state):
self.state = state
@@ -18,6 +19,7 @@ class EventLogThresholdData(object):
"""
Event Log Threshold Data
"""
def __init__(self, threshold_value, observed_value):
self.threshold_value = threshold_value
self.observed_value = observed_value
@@ -27,11 +29,23 @@ class EventLogData(object):
"""
Event Log Data
"""
_id = 1
def __init__(self, event_id, event_type, event_context, entity_type, entity,
reason_text, importance, additional_text="", state_data=None,
threshold_data=None, suppression_allowed=True):
def __init__(
self,
event_id,
event_type,
event_context,
entity_type,
entity,
reason_text,
importance,
additional_text="",
state_data=None,
threshold_data=None,
suppression_allowed=True,
):
self.log_id = EventLogData._id
self.event_id = event_id
self.event_type = event_type
@@ -13,237 +13,312 @@ class _EventId(Constants, metaclass=Singleton):
"""
Event Type Constants
"""
UNKNOWN = Constant('unknown')
MULTI_NODE_RECOVERY_MODE_ENTER = Constant('multi-node-recovery-enter')
MULTI_NODE_RECOVERY_MODE_EXIT = Constant('multi-node-recovery-exit')
HOST_SERVICES_ENABLED = Constant('host-services-enabled')
HOST_SERVICES_DISABLED = Constant('host-services-disabled')
HOST_SERVICES_FAILED = Constant('host-services-failed')
HYPERVISOR_STATE_CHANGE = Constant('hypervisor-state-change')
INSTANCE_RENAMED = Constant('instance-renamed')
INSTANCE_ENABLED = Constant('instance-enabled')
INSTANCE_FAILED = Constant('instance-failed')
INSTANCE_SCHEDULING_FAILED = Constant('instance-scheduling-failed')
INSTANCE_CREATE_BEGIN = Constant('instance-create-begin')
INSTANCE_CREATING = Constant('instance-creating')
INSTANCE_CREATE_REJECTED = Constant('instance-create-rejected')
INSTANCE_CREATE_CANCELLED = Constant('instance-create-cancelled')
INSTANCE_CREATE_FAILED = Constant('instance-create-failed')
INSTANCE_CREATED = Constant('instance-created')
INSTANCE_DELETE_BEGIN = Constant('instance-delete-begin')
INSTANCE_DELETING = Constant('instance-deleting')
INSTANCE_DELETE_REJECTED = Constant('instance-delete-rejected')
INSTANCE_DELETE_CANCELLED = Constant('instance-delete-cancelled')
INSTANCE_DELETE_FAILED = Constant('instance-delete-failed')
INSTANCE_DELETED = Constant('instance-deleted')
INSTANCE_PAUSE_BEGIN = Constant('instance-pause-begin')
INSTANCE_PAUSING = Constant('instance-pausing')
INSTANCE_PAUSE_REJECTED = Constant('instance-pause-rejected')
INSTANCE_PAUSE_CANCELLED = Constant('instance-pause-cancelled')
INSTANCE_PAUSE_FAILED = Constant('instance-pause-failed')
INSTANCE_PAUSED = Constant('instance-paused')
INSTANCE_UNPAUSE_BEGIN = Constant('instance-unpause-begin')
INSTANCE_UNPAUSING = Constant('instance-unpausing')
INSTANCE_UNPAUSE_REJECTED = Constant('instance-unpause-rejected')
INSTANCE_UNPAUSE_CANCELLED = Constant('instance-unpause-cancelled')
INSTANCE_UNPAUSE_FAILED = Constant('instance-unpause-failed')
INSTANCE_UNPAUSED = Constant('instance-unpaused')
INSTANCE_SUSPEND_BEGIN = Constant('instance-suspend-begin')
INSTANCE_SUSPENDING = Constant('instance-suspending')
INSTANCE_SUSPEND_REJECTED = Constant('instance-suspend-rejected')
INSTANCE_SUSPEND_CANCELLED = Constant('instance-suspend-cancelled')
INSTANCE_SUSPEND_FAILED = Constant('instance-suspend-failed')
INSTANCE_SUSPENDED = Constant('instance-suspended')
INSTANCE_RESUME_BEGIN = Constant('instance-resume-begin')
INSTANCE_RESUMING = Constant('instance-resuming')
INSTANCE_RESUME_REJECTED = Constant('instance-resume-rejected')
INSTANCE_RESUME_CANCELLED = Constant('instance-resume-cancelled')
INSTANCE_RESUME_FAILED = Constant('instance-resume-failed')
INSTANCE_RESUMED = Constant('instance-resumed')
INSTANCE_START_BEGIN = Constant('instance-start-begin')
INSTANCE_STARTING = Constant('instance-starting')
INSTANCE_START_REJECTED = Constant('instance-start-rejected')
INSTANCE_START_CANCELLED = Constant('instance-start-cancelled')
INSTANCE_START_FAILED = Constant('instance-start-failed')
INSTANCE_STARTED = Constant('instance-started')
INSTANCE_STOP_BEGIN = Constant('instance-stop-begin')
INSTANCE_STOPPING = Constant('instance-stopping')
INSTANCE_STOP_REJECTED = Constant('instance-stop-rejected')
INSTANCE_STOP_CANCELLED = Constant('instance-stop-cancelled')
INSTANCE_STOP_FAILED = Constant('instance-stop-failed')
INSTANCE_STOPPED = Constant('instance-stopped')
INSTANCE_LIVE_MIGRATE_BEGIN = Constant('instance-live-migrate-begin')
INSTANCE_LIVE_MIGRATING = Constant('instance-live-migrating')
INSTANCE_LIVE_MIGRATE_REJECTED = Constant('instance-live-migrate-rejected')
INSTANCE_LIVE_MIGRATE_CANCELLED = Constant('instance-live-migrate-cancelled')
INSTANCE_LIVE_MIGRATE_FAILED = Constant('instance-live-migrate-failed')
INSTANCE_LIVE_MIGRATED = Constant('instance-live-migrated')
INSTANCE_COLD_MIGRATE_BEGIN = Constant('instance-cold-migrate-begin')
INSTANCE_COLD_MIGRATING = Constant('instance-cold-migrating')
INSTANCE_COLD_MIGRATE_REJECTED = Constant('instance-cold-migrate-rejected')
INSTANCE_COLD_MIGRATE_CANCELLED = Constant('instance-cold-migrate-cancelled')
INSTANCE_COLD_MIGRATE_FAILED = Constant('instance-cold-migrate-failed')
INSTANCE_COLD_MIGRATED = Constant('instance-cold-migrated')
INSTANCE_COLD_MIGRATE_CONFIRM_BEGIN = Constant('instance-cold-migrate-confirm-begin')
INSTANCE_COLD_MIGRATE_CONFIRMING = Constant('instance-cold-migrate-confirming')
INSTANCE_COLD_MIGRATE_CONFIRM_REJECTED = Constant('instance-cold-migrate-confirm-rejected')
INSTANCE_COLD_MIGRATE_CONFIRM_CANCELLED = Constant('instance-cold-migrate-confirm-cancelled')
INSTANCE_COLD_MIGRATE_CONFIRM_FAILED = Constant('instance-cold-migrate-confirm-failed')
INSTANCE_COLD_MIGRATE_CONFIRMED = Constant('instance-cold-migrate-confirmed')
INSTANCE_COLD_MIGRATE_REVERT_BEGIN = Constant('instance-cold-migrate-revert-begin')
INSTANCE_COLD_MIGRATE_REVERTING = Constant('instance-cold-migrate-reverting')
INSTANCE_COLD_MIGRATE_REVERT_REJECTED = Constant('instance-cold-migrate-revert-rejected')
INSTANCE_COLD_MIGRATE_REVERT_CANCELLED = Constant('instance-cold-migrate-revert-cancelled')
INSTANCE_COLD_MIGRATE_REVERT_FAILED = Constant('instance-cold-migrate-revert-failed')
INSTANCE_COLD_MIGRATE_REVERTED = Constant('instance-cold-migrate-reverted')
INSTANCE_EVACUATE_BEGIN = Constant('instance-evacuate-begin')
INSTANCE_EVACUATING = Constant('instance-evacuating')
INSTANCE_EVACUATE_REJECTED = Constant('instance-evacuate-rejected')
INSTANCE_EVACUATE_CANCELLED = Constant('instance-evacuate-cancelled')
INSTANCE_EVACUATE_FAILED = Constant('instance-evacuate-failed')
INSTANCE_EVACUATED = Constant('instance-evacuated')
INSTANCE_REBOOT_BEGIN = Constant('instance-reboot-begin')
INSTANCE_REBOOTING = Constant('instance-rebooting')
INSTANCE_REBOOT_REJECTED = Constant('instance-reboot-rejected')
INSTANCE_REBOOT_CANCELLED = Constant('instance-reboot-cancelled')
INSTANCE_REBOOT_FAILED = Constant('instance-reboot-failed')
INSTANCE_REBOOTED = Constant('instance-rebooted')
INSTANCE_REBUILD_BEGIN = Constant('instance-rebuild-begin')
INSTANCE_REBUILDING = Constant('instance-rebuilding')
INSTANCE_REBUILD_REJECTED = Constant('instance-rebuild-rejected')
INSTANCE_REBUILD_CANCELLED = Constant('instance-rebuild-cancelled')
INSTANCE_REBUILD_FAILED = Constant('instance-rebuild-failed')
INSTANCE_REBUILT = Constant('instance-rebuilt')
INSTANCE_RESIZE_BEGIN = Constant('instance-resize-begin')
INSTANCE_RESIZING = Constant('instance-resizing')
INSTANCE_RESIZE_REJECTED = Constant('instance-resize-rejected')
INSTANCE_RESIZE_CANCELLED = Constant('instance-resize-cancelled')
INSTANCE_RESIZE_FAILED = Constant('instance-resize-failed')
INSTANCE_RESIZED = Constant('instance-resized')
INSTANCE_RESIZE_CONFIRM_BEGIN = Constant('instance-resize-confirm-begin')
INSTANCE_RESIZE_CONFIRMING = Constant('instance-resize-confirming')
INSTANCE_RESIZE_CONFIRM_REJECTED = Constant('instance-resize-confirm-rejected')
INSTANCE_RESIZE_CONFIRM_CANCELLED = Constant('instance-resize-confirm-cancelled')
INSTANCE_RESIZE_CONFIRM_FAILED = Constant('instance-resize-confirm-failed')
INSTANCE_RESIZE_CONFIRMED = Constant('instance-resize-confirmed')
INSTANCE_RESIZE_REVERT_BEGIN = Constant('instance-resize-revert-begin')
INSTANCE_RESIZE_REVERTING = Constant('instance-resize-reverting')
INSTANCE_RESIZE_REVERT_REJECTED = Constant('instance-resize-revert-rejected')
INSTANCE_RESIZE_REVERT_CANCELLED = Constant('instance-resize-revert-cancelled')
INSTANCE_RESIZE_REVERT_FAILED = Constant('instance-resize-revert-failed')
INSTANCE_RESIZE_REVERTED = Constant('instance-resize-reverted')
INSTANCE_GUEST_HEARTBEAT_ESTABLISHED = Constant('instance-guest-heartbeat-established')
INSTANCE_GUEST_HEARTBEAT_DISCONNECTED = Constant('instance-guest-heartbeat-disconnected')
INSTANCE_GUEST_HEARTBEAT_FAILED = Constant('instance-guest-heartbeat-failed')
INSTANCE_GUEST_HEALTH_CHECK_FAILED = Constant('instance-guest-health_check-failed')
SW_PATCH_AUTO_APPLY_START = Constant('sw-patch-auto-apply-started')
SW_PATCH_AUTO_APPLY_INPROGRESS = Constant('sw-patch-auto-apply-inprogress')
SW_PATCH_AUTO_APPLY_REJECTED = Constant('sw-patch-auto-apply-rejected')
SW_PATCH_AUTO_APPLY_CANCELLED = Constant('sw-patch-auto-apply-cancelled')
SW_PATCH_AUTO_APPLY_FAILED = Constant('sw-patch-auto-apply-failed')
SW_PATCH_AUTO_APPLY_COMPLETED = Constant('sw-patch-auto-apply-completed')
SW_PATCH_AUTO_APPLY_ABORT = Constant('sw-patch-auto-apply-abort')
SW_PATCH_AUTO_APPLY_ABORTING = Constant('sw-patch-auto-apply-aborting')
SW_PATCH_AUTO_APPLY_ABORT_REJECTED = Constant('sw-patch-auto-apply-abort-rejected')
SW_PATCH_AUTO_APPLY_ABORT_FAILED = Constant('sw-patch-auto-apply-abort-failed')
SW_PATCH_AUTO_APPLY_ABORTED = Constant('sw-patch-auto-apply-aborted')
SW_UPGRADE_AUTO_APPLY_START = Constant('sw-upgrade-auto-apply-started')
SW_UPGRADE_AUTO_APPLY_INPROGRESS = Constant('sw-upgrade-auto-apply-inprogress')
SW_UPGRADE_AUTO_APPLY_REJECTED = Constant('sw-upgrade-auto-apply-rejected')
SW_UPGRADE_AUTO_APPLY_CANCELLED = Constant('sw-upgrade-auto-apply-cancelled')
SW_UPGRADE_AUTO_APPLY_FAILED = Constant('sw-upgrade-auto-apply-failed')
SW_UPGRADE_AUTO_APPLY_COMPLETED = Constant('sw-upgrade-auto-apply-completed')
SW_UPGRADE_AUTO_APPLY_ABORT = Constant('sw-upgrade-auto-apply-abort')
SW_UPGRADE_AUTO_APPLY_ABORTING = Constant('sw-upgrade-auto-apply-aborting')
SW_UPGRADE_AUTO_APPLY_ABORT_REJECTED = Constant('sw-upgrade-auto-apply-abort-rejected')
SW_UPGRADE_AUTO_APPLY_ABORT_FAILED = Constant('sw-upgrade-auto-apply-abort-failed')
SW_UPGRADE_AUTO_APPLY_ABORTED = Constant('sw-upgrade-auto-apply-aborted')
FW_UPDATE_AUTO_APPLY_START = Constant('fw-update-auto-apply-started')
FW_UPDATE_AUTO_APPLY_INPROGRESS = Constant('fw-update-auto-apply-inprogress')
FW_UPDATE_AUTO_APPLY_REJECTED = Constant('fw-update-auto-apply-rejected')
FW_UPDATE_AUTO_APPLY_CANCELLED = Constant('fw-update-auto-apply-cancelled')
FW_UPDATE_AUTO_APPLY_FAILED = Constant('fw-update-auto-apply-failed')
FW_UPDATE_AUTO_APPLY_COMPLETED = Constant('fw-update-auto-apply-completed')
FW_UPDATE_AUTO_APPLY_ABORT = Constant('fw-update-auto-apply-abort')
FW_UPDATE_AUTO_APPLY_ABORTING = Constant('fw-update-auto-apply-aborting')
FW_UPDATE_AUTO_APPLY_ABORT_REJECTED = Constant('fw-update-auto-apply-abort-rejected')
FW_UPDATE_AUTO_APPLY_ABORT_FAILED = Constant('fw-update-auto-apply-abort-failed')
FW_UPDATE_AUTO_APPLY_ABORTED = Constant('fw-update-auto-apply-aborted')
KUBE_ROOTCA_UPDATE_AUTO_APPLY_START = Constant('kube-rootca-update-auto-apply-started')
KUBE_ROOTCA_UPDATE_AUTO_APPLY_INPROGRESS = Constant('kube-rootca-update-auto-apply-inprogress')
KUBE_ROOTCA_UPDATE_AUTO_APPLY_REJECTED = Constant('kube-rootca-update-auto-apply-rejected')
KUBE_ROOTCA_UPDATE_AUTO_APPLY_CANCELLED = Constant('kube-rootca-update-auto-apply-cancelled')
KUBE_ROOTCA_UPDATE_AUTO_APPLY_FAILED = Constant('kube-rootca-update-auto-apply-failed')
KUBE_ROOTCA_UPDATE_AUTO_APPLY_COMPLETED = Constant('kube-rootca-update-auto-apply-completed')
KUBE_ROOTCA_UPDATE_AUTO_APPLY_ABORT = Constant('kube-rootca-update-auto-apply-abort')
KUBE_ROOTCA_UPDATE_AUTO_APPLY_ABORTING = Constant('kube-rootca-update-auto-apply-aborting')
KUBE_ROOTCA_UPDATE_AUTO_APPLY_ABORT_REJECTED = Constant('kube-rootca-update-auto-apply-abort-rejected')
KUBE_ROOTCA_UPDATE_AUTO_APPLY_ABORT_FAILED = Constant('kube-rootca-update-auto-apply-abort-failed')
KUBE_ROOTCA_UPDATE_AUTO_APPLY_ABORTED = Constant('kube-rootca-update-auto-apply-aborted')
UNKNOWN = Constant("unknown")
MULTI_NODE_RECOVERY_MODE_ENTER = Constant("multi-node-recovery-enter")
MULTI_NODE_RECOVERY_MODE_EXIT = Constant("multi-node-recovery-exit")
HOST_SERVICES_ENABLED = Constant("host-services-enabled")
HOST_SERVICES_DISABLED = Constant("host-services-disabled")
HOST_SERVICES_FAILED = Constant("host-services-failed")
HYPERVISOR_STATE_CHANGE = Constant("hypervisor-state-change")
INSTANCE_RENAMED = Constant("instance-renamed")
INSTANCE_ENABLED = Constant("instance-enabled")
INSTANCE_FAILED = Constant("instance-failed")
INSTANCE_SCHEDULING_FAILED = Constant("instance-scheduling-failed")
INSTANCE_CREATE_BEGIN = Constant("instance-create-begin")
INSTANCE_CREATING = Constant("instance-creating")
INSTANCE_CREATE_REJECTED = Constant("instance-create-rejected")
INSTANCE_CREATE_CANCELLED = Constant("instance-create-cancelled")
INSTANCE_CREATE_FAILED = Constant("instance-create-failed")
INSTANCE_CREATED = Constant("instance-created")
INSTANCE_DELETE_BEGIN = Constant("instance-delete-begin")
INSTANCE_DELETING = Constant("instance-deleting")
INSTANCE_DELETE_REJECTED = Constant("instance-delete-rejected")
INSTANCE_DELETE_CANCELLED = Constant("instance-delete-cancelled")
INSTANCE_DELETE_FAILED = Constant("instance-delete-failed")
INSTANCE_DELETED = Constant("instance-deleted")
INSTANCE_PAUSE_BEGIN = Constant("instance-pause-begin")
INSTANCE_PAUSING = Constant("instance-pausing")
INSTANCE_PAUSE_REJECTED = Constant("instance-pause-rejected")
INSTANCE_PAUSE_CANCELLED = Constant("instance-pause-cancelled")
INSTANCE_PAUSE_FAILED = Constant("instance-pause-failed")
INSTANCE_PAUSED = Constant("instance-paused")
INSTANCE_UNPAUSE_BEGIN = Constant("instance-unpause-begin")
INSTANCE_UNPAUSING = Constant("instance-unpausing")
INSTANCE_UNPAUSE_REJECTED = Constant("instance-unpause-rejected")
INSTANCE_UNPAUSE_CANCELLED = Constant("instance-unpause-cancelled")
INSTANCE_UNPAUSE_FAILED = Constant("instance-unpause-failed")
INSTANCE_UNPAUSED = Constant("instance-unpaused")
INSTANCE_SUSPEND_BEGIN = Constant("instance-suspend-begin")
INSTANCE_SUSPENDING = Constant("instance-suspending")
INSTANCE_SUSPEND_REJECTED = Constant("instance-suspend-rejected")
INSTANCE_SUSPEND_CANCELLED = Constant("instance-suspend-cancelled")
INSTANCE_SUSPEND_FAILED = Constant("instance-suspend-failed")
INSTANCE_SUSPENDED = Constant("instance-suspended")
INSTANCE_RESUME_BEGIN = Constant("instance-resume-begin")
INSTANCE_RESUMING = Constant("instance-resuming")
INSTANCE_RESUME_REJECTED = Constant("instance-resume-rejected")
INSTANCE_RESUME_CANCELLED = Constant("instance-resume-cancelled")
INSTANCE_RESUME_FAILED = Constant("instance-resume-failed")
INSTANCE_RESUMED = Constant("instance-resumed")
INSTANCE_START_BEGIN = Constant("instance-start-begin")
INSTANCE_STARTING = Constant("instance-starting")
INSTANCE_START_REJECTED = Constant("instance-start-rejected")
INSTANCE_START_CANCELLED = Constant("instance-start-cancelled")
INSTANCE_START_FAILED = Constant("instance-start-failed")
INSTANCE_STARTED = Constant("instance-started")
INSTANCE_STOP_BEGIN = Constant("instance-stop-begin")
INSTANCE_STOPPING = Constant("instance-stopping")
INSTANCE_STOP_REJECTED = Constant("instance-stop-rejected")
INSTANCE_STOP_CANCELLED = Constant("instance-stop-cancelled")
INSTANCE_STOP_FAILED = Constant("instance-stop-failed")
INSTANCE_STOPPED = Constant("instance-stopped")
INSTANCE_LIVE_MIGRATE_BEGIN = Constant("instance-live-migrate-begin")
INSTANCE_LIVE_MIGRATING = Constant("instance-live-migrating")
INSTANCE_LIVE_MIGRATE_REJECTED = Constant("instance-live-migrate-rejected")
INSTANCE_LIVE_MIGRATE_CANCELLED = Constant("instance-live-migrate-cancelled")
INSTANCE_LIVE_MIGRATE_FAILED = Constant("instance-live-migrate-failed")
INSTANCE_LIVE_MIGRATED = Constant("instance-live-migrated")
INSTANCE_COLD_MIGRATE_BEGIN = Constant("instance-cold-migrate-begin")
INSTANCE_COLD_MIGRATING = Constant("instance-cold-migrating")
INSTANCE_COLD_MIGRATE_REJECTED = Constant("instance-cold-migrate-rejected")
INSTANCE_COLD_MIGRATE_CANCELLED = Constant("instance-cold-migrate-cancelled")
INSTANCE_COLD_MIGRATE_FAILED = Constant("instance-cold-migrate-failed")
INSTANCE_COLD_MIGRATED = Constant("instance-cold-migrated")
INSTANCE_COLD_MIGRATE_CONFIRM_BEGIN = Constant(
"instance-cold-migrate-confirm-begin"
)
INSTANCE_COLD_MIGRATE_CONFIRMING = Constant("instance-cold-migrate-confirming")
INSTANCE_COLD_MIGRATE_CONFIRM_REJECTED = Constant(
"instance-cold-migrate-confirm-rejected"
)
INSTANCE_COLD_MIGRATE_CONFIRM_CANCELLED = Constant(
"instance-cold-migrate-confirm-cancelled"
)
INSTANCE_COLD_MIGRATE_CONFIRM_FAILED = Constant(
"instance-cold-migrate-confirm-failed"
)
INSTANCE_COLD_MIGRATE_CONFIRMED = Constant("instance-cold-migrate-confirmed")
INSTANCE_COLD_MIGRATE_REVERT_BEGIN = Constant("instance-cold-migrate-revert-begin")
INSTANCE_COLD_MIGRATE_REVERTING = Constant("instance-cold-migrate-reverting")
INSTANCE_COLD_MIGRATE_REVERT_REJECTED = Constant(
"instance-cold-migrate-revert-rejected"
)
INSTANCE_COLD_MIGRATE_REVERT_CANCELLED = Constant(
"instance-cold-migrate-revert-cancelled"
)
INSTANCE_COLD_MIGRATE_REVERT_FAILED = Constant(
"instance-cold-migrate-revert-failed"
)
INSTANCE_COLD_MIGRATE_REVERTED = Constant("instance-cold-migrate-reverted")
INSTANCE_EVACUATE_BEGIN = Constant("instance-evacuate-begin")
INSTANCE_EVACUATING = Constant("instance-evacuating")
INSTANCE_EVACUATE_REJECTED = Constant("instance-evacuate-rejected")
INSTANCE_EVACUATE_CANCELLED = Constant("instance-evacuate-cancelled")
INSTANCE_EVACUATE_FAILED = Constant("instance-evacuate-failed")
INSTANCE_EVACUATED = Constant("instance-evacuated")
INSTANCE_REBOOT_BEGIN = Constant("instance-reboot-begin")
INSTANCE_REBOOTING = Constant("instance-rebooting")
INSTANCE_REBOOT_REJECTED = Constant("instance-reboot-rejected")
INSTANCE_REBOOT_CANCELLED = Constant("instance-reboot-cancelled")
INSTANCE_REBOOT_FAILED = Constant("instance-reboot-failed")
INSTANCE_REBOOTED = Constant("instance-rebooted")
INSTANCE_REBUILD_BEGIN = Constant("instance-rebuild-begin")
INSTANCE_REBUILDING = Constant("instance-rebuilding")
INSTANCE_REBUILD_REJECTED = Constant("instance-rebuild-rejected")
INSTANCE_REBUILD_CANCELLED = Constant("instance-rebuild-cancelled")
INSTANCE_REBUILD_FAILED = Constant("instance-rebuild-failed")
INSTANCE_REBUILT = Constant("instance-rebuilt")
INSTANCE_RESIZE_BEGIN = Constant("instance-resize-begin")
INSTANCE_RESIZING = Constant("instance-resizing")
INSTANCE_RESIZE_REJECTED = Constant("instance-resize-rejected")
INSTANCE_RESIZE_CANCELLED = Constant("instance-resize-cancelled")
INSTANCE_RESIZE_FAILED = Constant("instance-resize-failed")
INSTANCE_RESIZED = Constant("instance-resized")
INSTANCE_RESIZE_CONFIRM_BEGIN = Constant("instance-resize-confirm-begin")
INSTANCE_RESIZE_CONFIRMING = Constant("instance-resize-confirming")
INSTANCE_RESIZE_CONFIRM_REJECTED = Constant("instance-resize-confirm-rejected")
INSTANCE_RESIZE_CONFIRM_CANCELLED = Constant("instance-resize-confirm-cancelled")
INSTANCE_RESIZE_CONFIRM_FAILED = Constant("instance-resize-confirm-failed")
INSTANCE_RESIZE_CONFIRMED = Constant("instance-resize-confirmed")
INSTANCE_RESIZE_REVERT_BEGIN = Constant("instance-resize-revert-begin")
INSTANCE_RESIZE_REVERTING = Constant("instance-resize-reverting")
INSTANCE_RESIZE_REVERT_REJECTED = Constant("instance-resize-revert-rejected")
INSTANCE_RESIZE_REVERT_CANCELLED = Constant("instance-resize-revert-cancelled")
INSTANCE_RESIZE_REVERT_FAILED = Constant("instance-resize-revert-failed")
INSTANCE_RESIZE_REVERTED = Constant("instance-resize-reverted")
INSTANCE_GUEST_HEARTBEAT_ESTABLISHED = Constant(
"instance-guest-heartbeat-established"
)
INSTANCE_GUEST_HEARTBEAT_DISCONNECTED = Constant(
"instance-guest-heartbeat-disconnected"
)
INSTANCE_GUEST_HEARTBEAT_FAILED = Constant("instance-guest-heartbeat-failed")
INSTANCE_GUEST_HEALTH_CHECK_FAILED = Constant("instance-guest-health_check-failed")
SW_PATCH_AUTO_APPLY_START = Constant("sw-patch-auto-apply-started")
SW_PATCH_AUTO_APPLY_INPROGRESS = Constant("sw-patch-auto-apply-inprogress")
SW_PATCH_AUTO_APPLY_REJECTED = Constant("sw-patch-auto-apply-rejected")
SW_PATCH_AUTO_APPLY_CANCELLED = Constant("sw-patch-auto-apply-cancelled")
SW_PATCH_AUTO_APPLY_FAILED = Constant("sw-patch-auto-apply-failed")
SW_PATCH_AUTO_APPLY_COMPLETED = Constant("sw-patch-auto-apply-completed")
SW_PATCH_AUTO_APPLY_ABORT = Constant("sw-patch-auto-apply-abort")
SW_PATCH_AUTO_APPLY_ABORTING = Constant("sw-patch-auto-apply-aborting")
SW_PATCH_AUTO_APPLY_ABORT_REJECTED = Constant("sw-patch-auto-apply-abort-rejected")
SW_PATCH_AUTO_APPLY_ABORT_FAILED = Constant("sw-patch-auto-apply-abort-failed")
SW_PATCH_AUTO_APPLY_ABORTED = Constant("sw-patch-auto-apply-aborted")
SW_UPGRADE_AUTO_APPLY_START = Constant("sw-upgrade-auto-apply-started")
SW_UPGRADE_AUTO_APPLY_INPROGRESS = Constant("sw-upgrade-auto-apply-inprogress")
SW_UPGRADE_AUTO_APPLY_REJECTED = Constant("sw-upgrade-auto-apply-rejected")
SW_UPGRADE_AUTO_APPLY_CANCELLED = Constant("sw-upgrade-auto-apply-cancelled")
SW_UPGRADE_AUTO_APPLY_FAILED = Constant("sw-upgrade-auto-apply-failed")
SW_UPGRADE_AUTO_APPLY_COMPLETED = Constant("sw-upgrade-auto-apply-completed")
SW_UPGRADE_AUTO_APPLY_ABORT = Constant("sw-upgrade-auto-apply-abort")
SW_UPGRADE_AUTO_APPLY_ABORTING = Constant("sw-upgrade-auto-apply-aborting")
SW_UPGRADE_AUTO_APPLY_ABORT_REJECTED = Constant(
"sw-upgrade-auto-apply-abort-rejected"
)
SW_UPGRADE_AUTO_APPLY_ABORT_FAILED = Constant("sw-upgrade-auto-apply-abort-failed")
SW_UPGRADE_AUTO_APPLY_ABORTED = Constant("sw-upgrade-auto-apply-aborted")
FW_UPDATE_AUTO_APPLY_START = Constant("fw-update-auto-apply-started")
FW_UPDATE_AUTO_APPLY_INPROGRESS = Constant("fw-update-auto-apply-inprogress")
FW_UPDATE_AUTO_APPLY_REJECTED = Constant("fw-update-auto-apply-rejected")
FW_UPDATE_AUTO_APPLY_CANCELLED = Constant("fw-update-auto-apply-cancelled")
FW_UPDATE_AUTO_APPLY_FAILED = Constant("fw-update-auto-apply-failed")
FW_UPDATE_AUTO_APPLY_COMPLETED = Constant("fw-update-auto-apply-completed")
FW_UPDATE_AUTO_APPLY_ABORT = Constant("fw-update-auto-apply-abort")
FW_UPDATE_AUTO_APPLY_ABORTING = Constant("fw-update-auto-apply-aborting")
FW_UPDATE_AUTO_APPLY_ABORT_REJECTED = Constant(
"fw-update-auto-apply-abort-rejected"
)
FW_UPDATE_AUTO_APPLY_ABORT_FAILED = Constant("fw-update-auto-apply-abort-failed")
FW_UPDATE_AUTO_APPLY_ABORTED = Constant("fw-update-auto-apply-aborted")
KUBE_UPGRADE_AUTO_APPLY_START = Constant('kube-upgrade-auto-apply-started')
KUBE_UPGRADE_AUTO_APPLY_INPROGRESS = Constant('kube-upgrade-auto-apply-inprogress')
KUBE_UPGRADE_AUTO_APPLY_REJECTED = Constant('kube-upgrade-auto-apply-rejected')
KUBE_UPGRADE_AUTO_APPLY_CANCELLED = Constant('kube-upgrade-auto-apply-cancelled')
KUBE_UPGRADE_AUTO_APPLY_FAILED = Constant('kube-upgrade-auto-apply-failed')
KUBE_UPGRADE_AUTO_APPLY_COMPLETED = Constant('kube-upgrade-auto-apply-completed')
KUBE_UPGRADE_AUTO_APPLY_ABORT = Constant('kube-upgrade-auto-apply-abort')
KUBE_UPGRADE_AUTO_APPLY_ABORTING = Constant('kube-upgrade-auto-apply-aborting')
KUBE_UPGRADE_AUTO_APPLY_ABORT_REJECTED = Constant('kube-upgrade-auto-apply-abort-rejected')
KUBE_UPGRADE_AUTO_APPLY_ABORT_FAILED = Constant('kube-upgrade-auto-apply-abort-failed')
KUBE_UPGRADE_AUTO_APPLY_ABORTED = Constant('kube-upgrade-auto-apply-aborted')
KUBE_ROOTCA_UPDATE_AUTO_APPLY_START = Constant(
"kube-rootca-update-auto-apply-started"
)
KUBE_ROOTCA_UPDATE_AUTO_APPLY_INPROGRESS = Constant(
"kube-rootca-update-auto-apply-inprogress"
)
KUBE_ROOTCA_UPDATE_AUTO_APPLY_REJECTED = Constant(
"kube-rootca-update-auto-apply-rejected"
)
KUBE_ROOTCA_UPDATE_AUTO_APPLY_CANCELLED = Constant(
"kube-rootca-update-auto-apply-cancelled"
)
KUBE_ROOTCA_UPDATE_AUTO_APPLY_FAILED = Constant(
"kube-rootca-update-auto-apply-failed"
)
KUBE_ROOTCA_UPDATE_AUTO_APPLY_COMPLETED = Constant(
"kube-rootca-update-auto-apply-completed"
)
KUBE_ROOTCA_UPDATE_AUTO_APPLY_ABORT = Constant(
"kube-rootca-update-auto-apply-abort"
)
KUBE_ROOTCA_UPDATE_AUTO_APPLY_ABORTING = Constant(
"kube-rootca-update-auto-apply-aborting"
)
KUBE_ROOTCA_UPDATE_AUTO_APPLY_ABORT_REJECTED = Constant(
"kube-rootca-update-auto-apply-abort-rejected"
)
KUBE_ROOTCA_UPDATE_AUTO_APPLY_ABORT_FAILED = Constant(
"kube-rootca-update-auto-apply-abort-failed"
)
KUBE_ROOTCA_UPDATE_AUTO_APPLY_ABORTED = Constant(
"kube-rootca-update-auto-apply-aborted"
)
SYSTEM_CONFIG_UPDATE_AUTO_APPLY_START = Constant('system-config-update-auto-apply-started')
SYSTEM_CONFIG_UPDATE_AUTO_APPLY_INPROGRESS = Constant('system-config-update-auto-apply-inprogress')
SYSTEM_CONFIG_UPDATE_AUTO_APPLY_REJECTED = Constant('system-config-update-auto-apply-rejected')
SYSTEM_CONFIG_UPDATE_AUTO_APPLY_CANCELLED = Constant('system-config-update-auto-apply-cancelled')
SYSTEM_CONFIG_UPDATE_AUTO_APPLY_FAILED = Constant('system-config-update-auto-apply-failed')
SYSTEM_CONFIG_UPDATE_AUTO_APPLY_COMPLETED = Constant('system-config-update-auto-apply-completed')
SYSTEM_CONFIG_UPDATE_AUTO_APPLY_ABORT = Constant('system-config-update-auto-apply-abort')
SYSTEM_CONFIG_UPDATE_AUTO_APPLY_ABORTING = Constant('system-config-update-auto-apply-aborting')
SYSTEM_CONFIG_UPDATE_AUTO_APPLY_ABORT_REJECTED = Constant('system-config-update-auto-apply-abort-rejected')
SYSTEM_CONFIG_UPDATE_AUTO_APPLY_ABORT_FAILED = Constant('system-config-update-auto-apply-abort-failed')
SYSTEM_CONFIG_UPDATE_AUTO_APPLY_ABORTED = Constant('system-config-update-auto-apply-aborted')
KUBE_UPGRADE_AUTO_APPLY_START = Constant("kube-upgrade-auto-apply-started")
KUBE_UPGRADE_AUTO_APPLY_INPROGRESS = Constant("kube-upgrade-auto-apply-inprogress")
KUBE_UPGRADE_AUTO_APPLY_REJECTED = Constant("kube-upgrade-auto-apply-rejected")
KUBE_UPGRADE_AUTO_APPLY_CANCELLED = Constant("kube-upgrade-auto-apply-cancelled")
KUBE_UPGRADE_AUTO_APPLY_FAILED = Constant("kube-upgrade-auto-apply-failed")
KUBE_UPGRADE_AUTO_APPLY_COMPLETED = Constant("kube-upgrade-auto-apply-completed")
KUBE_UPGRADE_AUTO_APPLY_ABORT = Constant("kube-upgrade-auto-apply-abort")
KUBE_UPGRADE_AUTO_APPLY_ABORTING = Constant("kube-upgrade-auto-apply-aborting")
KUBE_UPGRADE_AUTO_APPLY_ABORT_REJECTED = Constant(
"kube-upgrade-auto-apply-abort-rejected"
)
KUBE_UPGRADE_AUTO_APPLY_ABORT_FAILED = Constant(
"kube-upgrade-auto-apply-abort-failed"
)
KUBE_UPGRADE_AUTO_APPLY_ABORTED = Constant("kube-upgrade-auto-apply-aborted")
SYSTEM_CONFIG_UPDATE_AUTO_APPLY_START = Constant(
"system-config-update-auto-apply-started"
)
SYSTEM_CONFIG_UPDATE_AUTO_APPLY_INPROGRESS = Constant(
"system-config-update-auto-apply-inprogress"
)
SYSTEM_CONFIG_UPDATE_AUTO_APPLY_REJECTED = Constant(
"system-config-update-auto-apply-rejected"
)
SYSTEM_CONFIG_UPDATE_AUTO_APPLY_CANCELLED = Constant(
"system-config-update-auto-apply-cancelled"
)
SYSTEM_CONFIG_UPDATE_AUTO_APPLY_FAILED = Constant(
"system-config-update-auto-apply-failed"
)
SYSTEM_CONFIG_UPDATE_AUTO_APPLY_COMPLETED = Constant(
"system-config-update-auto-apply-completed"
)
SYSTEM_CONFIG_UPDATE_AUTO_APPLY_ABORT = Constant(
"system-config-update-auto-apply-abort"
)
SYSTEM_CONFIG_UPDATE_AUTO_APPLY_ABORTING = Constant(
"system-config-update-auto-apply-aborting"
)
SYSTEM_CONFIG_UPDATE_AUTO_APPLY_ABORT_REJECTED = Constant(
"system-config-update-auto-apply-abort-rejected"
)
SYSTEM_CONFIG_UPDATE_AUTO_APPLY_ABORT_FAILED = Constant(
"system-config-update-auto-apply-abort-failed"
)
SYSTEM_CONFIG_UPDATE_AUTO_APPLY_ABORTED = Constant(
"system-config-update-auto-apply-aborted"
)
class _EventType(Constants, metaclass=Singleton):
"""
Event Type Constants
"""
UNKNOWN = Constant('unknown')
STATE_EVENT = Constant('state-event')
ACTION_EVENT = Constant('action-event')
GUEST_HEARTBEAT_EVENT = Constant('guest-heartbeat-event')
PROCESSING_ERROR = Constant('processing-error')
UNKNOWN = Constant("unknown")
STATE_EVENT = Constant("state-event")
ACTION_EVENT = Constant("action-event")
GUEST_HEARTBEAT_EVENT = Constant("guest-heartbeat-event")
PROCESSING_ERROR = Constant("processing-error")
class _EventContext(Constants, metaclass=Singleton):
"""
Event Context Constants
"""
ADMIN = Constant('admin')
TENANT = Constant('tenant')
ADMIN = Constant("admin")
TENANT = Constant("tenant")
class _EventImportance(Constants, metaclass=Singleton):
"""
Event Importance Constants
"""
UNKNOWN = Constant('unknown')
HIGH = Constant('high')
MEDIUM = Constant('medium')
LOW = Constant('low')
UNKNOWN = Constant("unknown")
HIGH = Constant("high")
MEDIUM = Constant("medium")
LOW = Constant("low")
class _EventInitiatedBy(Constants, metaclass=Singleton):
"""
Initiated-By Constants
"""
UNKNOWN = Constant('unknown')
TENANT = Constant('tenant')
INSTANCE = Constant('instance')
INSTANCE_DIRECTOR = Constant('instance-director')
UNKNOWN = Constant("unknown")
TENANT = Constant("tenant")
INSTANCE = Constant("instance")
INSTANCE_DIRECTOR = Constant("instance-director")
# Constant Instantiation
+2 -1
View File
@@ -1,5 +1,5 @@
#
# Copyright (c) 2015-2016 Wind River Systems, Inc.
# Copyright (c) 2015-2016, 2026 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
@@ -10,4 +10,5 @@ class PickleableException(Exception):
Pickleable Exception
Used to mark custom exception classes that can be pickled.
"""
pass
+39 -20
View File
@@ -1,24 +1,43 @@
#
# Copyright (c) 2015-2016 Wind River Systems, Inc.
# Copyright (c) 2015-2016, 2026 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
from nfv_common.forensic._analysis import analysis_instance_cold_migrate_confirm_success # noqa: F401
from nfv_common.forensic._analysis import analysis_instance_cold_migrate_revert_success # noqa: F401
from nfv_common.forensic._analysis import analysis_instance_cold_migrate_success # noqa: F401
from nfv_common.forensic._analysis import analysis_instance_live_migrate_success # noqa: F401
from nfv_common.forensic._analysis import analysis_instance_pause_success # noqa: F401
from nfv_common.forensic._analysis import analysis_instance_reboot_success # noqa: F401
from nfv_common.forensic._analysis import analysis_instance_rebuild_success # noqa: F401
from nfv_common.forensic._analysis import analysis_instance_resize_confirm_success # noqa: F401
from nfv_common.forensic._analysis import analysis_instance_resize_revert_success # noqa: F401
from nfv_common.forensic._analysis import analysis_instance_resize_success # noqa: F401
from nfv_common.forensic._analysis import analysis_instance_resume_success # noqa: F401
from nfv_common.forensic._analysis import analysis_instance_start_success # noqa: F401
from nfv_common.forensic._analysis import analysis_instance_stop_success # noqa: F401
from nfv_common.forensic._analysis import analysis_instance_suspend_success # noqa: F401
from nfv_common.forensic._analysis import analysis_instance_unpause_success # noqa: F401
from nfv_common.forensic._analysis import analysis_stdout # noqa: F401
from nfv_common.forensic._evidence import evidence_from_files # noqa: F401
from nfv_common.forensic._forensic_module import forensic_finalize # noqa: F401
from nfv_common.forensic._forensic_module import forensic_initialize # noqa: F401
# flake8: noqa
from nfv_common.forensic._analysis import (
analysis_instance_cold_migrate_confirm_success,
)
from nfv_common.forensic._analysis import (
analysis_instance_cold_migrate_revert_success,
)
from nfv_common.forensic._analysis import (
analysis_instance_cold_migrate_success,
)
from nfv_common.forensic._analysis import (
analysis_instance_live_migrate_success,
)
from nfv_common.forensic._analysis import analysis_instance_pause_success
from nfv_common.forensic._analysis import analysis_instance_reboot_success
from nfv_common.forensic._analysis import (
analysis_instance_rebuild_success,
)
from nfv_common.forensic._analysis import (
analysis_instance_resize_confirm_success,
)
from nfv_common.forensic._analysis import (
analysis_instance_resize_revert_success,
)
from nfv_common.forensic._analysis import analysis_instance_resize_success
from nfv_common.forensic._analysis import analysis_instance_resume_success
from nfv_common.forensic._analysis import analysis_instance_start_success
from nfv_common.forensic._analysis import analysis_instance_stop_success
from nfv_common.forensic._analysis import (
analysis_instance_suspend_success,
)
from nfv_common.forensic._analysis import (
analysis_instance_unpause_success,
)
from nfv_common.forensic._analysis import analysis_stdout
from nfv_common.forensic._evidence import evidence_from_files
from nfv_common.forensic._forensic_module import forensic_finalize
from nfv_common.forensic._forensic_module import forensic_initialize
File diff suppressed because it is too large. Load diff
+158 -111
View File
@@ -1,5 +1,5 @@
#
# Copyright (c) 2015-2016 Wind River Systems, Inc.
# Copyright (c) 2015-2016, 2026 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
@@ -9,116 +9,163 @@ class _NfvVimRecordType(object):
"""
NFV-VIM Record Type Constants
"""
HOST_NFVI_STATE_CHANGE = 'nfv_vim_host_nfvi_state_change'
HOST_CONFIGURE_STATE = 'nfv_vim_host_configure_state'
HOST_ENABLING_STATE = 'nfv_vim_host_enabling_state'
HOST_ENABLED_STATE = 'nfv_vim_host_enabled_state'
HOST_DISABLING_STATE = 'nfv_vim_host_disabling_state'
HOST_DISABLED_STATE = 'nfv_vim_host_disabled_state'
HOST_DISABLING_FAILED_STATE = 'nfv_vim_host_disabling_failed_state'
HOST_DELETING_STATE = 'nfv_vim_host_deleting_state'
HOST_DELETED_STATE = 'nfv_vim_host_deleted_state'
INSTANCE_DIRECTOR_EVACUATE_FAILED = 'nfv_vim_director_evacuate_failed'
INSTANCE_DIRECTOR_EVACUATE_TIMEOUT = 'nfv_vim_director_evacuate_timeout'
INSTANCE_DIRECTOR_EVACUATE_SUCCESS = 'nfv_vim_director_evacuate_success'
INSTANCE_DIRECTOR_MIGRATE_FAILED = 'nfv_vim_director_migrate_failed'
INSTANCE_DIRECTOR_MIGRATE_TIMEOUT = 'nfv_vim_director_migrate_timeout'
INSTANCE_DIRECTOR_MIGRATE_SUCCESS = 'nfv_vim_director_migrate_success'
INSTANCE_INITIAL_STATE = 'nfv_vim_instance_initial_state'
INSTANCE_LIVE_MIGRATE_STATE = 'nfv_vim_instance_live_migrate_state'
INSTANCE_LIVE_MIGRATE_STATE_FAILED = 'nfv_vim_instance_live_migrate_state_failed'
INSTANCE_LIVE_MIGRATE_STATE_TIMED_OUT = 'nfv_vim_instance_live_migrate_state_timed_out'
INSTANCE_LIVE_MIGRATE_FINISH_STATE = 'nfv_vim_instance_live_migrate_finish_state'
INSTANCE_LIVE_MIGRATE_FINISH_STATE_FAILED = 'nfv_vim_instance_live_migrate_finish_state_failed'
INSTANCE_LIVE_MIGRATE_FINISH_STATE_TIMED_OUT = 'nfv_vim_instance_live_migrate_finish_state_timed_out'
INSTANCE_COLD_MIGRATE_STATE = 'nfv_vim_instance_cold_migrate_state'
INSTANCE_COLD_MIGRATE_STATE_FAILED = 'nfv_vim_instance_cold_migrate_state_failed'
INSTANCE_COLD_MIGRATE_STATE_TIMED_OUT = 'nfv_vim_instance_cold_migrate_state_timed_out'
INSTANCE_COLD_MIGRATE_CONFIRM_STATE = 'nfv_vim_instance_cold_migrate_confirm_state'
INSTANCE_COLD_MIGRATE_CONFIRM_STATE_FAILED = 'nfv_vim_instance_cold_migrate_confirm_state_failed'
INSTANCE_COLD_MIGRATE_CONFIRM_STATE_TIMED_OUT = 'nfv_vim_instance_cold_migrate_confirm_state_timed_out'
INSTANCE_COLD_MIGRATE_REVERT_STATE = 'nfv_vim_instance_cold_migrate_revert_state'
INSTANCE_COLD_MIGRATE_REVERT_STATE_FAILED = 'nfv_vim_instance_cold_migrate_revert_state_failed'
INSTANCE_COLD_MIGRATE_REVERT_STATE_TIMED_OUT = 'nfv_vim_instance_cold_migrate_revert_state_timed_out'
INSTANCE_EVACUATE_STATE = 'nfv_vim_instance_evacuate_state'
INSTANCE_START_STATE = 'nfv_vim_instance_start_state'
INSTANCE_START_STATE_INPROGRESS = 'nfv_vim_instance_start_state_inprogress'
INSTANCE_START_STATE_FAILED = 'nfv_vim_instance_start_state_failed'
INSTANCE_START_STATE_TIMED_OUT = 'nfv_vim_instance_start_state_timed_out'
INSTANCE_STOP_STATE = 'nfv_vim_instance_stop_state'
INSTANCE_STOP_STATE_COMPLETED = 'nfv_vim_instance_stop_state_completed'
INSTANCE_STOP_STATE_FAILED = 'nfv_vim_instance_stop_state_failed'
INSTANCE_STOP_STATE_TIMED_OUT = 'nfv_vim_instance_stop_state_timed_out'
INSTANCE_PAUSE_STATE = 'nfv_vim_instance_pause_state'
INSTANCE_PAUSE_STATE_COMPLETED = 'nfv_vim_instance_pause_state_completed'
INSTANCE_PAUSE_STATE_FAILED = 'nfv_vim_instance_pause_state_failed'
INSTANCE_PAUSE_STATE_TIMED_OUT = 'nfv_vim_instance_pause_state_timed_out'
INSTANCE_UNPAUSE_STATE = 'nfv_vim_instance_unpause_state'
INSTANCE_UNPAUSE_STATE_COMPLETED = 'nfv_vim_instance_unpause_state_completed'
INSTANCE_UNPAUSE_STATE_FAILED = 'nfv_vim_instance_unpause_state_failed'
INSTANCE_UNPAUSE_STATE_TIMED_OUT = 'nfv_vim_instance_unpause_state_timed_out'
INSTANCE_SUSPEND_STATE = 'nfv_vim_instance_suspend_state'
INSTANCE_SUSPEND_STATE_COMPLETED = 'nfv_vim_instance_suspend_state_completed'
INSTANCE_SUSPEND_STATE_FAILED = 'nfv_vim_instance_suspend_state_failed'
INSTANCE_SUSPEND_STATE_TIMED_OUT = 'nfv_vim_instance_suspend_state_timed_out'
INSTANCE_RESUME_STATE = 'nfv_vim_instance_resume_state'
INSTANCE_RESUME_STATE_COMPLETED = 'nfv_vim_instance_resume_state_completed'
INSTANCE_RESUME_STATE_FAILED = 'nfv_vim_instance_resume_state_failed'
INSTANCE_RESUME_STATE_TIMED_OUT = 'nfv_vim_instance_resume_state_timed_out'
INSTANCE_REBOOT_STATE = 'nfv_vim_instance_reboot_state'
INSTANCE_REBOOT_STATE_COMPLETED = 'nfv_vim_instance_reboot_state_completed'
INSTANCE_REBOOT_STATE_FAILED = 'nfv_vim_instance_reboot_state_failed'
INSTANCE_REBOOT_STATE_TIMED_OUT = 'nfv_vim_instance_reboot_state_timed_out'
INSTANCE_REBUILD_STATE = 'nfv_vim_instance_rebuild_state'
INSTANCE_REBUILD_STATE_COMPLETED = 'nfv_vim_instance_rebuild_state_completed'
INSTANCE_REBUILD_STATE_FAILED = 'nfv_vim_instance_rebuild_state_failed'
INSTANCE_REBUILD_STATE_TIMED_OUT = 'nfv_vim_instance_rebuild_state_timed_out'
INSTANCE_FAIL_STATE = 'nfv_vim_instance_fail_state'
INSTANCE_DELETE_STATE = 'nfv_vim_instance_delete_state'
INSTANCE_RESIZE_STATE = 'nfv_vim_instance_resize_state'
INSTANCE_RESIZE_STATE_FAILED = 'nfv_vim_instance_resize_state_failed'
INSTANCE_RESIZE_STATE_TIMED_OUT = 'nfv_vim_instance_resize_state_timed_out'
INSTANCE_RESIZE_CONFIRM_STATE = 'nfv_vim_instance_resize_confirm_state'
INSTANCE_RESIZE_CONFIRM_STATE_FAILED = 'nfv_vim_instance_resize_confirm_state_failed'
INSTANCE_RESIZE_CONFIRM_STATE_TIMED_OUT = 'nfv_vim_instance_resize_confirm_state_timed_out'
INSTANCE_RESIZE_REVERT_STATE = 'nfv_vim_instance_resize_revert_state'
INSTANCE_RESIZE_REVERT_STATE_FAILED = 'nfv_vim_instance_resize_revert_state_failed'
INSTANCE_RESIZE_REVERT_STATE_TIMED_OUT = 'nfv_vim_instance_resize_revert_state_timed_out'
INSTANCE_GUEST_SERVICES_CREATE_STATE = 'nfv_vim_instance_guest_services_create_state'
INSTANCE_GUEST_SERVICES_DELETE_STATE = 'nfv_vim_instance_guest_services_delete_state'
INSTANCE_GUEST_SERVICES_ENABLE_STATE = 'nfv_vim_instance_guest_services_enable_state'
INSTANCE_GUEST_SERVICES_DISABLE_STATE = 'nfv_vim_instance_guest_services_disable_state'
INSTANCE_GUEST_SERVICES_SET_STATE = 'nfv_vim_instance_guest_services_set_state'
INSTANCE_NFVI_ACTION_START = 'nfv_vim_instance_nfvi_action_initial'
INSTANCE_NFVI_STATE_CHANGE = 'nfv_vim_instance_nfvi_state_change'
INSTANCE_START_CALLBACK = 'nfv_vim_instance_start_callback'
INSTANCE_STOP_CALLBACK = 'nfv_vim_instance_stop_callback'
INSTANCE_PAUSE_CALLBACK = 'nfv_vim_instance_pause_callback'
INSTANCE_UNPAUSE_CALLBACK = 'nfv_vim_instance_unpause_callback'
INSTANCE_SUSPEND_CALLBACK = 'nfv_vim_instance_suspend_callback'
INSTANCE_RESUME_CALLBACK = 'nfv_vim_instance_resume_callback'
INSTANCE_REBOOT_CALLBACK = 'nfv_vim_instance_reboot_callback'
INSTANCE_REBUILD_CALLBACK = 'nfv_vim_instance_rebuild_callback'
INSTANCE_LIVE_MIGRATE_CALLBACK = 'nfv_vim_instance_live_migrate_callback'
INSTANCE_COLD_MIGRATE_CALLBACK = 'nfv_vim_instance_cold_migrate_callback'
INSTANCE_COLD_MIGRATE_CONFIRM_CALLBACK = 'nfv_vim_instance_cold_migrate_confirm_callback'
INSTANCE_COLD_MIGRATE_REVERT_CALLBACK = 'nfv_vim_instance_cold_migrate_revert_callback'
INSTANCE_RESIZE_CALLBACK = 'nfv_vim_instance_resize_callback'
INSTANCE_RESIZE_CONFIRM_CALLBACK = 'nfv_vim_instance_resize_confirm_callback'
INSTANCE_RESIZE_REVERT_CALLBACK = 'nfv_vim_instance_resize_revert_callback'
INSTANCE_GUEST_SERVICES_NOTIFY = 'nfv_vim_instance_guest_services_notify'
INSTANCE_GUEST_SERVICES_ENABLE = 'nfv_vim_instance_guest_services_enable'
INSTANCE_GUEST_SERVICES_ENABLE_CALLBACK = 'nfv_vim_instance_guest_services_enable_callback'
INSTANCE_GUEST_SERVICES_DISABLE = 'nfv_vim_instance_guest_services_disable'
INSTANCE_GUEST_SERVICES_DISABLE_CALLBACK = 'nfv_vim_instance_guest_services_disable_callback'
INSTANCE_GUEST_SERVICES_VOTE = 'nfv_vim_instance_guest_services_vote'
INSTANCE_GUEST_SERVICES_VOTE_RESULT = 'nfv_vim_instance_guest_services_vote_result'
INSTANCE_GUEST_SERVICES_VOTE_CALLBACK = 'nfv_vim_instance_guest_services_vote_callback'
INSTANCE_GUEST_SERVICES_PRE_NOTIFY = 'nfv_vim_instance_guest_services_pre_notify'
INSTANCE_GUEST_SERVICES_PRE_NOTIFY_CALLBACK = 'nfv_vim_instance_guest_services_pre_notify_callback'
INSTANCE_GUEST_SERVICES_POST_NOTIFY = 'nfv_vim_instance_guest_services_post_notify'
INSTANCE_GUEST_SERVICES_POST_NOTIFY_CALLBACK = 'nfv_vim_instance_guest_services_post_notify_callback'
INSTANCE_GUEST_SERVICES_POST_NOTIFY_HEARTBEAT = 'nfv_vim_instance_guest_services_post_notify_heartbeat'
HOST_NFVI_STATE_CHANGE = "nfv_vim_host_nfvi_state_change"
HOST_CONFIGURE_STATE = "nfv_vim_host_configure_state"
HOST_ENABLING_STATE = "nfv_vim_host_enabling_state"
HOST_ENABLED_STATE = "nfv_vim_host_enabled_state"
HOST_DISABLING_STATE = "nfv_vim_host_disabling_state"
HOST_DISABLED_STATE = "nfv_vim_host_disabled_state"
HOST_DISABLING_FAILED_STATE = "nfv_vim_host_disabling_failed_state"
HOST_DELETING_STATE = "nfv_vim_host_deleting_state"
HOST_DELETED_STATE = "nfv_vim_host_deleted_state"
INSTANCE_DIRECTOR_EVACUATE_FAILED = "nfv_vim_director_evacuate_failed"
INSTANCE_DIRECTOR_EVACUATE_TIMEOUT = "nfv_vim_director_evacuate_timeout"
INSTANCE_DIRECTOR_EVACUATE_SUCCESS = "nfv_vim_director_evacuate_success"
INSTANCE_DIRECTOR_MIGRATE_FAILED = "nfv_vim_director_migrate_failed"
INSTANCE_DIRECTOR_MIGRATE_TIMEOUT = "nfv_vim_director_migrate_timeout"
INSTANCE_DIRECTOR_MIGRATE_SUCCESS = "nfv_vim_director_migrate_success"
INSTANCE_INITIAL_STATE = "nfv_vim_instance_initial_state"
INSTANCE_LIVE_MIGRATE_STATE = "nfv_vim_instance_live_migrate_state"
INSTANCE_LIVE_MIGRATE_STATE_FAILED = "nfv_vim_instance_live_migrate_state_failed"
INSTANCE_LIVE_MIGRATE_STATE_TIMED_OUT = (
"nfv_vim_instance_live_migrate_state_timed_out"
)
INSTANCE_LIVE_MIGRATE_FINISH_STATE = "nfv_vim_instance_live_migrate_finish_state"
INSTANCE_LIVE_MIGRATE_FINISH_STATE_FAILED = (
"nfv_vim_instance_live_migrate_finish_state_failed"
)
INSTANCE_LIVE_MIGRATE_FINISH_STATE_TIMED_OUT = (
"nfv_vim_instance_live_migrate_finish_state_timed_out"
)
INSTANCE_COLD_MIGRATE_STATE = "nfv_vim_instance_cold_migrate_state"
INSTANCE_COLD_MIGRATE_STATE_FAILED = "nfv_vim_instance_cold_migrate_state_failed"
INSTANCE_COLD_MIGRATE_STATE_TIMED_OUT = (
"nfv_vim_instance_cold_migrate_state_timed_out"
)
INSTANCE_COLD_MIGRATE_CONFIRM_STATE = "nfv_vim_instance_cold_migrate_confirm_state"
INSTANCE_COLD_MIGRATE_CONFIRM_STATE_FAILED = (
"nfv_vim_instance_cold_migrate_confirm_state_failed"
)
INSTANCE_COLD_MIGRATE_CONFIRM_STATE_TIMED_OUT = (
"nfv_vim_instance_cold_migrate_confirm_state_timed_out"
)
INSTANCE_COLD_MIGRATE_REVERT_STATE = "nfv_vim_instance_cold_migrate_revert_state"
INSTANCE_COLD_MIGRATE_REVERT_STATE_FAILED = (
"nfv_vim_instance_cold_migrate_revert_state_failed"
)
INSTANCE_COLD_MIGRATE_REVERT_STATE_TIMED_OUT = (
"nfv_vim_instance_cold_migrate_revert_state_timed_out"
)
INSTANCE_EVACUATE_STATE = "nfv_vim_instance_evacuate_state"
INSTANCE_START_STATE = "nfv_vim_instance_start_state"
INSTANCE_START_STATE_INPROGRESS = "nfv_vim_instance_start_state_inprogress"
INSTANCE_START_STATE_FAILED = "nfv_vim_instance_start_state_failed"
INSTANCE_START_STATE_TIMED_OUT = "nfv_vim_instance_start_state_timed_out"
INSTANCE_STOP_STATE = "nfv_vim_instance_stop_state"
INSTANCE_STOP_STATE_COMPLETED = "nfv_vim_instance_stop_state_completed"
INSTANCE_STOP_STATE_FAILED = "nfv_vim_instance_stop_state_failed"
INSTANCE_STOP_STATE_TIMED_OUT = "nfv_vim_instance_stop_state_timed_out"
INSTANCE_PAUSE_STATE = "nfv_vim_instance_pause_state"
INSTANCE_PAUSE_STATE_COMPLETED = "nfv_vim_instance_pause_state_completed"
INSTANCE_PAUSE_STATE_FAILED = "nfv_vim_instance_pause_state_failed"
INSTANCE_PAUSE_STATE_TIMED_OUT = "nfv_vim_instance_pause_state_timed_out"
INSTANCE_UNPAUSE_STATE = "nfv_vim_instance_unpause_state"
INSTANCE_UNPAUSE_STATE_COMPLETED = "nfv_vim_instance_unpause_state_completed"
INSTANCE_UNPAUSE_STATE_FAILED = "nfv_vim_instance_unpause_state_failed"
INSTANCE_UNPAUSE_STATE_TIMED_OUT = "nfv_vim_instance_unpause_state_timed_out"
INSTANCE_SUSPEND_STATE = "nfv_vim_instance_suspend_state"
INSTANCE_SUSPEND_STATE_COMPLETED = "nfv_vim_instance_suspend_state_completed"
INSTANCE_SUSPEND_STATE_FAILED = "nfv_vim_instance_suspend_state_failed"
INSTANCE_SUSPEND_STATE_TIMED_OUT = "nfv_vim_instance_suspend_state_timed_out"
INSTANCE_RESUME_STATE = "nfv_vim_instance_resume_state"
INSTANCE_RESUME_STATE_COMPLETED = "nfv_vim_instance_resume_state_completed"
INSTANCE_RESUME_STATE_FAILED = "nfv_vim_instance_resume_state_failed"
INSTANCE_RESUME_STATE_TIMED_OUT = "nfv_vim_instance_resume_state_timed_out"
INSTANCE_REBOOT_STATE = "nfv_vim_instance_reboot_state"
INSTANCE_REBOOT_STATE_COMPLETED = "nfv_vim_instance_reboot_state_completed"
INSTANCE_REBOOT_STATE_FAILED = "nfv_vim_instance_reboot_state_failed"
INSTANCE_REBOOT_STATE_TIMED_OUT = "nfv_vim_instance_reboot_state_timed_out"
INSTANCE_REBUILD_STATE = "nfv_vim_instance_rebuild_state"
INSTANCE_REBUILD_STATE_COMPLETED = "nfv_vim_instance_rebuild_state_completed"
INSTANCE_REBUILD_STATE_FAILED = "nfv_vim_instance_rebuild_state_failed"
INSTANCE_REBUILD_STATE_TIMED_OUT = "nfv_vim_instance_rebuild_state_timed_out"
INSTANCE_FAIL_STATE = "nfv_vim_instance_fail_state"
INSTANCE_DELETE_STATE = "nfv_vim_instance_delete_state"
INSTANCE_RESIZE_STATE = "nfv_vim_instance_resize_state"
INSTANCE_RESIZE_STATE_FAILED = "nfv_vim_instance_resize_state_failed"
INSTANCE_RESIZE_STATE_TIMED_OUT = "nfv_vim_instance_resize_state_timed_out"
INSTANCE_RESIZE_CONFIRM_STATE = "nfv_vim_instance_resize_confirm_state"
INSTANCE_RESIZE_CONFIRM_STATE_FAILED = (
"nfv_vim_instance_resize_confirm_state_failed"
)
INSTANCE_RESIZE_CONFIRM_STATE_TIMED_OUT = (
"nfv_vim_instance_resize_confirm_state_timed_out"
)
INSTANCE_RESIZE_REVERT_STATE = "nfv_vim_instance_resize_revert_state"
INSTANCE_RESIZE_REVERT_STATE_FAILED = "nfv_vim_instance_resize_revert_state_failed"
INSTANCE_RESIZE_REVERT_STATE_TIMED_OUT = (
"nfv_vim_instance_resize_revert_state_timed_out"
)
INSTANCE_GUEST_SERVICES_CREATE_STATE = (
"nfv_vim_instance_guest_services_create_state"
)
INSTANCE_GUEST_SERVICES_DELETE_STATE = (
"nfv_vim_instance_guest_services_delete_state"
)
INSTANCE_GUEST_SERVICES_ENABLE_STATE = (
"nfv_vim_instance_guest_services_enable_state"
)
INSTANCE_GUEST_SERVICES_DISABLE_STATE = (
"nfv_vim_instance_guest_services_disable_state"
)
INSTANCE_GUEST_SERVICES_SET_STATE = "nfv_vim_instance_guest_services_set_state"
INSTANCE_NFVI_ACTION_START = "nfv_vim_instance_nfvi_action_initial"
INSTANCE_NFVI_STATE_CHANGE = "nfv_vim_instance_nfvi_state_change"
INSTANCE_START_CALLBACK = "nfv_vim_instance_start_callback"
INSTANCE_STOP_CALLBACK = "nfv_vim_instance_stop_callback"
INSTANCE_PAUSE_CALLBACK = "nfv_vim_instance_pause_callback"
INSTANCE_UNPAUSE_CALLBACK = "nfv_vim_instance_unpause_callback"
INSTANCE_SUSPEND_CALLBACK = "nfv_vim_instance_suspend_callback"
INSTANCE_RESUME_CALLBACK = "nfv_vim_instance_resume_callback"
INSTANCE_REBOOT_CALLBACK = "nfv_vim_instance_reboot_callback"
INSTANCE_REBUILD_CALLBACK = "nfv_vim_instance_rebuild_callback"
INSTANCE_LIVE_MIGRATE_CALLBACK = "nfv_vim_instance_live_migrate_callback"
INSTANCE_COLD_MIGRATE_CALLBACK = "nfv_vim_instance_cold_migrate_callback"
INSTANCE_COLD_MIGRATE_CONFIRM_CALLBACK = (
"nfv_vim_instance_cold_migrate_confirm_callback"
)
INSTANCE_COLD_MIGRATE_REVERT_CALLBACK = (
"nfv_vim_instance_cold_migrate_revert_callback"
)
INSTANCE_RESIZE_CALLBACK = "nfv_vim_instance_resize_callback"
INSTANCE_RESIZE_CONFIRM_CALLBACK = "nfv_vim_instance_resize_confirm_callback"
INSTANCE_RESIZE_REVERT_CALLBACK = "nfv_vim_instance_resize_revert_callback"
INSTANCE_GUEST_SERVICES_NOTIFY = "nfv_vim_instance_guest_services_notify"
INSTANCE_GUEST_SERVICES_ENABLE = "nfv_vim_instance_guest_services_enable"
INSTANCE_GUEST_SERVICES_ENABLE_CALLBACK = (
"nfv_vim_instance_guest_services_enable_callback"
)
INSTANCE_GUEST_SERVICES_DISABLE = "nfv_vim_instance_guest_services_disable"
INSTANCE_GUEST_SERVICES_DISABLE_CALLBACK = (
"nfv_vim_instance_guest_services_disable_callback"
)
INSTANCE_GUEST_SERVICES_VOTE = "nfv_vim_instance_guest_services_vote"
INSTANCE_GUEST_SERVICES_VOTE_RESULT = "nfv_vim_instance_guest_services_vote_result"
INSTANCE_GUEST_SERVICES_VOTE_CALLBACK = (
"nfv_vim_instance_guest_services_vote_callback"
)
INSTANCE_GUEST_SERVICES_PRE_NOTIFY = "nfv_vim_instance_guest_services_pre_notify"
INSTANCE_GUEST_SERVICES_PRE_NOTIFY_CALLBACK = (
"nfv_vim_instance_guest_services_pre_notify_callback"
)
INSTANCE_GUEST_SERVICES_POST_NOTIFY = "nfv_vim_instance_guest_services_post_notify"
INSTANCE_GUEST_SERVICES_POST_NOTIFY_CALLBACK = (
"nfv_vim_instance_guest_services_post_notify_callback"
)
INSTANCE_GUEST_SERVICES_POST_NOTIFY_HEARTBEAT = (
"nfv_vim_instance_guest_services_post_notify_heartbeat"
)
# Constant Instantiation
@@ -1,12 +1,12 @@
#
# Copyright (c) 2015-2016 Wind River Systems, Inc.
# Copyright (c) 2015-2016, 2026 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
from nfv_common import debug
from nfv_common.forensic import _parsers
DLOG = debug.debug_get_logger('forensic-evidence')
DLOG = debug.debug_get_logger("forensic-evidence")
def evidence_from_files(files, start_date, end_date, progress=None):
@@ -48,7 +48,7 @@ def evidence_from_files(files, start_date, end_date, progress=None):
earliest = (file_name, parser_name, f, record)
else:
_, _, _, earliest_record = earliest
if earliest_record['timestamp'] > record['timestamp']:
if earliest_record["timestamp"] > record["timestamp"]:
earliest = (file_name, parser_name, f, record)
if earliest is not None:
@@ -1,5 +1,5 @@
#
# Copyright (c) 2015-2016 Wind River Systems, Inc.
# Copyright (c) 2015-2016, 2026 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
@@ -21,51 +21,67 @@ class NfvVimParser(object):
"""
NFV-VIM Parser
"""
def __init__(self, config_data):
self._config_data = config_data
year = Word(nums)
month = Suppress('-') + Word(nums)
day = Suppress('-') + Word(nums)
month = Suppress("-") + Word(nums)
day = Suppress("-") + Word(nums)
hour = Suppress('T') + Word(nums)
minute = Suppress(':') + Word(nums)
second = Suppress(':') + Word(nums)
millisecond = Suppress('.') + Word(nums)
hour = Suppress("T") + Word(nums)
minute = Suppress(":") + Word(nums)
second = Suppress(":") + Word(nums)
millisecond = Suppress(".") + Word(nums)
hostname = Word(alphas + nums + '_' + '-' + '.')
hostname = Word(alphas + nums + "_" + "-" + ".")
pid = (Suppress(Word(alphas + '_' + alphas + '-' + '[')) + Word(nums) +
Suppress(']'))
pid = (
Suppress(Word(alphas + "_" + alphas + "-" + "["))
+ Word(nums)
+ Suppress("]")
)
ignore = Suppress(Word(alphas))
filename = Combine(Word(alphas + '_') + Literal(".py"))
filename = Combine(Word(alphas + "_") + Literal(".py"))
lineno = Suppress('.') + Word(nums)
lineno = Suppress(".") + Word(nums)
message = Regex(".*")
self.__pattern = (year + month + day + hour + minute + second +
millisecond + hostname + pid + ignore + filename +
lineno + message)
self.__pattern = (
year
+ month
+ day
+ hour
+ minute
+ second
+ millisecond
+ hostname
+ pid
+ ignore
+ filename
+ lineno
+ message
)
def parse_message(self, filename, lineno, message):
for log in self._config_data['logs']:
if log.get('file', None) is not None:
if filename != log['file']:
for log in self._config_data["logs"]:
if log.get("file", None) is not None:
if filename != log["file"]:
continue
if log.get('lineno', None) is not None:
if lineno != str(log['lineno']):
if log.get("lineno", None) is not None:
if lineno != str(log["lineno"]):
continue
query_obj = re.match(log['regex'], message)
query_obj = re.match(log["regex"], message)
if query_obj is not None:
message_data = dict()
message_data['type'] = log['type']
message_data['log'] = message
for idx, field_name in enumerate(log['fields'], 1):
message_data["type"] = log["type"]
message_data["log"] = message
for idx, field_name in enumerate(log["fields"], 1):
message_data[field_name] = query_obj.group(idx)
return message_data
return None
@@ -78,22 +94,26 @@ class NfvVimParser(object):
if 70 < len(line):
parsed = self.__pattern.parseString(line)
timestamp = datetime.datetime(int(parsed[0]), int(parsed[1]),
int(parsed[2]), int(parsed[3]),
int(parsed[4]), int(parsed[5]),
int(parsed[6]) * 1000)
timestamp = datetime.datetime(
int(parsed[0]),
int(parsed[1]),
int(parsed[2]),
int(parsed[3]),
int(parsed[4]),
int(parsed[5]),
int(parsed[6]) * 1000,
)
if start_date <= timestamp <= end_date:
message_data = self.parse_message(parsed[9], parsed[10],
parsed[11])
message_data = self.parse_message(parsed[9], parsed[10], parsed[11])
if message_data is not None:
record = dict()
record['timestamp'] = timestamp
record['hostname'] = parsed[7]
record['pid'] = parsed[8]
record['filename'] = parsed[9]
record['lineno'] = parsed[10]
record['data'] = message_data
record["timestamp"] = timestamp
record["hostname"] = parsed[7]
record["pid"] = parsed[8]
record["filename"] = parsed[9]
record["lineno"] = parsed[10]
record["data"] = message_data
except Exception as e:
print("Bad line: %s, exception=%s." % (line, e))
@@ -1,4 +1,4 @@
# Copyright (c) 2015-2016 Wind River Systems, Inc.
# Copyright (c) 2015-2016, 2026 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
@@ -20,7 +20,7 @@ def parser_initialize():
"""
global _parsers
_parsers['nfv-vim'] = _nfv_vim_parser.parser_initialize()
_parsers["nfv-vim"] = _nfv_vim_parser.parser_initialize()
def parser_finalize():
+20 -11
View File
@@ -1,5 +1,5 @@
#
# Copyright (c) 2015-2016 Wind River Systems, Inc.
# Copyright (c) 2015-2016, 2026 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
@@ -11,7 +11,7 @@ import socket
def syscall_retry_on_interrupt(func, *args):
"""Attempt system call again if interrupted by EINTR """
"""Attempt system call again if interrupted by EINTR"""
for _ in range(0, 5):
try:
return func(*args)
@@ -22,7 +22,7 @@ def syscall_retry_on_interrupt(func, *args):
def local_uptime_in_secs():
try:
with open('/proc/uptime', 'r') as f:
with open("/proc/uptime", "r") as f:
uptime_secs = int(float(f.readline().split()[0]))
except IOError:
uptime_secs = 0
@@ -40,6 +40,7 @@ class Object(object):
"""
Class Object Type Definition
"""
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
@@ -51,13 +52,16 @@ class Result(object):
"""
Generic Result Object Type Definition
"""
def __init__(self, result_data, ancillary_data=None):
self.result_data = result_data
self.ancillary_data = ancillary_data
def __str__(self):
return ("Result: result-data: %s ancillary-data: %s"
% (self.result_data, self.ancillary_data))
return "Result: result-data: %s ancillary-data: %s" % (
self.result_data,
self.ancillary_data,
)
class Constants(object):
@@ -72,6 +76,7 @@ class Constant(object):
"""
Constant Type Definition
"""
def __init__(self, value):
self.value = value
@@ -89,12 +94,12 @@ class Singleton(type):
"""
Singleton Type Definition
"""
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = \
super(Singleton, cls).__call__(*args, **kwargs)
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
@@ -102,11 +107,13 @@ def coroutine(func):
"""
Co-Routine decorator that wraps a function and starts the co-routine
"""
def start(*args, **kwargs):
target = func(*args, **kwargs)
target.send(None)
functools.update_wrapper(start, func)
return target
return start
@@ -121,10 +128,12 @@ def get_system_ca_file():
"""Return path to system default CA file."""
# Standard CA file locations for Debian/Ubuntu, RedHat/Fedora,
# Suse, FreeBSD/OpenBSD
ca_path = ['/etc/ssl/certs/ca-certificates.crt',
'/etc/pki/tls/certs/ca-bundle.crt',
'/etc/ssl/ca-bundle.pem',
'/etc/ssl/cert.pem']
ca_path = [
"/etc/ssl/certs/ca-certificates.crt",
"/etc/pki/tls/certs/ca-bundle.crt",
"/etc/ssl/ca-bundle.pem",
"/etc/ssl/cert.pem",
]
for ca in ca_path:
if os.path.exists(ca):
return ca
+31 -17
View File
@@ -1,5 +1,5 @@
#
# Copyright (c) 2015-2016 Wind River Systems, Inc.
# Copyright (c) 2015-2016, 2026 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
@@ -9,13 +9,14 @@ import math
from nfv_common import debug
DLOG = debug.debug_get_logger('nfv_common.histogram')
DLOG = debug.debug_get_logger("nfv_common.histogram")
class Histogram(object):
"""
Histogram Object
"""
def __init__(self, name, num_buckets, units):
self._name = name
self._units = units
@@ -55,7 +56,7 @@ class Histogram(object):
self._sample_total += sample_as_int
self._num_samples += 1
self._average_sample = (self._sample_total // self._num_samples)
self._average_sample = self._sample_total // self._num_samples
self._buckets[bucket_idx] += 1
@@ -83,8 +84,10 @@ class Histogram(object):
if sample_min == sample_max:
return sample
return ((((scale_max - scale_min) * (sample - sample_min)) //
(sample_max - sample_min)) + sample_max)
return (
((scale_max - scale_min) * (sample - sample_min))
// (sample_max - sample_min)
) + sample_max
def display_data(self, pretty_format=True):
"""
@@ -104,10 +107,12 @@ class Histogram(object):
values_str += " avg: %s" % self._average_sample
if self._max_sample_date is not None:
values_str += (" max: %s (%s)" % (self._max_sample,
self._max_sample_date))
values_str += " max: %s (%s)" % (
self._max_sample,
self._max_sample_date,
)
DLOG.info("%s" % '-' * 120)
DLOG.info("%s" % "-" * 120)
DLOG.info("Histogram: %s" % self._name)
@@ -120,19 +125,28 @@ class Histogram(object):
for idx, bucket_value in enumerate(self._buckets):
if 0 != bucket_value:
if pretty_format:
scaled_bucket_value \
= self._scale_sample(0, 60, 0, self._max_sample,
bucket_value)
scaled_bucket_value = self._scale_sample(
0, 60, 0, self._max_sample, bucket_value
)
DLOG.info(" %03i [up to %03i %s]: %07i %s"
% (idx, math.pow(2, idx), self._units, bucket_value,
'*' * min(60, scaled_bucket_value)))
DLOG.info(
" %03i [up to %03i %s]: %07i %s"
% (
idx,
math.pow(2, idx),
self._units,
bucket_value,
"*" * min(60, scaled_bucket_value),
)
)
else:
DLOG.info(" %03i [up to %03i %s]: %07i"
% (idx, math.pow(2, idx), self._units, bucket_value))
DLOG.info(
" %03i [up to %03i %s]: %07i"
% (idx, math.pow(2, idx), self._units, bucket_value)
)
if pretty_format:
DLOG.info("%s" % '-' * 120)
DLOG.info("%s" % "-" * 120)
_histograms = dict()
+12 -9
View File
@@ -1,15 +1,16 @@
#
# Copyright (c) 2015-2016 Wind River Systems, Inc.
# Copyright (c) 2015-2016, 2026 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
from nfv_common import debug
DLOG = debug.debug_get_logger('nfv_common.profiler')
DLOG = debug.debug_get_logger("nfv_common.profiler")
try:
import guppy
import objgraph
memory_profiling = guppy.hpy()
except ImportError:
@@ -22,10 +23,12 @@ def profile_memory_references(obj_type, obj_name):
"""
if memory_profiling is not None:
objs = objgraph.by_type(obj_type)
objgraph.show_backrefs(objs, max_depth=5,
filename='/tmp/%s_memory_back_refs.dot' % obj_name)
objgraph.show_refs(objs, max_depth=5,
filename='/tmp/%s_memory_refs.dot' % obj_name)
objgraph.show_backrefs(
objs, max_depth=5, filename="/tmp/%s_memory_back_refs.dot" % obj_name
)
objgraph.show_refs(
objs, max_depth=5, filename="/tmp/%s_memory_refs.dot" % obj_name
)
def profile_memory_set_reference():
@@ -41,10 +44,10 @@ def profile_memory_dump():
Dumps the current memory usage
"""
if memory_profiling is not None:
DLOG.info("%s" % '-' * 120)
DLOG.info("%s" % "-" * 120)
DLOG.info("Memory Profile: %s" % memory_profiling.heap())
profile_memory_references('nfv_vim.objects._instance.Instance', 'instance')
DLOG.info("%s" % '-' * 120)
profile_memory_references("nfv_vim.objects._instance.Instance", "instance")
DLOG.info("%s" % "-" * 120)
def profiler_initialize():
@@ -13,7 +13,7 @@ _send_socket = None
_receive_socket = None
_pending_function_calls = list()
MESSAGE_ONE = b'1'
MESSAGE_ONE = b"1"
def schedule_function_call(func, *args, **kwargs):
@@ -32,7 +32,7 @@ def _schedule_dispatch():
global _receive_socket, _pending_function_calls
while True:
select_obj = (yield)
select_obj = yield
if select_obj == _receive_socket.fileno():
_receive_socket.recv(1)
@@ -1,5 +1,5 @@
#
# Copyright (c) 2015-2016 Wind River Systems, Inc.
# Copyright (c) 2015-2016, 2026 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
@@ -9,7 +9,7 @@ import socket
from nfv_common import debug
DLOG = debug.debug_get_logger('nfv_common.selobj')
DLOG = debug.debug_get_logger("nfv_common.selobj")
_read_callbacks = dict()
_write_callbacks = dict()
@@ -58,8 +58,7 @@ def selobj_del_write_obj(selobj):
_write_callbacks.pop(selobj)
def selobj_add_error_callback(selobj, callback, *callback_args,
**callback_kwargs):
def selobj_add_error_callback(selobj, callback, *callback_args, **callback_kwargs):
"""
Add selection object error callback which is a co-routine that is
called when the selection object is in error
@@ -94,8 +93,9 @@ def selobj_dispatch(timeout_in_ms):
write_objs = list(_write_callbacks)
try:
readable, writeable, in_error = select.select(read_objs, write_objs, [],
timeout_in_ms / 1000.0)
readable, writeable, in_error = select.select(
read_objs, write_objs, [], timeout_in_ms / 1000.0
)
for selobj in readable:
callback = _read_callbacks.get(selobj, None)
@@ -106,8 +106,9 @@ def selobj_dispatch(timeout_in_ms):
except (StopIteration, RuntimeError):
_read_callbacks.pop(selobj)
elapsed_ms = timers.get_monotonic_timestamp_in_ms() - start_ms
histogram.add_histogram_data("selobj read: " + callback.__name__,
elapsed_ms // 100, "decisecond")
histogram.add_histogram_data(
"selobj read: " + callback.__name__, elapsed_ms // 100, "decisecond"
)
for selobj in writeable:
callback = _write_callbacks.get(selobj, None)
@@ -118,8 +119,11 @@ def selobj_dispatch(timeout_in_ms):
except (StopIteration, RuntimeError):
_write_callbacks.pop(selobj)
elapsed_ms = timers.get_monotonic_timestamp_in_ms() - start_ms
histogram.add_histogram_data("selobj write: " + callback.__name__,
elapsed_ms // 100, "decisecond")
histogram.add_histogram_data(
"selobj write: " + callback.__name__,
elapsed_ms // 100,
"decisecond",
)
for selobj in in_error:
callback = _error_callbacks.get(selobj, None)
@@ -130,8 +134,11 @@ def selobj_dispatch(timeout_in_ms):
except (StopIteration, RuntimeError):
_error_callbacks.pop(selobj)
elapsed_ms = timers.get_monotonic_timestamp_in_ms() - start_ms
histogram.add_histogram_data("selobj error: " + callback.__name__,
elapsed_ms // 100, "decisecond")
histogram.add_histogram_data(
"selobj error: " + callback.__name__,
elapsed_ms // 100,
"decisecond",
)
if selobj in list(_read_callbacks):
_read_callbacks.pop(selobj)
@@ -1,13 +1,18 @@
#
# Copyright (c) 2015-2016 Wind River Systems, Inc.
# Copyright (c) 2015-2016, 2026 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
from nfv_common.state_machine._state import State # noqa: F401
from nfv_common.state_machine._state_exception import StateException # noqa: F401
from nfv_common.state_machine._state_machine import StateMachine # noqa: F401
from nfv_common.state_machine._state_task import StateTask # noqa: F401
from nfv_common.state_machine._state_task_result import STATE_TASK_RESULT # noqa: F401
from nfv_common.state_machine._state_task_result import state_task_result_update # noqa: F401
from nfv_common.state_machine._state_task_work import StateTaskWork # noqa: F401
from nfv_common.state_machine._state_task_work_result import STATE_TASK_WORK_RESULT # noqa: F401
# flake8: noqa
from nfv_common.state_machine._state import State
from nfv_common.state_machine._state_exception import StateException
from nfv_common.state_machine._state_machine import StateMachine
from nfv_common.state_machine._state_task import StateTask
from nfv_common.state_machine._state_task_result import STATE_TASK_RESULT
from nfv_common.state_machine._state_task_result import (
state_task_result_update,
)
from nfv_common.state_machine._state_task_work import StateTaskWork
from nfv_common.state_machine._state_task_work_result import (
STATE_TASK_WORK_RESULT,
)
@@ -1,17 +1,18 @@
#
# Copyright (c) 2015-2016 Wind River Systems, Inc.
# Copyright (c) 2015-2016, 2026 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
from nfv_common import debug
DLOG = debug.debug_get_logger('nfv_common.state_machine.state')
DLOG = debug.debug_get_logger("nfv_common.state_machine.state")
class State(object):
"""
State Object
"""
def __init__(self, name):
"""
Create State
@@ -1,17 +1,18 @@
#
# Copyright (c) 2015-2016 Wind River Systems, Inc.
# Copyright (c) 2015-2016, 2026 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
from nfv_common import debug
DLOG = debug.debug_get_logger('nfv_common.state_machine.state_exception')
DLOG = debug.debug_get_logger("nfv_common.state_machine.state_exception")
class StateException(Exception):
"""
State Exception
"""
def __init__(self, message, reason):
"""
Create a State exception
@@ -1,5 +1,5 @@
#
# Copyright (c) 2015-2016 Wind River Systems, Inc.
# Copyright (c) 2015-2016, 2026 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
@@ -9,15 +9,15 @@ from nfv_common import debug
from nfv_common.state_machine._state_exception import StateException
DLOG = debug.debug_get_logger('nfv_common.state_machine.state_machine')
DLOG = debug.debug_get_logger("nfv_common.state_machine.state_machine")
class StateMachine(object):
"""
State Machine Object
"""
def __init__(self, context, context_args, context_kwargs, initial_state,
states):
def __init__(self, context, context_args, context_kwargs, initial_state, states):
"""
Create State Machine
"""
@@ -64,21 +64,23 @@ class StateMachine(object):
Handle event
"""
if self._transitioning:
self._event_backlog.append((self._event_backlog_state, event,
event_data))
self._event_backlog.append((self._event_backlog_state, event, event_data))
return
try:
prev_state = self._current_state
next_state_name = self._current_state.handle_event(
self._context, event, event_data)
self._context, event, event_data
)
next_state = self._states[next_state_name]
if prev_state != self._current_state:
# Nested handle event calls, we have already moved away
DLOG.verbose("Nested handle event calls detected, "
"prev_state=%s, current_state=%s."
% (prev_state.name, self.current_state.name))
DLOG.verbose(
"Nested handle event calls detected, "
"prev_state=%s, current_state=%s."
% (prev_state.name, self.current_state.name)
)
return
if next_state_name != prev_state.name:
@@ -87,30 +89,34 @@ class StateMachine(object):
prev_state.exit(self._context)
except StateException as e:
DLOG.error("Caught exception while trying to exit state "
"(%s), event=%s, error=%s."
% (prev_state, event, e))
DLOG.error(
"Caught exception while trying to exit state "
"(%s), event=%s, error=%s." % (prev_state, event, e)
)
return
# Attempt to transition from the current state
try:
prev_state.transition(self._context, event, event_data,
next_state)
prev_state.transition(self._context, event, event_data, next_state)
except StateException as e:
DLOG.error("Caught exception while trying to transition "
"from state (%s) to state (%s), event=%s, "
"error=%s." % (prev_state, next_state, event, e))
prev_state.enter(self._context, *self._context_args,
**self._context_kwargs)
DLOG.error(
"Caught exception while trying to transition "
"from state (%s) to state (%s), event=%s, "
"error=%s." % (prev_state, next_state, event, e)
)
prev_state.enter(
self._context, *self._context_args, **self._context_kwargs
)
return
# Attempt to enter the next state
try:
self._transitioning = True
self._event_backlog_state = next_state
next_state.enter(self._context, *self._context_args,
**self._context_kwargs)
next_state.enter(
self._context, *self._context_args, **self._context_kwargs
)
self._current_state = next_state
for callback in self._state_change_callbacks:
@@ -124,32 +130,39 @@ class StateMachine(object):
for event_state, event, event_data in event_backlog:
if event_state != self._current_state:
DLOG.info("Ignoring event %s, no longer in state "
"%s, now in state %s."
% (event, event_state,
self._current_state))
DLOG.info(
"Ignoring event %s, no longer in state "
"%s, now in state %s."
% (event, event_state, self._current_state)
)
else:
DLOG.info("Handling event backlog, event=%s while "
"transitioning to state %s."
% (event, self._current_state))
DLOG.info(
"Handling event backlog, event=%s while "
"transitioning to state %s."
% (event, self._current_state)
)
self.handle_event(event, event_data)
del event_backlog[:]
except StateException as e:
DLOG.error("Caught exception while trying to enter state "
"(%s) from state (%s), event=%s, error=%s."
% (next_state, prev_state, event, e))
DLOG.error(
"Caught exception while trying to enter state "
"(%s) from state (%s), event=%s, error=%s."
% (next_state, prev_state, event, e)
)
self._transitioning = False
self._event_backlog_state = None
del self._event_backlog[:]
prev_state.transition(self._context, event, event_data,
prev_state)
prev_state.enter(self._context, *self._context_args,
**self._context_kwargs)
prev_state.transition(self._context, event, event_data, prev_state)
prev_state.enter(
self._context, *self._context_args, **self._context_kwargs
)
return
except StateException as e:
DLOG.error("Caught exception while trying to handle event (%s), "
"error=%s." % (event, e))
DLOG.error(
"Caught exception while trying to handle event (%s), "
"error=%s." % (event, e)
)
return
@@ -1,5 +1,5 @@
#
# Copyright (c) 2015-2016 Wind River Systems, Inc.
# Copyright (c) 2015-2016, 2026 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
@@ -11,15 +11,15 @@ from nfv_common.state_machine._state_task_result import STATE_TASK_RESULT
from nfv_common.state_machine._state_task_result import state_task_result_update
from nfv_common.state_machine._state_task_work_result import STATE_TASK_WORK_RESULT
DLOG = debug.debug_get_logger('nfv_common.state_machine.state_task')
DLOG = debug.debug_get_logger("nfv_common.state_machine.state_task")
RESULT_LOG_LEVELS = {
STATE_TASK_RESULT.SUCCESS: DLOG.debug,
STATE_TASK_RESULT.FAILED: DLOG.error,
STATE_TASK_RESULT.TIMED_OUT: DLOG.error,
STATE_TASK_RESULT.ABORTED: DLOG.notice,
STATE_TASK_RESULT.DEGRADED: DLOG.warn,
STATE_TASK_RESULT.SUCCESS: DLOG.debug,
STATE_TASK_RESULT.FAILED: DLOG.error,
STATE_TASK_RESULT.TIMED_OUT: DLOG.error,
STATE_TASK_RESULT.ABORTED: DLOG.notice,
STATE_TASK_RESULT.DEGRADED: DLOG.warn,
}
@@ -32,13 +32,14 @@ class StateTask(object):
"""
State Task
"""
def __init__(self, name, task_work_list):
self._name = name
self._current_task_work = 0
self._task_work_timer_id = None
self._task_work_list = task_work_list
self._task_result = STATE_TASK_RESULT.SUCCESS
self._task_result_reason = ''
self._task_result_reason = ""
self._timer_id = None
self._timeout_in_secs = 0
for task_work in task_work_list:
@@ -79,8 +80,9 @@ class StateTask(object):
for idx in range(self._current_task_work, -1, -1):
task_work = self._task_work_list[idx]
task_work.abort()
DLOG.debug("Task (%s) aborted work (%s)."
% (self._name, task_work.name))
DLOG.debug(
"Task (%s) aborted work (%s)." % (self._name, task_work.name)
)
self._current_task_work = 0
self._task_inprogress = False
self._cleanup()
@@ -90,7 +92,7 @@ class StateTask(object):
State Task Abort
"""
self._task_result = STATE_TASK_RESULT.ABORTED
self._task_result_reason = 'aborted'
self._task_result_reason = "aborted"
self._abort()
def start(self):
@@ -101,11 +103,10 @@ class StateTask(object):
self._current_task_work = 0
self._task_inprogress = True
self._task_result = STATE_TASK_RESULT.SUCCESS
self._task_result_reason = 'success'
self._timer_id = timers.timers_create_timer(self._name,
self._timeout_in_secs,
self._timeout_in_secs,
self._timeout)
self._task_result_reason = "success"
self._timer_id = timers.timers_create_timer(
self._name, self._timeout_in_secs, self._timeout_in_secs, self._timeout
)
self._run()
def refresh_timeouts(self):
@@ -127,10 +128,9 @@ class StateTask(object):
self._timeout_in_secs += 1
# Re-start task timer
self._timer_id = timers.timers_create_timer(self._name,
self._timeout_in_secs,
self._timeout_in_secs,
self._timeout)
self._timer_id = timers.timers_create_timer(
self._name, self._timeout_in_secs, self._timeout_in_secs, self._timeout
)
if self._task_work_timer_id is None:
# No need to refresh task work timer, no task work running
@@ -147,8 +147,11 @@ class StateTask(object):
task_work = self._task_work_list[self._current_task_work]
if 0 < task_work.timeout_in_secs:
self._task_work_timer_id = timers.timers_create_timer(
task_work.name, task_work.timeout_in_secs,
task_work.timeout_in_secs, self._task_work_timeout)
task_work.name,
task_work.timeout_in_secs,
task_work.timeout_in_secs,
self._task_work_timeout,
)
def _run(self):
"""
@@ -164,8 +167,7 @@ class StateTask(object):
timers.timers_delete_timer(self._task_work_timer_id)
self._task_work_timer_id = None
DLOG.debug("Task %s running %s work." % (self._name,
task_work.name))
DLOG.debug("Task %s running %s work." % (self._name, task_work.name))
task_work_result, task_work_result_reason = task_work.run()
self._current_task_work = idx
@@ -173,22 +175,31 @@ class StateTask(object):
if STATE_TASK_WORK_RESULT.WAIT == task_work_result:
if 0 < task_work.timeout_in_secs:
self._task_work_timer_id = timers.timers_create_timer(
task_work.name, task_work.timeout_in_secs,
task_work.timeout_in_secs, self._task_work_timeout)
task_work.name,
task_work.timeout_in_secs,
task_work.timeout_in_secs,
self._task_work_timeout,
)
DLOG.debug("Task (%s) is waiting for work (%s) to complete, "
"timeout_in_secs=%s." % (self._name, task_work.name,
task_work.timeout_in_secs))
DLOG.debug(
"Task (%s) is waiting for work (%s) to complete, "
"timeout_in_secs=%s."
% (self._name, task_work.name, task_work.timeout_in_secs)
)
break
else:
self._task_result, self._task_result_reason = \
state_task_result_update(
self._task_result, self._task_result_reason,
task_work_result, task_work_result_reason)
self._task_result, self._task_result_reason = state_task_result_update(
self._task_result,
self._task_result_reason,
task_work_result,
task_work_result_reason,
)
if STATE_TASK_RESULT.FAILED == self._task_result \
or STATE_TASK_RESULT.ABORTED == self._task_result \
or STATE_TASK_RESULT.TIMED_OUT == self._task_result:
if (
STATE_TASK_RESULT.FAILED == self._task_result
or STATE_TASK_RESULT.ABORTED == self._task_result
or STATE_TASK_RESULT.TIMED_OUT == self._task_result
):
self._abort()
self._complete(self._task_result, self._task_result_reason)
break
@@ -228,11 +239,13 @@ class StateTask(object):
State Task Timeout
"""
(yield)
DLOG.debug("Task (%s) timed out, timeout_in_secs=%s."
% (self._name, self._timeout_in_secs))
DLOG.debug(
"Task (%s) timed out, timeout_in_secs=%s."
% (self._name, self._timeout_in_secs)
)
self._abort()
self._task_result = STATE_TASK_RESULT.TIMED_OUT
self._task_result_reason = 'timeout'
self._task_result_reason = "timeout"
self._complete(self._task_result, self._task_result_reason)
def task_work_complete(self, task_work_result, task_work_result_reason=None):
@@ -240,30 +253,43 @@ class StateTask(object):
State Task Work Complete
"""
task_work = self._task_work_list[self._current_task_work]
result_log(task_work_result,
"Task (%s) work (%s) complete, result=%s, reason=%s."
% (self._name, task_work.name, task_work_result,
task_work_result_reason))
result_log(
task_work_result,
"Task (%s) work (%s) complete, result=%s, reason=%s."
% (self._name, task_work.name, task_work_result, task_work_result_reason),
)
updated_task_work_result, updated_task_work_result_reason = \
task_work.complete(task_work_result, task_work_result_reason)
updated_task_work_result, updated_task_work_result_reason = task_work.complete(
task_work_result, task_work_result_reason
)
if task_work_result != updated_task_work_result:
result_log(updated_task_work_result,
"Task (%s) work (%s) complete, result updated, "
"was_result=%s, now_result=%s."
% (self._name, task_work.name, task_work_result,
updated_task_work_result))
result_log(
updated_task_work_result,
"Task (%s) work (%s) complete, result updated, "
"was_result=%s, now_result=%s."
% (
self._name,
task_work.name,
task_work_result,
updated_task_work_result,
),
)
task_work_result = updated_task_work_result
task_work_result_reason = updated_task_work_result_reason
self._task_result, self._task_result_reason = \
state_task_result_update(self._task_result, self._task_result_reason,
task_work_result, task_work_result_reason)
self._task_result, self._task_result_reason = state_task_result_update(
self._task_result,
self._task_result_reason,
task_work_result,
task_work_result_reason,
)
if STATE_TASK_RESULT.FAILED == self._task_result \
or STATE_TASK_RESULT.ABORTED == self._task_result \
or STATE_TASK_RESULT.TIMED_OUT == self._task_result:
if (
STATE_TASK_RESULT.FAILED == self._task_result
or STATE_TASK_RESULT.ABORTED == self._task_result
or STATE_TASK_RESULT.TIMED_OUT == self._task_result
):
self._abort()
self._complete(self._task_result, self._task_result_reason)
else:
@@ -277,14 +303,17 @@ class StateTask(object):
"""
(yield)
if len(self._task_work_list) <= self._current_task_work:
DLOG.error("Task work timeout timer fired, but current task "
"work is invalid, current_task_work=%i."
% self._current_task_work)
DLOG.error(
"Task work timeout timer fired, but current task "
"work is invalid, current_task_work=%i." % self._current_task_work
)
return
task_work = self._task_work_list[self._current_task_work]
DLOG.debug("Task (%s) work (%s) timed out, timeout_in_secs=%s."
% (self._name, task_work.name, task_work.timeout_in_secs))
DLOG.debug(
"Task (%s) work (%s) timed out, timeout_in_secs=%s."
% (self._name, task_work.name, task_work.timeout_in_secs)
)
task_work_result, task_work_result_reason = task_work.timeout()
if STATE_TASK_WORK_RESULT.TIMED_OUT == task_work_result:
@@ -14,15 +14,17 @@ class _StateTaskResult(object, metaclass=Singleton):
"""
State Task Result - Constants
"""
SUCCESS = Constant('success')
FAILED = Constant('failed')
DEGRADED = Constant('degraded')
ABORTED = Constant('aborted')
TIMED_OUT = Constant('timed-out')
SUCCESS = Constant("success")
FAILED = Constant("failed")
DEGRADED = Constant("degraded")
ABORTED = Constant("aborted")
TIMED_OUT = Constant("timed-out")
def state_task_result_update(task_result, task_result_reason, task_work_result,
task_work_result_reason):
def state_task_result_update(
task_result, task_result_reason, task_work_result, task_work_result_reason
):
"""
Update State Task Result given a state task work result
"""
@@ -1,5 +1,5 @@
#
# Copyright (c) 2015-2016 Wind River Systems, Inc.
# Copyright (c) 2015-2016, 2026 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
@@ -9,15 +9,15 @@ from nfv_common import debug
from nfv_common.state_machine._state_task_result import STATE_TASK_WORK_RESULT
DLOG = debug.debug_get_logger('nfv_common.state_machine.state_task_work')
DLOG = debug.debug_get_logger("nfv_common.state_machine.state_task_work")
class StateTaskWork(object):
"""
State Task Work
"""
def __init__(self, name, task, force_pass=False, timeout_in_secs=1,
max_retries=1):
def __init__(self, name, task, force_pass=False, timeout_in_secs=1, max_retries=1):
self._name = name
self._force_pass = force_pass
self._max_retries = max_retries
@@ -61,8 +61,10 @@ class StateTaskWork(object):
"""
Allow the task work timeout to be extended
"""
DLOG.verbose("Extending state task work timeout for %s to %s."
% (self._name, timeout_in_secs))
DLOG.verbose(
"Extending state task work timeout for %s to %s."
% (self._name, timeout_in_secs)
)
self._timeout_in_secs = timeout_in_secs
self.task.refresh_timeouts()
@@ -71,14 +73,16 @@ class StateTaskWork(object):
State Task Work Run (expected to be overridden by child class)
"""
DLOG.verbose("Default state task work run for %s." % self._name)
return STATE_TASK_WORK_RESULT.SUCCESS, ''
return STATE_TASK_WORK_RESULT.SUCCESS, ""
def complete(self, result, reason):
"""
State Task Work Completed (can be overridden by child class)
"""
DLOG.verbose("Default state task work complete for %s, result=%s, "
"reason=%s." % (self._name, result, reason))
DLOG.verbose(
"Default state task work complete for %s, result=%s, "
"reason=%s." % (self._name, result, reason)
)
return result, reason
def abort(self):
@@ -91,14 +95,15 @@ class StateTaskWork(object):
"""
State Task Work Timeout (can be overridden by child class)
"""
DLOG.verbose("Default state task work timeout for %s, timeout=%s secs."
% (self._name, self._timeout_in_secs))
return STATE_TASK_WORK_RESULT.TIMED_OUT, ''
DLOG.verbose(
"Default state task work timeout for %s, timeout=%s secs."
% (self._name, self._timeout_in_secs)
)
return STATE_TASK_WORK_RESULT.TIMED_OUT, ""
def handle_event(self, event, event_data=None):
"""
State Task Work Handle Event (expected to be overridden by child class)
"""
DLOG.verbose("Default state task work handle event for %s."
% self._name)
DLOG.verbose("Default state task work handle event for %s." % self._name)
return False
@@ -12,12 +12,13 @@ class _StateTaskWorkResult(object, metaclass=Singleton):
"""
State Task Work Result - Constants
"""
WAIT = Constant('wait')
SUCCESS = Constant('success')
FAILED = Constant('failed')
DEGRADED = Constant('degraded')
ABORTED = Constant('aborted')
TIMED_OUT = Constant('timed-out')
WAIT = Constant("wait")
SUCCESS = Constant("success")
FAILED = Constant("failed")
DEGRADED = Constant("degraded")
ABORTED = Constant("aborted")
TIMED_OUT = Constant("timed-out")
# Constant Instantiation
+15 -12
View File
@@ -3,15 +3,18 @@
#
# SPDX-License-Identifier: Apache-2.0
#
from nfv_common.strategy._strategy import Strategy # noqa: F401
from nfv_common.strategy._strategy_defs import STRATEGY_ALARM_RESTRICTION_TYPES # noqa: F401
from nfv_common.strategy._strategy_defs import STRATEGY_APPLY_TYPE # noqa: F401
from nfv_common.strategy._strategy_defs import STRATEGY_PHASE # noqa: F401
from nfv_common.strategy._strategy_defs import STRATEGY_STATE # noqa: F401
from nfv_common.strategy._strategy_phase import StrategyPhase # noqa: F401
from nfv_common.strategy._strategy_result import STRATEGY_PHASE_RESULT # noqa: F401
from nfv_common.strategy._strategy_result import STRATEGY_RESULT # noqa: F401
from nfv_common.strategy._strategy_result import STRATEGY_STAGE_RESULT # noqa: F401
from nfv_common.strategy._strategy_result import STRATEGY_STEP_RESULT # noqa: F401
from nfv_common.strategy._strategy_stage import StrategyStage # noqa: F401
from nfv_common.strategy._strategy_step import StrategyStep # noqa: F401
# flake8: noqa
from nfv_common.strategy._strategy import Strategy
from nfv_common.strategy._strategy_defs import (
STRATEGY_ALARM_RESTRICTION_TYPES,
)
from nfv_common.strategy._strategy_defs import STRATEGY_APPLY_TYPE
from nfv_common.strategy._strategy_defs import STRATEGY_PHASE
from nfv_common.strategy._strategy_defs import STRATEGY_STATE
from nfv_common.strategy._strategy_phase import StrategyPhase
from nfv_common.strategy._strategy_result import STRATEGY_PHASE_RESULT
from nfv_common.strategy._strategy_result import STRATEGY_RESULT
from nfv_common.strategy._strategy_result import STRATEGY_STAGE_RESULT
from nfv_common.strategy._strategy_result import STRATEGY_STEP_RESULT
from nfv_common.strategy._strategy_stage import StrategyStage
from nfv_common.strategy._strategy_step import StrategyStep
+104 -59
View File
@@ -1,5 +1,5 @@
#
# Copyright (c) 2015-2016 Wind River Systems, Inc.
# Copyright (c) 2015-2016, 2026 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
@@ -13,15 +13,24 @@ from nfv_common.strategy._strategy_phase import StrategyPhase
from nfv_common.strategy._strategy_result import STRATEGY_RESULT
from nfv_common.strategy._strategy_result import strategy_result_update
DLOG = debug.debug_get_logger('nfv_common.strategy')
DLOG = debug.debug_get_logger("nfv_common.strategy")
class Strategy(object):
"""
Strategy
"""
def __init__(self, uuid, name, state=None, current_phase=None, build_phase=None,
apply_phase=None, abort_phase=None):
def __init__(
self,
uuid,
name,
state=None,
current_phase=None,
build_phase=None,
apply_phase=None,
abort_phase=None,
):
self._uuid = uuid
self._name = name
@@ -117,15 +126,18 @@ class Strategy(object):
"""
Returns true if the strategy build failed
"""
return (STRATEGY_STATE.BUILD_FAILED == self._state or
self.build_phase.is_failed())
return (
STRATEGY_STATE.BUILD_FAILED == self._state or self.build_phase.is_failed()
)
def is_build_timed_out(self):
"""
Returns true if the strategy build timed out
"""
return (STRATEGY_STATE.BUILD_TIMEOUT == self._state or
self.build_phase.is_timed_out())
return (
STRATEGY_STATE.BUILD_TIMEOUT == self._state
or self.build_phase.is_timed_out()
)
def is_ready_to_apply(self):
"""
@@ -143,15 +155,18 @@ class Strategy(object):
"""
Returns true if the strategy apply failed
"""
return (STRATEGY_STATE.APPLY_FAILED == self._state or
self.apply_phase.is_failed())
return (
STRATEGY_STATE.APPLY_FAILED == self._state or self.apply_phase.is_failed()
)
def is_apply_timed_out(self):
"""
Returns true if the strategy apply timed out
"""
<