Skip to content

Commit

Permalink
Refacto globalhook
Browse files Browse the repository at this point in the history
refacto globalhook
  • Loading branch information
a-belhadj committed Sep 12, 2023
1 parent 259ea05 commit ff8782a
Show file tree
Hide file tree
Showing 37 changed files with 636 additions and 651 deletions.
4 changes: 0 additions & 4 deletions Squest/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -499,11 +499,7 @@ def backup_filename(databasename, servername, datetime, extension, content_type)
# -----------------------------------------
# SQL Debug
# -----------------------------------------

if SQL_DEBUG:
LOGGING["handlers"]["console"] = {
"level": "DEBUG", "class": "logging.StreamHandler"
}
LOGGING["loggers"]["django.db.backends"] = {
"level": "DEBUG", "handlers": ["console"]
}
Expand Down
16 changes: 12 additions & 4 deletions profiles/templatetags/squest_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,11 +248,19 @@ def generate_sidebar(user):
'active': [],
'treeview_items': [
{
'name': 'Global hook',
'view_name': 'service_catalog:globalhook_list',
'name': 'Request hook ',
'view_name': 'service_catalog:requesthook_list',
'icon': 'fas fa-file-code',
'permission_required': 'service_catalog.list_globalhook',
'active': ["globalhook_list", "globalhook_create", "globalhook_edit", "globalhook_delete"]
'permission_required': 'service_catalog.list_requesthook',
'active': ["requesthook_list", "requesthook_create", "requesthook_edit",
"requesthook_delete"]
},
{
'name': 'Instance hook ',
'view_name': 'service_catalog:instancehook_list',
'icon': 'fas fa-file-code',
'permission_required': 'service_catalog.list_instancehook',
'active': ["instancehook_list", "instancehook_create", "instancehook_edit", "instancehook_delete"]
},
{
'name': 'Announcements',
Expand Down
39 changes: 0 additions & 39 deletions project-static/squest/js/global_hook.js

This file was deleted.

2 changes: 1 addition & 1 deletion resource_tracker_v2/views/transformer_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,5 +143,5 @@ def ajax_load_attribute(request):

options = [(transformer.attribute_definition.id, transformer.attribute_definition.name) for transformer in
all_available_attribute_to_target_rg.all()]
return render(request, 'service_catalog/settings/global_hooks/state-dropdown-list-option.html',
return render(request, 'generics/ajax.html',
{'options': options})
48 changes: 8 additions & 40 deletions service_catalog/filters/global_hook_filter.py
Original file line number Diff line number Diff line change
@@ -1,46 +1,14 @@
from django.forms import SelectMultiple
from django_filters import MultipleChoiceFilter

from Squest.utils.squest_filter import SquestFilter
from service_catalog.models import GlobalHook
from service_catalog.models.instance import InstanceState
from service_catalog.models.request import RequestState
from service_catalog.models.state_hooks import HookModel
from service_catalog.models import InstanceHook, RequestHook


class GlobalHookFilter(SquestFilter):
class InstanceHookFilter(SquestFilter):
class Meta:
model = GlobalHook
fields = ['name', 'model']

model = MultipleChoiceFilter(
choices=HookModel.choices,
widget=SelectMultiple())

state_instance = MultipleChoiceFilter(
label="Instance state",
method='add_states_in_filter',
choices=InstanceState.choices,
null_value=None,
widget=SelectMultiple(attrs={'data-live-search': "true"}))
model = InstanceHook
fields = ['name', 'state']

state_request = MultipleChoiceFilter(
label="Request state",
method='add_states_in_filter',
choices=RequestState.choices,
null_value=None,
widget=SelectMultiple(attrs={'data-live-search': "true"}))

def __init__(self, *args, **kwargs):
super(GlobalHookFilter, self).__init__(*args, **kwargs)
self.state_filter_value = list()

def add_states_in_filter(self, queryset, field_name, value):
self.state_filter_value += value
return queryset

def filter_queryset(self, queryset):
queryset = super(GlobalHookFilter, self).filter_queryset(queryset)
tmp = self.state_filter_value
self.state_filter_value = []
return queryset.filter(state__in=tmp)
class RequestHookFilter(SquestFilter):
class Meta:
model = RequestHook
fields = ['name', 'state']
40 changes: 8 additions & 32 deletions service_catalog/forms/global_hook_forms.py
Original file line number Diff line number Diff line change
@@ -1,38 +1,14 @@
from django import forms
from django.core.exceptions import ValidationError
from django.forms import ChoiceField

from Squest.utils.squest_model_form import SquestModelForm
from service_catalog.models import GlobalHook
from service_catalog.models.instance import InstanceState
from service_catalog.models.request import RequestState

from service_catalog.models import InstanceHook, RequestHook

class GlobalHookForm(SquestModelForm):
def __init__(self, *args, **kwargs):
super(GlobalHookForm, self).__init__(*args, **kwargs)
self.fields['operation'].widget.attrs['class'] = 'form-control'
self.fields['state'] = ChoiceField(label="State",
choices=InstanceState.choices + RequestState.choices,
error_messages={'required': 'At least you must select one state'},
widget=forms.Select(attrs={'class': 'form-control'}))

def clean(self):
cleaned_data = super(GlobalHookForm, self).clean()
model = cleaned_data.get('model')
state = cleaned_data.get('state')
class InstanceHookForm(SquestModelForm):
class Meta:
model = InstanceHook
fields = ["name", "service", "state", "job_template", "extra_vars"]

choices = ""
if model == "Request":
choices = RequestState.choices
if model == "Instance":
choices = InstanceState.choices
if state not in (choice[0] for choice in choices):
raise ValidationError({
'state': f"'{state}' is not a valid state of model '{model}'"
})
return cleaned_data

class RequestHookForm(SquestModelForm):
class Meta:
model = GlobalHook
fields = ["name", "model", "service", "operation", "state", "job_template", "extra_vars"]
model = RequestHook
fields = ["name", "operation", "state", "job_template", "extra_vars"]
89 changes: 89 additions & 0 deletions service_catalog/migrations/0024_alter_globalhook_state.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
# Generated by Django 3.2.13 on 2023-09-12 14:52

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('service_catalog', '0023_auto_20230912_1524'),
]

operations = [
migrations.RunSQL('UPDATE service_catalog_globalhook SET state = 1 WHERE state = "SUBMITTED";'),
migrations.RunSQL('UPDATE service_catalog_globalhook SET state = 2 WHERE state = "NEED_INFO";'),
migrations.RunSQL('UPDATE service_catalog_globalhook SET state = 3 WHERE state = "REJECTED";'),
migrations.RunSQL('UPDATE service_catalog_globalhook SET state = 4 WHERE state = "ACCEPTED";'),
migrations.RunSQL('UPDATE service_catalog_globalhook SET state = 5 WHERE state = "CANCELED";'),
migrations.RunSQL('UPDATE service_catalog_globalhook SET state = 6 WHERE state = "PROCESSING";'),
migrations.RunSQL('UPDATE service_catalog_globalhook SET state = 7 WHERE state = "COMPLETE";'),
migrations.RunSQL('UPDATE service_catalog_globalhook SET state = 8 WHERE state = "FAILED";'),
migrations.RunSQL('UPDATE service_catalog_globalhook SET state = 9 WHERE state = "ARCHIVED";'),

migrations.RunSQL('UPDATE service_catalog_globalhook SET state = 1 WHERE state = "SUBMITTED";'),
migrations.RunSQL('UPDATE service_catalog_globalhook SET state = 1 WHERE state = "PENDING";'),
migrations.RunSQL('UPDATE service_catalog_globalhook SET state = 2 WHERE state = "PROVISION_FAILED";'),
migrations.RunSQL('UPDATE service_catalog_globalhook SET state = 3 WHERE state = "PROVISIONING";'),
migrations.RunSQL('UPDATE service_catalog_globalhook SET state = 4 WHERE state = "UPDATING";'),
migrations.RunSQL('UPDATE service_catalog_globalhook SET state = 5 WHERE state = "UPDATE_FAILED";'),
migrations.RunSQL('UPDATE service_catalog_globalhook SET state = 6 WHERE state = "DELETING";'),
migrations.RunSQL('UPDATE service_catalog_globalhook SET state = 7 WHERE state = "DELETED";'),
migrations.RunSQL('UPDATE service_catalog_globalhook SET state = 8 WHERE state = "DELETE_FAILED";'),
migrations.RunSQL('UPDATE service_catalog_globalhook SET state = 9 WHERE state = "ARCHIVED";'),
migrations.RunSQL('UPDATE service_catalog_globalhook SET state = 10 WHERE state = "AVAILABLE";'),
migrations.RunSQL('UPDATE service_catalog_globalhook SET state = 11 WHERE state = "ABORTED";'),

migrations.AlterField(
model_name='globalhook',
name='state',
field=models.IntegerField(),
),
migrations.DeleteModel(
name='GlobalHook',
),
migrations.CreateModel(
name='InstanceHook',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created', models.DateTimeField(auto_now_add=True, null=True)),
('last_updated', models.DateTimeField(auto_now=True, null=True)),
('name', models.CharField(max_length=100, unique=True)),
('extra_vars', models.JSONField(blank=True, default=dict)),
('state', models.IntegerField(
choices=[(1, 'PENDING'), (2, 'PROVISION_FAILED'), (3, 'PROVISIONING'), (4, 'UPDATING'),
(5, 'UPDATE_FAILED'), (6, 'DELETING'), (7, 'DELETED'), (8, 'DELETE_FAILED'),
(9, 'ARCHIVED'), (10, 'AVAILABLE'), (11, 'ABORTED')])),
('job_template',
models.ForeignKey(on_delete=models.deletion.CASCADE, to='service_catalog.jobtemplate')),
('service',
models.ForeignKey(blank=True, default=None, null=True, on_delete=models.deletion.SET_NULL,
to='service_catalog.service')),
],
options={
'abstract': False,
'default_permissions': ('add', 'change', 'delete', 'view', 'list'),
},
),
migrations.CreateModel(
name='RequestHook',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created', models.DateTimeField(auto_now_add=True, null=True)),
('last_updated', models.DateTimeField(auto_now=True, null=True)),
('name', models.CharField(max_length=100, unique=True)),
('extra_vars', models.JSONField(blank=True, default=dict)),
('state', models.IntegerField(
choices=[(1, 'SUBMITTED'), (2, 'NEED_INFO'), (3, 'REJECTED'), (4, 'ACCEPTED'), (5, 'CANCELED'),
(6, 'PROCESSING'), (7, 'COMPLETE'), (8, 'FAILED'), (9, 'ARCHIVED')])),
('job_template',
models.ForeignKey(on_delete=models.deletion.CASCADE, to='service_catalog.jobtemplate')),
('operation',
models.ForeignKey(blank=True, default=None, null=True, on_delete=models.deletion.SET_NULL,
to='service_catalog.operation')),
],
options={
'abstract': False,
'default_permissions': ('add', 'change', 'delete', 'view', 'list'),
},
),
]
2 changes: 1 addition & 1 deletion service_catalog/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from service_catalog.models.request import Request
from service_catalog.models.message import Message, RequestMessage, SupportMessage
from service_catalog.models.support import Support
from service_catalog.models.state_hooks import GlobalHook
from service_catalog.models.state_hooks import InstanceHook, RequestHook
from service_catalog.models.documentation import Doc
from service_catalog.models.announcement import Announcement
from service_catalog.models.squest_settings import SquestSettings
Expand Down
22 changes: 13 additions & 9 deletions service_catalog/models/instance.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from django.core.exceptions import ValidationError
from django.db.models import CharField, JSONField, ForeignKey, SET_NULL, DateTimeField, ManyToManyField, PROTECT, Q, \
CASCADE
from django.db.models.signals import post_save, pre_delete
from django.db.models.signals import post_save, pre_delete, pre_save
from django.dispatch import receiver
from django.utils.translation import gettext_lazy as _
from django_fsm import transition, post_transition, FSMIntegerField
Expand Down Expand Up @@ -201,21 +201,25 @@ def reset_to_last_stable_state(self):
def delete_linked_resources(self):
self.resources.filter(is_deleted_on_instance_deletion=True).delete()

