lib.sh 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838
  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. # system accounts
  676. # ---------------
  677. service_account_is_available() {
  678. # usage: service_account_is_available "$SERVICE_USER" && echo "OK"
  679. sudo -i -u "$1" echo \$HOME &>/dev/null
  680. }
  681. drop_service_account() {
  682. # usage: drop_service_account "${SERVICE_USER}"
  683. rst_title "Drop ${1} HOME" section
  684. if ask_yn "Do you really want to drop ${1} home folder?"; then
  685. userdel -r -f "${1}" 2>&1 | prefix_stdout
  686. else
  687. rst_para "Leave HOME folder $(du -sh "${1}") unchanged."
  688. fi
  689. }
  690. interactive_shell(){
  691. # usage: interactive_shell "${SERVICE_USER}"
  692. echo -e "// exit with [${_BCyan}CTRL-D${_creset}]"
  693. sudo -H -u "${1}" -i
  694. }
  695. # systemd
  696. # -------
  697. SYSTEMD_UNITS="${SYSTEMD_UNITS:-/lib/systemd/system}"
  698. systemd_install_service() {
  699. # usage: systemd_install_service "${SERVICE_NAME}" "${SERVICE_SYSTEMD_UNIT}"
  700. rst_title "Install System-D Unit ${1}" section
  701. echo
  702. install_template "${2}" root root 644
  703. wait_key
  704. systemd_activate_service "${1}"
  705. }
  706. systemd_remove_service() {
  707. # usage: systemd_remove_service "${SERVICE_NAME}" "${SERVICE_SYSTEMD_UNIT}"
  708. if ! ask_yn "Do you really want to deinstall systemd unit ${1}?"; then
  709. return 42
  710. fi
  711. systemd_deactivate_service "${1}"
  712. rm "${2}" 2>&1 | prefix_stdout
  713. }
  714. systemd_activate_service() {
  715. # usage: systemd_activate_service "${SERVICE_NAME}"
  716. rst_title "Activate ${1} (service)" section
  717. echo
  718. tee_stderr <<EOF | bash 2>&1
  719. systemctl enable ${1}.service
  720. systemctl restart ${1}.service
  721. EOF
  722. tee_stderr <<EOF | bash 2>&1
  723. systemctl status --no-pager ${1}.service
  724. EOF
  725. }
  726. systemd_deactivate_service() {
  727. # usage: systemd_deactivate_service "${SERVICE_NAME}"
  728. rst_title "De-Activate ${1} (service)" section
  729. echo
  730. tee_stderr <<EOF | bash 2>&1 | prefix_stdout
  731. systemctl stop ${1}.service
  732. systemctl disable ${1}.service
  733. EOF
  734. }
  735. systemd_restart_service() {
  736. # usage: systemd_restart_service "${SERVICE_NAME}"
  737. rst_title "Restart ${1} (service)" section
  738. echo
  739. tee_stderr <<EOF | bash 2>&1
  740. systemctl restart ${1}.service
  741. EOF
  742. tee_stderr <<EOF | bash 2>&1
  743. systemctl status --no-pager ${1}.service
  744. EOF
  745. }
  746. # nginx
  747. # -----
  748. nginx_distro_setup() {
  749. # shellcheck disable=SC2034
  750. NGINX_DEFAULT_SERVER=/etc/nginx/nginx.conf
  751. # Including *location* directives from a dedicated config-folder into the
  752. # server directive is, what fedora and centos (already) does.
  753. NGINX_APPS_ENABLED="/etc/nginx/default.d"
  754. # We add a apps-available folder and linking configurations into the
  755. # NGINX_APPS_ENABLED folder. See also nginx_include_apps_enabled().
  756. NGINX_APPS_AVAILABLE="/etc/nginx/default.apps-available"
  757. case $DIST_ID-$DIST_VERS in
  758. ubuntu-*|debian-*)
  759. NGINX_PACKAGES="nginx"
  760. NGINX_DEFAULT_SERVER=/etc/nginx/sites-available/default
  761. ;;
  762. arch-*)
  763. NGINX_PACKAGES="nginx-mainline"
  764. ;;
  765. fedora-*|centos-7)
  766. NGINX_PACKAGES="nginx"
  767. ;;
  768. *)
  769. err_msg "$DIST_ID-$DIST_VERS: nginx not yet implemented"
  770. ;;
  771. esac
  772. }
  773. nginx_distro_setup
  774. install_nginx(){
  775. info_msg "installing nginx ..."
  776. pkg_install "${NGINX_PACKAGES}"
  777. case $DIST_ID-$DIST_VERS in
  778. arch-*|fedora-*|centos-7)
  779. systemctl enable nginx
  780. systemctl start nginx
  781. ;;
  782. esac
  783. }
  784. nginx_is_installed() {
  785. command -v nginx &>/dev/null
  786. }
  787. nginx_reload() {
  788. info_msg "reload nginx .."
  789. echo
  790. if ! nginx -t; then
  791. err_msg "testing nginx configuration failed"
  792. return 42
  793. fi
  794. systemctl restart nginx
  795. }
  796. nginx_install_app() {
  797. # usage: nginx_install_app [<template option> ...] <myapp.conf>
  798. #
  799. # <template option>: see install_template
  800. local template_opts=()
  801. local pos_args=("$0")
  802. for i in "$@"; do
  803. case $i in
  804. -*) template_opts+=("$i");;
  805. *) pos_args+=("$i");;
  806. esac
  807. done
  808. nginx_include_apps_enabled "${NGINX_DEFAULT_SERVER}"
  809. install_template "${template_opts[@]}" \
  810. "${NGINX_APPS_AVAILABLE}/${pos_args[1]}" \
  811. root root 644
  812. nginx_enable_app "${pos_args[1]}"
  813. info_msg "installed nginx app: ${pos_args[1]}"
  814. }
  815. nginx_include_apps_enabled() {
  816. # Add the *NGINX_APPS_ENABLED* infrastruture to a nginx server block. Such
  817. # infrastruture is already known from fedora and centos, including apps (location
  818. # directives) from the /etc/nginx/default.d folder into the *default* nginx
  819. # server.
  820. # usage: nginx_include_apps_enabled <config-file>
  821. #
  822. # config-file: Config file with server directive in.
  823. [[ -z $1 ]] && die_caller 42 "missing argument <config-file>"
  824. local server_conf="$1"
  825. # include /etc/nginx/default.d/*.conf;
  826. local include_directive="include ${NGINX_APPS_ENABLED}/*.conf;"
  827. local include_directive_re="^\s*include ${NGINX_APPS_ENABLED}/\*\.conf;"
  828. info_msg "checking existence: '${include_directive}' in file ${server_conf}"
  829. if grep "${include_directive_re}" "${server_conf}"; then
  830. info_msg "OK, already exists."
  831. return
  832. fi
  833. info_msg "add missing directive: '${include_directive}'"
  834. cp "${server_conf}" "${server_conf}.bak"
  835. (
  836. local line
  837. local stage=0
  838. while IFS= read -r line
  839. do
  840. echo "$line"
  841. if [[ $stage = 0 ]]; then
  842. if [[ $line =~ ^[[:space:]]*server*[[:space:]]*\{ ]]; then
  843. stage=1
  844. fi
  845. fi
  846. if [[ $stage = 1 ]]; then
  847. echo " # Load configuration files for the default server block."
  848. echo " $include_directive"
  849. echo ""
  850. stage=2
  851. fi
  852. done < "${server_conf}.bak"
  853. ) > "${server_conf}"
  854. }
  855. nginx_remove_app() {
  856. # usage: nginx_remove_app <myapp.conf>
  857. info_msg "remove nginx app: $1"
  858. nginx_dissable_app "$1"
  859. rm -f "${NGINX_APPS_AVAILABLE}/$1"
  860. }
  861. nginx_enable_app() {
  862. # usage: nginx_enable_app <myapp.conf>
  863. local CONF="$1"
  864. info_msg "enable nginx app: ${CONF}"
  865. mkdir -p "${NGINX_APPS_ENABLED}"
  866. rm -f "${NGINX_APPS_ENABLED}/${CONF}"
  867. ln -s "${NGINX_APPS_AVAILABLE}/${CONF}" "${NGINX_APPS_ENABLED}/${CONF}"
  868. nginx_reload
  869. }
  870. nginx_dissable_app() {
  871. # usage: nginx_disable_app <myapp.conf>
  872. local CONF="$1"
  873. info_msg "disable nginx app: ${CONF}"
  874. rm -f "${NGINX_APPS_ENABLED}/${CONF}"
  875. nginx_reload
  876. }
  877. # Apache
  878. # ------
  879. apache_distro_setup() {
  880. # shellcheck disable=SC2034
  881. case $DIST_ID-$DIST_VERS in
  882. ubuntu-*|debian-*)
  883. # debian uses the /etc/apache2 path, while other distros use
  884. # the apache default at /etc/httpd
  885. APACHE_SITES_AVAILABLE="/etc/apache2/sites-available"
  886. APACHE_SITES_ENABLED="/etc/apache2/sites-enabled"
  887. APACHE_MODULES="/usr/lib/apache2/modules"
  888. APACHE_PACKAGES="apache2"
  889. ;;
  890. arch-*)
  891. APACHE_SITES_AVAILABLE="/etc/httpd/sites-available"
  892. APACHE_SITES_ENABLED="/etc/httpd/sites-enabled"
  893. APACHE_MODULES="modules"
  894. APACHE_PACKAGES="apache"
  895. ;;
  896. fedora-*|centos-7)
  897. APACHE_SITES_AVAILABLE="/etc/httpd/sites-available"
  898. APACHE_SITES_ENABLED="/etc/httpd/sites-enabled"
  899. APACHE_MODULES="modules"
  900. APACHE_PACKAGES="httpd"
  901. ;;
  902. *)
  903. err_msg "$DIST_ID-$DIST_VERS: apache not yet implemented"
  904. ;;
  905. esac
  906. }
  907. apache_distro_setup
  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_dissable_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_dissable_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. uWSGI_USER=
  1008. uWSGI_GROUP=
  1009. # How distros manage uWSGI apps is very different. From uWSGI POV read:
  1010. # - https://uwsgi-docs.readthedocs.io/en/latest/Management.html
  1011. uWSGI_distro_setup() {
  1012. case $DIST_ID-$DIST_VERS in
  1013. ubuntu-*|debian-*)
  1014. # init.d --> /usr/share/doc/uwsgi/README.Debian.gz
  1015. # For uWSGI debian uses the LSB init process, this might be changed
  1016. # one day, see https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=833067
  1017. uWSGI_APPS_AVAILABLE="${uWSGI_SETUP}/apps-available"
  1018. uWSGI_APPS_ENABLED="${uWSGI_SETUP}/apps-enabled"
  1019. uWSGI_PACKAGES="uwsgi"
  1020. ;;
  1021. arch-*)
  1022. # systemd --> /usr/lib/systemd/system/uwsgi@.service
  1023. # For uWSGI archlinux uses systemd template units, see
  1024. # - http://0pointer.de/blog/projects/instances.html
  1025. # - https://uwsgi-docs.readthedocs.io/en/latest/Systemd.html#one-service-per-app-in-systemd
  1026. uWSGI_APPS_AVAILABLE="${uWSGI_SETUP}/apps-archlinux"
  1027. uWSGI_APPS_ENABLED="${uWSGI_SETUP}"
  1028. uWSGI_PACKAGES="uwsgi"
  1029. ;;
  1030. fedora-*|centos-7)
  1031. # systemd --> /usr/lib/systemd/system/uwsgi.service
  1032. # The unit file starts uWSGI in emperor mode (/etc/uwsgi.ini), see
  1033. # - https://uwsgi-docs.readthedocs.io/en/latest/Emperor.html
  1034. uWSGI_APPS_AVAILABLE="${uWSGI_SETUP}/apps-available"
  1035. uWSGI_APPS_ENABLED="${uWSGI_SETUP}.d"
  1036. uWSGI_PACKAGES="uwsgi"
  1037. uWSGI_USER="uwsgi"
  1038. uWSGI_GROUP="uwsgi"
  1039. ;;
  1040. *)
  1041. err_msg "$DIST_ID-$DIST_VERS: uWSGI not yet implemented"
  1042. ;;
  1043. esac
  1044. }
  1045. uWSGI_distro_setup
  1046. install_uwsgi(){
  1047. info_msg "installing uwsgi ..."
  1048. pkg_install "$uWSGI_PACKAGES"
  1049. case $DIST_ID-$DIST_VERS in
  1050. fedora-*|centos-7)
  1051. # enable & start should be called once at uWSGI installation time
  1052. systemctl enable uwsgi
  1053. systemctl restart uwsgi
  1054. ;;
  1055. esac
  1056. }
  1057. uWSGI_restart() {
  1058. # usage: uWSGI_restart() <myapp.ini>
  1059. local CONF="$1"
  1060. [[ -z $CONF ]] && die_caller 42 "missing argument <myapp.ini>"
  1061. info_msg "restart uWSGI service"
  1062. case $DIST_ID-$DIST_VERS in
  1063. ubuntu-*|debian-*)
  1064. # the 'service' method seems broken in that way, that it (re-)starts
  1065. # the whole uwsgi process.
  1066. service uwsgi restart "${CONF%.*}"
  1067. ;;
  1068. arch-*)
  1069. # restart systemd template instance
  1070. if uWSGI_app_available "${CONF}"; then
  1071. systemctl restart "uwsgi@${CONF%.*}"
  1072. else
  1073. info_msg "[uWSGI:systemd-template] ${CONF} not installed (no need to restart)"
  1074. fi
  1075. ;;
  1076. fedora-*|centos-7)
  1077. # in emperor mode, just touch the file to restart
  1078. if uWSGI_app_enabled "${CONF}"; then
  1079. touch "${uWSGI_APPS_ENABLED}/${CONF}"
  1080. # it seems, there is a polling time in between touch and restart
  1081. # of the service.
  1082. sleep 3
  1083. else
  1084. info_msg "[uWSGI:emperor] ${CONF} not installed (no need to restart)"
  1085. fi
  1086. ;;
  1087. *)
  1088. err_msg "$DIST_ID-$DIST_VERS: uWSGI not yet implemented"
  1089. return 42
  1090. ;;
  1091. esac
  1092. }
  1093. uWSGI_prepare_app() {
  1094. # usage: uWSGI_prepare_app <myapp.ini>
  1095. [[ -z $1 ]] && die_caller 42 "missing argument <myapp.ini>"
  1096. local APP="${1%.*}"
  1097. case $DIST_ID-$DIST_VERS in
  1098. fedora-*|centos-7)
  1099. # in emperor mode, the uwsgi user is the owner of the sockets
  1100. info_msg "prepare (uwsgi:uwsgi) /run/uwsgi/app/${APP}"
  1101. mkdir -p "/run/uwsgi/app/${APP}"
  1102. chown -R "uwsgi:uwsgi" "/run/uwsgi/app/${APP}"
  1103. ;;
  1104. *)
  1105. info_msg "prepare (${SERVICE_USER}:${SERVICE_GROUP}) /run/uwsgi/app/${APP}"
  1106. mkdir -p "/run/uwsgi/app/${APP}"
  1107. chown -R "${SERVICE_USER}:${SERVICE_GROUP}" "/run/uwsgi/app/${APP}"
  1108. ;;
  1109. esac
  1110. }
  1111. uWSGI_app_available() {
  1112. # usage: uWSGI_app_available <myapp.ini>
  1113. local CONF="$1"
  1114. [[ -z $CONF ]] && die_caller 42 "missing argument <myapp.ini>"
  1115. [[ -f "${uWSGI_APPS_AVAILABLE}/${CONF}" ]]
  1116. }
  1117. uWSGI_install_app() {
  1118. # usage: uWSGI_install_app [<template option> ...] <myapp.ini>
  1119. #
  1120. # <template option>: see install_template
  1121. local pos_args=("$0")
  1122. for i in "$@"; do
  1123. case $i in
  1124. -*) template_opts+=("$i");;
  1125. *) pos_args+=("$i");;
  1126. esac
  1127. done
  1128. uWSGI_prepare_app "${pos_args[1]}"
  1129. mkdir -p "${uWSGI_APPS_AVAILABLE}"
  1130. install_template "${template_opts[@]}" \
  1131. "${uWSGI_APPS_AVAILABLE}/${pos_args[1]}" \
  1132. root root 644
  1133. uWSGI_enable_app "${pos_args[1]}"
  1134. uWSGI_restart "${pos_args[1]}"
  1135. info_msg "uWSGI app: ${pos_args[1]} is installed"
  1136. }
  1137. uWSGI_remove_app() {
  1138. # usage: uWSGI_remove_app <myapp.ini>
  1139. local CONF="$1"
  1140. [[ -z $CONF ]] && die_caller 42 "missing argument <myapp.ini>"
  1141. info_msg "remove uWSGI app: ${CONF}"
  1142. uWSGI_disable_app "${CONF}"
  1143. uWSGI_restart "${CONF}"
  1144. rm -f "${uWSGI_APPS_AVAILABLE}/${CONF}"
  1145. }
  1146. uWSGI_app_enabled() {
  1147. # usage: uWSGI_app_enabled <myapp.ini>
  1148. local exit_val=0
  1149. local CONF="$1"
  1150. [[ -z $CONF ]] && die_caller 42 "missing argument <myapp.ini>"
  1151. case $DIST_ID-$DIST_VERS in
  1152. ubuntu-*|debian-*)
  1153. [[ -f "${uWSGI_APPS_ENABLED}/${CONF}" ]]
  1154. exit_val=$?
  1155. ;;
  1156. arch-*)
  1157. systemctl -q is-enabled "uwsgi@${CONF%.*}"
  1158. exit_val=$?
  1159. ;;
  1160. fedora-*|centos-7)
  1161. [[ -f "${uWSGI_APPS_ENABLED}/${CONF}" ]]
  1162. exit_val=$?
  1163. ;;
  1164. *)
  1165. # FIXME
  1166. err_msg "$DIST_ID-$DIST_VERS: uWSGI not yet implemented"
  1167. exit_val=1
  1168. ;;
  1169. esac
  1170. return $exit_val
  1171. }
  1172. # shellcheck disable=SC2164
  1173. uWSGI_enable_app() {
  1174. # usage: uWSGI_enable_app <myapp.ini>
  1175. local CONF="$1"
  1176. [[ -z $CONF ]] && die_caller 42 "missing argument <myapp.ini>"
  1177. case $DIST_ID-$DIST_VERS in
  1178. ubuntu-*|debian-*)
  1179. mkdir -p "${uWSGI_APPS_ENABLED}"
  1180. rm -f "${uWSGI_APPS_ENABLED}/${CONF}"
  1181. ln -s "${uWSGI_APPS_AVAILABLE}/${CONF}" "${uWSGI_APPS_ENABLED}/${CONF}"
  1182. info_msg "enabled uWSGI app: ${CONF} (restart required)"
  1183. ;;
  1184. arch-*)
  1185. mkdir -p "${uWSGI_APPS_ENABLED}"
  1186. rm -f "${uWSGI_APPS_ENABLED}/${CONF}"
  1187. ln -s "${uWSGI_APPS_AVAILABLE}/${CONF}" "${uWSGI_APPS_ENABLED}/${CONF}"
  1188. systemctl enable "uwsgi@${CONF%.*}"
  1189. info_msg "enabled uWSGI app: ${CONF} (restart required)"
  1190. ;;
  1191. fedora-*|centos-7)
  1192. mkdir -p "${uWSGI_APPS_ENABLED}"
  1193. rm -f "${uWSGI_APPS_ENABLED}/${CONF}"
  1194. ln -s "${uWSGI_APPS_AVAILABLE}/${CONF}" "${uWSGI_APPS_ENABLED}/${CONF}"
  1195. chown "${uWSGI_USER}:${uWSGI_GROUP}" "${uWSGI_APPS_ENABLED}/${CONF}"
  1196. info_msg "enabled uWSGI app: ${CONF}"
  1197. ;;
  1198. *)
  1199. # FIXME
  1200. err_msg "$DIST_ID-$DIST_VERS: uWSGI not yet implemented"
  1201. ;;
  1202. esac
  1203. }
  1204. uWSGI_disable_app() {
  1205. # usage: uWSGI_disable_app <myapp.ini>
  1206. local CONF="$1"
  1207. [[ -z $CONF ]] && die_caller 42 "missing argument <myapp.ini>"
  1208. case $DIST_ID-$DIST_VERS in
  1209. ubuntu-*|debian-*)
  1210. service uwsgi stop "${CONF%.*}"
  1211. rm -f "${uWSGI_APPS_ENABLED}/${CONF}"
  1212. info_msg "disabled uWSGI app: ${CONF} (restart uWSGI required)"
  1213. ;;
  1214. arch-*)
  1215. systemctl stop "uwsgi@${CONF%.*}"
  1216. systemctl disable "uwsgi@${CONF%.*}"
  1217. rm -f "${uWSGI_APPS_ENABLED}/${CONF}"
  1218. ;;
  1219. fedora-*|centos-7)
  1220. # in emperor mode, just remove the app.ini file
  1221. rm -f "${uWSGI_APPS_ENABLED}/${CONF}"
  1222. ;;
  1223. *)
  1224. # FIXME
  1225. err_msg "$DIST_ID-$DIST_VERS: uWSGI not yet implemented"
  1226. ;;
  1227. esac
  1228. }
  1229. # distro's package manager
  1230. # ------------------------
  1231. _apt_pkg_info_is_updated=0
  1232. pkg_install() {
  1233. # usage: TITEL='install foobar' pkg_install foopkg barpkg
  1234. rst_title "${TITLE:-installation of packages}" section
  1235. echo -e "\npackage(s)::\n"
  1236. # shellcheck disable=SC2068
  1237. echo " " $@ | $FMT
  1238. if ! ask_yn "Should packages be installed?" Yn 30; then
  1239. return 42
  1240. fi
  1241. case $DIST_ID in
  1242. ubuntu|debian)
  1243. if [[ $_apt_pkg_info_is_updated == 0 ]]; then
  1244. export _apt_pkg_info_is_updated=1
  1245. apt update
  1246. fi
  1247. # shellcheck disable=SC2068
  1248. apt-get install -m -y $@
  1249. ;;
  1250. arch)
  1251. # shellcheck disable=SC2068
  1252. pacman --noprogressbar -Sy --noconfirm --needed $@
  1253. ;;
  1254. fedora)
  1255. # shellcheck disable=SC2068
  1256. dnf install -y $@
  1257. ;;
  1258. centos)
  1259. # shellcheck disable=SC2068
  1260. yum install -y $@
  1261. ;;
  1262. esac
  1263. }
  1264. pkg_remove() {
  1265. # usage: TITEL='remove foobar' pkg_remove foopkg barpkg
  1266. rst_title "${TITLE:-remove packages}" section
  1267. echo -e "\npackage(s)::\n"
  1268. # shellcheck disable=SC2068
  1269. echo " " $@ | $FMT
  1270. if ! ask_yn "Should packages be removed (purge)?" Yn 30; then
  1271. return 42
  1272. fi
  1273. case $DIST_ID in
  1274. ubuntu|debian)
  1275. # shellcheck disable=SC2068
  1276. apt-get purge --autoremove --ignore-missing -y $@
  1277. ;;
  1278. arch)
  1279. # shellcheck disable=SC2068
  1280. pacman --noprogressbar -R --noconfirm $@
  1281. ;;
  1282. fedora)
  1283. # shellcheck disable=SC2068
  1284. dnf remove -y $@
  1285. ;;
  1286. centos)
  1287. # shellcheck disable=SC2068
  1288. yum remove -y $@
  1289. ;;
  1290. esac
  1291. }
  1292. pkg_is_installed() {
  1293. # usage: pkg_is_install foopkg || pkg_install foopkg
  1294. case $DIST_ID in
  1295. ubuntu|debian)
  1296. dpkg -l "$1" &> /dev/null
  1297. return $?
  1298. ;;
  1299. arch)
  1300. pacman -Qsq "$1" &> /dev/null
  1301. return $?
  1302. ;;
  1303. fedora)
  1304. dnf list -q --installed "$1" &> /dev/null
  1305. return $?
  1306. ;;
  1307. centos)
  1308. yum list -q --installed "$1" &> /dev/null
  1309. return $?
  1310. ;;
  1311. esac
  1312. }
  1313. # git tooling
  1314. # -----------
  1315. # shellcheck disable=SC2164
  1316. git_clone() {
  1317. # usage:
  1318. #
  1319. # git_clone <url> <name> [<branch> [<user>]]
  1320. # git_clone <url> <path> [<branch> [<user>]]
  1321. #
  1322. # First form uses $CACHE/<name> as destination folder, second form clones
  1323. # into <path>. If repository is already cloned, pull from <branch> and
  1324. # update working tree (if needed, the caller has to stash local changes).
  1325. #
  1326. # git clone https://github.com/searxng/searxng searx-src origin/master searxlogin
  1327. #
  1328. local url="$1"
  1329. local dest="$2"
  1330. local branch="$3"
  1331. local user="$4"
  1332. local bash_cmd="bash"
  1333. local remote="origin"
  1334. if [[ ! "${dest:0:1}" = "/" ]]; then
  1335. dest="$CACHE/$dest"
  1336. fi
  1337. [[ -z $branch ]] && branch=master
  1338. [[ -z $user ]] && [[ -n "${SUDO_USER}" ]] && user="${SUDO_USER}"
  1339. [[ -n $user ]] && bash_cmd="sudo -H -u $user -i"
  1340. if [[ -d "${dest}" ]] ; then
  1341. info_msg "already cloned: $dest"
  1342. tee_stderr 0.1 <<EOF | $bash_cmd 2>&1 | prefix_stdout " ${_Yellow}|$user|${_creset} "
  1343. cd "${dest}"
  1344. git checkout -m -B "$branch" --track "$remote/$branch"
  1345. git pull --all
  1346. EOF
  1347. else
  1348. info_msg "clone into: $dest"
  1349. tee_stderr 0.1 <<EOF | $bash_cmd 2>&1 | prefix_stdout " ${_Yellow}|$user|${_creset} "
  1350. mkdir -p "$(dirname "$dest")"
  1351. cd "$(dirname "$dest")"
  1352. git clone --branch "$branch" --origin "$remote" "$url" "$(basename "$dest")"
  1353. EOF
  1354. fi
  1355. }
  1356. # containers
  1357. # ----------
  1358. in_container() {
  1359. # Test if shell runs in a container.
  1360. #
  1361. # usage: in_container && echo "process running inside a LXC container"
  1362. # in_container || echo "process is not running inside a LXC container"
  1363. #
  1364. # sudo_or_exit
  1365. # hint: Reads init process environment, therefore root access is required!
  1366. # to be safe, take a look at the environment of process 1 (/sbin/init)
  1367. # grep -qa 'container=lxc' /proc/1/environ
  1368. # see lxc_init_container_env
  1369. [[ -f /.lxcenv ]]
  1370. }
  1371. LXC_ENV_FOLDER=
  1372. if in_container; then
  1373. # shellcheck disable=SC2034
  1374. LXC_ENV_FOLDER="lxc-env/$(hostname)/"
  1375. PY_ENV="${LXC_ENV_FOLDER}${PY_ENV}"
  1376. PY_ENV_BIN="${LXC_ENV_FOLDER}${PY_ENV_BIN}"
  1377. PYDIST="${LXC_ENV_FOLDER}${PYDIST}"
  1378. PYBUILD="${LXC_ENV_FOLDER}${PYBUILD}"
  1379. DOCS_DIST="${LXC_ENV_FOLDER}${DOCS_DIST}"
  1380. DOCS_BUILD="${LXC_ENV_FOLDER}${DOCS_BUILD}"
  1381. fi
  1382. lxc_init_container_env() {
  1383. # usage: lxc_init_container_env <name>
  1384. # Create a /.lxcenv file in the root folder. Call this once after the
  1385. # container is inital started and before installing any boilerplate stuff.
  1386. info_msg "create /.lxcenv in container $1"
  1387. cat <<EOF | lxc exec "${1}" -- bash | prefix_stdout "[${_BBlue}${1}${_creset}] "
  1388. touch "/.lxcenv"
  1389. ls -l "/.lxcenv"
  1390. EOF
  1391. }
  1392. # apt packages
  1393. LXC_BASE_PACKAGES_debian="bash git build-essential python3 python3-venv"
  1394. # pacman packages
  1395. LXC_BASE_PACKAGES_arch="bash git base-devel python"
  1396. # dnf packages
  1397. LXC_BASE_PACKAGES_fedora="bash git @development-tools python"
  1398. # yum packages
  1399. LXC_BASE_PACKAGES_centos="bash git python3"
  1400. case $DIST_ID in
  1401. ubuntu|debian) LXC_BASE_PACKAGES="${LXC_BASE_PACKAGES_debian}" ;;
  1402. arch) LXC_BASE_PACKAGES="${LXC_BASE_PACKAGES_arch}" ;;
  1403. fedora) LXC_BASE_PACKAGES="${LXC_BASE_PACKAGES_fedora}" ;;
  1404. centos) LXC_BASE_PACKAGES="${LXC_BASE_PACKAGES_centos}" ;;
  1405. *) err_msg "$DIST_ID-$DIST_VERS: pkg_install LXC_BASE_PACKAGES not yet implemented" ;;
  1406. esac
  1407. lxc_install_base_packages() {
  1408. info_msg "install LXC_BASE_PACKAGES in container $1"
  1409. case $DIST_ID in
  1410. centos) yum groupinstall "Development Tools" -y ;;
  1411. esac
  1412. pkg_install "${LXC_BASE_PACKAGES}"
  1413. }
  1414. lxc_image_copy() {
  1415. # usage: lxc_image_copy <remote image> <local image>
  1416. #
  1417. # lxc_image_copy "images:ubuntu/20.04" "ubu2004"
  1418. if lxc_image_exists "local:${LXC_SUITE[i+1]}"; then
  1419. info_msg "image ${LXC_SUITE[i]} already copied --> ${LXC_SUITE[i+1]}"
  1420. else
  1421. info_msg "copy image locally ${LXC_SUITE[i]} --> ${LXC_SUITE[i+1]}"
  1422. lxc image copy "${LXC_SUITE[i]}" local: \
  1423. --alias "${LXC_SUITE[i+1]}" | prefix_stdout
  1424. fi
  1425. }
  1426. lxc_init_container() {
  1427. # usage: lxc_init_container <image name> <container name>
  1428. local image_name="$1"
  1429. local container_name="$2"
  1430. if lxc info "${container_name}" &>/dev/null; then
  1431. info_msg "container '${container_name}' already exists"
  1432. else
  1433. info_msg "create container instance: ${container_name}"
  1434. lxc init "local:${image_name}" "${container_name}"
  1435. fi
  1436. }
  1437. lxc_exists(){
  1438. # usage: lxc_exists <name> || echo "container <name> does not exists"
  1439. lxc info "$1" &>/dev/null
  1440. }
  1441. lxc_image_exists(){
  1442. # usage: lxc_image_exists <alias> || echo "image <alias> does locally not exists"
  1443. lxc image info "local:$1" &>/dev/null
  1444. }
  1445. lxc_delete_container() {
  1446. # usage: lxc_delete_container <container-name>
  1447. if lxc info "$1" &>/dev/null; then
  1448. info_msg "stop & delete instance ${_BBlue}${1}${_creset}"
  1449. lxc stop "$1" &>/dev/null
  1450. lxc delete "$1" | prefix_stdout
  1451. else
  1452. warn_msg "instance '$1' does not exist / can't delete :o"
  1453. fi
  1454. }
  1455. lxc_delete_local_image() {
  1456. # usage: lxc_delete_local_image <container-name>
  1457. info_msg "delete image 'local:$i'"
  1458. lxc image delete "local:$i"
  1459. }
  1460. # IP
  1461. # --
  1462. global_IPs(){
  1463. # usage: global_IPS
  1464. #
  1465. # print list of host's SCOPE global addresses and adapters e.g::
  1466. #
  1467. # $ global_IPs
  1468. # enp4s0|192.168.1.127
  1469. # lxdbr0|10.246.86.1
  1470. # lxdbr0|fd42:8c58:2cd:b73f::1
  1471. ip -o addr show | sed -nr 's/[0-9]*:\s*([a-z0-9]*).*inet[6]?\s*([a-z0-9.:]*).*scope global.*/\1|\2/p'
  1472. }
  1473. primary_ip() {
  1474. case $DIST_ID in
  1475. arch)
  1476. ip -o addr show \
  1477. | sed -nr 's/[0-9]*:\s*([a-z0-9]*).*inet[6]?\s*([a-z0-9.:]*).*scope global.*/\2/p' \
  1478. | head -n 1
  1479. ;;
  1480. *) hostname -I | cut -d' ' -f1 ;;
  1481. esac
  1482. }
  1483. # URL
  1484. # ---
  1485. url_replace_hostname(){
  1486. # usage: url_replace_hostname <url> <new hostname>
  1487. # to replace hostname by primary IP::
  1488. #
  1489. # url_replace_hostname http://searx-ubu1604/morty $(primary_ip)
  1490. # http://10.246.86.250/morty
  1491. # shellcheck disable=SC2001
  1492. echo "$1" | sed "s|\(http[s]*://\)[^/]*\(.*\)|\1$2\2|"
  1493. }