(
overrides: Partial<SystemdManagerDeps> = {},
)
| 49 | }; |
| 50 | |
| 51 | export function createSystemdManager( |
| 52 | overrides: Partial<SystemdManagerDeps> = {}, |
| 53 | ): ServiceManager { |
| 54 | const deps: SystemdManagerDeps = { ...DEFAULT_DEPS, ...overrides }; |
| 55 | |
| 56 | async function install(args: InstallArgs): Promise<InstallResult> { |
| 57 | const unitPath = deps.unitPath(); |
| 58 | const logPath = deps.logPath(); |
| 59 | const program = deps.resolveProgram(); |
| 60 | const plan = buildInstallPlan({ ...args, program, logPath }); |
| 61 | |
| 62 | const alreadyInstalled = existsSync(unitPath); |
| 63 | if (alreadyInstalled && args.force !== true) { |
| 64 | return { |
| 65 | status: 'already-installed', |
| 66 | message: `systemd unit already installed at ${unitPath}. Rerun with --force to replace it.`, |
| 67 | unitPath, |
| 68 | }; |
| 69 | } |
| 70 | |
| 71 | await assertUserSystemdAvailable(deps); |
| 72 | |
| 73 | writeUnit(unitPath, plan); |
| 74 | writeInstallPlan(plan); |
| 75 | |
| 76 | const reload = await deps.execSystemctl(['daemon-reload']); |
| 77 | if (reload.code !== 0) { |
| 78 | throw new Error( |
| 79 | `systemctl --user daemon-reload failed (code ${reload.code}): ${detail(reload) ?? 'unknown error'}`, |
| 80 | ); |
| 81 | } |
| 82 | |
| 83 | const enable = await deps.execSystemctl(['enable', '--now', KIMI_SERVER_SYSTEMD_UNIT]); |
| 84 | if (enable.code !== 0) { |
| 85 | throw new Error( |
| 86 | `systemctl --user enable --now failed (code ${enable.code}): ${detail(enable) ?? 'unknown error'}`, |
| 87 | ); |
| 88 | } |
| 89 | |
| 90 | return { |
| 91 | status: alreadyInstalled ? 'replaced' : 'installed', |
| 92 | message: `Kimi server systemd unit ${alreadyInstalled ? 'replaced' : 'installed'} at ${unitPath} (port ${plan.port}).`, |
| 93 | unitPath, |
| 94 | }; |
| 95 | } |
| 96 | |
| 97 | async function uninstall(): Promise<LifecycleResult> { |
| 98 | const unitPath = deps.unitPath(); |
| 99 | if (!existsSync(unitPath)) { |
| 100 | deleteInstallPlan(); |
| 101 | return { ok: true, message: 'systemd unit was not installed; nothing to remove.' }; |
| 102 | } |
| 103 | await deps.execSystemctl(['disable', '--now', KIMI_SERVER_SYSTEMD_UNIT]).catch(() => undefined); |
| 104 | try { |
| 105 | rmSync(unitPath, { force: true }); |
| 106 | } catch (error) { |
| 107 | throw new Error( |
| 108 | `failed to remove unit ${unitPath}: ${error instanceof Error ? error.message : String(error)}`, |
no outgoing calls
no test coverage detected