Skip to content

Commit

Permalink
Add new endpoint for creation of approval nodes
Browse files Browse the repository at this point in the history
  • Loading branch information
beeankha committed Jul 18, 2019
1 parent b6339ad commit 038092f
Show file tree
Hide file tree
Showing 21 changed files with 151 additions and 79 deletions.
21 changes: 19 additions & 2 deletions awx/api/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -3068,7 +3068,7 @@ def validate(self, attrs):
attrs = super(JobRelaunchSerializer, self).validate(attrs)
return attrs


# &&&&&&
class JobCreateScheduleSerializer(BaseSerializer):

can_schedule = serializers.SerializerMethodField()
Expand Down Expand Up @@ -3406,7 +3406,7 @@ class WorkflowApprovalTemplateSerializer(UnifiedJobTemplateSerializer):

class Meta:
model = WorkflowApprovalTemplate
fields = ('*',)
fields = ('*', 'timeout', 'name',)

def get_related(self, obj):
res = super(WorkflowApprovalTemplateSerializer, self).get_related(obj)
Expand All @@ -3422,6 +3422,15 @@ def get_related(self, obj):
return res


# class WorkflowJobTemplateApprovalSerializer(UnifiedJobTemplateSerializer):
# class Meta:
# model = WorkflowJobTemplateApproval
# fields = ('*',)
#
# def post(self, obj):
# return # POST only!!!


class LaunchConfigurationBaseSerializer(BaseSerializer):
job_type = serializers.ChoiceField(allow_blank=True, allow_null=True, required=False, default=None,
choices=NEW_JOB_TYPE_CHOICES)
Expand Down Expand Up @@ -3567,6 +3576,7 @@ class Meta:

def get_related(self, obj):
res = super(WorkflowJobTemplateNodeSerializer, self).get_related(obj)
res['create_approval_job_template'] = self.reverse('api:workflow_job_template_node_create_approval', kwargs={'pk': obj.pk})
res['success_nodes'] = self.reverse('api:workflow_job_template_node_success_nodes_list', kwargs={'pk': obj.pk})
res['failure_nodes'] = self.reverse('api:workflow_job_template_node_failure_nodes_list', kwargs={'pk': obj.pk})
res['always_nodes'] = self.reverse('api:workflow_job_template_node_always_nodes_list', kwargs={'pk': obj.pk})
Expand Down Expand Up @@ -3693,6 +3703,13 @@ def build_relational_field(self, field_name, relation_info):
field_kwargs.pop('queryset', None)
return field_class, field_kwargs

# &&&&&&
class WorkflowJobTemplateNodeCreateApprovalSerializer(BaseSerializer):

class Meta:
model = WorkflowApprovalTemplate
fields = ('timeout', 'name', 'description',)


class JobListSerializer(JobSerializer, UnifiedJobListSerializer):
pass
Expand Down
4 changes: 2 additions & 2 deletions awx/api/urls/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,8 +133,8 @@
url(r'^unified_job_templates/$', UnifiedJobTemplateList.as_view(), name='unified_job_template_list'),
url(r'^unified_jobs/$', UnifiedJobList.as_view(), name='unified_job_list'),
url(r'^activity_stream/', include(activity_stream_urls)),
url(r'^workflow_approval_templates/', include(workflow_approval_template_urls)),
url(r'^workflow_approval/', include(workflow_approval_urls)),
url(r'^workflow_approval_templates/', include(workflow_approval_template_urls)), # &&&&&& Take this line out completely?
url(r'^workflow_approvals/', include(workflow_approval_urls)),
]


Expand Down
2 changes: 2 additions & 0 deletions awx/api/urls/workflow_job_template_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
WorkflowJobTemplateNodeFailureNodesList,
WorkflowJobTemplateNodeAlwaysNodesList,
WorkflowJobTemplateNodeCredentialsList,
WorkflowJobTemplateNodeCreateApproval,
)


