Ejemplo n.º 1
0
    def set_env(self):
        input_data = request.data.decode("UTF-8", "replace").strip()

        try:
            env_vars_attempted = json.loads(input_data)
        except Exception as e:
            raise ApiExceptionDocker(
                ApiCode.INVALID_JSON_PAYLOAD.value,
                ErrorMessage.HTTP_CODE.get(ApiCode.INVALID_JSON_PAYLOAD.value)
                % str(input_data), e)

        try:
            env_vars_added = EnvironmentSingleton.get_instance().set_env_vars(
                env_vars_attempted)
        except Exception as e:
            raise ApiExceptionDocker(
                ApiCode.SET_ENV_VAR_FAILURE,
                ErrorMessage.HTTP_CODE.get(ApiCode.SET_ENV_VAR_FAILURE) %
                str(input_data), e)
        return Response(json.dumps(HttpResponse().response(
            ApiCode.SUCCESS.value,
            ErrorMessage.HTTP_CODE.get(ApiCode.SUCCESS.value),
            env_vars_added)),
                        200,
                        mimetype="application/json")
Ejemplo n.º 2
0
    def execute_command(self):
        input_data = request.data.decode("UTF-8", "replace").strip()

        if not input_data:
            raise ApiExceptionDocker(
                ApiCode.EMPTY_REQUEST_BODY_PROVIDED.value,
                ErrorMessage.HTTP_CODE.get(
                    ApiCode.EMPTY_REQUEST_BODY_PROVIDED.value),
                ErrorMessage.HTTP_CODE.get(
                    ApiCode.EMPTY_REQUEST_BODY_PROVIDED.value))
        try:
            input_data_list = input_data.split("\n")
            input_data_list = list(map(lambda x: x.strip(), input_data_list))
            command_in_memory = CommandInMemory()
            response = command_in_memory.run_commands(input_data_list)
        except Exception as e:
            raise ApiExceptionDocker(
                ApiCode.COMMAND_EXEC_FAILURE.value,
                ErrorMessage.HTTP_CODE.get(ApiCode.COMMAND_EXEC_FAILURE.value),
                e)
        return Response(json.dumps(HttpResponse().response(
            ApiCode.SUCCESS.value,
            ErrorMessage.HTTP_CODE.get(ApiCode.SUCCESS.value), response)),
                        200,
                        mimetype="application/json")
Ejemplo n.º 3
0
    def container_docker_network_connect(self, env_id):
        env_id = env_id.lower()
        http = HttpResponse()
        docker_utils = DockerUtils()
        headers = request.headers
        service_name = "container"

        if request.args.get('service') is not None:
            service_name = request.args.get('service')
        container_id = f"{env_id}_{service_name}_1"

        try:
            status = CmdUtils.run_cmd_shell_false([
                "docker", "network", "ls", "--filter",
                "name={}".format("deployer")
            ])
            app.logger.debug({"msg": status})
            if not status.get('out'):
                raise Exception(status.get('err'))
        except Exception as e:
            raise ApiExceptionDocker(
                ApiCode.GET_DEPLOYER_NETWORK_FAILED.value,
                ErrorMessage.HTTP_CODE.get(
                    ApiCode.GET_DEPLOYER_NETWORK_FAILED.value), e)

        try:
            deployer_network = status.get('out').split("\n")[1].split(
                " ")[0].strip()
            if headers.get("Docker-Network"):
                deployer_network = headers.get("Docker-Network")
            status = docker_utils.network_connect(deployer_network,
                                                  container_id)

            if "already exists in network".lower() in status.get(
                    'err').lower():
                return Response(json.dumps(
                    http.response(
                        ApiCode.SUCCESS.value,
                        ErrorMessage.HTTP_CODE.get(ApiCode.SUCCESS.value),
                        "Success, already connected: " + status.get('err'))),
                                200,
                                mimetype="application/json")

            if "Error response from daemon".lower() in status.get(
                    'err').lower():
                raise Exception(status.get('err'))
        except Exception as e:
            raise ApiExceptionDocker(
                ApiCode.CONTAINER_NET_CONNECT_FAILED.value,
                ErrorMessage.HTTP_CODE.get(
                    ApiCode.CONTAINER_NET_CONNECT_FAILED.value), e)
        return Response(json.dumps(
            http.response(ApiCode.SUCCESS.value,
                          ErrorMessage.HTTP_CODE.get(ApiCode.SUCCESS.value),
                          status.get('out'))),
                        200,
                        mimetype="application/json")
