aboutsummaryrefslogtreecommitdiff
path: root/buildos
blob: 52e984e120074603c2c1c67fe62bdbde99d3f99b (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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
#!/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
}

# Network timeouts: 60 seconds to connect, 10 minutes to complete, 4 retries
# (5 attempts total). These are similar to bbot timeouts. Note that the
# toolchain archives can be quite sizable.
#
timeout=600

curl=(curl -f -L -s -S         \
  --retry           4          \
  --retry-max-time  "$timeout" \
  --max-time        "$timeout" \
  --connect-timeout 60)

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, we 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.

    # Recognize some variables as arrays.
    #
    a=

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

      if [ "$var" = "controller_url" -o "$var" = "controller_trust" ]; then
	a=true
      fi

      var="${tn}_$var"
      toolchains["$tn"]="${tn}_"
    fi

    if [ -n "$a" ]; then
      declare -a "$var+=('$val')"
    else
      declare "$var=$val"
    fi
  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
}

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

# Process toolchains.
#

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

instances=0        # Number of bbot instances across all toolchains.
toolchain_names=()

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

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

  toolchain_names+=("$tn")

  # 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="
  declare "${tp}toolchain_fver=" # Full version (with snapshot).

  # Default to 1 bbot agent instance.
  #
  if [ -z "$(toolchain_value "$tp" instances)" ]; then
    declare "${tp}instances=1"
  fi

  instances=$(($instances + $(toolchain_value "$tp" instances)))

  # Default to 0 nice value.
  #
  if [ -z "$(toolchain_value "$tp" nice)" ]; then
    declare "${tp}nice=0"
  fi

  # Default to br1 (private/NAT bridge).
  #
  if [ -z "$(toolchain_value "$tp" bridge)" ]; then
    declare "${tp}bridge=br1"
  fi

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

  # Warn if we have no controller URLs for this toolchain.
  #
  n="${tp}controller_url[0]"
  if [ -z "${!n}" ]; then
    info "no buildos.controller_url.$tn specified, not starting bbot agent"
  fi
done

if [ "${#toolchain_names[@]}" -eq 0 ]; then
  info "no buildos.toolchain_url specified, not bootstrapping"
fi

# Divide CPUs and RAM (in KB) among the instances.
#
# By default reserve 4G of RAM for ourselves (rootfs, tmpfs).
#
# Note that MemTotal in /proc/meminfo is the available memory, not physical.
# And to make it easier to provision memory it's really helpful to base it
# in the physical value.
#
ram_total=0
for i in $(sudo dmidecode -t 17 | sed -n -re 's/^\s*Size:\s*([0-9]+)\s*MB.*$/\1/p'); do
  ram_total=$(($ram_total + $i * 1024))
done

if [ "$ram_total" -eq 0 ]; then
  error "unable to determine physical memory size"
fi

cpu_total="$(lscpu | sed -n -re 's/^CPU\(s\): *([0-9]+)$/\1/p')"

if [ -z "$ram_reserved" ]; then
  ram_reserved=4
fi
ram_reserved=$(($ram_reserved * 1024 * 1024))

if [ -z "$ram_overcommit" ]; then
  ram_overcommit=1
fi

if [ -z "$cpu_reserved" ]; then
  cpu_reserved=0
fi

if [ -z "$cpu_overcommit" ]; then
  cpu_overcommit=1
fi

ram_slice=$(($ram_total - $ram_reserved))
cpu_slice=$(($cpu_total - $cpu_reserved))

if [ "$instances" -gt 1 ]; then
  ram_slice=$(($ram_slice * $ram_overcommit / $instances))
  cpu_slice=$(($cpu_slice * $cpu_overcommit / $instances))

  if [ "$cpu_slice" -eq 0 ]; then
    cpu_slice=1
  fi
fi

# Print monitor configuration as email body.
#
function print ()
{
  echo "cpu_total:      $cpu_total"
  echo "cpu_reserved:   $cpu_reserved"
  echo "cpu_overcommit: $cpu_overcommit"
  echo "cpu_slice:      $cpu_slice"
  echo

  echo "ram_total:      $ram_total KB"
  echo "ram_reserved:   $ram_reserved KB"
  echo "ram_overcommit: $ram_overcommit"
  echo "ram_slice:      $ram_slice KB"
  echo

  echo "buildid:        $buildid"
  echo "buildid_url:    $buildid_url"
  echo

  local n i tn tp tu tt
  for tn in "${toolchain_names[@]}"; do
    tp="${toolchains["$tn"]}"
    tc="$(toolchain_value "$tp" nice)"
    tb="$(toolchain_value "$tp" bridge)"
    ti="$(toolchain_value "$tp" instances)"
    tu="$(toolchain_value "$tp" toolchain_url)"
    tt="$(toolchain_value "$tp" toolchain_trust)"

    echo "$tn.nice:              $tc"
    echo "$tn.bridge:            $tb"
    echo "$tn.instances:         $ti"
    echo "$tn.toolchain_url:     $tu"
    echo "$tn.toolchain_trust:   $tt"

    n="${tp}controller_url[@]"
    for i in "${!n}"; do
      echo "$tn.controller_url:    $i"
    done

    n="${tp}controller_trust[@]"
    for i in "${!n}"; do
      echo "$tn.controller_trust:  $i"
    done

    echo
  done

  echo "host key:"
  echo

  openssl rsa -pubout -in /state/etc/host-key.pem 2>/dev/null
}

print | email "starting build os monitor"

# Machines cleanup (/build/machines/).
#
diag=()
fail=

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

# Iterate over all the machines and call a function (one of the below
# machines_clean_*()) for each.
#
function machines_for () # <function> <function-args>...
{
  local f="$1"
  shift

  diag=()
  fail=

  local v m
  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

      "$f" "$v" "$m" "$@"

    done

    cd "$owd"
  done
}

function machines_clean_subvolume () # <subvolume-path>
{
  if ! btrfs property set -ts "$1" ro false; then
    diag+=("$1: error: unable to change subvolume property")
    fail=true
    return 1
  fi

  if ! btrfs subvolume delete "$1"; then
    diag+=("$1: error: unable to delete subvolume")
    fail=true
    return 1
  fi
}

function machines_clean_lockfile () # <lockfile-path>
{
  if ! rm -f "$1"; then
    diag+=("$1: error: unable to delete lockfile")
    fail=true
    return 1
  fi
}

# Cleanup the <name>-<toolchain>-<xxx> entries for the specified toolchain
# (all instances) as well as <name>-<toolchain>.lock file. Called before
# starting bbot instances for each toolchain.
#
function machines_clean_toolchain () # <volume-dir> <machine> <toolchain>
{
  local v="$1"
  local m="$2"
  local tn="$3"

  cd "$m"

  local i
  for i in "$m"-"$tn"-*; do

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

    if machines_clean_subvolume "$v/$m/$i"; then
      diag+=("$v/$m/$i: info: deleted stray toolchain working subvolume")
    fi
  done

  i="$m-$tn.lock"
  if [ -f "$i" ]; then

    if machines_clean_lockfile "$v/$m/$i"; then
      diag+=("$v/$m/$i: info: deleted stray lockfile")
    fi
  fi

  cd "$v"
}

# Cleanup stray snapshots and lockfiles as well as deleted machines. Called
# once during startup.
#
function machines_clean_stray () # <volume-dir> <machine>
{
  local v="$1"
  local m="$2"

  cd "$m"

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

      if [ ! -L "$i" ]; then
	diag+=("$v/$m/$i: 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' <<<"$i")")
    fi
  done

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

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

    # Lockfile.
    #
    if [ -f "$i" ]; then

      if [[ "$i" =~ ^"$m"-.+\.lock$ ]]; then

	if machines_clean_lockfile "$v/$m/$i"; then
	  diag+=("$v/$m/$i: info: deleted lockfile")
	fi
	continue
      fi
    fi

    if [ ! -d "$i" ]; then
      diag+=("$v/$m/$i: 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)
      #
      local p f=
      for p in "${ps[@]}"; do
	if [[ "$i" =~ ^"$m"-"$p"\.[0-9]+$ ]]; then
	  f=false
	  break
	fi
      done

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

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

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

    # This is either a stray working subvolume or a bootsrapped subvolume
    # for a toolchain that was deleted (or we are deleting everything).
    #
    if machines_clean_subvolume "$v/$m/$i"; then
      diag+=("$v/$m/$i: info: deleted subvolume")
    fi
  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: info: deleted machine directory")
    else
      diag+=("$v/$m: error: unable to delete machine directory")
      fail=true
    fi
  fi
}

# Do the initial cleanup.
#
machines_for machines_clean_stray

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 1>&2

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

# Toolchain-related funtions.
#

# Calculate the file checksum using the shaNNNsum utility.
#
function toolchain_checksum () # <toolchain-prefix> <file>
{
  "$(toolchain_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 toolchain_fetch () # <toolchain-name> <line>
{
  local s p f u l tn tp tu tr tv

  tn="$1"
  tp="${toolchains["$tn"]}"
  tu="$(toolchain_value "$tp" toolchain_url)"
  tr="$(toolchain_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 and derive a predictable name link.
  #
  tv="$(toolchain_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

    info "toolchain $tn version $tv"

    declare -g "${tp}toolchain_fver=$tv" # Full version.
    echo "$tv" >"$tr/version-full"
    l="$(sed -n -re "s/^(.+)-$tv(.*)$/\1\2/p" <<<"$f")" # Use full version.

    # Strip snapshot.
    #
    tv="$(sed -n -re 's/^([^.]+\.[^.]+\.[^-]+(-[ab]\.[^.+]+)?).*/\1/p' <<<"$tv")"

    declare -g "${tp}toolchain_ver=$tv"
    echo "$tv" >"$tr/version"
  else
    # For files other that build2-toolchain we expect the version component to
    # be in the <ver>[-<name>] form, for example 1.2.3-stage.
    #
    l="$(sed -n -re "s/^(.+)-$tv(-$tn)?(.*)$/\1\3/p" <<<"$f")"
  fi

  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[@]}" -o "$tr/$f" "$u"; then
    info "unable to fetch $u"
    return 1
  fi

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

  local cs
  cs="$(toolchain_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.
  #
  # Note that the target must be just the file for TFTP chroot to work.
  #
  ln -s "$f" "$tr/$l"
}

# Bootstrap the toolchain.
#
# Return 0 on success, 1 if the toolchain is disabled, and 2 in case of
# an error.
#
function toolchain_bootstrap () # <toolchain-name>
{
  local tn="$1"
  local tp="${toolchains["$tn"]}"
  local tr="$(toolchain_value "$tp" toolchain_root)"
  local tf="$(toolchain_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")

  if [ "${#ls[@]}" -eq 0 ]; then
    info "empty $tr/$tf"
    return 2
  fi

  # Check if this toolchain is disabled.
  #
  if [ "${ls[0]}" = "disabled" ]; then
    return 1
  fi

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

  local tv="$(toolchain_value "$tp" toolchain_fver)" # Set by fetch().
  local tt="$(toolchain_value "$tp" toolchain_trust)"

  # Save the repository certificate fingerprint into the trust file (used
  # by machine bootstrap).
  #
  echo "$tt" >"$tr/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=2

  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. Do
    # parallel bootstrap using make.
    #
    if ! ./build.sh --make make           \
	            --make "-j$cpu_total" \
	            --timeout "$timeout"  \
	            --install-dir "$id"   \
	            --trust "$tt"         \
		    g++; then
      info "failed to build $(pwd)"
      break
    fi

    cd "$wd"
    rm -r "build2-toolchain-$tv"*/
    mv -T build2-toolchain-* build2-toolchain # Strip version.

    r=0
    break
  done
  cd "$owd"

  return "$r"
}

# Check if we need to build/start or rebuild/restart the bbot agent. Return
# 0 if nothing to do, 1 for upgrades, 2 for first build, and 3 for failure.
#
function bbot_check () # <toolchain-name>
{
  local tn="$1"

  export PATH="/build/toolchains/$tn/bin:$PATH" # Running in subshell.

  cd "/tmp/toolchains/$tn/build2-toolchain"

  local r=3

  local l_stat b_stat
  while true; do # The "breakout loop".

    l_stat="$(bpkg status libbbot)"
    b_stat="$(bpkg status bbot)"

    if ! bpkg --fetch-timeout "$timeout" fetch -q; then
      info "failed to fetch package information"
      break
    fi

    # See if this is the first time or if we need to upgrade.
    #
    if [ "$(cut -d ' ' -f 2 <<<"$b_stat")" = "configured" ]; then

      # We assume that if anything has changed in the status line, then we
      # have a new version.
      #
      if [ "$b_stat" = "$(bpkg status bbot)" -a \
           "$l_stat" = "$(bpkg status libbbot)" ]; then
	r=0
	break
      fi

      r=1
      break
    fi

    r=2
    break
  done
  cd "$owd"

  return "$r"
}

