Skip to content

Instantly share code, notes, and snippets.

@gdamjan
Last active November 26, 2022 12:19
Show Gist options
  • Save gdamjan/9f3e4a4016459d3e12f576ec0813c785 to your computer and use it in GitHub Desktop.
Save gdamjan/9f3e4a4016459d3e12f576ec0813c785 to your computer and use it in GitHub Desktop.
A demo "Portable Service" for a shell program built with nix - https://systemd.io/PORTABLE_SERVICES/
{ pkgs ? import <nixpkgs> { } }:
let
demo-program = pkgs.writeShellScriptBin "helloWorld" "while sleep 3; do echo Hello World; done";
demo-service = pkgs.substituteAll {
name = "demo.service";
src = ./demo.service.in;
demoExe = "${demo-program}/bin/helloWorld";
};
demo-socket = pkgs.concatText "demo.socket" [ ./demo.socket ];
in
pkgs.portableService {
pname = "demo";
version = "1.0";
description = ''A demo "Portable Service" for a shell program built with nix'';
homepage = "https://gist.github.com/gdamjan/9f3e4a4016459d3e12f576ec0813c785";
units = [ demo-service demo-socket ];
# let's assume a legacy app will need these at the exact locations
symlinks = [
{ object = "${pkgs.cacert}/etc/ssl"; symlink = "/etc/ssl"; }
{ object = "${pkgs.bash}/bin/bash"; symlink = "/bin/sh"; }
];
}
[Unit]
Description=demo service
Requires=demo.socket
After=demo.socket
[Service]
Type=simple
ExecStart=@demoExe@
Restart=always
[Install]
WantedBy=multi-user.target
Also=demo.socket
[Unit]
Description=demo socket
[Socket]
ListenStream=/run/demo.sock
SocketMode=0666
[Install]
WantedBy=sockets.target
@gdamjan
Copy link
Author

gdamjan commented Aug 25, 2022

If you don't run Nix, you can play with this by using podman (or docker):

git clone https://gist.github.com/gdamjan/9f3e4a4016459d3e12f576ec0813c785.git demo-portable-service-nix

# run an interactive container
podman run -ti --rm \
  -v $PWD/demo-portable-service-nix/:/work \
  -e NIX_PATH=nixpkgs=channel:nixos-unstable \
  nixos/nix:latest

# inside the container:
nix-build /work/default.nix
ls result/
sha256sum result/demo_1.0.raw

you should get 93e80c095771dd2e2c45a5755d037ae27e0e15025b41e2c0ba7d08b49bf14181 result/demo_1.0.raw

then, the built image can be run on any Linux with systemd>=240:

sudo portablectl attach --now --runtime $PWD/demo_1.0.raw

(moving the image from one place to another is outside the scope of this gist 🙂)

pkgs.portableService was implemented in NixOS/nixpkgs#161278 and should become available in NixOS 22.11 (in the meanwhile it's available in the nixos-unstable channel)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment