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.

595 lines
16 KiB

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