Пример #1
0
def incident_update(incident_update_id, user_id):

    incident_update_notification_module = IncidentUpdateNotificationModule()
    subscriber_module = SubscriberModule()
    task_module = TaskModule()

    for subscriber in subscriber_module.get_iterator():
        notification = incident_update_notification_module.is_subscriber_notified(
            incident_update_id, subscriber.id)
        if notification:
            # Send notification.id to the queue again
            task_module.delay("notify_subscriber",
                              {"notification_id": notification.id}, user_id)

        else:
            # Create new notification and send to queue
            new_notification = incident_update_notification_module.insert_one({
                "status":
                "pending",
                "incident_update_id":
                incident_update_id,
                "subscriber_id":
                subscriber.id
            })
            if new_notification:
                # Send new_notification.id to the Queue
                task_module.delay("notify_subscriber",
                                  {"notification_id": new_notification.id},
                                  user_id)

    return {"status": "passed", "result": "{}", "notify_type": "passed"}
Пример #2
0
 def __init__(self):
     self.__acl = ACL()
     self.__option_entity = OptionEntity()
     self.__user_entity = UserEntity()
     self.__notification_entity = NotificationEntity()
     self.__register_request_entity = RegisterRequestEntity()
     self.__task_core = TaskCore()
Пример #3
0
class IncidentUpdatesNotify(View):

    __request = None
    __response = None
    __helpers = None
    __form = None
    __logger = None
    __user_id = None
    __incident_update = None
    __task = None
    __notification = None
    __subscriber = None
    __correlation_id = None

    def __init__(self):
        self.__request = Request()
        self.__response = Response()
        self.__helpers = Helpers()
        self.__form = Form()
        self.__incident_update = IncidentUpdateModule()
        self.__task = Task_Module()
        self.__notification = NotificationModule()
        self.__subscriber = SubscriberModule()
        self.__logger = self.__helpers.get_logger(__name__)
        self.__form.add_validator(ExtraRules())

    @allow_if_authenticated
    def post(self, request, incident_id, update_id):

        self.__correlation_id = request.META["X-Correlation-ID"] if "X-Correlation-ID" in request.META else ""
        self.__user_id = request.user.id

        task = self.__task.delay("incident_update", {
            "incident_update_id": update_id,
            "user_id": self.__user_id
        }, self.__user_id)

        result = False

        if task:
            result = self.__notification.create_notification({
                "highlight": "Incident Update",
                "notification": "notifying subscribers with the incident update",
                "url": "#",
                "type": NotificationModule.PENDING,
                "delivered": False,
                "user_id": self.__user_id,
                "task_id": task.id
            })

        if task and result:
            return JsonResponse(self.__response.send_private_success([{
                "type": "success",
                "message": _("Notification delivery started successfully.")
            }], {}, self.__correlation_id))
        else:
            return JsonResponse(self.__response.send_private_failure([{
                "type": "error",
                "message": _("Error! Something goes wrong while starting delivery.")
            }], {}, self.__correlation_id))
Пример #4
0
 def __init__(self):
     self.__request = Request()
     self.__response = Response()
     self.__helpers = Helpers()
     self.__form = Form()
     self.__host_module = Host_Module()
     self.__task_module = Task_Module()
     self.__notification_module = Notification_Module()
     self.__logger = self.__helpers.get_logger(__name__)
Пример #5
0
 def __init__(self):
     self.__request = Request()
     self.__response = Response()
     self.__helpers = Helpers()
     self.__form = Form()
     self.__incident_update = IncidentUpdateModule()
     self.__task = Task_Module()
     self.__notification = NotificationModule()
     self.__subscriber = SubscriberModule()
     self.__logger = self.__helpers.get_logger(__name__)
     self.__form.add_validator(ExtraRules())
Пример #6
0
    def check_workers(self):
        errors = []
        task_core = TaskCore()
        task_core.delete_old_tasks_by_executor(
            "app.tasks.ping.ping",
            int(os.getenv("DELETE_PING_TASK_AFTER_MINUTES", 1)))
        tasks = task_core.get_many_by_executor("app.tasks.ping.ping")

        for task in tasks:
            if task.status != "passed" and task.created_at < make_aware(
                    datetime.now() - timedelta(seconds=int(
                        os.getenv("WORKERS_CALM_DOWN_SECONDS", 30)))):
                errors.append(
                    _("Error: celery workers not performing well or down.") %
                    {"task_id": task.id})

        if len(tasks) == 0:
            try:
                task_core.delay("ping", {"text": "PONG"}, None)
            except Exception as e:
                errors.append(
                    _("Error while creating a ping task: %(error)s") %
                    {"error": str(e)})

        return errors
