-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
executable file
·78 lines (57 loc) · 2.1 KB
/
index.js
File metadata and controls
executable file
·78 lines (57 loc) · 2.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
'use strict'
const VERBOSE = process.env.VERBOSE == "true"
const MAX_PING_DELTA = process.env.MAX_PING_DELTA || 60
const COMPUTE_ZONE = process.env.COMPUTE_ZONE
const COMPUTE_INSTANCE = process.env.COMPUTE_INSTANCE
if ( ! COMPUTE_ZONE ) throw new Error( "No COMPUTE_ZONE environment variable defined." )
if ( ! COMPUTE_INSTANCE ) throw new Error( "No COMPUTE_INSTANCE environment variable defined." )
const compute = new (require('@google-cloud/compute'))()
console.log(`\x1b[93mWill kill vm on ${MAX_PING_DELTA} seconds inactivity from codemaster\x1b[0m`)
async function stopinstance() {
const zone = compute.zone(COMPUTE_ZONE)
const [error, operation, response ] = await zone.vm(COMPUTE_INSTANCE).stop()
await operation
console.log("Instance stopped")
}
const fetch = require("node-fetch")
function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)) }
async function loop() {
while( true )
{
await sleep(1000)
try {
const pingdelta = Math.floor( .001 * (new Date().getTime() - lastping) )
if ( VERBOSE )
console.log( `\x1b[${pingdelta>.9?93:94};1m${pingdelta}\x1b[0;94m seconds since last ping\x1b[0m` )
if ( pingdelta > MAX_PING_DELTA )
{
console.log("That's it! i'm killing the vm...")
await stopinstance()
return
}
}
catch( e ) {
// console.error( e.message )
// exit( 500 )
throw e
}
}
}
loop()
// // // // // // // // // // // //
const {readdirSync} = require('fs')
const execSync = require('child_process').execSync
console.clear()
var express = require('express')
var app = express()
const PORT = process.env.PORT || 1234
app.use( function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*")
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
next()
} )
app.use( '/', express.static('public') )
let lastping = new Date().getTime()
app.get( '/ping/update', (req, res) => res.send( ( lastping = new Date().getTime() ).toString() ) )
app.get( '/ping/get', (req, res) => res.send( lastping.toString() ) )
app.listen( PORT )