### Install mirrord CLI with install script Source: https://github.com/metalbear-co/mirrord/blob/main/README.md Use a curl script to download and install the mirrord CLI tool. ```sh curl -fsSL https://raw.githubusercontent.com/metalbear-co/mirrord/main/scripts/install.sh | bash ``` -------------------------------- ### Install mirrord CLI with Nix (nix-env) Source: https://github.com/metalbear-co/mirrord/blob/main/README.md Install the mirrord CLI using the legacy nix-env command. ```sh nix-env -iA nixpkgs.mirrord ``` -------------------------------- ### Local Development Build Examples Source: https://github.com/metalbear-co/mirrord/blob/main/xtask/README.md Examples for performing quick debug and full release builds of the mirrord CLI on macOS for local testing. ```bash cargo xtask build-cli ``` ```bash cargo xtask build-cli --release ``` -------------------------------- ### Install mirrord CLI with Nix (nix profile) Source: https://github.com/metalbear-co/mirrord/blob/main/README.md Install the mirrord CLI using the recommended nix profile command. ```sh nix profile install nixpkgs#mirrord ``` -------------------------------- ### Building Components Separately Examples Source: https://github.com/metalbear-co/mirrord/blob/main/xtask/README.md Examples demonstrating how to build individual components like the wizard, layer, or the full CLI separately. This is useful for targeted development or understanding the build process. ```bash cargo xtask build-wizard ``` ```bash cargo xtask build-layer --release ``` ```bash cargo xtask build-cli --release ``` -------------------------------- ### Install gon for CI Signing Source: https://github.com/metalbear-co/mirrord/blob/main/xtask/README.md Instructions for installing the 'gon' tool using Homebrew, which is required for code signing and notarization in CI environments. ```bash brew tap mitchellh/gon brew install mitchellh/gon/gon ``` -------------------------------- ### CI Linux Release Build Examples Source: https://github.com/metalbear-co/mirrord/blob/main/xtask/README.md Examples for building mirrord CLI for Linux platforms in release mode on a CI environment. Ensure cross-compilation is configured. ```bash cargo xtask build-cli --release --platform linux-x86_64 ``` ```bash cargo xtask build-cli --release --platform linux-aarch64 ``` -------------------------------- ### Start Minikube Cluster Source: https://github.com/metalbear-co/mirrord/blob/main/CONTRIBUTING.md Starts a Minikube cluster using the Docker driver. This is a prerequisite for running E2E tests and manual testing. ```bash minikube start --driver=docker ``` -------------------------------- ### Comparison: Before (shell scripts) Source: https://github.com/metalbear-co/mirrord/blob/main/xtask/README.md Example of the old shell script command for building a fat macOS binary with release mode and wizard features. ```bash ./scripts/build_fat_mac.sh --release --features wizard ``` -------------------------------- ### Example: Execute Node.js app with mirrord Source: https://github.com/metalbear-co/mirrord/blob/main/README.md An example of using the mirrord CLI to execute a Node.js application, targeting a pod named 'my-pod'. ```sh mirrord exec node app.js --target pod/my-pod ``` -------------------------------- ### Install x86 Linux Target Source: https://github.com/metalbear-co/mirrord/blob/main/CONTRIBUTING.md Installs the necessary target for cross-compiling to x86_64 Linux. ```shell rustup target add x86_64-unknown-linux-gnu ``` -------------------------------- ### Install mirrord CLI with Homebrew Source: https://github.com/metalbear-co/mirrord/blob/main/README.md Use Homebrew to install the mirrord CLI tool on macOS or Linux. ```sh brew install metalbear-co/mirrord/mirrord ``` -------------------------------- ### Changelog Entry Examples Source: https://github.com/metalbear-co/mirrord/blob/main/CONTRIBUTING.md Examples of how to name changelog files in the 'changelog.d/' directory, indicating whether a GitHub issue is included and the category of the change. ```text 1054.changed.md ``` ```text +some-name.added.md ``` -------------------------------- ### Install mirrord CLI on Windows with Chocolatey Source: https://github.com/metalbear-co/mirrord/blob/main/README.md Use Chocolatey to install the mirrord CLI tool on Windows. ```sh choco install --pre mirrord ``` -------------------------------- ### Run Mirrord Console Source: https://github.com/metalbear-co/mirrord/blob/main/CONTRIBUTING.md Start the mirrord console application to receive log information from mirrord instances. This is useful for debugging. ```bash cargo run --bin mirrord-console --features binary ``` -------------------------------- ### Mirrord Flow Diagram Source: https://github.com/metalbear-co/mirrord/blob/main/CONTRIBUTING.md Illustrates the step-by-step flow when a user executes their application with Mirrord, from starting the CLI to the Layer intercepting syscalls. ```mermaid %%{init: {'theme': 'neutral', 'themeVariables': {'lineColor': '#f00'}}}%% flowchart TB Start([User starts mirrord]) --> CLI[CLI parses config & args] CLI --> Deploy[Deploy mirrord Agent] Deploy --> WaitAgent[Wait for Agent to be ready] WaitAgent --> StartProxy[Start Internal Proxy] StartProxy --> InjectLayer[Inject Layer into binary] InjectLayer --> StartBinary[Start user binary] StartBinary --> |"Layer intercepts syscalls"| Layer Layer --> |"Layer forwards intercepted calls"| IntProxy[Internal Proxy] IntProxy --> |"Proxy sends requests to agent"| Agent Agent --> |"Agent executes in pod context"| Pod[Target Pod] Pod --> |"Pod returns execution results"| Agent Agent --> |"Agent sends results back"| IntProxy IntProxy --> |"Proxy forwards results"| Layer Layer --> |"Layer returns to application"| Binary[User Binary] style Start fill:#f9f9f9,stroke:#333,stroke-width:2px style CLI fill:#e6f3ff,stroke:#0066cc,stroke-width:2px style Deploy fill:#e6f3ff,stroke:#0066cc,stroke-width:2px style WaitAgent fill:#e6f3ff,stroke:#0066cc,stroke-width:2px style StartProxy fill:#e6f3ff,stroke:#0066cc,stroke-width:2px style InjectLayer fill:#e6f3ff,stroke:#0066cc,stroke-width:2px style Layer fill:#e6f3ff,stroke:#0066cc,stroke-width:2px style IntProxy fill:#e6f3ff,stroke:#0066cc,stroke-width:2px style Agent fill:#fff2cc,stroke:#d6b656,stroke-width:2px style Pod fill:#e6ffe6,stroke:#006600,stroke-width:2px style Binary fill:#f9f9f9,stroke:#333,stroke-width:2px ``` -------------------------------- ### Mirrord Debugging Output - Socket Operations Source: https://github.com/metalbear-co/mirrord/blob/main/CONTRIBUTING.md Example log output from mirrord during socket operations, showing hooks for getpeername, getsockname, accept, bind, and listen. This helps in understanding mirrord's interaction with the network stack. ```log 2022-06-30T05:14:01.592418Z DEBUG hyper::proto::h1::io: flushed 299 bytes 2022-06-30T05:14:01.657977Z DEBUG hyper::proto::h1::io: parsed 4 headers 2022-06-30T05:14:01.658075Z DEBUG hyper::proto::h1::conn: incoming body is empty 2022-06-30T05:14:01.661729Z DEBUG rustls::conn: Sending warning alert CloseNotify 2022-06-30T05:14:01.678534Z DEBUG mirrord_layer::sockets: getpeername hooked 2022-06-30T05:14:01.678638Z DEBUG mirrord_layer::sockets: getsockname hooked 2022-06-30T05:14:01.678713Z DEBUG mirrord_layer::sockets: accept hooked 2022-06-30T05:14:01.905378Z DEBUG mirrord_layer::sockets: socket called domain:30, type:1 2022-06-30T05:14:01.905639Z DEBUG mirrord_layer::sockets: bind called sockfd: 32 2022-06-30T05:14:01.905821Z DEBUG mirrord_layer::sockets: bind:port: 80 2022-06-30T05:14:01.906029Z DEBUG mirrord_layer::sockets: listen called 2022-06-30T05:14:01.906182Z DEBUG mirrord_layer::sockets: bind called sockfd: 32 2022-06-30T05:14:01.906319Z DEBUG mirrord_layer::sockets: bind: no socket found for fd: 32 2022-06-30T05:14:01.906467Z DEBUG mirrord_layer::sockets: getsockname called 2022-06-30T05:14:01.906533Z DEBUG mirrord_layer::sockets: getsockname: no socket found for fd: 32 2022-06-30T05:14:01.906852Z DEBUG mirrord_layer::sockets: listen: success 2022-06-30T05:14:01.907034Z DEBUG mirrord_layer::tcp: handle_listen -> listen Listen { fake_port: 51318, real_port: 80, ipv6: true, fd: 32, } Server listening on port 80 ``` -------------------------------- ### Get Kubernetes Service URL (macOS) Source: https://github.com/metalbear-co/mirrord/blob/main/CONTRIBUTING.md Command to retrieve the URL of a Kubernetes service using `minikube`. This command should be kept running on macOS to maintain the service URL. ```bash minikube service py-serv --url ``` -------------------------------- ### Build CLI Source: https://github.com/metalbear-co/mirrord/blob/main/CLAUDE.md Builds the mirrord command-line interface. ```bash # CLI cargo xtask build-cli ``` -------------------------------- ### Build Monitor Frontend Assets Source: https://github.com/metalbear-co/mirrord/blob/main/xtask/README.md Prepares the monitor frontend assets required for the CLI build. This command is usually handled by `build-cli`. ```bash cargo xtask build-monitor ``` -------------------------------- ### Run Integration Tests with Pre-built Artifacts Source: https://github.com/metalbear-co/mirrord/blob/main/CONTRIBUTING.md Run integration tests using pre-built binary and layer artifacts. Specify the paths to your artifacts using MIRRORD_TESTS_USE_BINARY and MIRRORD_LAYER_FILE environment variables. ```bash MIRRORD_TESTS_USE_BINARY=target/x86_64-unknown-linux-gnu/debug/mirrord \ MIRRORD_LAYER_FILE=target/x86_64-unknown-linux-gnu/debug/libmirrord_layer.so \ cargo xtask test-integration ``` -------------------------------- ### Sample Node.js Web Server (app.mjs) Source: https://github.com/metalbear-co/mirrord/blob/main/CONTRIBUTING.md This Node.js script creates a simple HTTP server and demonstrates file operations. It's used as a sample application to be run with mirrord. ```javascript import { Buffer } from "node:buffer"; import { createServer } from "net"; import { open, readFile } from "fs/promises"; async function debug_file_ops() { try { const readOnlyFile = await open("/var/log/dpkg.log", "r"); console.log(">>>>> open readOnlyFile ", readOnlyFile); let buffer = Buffer.alloc(128); let bufferResult = await readOnlyFile.read(buffer); console.log(">>>>> read readOnlyFile returned with ", bufferResult); const sampleFile = await open("/tmp/node_sample.txt", "w+"); console.log(">>>>> open file ", sampleFile); const written = await sampleFile.write("mirrord sample node"); console.log(">>>>> written ", written, " bytes to file ", sampleFile); let sampleBuffer = Buffer.alloc(32); let sampleBufferResult = await sampleFile.read(buffer); console.log(">>>>> read ", sampleBufferResult, " bytes from ", sampleFile); readOnlyFile.close(); sampleFile.close(); } catch (fail) { console.error("!!! Failed file operation with ", fail); } } // debug_file_ops(); const server = createServer(); server.on("connection", handleConnection); server.listen( { host: "localhost", port: 80, }, function () { console.log("server listening to %j", server.address()); } ); function handleConnection(conn) { var remoteAddress = conn.remoteAddress + ":" + conn.remotePort; console.log("new client connection from %s", remoteAddress); conn.on("data", onConnData); conn.once("close", onConnClose); conn.on("error", onConnError); function onConnData(d) { console.log("connection data from %s: %j", remoteAddress, d.toString()); conn.write(d); } function onConnClose() { console.log("connection from %s closed", remoteAddress); } function onConnError(err) { console.log("Connection %s error: %s", remoteAddress, err.message); } } ``` -------------------------------- ### Disable Telemetry via Command-Line Flag Source: https://github.com/metalbear-co/mirrord/blob/main/TELEMETRY.md Telemetry can be disabled during the wizard setup using the --telemetry=false command-line flag. ```bash mirrord wizard --telemetry=false ``` -------------------------------- ### List Kubernetes Contexts Source: https://github.com/metalbear-co/mirrord/blob/main/CONTRIBUTING.md Retrieves and displays all available Kubernetes contexts configured on the system. ```bash kubectl config get-contexts ``` -------------------------------- ### Build CLI with Existing Dist Directory Source: https://github.com/metalbear-co/mirrord/blob/main/xtask/README.md Builds the mirrord CLI, including the wizard feature, while reusing an existing distribution directory. This can save time by skipping redundant builds. ```bash cargo xtask build-cli --release --skip-build-wizard ``` -------------------------------- ### List Docker Images Source: https://github.com/metalbear-co/mirrord/blob/main/CONTRIBUTING.md Displays a list of Docker images available locally, including the recently built 'test' image for mirrord-agent. ```bash docker images ``` -------------------------------- ### Retrieve Specific Agent Log Source: https://github.com/metalbear-co/mirrord/blob/main/CONTRIBUTING.md Get logs from a specific mirrord agent pod by its name. First, list all pods to find the correct name. ```bash kubectl get pods ``` ```bash kubectl logs | less -R ``` -------------------------------- ### Disable Mirrord Agent Capabilities Source: https://github.com/metalbear-co/mirrord/blob/main/README.md Use this environment variable to disable specific Linux capabilities for the mirrord agent. This can limit mirrord's functionality or make it unusable in certain setups. ```bash MIRRORD_AGENT_DISABLED_CAPABILITIES=CAP_NET_RAW,CAP_SYS_PTRACE mirrord exec node app.js --target pod/my-pod ``` -------------------------------- ### Run E2E Tests with Pre-built Artifacts Source: https://github.com/metalbear-co/mirrord/blob/main/CONTRIBUTING.md Run E2E tests using pre-built binary and layer artifacts. Set the MIRRORD_TESTS_USE_BINARY and MIRRORD_LAYER_FILE environment variables to point to your artifacts. ```bash MIRRORD_TESTS_USE_BINARY=target/universal-apple-darwin/debug/mirrord \ MIRRORD_LAYER_FILE=target/universal-apple-darwin/debug/libmirrord_layer.dylib \ cargo xtask test-e2e ``` -------------------------------- ### Build Go Test App on Linux Source: https://github.com/metalbear-co/mirrord/blob/main/CONTRIBUTING.md Use this command to build Go test applications on Linux, especially when specific Go test apps are excluded on macOS. It ensures the script continues building other applications. ```bash go build -o "$1.go_test_app" || echo "Failed to build $directory/$1.go_test_app" ``` -------------------------------- ### Mirrord Debugging Output - Traffic Verification Source: https://github.com/metalbear-co/mirrord/blob/main/CONTRIBUTING.md Example log output from mirrord indicating successful receipt and processing of traffic, including connection closing and request completion messages. This confirms that traffic sent to the service was received by the local process. ```log 2022-06-30T05:17:31.877560Z DEBUG mirrord_layer::tcp: handle_incoming_message -> message Close( TcpClose { connection_id: 0, }, ) 2022-06-30T05:17:31.877608Z DEBUG mirrord_layer::tcp_mirror: handle_close -> close TcpClose { connection_id: 0, } 2022-06-30T05:17:31.877655Z DEBUG mirrord_layer::tcp: handle_incoming_message -> handled Ok( (), ) 2022-06-30T05:17:31.878193Z WARN mirrord_layer::tcp_mirror: tcp_tunnel -> exiting due to remote stream closed! 2022-06-30T05:17:31.878255Z DEBUG mirrord_layer::tcp_mirror: tcp_tunnel -> exiting OK - GET: Request completed ``` -------------------------------- ### Incorrect Busy Loop in Async Rust Source: https://github.com/metalbear-co/mirrord/blob/main/mirrord/agent/CONTRIBUTING.md This example demonstrates a common mistake in asynchronous Rust where a `tokio::select!` macro can lead to a busy loop if a future is always ready and lacks an `.await` point. This prevents other futures from being processed, potentially freezing the agent. ```rust struct HttpConnection { // ... } impl HttpConnection { /// Starts a graceful shutdown of this HTTP connection, allowing started requests to finish. /// After calling this, the connection should eventually stop yielding new requests. fn start_graceful_shutdown(&mut self) { // ... } async fn next_request(&mut self) -> Option { // ... } } async fn handle_single_request(request: HttpRequest) { // ... } async fn handle_requests( mut connection: HttpConnection, token: CancellationToken, ) { let mut requests = FuturesUnordered::new(); loop { tokio::select! { biased; // Wrapping up, start graceful shutdown on the connection. // We don't want to receive any more requests. _ = token.cancelled() => { connection.start_graceful_shutdown(); }, // Progress previously received requests. Some(()) = requests.next() => {}, // Receive the next request. request = connection.next_request() => { let Some(request) = request else { // Connection is finished. // Wait for requests to be processed, and exit. requests.for_each(std::future::ready).await; break; }; requests.push(handle_single_request(request)); }, } } } ``` -------------------------------- ### Apply Kubernetes Deployment and Service Source: https://github.com/metalbear-co/mirrord/blob/main/CONTRIBUTING.md Use kubectl to apply a sample application deployment and service manifest to your Kubernetes cluster. Ensure the manifest file is correctly specified. ```bash kubectl apply -f sample/kubernetes/app.yaml ``` -------------------------------- ### Build Layer Source: https://github.com/metalbear-co/mirrord/blob/main/CLAUDE.md Builds the mirrord layer component. ```bash # layer cargo xtask build-layer ``` -------------------------------- ### Build Release CLI Source: https://github.com/metalbear-co/mirrord/blob/main/xtask/README.md Builds the release version of the mirrord CLI for your current platform. This is the primary command for creating a production-ready CLI. ```bash cargo xtask build-cli --release ``` -------------------------------- ### Verify Kubernetes Resources Source: https://github.com/metalbear-co/mirrord/blob/main/CONTRIBUTING.md Check the status of services, deployments, and pods after applying the Kubernetes manifest. This confirms that the sample application has been successfully deployed. ```bash ❯ kubectl get services NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE kubernetes ClusterIP 10.96.0.1 443/TCP 3h13m py-serv NodePort 10.96.139.36 80:30000/TCP 3h8m ❯ kubectl get deployments NAME READY UP-TO-DATE AVAILABLE AGE py-serv-deployment 1/1 1 1 3h8m ❯ kubectl get pods NAME READY STATUS RESTARTS AGE py-serv-deployment-ff89b5974-x9tjx 1/1 Running 0 3h8m ``` -------------------------------- ### Run E2E Tests with Default Build Source: https://github.com/metalbear-co/mirrord/blob/main/CONTRIBUTING.md Execute the End-to-End tests for Mirrord. This command will automatically build the binary and layer from source if not provided. ```bash cargo xtask test-e2e ``` -------------------------------- ### Run Mirrord with Local Node.js Process Source: https://github.com/metalbear-co/mirrord/blob/main/CONTRIBUTING.md Command to execute the sample Node.js application using mirrord, targeting a specific Kubernetes pod. Ensure the pod name is updated to match your environment. ```bash RUST_LOG=debug target/debug/mirrord exec -i test -l debug -c --target pod/py-serv-deployment-ff89b5974-x9tjx node sample/node/app.mjs ``` -------------------------------- ### Build CLI for Specific Platforms Source: https://github.com/metalbear-co/mirrord/blob/main/xtask/README.md Builds the mirrord CLI for specific target platforms in release mode. Ensure you have the necessary cross-compilation toolchains set up. ```bash cargo xtask build-cli --release --platform macos-universal ``` ```bash cargo xtask build-cli --release --platform linux-x86_64 ``` ```bash cargo xtask build-cli --release --platform linux-aarch64 ``` ```bash cargo xtask build-cli --release --platform windows ``` -------------------------------- ### Build CLI without Frontend Components Source: https://github.com/metalbear-co/mirrord/blob/main/xtask/README.md Builds the mirrord CLI while excluding the wizard or monitor frontend assets. Use these flags to speed up builds or if these components are not needed. ```bash cargo xtask build-cli --release --no-wizard ``` ```bash cargo xtask build-cli --release --no-monitor ``` -------------------------------- ### Run Medschool in a Project Directory Source: https://github.com/metalbear-co/mirrord/blob/main/medschool/readme.md Navigate to your Rust project directory and run `medschool` to generate a `configuration.md` file from the project's documentation. ```sh cd rust-project medschool ``` -------------------------------- ### Build Mirrord CLI on macOS Source: https://github.com/metalbear-co/mirrord/blob/main/CONTRIBUTING.md Execute the build script for macOS to create a fat binary. This script handles platform-specific build requirements for macOS. ```bash scripts/build_fat_mac.sh ``` -------------------------------- ### Run Unit Tests Source: https://github.com/metalbear-co/mirrord/blob/main/CLAUDE.md Executes the unit tests for mirrord. ```bash # Unit tests cargo xtask test-ut ``` -------------------------------- ### Build Wizard Frontend Assets Source: https://github.com/metalbear-co/mirrord/blob/main/xtask/README.md Builds and packages the wizard frontend assets. This command is typically orchestrated by `build-cli` but can be run independently. ```bash cargo xtask build-wizard ``` -------------------------------- ### Execute a process with mirrord Source: https://github.com/metalbear-co/mirrord/blob/main/README.md Use the mirrord CLI to execute a command, targeting a specific pod in Kubernetes. ```sh mirrord exec --target ``` -------------------------------- ### Run Integration Tests Source: https://github.com/metalbear-co/mirrord/blob/main/CLAUDE.md Executes the integration tests for mirrord. ```bash # Integration tests cargo xtask test-integration ``` -------------------------------- ### Execute Manual Release Script Source: https://github.com/metalbear-co/mirrord/blob/main/CONTRIBUTING.md Run this bash script to initiate a manual release. Ensure no uncommitted changes exist before execution. This script handles branch creation, version bumping, changelog generation, and pushing the release branch. ```bash ./scripts/release.sh 3.333.0 ``` -------------------------------- ### Load Mirrord-Agent Image to Minikube Source: https://github.com/metalbear-co/mirrord/blob/main/CONTRIBUTING.md Loads the locally built 'test' image into the Minikube cluster's Docker daemon, making it available for Kubernetes jobs. ```bash minikube image load test ``` -------------------------------- ### Build CLI with Cargo Source: https://github.com/metalbear-co/mirrord/blob/main/AGENTS.md Compiles the mirrord command-line interface using the Cargo build tool. ```bash cargo xtask build-cli ``` -------------------------------- ### mirrord exec Usage Source: https://github.com/metalbear-co/mirrord/blob/main/mirrord/cli/README.md The basic command to execute a binary with mirrord injected. Replace with the target pod name and with the executable. ```bash mirrord exec --pod-name [BINARY_ARGS..] ``` -------------------------------- ### Format Code Source: https://github.com/metalbear-co/mirrord/blob/main/CLAUDE.md Formats the codebase according to the project's style guidelines. ```bash # Formatting cargo fmt ``` -------------------------------- ### Sample Kubernetes Deployment and Service Manifest Source: https://github.com/metalbear-co/mirrord/blob/main/CONTRIBUTING.md This YAML defines a Kubernetes Deployment for a Python service and a corresponding NodePort Service. It includes environment variables for mirrord and specifies container ports and image. ```yaml apiVersion: apps/v1 kind: Deployment metadata: name: py-serv-deployment labels: app: py-serv spec: replicas: 1 selector: matchLabels: app: py-serv template: metadata: labels: app: py-serv spec: containers: - name: py-serv image: ghcr.io/metalbear-co/mirrord-pytest:latest ports: - containerPort: 80 env: - name: MIRRORD_FAKE_VAR_FIRST value: mirrord.is.running - name: MIRRORD_FAKE_VAR_SECOND value: "7777" --- apiVersion: v1 kind: Service metadata: labels: app: py-serv name: py-serv spec: ports: - port: 80 protocol: TCP targetPort: 80 nodePort: 30000 selector: app: py-serv sessionAffinity: None type: NodePort ``` -------------------------------- ### Generate Configuration Markdown with Specific Paths Source: https://github.com/metalbear-co/mirrord/blob/main/medschool/readme.md Use `cargo run` to execute Medschool, specifying the input directory for Rust source documentation and the output file path for the generated markdown. ```sh cargo run -p medschool -- --input ./mirrord/config/src --output ./mirrord/config/configuration.md ``` -------------------------------- ### Load Docker Image to Kind Registry Source: https://github.com/metalbear-co/mirrord/blob/main/CONTRIBUTING.md Load a Docker image into Kind's local registry. This is useful when testing with custom agent images, such as 'test:latest', on a Kind cluster. ```bash kind load docker-image test:latest ``` -------------------------------- ### Run Unit Tests with Cargo Source: https://github.com/metalbear-co/mirrord/blob/main/AGENTS.md Executes the unit tests for the mirrord project using Cargo. ```bash cargo xtask test-ut ``` -------------------------------- ### Build Mirrord-Agent Image Source: https://github.com/metalbear-co/mirrord/blob/main/CONTRIBUTING.md Builds the mirrord-agent container image for local development. It specifies the target platform and tags the image as 'test'. The image is loaded into the local Docker daemon. ```bash PLATFORMS="linux/$(uname -m | sed 's/x86_64/amd64/;s/aarch64/arm64/') ``` ```bash AGENT_TAGS=test docker buildx bake -f ci/docker-bake.hcl agent --load ``` -------------------------------- ### Format Code with Cargo Source: https://github.com/metalbear-co/mirrord/blob/main/AGENTS.md Applies code formatting to the entire project using the `cargo fmt` command. ```bash cargo fmt ``` -------------------------------- ### Build Layer with Cargo Source: https://github.com/metalbear-co/mirrord/blob/main/AGENTS.md Compiles the mirrord-layer component using the Cargo build tool. ```bash cargo xtask build-layer ``` -------------------------------- ### Check mirrord-intproxy Source: https://github.com/metalbear-co/mirrord/blob/main/CLAUDE.md Checks the mirrord-intproxy crate, surfacing all errors at once. ```bash # intproxy cargo check -p mirrord-intproxy --keep-going ``` -------------------------------- ### Run E2E Tests with Resource Preservation Source: https://github.com/metalbear-co/mirrord/blob/main/tests/README.md Execute E2E tests and preserve Kubernetes resources from failed tests for debugging by setting the MIRRORD_E2E_PRESERVE_FAILED environment variable. ```bash MIRRORD_E2E_PRESERVE_FAILED=y cargo xtask test-e2e ``` -------------------------------- ### Configure Kind for IPv6 Cluster Source: https://github.com/metalbear-co/mirrord/blob/main/CONTRIBUTING.md Create a Kind Kubernetes cluster configuration file that enables IPv6 networking. This is necessary for running IPv6-specific E2E tests on a local macOS environment. ```shell cat >kind-config.yaml < CLI CLI --> Config Config --> Target Target --> |If operator enabled| Operator Operator --> |Create agent| Agent Target --> |If no operator| CreateAgent CreateAgent --> |Create via k8s API| Agent Target --> |Extract library| Init Init --> Connect Connect --> ProxyStart ProxyStart --> |macOS only| Patch Patch --> Exec Exec --> |Communicates via| IntProxy IntProxy --> |Forwards messages| Agent %% Note: Create Agent, mirrord Operator, and Initialize steps happen in parallel subgraph Parallel direction LR CreateAgent Operator Init end ``` -------------------------------- ### Configure Agent Pod TTL Source: https://github.com/metalbear-co/mirrord/blob/main/CONTRIBUTING.md Set the time-to-live for the agent's pod after it exits. This allows retrieval of logs even if the agent crashes. Can be set via command line, environment variable, or configuration file. ```toml [agent] ttl = 30 ``` -------------------------------- ### Retrieve All Agent Logs Source: https://github.com/metalbear-co/mirrord/blob/main/CONTRIBUTING.md Fetch logs from all running mirrord agent pods. This command is most useful when only one agent pod is active. ```bash kubectl logs -l app=mirrord --tail=-1 | less -R ``` -------------------------------- ### Configure rust-analyzer for Linux Target Source: https://github.com/metalbear-co/mirrord/blob/main/CONTRIBUTING.md Sets the default target for rust-analyzer to x86_64-unknown-linux-gnu for cross-compilation. ```json "rust-analyzer.cargo.target": "x86_64-unknown-linux-gnu" ``` -------------------------------- ### Enable Prometheus Metrics in mirrord.json Source: https://github.com/metalbear-co/mirrord/blob/main/mirrord/agent/README.md Configure mirrord.json to enable the Prometheus metrics server. Ensure the 'metrics' and 'annotations.prometheus.io/port' values match. ```json { "agent": { "metrics": "0.0.0.0:9000", "annotations": { "prometheus.io/scrape": "true", "prometheus.io/port": "9000" } } } ``` -------------------------------- ### Check mirrord-agent Source: https://github.com/metalbear-co/mirrord/blob/main/CLAUDE.md Checks the mirrord-agent crate for Linux, surfacing all errors at once. ```bash # agent (Linux only) cargo check -p mirrord-agent --target x86_64-unknown-linux-gnu --keep-going ``` -------------------------------- ### Instrumenting Fallible Functions with Tracing Source: https://github.com/metalbear-co/mirrord/blob/main/mirrord/agent/CONTRIBUTING.md Demonstrates how to use `#[tracing::instrument]` to log function return values and errors. By default, errors are logged at `Level::ERROR`, but this can be customized. ```rust #[tracing::instrument( level = Level::TRACE, ret, // <- `tracing` will emit a log on the span level err, // <- without explicit level, `tracing` will emit a log on `Level::ERROR` )] async fn open_file(path: &Path) -> io::Result { unimplemented!() } ``` ```rust #[tracing::instrument( level = Level::TRACE, ret, err(level = Level::TRACE), )] async fn open_file(path: &Path) -> io::Result { unimplemented!() } ``` -------------------------------- ### mirrord exec Sequence Diagram Source: https://github.com/metalbear-co/mirrord/blob/main/mirrord/cli/README.md A Mermaid sequence diagram detailing the 'mirrord exec' interaction between mirrord CLI, agent, and user binary, including operator and initialization steps. ```mermaid %%{init: {'theme': 'neutral', 'themeVariables': {'lineColor': '#f00'}}}%% sequenceDiagram participant CLI as mirrord CLI participant Config as Config Parser participant Target as Target Resolution participant Operator as mirrord Operator participant Agent as mirrord Agent participant Init as Initializer participant Proxy as Internal Proxy participant Binary as User Binary CLI->>Config: Parse & Verify Config Config->>Target: Resolve Target alt Operator Enabled Target->>Operator: Request Agent Operator->>Agent: Create Agent else No Operator Target->>Agent: Create via k8s API end Target->>Init: Extract Library Init->>Proxy: Initialize & Connect Proxy->>Agent: Establish Connection Note over Binary: On macOS Only Init->>Binary: Patch Binary Binary->>Proxy: Execute & Communicate Proxy->>Agent: Forward Messages Agent->>Operator: Report Status (if enabled) ``` -------------------------------- ### Configure Mirrord Console Address Source: https://github.com/metalbear-co/mirrord/blob/main/CONTRIBUTING.md Set the environment variable to specify the address where mirrord should send its console logs. Ensure the mirrord console is running. ```bash MIRRORD_CONSOLE_ADDR=127.0.0.1:11233 ``` -------------------------------- ### Configure C Compiler for bindgen Source: https://github.com/metalbear-co/mirrord/blob/main/CONTRIBUTING.md Sets the C compiler for bindgen to target the x86_64-unknown-linux-gnu triplet, required for building frida-gum. ```shell export CC_x86_64_unknown_linux_gnu=(C compiler from step 2) ``` -------------------------------- ### Send Traffic to Kubernetes Pod (Linux) Source: https://github.com/metalbear-co/mirrord/blob/main/CONTRIBUTING.md Command to send traffic to a Kubernetes service using `minikube`. This command is specific to Linux environments. ```bash curl $(minikube service py-serv --url) ``` -------------------------------- ### Run Vale Locally Source: https://github.com/metalbear-co/mirrord/blob/main/CONTRIBUTING.md Execute Vale, the prose checking tool, locally to enforce writing style in Markdown files and Rust doc comments. ```bash vale . ``` -------------------------------- ### Mirrord Architecture Diagram Source: https://github.com/metalbear-co/mirrord/blob/main/CONTRIBUTING.md Visual representation of the Mirrord architecture, showing the interaction between the CLI, Layer, Internal Proxy, Agent, Kubernetes, and Operator. ```mermaid %%{init: {'theme': 'neutral', 'themeVariables': {'lineColor': '#f00'}}}%% graph TB ExternalTraffic["External Traffic"] subgraph mirrord["mirrord"] direction TB CLI["CLI"] Layer["Layer"] Process["User Process"] IntProxy["Internal Proxy"] CLI --> Layer Layer --> Process CLI --> IntProxy IntProxy <--> Layer end subgraph K8s["Kubernetes"] Agent["mirrord Agent"] Pod[Target Pod] CRDs[Custom Resources] end subgraph Operator["Operator (Optional)"] direction TB Manager["Resource Manager"] end IntProxy <--> |"Traffic"| Agent IntProxy <--> |"File Operations"| Agent CLI -- "Creates/Deploys" --> Agent CLI -- "Uses" --> Operator Agent <--> |"Traffic"| Pod Agent <--> |"File Operations"| Pod ExternalTraffic <--> Pod Operator -- "Manages" --> Agent Operator -- "Manages" --> CRDs classDef default fill:#f9f9f9,stroke:#333,stroke-width:2px classDef mirrord fill:#e6f3ff,stroke:#0066cc,stroke-width:2px classDef operator fill:#ffe6e6,stroke:#cc0000,stroke-width:2px classDef k8s fill:#e6ffe6,stroke:#006600,stroke-width:2px classDef agent fill:#fff2cc,stroke:#d6b656,stroke-width:2px class mirrord mirrord class Operator operator class K8s k8s class Agent agent ``` -------------------------------- ### Build Mirrord CLI for Specific Platform with xtask Source: https://github.com/metalbear-co/mirrord/blob/main/CONTRIBUTING.md Build the mirrord CLI for a specific target platform using xtask. This is useful for cross-compilation or targeting different environments. ```bash cargo xtask build-cli --release --platform macos-universal ``` ```bash cargo xtask build-cli --release --platform linux-x86_64 ``` -------------------------------- ### Switch Kubernetes Context Source: https://github.com/metalbear-co/mirrord/blob/main/CONTRIBUTING.md Sets the active Kubernetes context to 'minikube', ensuring subsequent kubectl commands target the Minikube cluster. ```bash kubectl config use-context minikube ``` -------------------------------- ### Struct with MirrordConfig Derive Source: https://github.com/metalbear-co/mirrord/blob/main/mirrord/config/derive/README.md Demonstrates how to use the `#[derive(MirrordConfig)]` attribute on a struct with various field configurations like environment variables, defaults, renaming, and nested structs. ```rust /// MyConfig Comments #[derive(MirrordConfig, Default)] #[config(map_to = "MyFileConfig", derive = "Eq,PartialEq")] // If map_to isn't given, it will default to FileMyConfig pub struct MyConfig { /// Value 1 Comment #[config(env = "VALUE_1")] pub value_1: Option, /// Value 2 Comment #[config(env = "VALUE_2", default = "2")] pub value_2: i32, /// Value 3 Comment #[config(env = "VALUE_3", rename = "foobar")] pub value_3: String, /// Value 4 Comment #[config(nested)] pub value_4: OtherConfig, } ``` -------------------------------- ### Build Layer Component Source: https://github.com/metalbear-co/mirrord/blob/main/xtask/README.md Builds only the mirrord layer component. Useful for focusing on layer-specific development or debugging. ```bash cargo xtask build-layer ``` ```bash cargo xtask build-layer --platform macos-universal --release ``` ```bash cargo xtask build-layer --platform linux-x86_64 --release ``` -------------------------------- ### Lint Code with Cargo Clippy Source: https://github.com/metalbear-co/mirrord/blob/main/AGENTS.md Runs the Clippy linter on the project, denying all warnings. ```bash cargo clippy -- --deny warnings ```