Debian Codegraph @

tools/ds-identify

raw symbols SCIP
1 #!/bin/sh
2 # shellcheck disable=2015,2039,2162,2166,3043
3 #
4 # ds-identify is configured via /etc/cloud/ds-identify.cfg
5 # or on the kernel command line. It takes the following inputs:
6 #
7 # datasource: can specify the datasource that should be used.
8 # kernel command line option: ci.datasource=<dsname> or ci.ds=<dsname>
9 # example line in /etc/cloud/ds-identify.cfg:
10 # datasource: Ec2
11 #
12 # policy: a string that indicates how ds-identify should operate.
13 #
14 # The format is:
15 # <mode>,found=value,maybe=value,notfound=value
16 # default setting is:
17 # search,found=all,maybe=none,notfound=disabled
18 #
19 # kernel command line option: ci.di.policy=<policy>
20 # example line in /etc/cloud/ds-identify.cfg:
21 # policy: search,found=all,maybe=none,notfound=disabled
22 #
23 #
24 # Mode:
25 # disabled: disable cloud-init
26 # enabled: enable cloud-init.
27 # ds-identify writes no config and just exits success.
28 # the caller (cloud-init-generator) then enables cloud-init to
29 # run just without any aid from ds-identify.
30 # search: determine which source or sources should be used
31 # and write the result (datasource_list) to
32 # /run/cloud-init/cloud.cfg
33 # report: basically 'dry run' for search. results are still written
34 # to the file, but are namespaced under the top level key
35 # 'di_report' Thus cloud-init is not affected, but can still
36 # see the result.
37 #
38 # found,maybe,notfound:
39 # found: (default=all)
40 # first: use the first found do no further checking
41 # all: enable all DS_FOUND
42 #
43 # maybe: (default=none)
44 # if nothing returned 'found', then how to handle maybe.
45 # no network sources are allowed to return 'maybe'.
46 # all: enable all DS_MAYBE
47 # none: ignore any DS_MAYBE
48 #
49 # notfound: (default=disabled)
50 # disabled: disable cloud-init
51 # enabled: enable cloud-init
52 #
53 # ci.datasource.ec2.strict_id: (true|false|warn[,0-9])
54 # if ec2 datasource does not strictly match,
55 # return not_found if true
56 # return maybe if false or warn*.
57 #
58
59 set -u
60 set -f
61 UNAVAILABLE="unavailable"
62 CR="
63 "
64 ERROR="error"
65 DI_ENABLED="enabled"
66 DI_DISABLED="disabled"
67
68 DI_DEBUG_LEVEL="${DEBUG_LEVEL:-1}"
69
70 PATH_ROOT=${PATH_ROOT:-""}
71 PATH_SYS_CLASS_DMI_ID=${PATH_SYS_CLASS_DMI_ID:-${PATH_ROOT}/sys/class/dmi/id}
72 PATH_SYS_HYPERVISOR=${PATH_SYS_HYPERVISOR:-${PATH_ROOT}/sys/hypervisor}
73 PATH_SYS_CLASS_BLOCK=${PATH_SYS_CLASS_BLOCK:-${PATH_ROOT}/sys/class/block}
74 PATH_DEV_DISK="${PATH_DEV_DISK:-${PATH_ROOT}/dev/disk}"
75 PATH_VAR_LIB_CLOUD="${PATH_VAR_LIB_CLOUD:-${PATH_ROOT}/var/lib/cloud}"
76 PATH_DI_CONFIG="${PATH_DI_CONFIG:-${PATH_ROOT}/etc/cloud/ds-identify.cfg}"
77 PATH_DI_ENV="${PATH_DI_ENV:-${PATH_ROOT}/usr/libexec/ds-identify-env}"
78 PATH_PROC_CMDLINE="${PATH_PROC_CMDLINE:-${PATH_ROOT}/proc/cmdline}"
79 PATH_PROC_1_CMDLINE="${PATH_PROC_1_CMDLINE:-${PATH_ROOT}/proc/1/cmdline}"
80 PATH_PROC_1_ENVIRON="${PATH_PROC_1_ENVIRON:-${PATH_ROOT}/proc/1/environ}"
81 PATH_PROC_UPTIME=${PATH_PROC_UPTIME:-${PATH_ROOT}/proc/uptime}
82 PATH_ETC_CLOUD="${PATH_ETC_CLOUD:-${PATH_ROOT}/etc/cloud}"
83 PATH_ETC_CI_CFG="${PATH_ETC_CI_CFG:-${PATH_ETC_CLOUD}/cloud.cfg}"
84 PATH_ETC_CI_CFG_D="${PATH_ETC_CI_CFG_D:-${PATH_ETC_CI_CFG}.d}"
85
86 # Declare global here, so they can be overwritten from the outside.
87 # if not overwritten from the outside, we'll populate them with system default
88 # paths, once we have determined the system we're running on.
89 # This is done in set_run_path(), which must run after read_uname_info().
90 PATH_RUN="${PATH_RUN:-}"
91 PATH_RUN_CI="${PATH_RUN_CI:-}"
92 PATH_RUN_CI_CFG="${PATH_RUN_CI_CFG:-}"
93 PATH_RUN_DI_RESULT="${PATH_RUN_DI_RESULT:-}"
94
95 DI_LOG="${DI_LOG:-}"
96 _DI_LOGGED=""
97
98 # set DI_MAIN='noop' in environment to source this file with no main called.
99 DI_MAIN=${DI_MAIN:-main}
100
101 DI_BLKID_EXPORT_OUT=""
102 DI_GEOM_LABEL_STATUS_OUT=""
103 DI_DEFAULT_POLICY="search,found=all,maybe=none,notfound=${DI_DISABLED}"
104 DI_DEFAULT_POLICY_NO_DMI="search,found=all,maybe=none,notfound=${DI_DISABLED}"
105 DI_DMI_BOARD_NAME=""
106 DI_DMI_CHASSIS_ASSET_TAG=""
107 DI_DMI_PRODUCT_NAME=""
108 DI_DMI_SYS_VENDOR=""
109 DI_DMI_PRODUCT_SERIAL=""
110 DI_DMI_PRODUCT_UUID=""
111 DI_FS_LABELS=""
112 DI_FS_UUIDS=""
113 DI_ISO9660_DEVS=""
114 DI_KERNEL_CMDLINE=""
115 DI_VIRT=""
116 DI_PID_1_PRODUCT_NAME=""
117
118 DI_UNAME_KERNEL_NAME=""
119 DI_UNAME_KERNEL_VERSION=""
120 DI_UNAME_MACHINE=""
121 DI_UNAME_CMD_OUT=""
122
123 DS_FOUND=0
124 DS_NOT_FOUND=1
125 DS_MAYBE=2
126
127 DI_SYSTEMD_VIRTUALIZATION=${SYSTEMD_VIRTUALIZATION:-}
128 DI_DSNAME=""
129 # this has to match the builtin list in cloud-init, it is what will
130 # be searched if there is no setting found in config.
131 DI_DSLIST_DEFAULT="MAAS ConfigDrive NoCloud AltCloud Azure Bigstep \
132 CloudSigma CloudStack DigitalOcean Vultr AliYun Ec2 GCE OpenNebula OpenStack \
133 VMware OVF SmartOS Scaleway Hetzner IBMCloud Oracle Exoscale RbxCloud UpCloud \
134 LXD NWCS Akamai WSL CloudCIX"
135 DI_DSLIST=""
136 DI_MODE=""
137 DI_ON_FOUND=""
138 DI_ON_MAYBE=""
139 DI_ON_NOTFOUND=""
140
141 DI_EC2_STRICT_ID_DEFAULT="true"
142
143 _IS_IBM_CLOUD=""
144
145 error() {
146 set -- "ERROR:" "$@"
147 debug 0 "$@"
148 stderr "$@"
149 }
150
151 warn() {
152 set -- "WARN:" "$@"
153 debug 0 "$@"
154 stderr "$@"
155 }
156
157 stderr() { echo "$@" 1>&2; }
158
159 debug() {
160 local lvl="$1"
161 shift
162 [ "$lvl" -gt "${DI_DEBUG_LEVEL}" ] && return
163
164 [ "$DI_LOG" = "" ] && DI_LOG="stderr"
165
166 if [ "$_DI_LOGGED" != "$DI_LOG" ]; then
167 # first time here, open file descriptor for append
168 case "$DI_LOG" in
169 stderr) : ;;
170 ?*/*)
171 if [ ! -d "${DI_LOG%/*}" ]; then
172 mkdir -p "${DI_LOG%/*}" || {
173 stderr "ERROR:" "cannot write to $DI_LOG"
174 DI_LOG="stderr"
175 }
176 fi
177 ;;
178 esac
179 if [ "$DI_LOG" = "stderr" ]; then
180 exec 3>&2
181 else
182 (exec 3>> "$DI_LOG") && exec 3>> "$DI_LOG" || {
183 stderr "ERROR: failed writing to $DI_LOG. logging to stderr."
184 exec 3>&2
185 DI_LOG="stderr"
186 }
187 fi
188 _DI_LOGGED="$DI_LOG"
189 fi
190 echo "$@" 1>&3
191 }
192
193 get_kenv_field() {
194 local sys_field="$1" kenv_field="" val=""
195 command -v kenv > /dev/null 2>&1 || {
196 warn "No kenv program. Cannot read $sys_field."
197 return 1
198 }
199 case "$sys_field" in
200 board_asset_tag) kenv_field="smbios.planar.tag" ;;
201 board_vendor) kenv_field='smbios.planar.maker' ;;
202 board_name) kenv_field='smbios.planar.product' ;;
203 board_serial) kenv_field='smbios.planar.serial' ;;
204 board_version) kenv_field='smbios.planar.version' ;;
205 bios_date) kenv_field='smbios.bios.reldate' ;;
206 bios_vendor) kenv_field='smbios.bios.vendor' ;;
207 bios_version) kenv_field='smbios.bios.version' ;;
208 chassis_asset_tag) kenv_field='smbios.chassis.tag' ;;
209 chassis_vendor) kenv_field='smbios.chassis.maker' ;;
210 chassis_serial) kenv_field='smbios.chassis.serial' ;;
211 chassis_version) kenv_field='smbios.chassis.version' ;;
212 sys_vendor) kenv_field='smbios.system.maker' ;;
213 product_name) kenv_field='smbios.system.product' ;;
214 product_serial) kenv_field='smbios.system.serial' ;;
215 product_uuid) kenv_field='smbios.system.uuid' ;;
216 *)
217 error "Unknown field $sys_field. Cannot call kenv."
218 return 1
219 ;;
220 esac
221 val=$(kenv -q "$kenv_field" 2> /dev/null) || return 1
222 _RET="$val"
223 }
224
225 get_sysctl_field() {
226 local sys_field="$1" sysctl_field="" val=""
227 command -v sysctl > /dev/null 2>&1 || {
228 warn "No sysctl program. Cannot read $sys_field."
229 return 1
230 }
231 case "$sys_field" in
232 chassis_vendor) sysctl_field='hw.vendor' ;;
233 chassis_serial) sysctl_field='hw.type' ;;
234 chassis_version) sysctl_field='hw.uuid' ;;
235 sys_vendor) sysctl_field='hw.vendor' ;;
236 product_name) sysctl_field='hw.product' ;;
237 product_serial) sysctl_field='hw.uuid' ;;
238 product_uuid) sysctl_field='hw.uuid' ;;
239 *)
240 error "Unknown field $sys_field. Cannot call sysctl."
241 return 1
242 ;;
243 esac
244 val=$(sysctl -nq "$sysctl_field" 2> /dev/null) || return 1
245 _RET="$val"
246 }
247
248 dmi_decode() {
249 local sys_field="$1" dmi_field="" val=""
250 command -v dmidecode > /dev/null 2>&1 || {
251 warn "No dmidecode program. Cannot read $sys_field."
252 return 1
253 }
254 case "$sys_field" in
255 sys_vendor) dmi_field="system-manufacturer" ;;
256 product_name) dmi_field="system-product-name" ;;
257 product_uuid) dmi_field="system-uuid" ;;
258 product_serial) dmi_field="system-serial-number" ;;
259 chassis_asset_tag) dmi_field="chassis-asset-tag" ;;
260 *)
261 error "Unknown field $sys_field. Cannot call dmidecode."
262 return 1
263 ;;
264 esac
265 val=$(dmidecode --quiet "--string=$dmi_field" 2> /dev/null) || return 1
266 _RET="$val"
267 }
268
269 get_dmi_field() {
270 _RET="$UNAVAILABLE"
271
272 if [ "$DI_UNAME_KERNEL_NAME" = "FreeBSD" -o "$DI_UNAME_KERNEL_NAME" = "Dragonfly" ]; then
273 get_kenv_field "$1" || _RET="$ERROR"
274 return $?
275 elif [ "$DI_UNAME_KERNEL_NAME" = "OpenBSD" ]; then
276 get_sysctl_field "$1" || _RET="$ERROR"
277 return $?
278 fi
279
280 local path="${PATH_SYS_CLASS_DMI_ID}/$1"
281 if [ -d "${PATH_SYS_CLASS_DMI_ID}" ]; then
282 if [ -f "$path" ] && [ -r "$path" ]; then
283 read _RET < "${path}" || _RET="$ERROR"
284 return
285 fi
286 # if `/sys/class/dmi/id` exists, but not the object we're looking for,
287 # do *not* fallback to dmidecode!
288 return
289 fi
290 dmi_decode "$1" || _RET="$ERROR"
291 return
292 }
293
294 block_dev_with_label() {
295 local p="${PATH_DEV_DISK}/by-label/$1"
296 [ -b "$p" ] || return 1
297 _RET=$p
298 return 0
299 }
300
301 ensure_sane_path() {
302 local t
303 for t in /sbin /usr/sbin /bin /usr/bin; do
304 case ":$PATH:" in
305 *:$t:* | *:$t/:*) continue ;;
306 esac
307 PATH="${PATH:+${PATH}:}$t"
308 done
309 }
310
311 blkid_export() {
312 # call 'blkid -c /dev/null export', set DI_BLKID_EXPORT_OUT
313 cached "$DI_BLKID_EXPORT_OUT" && return 0
314 local out="" ret=0
315 out=$(blkid -c /dev/null -o export) && DI_BLKID_EXPORT_OUT="$out" || {
316 ret=$?
317 error "failed running [$ret]: blkid -c /dev/null -o export"
318 DI_BLKID_EXPORT_OUT="$UNAVAILABLE"
319 }
320 return $ret
321 }
322
323 read_fs_info_linux() {
324 # do not rely on links in /dev/disk which might not be present yet.
325 # Note that blkid < 2.22 (centos6, trusty) do not output DEVNAME.
326 # that means that DI_ISO9660_DEVS will not be set.
327 if is_container; then
328 # blkid will in a container, or at least currently in lxd
329 # not provide useful information.
330 DI_FS_LABELS="$UNAVAILABLE:container"
331 DI_ISO9660_DEVS="$UNAVAILABLE:container"
332 return
333 fi
334 local oifs="$IFS" line="" delim=","
335 local ret=0 labels="" dev="" label="" ftype="" isodevs="" uuids=""
336
337 blkid_export
338 ret=$?
339 [ "$DI_BLKID_EXPORT_OUT" = "$UNAVAILABLE" ] && {
340 DI_FS_LABELS="$UNAVAILABLE:error"
341 DI_ISO9660_DEVS="$UNAVAILABLE:error"
342 DI_FS_UUIDS="$UNAVAILABLE:error"
343 return $ret
344 }
345
346 # 'set --' will collapse multiple consecutive entries in IFS for
347 # whitespace characters (\n, tab, " ") so we cannot rely on getting
348 # empty lines in "$@" below.
349
350 # shellcheck disable=2086
351 {
352 IFS="$CR"
353 set -- $DI_BLKID_EXPORT_OUT
354 IFS="$oifs"
355 }
356
357 for line in "$@"; do
358 case "${line}" in
359 DEVNAME=*)
360 [ -n "$dev" -a "$ftype" = "iso9660" ] &&
361 isodevs="${isodevs},${dev}=$label"
362 ftype=""
363 dev=""
364 label=""
365 dev=${line#DEVNAME=}
366 ;;
367 LABEL=* | LABEL_FATBOOT=*)
368 label="${line#*=}"
369 labels="${labels}${label}${delim}"
370 ;;
371 TYPE=*) ftype=${line#TYPE=} ;;
372 UUID=*) uuids="${uuids}${line#UUID=}$delim" ;;
373 esac
374 done
375 [ -n "$dev" -a "$ftype" = "iso9660" ] &&
376 isodevs="${isodevs},${dev}=$label"
377
378 DI_FS_LABELS="${labels%"${delim}"}"
379 DI_FS_UUIDS="${uuids%"${delim}"}"
380 DI_ISO9660_DEVS="${isodevs#,}"
381 }
382
383 geom_label_status_as() {
384 # call 'geom label status -as', set DI_GEOM_LABEL_STATUS_OUT
385 cached "$DI_GEOM_LABEL_STATUS_OUT" && return 0
386 local out="" ret=0
387 out=$(geom label status -as) && DI_GEOM_LABEL_STATUS_OUT="$out" || {
388 ret=$?
389 error "failed running [$ret]: geom label status -as"
390 DI_GEOM_LABEL_STATUS_OUT="$UNAVAILABLE"
391 }
392 return $ret
393 }
394
395 read_fs_info_freebsd() {
396 local oifs="$IFS" line="" delim=","
397 local ret=0 labels="" dev="" label="" ftype="" isodevs=""
398
399 geom_label_status_as
400 ret=$?
401 [ "$DI_GEOM_LABEL_STATUS_OUT" = "$UNAVAILABLE" ] && {
402 DI_FS_LABELS="$UNAVAILABLE:error"
403 DI_ISO9660_DEVS="$UNAVAILABLE:error"
404 return $ret
405 }
406
407 # The expected output looks like this:
408 # gpt/gptboot0 N/A vtbd1p1
409 # gpt/swap0 N/A vtbd1p2
410 # iso9660/cidata N/A vtbd2
411
412 # shellcheck disable=2086
413 {
414 IFS="$CR"
415 set -- $DI_GEOM_LABEL_STATUS_OUT
416 IFS="$oifs"
417 }
418
419 for line in "$@"; do
420 # shellcheck disable=2086
421 set -- $line
422 provider=$1
423 ftype="${provider%/*}"
424 label="${provider#*/}"
425 dev=$3
426
427 [ -n "$dev" -a "$ftype" = "iso9660" ] &&
428 isodevs="${isodevs},${dev}=$label"
429
430 labels="${labels}${label}${delim}"
431 done
432
433 DI_FS_LABELS="${labels%"${delim}"}"
434 DI_ISO9660_DEVS="${isodevs#,}"
435 }
436
437 read_fs_info() {
438 # After calling its subfunctions, read_fs_info() will set the following
439 # variables:
440 #
441 # - DI_FS_LABELS
442 # - DI_ISO9660_DEVS
443 # - DI_FS_UUIDS
444
445 if [ "$DI_UNAME_KERNEL_NAME" = "FreeBSD" -o "$DI_UNAME_KERNEL_NAME" = "Dragonfly" ]; then
446 read_fs_info_freebsd
447 return $?
448 else
449 read_fs_info_linux
450 return $?
451 fi
452 }
453
454 cached() {
455 [ -n "$1" ] && _RET="$1" && return || return 1
456 }
457
458 detect_virt() {
459 local virt="${UNAVAILABLE}" r="" out=""
460 if [ -d "${PATH_ROOT}/run/systemd" ]; then
461 if [ -n "$DI_SYSTEMD_VIRTUALIZATION" ]; then
462 virt=${DI_SYSTEMD_VIRTUALIZATION#*:}
463 debug 2 "detected $virt via env variable SYSTEMD_VIRTUALIZATION"
464 else
465 # required for compatibility with systemd version <251
466 out=$(systemd-detect-virt 2>&1)
467 r=$?
468 if [ $r -eq 0 ] || { [ $r -ne 0 ] && [ "$out" = "none" ]; }; then
469 virt="$out"
470 fi
471 debug 2 "detected $virt via ds-identify"
472 fi
473 elif command -v virt-what > /dev/null 2>&1; then
474 # Map virt-what's names to those systemd-detect-virt that
475 # don't match up.
476 out=$(virt-what 2>&1 | head -n 1) && {
477 case "$out" in
478 ibm_systemz-zvm) virt="zvm" ;;
479 hyperv) virt="microsoft" ;;
480 virtualbox) virt="oracle" ;;
481 xen-domU) virt="xen" ;;
482 *) virt="$out" ;;
483 esac
484 }
485 elif [ "$DI_UNAME_KERNEL_NAME" = "FreeBSD" -o "$DI_UNAME_KERNEL_NAME" = "Dragonfly" ]; then
486 # Map FreeBSD's vm_guest names to those systemd-detect-virt that
487 # don't match up. See
488 # https://github.com/freebsd/freebsd/blob/master/sys/kern/subr_param.c#L144-L160
489 # https://www.freedesktop.org/software/systemd/man/systemd-detect-virt.html
490 #
491 # systemd | kern.vm_guest
492 # ---------------------+---------------
493 # none | none
494 # kvm | kvm
495 # vmware | vmware
496 # microsoft | hv
497 # oracle | vbox
498 # xen | xen
499 # parallels | parallels
500 # bhyve | bhyve
501 # vm-other | generic
502 out=$(sysctl -qn kern.vm_guest 2> /dev/null) && {
503 case "$out" in
504 hv) virt="microsoft" ;;
505 vbox) virt="oracle" ;;
506 generic) virt="vm-other" ;;
507 *) virt="$out" ;;
508 esac
509 }
510 out=$(sysctl -qn security.jail.jailed 2> /dev/null) && {
511 if [ "$out" = "1" ]; then
512 virt="jail"
513 fi
514 }
515 fi
516 _RET="$virt"
517 }
518
519 read_virt() {
520 cached "$DI_VIRT" && return 0
521 detect_virt
522 DI_VIRT="${_RET}"
523 }
524
525 is_container() {
526 case "${DI_VIRT}" in
527 container-other | lxc | lxc-libvirt | systemd-nspawn | docker | rkt | jail) return 0 ;;
528 *) return 1 ;;
529 esac
530 }
531
532 is_socket_file() {
533 [ -S "$1" ] && return 0 || return 1
534 }
535
536 read_kernel_cmdline() {
537 cached "${DI_KERNEL_CMDLINE}" && return
538 local cmdline="" fpath="${PATH_PROC_CMDLINE}"
539 if is_container; then
540 local p1path="${PATH_PROC_1_CMDLINE}" x=""
541 cmdline="${UNAVAILABLE}:container"
542 if [ -f "$p1path" ] && x=$(tr '\0' ' ' < "$p1path"); then
543 cmdline=$x
544 fi
545 elif [ -f "$fpath" ]; then
546 read cmdline < "$fpath"
547 else
548 cmdline="${UNAVAILABLE}:no-cmdline"
549 fi
550 DI_KERNEL_CMDLINE="$cmdline"
551 }
552
553 read_dmi_board_name() {
554 cached "${DI_DMI_BOARD_NAME}" && return
555 get_dmi_field board_name
556 DI_DMI_BOARD_NAME="$_RET"
557 }
558
559 read_dmi_chassis_asset_tag() {
560 cached "${DI_DMI_CHASSIS_ASSET_TAG}" && return
561 get_dmi_field chassis_asset_tag
562 DI_DMI_CHASSIS_ASSET_TAG="$_RET"
563 }
564
565 read_dmi_sys_vendor() {
566 cached "${DI_DMI_SYS_VENDOR}" && return
567 get_dmi_field sys_vendor
568 DI_DMI_SYS_VENDOR="$_RET"
569 }
570
571 read_dmi_product_name() {
572 cached "${DI_DMI_PRODUCT_NAME}" && return
573 get_dmi_field product_name
574 DI_DMI_PRODUCT_NAME="$_RET"
575 }
576
577 read_dmi_product_uuid() {
578 cached "${DI_DMI_PRODUCT_UUID}" && return
579 get_dmi_field product_uuid
580 DI_DMI_PRODUCT_UUID="$_RET"
581 }
582
583 read_dmi_product_serial() {
584 cached "${DI_DMI_PRODUCT_SERIAL}" && return
585 get_dmi_field product_serial
586 DI_DMI_PRODUCT_SERIAL="$_RET"
587 }
588
589 read_uname_info() {
590 # run uname, and parse output.
591 # uname is tricky to parse as it outputs always in a given order
592 # independent of option order. kernel-version is known to have spaces.
593 # 1 -s kernel-name
594 # 2.. -v kernel-version(whitespace)
595 # N-1 -m machine
596 cached "${DI_UNAME_CMD_OUT}" && return
597 local out="${1:-}" ret=0 buf=""
598 if [ -z "$out" ]; then
599 out=$(uname -svm) || {
600 ret=$?
601 error "failed reading uname with 'uname -svm'"
602 return $ret
603 }
604 fi
605 # shellcheck disable=2086
606 set -- $out
607 DI_UNAME_KERNEL_NAME="$1"
608 shift
609 while [ $# -gt 1 ]; do
610 buf="$buf $1"
611 shift
612 done
613 DI_UNAME_KERNEL_VERSION="${buf# }"
614 DI_UNAME_MACHINE="$1"
615 DI_UNAME_CMD_OUT="$out"
616 return 0
617 }
618
619 parse_yaml_array() {
620 # parse a yaml single line array value ([1,2,3], not key: [1,2,3]).
621 # supported with or without leading and closing brackets
622 # ['1'] or [1]
623 # '1', '2'
624 local val="$1" oifs="$IFS" ret="" tok=""
625 # i386/14.04 (dash=0.5.7-4ubuntu1): the following outputs "[foo"
626 # sh -c 'n="$1"; echo ${n#[}' -- "[foo"
627 # the fix was to quote the open bracket (val=${val#"["}) (LP: #1689648)
628 val=${val#"["}
629 val=${val%"]"}
630 # shellcheck disable=2086
631 {
632 IFS=","
633 set -- $val
634 IFS="$oifs"
635 }
636 for tok in "$@"; do
637 trim "$tok"
638 unquote "$_RET"
639 ret="${ret} $_RET"
640 done
641 _RET="${ret# }"
642 }
643
644 read_datasource_list() {
645 cached "$DI_DSLIST" && return
646 local dslist="" key="datasource_list"
647 # if DI_DSNAME is set directly, then avoid parsing config.
648 if [ -n "${DI_DSNAME}" ]; then
649 dslist="${DI_DSNAME}"
650 fi
651
652 # LP: #1582323. cc:{'datasource_list': ['name']}
653 # more generically cc:<yaml>[end_cc]
654 local cb="]" ob="["
655 case "$DI_KERNEL_CMDLINE" in
656 *cc:*datasource_list*)
657 t=${DI_KERNEL_CMDLINE##*datasource_list}
658 t=${t%%"${cb}"*}
659 t=${t##*"${ob}"}
660 parse_yaml_array "$t"
661 dslist=${_RET}
662 ;;
663 esac
664 if [ -z "$dslist" ] && check_config "$key" && get_single_line_flow_sequence "$key" "$_RET"; then
665 debug 1 "$_RET_fname set datasource_list: $_RET"
666 parse_yaml_array "$_RET"
667 dslist=${_RET}
668 fi
669 if [ -z "$dslist" ]; then
670 dslist=${DI_DSLIST_DEFAULT}
671 warn "no datasource_list found, using default: $dslist"
672 fi
673 DI_DSLIST=$dslist
674 return 0
675 }
676
677 read_pid1_product_name() {
678 local oifs="$IFS" out="" tok="" key="" val="" product_name="${UNAVAILABLE}"
679 cached "${DI_PID_1_PRODUCT_NAME}" && return
680 [ -r "${PATH_PROC_1_ENVIRON}" ] || return
681 out=$(tr '\0' '\n' < "${PATH_PROC_1_ENVIRON}")
682 # shellcheck disable=2086
683 {
684 IFS="$CR"
685 set -- $out
686 IFS="$oifs"
687 }
688 for tok in "$@"; do
689 key=${tok%%=*}
690 [ "$key" != "$tok" ] || continue
691 val=${tok#*=}
692 [ "$key" = "product_name" ] && product_name="$val" && break
693 done
694 DI_PID_1_PRODUCT_NAME="$product_name"
695 }
696
697 dmi_chassis_asset_tag_matches() {
698 is_container && return 1
699 # shellcheck disable=2254
700 case "${DI_DMI_CHASSIS_ASSET_TAG}" in
701 $1) return 0 ;;
702 esac
703 return 1
704 }
705
706 dmi_product_name_matches() {
707 is_container && return 1
708 # shellcheck disable=2254
709 case "${DI_DMI_PRODUCT_NAME}" in
710 $1) return 0 ;;
711 esac
712 return 1
713 }
714
715 dmi_product_serial_matches() {
716 is_container && return 1
717 # shellcheck disable=2254
718 case "${DI_DMI_PRODUCT_SERIAL}" in
719 $1) return 0 ;;
720 esac
721 return 1
722 }
723
724 dmi_sys_vendor_is() {
725 is_container && return 1
726 [ "${DI_DMI_SYS_VENDOR}" = "$1" ]
727 }
728
729 has_fs_with_uuid() {
730 case ",${DI_FS_UUIDS}," in
731 *,$1,*) return 0 ;;
732 esac
733 return 1
734 }
735
736 has_fs_with_label() {
737 # has_fs_with_label(label1[ ,label2 ..])
738 # return 0 if a there is a filesystem that matches any of the labels.
739 local label=""
740 for label in "$@"; do
741 case ",${DI_FS_LABELS}," in
742 *,$label,*) return 0 ;;
743 esac
744 done
745 return 1
746 }
747
748 nocase_equal() {
749 # nocase_equal(a, b)
750 # return 0 if case insensitive comparison a.lower() == b.lower()
751 # different lengths
752 [ "${#1}" = "${#2}" ] || return 1
753 # case sensitive equal
754 [ "$1" = "$2" ] && return 0
755
756 local delim="-delim-"
757 out=$(echo "$1${delim}$2" | tr '[:upper:]' '[:lower:]')
758 # delim is known not to be a pattern, and some editors currently struggle
759 # with parsing the quoted output required to satisfy SC2295
760 # shellcheck disable=2295
761 # https://github.com/tree-sitter/tree-sitter-bash/issues/254
762 [ "${out#*${delim}}" = "${out%${delim}*}" ]
763 }
764
765 check_seed_dir() {
766 # check_seed_dir(name, [required])
767 # check the seed dir /var/lib/cloud/seed/<name> for 'required'
768 # required defaults to 'meta-data'
769 local name="$1"
770 local dir="${PATH_VAR_LIB_CLOUD}/seed/$name"
771 [ -d "$dir" ] || return 1
772 shift
773 if [ $# -eq 0 ]; then
774 set -- meta-data
775 fi
776 local f=""
777 for f in "$@"; do
778 [ -f "$dir/$f" ] || return 1
779 done
780 return 0
781 }
782
783 check_writable_seed_dir() {
784 # ubuntu core bind-mounts /writable/system-data/var/lib/cloud
785 # over the top of /var/lib/cloud, but the mount might not be done yet.
786 local wdir="/writable/system-data"
787 [ -d "${PATH_ROOT}$wdir" ] || return 1
788 local sdir="${PATH_ROOT}$wdir${PATH_VAR_LIB_CLOUD#"${PATH_ROOT}"}"
789 local PATH_VAR_LIB_CLOUD="$sdir"
790 check_seed_dir "$@"
791 }
792
793 probe_floppy() {
794 cached "${STATE_FLOPPY_PROBED}" && return "${STATE_FLOPPY_PROBED}"
795 local fpath=/dev/floppy
796
797 [ -b "$fpath" ] ||
798 {
799 STATE_FLOPPY_PROBED=1
800 return 1
801 }
802
803 # Use "-b" option as Busybox modprobe doesn't support long-option
804 modprobe -b floppy > /dev/null 2>&1 ||
805 {
806 STATE_FLOPPY_PROBED=1
807 return 1
808 }
809
810 # Some Linux distros/non-Linux OSes may not have udev
811 if command -v udevadm; then
812 udevadm settle "--exit-if-exists=$fpath" ||
813 {
814 STATE_FLOPPY_PROBED=1
815 return 1
816 }
817 fi
818
819 [ -b "$fpath" ]
820 STATE_FLOPPY_PROBED=$?
821 return "${STATE_FLOPPY_PROBED}"
822 }
823
824 dscheck_CloudStack() {
825 is_container && return ${DS_NOT_FOUND}
826 dmi_product_name_matches "CloudStack*" && return $DS_FOUND
827 return $DS_NOT_FOUND
828 }
829
830 dscheck_CloudCIX() {
831 dmi_product_name_matches "CloudCIX" && return $DS_FOUND
832 return $DS_NOT_FOUND
833 }
834
835 dscheck_Exoscale() {
836 dmi_product_name_matches "Exoscale*" && return $DS_FOUND
837 return $DS_NOT_FOUND
838 }
839
840 dscheck_CloudSigma() {
841 # http://paste.ubuntu.com/23624795/
842 dmi_product_name_matches "CloudSigma" && return $DS_FOUND
843 return $DS_NOT_FOUND
844 }
845
846 dscheck_Akamai() {
847 dmi_sys_vendor_is Linode && return ${DS_FOUND}
848 dmi_sys_vendor_is Akamai && return ${DS_FOUND}
849 return ${DS_NOT_FOUND}
850 }
851
852 check_config() {
853 # check_config(key [,file_globs])
854 # somewhat hackily read through file_globs for 'key'
855 # file_globs are expanded via path expansion and
856 # default to /etc/cloud/cloud.cfg /etc/cloud/cloud.cfg.d/*.cfg
857 # currently does not respect any hierarchy in searching for key.
858 local key="$1" files=""
859 shift
860 if [ $# -eq 0 ]; then
861 files="${PATH_ETC_CI_CFG} ${PATH_ETC_CI_CFG_D}/*.cfg"
862 else
863 files="$*"
864 fi
865 # shellcheck disable=2086
866 {
867 set +f
868 set -- $files
869 set -f
870 }
871 if [ "$1" = "$files" -a ! -f "$1" ]; then
872 return 1
873 fi
874 local line="" ret="" found=0 found_fn="" oifs="$IFS" out=""
875 # check for a yaml key/value pair on a single line
876 #
877 # note that:
878 # - keys may be single or double quoted
879 # - spaces and tabs may exist between key and colon
880 #
881 # the following are all valid under the yaml spec (as of 1.2.2):
882 #
883 # key: string
884 # key: "quoted string"
885 # key: 1
886 # key: [ some_value ]
887 # key : [ "some value" ]
888 # key\t:\t[\tsome_value\t]\t
889 #
890 # The syntax warned about is not valid posix shell, and we are not
891 # attempting to access an index of arrays. Silence it.
892 # shellcheck disable=1087
893 out=$(grep "$key[\"\']*[[:space:]]*:" "$@" 2> /dev/null)
894 IFS=${CR}
895 for line in $out; do
896 # drop '# comment'
897 line=${line%%#*}
898 # if more than one file was 'grep'ed, then grep will output filename:
899 # but if only one file, line will not be prefixed.
900 if [ $# -eq 1 ]; then
901 found_fn="$1"
902 if [ "${#line}" -eq 0 ]; then
903 continue
904 fi
905 else
906 found_fn="${line%%:*}"
907 line=${line#"$found_fn:"}
908 if [ "${#line}" -eq 0 ]; then
909 continue
910 fi
911 fi
912 ret=${line#*: }
913 found=$((found + 1))
914 done
915 IFS="$oifs"
916 if [ $found -ne 0 ]; then
917 _RET="$ret"
918 _RET_fname="$found_fn"
919 return 0
920 fi
921 return 1
922 }
923
924 get_value() {
925 # get_value(key, value)
926 # for a key / value pair, check that the value is non-empty and
927 # return the value if it exists
928 #
929 # This function is intended to be run on the output of check_config
930 # when the value for a key needs to be in the output.
931 #
932 # `check_config` returns true when no value is in the line, but this
933 # is insufficient when a value is required, as in the case of
934 # parsing 'datasource_list:'
935 local key="$1" value="$2" found=0 ret=""
936
937 # remove everything before final ':'
938 ret="${value##*:}"
939
940 # remove preceding and trailing whitespace
941 trim "$ret"
942
943 # check value length
944 if [ "${#_RET}" -ne 0 ]; then
945 return 0
946 fi
947 debug 1 "key $key didn't have a valid value"
948 return 1
949 }
950
951 get_single_line_flow_sequence() {
952 # get_single_line_flow_sequence(key, value)
953 # for a key / value pair, check that the value contains a single
954 # line flow sequence[1] with a value
955 #
956 # return 0 if a single line flow sequence is found, otherwise 1
957 # does not modify _RET
958 #
959 # [1] https://yaml.org/spec/1.2.2/#741-flow-sequences
960 local ret="" tmp=""
961 get_value "$1" "$2" || return 1
962 ret="$_RET"
963 tmp="$_RET"
964
965 # remove smallest ] suffix
966 tmp="${tmp%]}"
967
968 # remove smallest [ prefix
969 tmp="${tmp#[}"
970
971 # remove preceding and trailing whitespace
972 trim "$tmp"
973 _RET="$ret"
974
975 # check value length
976 if [ "${#_RET}" -ne 0 ]; then
977 return 0
978 fi
979 debug 1 "key $key didn't have a valid single line flow sequence"
980 return 1
981 }
982
983 # LXD datasource requires active /dev/lxd/sock
984 # https://documentation.ubuntu.com/lxd/en/latest/dev-lxd/
985 dscheck_LXD() {
986 if is_socket_file /dev/lxd/sock; then
987 return ${DS_FOUND}
988 fi
989
990 # On LXD KVM instances, /dev/lxd/sock will not be available during systemd
991 # generator timeframe until systemd lxd-agent.service runs.
992 # Check for LXD virtio serial device which is supported on platforms
993 # without DMI data.
994 if [ "${DI_VIRT}" != "kvm" -a "${DI_VIRT}" != "qemu" ]; then
995 return ${DS_NOT_FOUND}
996 fi
997 local virtio_ports_path="${PATH_ROOT}/sys/class/virtio-ports"
998 if [ ! -d "${virtio_ports_path}" ]; then
999 return ${DS_NOT_FOUND}
1000 fi
1001 # Temporarily enable globbing to walk virtio_ports_path.
1002 set +f
1003 set -- "${virtio_ports_path}/"*
1004 set -f
1005 for port_dir in "$@"; do
1006 local name_file="${port_dir}/name" port_name
1007 [ ! -f "${name_file}" ] && continue
1008 read port_name < "${name_file}" ||
1009 warn "unable to read file: $name_file"
1010 # Check for both current and legacy LXD serial names
1011 if [ "${port_name}" = "com.canonical.lxd" ] ||
1012 [ "${port_name}" = "org.linuxcontainers.lxd" ]; then
1013 return ${DS_FOUND}
1014 fi
1015 done
1016 return ${DS_NOT_FOUND}
1017 }
1018
1019 dscheck_NoCloud() {
1020 local fslabel="cidata CIDATA" d=""
1021 case " ${DI_DMI_PRODUCT_SERIAL} " in
1022 *\ ds=nocloud*) return ${DS_FOUND} ;;
1023 esac
1024
1025 for d in nocloud nocloud-net; do
1026 check_seed_dir "$d" meta-data user-data && return ${DS_FOUND}
1027 check_writable_seed_dir "$d" meta-data user-data && return ${DS_FOUND}
1028 done
1029 # shellcheck disable=2086
1030 if has_fs_with_label $fslabel; then
1031 return ${DS_FOUND}
1032 fi
1033
1034 # This is a bit hacky, but a NoCloud false positive isn't the end of the world
1035 if check_config "NoCloud"; then
1036 if check_config "user-data" && check_config "meta-data"; then
1037 return ${DS_FOUND}
1038 elif check_config "seedfrom"; then
1039 return ${DS_FOUND}
1040 fi
1041 fi
1042
1043 return ${DS_NOT_FOUND}
1044 }
1045
1046 is_ds_enabled() {
1047 local name="$1" pad=" ${DI_DSLIST} "
1048 [ "${pad#* "${name}" }" != "${pad}" ]
1049 }
1050
1051 check_configdrive_v2() {
1052 # look in /config-drive <vlc>/seed/config_drive for a directory
1053 # openstack/YYYY-MM-DD format with a file meta_data.json
1054 local d=""
1055 local vlc_config_drive_path="${PATH_VAR_LIB_CLOUD}/seed/config_drive"
1056 for d in /config-drive $vlc_config_drive_path; do
1057 set +f
1058 set -- "$d/openstack/"2???-??-??/meta_data.json
1059 set -f
1060 [ -f "$1" ] && return ${DS_FOUND}
1061 done
1062 # at least one cloud (softlayer) seeds config drive with only 'latest'.
1063 local lpath="openstack/latest/meta_data.json"
1064 if [ -e "$vlc_config_drive_path/$lpath" ]; then
1065 debug 1 "config drive seeded directory had only 'latest'"
1066 return ${DS_FOUND}
1067 fi
1068
1069 local ibm_enabled=false
1070 is_ds_enabled "IBMCloud" && ibm_enabled=true
1071 debug 1 "is_ds_enabled(IBMCloud) = $ibm_enabled."
1072 [ "$ibm_enabled" = "true" ] && is_ibm_cloud && return ${DS_NOT_FOUND}
1073
1074 if has_fs_with_label CONFIG-2 config-2; then
1075 return ${DS_FOUND}
1076 fi
1077 return ${DS_NOT_FOUND}
1078 }
1079
1080 check_configdrive_v1() {
1081 # FIXME: this has to check any file system that is vfat...
1082 # for now, just return not found.
1083 return ${DS_NOT_FOUND}
1084 }
1085
1086 dscheck_ConfigDrive() {
1087 local ret=""
1088 check_configdrive_v2
1089 ret=$?
1090 [ $DS_FOUND -eq $ret ] && return $ret
1091
1092 check_configdrive_v1
1093 }
1094
1095 dscheck_DigitalOcean() {
1096 dmi_sys_vendor_is DigitalOcean && return ${DS_FOUND}
1097 return ${DS_NOT_FOUND}
1098 }
1099
1100 dscheck_OpenNebula() {
1101 check_seed_dir opennebula && return ${DS_FOUND}
1102 has_fs_with_label "CONTEXT" "CDROM" && return ${DS_FOUND}
1103 return ${DS_NOT_FOUND}
1104 }
1105
1106 dscheck_RbxCloud() {
1107 has_fs_with_label "CLOUDMD" "cloudmd" && return ${DS_FOUND}
1108 return ${DS_NOT_FOUND}
1109 }
1110
1111 dscheck_UpCloud() {
1112 dmi_sys_vendor_is UpCloud && return ${DS_FOUND}
1113 return ${DS_NOT_FOUND}
1114 }
1115
1116 vmware_guest_customization() {
1117 # vmware guest customization
1118
1119 # virt provider must be vmware
1120 [ "${DI_VIRT}" = "vmware" ] || return 1
1121
1122 # we have to have the plugin to do vmware customization
1123 local found="" pkg="" pre="${PATH_ROOT}/usr/lib"
1124 local x86="x86_64-linux-gnu" aarch="aarch64-linux-gnu" i386="i386-linux-gnu"
1125 local ppath="plugins/vmsvc/libdeployPkgPlugin.so"
1126 for pkg in vmware-tools open-vm-tools; do
1127 if [ -f "$pre/$pkg/$ppath" -o -f "${pre}64/$pkg/$ppath" ]; then
1128 found="$pkg"
1129 break
1130 fi
1131 # search in multiarch dir
1132 if [ -f "$pre/$x86/$pkg/$ppath" ] ||
1133 [ -f "$pre/$aarch/$pkg/$ppath" ] ||
1134 [ -f "$pre/$i386/$pkg/$ppath" ]; then
1135 found="$pkg"
1136 break
1137 fi
1138 done
1139 [ -n "$found" ] || return 1
1140 # vmware customization is disabled by default
1141 # (disable_vmware_customization=true). If it is set to false, then
1142 # user has requested customization.
1143 local key="disable_vmware_customization"
1144 if check_config "$key" && get_value "$key" "$_RET"; then
1145 debug 2 "${_RET_fname} set $key to $_RET"
1146 case "$_RET" in
1147 0 | false | False) return 0 ;;
1148 *) return 1 ;;
1149 esac
1150 fi
1151
1152 return 1
1153 }
1154
1155 vmware_has_rpctool() {
1156 command -v vmware-rpctool > /dev/null 2>&1
1157 }
1158
1159 vmware_rpctool_guestinfo() {
1160 vmware-rpctool "info-get guestinfo.${1}" 2> /dev/null | grep "[[:alnum:]]"
1161 }
1162
1163 vmware_rpctool_guestinfo_err() {
1164 vmware-rpctool "info-get guestinfo.${1}" 2>&1 | grep "[[:alnum:]]"
1165 }
1166
1167 vmware_has_vmtoolsd() {
1168 command -v vmtoolsd > /dev/null 2>&1
1169 }
1170
1171 vmware_vmtoolsd_guestinfo() {
1172 vmtoolsd --cmd "info-get guestinfo.${1}" 2> /dev/null | grep "[[:alnum:]]"
1173 }
1174
1175 vmware_vmtoolsd_guestinfo_err() {
1176 vmtoolsd --cmd "info-get guestinfo.${1}" 2>&1 | grep "[[:alnum:]]"
1177 }
1178
1179 vmware_guestinfo() {
1180 vmware_rpctool_guestinfo "${1}" || vmware_vmtoolsd_guestinfo "${1}"
1181 }
1182
1183 vmware_guestinfo_err() {
1184 vmware_rpctool_guestinfo_err "${1}" || vmware_vmtoolsd_guestinfo_err "${1}"
1185 }
1186
1187 vmware_guestinfo_ovfenv_err() {
1188 vmware_guestinfo_err "ovfEnv"
1189 }
1190
1191 vmware_guestinfo_metadata() {
1192 vmware_guestinfo "metadata"
1193 }
1194
1195 vmware_guestinfo_userdata() {
1196
1197 vmware_guestinfo "userdata"
1198 }
1199
1200 vmware_guestinfo_vendordata() {
1201
1202 vmware_guestinfo "vendordata"
1203 }
1204
1205 ovf_vmware_transport_guestinfo() {
1206 [ "${DI_VIRT}" = "vmware" ] || return 1
1207 vmware_has_rpctool || vmware_has_vmtoolsd || return 1
1208 local out="" ret=""
1209 out=$(vmware_guestinfo_ovfenv_err)
1210 ret=$?
1211 if [ $ret -ne 0 ]; then
1212 debug 1 "Running on vmware but query returned $ret: $out"
1213 return 1
1214 fi
1215 case "$out" in
1216 "<?xml"* | "<?XML"*) : ;;
1217 *)
1218 debug 1 "guestinfo.ovfEnv had non-xml content: $out"
1219 return 1
1220 ;;
1221 esac
1222 debug 1 "Found guestinfo transport."
1223 return 0
1224 }
1225
1226 is_cdrom_ovf() {
1227 local dev="$1" label="$2"
1228 # skip devices that don't look like cdrom paths.
1229 case "$dev" in
1230 /dev/sr[0-9] | /dev/hd[a-z]) : ;;
1231 *)
1232 debug 1 "skipping iso dev $dev"
1233 return 1
1234 ;;
1235 esac
1236
1237 debug 1 "got label=$label"
1238 # fast path known 'OVF' labels
1239 case "$label" in
1240 OVF-TRANSPORT | ovf-transport | OVFENV | ovfenv | OVF\ ENV | ovf\ env) return 0 ;;
1241 esac
1242
1243 # explicitly skip known labels of other types. rd_rdfe is azure.
1244 case "$label" in
1245 config-2 | CONFIG-2 | rd_rdfe_stable* | cidata | CIDATA) return 1 ;;
1246 esac
1247
1248 # skip device which size is 10MB or larger
1249 local size="" sfile="${PATH_SYS_CLASS_BLOCK}/${dev##*/}/size"
1250 [ -f "$sfile" ] || return 1
1251 read size < "$sfile" || {
1252 warn "failed reading from $sfile"
1253 return 1
1254 }
1255 # size is in 512 byte units. so convert to MB (integer division)
1256 if [ $((size / 2048)) -ge 10 ]; then
1257 debug 2 "$dev: size $((size / 2048))MB is considered too large for OVF"
1258 return 1
1259 fi
1260
1261 local idstr="http://schemas.dmtf.org/ovf/environment/1"
1262 # POSIX grep only supports short-options, long-options are GNU-specific
1263 grep -q -i "$idstr" "${PATH_ROOT}$dev"
1264 }
1265
1266 has_ovf_cdrom() {
1267 # DI_ISO9660_DEVS is <device>=label,<device>=label2
1268 # like /dev/sr0=OVF-TRANSPORT,/dev/other=with spaces
1269 if [ "${DI_ISO9660_DEVS#"${UNAVAILABLE}":}" = "${DI_ISO9660_DEVS}" ]; then
1270 local oifs="$IFS"
1271 # shellcheck disable=2086
1272 {
1273 IFS=","
1274 set -- ${DI_ISO9660_DEVS}
1275 IFS="$oifs"
1276 }
1277 for tok in "$@"; do
1278 is_cdrom_ovf "${tok%%=*}" "${tok#*=}" && return 0
1279 done
1280 fi
1281 return 1
1282 }
1283
1284 is_disabled() {
1285 if [ -f /etc/cloud/cloud-init.disabled ]; then
1286 debug 1 "disabled by marker file /etc/cloud/cloud-init.disabled"
1287 return 0
1288 fi
1289 if [ "${KERNEL_CMDLINE:-}" = "cloud-init=disabled" ]; then
1290 debug 1 "disabled by KERNEL_CMDLINE environment variable"
1291 return 0
1292 fi
1293 case "$DI_KERNEL_CMDLINE" in
1294 *cloud-init=disabled*)
1295 debug 1 "disabled by kernel command line cloud-init=disabled"
1296 return 0
1297 ;;
1298 esac
1299 return 1
1300 }
1301
1302 dscheck_OVF() {
1303 check_seed_dir ovf ovf-env.xml && return "${DS_FOUND}"
1304
1305 [ "${DI_VIRT}" = "none" ] && return ${DS_NOT_FOUND}
1306
1307 # Azure provides ovf. Skip false positive by dis-allowing.
1308 is_azure_chassis && return $DS_NOT_FOUND
1309
1310 ovf_vmware_transport_guestinfo && return "${DS_FOUND}"
1311
1312 has_ovf_cdrom && return "${DS_FOUND}"
1313
1314 return ${DS_NOT_FOUND}
1315 }
1316
1317 is_azure_chassis() {
1318 local azure_chassis="7783-7084-3265-9085-8269-3286-77"
1319 dmi_chassis_asset_tag_matches "${azure_chassis}"
1320 }
1321
1322 dscheck_Azure() {
1323 is_azure_chassis && return $DS_FOUND
1324 check_seed_dir azure ovf-env.xml && return ${DS_FOUND}
1325
1326 return ${DS_NOT_FOUND}
1327 }
1328
1329 dscheck_Bigstep() {
1330 # bigstep is activated by presence of seed file 'url'
1331 [ -f "${PATH_VAR_LIB_CLOUD}/data/seed/bigstep/url" ] &&
1332 return ${DS_FOUND}
1333 return ${DS_NOT_FOUND}
1334 }
1335
1336 ec2_read_strict_setting() {
1337 # the 'strict_id' setting for Ec2 controls behavior when
1338 # the platform does not identify itself directly as Ec2.
1339 # order of precedence is:
1340 # 1. builtin setting here cloud-init/ds-identify builtin
1341 # 2. ds-identify config
1342 # 3. system config (/etc/cloud/cloud.cfg.d/*Ec2*.cfg)
1343 # 4. kernel command line (undocumented)
1344 # 5. user-data or vendor-data (not available here)
1345 local default="$1" key="ci.datasource.ec2.strict_id" val=""
1346
1347 # 4. kernel command line
1348 case " ${DI_KERNEL_CMDLINE} " in
1349 *\ $key=*\ )
1350 val=${DI_KERNEL_CMDLINE##*"${key}"=}
1351 val=${val%% *}
1352 _RET=${val:-$default}
1353 return 0
1354 ;;
1355 esac
1356
1357 # 3. look for the key 'strict_id' (datasource/Ec2/strict_id)
1358 # only in cloud.cfg or cloud.cfg.d/EC2.cfg (case insensitive)
1359 local cfg="${PATH_ETC_CI_CFG}" cfg_d="${PATH_ETC_CI_CFG_D}"
1360 if check_config strict_id "$cfg" "$cfg_d/*[Ee][Cc]2*.cfg"; then
1361 debug 2 "${_RET_fname} set strict_id to $_RET"
1362 return 0
1363 fi
1364
1365 # 2. ds-identify config (datasource.ec2.strict)
1366 local config="${PATH_DI_CONFIG}"
1367 if [ -f "$config" ]; then
1368 if _read_config "$key" < "$config"; then
1369 _RET=${_RET:-$default}
1370 return 0
1371 fi
1372 fi
1373
1374 # 1. Default
1375 _RET=$default
1376 return 0
1377 }
1378
1379 ec2_identify_platform() {
1380 local default="$1"
1381 local serial="${DI_DMI_PRODUCT_SERIAL}"
1382
1383 case "$serial" in
1384 *.brightbox.com)
1385 _RET="Brightbox"
1386 return 0
1387 ;;
1388 esac
1389
1390 local asset_tag="${DI_DMI_CHASSIS_ASSET_TAG}"
1391 case "$asset_tag" in
1392 *.zstack.io)
1393 _RET="ZStack"
1394 return 0
1395 ;;
1396 esac
1397
1398 local vendor="${DI_DMI_SYS_VENDOR}"
1399 case "$vendor" in
1400 e24cloud)
1401 _RET="E24cloud"
1402 return 0
1403 ;;
1404 Tilaa)
1405 _RET="Tilaa"
1406 return 0
1407 ;;
1408 esac
1409
1410 local product_name="${DI_DMI_PRODUCT_NAME}"
1411 if [ "${product_name}" = "3DS Outscale VM" ] &&
1412 [ "${vendor}" = "3DS Outscale" ]; then
1413 _RET="Outscale"
1414 return 0
1415 fi
1416
1417 # AWS http://docs.aws.amazon.com/AWSEC2/
1418 # latest/UserGuide/identify_ec2_instances.html
1419 local uuid="" hvuuid="${PATH_SYS_HYPERVISOR}/uuid"
1420 # if the (basically) xen specific /sys/hypervisor/uuid starts with 'ec2'
1421 if [ -r "$hvuuid" ] && read uuid < "$hvuuid" &&
1422 [ "${uuid#ec2}" != "$uuid" ]; then
1423 _RET="AWS"
1424 return 0
1425 fi
1426
1427 # keep only the first octet
1428 local start_uuid="${DI_DMI_PRODUCT_UUID%%-*}"
1429 case "$start_uuid" in
1430 # example ec2 uuid:
1431 # EC2E1916-9099-7CAF-FD21-012345ABCDEF
1432 [Ee][Cc]2*)
1433 _RET="AWS"
1434 ;;
1435 # example ec2 uuid:
1436 # 45E12AEC-DCD1-B213-94ED-012345ABCDEF
1437 *2[0-9a-fA-F][Ee][Cc])
1438 _RET="AWS"
1439 ;;
1440 *)
1441 _RET="$default"
1442 ;;
1443 esac
1444 return 0
1445 }
1446
1447 dscheck_Ec2() {
1448 check_seed_dir "ec2" meta-data user-data && return ${DS_FOUND}
1449 is_container && return ${DS_NOT_FOUND}
1450
1451 local unknown="Unknown" platform=""
1452 if ec2_identify_platform "$unknown"; then
1453 platform="$_RET"
1454 else
1455 warn "Failed to identify ec2 platform. Using '$unknown'."
1456 platform=$unknown
1457 fi
1458
1459 debug 1 "ec2 platform is '$platform'."
1460 if [ "$platform" != "$unknown" ]; then
1461 return $DS_FOUND
1462 fi
1463
1464 local default="${DI_EC2_STRICT_ID_DEFAULT}"
1465 if ec2_read_strict_setting "$default"; then
1466 strict="$_RET"
1467 else
1468 debug 1 "ec2_read_strict returned non-zero: $?. using '$default'."
1469 strict="$default"
1470 fi
1471
1472 local key="datasource/Ec2/strict_id"
1473 case "$strict" in
1474 true | false | warn | warn,[0-9]*) : ;;
1475 *)
1476 warn "$key was set to invalid '$strict'. using '$default'"
1477 strict="$default"
1478 ;;
1479 esac
1480
1481 _RET_excfg="datasource: {Ec2: {strict_id: \"$strict\"}}"
1482 if [ "$strict" = "true" ]; then
1483 return $DS_NOT_FOUND
1484 else
1485 return $DS_MAYBE
1486 fi
1487 }
1488
1489 dscheck_GCE() {
1490 if dmi_product_name_matches "Google Compute Engine"; then
1491 return ${DS_FOUND}
1492 fi
1493 # product name is not guaranteed (LP: #1674861)
1494 if dmi_product_serial_matches "GoogleCloud-*"; then
1495 return ${DS_FOUND}
1496 fi
1497 return ${DS_NOT_FOUND}
1498 }
1499
1500 dscheck_OpenStack() {
1501 # the openstack metadata http service
1502
1503 # if there is a config drive, then do not check metadata
1504 # FIXME: if config drive not in the search list, then we should not
1505 # do this check.
1506 check_configdrive_v2
1507 if [ $? -eq ${DS_FOUND} ]; then
1508 return ${DS_NOT_FOUND}
1509 fi
1510 local nova="OpenStack Nova" compute="OpenStack Compute"
1511 if dmi_product_name_matches "$nova"; then
1512 return ${DS_FOUND}
1513 fi
1514 if dmi_product_name_matches "$compute"; then
1515 # RDO installed nova (LP: #1675349).
1516 return ${DS_FOUND}
1517 fi
1518 if [ "${DI_PID_1_PRODUCT_NAME}" = "$nova" ]; then
1519 return ${DS_FOUND}
1520 fi
1521
1522 if dmi_chassis_asset_tag_matches "OpenTelekomCloud"; then
1523 return ${DS_FOUND}
1524 fi
1525
1526 if dmi_chassis_asset_tag_matches "SAP CCloud VM"; then
1527 return ${DS_FOUND}
1528 fi
1529
1530 if dmi_chassis_asset_tag_matches "HUAWEICLOUD"; then
1531 return ${DS_FOUND}
1532 fi
1533
1534 if dmi_chassis_asset_tag_matches "Samsung Cloud Platform"; then
1535 return ${DS_FOUND}
1536 fi
1537
1538 # LP: #1669875 : allow identification of OpenStack by asset tag
1539 if dmi_chassis_asset_tag_matches "$nova"; then
1540 return ${DS_FOUND}
1541 fi
1542 if dmi_chassis_asset_tag_matches "$compute"; then
1543 return ${DS_FOUND}
1544 fi
1545
1546 # LP: #1715241 : arch other than intel are not identified properly.
1547 case "$DI_UNAME_MACHINE" in
1548 i?86 | x86_64) : ;;
1549 *) return ${DS_MAYBE} ;;
1550 esac
1551
1552 return ${DS_NOT_FOUND}
1553 }
1554
1555 dscheck_AliYun() {
1556 check_seed_dir "AliYun" meta-data user-data && return ${DS_FOUND}
1557 if dmi_product_name_matches "Alibaba Cloud ECS"; then
1558 return $DS_FOUND
1559 fi
1560 return $DS_NOT_FOUND
1561 }
1562
1563 dscheck_AltCloud() {
1564 # ctype: either the dmi product name, or contents of
1565 # /etc/sysconfig/cloud-info
1566 # if ctype == "vsphere"
1567 # device = device with label 'CDROM'
1568 # elif ctype == "rhev"
1569 # device = /dev/floppy
1570 # then, filesystem on that device must have
1571 # user-data.txt or deltacloud-user-data.txt
1572 local ctype="" dev=""
1573 local match_rhev="[Rr][Hh][Ee][Vv]"
1574 local match_vsphere="[Vv][Ss][Pp][Hh][Ee][Rr][Ee]"
1575 local cinfo="${PATH_ROOT}/etc/sysconfig/cloud-info"
1576 if [ -f "$cinfo" ]; then
1577 read ctype < "$cinfo"
1578 else
1579 ctype="${DI_DMI_PRODUCT_NAME}"
1580 fi
1581 case "$ctype" in
1582 "${match_rhev}")
1583 probe_floppy || return ${DS_NOT_FOUND}
1584 dev="/dev/floppy"
1585 ;;
1586 "${match_vsphere}")
1587 block_dev_with_label CDROM || return ${DS_NOT_FOUND}
1588 dev="$_RET"
1589 ;;
1590 *) return ${DS_NOT_FOUND} ;;
1591 esac
1592
1593 # FIXME: need to check $dev for user-data.txt or deltacloud-user-data.txt
1594 : "$dev"
1595 return $DS_MAYBE
1596 }
1597
1598 dscheck_SmartOS() {
1599 # joyent cloud has two virt types: kvm and container
1600 # on kvm, product name on joyent public cloud shows 'SmartDC HVM'
1601 # on the container platform, uname's version has: BrandZ virtual linux
1602 # for container, we also verify that the socketfile exists to protect
1603 # against embedded containers (lxd running on brandz)
1604 local smartdc_kver="BrandZ virtual linux"
1605 local metadata_sockfile="${PATH_ROOT}/native/.zonecontrol/metadata.sock"
1606 dmi_product_name_matches "SmartDC*" && return $DS_FOUND
1607 [ "${DI_UNAME_KERNEL_VERSION}" = "${smartdc_kver}" ] &&
1608 [ -e "${metadata_sockfile}" ] &&
1609 return ${DS_FOUND}
1610 return ${DS_NOT_FOUND}
1611 }
1612
1613 dscheck_None() {
1614 return ${DS_NOT_FOUND}
1615 }
1616
1617 dscheck_Scaleway() {
1618 if [ "${DI_DMI_SYS_VENDOR}" = "Scaleway" ]; then
1619 return $DS_FOUND
1620 fi
1621
1622 case " ${DI_KERNEL_CMDLINE} " in
1623 *\ scaleway\ *) return ${DS_FOUND} ;;
1624 esac
1625
1626 if [ -f "${PATH_ROOT}/var/run/scaleway" ]; then
1627 return ${DS_FOUND}
1628 fi
1629
1630 return ${DS_NOT_FOUND}
1631 }
1632
1633 dscheck_Hetzner() {
1634 dmi_sys_vendor_is Hetzner && return ${DS_FOUND}
1635 return ${DS_NOT_FOUND}
1636 }
1637
1638 dscheck_NWCS() {
1639 dmi_sys_vendor_is NWCS && return ${DS_FOUND}
1640 return ${DS_NOT_FOUND}
1641 }
1642
1643 dscheck_Oracle() {
1644 local asset_tag="OracleCloud.com"
1645 dmi_chassis_asset_tag_matches "${asset_tag}" && return ${DS_FOUND}
1646 return ${DS_NOT_FOUND}
1647 }
1648
1649 is_ibm_provisioning() {
1650 local pcfg="${PATH_ROOT}/root/provisioningConfiguration.cfg"
1651 local logf="${PATH_ROOT}/root/swinstall.log"
1652 local is_prov=false msg="config '$pcfg' did not exist."
1653 if [ -f "$pcfg" ]; then
1654 msg="config '$pcfg' exists."
1655 is_prov=true
1656 if [ -f "$logf" ]; then
1657 # shellcheck disable=3013
1658 if [ "$logf" -nt "$PATH_PROC_1_ENVIRON" ]; then
1659 msg="$msg log '$logf' from current boot."
1660 else
1661 is_prov=false
1662 msg="$msg log '$logf' from previous boot."
1663 fi
1664 else
1665 msg="$msg log '$logf' did not exist."
1666 fi
1667 fi
1668 debug 2 "ibm_provisioning=$is_prov: $msg"
1669 [ "$is_prov" = "true" ]
1670 }
1671
1672 is_ibm_cloud() {
1673 cached "${_IS_IBM_CLOUD}" && return "${_IS_IBM_CLOUD}"
1674 local ret=1
1675 if [ "$DI_VIRT" = "xen" ]; then
1676 if is_ibm_provisioning; then
1677 ret=0
1678 elif has_fs_with_label METADATA metadata; then
1679 ret=0
1680 elif has_fs_with_uuid 9796-932E &&
1681 has_fs_with_label CONFIG-2 config-2; then
1682 ret=0
1683 fi
1684 fi
1685 _IS_IBM_CLOUD=$ret
1686 return $ret
1687 }
1688
1689 dscheck_IBMCloud() {
1690 if is_ibm_provisioning; then
1691 debug 1 "cloud-init disabled during provisioning on IBMCloud"
1692 return ${DS_NOT_FOUND}
1693 fi
1694 is_ibm_cloud && return ${DS_FOUND}
1695 return ${DS_NOT_FOUND}
1696 }
1697
1698 dscheck_Vultr() {
1699 dmi_sys_vendor_is Vultr && return $DS_FOUND
1700
1701 case " $DI_KERNEL_CMDLINE " in
1702 *\ vultr\ *) return $DS_FOUND ;;
1703 esac
1704
1705 if [ -f "${PATH_ROOT}/etc/vultr" ]; then
1706 return $DS_FOUND
1707 fi
1708
1709 return $DS_NOT_FOUND
1710 }
1711
1712 vmware_has_envvar_vmx_guestinfo() {
1713 [ -n "${VMX_GUESTINFO:-}" ]
1714 }
1715
1716 vmware_has_envvar_vmx_guestinfo_metadata() {
1717 [ -n "${VMX_GUESTINFO_METADATA:-}" ]
1718 }
1719
1720 vmware_has_envvar_vmx_guestinfo_userdata() {
1721 [ -n "${VMX_GUESTINFO_USERDATA:-}" ]
1722 }
1723
1724 vmware_has_envvar_vmx_guestinfo_vendordata() {
1725 [ -n "${VMX_GUESTINFO_VENDORDATA:-}" ]
1726 }
1727
1728 dscheck_VMware() {
1729 # Checks to see if there is valid data for the VMware datasource.
1730 # The data transports are checked in the following order:
1731 #
1732 # * envvars
1733 # * guestinfo
1734 # * imc (VMware Guest Customization)
1735 #
1736 # Please note when updating this function with support for new data
1737 # transports, the order should match the order in the _get_data
1738 # function from the file DataSourceVMware.py.
1739
1740 # Check to see if running in a container and the VMware
1741 # datasource is configured via environment variables.
1742 if vmware_has_envvar_vmx_guestinfo; then
1743 if vmware_has_envvar_vmx_guestinfo_metadata ||
1744 vmware_has_envvar_vmx_guestinfo_userdata ||
1745 vmware_has_envvar_vmx_guestinfo_vendordata; then
1746 return "${DS_FOUND}"
1747 fi
1748 fi
1749
1750 # Do not proceed unless the detected platform is VMware.
1751 if [ ! "${DI_VIRT}" = "vmware" ]; then
1752 return "${DS_NOT_FOUND}"
1753 fi
1754
1755 # Do not proceed if neither the vmware-rpctool or vmtoolsd command exists.
1756 if ! vmware_has_rpctool && ! vmware_has_vmtoolsd; then
1757 return "${DS_NOT_FOUND}"
1758 fi
1759
1760 # Activate the VMware datasource only if any of the fields used
1761 # by the datasource are present in the guestinfo table.
1762 if { vmware_guestinfo_metadata ||
1763 vmware_guestinfo_userdata ||
1764 vmware_guestinfo_vendordata; } > /dev/null 2>&1; then
1765 return "${DS_FOUND}"
1766 fi
1767
1768 # Activate the VMware datasource only if tools plugin is available and
1769 # guest customization is enabled.
1770 vmware_guest_customization && return "${DS_FOUND}"
1771
1772 return "${DS_NOT_FOUND}"
1773 }
1774
1775 WSL_path() {
1776 local params="$1" path="$2" val=""
1777 val="$(wslpath "$params" "$path")"
1778 _RET="$val"
1779 }
1780
1781 WSL_run_cmd() {
1782 local val="" exepath="$1"
1783 shift
1784 # Using the '/u' flag to enforce Unicode (UTF-16 LE), thus we need to decode it afterwards.
1785 # It's more reliable than the default ANSI Code Pages for anything above the ASCII range.
1786 _RET=$(/init "$exepath" /u /c "$@" 2> /dev/null | iconv --from-code UTF-16LE --to-code UTF-8)
1787 }
1788
1789 WSL_profile_dir() {
1790 # Determine where a suitable user profile home is located
1791 _RET=""
1792 local cmdexe="" profiledir="" val=""
1793 # shellcheck disable=SC2068
1794 for m in $@; do
1795 cmdexe="$m/Windows/System32/cmd.exe"
1796 if command -v "$cmdexe" > /dev/null 2>&1; then
1797 # Here WSL's `/init` is used to start the Windows cmd.exe
1798 # to output the Windows user profile directory path, which is
1799 # held by the environment variable %USERPROFILE%.
1800 # See https://wsl.dev/technical-documentation/interop/ for more information on how /init
1801 # is used to launch Windows binaries.
1802 WSL_run_cmd "$cmdexe" "echo.%USERPROFILE%"
1803 profiledir="${_RET%%[[:cntrl:]]}"
1804 if [ -n "$profiledir" ]; then
1805 # wslpath is a program supplied by WSL itself that translates Windows and Linux paths,
1806 # respecting the mountpoints where the Windows drives are mounted.
1807 # (in fact it's a symlink to /init).
1808 WSL_path "-au" "$profiledir"
1809 return $?
1810 fi
1811 fi
1812 done
1813
1814 return 1
1815 }
1816
1817 WSL_instance_name() {
1818 local val="" instance_name=""
1819 WSL_path "-am" "/"
1820 instance_name="${_RET}"
1821 # Extracts "Ubuntu/" from "//wsl.localhost/Ubuntu/"
1822 val="${instance_name#//*/}"
1823 # Extracts "Ubuntu" from "Ubuntu/"
1824 _RET="${val%/}"
1825 }
1826
1827 dscheck_WSL() {
1828 local mountpoints="" cloudinitdir="" candidate="" instance_name=""
1829 if [ "${DI_UNAME_KERNEL_NAME}" != "Linux" ]; then
1830 return "${DS_NOT_FOUND}"
1831 fi
1832
1833 if [ "${DI_VIRT}" != "wsl" ]; then
1834 return "${DS_NOT_FOUND}"
1835 fi
1836
1837 # The datasource needs to find the cloud-config files in the Windows host
1838 # filesystem, which is exposed as 9p mount points, one per disk drive (partition).
1839 # If none is found, the datasource cannot proceed.
1840 # See https://youtu.be/lwhMThePdIo?t=2431&si=JKTHx39TyRgPbzkZ and
1841 # https://learn.microsoft.com/en-us/windows/wsl/wsl-config#what-is-drvfs
1842 # for more information.
1843 mountpoints=$(grep '^[^[:space:]]* [^[:space:]]* 9p [^[:space:]]*aname=drvfs;.*' "${PATH_ROOT}/proc/mounts" | cut -f2 -d' ')
1844
1845 if [ -z "$mountpoints" ]; then
1846 debug 1 "WSL datasource requires access to Windows drives mount points"
1847 return "${DS_NOT_FOUND}"
1848 fi
1849
1850 # We know we are under WSL and have access to the host filesystem,
1851 # so let's find the user's home directory
1852 WSL_profile_dir "$mountpoints"
1853 profile_dir="${_RET}"
1854 if [ -z "$profile_dir" ]; then
1855 debug 1 "%USERPROFILE% directory not found"
1856 return "${DS_NOT_FOUND}"
1857 fi
1858
1859 # Then we can check for any .cloud-init folders for the user
1860 if [ ! -d "$profile_dir/.cloud-init/" ] && [ ! -d "$profile_dir/.ubuntupro/.cloud-init/" ]; then
1861 debug 1 "No .cloud-init directories found in $profile_dir"
1862 return "${DS_NOT_FOUND}"
1863 fi
1864
1865 WSL_instance_name
1866 instance_name="${_RET}"
1867 # shellcheck source=/dev/null
1868 . "${PATH_ROOT}/etc/os-release"
1869
1870 # and the applicable userdata file. Notice the ordering in the for-loop
1871 # must match our expected precedence, so the file we find is what the
1872 # datasource must process.
1873 # We only care about ubuntupro configs if the distro is an Ubuntu distro.
1874 # shellcheck disable=SC2153
1875 if [ "$NAME" = "Ubuntu" ]; then
1876 cloudinitdir="$profile_dir/.ubuntupro/.cloud-init"
1877 for userdatafile in "${instance_name}.user-data" "agent.yaml"; do
1878 candidate="$cloudinitdir/$userdatafile"
1879 if [ -f "$candidate" ]; then
1880 debug 1 "Found applicable pro data file for this instance at: $candidate"
1881 return ${DS_FOUND}
1882 fi
1883 done
1884 fi
1885
1886 cloudinitdir="$profile_dir/.cloud-init"
1887 for userdatafile in "${instance_name}.user-data" "${ID:-linux}-${VERSION_ID:-${VERSION_CODENAME}}.user-data" "${ID:-linux}-all.user-data" "default.user-data"; do
1888 candidate="$cloudinitdir/$userdatafile"
1889 if [ -f "$candidate" ]; then
1890 debug 1 "Found applicable user data file for this instance at: $candidate"
1891 return ${DS_FOUND}
1892 fi
1893 done
1894
1895 debug 1 "Didn't find any applicable user data file for instance named $instance_name in $cloudinitdir"
1896
1897 return "${DS_NOT_FOUND}"
1898 }
1899
1900 collect_info() {
1901 read_pid1_product_name
1902 read_config
1903 read_datasource_list
1904 read_dmi_sys_vendor
1905 read_dmi_board_name
1906 read_dmi_chassis_asset_tag
1907 read_dmi_product_name
1908 read_dmi_product_serial
1909 read_dmi_product_uuid
1910 read_fs_info
1911 }
1912
1913 print_info() {
1914 read_uname_info
1915 collect_info
1916 _print_info
1917 }
1918
1919 _print_info() {
1920 local n="" v="" vars=""
1921 vars="DMI_PRODUCT_NAME DMI_SYS_VENDOR DMI_PRODUCT_SERIAL"
1922 vars="$vars DMI_PRODUCT_UUID PID_1_PRODUCT_NAME DMI_CHASSIS_ASSET_TAG"
1923 vars="$vars DMI_BOARD_NAME FS_LABELS ISO9660_DEVS KERNEL_CMDLINE VIRT"
1924 vars="$vars UNAME_KERNEL_NAME UNAME_KERNEL_VERSION UNAME_MACHINE"
1925 vars="$vars DSNAME DSLIST"
1926 vars="$vars MODE ON_FOUND ON_MAYBE ON_NOTFOUND"
1927 for v in ${vars}; do
1928 eval n='${DI_'"$v"'}'
1929 echo "$v=$n"
1930 done
1931 echo "pid=$$ ppid=$PPID"
1932 is_container && echo "is_container=true" || echo "is_container=false"
1933 }
1934
1935 write_result() {
1936 local runcfg="${PATH_RUN_CI_CFG}" ret="" line="" pre=""
1937 {
1938 if [ "$DI_MODE" = "report" ]; then
1939 echo "di_report:"
1940 pre=" "
1941 fi
1942 for line in "$@"; do
1943 echo "${pre}$line"
1944 done
1945 } > "$runcfg"
1946 ret=$?
1947 [ $ret -eq 0 ] || {
1948 error "failed to write to ${runcfg}"
1949 return $ret
1950 }
1951 return 0
1952 }
1953
1954 record_notfound() {
1955 # in report mode, report nothing was found.
1956 # if not report mode: only report the negative result.
1957 # reporting an empty list would mean cloud-init would not search
1958 # any datasources.
1959 if [ "$DI_MODE" = "report" ]; then
1960 found --
1961 elif [ "$DI_MODE" = "search" ]; then
1962 local msg="# reporting not found result. notfound=${DI_ON_NOTFOUND}."
1963 local DI_MODE="report"
1964 found -- "$msg"
1965 fi
1966 }
1967
1968 found() {
1969 # found(ds1, [ds2 ...], [-- [extra lines]])
1970 local list="" ds=""
1971 while [ $# -ne 0 ]; do
1972 if [ "$1" = "--" ]; then
1973 shift
1974 break
1975 fi
1976 list="${list:+${list}, }$1"
1977 shift
1978 done
1979 if [ $# -eq 1 ] && [ -z "$1" ]; then
1980 # do not pass an empty line through.
1981 shift
1982 fi
1983 # if None is not already in the list, then add it last.
1984 case " $list " in
1985 *\ None,\ * | *\ None\ ) : ;;
1986 *) list=${list:+${list}, None} ;;
1987 esac
1988 write_result "datasource_list: [ $list ]" "$@"
1989 return
1990 }
1991
1992 trim() {
1993 # trim all whitespace from the string, assign output to _RET
1994 local tmp="" cur="$*"
1995 until
1996 tmp="${cur#[[:space:]]}"
1997 [ "$tmp" = "$cur" ]
1998 do cur="$tmp"; done
1999 until
2000 tmp="${cur%[[:space:]]}"
2001 [ "$tmp" = "$cur" ]
2002 do cur="$tmp"; done
2003 _RET="$tmp"
2004 }
2005
2006 unquote() {
2007 # remove quotes from quoted value
2008 local quote='"' tick="'"
2009 local val="$1"
2010 case "$val" in
2011 ${quote}*${quote} | ${tick}*${tick})
2012 val=${val#?}
2013 val=${val%?}
2014 ;;
2015 esac
2016 _RET="$val"
2017 }
2018
2019 _read_config() {
2020 # reads config from stdin,
2021 # if no parameters are set, modifies _rc scoped environment vars.
2022 # if keyname is provided, then returns found value of that key.
2023 local keyname="${1:-_unset}"
2024 local line="" hash="#" key="" val=""
2025 while read line; do
2026 line=${line%%"${hash}"*}
2027 key="${line%%:*}"
2028
2029 # no : in the line.
2030 [ "$key" = "$line" ] && continue
2031 trim "$key"
2032 key=${_RET}
2033
2034 [ "$keyname" != "_unset" ] && [ "$keyname" != "$key" ] &&
2035 continue
2036
2037 val="${line#*:}"
2038 trim "$val"
2039 unquote "${_RET}"
2040 val=${_RET}
2041
2042 if [ "$keyname" = "$key" ]; then
2043 _RET="$val"
2044 return 0
2045 fi
2046
2047 case "$key" in
2048 datasource) _rc_dsname="$val" ;;
2049 policy) _rc_policy="$val" ;;
2050 esac
2051 done
2052 if [ "$keyname" = "_unset" ]; then
2053 return 1
2054 fi
2055 _RET=""
2056 return 0
2057 }
2058
2059 parse_warn() {
2060 echo "WARN: invalid value '$2' for key '$1'. Using $1=$3." 1>&2
2061 }
2062
2063 parse_def_policy() {
2064 local _rc_mode="" _rc_report="" _rc_found="" _rc_maybe="" _rc_notfound=""
2065 local ret=""
2066 parse_policy "$@"
2067 ret=$?
2068 _def_mode=$_rc_mode
2069 _def_report=$_rc_report
2070 _def_found=$_rc_found
2071 _def_maybe=$_rc_maybe
2072 _def_notfound=$_rc_notfound
2073 return $ret
2074 }
2075
2076 parse_policy() {
2077 # parse_policy(policy, default)
2078 # parse a policy string. sets
2079 # _rc_mode (enabled|disabled|search|report)
2080 # _rc_report true|false
2081 # _rc_found first|all
2082 # _rc_maybe all|none
2083 # _rc_notfound enabled|disabled
2084 local def=""
2085 case "$DI_UNAME_MACHINE" in
2086 # these have dmi data
2087 i?86 | x86_64) def=${DI_DEFAULT_POLICY} ;;
2088 # aarch64 has dmi, but not currently used (LP: #1663304)
2089 aarch64) def=${DI_DEFAULT_POLICY_NO_DMI} ;;
2090 *) def=${DI_DEFAULT_POLICY_NO_DMI} ;;
2091 esac
2092 local policy="$1"
2093 local _def_mode="" _def_report="" _def_found="" _def_maybe=""
2094 local _def_notfound=""
2095 if [ $# -eq 1 ] || [ "$2" != "-" ]; then
2096 def=${2:-${def}}
2097 parse_def_policy "$def" -
2098 fi
2099
2100 local mode="" report="" found="" maybe="" notfound=""
2101 local oifs="$IFS" tok="" val=""
2102 # shellcheck disable=2086
2103 {
2104 IFS=","
2105 set -- $policy
2106 IFS="$oifs"
2107 }
2108 for tok in "$@"; do
2109 val=${tok#*=}
2110 case "$tok" in
2111 "${DI_ENABLED}" | "${DI_DISABLED}" | search | report) mode=$tok ;;
2112 found=all | found=first) found=$val ;;
2113 maybe=all | maybe=none) maybe=$val ;;
2114 notfound="${DI_ENABLED}" | notfound="${DI_DISABLED}") notfound=$val ;;
2115 found=*)
2116 parse_warn found "$val" "${_def_found}"
2117 found=${_def_found}
2118 ;;
2119 maybe=*)
2120 parse_warn maybe "$val" "${_def_maybe}"
2121 maybe=${_def_maybe}
2122 ;;
2123 notfound=*)
2124 parse_warn notfound "$val" "${_def_notfound}"
2125 notfound=${_def_notfound}
2126 ;;
2127 esac
2128 done
2129 report=${report:-${_def_report:-false}}
2130 _rc_report=${report}
2131 _rc_mode=${mode:-${_def_mode}}
2132 _rc_found=${found:-${_def_found}}
2133 _rc_maybe=${maybe:-${_def_maybe}}
2134 _rc_notfound=${notfound:-${_def_notfound}}
2135 }
2136
2137 read_config() {
2138 local config="${PATH_DI_CONFIG}"
2139 local _rc_dsname="" _rc_policy="" ret=""
2140 if [ -f "$config" ]; then
2141 _read_config < "$config"
2142 ret=$?
2143 elif [ -e "$config" ]; then
2144 error "$config exists but is not a file!"
2145 ret=1
2146 fi
2147 local tok="" key="" val=""
2148 for tok in ${DI_KERNEL_CMDLINE}; do
2149 key=${tok%%=*}
2150 val=${tok#*=}
2151
2152 # discard anything after the first delimiter
2153 val=${val%%;*}
2154 case "$key" in
2155 ds) _rc_dsname="$val" ;;
2156 ci.ds) _rc_dsname="$val" ;;
2157 ci.datasource) _rc_dsname="$val" ;;
2158 ci.di.policy) _rc_policy="$val" ;;
2159 esac
2160 done
2161
2162 local _rc_mode _rc_report _rc_found _rc_maybe _rc_notfound
2163 parse_policy "${_rc_policy}"
2164 debug 1 "policy loaded: mode=${_rc_mode} report=${_rc_report}" \
2165 "found=${_rc_found} maybe=${_rc_maybe} notfound=${_rc_notfound}"
2166 DI_MODE=${_rc_mode}
2167 DI_ON_FOUND=${_rc_found}
2168 DI_ON_MAYBE=${_rc_maybe}
2169 DI_ON_NOTFOUND=${_rc_notfound}
2170
2171 DI_DSNAME="${_rc_dsname}"
2172 return $ret
2173 }
2174
2175 manual_clean_and_existing() {
2176 [ -f "${PATH_VAR_LIB_CLOUD}/instance/manual-clean" ]
2177 }
2178
2179 read_uptime() {
2180 local up _
2181 _RET="${UNAVAILABLE}"
2182 [ -f "$PATH_PROC_UPTIME" ] && read up _ < "$PATH_PROC_UPTIME" &&
2183 _RET="$up"
2184 return
2185 }
2186
2187 set_run_path() {
2188 if [ "$DI_UNAME_KERNEL_NAME" != "Linux" ]; then
2189 PATH_RUN=${PATH_RUN:-"${PATH_ROOT}/var/run"}
2190 else
2191 PATH_RUN=${PATH_RUN:-"${PATH_ROOT}/run"}
2192 fi
2193
2194 PATH_RUN_CI="${PATH_RUN_CI:-${PATH_RUN}/cloud-init}"
2195 PATH_RUN_CI_CFG=${PATH_RUN_CI_CFG:-${PATH_RUN_CI}/cloud.cfg}
2196 PATH_RUN_DI_RESULT=${PATH_RUN_DI_RESULT:-${PATH_RUN_CI}/.ds-identify.result}
2197
2198 DI_LOG="${DI_LOG:-${PATH_RUN_CI}/ds-identify.log}"
2199 }
2200
2201 # set ds-identify internal variables by providing an env file
2202 # testing only - NOT use for production code, it is NOT supported
2203 get_environment() {
2204 if [ -f "$PATH_DI_ENV" ]; then
2205 debug 0 "WARN: loading environment file [${PATH_DI_ENV}]"
2206 # shellcheck source=/dev/null
2207 . "$PATH_DI_ENV"
2208 fi
2209 }
2210
2211 _main() {
2212 local dscheck_fn="" ret_dis=1 ret_en=0
2213
2214 read_uptime
2215 debug 1 "[up ${_RET}s]" "ds-identify $*"
2216 read_virt
2217 read_kernel_cmdline
2218 if is_disabled; then
2219 return 2
2220 fi
2221 collect_info
2222
2223 if [ "$DI_LOG" = "stderr" ]; then
2224 _print_info 1>&2
2225 else
2226 _print_info >> "$DI_LOG"
2227 fi
2228
2229 case "$DI_MODE" in
2230 "${DI_DISABLED}")
2231 debug 1 "mode=$DI_DISABLED. returning $ret_dis"
2232 return $ret_dis
2233 ;;
2234 "${DI_ENABLED}")
2235 debug 1 "mode=$DI_ENABLED. returning $ret_en"
2236 return $ret_en
2237 ;;
2238 search | report) : ;;
2239 esac
2240
2241 if [ -n "${DI_DSNAME}" ]; then
2242 debug 1 "datasource '$DI_DSNAME' specified."
2243 found "$DI_DSNAME"
2244 return
2245 fi
2246
2247 if manual_clean_and_existing; then
2248 debug 1 "manual_cache_clean enabled. Not writing datasource_list."
2249 write_result "# manual_cache_clean."
2250 return
2251 fi
2252
2253 # shellcheck disable=2086
2254 set -- $DI_DSLIST
2255 # if there is only a single entry in $DI_DSLIST
2256 if [ $# -eq 1 ] || [ $# -eq 2 -a "$2" = "None" ]; then
2257 debug 1 "single entry in datasource_list ($DI_DSLIST) use that."
2258 if [ $# -eq 1 ]; then
2259 write_result "datasource_list: [ $1 ]"
2260 else
2261 found "$@"
2262 fi
2263 return
2264 fi
2265
2266 local found="" ret="" ds="" maybe="" _RET_excfg=""
2267 local exfound_cfg="" exmaybe_cfg=""
2268 for ds in ${DI_DSLIST}; do
2269 dscheck_fn="dscheck_${ds}"
2270 debug 2 "Checking for datasource '$ds' via '$dscheck_fn'"
2271 if ! type "$dscheck_fn" > /dev/null 2>&1; then
2272 warn "No check method '$dscheck_fn' for datasource '$ds'"
2273 continue
2274 fi
2275 _RET_excfg=""
2276 $dscheck_fn
2277 ret="$?"
2278 case "$ret" in
2279 "${DS_FOUND}")
2280 debug 1 "check for '$ds' returned found"
2281 exfound_cfg="${exfound_cfg:+${exfound_cfg}${CR}}${_RET_excfg}"
2282 found="${found} $ds"
2283 ;;
2284 "${DS_MAYBE}")
2285 debug 1 "check for '$ds' returned maybe"
2286 exmaybe_cfg="${exmaybe_cfg:+${exmaybe_cfg}${CR}}${_RET_excfg}"
2287 maybe="${maybe} $ds"
2288 ;;
2289 *) debug 2 "check for '$ds' returned not-found[$ret]" ;;
2290 esac
2291 done
2292
2293 debug 2 "found=${found# } maybe=${maybe# }"
2294 # shellcheck disable=2086
2295 set -- $found
2296 if [ $# -ne 0 ]; then
2297 if [ $# -eq 1 ]; then
2298 debug 1 "Found single datasource: $1"
2299 else
2300 # found=all
2301 debug 1 "Found $# datasources found=${DI_ON_FOUND}: $*"
2302 if [ "${DI_ON_FOUND}" = "first" ]; then
2303 set -- "$1"
2304 fi
2305 fi
2306 found "$@" -- "${exfound_cfg}"
2307 return
2308 fi
2309
2310 # shellcheck disable=2086
2311 set -- $maybe
2312 if [ $# -ne 0 -a "${DI_ON_MAYBE}" != "none" ]; then
2313 debug 1 "$# datasources returned maybe: $*"
2314 found "$@" -- "${exmaybe_cfg}"
2315 return
2316 fi
2317
2318 # record the empty result.
2319 record_notfound
2320
2321 local basemsg="No ds found [mode=$DI_MODE, notfound=$DI_ON_NOTFOUND]."
2322 local msg="" ret=3
2323 case "$DI_MODE:$DI_ON_NOTFOUND" in
2324 report:"${DI_DISABLED}")
2325 msg="$basemsg Would disable cloud-init [$ret_dis]"
2326 ret=$ret_en
2327 ;;
2328 report:"${DI_ENABLED}")
2329 msg="$basemsg Would enable cloud-init [$ret_en]"
2330 ret=$ret_en
2331 ;;
2332 search:"${DI_DISABLED}")
2333 msg="$basemsg Disabled cloud-init [$ret_dis]"
2334 ret=$ret_dis
2335 ;;
2336 search:"${DI_ENABLED}")
2337 msg="$basemsg Enabled cloud-init [$ret_en]"
2338 ret=$ret_en
2339 ;;
2340 *) error "Unexpected result" ;;
2341 esac
2342 debug 1 "$msg"
2343 return "$ret"
2344 }
2345
2346 main() {
2347 local ret=""
2348 get_environment
2349 ensure_sane_path
2350 read_uname_info
2351 set_run_path
2352
2353 [ -d "$PATH_RUN_CI" ] || mkdir -p "$PATH_RUN_CI"
2354 if [ "${1:+$1}" != "--force" ] && [ -f "$PATH_RUN_CI_CFG" ] &&
2355 [ -f "$PATH_RUN_DI_RESULT" ]; then
2356 if read ret < "$PATH_RUN_DI_RESULT"; then
2357 if [ "$ret" = "0" ] || [ "$ret" = "1" ] || [ "$ret" = "2" ]; then
2358 debug 2 "used cached result $ret. pass --force to re-run."
2359 return "$ret"
2360 fi
2361 debug 1 "previous run returned unexpected '$ret'. Re-running."
2362 else
2363 error "failed to read result from $PATH_RUN_DI_RESULT!"
2364 fi
2365 fi
2366 _main "$@"
2367 ret=$?
2368 echo "$ret" > "$PATH_RUN_DI_RESULT"
2369 read_uptime
2370 debug 1 "[up ${_RET}s]" "returning $ret"
2371 return "$ret"
2372 }
2373
2374 noop() {
2375 :
2376 }
2377
2378 get_environment
2379 case "${DI_MAIN}" in
2380 # builtin DI_MAIN implementations
2381 main | print_info | noop) "${DI_MAIN}" "$@" ;;
2382
2383 # side-load an alternate implementation
2384 # testing only - NOT use for production code, it is NOT supported
2385 *)
2386 debug 0 "WARN: side-loading alternate implementation: [${DI_MAIN}]"
2387 exec "${DI_MAIN}" "$@"
2388 ;;
2389 esac