Files: a0b1792b4abd832c8abb3959057e090cd3e33741 / index.js
1536 bytesRaw
1 | const Graph = require('ipld-graph-builder') |
2 | const Kernel = require('./kernel.js') |
3 | |
4 | module.exports = class Hypervisor { |
5 | constructor (opts) { |
6 | this._opts = { |
7 | hypervisor: this, |
8 | VMs: {} |
9 | } |
10 | |
11 | this.graph = new Graph(opts.dag) |
12 | delete opts.dag |
13 | this._vmInstances = new Map() |
14 | Object.assign(this._opts, opts) |
15 | } |
16 | |
17 | async getInstance (port) { |
18 | const id = await this.generateID(port) |
19 | let kernel = this._vmInstances.get(id) |
20 | if (!kernel) { |
21 | // load the container from the state |
22 | await this.graph.tree(port, 2) |
23 | |
24 | // create a new kernel instance |
25 | const VM = this._opts.VMs[port.type] |
26 | const opts = Object.assign({ |
27 | state: port.vm, |
28 | id: port.id, |
29 | VM: VM |
30 | }, this._opts) |
31 | |
32 | kernel = new Kernel(opts) |
33 | await kernel.start() |
34 | kernel.on('idle', () => { |
35 | this._vmInstances.delete(id) |
36 | }) |
37 | this._vmInstances.set(id, kernel) |
38 | } |
39 | return kernel |
40 | } |
41 | |
42 | async send (port, message) { |
43 | const vm = await this.getInstance(port) |
44 | message._fromPort = 'root' |
45 | vm.queue(message) |
46 | } |
47 | |
48 | // given a port, wait untill its source contract has reached the threshold |
49 | // tick count |
50 | async wait (port, ticks) { |
51 | let kernel = await this.getInstance(port) |
52 | await kernel.wait(ticks) |
53 | return kernel |
54 | } |
55 | |
56 | async createStateRoot (port, ticks) { |
57 | await this.wait(port, ticks) |
58 | return this.graph.flush(port) |
59 | } |
60 | |
61 | generateID (port) { |
62 | this.graph.flush(port.id) |
63 | } |
64 | |
65 | addVM (type, vm) { |
66 | this._opts.VMs[type] = vm |
67 | } |
68 | } |
69 |
Built with git-ssb-web