Exemplo n.º 1
0
 def delete_field(self, request, **kwargs):
     cur_obj = StaticAssetFieldValue.objects.get(Q(pk=kwargs["pk"]))
     can_delete_answer = can_delete_obj(cur_obj)
     if can_delete_answer:
         cur_obj.delete()
         return Response(status=status.HTTP_204_NO_CONTENT)
     else:
         raise ValueError(can_delete_answer.msg)
Exemplo n.º 2
0
 def delete(self, request, *args, **kwargs):
     # just be careful
     cur_obj = self.model.objects.get(Q(pk=kwargs["pk"]))
     can_delete_answer = can_delete_obj(cur_obj, logger)
     if can_delete_answer:
         cur_obj.delete()
         return Response(status=status.HTTP_204_NO_CONTENT)
     else:
         raise ValueError(can_delete_answer.msg)
Exemplo n.º 3
0
 def delete_entry(self, request, **kwargs):
     dvs_entry = dvs_allowed_name.objects.get(Q(pk=kwargs["pk"]))
     can_delete_answer = can_delete_obj(dvs_entry, logger)
     if can_delete_answer:
         dvs_entry.delete()
     else:
         raise ValidationError("cannot delete: {}".format(
             logging_tools.get_plural(
                 "reference", len(can_delete_answer.related_objects))))
     return Response(status=status.HTTP_204_NO_CONTENT)
Exemplo n.º 4
0
    def delete_field(self, request, **kwargs):
        _ = request
        from initat.cluster.backbone.models import StaticAssetFieldValue
        from initat.cluster.backbone.models.functions import can_delete_obj

        cur_obj = StaticAssetFieldValue.objects.get(pk=kwargs["pk"])
        can_delete_answer = can_delete_obj(cur_obj)
        if can_delete_answer:
            from rest_framework import status
            from rest_framework.response import Response
            cur_obj.delete()
            return Response(status=status.HTTP_204_NO_CONTENT)
        else:
            raise ValueError(can_delete_answer.msg)
Exemplo n.º 5
0
 def delete_field(self, request, **kwargs):
     cur_obj = StaticAssetTemplateField.objects.get(Q(pk=kwargs["pk"]))
     can_delete_answer = can_delete_obj(cur_obj)
     if can_delete_answer:
         cur_obj.delete()
         return Response(status=status.HTTP_204_NO_CONTENT)
         # it makes no sense to return something meaningful because the DestroyModelMixin returns
         # a 204 status on successful deletion
         # print "****", "del"
         # print unicode(cur_obj), resp.data
         # if not resp.data:
         #    resp.data = {}
         # resp.data["_messages"] = [u"deleted '%s'" % (unicode(cur_obj))]
         # return resp
     else:
         raise ValueError(can_delete_answer.msg)
Exemplo n.º 6
0
    def delete_field(self, request, **kwargs):
        _ = request
        from initat.cluster.backbone.models import StaticAssetTemplateField
        from initat.cluster.backbone.models.functions import can_delete_obj

        cur_obj = StaticAssetTemplateField.objects.get(pk=kwargs["pk"])
        can_delete_answer = can_delete_obj(cur_obj)
        if can_delete_answer:
            from rest_framework import status
            from rest_framework.response import Response
            cur_obj.delete()
            return Response(status=status.HTTP_204_NO_CONTENT)
            # it makes no sense to return something meaningful because the DestroyModelMixin returns
            # a 204 status on successful deletion
            # print "****", "del"
            # print unicode(cur_obj), resp.data
            # if not resp.data:
            #    resp.data = {}
            # resp.data["_messages"] = [u"deleted '%s'" % (unicode(cur_obj))]
            # return resp
        else:
            raise ValueError(can_delete_answer.msg)
