UNPKG

@microsoft/windows-admin-center-sdk

Version:

Microsoft - Windows Admin Center Shell

594 lines (592 loc) 26.3 kB
import { concat, of, ReplaySubject, Subject, throwError } from 'rxjs'; import { catchError, map, mergeMap, take, tap } from 'rxjs/operators'; import { VersionedObject } from '../base/versioned-object'; import { Net } from '../data/net'; import { LogLevel } from '../diagnostics/log-level'; import { Logging } from '../diagnostics/logging'; import { RpcServiceForwarder } from '../rpc/rpc-forwarder'; import { connectionTypeConstants, ConnectionUtility } from './connection'; import { ConnectionSettings } from './connection-manager-settings/connection-settings'; export var ConnectionChangeType; (function (ConnectionChangeType) { ConnectionChangeType[ConnectionChangeType["Initialized"] = 0] = "Initialized"; ConnectionChangeType[ConnectionChangeType["Activated"] = 1] = "Activated"; ConnectionChangeType[ConnectionChangeType["Added"] = 2] = "Added"; ConnectionChangeType[ConnectionChangeType["Removed"] = 3] = "Removed"; })(ConnectionChangeType || (ConnectionChangeType = {})); export class ConnectionManager extends RpcServiceForwarder { gatewayConnection; static activeConnectionPropertyName = 'activeConnection'; static connectionsPropertyName = 'connections'; static saveConnectionMethodName = 'saveConnection'; static saveConnectionsMethodName = 'saveConnections'; static removeConnectionMethodName = 'removeConnection'; static gatewayConnectionApi = 'connections'; allConnections = []; activeConnectionIndex = -1; /** * The map of active nodes aliases list, this will be build on demand and clear up whenever any connection aliases changed * key: nodeName, this is unique, that means same nodeName with different connection type treat as one entry * value: A aliases list for this nodeName (say cluster name), * this may contains child aliases (say IP address) of any alias (say server node). */ connectionAliasesMap = {}; /** * nodeAliasesVisit map, the key is connection nodeName */ nodeAliasesVisitMap = {}; /** * Subject that Fires once and remembers when connections have been initialized */ connectionsInitialized = new ReplaySubject(1); /** * Event subject that signals that the connection(s) have changed. * Filter on changeType to determine what type of change has occurred */ connectionsChanged = new Subject(); /** * Indicates that restoring connections has started and shouldnt call the gateway again */ restoreInProgress = false; /** * Indicates that restoring connections has started and shouldnt call the gateway again */ restoreCompleted = false; /** * The connection settings subject for caching the connection's settings while active. */ connectionSettings = new ReplaySubject(1); constructor(rpc, gatewayConnection) { super('connection-manager', rpc); this.gatewayConnection = gatewayConnection; } restoreConnections(refresh = false) { if (!this.canForward(0 /* RpcRelationshipType.Parent */) && (refresh || (!this.restoreCompleted && !this.restoreInProgress))) { this.restoreInProgress = true; this.gatewayConnection.get(ConnectionManager.gatewayConnectionApi) .pipe(map(data => { if (data.value) { (Array.isArray(data.value) ? data.value : [data.value]) .forEach(connection => { // for some reason the node api returns properties in a nested format. Unpack it into the correct format if (connection.properties) { connection = connection.properties; } // ensure bare minimum properties exist, ignore otherwise if (connection && connection.name && connection.type && connection.id) { this.addOrUpdateConnection(connection, false); return; } }); } return this.allConnections; }), catchError(error => { this.restoreInProgress = false; const message = MsftSme.getStrings().MsftSmeShell.Core.Error.ServerListRetrieve.message; Logging.log({ source: 'ConnectionManager', level: LogLevel.Error, message: message.format(Net.getErrorMessage(error)) }); this.connectionsInitialized.error(error); return of(this.allConnections); })) .subscribe(() => { this.forwardNotify(1 /* RpcRelationshipType.Child */, ConnectionManager.connectionsPropertyName, this.allConnections); this.connectionsChanged.next({ type: ConnectionChangeType.Initialized, connections: this.allConnections }); this.connectionsInitialized.next(this.allConnections); this.restoreInProgress = false; this.restoreCompleted = true; }); } return this.connectionsInitialized; } /** * Gets all connections */ get connections() { return this.allConnections; } /** * Gets active connection. */ get activeConnection() { return this.allConnections[this.activeConnectionIndex]; } /** * Sets active connection. */ set activeConnection(connection) { // only change active connection if it has really changed if (!ConnectionUtility.areEqual(this.activeConnection, connection)) { if (!connection) { this.activeConnectionIndex = -1; } else { this.activeConnectionIndex = this.addOrUpdateConnection(connection, false); } this.connectionsChanged.next({ type: ConnectionChangeType.Activated, connection: connection }); this.forwardNotify(1 /* RpcRelationshipType.Child */, ConnectionManager.activeConnectionPropertyName, this.activeConnection); this.forwardNotify(0 /* RpcRelationshipType.Parent */, ConnectionManager.activeConnectionPropertyName, this.activeConnection); // collect connection settings for new active connection this.getConnectionSettings().pipe(take(1)).subscribe(settings => this.connectionSettings.next(settings)); } } /** * Add or update connection. */ addOrUpdateConnection(connection, save = true, merge = false) { connection.id = ConnectionUtility.createConnectionId(connection.type, connection.name, connection.groupId); ConnectionUtility.forceLowercase(connection); let index = this.allConnections.findIndex(c => ConnectionUtility.areEqual(c, connection)); if (index >= 0) { if (merge) { const oldConnection = this.allConnections[index]; if (oldConnection.tags) { connection.tags = oldConnection.tags.concat(connection.tags || []).unique(); } if (oldConnection.properties) { connection.properties = { ...oldConnection.properties, ...connection.properties || {} }; } } this.allConnections[index] = connection; this.connectionsChanged.next({ type: ConnectionChangeType.Added, connection: connection }); } else { this.allConnections.push(connection); this.connectionsChanged.next({ type: ConnectionChangeType.Added, connection: connection }); if (!this.restoreInProgress) { this.connectionsInitialized.next(this.allConnections); } index = this.allConnections.length - 1; // notify parent and child of collection changed. this.forwardNotify(0 /* RpcRelationshipType.Parent */, ConnectionManager.connectionsPropertyName, this.allConnections); this.forwardNotify(1 /* RpcRelationshipType.Child */, ConnectionManager.connectionsPropertyName, this.allConnections); } if (save) { this.saveConnection(connection).subscribe(); } return index; } /** * Remove connection. */ removeConnection(connection) { const forward = this.forwardExecute(0 /* RpcRelationshipType.Parent */, ConnectionManager.removeConnectionMethodName, [connection]); if (forward) { return forward; } const urlEncodedID = encodeURIComponent(connection.id); return this.gatewayConnection.delete(`${ConnectionManager.gatewayConnectionApi}/${urlEncodedID}`) .pipe(map(response => { const index = this.allConnections.findIndex(c => ConnectionUtility.areEqual(c, connection)); if (index >= 0) { // if this connection is active, set active connection to null if (this.activeConnectionIndex === index) { this.activeConnection = null; } // remove the connection from all connections this.allConnections.splice(index, 1); } this.connectionsChanged.next({ type: ConnectionChangeType.Removed, connection: connection }); if (!this.restoreInProgress) { this.connectionsInitialized.next(this.allConnections); } // notify our children that connections have changed this.forwardNotify(1 /* RpcRelationshipType.Child */, ConnectionManager.connectionsPropertyName, this.allConnections); return response; })); } updateConnectionsLastCheckedTime(connections) { const now = Date.now(); const observables = []; if (connections && connections.length > 0) { connections.forEach(connection => { if (connection.properties == null || connection.properties.lastUpdatedTime == null || MsftSme.round(connection.properties.lastUpdatedTime / 1000) + 2 < MsftSme.round(now / 1000)) { // update if there is more than 2 second difference. connection.properties = connection.properties || {}; connection.properties.lastUpdatedTime = now; observables.push(this.saveConnection(connection)); } observables.push(of(null)); }); } else { observables.push(of(null)); } return concat(...observables); } saveConnection(connection) { ConnectionUtility.forceLowercase(connection); const forward = this.forwardExecute(0 /* RpcRelationshipType.Parent */, ConnectionManager.saveConnectionMethodName, [connection]); if (forward) { return forward; } if (!connection.type || !connection.name) { const message = MsftSme.getStrings().MsftSmeShell.Core.Error.ServerListFailedSave.message; return throwError(() => new Error(message)); } connection.id = ConnectionUtility.createConnectionId(connection.type, connection.name, connection.groupId); // define properties if it doesn't exist on the connection if (MsftSme.isNullOrUndefined(connection.properties)) { connection.properties = {}; } this.addOrUpdateConnection(connection, false); const urlEncodedID = encodeURIComponent(connection.id); return this.gatewayConnection.put(`${ConnectionManager.gatewayConnectionApi}/${urlEncodedID}`, JSON.stringify(connection)) .pipe(tap((data) => { if (data.properties && data.properties.displayName) { // merge the display name from the gateway into the connection properties connection.properties.displayName = data.properties.displayName; } this.forwardNotify(1 /* RpcRelationshipType.Child */, ConnectionManager.connectionsPropertyName, this.allConnections); })); } /** * Bulk operation for saving multiple connections * @param connection the connection object. */ saveConnections(connections) { connections.forEach(connection => { this.addOrUpdateConnection(connection, false); ConnectionUtility.forceLowercase(connection); if (!connection.type || !connection.name) { const message = MsftSme.getStrings().MsftSmeShell.Core.Error.ServerListFailedSave.message; return throwError(() => new Error(message)); } connection.id = ConnectionUtility.createConnectionId(connection.type, connection.name, connection.groupId); }); const forward = this.forwardExecute(0 /* RpcRelationshipType.Parent */, ConnectionManager.saveConnectionsMethodName, [connections]); if (forward) { return forward; } return this.gatewayConnection.put(`${ConnectionManager.gatewayConnectionApi}`, JSON.stringify(connections)) .pipe(tap(_ => { this.forwardNotify(1 /* RpcRelationshipType.Child */, ConnectionManager.connectionsPropertyName, this.allConnections); })); } /** * Finds a connection given a name and type * @param name the name of the connection to find * @param type the type of the connection to find, defaults to server type */ findConnection(name, type) { if (!name) { return of(null); } type = type || connectionTypeConstants.server; if (this.activeConnection && this.activeConnection.name === name && this.activeConnection.type === type) { return of(this.activeConnection); } return this.connectionsInitialized .pipe(map(_ => { return this.connections.find(c => c.name === name && c.type === type); })); } /** * Called on a child service instance when onForwardInit returns from the parent * @param data The response from the forwardInit call */ onForwardInitResponse(data) { if (data.error) { // if there is an error, we cannot continue, so throw its throw data.error; } this.allConnections = data.result.connections; this.activeConnection = data.result.activeConnection; this.connectionsChanged.next({ type: ConnectionChangeType.Initialized, connections: this.allConnections }); this.connectionsInitialized.next(this.allConnections); } /** * Called when a new instance of the service in another window is initialized and needs to synchronize with its parent * @param from The RpcRelationshipType that this request is from * @returns an observable for the all the values needed to initialize the service */ onForwardInit() { return of({ connections: this.connections, activeConnection: this.activeConnection }); } /** * Called when the forwarded services counterpart wants to get data from the parent * @param from The RpcRelationshipType that this request is from * @param name The name of the method to forward to * @param args The arguments of the method * @returns an observable for the result of the method call */ onForwardExecute(from, name, args) { if (from === 1 /* RpcRelationshipType.Child */ && args && args.length >= 1) { if (name === ConnectionManager.saveConnectionMethodName) { // we dont actually have anything to return here. return this.saveConnection(args[0]).pipe(map(() => null)); } if (name === ConnectionManager.saveConnectionsMethodName) { return this.saveConnections(args[0]); } if (name === ConnectionManager.removeConnectionMethodName) { // we dont actually have anything to return here. return this.removeConnection(args[0]).pipe(map(() => null)); } } // ConnectionManager does not allow any method calls at this time return this.nameNotFound(name); } /** * Called when the forwarded services counterpart sends a notify message * @param from The RpcRelationshipType that this request is from * @param name The name of the property to change * @param value The new value of the property * @returns an observable that completes when the property has been changed. */ onForwardNotify(from, name, value) { if (name === ConnectionManager.connectionsPropertyName) { this.allConnections = value; this.connectionsChanged.next({ type: ConnectionChangeType.Initialized, connections: this.allConnections }); this.connectionsInitialized.next(this.allConnections); return of(null); } if (name === ConnectionManager.activeConnectionPropertyName) { this.activeConnection = value; return of(null); } return this.nameNotFound(name); } /** * Get aliases data and save the change with connection * @param aliases the alias list. * @param connection the connection object. * @param nodeName the node name. */ saveAliasesData(aliases, connection, nodeName) { let save = false; // save the connection if aliase info changed if (!this.isArraySame(aliases, connection.aliases)) { connection.aliases = aliases; // remove the activeAlias if it's not in aliases any more if (connection.aliases.indexOf(connection.activeAlias) === -1) { connection.activeAlias = null; } save = true; } // if current nodeName is not connection name save it as activeAlias if (connection.name !== nodeName && connection.activeAlias !== nodeName) { connection.activeAlias = nodeName; save = true; } else { // current nodeName is connection name, remove connection activeAlias if (connection.name === nodeName && !!connection.activeAlias) { connection.activeAlias = null; save = true; } } if (save) { this.saveConnection(connection); } // delete visit map entry when succeed this.deleteAliasesVisitList(connection.name); } /** * Get active alias from nodeAliasesVisit map with given nodeName * return the node in aliases list in order, * return null if no alias or end of list * @param nodeName key in nodeAliasesVisitMap */ getActiveAlias(nodeName) { // aliases visit list already exists if (nodeName in this.nodeAliasesVisitMap) { const vlist = this.nodeAliasesVisitMap[nodeName]; // move currentIndex to next if (++vlist.currentIndex < vlist.aliases.length) { return vlist.aliases[vlist.currentIndex]; } else { // end of the list this.deleteAliasesVisitList(nodeName); return null; } } else { // no aliases list yet (first time or none) const aliases = this.getNodeAliasesList(nodeName); if (aliases) { // create aliases visit list for the first time const vlist = { currentIndex: 0, aliases: aliases }; this.nodeAliasesVisitMap[nodeName] = vlist; // return first item, aliases[vlist.currentIndex] return aliases[0]; } else { // no aliases, return null return null; } } } /** * Delete aliasesVistList entry with given nodeName from nodeAliasesVisitMap * @param nodeName the node name. */ deleteAliasesVisitList(nodeName) { if (nodeName in this.nodeAliasesVisitMap) { delete this.nodeAliasesVisitMap[nodeName]; } } isArraySame(array1, array2) { // both are not null, compare every element array1 = [].concat(array1); array2 = [].concat(array2); if (array1 && array2) { return (array1.length === array2.length) && array1.every(function (element, index) { return element === array2[index]; }); } else { // both are null if (!array1 && !array2) { return true; } else { // one of it is null return false; } } } /** * Get nodeAliasesList from map; if not exists create it * @param nodeName name of the node, this is unique regardless connection type */ getNodeAliasesList(nodeName) { if (nodeName in this.connectionAliasesMap) { return this.connectionAliasesMap[nodeName]; } else { return this.buildNodeAliasesList(nodeName); } } /** * Build nodeAliasesList entry with given nodeName, then add it into the map, * return the list of aliases * @param nodeName name of the node */ buildNodeAliasesList(nodeName) { const connection = this.findConnectionWithAliases(nodeName); if (!connection) { return null; } // assume activeAlias is in aliases[] let aliases = []; if (connection.activeAlias) { // put activeAlias at the first of the list aliases.push(connection.activeAlias); aliases = aliases.concat(connection.aliases.filter(item => item !== connection.activeAlias)); } else { aliases = connection.aliases; } for (let i = 0; i < aliases.length; i++) { const childList = this.buildNodeAliasesList(aliases[i]); // insert the childList to list, the list.length will increase if (childList) { // remove remaining items after current item const remainList = aliases.splice(i + 1, aliases.length - i); aliases = aliases.concat(childList, remainList); // next iteration move to node in childList } } this.connectionAliasesMap[nodeName] = aliases; return aliases; } /** * Finds the first connection with aliases info given a name, assume the connections already initialized * @param name the name of the connection to find */ findConnectionWithAliases(name) { if (!name) { return null; } if (this.activeConnection && this.activeConnection.name === name && !!this.activeConnection.aliases) { return this.activeConnection; } return this.connections.find(c => c.name === name && !!(c.aliases)); } /** * Gets the common connection settings. * By default, will use the active connection, but allows input for different connection objects. * @return Observable of the common connection settings object */ getCommonConnectionSettings(connection) { if (connection) { return this.getConnectionSettings(connection) .pipe(take(1), map(settings => settings.common), take(1)); } else { return this.connectionSettings.pipe(map(settings => settings.common), take(1)); } } /** * Get extension connection settings for the active connection. * @return Observable of specified type */ getExtensionConnectionSettings(type) { const name = MsftSme.self().Environment.name; return this.connectionSettings .pipe(map(settings => VersionedObject.ensureIsVersionedObject(settings.extensions[name])), map(settings => { return new type(settings, { save: (object) => this.setExtensionSettings(name, object) }); }), take(1)); } /** * Sets extension settings for the active connection. * @param extensionName the extension name. * @param extensionSettings the extension settings. */ setExtensionSettings(extensionName, extensionSettings) { return this.connectionSettings .pipe(mergeMap(settings => settings.trySave(() => { settings.extensions[extensionName] = extensionSettings; }))); } /** * Gets the connection settings object * By default, will use the active connection, but allows input for different connection objects. * @return Observable of ConnectionSettings */ getConnectionSettings(connection = this.activeConnection) { return of(connection).pipe(map(connectionObject => { return connectionObject.settings; }), take(1), catchError((error) => { const messageFormat = MsftSme.getStrings().MsftSmeShell.Core.Errors.UserProfile.Get.formatMessage; Logging.logError('ConnectionManager.getConnectionSettings', messageFormat.format(Net.getErrorMessage(error))); return throwError(() => error); }), map((settings) => { // If the setttings are not versioned (or not defined), then start with empty settings object settings = VersionedObject.ensureIsVersionedObject(settings); // return new connection settings object return new ConnectionSettings(settings, { save: (object) => this.setConnectionSettings(object, connection) }); })); } /** * Sets the connection settings from the active connection * @param settings a PlainVersionedObject * @return An observable with the result from the set operation */ setConnectionSettings(settings, connection) { // return an observable that saves the connection connection.settings = settings; return this.saveConnection(connection); } } //# sourceMappingURL=connection-manager.js.map