# Build and start bbot agent using the bpkg configuration created by
# toolchain_bootstrap().
#
function bbot_start () # <toolchain-name> <toolchain-index>
{
  local tn="$1"
  local tx="$2"

  local tp="${toolchains["$tn"]}"
  local tc="$(toolchain_value "$tp" nice)"
  local tb="$(toolchain_value "$tp" bridge)"
  local ti="$(toolchain_value "$tp" instances)"
  local tv="$(toolchain_value "$tp" toolchain_fver)"
  local ts="$(toolchain_value "$tp" toolchain_file_csum)"

  local id="/build/bots/$tn"
  mkdir -p "$id"

  # Install/uninstall vars.
  #
  local vars=(config.install.root="$id" config.bin.rpath="$id/lib")

  export PATH="/build/toolchains/$tn/bin:$PATH" # Running in subshell.

  cd "/tmp/toolchains/$tn/build2-toolchain"

  local r=1

  local i n b_word
  while true; do # The "breakout loop".

    b_word="$(bpkg status bbot | cut -d ' ' -f 2)"

    # If upgrading, stop the service and uninstall.
    #
    if [ "$b_word" = "configured" ]; then

      for ((i=1; i <= ti; i++)); do
	if ! sudo systemctl stop "bbot-agent-$tn@$i"; then
	  info "failed to stop bbot-agent-$tn@$i service, assuming not running"
	  continue
	fi
	info "stopped bbot-agent-$tn@$i service"
      done

      # We may not be able to uninstall if we previously failed to build.
      #
      if ! bpkg uninstall "${vars[@]}" bbot; then
	info "failed to uninstall bbot agent, assuming not installed"
      fi
    fi

    # Build and install the bbot agent. Since other agents might already be
    # running, limit the number of jobs to our slice.
    #
    if ! bpkg --fetch-timeout "$timeout" \
	      --build-option --jobs=$(($ti * $cpu_slice)) \
	      build --yes libbbot bbot; then
      info "failed to build bbot-agent for $tn"
      break
    fi

    if ! bpkg install "${vars[@]}" bbot; then
      info "failed to install bbot-agent for $tn"
      break
    fi

    # Post-process and install the systemd .service file. Since we may have
    # multiple toolchains, we embed the toolchain name into the service name
    # with the systemd pattern machinery used to run multiple bbot instances
    # per toolchain.
    #
    # We assume `%I` is only used in Description and similar and rewrite it
    # as `<name>/%i` (e.g., `stage/1`).
    #
    sed -i -r \
	-e "s#%I#$tn/%I#g" \
	-e "s/^(Environment=CPU)=.*/\1=$cpu_slice/" \
	-e "s/^(Environment=RAM)=.*/\1=$ram_slice/" \
	-e "s/^(Environment=BRIDGE)=.*/\1=$tb/" \
	-e "s#^(Environment=AUTH_KEY)=.*#\1=/state/etc/host-key.pem#" \
	-e "s/^(Environment=TOOLCHAIN_ID)=.*/\1=$ts/" \
	-e "s/^(Environment=TOOLCHAIN_NUM)=.*/\1=$tx/" \
	-e "s/^(Environment=TOOLCHAIN_VER)=.*/\1=$tv/" \
	-e "s/^(Environment=TOOLCHAIN_NAME)=.*/\1=$tn/" \
	-e "s/^(Nice)=.*/\1=$tc/" \
	-e "s#^ExecStart=[^ ]+(.*)#ExecStart=$id/bin/bbot-agent\1#" \
	"$id/lib/systemd/system/bbot-agent@.service"

    # Patch in the controller URLs. These can contain special characters
    # like `&` so we have to escape them.
    #
    n="${tp}controller_url[@]"
    for i in "${!n}"; do
      i="$(sed -e 's/[&/\]/\\&/g' <<<"$i")"
      sed -i -r \
          -e "s#^(Environment=\"CONTROLLER_URL=[^\"]*)\"\$#\1 $i\"#" \
	  "$id/lib/systemd/system/bbot-agent@.service"
    done

    # Patch in the controller trust fingerprints.
    #
    n="${tp}controller_trust[@]"
    for i in "${!n}"; do
      sed -i -r \
          -e "s#^(Environment=\"CONTROLLER_TRUST=[^\"]*)\"\$#\1 --trust $i\"#" \
	  "$id/lib/systemd/system/bbot-agent@.service"
    done

    # Note: using a hard link to prevent systemd from being too clever and
    # calling the service bbot-agent@.
    #
    sudo ln -f "$id/lib/systemd/system/bbot-agent@.service" \
      "/usr/lib/systemd/system/bbot-agent-$tn@.service"

    # Clean up any machine snapshots that might have been left behind.
    #
    machines_for machines_clean_toolchain "$tn"

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

      print_diag 1>&2

      if [ -n "$fail" ]; then
	info "correct and start bbot-agent for $tn (systemctl start bbot-agent-$tn@N)"
	break
      fi
    fi

    # Start each service instance. With Type=simple start returns as soon as
    # the process has forked. Making sure the service has actually started is
    # done as part of the service monitoring.
    #
    r=0
    for ((i=1; i <= ti; i++)); do
      if ! sudo systemctl start "bbot-agent-$tn@$i"; then
	info "failed to start bbot-agent-$tn@$i service instance"
	r=1
	break
      fi
    done

    break
  done

  cd "$owd"
  return "$r"
}

