Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
if operation.operation_type in ("SYSTEM_DELETE", "SYSTEM_RELOAD", "SYSTEM_UPDATE"):
target_system = db.query_unique(System, id=operation.args[0])
elif "INSTANCE" in operation.operation_type:
target_instance = db.query_unique(Instance, id=operation.args[0])
target_system = db.query_unique(System, instances__contains=target_instance)
elif operation.operation_type == "REQUEST_CREATE":
target_system = System(
namespace=operation.model.namespace,
name=operation.model.system,
version=operation.model.system_version,
)
elif operation.operation_type.startswith("REQUEST"):
request = db.query_unique(Request, id=operation.args[0])
target_system = System(
namespace=request.namespace,
name=request.system,
version=request.system_version,
)
elif operation.operation_type == "QUEUE_DELETE":
# Need to deconstruct the queue name
parts = operation.args[0].split(".")
version = parts[2].replace("-", ".")
target_system = System(namespace=parts[0], name=parts[1], version=version)
return _garden_name_lookup(target_system)
def start(instance_id: str) -> Instance:
"""Starts an instance.
Args:
instance_id: The Instance ID
Returns:
The updated Instance
"""
instance = db.query_unique(Instance, id=instance_id)
system = db.query_unique(System, instances__contains=instance)
logger.info(f"Starting instance {system}[{instance}]")
requests.admin_process_request(
Request.from_template(
start_request,
namespace=system.namespace,
system=system.name,
system_version=system.version,
instance_name=instance.name,
)
)
return instance
def start_request(request_id: str) -> Request:
"""Mark a Request as IN PROGRESS
Args:
request_id: The Request ID to start
Returns:
The modified Request
Raises:
ModelValidationError: The Request is already completed
"""
request = db.query_unique(Request, raise_missing=True, id=request_id)
request.status = "IN_PROGRESS"
request = db.update(request)
# Metrics
request_started(request)
return request
def clean_update(self):
"""Ensure that the update would not result in an illegal status transition"""
# Get the original status
old_status = Request.objects.get(id=self.id).status
if self.status != old_status:
if old_status in BrewtilsRequest.COMPLETED_STATUSES:
raise RequestStatusTransitionError(
f"Status for a request cannot be updated once it has been "
f"completed. Current: {old_status}, Requested: {self.status}"
)
if (
old_status == "IN_PROGRESS"
and self.status not in BrewtilsRequest.COMPLETED_STATUSES
):
raise RequestStatusTransitionError(
f"Request status can only transition from IN_PROGRESS to a "
f"completed status. Requested: {self.status}, completed statuses "
# If a field specification is provided it must also be passed to the serializer
# Also, be aware that serialize_kwargs["only"] = [] means 'serialize nothing'
if query_args.get("include_fields"):
serialize_kwargs["only"] = query_args.get("include_fields")
requests = await self.client(
Operation(operation_type="REQUEST_READ_ALL", kwargs=query_args),
serialize_kwargs=serialize_kwargs,
)
response_headers = {
# These are for information
"start": query_args["start"],
"length": len(requests),
# And these are required by datatables
"recordsFiltered": db.count(Request, **query_args["filter_params"]),
"recordsTotal": db.count(Request),
"draw": self.get_argument("draw", ""),
}
for key, value in response_headers.items():
self.add_header(key, value)
self.add_header("Access-Control-Expose-Headers", key)
self.set_header("Content-Type", "application/json; charset=UTF-8")
self.write(json.dumps(requests))
)
elif op.path == "/output":
operation.kwargs["output"] = op.value
elif op.path == "/error_class":
operation.kwargs["error_class"] = op.value
else:
raise ModelValidationError(f"Unsupported path '{op.path}'")
elif op.operation == "is_admin":
if op.path == "/status":
if op.value.upper() == "IN_PROGRESS":
break
# If we get a start just assume there's no other op in patch
if op.value.upper() in Request.COMPLETED_STATUSES:
operation.operation_type = "ADMIN_REQUEST_COMPLETE"
operation.kwargs["status"] = op.value
else:
raise ModelValidationError(
f"Unsupported status value '{op.value}'"
)
elif op.path == "/output":
operation.kwargs["output"] = op.value
elif op.path == "/error_class":
operation.kwargs["error_class"] = op.value
else:
raise ModelValidationError(f"Unsupported operation '{op.operation}'")
ModelType = Union[
Type[brewtils.models.Command],
Type[brewtils.models.Instance],
Type[brewtils.models.Job],
Type[brewtils.models.Request],
Type[brewtils.models.RequestTemplate],
Type[brewtils.models.System],
Type[brewtils.models.Garden],
]
ModelItem = Union[
brewtils.models.Command,
brewtils.models.Instance,
brewtils.models.Job,
brewtils.models.Request,
brewtils.models.RequestTemplate,
brewtils.models.System,
brewtils.models.Garden,
]
_model_map = beer_garden.db.sql.models.schema_mapping
engine = None
Session = None
def from_brewtils(obj: ModelItem) -> SqlModel:
"""Convert an item from its Brewtils model to its one
Args:
obj: The Brewtils model item
"""
operation = Operation(args=[request_id])
patch = SchemaParser.parse_patch(self.request.decoded_body, from_string=True)
for op in patch:
if op.operation == "replace":
if op.path == "/status":
# If we get a start just assume there's no other op in patch
if op.value.upper() == "IN_PROGRESS":
operation.operation_type = "REQUEST_START"
operation.kwargs = {}
break
elif op.value.upper() in Request.COMPLETED_STATUSES:
operation.operation_type = "REQUEST_COMPLETE"
operation.kwargs["status"] = op.value
else:
raise ModelValidationError(
f"Unsupported status value '{op.value}'"
)
elif op.path == "/output":
operation.kwargs["output"] = op.value
elif op.path == "/error_class":
operation.kwargs["error_class"] = op.value
else:
raise ModelValidationError(f"Unsupported path '{op.path}'")
queue_type = StringField()
queue_info = DictField()
icon_name = StringField()
metadata = DictField()
def clean(self):
"""Validate before saving to the database"""
if self.status not in BrewtilsInstance.INSTANCE_STATUSES:
raise ModelValidationError(
f"Can not save Instance {self}: Invalid status '{self.status}'"
)
class Request(MongoModel, Document):
brewtils_model = brewtils.models.Request
# These fields are duplicated for job types, changes to this field
# necessitate a change to the RequestTemplateSchema in brewtils.
TEMPLATE_FIELDS = {
"system": {"field": StringField, "kwargs": {"required": True}},
"system_version": {"field": StringField, "kwargs": {"required": True}},
"instance_name": {"field": StringField, "kwargs": {"required": True}},
"namespace": {"field": StringField, "kwargs": {"required": True}},
"command": {"field": StringField, "kwargs": {"required": True}},
"command_type": {"field": StringField, "kwargs": {}},
"parameters": {"field": DictField, "kwargs": {}},
"comment": {"field": StringField, "kwargs": {"required": False}},
"metadata": {"field": DictField, "kwargs": {}},
"output_type": {"field": StringField, "kwargs": {}},
"output_types": {"field": ListField, "kwargs": {}},
"output_labels": {"field": ListField, "kwargs": {}},
"Unable to validate choices for parameter '%s' - Choices value"
" must be a list or dictionary " % command_parameter.key
)
elif choices.type == "url":
parsed_value = parse(choices.value, parse_as="url")
query_params = map_param_values(parsed_value["args"])
raw_allowed = json.loads(
self._session.get(parsed_value["address"], params=query_params).text
)
elif choices.type == "command":
if isinstance(choices.value, six.string_types):
parsed_value = parse(choices.value, parse_as="func")
choices_request = Request(
system=request.system,
system_version=request.system_version,
instance_name=request.instance_name,
command=parsed_value["name"],
parameters=map_param_values(parsed_value["args"]),
)
elif isinstance(choices.value, dict):
parsed_value = parse(choices.value["command"], parse_as="func")
choices_request = Request(
system=choices.value.get("system"),
system_version=choices.value.get("version"),
instance_name=choices.value.get("instance_name", "default"),
command=parsed_value["name"],
parameters=map_param_values(parsed_value["args"]),
)
else: