-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.js
More file actions
executable file
·226 lines (213 loc) · 6.1 KB
/
app.js
File metadata and controls
executable file
·226 lines (213 loc) · 6.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
const Koa = require('koa')
const Router = require('koa-router')
const app = new Koa()
const fs = require('fs')
const server = require('http').Server(app.callback())
const io = require('socket.io')(server)
const path = require('path')
const cors = require('koa2-cors')
const os = require('os')
const CronJob = require('cron').CronJob
const { spawn, exec } = require('child_process')
//var process = require('process')
//var Docker = require('dockerode')
function deleteDir(path) {
let files = []
if (fs.existsSync(path)) {
files = fs.readdirSync(path)
files.forEach((file, index) => {
let curPath = path + '/' + file
if (fs.statSync(curPath).isDirectory()) {
deleteDir(curPath) //递归删除文件夹
} else {
fs.unlinkSync(curPath) //删除文件
}
})
fs.rmdirSync(path)
}
}
var pty = require('node-pty')
const USE_BINARY = os.platform() !== 'win32'
const port = 8085
var terms = {},
logs = {}
app.use(
cors({
origin: function(ctx) {
return '*'
},
exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
maxAge: 5,
credentials: true,
allowMethods: ['GET', 'POST', 'DELETE'],
allowHeaders: ['Content-Type', 'Authorization', 'Accept']
})
)
// 首页路由
let router = new Router()
router.get('/', async (ctx, next) => {
ctx.response.type = 'html'
ctx.response.body = fs.createReadStream('./index.html')
await next()
})
router.post('/term', async (ctx, next) => {
// var ourDocker = new Docker();
// ourDocker
// .createContainer({
// Tty: true,
// Image: "centos",
// Cmd: ["/bin/bash"],
// OpenStdin: true
// })
// .then(container => {
// console.log(container);
// return container.start();
// });
const env = Object.assign({}, process.env)
env['COLORTERM'] = 'truecolor'
var name = path.join(__dirname, '/file', `${new Date().getTime()}`)
fs.mkdirSync(name)
var cols = parseInt(ctx.request.query.cols),
rows = parseInt(ctx.request.query.rows),
term = pty.spawn(
process.platform === 'win32' ? 'powershell.exe' : 'docker',
['run', '-it', '-v', `${name}:/app`, 'own:v1', '/bin/bash'],
{
name: 'xterm-color',
cols: cols || 80,
rows: rows || 24,
cwd: env.HOME,
env: env,
encoding: 'utf8' //让输出的编码为utf8
}
)
console.log('Created terminal with PID: ', term.pid)
if (!terms[term.pid]) {
terms[term.pid] = {}
}
terms[term.pid].dirName = name
terms[term.pid].terminal = term
terms[term.pid].writable = true
logs[term.pid] = ''
function getData() {
return new Promise((resolve, reject) => {
term.on('data', data => {
logs[term.pid] += data
console.log('initdata', data)
if (!terms[parseInt(term.pid)].initCode) {
terms[parseInt(term.pid)].initCode = data
var reg = /root@(.*?)\ app/
var regExecRes = reg.exec(data)
if (regExecRes && regExecRes[1]) {
resolve(data)
terms[parseInt(term.pid)].dockerContainerID = regExecRes[1]
terms[parseInt(term.pid)].initCode = data
}
}
})
term.on('error', () => {
reject('node-pty connection error')
})
})
}
try {
let res = await getData()
ctx.response.body = {
data: term.pid.toString(),
code: 200,
message: 'success'
}
} catch {
ctx.response.body = {
data: '服务器异常',
code: 301,
message: 'success'
}
}
await next()
})
app.use(router.routes())
io.of('/termsocket').on('connection', socket => {
var pid = parseInt(socket.request._query.pid)
console.log(terms)
if (!terms || !terms[pid]) {
return
}
// console.log('socket连接时发送', logs[pid], terms[pid].initCode)
//socket连接根据pid操作对应的terminal
var term = terms[pid].terminal
//把存起来的初始化数据发送给前端展示
socket.emit('initmessage', terms[pid].initCode)
//socket.emit('message', logs[pid])
//监听terminal输出数据 通过socket发送给前端展示
term.on('data', function(data) {
if (terms[pid].initCode && data.indexOf(terms[pid].initCode) != -1) {
terms[pid].writable = false
}
console.log(data)
try {
socket.emit('message', data)
} catch (ex) {
// The WebSocket is not open, ignore
}
})
socket.on('message', data => {
if (terms[pid].writable) term.write(data)
})
socket.on('leftmessage', data => {
console.log('输入', data)
var sname =
new Date().getTime() +
'_' +
parseInt((Math.random() * 100000).toString(), 10) +
'.py'
let name = path.join(`${terms[pid].dirName}/`, sname)
let newData = data
fs.writeFileSync(name, newData, {
encoding: 'utf8'
})
if (!terms[pid].writable) {
terms[pid].writable = true
}
term.write(`python3.8 /app/${sname}\r`)
})
//socket关闭的时候关闭term
socket.on('close', () => {
console.log('terminal关闭PID:' + pid)
if (terms[pid].dirName && terms[pid].dirName.length > 0) {
deleteDir(terms[pid].dirName)
}
term.destroy()
term.kill()
spawn('docker', ['stop', terms[pid].dockerContainerID])
delete terms[term.pid]
delete logs[term.pid]
})
})
io.close(() => {
for (let key in terms) {
if (terms[key].dirName && terms[key].dirName.length > 0) {
deleteDir(terms[key].dirName)
}
terms[key].destroy()
term[key].kill()
spawn('docker', ['stop', `${terms[key].dockerContainerID}`])
}
delete terms
delete logs
console.log('socket服务关闭')
})
//定时任务
new CronJob(
'* */5 * * * *',
() => {
console.log('定时删除已经停止的docker容器任务')
exec("docker rm `docker ps -a|grep Exited|awk '{print $1}'`")
},
null,
true
)
// 监听端口
server.listen(process.env.PORT || port, () => {
console.log(`app run at : http://127.0.0.1/:${port}`)
})