fork 0k-charms
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

565 lines
15 KiB

  1. # -*- mode: shell-script -*-
  2. config_hash=
  3. apache_proxy_dir () {
  4. DOMAIN=$(relation-get domain) || {
  5. err "You must specify a ${WHITE}domain$NORMAL option in relation."
  6. return 1
  7. }
  8. proxy=yes apache_vhost_create || return 1
  9. info "Added $DOMAIN as a proxy to $TARGET."
  10. }
  11. export -f apache_proxy_dir
  12. apache_publish_dir () {
  13. DOMAIN=$(relation-get domain) || {
  14. err "You must specify a ${WHITE}domain$NORMAL option in relation."
  15. return 1
  16. }
  17. DOCKER_SITE_PATH="/var/www/${DOMAIN}"
  18. LOCATION=$(relation-get location 2>/dev/null) ||
  19. LOCATION="$DATASTORE/$BASE_SERVICE_NAME$DOCKER_SITE_PATH"
  20. apache_vhost_create || return 1
  21. info "Added $DOMAIN apache config."
  22. apache_code_dir || return 1
  23. apache_data_dirs
  24. }
  25. export -f apache_publish_dir
  26. apache_vhost_create () {
  27. export APACHE_CONFIG_LOCATION="$SERVICE_CONFIGSTORE/etc/apache2/sites-enabled"
  28. SERVER_ALIAS=$(relation-get server-aliases 2>/dev/null) || true
  29. PROTOCOLS=$(__vhost_cfg_normalize_protocol) || return 1
  30. export SERVER_ALIAS PROTOCOLS SSL_PLUGIN_FUN SSL_CFG_{VALUE,OPTION}
  31. if is_protocol_enabled https; then
  32. read-0 SSL_PLUGIN_FUN SSL_CFG_VALUE SSL_CFG_OPTIONS < <(ssl_get_plugin_fun) || return 1
  33. "$SSL_PLUGIN_FUN"_vars "$SSL_CFG_OPTIONS" "$SSL_CFG_VALUE" || return 1
  34. fi
  35. apache_vhost_statement "$PROTOCOLS" |
  36. file_put "$APACHE_CONFIG_LOCATION/$prefix$DOMAIN.conf" || return 1
  37. __vhost_cfg_creds_enabled=$(relation-get creds 2>/dev/null) || true
  38. if [ "$__vhost_cfg_creds_enabled" ]; then
  39. apache_passwd_file || return 1
  40. fi
  41. if is_protocol_enabled https; then
  42. "$SSL_PLUGIN_FUN"_prepare "$SSL_CFG_OPTIONS" "$SSL_CFG_VALUE" || return 1
  43. fi
  44. }
  45. is_protocol_enabled() {
  46. local protocol=$1
  47. [[ "$PROTOCOLS" == *",$protocol,"* ]]
  48. }
  49. export -f is_protocol_enabled
  50. __vhost_cfg_normalize_protocol() {
  51. local protocol
  52. if ! protocol=$(relation-get protocol 2>/dev/null); then
  53. protocol=auto
  54. else
  55. protocol=${protocol:-auto}
  56. fi
  57. case "$protocol" in
  58. auto)
  59. if __vhost_cfg_ssl="$(relation-get ssl 2>/dev/null)"; then
  60. protocol="https"
  61. export __vhost_cfg_ssl
  62. else
  63. protocol="http"
  64. fi
  65. ;;
  66. both)
  67. protocol="https,http"
  68. ;;
  69. ssl|https)
  70. protocol="https"
  71. ;;
  72. http)
  73. protocol="http"
  74. ;;
  75. *)
  76. err "Invalid value '$protocol' for ${WHITE}protocol$NORMAL option (use one of: http, https, both, auto)."
  77. return 1
  78. esac
  79. echo ",$protocol,"
  80. }
  81. ## ssl_plugin_* and ssl_fallback should :
  82. ## - do anything to ensure that
  83. ## - issue config-add to add volumes if necessary
  84. ## - output 3 vars of where to find the 3 files from within the docker apache
  85. ssl_get_plugin_fun() {
  86. # from ssl conf, return the function that should manage SSL code creation
  87. local cfg="$(relation-get ssl 2>/dev/null)" type keys
  88. if [ -z "$cfg" ]; then
  89. return 0
  90. else
  91. type="$(echo "$cfg" | shyaml -y get-type 2>/dev/null)" || return 1
  92. fi
  93. if [[ "$type" == "bool" ]]; then
  94. printf "%s\0" "ssl_fallback" "" "$cfg"
  95. echo ssl_fallback
  96. return 0
  97. fi
  98. if ! [[ "$type" == "str" || "$type" == "struct" ]]; then
  99. err "Invalid ${WHITE}ssl${NORMAL} value type '$type': please provide a string or a struct."
  100. return 1
  101. fi
  102. if [ -z "$NO_CERT_PROVIDER" ]; then
  103. if [[ "$type" == "str" ]]; then
  104. keys=("$cfg")
  105. else
  106. keys=($(echo "$cfg" | shyaml keys 2>/dev/null))
  107. fi
  108. for key in "${keys[@]}"; do
  109. target_relation="cert-provider"
  110. fun="ssl_plugin_${target_relation}"
  111. while read-0 relation_name target_service relation_config tech_dep; do
  112. [ "$relation_name" == "${target_relation}" ] || continue
  113. [ "$target_service" == "$key" ] || continue
  114. verb "Corresponding plugin ${DARKGREEN}found${NORMAL}" \
  115. "in ${DARKBLUE}$relation_name${NORMAL}/${DARKYELLOW}$key${NORMAL}"
  116. ssl_cfg=$(printf "%s" "$cfg" | shyaml get-value "$key" 2>/dev/null) || true
  117. merged_config=$(merge_yaml_str "$relation_config" "$ssl_cfg") || return 1
  118. printf "%s\0" "$fun" "$key" "$merged_config"
  119. return 0
  120. done < <(get_compose_relations "$SERVICE_NAME") || return 1
  121. case "$key" in
  122. cert|ca-cert|key)
  123. :
  124. ;;
  125. *)
  126. err "Invalid key '$key' in ${WHITE}ssl${NORMAL}:" \
  127. "no corresponding services declared in ${DARKBLUE}${target_relation}$NORMAL"
  128. return 1
  129. ;;
  130. esac
  131. done
  132. fi
  133. ## No key of the struct seem to be declared cert-provider, so fallback
  134. printf "%s\0" "ssl_fallback" "" "$cfg"
  135. echo ssl_fallback
  136. }
  137. ssl_fallback_vars() {
  138. local cfg="$1" cert key ca_cert
  139. if __vhost_cfg_ssl_cert=$(echo "$cfg" | shyaml get-value cert 2>/dev/null); then
  140. __vhost_cfg_SSL_CERT_LOCATION=/etc/ssl/certs/${DOMAIN}.pem
  141. fi
  142. if __vhost_cfg_ssl_key=$(echo "$cfg" | shyaml get-value key 2>/dev/null); then
  143. __vhost_cfg_SSL_KEY_LOCATION=/etc/ssl/private/${DOMAIN}.key
  144. fi
  145. if __vhost_cfg_ssl_ca_cert=$(echo "$cfg" | shyaml get-value ca-cert 2>/dev/null); then
  146. __vhost_cfg_SSL_CA_CERT_LOCATION=/etc/ssl/certs/${DOMAIN}-ca.pem
  147. fi
  148. }
  149. ssl_fallback_prepare() {
  150. local cfg="$1" cert key ca_cert
  151. dst="$CONFIGSTORE/$BASE_SERVICE_NAME"
  152. volumes=""
  153. for label in cert key ca_cert; do
  154. content="$(eval echo "\"\$__vhost_cfg_ssl_$label\"")"
  155. if [ "$content" ]; then
  156. location="$(eval echo "\$__vhost_cfg_SSL_${label^^}_LOCATION")"
  157. echo "$content" | file_put "$dst$location"
  158. config_hash=$(printf "%s\0" "$config_hash" "$label" "$content" | md5_compat)
  159. volumes="$volumes
  160. - $dst$location:$location:ro"
  161. fi
  162. done
  163. if [ "$volumes" ]; then
  164. config-add "\
  165. services:
  166. $MASTER_TARGET_SERVICE_NAME:
  167. volumes:
  168. $volumes
  169. "
  170. fi
  171. }
  172. ssl_plugin_cert-provider_vars() {
  173. __vhost_cfg_SSL_CERT_LOCATION=/etc/letsencrypt/live/${DOMAIN}/cert.pem
  174. __vhost_cfg_SSL_KEY_LOCATION=/etc/letsencrypt/live/${DOMAIN}/privkey.pem
  175. __vhost_cfg_SSL_CHAIN=/etc/letsencrypt/live/${DOMAIN}/chain.pem
  176. }
  177. ssl_plugin_cert-provider_prepare() {
  178. local cfg="$1" service="$2" options
  179. options=$(yaml_key_val_str "options" "$cfg") || return 1
  180. service_config=$(yaml_key_val_str "$service" "$options")
  181. compose --debug --add-compose-content "$service_config" run --service-ports "$service" \
  182. crt create "$DOMAIN" $(echo "$SERVER_ALIAS" | shyaml -y get-values 2>/dev/null) || return 1
  183. config-add "\
  184. services:
  185. $MASTER_TARGET_SERVICE_NAME:
  186. volumes:
  187. - $DATASTORE/$service/etc/letsencrypt:/etc/letsencrypt:ro
  188. " || return 1
  189. }
  190. apache_passwd_file() {
  191. include parse || true
  192. ## XXXvlab: called twice... no better way to do this ?
  193. __vhost_creds_statement >/dev/null
  194. first=
  195. if ! [ -e "$CONFIGSTORE/$MASTER_TARGET_SERVICE_NAME$password_file" ]; then
  196. debug "No file $CONFIGSTORE/$MASTER_TARGET_SERVICE_NAME$password_file, creating password file." || true
  197. first=c
  198. fi
  199. while read-0 login password; do
  200. debug "htpasswd -b$first '${password_file}' '$login' '$password'"
  201. echo "htpasswd -b$first '${password_file}' '$login' '$password'"
  202. if [ "$first" ]; then
  203. first=
  204. fi
  205. done < <(echo "$__vhost_cfg_creds_enabled" | shyaml key-values-0 2>/dev/null) |
  206. docker run -i --entrypoint "/bin/bash" \
  207. -v "$APACHE_CONFIG_LOCATION:/etc/apache2/sites-enabled" \
  208. "$DOCKER_BASE_IMAGE" || return 1
  209. }
  210. ## Produce the full statements depending on relation-get informations
  211. apache_vhost_statement() {
  212. local vhost_statement
  213. export SERVER_ALIAS=$(relation-get server-aliases 2>/dev/null) || true
  214. export PROTOCOLS="$1"
  215. if is_protocol_enabled http; then
  216. __vhost_full_vhost_statement http
  217. fi
  218. if is_protocol_enabled https; then
  219. "$SSL_PLUGIN_FUN"_vars "$(relation-get ssl 2>/dev/null)"
  220. cat <<EOF
  221. <IfModule mod_ssl.c>
  222. $(__vhost_full_vhost_statement https | prefix " ")
  223. </IfModule>
  224. EOF
  225. fi
  226. }
  227. export -f apache_vhost_statement
  228. apache_code_dir() {
  229. local www_data_gid
  230. www_data_gid=$(cached_cmd_on_base_image apache 'id -g www-data') || {
  231. debug "Failed to query for www-data gid in ${DARKYELLOW}apache${NORMAL} base image."
  232. return 1
  233. }
  234. mkdir -p "$LOCATION" || return 1
  235. setfacl -R -m g:"$www_data_gid":rx "$LOCATION"
  236. info "Set permission for read and traversal on '$LOCATION'."
  237. config-add "
  238. $MASTER_BASE_SERVICE_NAME:
  239. volumes:
  240. - $LOCATION:$DOCKER_SITE_PATH
  241. "
  242. }
  243. apache_data_dirs() {
  244. DATA_DIRS=$(relation-get data-dirs 2>/dev/null | shyaml get-values 2>/dev/null) || true
  245. if [ -z "$DATA_DIRS" ]; then
  246. return 0
  247. fi
  248. DST=$DATASTORE/$BASE_SERVICE_NAME$DOCKER_SITE_PATH
  249. DATA=()
  250. while IFS="," read -ra ADDR; do
  251. for dir in "${ADDR[@]}"; do
  252. DATA+=($dir)
  253. done
  254. done <<< "$DATA_DIRS"
  255. www_data_gid=$(cached_cmd_on_base_image apache 'id -g www-data') || {
  256. debug "Failed to query for www-data gid in ${DARKYELLOW}apache${NORMAL} base image."
  257. return 1
  258. }
  259. info "www-data gid from ${DARKYELLOW}apache${NORMAL} is '$www_data_gid'"
  260. dirs=()
  261. for d in "${DATA[@]}"; do
  262. dirs+=("$DST/$d")
  263. done
  264. mkdir -p "${dirs[@]}"
  265. setfacl -R -m g:"$www_data_gid":rwx "${dirs[@]}"
  266. setfacl -R -d -m g:"$www_data_gid":rwx "${dirs[@]}"
  267. config-add "
  268. $MASTER_BASE_SERVICE_NAME:
  269. volumes:
  270. $(
  271. for d in "${DATA[@]}"; do
  272. echo " - $DST/$d:$DOCKER_SITE_PATH/$d"
  273. done
  274. )"
  275. }
  276. deploy_files() {
  277. local src="$1" dst="$2"
  278. if ! [ -d "$dst" ]; then
  279. err "Destination '$dst' does not exist or is not a directory"
  280. return 1
  281. fi
  282. (
  283. cd "$dst" && info "In $dst:" &&
  284. get_file "$src" | tar xv
  285. )
  286. }
  287. export -f deploy_files
  288. apache_core_rules_add() {
  289. local conf="$1" dst="/etc/apache2/conf-enabled/$BASE_SERVICE_NAME.conf"
  290. debug "Adding core rule."
  291. echo "$conf" | file_put "$CONFIGSTORE/$BASE_SERVICE_NAME$dst"
  292. config_hash=$(printf "%s\0" "$config_hash" "$conf" | md5_compat)
  293. config-add "
  294. $MASTER_BASE_SERVICE_NAME:
  295. volumes:
  296. - $CONFIGSTORE/$BASE_SERVICE_NAME$dst:$dst:ro
  297. "
  298. }
  299. __vhost_ssl_statement() {
  300. ## defaults
  301. __vhost_cfg_SSL_CERT_LOCATION=${__vhost_cfg_SSL_CERT_LOCATION:-/etc/ssl/certs/ssl-cert-snakeoil.pem}
  302. __vhost_cfg_SSL_KEY_LOCATION=${__vhost_cfg_SSL_KEY_LOCATION:-/etc/ssl/private/ssl-cert-snakeoil.key}
  303. cat <<EOF
  304. ##
  305. ## SSL Configuration
  306. ##
  307. SSLEngine On
  308. SSLCertificateFile $__vhost_cfg_SSL_CERT_LOCATION
  309. SSLCertificateKeyFile $__vhost_cfg_SSL_KEY_LOCATION
  310. $([ -z "$__vhost_cfg_SSL_CA_CERT_LOCATION" ] || echo "SSLCACertificateFile $__vhost_cfg_SSL_CA_CERT_LOCATION")
  311. $([ -z "$__vhost_cfg_SSL_CHAIN" ] || echo "SSLCertificateChainFile $__vhost_cfg_SSL_CHAIN")
  312. SSLVerifyClient None
  313. EOF
  314. }
  315. __vhost_creds_statement() {
  316. if ! __vhost_cfg_creds_enabled=$(relation-get creds 2>/dev/null); then
  317. echo "Allow from all"
  318. return 0
  319. fi
  320. password_file=/etc/apache2/sites-enabled/${DOMAIN}.passwd
  321. cat <<EOF
  322. AuthType basic
  323. AuthName "private"
  324. AuthUserFile ${password_file}
  325. Require valid-user
  326. EOF
  327. }
  328. __vhost_head_statement() {
  329. local protocol="$1"
  330. if [ "$protocol" == "https" ]; then
  331. prefix="s-"
  332. else
  333. prefix=
  334. fi
  335. cat <<EOF
  336. ServerAdmin ${ADMIN_MAIL:-contact@$DOMAIN}
  337. ServerName ${DOMAIN}
  338. $(
  339. while read-0 alias; do
  340. echo "ServerAlias $alias"
  341. done < <(echo "$SERVER_ALIAS" | shyaml get-values-0 2>/dev/null)
  342. )
  343. ServerSignature Off
  344. CustomLog /var/log/apache2/${prefix}${DOMAIN}_access.log combined
  345. ErrorLog /var/log/apache2/${prefix}${DOMAIN}_error.log
  346. ErrorLog syslog:local2
  347. EOF
  348. }
  349. __vhost_custom_rules() {
  350. local custom_rules
  351. if custom_rules=$(relation-get apache-custom-rules 2>/dev/null); then
  352. cat <<EOF
  353. ##
  354. ## Custom rules
  355. ##
  356. $custom_rules
  357. EOF
  358. fi
  359. }
  360. __vhost_content_statement() {
  361. if [ "$proxy" ]; then
  362. __vhost_proxy_statement "$@"
  363. else
  364. __vhost_publish_dir_statement "$@"
  365. fi
  366. }
  367. __vhost_proxy_statement() {
  368. local protocol="$1"
  369. TARGET=$(relation-get target 2>/dev/null) || true
  370. if [ -z "$TARGET" ]; then
  371. ## First exposed port:
  372. base_image=$(service_base_docker_image "$BASE_SERVICE_NAME") || return 1
  373. first_exposed_port=$(image_exposed_ports_0 "$base_image" | tr '\0' '\n' | head -n 1 | cut -f 1 -d /) || return 1
  374. TARGET=$MASTER_BASE_SERVICE_NAME:$first_exposed_port
  375. info "No target was specified, introspection found: $TARGET"
  376. fi
  377. cat <<EOF
  378. ##
  379. ## Proxy declaration towards $TARGET
  380. ##
  381. <IfModule mod_proxy.c>
  382. ProxyRequests Off
  383. <Proxy *>
  384. Order deny,allow
  385. Allow from all
  386. </Proxy>
  387. ProxyVia On
  388. ProxyPass / http://$TARGET/ retry=0
  389. <Location / >
  390. $(__vhost_creds_statement | prefix " ")
  391. ProxyPassReverse /
  392. </Location>
  393. $([ "$protocol" == "https" ] && echo " SSLProxyEngine On")
  394. </IfModule>
  395. RequestHeader set "X-Forwarded-Proto" "$protocol"
  396. ## Fix IE problem (httpapache proxy dav error 408/409)
  397. SetEnv proxy-nokeepalive 1
  398. EOF
  399. }
  400. __vhost_full_vhost_statement() {
  401. local protocol="$1"
  402. case "$protocol" in
  403. https)
  404. PORT=443
  405. ;;
  406. http)
  407. PORT=80
  408. ;;
  409. esac
  410. cat <<EOF
  411. <VirtualHost *:$PORT>
  412. $(__vhost_head_statement "$protocol" | prefix " " && echo)
  413. $(__vhost_custom_rules | prefix " " && echo)
  414. $(__vhost_content_statement "$protocol" | prefix " ")
  415. ## Forbid any cache, this is only usefull on dev server.
  416. #Header set Cache-Control "no-cache"
  417. #Header set Access-Control-Allow-Origin "*"
  418. #Header set Access-Control-Allow-Methods "POST, GET, OPTIONS"
  419. #Header set Access-Control-Allow-Headers "origin, content-type, accept"
  420. $([ "$protocol" == "https" ] && __vhost_ssl_statement | prefix " " && echo )
  421. </VirtualHost>
  422. EOF
  423. }
  424. __vhost_publish_dir_statement() {
  425. cat <<EOF
  426. ##
  427. ## Publish directory $DOCKER_SITE_PATH
  428. ##
  429. DocumentRoot $DOCKER_SITE_PATH
  430. <Directory />
  431. Options FollowSymLinks
  432. AllowOverride None
  433. </Directory>
  434. <Directory $DOCKER_SITE_PATH>
  435. Options Indexes FollowSymLinks MultiViews
  436. AllowOverride all
  437. $(__vhost_creds_statement | prefix " ")
  438. </Directory>
  439. EOF
  440. }
  441. apache_config_hash() {
  442. debug "Adding config hash to enable recreating upon config change."
  443. config_hash=$({
  444. printf "%s\0" "$config_hash"
  445. find "$SERVICE_CONFIGSTORE/etc/apache2/sites-enabled" \
  446. -name \*.conf -exec md5sum {} \;
  447. } | md5_compat) || exit 1
  448. init-config-add "
  449. $MASTER_BASE_SERVICE_NAME:
  450. labels:
  451. - compose.config_hash=$config_hash
  452. "
  453. }