lib.sh 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860
  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. pyenv.check \
  501. | "${PY_ENV_BIN}/python" 2>&1 \
  502. | prefix_stdout "${_Blue}PYENV ${_creset}[check] "
  503. local err=${PIPESTATUS[1]}
  504. if [ "$err" -ne "0" ]; then
  505. build_msg PYENV "[check] python test failed"
  506. return "$err"
  507. fi
  508. build_msg PYENV "OK"
  509. _pyenv_OK="OK"
  510. return 0
  511. }
  512. pyenv.drop() {
  513. build_msg PYENV "[virtualenv] drop ${PY_ENV}"
  514. rm -rf "${PY_ENV}"
  515. _pyenv_OK=''
  516. }
  517. pyenv.check() {
  518. # Prompts a python script with additional checks. Used by pyenv.OK to check
  519. # if virtualenv is ready to install python objects. This function should be
  520. # overwritten by the application script.
  521. local imp=""
  522. for i in "${PIP_BOILERPLATE[@]}"; do
  523. imp="$imp, $i"
  524. done
  525. cat <<EOF
  526. import ${imp#,*}
  527. EOF
  528. }
  529. pyenv.install() {
  530. if ! pyenv.OK; then
  531. py.clean > /dev/null
  532. fi
  533. if ! pyenv.install.OK > /dev/null; then
  534. build_msg PYENV "[install] ${PYOBJECTS}"
  535. if ! pyenv.OK >/dev/null; then
  536. pyenv
  537. fi
  538. for i in ${PYOBJECTS}; do
  539. build_msg PYENV "[install] pip install -e '$i${PY_SETUP_EXTRAS}'"
  540. "${PY_ENV_BIN}/python" -m pip install -e "$i${PY_SETUP_EXTRAS}"
  541. done
  542. fi
  543. pyenv.install.OK
  544. }
  545. _pyenv_install_OK=''
  546. pyenv.install.OK() {
  547. [ "$_pyenv_install_OK" == "OK" ] && return 0
  548. local imp=""
  549. local err=""
  550. if [ "." = "${PYOBJECTS}" ]; then
  551. imp="import $(basename "$(pwd)")"
  552. else
  553. # shellcheck disable=SC2086
  554. for i in ${PYOBJECTS}; do imp="$imp, $i"; done
  555. imp="import ${imp#,*} "
  556. fi
  557. (
  558. [ "$VERBOSE" = "1" ] && set -x
  559. "${PY_ENV_BIN}/python" -c "import sys; sys.path.pop(0); $imp;" 2>/dev/null
  560. )
  561. err=$?
  562. if [ "$err" -ne "0" ]; then
  563. build_msg PYENV "[install] python installation test failed"
  564. return "$err"
  565. fi
  566. build_msg PYENV "[install] OK"
  567. _pyenv_install_OK="OK"
  568. return 0
  569. }
  570. pyenv.uninstall() {
  571. build_msg PYENV "[uninstall] ${PYOBJECTS}"
  572. if [ "." = "${PYOBJECTS}" ]; then
  573. pyenv.cmd python setup.py develop --uninstall 2>&1 \
  574. | prefix_stdout "${_Blue}PYENV ${_creset}[pyenv.uninstall] "
  575. else
  576. pyenv.cmd python -m pip uninstall --yes ${PYOBJECTS} 2>&1 \
  577. | prefix_stdout "${_Blue}PYENV ${_creset}[pyenv.uninstall] "
  578. fi
  579. }
  580. pyenv.cmd() {
  581. pyenv.install
  582. ( set -e
  583. # shellcheck source=/dev/null
  584. source "${PY_ENV_BIN}/activate"
  585. [ "$VERBOSE" = "1" ] && set -x
  586. "$@"
  587. )
  588. }
  589. # Sphinx doc
  590. # ----------
  591. GH_PAGES="build/gh-pages"
  592. DOCS_DIST="${DOCS_DIST:=dist/docs}"
  593. DOCS_BUILD="${DOCS_BUILD:=build/docs}"
  594. docs.html() {
  595. build_msg SPHINX "HTML ./docs --> file://$(readlink -e "$(pwd)/$DOCS_DIST")"
  596. pyenv.install
  597. docs.prebuild
  598. # shellcheck disable=SC2086
  599. PATH="${PY_ENV_BIN}:${PATH}" pyenv.cmd sphinx-build \
  600. ${SPHINX_VERBOSE} ${SPHINXOPTS} \
  601. -b html -c ./docs -d "${DOCS_BUILD}/.doctrees" ./docs "${DOCS_DIST}"
  602. dump_return $?
  603. }
  604. docs.live() {
  605. build_msg SPHINX "autobuild ./docs --> file://$(readlink -e "$(pwd)/$DOCS_DIST")"
  606. pyenv.install
  607. docs.prebuild
  608. # shellcheck disable=SC2086
  609. PATH="${PY_ENV_BIN}:${PATH}" pyenv.cmd sphinx-autobuild \
  610. ${SPHINX_VERBOSE} ${SPHINXOPTS} --open-browser --host 0.0.0.0 \
  611. -b html -c ./docs -d "${DOCS_BUILD}/.doctrees" ./docs "${DOCS_DIST}"
  612. dump_return $?
  613. }
  614. docs.clean() {
  615. build_msg CLEAN "docs -- ${DOCS_BUILD} ${DOCS_DIST}"
  616. # shellcheck disable=SC2115
  617. rm -rf "${GH_PAGES}" "${DOCS_BUILD}" "${DOCS_DIST}"
  618. dump_return $?
  619. }
  620. docs.prebuild() {
  621. # Dummy function to run some actions before sphinx-doc build gets started.
  622. # This finction needs to be overwritten by the application script.
  623. true
  624. dump_return $?
  625. }
  626. # shellcheck disable=SC2155
  627. docs.gh-pages() {
  628. # The commit history in the gh-pages branch makes no sense, the history only
  629. # inflates the repository unnecessarily. Therefore a *new orphan* branch
  630. # is created each time we deploy on the gh-pages branch.
  631. docs.clean
  632. docs.prebuild
  633. docs.html
  634. [ "$VERBOSE" = "1" ] && set -x
  635. local head="$(git rev-parse HEAD)"
  636. local branch="$(git name-rev --name-only HEAD)"
  637. local remote="$(git config branch."${branch}".remote)"
  638. local remote_url="$(git config remote."${remote}".url)"
  639. build_msg GH-PAGES "prepare folder: ${GH_PAGES}"
  640. build_msg GH-PAGES "remote of the gh-pages branch: ${remote} / ${remote_url}"
  641. build_msg GH-PAGES "current branch: ${branch}"
  642. # prepare the *orphan* gh-pages working tree
  643. (
  644. git worktree remove -f "${GH_PAGES}"
  645. git branch -D gh-pages
  646. ) &> /dev/null || true
  647. git worktree add --no-checkout "${GH_PAGES}" "${remote}/master"
  648. pushd "${GH_PAGES}" &> /dev/null
  649. git checkout --orphan gh-pages
  650. git rm -rfq .
  651. popd &> /dev/null
  652. cp -r "${DOCS_DIST}"/* "${GH_PAGES}"/
  653. touch "${GH_PAGES}/.nojekyll"
  654. cat > "${GH_PAGES}/404.html" <<EOF
  655. <html><head><META http-equiv='refresh' content='0;URL=index.html'></head></html>
  656. EOF
  657. pushd "${GH_PAGES}" &> /dev/null
  658. git add --all .
  659. git commit -q -m "gh-pages build from: ${branch}@${head} (${remote_url})"
  660. git push -f "${remote}" gh-pages
  661. popd &> /dev/null
  662. set +x
  663. build_msg GH-PAGES "deployed"
  664. }
  665. # golang
  666. # ------
  667. go_is_available() {
  668. # usage: go_is_available $SERVICE_USER && echo "go is installed!"
  669. sudo -i -u "${1}" which go &>/dev/null
  670. }
  671. install_go() {
  672. # usage: install_go "${GO_PKG_URL}" "${GO_TAR}" "${SERVICE_USER}"
  673. local _svcpr=" ${_Yellow}|${3}|${_creset} "
  674. rst_title "Install Go in user's HOME" section
  675. rst_para "download and install go binary .."
  676. cache_download "${1}" "${2}"
  677. tee_stderr 0.1 <<EOF | sudo -i -u "${3}" | prefix_stdout "$_svcpr"
  678. echo \$PATH
  679. echo \$GOPATH
  680. mkdir -p \$HOME/local
  681. rm -rf \$HOME/local/go
  682. tar -C \$HOME/local -xzf ${CACHE}/${2}
  683. EOF
  684. sudo -i -u "${3}" <<EOF | prefix_stdout
  685. ! which go >/dev/null && echo "ERROR - Go Installation not found in PATH!?!"
  686. which go >/dev/null && go version && echo "congratulations -- Go installation OK :)"
  687. EOF
  688. }
  689. # system accounts
  690. # ---------------
  691. service_account_is_available() {
  692. # usage: service_account_is_available "$SERVICE_USER" && echo "OK"
  693. sudo -i -u "$1" echo \$HOME &>/dev/null
  694. }
  695. drop_service_account() {
  696. # usage: drop_service_account "${SERVICE_USER}"
  697. rst_title "Drop ${1} HOME" section
  698. if ask_yn "Do you really want to drop ${1} home folder?"; then
  699. userdel -r -f "${1}" 2>&1 | prefix_stdout
  700. else
  701. rst_para "Leave HOME folder $(du -sh "${1}") unchanged."
  702. fi
  703. }
  704. interactive_shell(){
  705. # usage: interactive_shell "${SERVICE_USER}"
  706. echo -e "// exit with [${_BCyan}CTRL-D${_creset}]"
  707. sudo -H -u "${1}" -i
  708. }
  709. # systemd
  710. # -------
  711. SYSTEMD_UNITS="${SYSTEMD_UNITS:-/lib/systemd/system}"
  712. systemd_install_service() {
  713. # usage: systemd_install_service "${SERVICE_NAME}" "${SERVICE_SYSTEMD_UNIT}"
  714. rst_title "Install System-D Unit ${1}" section
  715. echo
  716. install_template "${2}" root root 644
  717. wait_key
  718. systemd_activate_service "${1}"
  719. }
  720. systemd_remove_service() {
  721. # usage: systemd_remove_service "${SERVICE_NAME}" "${SERVICE_SYSTEMD_UNIT}"
  722. if ! ask_yn "Do you really want to deinstall systemd unit ${1}?"; then
  723. return 42
  724. fi
  725. systemd_deactivate_service "${1}"
  726. rm "${2}" 2>&1 | prefix_stdout
  727. }
  728. systemd_activate_service() {
  729. # usage: systemd_activate_service "${SERVICE_NAME}"
  730. rst_title "Activate ${1} (service)" section
  731. echo
  732. tee_stderr <<EOF | bash 2>&1
  733. systemctl enable ${1}.service
  734. systemctl restart ${1}.service
  735. EOF
  736. tee_stderr <<EOF | bash 2>&1
  737. systemctl status --no-pager ${1}.service
  738. EOF
  739. }
  740. systemd_deactivate_service() {
  741. # usage: systemd_deactivate_service "${SERVICE_NAME}"
  742. rst_title "De-Activate ${1} (service)" section
  743. echo
  744. tee_stderr <<EOF | bash 2>&1 | prefix_stdout
  745. systemctl stop ${1}.service
  746. systemctl disable ${1}.service
  747. EOF
  748. }
  749. systemd_restart_service() {
  750. # usage: systemd_restart_service "${SERVICE_NAME}"
  751. rst_title "Restart ${1} (service)" section
  752. echo
  753. tee_stderr <<EOF | bash 2>&1
  754. systemctl restart ${1}.service
  755. EOF
  756. tee_stderr <<EOF | bash 2>&1
  757. systemctl status --no-pager ${1}.service
  758. EOF
  759. }
  760. # nginx
  761. # -----
  762. nginx_distro_setup() {
  763. # shellcheck disable=SC2034
  764. NGINX_DEFAULT_SERVER=/etc/nginx/nginx.conf
  765. # Including *location* directives from a dedicated config-folder into the
  766. # server directive is, what fedora and centos (already) does.
  767. NGINX_APPS_ENABLED="/etc/nginx/default.d"
  768. # We add a apps-available folder and linking configurations into the
  769. # NGINX_APPS_ENABLED folder. See also nginx_include_apps_enabled().
  770. NGINX_APPS_AVAILABLE="/etc/nginx/default.apps-available"
  771. case $DIST_ID-$DIST_VERS in
  772. ubuntu-*|debian-*)
  773. NGINX_PACKAGES="nginx"
  774. NGINX_DEFAULT_SERVER=/etc/nginx/sites-available/default
  775. ;;
  776. arch-*)
  777. NGINX_PACKAGES="nginx-mainline"
  778. ;;
  779. fedora-*|centos-7)
  780. NGINX_PACKAGES="nginx"
  781. ;;
  782. *)
  783. err_msg "$DIST_ID-$DIST_VERS: nginx not yet implemented"
  784. ;;
  785. esac
  786. }
  787. nginx_distro_setup
  788. install_nginx(){
  789. info_msg "installing nginx ..."
  790. pkg_install "${NGINX_PACKAGES}"
  791. case $DIST_ID-$DIST_VERS in
  792. arch-*|fedora-*|centos-7)
  793. systemctl enable nginx
  794. systemctl start nginx
  795. ;;
  796. esac
  797. }
  798. nginx_is_installed() {
  799. command -v nginx &>/dev/null
  800. }
  801. nginx_reload() {
  802. info_msg "reload nginx .."
  803. echo
  804. if ! nginx -t; then
  805. err_msg "testing nginx configuration failed"
  806. return 42
  807. fi
  808. systemctl restart nginx
  809. }
  810. nginx_install_app() {
  811. # usage: nginx_install_app [<template option> ...] <myapp.conf>
  812. #
  813. # <template option>: see install_template
  814. local template_opts=()
  815. local pos_args=("$0")
  816. for i in "$@"; do
  817. case $i in
  818. -*) template_opts+=("$i");;
  819. *) pos_args+=("$i");;
  820. esac
  821. done
  822. nginx_include_apps_enabled "${NGINX_DEFAULT_SERVER}"
  823. install_template "${template_opts[@]}" \
  824. "${NGINX_APPS_AVAILABLE}/${pos_args[1]}" \
  825. root root 644
  826. nginx_enable_app "${pos_args[1]}"
  827. info_msg "installed nginx app: ${pos_args[1]}"
  828. }
  829. nginx_include_apps_enabled() {
  830. # Add the *NGINX_APPS_ENABLED* infrastruture to a nginx server block. Such
  831. # infrastruture is already known from fedora and centos, including apps (location
  832. # directives) from the /etc/nginx/default.d folder into the *default* nginx
  833. # server.
  834. # usage: nginx_include_apps_enabled <config-file>
  835. #
  836. # config-file: Config file with server directive in.
  837. [[ -z $1 ]] && die_caller 42 "missing argument <config-file>"
  838. local server_conf="$1"
  839. # include /etc/nginx/default.d/*.conf;
  840. local include_directive="include ${NGINX_APPS_ENABLED}/*.conf;"
  841. local include_directive_re="^\s*include ${NGINX_APPS_ENABLED}/\*\.conf;"
  842. info_msg "checking existence: '${include_directive}' in file ${server_conf}"
  843. if grep "${include_directive_re}" "${server_conf}"; then
  844. info_msg "OK, already exists."
  845. return
  846. fi
  847. info_msg "add missing directive: '${include_directive}'"
  848. cp "${server_conf}" "${server_conf}.bak"
  849. (
  850. local line
  851. local stage=0
  852. while IFS= read -r line
  853. do
  854. echo "$line"
  855. if [[ $stage = 0 ]]; then
  856. if [[ $line =~ ^[[:space:]]*server*[[:space:]]*\{ ]]; then
  857. stage=1
  858. fi
  859. fi
  860. if [[ $stage = 1 ]]; then
  861. echo " # Load configuration files for the default server block."
  862. echo " $include_directive"
  863. echo ""
  864. stage=2
  865. fi
  866. done < "${server_conf}.bak"
  867. ) > "${server_conf}"
  868. }
  869. nginx_remove_app() {
  870. # usage: nginx_remove_app <myapp.conf>
  871. info_msg "remove nginx app: $1"
  872. nginx_dissable_app "$1"
  873. rm -f "${NGINX_APPS_AVAILABLE}/$1"
  874. }
  875. nginx_enable_app() {
  876. # usage: nginx_enable_app <myapp.conf>
  877. local CONF="$1"
  878. info_msg "enable nginx app: ${CONF}"
  879. mkdir -p "${NGINX_APPS_ENABLED}"
  880. rm -f "${NGINX_APPS_ENABLED}/${CONF}"
  881. ln -s "${NGINX_APPS_AVAILABLE}/${CONF}" "${NGINX_APPS_ENABLED}/${CONF}"
  882. nginx_reload
  883. }
  884. nginx_dissable_app() {
  885. # usage: nginx_disable_app <myapp.conf>
  886. local CONF="$1"
  887. info_msg "disable nginx app: ${CONF}"
  888. rm -f "${NGINX_APPS_ENABLED}/${CONF}"
  889. nginx_reload
  890. }
  891. # Apache
  892. # ------
  893. apache_distro_setup() {
  894. # shellcheck disable=SC2034
  895. case $DIST_ID-$DIST_VERS in
  896. ubuntu-*|debian-*)
  897. # debian uses the /etc/apache2 path, while other distros use
  898. # the apache default at /etc/httpd
  899. APACHE_SITES_AVAILABLE="/etc/apache2/sites-available"
  900. APACHE_SITES_ENABLED="/etc/apache2/sites-enabled"
  901. APACHE_MODULES="/usr/lib/apache2/modules"
  902. APACHE_PACKAGES="apache2"
  903. ;;
  904. arch-*)
  905. APACHE_SITES_AVAILABLE="/etc/httpd/sites-available"
  906. APACHE_SITES_ENABLED="/etc/httpd/sites-enabled"
  907. APACHE_MODULES="modules"
  908. APACHE_PACKAGES="apache"
  909. ;;
  910. fedora-*|centos-7)
  911. APACHE_SITES_AVAILABLE="/etc/httpd/sites-available"
  912. APACHE_SITES_ENABLED="/etc/httpd/sites-enabled"
  913. APACHE_MODULES="modules"
  914. APACHE_PACKAGES="httpd"
  915. ;;
  916. *)
  917. err_msg "$DIST_ID-$DIST_VERS: apache not yet implemented"
  918. ;;
  919. esac
  920. }
  921. apache_distro_setup
  922. install_apache(){
  923. info_msg "installing apache ..."
  924. pkg_install "$APACHE_PACKAGES"
  925. case $DIST_ID-$DIST_VERS in
  926. arch-*|fedora-*|centos-7)
  927. if ! grep "IncludeOptional sites-enabled" "/etc/httpd/conf/httpd.conf"; then
  928. echo "IncludeOptional sites-enabled/*.conf" >> "/etc/httpd/conf/httpd.conf"
  929. fi
  930. systemctl enable httpd
  931. systemctl start httpd
  932. ;;
  933. esac
  934. }
  935. apache_is_installed() {
  936. case $DIST_ID-$DIST_VERS in
  937. ubuntu-*|debian-*) (command -v apachectl) &>/dev/null;;
  938. arch-*) (command -v httpd) &>/dev/null;;
  939. fedora-*|centos-7) (command -v httpd) &>/dev/null;;
  940. esac
  941. }
  942. apache_reload() {
  943. info_msg "reload apache .."
  944. echo
  945. case $DIST_ID-$DIST_VERS in
  946. ubuntu-*|debian-*)
  947. sudo -H apachectl configtest
  948. sudo -H systemctl force-reload apache2
  949. ;;
  950. arch-*|fedora-*|centos-7)
  951. sudo -H httpd -t
  952. sudo -H systemctl force-reload httpd
  953. ;;
  954. esac
  955. }
  956. apache_install_site() {
  957. # usage: apache_install_site [<template option> ...] <mysite.conf>
  958. #
  959. # <template option>: see install_template
  960. local template_opts=()
  961. local pos_args=("$0")
  962. for i in "$@"; do
  963. case $i in
  964. -*) template_opts+=("$i");;
  965. *) pos_args+=("$i");;
  966. esac
  967. done
  968. install_template "${template_opts[@]}" \
  969. "${APACHE_SITES_AVAILABLE}/${pos_args[1]}" \
  970. root root 644
  971. apache_enable_site "${pos_args[1]}"
  972. info_msg "installed apache site: ${pos_args[1]}"
  973. }
  974. apache_remove_site() {
  975. # usage: apache_remove_site <mysite.conf>
  976. info_msg "remove apache site: $1"
  977. apache_dissable_site "$1"
  978. rm -f "${APACHE_SITES_AVAILABLE}/$1"
  979. }
  980. apache_enable_site() {
  981. # usage: apache_enable_site <mysite.conf>
  982. local CONF="$1"
  983. info_msg "enable apache site: ${CONF}"
  984. case $DIST_ID-$DIST_VERS in
  985. ubuntu-*|debian-*)
  986. sudo -H a2ensite -q "${CONF}"
  987. ;;
  988. arch-*)
  989. mkdir -p "${APACHE_SITES_ENABLED}"
  990. rm -f "${APACHE_SITES_ENABLED}/${CONF}"
  991. ln -s "${APACHE_SITES_AVAILABLE}/${CONF}" "${APACHE_SITES_ENABLED}/${CONF}"
  992. ;;
  993. fedora-*|centos-7)
  994. mkdir -p "${APACHE_SITES_ENABLED}"
  995. rm -f "${APACHE_SITES_ENABLED}/${CONF}"
  996. ln -s "${APACHE_SITES_AVAILABLE}/${CONF}" "${APACHE_SITES_ENABLED}/${CONF}"
  997. ;;
  998. esac
  999. apache_reload
  1000. }
  1001. apache_dissable_site() {
  1002. # usage: apache_disable_site <mysite.conf>
  1003. local CONF="$1"
  1004. info_msg "disable apache site: ${CONF}"
  1005. case $DIST_ID-$DIST_VERS in
  1006. ubuntu-*|debian-*)
  1007. sudo -H a2dissite -q "${CONF}"
  1008. ;;
  1009. arch-*)
  1010. rm -f "${APACHE_SITES_ENABLED}/${CONF}"
  1011. ;;
  1012. fedora-*|centos-7)
  1013. rm -f "${APACHE_SITES_ENABLED}/${CONF}"
  1014. ;;
  1015. esac
  1016. apache_reload
  1017. }
  1018. # uWSGI
  1019. # -----
  1020. uWSGI_SETUP="${uWSGI_SETUP:=/etc/uwsgi}"
  1021. uWSGI_USER=
  1022. uWSGI_GROUP=
  1023. # How distros manage uWSGI apps is very different. From uWSGI POV read:
  1024. # - https://uwsgi-docs.readthedocs.io/en/latest/Management.html
  1025. uWSGI_distro_setup() {
  1026. case $DIST_ID-$DIST_VERS in
  1027. ubuntu-*|debian-*)
  1028. # init.d --> /usr/share/doc/uwsgi/README.Debian.gz
  1029. # For uWSGI debian uses the LSB init process, this might be changed
  1030. # one day, see https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=833067
  1031. uWSGI_APPS_AVAILABLE="${uWSGI_SETUP}/apps-available"
  1032. uWSGI_APPS_ENABLED="${uWSGI_SETUP}/apps-enabled"
  1033. uWSGI_PACKAGES="uwsgi"
  1034. ;;
  1035. arch-*)
  1036. # systemd --> /usr/lib/systemd/system/uwsgi@.service
  1037. # For uWSGI archlinux uses systemd template units, see
  1038. # - http://0pointer.de/blog/projects/instances.html
  1039. # - https://uwsgi-docs.readthedocs.io/en/latest/Systemd.html#one-service-per-app-in-systemd
  1040. uWSGI_APPS_AVAILABLE="${uWSGI_SETUP}/apps-archlinux"
  1041. uWSGI_APPS_ENABLED="${uWSGI_SETUP}"
  1042. uWSGI_PACKAGES="uwsgi"
  1043. ;;
  1044. fedora-*|centos-7)
  1045. # systemd --> /usr/lib/systemd/system/uwsgi.service
  1046. # The unit file starts uWSGI in emperor mode (/etc/uwsgi.ini), see
  1047. # - https://uwsgi-docs.readthedocs.io/en/latest/Emperor.html
  1048. uWSGI_APPS_AVAILABLE="${uWSGI_SETUP}/apps-available"
  1049. uWSGI_APPS_ENABLED="${uWSGI_SETUP}.d"
  1050. uWSGI_PACKAGES="uwsgi"
  1051. uWSGI_USER="uwsgi"
  1052. uWSGI_GROUP="uwsgi"
  1053. ;;
  1054. *)
  1055. err_msg "$DIST_ID-$DIST_VERS: uWSGI not yet implemented"
  1056. ;;
  1057. esac
  1058. }
  1059. uWSGI_distro_setup
  1060. install_uwsgi(){
  1061. info_msg "installing uwsgi ..."
  1062. pkg_install "$uWSGI_PACKAGES"
  1063. case $DIST_ID-$DIST_VERS in
  1064. fedora-*|centos-7)
  1065. # enable & start should be called once at uWSGI installation time
  1066. systemctl enable uwsgi
  1067. systemctl restart uwsgi
  1068. ;;
  1069. esac
  1070. }
  1071. uWSGI_restart() {
  1072. # usage: uWSGI_restart() <myapp.ini>
  1073. local CONF="$1"
  1074. [[ -z $CONF ]] && die_caller 42 "missing argument <myapp.ini>"
  1075. info_msg "restart uWSGI service"
  1076. case $DIST_ID-$DIST_VERS in
  1077. ubuntu-*|debian-*)
  1078. # the 'service' method seems broken in that way, that it (re-)starts
  1079. # the whole uwsgi process.
  1080. service uwsgi restart "${CONF%.*}"
  1081. ;;
  1082. arch-*)
  1083. # restart systemd template instance
  1084. if uWSGI_app_available "${CONF}"; then
  1085. systemctl restart "uwsgi@${CONF%.*}"
  1086. else
  1087. info_msg "[uWSGI:systemd-template] ${CONF} not installed (no need to restart)"
  1088. fi
  1089. ;;
  1090. fedora-*|centos-7)
  1091. # in emperor mode, just touch the file to restart
  1092. if uWSGI_app_enabled "${CONF}"; then
  1093. touch "${uWSGI_APPS_ENABLED}/${CONF}"
  1094. # it seems, there is a polling time in between touch and restart
  1095. # of the service.
  1096. sleep 3
  1097. else
  1098. info_msg "[uWSGI:emperor] ${CONF} not installed (no need to restart)"
  1099. fi
  1100. ;;
  1101. *)
  1102. err_msg "$DIST_ID-$DIST_VERS: uWSGI not yet implemented"
  1103. return 42
  1104. ;;
  1105. esac
  1106. }
  1107. uWSGI_prepare_app() {
  1108. # usage: uWSGI_prepare_app <myapp.ini>
  1109. [[ -z $1 ]] && die_caller 42 "missing argument <myapp.ini>"
  1110. local APP="${1%.*}"
  1111. case $DIST_ID-$DIST_VERS in
  1112. fedora-*|centos-7)
  1113. # in emperor mode, the uwsgi user is the owner of the sockets
  1114. info_msg "prepare (uwsgi:uwsgi) /run/uwsgi/app/${APP}"
  1115. mkdir -p "/run/uwsgi/app/${APP}"
  1116. chown -R "uwsgi:uwsgi" "/run/uwsgi/app/${APP}"
  1117. ;;
  1118. *)
  1119. info_msg "prepare (${SERVICE_USER}:${SERVICE_GROUP}) /run/uwsgi/app/${APP}"
  1120. mkdir -p "/run/uwsgi/app/${APP}"
  1121. chown -R "${SERVICE_USER}:${SERVICE_GROUP}" "/run/uwsgi/app/${APP}"
  1122. ;;
  1123. esac
  1124. }
  1125. uWSGI_app_available() {
  1126. # usage: uWSGI_app_available <myapp.ini>
  1127. local CONF="$1"
  1128. [[ -z $CONF ]] && die_caller 42 "missing argument <myapp.ini>"
  1129. [[ -f "${uWSGI_APPS_AVAILABLE}/${CONF}" ]]
  1130. }
  1131. uWSGI_install_app() {
  1132. # usage: uWSGI_install_app [<template option> ...] <myapp.ini>
  1133. #
  1134. # <template option>: see install_template
  1135. local pos_args=("$0")
  1136. for i in "$@"; do
  1137. case $i in
  1138. -*) template_opts+=("$i");;
  1139. *) pos_args+=("$i");;
  1140. esac
  1141. done
  1142. uWSGI_prepare_app "${pos_args[1]}"
  1143. mkdir -p "${uWSGI_APPS_AVAILABLE}"
  1144. install_template "${template_opts[@]}" \
  1145. "${uWSGI_APPS_AVAILABLE}/${pos_args[1]}" \
  1146. root root 644
  1147. uWSGI_enable_app "${pos_args[1]}"
  1148. uWSGI_restart "${pos_args[1]}"
  1149. info_msg "uWSGI app: ${pos_args[1]} is installed"
  1150. }
  1151. uWSGI_remove_app() {
  1152. # usage: uWSGI_remove_app <myapp.ini>
  1153. local CONF="$1"
  1154. [[ -z $CONF ]] && die_caller 42 "missing argument <myapp.ini>"
  1155. info_msg "remove uWSGI app: ${CONF}"
  1156. uWSGI_disable_app "${CONF}"
  1157. uWSGI_restart "${CONF}"
  1158. rm -f "${uWSGI_APPS_AVAILABLE}/${CONF}"
  1159. }
  1160. uWSGI_app_enabled() {
  1161. # usage: uWSGI_app_enabled <myapp.ini>
  1162. local exit_val=0
  1163. local CONF="$1"
  1164. [[ -z $CONF ]] && die_caller 42 "missing argument <myapp.ini>"
  1165. case $DIST_ID-$DIST_VERS in
  1166. ubuntu-*|debian-*)
  1167. [[ -f "${uWSGI_APPS_ENABLED}/${CONF}" ]]
  1168. exit_val=$?
  1169. ;;
  1170. arch-*)
  1171. systemctl -q is-enabled "uwsgi@${CONF%.*}"
  1172. exit_val=$?
  1173. ;;
  1174. fedora-*|centos-7)
  1175. [[ -f "${uWSGI_APPS_ENABLED}/${CONF}" ]]
  1176. exit_val=$?
  1177. ;;
  1178. *)
  1179. # FIXME
  1180. err_msg "$DIST_ID-$DIST_VERS: uWSGI not yet implemented"
  1181. exit_val=1
  1182. ;;
  1183. esac
  1184. return $exit_val
  1185. }
  1186. # shellcheck disable=SC2164
  1187. uWSGI_enable_app() {
  1188. # usage: uWSGI_enable_app <myapp.ini>
  1189. local CONF="$1"
  1190. [[ -z $CONF ]] && die_caller 42 "missing argument <myapp.ini>"
  1191. case $DIST_ID-$DIST_VERS in
  1192. ubuntu-*|debian-*)
  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. info_msg "enabled uWSGI app: ${CONF} (restart required)"
  1197. ;;
  1198. arch-*)
  1199. mkdir -p "${uWSGI_APPS_ENABLED}"
  1200. rm -f "${uWSGI_APPS_ENABLED}/${CONF}"
  1201. ln -s "${uWSGI_APPS_AVAILABLE}/${CONF}" "${uWSGI_APPS_ENABLED}/${CONF}"
  1202. systemctl enable "uwsgi@${CONF%.*}"
  1203. info_msg "enabled uWSGI app: ${CONF} (restart required)"
  1204. ;;
  1205. fedora-*|centos-7)
  1206. mkdir -p "${uWSGI_APPS_ENABLED}"
  1207. rm -f "${uWSGI_APPS_ENABLED}/${CONF}"
  1208. ln -s "${uWSGI_APPS_AVAILABLE}/${CONF}" "${uWSGI_APPS_ENABLED}/${CONF}"
  1209. chown "${uWSGI_USER}:${uWSGI_GROUP}" "${uWSGI_APPS_ENABLED}/${CONF}"
  1210. info_msg "enabled uWSGI app: ${CONF}"
  1211. ;;
  1212. *)
  1213. # FIXME
  1214. err_msg "$DIST_ID-$DIST_VERS: uWSGI not yet implemented"
  1215. ;;
  1216. esac
  1217. }
  1218. uWSGI_disable_app() {
  1219. # usage: uWSGI_disable_app <myapp.ini>
  1220. local CONF="$1"
  1221. [[ -z $CONF ]] && die_caller 42 "missing argument <myapp.ini>"
  1222. case $DIST_ID-$DIST_VERS in
  1223. ubuntu-*|debian-*)
  1224. service uwsgi stop "${CONF%.*}"
  1225. rm -f "${uWSGI_APPS_ENABLED}/${CONF}"
  1226. info_msg "disabled uWSGI app: ${CONF} (restart uWSGI required)"
  1227. ;;
  1228. arch-*)
  1229. systemctl stop "uwsgi@${CONF%.*}"
  1230. systemctl disable "uwsgi@${CONF%.*}"
  1231. rm -f "${uWSGI_APPS_ENABLED}/${CONF}"
  1232. ;;
  1233. fedora-*|centos-7)
  1234. # in emperor mode, just remove the app.ini file
  1235. rm -f "${uWSGI_APPS_ENABLED}/${CONF}"
  1236. ;;
  1237. *)
  1238. # FIXME
  1239. err_msg "$DIST_ID-$DIST_VERS: uWSGI not yet implemented"
  1240. ;;
  1241. esac
  1242. }
  1243. # distro's package manager
  1244. # ------------------------
  1245. _apt_pkg_info_is_updated=0
  1246. pkg_install() {
  1247. # usage: TITEL='install foobar' pkg_install foopkg barpkg
  1248. rst_title "${TITLE:-installation of packages}" section
  1249. echo -e "\npackage(s)::\n"
  1250. # shellcheck disable=SC2068
  1251. echo " " $@ | $FMT
  1252. if ! ask_yn "Should packages be installed?" Yn 30; then
  1253. return 42
  1254. fi
  1255. case $DIST_ID in
  1256. ubuntu|debian)
  1257. if [[ $_apt_pkg_info_is_updated == 0 ]]; then
  1258. export _apt_pkg_info_is_updated=1
  1259. apt update
  1260. fi
  1261. # shellcheck disable=SC2068
  1262. apt-get install -m -y $@
  1263. ;;
  1264. arch)
  1265. # shellcheck disable=SC2068
  1266. pacman --noprogressbar -Sy --noconfirm $@
  1267. ;;
  1268. fedora)
  1269. # shellcheck disable=SC2068
  1270. dnf install -y $@
  1271. ;;
  1272. centos)
  1273. # shellcheck disable=SC2068
  1274. yum install -y $@
  1275. ;;
  1276. esac
  1277. }
  1278. pkg_remove() {
  1279. # usage: TITEL='remove foobar' pkg_remove foopkg barpkg
  1280. rst_title "${TITLE:-remove packages}" section
  1281. echo -e "\npackage(s)::\n"
  1282. # shellcheck disable=SC2068
  1283. echo " " $@ | $FMT
  1284. if ! ask_yn "Should packages be removed (purge)?" Yn 30; then
  1285. return 42
  1286. fi
  1287. case $DIST_ID in
  1288. ubuntu|debian)
  1289. # shellcheck disable=SC2068
  1290. apt-get purge --autoremove --ignore-missing -y $@
  1291. ;;
  1292. arch)
  1293. # shellcheck disable=SC2068
  1294. pacman --noprogressbar -R --noconfirm $@
  1295. ;;
  1296. fedora)
  1297. # shellcheck disable=SC2068
  1298. dnf remove -y $@
  1299. ;;
  1300. centos)
  1301. # shellcheck disable=SC2068
  1302. yum remove -y $@
  1303. ;;
  1304. esac
  1305. }
  1306. pkg_is_installed() {
  1307. # usage: pkg_is_install foopkg || pkg_install foopkg
  1308. case $DIST_ID in
  1309. ubuntu|debian)
  1310. dpkg -l "$1" &> /dev/null
  1311. return $?
  1312. ;;
  1313. arch)
  1314. pacman -Qsq "$1" &> /dev/null
  1315. return $?
  1316. ;;
  1317. fedora)
  1318. dnf list -q --installed "$1" &> /dev/null
  1319. return $?
  1320. ;;
  1321. centos)
  1322. yum list -q --installed "$1" &> /dev/null
  1323. return $?
  1324. ;;
  1325. esac
  1326. }
  1327. # git tooling
  1328. # -----------
  1329. # shellcheck disable=SC2164
  1330. git_clone() {
  1331. # usage:
  1332. #
  1333. # git_clone <url> <name> [<branch> [<user>]]
  1334. # git_clone <url> <path> [<branch> [<user>]]
  1335. #
  1336. # First form uses $CACHE/<name> as destination folder, second form clones
  1337. # into <path>. If repository is allready cloned, pull from <branch> and
  1338. # update working tree (if needed, the caller has to stash local changes).
  1339. #
  1340. # git clone https://github.com/searxng/searxng searx-src origin/master searxlogin
  1341. #
  1342. local url="$1"
  1343. local dest="$2"
  1344. local branch="$3"
  1345. local user="$4"
  1346. local bash_cmd="bash"
  1347. local remote="origin"
  1348. if [[ ! "${dest:0:1}" = "/" ]]; then
  1349. dest="$CACHE/$dest"
  1350. fi
  1351. [[ -z $branch ]] && branch=master
  1352. [[ -z $user ]] && [[ -n "${SUDO_USER}" ]] && user="${SUDO_USER}"
  1353. [[ -n $user ]] && bash_cmd="sudo -H -u $user -i"
  1354. if [[ -d "${dest}" ]] ; then
  1355. info_msg "already cloned: $dest"
  1356. tee_stderr 0.1 <<EOF | $bash_cmd 2>&1 | prefix_stdout " ${_Yellow}|$user|${_creset} "
  1357. cd "${dest}"
  1358. git checkout -m -B "$branch" --track "$remote/$branch"
  1359. git pull --all
  1360. EOF
  1361. else
  1362. info_msg "clone into: $dest"
  1363. tee_stderr 0.1 <<EOF | $bash_cmd 2>&1 | prefix_stdout " ${_Yellow}|$user|${_creset} "
  1364. mkdir -p "$(dirname "$dest")"
  1365. cd "$(dirname "$dest")"
  1366. git clone --branch "$branch" --origin "$remote" "$url" "$(basename "$dest")"
  1367. EOF
  1368. fi
  1369. }
  1370. # containers
  1371. # ----------
  1372. in_container() {
  1373. # Test if shell runs in a container.
  1374. #
  1375. # usage: in_container && echo "process running inside a LXC container"
  1376. # in_container || echo "process is not running inside a LXC container"
  1377. #
  1378. # sudo_or_exit
  1379. # hint: Reads init process environment, therefore root access is required!
  1380. # to be safe, take a look at the environment of process 1 (/sbin/init)
  1381. # grep -qa 'container=lxc' /proc/1/environ
  1382. # see lxc_init_container_env
  1383. [[ -f /.lxcenv ]]
  1384. }
  1385. LXC_ENV_FOLDER=
  1386. if in_container; then
  1387. # shellcheck disable=SC2034
  1388. LXC_ENV_FOLDER="lxc-env/$(hostname)/"
  1389. PY_ENV="${LXC_ENV_FOLDER}${PY_ENV}"
  1390. PY_ENV_BIN="${LXC_ENV_FOLDER}${PY_ENV_BIN}"
  1391. PYDIST="${LXC_ENV_FOLDER}${PYDIST}"
  1392. PYBUILD="${LXC_ENV_FOLDER}${PYBUILD}"
  1393. DOCS_DIST="${LXC_ENV_FOLDER}${DOCS_DIST}"
  1394. DOCS_BUILD="${LXC_ENV_FOLDER}${DOCS_BUILD}"
  1395. fi
  1396. lxc_init_container_env() {
  1397. # usage: lxc_init_container_env <name>
  1398. # Create a /.lxcenv file in the root folder. Call this once after the
  1399. # container is inital started and before installing any boilerplate stuff.
  1400. info_msg "create /.lxcenv in container $1"
  1401. cat <<EOF | lxc exec "${1}" -- bash | prefix_stdout "[${_BBlue}${1}${_creset}] "
  1402. touch "/.lxcenv"
  1403. ls -l "/.lxcenv"
  1404. EOF
  1405. }
  1406. # apt packages
  1407. LXC_BASE_PACKAGES_debian="bash git build-essential python3 python3-venv"
  1408. # pacman packages
  1409. LXC_BASE_PACKAGES_arch="bash git base-devel python"
  1410. # dnf packages
  1411. LXC_BASE_PACKAGES_fedora="bash git @development-tools python"
  1412. # yum packages
  1413. LXC_BASE_PACKAGES_centos="bash git python3"
  1414. case $DIST_ID in
  1415. ubuntu|debian) LXC_BASE_PACKAGES="${LXC_BASE_PACKAGES_debian}" ;;
  1416. arch) LXC_BASE_PACKAGES="${LXC_BASE_PACKAGES_arch}" ;;
  1417. fedora) LXC_BASE_PACKAGES="${LXC_BASE_PACKAGES_fedora}" ;;
  1418. centos) LXC_BASE_PACKAGES="${LXC_BASE_PACKAGES_centos}" ;;
  1419. *) err_msg "$DIST_ID-$DIST_VERS: pkg_install LXC_BASE_PACKAGES not yet implemented" ;;
  1420. esac
  1421. lxc_install_base_packages() {
  1422. info_msg "install LXC_BASE_PACKAGES in container $1"
  1423. case $DIST_ID in
  1424. centos) yum groupinstall "Development Tools" -y ;;
  1425. esac
  1426. pkg_install "${LXC_BASE_PACKAGES}"
  1427. }
  1428. lxc_image_copy() {
  1429. # usage: lxc_image_copy <remote image> <local image>
  1430. #
  1431. # lxc_image_copy "images:ubuntu/20.04" "ubu2004"
  1432. if lxc_image_exists "local:${LXC_SUITE[i+1]}"; then
  1433. info_msg "image ${LXC_SUITE[i]} already copied --> ${LXC_SUITE[i+1]}"
  1434. else
  1435. info_msg "copy image locally ${LXC_SUITE[i]} --> ${LXC_SUITE[i+1]}"
  1436. lxc image copy "${LXC_SUITE[i]}" local: \
  1437. --alias "${LXC_SUITE[i+1]}" | prefix_stdout
  1438. fi
  1439. }
  1440. lxc_init_container() {
  1441. # usage: lxc_init_container <image name> <container name>
  1442. local image_name="$1"
  1443. local container_name="$2"
  1444. if lxc info "${container_name}" &>/dev/null; then
  1445. info_msg "container '${container_name}' already exists"
  1446. else
  1447. info_msg "create container instance: ${container_name}"
  1448. lxc init "local:${image_name}" "${container_name}"
  1449. fi
  1450. }
  1451. lxc_exists(){
  1452. # usage: lxc_exists <name> || echo "container <name> does not exists"
  1453. lxc info "$1" &>/dev/null
  1454. }
  1455. lxc_image_exists(){
  1456. # usage: lxc_image_exists <alias> || echo "image <alias> does locally not exists"
  1457. lxc image info "local:$1" &>/dev/null
  1458. }
  1459. lxc_delete_container() {
  1460. # usage: lxc_delete_container <container-name>
  1461. if lxc info "$1" &>/dev/null; then
  1462. info_msg "stop & delete instance ${_BBlue}${1}${_creset}"
  1463. lxc stop "$1" &>/dev/null
  1464. lxc delete "$1" | prefix_stdout
  1465. else
  1466. warn_msg "instance '$1' does not exist / can't delete :o"
  1467. fi
  1468. }
  1469. lxc_delete_local_image() {
  1470. # usage: lxc_delete_local_image <container-name>
  1471. info_msg "delete image 'local:$i'"
  1472. lxc image delete "local:$i"
  1473. }
  1474. # IP
  1475. # --
  1476. global_IPs(){
  1477. # usage: global_IPS
  1478. #
  1479. # print list of host's SCOPE global addresses and adapters e.g::
  1480. #
  1481. # $ global_IPs
  1482. # enp4s0|192.168.1.127
  1483. # lxdbr0|10.246.86.1
  1484. # lxdbr0|fd42:8c58:2cd:b73f::1
  1485. ip -o addr show | sed -nr 's/[0-9]*:\s*([a-z0-9]*).*inet[6]?\s*([a-z0-9.:]*).*scope global.*/\1|\2/p'
  1486. }
  1487. primary_ip() {
  1488. case $DIST_ID in
  1489. arch)
  1490. ip -o addr show \
  1491. | sed -nr 's/[0-9]*:\s*([a-z0-9]*).*inet[6]?\s*([a-z0-9.:]*).*scope global.*/\2/p' \
  1492. | head -n 1
  1493. ;;
  1494. *) hostname -I | cut -d' ' -f1 ;;
  1495. esac
  1496. }
  1497. # URL
  1498. # ---
  1499. url_replace_hostname(){
  1500. # usage: url_replace_hostname <url> <new hostname>
  1501. # to replace hostname by primary IP::
  1502. #
  1503. # url_replace_hostname http://searx-ubu1604/morty $(primary_ip)
  1504. # http://10.246.86.250/morty
  1505. # shellcheck disable=SC2001
  1506. echo "$1" | sed "s|\(http[s]*://\)[^/]*\(.*\)|\1$2\2|"
  1507. }