This is an automated email from the ASF dual-hosted git repository. DaanHoogland pushed a commit to branch lxc-hypervisor-extension in repository https://gitbox.apache.org/repos/asf/cloudstack-extensions.git
commit a729fcd0d0c16f5969b004d5dedb077d39d9b7e4 Author: Daan Hoogland <[email protected]> AuthorDate: Wed Dec 2 14:22:00 2026 +0100 LXC Orchestrator (hypervisor) extension in Rust --- lxc/.gitignore | 18 + lxc/Cargo.lock | 107 ++++++ lxc/Cargo.toml | 37 +++ lxc/README.md | 341 +++++++++++++++++++ lxc/src/config.rs | 355 ++++++++++++++++++++ lxc/src/error.rs | 51 +++ lxc/src/exec.rs | 225 +++++++++++++ lxc/src/log.rs | 59 ++++ lxc/src/lxc.rs | 952 +++++++++++++++++++++++++++++++++++++++++++++++++++++ lxc/src/main.rs | 93 ++++++ lxc/src/payload.rs | 228 +++++++++++++ lxc/src/shell.rs | 96 ++++++ 12 files changed, 2562 insertions(+) diff --git a/lxc/.gitignore b/lxc/.gitignore new file mode 100644 index 0000000..cc00709 --- /dev/null +++ b/lxc/.gitignore @@ -0,0 +1,18 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +/target/ diff --git a/lxc/Cargo.lock b/lxc/Cargo.lock new file mode 100644 index 0000000..a4d9bc3 --- /dev/null +++ b/lxc/Cargo.lock @@ -0,0 +1,107 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "cloudstack-lxc" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/lxc/Cargo.toml b/lxc/Cargo.toml new file mode 100644 index 0000000..759f37d --- /dev/null +++ b/lxc/Cargo.toml @@ -0,0 +1,37 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +[package] +name = "cloudstack-lxc" +version = "0.1.0" +edition = "2021" +license = "Apache-2.0" +description = "Apache CloudStack Orchestrator (hypervisor) extension for LXC containers" +publish = false + +[[bin]] +name = "lxc-extension" +path = "src/main.rs" + +[dependencies] +serde = { version = "1", features = ["derive"] } +serde_json = "1" + +[profile.release] +lto = true +strip = true +codegen-units = 1 diff --git a/lxc/README.md b/lxc/README.md new file mode 100644 index 0000000..247b545 --- /dev/null +++ b/lxc/README.md @@ -0,0 +1,341 @@ +<!-- + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. + --> +# LXC Orchestrator extension for Apache CloudStack + +An **Orchestrator** (hypervisor) extension that lets CloudStack deploy and +manage system containers with [LXC](https://linuxcontainers.org/lxc/) — the +classic `lxc-*` tools, not LXD/Incus. It is written in Rust and ships as a +single, dependency-free binary. + +## Contents + +1. [Architecture](#architecture) +2. [Requirements](#requirements) +3. [Building](#building) +4. [Installation and setup](#installation-and-setup) +5. [Configuration reference](#configuration-reference) +6. [Networking](#networking) +7. [Actions](#actions) +8. [Custom actions](#custom-actions) +9. [Security notes](#security-notes) +10. [Limitations](#limitations) +11. [Development](#development) + +## Architecture + +``` +┌──────────────────────────────────────────────────────────────┐ +│ CloudStack Management Server │ +│ │ +│ ExternalPathPayloadProvisioner │ +│ │ lxc-extension <action> <payload.json> <timeout> │ +│ ▼ │ +│ /usr/share/cloudstack-management/extensions/<ext>/ │ +│ lxc-extension (this binary) │ +└──────────────┬───────────────────────────────────────────────┘ + │ ssh (system OpenSSH client) or transport=local + ▼ +┌──────────────────────────────────────────────────────────────┐ +│ LXC host (one CloudStack "host" per machine) │ +│ │ +│ lxc-create / lxc-copy / lxc-start / lxc-stop / lxc-destroy │ +│ lxc-info / lxc-ls / lxc-snapshot / lxc-freeze │ +│ │ +│ container i-2-10-VM ── veth ──► cloudbr0 (VLAN filtering) │ +│ or ──► breth1-<vlan> (per VLAN) │ +└──────────────────────────────────────────────────────────────┘ +``` + +* The binary runs on the **management server**. Each call reads the payload + that CloudStack writes, runs one or more shell scripts on the LXC host over + SSH, and prints one JSON object on stdout. +* The container name is the CloudStack internal instance name + (`i-<account>-<id>-VM`). +* CPU, memory and NIC settings are written to a marked block in the + container config (`# BEGIN cloudstack-lxc` … `# END cloudstack-lxc`). The + block is rewritten on every start, so offering changes and host reboots + are picked up. +* Nothing is kept on the management server. Every call is idempotent where + CloudStack expects it to be (`stop`/`delete` of a missing container + succeeds, `start` of a running one succeeds). + +## Requirements + +**LXC host** + +* LXC 4.0 or later (`lxc-utils`), cgroup v2 by default (`cgroup_version=1` + for legacy hosts). +* `iproute2` (`ip`), POSIX `sh`, `sed`, `mktemp`. +* For the `download` template: outbound HTTPS to the image server. +* SSH access for the configured user. A non-root user needs passwordless + `sudo` for the `lxc-*` tools, `ip` and `sh`. + +**Management server** + +* OpenSSH client (`ssh`). `sshpass` only if you use password authentication. + +## Building + +```bash +cd lxc +cargo test +cargo build --release +# Fully static binary that runs on any x86_64 Linux management server: +rustup target add x86_64-unknown-linux-musl +cargo build --release --target x86_64-unknown-linux-musl +``` + +The binary is at `target/<target>/release/lxc-extension`. + +## Installation and setup + +The examples use CloudMonkey (`cmk`). The same steps work in the UI. + +### 1. Create the extension + +```bash +cmk create extension name=lxc type=Orchestrator path=lxc-extension \ + details[0].key=bridge details[0].value=cloudbr0 +``` + +CloudStack resolves the entry point to +`/usr/share/cloudstack-management/extensions/lxc/lxc-extension`. Copy the +binary there on **every** management server: + +```bash +install -o cloud -g cloud -m 0755 lxc-extension \ + /usr/share/cloudstack-management/extensions/lxc/lxc-extension +``` + +### 2. Create a cluster and register the extension + +Create a cluster with hypervisor `External` and extension `lxc`, or +register the extension on an existing External cluster: + +```bash +cmk add cluster zoneid=<zone> podid=<pod> clustername=lxc-cluster \ + clustertype=CloudManaged hypervisor=External extensionid=<extension-id> +``` + +### 3. Add LXC hosts + +Each LXC machine is one CloudStack host. Put the connection details on the +host: + +```bash +cmk add host zoneid=<zone> podid=<pod> clusterid=<cluster> hypervisor=External \ + url=http://10.0.0.5 username=root password=unused \ + details[0].key=host details[0].value=10.0.0.5 \ + details[1].key=username details[1].value=cloudstack \ + details[2].key=sshkey details[2].value=/var/lib/cloudstack/management/.ssh/id_lxc +``` + +`sshkey` can be a path on the management server or the PEM key itself. An +inline key is written to a 0600 temporary file for the duration of the call. + +### 4. Create a template + +Register a template with hypervisor `External`, extension `lxc`, a dummy +URL, and these **External Details**: + +| key | example | +|-----------|------------| +| `dist` | `ubuntu` | +| `release` | `noble` | +| `arch` | `amd64` | +| `variant` | `cloud` (optional) | + +Each template maps to one image from the LXC `download` template +(`lxc-create -t download -- --list` lists the available images). +Alternatively, set `clone_from` on the host or extension to clone a golden +container with `lxc-copy`. + +### 5. Deploy + +Deploy an instance from the template. CloudStack picks an LXC host in the +cluster. The container is created, configured, started, and reported as +`Running`. + +## Configuration reference + +Details are looked up in this order: **template/instance** → +**host** → **extension**. Template/instance details can only set the keys +marked "VM" below (see [Security notes](#security-notes)). + +| Key | Scope | Default | Description | +|-----|-------|---------|-------------| +| `transport` | host/ext | `ssh` | `ssh` or `local` (management server is the LXC host). | +| `host` | host/ext | — | Address of the LXC host (`url` is also accepted). Required for `ssh`. | +| `port` | host/ext | `22` | SSH port. | +| `username` | host/ext | `root` | SSH user. | +| `sshkey` | host/ext | — | Private key path or inline PEM. | +| `password` | host/ext | — | SSH password (needs `sshpass`). Used only if no `sshkey` is set. | +| `ssh_strict_host_key_checking` | host/ext | `accept-new` | Passed to `ssh -o StrictHostKeyChecking=`. | +| `sudo` | host/ext | `true` if user ≠ root | Wrap commands in `sudo -n`. | +| `lxc_path` | host/ext | `lxc-config lxc.lxcpath` | Container directory (`-P`). | +| `template` | host/ext | `download` | LXC template for `lxc-create -t`. | +| `dist`, `release` | VM/host/ext | — | Image for the `download` template. Required when `template=download`. | +| `arch` | VM/host/ext | `amd64` | Image architecture. | +| `variant` | VM/host/ext | — | Image variant (e.g. `cloud`). | +| `template_options` | host/ext | — | Extra arguments passed to the template after `--`. | +| `clone_from` | host/ext | — | Clone this container with `lxc-copy` instead of `lxc-create`. | +| `clone_snapshot` | host/ext | `false` | `lxc-copy -s` (overlay/btrfs/zfs/lvm snapshot clone). | +| `backingstore` | host/ext | LXC default | `-B` value: `dir`, `btrfs`, `zfs`, `lvm`, `overlay`, … | +| `fssize` | host/ext | — | `--fssize` for block-based backing stores, e.g. `10G`. | +| `bridge` | host/ext | `cloudbr0` | Bridge for untagged NICs, and for all NICs in `filter` mode. | +| `vlan_mode` | host/ext | `filter` | `filter`, `bridge` or `none`. See [Networking](#networking). | +| `guest_network_device` | host/ext | `eth1` | Parent NIC for VLAN sub-interfaces (`bridge` mode). | +| `bridge_name_template` | host/ext | `br{device}-{vlan}` | Bridge name in `bridge` mode (max 15 chars). | +| `static_ip` | host/ext | `false` | Have LXC set the CloudStack-assigned IPv4/IPv6 and gateway on the NIC. | +| `cgroup_version` | host/ext | `2` | `1` or `2`. | +| `limit_cpu` | host/ext | `true` | Limit CPU time to the offering's vCPU count (`cpu.max`). | +| `stop_timeout` | host/ext | `60` | Seconds `lxc-stop` waits for a clean shutdown before killing. | +| `lxc_config` | host/ext | — | Extra raw LXC config lines, separated by `;` or newlines. | + +Resource mapping: + +| CloudStack | LXC (cgroup v2) | +|------------|-----------------| +| offering memory (`maxRam`) | `lxc.cgroup2.memory.max` | +| guaranteed memory (`minRam`, when overprovisioned) | `lxc.cgroup2.memory.low` | +| vCPUs | `lxc.cgroup2.cpu.max = <n*100000> 100000` | +| NIC MAC / MTU | `lxc.net.N.hwaddr` / `lxc.net.N.mtu` | + +## Networking + +Each CloudStack NIC becomes a `veth` interface (`eth0`, `eth1`, … ordered by +device id) with the MAC address CloudStack assigned. CloudStack (the VR, or +e.g. the Network-Namespace extension) provides DHCP, DNS and routing as +usual. Images whose init brings up `eth0` with DHCP work without changes. + +`vlan_mode` sets how VLAN-isolated networks (`vlan://<id>`) are attached: + +* **`filter`** (default): every NIC goes onto one VLAN-aware bridge + (`bridge`), and LXC tags the host-side veth with `lxc.net.N.veth.vlan.id`. + Enable VLAN filtering on the bridge once: + `ip link set cloudbr0 type bridge vlan_filtering 1` and allow the VLANs + on the uplink port (`bridge vlan add dev eth1 vid 100-4094`). +* **`bridge`**: one Linux bridge per VLAN, created on demand on top of a + VLAN sub-interface. This is the layout the + [Network-Namespace](../Network-Namespace/README.md) extension uses + (`eth1.<vlan>` → `breth1-<vlan>`), so the two extensions can share a host + or a fabric. +* **`none`**: ignore VLAN tags and put everything on `bridge` (flat lab + setups). + +Untagged networks (`vlan://untagged` or no broadcast URI) always use +`bridge`. VXLAN and other broadcast domain types are rejected with a clear +error. + +## Actions + +| CloudStack action | LXC operation | +|-------------------|---------------| +| `prepare` | Validates that an image source is configured. Prints nothing. | +| `create` | `lxc-create` (or `lxc-copy`) → write config → `lxc-start -d` → `lxc-wait RUNNING`. Destroys the container on any failure. | +| `start` | Recreate VLAN bridges if needed, rewrite config, `lxc-start`. Unfreezes a frozen container. | +| `stop` | `lxc-stop -t <stop_timeout>` (clean shutdown, then kill). Succeeds if already stopped or missing. | +| `reboot` | `lxc-stop -r`. Starts the container if it was stopped. | +| `delete` | `lxc-destroy -f -s` (including snapshots). Succeeds if missing. | +| `status` | `lxc-info -s` → `poweron` / `poweroff` / `unknown`. A missing container reports `poweroff`. | +| `statuses` | `lxc-ls -f -F NAME,STATE` for the whole host (used by the power-state sync). | +| `getconsole` | Not supported. LXC has no VNC console. Returns an error. | + +Responses follow the same format as the in-tree extensions: +`{"status":"success","message":"…"}`, or `{"status":"error","error":"…"}` +with exit code 1. + +## Custom actions + +The binary implements the actions below. Register the ones you want with +`addCustomAction` (names are case-insensitive): + +| Name | Parameters | Operation | +|------|------------|-----------| +| `ListSnapshots` | — | `lxc-snapshot -L -C` | +| `CreateSnapshot` | `snap_comment` (optional) | `lxc-snapshot` (LXC names it `snapN`) | +| `RestoreSnapshot` | `snap_name` | Stop if running, `lxc-snapshot -r`, start again | +| `DeleteSnapshot` | `snap_name` | `lxc-snapshot -d` | +| `Freeze` | — | `lxc-freeze` | +| `Unfreeze` | — | `lxc-unfreeze` | + +Example: + +```bash +cmk add customaction extensionid=<id> name=RestoreSnapshot resourcetype=VirtualMachine \ + enabled=true timeout=300 \ + parameters[0].name=snap_name parameters[0].type=STRING parameters[0].required=true +``` + +Custom actions are disabled by default, and their default timeout is 5 +seconds. Snapshot operations on `dir` backed containers copy the whole +rootfs, so set `timeout` to a realistic value. + +## Security notes + +* **Template and instance details are untrusted.** Anyone who can register + a template can set its External Details. Only `dist`, `release`, `arch` + and `variant` are read from that scope, and they must match + `[A-Za-z0-9_.-]`. Connection settings, `clone_from`, `lxc_config` and so + on are read only from host and extension details, which only admins set. +* Every value passed to the LXC host is shell-quoted. Values written into + the container config are validated (MACs, IPs and netmasks are parsed, and + line breaks are rejected). +* The SSH password is passed to `sshpass` through the environment, not on + the command line. Inline keys are written with mode 0600 and removed after + the call. +* `lxc_config` is passed through as-is. It can weaken isolation (for example + privileged containers or bind mounts), so set it with care. +* By default `lxc-create` produces **privileged** containers when run as + root. For untrusted tenants, use unprivileged containers: configure + `lxc.idmap` in the host's `/etc/lxc/default.conf` (or through + `lxc_config`) and make sure subuid/subgid ranges exist. + +## Limitations + +* No console (`getconsole`), no volume or disk management, no live + migration, and no instance scaling while the container is running (new + limits apply on the next start). +* User data / cloud-init is not injected. Use an image `variant=cloud` + together with a config drive or metadata service if needed. +* `static_ip` relies on LXC configuring the interface before the container's + init runs. A network manager inside the container may override it. +* The extension does not remove per-VLAN bridges when the last container + using them is deleted (they may be shared with other workloads). + +## Development + +```bash +cargo test # unit tests, including a mock executor for the action flows +cargo clippy --all-targets +``` + +Debug logs are written to `/var/log/cloudstack/extensions/lxc-extension.log`. +Override the path with `CLOUDSTACK_LXC_LOG=/path`, or disable logging with +`CLOUDSTACK_LXC_LOG=none`. Nothing is written to stderr, because CloudStack +merges it into the JSON response. + +You can run the binary by hand against a payload file: + +```bash +lxc-extension status payload.json 60 +``` + +To try it without a remote host, put `{"externaldetails": {"extension": +{"transport": "local"}}}` in the payload and run it on an LXC machine. diff --git a/lxc/src/config.rs b/lxc/src/config.rs new file mode 100644 index 0000000..8dacf19 --- /dev/null +++ b/lxc/src/config.rs @@ -0,0 +1,355 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Resolution of extension settings from the three `externaldetails` +//! sections. +//! +//! Lookup order is most specific first: `virtualmachine` → `host` → +//! `extension`. The `virtualmachine` section is populated from template and +//! instance details, which may be under the control of end users, so only +//! the keys in [`VM_OVERRIDABLE`] are honoured there. Everything that +//! affects where commands run or what ends up in the container config +//! verbatim must come from the host or extension. + +use std::collections::HashMap; + +use crate::bail; +use crate::error::Result; +use crate::payload::Payload; +use crate::shell::{validate_config_value, validate_ident}; + +/// Keys that may be set per instance/template. +pub const VM_OVERRIDABLE: &[&str] = &["dist", "release", "arch", "variant"]; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Transport { + /// Run commands on the management server itself. + Local, + Ssh(SshTarget), +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SshTarget { + pub host: String, + pub port: u16, + pub username: String, + /// Inline PEM key, or a path to a key file on the management server. + pub sshkey: Option<String>, + pub password: Option<String>, + pub strict_host_key_checking: String, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum VlanMode { + /// One VLAN-aware bridge; LXC tags the host-side veth + /// (`lxc.net.N.veth.vlan.id`, LXC >= 4.0, bridge needs `vlan_filtering=1`). + Filter, + /// One bridge per VLAN on top of a VLAN sub-interface, created on demand + /// (same layout as the Network-Namespace extension: `br<dev>-<vlan>`). + Bridge, + /// Ignore VLANs; everything goes onto `bridge`. + None, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CgroupVersion { + V1, + V2, +} + +#[derive(Debug, Clone)] +pub struct Settings { + pub transport: Transport, + pub sudo: bool, + pub lxc_path: Option<String>, + + // image / creation + pub template: String, + pub dist: Option<String>, + pub release: Option<String>, + pub arch: String, + pub variant: Option<String>, + pub template_options: Vec<String>, + pub clone_from: Option<String>, + pub clone_snapshot: bool, + pub backingstore: Option<String>, + pub fssize: Option<String>, + + // networking + pub bridge: String, + pub vlan_mode: VlanMode, + pub guest_device: String, + pub bridge_name_template: String, + pub static_ip: bool, + + // resources / lifecycle + pub cgroup: CgroupVersion, + pub limit_cpu: bool, + pub stop_timeout: u64, + pub extra_config: Vec<String>, +} + +struct Lookup { + vm: HashMap<String, String>, + host: HashMap<String, String>, + extension: HashMap<String, String>, +} + +impl Lookup { + fn get(&self, key: &str) -> Option<String> { + let pick = |m: &HashMap<String, String>| { + m.get(key) + .map(|v| v.trim().to_string()) + .filter(|v| !v.is_empty()) + }; + let vm = if VM_OVERRIDABLE.contains(&key) { + pick(&self.vm) + } else { + None + }; + vm.or_else(|| pick(&self.host)) + .or_else(|| pick(&self.extension)) + } + + fn first(&self, keys: &[&str]) -> Option<String> { + keys.iter().find_map(|k| self.get(k)) + } + + fn bool(&self, key: &str, default: bool) -> Result<bool> { + match self.get(key).map(|v| v.to_ascii_lowercase()) { + None => Ok(default), + Some(v) if ["true", "yes", "1", "on"].contains(&v.as_str()) => Ok(true), + Some(v) if ["false", "no", "0", "off"].contains(&v.as_str()) => Ok(false), + Some(v) => bail!("invalid boolean for '{key}': '{v}'"), + } + } + + fn ident(&self, key: &str) -> Result<Option<String>> { + let v = self.get(key); + if let Some(v) = &v { + validate_ident(key, v)?; + } + Ok(v) + } +} + +impl Settings { + pub fn from_payload(p: &Payload) -> Result<Self> { + let l = Lookup { + vm: p.details("virtualmachine"), + host: p.details("host"), + extension: p.details("extension"), + }; + + let transport = match l.get("transport").as_deref().unwrap_or("ssh") { + "local" => Transport::Local, + "ssh" => { + let Some(host) = l.first(&["host", "url", "address"]) else { + bail!("missing required detail 'host' (address of the LXC host)"); + }; + if host.starts_with('-') || host.contains(char::is_whitespace) { + bail!("invalid host '{host}'"); + } + let port = match l.get("port") { + None => 22, + Some(p) => p + .parse() + .map_err(|_| crate::error::Error(format!("invalid port '{p}'")))?, + }; + let username = l + .first(&["username", "user"]) + .unwrap_or_else(|| "root".into()); + validate_ident("username", &username)?; + Transport::Ssh(SshTarget { + host, + port, + username, + sshkey: l.first(&["sshkey", "ssh_key"]), + password: l.get("password"), + strict_host_key_checking: l + .get("ssh_strict_host_key_checking") + .unwrap_or_else(|| "accept-new".into()), + }) + } + other => bail!("invalid transport '{other}', expected 'ssh' or 'local'"), + }; + + let sudo_default = match &transport { + Transport::Ssh(t) => t.username != "root", + Transport::Local => false, + }; + + let lxc_path = l.get("lxc_path"); + if let Some(p) = &lxc_path { + if !p.starts_with('/') || p.contains("..") { + bail!("lxc_path must be an absolute path"); + } + validate_config_value("lxc_path", p)?; + } + + let vlan_mode = match l.get("vlan_mode").as_deref().unwrap_or("filter") { + "filter" => VlanMode::Filter, + "bridge" => VlanMode::Bridge, + "none" => VlanMode::None, + other => bail!("invalid vlan_mode '{other}', expected 'filter', 'bridge' or 'none'"), + }; + + let cgroup = match l.get("cgroup_version").as_deref().unwrap_or("2") { + "1" | "v1" => CgroupVersion::V1, + "2" | "v2" => CgroupVersion::V2, + other => bail!("invalid cgroup_version '{other}'"), + }; + + let stop_timeout = match l.get("stop_timeout") { + None => 60, + Some(v) => v + .parse() + .map_err(|_| crate::error::Error(format!("invalid stop_timeout '{v}'")))?, + }; + + let bridge = l.get("bridge").unwrap_or_else(|| "cloudbr0".into()); + validate_ident("bridge", &bridge)?; + let guest_device = l + .get("guest_network_device") + .unwrap_or_else(|| "eth1".into()); + validate_ident("guest_network_device", &guest_device)?; + + let template = l.get("template").unwrap_or_else(|| "download".into()); + validate_ident("template", &template)?; + + let fssize = l.get("fssize"); + if let Some(s) = &fssize { + if !s.chars().all(|c| c.is_ascii_alphanumeric()) { + bail!("invalid fssize '{s}'"); + } + } + + // `lxc_config` holds raw config lines separated by newlines or `;`. + let extra_config = l + .get("lxc_config") + .map(|raw| { + raw.split(['\n', ';']) + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(String::from) + .collect() + }) + .unwrap_or_default(); + + Ok(Settings { + sudo: l.bool("sudo", sudo_default)?, + transport, + lxc_path, + template, + dist: l.ident("dist")?, + release: l.ident("release")?, + arch: l.ident("arch")?.unwrap_or_else(|| "amd64".into()), + variant: l.ident("variant")?, + template_options: l + .get("template_options") + .map(|s| s.split_whitespace().map(String::from).collect()) + .unwrap_or_default(), + clone_from: l.ident("clone_from")?, + clone_snapshot: l.bool("clone_snapshot", false)?, + backingstore: l.ident("backingstore")?, + fssize, + bridge, + vlan_mode, + guest_device, + bridge_name_template: l + .get("bridge_name_template") + .unwrap_or_else(|| "br{device}-{vlan}".into()), + static_ip: l.bool("static_ip", false)?, + cgroup, + limit_cpu: l.bool("limit_cpu", true)?, + stop_timeout, + extra_config, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn payload(json: &str) -> Payload { + serde_json::from_str(json).unwrap() + } + + #[test] + fn defaults_and_precedence() { + let p = payload( + r#"{"externaldetails": { + "extension": {"bridge": "lxcbr0", "release": "bookworm", "dist": "debian"}, + "host": {"host": "10.0.0.5", "bridge": "cloudbr1", "username": "cloud"}, + "virtualmachine": {"release": "trixie"} + }}"#, + ); + let s = Settings::from_payload(&p).unwrap(); + assert_eq!(s.bridge, "cloudbr1"); + assert_eq!(s.release.as_deref(), Some("trixie")); + assert_eq!(s.dist.as_deref(), Some("debian")); + assert_eq!(s.arch, "amd64"); + assert_eq!(s.vlan_mode, VlanMode::Filter); + assert!(s.sudo, "non-root user defaults to sudo"); + match s.transport { + Transport::Ssh(t) => { + assert_eq!(t.host, "10.0.0.5"); + assert_eq!(t.port, 22); + assert_eq!(t.username, "cloud"); + } + _ => panic!("expected ssh"), + } + } + + #[test] + fn vm_details_cannot_override_sensitive_keys() { + let p = payload( + r#"{"externaldetails": { + "host": {"host": "10.0.0.5"}, + "virtualmachine": {"host": "evil", "lxc_config": "lxc.mount.entry = / host none bind", "clone_from": "other-tenant"} + }}"#, + ); + let s = Settings::from_payload(&p).unwrap(); + assert!(matches!(s.transport, Transport::Ssh(ref t) if t.host == "10.0.0.5")); + assert!(s.extra_config.is_empty()); + assert!(s.clone_from.is_none()); + } + + #[test] + fn rejects_bad_values() { + for bad in [ + r#"{"externaldetails": {"host": {}}}"#, + r#"{"externaldetails": {"host": {"host": "-oProxyCommand=x"}}}"#, + r#"{"externaldetails": {"host": {"host": "h", "vlan_mode": "x"}}}"#, + r#"{"externaldetails": {"host": {"host": "h"}, "virtualmachine": {"dist": "a;b"}}}"#, + r#"{"externaldetails": {"host": {"host": "h", "lxc_path": "relative"}}}"#, + ] { + assert!(Settings::from_payload(&payload(bad)).is_err(), "{bad}"); + } + } + + #[test] + fn local_transport() { + let s = Settings::from_payload(&payload( + r#"{"externaldetails": {"extension": {"transport": "local"}}}"#, + )) + .unwrap(); + assert_eq!(s.transport, Transport::Local); + assert!(!s.sudo); + } +} diff --git a/lxc/src/error.rs b/lxc/src/error.rs new file mode 100644 index 0000000..eb0c451 --- /dev/null +++ b/lxc/src/error.rs @@ -0,0 +1,51 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +use std::fmt; + +/// Single error type for the extension; every failure ends up as +/// `{"status":"error","error":"<message>"}` on stdout. +#[derive(Debug)] +pub struct Error(pub String); + +pub type Result<T> = std::result::Result<T, Error>; + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +impl From<std::io::Error> for Error { + fn from(e: std::io::Error) -> Self { + Error(e.to_string()) + } +} + +impl From<serde_json::Error> for Error { + fn from(e: serde_json::Error) -> Self { + Error(format!("invalid JSON: {e}")) + } +} + +/// `bail!("...")` returns early with an [`Error`]. +#[macro_export] +macro_rules! bail { + ($($arg:tt)*) => { + return Err($crate::error::Error(format!($($arg)*))) + }; +} diff --git a/lxc/src/exec.rs b/lxc/src/exec.rs new file mode 100644 index 0000000..9561e73 --- /dev/null +++ b/lxc/src/exec.rs @@ -0,0 +1,225 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Running shell scripts on the LXC host, either locally or over SSH. +//! +//! The system `ssh` client is used rather than an SSH library so the binary +//! has no native dependencies and honours the management server's existing +//! `~/.ssh/config`, known hosts and agent. + +use std::fs::{self, OpenOptions}; +use std::io::{Read, Write}; +use std::os::unix::fs::OpenOptionsExt; +use std::path::PathBuf; +use std::process::{Command, Stdio}; +use std::thread; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +use crate::bail; +use crate::config::{SshTarget, Transport}; +use crate::error::Result; +use crate::log; +use crate::shell::quote; + +#[derive(Debug, Clone, Default)] +pub struct Output { + pub code: Option<i32>, + pub stdout: String, + pub stderr: String, +} + +impl Output { + pub fn success(&self) -> bool { + self.code == Some(0) + } + + /// The most useful text to report on failure. + pub fn message(&self) -> String { + let e = self.stderr.trim(); + if e.is_empty() { + self.stdout.trim().to_string() + } else { + e.to_string() + } + } +} + +/// Runs a `sh` script on the LXC host. +pub trait Executor { + fn run(&self, script: &str) -> Result<Output>; +} + +/// Private key written to a temporary 0600 file, removed on drop. +struct TempKey(PathBuf); + +impl TempKey { + fn create(pem: &str) -> Result<Self> { + let nanos = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0); + let path = std::env::temp_dir().join(format!("cs-lxc-key-{}-{nanos}", std::process::id())); + let mut f = OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(&path)?; + let mut pem = pem.replace("\\n", "\n"); + if !pem.ends_with('\n') { + pem.push('\n'); + } + f.write_all(pem.as_bytes())?; + Ok(TempKey(path)) + } +} + +impl Drop for TempKey { + fn drop(&mut self) { + let _ = fs::remove_file(&self.0); + } +} + +pub struct ProcessExecutor { + transport: Transport, + sudo: bool, + deadline: Instant, + key: Option<TempKey>, +} + +impl ProcessExecutor { + pub fn new(transport: Transport, sudo: bool, deadline: Instant) -> Result<Self> { + let key = match &transport { + Transport::Ssh(SshTarget { + sshkey: Some(k), .. + }) if k.contains("PRIVATE KEY") => Some(TempKey::create(k)?), + _ => None, + }; + Ok(ProcessExecutor { + transport, + sudo, + deadline, + key, + }) + } + + fn command(&self, script: &str) -> Command { + let mut argv: Vec<String> = Vec::new(); + if self.sudo { + argv.extend(["sudo".into(), "-n".into()]); + } + argv.extend(["sh".into(), "-c".into(), script.to_string()]); + + match &self.transport { + Transport::Local => { + let mut c = Command::new(&argv[0]); + c.args(&argv[1..]); + c + } + Transport::Ssh(t) => { + let mut c = match &t.password { + Some(pw) if self.key.is_none() && t.sshkey.is_none() => { + // Password via environment, never on the command line. + let mut c = Command::new("sshpass"); + c.env("SSHPASS", pw).arg("-e").arg("ssh"); + c + } + _ => { + let mut c = Command::new("ssh"); + c.args(["-o", "BatchMode=yes"]); + c + } + }; + c.args([ + "-T", + "-o", + "ConnectTimeout=15", + "-o", + "ServerAliveInterval=15", + ]); + c.arg("-o").arg(format!( + "StrictHostKeyChecking={}", + t.strict_host_key_checking + )); + c.arg("-p").arg(t.port.to_string()); + c.arg("-l").arg(&t.username); + if let Some(k) = &self.key { + c.arg("-i").arg(&k.0).args(["-o", "IdentitiesOnly=yes"]); + } else if let Some(path) = &t.sshkey { + c.arg("-i").arg(path).args(["-o", "IdentitiesOnly=yes"]); + } + c.arg(&t.host); + // ssh hands a single string to the remote login shell. + c.arg(argv.iter().map(|a| quote(a)).collect::<Vec<_>>().join(" ")); + c + } + } + } +} + +impl Executor for ProcessExecutor { + fn run(&self, script: &str) -> Result<Output> { + log::write(&format!("run: {script}")); + let mut child = self + .command(script) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .map_err(|e| crate::error::Error(format!("failed to spawn command: {e}")))?; + + let mut so = child.stdout.take().expect("piped stdout"); + let mut se = child.stderr.take().expect("piped stderr"); + let t_out = thread::spawn(move || { + let mut b = Vec::new(); + let _ = so.read_to_end(&mut b); + b + }); + let t_err = thread::spawn(move || { + let mut b = Vec::new(); + let _ = se.read_to_end(&mut b); + b + }); + + let status = loop { + if let Some(st) = child.try_wait()? { + break st; + } + if Instant::now() >= self.deadline { + let _ = child.kill(); + let _ = child.wait(); + bail!("timed out waiting for command on the LXC host"); + } + thread::sleep(Duration::from_millis(50)); + }; + + let out = Output { + code: status.code(), + stdout: String::from_utf8_lossy(&t_out.join().unwrap_or_default()).into_owned(), + stderr: String::from_utf8_lossy(&t_err.join().unwrap_or_default()).into_owned(), + }; + log::write(&format!( + "exit={:?} stdout={:?} stderr={:?}", + out.code, + out.stdout.trim(), + out.stderr.trim() + )); + if matches!(self.transport, Transport::Ssh(_)) && out.code == Some(255) { + bail!("SSH connection to the LXC host failed: {}", out.message()); + } + Ok(out) + } +} diff --git a/lxc/src/log.rs b/lxc/src/log.rs new file mode 100644 index 0000000..dc08389 --- /dev/null +++ b/lxc/src/log.rs @@ -0,0 +1,59 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Best-effort file logging. +//! +//! CloudStack merges stderr into stdout and parses the result as JSON, so +//! nothing may be written to either stream except the final answer. Debug +//! output goes to `$CLOUDSTACK_LXC_LOG`, or by default to +//! `/var/log/cloudstack/extensions/lxc-extension.log`. Failures to log are +//! ignored. + +use std::fs::OpenOptions; +use std::io::Write; +use std::sync::OnceLock; +use std::time::{SystemTime, UNIX_EPOCH}; + +static PATH: OnceLock<Option<String>> = OnceLock::new(); + +fn path() -> Option<&'static str> { + PATH.get_or_init(|| { + if cfg!(test) { + return None; + } + match std::env::var("CLOUDSTACK_LXC_LOG") { + Ok(p) if p.is_empty() || p == "none" => None, + Ok(p) => Some(p), + Err(_) => Some("/var/log/cloudstack/extensions/lxc-extension.log".into()), + } + }) + .as_deref() +} + +pub fn write(msg: &str) { + let Some(p) = path() else { return }; + if let Some(dir) = std::path::Path::new(p).parent() { + let _ = std::fs::create_dir_all(dir); + } + if let Ok(mut f) = OpenOptions::new().create(true).append(true).open(p) { + let ts = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0); + let _ = writeln!(f, "[{ts}] [{}] {msg}", std::process::id()); + } +} diff --git a/lxc/src/lxc.rs b/lxc/src/lxc.rs new file mode 100644 index 0000000..9cb1649 --- /dev/null +++ b/lxc/src/lxc.rs @@ -0,0 +1,952 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Mapping of CloudStack extension actions onto the classic LXC tools +//! (`lxc-create`, `lxc-start`, `lxc-stop`, `lxc-destroy`, `lxc-info`, +//! `lxc-ls`, `lxc-snapshot`, ...). + +use std::collections::BTreeSet; +use std::net::{Ipv4Addr, Ipv6Addr}; + +use serde_json::{json, Value}; + +use crate::bail; +use crate::config::{CgroupVersion, Settings, VlanMode}; +use crate::error::{Error, Result}; +use crate::exec::Executor; +use crate::payload::{Nic, Payload, Segment, VirtualMachine}; +use crate::shell::{join, quote, validate_config_value, validate_ident}; + +const BEGIN_MARK: &str = "# BEGIN cloudstack-lxc"; +const END_MARK: &str = "# END cloudstack-lxc"; +const IFNAMSIZ: usize = 15; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum State { + Running, + Stopped, + Frozen, + Other(String), +} + +impl State { + fn parse(s: &str) -> State { + let s = s.trim(); + let s = s.strip_prefix("State:").unwrap_or(s).trim(); + match s.to_ascii_uppercase().as_str() { + "RUNNING" => State::Running, + "STOPPED" => State::Stopped, + "FROZEN" => State::Frozen, + other => State::Other(other.to_string()), + } + } + + /// CloudStack power state string (`poweron` / `poweroff` / `unknown`). + pub fn power_state(&self) -> &'static str { + match self { + State::Running | State::Frozen => "poweron", + State::Stopped => "poweroff", + State::Other(_) => "unknown", + } + } +} + +fn success(message: &str) -> Value { + json!({"status": "success", "message": message}) +} + +pub struct Lxc<'a> { + s: &'a Settings, + x: &'a dyn Executor, +} + +impl<'a> Lxc<'a> { + pub fn new(s: &'a Settings, x: &'a dyn Executor) -> Self { + Lxc { s, x } + } + + /// Run an action. `Ok(None)` means: print nothing. + pub fn dispatch(&self, action: &str, p: &Payload) -> Result<Option<Value>> { + match action.to_ascii_lowercase().as_str() { + "prepare" => self.prepare().map(|_| None), + "create" => self.create(p).map(Some), + "start" => self.start(p).map(Some), + "stop" => self.stop(p).map(Some), + "reboot" => self.reboot(p).map(Some), + "delete" => self.delete(p).map(Some), + "status" => self.status(p).map(Some), + "statuses" => self.statuses().map(Some), + "getconsole" => bail!("console access is not supported for LXC containers"), + "listsnapshots" => self.list_snapshots(p).map(Some), + "createsnapshot" => self.create_snapshot(p).map(Some), + "restoresnapshot" => self.restore_snapshot(p).map(Some), + "deletesnapshot" => self.delete_snapshot(p).map(Some), + "freeze" => self.freeze(p, true).map(Some), + "unfreeze" => self.freeze(p, false).map(Some), + _ => bail!("unsupported action '{action}'"), + } + } + + // ------------------------------------------------------------------ + // helpers + // ------------------------------------------------------------------ + + /// `<tool> [-P lxcpath] args...`, shell quoted. + fn tool(&self, tool: &str, args: &[&str]) -> String { + let mut w: Vec<&str> = vec![tool]; + if let Some(p) = &self.s.lxc_path { + w.extend(["-P", p.as_str()]); + } + w.extend_from_slice(args); + join(&w) + } + + fn checked(&self, script: &str, what: &str) -> Result<String> { + let o = self.x.run(script)?; + if !o.success() { + bail!("{what} failed: {}", o.message()); + } + Ok(o.stdout) + } + + fn name<'p>(&self, p: &'p Payload) -> Result<&'p str> { + let Some(n) = p.vm_name() else { + bail!("payload does not contain the instance name"); + }; + validate_ident("instance name", n)?; + Ok(n) + } + + fn vm<'p>(&self, p: &'p Payload) -> Result<&'p VirtualMachine> { + p.vm.as_ref() + .ok_or_else(|| Error("payload does not contain 'cloudstack.vm.details'".into())) + } + + /// Current state, or `None` if the container does not exist. + pub fn state(&self, name: &str) -> Result<Option<State>> { + let o = self + .x + .run(&self.tool("lxc-info", &["-n", name, "-s", "-H"]))?; + if o.success() { + return Ok(Some(State::parse(&o.stdout))); + } + let msg = o.message(); + if msg.contains("doesn't exist") || msg.contains("does not exist") { + return Ok(None); + } + bail!("lxc-info failed: {msg}") + } + + fn destroy(&self, name: &str) -> Result<()> { + self.checked( + &self.tool("lxc-destroy", &["-n", name, "-f", "-s"]), + "lxc-destroy", + )?; + Ok(()) + } + + fn do_start(&self, name: &str) -> Result<()> { + let script = format!( + "{} && {}", + self.tool("lxc-start", &["-n", name, "-d"]), + self.tool("lxc-wait", &["-n", name, "-s", "RUNNING", "-t", "30"]) + ); + self.checked(&script, "lxc-start")?; + Ok(()) + } + + /// Create per-VLAN bridges (vlan_mode=bridge) and rewrite the managed + /// block of the container config. Runs on create and on every start, so + /// offering changes and host reboots are picked up. + fn apply(&self, name: &str, vm: &VirtualMachine) -> Result<()> { + if let Some(script) = bridge_script(self.s, &vm.nics)? { + self.checked(&script, "bridge setup")?; + } + let lines = render_config(self.s, vm)?; + self.checked( + &config_script(self.s, name, &lines), + "writing container config", + )?; + Ok(()) + } + + // ------------------------------------------------------------------ + // lifecycle + // ------------------------------------------------------------------ + + fn prepare(&self) -> Result<()> { + if self.s.clone_from.is_none() + && self.s.template == "download" + && (self.s.dist.is_none() || self.s.release.is_none()) + { + bail!("details 'dist' and 'release' are required for the 'download' template (or set 'clone_from')"); + } + Ok(()) + } + + fn create(&self, p: &Payload) -> Result<Value> { + let name = self.name(p)?; + let vm = self.vm(p)?; + self.prepare()?; + if self.state(name)?.is_some() { + bail!("container {name} already exists on the LXC host"); + } + + let script = if let Some(src) = &self.s.clone_from { + let mut a = vec!["-n", src.as_str(), "-N", name]; + if self.s.clone_snapshot { + a.push("-s"); + } + if let Some(bs) = &self.s.backingstore { + a.extend(["-B", bs.as_str()]); + } + self.tool("lxc-copy", &a) + } else { + let mut a = vec!["-n", name, "-t", self.s.template.as_str()]; + if let Some(bs) = &self.s.backingstore { + a.extend(["-B", bs.as_str()]); + } + if let Some(sz) = &self.s.fssize { + a.extend(["--fssize", sz.as_str()]); + } + a.push("--"); + if self.s.template == "download" { + a.extend(["-d", self.s.dist.as_deref().unwrap_or_default()]); + a.extend(["-r", self.s.release.as_deref().unwrap_or_default()]); + a.extend(["-a", self.s.arch.as_str()]); + if let Some(v) = &self.s.variant { + a.extend(["--variant", v.as_str()]); + } + } + a.extend(self.s.template_options.iter().map(String::as_str)); + self.tool("lxc-create", &a) + }; + + if let Err(e) = self.checked(&script, "container creation") { + let _ = self.destroy(name); + return Err(e); + } + if let Err(e) = self.apply(name, vm).and_then(|_| self.do_start(name)) { + let _ = self.destroy(name); + return Err(e); + } + Ok(success("Instance created")) + } + + fn start(&self, p: &Payload) -> Result<Value> { + let name = self.name(p)?; + match self.state(name)? { + None => bail!("container {name} does not exist on the LXC host"), + Some(State::Running) => return Ok(success("Instance already running")), + Some(State::Frozen) => { + self.checked(&self.tool("lxc-unfreeze", &["-n", name]), "lxc-unfreeze")?; + return Ok(success("Instance started")); + } + Some(_) => {} + } + self.apply(name, self.vm(p)?)?; + self.do_start(name)?; + Ok(success("Instance started")) + } + + fn stop(&self, p: &Payload) -> Result<Value> { + let name = self.name(p)?; + match self.state(name)? { + None | Some(State::Stopped) => return Ok(success("Instance stopped")), + Some(State::Frozen) => { + self.checked(&self.tool("lxc-unfreeze", &["-n", name]), "lxc-unfreeze")?; + } + Some(_) => {} + } + let t = self.s.stop_timeout.to_string(); + self.checked(&self.tool("lxc-stop", &["-n", name, "-t", &t]), "lxc-stop")?; + Ok(success("Instance stopped")) + } + + fn reboot(&self, p: &Payload) -> Result<Value> { + let name = self.name(p)?; + match self.state(name)? { + None => bail!("container {name} does not exist on the LXC host"), + Some(State::Running) => { + self.checked(&self.tool("lxc-stop", &["-n", name, "-r"]), "lxc-stop -r")?; + } + Some(_) => { + self.apply(name, self.vm(p)?)?; + self.do_start(name)?; + } + } + Ok(success("Instance rebooted")) + } + + fn delete(&self, p: &Payload) -> Result<Value> { + let name = self.name(p)?; + if self.state(name)?.is_some() { + self.destroy(name)?; + } + Ok(success("Instance deleted")) + } + + fn status(&self, p: &Payload) -> Result<Value> { + let name = self.name(p)?; + let ps = self + .state(name)? + .map(|s| s.power_state()) + .unwrap_or("poweroff"); + Ok(json!({"status": "success", "power_state": ps})) + } + + fn statuses(&self) -> Result<Value> { + let out = self.checked(&self.tool("lxc-ls", &["-f", "-F", "NAME,STATE"]), "lxc-ls")?; + let mut map = serde_json::Map::new(); + for (name, state) in parse_ls(&out) { + map.insert(name, Value::String(state.power_state().into())); + } + Ok(json!({"status": "success", "power_state": map})) + } + + fn freeze(&self, p: &Payload, freeze: bool) -> Result<Value> { + let name = self.name(p)?; + let tool = if freeze { "lxc-freeze" } else { "lxc-unfreeze" }; + self.checked(&self.tool(tool, &["-n", name]), tool)?; + Ok(success(if freeze { + "Instance frozen" + } else { + "Instance unfrozen" + })) + } + + // ------------------------------------------------------------------ + // snapshots (custom actions) + // ------------------------------------------------------------------ + + fn snap_name(&self, p: &Payload) -> Result<String> { + let Some(s) = p.parameter("snap_name") else { + bail!("missing parameter 'snap_name'"); + }; + validate_ident("snapshot name", &s)?; + Ok(s) + } + + fn list_snapshots(&self, p: &Payload) -> Result<Value> { + let name = self.name(p)?; + let out = self.checked( + &self.tool("lxc-snapshot", &["-n", name, "-L", "-C"]), + "lxc-snapshot -L", + )?; + Ok(json!({"status": "success", "printmessage": "true", "message": parse_snapshots(&out)})) + } + + fn create_snapshot(&self, p: &Payload) -> Result<Value> { + let name = self.name(p)?; + let script = match p.parameter("snap_comment") { + None => self.tool("lxc-snapshot", &["-n", name]), + Some(c) => format!( + "f=$(mktemp) || exit 1; printf '%s\\n' {} > \"$f\"; {} -c \"$f\"; rc=$?; rm -f \"$f\"; exit $rc", + quote(&c), + self.tool("lxc-snapshot", &["-n", name]) + ), + }; + self.checked(&script, "lxc-snapshot")?; + Ok(success("Instance Snapshot created")) + } + + fn restore_snapshot(&self, p: &Payload) -> Result<Value> { + let name = self.name(p)?; + let snap = self.snap_name(p)?; + let was_running = matches!(self.state(name)?, Some(State::Running | State::Frozen)); + if was_running { + self.stop(p)?; + } + self.checked( + &self.tool("lxc-snapshot", &["-n", name, "-r", &snap]), + "lxc-snapshot -r", + )?; + if was_running { + self.do_start(name)?; + } + Ok(success("Instance Snapshot restored")) + } + + fn delete_snapshot(&self, p: &Payload) -> Result<Value> { + let name = self.name(p)?; + let snap = self.snap_name(p)?; + self.checked( + &self.tool("lxc-snapshot", &["-n", name, "-d", &snap]), + "lxc-snapshot -d", + )?; + Ok(success("Instance Snapshot deleted")) + } +} + +// ---------------------------------------------------------------------- +// pure helpers (unit tested) +// ---------------------------------------------------------------------- + +/// Parse `lxc-ls -f -F NAME,STATE`. +pub fn parse_ls(out: &str) -> Vec<(String, State)> { + out.lines() + .skip(1) // header + .filter_map(|l| { + let mut it = l.split_whitespace(); + Some((it.next()?.to_string(), State::parse(it.next()?))) + }) + .collect() +} + +/// Parse `lxc-snapshot -L -C`: +/// ```text +/// snap0 (/var/lib/lxc/c1/snaps) 2026:01:02 10:20:30 +/// optional comment +/// ``` +pub fn parse_snapshots(out: &str) -> Vec<Value> { + let mut snaps: Vec<serde_json::Map<String, Value>> = Vec::new(); + for line in out.lines() { + if line.trim().is_empty() || line.starts_with("No snapshots") { + continue; + } + if line.starts_with(char::is_whitespace) { + if let Some(last) = snaps.last_mut() { + let prev = last + .get("description") + .and_then(Value::as_str) + .unwrap_or(""); + let joined = if prev.is_empty() { + line.trim().to_string() + } else { + format!("{prev} {}", line.trim()) + }; + last.insert("description".into(), Value::String(joined)); + } + continue; + } + let mut parts = line.split_whitespace(); + let Some(name) = parts.next() else { continue }; + let rest: Vec<&str> = parts.collect(); + let (path, time): (&str, Vec<&str>) = match rest.first() { + Some(p) if p.starts_with('(') => { + (p.trim_matches(|c| c == '(' || c == ')'), rest[1..].to_vec()) + } + _ => ("", rest), + }; + let mut m = serde_json::Map::new(); + m.insert("name".into(), name.into()); + m.insert("snaptime".into(), time.join(" ").into()); + m.insert("path".into(), path.into()); + m.insert("description".into(), "".into()); + snaps.push(m); + } + snaps.into_iter().map(Value::Object).collect() +} + +fn bridge_name(s: &Settings, vlan: u16) -> Result<String> { + let name = s + .bridge_name_template + .replace("{device}", &s.guest_device) + .replace("{vlan}", &vlan.to_string()); + validate_ident("bridge name", &name)?; + if name.len() > IFNAMSIZ { + bail!("bridge name '{name}' exceeds {IFNAMSIZ} characters; adjust 'bridge_name_template'"); + } + Ok(name) +} + +/// (bridge to attach to, VLAN id for `lxc.net.N.veth.vlan.id`) +fn nic_link(s: &Settings, nic: &Nic) -> Result<(String, Option<u16>)> { + match (s.vlan_mode, nic.segment()?) { + (_, Segment::Untagged) | (VlanMode::None, _) => Ok((s.bridge.clone(), None)), + (VlanMode::Filter, Segment::Vlan(v)) => Ok((s.bridge.clone(), Some(v))), + (VlanMode::Bridge, Segment::Vlan(v)) => Ok((bridge_name(s, v)?, None)), + } +} + +/// Idempotently create `<dev>.<vlan>` + bridge for every VLAN in use. +fn bridge_script(s: &Settings, nics: &[Nic]) -> Result<Option<String>> { + if s.vlan_mode != VlanMode::Bridge { + return Ok(None); + } + let mut vlans = BTreeSet::new(); + for n in nics { + if let Segment::Vlan(v) = n.segment()? { + vlans.insert(v); + } + } + if vlans.is_empty() { + return Ok(None); + } + let mut script = String::from("set -e\n"); + for v in vlans { + let br = quote(&bridge_name(s, v)?); + let sub = format!("{}.{v}", s.guest_device); + if sub.len() > IFNAMSIZ { + bail!("VLAN interface name '{sub}' exceeds {IFNAMSIZ} characters"); + } + let sub = quote(&sub); + let dev = quote(&s.guest_device); + script.push_str(&format!( + "if ! ip link show dev {sub} >/dev/null 2>&1; then ip link add link {dev} name {sub} type vlan id {v} || ip link show dev {sub} >/dev/null; fi\n\ + if ! ip link show dev {br} >/dev/null 2>&1; then ip link add name {br} type bridge || ip link show dev {br} >/dev/null; fi\n\ + ip link set dev {sub} master {br}\n\ + ip link set dev {sub} up\n\ + ip link set dev {br} up\n" + )); + } + Ok(Some(script)) +} + +fn netmask_prefix(mask: &str) -> Result<u32> { + let m: Ipv4Addr = mask + .parse() + .map_err(|_| Error(format!("invalid netmask '{mask}'")))?; + let bits = u32::from(m); + let ones = bits.leading_ones(); + if bits.checked_shl(ones).unwrap_or(0) != 0 { + bail!("non-contiguous netmask '{mask}'"); + } + Ok(ones) +} + +fn validate_mac(mac: &str) -> Result<()> { + let ok = mac.len() == 17 + && mac.split(':').count() == 6 + && mac + .split(':') + .all(|o| o.len() == 2 && o.chars().all(|c| c.is_ascii_hexdigit())); + if !ok { + bail!("invalid MAC address '{mac}'"); + } + Ok(()) +} + +/// The managed block of the container config. +pub fn render_config(s: &Settings, vm: &VirtualMachine) -> Result<Vec<String>> { + let mut l = vec![ + BEGIN_MARK.to_string(), + "# Managed by Apache CloudStack, rewritten on every start".into(), + ]; + + let max = vm + .max_ram + .filter(|&r| r > 0) + .or(vm.min_ram) + .filter(|&r| r > 0); + let min = vm.min_ram.filter(|&r| r > 0); + match s.cgroup { + CgroupVersion::V2 => { + if let Some(m) = max { + l.push(format!("lxc.cgroup2.memory.max = {m}")); + } + if let (Some(lo), Some(m)) = (min, max) { + if lo < m { + l.push(format!("lxc.cgroup2.memory.low = {lo}")); + } + } + } + CgroupVersion::V1 => { + if let Some(m) = max { + l.push(format!("lxc.cgroup.memory.limit_in_bytes = {m}")); + } + if let (Some(lo), Some(m)) = (min, max) { + if lo < m { + l.push(format!("lxc.cgroup.memory.soft_limit_in_bytes = {lo}")); + } + } + } + } + + if let Some(cpus) = vm.cpus.filter(|&c| c > 0 && s.limit_cpu) { + let period = 100_000u64; + let quota = period * cpus as u64; + match s.cgroup { + CgroupVersion::V2 => l.push(format!("lxc.cgroup2.cpu.max = {quota} {period}")), + CgroupVersion::V1 => { + l.push(format!("lxc.cgroup.cpu.cfs_period_us = {period}")); + l.push(format!("lxc.cgroup.cpu.cfs_quota_us = {quota}")); + } + } + } + + let mut nics = vm.nics.clone(); + nics.sort_by_key(|n| n.device_id); + if nics.is_empty() { + l.push("lxc.net.0.type = empty".into()); + } + for (i, nic) in nics.iter().enumerate() { + let (link, vlan) = nic_link(s, nic)?; + let k = format!("lxc.net.{i}"); + l.push(format!("{k}.type = veth")); + l.push(format!("{k}.link = {link}")); + l.push(format!("{k}.flags = up")); + l.push(format!("{k}.name = eth{i}")); + if let Some(mac) = nic.mac.as_deref().filter(|m| !m.is_empty()) { + validate_mac(mac)?; + l.push(format!("{k}.hwaddr = {}", mac.to_ascii_lowercase())); + } + if let Some(mtu) = nic.mtu.filter(|&m| m > 0) { + l.push(format!("{k}.mtu = {mtu}")); + } + if let Some(v) = vlan { + l.push(format!("{k}.veth.vlan.id = {v}")); + } + if s.static_ip { + if let (Some(ip), Some(mask)) = (nic.ip.as_deref(), nic.netmask.as_deref()) { + if !ip.is_empty() && !mask.is_empty() { + let ip: Ipv4Addr = ip + .parse() + .map_err(|_| Error(format!("invalid IPv4 address '{ip}'")))?; + l.push(format!("{k}.ipv4.address = {ip}/{}", netmask_prefix(mask)?)); + if nic.default_nic { + if let Some(gw) = nic.gateway.as_deref().filter(|g| !g.is_empty()) { + let gw: Ipv4Addr = gw + .parse() + .map_err(|_| Error(format!("invalid gateway '{gw}'")))?; + l.push(format!("{k}.ipv4.gateway = {gw}")); + } + } + } + } + if let Some(ip6) = nic.ip6address.as_deref().filter(|a| !a.is_empty()) { + let ip6: Ipv6Addr = ip6 + .parse() + .map_err(|_| Error(format!("invalid IPv6 address '{ip6}'")))?; + let prefix = nic + .ip6cidr + .as_deref() + .and_then(|c| c.split_once('/')) + .and_then(|(_, p)| p.parse::<u8>().ok()) + .filter(|&p| p <= 128) + .unwrap_or(64); + l.push(format!("{k}.ipv6.address = {ip6}/{prefix}")); + if nic.default_nic { + if let Some(gw) = nic.ip6gateway.as_deref().filter(|g| !g.is_empty()) { + let gw: Ipv6Addr = gw + .parse() + .map_err(|_| Error(format!("invalid IPv6 gateway '{gw}'")))?; + l.push(format!("{k}.ipv6.gateway = {gw}")); + } + } + } + } + } + + for extra in &s.extra_config { + l.push(extra.clone()); + } + l.push(END_MARK.to_string()); + + for line in &l { + validate_config_value("config line", line)?; + } + Ok(l) +} + +/// Shell script that replaces the managed block (and any template supplied +/// `lxc.net.*` lines) in the container config. +pub fn config_script(s: &Settings, name: &str, lines: &[String]) -> String { + let lxc_path = match &s.lxc_path { + Some(p) => quote(p), + None => "\"$(lxc-config lxc.lxcpath)\"".to_string(), + }; + format!( + "set -e\n\ + P={lxc_path}\n\ + C=\"$P\"/{name}/config\n\ + [ -f \"$C\" ] || {{ echo \"container config $C not found\" >&2; exit 1; }}\n\ + T=\"$C.cloudstack.tmp\"\n\ + sed -e '/^lxc\\.net\\./d' -e '/^{begin}$/,/^{end}$/d' \"$C\" > \"$T\"\n\ + printf '%s\\n' {lines} >> \"$T\"\n\ + cat \"$T\" > \"$C\"\n\ + rm -f \"$T\"\n", + name = quote(name), + begin = BEGIN_MARK, + end = END_MARK, + lines = join(lines), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::exec::Output; + use std::cell::RefCell; + + fn settings(extra: &str) -> Settings { + let json = format!( + r#"{{"externaldetails": {{"host": {{"host": "10.0.0.5" {extra}}}, + "virtualmachine": {{"dist": "debian", "release": "bookworm"}}}}}}"# + ); + Settings::from_payload(&serde_json::from_str(&json).unwrap()).unwrap() + } + + fn vm() -> VirtualMachine { + VirtualMachine { + name: Some("i-2-10-VM".into()), + cpus: Some(2), + min_ram: Some(512 * 1024 * 1024), + max_ram: Some(1024 * 1024 * 1024), + nics: vec![ + Nic { + device_id: 1, + mac: Some("02:00:4C:5E:00:02".into()), + broadcast_uri: Some("vlan://untagged".into()), + ..Default::default() + }, + Nic { + device_id: 0, + mac: Some("02:00:4c:5e:00:01".into()), + ip: Some("10.1.1.10".into()), + netmask: Some("255.255.255.0".into()), + gateway: Some("10.1.1.1".into()), + broadcast_uri: Some("vlan://1910".into()), + default_nic: true, + mtu: Some(1450), + ..Default::default() + }, + ], + } + } + + #[test] + fn renders_config_filter_mode() { + let l = render_config(&settings(r#", "static_ip": "true""#), &vm()).unwrap(); + let text = l.join("\n"); + assert!(text.contains("lxc.cgroup2.memory.max = 1073741824")); + assert!(text.contains("lxc.cgroup2.memory.low = 536870912")); + assert!(text.contains("lxc.cgroup2.cpu.max = 200000 100000")); + // sorted by deviceId + assert!(text.contains("lxc.net.0.hwaddr = 02:00:4c:5e:00:01")); + assert!(text.contains("lxc.net.0.link = cloudbr0")); + assert!(text.contains("lxc.net.0.veth.vlan.id = 1910")); + assert!(text.contains("lxc.net.0.mtu = 1450")); + assert!(text.contains("lxc.net.0.ipv4.address = 10.1.1.10/24")); + assert!(text.contains("lxc.net.0.ipv4.gateway = 10.1.1.1")); + assert!(text.contains("lxc.net.1.hwaddr = 02:00:4c:5e:00:02")); + assert!(!text.contains("lxc.net.1.veth.vlan.id")); + assert_eq!(l.first().unwrap(), BEGIN_MARK); + assert_eq!(l.last().unwrap(), END_MARK); + } + + #[test] + fn renders_config_bridge_mode_and_v1() { + let s = settings(r#", "vlan_mode": "bridge", "cgroup_version": "1""#); + let text = render_config(&s, &vm()).unwrap().join("\n"); + assert!(text.contains("lxc.net.0.link = breth1-1910")); + assert!(!text.contains("veth.vlan.id")); + assert!( + !text.contains("ipv4.address"), + "static_ip defaults to false" + ); + assert!(text.contains("lxc.cgroup.memory.limit_in_bytes = 1073741824")); + assert!(text.contains("lxc.cgroup.cpu.cfs_quota_us = 200000")); + let script = bridge_script(&s, &vm().nics).unwrap().unwrap(); + assert!(script.contains("ip link add link eth1 name eth1.1910 type vlan id 1910")); + assert!(script.contains("ip link add name breth1-1910 type bridge")); + assert!(bridge_script(&settings(""), &vm().nics).unwrap().is_none()); + } + + #[test] + fn rejects_hostile_values() { + let mut v = vm(); + v.nics[0].mac = Some("02:00:00:00:00:01\nlxc.mount.entry = / x".into()); + assert!(render_config(&settings(""), &v).is_err()); + let s = settings( + r#", "vlan_mode": "bridge", "bridge_name_template": "averylongbridge-{vlan}""#, + ); + assert!(render_config(&s, &vm()).is_err()); + } + + #[test] + fn netmasks() { + assert_eq!(netmask_prefix("255.255.255.0").unwrap(), 24); + assert_eq!(netmask_prefix("255.255.255.255").unwrap(), 32); + assert_eq!(netmask_prefix("0.0.0.0").unwrap(), 0); + assert!(netmask_prefix("255.0.255.0").is_err()); + } + + #[test] + fn config_script_is_quoted() { + let s = settings(""); + let sc = config_script(&s, "i-2-10-VM", &["lxc.net.0.type = veth".into()]); + assert!(sc.contains("C=\"$P\"/i-2-10-VM/config")); + assert!(sc.contains("printf '%s\\n' 'lxc.net.0.type = veth' >> \"$T\"")); + assert!(!sc.contains("sed -i"), "must not rely on GNU sed -i"); + assert!(sc.contains("P=\"$(lxc-config lxc.lxcpath)\"")); + } + + #[test] + fn parses_lxc_ls() { + let out = + "NAME STATE \ni-2-10-VM RUNNING \ni-2-11-VM STOPPED \nweird FROZEN\n"; + let v = parse_ls(out); + assert_eq!(v.len(), 3); + assert_eq!(v[0], ("i-2-10-VM".into(), State::Running)); + assert_eq!(v[1].1.power_state(), "poweroff"); + assert_eq!(v[2].1.power_state(), "poweron"); + assert!(parse_ls("NAME STATE\n").is_empty()); + } + + #[test] + fn parses_snapshots() { + let out = "snap0 (/var/lib/lxc/c1/snaps) 2026:01:02 10:20:30\n before upgrade\nsnap1 (/var/lib/lxc/c1/snaps) 2026:01:03 11:00:00\n"; + let v = parse_snapshots(out); + assert_eq!(v.len(), 2); + assert_eq!(v[0]["name"], "snap0"); + assert_eq!(v[0]["snaptime"], "2026:01:02 10:20:30"); + assert_eq!(v[0]["description"], "before upgrade"); + assert_eq!(v[1]["path"], "/var/lib/lxc/c1/snaps"); + assert!(parse_snapshots("No snapshots\n").is_empty()); + } + + /// Records scripts and answers based on the first matching substring. + struct Mock { + rules: Vec<(&'static str, Output)>, + seen: RefCell<Vec<String>>, + } + + impl Mock { + fn new(rules: Vec<(&'static str, i32, &'static str, &'static str)>) -> Self { + Mock { + rules: rules + .into_iter() + .map(|(p, c, o, e)| { + ( + p, + Output { + code: Some(c), + stdout: o.into(), + stderr: e.into(), + }, + ) + }) + .collect(), + seen: RefCell::new(vec![]), + } + } + } + + impl Executor for Mock { + fn run(&self, script: &str) -> Result<Output> { + self.seen.borrow_mut().push(script.to_string()); + Ok(self + .rules + .iter() + .find(|(p, _)| script.contains(p)) + .map(|(_, o)| o.clone()) + .unwrap_or(Output { + code: Some(0), + ..Default::default() + })) + } + } + + fn payload() -> Payload { + Payload { + vm: Some(vm()), + ..Default::default() + } + } + + #[test] + fn create_flow() { + let s = settings(""); + let m = Mock::new(vec![("lxc-info", 1, "", "i-2-10-VM doesn't exist")]); + let out = Lxc::new(&s, &m) + .dispatch("create", &payload()) + .unwrap() + .unwrap(); + assert_eq!(out["status"], "success"); + let seen = m.seen.borrow(); + assert!(seen[0].starts_with("lxc-info -n i-2-10-VM -s -H")); + assert_eq!( + seen[1], + "lxc-create -n i-2-10-VM -t download -- -d debian -r bookworm -a amd64" + ); + assert!(seen[2].contains("lxc.net.0.veth.vlan.id = 1910")); + assert!(seen[3].starts_with("lxc-start -n i-2-10-VM -d && lxc-wait")); + assert_eq!(seen.len(), 4); + } + + #[test] + fn create_rolls_back_on_start_failure() { + let s = settings(""); + let m = Mock::new(vec![ + ("lxc-info", 1, "", "i-2-10-VM doesn't exist"), + ("lxc-start", 1, "", "boom"), + ]); + let err = Lxc::new(&s, &m).dispatch("create", &payload()).unwrap_err(); + assert!(err.0.contains("boom")); + assert!(m + .seen + .borrow() + .last() + .unwrap() + .starts_with("lxc-destroy -n i-2-10-VM -f -s")); + } + + #[test] + fn create_requires_image() { + let json = r#"{"externaldetails": {"host": {"host": "h"}}}"#; + let s = Settings::from_payload(&serde_json::from_str(json).unwrap()).unwrap(); + let m = Mock::new(vec![]); + assert!(Lxc::new(&s, &m).dispatch("prepare", &payload()).is_err()); + assert!(m.seen.borrow().is_empty()); + } + + #[test] + fn stop_and_delete_are_idempotent() { + let s = settings(""); + let m = Mock::new(vec![("lxc-info", 1, "", "i-2-10-VM doesn't exist")]); + let l = Lxc::new(&s, &m); + assert_eq!( + l.dispatch("stop", &payload()).unwrap().unwrap()["status"], + "success" + ); + assert_eq!( + l.dispatch("delete", &payload()).unwrap().unwrap()["status"], + "success" + ); + assert_eq!( + l.dispatch("status", &payload()).unwrap().unwrap()["power_state"], + "poweroff" + ); + assert!(m.seen.borrow().iter().all(|c| c.starts_with("lxc-info"))); + } + + #[test] + fn stop_running_uses_timeout_and_lxc_path() { + let s = settings(r#", "lxc_path": "/srv/lxc", "stop_timeout": "30""#); + let m = Mock::new(vec![("lxc-info", 0, "RUNNING\n", "")]); + Lxc::new(&s, &m).dispatch("stop", &payload()).unwrap(); + assert_eq!( + m.seen.borrow()[1], + "lxc-stop -P /srv/lxc -n i-2-10-VM -t 30" + ); + } + + #[test] + fn statuses_and_console() { + let s = settings(""); + let m = Mock::new(vec![("lxc-ls", 0, "NAME STATE\ni-2-10-VM RUNNING\n", "")]); + let l = Lxc::new(&s, &m); + let v = l + .dispatch("statuses", &Payload::default()) + .unwrap() + .unwrap(); + assert_eq!(v["power_state"]["i-2-10-VM"], "poweron"); + assert!(l.dispatch("getconsole", &payload()).is_err()); + assert!(l.dispatch("bogus", &payload()).is_err()); + } +} diff --git a/lxc/src/main.rs b/lxc/src/main.rs new file mode 100644 index 0000000..875d867 --- /dev/null +++ b/lxc/src/main.rs @@ -0,0 +1,93 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! Apache CloudStack Orchestrator extension for LXC. +//! +//! Invoked by the management server as: +//! +//! ```text +//! lxc-extension <action> <payload-file> <timeout-seconds> +//! ``` +//! +//! and answers with a single JSON object on stdout. Exit code 0 means +//! success, anything else failure. + +mod config; +mod error; +mod exec; +mod log; +mod lxc; +mod payload; +mod shell; + +use std::path::Path; +use std::process::ExitCode; +use std::time::{Duration, Instant}; + +use serde_json::{json, Value}; + +use crate::config::Settings; +use crate::error::Result; +use crate::exec::ProcessExecutor; +use crate::lxc::Lxc; +use crate::payload::Payload; + +/// Seconds reserved to report a timeout before CloudStack kills us. +const TIMEOUT_MARGIN: u64 = 3; + +fn run(args: &[String], started: Instant) -> Result<Option<Value>> { + if args.len() < 3 { + bail!( + "usage: {} <action> <payload-file> [timeout-seconds]", + args.first().map(String::as_str).unwrap_or("lxc-extension") + ); + } + let action = args[1].as_str(); + let timeout: u64 = args + .get(3) + .and_then(|t| t.parse().ok()) + .filter(|&t| t > 0) + .unwrap_or(300); + let deadline = started + Duration::from_secs(timeout.saturating_sub(TIMEOUT_MARGIN).max(5)); + + let payload = Payload::load(Path::new(&args[2]))?; + log::write(&format!( + "action={action} instance={:?} timeout={timeout}", + payload.vm_name() + )); + + let settings = Settings::from_payload(&payload)?; + let executor = ProcessExecutor::new(settings.transport.clone(), settings.sudo, deadline)?; + Lxc::new(&settings, &executor).dispatch(action, &payload) +} + +fn main() -> ExitCode { + let started = Instant::now(); + let args: Vec<String> = std::env::args().collect(); + match run(&args, started) { + Ok(Some(v)) => { + println!("{v}"); + ExitCode::SUCCESS + } + Ok(None) => ExitCode::SUCCESS, + Err(e) => { + log::write(&format!("error: {e}")); + println!("{}", json!({"status": "error", "error": e.to_string()})); + ExitCode::from(1) + } + } +} diff --git a/lxc/src/payload.rs b/lxc/src/payload.rs new file mode 100644 index 0000000..e014418 --- /dev/null +++ b/lxc/src/payload.rs @@ -0,0 +1,228 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! The JSON payload file written by CloudStack's +//! `ExternalPathPayloadProvisioner`. Only the fields this extension uses are +//! modelled; everything is optional so that minor changes on the CloudStack +//! side do not break deserialisation. + +use std::collections::HashMap; +use std::path::Path; + +use serde::Deserialize; +use serde_json::Value; + +use crate::bail; +use crate::error::Result; + +#[derive(Debug, Default, Deserialize)] +pub struct Payload { + /// `{"extension": {...}, "host": {...}, "virtualmachine": {...}, ...}` + #[serde(default)] + pub externaldetails: HashMap<String, Value>, + + /// Gson serialisation of `VirtualMachineTO`. + #[serde(rename = "cloudstack.vm.details", default)] + pub vm: Option<VirtualMachine>, + + #[serde(default)] + pub virtualmachinename: Option<String>, + + /// Parameters of a custom action. + #[serde(default)] + pub parameters: Option<Value>, +} + +#[derive(Debug, Default, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct VirtualMachine { + #[serde(default)] + pub name: Option<String>, + #[serde(default)] + pub cpus: Option<u32>, + /// Bytes. + #[serde(default)] + pub min_ram: Option<u64>, + /// Bytes. + #[serde(default)] + pub max_ram: Option<u64>, + #[serde(default)] + pub nics: Vec<Nic>, +} + +#[derive(Debug, Default, Clone, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Nic { + #[serde(default)] + pub device_id: u32, + #[serde(default)] + pub mac: Option<String>, + #[serde(default)] + pub ip: Option<String>, + #[serde(default)] + pub netmask: Option<String>, + #[serde(default)] + pub gateway: Option<String>, + #[serde(default)] + pub ip6address: Option<String>, + #[serde(default)] + pub ip6cidr: Option<String>, + #[serde(default)] + pub ip6gateway: Option<String>, + #[serde(default)] + pub broadcast_uri: Option<String>, + #[serde(default)] + pub default_nic: bool, + #[serde(default)] + pub mtu: Option<u32>, +} + +/// How a NIC is attached to the physical network. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Segment { + Untagged, + Vlan(u16), +} + +impl Nic { + /// Interpret `broadcastUri` (`vlan://100`, `vlan://untagged`, absent, ...). + pub fn segment(&self) -> Result<Segment> { + let Some(uri) = self.broadcast_uri.as_deref().filter(|u| !u.is_empty()) else { + return Ok(Segment::Untagged); + }; + let (scheme, rest) = uri.split_once("://").unwrap_or(("vlan", uri)); + match scheme.to_ascii_lowercase().as_str() { + "vlan" => { + if rest.eq_ignore_ascii_case("untagged") { + return Ok(Segment::Untagged); + } + match rest.parse::<u16>() { + Ok(id) if (1..=4094).contains(&id) => Ok(Segment::Vlan(id)), + _ => bail!("invalid VLAN in broadcast URI '{uri}'"), + } + } + "native" => Ok(Segment::Untagged), + other => bail!("unsupported broadcast domain type '{other}' (URI '{uri}'); only VLAN and untagged networks are supported"), + } + } +} + +impl Payload { + pub fn load(path: &Path) -> Result<Self> { + let raw = std::fs::read_to_string(path).map_err(|e| { + crate::error::Error(format!("cannot read payload file {}: {e}", path.display())) + })?; + Ok(serde_json::from_str(&raw)?) + } + + /// One section of `externaldetails` (`extension`, `host`, `virtualmachine`) + /// flattened to strings. + pub fn details(&self, section: &str) -> HashMap<String, String> { + let mut out = HashMap::new(); + if let Some(Value::Object(map)) = self.externaldetails.get(section) { + for (k, v) in map { + if let Some(s) = value_to_string(v) { + out.insert(k.clone(), s); + } + } + } + out + } + + /// The CloudStack internal instance name, used as container name. + pub fn vm_name(&self) -> Option<&str> { + self.vm + .as_ref() + .and_then(|v| v.name.as_deref()) + .or(self.virtualmachinename.as_deref()) + .filter(|n| !n.is_empty()) + } + + /// A custom action parameter as a string. + pub fn parameter(&self, key: &str) -> Option<String> { + match &self.parameters { + Some(Value::Object(map)) => map.get(key).and_then(value_to_string), + _ => None, + } + .filter(|s| !s.is_empty()) + } +} + +fn value_to_string(v: &Value) -> Option<String> { + match v { + Value::String(s) => Some(s.clone()), + Value::Number(n) => Some(n.to_string()), + Value::Bool(b) => Some(b.to_string()), + _ => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const SAMPLE: &str = r#"{ + "externaldetails": { + "extension": {"bridge": "cloudbr0"}, + "host": {"host": "10.0.0.5", "username": "root"}, + "virtualmachine": {"dist": "debian", "release": "bookworm"} + }, + "virtualmachineid": "6b8b1a6a-0000-0000-0000-000000000000", + "virtualmachinename": "i-2-10-VM", + "cloudstack.vm.details": { + "id": 10, "name": "i-2-10-VM", "cpus": 2, "minRam": 536870912, "maxRam": 1073741824, + "uuid": "6b8b1a6a-0000-0000-0000-000000000000", + "nics": [ + {"deviceId": 0, "mac": "02:00:4c:5e:00:01", "ip": "10.1.1.10", "netmask": "255.255.255.0", + "gateway": "10.1.1.1", "broadcastUri": "vlan://1910", "defaultNic": true, "type": "Guest"} + ] + }, + "parameters": {"snap_name": "snap0", "n": 3} + }"#; + + #[test] + fn parses_cloudstack_payload() { + let p: Payload = serde_json::from_str(SAMPLE).unwrap(); + assert_eq!(p.vm_name(), Some("i-2-10-VM")); + let vm = p.vm.as_ref().unwrap(); + assert_eq!(vm.cpus, Some(2)); + assert_eq!(vm.max_ram, Some(1073741824)); + assert_eq!(vm.nics[0].segment().unwrap(), Segment::Vlan(1910)); + assert_eq!(p.details("host")["host"], "10.0.0.5"); + assert_eq!(p.details("virtualmachine")["release"], "bookworm"); + assert_eq!(p.parameter("snap_name").as_deref(), Some("snap0")); + assert_eq!(p.parameter("n").as_deref(), Some("3")); + assert_eq!(p.parameter("missing"), None); + } + + #[test] + fn segments() { + let nic = |u: Option<&str>| Nic { + broadcast_uri: u.map(String::from), + ..Default::default() + }; + assert_eq!(nic(None).segment().unwrap(), Segment::Untagged); + assert_eq!( + nic(Some("vlan://untagged")).segment().unwrap(), + Segment::Untagged + ); + assert_eq!(nic(Some("vlan://42")).segment().unwrap(), Segment::Vlan(42)); + assert!(nic(Some("vlan://0")).segment().is_err()); + assert!(nic(Some("vlan://5000")).segment().is_err()); + assert!(nic(Some("vxlan://5000")).segment().is_err()); + } +} diff --git a/lxc/src/shell.rs b/lxc/src/shell.rs new file mode 100644 index 0000000..f0db244 --- /dev/null +++ b/lxc/src/shell.rs @@ -0,0 +1,96 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! POSIX shell quoting. Every value that ends up in a command executed on +//! the LXC host goes through [`quote`], because the remote side always +//! parses the command with `sh`. + +use crate::bail; +use crate::error::Result; + +fn is_safe(c: char) -> bool { + c.is_ascii_alphanumeric() || "_./:=,@%+-".contains(c) +} + +/// Quote a single word for a POSIX shell. +pub fn quote(s: &str) -> String { + if !s.is_empty() && s.chars().all(is_safe) { + return s.to_string(); + } + format!("'{}'", s.replace('\'', r"'\''")) +} + +/// Quote and join words into a single command line. +pub fn join<S: AsRef<str>>(words: &[S]) -> String { + words + .iter() + .map(|w| quote(w.as_ref())) + .collect::<Vec<_>>() + .join(" ") +} + +/// Validate an identifier (container name, distribution, snapshot name, ...) +/// that is used both as a command argument and inside file paths. +pub fn validate_ident(what: &str, value: &str) -> Result<()> { + if value.is_empty() + || value.len() > 128 + || value.starts_with('-') + || value.starts_with('.') + || !value + .chars() + .all(|c| c.is_ascii_alphanumeric() || "_.-".contains(c)) + { + bail!( + "invalid {what} '{value}': only [A-Za-z0-9_.-] allowed, must not start with '-' or '.'" + ); + } + Ok(()) +} + +/// Validate a value that is written verbatim into an LXC config line. +pub fn validate_config_value(what: &str, value: &str) -> Result<()> { + if value.contains(['\n', '\r', '\0']) { + bail!("invalid {what}: must not contain line breaks"); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn quoting() { + assert_eq!(quote("i-2-10-VM"), "i-2-10-VM"); + assert_eq!(quote(""), "''"); + assert_eq!(quote("a b"), "'a b'"); + assert_eq!(quote("it's"), r"'it'\''s'"); + assert_eq!(quote("$(rm -rf /)"), "'$(rm -rf /)'"); + assert_eq!(join(&["lxc-start", "-n", "a b"]), "lxc-start -n 'a b'"); + } + + #[test] + fn idents() { + assert!(validate_ident("name", "i-2-10-VM").is_ok()); + assert!(validate_ident("name", "ubuntu_24.04").is_ok()); + assert!(validate_ident("name", "-rf").is_err()); + assert!(validate_ident("name", "../etc").is_err()); + assert!(validate_ident("name", "a/b").is_err()); + assert!(validate_ident("name", "a b").is_err()); + assert!(validate_ident("name", "").is_err()); + } +}
