lib.sh 49 KB

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