From 17e7ebde49a66c4f18eb80743af95dccc0387e5e Mon Sep 17 00:00:00 2001 From: stevensusas Date: Tue, 19 Nov 2024 17:12:19 -0500 Subject: [PATCH] hi --- backend/routes/userRoutes.js | 242 +---------------------------------- 1 file changed, 5 insertions(+), 237 deletions(-) diff --git a/backend/routes/userRoutes.js b/backend/routes/userRoutes.js index a07336e..11d776e 100644 --- a/backend/routes/userRoutes.js +++ b/backend/routes/userRoutes.js @@ -220,249 +220,17 @@ router.get('/:userId/instances', async (req, res) => { // Request instance by instance type router.post('/instances/request', authenticateToken, authenticateUser, async (req, res) => { - const { instanceType } = req.body; - const userId = req.user.userId; // from JWT - - try { - // Step 1: Find an available instance of the requested instance type - const instanceCheck = await pool.query(` - SELECT InstanceId FROM Instance - WHERE InstanceTypeId = ( - SELECT InstanceTypeId FROM InstanceType WHERE InstanceType = $1 - ) AND AllocatedUserId IS NULL - LIMIT 1 - `, [instanceType]); - - // Step 2: Check if any available instance was found - if (instanceCheck.rowCount === 0) { - return res.status(404).send('No available instances of the requested type'); - } - - const instanceId = instanceCheck.rows[0].instanceid; - - // Step 3: Allocate the instance to the user - await pool.query('UPDATE Instance SET AllocatedUserId = $1 WHERE InstanceId = $2', [userId, instanceId]); - - res.status(200).send(`Instance of type ${instanceType} allocated successfully`); - } catch (error) { - console.error('Error requesting instance:', error); - res.status(500).send('Error requesting instance'); - } -}); - - -// Update the start endpoint -router.post('/instances/:instanceName/start', async (req, res) => { - try { - const { instanceName } = req.params; - - // Check if instance is already running - const instanceCheck = await pool.query( - 'SELECT booted FROM Instance WHERE instancename = $1', - [instanceName] - ); - - if (instanceCheck.rows.length === 0) { - return res.status(404).json({ message: 'Instance not found' }); - } - - if (instanceCheck.rows[0].booted) { - return res.status(400).json({ message: 'Instance is already running' }); - } - - // 1. Get control endpoints from database - const endpointsResult = await pool.query( - 'SELECT start_endpoint FROM ControlEndpoints WHERE id = 1' - ); - - if (endpointsResult.rows.length === 0) { - return res.status(400).json({ message: 'Control endpoints not configured' }); - } - - const startEndpoint = endpointsResult.rows[0].start_endpoint; - - // 2. Call the control endpoint - const controlResponse = await fetch(startEndpoint, { - method: 'POST', - headers: { - 'Content-Type': 'application/json' - }, - body: JSON.stringify({ vm_name: instanceName }) - }); - - if (!controlResponse.ok) { - throw new Error('Failed to start instance through control endpoint'); - } - - // 3. Update instance status in database - const result = await pool.query(` - UPDATE Instance - SET booted = true - WHERE instancename = $1 - RETURNING * - `, [instanceName]); - - if (result.rows.length === 0) { - return res.status(404).json({ message: 'Instance not found' }); - } - - const startTime = new Date().toISOString(); - await redisClient.set(`instance:${instanceName}:startTime`, startTime); - - res.json(result.rows[0]); - } catch (error) { - console.error('Error starting instance:', error); - res.status(500).json({ - message: error.message || 'Error starting instance' - }); - } - - + const client = await pool.connect(); -}); - -router.post('/instances/:instanceName/stop', async (req, res) => { try { - const { instanceName } = req.params; + // Try both fields for backward compatibility + const userId = req.user.userId || req.user.id; - // Check if instance is already stopped - const instanceCheck = await pool.query( - 'SELECT booted FROM Instance WHERE instancename = $1', - [instanceName] - ); - - if (instanceCheck.rows.length === 0) { - return res.status(404).json({ message: 'Instance not found' }); + if (!userId) { + throw new Error('User ID not found in token'); } - if (!instanceCheck.rows[0].booted) { - return res.status(400).json({ message: 'Instance is already stopped' }); - } - - // 1. Get control endpoints from database - const endpointsResult = await pool.query( - 'SELECT stop_endpoint FROM ControlEndpoints WHERE id = 1' - ); - - if (endpointsResult.rows.length === 0) { - return res.status(400).json({ message: 'Control endpoints not configured' }); - } - - const stopEndpoint = endpointsResult.rows[0].stop_endpoint; - - // 2. Call the control endpoint - const controlResponse = await fetch(stopEndpoint, { - method: 'POST', - headers: { - 'Content-Type': 'application/json' - }, - body: JSON.stringify({ vm_name: instanceName }) - }); - - if (!controlResponse.ok) { - throw new Error('Failed to stop instance through control endpoint'); - } - - // 3. Update instance status in database to false (stopped) - const result = await pool.query(` - UPDATE Instance - SET booted = false - WHERE instancename = $1 - RETURNING * - `, [instanceName]); - - if (result.rows.length === 0) { - return res.status(404).json({ message: 'Instance not found' }); - } - - // Log the update for debugging - console.log('Instance status updated:', result.rows[0]); - - const startTime = await redisClient.get(`instance:${instanceName}:startTime`); - if (!startTime) { - console.warn(`No start time found for instance ${instanceName}`); - } - - const endTime = new Date().toISOString(); - // If we have a start time, log the usage - if (startTime) { - // Get the instance and user details - const instanceDetails = await pool.query( - 'SELECT InstanceId, AllocatedUserId FROM Instance WHERE InstanceName = $1', - [instanceName] - ); - - if (instanceDetails.rows.length > 0) { - const { instanceid, allocateduserid } = instanceDetails.rows[0]; - - // Insert into UsageLogs - await pool.query( - 'INSERT INTO UsageLogs (UserId, InstanceId, StartTime, EndTime) VALUES ($1, $2, $3, $4)', - [allocateduserid, instanceid, startTime, endTime] - ); - - // Clean up Redis - await redisClient.del(`instance:${instanceName}:startTime`); - } - } - - res.json(result.rows[0]); - } catch (error) { - console.error('Error stopping instance:', error); - res.status(500).json({ - message: error.message || 'Error stopping instance' - }); - } -}); - -router.get('/instances/:userId', authenticateToken, async (req, res) => { - try { - const userId = req.params.userId; - - // Add logging to debug - console.log('Fetching instances for userId:', userId); - - const query = ` - SELECT - i.instanceid, - i.instancename, - i.ipaddress, - i.booted as status, - i.username, - i.allocateduserid, - i.password, - it.instancetype as type, - it.systemtype, - it.cpucorecount, - it.storage, - it.memory, - pt.priceperhour - FROM instance i - LEFT JOIN instancetype it ON i.instancetypeid = it.instancetypeid - LEFT JOIN pricetier pt ON it.pricetierId = pt.pricetierId - WHERE i.allocateduserid = $1 - `; - - const result = await pool.query(query, [userId]); - - // Add logging to debug - console.log('Query result:', result.rows); - - res.json(result.rows); - } catch (error) { - console.error('Error fetching instances:', error); - res.status(500).json({ error: 'Internal server error' }); - } -}); - -// Main endpoint handler -router.post('/request-instance', authenticateToken, authenticateUser, async (req, res) => { - const client = await pool.connect(); - - try { - const userId = req.user.userId; const { instancetype } = req.body; - console.log('Starting instance allocation for:', { userId, instancetype }); await client.query('BEGIN TRANSACTION ISOLATION LEVEL SERIALIZABLE');