Expand All @@ -20,6 +21,7 @@
url(r'^(?P<pk>[0-9]+)/failure_nodes/$', WorkflowJobTemplateNodeFailureNodesList.as_view(), name='workflow_job_template_node_failure_nodes_list'),
url(r'^(?P<pk>[0-9]+)/always_nodes/$', WorkflowJobTemplateNodeAlwaysNodesList.as_view(), name='workflow_job_template_node_always_nodes_list'),
url(r'^(?P<pk>[0-9]+)/credentials/$', WorkflowJobTemplateNodeCredentialsList.as_view(), name='workflow_job_template_node_credentials_list'),
url(r'^(?P<pk>[0-9]+)/create_approval_job_template/$', WorkflowJobTemplateNodeCreateApproval.as_view(), name='workflow_job_template_node_create_approval'),
]

__all__ = ['urls']
19 changes: 17 additions & 2 deletions awx/api/views/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3013,6 +3013,21 @@ def is_valid_relation(self, parent, sub, created=False):
return None


class WorkflowJobTemplateNodeCreateApproval(RetrieveAPIView):

model = models.WorkflowJobTemplateNode
serializer_class = serializers.WorkflowJobTemplateNodeCreateApprovalSerializer

# &&&&&&
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
if not serializer.is_valid():
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
obj = self.get_object()
approval_template = obj.create_approval_template(**serializer.validated_data)
return Response(data={'id':approval_template.pk}, status=status.HTTP_200_OK)


class WorkflowJobTemplateNodeSuccessNodesList(WorkflowJobTemplateNodeChildrenBaseList):
relationship = 'success_nodes'

Expand Down Expand Up @@ -3582,7 +3597,7 @@ def post(self, request, *args, **kwargs):
headers = {'Location': new_job.get_absolute_url(request=request)}
return Response(data, status=status.HTTP_201_CREATED, headers=headers)


# &&&&&& Reference
class JobCreateSchedule(RetrieveAPIView):

model = models.Job
Expand Down Expand Up @@ -4466,7 +4481,7 @@ class WorkflowApprovalDetail(UnifiedJobDeletionMixin, RetrieveDestroyAPIView):
model = models.WorkflowApproval
serializer_class = serializers.WorkflowApprovalSerializer


# &&&&&& Include checks in the below two post methods
class WorkflowApprovalApprove(RetrieveAPIView):
model = models.WorkflowApproval
serializer_class = serializers.WorkflowApprovalViewSerializer
Expand Down
4 changes: 2 additions & 2 deletions awx/api/views/root.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,8 +124,8 @@ def get(self, request, format=None):
data['activity_stream'] = reverse('api:activity_stream_list', request=request)
data['workflow_job_templates'] = reverse('api:workflow_job_template_list', request=request)
data['workflow_jobs'] = reverse('api:workflow_job_list', request=request)
data['workflow_approval_templates'] = reverse('api:workflow_approval_template_list', request=request)
data['workflow_approval'] = reverse('api:workflow_approval_list', request=request)
data['workflow_approval_templates'] = reverse('api:workflow_approval_template_list', request=request) # &&&&&& Take this line out completely?
data['workflow_approvals'] = reverse('api:workflow_approval_list', request=request)
data['workflow_job_template_nodes'] = reverse('api:workflow_job_template_node_list', request=request)
data['workflow_job_nodes'] = reverse('api:workflow_job_node_list', request=request)
return Response(data)
Expand Down
24 changes: 16 additions & 8 deletions awx/main/access.py
Original file line number Diff line number Diff line change
Expand Up @@ -2787,24 +2787,32 @@ def filtered_queryset(self):

def can_start(self, obj, validate_license=True):
return False
# &&&&&& ??? Start of the RBAC method ???
# def can_approve_or_deny(self, obj):
# if self.user.is_superuser: # &&&&&& add "or self.user.approval_role"?
# return True
# return self.can_change(obj, ????)


# &&&&&& Why is the below not showing up as a class now??
class WorkflowApprovalTemplateAccess(BaseAccess):
'''
I can create approval nodes when:
-
I can approve workflows when:
- I'm authenticated
I can create when:
- I'm a superuser:
-
'''