@classmethod
def trigger_hook_handler(cls, sender, instance, name, source, target, *args, **kwargs):
"""
Proxy method. Cannot be mocked for testing
"""
HookManager.trigger_hook(sender, instance, name, source, target, *args, **kwargs)

@classmethod
def on_create_call_hook_manager(cls, sender, instance, created, *args, **kwargs):
if created:
HookManager.trigger_hook(sender=sender, instance=instance, name="create", source="create",
target=InstanceState.PENDING, *args, **kwargs)

@classmethod
def on_change(cls, sender, instance, *args, **kwargs):
if instance.id is not None:
previous = Instance.objects.get(id=instance.id)
if previous.state != instance.state:
HookManager.trigger_hook(sender=sender, instance=instance, name="on_change_instance", source=previous.state, target=instance.state,
*args, **kwargs)



pre_save.connect(Instance.on_change, sender=Instance)


post_transition.connect(Instance.trigger_hook_handler, sender=Instance)
post_save.connect(Instance.on_create_call_hook_manager, sender=Instance)


Expand Down
7 changes: 5 additions & 2 deletions service_catalog/models/job_templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,11 @@ def execute(self, extra_vars, inventory_override=None, credentials_override=None
}
logger.info(f"[job-template-execute] Execute job template with parameter: {parameters}")
tower_job_run = tower_job_template.launch(**parameters)
return tower_job_run.id

