instance-manager.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. import {
  2. EC2Client,
  3. RunInstancesCommand,
  4. DescribeInstancesCommand,
  5. CreateTagsCommand,
  6. StopInstancesCommand,
  7. StartInstancesCommand,
  8. RebootInstancesCommand,
  9. TerminateInstancesCommand,
  10. } from '@aws-sdk/client-ec2';
  11. import { getDb } from '../db';
  12. import { generateUserData, generateWindowsPassword } from './userdata';
  13. import { encrypt } from '../utils/crypto';
  14. import { terminateSessionsByInstance, deleteSessionsByInstance } from './connection-manager';
  15. /** Shape returned from aws_config table */
  16. interface AwsConfig {
  17. access_key: string;
  18. secret_key_encrypted: string;
  19. region: string;
  20. ami_id: string;
  21. instance_type: string | null;
  22. key_pair_name: string | null;
  23. security_group_id: string | null;
  24. subnet_id: string | null;
  25. }
  26. /** Shape of an instance row from the DB */
  27. export interface InstanceRecord {
  28. id: number;
  29. user_id: number;
  30. ec2_instance_id: string;
  31. machine_guid: string;
  32. status: string;
  33. public_ip: string | null;
  34. rdp_username: string | null;
  35. rdp_password_encrypted: string | null;
  36. started_at: number | null;
  37. expires_at: number | null;
  38. created_at: number;
  39. }
  40. /** Result returned after launching an instance */
  41. export interface LaunchResult {
  42. instanceId: number;
  43. ec2InstanceId: string;
  44. machineGuid: string;
  45. status: string;
  46. }
  47. // ---------------------------------------------------------------------------
  48. // Internal helpers
  49. // ---------------------------------------------------------------------------
  50. /** Build an EC2Client from the stored AWS configuration. */
  51. function buildEc2Client(config: AwsConfig, decryptFn: (s: string) => string): EC2Client {
  52. const secretKey = decryptFn(config.secret_key_encrypted);
  53. return new EC2Client({
  54. region: config.region,
  55. credentials: {
  56. accessKeyId: config.access_key,
  57. secretAccessKey: secretKey,
  58. },
  59. });
  60. }
  61. /** Write an instance action log entry. */
  62. function logInstanceAction(
  63. userId: number,
  64. username: string,
  65. ec2InstanceId: string | null,
  66. action: string,
  67. durationSeconds?: number,
  68. ): void {
  69. try {
  70. const db = getDb();
  71. db.prepare(
  72. 'INSERT INTO instance_logs (user_id, username, ec2_instance_id, action, duration_seconds) VALUES (?, ?, ?, ?, ?)'
  73. ).run(userId, username, ec2InstanceId, action, durationSeconds ?? null);
  74. } catch (err: any) {
  75. console.error('[InstanceLog] 写入日志失败:', err.message);
  76. }
  77. }
  78. /** Load the single AWS config row. Throws if not configured. */
  79. export function loadAwsConfig(): AwsConfig {
  80. const db = getDb();
  81. const config = db
  82. .prepare(
  83. 'SELECT access_key, secret_key_encrypted, region, ami_id, instance_type, key_pair_name, security_group_id, subnet_id FROM aws_config ORDER BY id DESC LIMIT 1',
  84. )
  85. .get() as AwsConfig | undefined;
  86. if (!config || !config.access_key || !config.secret_key_encrypted || !config.region || !config.ami_id) {
  87. throw new Error('请先配置 AWS 参数');
  88. }
  89. return config;
  90. }
  91. /** Read max_instance_lifetime_minutes from system_settings (default 1440 = 24h). */
  92. export function getMaxLifetimeMinutes(): number {
  93. const db = getDb();
  94. const row = db
  95. .prepare("SELECT value FROM system_settings WHERE key = 'max_instance_lifetime_minutes'")
  96. .get() as { value: string } | undefined;
  97. if (row && row.value) {
  98. const parsed = Number(row.value);
  99. if (!isNaN(parsed) && parsed > 0) return parsed;
  100. }
  101. return 1440;
  102. }
  103. /**
  104. * Poll DescribeInstances until the instance reaches the desired state or
  105. * the timeout is exceeded.
  106. */
  107. async function waitForState(
  108. ec2: EC2Client,
  109. ec2InstanceId: string,
  110. desiredState: string,
  111. timeoutMs = 300_000,
  112. intervalMs = 5_000,
  113. ): Promise<void> {
  114. const deadline = Date.now() + timeoutMs;
  115. while (Date.now() < deadline) {
  116. const desc = await ec2.send(
  117. new DescribeInstancesCommand({ InstanceIds: [ec2InstanceId] }),
  118. );
  119. const state = desc.Reservations?.[0]?.Instances?.[0]?.State?.Name;
  120. if (state === desiredState) return;
  121. await new Promise((r) => setTimeout(r, intervalMs));
  122. }
  123. throw new Error(`实例 ${ec2InstanceId} 未在超时时间内进入 ${desiredState} 状态`);
  124. }
  125. // ---------------------------------------------------------------------------
  126. // Public API
  127. // ---------------------------------------------------------------------------
  128. /**
  129. * Launch a new EC2 instance for the given user with the specified MachineGuid.
  130. *
  131. * Steps:
  132. * 1. Read AWS config from DB
  133. * 2. Call RunInstances with UserData script
  134. * 3. Wait for "running" state
  135. * 4. Retrieve public IP via DescribeInstances
  136. * 5. Retrieve Windows password via GetPasswordData
  137. * 6. Encrypt RDP password and persist instance record
  138. * 7. Return full instance info including RDP credentials
  139. */
  140. export async function launchInstance(
  141. userId: number,
  142. machineGuid: string,
  143. username: string,
  144. /** Injected decrypt function – defaults to the crypto util */
  145. decryptFn: (s: string) => string = require('../utils/crypto').decrypt,
  146. ): Promise<LaunchResult> {
  147. const config = loadAwsConfig();
  148. const ec2 = buildEc2Client(config, decryptFn);
  149. // Generate admin password
  150. const adminPassword = generateWindowsPassword();
  151. // 1. Build RunInstances params
  152. const userData = generateUserData(machineGuid, adminPassword);
  153. const runParams: any = {
  154. ImageId: config.ami_id,
  155. InstanceType: config.instance_type || 't3.medium',
  156. MinCount: 1,
  157. MaxCount: 1,
  158. UserData: userData,
  159. BlockDeviceMappings: [
  160. {
  161. DeviceName: '/dev/sda1',
  162. Ebs: {
  163. VolumeType: 'gp3',
  164. DeleteOnTermination: true,
  165. },
  166. },
  167. ],
  168. NetworkInterfaces: [
  169. {
  170. DeviceIndex: 0,
  171. AssociatePublicIpAddress: true,
  172. Ipv6AddressCount: 1,
  173. SubnetId: config.subnet_id || undefined,
  174. Groups: config.security_group_id ? [config.security_group_id] : undefined,
  175. },
  176. ],
  177. MetadataOptions: {
  178. HttpTokens: 'required',
  179. HttpEndpoint: 'enabled',
  180. },
  181. };
  182. if (config.key_pair_name) runParams.KeyName = config.key_pair_name;
  183. // 2. Launch
  184. let ec2InstanceId: string;
  185. try {
  186. const runResult = await ec2.send(new RunInstancesCommand(runParams));
  187. ec2InstanceId = runResult.Instances?.[0]?.InstanceId ?? '';
  188. if (!ec2InstanceId) {
  189. throw new Error('RunInstances 未返回实例 ID');
  190. }
  191. } catch (err: any) {
  192. throw new Error(`EC2 实例启动失败: ${err.message}`);
  193. }
  194. // Insert a pending record immediately with password
  195. const db = getDb();
  196. const now = Math.floor(Date.now() / 1000);
  197. const encryptedPassword = encrypt(adminPassword);
  198. const insertResult = db
  199. .prepare(
  200. `INSERT INTO instances (user_id, ec2_instance_id, machine_guid, status, rdp_username, rdp_password_encrypted, created_at)
  201. VALUES (?, ?, ?, 'pending', 'Administrator', ?, ?)`,
  202. )
  203. .run(userId, ec2InstanceId, machineGuid, encryptedPassword, now);
  204. const instanceId = Number(insertResult.lastInsertRowid);
  205. // Tag the instance with Name
  206. const nameTag = `BIFA-${username}-${now}-${userId}`;
  207. ec2.send(new CreateTagsCommand({
  208. Resources: [ec2InstanceId],
  209. Tags: [{ Key: 'Name', Value: nameTag }],
  210. })).catch((err) => {
  211. console.error(`[LaunchInstance] 打 Name Tag 失败:`, err.message);
  212. });
  213. logInstanceAction(userId, username, ec2InstanceId, 'launch');
  214. // 3. Async: wait for running, get IP, update record
  215. finalizeInstance(instanceId, ec2InstanceId, ec2).catch((err) => {
  216. console.error(`[LaunchInstance] 异步完成实例 ${instanceId} 失败:`, err.message);
  217. const db2 = getDb();
  218. db2.prepare("UPDATE instances SET status = 'terminated' WHERE id = ?").run(instanceId);
  219. });
  220. return {
  221. instanceId,
  222. ec2InstanceId,
  223. machineGuid,
  224. status: 'pending',
  225. };
  226. }
  227. /**
  228. * Async background work after RunInstances: wait for running, get IP/password, set expires_at.
  229. */
  230. async function finalizeInstance(
  231. instanceId: number,
  232. ec2InstanceId: string,
  233. ec2: EC2Client,
  234. ): Promise<void> {
  235. // Wait for running
  236. await waitForState(ec2, ec2InstanceId, 'running');
  237. // Get public IP
  238. const descResult = await ec2.send(
  239. new DescribeInstancesCommand({ InstanceIds: [ec2InstanceId] }),
  240. );
  241. const publicIp =
  242. descResult.Reservations?.[0]?.Instances?.[0]?.PublicIpAddress ?? '';
  243. // Compute expires_at from NOW (when instance is actually running)
  244. const runningNow = Math.floor(Date.now() / 1000);
  245. const maxLifetimeMinutes = getMaxLifetimeMinutes();
  246. const expiresAt = runningNow + maxLifetimeMinutes * 60;
  247. const db = getDb();
  248. db.prepare(
  249. `UPDATE instances
  250. SET status = 'running',
  251. public_ip = ?,
  252. started_at = ?,
  253. expires_at = ?
  254. WHERE id = ?`,
  255. ).run(publicIp, runningNow, expiresAt, instanceId);
  256. console.log(`[LaunchInstance] 实例 ${instanceId} (${ec2InstanceId}) 已就绪`);
  257. }
  258. /**
  259. * Stop (shut down) a running EC2 instance.
  260. */
  261. export async function stopInstance(
  262. instanceId: number,
  263. decryptFn: (s: string) => string = require('../utils/crypto').decrypt,
  264. ): Promise<void> {
  265. const db = getDb();
  266. const row = db.prepare('SELECT ec2_instance_id, status, user_id, started_at FROM instances WHERE id = ?').get(instanceId) as
  267. | (Pick<InstanceRecord, 'ec2_instance_id' | 'status' | 'user_id' | 'started_at'>)
  268. | undefined;
  269. if (!row) throw new Error('实例不存在');
  270. if (row.status !== 'running') throw new Error('只能关机运行中的实例');
  271. const config = loadAwsConfig();
  272. const ec2 = buildEc2Client(config, decryptFn);
  273. await ec2.send(new StopInstancesCommand({ InstanceIds: [row.ec2_instance_id] }));
  274. // Clean up all active RDP sessions for this instance
  275. terminateSessionsByInstance(row.ec2_instance_id);
  276. db.prepare("UPDATE instances SET status = 'stopped', public_ip = NULL WHERE id = ?").run(instanceId);
  277. const duration = row.started_at ? Math.floor(Date.now() / 1000) - row.started_at : undefined;
  278. const user = db.prepare('SELECT username FROM users WHERE id = ?').get(row.user_id) as { username: string } | undefined;
  279. logInstanceAction(row.user_id, user?.username || '', row.ec2_instance_id, 'stop', duration);
  280. }
  281. /**
  282. * Start a previously stopped EC2 instance.
  283. */
  284. export async function startInstance(
  285. instanceId: number,
  286. decryptFn: (s: string) => string = require('../utils/crypto').decrypt,
  287. ): Promise<void> {
  288. const db = getDb();
  289. const row = db.prepare('SELECT ec2_instance_id, status, user_id FROM instances WHERE id = ?').get(instanceId) as
  290. | Pick<InstanceRecord, 'ec2_instance_id' | 'status' | 'user_id'>
  291. | undefined;
  292. if (!row) throw new Error('实例不存在');
  293. if (row.status !== 'stopped') throw new Error('只能启动已停止的实例');
  294. const config = loadAwsConfig();
  295. const ec2 = buildEc2Client(config, decryptFn);
  296. await ec2.send(new StartInstancesCommand({ InstanceIds: [row.ec2_instance_id] }));
  297. db.prepare("UPDATE instances SET status = 'running' WHERE id = ?").run(instanceId);
  298. const user = db.prepare('SELECT username FROM users WHERE id = ?').get(row.user_id) as { username: string } | undefined;
  299. logInstanceAction(row.user_id, user?.username || '', row.ec2_instance_id, 'start');
  300. // Async: wait for running and re-fetch public IP
  301. (async () => {
  302. try {
  303. await waitForState(ec2, row.ec2_instance_id, 'running');
  304. const descResult = await ec2.send(
  305. new DescribeInstancesCommand({ InstanceIds: [row.ec2_instance_id] }),
  306. );
  307. const publicIp = descResult.Reservations?.[0]?.Instances?.[0]?.PublicIpAddress ?? '';
  308. db.prepare('UPDATE instances SET public_ip = ? WHERE id = ?').run(publicIp || null, instanceId);
  309. console.log(`[StartInstance] 实例 ${instanceId} 新公网 IP: ${publicIp}`);
  310. } catch (err: any) {
  311. console.error(`[StartInstance] 获取实例 ${instanceId} 公网 IP 失败:`, err.message);
  312. }
  313. })();
  314. }
  315. /**
  316. * Reboot a running EC2 instance.
  317. */
  318. export async function rebootInstance(
  319. instanceId: number,
  320. decryptFn: (s: string) => string = require('../utils/crypto').decrypt,
  321. ): Promise<void> {
  322. const db = getDb();
  323. const row = db.prepare('SELECT ec2_instance_id, status FROM instances WHERE id = ?').get(instanceId) as
  324. | Pick<InstanceRecord, 'ec2_instance_id' | 'status'>
  325. | undefined;
  326. if (!row) throw new Error('实例不存在');
  327. if (row.status !== 'running') throw new Error('只能重启运行中的实例');
  328. const config = loadAwsConfig();
  329. const ec2 = buildEc2Client(config, decryptFn);
  330. await ec2.send(new RebootInstancesCommand({ InstanceIds: [row.ec2_instance_id] }));
  331. // Status stays 'running' after reboot
  332. }
  333. /**
  334. * Terminate (destroy) an EC2 instance.
  335. */
  336. export async function terminateInstance(
  337. instanceId: number,
  338. decryptFn: (s: string) => string = require('../utils/crypto').decrypt,
  339. ): Promise<void> {
  340. const db = getDb();
  341. const row = db.prepare('SELECT ec2_instance_id, status, user_id, started_at FROM instances WHERE id = ?').get(instanceId) as
  342. | (Pick<InstanceRecord, 'ec2_instance_id' | 'status' | 'user_id' | 'started_at'>)
  343. | undefined;
  344. if (!row) throw new Error('实例不存在');
  345. if (row.status === 'terminated') throw new Error('实例已终止');
  346. const config = loadAwsConfig();
  347. const ec2 = buildEc2Client(config, decryptFn);
  348. await ec2.send(new TerminateInstancesCommand({ InstanceIds: [row.ec2_instance_id] }));
  349. // Clean up all active RDP sessions for this instance
  350. terminateSessionsByInstance(row.ec2_instance_id);
  351. const duration = row.started_at ? Math.floor(Date.now() / 1000) - row.started_at : undefined;
  352. const user = db.prepare('SELECT username FROM users WHERE id = ?').get(row.user_id) as { username: string } | undefined;
  353. logInstanceAction(row.user_id, user?.username || '', row.ec2_instance_id, 'terminate', duration);
  354. // Delete session records before deleting instance to avoid FK constraint violation
  355. deleteSessionsByInstance(row.ec2_instance_id);
  356. db.prepare('DELETE FROM instances WHERE id = ?').run(instanceId);
  357. }
  358. /**
  359. * Get RDP connection info for an instance.
  360. */
  361. export function getInstanceRdpInfo(
  362. instanceId: number,
  363. decryptFn: (s: string) => string = require('../utils/crypto').decrypt,
  364. ): { publicIp: string; rdpUsername: string; rdpPassword: string } {
  365. const db = getDb();
  366. const row = db
  367. .prepare('SELECT public_ip, rdp_username, rdp_password_encrypted FROM instances WHERE id = ?')
  368. .get(instanceId) as Pick<InstanceRecord, 'public_ip' | 'rdp_username' | 'rdp_password_encrypted'> | undefined;
  369. if (!row) throw new Error('实例不存在');
  370. let rdpPassword = '';
  371. if (row.rdp_password_encrypted) {
  372. rdpPassword = decryptFn(row.rdp_password_encrypted);
  373. }
  374. return {
  375. publicIp: row.public_ip ?? '',
  376. rdpUsername: row.rdp_username ?? '',
  377. rdpPassword,
  378. };
  379. }