Esempio n. 1
0
 def __init__(self):
     self.__request = Request()
     self.__response = Response()
     self.__helpers = Helpers()
     self.__form = Form()
     self.__host_module = Host_Module()
     self.__logger = self.__helpers.get_logger(__name__)
Esempio n. 2
0
class Get_Image(View):

    __request = None
    __response = None
    __helpers = None
    __form = None
    __logger = None
    __user_id = None
    __host_id = None
    __image_id = None
    __host_module = None
    __image_module = None

    def __init__(self):
        self.__request = Request()
        self.__response = Response()
        self.__helpers = Helpers()
        self.__form = Form()
        self.__host_module = Host_Module()
        self.__image_module = Image_Module()
        self.__logger = self.__helpers.get_logger(__name__)

    def get(self, request, host_id, image_id):

        self.__user_id = request.user.id
        self.__host_id = host_id
        self.__image_id = image_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.")
                }]))

        if self.__image_module.set_host(self.__host_id).check_health():
            _image = {'long_id': self.__image_id}
            return JsonResponse(
                self.__response.send_private_success([], {'image': _image}))
        else:
            return JsonResponse(
                self.__response.send_private_failure([{
                    "type":
                    "error",
                    "message":
                    _("Error! Something goes wrong with your host!")
                }], {'image': {}}))
Esempio n. 3
0
class Health_Check(View):

    __request = None
    __response = None
    __helpers = None
    __form = None
    __logger = None
    __user_id = None
    __host_id = None
    __host_module = None
    __status = None

    def __init__(self):
        self.__request = Request()
        self.__response = Response()
        self.__helpers = Helpers()
        self.__form = Form()
        self.__host_module = Host_Module()
        self.__status = Status()
        self.__logger = self.__helpers.get_logger(__name__)

    def get(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.")
                }]))

        health = self.__status.set_host(self.__host_id).ping()

        if health:
            return JsonResponse(
                self.__response.send_private_success([], {"status": "up"}))
        else:
            return JsonResponse(
                self.__response.send_private_success([], {"status": "down"}))
Esempio n. 4
0
class Search_Community_Images(View):

    __request = None
    __response = None
    __helpers = None
    __form = None
    __logger = None
    __user_id = None
    __host_id = None
    __host_module = None
    __image_module = None

    def __init__(self):
        self.__request = Request()
        self.__response = Response()
        self.__helpers = Helpers()
        self.__form = Form()
        self.__host_module = Host_Module()
        self.__image_module = Image_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", {"term": ""})

        self.__form.add_inputs({
            'term': {
                'value': request_data["term"],
                'validate': {
                    'not_empty': {
                        'error': _('Error! Search term is required!')
                    },
                    'length_between': {
                        'param': [1, 100],
                        'error': _('Error! a valid search term 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.")
                }]))

        if self.__image_module.set_host(self.__host_id).check_health():
            result = self.__image_module.search(
                self.__form.get_input_value("term"))
            print(result)
            return JsonResponse(self.__response.send_private_success([], {}))
        else:
            return JsonResponse(
                self.__response.send_private_failure([{
                    "type":
                    "error",
                    "message":
                    _("Error! Something goes wrong with your host!")
                }]))
Esempio n. 5
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.")
                }]))
Esempio n. 6
0
class Get_Images(View):

    __request = None
    __response = None
    __helpers = None
    __form = None
    __logger = None
    __user_id = None
    __host_id = None
    __host_module = None
    __image_module = None

    def __init__(self):
        self.__request = Request()
        self.__response = Response()
        self.__helpers = Helpers()
        self.__form = Form()
        self.__host_module = Host_Module()
        self.__image_module = Image_Module()
        self.__logger = self.__helpers.get_logger(__name__)

    def get(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.")
                }]))

        if self.__image_module.set_host(self.__host_id).check_health():
            _host = self.__host_module.get_one_by_id(host_id)
            return JsonResponse(
                self.__response.send_private_success(
                    [], {
                        'images':
                        self.__format_image(self.__image_module.list(),
                                            host_id, _host.slug)
                    }))
        else:
            return JsonResponse(
                self.__response.send_private_failure([{
                    "type":
                    "error",
                    "message":
                    _("Error! Something goes wrong with your host!")
                }], {'images': []}))

    def __format_image(self, images_list, host_id, host_slug):
        _image_list = []

        for image in images_list:
            date = image["created"].split("T")
            image["created_at"] = date[0]
            image["size"] = image["size"]["MB"]
            _tags = []
            for tag in image["tags"]:
                tag = tag.split(":")
                _tags.append({"name": tag[0], "version": tag[1]})
            image["tags"] = _tags
            image["url"] = reverse("app.web.admin.hosts.view.image",
                                   kwargs={
                                       'host_slug': host_slug,
                                       'image_id': image['long_id']
                                   })
            image["delete_url"] = reverse(
                "app.api.private.v1.admin.action.host.delete_image.endpoint",
                kwargs={'host_id': host_id})
            _image_list.append(image)

        return _image_list
Esempio n. 7
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.")
                }]))
Esempio n. 8
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.")
                }]))
Esempio n. 9
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.")
                }]))
Esempio n. 10
0
class Get_Volumes(View):

    __request = None
    __response = None
    __helpers = None
    __form = None
    __logger = None
    __user_id = None
    __host_id = None
    __volume_id = None
    __host_module = None
    __volume_module = None

    def __init__(self):
        self.__request = Request()
        self.__response = Response()
        self.__helpers = Helpers()
        self.__form = Form()
        self.__host_module = Host_Module()
        self.__volume_module = Volume_Module()
        self.__logger = self.__helpers.get_logger(__name__)

    def get(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.")
                }]))

        if self.__volume_module.set_host(self.__host_id).check_health():
            _host = self.__host_module.get_one_by_id(host_id)
            return JsonResponse(
                self.__response.send_private_success(
                    [], {
                        'volumes':
                        self.__format_volumes(self.__volume_module.list(),
                                              host_id, _host.slug)
                    }))
        else:
            return JsonResponse(
                self.__response.send_private_failure([{
                    "type":
                    "error",
                    "message":
                    _("Error! Something goes wrong with your host!")
                }], {'volumes': []}))

    def __format_volumes(self, volumes_list, host_id, host_slug):
        _volumes_list = []

        for volume in volumes_list:
            date = volume["created"].split("T")
            volume["created_at"] = date[0]
            volume["url"] = "#"
            volume["delete_url"] = "#"
            if volume["short_id"] in volume["name"]:
                volume["name"] = volume["short_id"]
            # volume["url"] = reverse("app.web.admin.hosts.view.volume", kwargs={'host_slug': host_slug, 'volume_id': volume['long_id']})
            # volume["delete_url"] = reverse("app.api.private.v1.admin.action.host.delete_volume.endpoint", kwargs={'host_id': host_id})
            _volumes_list.append(volume)

        return _volumes_list
Esempio n. 11
0
class Get_Networks(View):

    __request = None
    __response = None
    __helpers = None
    __form = None
    __logger = None
    __user_id = None
    __host_id = None
    __network_id = None
    __host_module = None
    __network_module = None

    def __init__(self):
        self.__request = Request()
        self.__response = Response()
        self.__helpers = Helpers()
        self.__form = Form()
        self.__host_module = Host_Module()
        self.__network_module = Network_Module()
        self.__logger = self.__helpers.get_logger(__name__)

    def get(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.")
            }]))

        if self.__network_module.set_host(self.__host_id).check_health():
            _host = self.__host_module.get_one_by_id(host_id)
            return JsonResponse(self.__response.send_private_success([], {
                'networks': self.__format_networks(
                    self.__network_module.list(),
                    host_id,
                    _host.slug
                )
            }))
        else:
            return JsonResponse(self.__response.send_private_failure([{
                "type": "error",
                "message": _(
                    "Error! Something goes wrong with your host!"
                )
            }], {
                'networks': []
            }))

    def __format_networks(self, networks_list, host_id, host_slug):
        _networks_list = []

        for network in networks_list:
            date = network["created"].split("T")
            network["created_at"] = date[0]
            network["url"] = "#"
            network["delete_url"] = "#"
            # network["url"] = reverse("app.web.admin.hosts.view.network", kwargs={'host_slug': host_slug, 'network_id': network['long_id']})
            # network["delete_url"] = reverse("app.api.private.v1.admin.action.host.delete_network.endpoint", kwargs={'host_id': host_id})
            _networks_list.append(network)

        return _networks_list
