39 lines
1.4 KiB
TypeScript
39 lines
1.4 KiB
TypeScript
import * as Koa from 'koa';
|
|
import { Instance } from '../entity/instance'
|
|
import { getRepository } from 'typeorm';
|
|
import { getLeastLoadedHost } from '../utils';
|
|
import { createInstance } from '../commands';
|
|
|
|
export async function showOrCreateInstance(ctx:Koa.Context) {
|
|
const uuid = ctx.params.uuid
|
|
if(!uuid) return await ctx.render("instane-not-found")
|
|
|
|
const instance = await getRepository(Instance).findOne(uuid)
|
|
if(!instance || instance.validUntil.valueOf() < Date.now()) return await ctx.render("instane-not-found")
|
|
console.log(instance)
|
|
if(instance.state == 'new') {
|
|
instance.state = 'creating'
|
|
await getRepository(Instance).save(instance)
|
|
const host = await getLeastLoadedHost()
|
|
createInstance(host.hostname, instance.uuid, instance.serverPassword, instance.suPassword)
|
|
.then(async (port) => {
|
|
instance.host = host.hostname
|
|
instance.port = port
|
|
instance.state = 'running'
|
|
await getRepository(Instance).save(instance)
|
|
})
|
|
.catch(err => {
|
|
console.log(instance)
|
|
console.log(err)
|
|
})
|
|
}
|
|
|
|
if(instance.state == 'running') {
|
|
await ctx.render("instance", {
|
|
instance,
|
|
expirationDate: instance.validUntil.toISOString().slice(0,16).replace('T', ' ')+' UTC'
|
|
})
|
|
} else {
|
|
await ctx.render("instance-creating")
|
|
}
|
|
} |