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.

532 lines
16 KiB

7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
5 months ago
7 months ago
7 months ago
7 months ago
7 months ago
6 months ago
6 months ago
6 months ago
6 months ago
7 months ago
6 months ago
5 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 months ago
7 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,TYPE -ti -P | grep 'FSTYPE="" TYPE="part"' | head -n1 | cut -d'"' -f2)
  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 ns4mDNc'
  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_BASEDIR/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-server' ]]; then
  311. if [[ -L '/opt/miaou-server' && -d '/opt/miaou-server' && $(readlink /opt/miaou-server) == "$MIAOU_BASEDIR" ]]; then
  312. echo "symbolic link /opt/miaou-server already set up!"
  313. else
  314. sudo rm -f /opt/miaou-server
  315. sudo ln -s "$MIAOU_BASEDIR" /opt/miaou-server
  316. echo "symbolic link /opt/miaou-server successfully defined!"
  317. fi
  318. else
  319. echo "real path /opt/miaou-server 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. echo -n "test gateway <$gateway> as DNS resolver..."
  327. if dig +short "@$gateway" "$FDN_DOMAINNAME" >/dev/null; then
  328. resolver="$gateway"
  329. PREFIX="" echoinfo DONE
  330. else
  331. PREFIX="" echoinfo "finally replaced by FDN_RESOLVER=<$FDN_RESOLVER>"
  332. resolver="$FDN_RESOLVER"
  333. fi
  334. if command -v nmcli &>/dev/null; then
  335. if [[ ! -f /etc/NetworkManager/dispatcher.d/50-miaou-resolver ]]; then
  336. echo -n "use NetworkManager dispatcher to deal with LXD bridge automatically..."
  337. sudo cp "$MIAOU_BASEDIR/templates/network-manager/50-miaou-resolver" /etc/NetworkManager/dispatcher.d/
  338. sudo chmod +x /etc/NetworkManager/dispatcher.d/50-miaou-resolver
  339. ACTIVE_CONNECTION=$(nmcli -g NAME connection show --active | head -n1)
  340. sudo nmcli connection up "$ACTIVE_CONNECTION" &>/dev/null
  341. PREFIX="" echoinfo DONE
  342. else
  343. echo "miaou-resolver in NetworkManager dispatcher already initialized!"
  344. fi
  345. fi
  346. if sudo systemctl is-enabled systemd-resolved.service --quiet &>/dev/null; then
  347. echo -n "disabling systemd-resolved..."
  348. sudo systemctl stop systemd-resolved.service --quiet
  349. sudo systemctl disable systemd-resolved.service --quiet
  350. PREFIX="" echoinfo DONE
  351. fi
  352. if ! grep -q "nameserver $bridge" /etc/resolv.conf; then
  353. echo -n "customize resolv.conf from scratch with bridge=<$bridge>, resolver=<$resolver> ..."
  354. sudo tee /etc/resolv.conf &>/dev/null <<EOF
  355. # generated by miaou
  356. nameserver $bridge # LXD bridge
  357. nameserver $resolver # resolver
  358. EOF
  359. PREFIX="" echoinfo DONE
  360. else
  361. echo "customize resolv.conf already defined!"
  362. fi
  363. }
  364. function extra_dev_desktop {
  365. # FIXME: detect if DEV && DESKTOP_USAGE to install spicy-client and other desktop tools
  366. :
  367. }
  368. function override_lxd_service {
  369. local PREFIX="lxd:override"
  370. if [[ ! -d /etc/systemd/system/lxd.service.d ]]; then
  371. echo -n "override lxd service..."
  372. sudo mkdir -p /etc/systemd/system/lxd.service.d
  373. sudo tee /etc/systemd/system/lxd.service.d/override.conf &>/dev/null <<EOF
  374. [Service]
  375. ExecStartPost=systemctl reload nftables.service
  376. Environment=LANGUAGE=en:en_US
  377. EOF
  378. sudo systemctl daemon-reload
  379. sudo systemctl restart lxd.service
  380. PREFIX="" echoinfo "DONE"
  381. else
  382. echo "lxd service already overridden!"
  383. fi
  384. }
  385. function ask_for_email {
  386. local PREFIX="install:ask_for_email"
  387. valid_email=$(auto_detect_email)
  388. while ! is_email_valid "$valid_email"; do
  389. echo -n "mandatory email: "
  390. read -rei "$valid_email" valid_email
  391. done
  392. }
  393. function preload_bookworm_image {
  394. local PREFIX="preload:bookworm"
  395. if [[ $(lxc image list debian/12/cloud -f csv | wc -l) -lt 1 ]]; then
  396. echo -n "downloading images from public remote, please hold on..."
  397. sg $NEW_GROUP -c 'lxc image copy images:debian/12/cloud local: --copy-aliases --quiet'
  398. PREFIX="" echoinfo DONE
  399. else
  400. echo -n "refreshing images from public remote..."
  401. sg $NEW_GROUP -c 'lxc image refresh debian/12/cloud --quiet'
  402. PREFIX="" echoinfo DONE
  403. fi
  404. }
  405. function is_email_valid {
  406. [[ "$1" =~ ^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$ ]]
  407. }
  408. function auto_detect_email {
  409. found_email="${EMAIL:-}"
  410. [[ -z "$found_email" ]] && [[ -f /etc/miaou/defaults.yaml ]] && found_email=$(yq '.credential.email' /etc/miaou/defaults.yaml)
  411. [[ "$found_email" == 'null' ]] && found_email=''
  412. if ! is_email_valid "$found_email"; then
  413. if [[ -f $HOME/.ssh/authorized_keys ]]; then
  414. while IFS= read -r line; do
  415. found_email="$line"
  416. is_email_valid "$found_email" && break
  417. done < <(cut -d ' ' -f3 <"$HOME/.ssh/authorized_keys")
  418. fi
  419. fi
  420. builtin echo "$found_email"
  421. }
  422. ### MAIN
  423. if [[ "${1:-}" == "SESSION_RELOAD_REQUIRED" ]]; then
  424. SESSION_RELOAD_REQUIRED=true
  425. shift
  426. else
  427. SESSION_RELOAD_REQUIRED=false
  428. fi
  429. if [[ "${1:-}" == "shellenv" ]]; then
  430. unset PREFIX
  431. echo "export MIAOU_BASEDIR=$MIAOU_BASEDIR"
  432. echo "export PATH=\"\$MIAOU_BASEDIR/scripts\":\$PATH"
  433. else
  434. . "$MIAOU_BASEDIR/lib/init.sh"
  435. trap 'status=$?; on_exit; exit $status' EXIT
  436. trap 'trap - HUP; on_exit SIGHUP; kill -HUP $$' HUP
  437. trap 'trap - INT; on_exit SIGINT; kill -INT $$' INT
  438. trap 'trap - TERM; on_exit SIGTERM; kill -TERM $$' TERM
  439. PREFIX="miaou"
  440. : $PREFIX
  441. TARGET=${1:-}
  442. CURRENT_USER=$(id -un)
  443. check_normal_user
  444. check_target
  445. ask_for_email
  446. sudo_required
  447. install_miaou_bash
  448. install_mandatory_commands
  449. prepare_toolbox
  450. add_toolbox_sudoers
  451. prepare_nftables
  452. prepare_lxd
  453. override_lxd_service
  454. configure_lxd
  455. preload_bookworm_image
  456. miaou_resolver
  457. miaou_evalfrombashrc
  458. miaou_configfiles
  459. opt_link
  460. extra_dev_desktop
  461. if [[ "$SESSION_RELOAD_REQUIRED" == true ]]; then
  462. echoinfo "successful \`session\` installation"
  463. echowarn "current session has been reloaded, due to new group <$NEW_GROUP>! Next time you type \`exit\`, this session will emit a kill signal!"
  464. else
  465. echoinfo "successful installation"
  466. fi
  467. fi