Ejemplo n.º 4
0
    def container_request(self, env_id, text):
        env_id = env_id.lower()
        container_url = text.strip()
        headers = request.headers

        service_name = "container"
        if request.args.get('service') is not None:
            service_name = request.args.get('service')
        container_id = f"{env_id}_{service_name}_1"

        container_port = 8080
        if request.args.get('port') is not None:
            container_port = request.args.get('port')

        input_data = None
        try:
            input_data = request.get_data()
        except Exception as e:
            app.logger.debug(
                f"Could not get data from the request: {e.__str__}")

        complete_url = f"http://{container_id}:{container_port}/{container_url}"
        try:
            r = requests.request(url=complete_url,
                                 method=request.method,
                                 data=input_data,
                                 headers=headers,
                                 timeout=5)
        except Exception as e:
            raise ApiExceptionDocker(
                ApiCode.CONTAINER_UNREACHABLE.value,
                ErrorMessage.HTTP_CODE.get(ApiCode.CONTAINER_UNREACHABLE.value)
                % (service_name, service_name), e)
        return Response(r.text, r.status_code)
Ejemplo n.º 5
0
    def deploy_logs(self, env_id):
        env_id = env_id.lower()
        http = HttpResponse()
        docker_utils = DockerUtils()
        env_id = env_id.strip()
        env_id_dir = EnvInit.init.get(EnvConstants.DEPLOY_PATH) + f"/{env_id}"
        file = f"{env_id_dir}/docker-compose.yml"

        try:
            status = docker_utils.logs(file)
            app.logger.debug({"msg": status})
            if status.get('err'):
                raise Exception(status.get('err'))
        except Exception as e:
            raise ApiExceptionDocker(
                ApiCode.GET_LOGS_FAILED.value,
                ErrorMessage.HTTP_CODE.get(ApiCode.GET_LOGS_FAILED.value) %
                env_id, e)

        return Response(json.dumps(
            http.response(ApiCode.SUCCESS.value,
                          ErrorMessage.HTTP_CODE.get(ApiCode.SUCCESS.value),
                          status.get('out'))),
                        200,
                        mimetype="application/json")
Ejemplo n.º 6
0
    def delete_all_deployments(self):
        docker_utils = DockerUtils()
        try:
            active_deployments = docker_utils.get_active_deployments()
            for deployment in active_deployments:
                depl_id = deployment.get('id')
                depl_folder = f"{EnvInit.init.get(EnvConstants.DEPLOY_PATH)}/{depl_id}"
                status = docker_utils.down(f"{depl_folder}/docker-compose.yml")
                if "Cannot connect to the Docker daemon".lower() in status.get(
                        'err').lower():
                    raise Exception(status.get('err'))
                app.logger.debug({"msg": status})
                DeploymentMetadataSingleton.get_instance(
                ).delete_metadata_for_deployment(depl_id)

            DockerUtils.folder_clean_up()
            result = docker_utils.get_active_deployments()
        except Exception as e:
            raise ApiExceptionDocker(
                ApiCode.DEPLOY_STOP_FAILURE.value,
                ErrorMessage.HTTP_CODE.get(ApiCode.DEPLOY_STOP_FAILURE.value),
                e)

        return Response(json.dumps(HttpResponse().response(
            ApiCode.SUCCESS.value,
            ErrorMessage.HTTP_CODE.get(ApiCode.SUCCESS.value), result)),
                        200,
                        mimetype="application/json")
