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.

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