Exemplo n.º 7
0
    def post(self, request):
        # returns:
        # - related_objs: {obj_ok : [related_obj_info] } for objects which have related objects
        # - deletable_objects: [obj_pk]
        _post = request.POST
        obj_pks = json.loads(_post.get("obj_pks"))
        model = getattr(initat.cluster.backbone.models, _post.get("model"))

        objs_to_delete = model.objects.filter(pk__in=obj_pks)

        if len(objs_to_delete) < len(obj_pks):
            request.xml_response.error("Could not find all objects to delete.")
            logger.warn("To delete: {}; found only: {}".format(
                obj_pks, [o.pk for o in objs_to_delete]))

        related_objects_info = {}
        deletable_objects = []
        # import time
        for obj_to_delete in objs_to_delete:
            # a = time.time()

            can_delete_answer = can_delete_obj(obj_to_delete, logger)
            # print 'can del took ', time.time() - a, bool(can_delete_answer), len(can_delete_answer.related_objects)
            if can_delete_answer:
                deletable_objects.append(obj_to_delete.pk)
            else:
                info = []
                # there are django related objects, which describe the fields that are related
                # and there are referenced objects, which are the actual db objects having these fields
                for related_object in can_delete_answer.related_objects:
                    referenced_objects_list = []
                    refs_of_refs = set()
                    for referenced_object in related_object.ref_list:
                        referenced_objects_list.append({
                            k: v
                            for (k,
                                 v) in referenced_object.__dict__.iteritems()
                            if k != '_state'
                        })
                        refs_of_refs.update(
                            get_related_models(referenced_object, detail=True))

                    info.append({
                        'model':
                        related_object.model._meta.object_name,
                        'model_verbose_name':
                        related_object.model._meta.verbose_name.capitalize(),
                        'field_name':
                        related_object.field.name,
                        'field_verbose_name':
                        related_object.field.verbose_name.capitalize(),
                        'null':
                        related_object.field.null,
                        'objects': {
                            'num_refs_of_refs': len(refs_of_refs),
                            'list': referenced_objects_list,
                        },
                    })
                related_objects_info[obj_to_delete.pk] = info
                # print 'build 2nd level rel list', time.time() - a
            # print 'obj', obj_pk, ' took ', time.time() - a

        # json can't deal with datetime, django formatter doesn't have nice dates
        def formatter(x):
            if isinstance(x, datetime.datetime):
                return x.strftime("%Y-%m-%d %H:%M")
            elif isinstance(x, datetime.date):
                # NOTE: datetime is instance of date, so check datetime first
                return x.isoformat()
            else:
                return x

        request.xml_response['related_objects'] = json.dumps(
            related_objects_info, default=formatter)
        request.xml_response['deletable_objects'] = json.dumps(
            deletable_objects)
Exemplo n.º 8
0
    def post(self, request):
        from initat.cluster.backbone.models.functions import can_delete_obj, get_related_models
        # returns:
        # - related_objs: {obj_ok : [related_obj_info] } for objects which have related objects
        # - deletable_objects: [obj_pk]
        _post = request.POST
        _start_time = time.time()
        obj_pks = json.loads(_post.get("obj_pks"))
        model = apps.get_model("backbone", _post.get("model_name"))

        objs_to_delete = model.objects.filter(pk__in=obj_pks)

        if len(objs_to_delete) < len(obj_pks):
            request.xml_response.error("Could not find all objects to delete.")
            logger.warning(
                "To delete: {}; found only: {}".format(
                    obj_pks,
                    [o.pk for o in objs_to_delete]
                )
            )

        related_objects_info = {}
        deletable_objects = []
        # import time
        for obj_to_delete in objs_to_delete:
            # a = time.time()

            can_delete_answer = can_delete_obj(obj_to_delete, logger)
            # print 'can del took ', time.time() - a, bool(can_delete_answer), len(can_delete_answer.related_objects)
            if can_delete_answer:  # or True:
                deletable_objects.append(obj_to_delete.pk)
            else:
                info = []
                # there are django related objects, which describe the fields that are related
                # and there are referenced objects, which are the actual db objects having these fields
                for related_object in can_delete_answer.related_objects:
                    referenced_objects_list = []
                    refs_of_refs = set()
                    for referenced_object in related_object.ref_list:
                        # add simple representations of referenced objects
                        # ignore all fields starting with underscore '_' (for example '_state')
                        referenced_objects_list.append(
                            {
                                k: v for (k, v) in referenced_object.__dict__.items() if not k.startswith("_")
                            }
                        )
                        refs_of_refs.update(get_related_models(referenced_object, simple_tuples=True))
                    # print("*", refs_of_refs)

                    info.append(
                        {
                            'model': related_object.model._meta.object_name,
                            'model_verbose_name': related_object.model._meta.verbose_name.capitalize(),
                            'related_model': related_object.related_model._meta.object_name,
                            'related_model_verbose_name': related_object.related_model._meta.verbose_name.capitalize(),
                            'field_name': related_object.field.name,
                            'field_verbose_name': related_object.field.verbose_name.capitalize(),
                            'null': related_object.field.null,
                            'objects': {
                                'num_refs_of_refs': len(refs_of_refs),
                                'list': referenced_objects_list,
                            },
                        }
                    )
                related_objects_info[obj_to_delete.pk] = {
                    "list": info,
                }
                # print 'build 2nd level rel list', time.time() - a
            # print 'obj', obj_pk, ' took ', time.time() - a
        _end_time = time.time()

        # json can't deal with datetime, django formatter doesn't have nice dates
        def formatter(val):
            if isinstance(val, datetime.datetime):
                return val.strftime("%Y-%m-%d %H:%M")
            elif isinstance(val, datetime.date):
                # NOTE: datetime is instance of date, so check datetime first
                return val.isoformat()
            else:
                return val
        request.xml_response['related_objects'] = json.dumps(
            related_objects_info, default=formatter
        )
        request.xml_response['deletable_objects'] = json.dumps(
            deletable_objects
        )
        request.xml_response["delete_info"] = json.dumps(
            {
                "runtime": _end_time - _start_time,
            }
        )