Ejemplo n.º 7
0
    def delete_deployment_id(self, depl_id):
        depl_id = depl_id.strip()
        docker_utils = DockerUtils()
        depl_folder = f"{EnvInit.init.get(EnvConstants.DEPLOY_PATH)}/{depl_id}"
        file = f"{depl_folder}/docker-compose.yml"
        try:
            status = docker_utils.down(file)
            if "Cannot connect to the Docker daemon".lower() in status.get(
                    'err').lower():
                raise Exception(status.get('err'))
            app.logger.debug({"msg": status})
            status = docker_utils.ps(depl_id)
            result = status.get('out').split("\n")[1:]
            DeploymentMetadataSingleton.get_instance(
            ).delete_metadata_for_deployment(depl_id)
            IOUtils.remove_directory(f"{depl_folder}")
        except Exception as e:
            raise ApiExceptionDocker(
                ApiCode.DEPLOY_STOP_FAILURE.value,
                ErrorMessage.HTTP_CODE.get(ApiCode.DEPLOY_STOP_FAILURE.value),
                e)

        return Response(json.dumps(HttpResponse().response(
            ApiCode.SUCCESS.value,
            ErrorMessage.HTTP_CODE.get(ApiCode.SUCCESS.value), result)),
                        200,
                        mimetype="application/json")
