Skip to Content

Examples

TL;DR

Common SDK examples including multi-server deployment scripts, health check monitors, log aggregators, file sync utilities, React dashboards with real-time metrics, CLI tools with commander, and webhook handlers for machine events. Each example demonstrates a complete, production-ready pattern using the Cmdop SDK.

Common patterns and use cases for the Cmdop SDK.

How do I write a deployment script?

Deploy to multiple servers:

import { Cmdop } from '@cmdop/sdk'; // Initialize the SDK client with your API key const client = new Cmdop({ apiKey: process.env.CMDOP_API_KEY }); async function deploy(machines: string[], branch: string) { // Define the shell script to run on each machine const script = ` cd /app git fetch origin git checkout ${branch} git pull npm install npm run build pm2 restart all `; // Execute the deployment script on all machines in parallel const results = await client.commands.execBatch(machines, script); // Check results for each machine and report success or failure for (const [machineId, result] of Object.entries(results)) { if (result.exitCode !== 0) { console.error(`Deploy failed on ${machineId}`); console.error(result.stderr); } else { console.log(`Deployed to ${machineId}`); } } } // Deploy the 'main' branch to three web servers deploy(['web-1', 'web-2', 'web-3'], 'main');

How do I build a health check monitor?

import { Cmdop } from '@cmdop/sdk'; const client = new Cmdop({ apiKey: process.env.CMDOP_API_KEY }); async function healthCheck() { // Fetch all machines that are currently online const machines = await client.machines.list({ status: 'online' }); for (const machine of machines) { // Get current resource usage for this machine const status = await client.machines.status(machine.id); // Alert if CPU usage exceeds 90% if (status.cpu.usage > 90) { console.warn(`High CPU on ${machine.name}: ${status.cpu.usage}%`); } // Alert if memory usage exceeds 90% if (status.memory.used / status.memory.total > 0.9) { console.warn(`High memory on ${machine.name}`); } // Alert if disk usage exceeds 85% if (status.disk.used / status.disk.total > 0.85) { console.warn(`Low disk space on ${machine.name}`); } } } // Schedule health checks to run every 5 minutes setInterval(healthCheck, 5 * 60 * 1000);

How do I aggregate logs from multiple machines?

import { Cmdop } from '@cmdop/sdk'; import fs from 'fs'; const client = new Cmdop({ apiKey: process.env.CMDOP_API_KEY }); async function aggregateLogs(machines: string[], logPath: string) { // Create a writable stream for the combined output file const output = fs.createWriteStream('aggregated.log'); for (const machineId of machines) { // Fetch the last 1000 lines of the log from each machine const result = await client.commands.exec( machineId, `cat ${logPath} | tail -1000` ); // Write a separator header and the log contents output.write(`\n=== ${machineId} ===\n`); output.write(result.stdout); } output.end(); }

How do I sync files to remote machines?

import { Cmdop } from '@cmdop/sdk'; import fs from 'fs'; const client = new Cmdop({ apiKey: process.env.CMDOP_API_KEY }); async function syncFile( localPath: string, machineId: string, remotePath: string ) { // Read the local file contents into a buffer const content = fs.readFileSync(localPath); // Upload the file to the remote machine at the specified path await client.files.upload(machineId, remotePath, content); console.log(`Synced ${localPath} to ${machineId}:${remotePath}`); }

How do I build a React dashboard?

import { CmdopProvider, useMachines, useRealtime } from '@cmdop/react'; // Main dashboard component that lists all machines in a grid function Dashboard() { // Fetch the list of all registered machines const { machines } = useMachines(); return ( <div className="grid grid-cols-3 gap-4"> {machines.map((machine) => ( <MachineCard key={machine.id} machine={machine} /> ))} </div> ); } // Individual machine card with real-time metric updates function MachineCard({ machine }) { // Subscribe to live metrics and status updates for this machine const { metrics, status } = useRealtime(machine.id); return ( <div className="border rounded p-4"> <h3>{machine.name}</h3> <p>Status: {status}</p> <div className="mt-2"> <div>CPU: {metrics?.cpu.usage}%</div> {/* Convert bytes to megabytes for display */} <div>Memory: {Math.round(metrics?.memory.used / 1024 / 1024)}MB</div> </div> </div> ); } // Wrap the app with CmdopProvider to supply SDK context to all children export default function App() { return ( <CmdopProvider apiKey={process.env.NEXT_PUBLIC_CMDOP_API_KEY}> <Dashboard /> </CmdopProvider> ); }

How do I build a CLI tool?

#!/usr/bin/env node import { Cmdop } from '@cmdop/sdk'; import { program } from 'commander'; const client = new Cmdop({ apiKey: process.env.CMDOP_API_KEY }); // Register the "list" command to display all machines with their status program .command('list') .description('List all machines') .action(async () => { const machines = await client.machines.list(); for (const m of machines) { console.log(`${m.name} (${m.status})`); } }); // Register the "exec" command to run a shell command on a specific machine program .command('exec <machine> <command>') .description('Execute command') .action(async (machine, command) => { const result = await client.commands.exec(machine, command); console.log(result.stdout); if (result.stderr) console.error(result.stderr); // Exit with the same code as the remote command process.exit(result.exitCode); }); // Parse CLI arguments and dispatch to the matching command handler program.parse();

How do I handle webhooks?

// Next.js API Route β€” handles incoming webhook events from Cmdop import { Cmdop, WebhookEvent } from '@cmdop/sdk'; const client = new Cmdop({ apiKey: process.env.CMDOP_API_KEY }); export async function POST(req: Request) { // Parse the incoming webhook payload const event: WebhookEvent = await req.json(); // Route the event to the appropriate handler based on type switch (event.type) { case 'machine.offline': // Notify the team via Slack when a machine goes offline await sendSlackAlert(`Machine ${event.machine.name} went offline`); break; case 'command.failed': // Log command failures for debugging console.error(`Command failed: ${event.command}`); break; } // Acknowledge receipt of the webhook return Response.json({ ok: true }); }
Last updated on