lib.sh 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846
  1. #!/usr/bin/env bash
  2. # -*- coding: utf-8; mode: sh indent-tabs-mode: nil -*-
  3. # SPDX-License-Identifier: AGPL-3.0-or-later
  4. # shellcheck disable=SC2059,SC1117
  5. # ubuntu, debian, arch, fedora, centos ...
  6. DIST_ID=$(source /etc/os-release; echo "$ID");
  7. # shellcheck disable=SC2034
  8. DIST_VERS=$(source /etc/os-release; echo "$VERSION_ID");
  9. ADMIN_NAME="${ADMIN_NAME:-$(git config user.name)}"
  10. ADMIN_NAME="${ADMIN_NAME:-$USER}"
  11. ADMIN_EMAIL="${ADMIN_EMAIL:-$(git config user.email)}"
  12. ADMIN_EMAIL="${ADMIN_EMAIL:-$USER@$(hostname)}"
  13. if [[ -z "${REPO_ROOT}" ]]; then
  14. REPO_ROOT=$(dirname "${BASH_SOURCE[0]}")
  15. while [ -h "${REPO_ROOT}" ] ; do
  16. REPO_ROOT=$(readlink "${REPO_ROOT}")
  17. done
  18. REPO_ROOT=$(cd "${REPO_ROOT}/.." && pwd -P )
  19. fi
  20. if [[ -z ${TEMPLATES} ]]; then
  21. TEMPLATES="${REPO_ROOT}/utils/templates"
  22. fi
  23. if [[ -z "$CACHE" ]]; then
  24. CACHE="${REPO_ROOT}/cache"
  25. fi
  26. if [[ -z ${DIFF_CMD} ]]; then
  27. DIFF_CMD="diff -u"
  28. if command -v colordiff >/dev/null; then
  29. DIFF_CMD="colordiff -u"
  30. fi
  31. fi
  32. DOT_CONFIG="${DOT_CONFIG:-${REPO_ROOT}/.config.sh}"
  33. source_dot_config() {
  34. if [[ ! -e "${DOT_CONFIG}" ]]; then
  35. err_msg "configuration does not exists at: ${DOT_CONFIG}"
  36. return 42
  37. fi
  38. # shellcheck disable=SC1090
  39. source "${DOT_CONFIG}"
  40. }
  41. sudo_or_exit() {
  42. # usage: sudo_or_exit
  43. if [ ! "$(id -u)" -eq 0 ]; then
  44. err_msg "this command requires root (sudo) privilege!" >&2
  45. exit 42
  46. fi
  47. }
  48. required_commands() {
  49. # usage: required_commands [cmd1 ...]
  50. local exit_val=0
  51. while [ -n "$1" ]; do
  52. if ! command -v "$1" &>/dev/null; then
  53. err_msg "missing command $1"
  54. exit_val=42
  55. fi
  56. shift
  57. done
  58. return $exit_val
  59. }
  60. # colors
  61. # ------
  62. # shellcheck disable=SC2034
  63. set_terminal_colors() {
  64. _colors=8
  65. _creset='\e[0m' # reset all attributes
  66. _Black='\e[0;30m'
  67. _White='\e[1;37m'
  68. _Red='\e[0;31m'
  69. _Green='\e[0;32m'
  70. _Yellow='\e[0;33m'
  71. _Blue='\e[0;94m'
  72. _Violet='\e[0;35m'
  73. _Cyan='\e[0;36m'
  74. _BBlack='\e[1;30m'
  75. _BWhite='\e[1;37m'
  76. _BRed='\e[1;31m'
  77. _BGreen='\e[1;32m'
  78. _BYellow='\e[1;33m'
  79. _BBlue='\e[1;94m'
  80. _BPurple='\e[1;35m'
  81. _BCyan='\e[1;36m'
  82. }
  83. if [ ! -p /dev/stdout ] && [ ! "$TERM" = 'dumb' ] && [ ! "$TERM" = 'unknown' ]; then
  84. set_terminal_colors
  85. fi
  86. # reST
  87. # ----
  88. if command -v fmt >/dev/null; then
  89. export FMT="fmt -u"
  90. else
  91. export FMT="cat"
  92. fi
  93. rst_title() {
  94. # usage: rst_title <header-text> [part|chapter|section]
  95. case ${2-chapter} in
  96. part) printf "\n${_BGreen}${1//?/=}${_creset}\n${_BCyan}${1}${_creset}\n${_BGreen}${1//?/=}${_creset}\n";;
  97. chapter) printf "\n${_BCyan}${1}${_creset}\n${_BGreen}${1//?/=}${_creset}\n";;
  98. section) printf "\n${_BCyan}${1}${_creset}\n${_BGreen}${1//?/-}${_creset}\n";;
  99. *)
  100. err_msg "invalid argument '${2}' in line $(caller)"
  101. return 42
  102. ;;
  103. esac
  104. }
  105. rst_para() {
  106. # usage: RST_INDENT=1 rst_para "lorem ipsum ..."
  107. local prefix=''
  108. if [[ -n $RST_INDENT ]] && [[ $RST_INDENT -gt 0 ]]; then
  109. prefix="$(for i in $(seq 1 "$RST_INDENT"); do printf " "; done)"
  110. echo -en "\n$*\n" | $FMT | prefix_stdout "$prefix"
  111. else
  112. echo -en "\n$*\n" | $FMT
  113. fi
  114. }
  115. die() {
  116. echo -e "${_BRed}ERROR:${_creset} ${BASH_SOURCE[1]}: line ${BASH_LINENO[0]}: ${2-died ${1-1}}" >&2;
  117. exit "${1-1}"
  118. }
  119. die_caller() {
  120. echo -e "${_BRed}ERROR:${_creset} ${BASH_SOURCE[2]}: line ${BASH_LINENO[1]}: ${FUNCNAME[1]}(): ${2-died ${1-1}}" >&2;
  121. exit "${1-1}"
  122. }
  123. err_msg() { echo -e "${_BRed}ERROR:${_creset} $*" >&2; }
  124. warn_msg() { echo -e "${_BBlue}WARN:${_creset} $*" >&2; }
  125. info_msg() { echo -e "${_BYellow}INFO:${_creset} $*" >&2; }
  126. build_msg() {
  127. local tag="$1 "
  128. shift
  129. echo -e "${_Blue}${tag:0:10}${_creset}$*"
  130. }
  131. dump_return() {
  132. # Use this as last command in your function to prompt an ERROR message if
  133. # the exit code is not zero.
  134. local err=$1
  135. [ "$err" -ne "0" ] && err_msg "${FUNCNAME[1]} exit with error ($err)"
  136. return "$err"
  137. }
  138. clean_stdin() {
  139. if [[ $(uname -s) != 'Darwin' ]]; then
  140. while read -r -n1 -t 0.1; do : ; done
  141. fi
  142. }
  143. wait_key(){
  144. # usage: wait_key [<timeout in sec>]
  145. clean_stdin
  146. local _t=$1
  147. local msg="${MSG}"
  148. [[ -z "$msg" ]] && msg="${_Green}** press any [${_BCyan}KEY${_Green}] to continue **${_creset}"
  149. [[ -n $FORCE_TIMEOUT ]] && _t=$FORCE_TIMEOUT
  150. [[ -n $_t ]] && _t="-t $_t"
  151. printf "$msg"
  152. # shellcheck disable=SC2086
  153. read -r -s -n1 $_t
  154. echo
  155. clean_stdin
  156. }
  157. ask_yn() {
  158. # usage: ask_yn <prompt-text> [Ny|Yn] [<timeout in sec>]
  159. local EXIT_YES=0 # exit status 0 --> successful
  160. local EXIT_NO=1 # exit status 1 --> error code
  161. local _t=$3
  162. [[ -n $FORCE_TIMEOUT ]] && _t=$FORCE_TIMEOUT
  163. [[ -n $_t ]] && _t="-t $_t"
  164. case "${FORCE_SELECTION:-${2}}" in
  165. Y) return ${EXIT_YES} ;;
  166. N) return ${EXIT_NO} ;;
  167. Yn)
  168. local exit_val=${EXIT_YES}
  169. local choice="[${_BGreen}YES${_creset}/no]"
  170. local default="Yes"
  171. ;;
  172. *)
  173. local exit_val=${EXIT_NO}
  174. local choice="[${_BGreen}NO${_creset}/yes]"
  175. local default="No"
  176. ;;
  177. esac
  178. echo
  179. while true; do
  180. clean_stdin
  181. printf "$1 ${choice} "
  182. # shellcheck disable=SC2086
  183. read -r -n1 $_t
  184. if [[ -z $REPLY ]]; then
  185. printf "$default\n"; break
  186. elif [[ $REPLY =~ ^[Yy]$ ]]; then
  187. exit_val=${EXIT_YES}
  188. printf "\n"
  189. break
  190. elif [[ $REPLY =~ ^[Nn]$ ]]; then
  191. exit_val=${EXIT_NO}
  192. printf "\n"
  193. break
  194. fi
  195. _t=""
  196. err_msg "invalid choice"
  197. done
  198. clean_stdin
  199. return $exit_val
  200. }
  201. tee_stderr () {
  202. # usage::
  203. # tee_stderr 1 <<EOF | python -i
  204. # print("hello")
  205. # EOF
  206. # ...
  207. # >>> print("hello")
  208. # hello
  209. local _t="0";
  210. if [[ -n $1 ]] ; then _t="$1"; fi
  211. (while read -r line; do
  212. # shellcheck disable=SC2086
  213. sleep $_t
  214. echo -e "$line" >&2
  215. echo "$line"
  216. done)
  217. }
  218. prefix_stdout () {
  219. # usage: <cmd> | prefix_stdout [prefix]
  220. local prefix="${_BYellow}-->|${_creset}"
  221. if [[ -n $1 ]] ; then prefix="$1"; fi
  222. # shellcheck disable=SC2162
  223. (while IFS= read line; do
  224. echo -e "${prefix}$line"
  225. done)
  226. }
  227. append_line() {
  228. # usage: append_line <line> <file>
  229. #
  230. # Append line if not exists, create file if not exists. E.g::
  231. #
  232. # append_line 'source ~/.foo' ~/bashrc
  233. local LINE=$1
  234. local FILE=$2
  235. grep -qFs -- "$LINE" "$FILE" || echo "$LINE" >> "$FILE"
  236. }
  237. cache_download() {
  238. # usage: cache_download <url> <local-filename>
  239. local exit_value=0
  240. if [[ -n ${SUDO_USER} ]]; then
  241. sudo -u "${SUDO_USER}" mkdir -p "${CACHE}"
  242. else
  243. mkdir -p "${CACHE}"
  244. fi
  245. if [[ -f "${CACHE}/$2" ]] ; then
  246. info_msg "already cached: $1"
  247. info_msg " --> ${CACHE}/$2"
  248. fi
  249. if [[ ! -f "${CACHE}/$2" ]]; then
  250. info_msg "caching: $1"
  251. info_msg " --> ${CACHE}/$2"
  252. if [[ -n ${SUDO_USER} ]]; then
  253. sudo -u "${SUDO_USER}" wget --progress=bar -O "${CACHE}/$2" "$1" ; exit_value=$?
  254. else
  255. wget --progress=bar -O "${CACHE}/$2" "$1" ; exit_value=$?
  256. fi
  257. if [[ ! $exit_value = 0 ]]; then
  258. err_msg "failed to download: $1"
  259. fi
  260. fi
  261. }
  262. backup_file() {
  263. # usage: backup_file /path/to/file.foo
  264. local stamp
  265. stamp=$(date +"_%Y%m%d_%H%M%S")
  266. info_msg "create backup: ${1}${stamp}"
  267. cp -a "${1}" "${1}${stamp}"
  268. }
  269. choose_one() {
  270. # usage:
  271. #
  272. # DEFAULT_SELECT= 2 \
  273. # choose_one <name> "your selection?" "Coffee" "Coffee with milk"
  274. local default=${DEFAULT_SELECT-1}
  275. local REPLY
  276. local env_name=$1 && shift
  277. local choice=$1;
  278. local max="${#@}"
  279. local _t
  280. [[ -n $FORCE_TIMEOUT ]] && _t=$FORCE_TIMEOUT
  281. [[ -n $_t ]] && _t="-t $_t"
  282. list=("$@")
  283. echo -e "${_BGreen}Menu::${_creset}"
  284. for ((i=1; i<= $((max -1)); i++)); do
  285. if [[ "$i" == "$default" ]]; then
  286. echo -e " ${_BGreen}$i.${_creset}) ${list[$i]} [default]"
  287. else
  288. echo -e " $i.) ${list[$i]}"
  289. fi
  290. done
  291. while true; do
  292. clean_stdin
  293. printf "$1 [${_BGreen}$default${_creset}] "
  294. if (( 10 > max )); then
  295. # shellcheck disable=SC2086
  296. read -r -n1 $_t
  297. else
  298. # shellcheck disable=SC2086,SC2229
  299. read -r $_t
  300. fi
  301. # selection fits
  302. [[ $REPLY =~ ^-?[0-9]+$ ]] && (( REPLY > 0 )) && (( REPLY < max )) && break
  303. # take default
  304. [[ -z $REPLY ]] && REPLY=$default && break
  305. _t=""
  306. err_msg "invalid choice"
  307. done
  308. eval "$env_name"='${list[${REPLY}]}'
  309. echo
  310. clean_stdin
  311. }
  312. install_template() {
  313. # usage:
  314. #
  315. # install_template [--no-eval] [--variant=<name>] \
  316. # {file} [{owner} [{group} [{chmod}]]]
  317. #
  318. # E.g. the origin of variant 'raw' of /etc/updatedb.conf is::
  319. #
  320. # ${TEMPLATES}/etc/updatedb.conf:raw
  321. #
  322. # To install variant 'raw' of /etc/updatedb.conf without evaluated
  323. # replacements you can use::
  324. #
  325. # install_template --variant=raw --no-eval \
  326. # /etc/updatedb.conf root root 644
  327. local _reply=""
  328. local do_eval=1
  329. local variant=""
  330. local pos_args=("$0")
  331. for i in "$@"; do
  332. case $i in
  333. --no-eval) do_eval=0; shift ;;
  334. --variant=*) variant=":${i#*=}"; shift ;;
  335. *) pos_args+=("$i") ;;
  336. esac
  337. done
  338. local dst="${pos_args[1]}"
  339. local template_origin="${TEMPLATES}${dst}${variant}"
  340. local template_file="${TEMPLATES}${dst}"
  341. local owner="${pos_args[2]-$(id -un)}"
  342. local group="${pos_args[3]-$(id -gn)}"
  343. local chmod="${pos_args[4]-644}"
  344. info_msg "install (eval=$do_eval): ${dst}"
  345. [[ -n $variant ]] && info_msg "variant --> ${variant}"
  346. if [[ ! -f "${template_origin}" ]] ; then
  347. err_msg "${template_origin} does not exists"
  348. err_msg "... can't install $dst"
  349. wait_key 30
  350. return 42
  351. fi
  352. if [[ "$do_eval" == "1" ]]; then
  353. template_file="${CACHE}${dst}${variant}"
  354. info_msg "BUILD template ${template_file}"
  355. if [[ -n ${SUDO_USER} ]]; then
  356. sudo -u "${SUDO_USER}" mkdir -p "$(dirname "${template_file}")"
  357. else
  358. mkdir -p "$(dirname "${template_file}")"
  359. fi
  360. # shellcheck disable=SC2086
  361. eval "echo \"$(cat ${template_origin})\"" > "${template_file}"
  362. if [[ -n ${SUDO_USER} ]]; then
  363. chown "${SUDO_USER}:${SUDO_USER}" "${template_file}"
  364. fi
  365. else
  366. template_file=$template_origin
  367. fi
  368. mkdir -p "$(dirname "${dst}")"
  369. if [[ ! -f "${dst}" ]]; then
  370. info_msg "install: ${template_file}"
  371. sudo -H install -v -o "${owner}" -g "${group}" -m "${chmod}" \
  372. "${template_file}" "${dst}" | prefix_stdout
  373. return $?
  374. fi
  375. if [[ -f "${dst}" ]] && cmp --silent "${template_file}" "${dst}" ; then
  376. info_msg "file ${dst} already installed"
  377. return 0
  378. fi
  379. info_msg "different file ${dst} already exists on this host"
  380. while true; do
  381. choose_one _reply "choose next step with file $dst" \
  382. "replace file" \
  383. "leave file unchanged" \
  384. "interactive shell" \
  385. "diff files"
  386. case $_reply in
  387. "replace file")
  388. info_msg "install: ${template_file}"
  389. sudo -H install -v -o "${owner}" -g "${group}" -m "${chmod}" \
  390. "${template_file}" "${dst}" | prefix_stdout
  391. break
  392. ;;
  393. "leave file unchanged")
  394. break
  395. ;;
  396. "interactive shell")
  397. echo -e "// edit ${_Red}${dst}${_creset} to your needs"
  398. echo -e "// exit with [${_BCyan}CTRL-D${_creset}]"
  399. sudo -H -u "${owner}" -i
  400. $DIFF_CMD "${dst}" "${template_file}"
  401. echo
  402. echo -e "// ${_BBlack}did you edit file ...${_creset}"
  403. echo -en "// ${_Red}${dst}${_creset}"
  404. if ask_yn "//${_BBlack}... to your needs?${_creset}"; then
  405. break
  406. fi
  407. ;;
  408. "diff files")
  409. $DIFF_CMD "${dst}" "${template_file}" | prefix_stdout
  410. esac
  411. done
  412. }
  413. service_is_available() {
  414. # usage: service_is_available <URL>
  415. [[ -z $1 ]] && die_caller 42 "missing argument <URL>"
  416. local URL="$1"
  417. http_code=$(curl -H 'Cache-Control: no-cache' \
  418. --silent -o /dev/null --head --write-out '%{http_code}' --insecure \
  419. "${URL}")
  420. exit_val=$?
  421. if [[ $exit_val = 0 ]]; then
  422. info_msg "got $http_code from ${URL}"
  423. fi
  424. case "$http_code" in
  425. 404|410|423) exit_val=$http_code;;
  426. esac
  427. return "$exit_val"
  428. }
  429. # python
  430. # ------
  431. PY="${PY:=3}"
  432. PYTHON="${PYTHON:=python$PY}"
  433. PY_ENV="${PY_ENV:=local/py${PY}}"
  434. PY_ENV_BIN="${PY_ENV}/bin"
  435. PY_ENV_REQ="${PY_ENV_REQ:=${REPO_ROOT}/requirements*.txt}"
  436. # List of python packages (folders) or modules (files) installed by command:
  437. # pyenv.install
  438. PYOBJECTS="${PYOBJECTS:=.}"
  439. # folder where the python distribution takes place
  440. PYDIST="${PYDIST:=dist}"
  441. # folder where the intermediate build files take place
  442. PYBUILD="${PYBUILD:=build/py${PY}}"
  443. # https://www.python.org/dev/peps/pep-0508/#extras
  444. #PY_SETUP_EXTRAS='[develop,test]'
  445. PY_SETUP_EXTRAS="${PY_SETUP_EXTRAS:=[develop,test]}"
  446. PIP_BOILERPLATE=( pip wheel setuptools )
  447. # shellcheck disable=SC2120
  448. pyenv() {
  449. # usage: pyenv [vtenv_opts ...]
  450. #
  451. # vtenv_opts: see 'pip install --help'
  452. #
  453. # Builds virtualenv with 'requirements*.txt' (PY_ENV_REQ) installed. The
  454. # virtualenv will be reused by validating sha256sum of the requirement
  455. # files.
  456. required_commands \
  457. sha256sum "${PYTHON}" \
  458. || exit
  459. local pip_req=()
  460. if ! pyenv.OK > /dev/null; then
  461. rm -f "${PY_ENV}/${PY_ENV_REQ}.sha256"
  462. pyenv.drop > /dev/null
  463. build_msg PYENV "[virtualenv] installing ${PY_ENV_REQ} into ${PY_ENV}"
  464. "${PYTHON}" -m venv "$@" "${PY_ENV}" || exit
  465. "${PY_ENV_BIN}/python" -m pip install -U "${PIP_BOILERPLATE[@]}" || exit
  466. for i in ${PY_ENV_REQ}; do
  467. pip_req=( "${pip_req[@]}" "-r" "$i" )
  468. done
  469. (
  470. [ "$VERBOSE" = "1" ] && set -x
  471. # shellcheck disable=SC2086
  472. "${PY_ENV_BIN}/python" -m pip install "${pip_req[@]}" \
  473. && sha256sum ${PY_ENV_REQ} > "${PY_ENV}/requirements.sha256"
  474. )
  475. fi
  476. pyenv.OK
  477. }
  478. _pyenv_OK=''
  479. pyenv.OK() {
  480. # probes if pyenv exists and runs the script from pyenv.check
  481. [ "$_pyenv_OK" == "OK" ] && return 0
  482. if [ ! -f "${PY_ENV_BIN}/python" ]; then
  483. build_msg PYENV "[virtualenv] missing ${PY_ENV_BIN}/python"
  484. return 1
  485. fi
  486. if [ ! -f "${PY_ENV}/requirements.sha256" ] \
  487. || ! sha256sum --check --status <"${PY_ENV}/requirements.sha256" 2>/dev/null; then
  488. build_msg PYENV "[virtualenv] requirements.sha256 failed"
  489. sed 's/^/ [virtualenv] - /' <"${PY_ENV}/requirements.sha256"
  490. return 1
  491. fi
  492. pyenv.check \
  493. | "${PY_ENV_BIN}/python" 2>&1 \
  494. | prefix_stdout "${_Blue}PYENV ${_creset}[check] "
  495. local err=${PIPESTATUS[1]}
  496. if [ "$err" -ne "0" ]; then
  497. build_msg PYENV "[check] python test failed"
  498. return "$err"
  499. fi
  500. build_msg PYENV "OK"
  501. _pyenv_OK="OK"
  502. return 0
  503. }
  504. pyenv.drop() {
  505. build_msg PYENV "[virtualenv] drop ${PY_ENV}"
  506. rm -rf "${PY_ENV}"
  507. _pyenv_OK=''
  508. }
  509. pyenv.check() {
  510. # Prompts a python script with additional checks. Used by pyenv.OK to check
  511. # if virtualenv is ready to install python objects. This function should be
  512. # overwritten by the application script.
  513. local imp=""
  514. for i in "${PIP_BOILERPLATE[@]}"; do
  515. imp="$imp, $i"
  516. done
  517. cat <<EOF
  518. import ${imp#,*}
  519. EOF
  520. }
  521. pyenv.install() {
  522. if ! pyenv.OK; then
  523. py.clean > /dev/null
  524. fi
  525. if ! pyenv.install.OK > /dev/null; then
  526. build_msg PYENV "[install] ${PYOBJECTS}"
  527. if ! pyenv.OK >/dev/null; then
  528. pyenv
  529. fi
  530. for i in ${PYOBJECTS}; do
  531. build_msg PYENV "[install] pip install -e '$i${PY_SETUP_EXTRAS}'"
  532. "${PY_ENV_BIN}/python" -m pip install -e "$i${PY_SETUP_EXTRAS}"
  533. done
  534. fi
  535. pyenv.install.OK
  536. }
  537. _pyenv_install_OK=''
  538. pyenv.install.OK() {
  539. [ "$_pyenv_install_OK" == "OK" ] && return 0
  540. local imp=""
  541. local err=""
  542. if [ "." = "${PYOBJECTS}" ]; then
  543. imp="import $(basename "$(pwd)")"
  544. else
  545. # shellcheck disable=SC2086
  546. for i in ${PYOBJECTS}; do imp="$imp, $i"; done
  547. imp="import ${imp#,*} "
  548. fi
  549. (
  550. [ "$VERBOSE" = "1" ] && set -x
  551. "${PY_ENV_BIN}/python" -c "import sys; sys.path.pop(0); $imp;" 2>/dev/null
  552. )
  553. err=$?
  554. if [ "$err" -ne "0" ]; then
  555. build_msg PYENV "[install] python installation test failed"
  556. return "$err"
  557. fi
  558. build_msg PYENV "[install] OK"
  559. _pyenv_install_OK="OK"
  560. return 0
  561. }
  562. pyenv.uninstall() {
  563. build_msg PYENV "[uninstall] ${PYOBJECTS}"
  564. if [ "." = "${PYOBJECTS}" ]; then
  565. pyenv.cmd python setup.py develop --uninstall 2>&1 \
  566. | prefix_stdout "${_Blue}PYENV ${_creset}[pyenv.uninstall] "
  567. else
  568. pyenv.cmd python -m pip uninstall --yes ${PYOBJECTS} 2>&1 \
  569. | prefix_stdout "${_Blue}PYENV ${_creset}[pyenv.uninstall] "
  570. fi
  571. }
  572. pyenv.cmd() {
  573. pyenv.install
  574. ( set -e
  575. # shellcheck source=/dev/null
  576. source "${PY_ENV_BIN}/activate"
  577. [ "$VERBOSE" = "1" ] && set -x
  578. "$@"
  579. )
  580. }
  581. # Sphinx doc
  582. # ----------
  583. GH_PAGES="build/gh-pages"
  584. DOCS_DIST="${DOCS_DIST:=dist/docs}"
  585. DOCS_BUILD="${DOCS_BUILD:=build/docs}"
  586. docs.html() {
  587. build_msg SPHINX "HTML ./docs --> file://$(readlink -e "$(pwd)/$DOCS_DIST")"
  588. pyenv.install
  589. docs.prebuild
  590. # shellcheck disable=SC2086
  591. PATH="${PY_ENV_BIN}:${PATH}" pyenv.cmd sphinx-build \
  592. ${SPHINX_VERBOSE} ${SPHINXOPTS} \
  593. -b html -c ./docs -d "${DOCS_BUILD}/.doctrees" ./docs "${DOCS_DIST}"
  594. dump_return $?
  595. }
  596. docs.live() {
  597. build_msg SPHINX "autobuild ./docs --> file://$(readlink -e "$(pwd)/$DOCS_DIST")"
  598. pyenv.install
  599. docs.prebuild
  600. # shellcheck disable=SC2086
  601. PATH="${PY_ENV_BIN}:${PATH}" pyenv.cmd sphinx-autobuild \
  602. ${SPHINX_VERBOSE} ${SPHINXOPTS} --open-browser --host 0.0.0.0 \
  603. -b html -c ./docs -d "${DOCS_BUILD}/.doctrees" ./docs "${DOCS_DIST}"
  604. dump_return $?
  605. }
  606. docs.clean() {
  607. build_msg CLEAN "docs -- ${DOCS_BUILD} ${DOCS_DIST}"
  608. # shellcheck disable=SC2115
  609. rm -rf "${GH_PAGES}" "${DOCS_BUILD}" "${DOCS_DIST}"
  610. dump_return $?
  611. }
  612. docs.prebuild() {
  613. # Dummy function to run some actions before sphinx-doc build gets started.
  614. # This finction needs to be overwritten by the application script.
  615. true
  616. dump_return $?
  617. }
  618. # shellcheck disable=SC2155
  619. docs.gh-pages() {
  620. # The commit history in the gh-pages branch makes no sense, the history only
  621. # inflates the repository unnecessarily. Therefore a *new orphan* branch
  622. # is created each time we deploy on the gh-pages branch.
  623. docs.clean
  624. docs.prebuild
  625. docs.html
  626. [ "$VERBOSE" = "1" ] && set -x
  627. local head="$(git rev-parse HEAD)"
  628. local branch="$(git name-rev --name-only HEAD)"
  629. local remote="$(git config branch."${branch}".remote)"
  630. local remote_url="$(git config remote."${remote}".url)"
  631. # prepare the *orphan* gh-pages working tree
  632. (
  633. git worktree remove -f "${GH_PAGES}"
  634. git branch -D gh-pages
  635. ) &> /dev/null || true
  636. git worktree add --no-checkout "${GH_PAGES}" origin/master
  637. pushd "${GH_PAGES}" &> /dev/null
  638. git checkout --orphan gh-pages
  639. git rm -rfq .
  640. popd &> /dev/null
  641. cp -r "${DOCS_DIST}"/* "${GH_PAGES}"/
  642. touch "${GH_PAGES}/.nojekyll"
  643. cat > "${GH_PAGES}/404.html" <<EOF
  644. <html><head><META http-equiv='refresh' content='0;URL=index.html'></head></html>
  645. EOF
  646. pushd "${GH_PAGES}" &> /dev/null
  647. git add --all .
  648. git commit -q -m "gh-pages build from: ${branch}@${head} (${remote_url})"
  649. git push -f "${remote}" gh-pages
  650. popd &> /dev/null
  651. set +x
  652. build_msg GH-PAGES "deployed"
  653. }
  654. # golang
  655. # ------
  656. go_is_available() {
  657. # usage: go_is_available $SERVICE_USER && echo "go is installed!"
  658. sudo -i -u "${1}" which go &>/dev/null
  659. }
  660. install_go() {
  661. # usage: install_go "${GO_PKG_URL}" "${GO_TAR}" "${SERVICE_USER}"
  662. local _svcpr=" ${_Yellow}|${3}|${_creset} "
  663. rst_title "Install Go in user's HOME" section
  664. rst_para "download and install go binary .."
  665. cache_download "${1}" "${2}"
  666. tee_stderr 0.1 <<EOF | sudo -i -u "${3}" | prefix_stdout "$_svcpr"
  667. echo \$PATH
  668. echo \$GOPATH
  669. mkdir -p \$HOME/local
  670. rm -rf \$HOME/local/go
  671. tar -C \$HOME/local -xzf ${CACHE}/${2}
  672. EOF
  673. sudo -i -u "${3}" <<EOF | prefix_stdout
  674. ! which go >/dev/null && echo "ERROR - Go Installation not found in PATH!?!"
  675. which go >/dev/null && go version && echo "congratulations -- Go installation OK :)"
  676. EOF
  677. }
  678. # system accounts
  679. # ---------------
  680. service_account_is_available() {
  681. # usage: service_account_is_available "$SERVICE_USER" && echo "OK"
  682. sudo -i -u "$1" echo \$HOME &>/dev/null
  683. }
  684. drop_service_account() {
  685. # usage: drop_service_account "${SERVICE_USER}"
  686. rst_title "Drop ${1} HOME" section
  687. if ask_yn "Do you really want to drop ${1} home folder?"; then
  688. userdel -r -f "${1}" 2>&1 | prefix_stdout
  689. else
  690. rst_para "Leave HOME folder $(du -sh "${1}") unchanged."
  691. fi
  692. }
  693. interactive_shell(){
  694. # usage: interactive_shell "${SERVICE_USER}"
  695. echo -e "// exit with [${_BCyan}CTRL-D${_creset}]"
  696. sudo -H -u "${1}" -i
  697. }
  698. # systemd
  699. # -------
  700. SYSTEMD_UNITS="${SYSTEMD_UNITS:-/lib/systemd/system}"
  701. systemd_install_service() {
  702. # usage: systemd_install_service "${SERVICE_NAME}" "${SERVICE_SYSTEMD_UNIT}"
  703. rst_title "Install System-D Unit ${1}" section
  704. echo
  705. install_template "${2}" root root 644
  706. wait_key
  707. systemd_activate_service "${1}"
  708. }
  709. systemd_remove_service() {
  710. # usage: systemd_remove_service "${SERVICE_NAME}" "${SERVICE_SYSTEMD_UNIT}"
  711. if ! ask_yn "Do you really want to deinstall systemd unit ${1}?"; then
  712. return 42
  713. fi
  714. systemd_deactivate_service "${1}"
  715. rm "${2}" 2>&1 | prefix_stdout
  716. }
  717. systemd_activate_service() {
  718. # usage: systemd_activate_service "${SERVICE_NAME}"
  719. rst_title "Activate ${1} (service)" section
  720. echo
  721. tee_stderr <<EOF | bash 2>&1
  722. systemctl enable ${1}.service
  723. systemctl restart ${1}.service
  724. EOF
  725. tee_stderr <<EOF | bash 2>&1
  726. systemctl status --no-pager ${1}.service
  727. EOF
  728. }
  729. systemd_deactivate_service() {
  730. # usage: systemd_deactivate_service "${SERVICE_NAME}"
  731. rst_title "De-Activate ${1} (service)" section
  732. echo
  733. tee_stderr <<EOF | bash 2>&1 | prefix_stdout
  734. systemctl stop ${1}.service
  735. systemctl disable ${1}.service
  736. EOF
  737. }
  738. systemd_restart_service() {
  739. # usage: systemd_restart_service "${SERVICE_NAME}"
  740. rst_title "Restart ${1} (service)" section
  741. echo
  742. tee_stderr <<EOF | bash 2>&1
  743. systemctl restart ${1}.service
  744. EOF
  745. tee_stderr <<EOF | bash 2>&1
  746. systemctl status --no-pager ${1}.service
  747. EOF
  748. }
  749. # nginx
  750. # -----
  751. nginx_distro_setup() {
  752. # shellcheck disable=SC2034
  753. NGINX_DEFAULT_SERVER=/etc/nginx/nginx.conf
  754. # Including *location* directives from a dedicated config-folder into the
  755. # server directive is, what fedora and centos (already) does.
  756. NGINX_APPS_ENABLED="/etc/nginx/default.d"
  757. # We add a apps-available folder and linking configurations into the
  758. # NGINX_APPS_ENABLED folder. See also nginx_include_apps_enabled().
  759. NGINX_APPS_AVAILABLE="/etc/nginx/default.apps-available"
  760. case $DIST_ID-$DIST_VERS in
  761. ubuntu-*|debian-*)
  762. NGINX_PACKAGES="nginx"
  763. NGINX_DEFAULT_SERVER=/etc/nginx/sites-available/default
  764. ;;
  765. arch-*)
  766. NGINX_PACKAGES="nginx-mainline"
  767. ;;
  768. fedora-*|centos-7)
  769. NGINX_PACKAGES="nginx"
  770. ;;
  771. *)
  772. err_msg "$DIST_ID-$DIST_VERS: nginx not yet implemented"
  773. ;;
  774. esac
  775. }
  776. nginx_distro_setup
  777. install_nginx(){
  778. info_msg "installing nginx ..."
  779. pkg_install "${NGINX_PACKAGES}"
  780. case $DIST_ID-$DIST_VERS in
  781. arch-*|fedora-*|centos-7)
  782. systemctl enable nginx
  783. systemctl start nginx
  784. ;;
  785. esac
  786. }
  787. nginx_is_installed() {
  788. command -v nginx &>/dev/null
  789. }
  790. nginx_reload() {
  791. info_msg "reload nginx .."
  792. echo
  793. if ! nginx -t; then
  794. err_msg "testing nginx configuration failed"
  795. return 42
  796. fi
  797. systemctl restart nginx
  798. }
  799. nginx_install_app() {
  800. # usage: nginx_install_app [<template option> ...] <myapp.conf>
  801. #
  802. # <template option>: see install_template
  803. local template_opts=()
  804. local pos_args=("$0")
  805. for i in "$@"; do
  806. case $i in
  807. -*) template_opts+=("$i");;
  808. *) pos_args+=("$i");;
  809. esac
  810. done
  811. nginx_include_apps_enabled "${NGINX_DEFAULT_SERVER}"
  812. install_template "${template_opts[@]}" \
  813. "${NGINX_APPS_AVAILABLE}/${pos_args[1]}" \
  814. root root 644
  815. nginx_enable_app "${pos_args[1]}"
  816. info_msg "installed nginx app: ${pos_args[1]}"
  817. }
  818. nginx_include_apps_enabled() {
  819. # Add the *NGINX_APPS_ENABLED* infrastructure to a nginx server block. Such
  820. # infrastructure is already known from fedora and centos, including apps (location
  821. # directives) from the /etc/nginx/default.d folder into the *default* nginx
  822. # server.
  823. # usage: nginx_include_apps_enabled <config-file>
  824. #
  825. # config-file: Config file with server directive in.
  826. [[ -z $1 ]] && die_caller 42 "missing argument <config-file>"
  827. local server_conf="$1"
  828. # include /etc/nginx/default.d/*.conf;
  829. local include_directive="include ${NGINX_APPS_ENABLED}/*.conf;"
  830. local include_directive_re="^\s*include ${NGINX_APPS_ENABLED}/\*\.conf;"
  831. info_msg "checking existence: '${include_directive}' in file ${server_conf}"
  832. if grep "${include_directive_re}" "${server_conf}"; then
  833. info_msg "OK, already exists."
  834. return
  835. fi
  836. info_msg "add missing directive: '${include_directive}'"
  837. cp "${server_conf}" "${server_conf}.bak"
  838. (
  839. local line
  840. local stage=0
  841. while IFS= read -r line
  842. do
  843. echo "$line"
  844. if [[ $stage = 0 ]]; then
  845. if [[ $line =~ ^[[:space:]]*server*[[:space:]]*\{ ]]; then
  846. stage=1
  847. fi
  848. fi
  849. if [[ $stage = 1 ]]; then
  850. echo " # Load configuration files for the default server block."
  851. echo " $include_directive"
  852. echo ""
  853. stage=2
  854. fi
  855. done < "${server_conf}.bak"
  856. ) > "${server_conf}"
  857. }
  858. nginx_remove_app() {
  859. # usage: nginx_remove_app <myapp.conf>
  860. info_msg "remove nginx app: $1"
  861. nginx_dissable_app "$1"
  862. rm -f "${NGINX_APPS_AVAILABLE}/$1"
  863. }
  864. nginx_enable_app() {
  865. # usage: nginx_enable_app <myapp.conf>
  866. local CONF="$1"
  867. info_msg "enable nginx app: ${CONF}"
  868. mkdir -p "${NGINX_APPS_ENABLED}"
  869. rm -f "${NGINX_APPS_ENABLED}/${CONF}"
  870. ln -s "${NGINX_APPS_AVAILABLE}/${CONF}" "${NGINX_APPS_ENABLED}/${CONF}"
  871. nginx_reload
  872. }
  873. nginx_dissable_app() {
  874. # usage: nginx_disable_app <myapp.conf>
  875. local CONF="$1"
  876. info_msg "disable nginx app: ${CONF}"
  877. rm -f "${NGINX_APPS_ENABLED}/${CONF}"
  878. nginx_reload
  879. }
  880. # Apache
  881. # ------
  882. apache_distro_setup() {
  883. # shellcheck disable=SC2034
  884. case $DIST_ID-$DIST_VERS in
  885. ubuntu-*|debian-*)
  886. # debian uses the /etc/apache2 path, while other distros use
  887. # the apache default at /etc/httpd
  888. APACHE_SITES_AVAILABLE="/etc/apache2/sites-available"
  889. APACHE_SITES_ENABLED="/etc/apache2/sites-enabled"
  890. APACHE_MODULES="/usr/lib/apache2/modules"
  891. APACHE_PACKAGES="apache2"
  892. ;;
  893. arch-*)
  894. APACHE_SITES_AVAILABLE="/etc/httpd/sites-available"
  895. APACHE_SITES_ENABLED="/etc/httpd/sites-enabled"
  896. APACHE_MODULES="modules"
  897. APACHE_PACKAGES="apache"
  898. ;;
  899. fedora-*|centos-7)
  900. APACHE_SITES_AVAILABLE="/etc/httpd/sites-available"
  901. APACHE_SITES_ENABLED="/etc/httpd/sites-enabled"
  902. APACHE_MODULES="modules"
  903. APACHE_PACKAGES="httpd"
  904. ;;
  905. *)
  906. err_msg "$DIST_ID-$DIST_VERS: apache not yet implemented"
  907. ;;
  908. esac
  909. }
  910. apache_distro_setup
  911. install_apache(){
  912. info_msg "installing apache ..."
  913. pkg_install "$APACHE_PACKAGES"
  914. case $DIST_ID-$DIST_VERS in
  915. arch-*|fedora-*|centos-7)
  916. if ! grep "IncludeOptional sites-enabled" "/etc/httpd/conf/httpd.conf"; then
  917. echo "IncludeOptional sites-enabled/*.conf" >> "/etc/httpd/conf/httpd.conf"
  918. fi
  919. systemctl enable httpd
  920. systemctl start httpd
  921. ;;
  922. esac
  923. }
  924. apache_is_installed() {
  925. case $DIST_ID-$DIST_VERS in
  926. ubuntu-*|debian-*) (command -v apachectl) &>/dev/null;;
  927. arch-*) (command -v httpd) &>/dev/null;;
  928. fedora-*|centos-7) (command -v httpd) &>/dev/null;;
  929. esac
  930. }
  931. apache_reload() {
  932. info_msg "reload apache .."
  933. echo
  934. case $DIST_ID-$DIST_VERS in
  935. ubuntu-*|debian-*)
  936. sudo -H apachectl configtest
  937. sudo -H systemctl force-reload apache2
  938. ;;
  939. arch-*|fedora-*|centos-7)
  940. sudo -H httpd -t
  941. sudo -H systemctl force-reload httpd
  942. ;;
  943. esac
  944. }
  945. apache_install_site() {
  946. # usage: apache_install_site [<template option> ...] <mysite.conf>
  947. #
  948. # <template option>: see install_template
  949. local template_opts=()
  950. local pos_args=("$0")
  951. for i in "$@"; do
  952. case $i in
  953. -*) template_opts+=("$i");;
  954. *) pos_args+=("$i");;
  955. esac
  956. done
  957. install_template "${template_opts[@]}" \
  958. "${APACHE_SITES_AVAILABLE}/${pos_args[1]}" \
  959. root root 644
  960. apache_enable_site "${pos_args[1]}"
  961. info_msg "installed apache site: ${pos_args[1]}"
  962. }
  963. apache_remove_site() {
  964. # usage: apache_remove_site <mysite.conf>
  965. info_msg "remove apache site: $1"
  966. apache_dissable_site "$1"
  967. rm -f "${APACHE_SITES_AVAILABLE}/$1"
  968. }
  969. apache_enable_site() {
  970. # usage: apache_enable_site <mysite.conf>
  971. local CONF="$1"
  972. info_msg "enable apache site: ${CONF}"
  973. case $DIST_ID-$DIST_VERS in
  974. ubuntu-*|debian-*)
  975. sudo -H a2ensite -q "${CONF}"
  976. ;;
  977. arch-*)
  978. mkdir -p "${APACHE_SITES_ENABLED}"
  979. rm -f "${APACHE_SITES_ENABLED}/${CONF}"
  980. ln -s "${APACHE_SITES_AVAILABLE}/${CONF}" "${APACHE_SITES_ENABLED}/${CONF}"
  981. ;;
  982. fedora-*|centos-7)
  983. mkdir -p "${APACHE_SITES_ENABLED}"
  984. rm -f "${APACHE_SITES_ENABLED}/${CONF}"
  985. ln -s "${APACHE_SITES_AVAILABLE}/${CONF}" "${APACHE_SITES_ENABLED}/${CONF}"
  986. ;;
  987. esac
  988. apache_reload
  989. }
  990. apache_dissable_site() {
  991. # usage: apache_disable_site <mysite.conf>
  992. local CONF="$1"
  993. info_msg "disable apache site: ${CONF}"
  994. case $DIST_ID-$DIST_VERS in
  995. ubuntu-*|debian-*)
  996. sudo -H a2dissite -q "${CONF}"
  997. ;;
  998. arch-*)
  999. rm -f "${APACHE_SITES_ENABLED}/${CONF}"
  1000. ;;
  1001. fedora-*|centos-7)
  1002. rm -f "${APACHE_SITES_ENABLED}/${CONF}"
  1003. ;;
  1004. esac
  1005. apache_reload
  1006. }
  1007. # uWSGI
  1008. # -----
  1009. uWSGI_SETUP="${uWSGI_SETUP:=/etc/uwsgi}"
  1010. uWSGI_USER=
  1011. uWSGI_GROUP=
  1012. # How distros manage uWSGI apps is very different. From uWSGI POV read:
  1013. # - https://uwsgi-docs.readthedocs.io/en/latest/Management.html
  1014. uWSGI_distro_setup() {
  1015. case $DIST_ID-$DIST_VERS in
  1016. ubuntu-*|debian-*)
  1017. # init.d --> /usr/share/doc/uwsgi/README.Debian.gz
  1018. # For uWSGI debian uses the LSB init process, this might be changed
  1019. # one day, see https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=833067
  1020. uWSGI_APPS_AVAILABLE="${uWSGI_SETUP}/apps-available"
  1021. uWSGI_APPS_ENABLED="${uWSGI_SETUP}/apps-enabled"
  1022. uWSGI_PACKAGES="uwsgi"
  1023. ;;
  1024. arch-*)
  1025. # systemd --> /usr/lib/systemd/system/uwsgi@.service
  1026. # For uWSGI archlinux uses systemd template units, see
  1027. # - http://0pointer.de/blog/projects/instances.html
  1028. # - https://uwsgi-docs.readthedocs.io/en/latest/Systemd.html#one-service-per-app-in-systemd
  1029. uWSGI_APPS_AVAILABLE="${uWSGI_SETUP}/apps-archlinux"
  1030. uWSGI_APPS_ENABLED="${uWSGI_SETUP}"
  1031. uWSGI_PACKAGES="uwsgi"
  1032. ;;
  1033. fedora-*|centos-7)
  1034. # systemd --> /usr/lib/systemd/system/uwsgi.service
  1035. # The unit file starts uWSGI in emperor mode (/etc/uwsgi.ini), see
  1036. # - https://uwsgi-docs.readthedocs.io/en/latest/Emperor.html
  1037. uWSGI_APPS_AVAILABLE="${uWSGI_SETUP}/apps-available"
  1038. uWSGI_APPS_ENABLED="${uWSGI_SETUP}.d"
  1039. uWSGI_PACKAGES="uwsgi"
  1040. uWSGI_USER="uwsgi"
  1041. uWSGI_GROUP="uwsgi"
  1042. ;;
  1043. *)
  1044. err_msg "$DIST_ID-$DIST_VERS: uWSGI not yet implemented"
  1045. ;;
  1046. esac
  1047. }
  1048. uWSGI_distro_setup
  1049. install_uwsgi(){
  1050. info_msg "installing uwsgi ..."
  1051. pkg_install "$uWSGI_PACKAGES"
  1052. case $DIST_ID-$DIST_VERS in
  1053. fedora-*|centos-7)
  1054. # enable & start should be called once at uWSGI installation time
  1055. systemctl enable uwsgi
  1056. systemctl restart uwsgi
  1057. ;;
  1058. esac
  1059. }
  1060. uWSGI_restart() {
  1061. # usage: uWSGI_restart() <myapp.ini>
  1062. local CONF="$1"
  1063. [[ -z $CONF ]] && die_caller 42 "missing argument <myapp.ini>"
  1064. info_msg "restart uWSGI service"
  1065. case $DIST_ID-$DIST_VERS in
  1066. ubuntu-*|debian-*)
  1067. # the 'service' method seems broken in that way, that it (re-)starts
  1068. # the whole uwsgi process.
  1069. service uwsgi restart "${CONF%.*}"
  1070. ;;
  1071. arch-*)
  1072. # restart systemd template instance
  1073. if uWSGI_app_available "${CONF}"; then
  1074. systemctl restart "uwsgi@${CONF%.*}"
  1075. else
  1076. info_msg "[uWSGI:systemd-template] ${CONF} not installed (no need to restart)"
  1077. fi
  1078. ;;
  1079. fedora-*|centos-7)
  1080. # in emperor mode, just touch the file to restart
  1081. if uWSGI_app_enabled "${CONF}"; then
  1082. touch "${uWSGI_APPS_ENABLED}/${CONF}"
  1083. # it seems, there is a polling time in between touch and restart
  1084. # of the service.
  1085. sleep 3
  1086. else
  1087. info_msg "[uWSGI:emperor] ${CONF} not installed (no need to restart)"
  1088. fi
  1089. ;;
  1090. *)
  1091. err_msg "$DIST_ID-$DIST_VERS: uWSGI not yet implemented"
  1092. return 42
  1093. ;;
  1094. esac
  1095. }
  1096. uWSGI_prepare_app() {
  1097. # usage: uWSGI_prepare_app <myapp.ini>
  1098. [[ -z $1 ]] && die_caller 42 "missing argument <myapp.ini>"
  1099. local APP="${1%.*}"
  1100. case $DIST_ID-$DIST_VERS in
  1101. fedora-*|centos-7)
  1102. # in emperor mode, the uwsgi user is the owner of the sockets
  1103. info_msg "prepare (uwsgi:uwsgi) /run/uwsgi/app/${APP}"
  1104. mkdir -p "/run/uwsgi/app/${APP}"
  1105. chown -R "uwsgi:uwsgi" "/run/uwsgi/app/${APP}"
  1106. ;;
  1107. *)
  1108. info_msg "prepare (${SERVICE_USER}:${SERVICE_GROUP}) /run/uwsgi/app/${APP}"
  1109. mkdir -p "/run/uwsgi/app/${APP}"
  1110. chown -R "${SERVICE_USER}:${SERVICE_GROUP}" "/run/uwsgi/app/${APP}"
  1111. ;;
  1112. esac
  1113. }
  1114. uWSGI_app_available() {
  1115. # usage: uWSGI_app_available <myapp.ini>
  1116. local CONF="$1"
  1117. [[ -z $CONF ]] && die_caller 42 "missing argument <myapp.ini>"
  1118. [[ -f "${uWSGI_APPS_AVAILABLE}/${CONF}" ]]
  1119. }
  1120. uWSGI_install_app() {
  1121. # usage: uWSGI_install_app [<template option> ...] <myapp.ini>
  1122. #
  1123. # <template option>: see install_template
  1124. local pos_args=("$0")
  1125. for i in "$@"; do
  1126. case $i in
  1127. -*) template_opts+=("$i");;
  1128. *) pos_args+=("$i");;
  1129. esac
  1130. done
  1131. uWSGI_prepare_app "${pos_args[1]}"
  1132. mkdir -p "${uWSGI_APPS_AVAILABLE}"
  1133. install_template "${template_opts[@]}" \
  1134. "${uWSGI_APPS_AVAILABLE}/${pos_args[1]}" \
  1135. root root 644
  1136. uWSGI_enable_app "${pos_args[1]}"
  1137. uWSGI_restart "${pos_args[1]}"
  1138. info_msg "uWSGI app: ${pos_args[1]} is installed"
  1139. }
  1140. uWSGI_remove_app() {
  1141. # usage: uWSGI_remove_app <myapp.ini>
  1142. local CONF="$1"
  1143. [[ -z $CONF ]] && die_caller 42 "missing argument <myapp.ini>"
  1144. info_msg "remove uWSGI app: ${CONF}"
  1145. uWSGI_disable_app "${CONF}"
  1146. uWSGI_restart "${CONF}"
  1147. rm -f "${uWSGI_APPS_AVAILABLE}/${CONF}"
  1148. }
  1149. uWSGI_app_enabled() {
  1150. # usage: uWSGI_app_enabled <myapp.ini>
  1151. local exit_val=0
  1152. local CONF="$1"
  1153. [[ -z $CONF ]] && die_caller 42 "missing argument <myapp.ini>"
  1154. case $DIST_ID-$DIST_VERS in
  1155. ubuntu-*|debian-*)
  1156. [[ -f "${uWSGI_APPS_ENABLED}/${CONF}" ]]
  1157. exit_val=$?
  1158. ;;
  1159. arch-*)
  1160. systemctl -q is-enabled "uwsgi@${CONF%.*}"
  1161. exit_val=$?
  1162. ;;
  1163. fedora-*|centos-7)
  1164. [[ -f "${uWSGI_APPS_ENABLED}/${CONF}" ]]
  1165. exit_val=$?
  1166. ;;
  1167. *)
  1168. # FIXME
  1169. err_msg "$DIST_ID-$DIST_VERS: uWSGI not yet implemented"
  1170. exit_val=1
  1171. ;;
  1172. esac
  1173. return $exit_val
  1174. }
  1175. # shellcheck disable=SC2164
  1176. uWSGI_enable_app() {
  1177. # usage: uWSGI_enable_app <myapp.ini>
  1178. local CONF="$1"
  1179. [[ -z $CONF ]] && die_caller 42 "missing argument <myapp.ini>"
  1180. case $DIST_ID-$DIST_VERS in
  1181. ubuntu-*|debian-*)
  1182. mkdir -p "${uWSGI_APPS_ENABLED}"
  1183. rm -f "${uWSGI_APPS_ENABLED}/${CONF}"
  1184. ln -s "${uWSGI_APPS_AVAILABLE}/${CONF}" "${uWSGI_APPS_ENABLED}/${CONF}"
  1185. info_msg "enabled uWSGI app: ${CONF} (restart required)"
  1186. ;;
  1187. arch-*)
  1188. mkdir -p "${uWSGI_APPS_ENABLED}"
  1189. rm -f "${uWSGI_APPS_ENABLED}/${CONF}"
  1190. ln -s "${uWSGI_APPS_AVAILABLE}/${CONF}" "${uWSGI_APPS_ENABLED}/${CONF}"
  1191. systemctl enable "uwsgi@${CONF%.*}"
  1192. info_msg "enabled uWSGI app: ${CONF} (restart required)"
  1193. ;;
  1194. fedora-*|centos-7)
  1195. mkdir -p "${uWSGI_APPS_ENABLED}"
  1196. rm -f "${uWSGI_APPS_ENABLED}/${CONF}"
  1197. ln -s "${uWSGI_APPS_AVAILABLE}/${CONF}" "${uWSGI_APPS_ENABLED}/${CONF}"
  1198. chown "${uWSGI_USER}:${uWSGI_GROUP}" "${uWSGI_APPS_ENABLED}/${CONF}"
  1199. info_msg "enabled uWSGI app: ${CONF}"
  1200. ;;
  1201. *)
  1202. # FIXME
  1203. err_msg "$DIST_ID-$DIST_VERS: uWSGI not yet implemented"
  1204. ;;
  1205. esac
  1206. }
  1207. uWSGI_disable_app() {
  1208. # usage: uWSGI_disable_app <myapp.ini>
  1209. local CONF="$1"
  1210. [[ -z $CONF ]] && die_caller 42 "missing argument <myapp.ini>"
  1211. case $DIST_ID-$DIST_VERS in
  1212. ubuntu-*|debian-*)
  1213. service uwsgi stop "${CONF%.*}"
  1214. rm -f "${uWSGI_APPS_ENABLED}/${CONF}"
  1215. info_msg "disabled uWSGI app: ${CONF} (restart uWSGI required)"
  1216. ;;
  1217. arch-*)
  1218. systemctl stop "uwsgi@${CONF%.*}"
  1219. systemctl disable "uwsgi@${CONF%.*}"
  1220. rm -f "${uWSGI_APPS_ENABLED}/${CONF}"
  1221. ;;
  1222. fedora-*|centos-7)
  1223. # in emperor mode, just remove the app.ini file
  1224. rm -f "${uWSGI_APPS_ENABLED}/${CONF}"
  1225. ;;
  1226. *)
  1227. # FIXME
  1228. err_msg "$DIST_ID-$DIST_VERS: uWSGI not yet implemented"
  1229. ;;
  1230. esac
  1231. }
  1232. # distro's package manager
  1233. # ------------------------
  1234. _apt_pkg_info_is_updated=0
  1235. pkg_install() {
  1236. # usage: TITLE='install foobar' pkg_install foopkg barpkg
  1237. rst_title "${TITLE:-installation of packages}" section
  1238. echo -e "\npackage(s)::\n"
  1239. # shellcheck disable=SC2068
  1240. echo " " $@ | $FMT
  1241. if ! ask_yn "Should packages be installed?" Yn 30; then
  1242. return 42
  1243. fi
  1244. case $DIST_ID in
  1245. ubuntu|debian)
  1246. if [[ $_apt_pkg_info_is_updated == 0 ]]; then
  1247. export _apt_pkg_info_is_updated=1
  1248. apt update
  1249. fi
  1250. # shellcheck disable=SC2068
  1251. apt-get install -m -y $@
  1252. ;;
  1253. arch)
  1254. # shellcheck disable=SC2068
  1255. pacman -Sy --noconfirm $@
  1256. ;;
  1257. fedora)
  1258. # shellcheck disable=SC2068
  1259. dnf install -y $@
  1260. ;;
  1261. centos)
  1262. # shellcheck disable=SC2068
  1263. yum install -y $@
  1264. ;;
  1265. esac
  1266. }
  1267. pkg_remove() {
  1268. # usage: TITLE='remove foobar' pkg_remove foopkg barpkg
  1269. rst_title "${TITLE:-remove packages}" section
  1270. echo -e "\npackage(s)::\n"
  1271. # shellcheck disable=SC2068
  1272. echo " " $@ | $FMT
  1273. if ! ask_yn "Should packages be removed (purge)?" Yn 30; then
  1274. return 42
  1275. fi
  1276. case $DIST_ID in
  1277. ubuntu|debian)
  1278. # shellcheck disable=SC2068
  1279. apt-get purge --autoremove --ignore-missing -y $@
  1280. ;;
  1281. arch)
  1282. # shellcheck disable=SC2068
  1283. pacman -R --noconfirm $@
  1284. ;;
  1285. fedora)
  1286. # shellcheck disable=SC2068
  1287. dnf remove -y $@
  1288. ;;
  1289. centos)
  1290. # shellcheck disable=SC2068
  1291. yum remove -y $@
  1292. ;;
  1293. esac
  1294. }
  1295. pkg_is_installed() {
  1296. # usage: pkg_is_install foopkg || pkg_install foopkg
  1297. case $DIST_ID in
  1298. ubuntu|debian)
  1299. dpkg -l "$1" &> /dev/null
  1300. return $?
  1301. ;;
  1302. arch)
  1303. pacman -Qsq "$1" &> /dev/null
  1304. return $?
  1305. ;;
  1306. fedora)
  1307. dnf list -q --installed "$1" &> /dev/null
  1308. return $?
  1309. ;;
  1310. centos)
  1311. yum list -q --installed "$1" &> /dev/null
  1312. return $?
  1313. ;;
  1314. esac
  1315. }
  1316. # git tooling
  1317. # -----------
  1318. # shellcheck disable=SC2164
  1319. git_clone() {
  1320. # usage:
  1321. #
  1322. # git_clone <url> <name> [<branch> [<user>]]
  1323. # git_clone <url> <path> [<branch> [<user>]]
  1324. #
  1325. # First form uses $CACHE/<name> as destination folder, second form clones
  1326. # into <path>. If repository is already cloned, pull from <branch> and
  1327. # update working tree (if needed, the caller has to stash local changes).
  1328. #
  1329. # git clone https://github.com/searx/searx searx-src origin/master searxlogin
  1330. #
  1331. local url="$1"
  1332. local dest="$2"
  1333. local branch="$3"
  1334. local user="$4"
  1335. local bash_cmd="bash"
  1336. local remote="origin"
  1337. if [[ ! "${dest:0:1}" = "/" ]]; then
  1338. dest="$CACHE/$dest"
  1339. fi
  1340. [[ -z $branch ]] && branch=master
  1341. [[ -z $user ]] && [[ -n "${SUDO_USER}" ]] && user="${SUDO_USER}"
  1342. [[ -n $user ]] && bash_cmd="sudo -H -u $user -i"
  1343. if [[ -d "${dest}" ]] ; then
  1344. info_msg "already cloned: $dest"
  1345. tee_stderr 0.1 <<EOF | $bash_cmd 2>&1 | prefix_stdout " ${_Yellow}|$user|${_creset} "
  1346. cd "${dest}"
  1347. git checkout -m -B "$branch" --track "$remote/$branch"
  1348. git pull --all
  1349. EOF
  1350. else
  1351. info_msg "clone into: $dest"
  1352. tee_stderr 0.1 <<EOF | $bash_cmd 2>&1 | prefix_stdout " ${_Yellow}|$user|${_creset} "
  1353. mkdir -p "$(dirname "$dest")"
  1354. cd "$(dirname "$dest")"
  1355. git clone --branch "$branch" --origin "$remote" "$url" "$(basename "$dest")"
  1356. EOF
  1357. fi
  1358. }
  1359. # containers
  1360. # ----------
  1361. in_container() {
  1362. # Test if shell runs in a container.
  1363. #
  1364. # usage: in_container && echo "process running inside a LXC container"
  1365. # in_container || echo "process is not running inside a LXC container"
  1366. #
  1367. # sudo_or_exit
  1368. # hint: Reads init process environment, therefore root access is required!
  1369. # to be safe, take a look at the environment of process 1 (/sbin/init)
  1370. # grep -qa 'container=lxc' /proc/1/environ
  1371. # see lxc_init_container_env
  1372. [[ -f /.lxcenv ]]
  1373. }
  1374. LXC_ENV_FOLDER=
  1375. if in_container; then
  1376. # shellcheck disable=SC2034
  1377. LXC_ENV_FOLDER="lxc-env/$(hostname)/"
  1378. PY_ENV="${LXC_ENV_FOLDER}${PY_ENV}"
  1379. PY_ENV_BIN="${LXC_ENV_FOLDER}${PY_ENV_BIN}"
  1380. PYDIST="${LXC_ENV_FOLDER}${PYDIST}"
  1381. PYBUILD="${LXC_ENV_FOLDER}${PYBUILD}"
  1382. DOCS_DIST="${LXC_ENV_FOLDER}${DOCS_DIST}"
  1383. DOCS_BUILD="${LXC_ENV_FOLDER}${DOCS_BUILD}"
  1384. fi
  1385. lxc_init_container_env() {
  1386. # usage: lxc_init_container_env <name>
  1387. # Create a /.lxcenv file in the root folder. Call this once after the
  1388. # container is initial started and before installing any boilerplate stuff.
  1389. info_msg "create /.lxcenv in container $1"
  1390. cat <<EOF | lxc exec "${1}" -- bash | prefix_stdout "[${_BBlue}${1}${_creset}] "
  1391. touch "/.lxcenv"
  1392. ls -l "/.lxcenv"
  1393. EOF
  1394. }
  1395. # apt packages
  1396. LXC_BASE_PACKAGES_debian="bash git build-essential python3 python3-venv"
  1397. # pacman packages
  1398. LXC_BASE_PACKAGES_arch="bash git base-devel python"
  1399. # dnf packages
  1400. LXC_BASE_PACKAGES_fedora="bash git @development-tools python"
  1401. # yum packages
  1402. LXC_BASE_PACKAGES_centos="bash git python3"
  1403. case $DIST_ID in
  1404. ubuntu|debian) LXC_BASE_PACKAGES="${LXC_BASE_PACKAGES_debian}" ;;
  1405. arch) LXC_BASE_PACKAGES="${LXC_BASE_PACKAGES_arch}" ;;
  1406. fedora) LXC_BASE_PACKAGES="${LXC_BASE_PACKAGES_fedora}" ;;
  1407. centos) LXC_BASE_PACKAGES="${LXC_BASE_PACKAGES_centos}" ;;
  1408. *) err_msg "$DIST_ID-$DIST_VERS: pkg_install LXC_BASE_PACKAGES not yet implemented" ;;
  1409. esac
  1410. lxc_install_base_packages() {
  1411. info_msg "install LXC_BASE_PACKAGES in container $1"
  1412. case $DIST_ID in
  1413. centos) yum groupinstall "Development Tools" -y ;;
  1414. esac
  1415. pkg_install "${LXC_BASE_PACKAGES}"
  1416. }
  1417. lxc_image_copy() {
  1418. # usage: lxc_image_copy <remote image> <local image>
  1419. #
  1420. # lxc_image_copy "images:ubuntu/20.04" "ubu2004"
  1421. if lxc_image_exists "local:${LXC_SUITE[i+1]}"; then
  1422. info_msg "image ${LXC_SUITE[i]} already copied --> ${LXC_SUITE[i+1]}"
  1423. else
  1424. info_msg "copy image locally ${LXC_SUITE[i]} --> ${LXC_SUITE[i+1]}"
  1425. lxc image copy "${LXC_SUITE[i]}" local: \
  1426. --alias "${LXC_SUITE[i+1]}" | prefix_stdout
  1427. fi
  1428. }
  1429. lxc_init_container() {
  1430. # usage: lxc_init_container <image name> <container name>
  1431. local image_name="$1"
  1432. local container_name="$2"
  1433. if lxc info "${container_name}" &>/dev/null; then
  1434. info_msg "container '${container_name}' already exists"
  1435. else
  1436. info_msg "create container instance: ${container_name}"
  1437. lxc init "local:${image_name}" "${container_name}"
  1438. fi
  1439. }
  1440. lxc_exists(){
  1441. # usage: lxc_exists <name> || echo "container <name> does not exists"
  1442. lxc info "$1" &>/dev/null
  1443. }
  1444. lxc_image_exists(){
  1445. # usage: lxc_image_exists <alias> || echo "image <alias> does locally not exists"
  1446. lxc image info "local:$1" &>/dev/null
  1447. }
  1448. lxc_delete_container() {
  1449. # usage: lxc_delete_container <container-name>
  1450. if lxc info "$1" &>/dev/null; then
  1451. info_msg "stop & delete instance ${_BBlue}${1}${_creset}"
  1452. lxc stop "$1" &>/dev/null
  1453. lxc delete "$1" | prefix_stdout
  1454. else
  1455. warn_msg "instance '$1' does not exist / can't delete :o"
  1456. fi
  1457. }
  1458. lxc_delete_local_image() {
  1459. # usage: lxc_delete_local_image <container-name>
  1460. info_msg "delete image 'local:$i'"
  1461. lxc image delete "local:$i"
  1462. }
  1463. # IP
  1464. # --
  1465. global_IPs(){
  1466. # usage: global_IPS
  1467. #
  1468. # print list of host's SCOPE global addresses and adapters e.g::
  1469. #
  1470. # $ global_IPs
  1471. # enp4s0|192.168.1.127
  1472. # lxdbr0|10.246.86.1
  1473. # lxdbr0|fd42:8c58:2cd:b73f::1
  1474. ip -o addr show | sed -nr 's/[0-9]*:\s*([a-z0-9]*).*inet[6]?\s*([a-z0-9.:]*).*scope global.*/\1|\2/p'
  1475. }
  1476. primary_ip() {
  1477. case $DIST_ID in
  1478. arch)
  1479. ip -o addr show \
  1480. | sed -nr 's/[0-9]*:\s*([a-z0-9]*).*inet[6]?\s*([a-z0-9.:]*).*scope global.*/\2/p' \
  1481. | head -n 1
  1482. ;;
  1483. *) hostname -I | cut -d' ' -f1 ;;
  1484. esac
  1485. }
  1486. # URL
  1487. # ---
  1488. url_replace_hostname(){
  1489. # usage: url_replace_hostname <url> <new hostname>
  1490. # to replace hostname by primary IP::
  1491. #
  1492. # url_replace_hostname http://searx-ubu1604/morty $(primary_ip)
  1493. # http://10.246.86.250/morty
  1494. # shellcheck disable=SC2001
  1495. echo "$1" | sed "s|\(http[s]*://\)[^/]*\(.*\)|\1$2\2|"
  1496. }