Files: 67f17984adbe450a9a06aa0987f1b232af5f3120 / creationService.js
1689 bytesRaw
1 | const chunk = require('chunk') |
2 | |
3 | const MAX_DATA_BYTES = 65533 |
4 | |
5 | module.exports = class CreationService { |
6 | constructor (opts) { |
7 | this.hypervisor = opts.hypervisor |
8 | this.scheduler = this.hypervisor.scheduler |
9 | } |
10 | |
11 | queue (port, message) { |
12 | if (message.data.type) { |
13 | let id |
14 | if (message.fromId) { |
15 | const creator = this.scheduler.getInstance(message.fromId) |
16 | id = creator.generateNextId() |
17 | } |
18 | return this.createInstance(message, id) |
19 | } |
20 | } |
21 | |
22 | getPort () { |
23 | return { |
24 | messages: [], |
25 | destId: 0 |
26 | } |
27 | } |
28 | |
29 | /** |
30 | * creates an new container instances and save it in the state |
31 | * @returns {Promise} |
32 | */ |
33 | async createInstance (message, id = {nonce: 0, parent: null}) { |
34 | const idHash = await this._getHashFromObj(id) |
35 | const state = { |
36 | nonce: [0], |
37 | ports: {}, |
38 | type: message.data.type |
39 | } |
40 | |
41 | if (message.data.code && message.data.code.length) { |
42 | state.code = message.data.code |
43 | } |
44 | |
45 | // create the container instance |
46 | const instance = await this.hypervisor._loadInstance(idHash, state) |
47 | |
48 | // send the intialization message |
49 | await instance.create(message) |
50 | |
51 | if (state.code && state.code.length > MAX_DATA_BYTES) { |
52 | state.code = chunk(state.code, MAX_DATA_BYTES).map(chk => { |
53 | return { |
54 | '/': chk |
55 | } |
56 | }) |
57 | } |
58 | // save the container in the state |
59 | await this.hypervisor.tree.set(idHash, state) |
60 | |
61 | if (!Object.keys(instance.ports.ports).length) { |
62 | this.hypervisor.addNodeToCheck(instance.id) |
63 | } |
64 | |
65 | return instance |
66 | } |
67 | |
68 | // get a hash from a POJO |
69 | _getHashFromObj (obj) { |
70 | return this.hypervisor.graph.flush(obj).then(obj => obj['/']) |
71 | } |
72 | } |
73 |
Built with git-ssb-web