Exemplo n.º 9
0
    def post(self, request):
        _post = request.POST
        c_dict = json.loads(_post.get("change_dict", ""))
        pk_list = json.loads(_post.get("device_list"))
        if c_dict.get("delete", False):
            num_deleted = 0
            error_msgs = []
            for pk in pk_list:
                obj = device.objects.get(Q(pk=pk))
                can_delete_answer = can_delete_obj(obj, logger)
                if can_delete_answer:
                    obj.delete()
                    num_deleted += 1
                else:
                    error_msgs.append((obj.name, can_delete_answer.msg))
            if num_deleted > 0:
                request.xml_response.info("delete {}".format(
                    logging_tools.get_plural("device", num_deleted)))
            for pk, msg in error_msgs:
                request.xml_response.error("Failed to delete {}: {}".format(
                    pk, msg))
        else:
            def_dict = {
                "bootserver": None,
                "monitor_server": None,
                "enabled": False,
                "store_rrd_data": False,
                "enable_perfdata": False,
            }
            # build change_dict
            c_dict = {
                key[7:]: c_dict.get(key[7:], def_dict.get(key[7:], None))
                for key in c_dict.iterkeys()
                if key.startswith("change_") and c_dict[key]
            }
            # resolve foreign keys
            res_c_dict = {
                key: {
                    "device_group": device_group,
                    "device_class": DeviceClass,
                    "domain_tree_node": domain_tree_node,
                    "bootserver": device,
                    "monitor_server": device,
                }[key].objects.get(Q(
                    pk=value)) if type(value) == int else value
                for key, value in c_dict.iteritems()
            }
            logger.info("change_dict has {}".format(
                logging_tools.get_plural("key", len(res_c_dict))))
            for key in sorted(res_c_dict):
                if key == "root_passwd":
                    logger.info(" {}: {}".format(key, "****"))
                else:
                    logger.info(" {}: {}".format(key,
                                                 unicode(res_c_dict.get(key))))
            dev_changes = 0
            changes_json = []
            for cur_dev in device.objects.filter(Q(pk__in=pk_list)):
                changed = False
                for c_key, c_value in res_c_dict.iteritems():
                    if getattr(cur_dev, c_key) != c_value:
                        if c_key == "root_passwd":
                            c_value = cur_dev.crypt(c_value)
                            if c_value:
                                setattr(cur_dev, c_key, c_value)
                                changed = True
                        else:
                            setattr(cur_dev, c_key, c_value)
                            changes_json.append({
                                "device": cur_dev.pk,
                                "attribute": c_key,
                                "value": c_dict[c_key],
                            })
                            changed = True

                if changed:
                    cur_dev.save()
                    dev_changes += 1
            request.xml_response["changed"] = dev_changes
            request.xml_response["json_changes"] = json.dumps(changes_json)
            request.xml_response.info("changed settings of {}".format(
                logging_tools.get_plural("device", dev_changes)))
Exemplo n.º 10
0
    def handle_deletion(obj_pk, model, delete_strategies, cur_inst):
        model = getattr(initat.cluster.backbone.models, model)
        try:
            obj_to_delete = model.objects.get(pk=obj_pk)
        except model.DoesNotExist:
            cur_inst.log(
                "Object with pk {} from model {} does not exist any more".
                format(obj_pk, model))
        else:
            cur_inst.log("Deleting {} ({}; pk:{})".format(
                obj_to_delete, model, obj_pk))

            start_time = time.time()
            if delete_strategies:
                # have to do elaborate deletion of references
                delete_strategy_list = json.loads(delete_strategies)

                delete_strategies = {}
                for entry in delete_strategy_list:
                    delete_strategies[(
                        entry['model'],
                        entry['field_name'])] = entry['selected_action']

                # get references again and apply the selected strategy for each according to delete_strategies
                can_delete_answer = can_delete_obj(obj_to_delete)
                for rel_obj in can_delete_answer.related_objects:
                    dict_key = (rel_obj.model._meta.object_name,
                                rel_obj.field.name)
                    strat = delete_strategies.get(dict_key, None)
                    if strat == "set null":
                        cur_inst.log("set null on {} ".format(rel_obj))
                        for db_obj in rel_obj.ref_list:
                            setattr(db_obj, rel_obj.field.name, None)
                            db_obj.save()
                    elif strat == "delete cascade":
                        for db_obj in rel_obj.ref_list:
                            cur_inst.log("delete cascade for {} ({})".format(
                                db_obj, rel_obj))
                            db_obj.delete()
                    elif strat == "delete object":
                        cur_inst.log("delete object on {}".format(rel_obj))
                        for db_obj in rel_obj.ref_list:
                            db_obj.delete()
                    else:
                        raise ValueError(
                            "Invalid strategy for {}: {}; available strategies: {}"
                            .format(dict_key, strat, delete_strategies))

                cur_inst.log("all refs have been deleted")
                can_delete_answer_after = can_delete_obj(obj_to_delete)
                if can_delete_answer_after:
                    # all references cleared
                    obj_to_delete.delete()
                else:
                    cur_inst.log(can_delete_answer_after.msg)

            else:
                # can delete obj right away
                obj_to_delete.delete()

            cur_inst.log("Deletion finished in {} seconds".format(time.time() -
                                                                  start_time))
Exemplo n.º 11
0
    def handle_deletion(obj_pk, model, delete_strategies, cur_inst):
        # delete strategies is a json-encoded list
        model = apps.get_model("backbone", model)
        try:
            obj_to_delete = model.objects.get(pk=obj_pk)
        except model.DoesNotExist:
            cur_inst.log(
                "Object with pk {} from model {} does not exist any more".
                format(obj_pk, model))
        else:
            _bgj = create_bg_job(
                global_config["SERVER_IDX"],
                None,
                "delete object '{}'".format(str(obj_to_delete)),
                "delete",
                None,
                state=BackgroundJobState.pending,
                timeout=60 * 60,
            )
            # just for testing
            # time.sleep(30)
            cur_inst.log("Deleting {} ({}; pk:{})".format(
                obj_to_delete, model, obj_pk))

            start_time = time.time()
            if delete_strategies:
                # have to do elaborate deletion of references
                delete_strategy_list = json.loads(delete_strategies)

                delete_strategies = {}
                for entry in delete_strategy_list:
                    delete_strategies[(
                        entry['model'],
                        entry['field_name'])] = entry['selected_action']

                # get references again and apply the selected strategy for each according to delete_strategies
                can_delete_answer = can_delete_obj(obj_to_delete)
                for rel_obj in can_delete_answer.related_objects:
                    dict_key = (rel_obj.model._meta.object_name,
                                rel_obj.field.name)
                    strat = delete_strategies.get(dict_key, None)
                    if strat == "set null":
                        cur_inst.log("set null on {} ".format(rel_obj))
                        for db_obj in rel_obj.ref_list:
                            setattr(db_obj, rel_obj.field.name, None)
                            db_obj.save()
                    elif strat == "delete cascade":
                        for db_obj in rel_obj.ref_list:
                            cur_inst.log("delete cascade for {} ({})".format(
                                db_obj, rel_obj))
                            db_obj.delete()
                    elif strat == "delete object":
                        cur_inst.log("delete object on {}".format(rel_obj))
                        for db_obj in rel_obj.ref_list:
                            db_obj.delete()
                    else:
                        raise ValueError(
                            "Invalid strategy for {}: {}; available strategies: {}"
                            .format(dict_key, strat, delete_strategies))

                cur_inst.log("all refs have been deleted")
                can_delete_answer_after = can_delete_obj(obj_to_delete)
                if can_delete_answer_after:
                    # all references cleared
                    obj_to_delete.delete()
                else:
                    cur_inst.log(can_delete_answer_after.msg)

            else:
                # can delete obj right away
                obj_to_delete.delete()

            _bgj.set_state(BackgroundJobState.done)
            cur_inst.log("Deletion finished in {} seconds".format(time.time() -
                                                                  start_time))