model = WorkflowApprovalTemplate
prefetch_related = ('created_by', 'modified_by',)

def can_read(self, obj):
return True

def can_use(self, obj):
return True
# &&&&&& I need to get the admin role of the WFJT, where WFJT is provided in the key portion vs the data (Alan said that, what does it mean exactly???)
@check_superuser
def can_add(self, data):
if data is None: # Hide direct creation in API browser
return False
return (
self.check_related('workflow_approval_template', UnifiedJobTemplate, role_field='admin_role')

def filtered_queryset(self):
return self.model.filter(workflowjobtemplatenodes__workflow_job_template=WorkflowJobTemplate.accessible_pk_qs(self.user, 'read_role'))
Expand Down
2 changes: 1 addition & 1 deletion awx/main/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ def is_implicit_parent(parent_role, child_role):
# The only singleton implicit parent is the system admin being
# a parent of the system auditor role
return bool(
child_role.singleton_name == ROLE_SINGLETON_SYSTEM_AUDITOR and
child_role.singleton_name == ROLE_SINGLETON_SYSTEM_AUDITOR and
parent_role.singleton_name == ROLE_SINGLETON_SYSTEM_ADMINISTRATOR
)
# Get the list of implicit parents that were defined at the class level.
Expand Down
2 changes: 2 additions & 0 deletions awx/main/management/commands/cleanup_jobs.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,8 @@ def cleanup_workflow_jobs(self):
skipped += WorkflowJob.objects.filter(created__gte=self.cutoff).count()
return skipped, deleted

# &&&&&& Add cleanup of orphaned approval nodes here?

def cleanup_notifications(self):
skipped, deleted = 0, 0
notifications = Notification.objects.filter(created__lt=self.cutoff)
Expand Down
41 changes: 0 additions & 41 deletions awx/main/migrations/0082_v360_workflowapproval.py

This file was deleted.

4 changes: 3 additions & 1 deletion awx/main/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ def o_auth2_token_get_absolute_url(self, request=None):


OAuth2AccessToken.add_to_class('get_absolute_url', o_auth2_token_get_absolute_url)

# &&&&&& "Add model here" - Alan
from awx.main.registrar import activity_stream_registrar # noqa
activity_stream_registrar.connect(Organization)
activity_stream_registrar.connect(Inventory)
Expand Down Expand Up @@ -195,6 +195,8 @@ def o_auth2_token_get_absolute_url(self, request=None):
activity_stream_registrar.connect(WorkflowJobTemplate)
activity_stream_registrar.connect(WorkflowJobTemplateNode)
activity_stream_registrar.connect(WorkflowJob)
# activity_stream_registrar.connect(WorkflowApproval) &&&&&&
# activity_stream_registrar.connect(WorkflowApprovalTemplate)
activity_stream_registrar.connect(OAuth2Application)
activity_stream_registrar.connect(OAuth2AccessToken)

Expand Down
1 change: 0 additions & 1 deletion awx/main/models/mixins.py
Original file line number Diff line number Diff line change
Expand Up @@ -483,4 +483,3 @@ def get_active_jobs(self):
raise RuntimeError("Programmer error. Expected _get_active_jobs() to return a QuerySet.")

return [dict(id=t[0], type=mapping[t[1]]) for t in jobs.values_list('id', 'polymorphic_ctype_id')]

4 changes: 4 additions & 0 deletions awx/main/models/organization.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,10 @@ class Meta:
'notification_admin_role', 'credential_admin_role',
'job_template_admin_role',],
)
# &&&&&& The below keeps complaining - fixed by new migration file, perhaps?
approval_role = ImplicitRoleField(
parent_role='admin_role',
)


def get_absolute_url(self, request=None):
Expand Down
4 changes: 3 additions & 1 deletion awx/main/models/rbac.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
'read_role': _('Read'),
'update_role': _('Update'),
'use_role': _('Use'),
'approval_role': _('Approve'), # &&&&&& Added this here!
}

role_descriptions = {
Expand All @@ -70,6 +71,7 @@
'read_role': _('May view settings for the %s'),
'update_role': _('May update the %s'),
'use_role': _('Can use the %s in a job template'),
'approval_role': _('Can approve or deny a workflow approval node'), # &&&&&& ...and here!
}


Expand Down Expand Up @@ -480,7 +482,7 @@ def get_roles_on_resource(resource, accessor):
).values_list('role_field', flat=True).distinct()
]


# &&&&&& This area is giving trouble?
def role_summary_fields_generator(content_object, role_field):
global role_descriptions
global role_names
Expand Down
40 changes: 40 additions & 0 deletions awx/main/models/workflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,13 @@ def create_wfjt_node_copy(self, user, workflow_job_template=None):
new_node.credentials.add(cred)
return new_node

def create_approval_template(self, **kwargs):
approval_template = WorkflowApprovalTemplate(**kwargs)
approval_template.save()
self.unified_job_template = approval_template
self.save()
return approval_template


class WorkflowJobNode(WorkflowNodeBase):
job = models.OneToOneField(
Expand Down Expand Up @@ -388,6 +395,11 @@ class Meta:
'singleton:' + ROLE_SINGLETON_SYSTEM_AUDITOR,
'organization.auditor_role', 'execute_role', 'admin_role'
])
# &&&&&& The below keeps complaining - fixed by new migration file, perhaps?
approval_role = ImplicitRoleField(parent_role=[
'singleton:' + ROLE_SINGLETON_SYSTEM_AUDITOR,
'organization.approval_role', 'admin_role',
])

@property
def workflow_nodes(self):
Expand Down Expand Up @@ -608,6 +620,12 @@ class WorkflowApprovalTemplate(UnifiedJobTemplate):
class Meta:
app_label = 'main'

timeout = models.IntegerField(
blank=True,
default=0,
help_text=_("The amount of time (in seconds) before the approval node expires and fails."),
)

@classmethod
def _get_unified_job_class(cls):
return WorkflowApproval
Expand All @@ -619,6 +637,28 @@ def _get_unified_job_field_names(cls):
def get_absolute_url(self, request=None):
return reverse('api:workflow_approval_template_detail', kwargs={'pk': self.pk}, request=request)

# @property
# def notification_templates(self):
# # Return all notification_templates defined on the Job Template, on the Project, and on the Organization for each trigger type
# base_notification_templates = NotificationTemplate.objects
# error_notification_templates = list(base_notification_templates.filter(
# unifiedjobtemplate_notification_templates_for_errors__in=[self, self.project]))
# started_notification_templates = list(base_notification_templates.filter(
# unifiedjobtemplate_notification_templates_for_started__in=[self, self.project]))
# success_notification_templates = list(base_notification_templates.filter(
# unifiedjobtemplate_notification_templates_for_success__in=[self, self.project]))
# &&&&&& Approvals don't have orgs! How to pull them in? Alan said to "get creative"!
# if self.project is not None and self.project.organization is not None:
# error_notification_templates = set(error_notification_templates + list(base_notification_templates.filter(
# organization_notification_templates_for_errors=self.project.organization)))
# started_notification_templates = set(started_notification_templates + list(base_notification_templates.filter(
# organization_notification_templates_for_started=self.project.organization)))
# success_notification_templates = set(success_notification_templates + list(base_notification_templates.filter(
# organization_notification_templates_for_success=self.project.organization)))
# return dict(error=list(error_notification_templates),
# started=list(started_notification_templates),
# success=list(success_notification_templates))


class WorkflowApproval(UnifiedJob):
class Meta:
Expand Down
2 changes: 1 addition & 1 deletion awx/main/registrar.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

from django.db.models.signals import pre_save, post_save, pre_delete, m2m_changed


# &&&&&& Where the signals are hooked up ??
class ActivityStreamRegistrar(object):

def __init__(self):
Expand Down
Loading

0 comments on commit 038092f

Please sign in to comment.