Пример #7
0
def incident_update(incident_update_id, user_id, correlation_id=""):
    logger = Helpers().get_logger(__name__)

    logger.info(
        _("Worker started processing incident_update task with parameters %(parameters)s {'correlationId':'%(correlationId)s'}"
          ) % {
              "parameters": json.dumps({}),
              "correlationId": correlation_id
          })

    incident_update_notification_module = IncidentUpdateNotificationModule()
    subscriber_module = SubscriberModule()
    task_module = TaskModule()

    for subscriber in subscriber_module.get_iterator():
        notification = incident_update_notification_module.is_subscriber_notified(
            incident_update_id, subscriber.id)
        if notification:
            # Send notification.id to the queue again
            task_module.delay("notify_subscriber",
                              {"notification_id": notification.id}, user_id)

        else:
            # Create new notification and send to queue
            new_notification = incident_update_notification_module.insert_one({
                "status":
                "pending",
                "incident_update_id":
                incident_update_id,
                "subscriber_id":
                subscriber.id
            })
            if new_notification:
                # Send new_notification.id to the Queue
                task_module.delay("notify_subscriber",
                                  {"notification_id": new_notification.id},
                                  user_id)

    return {"status": "passed", "result": "{}", "notify_type": "passed"}
Пример #8
0
    def __init__(self):
        self.__reset_request_entity = ResetRequestEntity()
        self.__option_entity = OptionEntity()
        self.__user_entity = UserEntity()
        self.__task_core = TaskCore()

        messages_count_option = self.__option_entity.get_one_by_key(
            "reset_mails_messages_count")
        reset_expire_option = self.__option_entity.get_one_by_key(
            "reset_mails_expire_after")

        if messages_count_option:
            self.__messages_count_option = int(messages_count_option.value)

        if reset_expire_option:
            self.__reset_expire_option = int(reset_expire_option.value)
Пример #9
0
class User():

    __notification_entity = None
    __option_entity = None
    __user_entity = None
    __acl = None
    __register_request_entity = None
    __task_core = None
    __register_expire_option = 24

    def __init__(self):
        self.__acl = ACL()
        self.__option_entity = OptionEntity()
        self.__user_entity = UserEntity()
        self.__notification_entity = NotificationEntity()
        self.__register_request_entity = RegisterRequestEntity()
        self.__task_core = TaskCore()

    def username_used(self, username):
        return False if self.__user_entity.get_one_by_username(
            username) is False else True

    def email_used(self, email):
        return False if self.__user_entity.get_one_by_email(
            email) is False else True

    def username_used_elsewhere(self, user_id, username):
        user = self.__user_entity.get_one_by_username(username)

        if user is False or user.id == user_id:
            return False

        return True

    def email_used_elsewhere(self, user_id, email):
        user = self.__user_entity.get_one_by_email(email)

        if user is False or user.id == user_id:
            return False

        return True

    def get_one_by_id(self, id):
        user = self.__user_entity.get_one_by_id(id)

        if not user:
            return False

        return {
            "id": user.id,
            "username": user.username,
            "first_name": user.first_name,
            "last_name": user.last_name,
            "email": user.email,
            "role": "admin" if user.is_superuser else "user",
        }

    def insert_one(self, user):
        return self.__user_entity.insert_one(user)

    def create_user(self, user_data):
        status = True

        user = self.__user_entity.insert_one({
            "username":
            user_data["username"],
            "email":
            user_data["email"],
            "password":
            user_data["password"],
            "first_name":
            user_data["first_name"],
            "last_name":
            user_data["last_name"],
            "is_superuser":
            False,
            "is_active":
            True,
            "is_staff":
            False
        })

        if user is not False:
            self.__acl.add_role_to_user("normal_user", user.id)

        status &= (user is not False)

        return status

    def update_one_by_id(self, id, user_data):
        return self.__user_entity.update_one_by_id(id, user_data)

    def check_register_request(self, token):
        request = self.__register_request_entity.get_one_by_token(token)
        if request is not False and timezone.now() < request.expire_at:
            return True
        return False

    def get_register_request_by_token(self, token):
        return self.__register_request_entity.get_one_by_token(token)

    def delete_register_request_by_token(self, token):
        return self.__register_request_entity.delete_one_by_token(token)

    def delete_register_request_by_email(self, email):
        return self.__register_request_entity.delete_one_by_email(email)

    def create_register_request(self, email, role):
        request = self.__register_request_entity.insert_one({
            "email":
            email,
            "payload":
            json.dumps({"role": role}),
            "expire_after":
            self.__register_expire_option
        })
        return request.token if request is not False else False

    def send_register_request_message(self, email, token):

        app_name = self.__option_entity.get_value_by_key("app_name")
        app_email = self.__option_entity.get_value_by_key("app_email")
        app_url = self.__option_entity.get_value_by_key("app_url")

        return self.__task_core.delay(
            "register_request_email", {
                "app_name": app_name,
                "app_email": app_email,
                "app_url": app_url,
                "recipient_list": [email],
                "token": token,
                "subject": _("%s Signup Invitation") % (app_name),
                "template": "mails/register_invitation.html",
                "fail_silently": False
            }, 1)

    def count_all(self):
        return self.__user_entity.count_all()

    def get_all(self, offset=None, limit=None):
        return self.__user_entity.get_all(offset, limit)

    def delete_one_by_id(self, id):
        return self.__user_entity.delete_one_by_id(id)
