server.ts 11 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
import path from 'path'
import fs from 'fs'
import lodash from 'lodash'
import { Telnet } from 'telnet-client'

export function getUserConfig (username: string, config: string) {
  let jsonPath = path.resolve('./server/data/' + username + '.json')
  try {
    let jsonStr = fs.readFileSync(jsonPath, { encoding: 'utf-8' })
    let json = JSON.parse(jsonStr) || {}
    return lodash.get(json, config)
  } catch (err: any) {
    console.log(err)
  }
}

// 在目标服务器上,获取 node 可用的端口
export async function getAvailableNodePort (ip: string, startPort = 30000) {
  const tryPortAvailable = async function (port: number): Promise<number> {
    let telnet = new Telnet()
    const params = {
      host: ip,
      port: port,
      negotiationMandatory: false,
      timeout: 1500
    }
    try {
      await telnet.connect(params)
      telnet.end()
      return tryPortAvailable(port + 1)
    } catch (err) {
      return port
    }
  }
  return tryPortAvailable(startPort)
}

export function getUserAllConfigs (username: string): Record<string, string> {
  let jsonPath = path.resolve('./server/data/' + username + '.json')
  let jsonStr = fs.readFileSync(jsonPath, { encoding: 'utf-8' })
  let json = JSON.parse(jsonStr) || {}
  return json
王曜嵚 Wang Yaoqin's avatar
王曜嵚 Wang Yaoqin committed
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
}

export function setUserConfig (username: string, config: string, value: any) {
  let jsonPath = path.resolve(__dirname, './database/' + username + '.json')
  let jsonStr = fs.readFileSync(jsonPath, { encoding: 'utf-8' })
  let json = JSON.parse(jsonStr) || {}
  let newJson = lodash.set(json, config, value)
  fs.writeFileSync(jsonPath, JSON.stringify(newJson, null, 2), { encoding: 'utf-8' })
}

export async function checkSshExists (username: string) {
  let gitEmail = username + '@greaconsulting.com'
  let docker = createDockerFactory(username)
  // 创建 node 容器
  let container = await docker.checkContainer('logwire_backend_helper.' + username + '.node')
  if (!container) {
    throw new Error('没有创建容器,请先初始化容器')
  }
  await docker.startContainer({ container })
  let sshKey = ''
  try {
    sshKey = await docker.getFile({ container, path: '/root/.ssh/id_rsa.pub' })
  } catch (err) {
    await docker.execContainerCommand({ container, cmd: 'rm -rf /root/.ssh' })
    await docker.execContainerCommand({ container, cmd: `ssh-keygen -f /root/.ssh/id_rsa -t ed25519 -C "${gitEmail}"` })
    sshKey = await docker.getFile({ container, path: '/root/.ssh/id_rsa.pub' })
  }
  return sshKey
}