Esempio n. 12
0
class Host(View):

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

    def __init__(self):
        self.__request = Request()
        self.__response = Response()
        self.__helpers = Helpers()
        self.__form = Form()
        self.__host_module = Host_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.")
                }]))

        self.__request.set_request(request)
        request_data = self.__request.get_request_data(
            "post", {
                "name": "",
                "slug": "",
                "server": "",
                "type": "",
                "auth_type": "",
                "tls_ca_certificate": "",
                "tls_certificate": "",
                "tls_key": ""
            })

        self.__form.add_inputs({
            'name': {
                'value': request_data["name"],
                'validate': {
                    'host_name': {
                        'error': _("Error! Host Name is invalid.")
                    },
                    'length_between': {
                        'param': [3, 41],
                        'error':
                        _("Error! Host slug length must be from 4 to 40 characters."
                          )
                    }
                }
            },
            'slug': {
                'value': request_data["slug"],
                'validate': {
                    'host_slug': {
                        'error': _('Error! Host slug is not valid.')
                    },
                    'length_between': {
                        'param': [3, 21],
                        'error':
                        _('Error! Host slug length must be from 4 to 20 characters.'
                          )
                    }
                }
            },
            'server': {
                'value': request_data["server"],
                'validate': {
                    'host_server': {
                        'error': _('Error! Host server is not valid.')
                    },
                    'length_between': {
                        'param': [3, 60],
                        'error':
                        _('Error! Host server length must be from 4 to 20 characters.'
                          )
                    }
                }
            },
            'type': {
                'value': request_data["type"],
                'validate': {
                    'any_of': {
                        'param': [["docker"]],
                        'error': _('Error! Host type is invalid.')
                    }
                }
            },
            'auth_type': {
                'value': request_data["auth_type"],
                'validate': {
                    'any_of': {
                        'param': [[
                            "no_auth", "tls_server_client", "tls_client_only",
                            "tls_server_only", "tls_only"
                        ]],
                        'error':
                        _('Error! Auth type is invalid.')
                    }
                }
            },
            'tls_ca_certificate': {
                'value': request_data["tls_ca_certificate"],
                'validate': {
                    'optional': {},
                    'tls_certificate': {
                        'error': _('Error! TLS CA Certificate is invalid.')
                    }
                }
            },
            'tls_certificate': {
                'value': request_data["tls_certificate"],
                'validate': {
                    'optional': {},
                    'tls_certificate': {
                        'error': _('Error! TLS Certificate is invalid.')
                    }
                }
            },
            'tls_key': {
                'value': request_data["tls_key"],
                'validate': {
                    'optional': {},
                    'tls_certificate': {
                        'error': _('Error! TLS Key is invalid.')
                    }
                }
            }
        })

        self.__form.process()

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

        if self.__host_module.slug_used_elsewhere(
                self.__host_id, self.__form.get_input_value("slug"),
                self.__user_id):
            return JsonResponse(
                self.__response.send_private_failure([{
                    "type":
                    "error",
                    "message":
                    _("Error! Host slug is already used.")
                }]))

        result = self.__host_module.update_one_by_id(
            self.__host_id, {
                "name":
                self.__form.get_input_value("name"),
                "slug":
                self.__form.get_input_value("slug"),
                "server":
                self.__form.get_input_value("server"),
                "type":
                self.__form.get_input_value("type"),
                "auth_data":
                self.__helpers.json_dumps({
                    "auth_type":
                    self.__form.get_input_value("auth_type"),
                    "tls_ca_certificate":
                    self.__form.get_input_value("tls_ca_certificate"),
                    "tls_certificate":
                    self.__form.get_input_value("tls_certificate"),
                    "tls_key":
                    self.__form.get_input_value("tls_key")
                }),
                "user_id":
                self.__user_id
            })

        if result:
            return JsonResponse(
                self.__response.send_private_success([{
                    "type":
                    "success",
                    "message":
                    _("Host updated successfully.")
                }]))

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

    def delete(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.")
                }]))

        if self.__host_module.delete_host(self.__host_id):
            return JsonResponse(
                self.__response.send_private_success([{
                    "type":
                    "success",
                    "message":
                    _("Host deleted successfully.")
                }]))

        else:
            return JsonResponse(
                self.__response.send_private_failure([{
                    "type":
                    "error",
                    "message":
                    _("Error! Something goes wrong while deleting a host.")
                }]))
