aboutsummaryrefslogtreecommitdiff
path: root/buildos
blob: c91c554af9d5979673f76447a9c4e67ab9dd4245 (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
#!/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.
#
trap "exit 1" ERR
set -o errtrace # Trap in functions.

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

  exit 1
}

info "starting buildos 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.
#
for v in "${cmdline[@]}"; do
  var="$(sed -r -n -e 's/^buildos\.([^=]+)=.*$/\1/p' <<<"$v")" # Extract name.

  if [ -n "$var" ]; then
    val="$(sed -r -e 's/^[^=]+=(.*)$/\1/' <<<"$v")"            # Extract value.
    val="$(sed -r -e "s/^('(.*)'|\"(.*)\")$/\2\3/" <<<"$val")" # Strip quoted.
    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
}

email "starting buildos monitor" <<EOF
buildid:       $buildid
buildid_url:   $buildid_url
toolchain_url: $toolchain_url
EOF

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

if [ -z "$toolchain_url" ]; then
  info "no buildos.toolchain_url specified, not bootstrapping"
else
  # 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.
  #
  tc_url="$toolchain_url"
  tc_file="$(sed -n -re 's%^.+/([^/]+)$%\1%p' <<<"$tc_url")"
  tc_sum="$(sed -n -re 's%^.+\.([^.]+)$%\1%p' <<<"$tc_file")"
  tc_root="/build/tftp"
  tc_path="$tc_root/$tc_file"
  tc_ver=
fi

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

# Fetch a file from the sums file into $tc_root, verify its checksum, and make
# a predictable name (without version) symlink.
#
function tc_fetch () # <line>
{
  local s p f u l

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

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

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

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

    info "toolchain version is $tc_ver"
    echo "$tc_ver" >"$tc_root/toolchain-version"
  fi

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

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

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

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

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

  local n
  n="$(tc_checksum "$tc_root/$f")"

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

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

# Bootstrap the toolchain.
#
function tc_bootstrap ()
{
  local l ls=()

  # Fetch files according to the sums file. Skip empty line and those that
  # start with '#'.
  #
  readarray -t ls < <(sed -e '/^\s*#/d;/^\s*$/d' "$tc_path")

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

# Monitoring loop.
#
while true; do

  # Check for toolchain changes. If this is the first run, bootstrap it.
  #
  if [ -n "$tc_url" ]; then

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

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

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

	n="$(tc_checksum "$f")"

	if [ "$tc_file_sum" != "$n" ]; then
	  email "rebooting because of new toolchain" <<EOF
old_toolchain: $tc_file_sum
new_toolchain: $n
EOF
	  info "new toolchain ($n), rebooting..."
	  restart
	fi
      else
	# This is the first run, bootstrap the toolchain.
	#
	tc_file_sum="$(tc_checksum "$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 tc_ver) won't be visible to us.
	#
	info "bootstrapping toolchain..."

	tc_bootstrap 2>&1 | tee "$tc_root/toolchain.log" 1>&2

	if [ "${PIPESTATUS[0]}" -eq 0 ]; then
	  tc_ver="$(cat $tc_root/toolchain-version)"
	  s="bootstrapped toolchain $tc_ver"
	else
	  s="failed to bootstrap toolchain, waiting for new version"
	fi

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

  # 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