# Array of bootstrapped toolchains.
#
# The idea is to collect them until we bootstrap all of them and only then
# start their bbot agents.
#
toolchain_boots=()
declare -A toolchain_cursors # Latest systemd journal cursor.

# Monitoring loop.
#
count=0
while true; do

  count=$(($count + 1))

  # Check for OS changes. Do this first in case of any issues in the following
  # checks.
  #
  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[@]}" "$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

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

    tr="$(toolchain_value "$tp" toolchain_root)"
    tf="$(toolchain_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[@]}" -o "$f" "$tu"; then

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

	ts="$(toolchain_value "$tp" toolchain_file_csum)"
	cs="$(toolchain_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=$(toolchain_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 toolchain_bootstrap() will run in
	# subshell and any variables it sets (like toolchain_ver) won't be
	# visible to us.
	#
	info "bootstrapping $tn toolchain..."

	toolchain_bootstrap "$tn" 2>&1 | tee "$tr/toolchain-$count.log" 1>&2

	case "${PIPESTATUS[0]}" in
	  0)
	    tv="$(cat $tr/version)"
	    declare "${tp}toolchain_ver=$tv"

	    tv="$(cat $tr/version-full)"
	    declare "${tp}toolchain_fver=$tv"

	    s="bootstrapped $tn toolchain $tv"
	    toolchain_boots+=("$tn")
	    ;;
	  1)
	    s="skipping disabled $tn toolchain, waiting for new version"
	    toolchain_boots+=("") # Skip.
	    ;;
	  *)
	    s="failed to bootstrap $tn toolchain, waiting for new version"
	    toolchain_boots+=("") # Skip.
	    ;;
	esac

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

  # If we have boostrapped all the toolchains, (re)build and (re)start their
  # bbot agents and then monitor them.
  #
  if [ "${#toolchain_names[@]}" -eq "${#toolchain_boots[@]}" ]; then

    tx=0 # Toolchain index.
    for tn in "${toolchain_boots[@]}"; do

      tx=$(($tx + 1))

      # Skip those that failed to bootstrap.
      #
      if [ -z "$tn" ]; then
	continue
      fi

      tp="${toolchains["$tn"]}"
      ti="$(toolchain_value "$tp" instances)"
      tr="$(toolchain_value "$tp" toolchain_root)"

      # Or those that have no controllers (maybe it would have been better
      # to build it but not start).
      #
      n="${tp}controller_url[0]"
      if [ -z "${!n}" ]; then
	continue
      fi

      s=
      bbot_check "$tn" 2>&1 | tee "$tr/bbot-agent-$count.log" 1>&2

      case "${PIPESTATUS[0]}" in
	0)
	  rm -f "$tr/bbot-agent-$count.log"

	  # For each service instance check if it has failed.
	  #
	  for ((i=1; i <= ti; i++)); do

	    if sudo systemctl is-failed --quiet "bbot-agent-$tn@$i"; then
	      s="bbot-agent-$tn@$i service has failed, stopping"

	      # Note: ignore errors.
	      #
	      sudo systemctl status "bbot-agent-$tn@$i" 2>&1 | \
		tee "$tr/bbot-agent-$i-$count.log" 1>&2

	      # Reset it so that we don't keep sending the log on each
	      # iteration. Note: ignore errors.
	      #
	      sudo systemctl reset-failed "bbot-agent-$tn@$i" 2>&1 | \
		tee -a "$tr/bbot-agent-$i-$count.log" 1>&2

	      info "$s"
	      email "$s" <<EOF