Ejemplo n.º 8
0
    def get_rendered_content_with_env(self, template, variables):
        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({
                "msg":
                f"Could not load the body 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())

        try:
            env_vars = EnvironmentSingleton.get_instance(
            ).get_env_and_virtual_env()
            rendered_content = Render(
                env_vars.get(EnvConstants.TEMPLATE),
                env_vars.get(EnvConstants.VARIABLES)).rend_template()
        except Exception as e:
            raise ApiExceptionDocker(
                ApiCode.JINJA2_RENDER_FAILURE.value,
                ErrorMessage.HTTP_CODE.get(
                    ApiCode.JINJA2_RENDER_FAILURE.value), e)

        return Response(rendered_content, 200, mimetype="text/plain")
Ejemplo n.º 9
0
    def get_file(self):
        header_key = 'File-Path'

        file_path = request.headers.get(f"{header_key}")
        if not file_path:
            raise ApiExceptionDocker(
                ApiCode.HTTP_HEADER_NOT_PROVIDED.value,
                ErrorMessage.HTTP_CODE.get(
                    ApiCode.HTTP_HEADER_NOT_PROVIDED.value) % header_key,
                ErrorMessage.HTTP_CODE.get(
                    ApiCode.HTTP_HEADER_NOT_PROVIDED.value) % header_key)

        try:
            file_content = IOUtils.read_file(file_path)
        except Exception as e:
            raise ApiExceptionDocker(
                ApiCode.GET_FILE_FAILURE.value,
                ErrorMessage.HTTP_CODE.get(ApiCode.GET_FILE_FAILURE.value), e)
        return Response(file_content, 200, mimetype="text/plain")
Ejemplo n.º 10
0
    def receive_prepared_deployment_and_unpack(self):
        token = token_hex(8)
        io_utils = IOUtils()
        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_path = f"{deploy_dir}/archive.zip"
        file_content = request.get_data()
        # send here the complete env. The deployment template can be overridden at deploy start
        if not file_content:
            raise ApiExceptionDocker(
                ApiCode.EMPTY_REQUEST_BODY_PROVIDED.value,
                ErrorMessage.HTTP_CODE.get(
                    ApiCode.EMPTY_REQUEST_BODY_PROVIDED.value),
                ErrorMessage.HTTP_CODE.get(
                    ApiCode.EMPTY_REQUEST_BODY_PROVIDED.value))

        try:
            io_utils.create_dir(deploy_dir)
            io_utils.write_to_file_binary(file_path, file_content)
        except Exception as e:
            raise ApiExceptionDocker(
                ApiCode.UPLOAD_FILE_FAILURE.value,
                ErrorMessage.HTTP_CODE.get(ApiCode.UPLOAD_FILE_FAILURE.value),
                e)
        try:
            shutil.unpack_archive(file_path, deploy_dir)
            io_utils.remove_file(file_path)
        except Exception as e:
            raise ApiExceptionDocker(
                ApiCode.FOLDER_UNZIP_FAILURE.value,
                ErrorMessage.HTTP_CODE.get(ApiCode.FOLDER_UNZIP_FAILURE.value),
                e)

        return Response(json.dumps(HttpResponse().response(
            ApiCode.SUCCESS.value,
            ErrorMessage.HTTP_CODE.get(ApiCode.SUCCESS.value), deployment_id)),
                        200,
                        mimetype="application/json")
Ejemplo n.º 11
0
    def upload_file(self):
        http = HttpResponse()
        io_utils = IOUtils()
        header_key = 'File-Path'
        file_content = request.get_data()
        file_path = request.headers.get(f"{header_key}")

        if not file_path:
            raise ApiExceptionDocker(
                ApiCode.HTTP_HEADER_NOT_PROVIDED.value,
                ErrorMessage.HTTP_CODE.get(
                    ApiCode.HTTP_HEADER_NOT_PROVIDED.value) % header_key,
                ErrorMessage.HTTP_CODE.get(
                    ApiCode.HTTP_HEADER_NOT_PROVIDED.value) % header_key)
        if not file_content:
            raise ApiExceptionDocker(
                ApiCode.EMPTY_REQUEST_BODY_PROVIDED.value,
                ErrorMessage.HTTP_CODE.get(
                    ApiCode.EMPTY_REQUEST_BODY_PROVIDED.value),
                ErrorMessage.HTTP_CODE.get(
                    ApiCode.EMPTY_REQUEST_BODY_PROVIDED.value))

        try:
            io_utils.write_to_file_binary(file_path, file_content)
        except Exception as e:
            raise ApiExceptionDocker(
                ApiCode.UPLOAD_FILE_FAILURE.value,
                ErrorMessage.HTTP_CODE.get(ApiCode.UPLOAD_FILE_FAILURE.value),
                e)

        return Response(json.dumps(
            http.response(ApiCode.SUCCESS.value,
                          ErrorMessage.HTTP_CODE.get(ApiCode.SUCCESS.value),
                          ErrorMessage.HTTP_CODE.get(ApiCode.SUCCESS.value))),
                        200,
                        mimetype="application/json")
Ejemplo n.º 12
0
    def cleanup_inactive_deployments(self):
        """ ! can be executed only after /deployments DELETE ! """
        try:
            deleted_folders = DockerUtils.folder_clean_up()
        except Exception as e:
            raise ApiExceptionDocker(
                ApiCode.DEPLOYMENTS_FOLDER_CLEANUP_FAILURE.value,
                ErrorMessage.HTTP_CODE.get(
                    ApiCode.DEPLOYMENTS_FOLDER_CLEANUP_FAILURE.value), e)

        return Response(json.dumps(HttpResponse().response(
            ApiCode.SUCCESS.value,
            ErrorMessage.HTTP_CODE.get(ApiCode.SUCCESS.value),
            deleted_folders)),
                        200,
                        mimetype="application/json")
Ejemplo n.º 13
0
    def get_deployment_status(self, env_id):
        env_id = env_id.lower()
        docker_utils = DockerUtils()
        env_id = env_id.strip()

        try:
            status = docker_utils.ps(env_id)
            if "Cannot connect to the Docker daemon".lower() in status.get(
                    'err').lower():
                raise Exception(status.get('err'))
            result = status.get('out').split("\n")[1:]
            app.logger.debug({"msg": status})
        except Exception as e:
            raise ApiExceptionDocker(
                ApiCode.DEPLOY_STATUS_FAILURE.value,
                ErrorMessage.HTTP_CODE.get(
                    ApiCode.DEPLOY_STATUS_FAILURE.value), e)

        return Response(json.dumps(HttpResponse().response(
            ApiCode.SUCCESS.value,
            ErrorMessage.HTTP_CODE.get(ApiCode.SUCCESS.value),
            ActiveDeployment.docker_deployment(env_id, result))),
                        200,
                        mimetype="application/json")
Ejemplo n.º 14
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")
Ejemplo n.º 15
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")