if tower_job_run:
return tower_job_run.id
else:
logger.critical(f"[job-template-execute] Fail to execute job template with parameter: {parameters}")
return None
def check_is_compliant(self):
return self.is_ask_variables_on_launch_compliant()

Expand Down
16 changes: 6 additions & 10 deletions service_catalog/models/request.py
Original file line number Diff line number Diff line change
Expand Up @@ -371,14 +371,6 @@ def auto_accept_and_process_signal(cls, sender, instance, created, *args, **kwar
if save_instance_on_update:
instance.save()

@classmethod
def trigger_hook_handler(cls, sender, instance, name, source, target, *args, **kwargs):
"""
Proxy method. Cannot be mocked for testing
"""
HookManager.trigger_hook(sender=sender, instance=instance, name=name, source=source, target=target,
*args, **kwargs)

@classmethod
def on_create(cls, sender, instance, created, *args, **kwargs):
if created:
Expand All @@ -392,9 +384,14 @@ def on_create(cls, sender, instance, created, *args, **kwargs):

@classmethod
def on_change(cls, sender, instance, *args, **kwargs):
# reset all approval step to pending if an approval workflow was attached to the request
if instance.id is not None:
previous = Request.objects.get(id=instance.id)
if previous.state != instance.state:
HookManager.trigger_hook(sender=sender, instance=instance, name="on_change_request",
source=previous.state, target=instance.state,
*args, **kwargs)

# reset all approval step to pending if an approval workflow was attached to the request
if previous.state != RequestState.SUBMITTED and instance.state == RequestState.SUBMITTED:
if instance.approval_workflow_state is not None:
instance.approval_workflow_state.reset()
Expand All @@ -403,4 +400,3 @@ def on_change(cls, sender, instance, *args, **kwargs):
pre_save.connect(Request.on_change, sender=Request)
post_save.connect(Request.on_create, sender=Request)
post_save.connect(Request.auto_accept_and_process_signal, sender=Request)
post_transition.connect(Request.trigger_hook_handler, sender=Request)
Loading

0 comments on commit ff8782a

Please sign in to comment.