lib.sh 47 KB

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