Merge pull request #3 from lancatlin/server-terminal-api

Server terminal api
This commit is contained in:
Lin, Hung-Shin authored and GitHub committed 2023-07-24 15:09:02 +08:00
commit 9ee9a8586f
8 files changed
+102 -24

No files matched your search

+1
View File
@@ -19,5 +19,6 @@ module.exports = {
'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off', 'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off', 'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'import/extensions': 'off', 'import/extensions': 'off',
camelcase: ['error', { properties: 'never', ignoreDestructuring: true }],
}, },
} }
+16 -2
View File
@@ -40,8 +40,22 @@ yarn app
## CLI terminal client ## CLI terminal client
Open server first, then Open server first, then create a session by `POST /api/v1/sessions`
```bash
curl -X 'POST' \
'http://localhost:3000/api/v1/sessions' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"quest_id": "helloworld"
}'
```
Then use the `_id` field in response
``` ```
yarn cli yarn cli [_id]
# example
yarn cli 64be226a39c0043cd1cdf7c2
``` ```
@@ -25,6 +25,7 @@ export async function createSession(req, res) {
const newSession = new Session({ const newSession = new Session({
user: req.user, user: req.user,
quest, quest,
containerId: `quest-${quest.id}-${req.user.username}-${Date.now()}`,
}) })
try { try {
+28 -2
View File
@@ -1,12 +1,38 @@
import { Server } from 'socket.io' import { Server } from 'socket.io'
import { getOrCreateContainer, attachContainer } from '../utils/docker.js' import { getOrCreateContainer, attachContainer } from '../utils/docker.js'
import Session from '../models/session.js'
import { defaultUser } from '../utils/auth.js'
export default (server) => { export default (server) => {
const io = new Server(server) const io = new Server(server)
io.use(async (socket, next) => {
console.log('Authenticating...')
try {
const user = await defaultUser()
// eslint-disable-next-line no-param-reassign
socket.user = user
next()
} catch (err) {
console.error(err)
next(err)
}
})
io.on('connection', async (socket) => { io.on('connection', async (socket) => {
console.log('Connected to the client.') console.log('Connected to the client.')
const container = await getOrCreateContainer('odyssey-test') const session = await Session.findOne({
_id: socket.handshake.query.session_id,
user: socket.user,
})
if (!session) {
socket.send('Session not found.')
socket.disconnect()
return
}
const container = await getOrCreateContainer(session.containerId)
const stream = await attachContainer(container) const stream = await attachContainer(container)
stream.on('data', (chunk) => { stream.on('data', (chunk) => {
@@ -22,6 +48,6 @@ export default (server) => {
console.log('Disconnected from the client.') console.log('Disconnected from the client.')
}) })
socket.send('Hello from server!') socket.send(`${container.id}\n`)
}) })
} }
+8 -1
View File
@@ -5,7 +5,14 @@ stdin.setRawMode(true)
stdin.resume() stdin.resume()
stdin.setEncoding('utf8') stdin.setEncoding('utf8')
const socket = io('ws://localhost:3000') const sessionId = process.argv[2]
console.log(`Session ID: ${sessionId}`)
const socket = io('ws://localhost:3000', {
query: {
session_id: sessionId,
},
})
socket.on('open', function open() { socket.on('open', function open() {
console.log('Connected to the server.') console.log('Connected to the server.')
+2 -10
View File
@@ -1,17 +1,9 @@
/* eslint-disable import/prefer-default-export */ /* eslint-disable import/prefer-default-export */
import User from '../models/user.js' import { defaultUser } from '../utils/auth.js'
export async function authMiddleware(req, res, next) { export async function authMiddleware(req, res, next) {
try { try {
let user = await User.findOne({ username: 'defaultUser' }) req.user = await defaultUser()
if (!user) {
user = new User({
username: 'defaultUser',
email: 'john@example.com',
})
await user.save()
}
req.user = user
next() next()
} catch (err) { } catch (err) {
res.status(500).json({ message: err.message }) res.status(500).json({ message: err.message })
+14
View File
@@ -0,0 +1,14 @@
/* eslint-disable import/prefer-default-export */
import User from '../models/user.js'
export async function defaultUser() {
let user = await User.findOne({ username: 'defaultUser' })
if (!user) {
user = new User({
username: 'defaultUser',
email: 'jackson@example.com',
})
await user.save()
}
return user
}
+32 -9
View File
@@ -13,9 +13,24 @@ const containerOptions = {
StdinOnce: false, StdinOnce: false,
} }
export async function getOrCreateContainer(name) { export async function createContainer() {
const container = await engine.createContainer({
...containerOptions,
})
await container.start()
return container
}
export async function getContainer(id) {
const container = await engine.getContainer(id)
await container.start()
return container
}
export async function getOrCreateContainer(id) {
console.log(`Getting container: ${id}`)
try { try {
const container = engine.getContainer(name) const container = engine.getContainer(id)
if (!(await container.inspect()).State.Running) { if (!(await container.inspect()).State.Running) {
await container.start() await container.start()
} }
@@ -23,7 +38,7 @@ export async function getOrCreateContainer(name) {
} catch (error) { } catch (error) {
const container = await engine.createContainer({ const container = await engine.createContainer({
...containerOptions, ...containerOptions,
name, name: id,
}) })
await container.start() await container.start()
console.log(container.id) console.log(container.id)
@@ -31,12 +46,20 @@ export async function getOrCreateContainer(name) {
} }
} }
export function attachContainer(container) { export async function attachContainer(container) {
// Create an exec instance with bash shell // Create an exec instance with bash shell
return container.attach({ const exec = await container.exec({
stream: true, AttachStdin: true,
stdin: true, AttachStdout: true,
stdout: true, AttachStderr: true,
stderr: true, Cmd: ['/bin/bash'],
Tty: true,
}) })
const execOutput = await exec.start({
Detach: false,
Tty: true,
})
return execOutput.socket
} }