@kapeta/local-cluster-service 0.8.3 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/cjs/src/assetManager.js +7 -4
  3. package/dist/cjs/src/clusterService.js +2 -0
  4. package/dist/cjs/src/codeGeneratorManager.js +3 -3
  5. package/dist/cjs/src/config/routes.js +1 -1
  6. package/dist/cjs/src/configManager.js +13 -1
  7. package/dist/cjs/src/containerManager.d.ts +25 -2
  8. package/dist/cjs/src/containerManager.js +51 -16
  9. package/dist/cjs/src/definitionsManager.d.ts +11 -0
  10. package/dist/cjs/src/definitionsManager.js +44 -0
  11. package/dist/cjs/src/filesystemManager.js +0 -2
  12. package/dist/cjs/src/instanceManager.d.ts +23 -47
  13. package/dist/cjs/src/instanceManager.js +416 -235
  14. package/dist/cjs/src/instances/routes.js +23 -14
  15. package/dist/cjs/src/middleware/kapeta.js +7 -0
  16. package/dist/cjs/src/networkManager.js +6 -0
  17. package/dist/cjs/src/operatorManager.js +8 -4
  18. package/dist/cjs/src/providerManager.js +3 -3
  19. package/dist/cjs/src/repositoryManager.js +7 -3
  20. package/dist/cjs/src/serviceManager.js +5 -0
  21. package/dist/cjs/src/types.d.ts +39 -13
  22. package/dist/cjs/src/types.js +28 -0
  23. package/dist/cjs/src/utils/BlockInstanceRunner.d.ts +3 -3
  24. package/dist/cjs/src/utils/BlockInstanceRunner.js +34 -32
  25. package/dist/cjs/src/utils/utils.d.ts +2 -0
  26. package/dist/cjs/src/utils/utils.js +17 -1
  27. package/dist/esm/src/assetManager.js +7 -4
  28. package/dist/esm/src/clusterService.js +2 -0
  29. package/dist/esm/src/codeGeneratorManager.js +3 -3
  30. package/dist/esm/src/config/routes.js +1 -1
  31. package/dist/esm/src/configManager.js +13 -1
  32. package/dist/esm/src/containerManager.d.ts +25 -2
  33. package/dist/esm/src/containerManager.js +50 -15
  34. package/dist/esm/src/definitionsManager.d.ts +11 -0
  35. package/dist/esm/src/definitionsManager.js +38 -0
  36. package/dist/esm/src/filesystemManager.js +0 -2
  37. package/dist/esm/src/instanceManager.d.ts +23 -47
  38. package/dist/esm/src/instanceManager.js +416 -236
  39. package/dist/esm/src/instances/routes.js +23 -14
  40. package/dist/esm/src/middleware/kapeta.js +7 -0
  41. package/dist/esm/src/networkManager.js +6 -0
  42. package/dist/esm/src/operatorManager.js +8 -4
  43. package/dist/esm/src/providerManager.js +3 -3
  44. package/dist/esm/src/repositoryManager.js +7 -3
  45. package/dist/esm/src/serviceManager.js +5 -0
  46. package/dist/esm/src/types.d.ts +39 -13
  47. package/dist/esm/src/types.js +27 -1
  48. package/dist/esm/src/utils/BlockInstanceRunner.d.ts +3 -3
  49. package/dist/esm/src/utils/BlockInstanceRunner.js +35 -33
  50. package/dist/esm/src/utils/utils.d.ts +2 -0
  51. package/dist/esm/src/utils/utils.js +14 -0
  52. package/package.json +2 -1
  53. package/src/assetManager.ts +7 -4
  54. package/src/clusterService.ts +3 -0
  55. package/src/codeGeneratorManager.ts +3 -2
  56. package/src/config/routes.ts +1 -1
  57. package/src/configManager.ts +13 -1
  58. package/src/containerManager.ts +72 -16
  59. package/src/definitionsManager.ts +54 -0
  60. package/src/filesystemManager.ts +0 -2
  61. package/src/instanceManager.ts +495 -266
  62. package/src/instances/routes.ts +23 -17
  63. package/src/middleware/kapeta.ts +10 -0
  64. package/src/networkManager.ts +6 -0
  65. package/src/operatorManager.ts +11 -6
  66. package/src/providerManager.ts +3 -2
  67. package/src/repositoryManager.ts +7 -3
  68. package/src/serviceManager.ts +6 -0
  69. package/src/types.ts +44 -14
  70. package/src/utils/BlockInstanceRunner.ts +39 -36
  71. package/src/utils/utils.ts +18 -0
@@ -9,6 +9,7 @@ const serviceManager_1 = require("../serviceManager");
9
9
  const cors_1 = require("../middleware/cors");
10
10
  const kapeta_1 = require("../middleware/kapeta");
11
11
  const stringBody_1 = require("../middleware/stringBody");
