# Keeping it running

- **A KVM that is down doesn't slow the others.** It is retried less and less often (up to every
  15 seconds), its tile says when it was last seen, and the other tiles carry on. A KVM that
  reboots is picked up again by itself.
- **Log:** `qkvm.log` in the data folder (rotated at 2 MB, three old files kept) records starts, listener
  changes, KVMs going down and coming back, and errors inside the program. What the web server and the
  libraries have to say goes there too, one line of each kind a minute at the most: a line for every
  request that is none would be the log's history gone in minutes. Sign-ins, refused ones too, are in
  the activity log. `--log-level debug` writes more.
- **Health check:** `GET /healthz` answers `{"status": "ok", "version": "...", "api": ["v1"], "page": "...", "locked": false}`
  without a login, for a monitor or a watchdog. (`"page"` is a mark of the page's own files: a
  browser tab left open across a restart compares it with its own, and fetches the page again
  when they differ.) `"locked": true` means qKVM cannot open the saved device passwords just
  now: it was started with `--locked-start` and nobody has signed in since, or it has not
  been signed in to once since it was set up or its key was changed. It is running, and
  until somebody signs in it cannot reach a single device, so nothing is watched and no
  alert is sent. Have whatever monitors qKVM tell you about it. `"video": "unavailable"`, there
  only then, means that no picture can be made on this computer: the last video worker that was
  to start could not, and none has since (one that only took longer than 15 seconds to start, as a
  computer under load can, counts only when three do so in a row). The tiles whose pictures qKVM makes itself (JetKVMs,
  servers, PCs with Intel AMT, VNC servers, Proxmox guests) say why (`no_video`), and so does
  `qkvm.log`, once.
- **Carrying on after a restart:** qKVM opens the saved device passwords itself at start, and
  goes on watching, alerting and answering a collector without anybody signing in. A browser
  that signed in with *Keep this browser signed in for 30 days* stays signed in across the
  restart; any other is asked for its password again, as is every visitor: the key opens
  the saved passwords for the program, not the wall for whoever comes by. What makes it
  possible is a key in the data folder (`unlock.key`), made at the first start. The first
  sign-in makes it fit this data folder, and from the next start on it opens it.

  The automatic-unlock key in the data folder opens only the inner credential layer; the
  separate server storage key is always required to read protected settings first.

  - `--unlock-file FILE` keeps the automatic-unlock secret outside the data folder. This is
    separate from `--vault-key-file`, which protects the entire saved settings document.
  - `--locked-start` keeps no automatic-unlock secret. After every restart nothing is watched
    and browsers sign in again before devices are reached. The server still needs its external
    storage key to load settings; a user's password alone cannot open a copied data folder.

  Switching this runtime policy does not revoke old backups or rotate device credentials.
- **Backup and restore:** *Settings > Backups* makes an encrypted backup of the whole wall every day, which
  restores with its recovery kit alone: see [Backups](https://qkvm.com/docs/backups). To copy the folder by hand instead,
  back up the data directory and the server storage key **separately**.
  Stop the server for a consistent backup including history and audit databases, or use a
  filesystem/database backup mechanism that preserves their transactional state. Restore the
  data and matching key privately, select the key with `--vault-key-file`, and run
  `--verify-vault` before starting the restored service. Then test private sign-in/MFA and
  device connectivity in an isolated acceptance environment. Accounts and their passwords
  are preserved. Account recovery codes cannot reconstruct a lost server storage key.
  See [migration and recovery guidance](https://github.com/qkvm/qkvm/blob/main/SECURITY.md#migrating-an-existing-data-folder).
- **How large:** the largest wall run so far had 13 real KVMs for a night, and 44 stand-ins for
  an hour with a picture a second each: about 40 % of one processor core and 130 MB of memory,
  steady. Each tile that is being looked at costs the KVM one picture a second and qKVM
  little; a JetKVM costs more (see [JetKVM](https://qkvm.com/docs/jetkvm)). Nothing is known yet about hundreds.
- **Memory on Linux:** with glibc, every wall of 0.4.0 keeps malloc to two arenas and a trim threshold
  of 131072 bytes (as `MALLOC_ARENA_MAX=2` and `MALLOC_TRIM_THRESHOLD_=131072` say), however it came to
  0.4.0: pip, the service, the image, or an update from inside the app. Memory it frees piles up more
  slowly over the days. Set either yourself (the unit's `Environment=`, `docker run -e`, or
  `GLIBC_TUNABLES`) and qKVM keeps yours.
- **Settings file:** every change is written atomically, and a second copy of what was just
  saved is kept as `qkvm.bak` next to it. If `qkvm.json` is ever unreadable or gone (storage damage
  or a start that was cut off), qKVM starts from that copy, sets a damaged file aside
  and says so. The copy is of what was saved last, not of what was there before: nothing that
  was taken away (an account, a token, a password) comes back by it. A change that cannot be
  saved (a full disk) is refused and taken back, and the answer says so.
- **One copy per data folder:** a second `qkvm` pointed at the same folder refuses to start,
  so typing `qkvm` while it is running already does no harm.
- **After changing the program's files by hand, restart it.** The page is loaded into memory
  at start, so a browser always gets the page that matches the running server. (Updates
  installed from inside the app restart it for you.)
- **Start it with the system (Linux):** a systemd unit does it. With qKVM installed in an
  environment of its own (`python3 -m venv /opt/qkvm`, then
  `/opt/qkvm/bin/python -m pip install --upgrade pip` and
  `/opt/qkvm/bin/python -m pip install qkvm`),
  this as `/etc/systemd/system/qkvm.service`:

  ```
  [Unit]
  Description=qKVM
  After=network-online.target
  Wants=network-online.target

  [Service]
  ExecStart=/opt/qkvm/bin/qkvm --data-dir /var/lib/qkvm --vault-key-file /var/lib/qkvm-keys/vault.key --https --setup-code
  DynamicUser=yes
  User=qkvm-web
  Group=qkvm-web
  StateDirectory=qkvm qkvm-keys
  StateDirectoryMode=0700
  UMask=0077
  CapabilityBoundingSet=
  ProtectKernelTunables=yes
  ProtectKernelModules=yes
  ProtectControlGroups=yes
  Restart=on-failure

  [Install]
  WantedBy=multi-user.target
  ```

  and `systemctl enable --now qkvm`. It runs as a user of its own that can write to
  its private data directory at `/var/lib/qkvm`, separate key directory at `/var/lib/qkvm-keys`,
  and private temporary files. Back up the two state directories separately. The code
  asked for at the first-run setup is in `journalctl -u qkvm`. Use a service identity
  that is not an existing login account: `DynamicUser=yes` reuses an account if its
  name already exists, including that account's supplementary groups. Do not use an
  administrator or an account in `sudo`, `docker` or `lxd` for the web service.
  The unit above uses `qkvm-web`; choose another unused name if that is already an account.
  These restrictions allow ordinary outbound device connections and application updates;
  they do not provide access to host administration tools. An explicit TLS proxy setup
  may replace `--https`, while retaining the protected first-run setup.

  It carries on by itself after a restart. To keep the key that makes that possible out of
  the data folder and its backups, make one that only root can read and hand it to the
  service as a credential, which no other user of the computer can see:

  ```
  install -d -m 700 /etc/qkvm
  head -c 32 /dev/urandom | base64 > /etc/qkvm/unlock.key
  chmod 600 /etc/qkvm/unlock.key
  ```

  then add `LoadCredential=qkvm-unlock:/etc/qkvm/unlock.key` under `[Service]`, and
  ` --unlock-file %d/qkvm-unlock` to the end of the `ExecStart` line. Sign in once, and from
  the next restart on it is this key that opens the saved passwords.
- **Start it with Windows:** one way is a task that runs at log-on, made in PowerShell:

  ```
  schtasks /Create /TN "qKVM" /SC ONLOGON /RL LIMITED /TR "pythonw -P -m qkvm"
  Set-ScheduledTask -TaskName qKVM -Settings (New-ScheduledTaskSettingsSet -ExecutionTimeLimit 0 -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries)
  ```

  The second line keeps Windows from stopping it: a task made with `schtasks` alone is ended
  after three days, and on a laptop as soon as it runs on its battery.

  qKVM comes up watching; a browser shows screens once someone has signed in there. Started this way there is
  no terminal: what it would say there is in `qkvm.log` in the data folder (the setup code
  too, where it was started with `--setup-code`), and it is stopped with `qkvm stop` from
  any terminal. Started as a Windows service, by a task that runs whether anybody is signed in
  or not, or over SSH, qKVM shows pictures as well since 0.4.0; before, it could make none there
  (each video worker is given a desktop of its own now: see [SECURITY.md](https://github.com/qkvm/qkvm/blob/main/SECURITY.md#native-video-isolation)).
