aboutsummaryrefslogtreecommitdiff
path: root/buildos
blob: e9c6acda4131d7129f3e86c127df50b55321172c (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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
#!/bin/bash

# Build OS monitor. It starts as a systemd service and performs the following
# steps:
#
# 1. Bootstrap the build2 toolchain.
# 2. Build and start bbot.
# 3. Build and start bslave.
# 4. Monitor for OS and toolchain changes and reboot if detected.
#

# @@ What will systemd do if we fail? Perhaps configure it to restart
#    us? Or not since we may hose the logs.
#
owd="$(pwd)"
trap "{ cd '$owd'; exit 1; }" ERR
set -o errtrace   # Trap in functions.
shopt -s nullglob # Expand patterns than don't match to empty.

# Note: diagnostics goes to stdout.
#
function info () { echo "$*" 1>&2; }
function error ()
{
  if [ "$#" -gt 0 ]; then
    info "$*";
  fi

  exit 1
}

info "starting build os monitor..."

# Parse the kernel command line. This is complicated by the fact that the
# values can be quoted, for example:
#
# foo='foo fox'
# bar="bar 'box'"
#
# First we separete quoted variables and arguments with newlines (giving
# priority to assignments). Then we replace whitespaces with newline on
# lines that don't contain quites. Finally, clean up by removing blank
# lines.
#
# Note: the same code as in init.
#
readarray -t cmdline < <(cat /proc/cmdline | \
  sed -r -e "s/([^ ]+=)?('[^']*'|\"[^\"]*\")/\n\1\2\n/g" | \
  sed -r -e "/['\"]/!s/ /\n/g" |
  sed -r -e '/^\s*$/d')

# Enter all buildos variables as bash variables.
#

# Map of toolchain names (as specified in buildos.<var>.<name>) to the
# corresponding bash variable prefix.
#
declare -A toolchains
toolchains["default"]=""

for v in "${cmdline[@]}"; do
  var="$(sed -n -re 's/^buildos\.([^=]+)=.*$/\1/p' <<<"$v")" # Extract name.

  if [ -n "$var" ]; then
    val="$(sed -re 's/^[^=]+=(.*)$/\1/' <<<"$v")"            # Extract value.
    val="$(sed -re "s/^('(.*)'|\"(.*)\")$/\2\3/" <<<"$val")" # Strip quoted.

    # If the variable contains a dot, then it is a toolchain variable.
    #
    if [[ "$var" == *.* ]]; then
      tn="$(sed -re 's/^[^.]+\.(.+)$/\1/' <<<"$var")"
      var="${tn}_$(sed -re 's/^([^.]+)\..+$/\1/' <<<"$var")"
      toolchains["$tn"]="${tn}_"
    fi

    declare "$var=$val"
  fi
done

hname="$(hostname)"

# Get the build id.
#
buildid="$(sed -n -re 's/^BUILD_ID="(.+)"$/\1/p' /etc/os-release)"

function email () # <subject> < <body>
{
  (echo -e "Subject: [$hname] $1\n"; cat -) | sendmail -i "$admin_email"
}

function restart ()
{
  sendmail -q # Flush mail queue.
  sleep 10    # Give any remaining mail chance to go through.
  sudo systemctl reboot
}

# Toolchain-related funtions.
#

# Return the value of one of the toolchain_* variables for this toolchain.
#
function tc_value () # <toolchain-prefix> <variable>
{
  local n="${1}${2}"
  echo "${!n}"
}

# Calculate the file checksum using the shaNNNsum utility.
#
function tc_checksum () # <toolchain-prefix> <file>
{
  "$(tc_value "$1" toolchain_csum)sum" -b "$2" | \
    sed -n -re 's/^([^ ]+) .+$/\1/p'
}

# Fetch a file from the sums file into $toolchain_root, verify its checksum,
# and make a predictable name (without version) symlink.
#
function tc_fetch () # <toolchain-prefix> <line>
{
  local s p f u l tp tu tr tv

  tp="$1"
  tu="$(tc_value "$tp" toolchain_url)"
  tr="$(tc_value "$tp" toolchain_root)"

  s="$(sed -n -re 's/^([^ ]+) .+$/\1/p' <<<"$2")"       # Checksum.
  p="$(sed -n -re 's/^[^ ]+ \*([^ ]+)$/\1/p' <<<"$2")"  # File path (relative).
  f="$(sed -n -re 's%^(.+/)?([^/]+)$%\2%p' <<<"$p")"    # File name.
  u="$(sed -n -re 's%^(.+)/[^/]+$%\1%p' <<<"$tu")/$p"   # File URL.

  if [ -z "$s" -o -z "$p" -o -z "$f" -o -z "$u" ]; then
    info "invalid sum line '$2'"
    return 1
  fi

  # Extract the version.
  #
  tv="$(tc_value "$tp" toolchain_ver)"

  if [ -z "$tv" ]; then
    tv="$(sed -n -re 's/build2-toolchain-(.+)\.tar.*/\1/p' <<<"$f")"

    if [ -z "$tv" ]; then
      info "unable to extract toolchain version from '$f'"
      return 1
    fi

    declare -g "${tp}toolchain_ver=$tv"

    info "toolchain version $tv"
    echo "$tv" >"$tr/version"
  fi

  # Derive a predictable name link.
  #
  l="$(sed -n -re "s/^(.+)-$tv(.*)$/\1\2/p" <<<"$f")"

  if [ -z "$l" ]; then
    info "unable to derive predicatable name from '$f' and '$tv'"
    return 1
  fi

  # Fetch the file.
  #
  info "fetching $u [$l]"

  if ! curl -f -L -s -S -o "$tr/$f" "$u"; then
    info "unable to fetch $u"
    return 1
  fi

  # Verify the checksum.
  #
  info "verifying checksum for $f"

  local cs
  cs="$(tc_checksum "$tp" "$tr/$f")"

  if [ "$cs" != "$s" ]; then
    info "checksum mismatch for $u"
    info "  expected:   $s"
    info "  calculated: $cs"
    return 1
  fi

  # Make the link.
  #
  ln -s "$f" "$tr/$l"
}

# Bootstrap the toolchain.
#
function tc_bootstrap () # <toolchain-name>
{
  local tn="$1"
  local tp="${toolchains["$tn"]}"
  local tr="$(tc_value "$tp" toolchain_root)"
  local tf="$(tc_value "$tp" toolchain_file)"

  # Fetch files according to the sums file. Skip empty lines and those that
  # start with '#'.
  #
  local l ls=()

  readarray -t ls < <(sed -e '/^\s*#/d;/^\s*$/d' "$tr/$tf")

  for l in "${ls[@]}"; do
    if ! tc_fetch "$tp" "$l"; then
      return 1 # Diagnostics has already been issued.
    fi
  done

  local tv="$(tc_value "$tp" toolchain_ver)"   # Should be set by tc_fetch().
  local tt="$(tc_value "$tp" toolchain_trust)"

  # Bootstrap in /tmp/toolchains/$tn/, install to /build/toolchains/$tn/.
  #
  local wd="/tmp/toolchains/$tn"
  local id="/build/toolchains/$tn"

  mkdir -p "$wd"
  mkdir -p "$id"

  local r=1

  cd "$wd"
  while true; do # The "breakout loop".

    # Extract the toolchain.
    #
    if ! tar -xf "$tr/build2-toolchain.tar.xz"; then
      info "unable to extract $tr/build2-toolchain.tar.xz"
      break
    fi

    cd "build2-toolchain-$tv"

    # Bootstrap, stage, and install using the provided build.sh script.
    #
    if ! ./build.sh --install-dir "$id" --trust "$tt" g++; then
      info "failed to build $(pwd)"
      break
    fi

    r=0
    break
  done
  cd "$owd"

  # Clean up.
  #
  rm -r "$wd"

  return "$r"
}

# Print monitor configuration as email body.
#
function print ()
{
  echo "buildid:       $buildid"
  echo "buildid_url:   $buildid_url"
  echo

  for tn in "${!toolchains[@]}"; do
    tp="${toolchains["$tn"]}"
    tu="$(tc_value "$tp" toolchain_url)"

    if [ -z "$tu" ]; then
      continue
    fi

    tt="$(tc_value "$tp" toolchain_trust)"

    echo "$tn.toolchain_url:   $tu"
    echo "$tn.toolchain_trust: $tt"
    echo
  done
}

print | email "starting build os monitor"

if [ -z "$buildid_url" ]; then
  info "no buildos.buildid_url specified, not monitoring for new os builds"
fi

tc=
for tn in "${!toolchains[@]}"; do
  tp="${toolchains["$tn"]}"
  tu="$(tc_value "$tp" toolchain_url)"

  if [ -z "$tu" ]; then
    continue
  fi

  tc="true"

  # The toolchain "sums" file (a list of SHA sums and relative file names, as
  # produced by shaNNNsum). The first entry should always be build2-toolchain
  # tar archive itself (which we use to figure out the version). Blank lines
  # and lines that start with '#' are ignored.
  #
  tf="$(sed -n -re 's%^.+/([^/]+)$%\1%p' <<<"$tu")"

  declare "${tp}toolchain_file=$tf"
  declare "${tp}toolchain_csum=$(sed -n -re 's%^.+\.([^.]+)$%\1%p' <<<"$tf")"
  declare "${tp}toolchain_root=/build/tftp/toolchains/$tn"
  declare "${tp}toolchain_ver="

  # If buildos.toolchain_trust was not specified, set it to "no" so that
  # we don't prompt if the repository happens to be signed.
  #
  if [ -z "$(tc_value "$tp" toolchain_trust)" ]; then
    declare "${tp}toolchain_trust=no"
  fi
done

if [ -z "$tc" ]; then
  info "no buildos.toolchain_url specified, not bootstrapping"
fi

# Cleanup /build/machines/ of any stray snapshots or deleted machines.
#
diag=()
fail=
for v in /build/machines/*; do
  if [ ! -d "$v" ]; then
    diag+=("$v: error: invalid volume")
    fail="true"
    continue
  fi

  cd "$v"

  for m in *; do
    if [ ! -d "$m" ]; then
      diag+=("$v/$m: error: invalid machine")
      fail="true"
      continue
    fi

    cd "$m"

    # Collect current machine symlink's bootstrap protocol numbers. If there
    # are no current machine symlinks, then we delete the whole thing.
    #
    ps=()
    for s in "$m"-*; do
      if [[ "$s" =~ ^"$m"-[0-9]+$ ]]; then

	if [ ! -L "$s" ]; then
	  diag+=("$v/$m/$s: error: not a symlink")
	  fail="true"
	fi

	# Treat it as if it were a symlink even if its not. Failed that we
	# may try to delete the whole thing.
	#
	ps+=("$(sed -n -re 's/^.+-([0-9]+)$/\1/p' <<<"$s")")
      fi
    done

    # Examine each machine subvolume.
    #
    for s in "$m"-*; do

      # <name>-<P> (current machine symlink)
      #
      if [[ "$s" =~ ^"$m"-[0-9]+$ ]]; then
	continue
      fi

      if [ ! -d "$s" ]; then
	diag+=("$v/$m/$s: error: invalid machine subvolume")
	fail="true"
	continue
      fi

      # Unless we are deleting the whole thing, keep initial and bootstrapped
      # (for known toolchains) subvolumes.
      #
      if [ "${#ps[@]}" -gt 0 ]; then

	# <name>-<P>.<R> (initial image)
	#
	f=
	for p in "${ps[@]}"; do
	  if [[ "$s" =~ ^"$m"-"$p"\.[0-9]+$ ]]; then
	    f="true"
	    break
	  fi
	done

	if [ -n "$f" ]; then
	  continue
	fi

	# <name>-<toolchain> (bootstrapped image)
	#
	f=
	for tn in "${!toolchains[@]}"; do
	  if [[ "$s" =~ ^"$m"-"$tn"$ ]]; then
	    f="true"
	    break
	  fi
	done

	if [ -n "$f" ]; then
	  continue
	fi
      fi

      # This is either a stray working submodule or a bootsrapped subvolume
      # for a toolchain that was deleted (or we are deleting everything).
      #
      if ! btrfs property set -ts "$s" ro false; then
	diag+=("$v/$m/$s: error: unable to change subvolume property")
	fail="true"
	continue
      fi

      if ! btrfs subvolume delete "$s"; then
	diag+=("$v/$m/$s: error: unable to delete subvolume")
	fail="true"
	continue
      fi

      diag+=("$v/$m/$s: info: deleted subvolume")
    done

    cd "$v"

    # Delete the machine directory (which we expect to be now empty).
    #
    if [ "${#ps[@]}" -eq 0 ]; then
      if ! rmdir "$m"; then
	diag+=("$v/$m: error: unable to delete machine directory")
	fail="true"
	continue
      fi

      diag+=("$v/$m: info: deleted machine directory")
    fi
  done
  cd "$owd"
done

function print_diag ()
{
  local p
  for p in "${diag[@]}"; do
    echo "  $p"
  done
}

if [ "${#diag[@]}" -gt 0 ]; then
  if [ -z "$fail" ]; then
    s="cleaned up entries in /build/machines/"
  else
    s="invalid entries in /build/machines/, halting"
  fi

  print_diag | email "$s"
  info "$s" && print_diag 2>&1

  if [ -n "$fail" ]; then
    info "correct and restart the monitor (systemctl restart buildos)"
    exit 1
  fi
fi

# Monitoring loop.
#
while true; do

  # Check for toolchain changes. If this is the first run, bootstrap them.
  #
  for tn in "${!toolchains[@]}"; do
    tp="${toolchains["$tn"]}"
    tu="$(tc_value "$tp" toolchain_url)"

    if [ -z "$tu" ]; then
      continue
    fi

    tr="$(tc_value "$tp" toolchain_root)"
    tf="$(tc_value "$tp" toolchain_file)"
    p="$tr/$tf"

    mkdir -p "$tr"

    # Fetch the toolchain sums either to $p if this is the first time or to
    # $p.new if we are checking for changes.
    #
    if [ -e "$p" ]; then
      f="$p.new"
    else
      f="$p"
    fi

    if curl -f -L -s -S -o "$f" "$tu"; then

      # Take care of change detection.
      #
      if [ "$f" != "$p" ]; then

	ts="$(tc_value "$tp" toolchain_file_csum)"
	cs="$(tc_checksum "$tp" "$f")"

	if [ "$ts" != "$cs" ]; then
	  email "rebooting because of new $tn toolchain" <<EOF
old_checksum: $ts
new_checksum: $cs
EOF
	  info "new $tn toolchain ($cs), rebooting..."
	  restart
	fi
      else
	# This is the first run, bootstrap the toolchain.
	#
	declare "${tp}toolchain_file_csum=$(tc_checksum "$tp" "$f")"

	# If we fail, we simply wait for a new toolchain to be uploaded (or
	# some manual intervention).
	#
	# Note that because of the pipe tc_bootstrap() will run in subshell
	# and any variables it sets (like toolchain_ver) won't be visible to
	# us.
	#
	info "bootstrapping $tn toolchain..."

	tc_bootstrap "$tn" 2>&1 | tee "$tr/bootstrap.log" 1>&2

	if [ "${PIPESTATUS[0]}" -eq 0 ]; then
	  v="$(cat $tr/version)"
	  declare "${tp}toolchain_ver=$v"

	  s="bootstrapped $tn toolchain $v"
	else
	  s="failed to bootstrap $tn toolchain, waiting for new version"
	fi

	info "$s"
	email "$s" <<EOF
$tn.bootstrap_log: tftp://$hname/toolchains/$tn/bootstrap.log
EOF
      fi
    else
      info "unable to fetch $tu, will try again"
      rm -f "$f"
    fi
  done

  # Check for OS changes.
  #
  if [ -n "$buildid_url" ]; then
    # Fetch the current id. While normally it will be a TFTP URL, it could also
    # be HTTP(S) so we configure sensible behavior for that.
    #
    if id="$(curl -f -L -s -S "$buildid_url")"; then
      if [ "$id" != "$buildid" ]; then
	email "rebooting because of new os build" <<EOF
old_buildid: $buildid
new_buildid: $id
EOF
	info "new os build ($id), rebooting..."
	restart
      fi
    else
      info "unable to fetch $buildid_url, will try again"
    fi
  fi

  info "monitoring..."
  sleep 10
done