lib.sh 48 KB

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