From 6e3604d6fa8881e903cb9f24d27a6dd14043e88d Mon Sep 17 00:00:00 2001 From: frankpagan Date: Sat, 25 Nov 2023 09:57:41 -0600 Subject: [PATCH] fix: metrics-server renamed to metrics --- CoCreate.config.js | 4 +- src/commands/other/aws.js | 67 +++++++++++++++++++ src/commands/other/google-cloud.js | 56 ++++++++++++++++ src/commands/other/haproxy.js | 76 ++++++++++++++++++++++ src/commands/other/haproxyConfigManager.js | 63 ++++++++++++++++++ src/commands/other/metrics.js | 33 ++++++++++ src/commands/other/nginx.js | 76 ++++++++++++++++++++++ src/commands/other/nodeCertManager.js | 34 ++++++++++ 8 files changed, 407 insertions(+), 2 deletions(-) create mode 100644 src/commands/other/aws.js create mode 100644 src/commands/other/google-cloud.js create mode 100644 src/commands/other/haproxy.js create mode 100644 src/commands/other/haproxyConfigManager.js create mode 100644 src/commands/other/metrics.js create mode 100644 src/commands/other/nginx.js diff --git a/CoCreate.config.js b/CoCreate.config.js index a43a17c..702e17c 100644 --- a/CoCreate.config.js +++ b/CoCreate.config.js @@ -402,8 +402,8 @@ module.exports = { "repo": "github.com/CoCreate-app/CoCreate-loadtest.git" }, { - "path": "../CoCreate-metrics-server", - "repo": "github.com/CoCreate-app/CoCreate-metrics-server.git" + "path": "../CoCreate-metrics", + "repo": "github.com/CoCreate-app/CoCreate-metrics.git" }, { "path": "../CoCreate-mongodb", diff --git a/src/commands/other/aws.js b/src/commands/other/aws.js new file mode 100644 index 0000000..800dbe7 --- /dev/null +++ b/src/commands/other/aws.js @@ -0,0 +1,67 @@ +const AWS = require('aws-sdk'); +const { NodeSSH } = require('node-ssh'); // npm install node-ssh +const ssh = new NodeSSH(); + +AWS.config.update({ region: 'us-west-2' }); + +const ec2 = new AWS.EC2({ apiVersion: '2016-11-15' }); + +const instanceParams = { + ImageId: 'ami-0abcdef1234567890', + InstanceType: 't2.micro', + KeyName: 'your-key-pair-name', + MinCount: 1, + MaxCount: 1 +}; + +ec2.runInstances(instanceParams, function (err, data) { + if (err) { + console.error("Could not create instance", err); + return; + } + const instanceId = data.Instances[0].InstanceId; + console.log("Created instance", instanceId); + + // Wait for instance to be in running state and get its Public DNS + waitForInstanceRunning(instanceId, (err, instanceData) => { + if (err) { + console.error("Error waiting for instance running", err); + return; + } + + // SSH into the instance and install Node.js + ssh.connect({ + host: instanceData.PublicDnsName, + username: 'ec2-user', // default username for Amazon AMI + privateKey: 'path/to/your/key-pair.pem' + }) + .then(function () { + // Commands to install Node.js and start your server + const commands = [ + 'curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -', + 'sudo apt-get install -y nodejs', + // additional commands to clone your project, install dependencies, and start the server + ]; + + return ssh.execCommand(commands.join(' && ')); + }) + .then(function (result) { + console.log('STDOUT: ' + result.stdout); + console.log('STDERR: ' + result.stderr); + }) + .catch(function (error) { + console.error('SSH Connection Error: ' + error); + }); + }); +}); + +function waitForInstanceRunning(instanceId, callback) { + ec2.waitFor('instanceRunning', { InstanceIds: [instanceId] }, function (err, data) { + if (err) { + callback(err); + return; + } + const instanceData = data.Reservations[0].Instances[0]; + callback(null, instanceData); + }); +} diff --git a/src/commands/other/google-cloud.js b/src/commands/other/google-cloud.js new file mode 100644 index 0000000..fdf25fd --- /dev/null +++ b/src/commands/other/google-cloud.js @@ -0,0 +1,56 @@ +const { Compute } = require('@google-cloud/compute'); +const path = require('path'); +const { NodeSSH } = require('node-ssh'); +const ssh = new NodeSSH(); + +// Set GCP Project ID and path to your service account key +const projectId = 'your-project-id'; +const keyFilename = path.join(__dirname, 'path-to-your-service-account-key.json'); + +// Initialize Google Compute Engine API +const compute = new Compute({ projectId, keyFilename }); + +// Configuration for the VM instance +const zone = compute.zone('us-central1-a'); // change as per your requirement +const config = { + os: 'ubuntu', + machineType: 'n1-standard-1', // change as per your requirement + http: true, + https: true +}; + +async function createVM() { + try { + const vmName = 'your-vm-name'; // choose a name for your VM + const [, operation] = await zone.createVM(vmName, config); + await operation.promise(); + + // Retrieve the newly created VM metadata + const vm = zone.vm(vmName); + const [metadata] = await vm.getMetadata(); + + // Connect to the VM via SSH and install Node.js + // This assumes you have set up SSH keys for GCP VMs + const externalIP = metadata.networkInterfaces[0].accessConfigs[0].natIP; + await ssh.connect({ + host: externalIP, + username: 'your-ssh-username', // default is often 'ubuntu' for Ubuntu VMs + privateKey: 'path/to/your/private/ssh/key' + }); + + const commands = [ + 'curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -', + 'sudo apt-get install -y nodejs', + // Additional commands as needed + ]; + + const result = await ssh.execCommand(commands.join(' && ')); + console.log('STDOUT:', result.stdout); + console.log('STDERR:', result.stderr); + + } catch (err) { + console.error('Error during VM creation:', err); + } +} + +createVM(); diff --git a/src/commands/other/haproxy.js b/src/commands/other/haproxy.js new file mode 100644 index 0000000..19c51c8 --- /dev/null +++ b/src/commands/other/haproxy.js @@ -0,0 +1,76 @@ +const fs = require('fs'); +const { exec } = require('child_process'); + +const haproxyConfigPath = '/etc/haproxy/haproxy.cfg'; +const backendSectionName = 'backend app_backend'; + +// Function to update HAProxy config with new servers +const updateHAProxyConfig = (newServers) => { + fs.readFile(haproxyConfigPath, 'utf8', (err, data) => { + if (err) { + console.error('Error reading HAProxy config:', err); + return; + } + + const updatedConfig = updateBackendServers(data, newServers); + fs.writeFile(haproxyConfigPath, updatedConfig, 'utf8', (err) => { + if (err) { + console.error('Error writing updated HAProxy config:', err); + return; + } + + reloadHAProxy(); + }); + }); +}; + +// Function to replace backend server entries in the config +const updateBackendServers = (configData, newServers) => { + const lines = configData.split('\n'); + let backendSectionStart = -1; + let backendSectionEnd = -1; + + // Find the start and end of the backend section + lines.forEach((line, index) => { + if (line.trim() === backendSectionName) { + backendSectionStart = index; + } + if (backendSectionStart !== -1 && backendSectionEnd === -1 && line.trim() === '') { + backendSectionEnd = index; + } + }); + + if (backendSectionStart === -1 || backendSectionEnd === -1) { + console.error('Backend section not found in HAProxy config'); + return configData; + } + + // Replace the server list in the backend section + const newServerLines = newServers.map(server => ` server ${server.name} ${server.address} check`); + const updatedLines = [ + ...lines.slice(0, backendSectionStart + 1), + ...newServerLines, + ...lines.slice(backendSectionEnd) + ]; + + return updatedLines.join('\n'); +}; + +// Function to reload HAProxy +const reloadHAProxy = () => { + exec('systemctl reload haproxy', (err, stdout, stderr) => { + if (err) { + console.error('Error reloading HAProxy:', err); + return; + } + console.log('HAProxy reloaded successfully'); + }); +}; + +// Example usage +const newServers = [ + { name: 'app1', address: '10.0.0.1:80' }, + { name: 'app2', address: '10.0.0.2:80' } +]; + +updateHAProxyConfig(newServers); diff --git a/src/commands/other/haproxyConfigManager.js b/src/commands/other/haproxyConfigManager.js new file mode 100644 index 0000000..ea6617e --- /dev/null +++ b/src/commands/other/haproxyConfigManager.js @@ -0,0 +1,63 @@ +const fs = require('fs'); +const { exec } = require('child_process'); + +const haproxyConfigPath = '/etc/haproxy/haproxy.cfg'; + +// Function to add a new configuration to HAProxy and restart it +const addHAProxyConfig = (frontendName, backendName, backendServers) => { + fs.readFile(haproxyConfigPath, 'utf8', (err, data) => { + if (err) { + console.error('Error reading HAProxy config:', err); + return; + } + + // Append new frontend and backend configuration + const newConfig = ` +# Frontend Configuration +frontend ${frontendName} + bind *:80 + mode http + default_backend ${backendName} + +# Backend Configuration +backend ${backendName} + mode http + balance roundrobin`; + + // Add server entries + backendServers.forEach((server, index) => { + newConfig += `\n server server${index} ${server.address} check`; + }); + + // Write updated configuration + fs.writeFile(haproxyConfigPath, data + newConfig, 'utf8', (err) => { + if (err) { + console.error('Error writing updated HAProxy config:', err); + return; + } + + restartHAProxy(); + }); + }); +}; + +// Function to restart HAProxy +const restartHAProxy = () => { + exec('systemctl restart haproxy', (err, stdout, stderr) => { + if (err) { + console.error('Error restarting HAProxy:', err); + return; + } + console.log('HAProxy restarted successfully'); + }); +}; + +// Example usage +const frontendName = 'my_frontend'; +const backendName = 'my_backend'; +const backendServers = [ + { address: '10.0.0.1:80' }, + { address: '10.0.0.2:80' } +]; + +addHAProxyConfig(frontendName, backendName, backendServers); diff --git a/src/commands/other/metrics.js b/src/commands/other/metrics.js new file mode 100644 index 0000000..398f3e4 --- /dev/null +++ b/src/commands/other/metrics.js @@ -0,0 +1,33 @@ +const fs = require('fs'); + +// Function to parse and display memory info +const readMemoryInfo = () => { + const memInfoContent = fs.readFileSync('/proc/meminfo', 'utf8'); + const memInfoLines = memInfoContent.split('\n'); + const memInfo = memInfoLines.reduce((info, line) => { + const parts = line.split(':'); + if (parts.length === 2) { + info[parts[0].trim()] = parts[1].trim(); + } + return info; + }, {}); + console.log('Memory Info:', memInfo); +}; + +// Function to read CPU info (simplified) +const readCpuInfo = () => { + const cpuInfoContent = fs.readFileSync('/proc/stat', 'utf8'); + const cpuLines = cpuInfoContent.split('\n'); + const cpuLine = cpuLines.find(line => line.startsWith('cpu ')); + if (cpuLine) { + // Example processing; more needed for actual CPU usage calculation + const cpuTimes = cpuLine.split(' ').slice(1).map(Number); + console.log('CPU Times:', cpuTimes); + } +}; + +// Read memory and CPU info +setInterval(() => { + readMemoryInfo(); + readCpuInfo(); +}, 500); diff --git a/src/commands/other/nginx.js b/src/commands/other/nginx.js new file mode 100644 index 0000000..5270f62 --- /dev/null +++ b/src/commands/other/nginx.js @@ -0,0 +1,76 @@ +const fs = require('fs'); +const { exec } = require('child_process'); + +const nginxConfigPath = '/etc/nginx/conf.d/myapp.conf'; +const upstreamBlockName = 'upstream app_backend'; + +// Function to update NGINX config with new servers +const updateNginxConfig = (newServers) => { + fs.readFile(nginxConfigPath, 'utf8', (err, data) => { + if (err) { + console.error('Error reading NGINX config:', err); + return; + } + + const updatedConfig = updateUpstreamServers(data, newServers); + fs.writeFile(nginxConfigPath, updatedConfig, 'utf8', (err) => { + if (err) { + console.error('Error writing updated NGINX config:', err); + return; + } + + reloadNginx(); + }); + }); +}; + +// Function to replace upstream server entries in the config +const updateUpstreamServers = (configData, newServers) => { + const lines = configData.split('\n'); + let upstreamSectionStart = -1; + let upstreamSectionEnd = -1; + + // Find the start and end of the upstream section + lines.forEach((line, index) => { + if (line.trim().startsWith(upstreamBlockName)) { + upstreamSectionStart = index; + } + if (upstreamSectionStart !== -1 && upstreamSectionEnd === -1 && line.trim() === '}') { + upstreamSectionEnd = index; + } + }); + + if (upstreamSectionStart === -1 || upstreamSectionEnd === -1) { + console.error('Upstream section not found in NGINX config'); + return configData; + } + + // Replace the server list in the upstream section + const newServerLines = newServers.map(server => ` server ${server.address};`); + const updatedLines = [ + ...lines.slice(0, upstreamSectionStart + 1), + ...newServerLines, + ...lines.slice(upstreamSectionEnd) + ]; + + return updatedLines.join('\n'); +}; + +// Function to reload NGINX +const reloadNginx = () => { + exec('systemctl reload nginx', (err, stdout, stderr) => { + if (err) { + console.error('Error reloading NGINX:', err); + return; + } + console.log('NGINX reloaded successfully'); + }); +}; + +// Example usage +const newServers = [ + { address: '10.0.0.1:80' }, + { address: '10.0.0.2:80' } +]; + +updateNginxConfig(newServers); diff --git a/src/commands/other/nodeCertManager.js b/src/commands/other/nodeCertManager.js index c83cf3f..a6ac034 100644 --- a/src/commands/other/nodeCertManager.js +++ b/src/commands/other/nodeCertManager.js @@ -6,6 +6,10 @@ const spawn = child_process.spawn; const localip = '3.231.17.247' const certificates = new Map() +const certbotPath = `/etc/letsencrypt/live/`; +const fullchainPath = `${certbotPath}/fullchain.pem`; +const privkeyPath = `${certbotPath}/privkey.pem`; +const combinedPath = `${certbotPath}/haproxy.pem`; async function checkDns(host) { @@ -96,6 +100,36 @@ async function checkCert(host) { } } +const combineCertificate = (host) => { + const certbotPath = `/etc/letsencrypt/live/${host}`; + const fullchainPath = `${certbotPath}/fullchain.pem`; + const privkeyPath = `${certbotPath}/privkey.pem`; + const combinedPath = `${certbotPath}/haproxy.pem`; + + fs.readFile(fullchainPath, (err, fullchainData) => { + if (err) { + console.error('Error reading fullchain.pem:', err); + return; + } + + fs.readFile(privkeyPath, (err, privkeyData) => { + if (err) { + console.error('Error reading privkey.pem:', err); + return; + } + + const combinedData = `${fullchainData}\n${privkeyData}`; + fs.writeFile(combinedPath, combinedData, (err) => { + if (err) { + console.error('Error writing combined haproxy.pem:', err); + } else { + console.log('Successfully combined certificates for HAProxy.'); + } + }); + }); + }); +}; + async function test(host) { try {