$tn.bbot_log: tftp://$hname/toolchains/$tn/bbot-agent-$i-$count.log
EOF
	    else
	      # See if there is any diagnostics in the systemd journal. We
	      # notify about warnings and up.
	      #
	      # The old versions journalctl behavior is to not output anything
	      # (not even the cursor) if there are no new entries. The new
	      # versions output the old cursor.
	      #
	      # Plus, it sometimes changes the cursor even without any errors
	      # in it (journal rewind/truncation maybe?) so we have to detect
	      # that.
	      #
	      c=(sudo journalctl --no-pager --quiet --output short-full \
                   --unit "bbot-agent-$tn@$i")

	      # Get the last cursor if any.
	      #
	      oc="${toolchain_cursors["$tn/$i"]}"
	      if [ -n "$oc" ]; then
		c+=("--after-cursor" "$oc")
	      fi

	      # Get the "log range": the first line is the date of the first
	      # error, the second line is the date of the last error, and the
	      # third line is the end cursor. It can also be just one line in
	      # which case it is the new cursor (that rewind stuff).
	      #
	      # Here is what's going on in that sed script:
	      #
	      # The first chunk matches the first line. We first put it into
	      # the hold space (in case that's the only line) and then extract
	      # and print the date.
	      #
	      # The second chunk matches the last line. We first handle the
	      # hold space which by now should contain the last error line and
	      # then the cursor.
	      #
	      # The last chunk matches every other line. We simply replace the
	      # hold space with the next line so that at the end we have the
	      # last line there.
	      #
	      lr="$("${c[@]}" --priority 4 --show-cursor | sed -n -r \
-e '1{h;s/^[MTWFS].. ([^ ]+ [^ ]+) .*$/\1/p;t}' \
-e '${x;s/^[MTWFS].. ([^ ]+ [^ ]+) .*$/\1/p;x;s/^-- cursor: (.+)$/\1/p;t}' \
-e 'h')"
	      lc="$(wc -l <<<"$lr")"
	      nc="$(sed -n -e "${lc}p" <<<"$lr")"

	      # If we have no new entries, then nothing to do.
	      #
	      if [ "$nc" != "$oc" ]; then

		# We may have no actual entries (cursor rewind).
		#
		if [ "$lc" -ne 1 ]; then

		  # Try to get some context before the first error and after
		  # the last. This is unexpectedly hard in systemd.
		  #
		  # This can be a lot of output which makes it hard to spot
		  # the error so we are going to print just the error summary
		  # first. Quite a mess, I agree.
		  #
		  sd="$(sed -n -e '1p' <<<"$lr")"
		  sd="$(date '+%s' -d "$sd")"                           # sec
		  sd="$(date '+%Y-%m-%d %H:%M:%S' -d "@$(($sd - 10))")" # -10sec

		  ed="$(sed -n -e '2p' <<<"$lr")"
		  ed="$(date '+%s' -d "$ed")"                           # sec
		  ed="$(date '+%Y-%m-%d %H:%M:%S' -d "@$(($ed + 10))")" # +10sec

		  s="bbot-agent-$tn@$i service issued new diagnostics"

		  info "$s"
		  {
		    echo "$tn.bbot_cmd: ssh build@$hname ${c[@]}";
		    echo;
		    echo "summary:";
		    echo;
		    "${c[@]}" --priority 4 | head -n 200;
		    echo;
		    echo "context:";
		    echo;
		    if [ -n "$oc" ]; then
		      unset 'c[-1]' # Pop cursor (for --since/--until).
		      unset 'c[-1]'
		    fi;
		    "${c[@]}" --since "$sd" --until "$ed" | head -n 200
		  } | email "$s"
		fi

		toolchain_cursors["$tn/$i"]="$nc"
	      fi
	    fi
	  done

	  continue # We have already issues diagnostics, if any.
	  ;;
	1)
	  s="re"
	  ;&
	2)
	  info "${s}starting bbot-agent for $tn..."

          # Note: appending to the same log.
	  #
	  bbot_start "$tn" "$tx" 2>&1 | tee -a "$tr/bbot-agent-$count.log" 1>&2

	  if [ "${PIPESTATUS[0]}" -eq 0 ]; then
	    s="${s}started bbot-agent for $tn, $ti instances"
	  else
	    s="failed to ${s}start bbot-agent for $tn, waiting for new version"
	  fi
	  ;;
	*)
	  s="failed to fetch package information for $tn toolchain, will try again"
	  ;;
      esac

      info "$s"
      email "$s" <<EOF
$tn.bbot_log: tftp://$hname/toolchains/$tn/bbot-agent-$count.log
EOF
    done
  fi

  sensors -A
  info "monitoring..."
  sleep 60
done