Explorar o código

@author liuqing
@commit 网关配置发布更新功能

lq hai 2 meses
pai
achega
8a12f1a3a4

+ 37 - 0
src/api/longchi/device/gatewayconfig.js

@@ -143,3 +143,40 @@ export const setLogCfg = (gid, tenant, data) => {
     data
   })
 }
+
+// 部署相关 API
+export const deployUpload = (file, gid, tenant) => {
+  const formData = new FormData()
+  formData.append('file', file)
+  return request({
+    url: '/api/longchi/device/gatewayconfig/deploy/upload',
+    method: 'post',
+    params: { gid, tenant: tenant || '000000' },
+    data: formData,
+    headers: { 'Content-Type': 'multipart/form-data' }
+  })
+}
+
+export const deployPush = (gid, tenant, version, fileName, filePath, md5) => {
+  return request({
+    url: '/api/longchi/device/gatewayconfig/deploy/push',
+    method: 'post',
+    params: { gid, tenant: tenant || '000000', version, fileName, filePath, md5 }
+  })
+}
+
+export const deployStatus = (gid, tenant) => {
+  return request({
+    url: '/api/longchi/device/gatewayconfig/deploy/status',
+    method: 'get',
+    params: { gid, tenant: tenant || '000000' }
+  })
+}
+
+export const deployBatchStatus = (tenant, gids) => {
+  return request({
+    url: '/api/longchi/device/gatewayconfig/deploy/batch-status',
+    method: 'get',
+    params: { tenant: tenant || '000000', gids }
+  })
+}

+ 276 - 0
src/views/longchi/device/DeployDialog.vue

@@ -0,0 +1,276 @@
+<template>
+  <el-dialog title="一键部署" :visible.sync="visible" width="680px" append-to-body @close="handleClose">
+    <!-- Step 1: Upload -->
+    <div v-if="step === 1">
+      <el-upload
+        ref="uploadRef"
+        drag
+        :auto-upload="false"
+        :limit="1"
+        :on-change="handleFileChange"
+        :on-remove="handleFileRemove"
+        action="">
+        <i class="el-icon-upload"></i>
+        <div class="el-upload__text">将 ipole 文件拖到此处,或<em>点击上传</em></div>
+      </el-upload>
+
+      <el-divider></el-divider>
+
+      <el-descriptions :column="2" border size="small">
+        <el-descriptions-item label="目标网关">{{ gid }}</el-descriptions-item>
+        <el-descriptions-item label="当前版本">{{ currentVersion || '未知' }}</el-descriptions-item>
+        <el-descriptions-item label="文件名">{{ fileInfo.name || '--' }}</el-descriptions-item>
+        <el-descriptions-item label="文件大小">{{ fileInfo.size || '--' }}</el-descriptions-item>
+      </el-descriptions>
+
+      <div style="margin-top: 16px; text-align: right">
+        <el-button @click="handleClose">取消</el-button>
+        <el-button type="primary" :disabled="!fileInfo.name" @click="step = 2">下一步</el-button>
+      </div>
+    </div>
+
+    <!-- Step 2: Confirm -->
+    <div v-if="step === 2">
+      <el-alert title="确认部署信息" type="warning" :closable="false" show-icon style="margin-bottom: 16px">
+        <div>即将把 <strong>{{ gid }}</strong> 升级到新版本</div>
+        <div style="margin-top: 4px; font-size: 12px; color: #909399">
+          部署期间网关将短暂离线,goforever 会自动重启新版本
+        </div>
+      </el-alert>
+
+      <el-descriptions :column="1" border size="small">
+        <el-descriptions-item label="文件">{{ fileInfo.name }} ({{ fileInfo.size }})</el-descriptions-item>
+        <el-descriptions-item label="MD5">{{ fileInfo.md5 || '--' }}</el-descriptions-item>
+      </el-descriptions>
+
+      <div style="margin-top: 16px; text-align: right">
+        <el-button @click="step = 1">上一步</el-button>
+        <el-button type="primary" :loading="pushing" @click="handlePush">确认下发</el-button>
+      </div>
+    </div>
+
+    <!-- Step 3: Result -->
+    <div v-if="step === 3">
+      <div style="text-align: center; padding: 20px 0">
+        <el-steps :active="pipelineStep" finish-status="success" align-center>
+          <el-step title="上传"></el-step>
+          <el-step title="下发"></el-step>
+          <el-step title="P1检测"></el-step>
+          <el-step title="P2检测"></el-step>
+        </el-steps>
+      </div>
+
+      <div v-if="deployResult" style="margin-top: 16px">
+        <el-alert
+          :title="deployResult.success ? '部署成功' : '部署失败'"
+          :type="deployResult.success ? 'success' : 'error'"
+          :closable="false" show-icon>
+        </el-alert>
+
+        <!-- Phase 1 检测项 -->
+        <div style="margin-top: 12px" v-if="deployResult.phase1Checks && deployResult.phase1Checks.length">
+          <p style="font-size:13px;color:#909399;margin-bottom:4px">Phase 1 — 基础设施检测</p>
+          <div v-for="check in deployResult.phase1Checks" :key="check.Name"
+               style="display:flex;align-items:center;padding:6px 0">
+            <i :class="check.Status === 'ok' ? 'el-icon-success' : 'el-icon-error'"
+               :style="{color: check.Status === 'ok' ? '#67c23a' : '#f56c6c'}"></i>
+            <span style="margin-left: 8px">{{ checkLabels[check.Name] || check.Name }}</span>
+            <span style="margin-left: auto; font-size: 12px; color: #909399">{{ check.Detail }}</span>
+          </div>
+        </div>
+
+        <!-- Phase 2 检测项 -->
+        <div style="margin-top: 12px; padding-top: 12px; border-top: 1px solid #eee"
+             v-if="deployResult.phase2Checks && deployResult.phase2Checks.length">
+          <p style="font-size:13px;color:#909399;margin-bottom:4px">Phase 2 — 业务恢复确认</p>
+          <div v-for="check in deployResult.phase2Checks" :key="check.Name"
+               style="display:flex;align-items:center;padding:6px 0">
+            <i :class="check.Status === 'ok' ? 'el-icon-success' : 'el-icon-error'"
+               :style="{color: check.Status === 'ok' ? '#67c23a' : '#f56c6c'}"></i>
+            <span style="margin-left: 8px">{{ checkLabels[check.Name] || check.Name }}</span>
+            <span style="margin-left: auto; font-size: 12px; color: #909399">{{ check.Detail }}</span>
+          </div>
+        </div>
+        <div v-else-if="deployResult.success"
+             style="margin-top:12px;padding:8px;background:#fff3e0;border-radius:4px;font-size:12px;color:#e65100">
+          ⏳ Phase 2 业务恢复检测将在约5分钟后完成,请稍后刷新...
+        </div>
+      </div>
+
+      <div v-if="!deployResult" style="text-align: center; padding: 20px; color: #909399">
+        <i class="el-icon-loading" style="font-size: 24px"></i>
+        <p>等待网关响应...</p>
+        <p style="font-size: 12px">网关正在重启并运行健康检测</p>
+      </div>
+
+      <div style="margin-top: 16px; text-align: right">
+        <el-button @click="handleClose">关闭</el-button>
+      </div>
+    </div>
+  </el-dialog>
+</template>
+
+<script>
+import { deployUpload, deployPush, deployStatus } from '@/api/longchi/device/gatewayconfig.js'
+
+export default {
+  name: 'DeployDialog',
+  props: {
+    gid: { type: String, required: true },
+    tenant: { type: String, required: true },
+    currentVersion: { type: String, default: '' }
+  },
+  data() {
+    return {
+      visible: false,
+      step: 1,
+      fileInfo: {},
+      pushing: false,
+      pipelineStep: 0,
+      deployResult: null,
+      pollTimer: null,
+      p2Timer: null,
+      checkLabels: {
+        mqtt: 'MQTT连接',
+        redis: 'Redis',
+        serial: '串口',
+        modbus: '设备采集',
+        device_online: '设备在线'
+      }
+    }
+  },
+  methods: {
+    open() {
+      this.visible = true
+      this.step = 1
+      this.fileInfo = {}
+      this.deployResult = null
+    },
+    handleFileChange(file) {
+      this.fileInfo = {
+        name: file.name,
+        size: this.formatSize(file.size),
+        file: file.raw
+      }
+    },
+    handleFileRemove() {
+      this.fileInfo = {}
+    },
+    formatSize(bytes) {
+      if (bytes < 1024) return bytes + ' B'
+      if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB'
+      return (bytes / (1024 * 1024)).toFixed(1) + ' MB'
+    },
+    async handlePush() {
+      this.pushing = true
+      try {
+        // 1. Upload
+        this.pipelineStep = 0
+        const uploadRes = await deployUpload(this.fileInfo.file, this.gid, this.tenant)
+        if (uploadRes.data.code !== 0) {
+          this.$message.error('上传失败: ' + (uploadRes.data.message || '未知错误'))
+          this.pushing = false
+          return
+        }
+        this.pipelineStep = 1
+        this.fileInfo.md5 = uploadRes.data.data.md5
+
+        // 2. Push
+        const pushRes = await deployPush(
+          this.gid, this.tenant, '', 'ipole',
+          uploadRes.data.data.path, uploadRes.data.data.md5
+        )
+        if (pushRes.data.code !== 0) {
+          this.$message.error('下发失败: ' + (pushRes.data.message || '未知错误'))
+          this.pushing = false
+          return
+        }
+        this.pipelineStep = 2
+
+        // 3. Poll results
+        this.step = 3
+        this.pollResult()
+      } catch (e) {
+        this.$message.error('部署失败: ' + (e.message || e))
+      }
+      this.pushing = false
+    },
+    pollResult() {
+      let attempts = 0
+      this.pollTimer = setInterval(async () => {
+        attempts++
+        try {
+          const res = await deployStatus(this.gid)
+          if (res.data.code === 0 && res.data.data) {
+            const d = res.data.data
+            // status !== 0 说明部署已结束,但需等 phase1Result 有值(health 数据晚于 ack 到达)
+            if (d.status !== 0 && d.phase1Result) {
+              clearInterval(this.pollTimer)
+              const p1 = JSON.parse(d.phase1Result)
+              const p2 = d.phase2Result ? JSON.parse(d.phase2Result) : null
+              this.deployResult = {
+                success: d.status === 1,
+                phase1Checks: p1 ? p1.Checks : [],
+                phase2Checks: p2 ? p2.Checks : []
+              }
+              this.pipelineStep = p2 ? 5 : 4
+              // P1 有数据但 P2 为空,继续慢速轮询等 P2
+              if (!p2) {
+                this.pollPhase2()
+              }
+            }
+            // 部署失败(status=2/3),无需等 health,直接展示
+            if (d.status === 2 || d.status === 3) {
+              clearInterval(this.pollTimer)
+              const p1 = d.phase1Result ? JSON.parse(d.phase1Result) : null
+              this.deployResult = {
+                success: false,
+                phase1Checks: p1 ? p1.Checks : [],
+                phase2Checks: [],
+                error: d.errorMsg
+              }
+            }
+          }
+        } catch (e) {
+          // continue polling
+        }
+        if (attempts > 120) {
+          clearInterval(this.pollTimer)
+          this.$message.warning('等待超时,请手动检查网关状态')
+        }
+      }, 3000)
+    },
+    pollPhase2() {
+      let attempts = 0
+      this.p2Timer = setInterval(async () => {
+        attempts++
+        try {
+          const res = await deployStatus(this.gid)
+          if (res.data.code === 0 && res.data.data && res.data.data.phase2Result) {
+            clearInterval(this.p2Timer)
+            const p2 = JSON.parse(res.data.data.phase2Result)
+            this.deployResult.phase2Checks = p2.Checks || []
+            this.pipelineStep = 5
+          }
+        } catch (e) {
+          // continue
+        }
+        if (attempts > 40) { // 10s × 40 = ~7min
+          clearInterval(this.p2Timer)
+        }
+      }, 10000)
+    },
+    handleClose() {
+      if (this.pollTimer) {
+        clearInterval(this.pollTimer)
+      }
+      if (this.p2Timer) {
+        clearInterval(this.p2Timer)
+      }
+      this.visible = false
+      this.$emit('close')
+      this.$emit('refresh')
+    }
+  }
+}
+</script>

+ 91 - 1
src/views/longchi/device/wisdomgateway.vue

@@ -41,6 +41,7 @@
                @refresh-change="refreshChange"
                @on-load="onLoad">
       <template slot="menu" slot-scope="{row}">
+        <el-button type="primary" size="small" icon="el-icon-upload2" @click="openDeploy(row)">部署</el-button>
         <el-button type="text" size="small" icon="el-icon-setting" @click="openGatewayConfig(row)">配置下发</el-button>
       </template>
       <!-- <template slot="menuLeft">
@@ -109,6 +110,42 @@
          <amap-long :row="row" :arriveIcon="row.networkState == 1 ? (row.runState ==1 ? arriveIcon : arriveIcon2) : arriveIcon3"></amap-long>
         </div>
       </template>
+      <template slot-scope="{row}" slot="deployStatus">
+        <el-popover v-if="deployStatusMap[row.gatewaySn]"
+                    trigger="click" placement="right" width="360"
+                    @show="showDeployDetail(row.gatewaySn)">
+          <div slot="reference" style="cursor:pointer">
+            <span v-if="deployStatusMap[row.gatewaySn].status === 0"
+                  style="color:#e6a23c"><i class="el-icon-loading"></i> 部署中...</span>
+            <span v-else-if="deployStatusMap[row.gatewaySn].status === 1"
+                  style="color:#67c23a">已部署 {{ deployStatusMap[row.gatewaySn].toVersion }}</span>
+            <span v-else-if="deployStatusMap[row.gatewaySn].status === 2"
+                  style="color:#f56c6c">部署失败</span>
+            <span v-else-if="deployStatusMap[row.gatewaySn].status === 3"
+                  style="color:#e6a23c">已回滚</span>
+          </div>
+          <div v-if="deployDetail" style="font-size:13px;line-height:2">
+            <p style="color:#909399">版本: {{ deployDetail.toVersion }}</p>
+            <p style="color:#909399">时间: {{ deployDetail.createTime }}</p>
+            <p v-if="deployDetail.errorMsg" style="color:#f56c6c">{{ deployDetail.errorMsg }}</p>
+            <div v-if="deployDetail.phase1Checks && deployDetail.phase1Checks.length">
+              <p style="font-weight:bold;margin-top:8px">Phase 1 — 基础设施检测</p>
+              <div v-for="c in deployDetail.phase1Checks" :key="c.Name">
+                {{ c.Status === 'ok' ? '✅' : '❌' }} {{ checkLabels[c.Name] || c.Name }}
+                <span style="color:#909399;font-size:12px"> — {{ c.Detail }}</span>
+              </div>
+            </div>
+            <div v-if="deployDetail.phase2Checks && deployDetail.phase2Checks.length">
+              <p style="font-weight:bold;margin-top:8px">Phase 2 — 业务恢复确认</p>
+              <div v-for="c in deployDetail.phase2Checks" :key="c.Name">
+                {{ c.Status === 'ok' ? '✅' : '❌' }} {{ checkLabels[c.Name] || c.Name }}
+                <span style="color:#909399;font-size:12px"> — {{ c.Detail }}</span>
+              </div>
+            </div>
+          </div>
+        </el-popover>
+        <span v-else style="color:#c0c4cc">未部署</span>
+      </template>
     </avue-crud>
     <el-dialog
       title="连接设备" left :close-on-click-modal="false"
@@ -462,6 +499,8 @@
       :gatewayName="configGatewayName"
       :tenant="configTenant"
     />
+    <DeployDialog ref="deployDialog" :gid="deployGid" :tenant="deployTenant"
+      :currentVersion="deployVersion" @close="refreshChange" @refresh="loadDeployStatus" />
   </basic-container>
 </template>
 
@@ -470,13 +509,16 @@
   import {mapGetters} from "vuex";
   import amapLong from '../amapLong2'
   import GatewayConfigDialog from './GatewayConfigDialog.vue'
+  import DeployDialog from './DeployDialog.vue'
   import website from '@/config/website';
   import {getToken} from '@/util/auth';
   import {filterParams} from '@/util/validate'
+  import {deployBatchStatus} from '@/api/longchi/device/gatewayconfig.js'
   export default {
     components:{
       amapLong,
-      GatewayConfigDialog
+      GatewayConfigDialog,
+      DeployDialog
     },
     data() {
       const validateIp = (rule, value, callback) => {
@@ -504,6 +546,15 @@
         configGatewayId: '',
         configGatewayName: '',
         configTenant: '',
+        deployGid: '',
+        deployTenant: '',
+        deployVersion: '',
+        deployStatusMap: {},
+        deployDetail: null,
+        checkLabels: {
+          mqtt: 'MQTT连接', redis: 'Redis', serial: '串口',
+          modbus: '设备采集', device_online: '设备在线'
+        },
         cameraList:[],
         activeName: 'first',
         excelBox: false,
@@ -753,6 +804,15 @@
                 trigger: "change"
               }]
             },
+            {
+              label: "部署状态",
+              prop: "deployStatus",
+              width: 150,
+              align: "center",
+              addDisplay: false,
+              editDisplay: false,
+              slot: true
+            },
             {
               label: "ip地址",
               prop: "ipAddress",
@@ -1034,6 +1094,7 @@
           this.data = data.records;
           this.loading = false;
           this.selectionClear();
+          this.loadDeployStatus();
         });
       },
       searchHand(page, params = {}){       // 搜索事件
@@ -1048,6 +1109,7 @@
           this.data = data.records;
           this.loading = false;
           this.selectionClear();
+          this.loadDeployStatus();
         });
       },
       getLampPoleListFun(){
@@ -1099,6 +1161,34 @@
         this.configTenant = row.tenantCode || this.tenantId;
         this.gatewayConfigVisible = true;
       },
+      openDeploy(row) {
+        this.deployGid = row.gatewaySn || ''
+        this.deployTenant = row.tenantCode || ''
+        this.deployVersion = row.version || row.Version || ''
+        this.$nextTick(() => {
+          this.$refs.deployDialog.open()
+        })
+      },
+      loadDeployStatus() {
+        const rows = this.data || []
+        const gids = rows.map(r => r.gatewaySn).filter(Boolean).join(',')
+        if (!gids) return
+        const tenant = (this.data && this.data.length > 0 && this.data[0].tenantCode) || '000000'
+        deployBatchStatus(tenant, gids).then(res => {
+          if (res.data.code === 0) {
+            this.deployStatusMap = res.data.data || {}
+          }
+        })
+      },
+      showDeployDetail(gid) {
+        const d = this.deployStatusMap[gid]
+        if (!d) { this.deployDetail = null; return }
+        this.deployDetail = {
+          ...d,
+          phase1Checks: d.phase1Result ? JSON.parse(d.phase1Result).Checks : [],
+          phase2Checks: d.phase2Result ? JSON.parse(d.phase2Result).Checks : []
+        }
+      },
       getTenantCodeFun(){
        let _this = this;
        getTenantCode('ZHWG').then((res) =>{