UNPKG

@mindconnect/mindconnect-nodejs

Version:

MindConnect Library for NodeJS (community based)

301 lines 13.9 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); const debug = require("debug"); const node_fetch_1 = require("node-fetch"); const credential_auth_1 = require("./credential-auth"); const utils_1 = require("./utils"); const log = debug("mindconnect-setup"); // Copyright (C), Siemens AG 2017 /** * This class can be used to perform some setup tasks * which can't be performed with the mindconnect agent itself. * * It is mostly used by the CLI to offboard the agents, clean up etc. * * @export * @class MindConnectSetup */ class MindConnectSetup extends credential_auth_1.CredentialAuth { /** * Register the agent for diagnostics. * * @param {string} agentId * @returns * * @memberOf MindConnectSetup */ RegisterForDiagnostic(agentId) { return __awaiter(this, void 0, void 0, function* () { utils_1.checkAssetId(agentId); yield this.RenewToken(); if (!this._accessToken) throw new Error("The agent doesn't have a valid access token."); const headers = Object.assign(Object.assign({}, this._apiHeaders), { Authorization: `Bearer ${this._accessToken.access_token}` }); const url = `${this._gateway}/api/mindconnect/v3/diagnosticActivations`; log(`RegisterForDiagnostic Headers ${JSON.stringify(headers)} Url ${url}`); const body = { agentId: agentId }; try { const response = yield node_fetch_1.default(url, { method: "POST", body: JSON.stringify(body), headers: headers, agent: this._proxyHttpAgent }); if (!response.ok) { throw new Error(`${response.statusText} ${yield response.text()}`); } if (response.status >= 200 && response.status <= 299) { const json = yield response.json(); log(`RegisterForDiagnostic Response ${JSON.stringify(json)}`); return json; } else { throw new Error(`invalid response ${JSON.stringify(response)}`); } } catch (err) { log(err); throw new Error(`Network error occured ${err.message}`); } }); } /** * Unregister the agent from the diagnostics. * * @param {string} agentId * @param {boolean} [ignoreError=false] * @returns * * @memberOf MindConnectSetup */ DeleteDiagnostic(agentId, ignoreError = false) { return __awaiter(this, void 0, void 0, function* () { if (!/[a-f0-9]{32}/gi.test(agentId)) { throw new Error("You have to pass valid 32 char long agent id"); } const activations = yield this.GetDiagnosticActivations(); for (const activation of activations.content) { if (activation.agentId === agentId) { if (!activation.id) { throw new Error("invalid activation id at diagnostic endpoint!"); } yield this.DeleteActivation(activation.id); return true; } } if (!ignoreError) { throw Error("there is no such agent id registered for diagnostic"); } }); } DeleteActivation(activationId) { return __awaiter(this, void 0, void 0, function* () { yield this.RenewToken(); if (!this._accessToken) throw new Error("The agent doesn't have a valid access token."); const headers = Object.assign(Object.assign({}, this._apiHeaders), { Authorization: `Bearer ${this._accessToken.access_token}` }); const url = `${this._gateway}/api/mindconnect/v3/diagnosticActivations/${activationId}`; log(`DeleteDiagnostic Headers ${JSON.stringify(headers)} Url ${url}`); try { const response = yield node_fetch_1.default(url, { method: "DELETE", headers: headers, agent: this._proxyHttpAgent }); if (!response.ok) { throw new Error(`${response.statusText} ${yield response.text()}`); } if (response.status >= 200 && response.status <= 299) { return true; } else { throw new Error(`invalid response ${JSON.stringify(response)}`); } } catch (err) { log(err); throw new Error(`Network error occured ${err.message}`); } }); } /** * Delete all diagnostic activations. As there are only 5 global diagnostic activations this can have unintended consequences. * Use with care. * * @memberOf MindConnectSetup */ DeleteAllDiagnosticActivations() { return __awaiter(this, void 0, void 0, function* () { const activations = yield this.GetDiagnosticActivations(); for (const activation of activations.content) { if (activation.id) yield this.DeleteActivation(activation.id); log(`Deleting activation with ${activation.id} for agent ${activation.agentId}`); } }); } /** * Gets all registered agents for diagnostic. * * @returns {Promise<PagedDiagnosticActivation>} * * @memberOf MindConnectSetup */ GetDiagnosticActivations() { return __awaiter(this, void 0, void 0, function* () { yield this.RenewToken(); if (!this._accessToken) throw new Error("The agent doesn't have a valid access token."); const headers = Object.assign(Object.assign({}, this._apiHeaders), { Authorization: `Bearer ${this._accessToken.access_token}` }); const url = `${this._gateway}/api/mindconnect/v3/diagnosticActivations`; log(`GetDiagnosticActivations Headers ${JSON.stringify(headers)} Url ${url}`); try { const response = yield node_fetch_1.default(url, { method: "GET", headers: headers, agent: this._proxyHttpAgent }); if (!response.ok) { throw new Error(`${response.statusText} ${yield response.text()}`); } if (response.status >= 200 && response.status <= 299) { const json = yield response.json(); log(`GetDiagnosticActivations Response ${JSON.stringify(json)}`); return json; } else { throw new Error(`invalid response ${JSON.stringify(response)}`); } } catch (err) { log(err); throw new Error(`Network error occured ${err.message}`); } }); } /** * Gets the diagnostic information for the registered agent(s) * * @param {string} [agentId] - Optional: If passed, only logs for this agent will be retrieved. * @param {(x: DiagnosticInformation[], ...args: any[]) => any} [callback] - Optional: pass the function which will handle the paged diagnostic info. The CLI uses printing to console function * @param {*} [callbackOptions] * @returns * * @memberOf MindConnectSetup */ GetDiagnosticInformation(agentId, callback, callbackOptions, skipToLast = true) { return __awaiter(this, void 0, void 0, function* () { let pagedInformation; let page = 0; do { pagedInformation = yield this.GetPagedInforamtion(page++, agentId); if (skipToLast) { page = pagedInformation.totalPages - 2; if (page < 0) page = 0; skipToLast = false; if (!pagedInformation.last) { continue; } } if (callback) { callback(pagedInformation.content, callbackOptions); } } while (!pagedInformation.last); return pagedInformation; }); } GetPagedInforamtion(page, agentId) { return __awaiter(this, void 0, void 0, function* () { yield this.RenewToken(); if (!this._accessToken) { throw new Error("The agent doesn't have a valid access token."); } const headers = Object.assign(Object.assign({}, this._apiHeaders), { Authorization: `Bearer ${this._accessToken.access_token}` }); let url = `${this._gateway}/api/mindconnect/v3/diagnosticInformation?size=50&page=${page}`; if (agentId) { url = `${url}&filter={"agentId" : "${agentId}"}`; } log(`GetDiagnosticInformation Headers ${JSON.stringify(headers)} Url ${url}`); try { const response = yield node_fetch_1.default(url, { method: "GET", headers: headers, agent: this._proxyHttpAgent }); if (!response.ok) { throw new Error(`${response.statusText} ${yield response.text()}`); } if (response.status >= 200 && response.status <= 299) { const json = yield response.json(); log(`GetDiagnosticInformation Response ${JSON.stringify(json)}`); return json; } else { throw new Error(`invalid response ${JSON.stringify(response)}`); } } catch (err) { log(err); throw new Error(`Network error occured ${err.message}`); } }); } GetAgentStatus(agentId) { return __awaiter(this, void 0, void 0, function* () { yield this.RenewToken(); if (!this._accessToken) { throw new Error("The agent doesn't have a valid access token."); } const headers = Object.assign(Object.assign({}, this._apiHeaders), { Authorization: `Bearer ${this._accessToken.access_token}` }); const url = `${this._gateway}/api/agentmanagement/v3/agents/${agentId}/status`; log(`GetAgentStatus Headers ${JSON.stringify(headers)} Url ${url}`); try { const response = yield node_fetch_1.default(url, { method: "GET", headers: headers, agent: this._proxyHttpAgent }); if (!response.ok) { throw new Error(`${response.statusText} ${yield response.text()}`); } if (response.status >= 200 && response.status <= 299) { const json = yield response.json(); log(`GetAgentStatus Response ${JSON.stringify(json)}`); return json; } else { throw new Error(`invalid response ${JSON.stringify(response)}`); } } catch (err) { log(err); throw new Error(`Network error occured ${err.message}`); } }); } GetBoardingStatus(agentId) { return __awaiter(this, void 0, void 0, function* () { yield this.RenewToken(); if (!this._accessToken) { throw new Error("The agent doesn't have a valid access token."); } const headers = Object.assign(Object.assign({}, this._apiHeaders), { Authorization: `Bearer ${this._accessToken.access_token}` }); const url = `${this._gateway}/api/agentmanagement/v3/agents/${agentId}/boarding/status`; log(`GetAgentStatus Headers ${JSON.stringify(headers)} Url ${url}`); try { const response = yield node_fetch_1.default(url, { method: "GET", headers: headers, agent: this._proxyHttpAgent }); if (!response.ok) { throw new Error(`${response.statusText} ${yield response.text()}`); } if (response.status >= 200 && response.status <= 299) { const json = yield response.json(); log(`GetBoardingStatus Response ${JSON.stringify(json)}`); return json; } else { throw new Error(`invalid response ${JSON.stringify(response)}`); } } catch (err) { log(err); throw new Error(`Network error occured ${err.message}`); } }); } } exports.MindConnectSetup = MindConnectSetup; //# sourceMappingURL=mindconnect-setup.js.map