Repository URL to install this package:
|
Version:
5.0.4 ▾
|
import json
from webob import exc
from workloadmgr.volume import cinder
from workloadmgr.keymanager import barbican
from workloadmgr.compute import nova
from workloadmgr.api.validation_models.validators import BaseValidator
from workloadmgr import exception as wlm_exception
from workloadmgr import workloads as workloadAPI
from workloadmgr.vault import vault
class WorkloadValidator(BaseValidator):
"""
Workload Validator Class.
Does All Validation Operations related to workloads.
partial Implementation.
TODO: Need to implement going further.
"""
def __init__(self, context=None, body=None, secret_ref=None, refresh=False):
super(WorkloadValidator, self).__init__()
self.body = body
self.context = context
self.encryption = body.get('encryption', False)
self.secret_uuid = body.get('secret_uuid')
# get workload encryption details in case of modify
# operation as horizon does not send it.
if refresh and not self.encryption and self.body.get("id"):
workload_api = workloadAPI.API()
workload_dict = workload_api.workload_get(self.context, self.body["id"])
if workload_dict:
if workload_dict.get("encryption"):
self.encryption = workload_dict["encryption"]
if workload_dict.get("secret_uuid"):
self.secret_uuid = workload_dict["secret_uuid"]
if self.encryption:
self.barbican_api = barbican.API()
self.cinder_api = cinder.API()
self.nova_api = nova.API()
def _validate_req_body(self):
raise NotImplementedError()
def _validate_workload_name(self):
raise NotImplementedError()
def _validate_workload_jobschedule(self):
raise NotImplementedError()
def _validate_workload_secrets(self, workload_id=None):
"""
* Validate the user secret from key-manager.
* If secret ref exists then only allow to create Workload.
optimized by breaking the loop when first occurence is met.
"""
if self.encryption:
try:
found = False
try:
secret = self.barbican_api.get_secret(
self.context, secret_id=self.secret_uuid)
except Exception as ex:
raise Exception("Secret could not be found, "
"either the secret is not present or "
"not accessible to the user")
if secret and secret.payload:
wl_metadata = json.loads(
self.barbican_api.get_secret_metadata(
self.context, self.secret_uuid)).get('metadata')
if wl_metadata == {}:
found = True
elif workload_id and \
wl_metadata.get("workload_id") == workload_id:
found = True
if not found:
message = 'Either the secret UUID or '\
'the payload of the secret is invalid.'
raise wlm_exception.ErrorOccurred(message)
except Exception as error:
raise exc.HTTPServerError(explanation=str(error))
def _validate_logical_path_for_workload_encryption(self):
"""
#################################
Not Supported-
#################################
Qcow2:-
1. If workload_encryption is False and Image/s is Encrypted.
2. If workload_encryption is True and Image/s is Encrypted.
Cinder:-
1. If workload_encryption is False and Image/s is Encrypted.
* This method ensures only correct logical paths is hit for snapshots.
* If Above path comes, simply returns False.
"""
if not self.encryption:
try:
instances = self.body.get('instances', [])
for instance in instances:
instance_id = instance.get('instance-id') or instance.get('id')
if instance_id:
workload_instance = self.nova_api.get_server_by_id(self.context, instance_id)
attached_volumes = getattr(workload_instance, 'os-extended-volumes:volumes_attached')
for volume in attached_volumes:
volume_encrypted = self.cinder_api.is_volume_encrypted(self.context, volume['id'])
if not self.encryption and volume_encrypted:
raise wlm_exception.ErrorOccurred(
"Unencrypted workload cannot have instance: {} with encrypted Volume: {}".format(
instance_id, volume.get('id')
)
)
except Exception as error:
raise exc.HTTPServerError(explanation=str(error))
def _ensure_trust(self):
workload_api = workloadAPI.API()
trust = workload_api.trust_list(self.context, get_hidden=True, is_cloud_admin=False)
if not trust:
trust = workload_api.trust_create(self.context, vault.CONF.trustee_role)
return trust
def validate_workload(func):
"""
Factory method for validating workloads.
* This Validation Decorator make sure All types of Validation are covered
* before hitting workload API.
TODO: Need to implement for all.
"""
def inner(*args, **kwargs):
context = kwargs['req'].environ["workloadmgr.context"]
body = kwargs['body']['workload']
# pass refresh=True as mostly request body won't have updated
# information in case of workload modify operation
if kwargs.get("id") and "id" not in body:
body.update({"id": kwargs['id']})
wv = WorkloadValidator(context=context, body=body, refresh=True)
# need to have trust to verify barbican secrets
wv._ensure_trust()
wv._validate_workload_secrets(workload_id=body.get("id", None))
wv._validate_logical_path_for_workload_encryption()
return func(*args, **kwargs)
return inner