Commit 5b640397 authored by 王曜嵚 Wang Yaoqin's avatar 王曜嵚 Wang Yaoqin

dev: v2 接口

parent 14984ae5
import { useUserStore } from "~/store/user"
export default defineNuxtRouteMiddleware((to, from) => { export default defineNuxtRouteMiddleware((to, from) => {
const user = useUserStore() if (to.path === '/') {
if (!user.username && to.path !== '/login') {
return navigateTo('/login') return navigateTo('/login')
} }
}) })
\ No newline at end of file
This diff is collapsed.
...@@ -11,14 +11,20 @@ ...@@ -11,14 +11,20 @@
}, },
"dependencies": { "dependencies": {
"@pinia/nuxt": "^0.5.1", "@pinia/nuxt": "^0.5.1",
"dockerode": "^3.3.5",
"lodash": "^4.17.21", "lodash": "^4.17.21",
"nuxt": "^3.11.1", "nuxt": "^3.11.1",
"pg": "^8.11.5",
"pinia": "^2.1.7", "pinia": "^2.1.7",
"tar-fs": "^3.0.5",
"telnet-client": "^2.2.0", "telnet-client": "^2.2.0",
"vue": "^3.4.21", "vue": "^3.4.21",
"vue-router": "^4.3.0" "vue-router": "^4.3.0"
}, },
"devDependencies": { "devDependencies": {
"@types/lodash": "^4.17.0" "@types/dockerode": "^3.3.28",
"@types/lodash": "^4.17.0",
"@types/pg": "^8.11.4",
"@types/tar-fs": "^2.0.4"
} }
} }
...@@ -178,7 +178,7 @@ function handleInstall() { ...@@ -178,7 +178,7 @@ function handleInstall() {
logs.value = [] logs.value = []
loading.value = true loading.value = true
status.value = 'creating' status.value = 'creating'
$fetch('/api/installProject', { method: 'post' }) $fetch('/api/devops/v2/install', { method: 'post' })
.then(handleGetStatus, handleGetStatus) .then(handleGetStatus, handleGetStatus)
.finally(() => { .finally(() => {
loading.value = false loading.value = false
......
export default defineEventHandler((event) => {
let username = req.session.user as string || '1234'
let docker = createDockerFactory(username)
let container = await docker.checkContainer('logwire_backend_helper.' + username + '.node')
if (!container) {
// 不存在容器,则说明用户还没初始化
res.sendStatus(200)
return
}
let info = await container.inspect()
if (info.State.Running) {
// 正在运行,则认为正常
res.sendStatus(200)
} else {
LogUtil.print(username, `[progress] [[1;34mInfo[m] 服务器异常关闭,正在重启...... \n`)
await docker.startContainer({ container })
// 依次打开 nginx, 后端服务,vscode-web
try {
await docker.execContainerCommand({ container, cmd: 'lsof -i:80' })
} catch (err) {
try {
await docker.execContainerCommand({ container, cmd: 'nginx' })
LogUtil.print(username, `[progress] [[1;34mInfo[m] Nginx 重启成功...... \n`)
} catch (err) {
res.status(500).send(err)
}
}
try {
await docker.execContainerCommand({ container, cmd: 'lsof -i:8000' })
} catch (err) {
try {
docker.execContainerCommand({ container, cmd: 'code-server --bind-addr 127.0.0.1:8000 --auth none' })
LogUtil.print(username, `[progress] [[1;34mInfo[m] Vscode 重启成功...... \n`)
} catch (err) {
res.status(500).send(err)
}
}
try {
await docker.execContainerCommand({ container, cmd: 'pm2 delete backend' })
await docker.execContainerCommand({ container, cmd: 'pm2 delete gateway' })
} catch (err) {
}
await docker.execContainerCommand({ container, cmd: 'pm2 start --name gateway --no-autorestart java -- -Xms128m -Xmx128m -XX:+UseG1GC --add-opens java.base/sun.util.locale.provider=ALL-UNNAMED -jar logwire-gateway-starter.jar', dir: '/var/logwire-backend/build-output/gateway', quiet: true })
await docker.execContainerCommand({ container, cmd: `pm2 start --name backend --no-autorestart java -- -Xms128m -Xmx128m -XX:+UseG1GC -DVALIDATE_XML_ENABLED=false --add-opens java.base/sun.util.locale.provider=ALL-UNNAMED -jar logwire-backend-starter.jar`, dir: '/var/logwire-backend/build-output/backend', quiet: true })
LogUtil.print(username, `[progress] [[1;34mInfo[m] 服务重启成功...... \n`)
res.sendStatus(200)
}
})
\ No newline at end of file
import LogUtil from "~/server/utils/log"
import { copyAndCreateGatewayPropertiesV2InDocker, copyAndCreateServerPropertiesV2InDocker } from "~/server/utils/server"
export default defineEventHandler(async (event) => {
try {
let username = event.context.username
let docker = createDockerFactory(username)
let port = getUserConfig(username, 'node-port')
setUserConfig(username, 'status', 'compiling')
// 每次编译前把已有的 tenants_config 文件夹拷贝到一个地方,编译完成后,再拷贝回来
let container = await docker.checkContainer('logwire_backend_helper.' + username + '.node')
if (!container) {
throw new Error('没有创建容器,请先初始化容器')
}
await docker.startContainer({ container })
await docker.preStartSystem({ container, username, platform: 'v2'})
try {
await docker.execContainerCommand({ container, cmd: 'mv -bf build-output/backend/tenants_config/ ../tenants_config', dir: '/var/logwire-backend' })
} catch (err) {
}
LogUtil.print(username, `[progress] [[1;34mInfo[m] 编译中..... \n`)
await docker.execContainerCommand({ container, cmd: 'bash build-release.sh --module=logwire', dir: '/var/logwire-backend', quiet: true })
await docker.execContainerCommand({ container, cmd: 'bash build-release.sh --module=assemble', dir: '/var/logwire-backend', quiet: true })
try {
// 打包完成后,移动默认配置文件, 修改配置文件信息
await docker.execContainerCommand({ container, cmd: 'mv -f ../tenants_config build-output/backend/', dir: '/var/logwire-backend' })
await docker.execContainerCommand({ container, cmd: 'chmod 755 build-output/backend/transform-miniapp.sh', dir: '/var/logwire-backend' })
} catch (err) {
}
copyAndCreateServerPropertiesV2InDocker(username)
copyAndCreateGatewayPropertiesV2InDocker(username)
LogUtil.print(username, `[progress] [[1;34mInfo[m] 编译完成 \n`)
setUserConfig(username, 'status', 'created')
} catch (err) {
let username = event.context.username
LogUtil.print(username, '[error] [[1;31mError[m]] ' + (err instanceof Error ? err.message : JSON.stringify(err)))
setResponseStatus(event, 500)
}
})
\ No newline at end of file
import LogUtil from "~/server/utils/log"
export default defineEventHandler(async (event) => {
// 先判断服务是否启动,启动则关闭,然后调用新的命令启动 java 端
try {
let username = event.context.username
let docker = createDockerFactory(username)
let container = await docker.checkContainer('logwire_backend_helper.' + username + '.node')
if (!container) {
throw new Error('没有创建容器,请先初始化容器')
}
const status = getUserConfig(username, 'status')
const tenants = getUserConfig(username, 'tenants')
const port = getUserConfig(username, 'node-port')
const debug = getUserConfig(username, 'debug') || { host: '192.168.0.190' }
// 有可能本身就关闭了
try {
LogUtil.print(username, `[progress] [[1;34mLoading[m] 关闭已存在的 Nginx 服务 ...... \n`)
await docker.execContainerCommand({ container, cmd: 'nginx -s stop'})
} catch (err) {}
await LogUtil.run(username, '初始化调试功能', async () => {
let key = 'InstallSteps'
let steps: string[] = getUserConfig(username, key) || []
if (steps.includes('初始化调试功能')) return
try {
if (container) {
LogUtil.print(username, `[progress] [Loading] 下载 Nginx ...... \n`)
await docker.execContainerCommand({ container, cmd: 'curl -O https://nginx.org/download/nginx-1.18.0.tar.gz', dir: '/var/tmp' })
LogUtil.print(username, `[progress] [Loading] 解压 Nginx ...... \n`)
await docker.execContainerCommand({ container, cmd: 'tar -xvzf nginx-1.18.0.tar.gz', dir: '/var/tmp'})
LogUtil.print(username, `[progress] [Loading] 配置 Nginx ...... \n`)
await docker.execContainerCommand({ container, cmd: './configure --prefix=/usr/share/nginx/ --conf-path=/etc/nginx/nginx.conf --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log --lock-path=/var/lock/nginx.lock --pid-path=/run/nginx.pid --modules-path=/usr/lib/nginx/modules --http-client-body-temp-path=/var/lib/nginx/body --http-fastcgi-temp-path=/var/lib/nginx/fastcgi --http-proxy-temp-path=/var/lib/nginx/proxy --http-scgi-temp-path=/var/lib/nginx/scgi --http-uwsgi-temp-path=/var/lib/nginx/uwsgi --with-compat --with-debug --with-pcre-jit --with-http_ssl_module --with-http_stub_status_module --with-http_realip_module --with-http_auth_request_module --with-http_v2_module --with-http_dav_module --with-http_slice_module --with-threads --with-http_addition_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_sub_module --with-stream=dynamic', dir: '/var/tmp/nginx-1.18.0' })
LogUtil.print(username, `[progress] [Loading] 编译 Nginx ...... \n`)
await docker.execContainerCommand({ container, cmd: 'make', dir: '/var/tmp/nginx-1.18.0'})
LogUtil.print(username, `[progress] [Loading] 替换 Nginx 文件 ...... \n`)
await docker.execContainerCommand({ container, cmd: 'cp /var/tmp/nginx-1.18.0/objs/nginx /usr/sbin/'})
}
} catch (err) {
console.log('err2', err)
throw err
}
})
LogUtil.print(username, `[progress] [[1;34mLoading[m] 替换 Nginx 配置 ...... \n`)
await copyAndCreateNginxConfInDocker(username)
LogUtil.print(username, `[progress] [[1;34mLoading[m] 启动 Nginx ...... \n`)
await docker.execContainerCommand({ container, cmd: 'nginx'})
LogUtil.print(username, `[progress] [[1;34mInfo[m] 程序启动中...... \n`)
try {
await docker.execContainerCommand({ container, cmd: 'pm2 delete backend' })
await docker.execContainerCommand({ container, cmd: 'pm2 delete gateway' })
} catch (err) {
}
await docker.execContainerCommand({ container, cmd: 'pm2 start --name gateway --no-autorestart java -- -Xms128m -Xmx128m -XX:+UseG1GC --add-opens java.base/sun.util.locale.provider=ALL-UNNAMED -jar logwire-gateway-starter.jar', dir: '/var/logwire-backend/build-output/gateway', quiet: true })
await docker.execContainerCommand({ container, cmd: 'pm2 start --name backend --no-autorestart java -- -Xms128m -Xmx128m -XX:+UseG1GC -DVALIDATE_XML_ENABLED=false --add-opens java.base/sun.util.locale.provider=ALL-UNNAMED -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=:6666,suspend=n -jar logwire-backend-starter.jar', dir: '/var/logwire-backend/build-output/backend', quiet: true })
LogUtil.print(username, `[progress] [[1;34mInfo[m] 程序运行中...... \n`)
LogUtil.print(username, `[progress] [[1;34mInfo[m] 请代理后端请求到 <strong>192.168.0.4:${port}</strong> 上 \n`)
LogUtil.print(username, `[progress] [[1;34mInfo[m] 请设置开发环境域名和端口号 <strong>${tenants.host}</strong> 上\n`)
LogUtil.print(username, `[progress] [[1;34mInfo[m] 调试程序已启动,请IP地址为 <strong>${debug?.host}</strong> 后端访问 <strong>192.168.0.4:${port}</strong> 进行调试\n`)
setUserConfig(username, 'status', 'running')
} catch (err) {
setResponseStatus(event, 500)
return err
}
})
\ No newline at end of file
import LogUtil from "~/server/utils/log"
export default defineEventHandler(async (event) => {
try {
let username = event.context.username
let docker = createDockerFactory(username)
let container = await docker.checkContainer('logwire_backend_helper.' + username + '.node')
let tenants = getUserConfig(username, 'tenants')
let port = getUserConfig(username, 'node-port')
LogUtil.printInfo(username, `程序初始化中......`)
if (!container) {
throw new Error('没有创建容器,请先初始化容器')
}
// 有可能本身就关闭了
try {
await docker.execContainerCommand({ container, cmd: 'nginx -s stop'})
} catch (err) {}
await docker.preStartSystem({ container, username, platform: 'v2'})
await copyAndCreateNginxConfInDocker(username)
await docker.execContainerCommand({ container, cmd: 'nginx'})
await docker.execContainerCommand({ container, cmd: 'pm2 start --name gateway --no-autorestart java -- -Xms128m -Xmx128m -XX:+UseG1GC --add-opens java.base/sun.util.locale.provider=ALL-UNNAMED -jar logwire-gateway-starter.jar', dir: '/var/logwire-backend/build-output/gateway', quiet: true })
await docker.execContainerCommand({ container, cmd: `pm2 start --name backend --no-autorestart java -- -Xms128m -Xmx128m -XX:+UseG1GC -DVALIDATE_XML_ENABLED=false --add-opens java.base/sun.util.locale.provider=ALL-UNNAMED -jar logwire-backend-starter.jar`, dir: '/var/logwire-backend/build-output/backend', quiet: true })
LogUtil.printInfo(username, `程序运行中......`)
LogUtil.printInfo(username, `请代理后端请求到 <strong>192.168.0.4:${port}</strong> 上`)
LogUtil.printInfo(username, `请设置开发环境域名和端口号 <strong>${tenants.host}</strong> 上`)
setUserConfig(username, 'status', 'running')
} catch (err) {
let username = event.context.username
LogUtil.printError(username, (err instanceof Error ? err.message : JSON.stringify(err)))
setResponseStatus(event, 500)
return err
}
})
\ No newline at end of file
This diff is collapsed.
import LogUtil from "~/server/utils/log"
export default defineEventHandler(async (event) => {
try {
let username = event.context.username
let docker = createDockerFactory(username)
let container = await docker.checkContainer('logwire_backend_helper.' + username + '.node')
if (!container) {
throw new Error('没有创建容器,请先初始化容器')
}
LogUtil.printInfo(username, `程序停止中......`)
await docker.execContainerCommand({ container, cmd: 'pm2 delete backend', quiet: true })
await docker.execContainerCommand({ container, cmd: 'pm2 delete gateway', quiet: true })
LogUtil.print(username, `程序已停止`)
setUserConfig(username, 'status', 'stopped')
} catch (err) {
setResponseStatus(event, 500)
return err
}
})
\ No newline at end of file
import LogUtil from "~/server/utils/log"
export default defineEventHandler(async (event) => {
try {
let username = event.context.username
let docker = createDockerFactory(username)
let container = await docker.checkContainer('logwire_backend_helper.' + username + '.node')
LogUtil.printInfo(username, '测试消息')
} catch (err) {
setResponseStatus(event, 500)
return err
}
})
\ No newline at end of file
export default defineEventHandler(async (event) => { export default defineEventHandler(async (event) => {
const session = await getSession(event, { password: '123456abcdefghijklmnopqrstuvwxyz'}) const username = event.context.username
const username = 'wyq' const configs = getUserAllConfigs(username)
console.log('session', session)
let configs = getUserAllConfigs(username)
return configs return configs
}) })
\ No newline at end of file
import { readJson, writeJson } from "../../utils" import { SESSION_PASSWORD, readJson, writeJson } from "../../utils"
import { getAvailableNodePort, getUserAllConfigs, getUserConfig } from "../../utils/server" import { getAvailableNodePort, getUserAllConfigs, getUserConfig } from "../../utils/server"
export default defineEventHandler(async (event) => { export default defineEventHandler(async (event) => {
...@@ -17,7 +17,9 @@ export default defineEventHandler(async (event) => { ...@@ -17,7 +17,9 @@ export default defineEventHandler(async (event) => {
const userDataPath = `./server/data/${username}.json` const userDataPath = `./server/data/${username}.json`
writeJson(userDataPath, userSetting) writeJson(userDataPath, userSetting)
} }
return useSession(event, { name: username, password: '123456abcdefghijklmnopqrstuvwxyz' }) const session = await useSession(event, { password: SESSION_PASSWORD })
await session.update({ username })
return session.data
} catch (err) { } catch (err) {
console.log(err) console.log(err)
throw createError({ throw createError({
......
{
"postgres": {
"visible": false,
"username": "postgres",
"password": "postgres",
"ip": "192.168.0.4",
"port": "25556",
"database": {
"username": "wyq"
},
"schema": "library"
},
"redis": {
"visible": false,
"ip": "192.168.0.4",
"port": "25557"
},
"zookeeper": {
"visible": false,
"ip": "192.168.0.4",
"port": "2182"
},
"rocketmq": {
"visible": false,
"ip": "192.168.0.4",
"port": "9876"
},
"tenants": {
"visible": false,
"id": {
"username": "wyq"
},
"host": "a.test.com:23333,a.test.com:23334",
"database-schema": "library",
"primary-namespace": "library"
},
"postgresV1": {
"visible": false,
"username": "postgres",
"password": "postgres",
"ip": "192.168.0.4",
"port": "25556",
"database": "logwirev2",
"schema": "library"
},
"redisV1": {
"visible": false,
"ip": "192.168.0.4",
"port": "25557"
},
"tenantsV1": {
"visible": false,
"id": "wongyaqi",
"port": 8080
},
"debug": {
"host": "192.168.1.94"
},
"node-port": 30000
}
\ No newline at end of file
console
console
\ No newline at end of file
export default defineEventHandler((event) => { import { SESSION_PASSWORD } from "../utils"
// console.log(event)
declare module 'h3' {
interface H3EventContext {
username: string
}
}
export default defineEventHandler(async (event) => {
const session = await useSession(event, { password: SESSION_PASSWORD })
if (session.data && session.data.username) {
event.context.username = session.data.username
} else {
const nonAuthorizedUrls = ['/login', '/', '/api/user/login']
const url = event.node.req.url || '/'
if (!nonAuthorizedUrls.includes(url)) {
throw createError({
statusCode: 401,
message: '未授权'
})
}
}
}) })
\ No newline at end of file
/**
* TODOLIST
* * [ ] 根据操作系统的不同,获取到特定的 Docker 对象
* * [ ] 查询容器状态
* * [ ] 安装镜像容器
* * [ ] 在容器内操作命令, Docker API.exec
*/
import Dockerode from 'dockerode'
import { chmod, createReadStream, createWriteStream, mkdirSync, readFileSync, rmdirSync, rmSync } from 'fs'
import { resolve } from 'path'
import { getUserConfig, setUserConfig } from './server'
import { removeUnreadCharacter } from '.'
import LogUtil from './log'
import tar from 'tar-fs'
class Docker {
docker: Dockerode
username: string
env: string[]
host: string
constructor (host = 'host.docker.internal', username: string) {
this.host = host
this.docker = new Dockerode({ host, port: 2375 })
this.username = username
this.env = []
}
async checkContainer (name: string) {
let targetContainerName = name
let containers = await this.docker.listContainers({ filters: JSON.stringify({ status: ['created', 'restarting', 'running', 'removing', 'paused', 'exited', 'dead' ], name: [targetContainerName] }) })
if (containers.length) {
let container = await this.docker.getContainer(containers[0].Id)
return container
} else {
return
}
}
async checkAndCreateContainer ({ name, img, env, portBindings, cmd, exposedPorts }: { name: string, img: string, env?: string[], portBindings?: Record<string, any>, cmd?: string[], exposedPorts?: Record<string, any> }) {
let targetContainerName = 'logwire_backend_helper.' + name
let containers = await this.docker.listContainers({ filters: JSON.stringify({ status: ['created', 'restarting', 'running', 'removing', 'paused', 'exited', 'dead' ], name: [targetContainerName] }) })
if (containers.length) {
let container = await this.docker.getContainer(containers[0].Id)
return container
} else {
let images = await this.docker.listImages({ filters: `{ "reference": ["${img}"] }` })
if (images.length === 0) {
await new Promise<void>((resolve, reject) => {
this.docker.pull(img, (err: any, stream: any) => {
this.docker.modem.followProgress(stream, onFinished, onProgress);
function onFinished(err: any, output: any) {
if (!err) {
resolve()
} else {
reject(err)
}
}
function onProgress(event: any) {
}
})
})
}
let opt = {
name: targetContainerName,
"Tty": true,
Image: img,
Env: env,
Cmd: cmd,
ExposedPorts: exposedPorts,
HostConfig: {
PortBindings: portBindings || {}
}
}
return this.docker.createContainer(opt)
}
}
async startContainer({ container }: { container: Dockerode.Container }) {
let info = await container.inspect()
if (info.State.Running) {
} else {
await container.start()
}
return container
}
async execContainerCommand ({ container, cmd, dir, quiet }: {container: Dockerode.Container, cmd: string | string[], dir?: string, quiet?: boolean }) {
let exec = await container.exec({
Cmd: cmd instanceof Array ? cmd : cmd.split(' '),
AttachStdout: true,
AttachStderr: true,
WorkingDir: dir,
User: 'root',
Env: this.env
})
let result = await exec?.start({})
return new Promise<string>((resolve, reject) => {
let logs = ''
let data = ''
result?.on('data', chunk => {
let text = removeUnreadCharacter(chunk.toString())
!quiet && LogUtil.print(this.username, '[info] ' + text )
logs += text
data += text
logs = logs.substring(logs.length - 1200)
})
result?.on('error', error => {
logs += error.message + '\n' + error.stack
})
result?.on('end', async () => {
let info = await exec.inspect()
if (info?.ExitCode) {
reject({ command: cmd, message: 'ExitCode: ' + info.ExitCode, exitcode: info.ExitCode, logs })
} else {
resolve(data)
}
})
})
}
async putArchive ({ container, tarPath, targetPath }: { container: Dockerode.Container, tarPath: string, targetPath: string }) {
return new Promise((resolve) => {
container.putArchive(tarPath, { path: targetPath }).then(resolve)
})
}
async writeFile ({ container, path, text }: { container: Dockerode.Container, path: string, text: string }) {
await this.execContainerCommand({ container, cmd: ['bash', '-c', 'echo ' + text + ' > ' + path] })
}
async appendFile({ container, path, text }: { container: Dockerode.Container, path: string, text: string }) {
await this.execContainerCommand({ container, cmd: ['bash', '-c', 'echo ' + text + ' >> ' + path] })
}
async getFile ({ container, path }: { container: Dockerode.Container, path: string }): Promise<string> {
return new Promise(async (resolve, reject) => {
try {
let readstream = await container.getArchive({ path })
let tempFilePath = './temp_' + Math.random() + '.tar'
let tempUnpackFolder = tempFilePath.replace('.tar', '')
let tempUnpackFile = tempUnpackFolder + '/' + path.replace(/.*\//, '')
mkdirSync(tempUnpackFolder)
let writestream = createWriteStream(tempFilePath)
readstream.pipe(writestream).on('finish', () => {
createReadStream(tempFilePath).pipe(tar.extract(tempUnpackFolder)).on('finish', () => {
let content = readFileSync(tempUnpackFile, { encoding: 'utf-8' })
rmSync(tempFilePath)
rmSync(tempUnpackFolder, { recursive: true, force: true })
resolve(content)
})
})
} catch (err) {
reject(err)
}
})
}
async switchJavaVersion ({ container, username, version }: { container: Dockerode.Container, username: string, version: 17 | 8}) {
LogUtil.printInfo(username, '更换 Java 环境')
await this.execContainerCommand({ container, cmd: 'rm /etc/alternatives/java'})
if (version === 8) {
await this.execContainerCommand({ container, cmd: 'ln -s /var/java-8-openjdk/bin/java /etc/alternatives/java'})
} else {
await this.execContainerCommand({ container, cmd: 'ln -s /var/java-17-openjdk/bin/java /etc/alternatives/java'})
}
}
async preStartSystem ({ container, username, platform }: { container: Dockerode.Container, username: string, platform: 'v1' | 'v2' }) {
try {
await this.execContainerCommand({ container, cmd: 'rm /root/.pm2/logs/backend-out.log'})
await this.execContainerCommand({ container, cmd: 'rm /root/.pm2/logs/backend-error.log'})
await this.execContainerCommand({ container, cmd: 'rm /root/.pm2/logs/gateway-out.log'})
await this.execContainerCommand({ container, cmd: 'rm /root/.pm2/logs/gateway-out.log'})
await this.execContainerCommand({ container, cmd: 'rm /root/.pm2/logs/platform-out.log'})
await this.execContainerCommand({ container, cmd: 'rm /root/.pm2/logs/platform-out.log'})
} catch (err) {
}
try { await this.execContainerCommand({ container, cmd: 'pm2 delete backend' }) } catch (err) {}
try { await this.execContainerCommand({ container, cmd: 'pm2 delete gateway' }) } catch (err) {}
try { await this.execContainerCommand({ container, cmd: 'pm2 delete platform' }) } catch (err) {}
if (platform === 'v1') {
await this.switchJavaVersion({ container, username, version: 8 })
const statusV2 = getUserConfig(username, 'status')
if (statusV2) setUserConfig(username, 'status', 'created') // 如果系统在运行,回退到已创建的状态
} else {
await this.switchJavaVersion({ container, username, version: 17 })
const statusV1 = getUserConfig(username, 'v1-status')
if (statusV1) setUserConfig(username, 'v1-status', 'created') // 如果系统在运行,回退到已创建的状态
}
}
}
class DevDocker extends Docker {
constructor (username: string) {
super('localhost', username)
}
}
class ProductionDocker extends Docker {
constructor (username: string) {
super('192.168.0.4', username)
}
}
export function createDockerFactory (username: string) {
if (process.env.NODE_ENV?.trim() === 'production') {
return new ProductionDocker(username)
} else {
return new DevDocker(username)
}
}
\ No newline at end of file
...@@ -17,3 +17,10 @@ export function writeJson(path: string, obj: Record<string, string>) { ...@@ -17,3 +17,10 @@ export function writeJson(path: string, obj: Record<string, string>) {
JSON.stringify(obj, null, 2) JSON.stringify(obj, null, 2)
) )
} }
export function removeUnreadCharacter (str: string) {
// return str.replace(/[\u0000-\u0009]/g, '').replace(/[\u000B-\u001F]/g, '')
return str.replace(/\u0001\u0000\u0000\u0000\u0000\u0000\u0000\n/g, '').replace(/[\u0000-\u0009]/g, '').replace(/[\u000B-\u001F]/g, '')
}
export const SESSION_PASSWORD = '80d42cfb-1cd2-462c-8f17-e3237d9027e9'
\ No newline at end of file
/**
* Logs 模块
* 使用 LogsModule 包裹后,为某个安装流程增加日志处理,并且对外还是返回 Promise 对象
*/
import { setUserConfig, getUserConfig } from "./server"
// import { Socket } from "socket.io/dist/socket";
// let websocket: Map<string, Socket> = new Map()
// export function setWebsocketIo (username: string, io: Socket) {
// websocket.set(username, io)
// }
// export function getWebsocketIo (username: string) {
// return websocket.get(username) as Socket
// }
export default class LogUtil {
// 根据 log 判断用户是否已经执行过
static async run (username: string, log: string, cb: () => Promise<void>) {
let key = 'InstallSteps'
let steps: string[] = getUserConfig(username, key) || []
// let socket = getWebsocketIo(username)
// socket.emit('Log', '[progress] [1m[Loading][m ' + log + '中...\n')
await cb()
steps.push(log)
setUserConfig(username, key, steps)
// socket.emit('Log', '[progress] [1m[Info][m ' + log + '完成\n')
}
static async print(username: string, log: string) {
// let socket = getWebsocketIo(username)
// socket.emit('Log', removeUnreadCharacter(log))
}
static async printInfo(username: string, log: string) {
// let socket = getWebsocketIo(username)
// socket.emit('Log', removeUnreadCharacter(`[progress] [[1;34mInfo[m] ${log} \n`))
}
static async printError(username: string, log: string) {
// let socket = getWebsocketIo(username)
// socket.emit('Log', removeUnreadCharacter(`[error] [[1;31mError[m] ${log} \n`))
}
static async printSuccess(username: string, log: string) {
// let socket = getWebsocketIo(username)
// socket.emit('Log', removeUnreadCharacter(`[progress] [[1;31mSuccess[m] ${log} \n`))
}
static async printWarning (username: string, log: string) {
}
}
import pg from 'pg'
export async function createPgClient ({ host, port, database }: { host: string, port: number, database?: string }) {
let client = new pg.Client({
user: 'postgres',
password: 'postgres',
database,
host,
port
})
await client.connect()
return client
}
export function executePgQuery ({ client, query }: { client: pg.Client, query: string }) {
return client.query(query)
}
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment