localVm.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. import { existsSync } from 'node:fs'
  2. import { dirname, join, resolve } from 'node:path'
  3. import type { DatabaseSync } from 'node:sqlite'
  4. import { ComputerImages } from './images.js'
  5. import { ComputerError } from './container.js'
  6. import { UNCONFIGURED_COMPUTER_IMAGE } from '../../shared/runner.js'
  7. import type { LocalVmMode, LocalVmStatus } from '../../shared/localVm.js'
  8. import {LOCAL_VM_IMAGES, DEFAULT_VM_IDLE_STOP_MINUTES, MAX_VM_IDLE_STOP_MINUTES, type LocalVmImageKey, type LocalVmImageOption} from '../../shared/localVm.js'
  9. import type { ComputerRuntime, ComputerTarget } from '../worker/gateway.js'
  10. import {ComposeComputerProvider} from './compose.js'
  11. import {COMPOSE_DESKTOP_IMAGE} from '../../shared/composeDesktops.js'
  12. type State = { imageId: string; images?: Partial<Record<LocalVmImageKey,string>>; mode: LocalVmMode; maxInstances: number; idleStopMinutes?: number; job?: LocalVmStatus['job'] }
  13. /** Settings prepares trusted recipes; each desktop keeps one immutable image. */
  14. export class LocalVmImages {
  15. readonly images: ComputerImages
  16. readonly ready: Promise<void>
  17. private state: State
  18. private pending?: Promise<void>
  19. private closed = false
  20. private releaseMaintenance?: () => void
  21. constructor(readonly runtime: ComputerRuntime, readonly db: DatabaseSync) {
  22. this.images = new ComputerImages(runtime.config.runtime)
  23. db.exec('CREATE TABLE IF NOT EXISTS local_vm_runtime(id INTEGER PRIMARY KEY CHECK(id=1),value TEXT NOT NULL)')
  24. const row = db.prepare('SELECT value FROM local_vm_runtime WHERE id=1').get() as {value:string}|undefined
  25. this.state = row ? JSON.parse(row.value) : {imageId:runtime.config.imageId,mode:'per-bot',maxInstances:runtime.config.maxConcurrent ?? 2}
  26. if(runtime.provider.fixedCapacity)this.state={imageId:COMPOSE_DESKTOP_IMAGE,mode:'shared',maxInstances:2}
  27. // Preserve an already selected image when migrating; old archives and workspaces are untouched.
  28. if (!runtime.provider.fixedCapacity && !row && db.prepare("SELECT name FROM sqlite_master WHERE name='managed_image_selection'").get()) {
  29. const old = db.prepare('SELECT value FROM managed_image_selection WHERE id=1').get() as {value:string}|undefined
  30. if (old) this.state.imageId = JSON.parse(old.value).active ?? this.state.imageId
  31. }
  32. runtime.config.imageId = this.state.imageId
  33. this.state.images??={standard:this.state.imageId}
  34. runtime.pool.limits.concurrent = this.state.maxInstances
  35. runtime.pool.idleStopMinutes = this.state.idleStopMinutes ?? DEFAULT_VM_IDLE_STOP_MINUTES
  36. runtime.retainDesktops = true
  37. this.releaseMaintenance = runtime.pool.holdMaintenance()
  38. this.ready = runtime.ready.then(async () => {
  39. if (this.state.job?.state === 'running') {
  40. try { await this.cleanup(this.state.job.id) }
  41. catch {this.state.job={...this.state.job,state:'failed',message:'上次准备的测试虚拟机停止状态待核对,请启动容器运行环境后重新检查'};this.save();return}
  42. this.state.job={...this.state.job,state:'failed',message:'上次准备已中断,可重新准备本地虚拟机'};this.save()
  43. }
  44. this.releaseMaintenance?.(); this.releaseMaintenance = undefined
  45. })
  46. void this.ready.catch(() => {})
  47. }
  48. private save() { this.db.prepare('INSERT OR REPLACE INTO local_vm_runtime VALUES(1,?)').run(JSON.stringify(this.state)) }
  49. private spec(id:string,imageId=this.runtime.config.imageId) { return {id,ownerKey:'local-vm-prepare',imageId} }
  50. private async cleanup(id:string) {
  51. const spec = this.spec(id)
  52. await this.runtime.provider.remove(spec)
  53. await this.runtime.provider.deleteWorkspace(spec)
  54. }
  55. async options():Promise<LocalVmImageOption[]> {
  56. await this.ready
  57. return Promise.all(LOCAL_VM_IMAGES.map(async option=>{
  58. const imageId=this.state.images?.[option.key]
  59. let ready=false
  60. if(imageId&&imageId!==UNCONFIGURED_COMPUTER_IMAGE)try{const image=await this.images.inspect(imageId);ready=(image.imageKey??'standard')===option.key}catch{}
  61. return {...option,ready,...(ready?{imageId}:{})}
  62. }))
  63. }
  64. async select(meta:ComputerTarget,key:LocalVmImageKey,authorize:()=>void) {
  65. if(this.runtime.provider.fixedCapacity)throw new ComputerError('compose_desktop_managed','桌面镜像由 Compose 配置')
  66. await this.ready;authorize();this.runtime.assertTarget(meta)
  67. const release=this.runtime.pool.beginMaintenance({allowIdle:true})
  68. try {
  69. this.runtime.imageFor(meta) // Validate ownership, including bindings without an instance.
  70. if(this.runtime.pool.definition(meta.ownerKey,meta.environmentId))throw new ComputerError('computer_image_in_use','请先移除虚拟机实例再切换镜像,工作文件和浏览器资料会保留')
  71. const image=(await this.options()).find(option=>option.key===key&&option.ready)
  72. if(!image?.imageId)throw new ComputerError('computer_image_required','请先在本地虚拟机设置中准备这个镜像')
  73. authorize()
  74. this.db.prepare('INSERT INTO computer_image_bindings VALUES(?,?,?) ON CONFLICT(id) DO UPDATE SET image_id=excluded.image_id').run(meta.environmentId,meta.ownerKey,image.imageId)
  75. return {ok:true}
  76. } finally {release()}
  77. }
  78. async status(owner?:string): Promise<LocalVmStatus> {
  79. await this.ready
  80. if(this.runtime.provider instanceof ComposeComputerProvider){
  81. const desktops=await this.runtime.provider.inventory()
  82. this.runtime.pool.limits.concurrent=Math.max(1,desktops.length)
  83. return {configured:true,executionHost:'runner',fixedCapacity:true,desktops,daemonUp:true,image:desktops.some((d:any)=>d.ready),imageId:COMPOSE_DESKTOP_IMAGE,mode:'shared',maxInstances:desktops.length,busy:false}
  84. }
  85. if(this.releaseMaintenance&&!this.pending&&this.state.job?.state==='failed') {
  86. try{await this.cleanup(this.state.job.id);this.releaseMaintenance();this.releaseMaintenance=undefined}catch{}
  87. }
  88. let daemonUp=false,image=false,problem:string|undefined
  89. try { await this.runtime.provider.verifyRuntime();daemonUp=true }
  90. catch { problem='请先安装并启动 Docker 或 Podman' }
  91. if(daemonUp && this.state.imageId!==UNCONFIGURED_COMPUTER_IMAGE) {
  92. try { await this.images.inspect(this.state.imageId);image=true } catch { problem='本地虚拟机镜像尚未就绪,请重新准备' }
  93. }
  94. return {configured:true,runtime:this.runtime.config.runtime,daemonUp,image,imageId:image?this.state.imageId:undefined,images:await this.options(),
  95. mode:this.state.mode,maxInstances:this.state.maxInstances,idleStopMinutes:this.runtime.pool.idleStopMinutes,busy:!!this.pending||!!this.releaseMaintenance,problem,job:this.state.job,
  96. instances:owner?this.runtime.pool.status(owner).map(row=>({id:row.environmentId,status:row.status})):[]}
  97. }
  98. async idlePolicy(minutes:number) {
  99. if(this.runtime.provider.fixedCapacity)throw new ComputerError('compose_desktop_managed','桌面的停止策略由 Compose 管理')
  100. if(!Number.isSafeInteger(minutes)||minutes<0||minutes>MAX_VM_IDLE_STOP_MINUTES)throw new ComputerError('local_vm_idle_policy_invalid','请选择有效的空闲停止时间')
  101. await this.ready
  102. this.state.idleStopMinutes=minutes;this.runtime.pool.idleStopMinutes=minutes;this.save()
  103. return this.status()
  104. }
  105. async policy(mode:LocalVmMode,maxInstances:number) {
  106. if(this.runtime.provider.fixedCapacity)throw new ComputerError('compose_desktop_managed','桌面数量与共享方式由 Compose 固定,不能在界面修改')
  107. await this.ready
  108. // Sharing changes future Agent bindings; an idle desktop can keep running.
  109. // Image preparation still requires every desktop to be stopped.
  110. const release=this.runtime.pool.beginMaintenance({allowIdle:true})
  111. try { this.state.mode=mode;this.state.maxInstances=maxInstances;this.runtime.pool.limits.concurrent=maxInstances;this.save() }
  112. finally { release() }
  113. return this.status()
  114. }
  115. async prepare(id:string,check:()=>Promise<void>,key:LocalVmImageKey='standard') {
  116. if(this.runtime.provider.fixedCapacity)throw new ComputerError('compose_desktop_managed','桌面镜像由 Compose 配置,无需在界面准备')
  117. await this.ready;await check()
  118. if(this.state.job?.id===id){if((this.state.job.imageKey??'standard')!==key)throw new ComputerError('idempotency_conflict','请求编号已用于其他镜像');return this.status()}
  119. if(this.pending||this.closed)throw new ComputerError('local_vm_busy','本地虚拟机正在准备,请稍后查看')
  120. this.releaseMaintenance=this.runtime.pool.beginMaintenance()
  121. this.state.job={id,state:'running',imageKey:key,message:'正在准备本地虚拟机'};this.save()
  122. const progress=(message:string)=>{this.state.job!.message=message;this.save()}
  123. this.pending=(async()=>{
  124. try {
  125. await this.runtime.provider.verifyRuntime();await check()
  126. const verify=async(manifest:{imageId:string})=>{
  127. progress('正在检查虚拟机桌面与电脑驱动')
  128. const spec=this.spec(id,manifest.imageId)
  129. try {
  130. await this.runtime.provider.ensure(spec,()=>{if(this.closed)throw new Error('服务已停止')})
  131. const deadline=Date.now()+60000
  132. for(;;) { await check();try{await this.runtime.provider.health(spec,()=>{});await this.runtime.provider.capture(spec,()=>{});break}catch(error){if(Date.now()>deadline)throw error;await new Promise(r=>setTimeout(r,1000))} }
  133. } finally { await this.runtime.provider.remove(spec);await this.runtime.provider.deleteWorkspace(spec) }
  134. }
  135. this.images.verify=verify
  136. const ids=(await this.images.run(this.images.runtime,['image','ls','--no-trunc','--quiet','--filter','label=cn.samien.yaoyao.computer-image=1'])).trim().split(/\s+/).filter(Boolean)
  137. let image
  138. for(const value of [this.state.images?.[key],...ids].filter((id):id is string=>!!id&&id!==UNCONFIGURED_COMPUTER_IMAGE)) { try{const candidate=await this.images.inspect(value);if((candidate.imageKey??'standard')===key){image=candidate;break}}catch{} }
  139. const recipe=[join(dirname(this.runtime.script),'computer-image'),join(dirname(this.runtime.script),'../computers/computer-image'),resolve('deploy/computer')].find(p=>existsSync(join(p,'Dockerfile')))
  140. if(!recipe)throw new Error('缺少本地虚拟机资源,请重新安装 App')
  141. if(image){progress('正在准备虚拟机网络网关');await this.images.prepareNetwork(recipe);await check();await verify(image)}
  142. else {
  143. progress('正在准备托管桌面镜像,首次下载可能需要数分钟')
  144. image=await this.images.prepare(recipe,key)
  145. }
  146. await check();const previous=this.state.images![key];this.state.images![key]=image.imageId
  147. // Preparing a second image must not change an existing desktop's choice.
  148. if(this.state.imageId===UNCONFIGURED_COMPUTER_IMAGE||this.state.imageId===previous){this.state.imageId=image.imageId;this.runtime.config.imageId=image.imageId}
  149. this.state.job={id,state:'complete',imageKey:key,message:'镜像已就绪,可在机器人的电脑面板中选择并创建桌面'};this.save()
  150. } catch(error) {
  151. this.state.job={id,state:'failed',imageKey:key,message:error instanceof Error?error.message.slice(0,240):'本地虚拟机准备失败'};this.save()
  152. } finally {
  153. // Do not release maintenance when an interrupted verification VM may still be alive.
  154. try { await this.cleanup(id);this.releaseMaintenance?.();this.releaseMaintenance=undefined } catch { this.state.job={id,state:'failed',message:'测试虚拟机停止状态待核对,请重启执行环境后重试'};this.save() }
  155. this.pending=undefined
  156. }
  157. })()
  158. return this.status()
  159. }
  160. async close() { this.closed=true;await this.ready;await this.pending }
  161. }