Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 | 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x | import {
createNetworkGroup,
deleteNetworkGroup,
getNetworkGroup,
getNetworkGroupWireGuardConfiguration,
listNetworkGroups,
} from '@clevercloud/client/esm/api/v4/network-group.js';
import crypto from 'node:crypto';
import { searchNetworkGroupOrResource } from '../clever-client/ng.js';
import { styleText } from '../lib/style-text.js';
import { Logger } from '../logger.js';
import { getOwnerIdFromOrgIdOrName } from './ids-resolver.js';
import { checkMembersToLink } from './ng-resources.js';
import { sendToApi } from './send-to-api.js';
export const POLLING_TIMEOUT_MS = 30_000;
export const POLLING_INTERVAL_MS = 1000;
export const DOMAIN = 'cc-ng.cloud';
export const NG_MEMBER_PREFIXES = {
app_: 'APPLICATION',
elasticsearch_: 'ADDON',
mongodb_: 'ADDON',
mysql_: 'ADDON',
postgresql_: 'ADDON',
redis_: 'ADDON',
external_: 'EXTERNAL',
};
/**
* Ask for a Network Group creation
* @param {string} label The Network Group label
* @param {string} description The Network Group description
* @param {string} tags The Network Group tags
* @param {Array<string>} membersIds The members to link to the Network Group
* @param {string} orgaIdOrName The owner ID or name
* @throws {Error} If the Network Group label is missing
*/
export async function create(label, description, tags, membersIds, orgaIdOrName) {
const id = `ng_${crypto.randomUUID()}`;
const ownerId = await getOwnerIdFromOrgIdOrName(orgaIdOrName);
if (membersIds?.length > 0) {
checkMembersToLink(membersIds);
}
const members = constructMembers(id, membersIds || []);
const body = { ownerId, id, label, description, tags, members };
Logger.info(`Creating Network Group ${label} (${id}) from owner ${ownerId}`);
Logger.info(`${members.length} members will be added: ${members.map((m) => m.id).join(', ')}`);
Logger.debug(`Sending body: ${JSON.stringify(body, null, 2)}`);
await createNetworkGroup({ ownerId }, body).then(sendToApi);
await pollNetworkGroup(ownerId, id, { waitForMembers: membersIds });
Logger.info(`Network Group ${label} (${id}) created from owner ${ownerId}`);
}
/**
* Ask for a Network Group deletion
* @param {object} ngIdOrLabel The Network Group ID or Label
* @param {object} orgaIdOrName The owner ID or name
* @throws {Error} If the Network Group is not found
*/
export async function destroy(ngIdOrLabel, orgaIdOrName) {
const [found] = await searchNgOrResource(ngIdOrLabel, orgaIdOrName, 'NetworkGroup');
if (!found) {
throw new Error(`Network Group ${styleText('red', ngIdOrLabel.ngId ?? ngIdOrLabel.ngResourceLabel)} not found`);
}
await deleteNetworkGroup({ ownerId: found.ownerId, networkGroupId: found.id }).then(sendToApi);
Logger.info(`Deleting Network Group ${found.id} from owner ${found.ownerId}`);
await pollNetworkGroup(found.ownerId, found.id, { waitForDeletion: true });
Logger.info(`Network Group ${found.id} deleted from owner ${found.ownerId}`);
}
/**
* Get the WireGuard configuration of a Network Group peer
* @param {object} peerIdOrLabel The Peer ID or Label
* @param {object} ngIdOrLabel The Network Group ID or Label
* @param {object} orgaIdOrName The owner ID or name
* @returns {Promise<string>} The Peer WireGuard configuration
* @throws {Error} If the Peer is not found
* @throws {Error} If the Network Group is not found
* @throws {Error} If the Peer is not in the Network Group
*/
export async function getPeerConfig(peerIdOrLabel, ngIdOrLabel, orgaIdOrName) {
const [parentNg] = await searchNgOrResource(ngIdOrLabel, orgaIdOrName, 'NetworkGroup');
if (!parentNg) {
throw new Error(`Network Group ${styleText('red', ngIdOrLabel.ngId ?? ngIdOrLabel.ngResourceLabel)} not found`);
}
const [peer] = await searchNgOrResource(peerIdOrLabel, orgaIdOrName, 'Peer');
// peer.id is catched as a ngResourceLabel as it's a string with no distinctive prefix for now, it will change from API
if (
!peer ||
(peerIdOrLabel.ngResourceLabel &&
peerIdOrLabel.ngResourceLabel !== peer.label &&
peerIdOrLabel.ngResourceLabel !== peer.id)
) {
throw new Error(`Peer ${styleText('red', peerIdOrLabel.ngResourceLabel ?? peerIdOrLabel.member)} not found`);
}
if (!parentNg.peers.find((p) => p.id === peer.id)) {
throw new Error(`Peer ${styleText('red', peer.id)} is not in Network Group ${styleText('red', parentNg.id)}`);
}
Logger.debug(`Getting configuration for Peer ${peer.id}`);
const result = await getNetworkGroupWireGuardConfiguration({
ownerId: parentNg.ownerId,
networkGroupId: parentNg.id,
peerId: peer.id,
}).then(sendToApi);
Logger.debug(`Received from API:\n${result}`);
return result;
}
/**
* Get a Network Group from an owner with members and peers
* @param {string} networkGroupId The Network Group ID
* @param {string} orgaIdOrName The owner ID or name
* @returns {Promise<Array<Object>>} The Network Groups
*/
export async function getNG(networkGroupId, orgaIdOrName) {
const ownerId = await getOwnerIdFromOrgIdOrName(orgaIdOrName);
Logger.info(`Get Network Group ${networkGroupId} for owner ${ownerId}`);
const result = await getNetworkGroup({ networkGroupId, ownerId }).then(sendToApi);
Logger.debug(`Received from API:\n${JSON.stringify(result, null, 2)}`);
return result;
}
/**
* Get all Network Groups from an owner with members and peers
* @param {string} orgaIdOrName The owner ID or name
* @returns {Promise<Array<Object>>} The Network Groups
*/
export async function getAllNGs(orgaIdOrName) {
const ownerId = await getOwnerIdFromOrgIdOrName(orgaIdOrName);
Logger.info(`Listing Network Groups from owner ${ownerId}`);
const result = await listNetworkGroups({ ownerId }).then(sendToApi);
Logger.debug(`Received from API:\n${JSON.stringify(result, null, 2)}`);
return result;
}
/**
* Search a Network Group or a resource (member/peer)
* @param {string|Object} idOrLabel The ID or label to look for
* @param {Object} orgaIdOrName The owner ID or name
* @param {string} [type] Look only for a specific type (NetworkGroup, Member, CleverPeer, ExternalPeer, Peer), can be 'single', default to 'all'
* @param {boolean} exactMatch Look for exact match, default to true
* @throws {Error} If multiple Network Groups or member/peer are found in single_result mode
* @returns {Promise<Object>} Found results
*/
export async function searchNgOrResource(idOrLabel, orgaIdOrName, type = 'all', exactMatch = true) {
const ownerId = await getOwnerIdFromOrgIdOrName(orgaIdOrName);
// If idOrLabel is a string we use it, or we look through multiple keys
const query =
typeof idOrLabel === 'string' ? idOrLabel : (idOrLabel.ngId ?? idOrLabel.memberId ?? idOrLabel.ngResourceLabel);
const found = await searchNetworkGroupOrResource({ ownerId, query }).then(sendToApi);
let filtered = found;
switch (type) {
case 'all':
case 'single':
break;
case 'Peer':
filtered = found.filter((f) => f.type === 'CleverPeer' || f.type === 'ExternalPeer');
break;
case 'CleverPeer':
case 'ExternalPeer':
case 'Member':
case 'NetworkGroup':
filtered = found.filter((f) => f.type === type);
break;
default:
throw new Error(`Unsupported type: ${type}`);
}
if (exactMatch) {
filtered = filtered.filter((f) => f.id === query || f.label === query);
}
if (filtered.length > 1 && type !== 'all') {
throw new Error(`Multiple resources found for ${styleText('red', query)}, use ID instead:
${filtered.map((f) => ` • ${f.id} ${styleText('grey', `(${f.domainName || f.label} - ${f.type})`)}`).join('\n')}`);
}
// Deduplicate results
return filtered.filter((item, index, array) => array.findIndex((element) => element.id === item.id) === index);
}
/**
* Construct members from members_ids
* @param {string} ngId The Network Group ID
* @param {Array<string>} membersIds The members IDs
* @returns {Array<Object>} Array of members with id, domainName and kind
*/
export function constructMembers(ngId, membersIds) {
return membersIds.map((id) => {
const domainName = `${id}.m.${ngId}.${DOMAIN}`;
const prefix = Object.keys(NG_MEMBER_PREFIXES).find((p) => id.startsWith(p));
const kind = NG_MEMBER_PREFIXES[prefix];
return { id, domainName, kind };
});
}
/**
* Poll Network Groups to check its status and members
* @param {string} ownerId The owner ID
* @param {string} ngId The Network Group ID
* @param {Array<string>} waitForMembers The members IDs to wait for
* @param {boolean} waitForDeletion Wait for the Network Group deletion
* @throws {Error} When timeout is reached
* @returns {Promise<void>}
*/
async function pollNetworkGroup(ownerId, ngId, { waitForMembers = null, waitForDeletion = false } = {}) {
return new Promise((resolve, reject) => {
Logger.info(`Polling Network Groups from owner ${ownerId}`);
const timeoutTime = Date.now() + POLLING_TIMEOUT_MS;
async function pollOnce() {
if (Date.now() > timeoutTime) {
const action = waitForDeletion ? 'deletion of' : 'creation of';
reject(new Error(`Timeout while checking ${action} Network Group ${ngId}`));
return;
}
try {
const ngs = await listNetworkGroups({ ownerId }).then(sendToApi);
const ng = ngs.find((ng) => ng.id === ngId);
if (waitForDeletion && !ng) {
resolve();
return;
}
if (!waitForDeletion && ng) {
if (waitForMembers?.length) {
const members = ng.members.filter((member) => waitForMembers.includes(member.id));
if (members.length !== waitForMembers.length) {
Logger.debug(`Waiting for members: ${waitForMembers.join(', ')}`);
setTimeout(pollOnce, POLLING_INTERVAL_MS);
return;
}
}
resolve();
return;
}
setTimeout(pollOnce, POLLING_INTERVAL_MS);
} catch (error) {
reject(error);
}
}
pollOnce();
});
}
|