12
+ const types_1 = require("../types");
12
13
  const router = (0, express_promise_router_1.default)();
13
14
  router.use('/', cors_1.corsHandler);
14
15
  router.use('/', kapeta_1.kapetaHeaders);
@@ -28,10 +29,10 @@ router.get('/:systemId/instances', (req, res) => {
28
29
  * Start all instances in a plan
29
30
  */
30
31
  router.post('/:systemId/start', async (req, res) => {
31
- const processes = await instanceManager_1.instanceManager.createProcessesForPlan(req.params.systemId);
32
+ const instances = await instanceManager_1.instanceManager.startAllForPlan(req.params.systemId);
32
33
  res.status(202).send({
33
34
  ok: true,
34
- processes: processes.map((p) => {
35
+ processes: instances.map((p) => {
35
36
  return { pid: p.pid, type: p.type };
36
37
  }),
37
38
  });
@@ -49,7 +50,7 @@ router.post('/:systemId/stop', async (req, res) => {
49
50
  * Start single instance in a plan
50
51
  */
51
52
  router.post('/:systemId/:instanceId/start', async (req, res) => {
52
- const process = await instanceManager_1.instanceManager.createProcess(req.params.systemId, req.params.instanceId);
53
+ const process = await instanceManager_1.instanceManager.start(req.params.systemId, req.params.instanceId);
53
54
  res.status(202).send({
54
55
  ok: true,
55
56
  pid: process.pid,
@@ -60,20 +61,20 @@ router.post('/:systemId/:instanceId/start', async (req, res) => {
60
61
  * Stop single instance in a plan
61
62
  */
62
63
  router.post('/:systemId/:instanceId/stop', async (req, res) => {
63
- await instanceManager_1.instanceManager.stopProcess(req.params.systemId, req.params.instanceId);
64
+ await instanceManager_1.instanceManager.stop(req.params.systemId, req.params.instanceId);
64
65
  res.status(202).send({ ok: true });
65
66
  });
66
67
  /**
67
68
  * Get logs for instance in a plan
68
69
  */
69
70
  router.get('/:systemId/:instanceId/logs', (req, res) => {
70
- const processInfo = instanceManager_1.instanceManager.getProcessForInstance(req.params.systemId, req.params.instanceId);
71
- if (!processInfo) {
71
+ const instanceInfo = instanceManager_1.instanceManager.getInstance(req.params.systemId, req.params.instanceId);
72
+ if (!instanceInfo) {
72
73
  res.status(404).send({ ok: false });
73
74
  return;
74
75
  }
75
76
  res.status(202).send({
76
- logs: processInfo.logs(),
77
+ logs: instanceInfo.internal?.logs() ?? [],
77
78
  });
78
79
  });
79
80
  /**
@@ -106,7 +107,7 @@ router.use('/', (req, res, next) => {
106
107
  next();
107
108
  });
108
109
  /**
109
- * Updates the full configuration for a given service.
110
+ * Updates the full configuration for a given instance.
110
111
  */
111
112
  router.put('/', async (req, res) => {
112
113
  let instance = req.stringBody ? JSON.parse(req.stringBody) : null;
@@ -116,19 +117,27 @@ router.put('/', async (req, res) => {
116
117
  if (oldInstance) {
117
118
  instance.pid = oldInstance.pid;
118
119
  }
119
- instance.type = 'docker';
120
+ instance.type = types_1.InstanceType.DOCKER;
120
121
  }
121
- else if (req.kapeta.environment === 'process') {
122
- instance.type = 'process';
122
+ else {
123
+ // Coming from user starting the instance outside of kapeta
124
+ instance.type = types_1.InstanceType.LOCAL;
125
+ instance.owner = types_1.InstanceOwner.EXTERNAL;
126
+ instance.desiredStatus = types_1.DesiredInstanceStatus.EXTERNAL;
127
+ }
128
+ try {
129
+ await instanceManager_1.instanceManager.registerInstanceFromSDK(req.kapeta.systemId, req.kapeta.instanceId, instance);
130
+ res.status(202).send({ ok: true });
131
+ }
132
+ catch (e) {
133
+ res.status(400).send({ error: e.message });
123
134
  }
124
- await instanceManager_1.instanceManager.registerInstance(req.kapeta.systemId, req.kapeta.instanceId, instance);
125
- res.status(202).send({ ok: true });
126
135
  });
127
136
  /**
128
137
  * Delete instance
129
138
  */
130
139
  router.delete('/', async (req, res) => {
131
- await instanceManager_1.instanceManager.setInstanceAsStopped(req.kapeta.systemId, req.kapeta.instanceId);
140
+ await instanceManager_1.instanceManager.markAsStopped(req.kapeta.systemId, req.kapeta.instanceId);
132
141
  res.status(202).send({ ok: true });
133
142
  });
134
143
  exports.default = router;
@@ -1,11 +1,18 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.kapetaHeaders = void 0;
4
+ const utils_1 = require("../utils/utils");
4
5
  function kapetaHeaders(req, res, next) {
5
6
  let blockRef = req.headers['x-kapeta-block'];
6
7
  let systemId = req.headers['x-kapeta-system'];
7
8
  let instanceId = req.headers['x-kapeta-instance'];
8
9
  let environment = req.headers['x-kapeta-environment'];
10
+ if (blockRef) {
11
+ blockRef = (0, utils_1.normalizeKapetaUri)(blockRef);
12
+ }
13
+ if (systemId) {
14
+ systemId = (0, utils_1.normalizeKapetaUri)(systemId);
15
+ }
9
16
  req.kapeta = {
10
17
  blockRef,
11
18
  instanceId,
@@ -5,6 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.networkManager = void 0;
7
7
  const node_uuid_1 = __importDefault(require("node-uuid"));
8
+ const utils_1 = require("./utils/utils");
8
9
  class NetworkManager {
9
10
  _connections;
10
11
  _sources;
@@ -23,6 +24,7 @@ class NetworkManager {
23
24
  this._targets = {};
24
25
  }
25
26
  _ensureSystem(systemId) {
27
+ systemId = (0, utils_1.normalizeKapetaUri)(systemId);
26
28
  if (!this._connections[systemId]) {
27
29
  this._connections[systemId] = {};
28
30
  }
@@ -34,6 +36,7 @@ class NetworkManager {
34
36
  }
35
37
  }
36
38
  _ensureConnection(systemId, connectionId) {
39
+ systemId = (0, utils_1.normalizeKapetaUri)(systemId);
37
40
  this._ensureSystem(systemId);
38
41
  if (!this._connections[systemId][connectionId]) {
39
42
  this._connections[systemId][connectionId] = [];
@@ -41,6 +44,7 @@ class NetworkManager {
41
44
  return this._connections[systemId][connectionId];
42
45
  }
43
46
  _ensureSource(systemId, sourceBlockInstanceId) {
47
+ systemId = (0, utils_1.normalizeKapetaUri)(systemId);
44
48
  this._ensureSystem(systemId);
45
49
  if (!this._sources[systemId][sourceBlockInstanceId]) {
46
50
  this._sources[systemId][sourceBlockInstanceId] = [];
@@ -48,6 +52,7 @@ class NetworkManager {
48
52
  return this._sources[systemId][sourceBlockInstanceId];
49
53
  }
50
54
  _ensureTarget(systemId, targetBlockInstanceId) {
55
+ systemId = (0, utils_1.normalizeKapetaUri)(systemId);
51
56
  this._ensureSystem(systemId);
52
57
  if (!this._targets[systemId][targetBlockInstanceId]) {
53
58
  this._targets[systemId][targetBlockInstanceId] = [];
@@ -55,6 +60,7 @@ class NetworkManager {
55
60
  return this._targets[systemId][targetBlockInstanceId];
56
61
  }
57
62
  addRequest(systemId, connection, request, consumerMethodId, providerMethodId) {
63
+ systemId = (0, utils_1.normalizeKapetaUri)(systemId);
58
64
  const traffic = new Traffic(connection, request, consumerMethodId, providerMethodId);
59
65
  this._ensureConnection(systemId, traffic.connectionId).push(traffic);
60
66
  this._ensureSource(systemId, connection.provider.blockId).push(traffic);
@@ -4,7 +4,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.operatorManager = void 0;
7
- const local_cluster_config_1 = __importDefault(require("@kapeta/local-cluster-config"));
8
7
  const path_1 = __importDefault(require("path"));
9
8
  const md5_1 = __importDefault(require("md5"));
10
9
  const nodejs_utils_1 = require("@kapeta/nodejs-utils");
@@ -12,6 +11,8 @@ const serviceManager_1 = require("./serviceManager");
12
11
  const storageService_1 = require("./storageService");
13
12
  const containerManager_1 = require("./containerManager");
14
13
  const fs_extra_1 = __importDefault(require("fs-extra"));
14
+ const definitionsManager_1 = require("./definitionsManager");
15
+ const utils_1 = require("./utils/utils");
15
16
  const KIND_OPERATOR = 'core/resource-type-operator';
16
17
  class Operator {
17
18
  _data;
@@ -42,7 +43,7 @@ class OperatorManager {
42
43
  * @return {Operator}
43
44
  */
44
45
  getOperator(resourceType, version) {
45
- const operators = local_cluster_config_1.default.getDefinitions(KIND_OPERATOR);
46
+ const operators = definitionsManager_1.definitionsManager.getDefinitions(KIND_OPERATOR);
46
47
  const operator = operators.find((operator) => operator.definition &&
47
48
  operator.definition.metadata &&
48
49
  operator.definition.metadata.name &&
@@ -60,7 +61,8 @@ class OperatorManager {
60
61
  * Get information about a specific consumed resource
61
62
  */
62
63
  async getConsumerResourceInfo(systemId, fromServiceId, resourceType, portType, name, environment) {
63
- const plans = local_cluster_config_1.default.getDefinitions('core/plan');
64
+ systemId = (0, utils_1.normalizeKapetaUri)(systemId);
65
+ const plans = definitionsManager_1.definitionsManager.getDefinitions('core/plan');
64
66
  const planUri = (0, nodejs_utils_1.parseKapetaUri)(systemId);
65
67
  const currentPlan = plans.find((plan) => plan.definition.metadata.name === planUri.fullName && plan.version === planUri.version);
66
68
  if (!currentPlan) {
@@ -71,7 +73,9 @@ class OperatorManager {
71
73
  throw new Error(`Unknown instance: ${fromServiceId} in plan ${systemId}`);
72
74
  }
73
75
  const blockUri = (0, nodejs_utils_1.parseKapetaUri)(currentInstance.block.ref);
74
- const blockDefinition = local_cluster_config_1.default.getDefinitions().find((definition) => definition.version === blockUri.version && definition.definition.metadata.name === blockUri.fullName);
76
+ const blockDefinition = definitionsManager_1.definitionsManager
77
+ .getDefinitions()
78
+ .find((definition) => definition.version === blockUri.version && definition.definition.metadata.name === blockUri.fullName);
75
79
  if (!blockDefinition) {
76
80
  throw new Error(`Unknown block: ${currentInstance.block.ref} in plan ${systemId}`);
77
81
  }
@@ -7,14 +7,14 @@ exports.providerManager = void 0;
7
7
  const path_1 = __importDefault(require("path"));
8
8
  const fs_extra_1 = __importDefault(require("fs-extra"));
9
9
  const repositoryManager_1 = require("./repositoryManager");
10
- const local_cluster_config_1 = __importDefault(require("@kapeta/local-cluster-config"));
10
+ const definitionsManager_1 = require("./definitionsManager");
11
11
  class ProviderManager {
12
12
  _webAssetCache;
13
13
  constructor() {
14
14
  this._webAssetCache = {};
15
15
  }
16
16
  getWebProviders() {
17
- return local_cluster_config_1.default.getProviderDefinitions().filter((providerDefinition) => providerDefinition.hasWeb);
17
+ return definitionsManager_1.definitionsManager.getProviderDefinitions().filter((providerDefinition) => providerDefinition.hasWeb);
18
18
  }
19
19
  async getAsset(handle, name, version, sourceMap = false) {
20
20
  const fullName = `${handle}/${name}`;
@@ -37,7 +37,7 @@ class ProviderManager {
37
37
  return null;
38
38
  }
39
39
  }
40
- const providerDefinitions = local_cluster_config_1.default.getProviderDefinitions();
40
+ const providerDefinitions = definitionsManager_1.definitionsManager.getProviderDefinitions();
41
41
  if (providerDefinitions.length > 0) {
42
42
  console.log('## Loaded the following providers ##');
43
43
  providerDefinitions.forEach((providerDefinition) => {
@@ -14,6 +14,7 @@ const nodejs_utils_1 = require("@kapeta/nodejs-utils");
14
14
  const socketManager_1 = require("./socketManager");
15
15
  const progressListener_1 = require("./progressListener");
16
16
  const nodejs_registry_utils_1 = require("@kapeta/nodejs-registry-utils");
17
+ const definitionsManager_1 = require("./definitionsManager");
17
18
  const INSTALL_ATTEMPTED = {};
18
19
  class RepositoryManager {
19
20
  changeEventsEnabled;
@@ -89,6 +90,7 @@ class RepositoryManager {
89
90
  };
90
91
  allDefinitions = newDefinitions;
91
92
  socketManager_1.socketManager.emit(`assets`, 'changed', payload);
93
+ definitionsManager_1.definitionsManager.clearCache();
92
94
  });
93
95
  }
94
96
  catch (e) {
@@ -179,7 +181,7 @@ class RepositoryManager {
179
181
  //TODO: Get dependencies for local asset
180
182
  return;
181
183
  }
182
- const definitions = local_cluster_config_1.default.getDefinitions();
184
+ const definitions = definitionsManager_1.definitionsManager.getDefinitions();
183
185
  const installedAsset = definitions.find((d) => d.definition.metadata.name === fullName && d.version === version);
184
186
  if (installedAsset && this._cache[ref] === true) {
185
187
  return;
@@ -210,8 +212,10 @@ class RepositoryManager {
210
212
  else {
211
213
  //Ensure dependencies are installed
212
214
  const refs = assetVersion.dependencies.map((dep) => dep.name);
213
- console.log(`Auto-installing dependencies: ${refs.join(', ')}`);
214
- await this._install(refs);
215
+ if (refs.length > 0) {
216
+ console.log(`Auto-installing dependencies: ${refs.join(', ')}`);
217
+ await this._install(refs);
218
+ }
215
219
  }
216
220
  }
217
221
  }
@@ -7,6 +7,7 @@ exports.serviceManager = void 0;
7
7
  const lodash_1 = __importDefault(require("lodash"));
8
8
  const clusterService_1 = require("./clusterService");
9
9
  const storageService_1 = require("./storageService");
10
+ const utils_1 = require("./utils/utils");
10
11
  const DEFAULT_PORT_TYPE = 'rest';
11
12
  class ServiceManager {
12
13
  _systems;
@@ -41,6 +42,7 @@ class ServiceManager {
41
42
  return `http://${host}:${port}/${path}`;
42
43
  }
43
44
  _ensureSystem(systemId) {
45
+ systemId = (0, utils_1.normalizeKapetaUri)(systemId);
44
46
  if (!this._systems[systemId]) {
45
47
  this._systems[systemId] = {};
46
48
  }
@@ -54,6 +56,7 @@ class ServiceManager {
54
56
  return system[serviceId];
55
57
  }
56
58
  async ensureServicePort(systemId, blockInstanceId, portType = DEFAULT_PORT_TYPE) {
59
+ systemId = (0, utils_1.normalizeKapetaUri)(systemId);
57
60
  if (!portType) {
58
61
  portType = DEFAULT_PORT_TYPE;
59
62
  }
@@ -76,6 +79,7 @@ class ServiceManager {
76
79
  *
77
80
  */
78
81
  getConsumerAddress(systemId, consumerInstanceId, consumerResourceName, portType, environmentType) {
82
+ systemId = (0, utils_1.normalizeKapetaUri)(systemId);
79
83
  const port = clusterService_1.clusterService.getClusterServicePort();
80
84
  const path = clusterService_1.clusterService.getProxyPath(systemId, consumerInstanceId, consumerResourceName, portType);
81
85
  return this._forLocal(port, path, environmentType);
@@ -89,6 +93,7 @@ class ServiceManager {
89
93
  *
90
94
  */
91
95
  async getProviderAddress(systemId, providerInstanceId, portType) {
96
+ systemId = (0, utils_1.normalizeKapetaUri)(systemId);
92
97
  const port = await this.ensureServicePort(systemId, providerInstanceId, portType);
93
98
  return this._forLocal(port);
94
99
  }
@@ -24,29 +24,55 @@ export interface BlockProcessParams {
24
24
  ref: string;
25
25
  configuration?: AnyMap;
26
26
  }
27
- export type ProcessType = 'docker' | 'local';
28
- export interface ProcessDetails {
29
- pid: number | string;
30
- type: ProcessType;
31
- portType?: string;
27
+ export declare enum InstanceType {
28
+ DOCKER = "docker",
29
+ LOCAL = "local",
30
+ UNKNOWN = "unknown"
31
+ }
32
+ export declare enum InstanceOwner {
33
+ INTERNAL = "internal",
34
+ EXTERNAL = "external"
35
+ }
36
+ export declare enum InstanceStatus {
37
+ STOPPED = "stopped",
38
+ STARTING = "starting",
39
+ BUSY = "busy",
40
+ READY = "ready",
41
+ STOPPING = "stopping",
42
+ UNHEALTHY = "unhealthy",
43
+ FAILED = "failed"
44
+ }
45
+ export declare enum DesiredInstanceStatus {
46
+ STOP = "stop",
47
+ RUN = "run",
48
+ EXTERNAL = "external"
49
+ }
50
+ export type ProcessInfo = {
51
+ type: InstanceType;
52
+ pid?: number | string | null;
32
53
  output: EventEmitter;
54
+ portType?: string;
33
55
  logs: () => LogEntry[];
34
56
  stop: () => Promise<void> | void;
35
- }
36
- export interface ProcessInfo extends ProcessDetails {
37
- id: string;
38
- ref: string;
39
- name: string;
40
- }
57
+ };
41
58
  export type InstanceInfo = {
42
59
  systemId: string;
43
60
  instanceId: string;
61
+ ref: string;
62
+ name: string;
63
+ type: InstanceType;
64
+ owner: InstanceOwner;
65
+ status: InstanceStatus;
66
+ desiredStatus: DesiredInstanceStatus;
44
67
  address?: string;
68
+ startedAt?: number;
45
69
  health?: string | null;
46
- status: string;
47
70
  pid?: number | string | null;
48
- type: ProcessType;
49
71
  portType?: string;
72
+ internal?: {
73
+ output: EventEmitter;
74
+ logs: () => LogEntry[];
75
+ };
50
76
  };
51
77
  interface ResourceRef {
52
78
  blockId: string;
@@ -1,2 +1,30 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DesiredInstanceStatus = exports.InstanceStatus = exports.InstanceOwner = exports.InstanceType = void 0;
4
+ var InstanceType;
5
+ (function (InstanceType) {
6
+ InstanceType["DOCKER"] = "docker";
7
+ InstanceType["LOCAL"] = "local";
8
+ InstanceType["UNKNOWN"] = "unknown";
9
+ })(InstanceType || (exports.InstanceType = InstanceType = {}));
10
+ var InstanceOwner;
11
+ (function (InstanceOwner) {
12
+ InstanceOwner["INTERNAL"] = "internal";
13
+ InstanceOwner["EXTERNAL"] = "external";
14
+ })(InstanceOwner || (exports.InstanceOwner = InstanceOwner = {}));
15
+ var InstanceStatus;
16
+ (function (InstanceStatus) {
17
+ InstanceStatus["STOPPED"] = "stopped";
18
+ InstanceStatus["STARTING"] = "starting";
19
+ InstanceStatus["BUSY"] = "busy";
20
+ InstanceStatus["READY"] = "ready";
21
+ InstanceStatus["STOPPING"] = "stopping";
22
+ InstanceStatus["UNHEALTHY"] = "unhealthy";
23
+ InstanceStatus["FAILED"] = "failed";
24
+ })(InstanceStatus || (exports.InstanceStatus = InstanceStatus = {}));
25
+ var DesiredInstanceStatus;
26
+ (function (DesiredInstanceStatus) {
27
+ DesiredInstanceStatus["STOP"] = "stop";
28
+ DesiredInstanceStatus["RUN"] = "run";
29
+ DesiredInstanceStatus["EXTERNAL"] = "external";
30
+ })(DesiredInstanceStatus || (exports.DesiredInstanceStatus = DesiredInstanceStatus = {}));
@@ -1,9 +1,9 @@
1
1
  import { DefinitionInfo } from '@kapeta/local-cluster-config';
2
2
  import { KapetaURI } from '@kapeta/nodejs-utils';
3
- import { AnyMap, BlockProcessParams, ProcessDetails, ProcessInfo, StringMap } from '../types';
3
+ import { AnyMap, BlockProcessParams, ProcessInfo, StringMap } from '../types';
4
4
  export declare class BlockInstanceRunner {
5
5
  private readonly _systemId;
6
- constructor(planReference: string);
6
+ constructor(systemId: string);
7
7
  /**
8
8
  * Start a block
9
9
  *
@@ -25,5 +25,5 @@ export declare class BlockInstanceRunner {
25
25
  * @return {Promise<ProcessDetails>}
26
26
  * @private
27
27
  */
28
- _startOperatorProcess(blockInstance: BlockProcessParams, blockUri: KapetaURI, providerDefinition: DefinitionInfo, env: StringMap): Promise<ProcessDetails>;
28
+ _startOperatorProcess(blockInstance: BlockProcessParams, blockUri: KapetaURI, providerDefinition: DefinitionInfo, env: StringMap): Promise<ProcessInfo>;
29
29
  }
@@ -12,8 +12,9 @@ const serviceManager_1 = require("../serviceManager");
12
12
  const containerManager_1 = require("../containerManager");
13
13
  const LogData_1 = require("./LogData");
14
14
  const events_1 = __importDefault(require("events"));
15
- const md5_1 = __importDefault(require("md5"));
16
15
  const clusterService_1 = require("../clusterService");
16
+ const types_1 = require("../types");
17
+ const definitionsManager_1 = require("../definitionsManager");
17
18
  const KIND_BLOCK_TYPE_OPERATOR = 'core/block-type-operator';
18
19
  const KAPETA_SYSTEM_ID = 'KAPETA_SYSTEM_ID';
19
20
  const KAPETA_BLOCK_REF = 'KAPETA_BLOCK_REF';
@@ -28,7 +29,7 @@ const DOCKER_ENV_VARS = [
28
29
  `KAPETA_ENVIRONMENT_TYPE=docker`,
29
30
  ];
30
31
  function getProvider(uri) {
31
- return local_cluster_config_1.default.getProviderDefinitions().find((provider) => {
32
+ return definitionsManager_1.definitionsManager.getProviderDefinitions().find((provider) => {
32
33
  const ref = `${provider.definition.metadata.name}:${provider.version}`;
33
34
  return (0, nodejs_utils_1.parseKapetaUri)(ref).id === uri.id;
34
35
  });
@@ -42,13 +43,13 @@ function getProviderPorts(assetVersion) {
42
43
  }
43
44
  class BlockInstanceRunner {
44
45
  _systemId;
45
- constructor(planReference) {
46
+ constructor(systemId) {
46
47
  /**
47
48
  *
48
49
  * @type {string}
49
50
  * @private
50
51
  */
51
- this._systemId = planReference ?? '';
52
+ this._systemId = (0, utils_1.normalizeKapetaUri)(systemId);
52
53
  }
53
54
  /**
54
55
  * Start a block
@@ -76,7 +77,7 @@ class BlockInstanceRunner {
76
77
  if (!blockUri.version) {
77
78
  blockUri.version = 'local';
78
79
  }
79
- const assetVersion = local_cluster_config_1.default.getDefinitions().find((definitions) => {
80
+ const assetVersion = definitionsManager_1.definitionsManager.getDefinitions().find((definitions) => {
80
81
  const ref = `${definitions.definition.metadata.name}:${definitions.version}`;
81
82
  return (0, nodejs_utils_1.parseKapetaUri)(ref).id === blockUri.id;
82
83
  });
@@ -88,28 +89,24 @@ class BlockInstanceRunner {
88
89
  if (!providerVersion) {
89
90
  throw new Error(`Kind not found: ${kindUri.id}`);
90
91
  }
91
- let processDetails;
92
+ let processInfo;
92
93
  if (providerVersion.definition.kind === KIND_BLOCK_TYPE_OPERATOR) {
93
- processDetails = await this._startOperatorProcess(blockInstance, blockUri, providerVersion, env);
94
+ processInfo = await this._startOperatorProcess(blockInstance, blockUri, providerVersion, env);
94
95
  }
95
96
  else {
96
97
  //We need a port type to know how to connect to the block consistently
97
98
  const portTypes = getProviderPorts(assetVersion);
98
99
  if (blockUri.version === 'local') {
99
- processDetails = await this._startLocalProcess(blockInstance, blockUri, env, assetVersion);
100
+ processInfo = await this._startLocalProcess(blockInstance, blockUri, env, assetVersion);
100
101
  }
101
102
  else {
102
- processDetails = await this._startDockerProcess(blockInstance, blockUri, env);
103
+ processInfo = await this._startDockerProcess(blockInstance, blockUri, env);
103
104
  }
104
105
  if (portTypes.length > 0) {
105
- processDetails.portType = portTypes[0];
106
+ processInfo.portType = portTypes[0];
106
107
  }
107
108
  }
108
- return {
109
- name: blockUri.id,
110
- ...blockInstance,
111
- ...processDetails,
112
- };
109
+ return processInfo;
113
110
  }
114
111
  /**
115
112
  * Starts local process
@@ -136,22 +133,24 @@ class BlockInstanceRunner {
136
133
  if (!dockerImage) {
137
134
  throw new Error(`Missing docker image information: ${JSON.stringify(localContainer)}`);
138
135
  }
139
- const containerName = `kapeta-block-instance-${blockInstance.id}`;
136
+ const containerName = (0, utils_1.getBlockInstanceContainerName)(blockInstance.id);
140
137
  const logs = new LogData_1.LogData();
141
138
  logs.addLog(`Starting block ${blockInstance.ref}`);
142
- let container = (await containerManager_1.containerManager.getContainerByName(containerName)) ?? null;
139
+ let containerInfo = await containerManager_1.containerManager.getContainerByName(containerName);
140
+ let container = containerInfo?.native;
143
141
  console.log('Starting dev container', containerName);
144
- if (container) {
145
- console.log(`Container already exists. Deleting...`);
142
+ if (containerInfo) {
143
+ console.log(`Dev container already exists. Deleting...`);
146
144
  try {
147
- await container.delete({
145
+ await containerInfo.remove({
148
146
  force: true,
149
147
  });
150
148
  }
151
149
  catch (e) {
152
150
  throw new Error('Failed to delete existing container: ' + e.message);
153
151
  }
154
- container = null;
152
+ container = undefined;
153
+ containerInfo = undefined;
155
154
  }
156
155
  logs.addLog(`Creating new container for block: ${containerName}`);
157
156
  console.log('Creating new dev container', containerName, dockerImage);
@@ -184,6 +183,7 @@ class BlockInstanceRunner {
184
183
  if (localContainer.healthcheck) {
185
184
  HealthCheck = containerManager_1.containerManager.toDockerHealth({ cmd: localContainer.healthcheck });
186
185
  }
186
+ console.log('Starting dev container', containerName, dockerImage);
187
187
  container = await containerManager_1.containerManager.startContainer({
188
188
  Image: dockerImage,
189
189
  name: containerName,
@@ -246,14 +246,14 @@ class BlockInstanceRunner {
246
246
  const data = status.data;
247
247
  if (deleteOnExit) {
248
248
  try {
249
- await container.delete();
249
+ await containerManager_1.containerManager.remove(container);
250
250
  }
251
251
  catch (e) { }
252
252
  }
253
253
  outputEvents.emit('exit', data?.State?.ExitCode ?? 0);
254
254
  });
255
255
  return {
256
- type: 'docker',
256
+ type: types_1.InstanceType.DOCKER,
257
257
  pid: container.id,
258
258
  output: outputEvents,
259
259
  stop: async () => {
@@ -263,7 +263,7 @@ class BlockInstanceRunner {
263
263
  try {
264
264
  await localContainer.stop();
265
265
  if (deleteOnExit) {
266
- await localContainer.delete();
266
+ await containerManager_1.containerManager.remove(localContainer);
267
267
  }
268
268
  }
269
269
  catch (e) { }
@@ -288,9 +288,10 @@ class BlockInstanceRunner {
288
288
  if (!dockerImage) {
289
289
  throw new Error(`Missing docker image information: ${JSON.stringify(versionInfo?.artifact?.details)}`);
290
290
  }
291
- const containerName = `kapeta-block-instance-${blockInstance.id}`;
291
+ const containerName = (0, utils_1.getBlockInstanceContainerName)(blockInstance.id);
292
292
  const logs = new LogData_1.LogData();
293
- let container = await containerManager_1.containerManager.getContainerByName(containerName);
293
+ const containerInfo = await containerManager_1.containerManager.getContainerByName(containerName);
294
+ let container = containerInfo?.native;
294
295
  // For windows we need to default to root
295
296
  const innerHome = process.platform === 'win32' ? '/root/.kapeta' : local_cluster_config_1.default.getKapetaBasedir();
296
297
  if (container) {
@@ -356,9 +357,10 @@ class BlockInstanceRunner {
356
357
  catch (e) {
357
358
  console.warn('Failed to pull image. Continuing...', e);
358
359
  }
359
- const containerName = `kapeta-block-instance-${(0, md5_1.default)(blockInstance.id)}`;
360
+ const containerName = (0, utils_1.getBlockInstanceContainerName)(blockInstance.id);
360
361
  const logs = new LogData_1.LogData();
361
- let container = (await containerManager_1.containerManager.getContainerByName(containerName)) ?? null;
362
+ const containerInfo = await containerManager_1.containerManager.getContainerByName(containerName);
363
+ let container = containerInfo?.native;
362
364
  if (container) {
363
365
  const containerData = container.data;
364
366
  if (containerData.State === 'running') {
@@ -368,10 +370,10 @@ class BlockInstanceRunner {
368
370
  if (containerData.State?.ExitCode > 0) {
369
371
  logs.addLog(`Container exited with code: ${containerData.State.ExitCode}. Deleting...`);
370
372
  try {
371
- await container.delete();
373
+ await containerManager_1.containerManager.remove(container);
372
374
  }
373
375
  catch (e) { }
374
- container = null;
376
+ container = undefined;
375
377
  }
376
378
  else {
377
379
  logs.addLog(`Found existing container for block: ${containerName}. Starting now`);
@@ -381,10 +383,10 @@ class BlockInstanceRunner {
381
383
  catch (e) {
382
384
  console.warn('Failed to start container. Deleting...', e);
383
385
  try {
384
- await container.delete();
386
+ await containerManager_1.containerManager.remove(container);
385
387
  }
386
388
  catch (e) { }
387
- container = null;
389
+ container = undefined;
388
390
  }
389
391
  }
390
392
  }
@@ -1,3 +1,5 @@
1
+ export declare function getBlockInstanceContainerName(instanceId: string): string;
2
+ export declare function normalizeKapetaUri(uri: string): string;
1
3
  export declare function readYML(path: string): any;
2
4
  export declare function isWindows(): boolean;
3
5
  export declare function isMac(): boolean;
@@ -3,9 +3,25 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.getBindHost = exports.isLinux = exports.isMac = exports.isWindows = exports.readYML = void 0;
6
+ exports.getBindHost = exports.isLinux = exports.isMac = exports.isWindows = exports.readYML = exports.normalizeKapetaUri = exports.getBlockInstanceContainerName = void 0;
7
7
  const node_fs_1 = __importDefault(require("node:fs"));
8
8
  const yaml_1 = __importDefault(require("yaml"));
9
+ const nodejs_utils_1 = require("@kapeta/nodejs-utils");
10
+ function getBlockInstanceContainerName(instanceId) {
11
+ return `kapeta-block-instance-${instanceId}`;
12
+ }
13
+ exports.getBlockInstanceContainerName = getBlockInstanceContainerName;
14
+ function normalizeKapetaUri(uri) {
15
+ if (!uri) {
16
+ return '';
17
+ }
18
+ const uriObj = (0, nodejs_utils_1.parseKapetaUri)(uri);
19
+ if (!uriObj.version) {
20
+ return `kapeta://${(0, nodejs_utils_1.parseKapetaUri)(uri).fullName}`;
21
+ }
22
+ return `kapeta://${(0, nodejs_utils_1.parseKapetaUri)(uri).id}`;
23
+ }
24
+ exports.normalizeKapetaUri = normalizeKapetaUri;
9
25
  function readYML(path) {
10
26
  const rawYaml = node_fs_1.default.readFileSync(path);
11
27
  try {