python+django自动化部署日志采用‌WebSocket前端实时展示

一、开发环境搭建和配置

# channels是一个用于在Django中实现WebSocket、HTTP/2和其他异步协议的库。
pip install channels#channels-redis是一个用于在Django Channels中使用Redis作为后台存储的库。它可以用于处理#WebSocket连接的持久化和消息传递。
pip install channels-redis#安装 docker(此处采用 mac安装)
brew install --cask docker

二、django应用模块目录

deployments
├── Consumers.py
├── __init__.py
├── __pycache__
│   ├── Consumers.cpython-313.pyc
│   ├── __init__.cpython-313.pyc
│   ├── admin.cpython-313.pyc
│   ├── apps.cpython-313.pyc
│   ├── models.cpython-313.pyc
│   ├── routing.cpython-313.pyc
│   └── views.cpython-313.pyc
├── admin.py
├── apps.py
├── migrations
│   ├── 0001_initial.py
│   ├── __init__.py
│   └── __pycache__
│       ├── 0001_initial.cpython-313.pyc
│       └── __init__.cpython-313.pyc
├── models.py
├── routing.py
├── tests.py
└── views.py

三、django模块相关代码

***************************/operation/settings.py***************************
CHANNEL_LAYERS = {'default': {'BACKEND': 'channels_redis.core.RedisChannelLayer','CONFIG': {"hosts": ["redis://:xx@xx:6379/0",],},},
}INSTALLED_APPS = ['deployments','channels'
]ASGI_APPLICATION = 'operation.asgi.application'
***************************/operation/asgi.py***************************"""
ASGI config for operation project.It exposes the ASGI callable as a module-level variable named ``application``.For more information on this file, see
https://docs.djangoproject.com/en/4.2/howto/deployment/asgi/Django项目支持ASGI的入口点,ASGI是一个Python标准,用于异步Web服务器、Web框架和Web应用之间的通信,它允许你编写异步的Django视图和其他组件,以提高应用的性能和响应能力,部署时需要用到部署的时候才用到
"""import osfrom django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack# 设置 DJANGO_SETTINGS_MODULE 环境变量
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'operation.settings')# 获取 ASGI 应用
django_asgi_app = get_asgi_application()# 延迟导入其他模块
from deployments import routing  # 这里是你需要延迟导入的模块application = ProtocolTypeRouter({"http": django_asgi_app,"websocket": AuthMiddlewareStack(URLRouter(routing.websocket_urlpatterns))
})
************************/deployments/routing.py************************
from django.urls import pathfrom . import Consumerswebsocket_urlpatterns = [path('ws/cicd_progress/', Consumers.ChatConsumer.as_asgi())
]
************************/deployments/views.py***************************import asyncio
import json
import logging
import os
import subprocessimport git
from django.http import JsonResponse, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from git import Repofrom deployments.models import Deployment
from operation import settings
from operation.common.enum.BuildProjectEnum import BuildProjectEnum
from operation.common.enum.ResponeCodeEnum import ResponseCodeEnum
from operation.common.exception.BusinessException import BusinessException
from operation.common.utils.CommonResult import CommonResult
from operation.common.utils.PageUtils import paginate_queryset
from asgiref.sync import sync_to_async# Create your views here."""
****************************创建 deployments API视图
""""""获取应用列表
"""@csrf_exempt
def getDeploymentsList(request):try:if request.method == 'POST':json_data = request.bodydata = json.loads(json_data)page = data.get('page', 1)page_size = data.get('page_size', 10)else:raise BusinessException(ResponseCodeEnum.METHOD_ERROR.message, ResponseCodeEnum.METHOD_ERROR.code)deployment_list = Deployment.objects.all().order_by('created_at')deployment_lists, pagination_info = paginate_queryset(deployment_list, page, page_size)deployment_lists = [Deployment.to_dict() for Deployment in deployment_lists]logging.info(type(deployment_lists))return JsonResponse(CommonResult.success_pagination(deployment_lists, pagination_info),json_dumps_params={'ensure_ascii': False})except BusinessException as e:return JsonResponse(CommonResult.error(e.code, e.message), json_dumps_params={'ensure_ascii': False})"""增加应用
"""@csrf_exempt
def addDeployment(request):if request.method == "GET":return BusinessException(ResponseCodeEnum.METHOD_ERROR.message, ResponseCodeEnum.METHOD_ERROR.code)try:json_data = request.bodydata = json.loads(json_data)name = data.get('name')if name is None:raise BusinessException(ResponseCodeEnum.PARAMS_ERROR.message, ResponseCodeEnum.PARAMS_ERROR.code)# 保存应用Deployment.objects.create(name=name,status=BuildProjectEnum.NOT_STARTED.code)return JsonResponse(CommonResult.success_data(None), json_dumps_params={'ensure_ascii': False})except BusinessException as e:return JsonResponse(CommonResult.error(e.code, e.message), json_dumps_params={'ensure_ascii': False})"""*********部署角本报错: You cannot call this from an async context - use a thread or sync_to_async.解决方案:1.使用 sync_to_async  2.使用 使用线程
"""
# 定义全局变量 progress
progress = 0async def cicd_execute(project_id, project_name, send_progress, send_news):global progress  # 声明 progress 为全局变量try:# 每次点击发布时,重置 progress 为0progress = 0# 1.初始化阶段await init_project(project_id, project_name, send_progress)# 2.构建阶段await build_and_deploy_project(project_id, project_name, send_progress, send_news)# 3.运行阶段await run_project(project_id, project_name, send_progress,send_news)except BusinessException as e:logging.info(f"发生系统内部异常: {e}")return"""1.初始化阶段
"""async def init_project(project_id, project_name, send_progress):global progress  # 声明 progress 为全局变量try:logging.info("=================开始初始化 项目 %s" % (project_name))logging.info("初始化中......")# 更新状态为 "初始化中" 记录进度值progress += 20await update_deployment_status(project_id, project_name, BuildProjectEnum.INITIALIZING.code, progress)# 发送事件await send_progress(progress, BuildProjectEnum.INITIALIZING.code, ResponseCodeEnum.SUCCESS.status_code,ResponseCodeEnum.SUCCESS.message)projectName = project_nameprojectId = project_idif projectName is None or projectId is None:raise BusinessException(ResponseCodeEnum.PARAMS_ERROR.message, ResponseCodeEnum.PARAMS_ERROR.code)# 环境变量配置set_environment_variables()# 加载仓库 拉取代码await clone_or_pull_repo(project_name)# 更新状态为 "初始化成功" 记录进度值progress += 20await update_deployment_status(project_id, project_name, BuildProjectEnum.INITIAL_SUCCESS.code, progress)# 发送事件await send_progress(progress, BuildProjectEnum.INITIAL_SUCCESS.code, ResponseCodeEnum.SUCCESS.status_code,ResponseCodeEnum.SUCCESS.message)logging.info("初始化成功......")except BusinessException as e:logging.info("初始化失败......")# 更新状态为 "初始化失败"await update_deployment_status(project_id, project_name, BuildProjectEnum.INITIAL_FAILURE.code, progress)# 发送事件await send_progress(progress, BuildProjectEnum.INITIAL_FAILURE.code,ResponseCodeEnum.INTERNAL_SERVER_ERROR.status_code,ResponseCodeEnum.INTERNAL_SERVER_ERROR.message)# 抛出异常raise BusinessException(ResponseCodeEnum.INTERNAL_SERVER_ERROR.message,ResponseCodeEnum.INTERNAL_SERVER_ERROR.code)"""2.构建阶段
"""
async def build_and_deploy_project(project_id, project_name, send_progress, send_news):global progresslogging.info("=================构建 项目 %s" % (project_name))logging.info("部署中......")try:# 更新状态为 "部署中" 记录进度值 60progress += 20await update_deployment_status(project_id, project_name, BuildProjectEnum.DEPLOYMENT_IN.code, progress)# 发送事件await send_progress(progress, BuildProjectEnum.DEPLOYMENT_IN.code, ResponseCodeEnum.SUCCESS.status_code,ResponseCodeEnum.SUCCESS.message)projectName_image = project_name + "-image"projectName_dir = os.path.join(settings.PROJECT_REPO_DIR, project_name)await clean_old_containers(projectName_image)await clean_old_images(projectName_image)os.chdir(projectName_dir)logging.info(f"当前工作目录: {os.getcwd()}")# 执行 maven 打包await execute_maven_build(send_news)logging.info("mvn clean install -DskipTests 执行完成......")# 构建 imageawait build_docker_image(projectName_image,send_news)logging.info("docker build -t , projectName_image . 执行完成")# 更新状态为 "部署成功" 记录进度值 80progress += 20await update_deployment_status(project_id, project_name, BuildProjectEnum.DEPLOYMENT_SUCCESS.code, progress)# 发送事件await send_progress(progress, BuildProjectEnum.DEPLOYMENT_SUCCESS.code, ResponseCodeEnum.SUCCESS.status_code,ResponseCodeEnum.SUCCESS.message)logging.info("部署成功......")except Exception as ex:# 更新状态为 "部署失败"logging.info("部署失败......")await update_deployment_status(project_id, project_name, BuildProjectEnum.DEPLOYMENT_FAILURE.code, progress)# 发送事件await send_progress(progress, BuildProjectEnum.DEPLOYMENT_FAILURE.code,ResponseCodeEnum.INTERNAL_SERVER_ERROR.status_code,ResponseCodeEnum.INTERNAL_SERVER_ERROR.message)# 抛出异常raise BusinessException(ResponseCodeEnum.INTERNAL_SERVER_ERROR.message,ResponseCodeEnum.INTERNAL_SERVER_ERROR.code)"""3.运行阶段
"""
async def run_project(project_id, project_name, send_progress,send_news):global progresslogging.info("=================启动 项目 %s" % (project_name))logging.info("启动中......")try:# 更新状态为 "启动中" 记录进度值 70progress += 10await update_deployment_status(project_id, project_name, BuildProjectEnum.STARTING.code, progress)# 发送事件await send_progress(progress, BuildProjectEnum.STARTING.code, ResponseCodeEnum.SUCCESS.status_code,ResponseCodeEnum.SUCCESS.message)projectName_image = project_name + "-image"await run_docker_container(projectName_image,send_news)# 更新状态为 "启动成功" 记录进度值 80progress += 10await update_deployment_status(project_id, project_name, BuildProjectEnum.STARTED_SECCESS.code, progress)# 发送事件await send_progress(progress, BuildProjectEnum.STARTED_SECCESS.code, ResponseCodeEnum.SUCCESS.status_code,ResponseCodeEnum.SUCCESS.message)logging.info("启动成功......")except Exception as ex:# 更新状态为 "启动失败"logging.info("启动失败......")await update_deployment_status(project_id, project_name, BuildProjectEnum.STARTED_FAILURE.code, progress)# 发送事件await send_progress(progress, BuildProjectEnum.STARTED_FAILURE.code,ResponseCodeEnum.INTERNAL_SERVER_ERROR.status_code,ResponseCodeEnum.INTERNAL_SERVER_ERROR.message)# 抛出异常raise BusinessException(ResponseCodeEnum.INTERNAL_SERVER_ERROR.message,ResponseCodeEnum.INTERNAL_SERVER_ERROR.code)"""加载环境变量
"""def set_environment_variables():logging.info("加载环境变量......")os.environ['PATH'] = settings.MAVEN_PATH + os.environ['PATH']jdk_path = settings.JDK_PATHos.environ['JAVA_HOME'] = jdk_pathos.environ['PATH'] = f"{jdk_path}/bin:{os.environ['PATH']}"logging.info("环境变量加载成功......")"""加载仓库 拉取代码
"""async def clone_or_pull_repo(project_name):logging.info("拉取仓库代码......")project_repo_url = settings.PROJECT_REPO_URLproject_repo_dir = settings.PROJECT_REPO_DIRif not os.path.exists(project_repo_dir):await sync_to_async(Repo.clone_from)(project_repo_url, project_repo_dir)else:project_repo = await sync_to_async(Repo)(project_repo_dir)await sync_to_async(project_repo.remotes.origin.pull)()logging.info("拉取仓库代码成功......")"""清理旧容器
"""
async def clean_old_containers(projectName_image):cid = await sync_to_async(subprocess.check_output)(["docker", "ps", "-a", "-q", "--filter", f"ancestor={projectName_image}"])if cid:# 去除末尾的换行符并转换为字符串cid_str = cid.decode().strip()logging.info("=================cid: %s" % (cid_str))logging.info(f"清理旧容器 docker rm -f {cid_str}")await sync_to_async(subprocess.run)(["docker", "rm", "-f", cid_str])"""清理旧镜像
"""
async def clean_old_images(projectName_image):iid = await sync_to_async(subprocess.check_output)(["docker", "images", "-q", projectName_image])if iid:# 去除末尾的换行符并转换为字符串iid_str = iid.strip()logging.info("=================iid: %s" % (iid_str))logging.info(f"清理旧镜像 docker rmi -f {iid_str}")await sync_to_async(subprocess.run)(["docker", "rmi", "-f", iid_str])"""maven 打包构建
"""
async def execute_maven_build(send_news):# 使用 asyncio.create_subprocess_exec 创建异步进程processObject = await asyncio.create_subprocess_exec('mvn', 'clean', 'install', '-DskipTests',stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.PIPE)logging.info("发送maven打包构建执行日志......")await deployment_log_output(processObject, send_news, ResponseCodeEnum.SUCCESS)"""构建镜像
"""
async def build_docker_image(projectName_image, send_news):logging.info(f"=================构建镜像 docker build -t {projectName_image} .")# 使用 asyncio.create_subprocess_exec 来异步执行命令imageProcessObject = await asyncio.create_subprocess_exec('docker', 'build', '-t', projectName_image, '.',stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.PIPE)logging.info("发送构建镜像执行日志......")await deployment_log_output(imageProcessObject, send_news, ResponseCodeEnum.SUCCESS)"""运行 docker
"""
async def run_docker_container(projectName_image, send_news):logging.info(f"=================运行 docker run -d -p 8084:8084 {projectName_image} .")containerRunProcessObject = await asyncio.create_subprocess_exec('docker', 'run', '-d', '-p', '8084:8084', projectName_image, '.',stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.PIPE)logging.info("发送启动docker执行日志......")# 获取容器 IDstdout, stderr = await containerRunProcessObject.communicate()container_id = stdout.decode('utf-8').strip()# 异步运行 docker logs 命令containerRunlogprocess = await asyncio.create_subprocess_exec('docker', 'logs', '-f', '-n', '100', container_id,stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.PIPE)# 异步读取容器日志asyncio.create_task(deployment_log_output(containerRunlogprocess, send_news, ResponseCodeEnum.SUCCESS))"""更新model
"""
async def update_deployment_status(project_id, project_name, status, progress):await sync_to_async(Deployment.update_deployment_model)(project_id, project_name, status=status, progress=progress)"""
读取mvn 执行命令定义一个异步的 函数 deployment_log_outputasync def:协程(协程是由用户程序控制的) 可以暂停和恢复执行部署日志模块记录processObject: 进程对象send_news: 处理消息的方法buildProjectEnum:构建项目的 Enum类responseCodeEnum: 响应Enum类progress: 进度值
"""
async def deployment_log_output(processObject, send_news, responseCodeEnum: ResponseCodeEnum):try:# 使用 async for 循环读取日志async for line in processObject.stdout:if not line:break# 发送日志await send_news(line.decode('utf-8'), responseCodeEnum)logging.info(f"发送日志信息成功: %s" % (line.decode('utf-8')))finally:# 等待子进程执行完毕await processObject.wait()
************************/deployments/Consumers.py***************************
import os
from typing import Anyimport django
import loggingfrom channels.generic.websocket import AsyncWebsocketConsumer
import jsonfrom deployments.views import cicd_execute
from operation.common.enum.ResponeCodeEnum import ResponseCodeEnum# 手动设置 DJANGO_SETTINGS_MODULE
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'operation.settings')# 配置 Django
django.setup()class ChatConsumer(AsyncWebsocketConsumer):async def connect(self):logging.info("connect")await self.accept()async def disconnect(self, close_code):pass"""Exception inside application: You cannot call this from an async context - use a thread or sync_to_async.Traceback (most recent call last):这个错误提示表明你在异步上下文中调用了同步代码,这在 Django Channels 中是不允许的。你需要将同步代码转换为异步代码,或者使用 sync_to_async 包装同步代码。"""async def receive(self, text_data):text_data_json = json.loads(text_data)id = text_data_json['id']project_name = text_data_json['projectName']# 调用CI/CD执行函数await self.channel_layer.send(self.channel_name,{'type': 'execute_cicd','id': id,'project_name': project_name,})async def execute_cicd(self, event):id = event['id']project_name = event['project_name']# 调用CI/CD执行函数await cicd_execute(id, project_name, self.send_progress,self.send_news)"""发送 进度"""async def send_progress(self, progress,status,code,message):await self.send(text_data=json.dumps({'type': 'progress','code': code,'message': message,'data': {'progress': progress,  #进度值'status': status        # 状态}}))"""发送 执行日志: 类型注解,用于明确指定 responseCodeEnum 参数的类型是 ResponseCodeEnum"""async def send_news(self,logInfo: Any,responseCodeEnum:ResponseCodeEnum):await self.send(text_data=json.dumps({'type': 'news','code': responseCodeEnum.code,'message': responseCodeEnum.message,'data': {'logInfo':logInfo   #日志信息}}))

四、启动django项目 (需要支持WebSocket或其他异步通信,使用daphne启动)

"""和项目交互基本上都是基于这个文件,一般都是在终端输入python3 manage.py [子命令]manage.py输入python3 manage.py help查看更多启动项目  python3 manage.py runserver 创建app模块 python3 manage.py startapp app生成迁移文件,描述如何将模型更改应用到数据库中 python3 manage.py makemigrations将这些文件迁移应用到数据库中 python3 manage.py migrate如果你需要支持WebSocket或其他异步通信,使用daphne operation.asgi:application。如果你只需要简单的HTTP服务,使用python manage.py runserver。export DJANGO_SETTINGS_MODULE=your_project_name.settings"""
#安装Daphne
pip install daphne#终端输入
daphne operation.asgi:application

五、前端代码

<template><div class="app-container"><el-card shadow="always"><el-form ref="searchForm" :inline="true" :model="searchMap" style="margin-top: 20px"><el-form-item><el-button type="primary" icon="el-icon-search" @click="searchLog('searchForm')">搜索</el-button><el-button type="primary" icon="el-icon-clear" @click="resetForm('searchForm')">重置</el-button></el-form-item></el-form></el-card><el-card shadow="always"><template><el-button size="mini" icon="el-icon-plus" type="primary" @click="openAddDrawer()">新增</el-button></template></el-card><el-row :gutter="24"><el-col :span="24"><el-card shadow="always"><div><el-table ref="multipleTable" v-loading="listLoading" :data="getDeploymentListDto" border fit highlight-current-row style="width: 100%;" class="tb-edit"><el-table-column prop="id" label="应用id" width="180px" align="center"></el-table-column><el-table-column prop="name" label="应用名称" width="180px" align="center"></el-table-column><el-table-column prop="status" label="状态" width="180px" align="center" :formatter="statusFormatter"></el-table-column><el-table-column prop="created_at" label="创建时间" width="180px" align="center"></el-table-column><el-table-column prop="actions" label="操作"><template slot-scope="scope"><el-button type="text" @click="redeploy(scope.row)">重新部署</el-button></template></el-table-column><!-- <el-table-column label="部署进度"><template slot-scope="scope"><el-progress :percentage="scope.row.progress" v-if="scope.row.progress"></el-progress></template></el-table-column> --><el-table-column label="部署进度"><template slot-scope="scope"><div style="display: flex; align-items: center;"><el-progress :percentage="scope.row.progress" v-if="scope.row.progress" style="flex: 1;"></el-progress><el-button type="text" @click="viewLogs(scope.row)" style="margin-left: 10px;">查看日志</el-button></div></template></el-table-column></el-table></div><div class="block"><el-pagination :current-page="currentPage" :page-sizes="[5, 10, 15, 20]" :page-size="5" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" /></div></el-card></el-col></el-row><!--新增项目 Drawer 层--><el-drawer title="增加应用" :visible.sync="addDrawerVisible" :direction="direction" size="50%"><el-card shadow="always"><el-form ref="addProjectForm" :model="addProjectForm" status-icon :rules="rules" label-width="100px" class="demo-ruleForm"><el-form-item label="应用名称" prop="name"><el-input v-model="addProjectForm.name" placeholder="请输入应用名称" /></el-form-item><el-form-item><el-button type="primary" @click="addProjectSubmitForm('addProjectForm')">保存</el-button></el-form-item></el-form></el-card></el-drawer><!-- 日志弹出层 --><el-drawer title="日志信息" :visible.sync="viewLogDrawerVisible" :direction="direction" size="50%"><el-card shadow="always"><el-scrollbar ref="logScrollbar" style="height: 800px;"> <!--设置滚动区域的高度--><div v-html="logContent"></div></el-scrollbar></el-card></el-drawer></div>
</template><script>import {getDeploymentsList,viewCICD,addDeployment} from '@/api/deployment/deployment-request'import {message} from 'rhea-promise'import {ElScrollbar} from 'element-ui';export default {name: 'DeploymentPage',data() {return {getDeploymentListDto: [], // 数据传给list,列表渲染的数据total: 0,listLoading: true,dialogVisible: false,currentPage: 1,addDrawerVisible: false,viewLogDrawerVisible: false,direction: 'rtl',logContent: '',jsonstr: {"id": "","projectName": ""},addProjectForm: {name: ""},rules: {name: [{required: true,message: '请输入应用名称',trigger: 'blur'}],},params: {page: 1, // 当前页码page_size: 5 // 每页显示数目},searchMap: {},socket: null}},mounted() {this.getDeploymentsList()},beforeDestroy() {if (this.socket) {this.socket.close()}},methods: {handleSizeChange(val) {console.log(`每页 ${val} 条`)this.params.page_size = valthis.getDeploymentsList()},handleCurrentChange(val) {console.log(`当前页: ${val}`)this.params.page = valthis.getDeploymentsList()},// 格式化 列statusFormatter(row, column, cellValue) {switch (cellValue) {case '0':return '未启动';case '1':return '初始化中';case '2':return '初始化成功';case '3':return '初始失败';case '4':return '部署中';case '5':return '部署成功';case '6':return '部署失败';case '7':return '启动中';case '8':return '启动成功';case '9':return '启动失败';default:return '未知状态';}},// 重置功能, element ui 提供的功能resetForm(formName) {console.log(this.$refs[formName].resetFields)this.$refs[formName].resetFields()this.getDeploymentsList()},searchLog(formName) {console.log(this.searchMap)this.getDeploymentsList()},//新增项目openAddDrawer() {this.addDrawerVisible = true; // 显示Drawer},viewLogs(row) {// 这里可以添加查看日志的逻辑// console.log('查看日志:', row);// // 例如,可以打开一个新的对话框或跳转到日志页面// this.$message.info(`查看日志: ${row.name}`);this.viewLogDrawerVisible = true},// 操作日志列表 ajax 请求getDeploymentsList() {// 目标需求:在历史查询列表页面中加入查询的转圈的loading加载动画。this.dataLoading = trueconsole.log('请求参数:' + this.params)getDeploymentsList(this.params).then((res) => {console.log('响应:', res.data.data)this.getDeploymentListDto = res.data.datathis.total = res.data.pagination.totalsetTimeout(() => { // 超过指定超时时间  关闭查询的转圈的loading加载动画this.listLoading = false}, 1.5 * 1000)})},addProjectSubmitForm(formName) {this.$refs[formName].validate((valid) => {if (valid) {this.addProjectInfo();} else {console.log('error submit!!');this.getDeploymentsList();return false;}});},//增加应用addProjectInfo() {this.dataLoading = trueaddDeployment(this.addProjectForm).then((res) => {console.log(res);this.addDrawerVisible = false; // 关闭抽屉this.getDeploymentsList();this.$refs.addOrgForm.resetFields();// this.$router.push('/organizationList'); // 假设列表页的路由路径是 /listsetTimeout(() => {this.listLoading = false}, 1.5 * 1000)})},redeploy(row) {this.socket = new WebSocket('ws://localhost:8000/ws/cicd_progress/');this.jsonstr.id = row.id;this.jsonstr.projectName = row.name;this.socket.onopen = () => {this.socket.send(JSON.stringify(this.jsonstr));};this.socket.onmessage = (event) => {const data = JSON.parse(event.data);if (data.type === 'progress') {// 处理进度消息if (data.code !== 200) {// 处理错误消息row.status = data.data.status; // 更新当前状态alert(data.data.status)this.getDeploymentsList();} else {// 更新进度条const progress = data.data.progress; // 假设服务器返回的进度数据在progress字段中row.progress = progress; // 更新进度条的百分比row.status = data.data.status; //更新当前状态this.getDeploymentsList();}} else if (data.type === 'news') {// 处理日志消息this.logContent += `<p>${data.data.logInfo}</p>`; // 追加日志this.$nextTick(() => {this.scrollToBottom(); // 每次更新日志后滚动到底部});} else {console.error('Unknown message type:', data.type);}};this.socket.onclose = () => {console.log('WebSocket closed');row.status = '5'; // 假设部署成功后状态为5};this.socket.onerror = (error) => {console.error('WebSocket error:', error);row.status = '6'; // 假设部署失败后状态为6this.$message.error('WebSocket 连接错误'); // 显示错误消息};},scrollToBottom() {const scrollbar = this.$refs.logScrollbar.$refs.wrap;scrollbar.scrollTop = scrollbar.scrollHeight;},}}
</script><style>
</style>

六、效果

#启动前端项目 点击重新发布  点击查看日志
npm run dev

#maven 打包构建 日志显示

#运行 docker run 后   docker logs 日志显示

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/pingmian/62588.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

[MySQL]流程控制语句

流程控制语句需要借助存储过程才有效。关于存储过程&#xff0c;我会在后续的文章详述&#xff0c;本篇文章只是阐述流程控制语句。因此&#xff0c;大家只需要注意存储过程中相应的流程控制语句即可。 如果文中阐述不全或不对的&#xff0c;多多交流。 参考笔记三&#xff0c…

使用 pycharm 新建使用 conda 虚拟 python 环境的工程

1. conda 常见命令复习&#xff1a; conda env list // 查看 conda 环境列表 conda activate xxxenv // 进入指定 conda 环境2. 环境展示&#xff1a; 2.1. 我的物理环境的 Python 版本为 3.10.9&#xff1a; 2.2. 我的 conda 虚拟环境 env_yolov9_python_3_8 中的 pyth…

上传镜像docker hub登不上和docker desktop的etx4.vhdx占用空间很大等解决办法

平时使用docker一般都在Linux服务器上&#xff0c;但这次需要将镜像上传到docker hub上&#xff0c;但是服务器上一直无法登录本人的账号&#xff0c;&#xff08;这里的问题应该docker 网络配置中没有开代理的问题&#xff0c;因服务器上有其他用户使用&#xff0c;不可能直接…

混乱原理与程序设计。

混乱原理就是&#xff1a;对于每一种管控方案&#xff0c;都会对应到一个规模极限和一个效率适配范围&#xff1b;所谓规模极限&#xff0c;就是超过极限就必然会发生失控、产生混乱&#xff1b;适配效率是指极限规模增加必然导致效率降低、成本增加。 在开发语言中&#xff0c…

时频转换 | Matlab基于S变换S-transform一维数据转二维图像方法

目录 基本介绍程序设计参考资料获取方式基本介绍 时频转换 | Matlab基于S变换S-transform一维数据转二维图像方法 程序设计 clear clc % close all load x.mat % 导入数据 x =

【娱乐项目】竖式算术器

Demo介绍 一个加减法随机数生成器&#xff0c;它能够生成随机的加减法题目&#xff0c;并且支持用户输入答案。系统会根据用户输入的答案判断是否正确&#xff0c;统计正确和错误的次数&#xff0c;并显示历史记录和错题记录。该工具适合用于数学练习&#xff0c;尤其适合练习基…

Java抛出自定义运行运行

1.重新生成异常的.java文件 Empty&#xff1a;空 Exception&#xff1a;异常 加起来就是 空指针异常的文件 2.打上extends 运行的异常&#xff08;异常的类型&#xff09; 3.点击ctrlo&#xff0c;选着这两个快捷重写 4.在需要抛出异常的地方写上&#xff1a;th…

使用Github Action将Docker镜像转存到阿里云私有仓库,供国内服务器使用,免费易用

文章目录 一、前言二、 工具准备&#xff1a;三、最终效果示例四、具体步骤第一大部分是配置阿里云1. 首先登录阿里云容器镜像服务 [服务地址](https://cr.console.aliyun.com/cn-hangzhou/instances)2. 选择个人版本3. 创建 命名空间4. 进入访问凭证来查看&#xff0c;用户名字…

YOLO系列论文综述(从YOLOv1到YOLOv11)【第13篇:YOLOv10——实时端到端物体检测】

YOLOv10 1 摘要2 网络结构3 YOLOv1-v10对比 YOLO系列博文&#xff1a; 【第1篇&#xff1a;概述物体检测算法发展史、YOLO应用领域、评价指标和NMS】【第2篇&#xff1a;YOLO系列论文、代码和主要优缺点汇总】【第3篇&#xff1a;YOLOv1——YOLO的开山之作】【第4篇&#xff1a…

Cursor AI快捷键的使用场景及作用

快捷键 Cursor AI 编辑器提供了一系列快捷键&#xff0c;以提高开发者的编程效率和体验。以下是几个常用的快捷键及其使用场景和作用&#xff1a; Ctrl L 或 CMD L&#xff1a; 使用场景&#xff1a;打开对话框&#xff0c;用于与 AI 进行交互。作用&#xff1a;通过对话框&…

Figma入门-自动布局

Figma入门-自动布局 前言 在之前的工作中&#xff0c;大家的原型图都是使用 Axure 制作的&#xff0c;印象中 Figma 一直是个专业设计软件。 最近&#xff0c;很多产品朋友告诉我&#xff0c;很多原型图都开始用Figma制作了&#xff0c;并且很多组件都是内置的&#xff0c;对…

《Java核心技术I》队列与双端队列以及优先队列

队列与双端队列 队列允许你高效的在尾部添加元素&#xff0c;并在头部删除元素。 双端队列(deque)&#xff1a;允许在头部和尾部都高效的添加或删除元素&#xff0c;不支持在中间添加元素。ArrayDeque和LinkedList实现了这个接口。 以下是两个接口的API: java.util.Queue 5…

零基础学安全--Burp Suite(4)proxy模块以及漏洞测试理论

目录 学习连接 一些思路 proxy模块 所在位置 功能简介 使用例子 抓包有一个很重要的点&#xff0c;就是我们可以看到一些在浏览器中看不到的传参点&#xff0c;传参点越多就意味着攻击面越广 学习连接 声明&#xff01; 学习视频来自B站up主 **泷羽sec** 有兴趣的师傅可…

CAD 文件 批量转为PDF或批量打印

CAD 文件 批量转为PDF或批量打印&#xff0c;还是比较稳定的 1.需要本地安装CAD软件 2.通过 Everything 搜索工具搜索&#xff0c;DWG To PDF.pc3 &#xff0c;获取到文件目录 &#xff0c;替换到代码中&#xff0c; originalValue ACADPref.PrinterConfigPath \ r"C:…

【Linux网络编程】TCP套接字

TCP与UDP的区别&#xff1a; udp是无连接的、面向数据报&#xff08;通信时以数据报为单位传输&#xff09;的传输层通信协议&#xff0c;其中每个数据报都是独立的&#xff0c;通信之前不需要建立连接&#xff0c;bind绑定套接字后直接可以进行通信。 tcp是面向连接的、基于字…

spring-boot-maven-plugin 标红

情况&#xff1a;创建好 Spring Boot 项目后&#xff0c;pom.xml 文件中 spring-boot-maven-plugin 标红。 解决方案&#xff1a;加上 Spring Boot 的版本即可解决。

xv6前置知识

fork函数 一个进程,包括代码、数据和分配给进程的资源。fork()函数通过系统调用创建一个与原来进程几乎完全相同的进程,也就是两个进程可以做完全相同的事,但如果初始参数或者传入的变量不同,两个进程也可以做不同的事。 一个进程调用fork()函数后,系统先给新的进程分…

(11)(2.2) BLHeli32 and BLHeli_S ESCs(二)

文章目录 前言 1 传递支持 前言 BLHeli 固件和配置应用程序的开发是为了允许配置 ESC 并提供额外功能。带有此固件的 ESC 允许配置定时、电机方向、LED、电机驱动频率等。在尝试使用 BLHeli 之前&#xff0c;请按照 DShot 设置说明进行操作(DShot setup instructions)。 1 传…

Flink的双流join理解

如何保证Flink双流Join准确性和及时性、除了窗口join还存在哪些实现方式、究竟如何回答才能完全打动面试官呢。。你将在文中找到答案。 1 引子 1.1 数据库SQL中的JOIN 我们先来看看数据库SQL中的JOIN操作。如下所示的订单查询SQL&#xff0c;通过将订单表的id和订单详情表ord…

1.1 数据结构的基本概念

1.1.1 基本概念和术语 一、数据、数据对象、数据元素和数据项的概念和关系 数据&#xff1a;是客观事物的符号表示&#xff0c;是所有能输入到计算机中并被计算机程序处理的符号的总称。 数据是计算机程序加工的原料。 数据对象&#xff1a;是具有相同性质的数据元素的集合&…