Пример #10
0
class ForgotPassword():

    __reset_expire_option = 24
    __messages_count_option = 5

    def __init__(self):
        self.__reset_request_entity = ResetRequestEntity()
        self.__option_entity = OptionEntity()
        self.__user_entity = UserEntity()
        self.__task_core = TaskCore()

        messages_count_option = self.__option_entity.get_one_by_key(
            "reset_mails_messages_count")
        reset_expire_option = self.__option_entity.get_one_by_key(
            "reset_mails_expire_after")

        if messages_count_option:
            self.__messages_count_option = int(messages_count_option.value)

        if reset_expire_option:
            self.__reset_expire_option = int(reset_expire_option.value)

    def check_email(self, email):
        return True if self.__user_entity.get_one_by_email(
            email) is not False else False

    def reset_request_exists(self, email):
        return self.__reset_request_entity.get_one_by_email(email)

    def is_spam(self, request):
        if request.messages_count >= self.__messages_count_option and timezone.now(
        ) < request.expire_at:
            return True
        return False

    def update_request(self, request):

        # Delete Old Request
        self.__reset_request_entity.delete_one_by_id(request.id)

        # Create a Fresh Request
        if timezone.now() > request.expire_at:
            return self.create_request(request.email)

        # Create from the Old Request
        request = self.__reset_request_entity.insert_one({
            "email":
            request.email,
            "expire_at":
            request.expire_at,
            "messages_count":
            request.messages_count + 1
        })
        return request.token if request is not False else False

    def create_request(self, email):
        request = self.__reset_request_entity.insert_one({
            "email": email,
            "expire_after": self.__reset_expire_option,
            "messages_count": 0
        })
        return request.token if request is not False else False

    def send_message(self, email, token):

        app_name = self.__option_entity.get_value_by_key("app_name")
        app_email = self.__option_entity.get_value_by_key("app_email")
        app_url = self.__option_entity.get_value_by_key("app_url")
        user = self.__user_entity.get_one_by_email(email)

        return self.__task_core.delay(
            "forgot_password_email", {
                "app_name": app_name,
                "app_email": app_email,
                "app_url": app_url,
                "recipient_list": [email],
                "token": token,
                "subject": _("%s Password Reset") % (app_name),
                "template": "mails/reset_password.html",
                "fail_silently": False
            }, user.id)