Esempio n. 13
0
class Hosts(View):

    __request = None
    __response = None
    __helpers = None
    __form = None
    __logger = None
    __user_id = None
    __host_module = None
    __status = None

    def __init__(self):
        self.__request = Request()
        self.__response = Response()
        self.__helpers = Helpers()
        self.__form = Form()
        self.__host_module = Host_Module()
        self.__status = Status()
        self.__logger = self.__helpers.get_logger(__name__)

    def get(self, request):

        self.__user_id = request.user.id

        return JsonResponse(
            self.__response.send_private_success(
                [], {
                    'hosts':
                    self.__format_host(
                        self.__host_module.get_many_by_user(
                            self.__user_id, "created_at", False))
                }))

    def post(self, request):

        self.__user_id = request.user.id

        self.__request.set_request(request)
        request_data = self.__request.get_request_data(
            "post", {
                "name": "",
                "slug": "",
                "server": "",
                "type": "",
                "auth_type": "",
                "tls_ca_certificate": "",
                "tls_certificate": "",
                "tls_key": ""
            })

        self.__form.add_inputs({
            'name': {
                'value': request_data["name"],
                'validate': {
                    'host_name': {
                        'error': _("Error! Host Name is invalid.")
                    },
                    'length_between': {
                        'param': [3, 41],
                        'error':
                        _("Error! Host slug length must be from 4 to 40 characters."
                          )
                    }
                }
            },
            'slug': {
                'value': request_data["slug"],
                'validate': {
                    'host_slug': {
                        'error': _('Error! Host slug is not valid.')
                    },
                    'length_between': {
                        'param': [3, 21],
                        'error':
                        _('Error! Host slug length must be from 4 to 20 characters.'
                          )
                    }
                }
            },
            'server': {
                'value': request_data["server"],
                'validate': {
                    'host_server': {
                        'error': _('Error! Host server is not valid.')
                    },
                    'length_between': {
                        'param': [3, 60],
                        'error':
                        _('Error! Host server length must be from 4 to 20 characters.'
                          )
                    }
                }
            },
            'type': {
                'value': request_data["type"],
                'validate': {
                    'any_of': {
                        'param': [["docker"]],
                        'error': _('Error! Host type is invalid.')
                    }
                }
            },
            'auth_type': {
                'value': request_data["auth_type"],
                'validate': {
                    'any_of': {
                        'param': [[
                            "no_auth", "tls_server_client", "tls_client_only",
                            "tls_server_only", "tls_only"
                        ]],
                        'error':
                        _('Error! Auth type is invalid.')
                    }
                }
            },
            'tls_ca_certificate': {
                'value': request_data["tls_ca_certificate"],
                'validate': {
                    'optional': {},
                    'tls_certificate': {
                        'error': _('Error! TLS CA Certificate is invalid.')
                    }
                }
            },
            'tls_certificate': {
                'value': request_data["tls_certificate"],
                'validate': {
                    'optional': {},
                    'tls_certificate': {
                        'error': _('Error! TLS Certificate is invalid.')
                    }
                }
            },
            'tls_key': {
                'value': request_data["tls_key"],
                'validate': {
                    'optional': {},
                    'tls_certificate': {
                        'error': _('Error! TLS Key is invalid.')
                    }
                }
            }
        })

        self.__form.process()

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

        if self.__host_module.slug_used(self.__form.get_input_value("slug"),
                                        self.__user_id):
            return JsonResponse(
                self.__response.send_private_failure([{
                    "type":
                    "error",
                    "message":
                    _("Error! Host slug is already used.")
                }]))

        result = self.__host_module.insert_one({
            "name":
            self.__form.get_input_value("name"),
            "slug":
            self.__form.get_input_value("slug"),
            "server":
            self.__form.get_input_value("server"),
            "type":
            self.__form.get_input_value("type"),
            "auth_data":
            self.__helpers.json_dumps({
                "auth_type":
                self.__form.get_input_value("auth_type"),
                "tls_ca_certificate":
                self.__form.get_input_value("tls_ca_certificate"),
                "tls_certificate":
                self.__form.get_input_value("tls_certificate"),
                "tls_key":
                self.__form.get_input_value("tls_key")
            }),
            "user_id":
            self.__user_id
        })

        if result:
            return JsonResponse(
                self.__response.send_private_success([{
                    "type":
                    "success",
                    "message":
                    _("Host created successfully.")
                }]))

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

    def __format_host(self, hosts_list):
        _hosts_list = []

        for host in hosts_list:
            _status = "up" if self.__status.set_host(
                host.id).ping() else "down"
            _hosts_list.append({
                "id":
                host.id,
                "name":
                host.name,
                "slug":
                host.slug,
                "status":
                _status,
                "type":
                host.type.capitalize(),
                "created_at":
                host.created_at.strftime("%b %d %Y %H:%M:%S"),
                "view_url":
                reverse("app.web.admin.hosts.view",
                        kwargs={'host_slug': host.slug}),
                "edit_url":
                reverse("app.web.admin.hosts.edit",
                        kwargs={'host_slug': host.slug}),
                "delete_url":
                reverse("app.api.private.v1.admin.host.endpoint",
                        kwargs={'host_id': host.id})
            })

        return _hosts_list