export async function copyAndCreateServerPropertiesV2InDocker (username: string) {
  let docker = createDockerFactory(username)
  let container = await docker.checkContainer('logwire_backend_helper.' + username + '.node')
  if (!container) {
      throw new Error('没有创建容器,请先初始化容器')
  }

  let backendText = fs.readFileSync(path.resolve(__dirname, './files/application-server.properties'), { encoding: 'utf-8' })
  const userDefaultSettingStr = fs.readFileSync(path.resolve(__dirname, './files/default-user-setting.json'), { encoding: 'utf-8'})
  const userConfigsStr = fs.readFileSync(path.resolve(__dirname, './database/' + username + '.json'), { encoding: 'utf-8'})
  const userDefaultSetting = JSON.parse(userDefaultSettingStr)
  const userConfigs = JSON.parse(userConfigsStr)

  const fn = (f: (obj: Record<string, any>) => string) => f(userConfigs) || f(userDefaultSetting)

  // postgres config
  backendText = backendText.replace(/spring.datasource.url=(.*?)\n/, `spring.datasource.url=jdbc:postgresql://${fn(o => o.postgres?.ip)}:${fn(o => o.postgres?.port)}/${fn(o => o.postgres?.database)}\n`)
  backendText = backendText.replace(/spring.datasource.username=(.*?)\n/, `spring.datasource.username=${fn(o => o.postgres?.username)}\n`)
  backendText = backendText.replace(/spring.datasource.password=(.*?)\n/, `spring.datasource.password=${fn(o => o.postgres?.password)}\n`)

  // redis config
  backendText = backendText.replace(/spring.redis.port=(.*?)\n/, `spring.redis.port=${fn(o => o.redis?.port)}\n`)
  backendText = backendText.replace(/spring.redis.host=(.*?)\n/, `spring.redis.host=${fn(o => o.redis?.ip)}\n`)

  // zookeeper config
  backendText = backendText.replace(/logwire.register-center-server-list=(.*?)\n/, `logwire.register-center-server-list=${fn(o => o.zookeeper?.ip)}:${fn(o => o.zookeeper?.port)}\n`)

  // rocketmq config
  backendText = backendText.replace(/logwire.mq.name-srv-address=(.*?)\n/, `logwire.mq.name-srv-address=${fn(o => o.rocketmq?.ip)}:${fn(o => o.rocketmq?.port)}\n`)

  // tenants config
  backendText = backendText.replace(/logwire.tenants\[0\].id=(.*?)\n/, `logwire.tenants[0].id=${fn(o => o.tenants?.id)}\n`)
  backendText = backendText.replace(/logwire.tenants\[0\].host=(.*?)\n/, `logwire.tenants[0].host=${fn(o => o.tenants?.host)}\n`)
  backendText = backendText.replace(/logwire.tenants\[0\].database-schema=(.*?)\n/, `logwire.tenants[0].database-schema=${fn(o => o.tenants?.["database-schema"])}\n`)
  backendText = backendText.replace(/logwire.tenants\[0\].primary-namespace=(.*?)\n/, `logwire.tenants[0].primary-namespace=${fn(o => o.tenants?.["primary-namespace"])}\n`)

  // user personal config
  const customServerProperties: { key: string, value: string }[] = userConfigs.serverProperties || []
  customServerProperties.forEach(item => {
    const RegExpKey = item.key.replaceAll('[', '\\[').replaceAll(']', '\\]').replace('.', '\\.')
    if (backendText.match(new RegExp(`#${RegExpKey}=(.*?)\n`))) {
      backendText = backendText.replace(new RegExp(`#${RegExpKey}=(.*?)\n`), `${item.key}=${item.value}\n`)
    } else if (backendText.match(new RegExp(`${RegExpKey}=(.*?)\n`))) {
      backendText = backendText.replace(new RegExp(`${RegExpKey}=(.*?)\n`), `${item.key}=${item.value}\n`)
    } else { // 如果完全没有匹配到内容,则直接追加到最后
      backendText += `\n${item.key}=${item.value}\n`
    }
  })
  
  await docker.writeFile({ container, path: '/var/logwire-backend/build-output/backend/config/application-server.properties', text: '\'' + backendText.replace(/'/g, '"') + '\'' })
}

export async function copyAndCreateGatewayPropertiesV2InDocker (username: string) {
  let docker = createDockerFactory(username)
  let container = await docker.checkContainer('logwire_backend_helper.' + username + '.node')
  if (!container) {
      throw new Error('没有创建容器,请先初始化容器')
  }
  let gatewayText = fs.readFileSync(path.resolve(__dirname, './files/application-gateway.properties'), { encoding: 'utf-8' })
  const userDefaultSettingStr = fs.readFileSync(path.resolve(__dirname, './files/default-user-setting.json'), { encoding: 'utf-8'})
  const userConfigsStr = fs.readFileSync(path.resolve(__dirname, './database/' + username + '.json'), { encoding: 'utf-8'})
  const userDefaultSetting = JSON.parse(userDefaultSettingStr)
  const userConfigs = JSON.parse(userConfigsStr)

  const fn = (f: (obj: Record<string, any>) => string) => f(userConfigs) || f(userDefaultSetting)

  // zookeeper config
  gatewayText = gatewayText.replace(/gateway.register-center-server-list=(.*?)\n/, `gateway.register-center-server-list=${fn(o => o.zookeeper?.ip)}:${fn(o => o.zookeeper?.port)}\n`)
  // rocketmq config
  gatewayText = gatewayText.replace(/gateway.mq.name-srv-address=(.*?)\n/, `gateway.mq.name-srv-address=${fn(o => o.rocketmq?.ip)}:${fn(o => o.rocketmq?.port)}`)

   await docker.writeFile({ container, path: '/var/logwire-backend/build-output/gateway/config/application-gateway.properties', text: '\'' + gatewayText.replace(/'/g, '"') + '\'' })
}

export async function copyAndCreateServerPropertiesV1InDocker (username: string) {
  let docker = createDockerFactory(username)
  let container = await docker.checkContainer('logwire_backend_helper.' + username + '.node')
  if (!container) {
      throw new Error('没有创建容器,请先初始化容器')
  }
  let backendText = fs.readFileSync(path.resolve(__dirname, './files/v1/application.properties'), { encoding: 'utf-8' })
  const userDefaultSettingStr = fs.readFileSync(path.resolve(__dirname, './files/default-user-setting.json'), { encoding: 'utf-8'})
  const userConfigsStr = fs.readFileSync(path.resolve(__dirname, './database/' + username + '.json'), { encoding: 'utf-8'})
  const userDefaultSetting = JSON.parse(userDefaultSettingStr)
  const userConfigs = JSON.parse(userConfigsStr)

  const fn = (f: (obj: Record<string, any>) => string) => f(userConfigs) || f(userDefaultSetting)

  // postgres config
  backendText = backendText.replace(/spring.datasource.url=(.*?)\n/, `spring.datasource.url=jdbc:postgresql://${fn(o => o.postgresV1?.ip)}:${fn(o => o.postgresV1?.port)}/${fn(o => o.postgresV1?.database)}\n`)
  backendText = backendText.replace(/spring.datasource.username=(.*?)\n/, `spring.datasource.username=${fn(o => o.postgresV1?.username)}\n`)
  backendText = backendText.replace(/spring.datasource.password=(.*?)\n/, `spring.datasource.password=${fn(o => o.postgresV1?.password)}\n`)

  // redis config
  backendText = backendText.replace(/spring.redis.port=(.*?)\n/, `spring.redis.port=${fn(o => o.redisV1?.port)}\n`)
  backendText = backendText.replace(/spring.redis.host=(.*?)\n/, `spring.redis.host=${fn(o => o.redisV1?.ip)}\n`)

  // user personal config
  const customServerProperties: { key: string, value: string }[] = userConfigs.serverPropertiesV1 || []
  customServerProperties.forEach(item => {
    const RegExpKey = item.key.replaceAll('[', '\\[').replaceAll(']', '\\]').replace('.', '\\.')
    if (backendText.match(new RegExp(`#${RegExpKey}=(.*?)\n`))) {
      backendText = backendText.replace(new RegExp(`#${RegExpKey}=(.*?)\n`), `${item.key}=${item.value}\n`)
    } else if (backendText.match(new RegExp(`${RegExpKey}=(.*?)\n`))) {
      backendText = backendText.replace(new RegExp(`${RegExpKey}=(.*?)\n`), `${item.key}=${item.value}\n`)
    } else { // 如果完全没有匹配到内容,则直接追加到最后
      backendText += `\n${item.key}=${item.value}\n`
    }
  })
  
  await docker.writeFile({ container, path: '/var/logwire-platform/dist/config/application.properties', text: '\'' + backendText.replace(/'/g, '"') + '\'' })
}

export async function copyAndCreateNginxConfInDocker (username: string) {
  let docker = createDockerFactory(username)
  let container = await docker.checkContainer('logwire_backend_helper.' + username + '.node')
  if (!container) {
      throw new Error('没有创建容器,请先初始化容器')
  }
  const userDefaultSettingStr = fs.readFileSync(path.resolve(__dirname, './files/default-user-setting.json'), { encoding: 'utf-8'})
  const userConfigsStr = fs.readFileSync(path.resolve(__dirname, './database/' + username + '.json'), { encoding: 'utf-8'})
  const userDefaultSetting = JSON.parse(userDefaultSettingStr)
  const userConfigs = JSON.parse(userConfigsStr)
  const nginxConfigStr = fs.readFileSync(path.resolve(__dirname, './files/nginx.conf'), { encoding: 'utf-8' })
  // 修改调试端口的 NGINX 配置
  const replacedNginxConfig = nginxConfigStr.replace(/192.168.1.94/, userConfigs?.debug?.host || userDefaultSetting.debug.host)

  await docker.writeFile({ container, path: '/etc/nginx/nginx.conf', text: '\'' + replacedNginxConfig + '\'' })
202
}