How to use the orchestra.contrib.orchestration.Operation function in orchestra

To help you get started, we’ve selected a few orchestra examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github glic3rinu / django-orchestra / orchestra / contrib / orchestration / middlewares.py View on Github external
@receiver(m2m_changed, dispatch_uid='orchestration.m2m_collector')
def m2m_collector(sender, *args, **kwargs):
    # m2m relations without intermediary models are shit. Model.post_save is not sent and
    # by the time related.post_save is sent rel objects are not accessible via RelatedManager.all()
    if kwargs.pop('action') == 'post_add' and kwargs['pk_set']:
        OperationsMiddleware.collect(Operation.SAVE, **kwargs)
github glic3rinu / django-orchestra / orchestra / contrib / orchestration / actions.py View on Github external
def retry_backend(modeladmin, request, queryset):
    related_operations = queryset.values_list('operations__id', flat=True).distinct()
    related_operations = BackendOperation.objects.filter(pk__in=related_operations)
    related_operations = related_operations.select_related('log__server').prefetch_related('instance')
    if request.POST.get('post') == 'generic_confirmation':
        operations = []
        for operation in related_operations:
            if operation.instance:
                op = Operation.load(operation)
                operations.append(op)
        if not operations:
            messages.warning(request, _("No backend operation has been executed."))
        else:
            logs = Operation.execute(operations)
            message_user(request, logs)
        for backendlog in queryset:
            modeladmin.log_change(request, backendlog, 'Retried')
        return
    opts = modeladmin.model._meta
    display_objects = []
    deleted_objects = []
    for op in related_operations:
        if not op.instance:
            deleted_objects.append(op)
        else:
github glic3rinu / django-orchestra / orchestra / contrib / orchestration / middlewares.py View on Github external
@receiver(post_save, dispatch_uid='orchestration.post_save_collector')
def post_save_collector(sender, *args, **kwargs):
    if sender not in [BackendLog, Operation]:
        OperationsMiddleware.collect(Operation.SAVE, **kwargs)
github glic3rinu / django-orchestra / orchestra / contrib / orchestration / middlewares.py View on Github external
def post_save_collector(sender, *args, **kwargs):
    if sender not in (BackendLog, BackendOperation, LogEntry):
        instance = kwargs.get('instance')
        OperationsMiddleware.collect(Operation.SAVE, **kwargs)
github glic3rinu / django-orchestra / orchestra / contrib / domains / backends.py View on Github external
def get_servers(self, domain, backend):
        """ Get related server IPs from registered backend routes """
        from orchestra.contrib.orchestration.manager import router
        operation = Operation(backend, domain, Operation.SAVE)
        servers = []
        for route in router.objects.get_for_operation(operation):
            servers.append(route.host.get_ip())
        return servers
github glic3rinu / django-orchestra / orchestra / contrib / letsencrypt / actions.py View on Github external
form = LetsEncryptForm(domains, wildcards, initial={'domains': '\n'.join(domains)})
    action_value = 'letsencrypt'
    if request.POST.get('post') == 'generic_confirmation':
        form = LetsEncryptForm(domains, wildcards, request.POST)
        if not content_error and form.is_valid():
            cleaned_data = form.cleaned_data
            domains = set(cleaned_data['domains'])
            operations = []
            for website in queryset:
                website_domains = [d.name for d in website.domains.all()]
                encrypt_domains = set()
                for domain in domains:
                    if is_valid_domain(domain, website_domains, wildcards):
                        encrypt_domains.add(domain)
                website.encrypt_domains = encrypt_domains
                operations.extend(Operation.create_for_action(website, 'encrypt'))
                modeladmin.log_change(request, website, _("Encrypted!"))
            if not operations:
                messages.error(request, _("No backend operation has been executed."))
            else:
                logs = Operation.execute(operations)
                helpers.message_user(request, logs)
                live_lineages = read_live_lineages(logs)
                errors = 0
                successes = 0
                no_https = 0
                for website in queryset:
                    try:
                        configure_cert(website, live_lineages)
                    except LookupError:
                        errors += 1
                        messages.error(request, _("No lineage found for website %s") % website.name)
github glic3rinu / django-orchestra / orchestra / contrib / resources / tasks.py View on Github external
# TODO async=True only when running with celery
        # monitor.request.id
        logs += Operation.execute(monitorings, async=async)
    
    kwargs = {'id__in': ids} if ids else {}
    # Update used resources and trigger resource exceeded and revovery
    triggers = []
    model = resource.content_type.model_class()
    for obj in model.objects.filter(**kwargs):
        data, __ = ResourceData.get_or_create(obj, resource)
        data.update()
        if not resource.disable_trigger:
            a = data.used
            b = data.allocated
            if data.used > (data.allocated or 0):
                op = Operation(backend, obj, Operation.EXCEEDED)
                triggers.append(op)
            elif data.used < (data.allocated or 0):
                op = Operation(backend, obj, Operation.RECOVERY)
                triggers.append(op)
    Operation.execute(triggers)
    return logs
github glic3rinu / django-orchestra / orchestra / contrib / systemusers / validators.py View on Github external
def validate_paths_exist(user, paths):
    operations = []
    user.paths_to_validate = paths
    operations.extend(Operation.create_for_action(user, 'validate_paths_exist'))
    logs = Operation.execute(operations)
    stderr = '\n'.join([log.stderr for log in logs])
    if 'path does not exists' in stderr:
        raise ValidationError(stderr)
github glic3rinu / django-orchestra / orchestra / contrib / orchestration / manager.py View on Github external
if action in backend_cls.actions:
            if backend_cls.is_main(instance):
                instances = [(instance, action)]
            else:
                for candidate in backend_cls.get_related(instance):
                    if candidate.__class__.__name__ == 'ManyRelatedManager':
                        if 'pk_set' in kwargs:
                            # m2m_changed signal
                            candidates = kwargs['model'].objects.filter(pk__in=kwargs['pk_set'])
                        else:
                            candidates = candidate.all()
                    else:
                        candidates = [candidate]
                    for candidate in candidates:
                        # Check if a delete for candidate is in operations
                        delete_mock = Operation(backend_cls, candidate, Operation.DELETE)
                        if delete_mock not in operations:
                            # related objects with backend.model trigger save()
                            instances.append((candidate, Operation.SAVE))
        for selected, iaction in instances:
            # Maintain consistent state of operations based on save/delete behaviour
            # Prevent creating a deleted selected by deleting existing saves
            if iaction == Operation.DELETE:
                save_mock = Operation(backend_cls, selected, Operation.SAVE)
                try:
                    operations.remove(save_mock)
                except KeyError:
                    pass
            else:
                update_fields = kwargs.get('update_fields', None)
                if update_fields is not None:
                    # TODO remove this, django does not execute post_save if update_fields=[]...
github glic3rinu / django-orchestra / orchestra / contrib / orchestration / manager.py View on Github external
# m2m_changed signal
                            candidates = kwargs['model'].objects.filter(pk__in=kwargs['pk_set'])
                        else:
                            candidates = candidate.all()
                    else:
                        candidates = [candidate]
                    for candidate in candidates:
                        # Check if a delete for candidate is in operations
                        delete_mock = Operation(backend_cls, candidate, Operation.DELETE)
                        if delete_mock not in operations:
                            # related objects with backend.model trigger save()
                            instances.append((candidate, Operation.SAVE))
        for selected, iaction in instances:
            # Maintain consistent state of operations based on save/delete behaviour
            # Prevent creating a deleted selected by deleting existing saves
            if iaction == Operation.DELETE:
                save_mock = Operation(backend_cls, selected, Operation.SAVE)
                try:
                    operations.remove(save_mock)
                except KeyError:
                    pass
            else:
                update_fields = kwargs.get('update_fields', None)
                if update_fields is not None:
                    # TODO remove this, django does not execute post_save if update_fields=[]...
                    # Maybe open a ticket at Djangoproject ?
                    # INITIAL INTENTION: "update_fields=[]" is a convention for explicitly executing backend
                    # i.e. account.disable()
                    if update_fields != []:
                        execute = False
                        for field in update_fields:
                            if field not in backend_cls.ignore_fields: