about summary refs log tree commit diff
path: root/bin/run-guix-container.rb
blob: c2d968996ee9a5ed61fcc7cb6d3ff9933b78cf4a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
#!/usr/bin/env ruby
# run-guix-container.rb
#
# Start (or stop) a Guix system container by its store hash.
#
#   ./run-guix-container.rb HASH                # find + run the container
#   ./run-guix-container.rb /gnu/store/HASH-...  # or a full store path
#   ./run-guix-container.rb --kill PID           # stop a running container
#   ./run-guix-container.rb --list               # list running containers
#   ./run-guix-container.rb --fingerprint v0.1   # verify the daemon first
#
# The script validates that:
#   * the hash looks like a valid base32 Guix store hash (32 chars)
#   * exactly one matching, executable container script exists in the store
#   * the script is a Guix container launcher (uses linux-container)
#
# It then starts the container in one of two ways:
#
# 1. Network API: if --daemon HOST:PORT (or GUIX_CONTAINER_DAEMON) is
#    given, it sends 'START <hash>' to a run-guix-system-container
#    --serve daemon on the underlying host, which validates and starts
#    the container with root privileges.  With --fingerprint WORD the
#    daemon's fingerprint is checked first (FINGERPRINT command), so
#    you never talk to a stale daemon by accident.
# 2. Local sudo: otherwise it invokes sudo run-guix-system-container,
#    which performs the same validation locally.

STORE = '/gnu/store'
LAUNCHER = 'run-guix-system-container'
DEFAULT_DAEMON = '127.0.0.1:8989'
HASH_RE = /\A[0-9a-z]{32}\z/

def fail(msg)
  warn "error: #{msg}"
  exit 1
end

require 'socket'

def talk_to_daemon(daemon, request)
  host, port = daemon.split(':', 2)
  fail "invalid daemon address: #{daemon}" if host.nil? || port.nil?
  sock = TCPSocket.new(host, Integer(port))
  sock.puts request
  response = sock.gets.to_s.strip
  sock.close
  response
end

# Like talk_to_daemon, but reads the whole (possibly multi-line)
# response — used for LOG, whose body follows the OK line.
def fetch_from_daemon(daemon, request)
  host, port = daemon.split(':', 2)
  fail "invalid daemon address: #{daemon}" if host.nil? || port.nil?
  sock = TCPSocket.new(host, Integer(port))
  sock.puts request
  sock.read
ensure
  sock&.close
end

# Ask the daemon for its fingerprint and compare it with EXPECTED.
# Returns the daemon's fingerprint; fails on mismatch or protocol error.
def verify_fingerprint(daemon, expected)
  response = talk_to_daemon(daemon, 'FINGERPRINT')
  fail "daemon fingerprint query failed: #{response}" unless response.start_with?('OK ')
  got = response.split(' ', 2)[1].to_s
  fail "daemon fingerprint mismatch: expected #{expected}, got #{got}" unless got == expected
  got
end

arg = nil
kill_pid = nil
log_arg = nil
list = nil
fingerprint = nil
daemon = ENV['GUIX_CONTAINER_DAEMON']

while !ARGV.empty? && ARGV[0].start_with?('--')
  case ARGV[0]
  when '--daemon'
    daemon = ARGV[1]
    ARGV.shift(2)
  when '--kill'
    kill_pid = ARGV[1]
    ARGV.shift(2)
  when '--list'
    list = true
    ARGV.shift
  when '--log'
    log_arg = ARGV[1]
    ARGV.shift(2)
  when '--fingerprint'
    fingerprint = ARGV[1]
    ARGV.shift(2)
  when '--daemon-local'
    daemon ||= DEFAULT_DAEMON
    ARGV.shift
  else
    fail "unknown option: #{ARGV[0]}"
  end
end
arg = ARGV[0]

# --list: show the containers the daemon has running.
if list
  fail '--list requires a daemon (--daemon HOST:PORT)' unless daemon
  verify_fingerprint(daemon, fingerprint) if fingerprint
  out = fetch_from_daemon(daemon, 'LIST')
  fail "daemon refused: #{out.lines.first&.strip}" unless out.start_with?("OK\n")
  print out.split("\n", 2)[1].to_s
  exit 0
end

# --log HASH: fetch and print a container's log from the daemon.
if log_arg
  fail "--log requires a daemon (--daemon HOST:PORT)" unless daemon
  verify_fingerprint(daemon, fingerprint) if fingerprint
  hash = log_arg.start_with?(STORE + '/') ? File.basename(log_arg).split('-', 2).first : log_arg
  fail "not a valid store hash: #{hash}" unless hash =~ HASH_RE
  out = fetch_from_daemon(daemon, "LOG #{hash}")
  fail "daemon refused: #{out.lines.first&.strip}" unless out.start_with?("OK\n")
  print out.split("\n", 2)[1].to_s
  exit 0
end

# --kill PID: ask the daemon to terminate a container.
if kill_pid
  fail "--kill requires a daemon (--daemon HOST:PORT)" unless daemon
  verify_fingerprint(daemon, fingerprint) if fingerprint
  fail "invalid pid: #{kill_pid}" unless kill_pid =~ /\A\d+\z/
  response = talk_to_daemon(daemon, "KILL #{kill_pid}")
  puts response
  fail "daemon refused: #{response}" unless response.start_with?('OK ')
  exit 0
end

fail 'usage: run-guix-container.rb [--daemon HOST:PORT] HASH|/gnu/store/HASH-...' if arg.nil?

hash =
  if arg.start_with?(STORE + '/')
    File.basename(arg).split('-', 2).first
  else
    arg
  end

fail "not a valid store hash: #{hash}" unless hash =~ HASH_RE

# Collect all store entries starting with the hash. A valid nix-base32
# hash is 32 chars, so no other store item can share the prefix.
entries = Dir.glob(File.join(STORE, "#{hash}-*")).sort
fail "no store item found for hash #{hash}" if entries.empty?

# Only keep real files (the container launcher), not .drv or directories.
candidates = entries.select do |path|
  File.file?(path) && File.executable?(path) && !path.end_with?('.drv')
end
fail "hash #{hash} matches no executable store item" if candidates.empty?
fail "hash #{hash} is ambiguous: #{candidates.join(' ')}" if candidates.size > 1

container = candidates.first

# Sanity check: it must be a Guix container launcher script (it uses the
# (gnu build linux-container) module to set up namespaces).
head = File.open(container, 'rb') { |f| f.read(4096) }
fail "#{container} is not a Guix container script" unless head.include?('linux-container')

# Start the container.
if daemon
  fp = verify_fingerprint(daemon, fingerprint) if fingerprint
  puts "Starting container #{hash} via daemon #{daemon}" +
       (fp ? " (fingerprint #{fp})" : '')
  response = talk_to_daemon(daemon, "START #{hash}")
  puts response
  fail "daemon refused: #{response}" unless response.start_with?('OK ')
  pid = response.split[1]
  puts "Container running as PID #{pid}; inspect with:"
  puts "  nsenter -at #{pid} /run/current-system/profile/bin/bash --login"
  exit 0
end

# Local sudo path: the privileged launcher must be installed in PATH
# (in a root-owned directory such as /usr/local/bin, see README).
launcher = ENV.fetch('PATH', '').split(File::PATH_SEPARATOR)
               .map { |d| File.join(d, LAUNCHER) }
               .find { |p| File.file?(p) && File.executable?(p) }
fail "launcher not found in PATH: #{LAUNCHER} (see README)" unless launcher

puts "Starting container: #{container}"
exec 'sudo', '--', launcher, container
fail "exec failed for #{container}"