lib.sh 49 KB

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