Esempio n. 1
0
    def deploy_start(self):
        http = HttpResponse()
        kubectl_utils = KubectlUtils()
        fluentd_tag = "deploy_start"
        token = token_hex(8)
        deploy_dir = f"{EnvInit.init.get(EnvConstants.DEPLOY_PATH)}/{token}"
        file = f"{deploy_dir}/k8s-deployment.yml"

        try:
            IOUtils.create_dir(deploy_dir)
            input_data = request.data.decode('utf-8')
            IOUtils.write_to_file(file, input_data)
            status = kubectl_utils.up(f"{file}")
            self.fluentd.emit(tag=fluentd_tag, msg={"msg": status})
            if status.get('err'):
                raise Exception(status.get('err'))
        except Exception as e:
            raise ApiExceptionKubectl(
                ApiCode.DEPLOY_START_FAILURE.value,
                ErrorMessage.HTTP_CODE.get(ApiCode.DEPLOY_START_FAILURE.value),
                e)

        return Response(json.dumps(
            http.response(ApiCode.SUCCESS.value,
                          ErrorMessage.HTTP_CODE.get(ApiCode.SUCCESS.value),
                          token)),
                        200,
                        mimetype="application/json")
    def send_request(self, app, request_object):
        resp = self.send_http_request(app, request_object=request_object)

        try:
            response = resp.json()
            response["homePageUrl"] = app.get('homePageUrl')
            response["ip_port"] = f"{app.get('ipAddr')}:{app.get('port')}"

            self.response_list.append(response)
        except:
            file_name = re.findall(
                ".*filename=(.+)", resp.headers["Content-Disposition"]
            )[0] if resp.headers.get("Content-Disposition") else ""

            self.__is_response_zip = True
            IOUtils.create_dir(
                f"{self.download_folder}/{self.__source_zip_folder}")
            IOUtils.write_to_file(
                f"{self.download_folder}/{self.__source_zip_folder}/{app.get('ipAddr')}_{app.get('port')}_{file_name}",
                resp.content)
Esempio n. 3
0
    def start_deployment_with_templates(self, template, variables):
        http = HttpResponse()
        docker_utils = DockerUtils()
        token = token_hex(8)
        deployment_id = request.headers.get("Deployment-Id").lower(
        ) if request.headers.get("Deployment-Id") else token
        deploy_dir = f"{EnvInit.init.get(EnvConstants.DEPLOY_PATH)}/{deployment_id}"
        file = f"{deploy_dir}/docker-compose.yml"

        try:
            input_json = request.get_json(force=True)
            for key, value in input_json.items():
                if key not in EnvironmentSingleton.get_instance().get_env():
                    EnvironmentSingleton.get_instance().set_env_var(
                        str(key), str(value))
        except Exception as e:
            app.logger.debug(
                f"Could not parse the input from the request as JSON: {e.__str__()}"
            )

        EnvironmentSingleton.get_instance().set_env_var(
            EnvConstants.TEMPLATE, template.strip())
        EnvironmentSingleton.get_instance().set_env_var(
            EnvConstants.VARIABLES, variables.strip())
        env_vars = EnvironmentSingleton.get_instance().get_env_and_virtual_env(
        )
        app.logger.debug(
            {"msg": {
                "template_file": env_vars.get(EnvConstants.TEMPLATE)
            }})
        app.logger.debug(
            {"msg": {
                "variables_file": env_vars.get(EnvConstants.VARIABLES)
            }})

        status = CmdUtils.run_cmd_shell_false(["docker", "ps"])
        if "Cannot connect to the Docker daemon".lower() in status.get(
                'err').lower():
            raise ApiExceptionDocker(
                ApiCode.DOCKER_DAEMON_NOT_RUNNING.value,
                ErrorMessage.HTTP_CODE.get(
                    ApiCode.DOCKER_DAEMON_NOT_RUNNING.value),
                status.get('err'))

        active_deployments = docker_utils.get_active_deployments()
        if len(active_deployments) >= EnvInit.init.get(
                EnvConstants.MAX_DEPLOYMENTS):
            raise ApiExceptionDocker(
                ApiCode.MAX_DEPLOYMENTS_REACHED.value,
                ErrorMessage.HTTP_CODE.get(
                    ApiCode.MAX_DEPLOYMENTS_REACHED.value) %
                str(EnvInit.init.get(EnvConstants.MAX_DEPLOYMENTS)),
                active_deployments)
        try:
            r = Render(env_vars.get(EnvConstants.TEMPLATE),
                       env_vars.get(EnvConstants.VARIABLES))
            IOUtils.create_dir(deploy_dir)
            IOUtils.write_to_file(file, r.rend_template())
            CmdUtils.run_cmd_detached(
                rf'''docker-compose -f {file} pull && docker-compose -f {file} up -d'''
            )
        except Exception as e:
            raise ApiExceptionDocker(
                ApiCode.DEPLOY_START_FAILURE.value,
                ErrorMessage.HTTP_CODE.get(ApiCode.DEPLOY_START_FAILURE.value),
                e)

        DeploymentMetadataSingleton.get_instance() \
            .delete_metadata_for_inactive_deployments(DockerUtils.get_active_deployments())
        metadata = DeploymentReader.get_metadata_for_deployment(
            IOUtils.read_file(file=file))
        IOUtils.write_to_file_dict(f"{deploy_dir}/metadata.json", metadata)
        DeploymentMetadataSingleton.get_instance().set_metadata_for_deployment(
            deployment_id, metadata)

        return Response(json.dumps(
            http.response(ApiCode.SUCCESS.value,
                          ErrorMessage.HTTP_CODE.get(ApiCode.SUCCESS.value),
                          deployment_id)),
                        200,
                        mimetype="application/json")
Esempio n. 4
0
    def start_deployment(self):
        docker_utils = DockerUtils()
        token = token_hex(8)
        deployment_id = request.headers.get("Deployment-Id").lower(
        ) if request.headers.get("Deployment-Id") else token
        deploy_dir = f"{EnvInit.init.get(EnvConstants.DEPLOY_PATH)}/{deployment_id}"
        file = f"{deploy_dir}/docker-compose.yml"
        header_key = 'Eureka-Server'
        eureka_server_header = request.headers.get(f"{header_key}")
        config_env_vars = EnvStartupSingleton.get_instance(
        ).get_config_env_vars()
        input_data = request.data.decode('UTF-8').strip()

        status = CmdUtils.run_cmd_shell_false(["docker", "ps"])
        if "Cannot connect to the Docker daemon".lower() in status.get(
                'err').lower():
            raise ApiExceptionDocker(
                ApiCode.DOCKER_DAEMON_NOT_RUNNING.value,
                ErrorMessage.HTTP_CODE.get(
                    ApiCode.DOCKER_DAEMON_NOT_RUNNING.value),
                status.get('err'))

        active_deployments = docker_utils.get_active_deployments()
        if len(active_deployments) >= EnvInit.init.get(
                EnvConstants.MAX_DEPLOYMENTS):
            raise ApiExceptionDocker(
                ApiCode.MAX_DEPLOYMENTS_REACHED.value,
                ErrorMessage.HTTP_CODE.get(
                    ApiCode.MAX_DEPLOYMENTS_REACHED.value) %
                str(EnvInit.init.get(EnvConstants.MAX_DEPLOYMENTS)),
                active_deployments)
        try:
            template_file_name = f"deployment_{deployment_id}.yml"
            template_file_path = f"{EnvInit.init.get(EnvConstants.TEMPLATES_DIR)}/{template_file_name}"
            app.logger.debug({
                "msg": {
                    "file": template_file_path,
                    "file_content": f"{input_data}"
                }
            })
            IOUtils.write_to_file(template_file_path, input_data)

            IOUtils.create_dir(deploy_dir)
            EnvironmentSingleton.get_instance().set_env_var(
                EnvConstants.TEMPLATE, template_file_name)
            env_vars = EnvironmentSingleton.get_instance(
            ).get_env_and_virtual_env()
            render = Render(env_vars.get(EnvConstants.TEMPLATE),
                            env_vars.get(EnvConstants.VARIABLES))
            if config_env_vars.get(
                    EnvConstants.EUREKA_SERVER) and config_env_vars.get(
                        EnvConstants.APP_IP_PORT):
                # if {{app_ip_port}} and {{eureka_server}} then register that instance too
                if '{{app_ip_port}}' in input_data and '{{eureka_server}}' in input_data:
                    eureka_server = config_env_vars.get(
                        EnvConstants.EUREKA_SERVER)
                    # header value overwrite the eureka server
                    if eureka_server_header:
                        eureka_server = eureka_server_header
                    input_data = render.get_jinja2env().get_template(
                        env_vars.get(EnvConstants.TEMPLATE)).render({
                            "deployment_id":
                            f"{deployment_id}",
                            "eureka_server":
                            eureka_server,
                            "app_ip_port":
                            config_env_vars.get(
                                EnvConstants.APP_IP_PORT).split("/")[0]
                        })
            os.remove(template_file_path) if os.path.exists(
                template_file_path) else None
            app.logger.debug(
                {"msg": {
                    "file": file,
                    "file_content": f"{input_data}"
                }})
            IOUtils.write_to_file(file, input_data) if input_data else None
            CmdUtils.run_cmd_detached(
                rf'''docker-compose -f {file} pull && docker-compose -f {file} up -d'''
            )
        except Exception as e:
            app.logger.debug({"msg": docker_utils.down(file)})
            raise ApiExceptionDocker(
                ApiCode.DEPLOY_START_FAILURE.value,
                ErrorMessage.HTTP_CODE.get(ApiCode.DEPLOY_START_FAILURE.value),
                e)

        DeploymentMetadataSingleton.get_instance() \
            .delete_metadata_for_inactive_deployments(DockerUtils.get_active_deployments())
        metadata = DeploymentReader.get_metadata_for_deployment(
            IOUtils.read_file(file=file))
        IOUtils.write_to_file_dict(f"{deploy_dir}/metadata.json", metadata)
        DeploymentMetadataSingleton.get_instance().set_metadata_for_deployment(
            deployment_id, metadata)

        return Response(json.dumps(HttpResponse().response(
            ApiCode.SUCCESS.value,
            ErrorMessage.HTTP_CODE.get(ApiCode.SUCCESS.value), deployment_id)),
                        200,
                        mimetype="application/json")
