provisioning tool for building opinionated architecture
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

533 lines
16 KiB

9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
7 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
7 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
  1. #!/bin/bash
  2. MIAOU_BASEDIR=$(readlink -f "$(dirname "$0")/..")
  3. readonly MIAOU_BASEDIR
  4. # shellcheck source=/dev/null
  5. . "$MIAOU_BASEDIR/lib/functions.sh"
  6. miaou_init
  7. EXPANDED_CONF="$MIAOU_CONFIGDIR/miaou.expanded.yaml"
  8. NEW_GROUP=lxd
  9. readonly NEW_GROUP EXPANDED_CONF
  10. on_exit() {
  11. if [ -n "${1:-}" ]; then
  12. echowarn "Aborted by $1"
  13. elif [ "${status:-}" -ne 0 ]; then
  14. echowarn "Failure (status $status)"
  15. fi
  16. }
  17. function prepare_lxd {
  18. local PREFIX="lxd:prepare"
  19. # test group lxd assign to current user
  20. if ! groups | grep -q lxd; then
  21. echo "define lxd and assign to user <$USER>"
  22. sudo groupadd --force "$NEW_GROUP"
  23. sudo usermod --append --groups "$NEW_GROUP" "$(whoami)"
  24. realcommand="$MIAOU_BASEDIR/lib/install.sh"
  25. sg "$NEW_GROUP" -c "EMAIL=$valid_email $realcommand SESSION_RELOAD_REQUIRED $TARGET"
  26. set +e
  27. disable_all_signals
  28. sudo su - "$(whoami)"
  29. kill -9 "$PPID"
  30. # no further processing because exec has been called!
  31. else
  32. echo "user <$USER> already belongs to group <lxd>!"
  33. fi
  34. sudo /opt/miaou-bash/tools/idem_apt_install lxd btrfs-progs
  35. sudo tee /etc/systemd/system/lxd-containers-restart-on-failure.service &>/dev/null <<EOF
  36. [Unit]
  37. Description=restart lxd containers when no dhclient
  38. After=lxd.service lxd-containers.service
  39. Requires=lxd.socket
  40. StartLimitInterval=60
  41. StartLimitBurst=5
  42. [Service]
  43. Type=exec
  44. ExecCondition=sh -c '[ \$(lxc list status=running -c4 -fcsv | wc -l) -gt 0 ]] && lxc list status=running -c4 -fcsv | grep -vq eth0'
  45. ExecStart=systemctl restart lxd-containers.service
  46. ExecStartPost=sh -c 'sleep 2 ; [ \$(lxc list status=running -c4 -fcsv | wc -l) -eq 0 ]] || lxc list status=running -c4 -fcsv | grep -q eth0'
  47. Restart=on-failure
  48. RestartSec=10
  49. [Install]
  50. WantedBy=multi-user.target
  51. EOF
  52. sudo systemctl daemon-reload
  53. }
  54. function configure_lxd {
  55. local PREFIX="lxd:configure"
  56. # test lxdbr0 FIXME: preseed too much repetitions!!!!
  57. if ! lxc network info lxdbr0 &>/dev/null; then
  58. echo "bridge <lxdbr0> down, so initialization will use default preseed..."
  59. if [[ $(printenv container) == 'lxc' ]]; then
  60. echo "--------------------------------"
  61. echo "nested configuration applying..."
  62. echo "--------------------------------"
  63. cat <<EOF | sg $NEW_GROUP -c 'lxd init --preseed'
  64. config: {}
  65. networks:
  66. - name: lxdbr0
  67. type: bridge
  68. config:
  69. ipv4.address: auto
  70. ipv6.address: none
  71. storage_pools:
  72. - config: {}
  73. description: ""
  74. name: default
  75. driver: dir
  76. profiles:
  77. - config:
  78. security.privileged: "true"
  79. description: ""
  80. devices:
  81. eth0:
  82. name: eth0
  83. nictype: bridged
  84. parent: lxdbr0
  85. type: nic
  86. root:
  87. path: /
  88. pool: default
  89. type: disk
  90. name: default
  91. projects: []
  92. cluster: null
  93. EOF
  94. else
  95. #empty_block_partition=$(lsblk -o NAME,FSTYPE,GROUP --noheadings -p | grep -E ^.─ | grep disk | awk '{if($3=="") print $1}' | cut -d'/' -f3)
  96. empty_block_partition=$(lsblk -o NAME,PTTYPE,FSTYPE -ti -P | grep 'PTTYPE="" FSTYPE=""' | head -n1 | cut -d'"' -f2)
  97. if [[ -n "$empty_block_partition" ]]; then
  98. echo "--------------------------------"
  99. echo "use empty block partition /dev/$empty_block_partition for speed and optimization"
  100. echo "--------------------------------"
  101. cat <<EOF | sudo lxd init --preseed
  102. config: {}
  103. networks:
  104. - config:
  105. ipv4.address: auto
  106. ipv6.address: none
  107. description: ""
  108. name: lxdbr0
  109. type: ""
  110. project: default
  111. storage_pools:
  112. - config:
  113. source: /dev/$empty_block_partition
  114. description: ""
  115. name: default
  116. driver: btrfs
  117. profiles:
  118. - config: {}
  119. description: ""
  120. devices:
  121. eth0:
  122. name: eth0
  123. network: lxdbr0
  124. type: nic
  125. root:
  126. path: /
  127. pool: default
  128. type: disk
  129. name: default
  130. projects: []
  131. cluster: null
  132. EOF
  133. else
  134. echo "--------------------------------"
  135. echo "use dir partition for development purpose"
  136. echo "--------------------------------"
  137. cat <<EOF | lxd init --preseed
  138. config: {}
  139. networks:
  140. - name: lxdbr0
  141. type: bridge
  142. config:
  143. ipv4.address: auto
  144. ipv6.address: none
  145. storage_pools:
  146. - config: {}
  147. description: ""
  148. name: default
  149. driver: dir
  150. profiles:
  151. - config: {}
  152. description: ""
  153. devices:
  154. eth0:
  155. name: eth0
  156. network: lxdbr0
  157. type: nic
  158. root:
  159. path: /
  160. pool: default
  161. type: disk
  162. name: default
  163. projects: []
  164. cluster: null
  165. EOF
  166. fi
  167. fi
  168. else
  169. echo "bridge <lxdbr0> found implies it has been already initialized!"
  170. fi
  171. set_alias 'sameuser' "exec @ARG1@ -- su --whitelist-environment container,container_hostname - $(whoami)"
  172. set_alias 'login' 'exec @ARGS@ --mode interactive -- /bin/bash -c $@${user:-root} - exec su --whitelist-environment container,container_hostname - '
  173. set_alias 'll' 'list -c ns4mDN'
  174. # test environment container hostname
  175. local env_container_hostname
  176. env_container_hostname=$(sg $NEW_GROUP -c 'lxc profile get default environment.container_hostname')
  177. if [[ -z "$env_container_hostname" ]]; then
  178. env_container_hostname=$(hostname -s)
  179. if env | grep -q container_hostname; then
  180. local previous_container_hostname
  181. previous_container_hostname=$(env | grep container_hostname | cut -d '=' -f2)
  182. env_container_hostname="$previous_container_hostname $env_container_hostname"
  183. fi
  184. echo -n "set environment container_hostname to <$env_container_hostname> ... "
  185. sg $NEW_GROUP -c "lxc profile set default environment.container_hostname \"$env_container_hostname\""
  186. PREFIX="" echoinfo DONE
  187. else
  188. echo "environment container_hostname <$env_container_hostname> already defined!"
  189. fi
  190. if ! grep -q "root:$(id -u):1" /etc/subuid; then
  191. echo -n "saving subuid, subgid permissions for <$(whoami)> ..."
  192. printf "root:$(id -u):1\n" | sudo tee -a /etc/subuid /etc/subgid &>/dev/null
  193. PREFIX="" echoinfo DONE
  194. else
  195. echo "subuid, subgid allowing <$(whoami)> already done!"
  196. fi
  197. if [[ ! -d "$HOME/LXD/SHARED" ]]; then
  198. echo -n "$HOME/LXD/SHARED creating ... "
  199. mkdir "$HOME/LXD/SHARED" -p
  200. PREFIX="" echoinfo DONE
  201. else
  202. echo "folder <$HOME/LXD/SHARED> already created!"
  203. fi
  204. if [[ ! -d "$HOME/LXD/BACKUP" ]]; then
  205. echo -n "$HOME/LXD/BACKUP creating ... "
  206. mkdir "$HOME/LXD/BACKUP" -p
  207. PREFIX="" echoinfo DONE
  208. else
  209. echo "folder <$HOME/LXD/BACKUP> already created!"
  210. fi
  211. }
  212. function set_alias {
  213. local name="$1"
  214. local command="$2"
  215. if ! lxc alias list -f csv | grep -q "^$name,"; then
  216. echo -n "defining new lxc alias <$name> ..."
  217. lxc alias add "$name" "$command"
  218. PREFIX="" echoinfo DONE
  219. else
  220. echo "lxc alias <$name> already defined!"
  221. fi
  222. }
  223. function miaou_evalfrombashrc() {
  224. local PREFIX="miaou:bashrc"
  225. output=$(
  226. /opt/miaou-bash/tools/append_or_replace \
  227. "^eval \"\\$\($MIAOU_BASEDIR/lib/install.sh shellenv\)\"$" \
  228. "eval \"\$($MIAOU_BASEDIR/lib/install.sh shellenv)\"" \
  229. "$HOME/.bashrc"
  230. )
  231. if [[ "$output" == "appended" ]]; then
  232. echo "new path <$MIAOU_BASEDIR> created!"
  233. SESSION_RELOAD_REQUIRED=true
  234. else
  235. echo "path <$MIAOU_BASEDIR> already loaded!"
  236. fi
  237. }
  238. function ask_target() {
  239. PS3='Choose miaou target purpose: '
  240. foods=("Dev" "Beta" "Prod")
  241. select ans in "${foods[@]}"; do
  242. builtin echo "${ans^^}"
  243. break
  244. done
  245. }
  246. function check_credential {
  247. local PREFIX="check:credential"
  248. check_yaml_defined_value /etc/miaou/defaults.yaml 'credential.username' &&
  249. check_yaml_defined_value /etc/miaou/defaults.yaml 'credential.shadow' &&
  250. check_yaml_defined_value /etc/miaou/defaults.yaml 'credential.email'
  251. }
  252. function check_target() {
  253. case "${TARGET^^}" in
  254. DEV) ;;
  255. BETA) ;;
  256. PROD) ;;
  257. *)
  258. if [[ -f /etc/miaou/defaults.yaml ]]; then
  259. # load already defined target in expanded conf
  260. TARGET=$(grep -Es "^target:" /etc/miaou/defaults.yaml | cut -d ' ' -f2)
  261. else
  262. TARGET=$(ask_target)
  263. fi
  264. ;;
  265. esac
  266. TARGET=${TARGET,,} # downcase
  267. return 0
  268. }
  269. function miaou_configfiles() {
  270. local PREFIX="miaou:config"
  271. if [[ ! -d /etc/miaou ]]; then
  272. echo -n "configuration initializing ..."
  273. sudo mkdir -p /etc/miaou
  274. sudo chown "$USER" /etc/miaou
  275. PREFIX="" echoinfo DONE
  276. fi
  277. if [[ ! -f /etc/miaou/defaults.yaml ]]; then
  278. echo -n "building /etc/miaou/defaults.yaml for the first time..."
  279. shadow_passwd=$(sudo grep "$CURRENT_USER" /etc/shadow | cut -d ':' -f2)
  280. env current_user="$CURRENT_USER" shadow_passwd="$shadow_passwd" valid_email="$valid_email" tera -e --env-key env --env-only -t "$MIAOU_BASEDIR/templates/etc/defaults.yaml.j2" -o /etc/miaou/defaults.yaml >/dev/null
  281. yq ".target=\"$TARGET\"" /etc/miaou/defaults.yaml -i
  282. PREFIX="" echoinfo DONE
  283. fi
  284. if [[ ! -f /etc/miaou/miaou.yaml ]]; then
  285. echo -n "building /etc/miaou/miaou.yaml for the first time..."
  286. cp "$MIAOU_BASEDIR/templates/etc/miaou.yaml.j2" /etc/miaou/miaou.yaml
  287. PREFIX="" echoinfo DONE
  288. fi
  289. PREVIOUS_TARGET=""
  290. echo "expanded configuration stored in <$MIAOU_CONFIGDIR>!"
  291. [[ -f "$EXPANDED_CONF" ]] && PREVIOUS_TARGET=$(grep -Es "^target:" "$EXPANDED_CONF" | cut -d ' ' -f2)
  292. if [[ "$PREVIOUS_TARGET" != "$TARGET" ]]; then
  293. if [[ -z "$PREVIOUS_TARGET" ]]; then
  294. echo "new target defined <$TARGET>"
  295. else
  296. echowarnn "TARGET has changed from <$PREVIOUS_TARGET> to <$TARGET>, do you agree?"
  297. if askConfirmation N; then
  298. echowarn "removing previous settings, please restart <miaou> to apply changes"
  299. rm "$MIAOU_CONFIGDIR" -rf
  300. else
  301. echoerr "TARGET not accepted, exit"
  302. exit 102
  303. fi
  304. fi
  305. yq ".target=\"$TARGET\"" /etc/miaou/defaults.yaml -i
  306. else
  307. echo "target <$TARGET> already defined!"
  308. fi
  309. }
  310. function opt_link() {
  311. if [[ $MIAOU_BASEDIR != '/opt/miaou-server' ]]; then
  312. if [[ -L '/opt/miaou-server' && -d '/opt/miaou-server' && $(readlink /opt/miaou-server) == "$MIAOU_BASEDIR" ]]; then
  313. echo "symbolic link /opt/miaou-server already set up!"
  314. else
  315. sudo rm -f /opt/miaou-server
  316. sudo ln -s "$MIAOU_BASEDIR" /opt/miaou-server
  317. echo "symbolic link /opt/miaou-server successfully defined!"
  318. fi
  319. else
  320. echo "real path /opt/miaou-server already set up!"
  321. fi
  322. }
  323. function miaou_resolver() {
  324. local PREFIX="miaou:resolver"
  325. bridge=$(ip addr show lxdbr0 | grep "inet\b" | awk '{print $2}' | cut -d/ -f1)
  326. gateway=$(ip route | grep default | cut -d' ' -f3)
  327. echo -n "test gateway <$gateway> as DNS resolver..."
  328. if dig +short "@$gateway" "$FDN_DOMAINNAME" >/dev/null; then
  329. resolver="$gateway"
  330. PREFIX="" echoinfo DONE
  331. else
  332. PREFIX="" echoinfo "finally replaced by FDN_RESOLVER=<$FDN_RESOLVER>"
  333. resolver="$FDN_RESOLVER"
  334. fi
  335. if command -v nmcli &>/dev/null; then
  336. if [[ ! -f /etc/NetworkManager/dispatcher.d/50-miaou-resolver ]]; then
  337. echo -n "use NetworkManager dispatcher to deal with LXD bridge automatically..."
  338. sudo cp "$MIAOU_BASEDIR/templates/network-manager/50-miaou-resolver" /etc/NetworkManager/dispatcher.d/
  339. sudo chmod +x /etc/NetworkManager/dispatcher.d/50-miaou-resolver
  340. ACTIVE_CONNECTION=$(nmcli -g NAME connection show --active | head -n1)
  341. sudo nmcli connection up "$ACTIVE_CONNECTION" &>/dev/null
  342. PREFIX="" echoinfo DONE
  343. else
  344. echo "miaou-resolver in NetworkManager dispatcher already initialized!"
  345. fi
  346. fi
  347. if sudo systemctl is-enabled systemd-resolved.service --quiet &>/dev/null; then
  348. echo -n "disabling systemd-resolved..."
  349. sudo systemctl stop systemd-resolved.service --quiet
  350. sudo systemctl disable systemd-resolved.service --quiet
  351. PREFIX="" echoinfo DONE
  352. fi
  353. if ! grep -q "nameserver $bridge" /etc/resolv.conf; then
  354. echo -n "customize resolv.conf from scratch with bridge=<$bridge>, resolver=<$resolver> ..."
  355. sudo tee /etc/resolv.conf &>/dev/null <<EOF
  356. # generated by miaou
  357. nameserver $bridge # LXD bridge
  358. nameserver $resolver # resolver
  359. EOF
  360. PREFIX="" echoinfo DONE
  361. else
  362. echo "customize resolv.conf already defined!"
  363. fi
  364. }
  365. function extra_dev_desktop {
  366. # FIXME: detect if DEV && DESKTOP_USAGE to install spicy-client and other desktop tools
  367. :
  368. }
  369. function override_lxd_service {
  370. local PREFIX="lxd:override"
  371. if [[ ! -d /etc/systemd/system/lxd.service.d ]]; then
  372. echo -n "override lxd service..."
  373. sudo mkdir -p /etc/systemd/system/lxd.service.d
  374. sudo tee /etc/systemd/system/lxd.service.d/override.conf &>/dev/null <<EOF
  375. [Service]
  376. ExecStartPost=systemctl reload nftables.service
  377. Environment=LANGUAGE=en:en_US
  378. EOF
  379. sudo systemctl daemon-reload
  380. sudo systemctl restart lxd.service
  381. PREFIX="" echoinfo "DONE"
  382. else
  383. echo "lxd service already overridden!"
  384. fi
  385. }
  386. function ask_for_email {
  387. local PREFIX="install:ask_for_email"
  388. valid_email=$(auto_detect_email)
  389. while ! is_email_valid "$valid_email"; do
  390. echo -n "mandatory email: "
  391. read -rei "$valid_email" valid_email
  392. done
  393. }
  394. function preload_bookworm_image {
  395. local PREFIX="preload:bookworm"
  396. if [[ $(lxc image list debian/12/cloud -f csv | wc -l) -lt 1 ]]; then
  397. echo -n "downloading images from public remote, please hold on..."
  398. sg $NEW_GROUP -c 'lxc image copy images:debian/12/cloud local: --copy-aliases --quiet'
  399. PREFIX="" echoinfo DONE
  400. else
  401. echo -n "refreshing images from public remote..."
  402. sg $NEW_GROUP -c 'lxc image refresh debian/12/cloud --quiet'
  403. PREFIX="" echoinfo DONE
  404. fi
  405. }
  406. function is_email_valid {
  407. [[ "$1" =~ ^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$ ]]
  408. }
  409. function auto_detect_email {
  410. found_email="${EMAIL:-}"
  411. [[ -z "$found_email" ]] && [[ -f /etc/miaou/defaults.yaml ]] && found_email=$(yq '.credential.email' /etc/miaou/defaults.yaml)
  412. [[ "$found_email" == 'null' ]] && found_email=''
  413. if ! is_email_valid "$found_email"; then
  414. if [[ -f $HOME/.ssh/authorized_keys ]]; then
  415. while IFS= read -r line; do
  416. found_email="$line"
  417. is_email_valid "$found_email" && break
  418. done < <(cut -d ' ' -f3 <"$HOME/.ssh/authorized_keys")
  419. fi
  420. fi
  421. builtin echo "$found_email"
  422. }
  423. ### MAIN
  424. if [[ "${1:-}" == "SESSION_RELOAD_REQUIRED" ]]; then
  425. SESSION_RELOAD_REQUIRED=true
  426. shift
  427. else
  428. SESSION_RELOAD_REQUIRED=false
  429. fi
  430. if [[ "${1:-}" == "shellenv" ]]; then
  431. unset PREFIX
  432. echo "export MIAOU_BASEDIR=$MIAOU_BASEDIR"
  433. echo "export PATH=\"\$MIAOU_BASEDIR/scripts\":\$PATH"
  434. else
  435. . "$MIAOU_BASEDIR/lib/init.sh"
  436. trap 'status=$?; on_exit; exit $status' EXIT
  437. trap 'trap - HUP; on_exit SIGHUP; kill -HUP $$' HUP
  438. trap 'trap - INT; on_exit SIGINT; kill -INT $$' INT
  439. trap 'trap - TERM; on_exit SIGTERM; kill -TERM $$' TERM
  440. PREFIX="miaou"
  441. : $PREFIX
  442. TARGET=${1:-}
  443. CURRENT_USER=$(id -un)
  444. check_normal_user
  445. check_target
  446. ask_for_email
  447. sudo_required
  448. install_miaou_bash
  449. install_mandatory_commands
  450. prepare_toolbox
  451. add_toolbox_sudoers
  452. prepare_nftables
  453. prepare_lxd
  454. override_lxd_service
  455. configure_lxd
  456. preload_bookworm_image
  457. miaou_resolver
  458. miaou_evalfrombashrc
  459. miaou_configfiles
  460. opt_link
  461. extra_dev_desktop
  462. if [[ "$SESSION_RELOAD_REQUIRED" == true ]]; then
  463. echoinfo "successful \`session\` installation"
  464. echowarn "current session has been reloaded, due to new group <$NEW_GROUP>! Next time you type \`exit\`, this session will emit a kill signal!"
  465. else
  466. echoinfo "successful installation"
  467. fi
  468. fi