Пример #11
0
class Tag_Image_By_Id(View):

    __request = None
    __response = None
    __helpers = None
    __form = None
    __logger = None
    __user_id = None
    __host_id = None
    __host_module = None
    __task_module = None
    __notification_module = None

    def __init__(self):
        self.__request = Request()
        self.__response = Response()
        self.__helpers = Helpers()
        self.__form = Form()
        self.__host_module = Host_Module()
        self.__task_module = Task_Module()
        self.__notification_module = Notification_Module()
        self.__logger = self.__helpers.get_logger(__name__)

    def post(self, request, host_id):

        self.__user_id = request.user.id
        self.__host_id = host_id

        self.__request.set_request(request)
        request_data = self.__request.get_request_data("post", {
            "long_id": "",
            "repository": "",
            "tag": "",
            "force": ""
        })

        self.__form.add_inputs({
            'long_id': {
                'value': request_data["long_id"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {}
            },
            'repository': {
                'value': request_data["repository"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {}
            },
            'tag': {
                'value': request_data["tag"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {}
            },
            'force': {
                'value': request_data["force"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {}
            }
        })

        self.__form.process()

        if not self.__form.is_passed():
            return JsonResponse(
                self.__response.send_private_failure(
                    self.__form.get_errors(with_type=True)))

        if not self.__host_module.user_owns(self.__host_id, self.__user_id):
            return JsonResponse(
                self.__response.send_private_failure([{
                    "type":
                    "error",
                    "message":
                    _("Error! Invalid Request.")
                }]))

        _long_id = self.__form.get_input_value("long_id")
        _repository = self.__form.get_input_value("repository")
        _tag = self.__form.get_input_value("tag")
        _force = self.__form.get_input_value("force")

        task = self.__task_module.delay(
            "tag_image_by_id", {
                "host_id": self.__host_id,
                "long_id": _long_id,
                "repository": _repository,
                "tag": _tag,
                "force": _force
            }, self.__user_id)

        if task:

            self.__notification_module.create_notification({
                "highlight":
                "",
                "notification":
                _("Tag docker image as %s:%s") % (_repository, _tag),
                "url":
                "#",
                "type":
                Notification_Module.PENDING,
                "delivered":
                False,
                "user_id":
                self.__user_id,
                "host_id":
                self.__host_id,
                "task_id":
                task.id
            })

            return JsonResponse(
                self.__response.send_private_success([{
                    "type":
                    "success",
                    "message":
                    _("Request is in progress!")
                }]))

        else:
            return JsonResponse(
                self.__response.send_private_failure([{
                    "type":
                    "error",
                    "message":
                    _("Error! Something goes wrong while creating request.")
                }]))
Пример #12
0
class Prune_All_Unused_Images(View):

    __request = None
    __response = None
    __helpers = None
    __form = None
    __logger = None
    __user_id = None
    __host_id = None
    __host_module = None
    __task_module = None
    __notification_module = None

    def __init__(self):
        self.__request = Request()
        self.__response = Response()
        self.__helpers = Helpers()
        self.__form = Form()
        self.__host_module = Host_Module()
        self.__task_module = Task_Module()
        self.__notification_module = Notification_Module()
        self.__logger = self.__helpers.get_logger(__name__)

    def post(self, request, host_id):

        self.__user_id = request.user.id
        self.__host_id = host_id

        if not self.__host_module.user_owns(self.__host_id, self.__user_id):
            return JsonResponse(
                self.__response.send_private_failure([{
                    "type":
                    "error",
                    "message":
                    _("Error! Invalid Request.")
                }]))

        task = self.__task_module.delay("prune_all_unused_images",
                                        {"host_id": self.__host_id},
                                        self.__user_id)

        if task:

            self.__notification_module.create_notification({
                "highlight":
                "",
                "notification":
                _("prune all unused docker images"),
                "url":
                "#",
                "type":
                Notification_Module.PENDING,
                "delivered":
                False,
                "user_id":
                self.__user_id,
                "host_id":
                self.__host_id,
                "task_id":
                task.id
            })

            return JsonResponse(
                self.__response.send_private_success([{
                    "type":
                    "success",
                    "message":
                    _("Request is in progress!")
                }]))

        else:
            return JsonResponse(
                self.__response.send_private_failure([{
                    "type":
                    "error",
                    "message":
                    _("Error! Something goes wrong while creating request.")
                }]))
Пример #13
0
class Pull_Image(View):

    __request = None
    __response = None
    __helpers = None
    __form = None
    __logger = None
    __user_id = None
    __host_id = None
    __host_module = None
    __task_module = None
    __notification_module = None

    def __init__(self):
        self.__request = Request()
        self.__response = Response()
        self.__helpers = Helpers()
        self.__form = Form()
        self.__host_module = Host_Module()
        self.__task_module = Task_Module()
        self.__notification_module = Notification_Module()
        self.__logger = self.__helpers.get_logger(__name__)

    def post(self, request, host_id):

        self.__user_id = request.user.id
        self.__host_id = host_id

        self.__request.set_request(request)
        request_data = self.__request.get_request_data("post",
                                                       {"image_name": ""})

        self.__form.add_inputs({
            'image_name': {
                'value': request_data["image_name"],
                'sanitize': {
                    'strip': {}
                },
                'validate': {
                    'not_empty': {
                        'error': _('Error! docker image is required!')
                    },
                    'length_between': {
                        'param': [1, 100],
                        'error': _('Error! a valid docker image is required!')
                    }
                }
            }
        })

        self.__form.process()

        if not self.__form.is_passed():
            return JsonResponse(
                self.__response.send_private_failure(
                    self.__form.get_errors(with_type=True)))

        if not self.__host_module.user_owns(self.__host_id, self.__user_id):
            return JsonResponse(
                self.__response.send_private_failure([{
                    "type":
                    "error",
                    "message":
                    _("Error! Invalid Request.")
                }]))

        _image_name = self.__form.get_input_value("image_name")

        if ":" not in _image_name:
            _image_name = "%s:latest" % _image_name

        task = self.__task_module.delay("pull_image", {
            "host_id": self.__host_id,
            "image_name": _image_name
        }, self.__user_id)

        if task:

            self.__notification_module.create_notification({
                "highlight":
                "",
                "notification":
                "pulling docker image %s" % _image_name,
                "url":
                "#",
                "type":
                Notification_Module.PENDING,
                "delivered":
                False,
                "user_id":
                self.__user_id,
                "host_id":
                self.__host_id,
                "task_id":
                task.id
            })

            return JsonResponse(
                self.__response.send_private_success([{
                    "type":
                    "success",
                    "message":
                    _("Request is in progress!")
                }]))

        else:
            return JsonResponse(
                self.__response.send_private_failure([{
                    "type":
                    "error",
                    "message":
                    _("Error! Something goes wrong while creating request.")
                }]))
Пример #14
0
class Build_Image(View):

    __request = None
    __response = None
    __helpers = None
    __form = None
    __logger = None
    __user_id = None
    __host_id = None
    __host_module = None
    __task_module = None
    __notification_module = None

    def __init__(self):
        self.__request = Request()
        self.__response = Response()
        self.__helpers = Helpers()
        self.__form = Form()
        self.__host_module = Host_Module()
        self.__task_module = Task_Module()
        self.__notification_module = Notification_Module()
        self.__logger = self.__helpers.get_logger(__name__)

    def post(self, request, host_id):

        self.__user_id = request.user.id
        self.__host_id = host_id

        self.__request.set_request(request)

        request_data = self.__request.get_request_data("post", {
            "tag": "",
            "dockerfile": "",
            "rm": "",
            "nocache": ""
        })

        self.__form.add_inputs({
            'tag': {
                'value': request_data["tag"],
                'sanitize': {},
                'validate': {}
            },
            'dockerfile': {
                'value': request_data["dockerfile"],
                'sanitize': {},
                'validate': {}
            },
            'rm': {
                'value': request_data["rm"],
                'sanitize': {},
                'validate': {}
            },
            'nocache': {
                'value': request_data["nocache"],
                'sanitize': {},
                'validate': {}
            }
        })

        self.__form.process()

        if not self.__form.is_passed():
            return JsonResponse(
                self.__response.send_private_failure(
                    self.__form.get_errors(with_type=True)))

        if not self.__host_module.user_owns(self.__host_id, self.__user_id):
            return JsonResponse(
                self.__response.send_private_failure([{
                    "type":
                    "error",
                    "message":
                    _("Error! Invalid Request.")
                }]))

        _tag = self.__form.get_input_value("tag")
        _fileobj = self.__form.get_input_value("dockerfile")
        _rm = bool(self.__form.get_input_value("rm") == "1")
        _nocache = bool(self.__form.get_input_value("nocache") == "1")

        task = self.__task_module.delay(
            "build_image", {
                "host_id": self.__host_id,
                "fileobj": _fileobj,
                "tag": _tag,
                "rm": _rm,
                "nocache": _nocache
            }, self.__user_id)

        if task:

            self.__notification_module.create_notification({
                "highlight":
                "",
                "notification":
                "building docker image %s" % _tag,
                "url":
                "#",
                "type":
                Notification_Module.PENDING,
                "delivered":
                False,
                "user_id":
                self.__user_id,
                "host_id":
                self.__host_id,
                "task_id":
                task.id
            })

            return JsonResponse(
                self.__response.send_private_success([{
                    "type":
                    "success",
                    "message":
                    _("Request is in progress!")
                }]))

        else:
            return JsonResponse(
                self.__response.send_private_failure([{
                    "type":
                    "error",
                    "message":
                    _("Error! Something goes wrong while creating request.")
                }]))