Esempio n. 5
0
    def start_deployment_with_template(self, template, variables):
        http = HttpResponse()
        kubectl_utils = KubectlUtils()
        fluentd_tag = "deploy_start"
        try:
            input_json = request.get_json(force=True)
            for key, value in input_json.items():
                if key not in EnvironmentSingleton.get_instance().get_env():
                    EnvironmentSingleton.get_instance().set_env_var(
                        str(key), str(value))
        except Exception as e:
            app.logger.debug(f"Exception: {e.__str__()}")

        EnvironmentSingleton.get_instance().set_env_var(
            EnvConstants.TEMPLATE, template.strip())
        EnvironmentSingleton.get_instance().set_env_var(
            EnvConstants.VARIABLES, variables.strip())
        app.logger.debug({
            "msg": {
                "template_file":
                EnvironmentSingleton.get_instance().get_env_and_virtual_env().
                get(EnvConstants.TEMPLATE)
            }
        })
        app.logger.debug({
            "msg": {
                "variables_file":
                EnvironmentSingleton.get_instance().get_env_and_virtual_env().
                get(EnvConstants.VARIABLES)
            }
        })
        token = token_hex(8)
        deploy_dir = f"{EnvInit.init.get(EnvConstants.DEPLOY_PATH)}/{token}"
        file = f"{deploy_dir}/k8s-deployment.yml"

        try:
            r = Render(
                EnvironmentSingleton.get_instance().get_env_and_virtual_env(
                ).get(EnvConstants.TEMPLATE),
                EnvironmentSingleton.get_instance().get_env_and_virtual_env().
                get(EnvConstants.VARIABLES))
            IOUtils.create_dir(deploy_dir)
            IOUtils.write_to_file(file)
            IOUtils.write_to_file(file, r.rend_template())
            status = kubectl_utils.up(f"{file}")
            self.fluentd.emit(tag=fluentd_tag, msg={"msg": status})
            if status.get('err'):
                raise Exception(status.get('error'))
            result = str(token)
        except Exception as e:
            raise ApiExceptionKubectl(
                ApiCode.DEPLOY_START_FAILURE.value,
                ErrorMessage.HTTP_CODE.get(ApiCode.DEPLOY_START_FAILURE.value),
                e)

        return Response(json.dumps(
            http.response(ApiCode.SUCCESS.value,
                          ErrorMessage.HTTP_CODE.get(ApiCode.SUCCESS.value),
                          result)),
                        200,
                        mimetype="application/json")