instance-manager.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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. try {
  117. const desc = await ec2.send(
  118. new DescribeInstancesCommand({ InstanceIds: [ec2InstanceId] }),
  119. );
  120. const state = desc.Reservations?.[0]?.Instances?.[0]?.State?.Name;
  121. if (state === desiredState) return;
  122. } catch (err: any) {
  123. // AWS eventual consistency: instance ID may not be visible yet
  124. const code = err.Code ?? err.name ?? '';
  125. if (
  126. code === 'InvalidInstanceID.NotFound' ||
  127. err.message?.includes('does not exist')
  128. ) {
  129. console.warn(
  130. `[waitForState] 实例 ${ec2InstanceId} 尚未可见,等待重试...`,
  131. );
  132. } else {
  133. throw err;
  134. }
  135. }
  136. await new Promise((r) => setTimeout(r, intervalMs));
  137. }
  138. throw new Error(`实例 ${ec2InstanceId} 未在超时时间内进入 ${desiredState} 状态`);
  139. }
  140. // ---------------------------------------------------------------------------
  141. // Public API
  142. // ---------------------------------------------------------------------------
  143. /**
  144. * Launch a new EC2 instance for the given user with the specified MachineGuid.
  145. *
  146. * Steps:
  147. * 1. Read AWS config from DB
  148. * 2. Call RunInstances with UserData script
  149. * 3. Wait for "running" state
  150. * 4. Retrieve public IP via DescribeInstances
  151. * 5. Retrieve Windows password via GetPasswordData
  152. * 6. Encrypt RDP password and persist instance record
  153. * 7. Return full instance info including RDP credentials
  154. */
  155. export async function launchInstance(
  156. userId: number,
  157. machineGuid: string,
  158. username: string,
  159. /** Injected decrypt function – defaults to the crypto util */
  160. decryptFn: (s: string) => string = require('../utils/crypto').decrypt,
  161. ): Promise<LaunchResult> {
  162. const config = loadAwsConfig();
  163. const ec2 = buildEc2Client(config, decryptFn);
  164. // Generate admin password
  165. const adminPassword = generateWindowsPassword();
  166. // 1. Build RunInstances params
  167. const userData = generateUserData(machineGuid, adminPassword);
  168. const runParams: any = {
  169. ImageId: config.ami_id,
  170. InstanceType: config.instance_type || 't3.medium',
  171. MinCount: 1,
  172. MaxCount: 1,
  173. UserData: userData,
  174. BlockDeviceMappings: [
  175. {
  176. DeviceName: '/dev/sda1',
  177. Ebs: {
  178. VolumeType: 'gp3',
  179. DeleteOnTermination: true,
  180. },
  181. },
  182. ],
  183. NetworkInterfaces: [
  184. {
  185. DeviceIndex: 0,
  186. AssociatePublicIpAddress: true,
  187. Ipv6AddressCount: 1,
  188. SubnetId: config.subnet_id || undefined,
  189. Groups: config.security_group_id ? [config.security_group_id] : undefined,
  190. },
  191. ],
  192. MetadataOptions: {
  193. HttpTokens: 'required',
  194. HttpEndpoint: 'enabled',
  195. },
  196. };
  197. if (config.key_pair_name) runParams.KeyName = config.key_pair_name;
  198. // 2. Launch
  199. let ec2InstanceId: string;
  200. try {
  201. const runResult = await ec2.send(new RunInstancesCommand(runParams));
  202. ec2InstanceId = runResult.Instances?.[0]?.InstanceId ?? '';
  203. if (!ec2InstanceId) {
  204. throw new Error('RunInstances 未返回实例 ID');
  205. }
  206. } catch (err: any) {
  207. throw new Error(`EC2 实例启动失败: ${err.message}`);
  208. }
  209. // Insert a pending record immediately with password
  210. const db = getDb();
  211. const now = Math.floor(Date.now() / 1000);
  212. const encryptedPassword = encrypt(adminPassword);
  213. const insertResult = db
  214. .prepare(
  215. `INSERT INTO instances (user_id, ec2_instance_id, machine_guid, status, rdp_username, rdp_password_encrypted, created_at)
  216. VALUES (?, ?, ?, 'pending', 'Administrator', ?, ?)`,
  217. )
  218. .run(userId, ec2InstanceId, machineGuid, encryptedPassword, now);
  219. const instanceId = Number(insertResult.lastInsertRowid);
  220. // Tag the instance with Name
  221. const nameTag = `BIFA-${username}-${now}-${userId}`;
  222. ec2.send(new CreateTagsCommand({
  223. Resources: [ec2InstanceId],
  224. Tags: [{ Key: 'Name', Value: nameTag }],
  225. })).catch((err) => {
  226. console.error(`[LaunchInstance] 打 Name Tag 失败:`, err.message);
  227. });
  228. logInstanceAction(userId, username, ec2InstanceId, 'launch');
  229. // 3. Async: wait for running, get IP, update record
  230. finalizeInstance(instanceId, ec2InstanceId, ec2).catch((err) => {
  231. console.error(`[LaunchInstance] 异步完成实例 ${instanceId} 失败:`, err.message);
  232. const db2 = getDb();
  233. db2.prepare("UPDATE instances SET status = 'terminated' WHERE id = ?").run(instanceId);
  234. });
  235. return {
  236. instanceId,
  237. ec2InstanceId,
  238. machineGuid,
  239. status: 'pending',
  240. };
  241. }
  242. /**
  243. * Async background work after RunInstances: wait for running, get IP/password, set expires_at.
  244. */
  245. async function finalizeInstance(
  246. instanceId: number,
  247. ec2InstanceId: string,
  248. ec2: EC2Client,
  249. ): Promise<void> {
  250. // Wait for running
  251. await waitForState(ec2, ec2InstanceId, 'running');
  252. // Get public IP
  253. const descResult = await ec2.send(
  254. new DescribeInstancesCommand({ InstanceIds: [ec2InstanceId] }),
  255. );
  256. const publicIp =
  257. descResult.Reservations?.[0]?.Instances?.[0]?.PublicIpAddress ?? '';
  258. // Compute expires_at from NOW (when instance is actually running)
  259. const runningNow = Math.floor(Date.now() / 1000);
  260. const maxLifetimeMinutes = getMaxLifetimeMinutes();
  261. const expiresAt = runningNow + maxLifetimeMinutes * 60;
  262. const db = getDb();
  263. db.prepare(
  264. `UPDATE instances
  265. SET status = 'running',
  266. public_ip = ?,
  267. started_at = ?,
  268. expires_at = ?
  269. WHERE id = ?`,
  270. ).run(publicIp, runningNow, expiresAt, instanceId);
  271. console.log(`[LaunchInstance] 实例 ${instanceId} (${ec2InstanceId}) 已就绪`);
  272. }
  273. /**
  274. * Stop (shut down) a running EC2 instance.
  275. */
  276. export async function stopInstance(
  277. instanceId: number,
  278. decryptFn: (s: string) => string = require('../utils/crypto').decrypt,
  279. ): Promise<void> {
  280. const db = getDb();
  281. const row = db.prepare('SELECT ec2_instance_id, status, user_id, started_at FROM instances WHERE id = ?').get(instanceId) as
  282. | (Pick<InstanceRecord, 'ec2_instance_id' | 'status' | 'user_id' | 'started_at'>)
  283. | undefined;
  284. if (!row) throw new Error('实例不存在');
  285. if (row.status !== 'running') throw new Error('只能关机运行中的实例');
  286. const config = loadAwsConfig();
  287. const ec2 = buildEc2Client(config, decryptFn);
  288. await ec2.send(new StopInstancesCommand({ InstanceIds: [row.ec2_instance_id] }));
  289. // Clean up all active RDP sessions for this instance
  290. terminateSessionsByInstance(row.ec2_instance_id);
  291. db.prepare("UPDATE instances SET status = 'stopped', public_ip = NULL WHERE id = ?").run(instanceId);
  292. const duration = row.started_at ? Math.floor(Date.now() / 1000) - row.started_at : undefined;
  293. const user = db.prepare('SELECT username FROM users WHERE id = ?').get(row.user_id) as { username: string } | undefined;
  294. logInstanceAction(row.user_id, user?.username || '', row.ec2_instance_id, 'stop', duration);
  295. }
  296. /**
  297. * Start a previously stopped EC2 instance.
  298. */
  299. export async function startInstance(
  300. instanceId: number,
  301. decryptFn: (s: string) => string = require('../utils/crypto').decrypt,
  302. ): Promise<void> {
  303. const db = getDb();
  304. const row = db.prepare('SELECT ec2_instance_id, status, user_id FROM instances WHERE id = ?').get(instanceId) as
  305. | Pick<InstanceRecord, 'ec2_instance_id' | 'status' | 'user_id'>
  306. | undefined;
  307. if (!row) throw new Error('实例不存在');
  308. if (row.status !== 'stopped') throw new Error('只能启动已停止的实例');
  309. const config = loadAwsConfig();
  310. const ec2 = buildEc2Client(config, decryptFn);
  311. await ec2.send(new StartInstancesCommand({ InstanceIds: [row.ec2_instance_id] }));
  312. db.prepare("UPDATE instances SET status = 'running' WHERE id = ?").run(instanceId);
  313. const user = db.prepare('SELECT username FROM users WHERE id = ?').get(row.user_id) as { username: string } | undefined;
  314. logInstanceAction(row.user_id, user?.username || '', row.ec2_instance_id, 'start');
  315. // Async: wait for running and re-fetch public IP
  316. (async () => {
  317. try {
  318. await waitForState(ec2, row.ec2_instance_id, 'running');
  319. const descResult = await ec2.send(
  320. new DescribeInstancesCommand({ InstanceIds: [row.ec2_instance_id] }),
  321. );
  322. const publicIp = descResult.Reservations?.[0]?.Instances?.[0]?.PublicIpAddress ?? '';
  323. db.prepare('UPDATE instances SET public_ip = ? WHERE id = ?').run(publicIp || null, instanceId);
  324. console.log(`[StartInstance] 实例 ${instanceId} 新公网 IP: ${publicIp}`);
  325. } catch (err: any) {
  326. console.error(`[StartInstance] 获取实例 ${instanceId} 公网 IP 失败:`, err.message);
  327. }
  328. })();
  329. }
  330. /**
  331. * Reboot a running EC2 instance.
  332. */
  333. export async function rebootInstance(
  334. instanceId: number,
  335. decryptFn: (s: string) => string = require('../utils/crypto').decrypt,
  336. ): Promise<void> {
  337. const db = getDb();
  338. const row = db.prepare('SELECT ec2_instance_id, status FROM instances WHERE id = ?').get(instanceId) as
  339. | Pick<InstanceRecord, 'ec2_instance_id' | 'status'>
  340. | undefined;
  341. if (!row) throw new Error('实例不存在');
  342. if (row.status !== 'running') throw new Error('只能重启运行中的实例');
  343. const config = loadAwsConfig();
  344. const ec2 = buildEc2Client(config, decryptFn);
  345. await ec2.send(new RebootInstancesCommand({ InstanceIds: [row.ec2_instance_id] }));
  346. // Status stays 'running' after reboot
  347. }
  348. /**
  349. * Terminate (destroy) an EC2 instance.
  350. */
  351. export async function terminateInstance(
  352. instanceId: number,
  353. decryptFn: (s: string) => string = require('../utils/crypto').decrypt,
  354. ): Promise<void> {
  355. const db = getDb();
  356. const row = db.prepare('SELECT ec2_instance_id, status, user_id, started_at FROM instances WHERE id = ?').get(instanceId) as
  357. | (Pick<InstanceRecord, 'ec2_instance_id' | 'status' | 'user_id' | 'started_at'>)
  358. | undefined;
  359. if (!row) throw new Error('实例不存在');
  360. if (row.status === 'terminated') throw new Error('实例已终止');
  361. const config = loadAwsConfig();
  362. const ec2 = buildEc2Client(config, decryptFn);
  363. await ec2.send(new TerminateInstancesCommand({ InstanceIds: [row.ec2_instance_id] }));
  364. // Clean up all active RDP sessions for this instance
  365. terminateSessionsByInstance(row.ec2_instance_id);
  366. const duration = row.started_at ? Math.floor(Date.now() / 1000) - row.started_at : undefined;
  367. const user = db.prepare('SELECT username FROM users WHERE id = ?').get(row.user_id) as { username: string } | undefined;
  368. logInstanceAction(row.user_id, user?.username || '', row.ec2_instance_id, 'terminate', duration);
  369. // Delete session records before deleting instance to avoid FK constraint violation
  370. deleteSessionsByInstance(row.ec2_instance_id);
  371. db.prepare('DELETE FROM instances WHERE id = ?').run(instanceId);
  372. }
  373. /**
  374. * Get RDP connection info for an instance.
  375. */
  376. export function getInstanceRdpInfo(
  377. instanceId: number,
  378. decryptFn: (s: string) => string = require('../utils/crypto').decrypt,
  379. ): { publicIp: string; rdpUsername: string; rdpPassword: string } {
  380. const db = getDb();
  381. const row = db
  382. .prepare('SELECT public_ip, rdp_username, rdp_password_encrypted FROM instances WHERE id = ?')
  383. .get(instanceId) as Pick<InstanceRecord, 'public_ip' | 'rdp_username' | 'rdp_password_encrypted'> | undefined;
  384. if (!row) throw new Error('实例不存在');
  385. let rdpPassword = '';
  386. if (row.rdp_password_encrypted) {
  387. rdpPassword = decryptFn(row.rdp_password_encrypted);
  388. }
  389. return {
  390. publicIp: row.public_ip ?? '',
  391. rdpUsername: row.rdp_username ?? '',
  392. rdpPassword,
  393. };
  394. }