Debian Codegraph @

lang/core/embedded/provisioner/main.mcl

raw
1 # Mgmt
2 # Copyright (C) 2013-2024+ James Shubin and the project contributors
3 # Written by James Shubin <[email protected]> and the project contributors
4 #
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <https://www.gnu.org/licenses/>.
17 #
18 # Additional permission under GNU GPL version 3 section 7
19 #
20 # If you modify this program, or any covered work, by linking or combining it
21 # with embedded mcl code and modules (and that the embedded mcl code and
22 # modules which link with this program, contain a copy of their source code in
23 # the authoritative form) containing parts covered by the terms of any other
24 # license, the licensors of this program grant you additional permission to
25 # convey the resulting work. Furthermore, the licensors of this program grant
26 # the original author, James Shubin, additional permission to update this
27 # additional permission if he deems it necessary to achieve the goals of this
28 # additional permission.
29
30 # Run `sudo setcap CAP_NET_BIND_SERVICE=+eip mgmt` first to avoid running as root.
31 # based on: https://docs.fedoraproject.org/en-US/fedora/f36/install-guide/advanced/Network_based_Installations/
32
33 import "convert"
34 import "deploy"
35 import "fmt"
36 import "golang"
37 import "golang/strings"
38 import "net"
39 import "os"
40 import "value"
41 import "world"
42
43 $http_suffix = "http/"
44 $tftp_suffix = "tftp/"
45 $uefi_suffix = "uefi/"
46 $kickstart_suffix = "kickstart/"
47
48 # The base class is the core provisioner which can also spawn child classes.
49 class base($config) {
50 #
51 # variables
52 #
53 $interface = $config->interface || "eth0" # XXX: what if no interface exists?
54 #$interface = _struct_lookup_optional($config, "interface", "eth0")
55
56 $http_port = $config->http_port || 4280 # using :4280 avoids needing root and isn't in /etc/services
57 $http_port_str = fmt.printf("%d", $http_port)
58
59 $network = $config->network || "192.168.42.0/24"
60 $router = $config->router || "192.168.42.1/24"
61 $router_ip = net.cidr_to_ip($router) # removes cidr suffix
62
63 $dns = $config->dns || ["8.8.8.8", "1.1.1.1",] # maybe google/cloudflare will sponsor!
64
65 $prefix = $config->prefix || ""
66 panic($prefix == "") # panic if prefix is empty
67 panic(not strings.has_suffix($prefix, "/"))
68
69 file "${prefix}" { # dir
70 state => $const.res.file.state.exists,
71 }
72 $tftp_prefix = "${prefix}${tftp_suffix}"
73 $http_prefix = "${prefix}${http_suffix}"
74 $uefi_prefix = "${prefix}${uefi_suffix}"
75
76 $firewalld = $config->firewalld || true
77
78 # eg: equivalent of: https://download.fedoraproject.org/pub/fedora/linux/
79 $inst_repo_base = "http://${router_ip}:${http_port_str}/fedora/" # private lan online, no https!
80
81 $syslinux_root = "/usr/share/syslinux/"
82
83 $nbp_bios = "tftp://${router_ip}/pxelinux.0" # for bios clients
84 $nbp_uefi = "tftp://${router_ip}/uefi/shim.efi" # for uefi clients
85
86 #
87 # network
88 #
89 net "${interface}" {
90 state => $const.res.net.state.up,
91 addrs => [$router,], # has cidr suffix
92 #gateway => "192.168.42.1", # TODO: get upstream public gateway with new function
93
94 ip_forward => true, # XXX: does this work?
95
96 Meta:reverse => true, # XXX: ^C doesn't reverse atm. Fix that!
97
98 Before => Dhcp:Server[":67"], # TODO: add autoedges
99 }
100
101 #
102 # packages
103 #
104 # TODO: do we need "syslinux-nonlinux" ?
105 $pkgs_bios = ["syslinux", "syslinux-nonlinux",]
106 $pkgs_uefi = ["shim-x64", "grub2-efi-x64",]
107 pkg $pkgs_bios {
108 state => "installed",
109 }
110 #pkg $pkgs_uefi {
111 # state => "installed",
112 #}
113
114 $pkgs_kickstart = ["fedora-kickstarts", "spin-kickstarts",]
115 pkg $pkgs_kickstart {
116 state => "installed",
117 }
118
119 #
120 # firewalld
121 #
122 if $firewalld {
123 firewalld "provisioner" { # name is irrelevant
124 services => [
125 "tftp",
126 "dhcp",
127 ],
128 ports => ["${http_port_str}/tcp",],
129
130 state => $const.res.firewalld.state.exists,
131 }
132 }
133
134 file "${tftp_prefix}" { # dir
135 state => $const.res.file.state.exists,
136 }
137 file "${uefi_prefix}" { # dir
138 state => $const.res.file.state.exists,
139 }
140
141 #
142 # tftp
143 #
144 tftp:server ":69" {
145 timeout => 60, # increase the timeout
146 #root => $root, # we're running in memory without needing a root!
147 #debug => true, # XXX: print out a `tree` representation in tmp prefix for the user
148
149 Depend => Pkg[$pkgs_bios], # hosted by tftp
150 #Depend => Pkg[$pkgs_uefi],
151 }
152
153 #
154 # bios bootloader images
155 #
156
157 # XXX: should this also be part of repo too?
158 class tftp_root_file($f) {
159 #tftp:file "${f}" { # without root slash
160 tftp:file "/${f}" { # with root slash
161 path => $syslinux_root + $f, # TODO: add autoedges
162
163 Depend => Pkg[$pkgs_bios],
164 }
165 }
166 include tftp_root_file("pxelinux.0")
167 include tftp_root_file("vesamenu.c32")
168 include tftp_root_file("ldlinux.c32")
169 include tftp_root_file("libcom32.c32")
170 include tftp_root_file("libutil.c32")
171
172 #
173 # dhcp
174 #
175 dhcp:server ":67" {
176 interface => $interface, # required for now
177 leasetime => "60s",
178 dns => $dns, # pick your own better ones!
179 routers => [$router_ip,],
180
181 serverid => $router_ip, # XXX: test automatic mode
182
183 #Depend => Net[$interface], # TODO: add autoedges
184 }
185
186 #
187 # http
188 #
189 file "${http_prefix}" { # dir
190 state => $const.res.file.state.exists,
191 }
192
193 http:server ":${http_port_str}" {
194 #address => ":${http_port_str}", # you can override the name like this
195 #timeout => 60, # add a timeout (seconds)
196 }
197
198 $kickstart_http_prefix = "${http_prefix}${kickstart_suffix}"
199 file "${kickstart_http_prefix}" {
200 state => $const.res.file.state.exists,
201 #source => "", # this default means empty directory
202 recurse => true,
203 purge => true, # remove unmanaged files in here
204 }
205
206 print "ready" {
207 msg => "ready to provision!",
208
209 Depend => Tftp:Server[":69"],
210 Depend => Dhcp:Server[":67"],
211 Depend => Http:Server[":${http_port_str}"],
212 }
213
214 # we're effectively returning a new class definition...
215 }
216
217 # The repo class which is a child of base, defines the distro repo to use.
218 class base:repo($config) {
219
220 $distro = $config->distro || "fedora"
221 $version = $config->version || "39" # not an int!
222 $arch = $config->arch || "x86_64"
223 #$flavour = $config->flavour || "" # is flavour needed for repo sync?
224
225 # export this value to parent scope for base:host to consume
226 $uid = "${distro}${version}-${arch}" # eg: fedora39-x86_64
227
228 # TODO: We need a way to pick a good default because if a lot of people
229 # use this, then most won't change it to one in their country...
230 $mirror = $config->mirror || "" # TODO: how do we pick a default?
231 $rsync = $config->rsync || ""
232
233 $is_fedora = $distro == "fedora"
234
235 $distroarch_tftp_prefix = "${tftp_prefix}${uid}/"
236 $distroarch_uefi_prefix = "${uefi_prefix}${uid}/"
237 $distroarch_http_prefix = "${http_prefix}${uid}/"
238 $distroarch_release_http_prefix = "${distroarch_http_prefix}release/"
239 $distroarch_updates_http_prefix = "${distroarch_http_prefix}updates/"
240
241 file "${distroarch_tftp_prefix}" { # dir
242 state => $const.res.file.state.exists,
243
244 #Meta:quiet => true, # TODO
245 }
246 file "${distroarch_uefi_prefix}" { # dir
247 state => $const.res.file.state.exists,
248 }
249 file "${distroarch_http_prefix}" { # root http dir
250 state => $const.res.file.state.exists,
251 }
252 file "${distroarch_release_http_prefix}" {
253 state => $const.res.file.state.exists,
254 }
255 file "${distroarch_updates_http_prefix}" {
256 state => $const.res.file.state.exists,
257 }
258
259 #
260 # uefi bootloader images
261 #
262 $uefi_download_dir = "${distroarch_uefi_prefix}download/"
263 $uefi_extract_dir = "${distroarch_uefi_prefix}extract/"
264
265 file "${uefi_extract_dir}" { # mkdir
266 state => $const.res.file.state.exists,
267
268 Depend => Exec["uefi-download-${uid}"],
269 Before => Exec["uefi-extract-${uid}"],
270 }
271
272 # Download the shim and grub2-efi packages. If your server is a BIOS
273 # system, you must download the packages to a temporary install root.
274 # Installing them directly on a BIOS machine will attempt to configure
275 # the system for UEFI booting and cause problems.
276 $pkgs_uefi_string = strings.join($pkgs_uefi, " ")
277 $repoidname = "local"
278 # eg: https://mirror.csclub.uwaterloo.ca/fedora/linux/releases/39/Everything/x86_64/os/
279 $repo_url = "http://${router_ip}:${http_port_str}/fedora/releases/${version}/Everything/${arch}/os/"
280
281 exec "uefi-download-${uid}" {
282 # no inner quotes because it's not bash handling this!
283 # the dnf download command makes the download destination dir
284 cmd => "/usr/bin/dnf download ${pkgs_uefi_string} --assumeyes --disablerepo=* --repofrompath ${repoidname},${repo_url} --downloaddir=${uefi_download_dir} --releasever ${version}",
285
286 # TODO: add an optional expiry mtime check that deletes these old files with an || rm * && false
287 ifcmd => "! test -s '${uefi_download_dir}shim-x64'*",
288 ifshell => "/usr/bin/bash",
289
290 Depend => Http:Server[":${http_port_str}"],
291 }
292
293 exec "uefi-extract-${uid}" {
294 # we use rpm2archive instead of cpio since the latter is deprecated for big files
295 # we do this in a loop for all the rpm files
296 cmd => "for i in ${uefi_download_dir}*.rpm; do /usr/bin/rpm2archive \$i | /usr/bin/tar -xvz --directory ${uefi_extract_dir} --exclude ./etc; done",
297 shell => "/usr/bin/bash",
298
299 # TODO: add an optional expiry mtime check that deletes these old files with an || rm * && false
300 creates => $uefi_shim,
301
302 Depend => Exec["uefi-download-${uid}"],
303 Before => Tftp:Server[":69"],
304 }
305
306 $uefi_root = "${uefi_extract_dir}/boot/efi/EFI/fedora/"
307 $uefi_shim = "${uefi_root}shim.efi"
308 tftp:file "/uefi/shim.efi" { # needs leading slash
309 path => $uefi_shim, # TODO: add autoedges
310
311 Depend => Exec["uefi-extract-${uid}"],
312 }
313 tftp:file "/uefi/grubx64.efi" { # sometimes used?
314 path => "${uefi_root}grubx64.efi", # TODO: add autoedges
315
316 Depend => Exec["uefi-extract-${uid}"],
317 }
318 tftp:file "grubx64.efi" { # no leading slash
319 path => "${uefi_root}grubx64.efi", # TODO: add autoedges
320
321 Depend => Exec["uefi-extract-${uid}"],
322 }
323
324 # XXX: replace with a download resource
325 # XXX: allow send->recv to pass this file to tftp:file->data to keep it in mem!
326 $vmlinuz_file = "${distroarch_tftp_prefix}vmlinuz"
327 exec "vmlinuz-${uid}" {
328 cmd => "/usr/bin/wget",
329 args => [
330 "--no-verbose",
331 "${repo_url}images/pxeboot/vmlinuz",
332 "-O",
333 $vmlinuz_file,
334 ],
335 creates => $vmlinuz_file,
336
337 Depend => File[$distroarch_tftp_prefix],
338 Depend => Http:Server[":${http_port_str}"],
339 Before => Print["ready"],
340 }
341
342 tftp:file "/${uid}/vmlinuz" {
343 path => $vmlinuz_file, # TODO: add autoedges
344
345 #Depend => Pkg[$pkgs],
346 }
347
348 $initrd_file = "${distroarch_tftp_prefix}initrd.img"
349 exec "initrd-${uid}" {
350 cmd => "/usr/bin/wget",
351 args => [
352 "--no-verbose",
353 "${repo_url}images/pxeboot/initrd.img",
354 "-O",
355 $initrd_file,
356 ],
357 creates => $initrd_file,
358
359 Depend => File[$distroarch_tftp_prefix],
360 Depend => Http:Server[":${http_port_str}"],
361 Before => Print["ready"],
362 }
363
364 tftp:file "/${uid}/initrd.img" {
365 path => $initrd_file, # TODO: add autoedges
366
367 #Depend => Pkg[$pkgs],
368 }
369
370 # this file resource serves the entire rsync directory over http
371 if $mirror == "" { # and $rsync != ""
372 http:file "/fedora/releases/${version}/Everything/${arch}/os/" {
373 path => $distroarch_release_http_prefix,
374 }
375 http:file "/fedora/updates/${version}/Everything/${arch}/" {
376 path => $distroarch_updates_http_prefix,
377 }
378 } else {
379 # same as the above http:file path would have been
380 http:proxy "/fedora/releases/${version}/Everything/${arch}/os/" {
381 sub => "/fedora/", # we remove this from the name!
382 head => $mirror,
383
384 cache => $distroarch_release_http_prefix, # $prefix/http/fedora39-x86_64/release/
385 }
386
387 # XXX: if we had both of these in the same http_prefix, we could overlap them with an rsync :/ hmm...
388 http:proxy "/fedora/updates/${version}/Everything/${arch}/" { # no os/ dir at the end
389 sub => "/fedora/", # we remove this from the name!
390 head => $mirror,
391
392 cache => $distroarch_updates_http_prefix, # $prefix/http/fedora39-x86_64/updates/
393 }
394 }
395
396 #
397 # rsync
398 #
399 #$source_pattern = if $is_fedora {
400 # "${rsync}releases/${version}/Everything/${arch}/os/" # source
401 #} else {
402 # "" # XXX: not implemented
403 #}
404 #panic($source_pattern == "") # distro is not specified
405 # TODO: combine release and updates?
406 #$is_safe = $distroarch_release_http_prefix != "" and $distroarch_release_http_prefix != "/"
407 #if $rsync != "" and $source_pattern != "" and $is_safe {
408 #
409 # $mtime_file = "${http_prefix}rsync-${uid}.mtime"
410 # $delta = convert.int_to_str(60 * 60 * 24 * 7) # ~1 week in seconds: 604800
411 # exec "rsync-${uid}" {
412 # cmd => "/usr/bin/rsync",
413 # args => [
414 # "-avSH",
415 # "--progress",
416 # # This flavour must always be Everything to work.
417 # # The Workstation flavour doesn't have an os/ dir.
418 # $source_pattern, # source
419 # $distroarch_release_http_prefix, # dest
420 # ],
421 #
422 # # run this when cmd completes successfully
423 # donecmd => "/usr/bin/date --utc > ${mtime_file}",
424 # doneshell => "/usr/bin/bash",
425 #
426 # # Run if the difference between the current date and the
427 # # saved date (both converted to sec) is greater than the
428 # # delta! (Or if the mtime file does not even exist yet.)
429 # ifcmd => "! /usr/bin/test -e ${mtime_file} || /usr/bin/test \$((`/usr/bin/date +%s` - `/usr/bin/stat -c %Y '${mtime_file}'`)) -gt ${delta}",
430 #
431 # ifshell => "/usr/bin/bash",
432 #
433 # Before => Http:Server[":${http_port_str}"],
434 # Before => File[$distroarch_release_http_prefix],
435 # }
436 #}
437 }
438
439 # The host class is used for each physical host we want to provision.
440 class base:host($name, $config) {
441 #print $name {
442 # msg => "host: ${name}",
443 #
444 # Meta:autogroup => false,
445 #}
446 $repouid = $config->repo || ""
447 $uidst = os.parse_distro_uid($repouid)
448 $distro = $uidst->distro
449 $version = $uidst->version # not an int!
450 $arch = $uidst->arch
451 panic($distro == "")
452 panic($version == "")
453 panic($arch == "")
454 $flavour = $config->flavour || ""
455
456 $mac = $config->mac || ""
457 #panic($mac == "") # provision anyone by default
458 $ip = $config->ip || "" # XXX: auto-generate it inside of the above network somehow (see below)
459 panic($ip == "")
460 #$ns = if $config->ip == "" {
461 # ""
462 #} else {
463 # "" + get_value("network") # XXX: implement some sort of lookup function
464 #}
465 #$ip = $config->ip || magic.pool($ns, [1,2,3,4], $name) # XXX: if $ns is "", then don't allocate. Otherwise get from list. Re-use based on $name hash.
466 $bios = $config->bios || false
467 $password = $config->password || "" # empty means disabled
468 panic(len($password) != 0 and len($password) != 106) # length of salted password
469
470 $part = $config->part || "" # partitioning scheme
471
472 $empty_list_str []str = [] # need an explicit type on empty list definition
473 $packages = $config->packages || $empty_list_str
474
475 # should we provision this host by default?
476 $provision_default = $config->provision || false # false is safest!
477
478 # unique host key which is usually a mac address unless it's a default
479 $hkey = if $mac == "" {
480 "default"
481 } else {
482 $mac
483 }
484 $provision_key = $hkey # XXX: what unique id should we use for the host? mac? name? hkey?
485
486 #$ret = world.getval($provision_key) # has it previously been provisioned?
487 #$val = if $ret->value == "" { # avoid an invalid string killing the parse_bool function
488 # convert.format_bool(false) # "false"
489 #} else {
490 # $ret->value
491 #}
492 #$provision = if not $ret->exists {
493 # $provision_default
494 #} else {
495 # not convert.parse_bool($val) # XXX: should an invalid string return false or error here?
496 #}
497 $provision = true
498
499 $nbp_path = if $bios {
500 "/pxelinux.0" # for bios clients
501 } else {
502 "/uefi/shim.efi" # for uefi clients
503 }
504
505 if $mac != "" {
506 dhcp:host "${name}" { # the hostname
507 mac => $mac,
508 ip => $ip, # cidr notation is required
509
510 nbp => $provision ?: if $bios { # XXX: do we want this from the base class?
511 $nbp_bios # from base class
512 } else {
513 $nbp_uefi # from base class
514 },
515 nbp_path => $provision ?: $nbp_path, # with leading slash
516
517 Depend => Tftp:Server[":69"],
518 }
519 } else {
520 # Handle ANY mac address since we don't have one specified!
521 # TODO: Our dhcp:range could send/recv a map from ip => mac address!
522 dhcp:range "${name}" {
523 network => "${network}", # eg: 192.168.42.0/24
524 skip => [$router,], # eg: 192.168.42.1/24
525
526 nbp => $provision ?: if $bios { # XXX: do we want this from the base class?
527 $nbp_bios # from base class
528 } else {
529 $nbp_uefi # from base class
530 },
531 nbp_path => $provision ?: $nbp_path, # with leading slash
532
533 Depend => Tftp:Server[":69"],
534 }
535 }
536
537 $tftp_menu_template = struct{
538 distro => $distro,
539 version => $version, # 39 for fedora 39
540 arch => $arch, # could also be aarch64
541 flavour => "Everything", # The install repo uses "Everything" even for "Workstation" or "Server"
542
543 ks => "http://${router_ip}:${http_port_str}/fedora/kickstart/${hkey}.ks", # usually $mac or `default`
544 inst_repo_base => $inst_repo_base,
545 }
546
547 #
548 # default menus
549 #
550 $safe_mac = if $mac == "" {
551 "00:00:00:00:00:00"
552 } else {
553 $mac
554 }
555 $old_mac = net.oldmacfmt($safe_mac)
556 # no idea why these need a 01- prefix
557 $bios_menu = if $mac == "" {
558 "/pxelinux.cfg/default"
559 } else {
560 # /pxelinux.cfg/01-00-11-22-33-44-55-66
561 "/pxelinux.cfg/01-${old_mac}"
562 }
563 $uefi_menu = if $mac == "" {
564 # XXX: add the front slash!?
565 #"pxelinux/uefi" # TODO: Did some machines use this?
566 "/uefi/grub.cfg"
567 } else {
568 # /uefi/grub.cfg-01-00-11-22-33-44-55-66
569 "/uefi/grub.cfg-01-${old_mac}"
570 }
571
572 if $bios {
573 tftp:file "${bios_menu}" { # for bios
574 data => golang.template(deploy.readfile("/files/bios-menu.tmpl"), $tftp_menu_template),
575 }
576 } else {
577 tftp:file "${uefi_menu}" { # for uefi
578 # XXX: linuxefi & initrdefi VS. kernel & append ?
579 data => golang.template(deploy.readfile("/files/uefi-menu.tmpl"), $tftp_menu_template),
580
581 #Depend => Pkg[$pkgs_uefi],
582 #Depend => Exec["uefi-extract"],
583 }
584 }
585
586 $http_kickstart_template = struct{
587 comment => "hello!",
588 lang => [
589 "en_CA.UTF-8",
590 "fr_CA.UTF-8",
591 "en_US.UTF-8",
592 ],
593 password => $password, # salted
594 bios => $bios,
595 part => $part,
596 flavour => $flavour,
597 url => "http://${router_ip}:${http_port_str}/fedora/releases/${version}/Everything/${arch}/os/",
598 repos => {
599 #"fedora" => "http://${router_ip}:${http_port_str}/fedora/releases/${version}/Everything/${arch}/os/", # TODO: this vs url ?
600 "updates" => "http://${router_ip}:${http_port_str}/fedora/updates/${version}/Everything/${arch}/",
601 },
602 #repos => { # needs internet or blocks at storage https://bugzilla.redhat.com/show_bug.cgi?id=2269752
603 # "fedora" => "https://mirrors.fedoraproject.org/mirrorlist?repo=fedora-\$releasever&arch=\$basearch",
604 # "updates" => "https://mirrors.fedoraproject.org/mirrorlist?repo=updates-released-f\$releasever&arch=\$basearch",
605 #},
606 packages => $packages,
607 post => [
608 "/usr/bin/wget --post-data 'done=true&password=sha1TODO' -O - 'http://${router_ip}:${http_port_str}/action/done/mac=${provision_key}'",
609 ],
610 }
611
612 $kickstart_file = "${kickstart_http_prefix}${hkey}.ks"
613 file "${kickstart_file}" {
614 state => $const.res.file.state.exists,
615 content => golang.template(deploy.readfile("/files/kickstart.ks.tmpl"), $http_kickstart_template),
616 }
617
618 http:file "/fedora/kickstart/${hkey}.ks" { # usually $mac or `default`
619 #data => golang.template(deploy.readfile("/files/kickstart.ks.tmpl"), $http_kickstart_template),
620 path => $kickstart_file,
621
622 Before => Print["ready"],
623 }
624
625 ##$str_true = convert.format_bool(true)
626 ##$str_false = convert.format_bool(false)
627 #http:flag "${name}" {
628 # key => "done",
629 # path => "/action/done/mac=${provision_key}",
630 # #mapped => {$str_true => $str_true, $str_false => $str_false,},
631 #}
632 #kv "${name}" {
633 # key => $provision_key,
634 #}
635 #value "${provision_key}" {
636 # #any => true, # bool
637 #}
638 #Http:Flag["${name}"].value -> Kv["${name}"].value
639 #Http:Flag["${name}"].value -> Value["${provision_key}"].any
640 ##$st_provisioned = value.get_bool($provision_key)
641 #$st_provisioned = value.get_str($provision_key)
642 #$provisioned = $st_provisioned->ready and $st_provisioned->value == "true" # export this value to parent scope
643 }