3
# reverseproxy-relation-changed - hook for when reverse proxy relation changes
5
# Copyright (C) 2011 Canonical Ltd.
6
# Author: Clint Byrum <clint.byrum@canonical.com>
8
# This program is free software: you can redistribute it and/or modify
9
# it under the terms of the GNU General Public License as published by
10
# the Free Software Foundation, either version 3 of the License, or
11
# (at your option) any later version.
13
# This program is distributed in the hope that it will be useful,
14
# but WITHOUT ANY WARRANTY; without even the implied warranty of
15
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
# GNU General Public License for more details.
18
# You should have received a copy of the GNU General Public License
19
# along with this program. If not, see <http://www.gnu.org/licenses/>.
29
from socket import getaddrinfo
31
remote_unit = os.environ.get("JUJU_REMOTE_UNIT")
33
service_name, _ = remote_unit.split("/")
35
# TODO: maybe load this from disk for easier customization
36
t1 = """# Generated by juju
37
proxy_cache_path /mnt/ramdisk/proxy-cache levels=1:2 keys_zone=proxycache:5m max_size=1000m;
39
# servers will go here
48
if ($request_method !~ ^(GET|HEAD)$) {
52
if ($no_cache = "1") {
53
add_header Set-Cookie "_mcnc=1; Max-Age=30; Path=/";
54
add_header X-Microcachable "0";
57
if ($http_cookie ~* "_mcnc") {
61
proxy_no_cache $no_cache;
62
proxy_cache_bypass $no_cache;
64
proxy_redirect http://backend /;
65
proxy_pass http://backend;
66
proxy_cache proxycache;
67
proxy_cache_key $scheme$host$request_method$request_uri;
68
proxy_cache_valid 200 60s;
69
proxy_cache_use_stale updating;
71
proxy_set_header Host $host;
72
proxy_set_header X-Real-IP $remote_addr;
73
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
74
proxy_set_header X-UA-Compatible "IE=Edge,chrome=1";
76
proxy_max_temp_file_size 1M;
82
p = subprocess.Popen("relation-list", stdout=subprocess.PIPE)
84
units.append(unit.strip())
90
server 127.0.0.1:8080;
93
p = subprocess.Popen(["relation-get", "private-address", unit],
94
stdout=subprocess.PIPE, close_fds=True)
95
paddress = p.stdout.read().strip()
97
# Add all configured units:
98
servers += (" server %s:8080;\n" % (paddress))
103
with tempfile.NamedTemporaryFile(dir="/etc/nginx/sites-available/",prefix="loadbalancer", delete=False) as conf:
104
conf.write(t1 + servers + template)
106
os.unlink("/etc/nginx/sites-available/loadbalancer.old")
110
os.rename("/etc/nginx/sites-available/loadbalancer","/etc/nginx/sites-available/loadbalancer.old")
114
os.rename(conf.name, "/etc/nginx/sites-available/loadbalancer")
120
# Just in case haproxy wouldn't start because of empty/bad configs before, start it now
121
subprocess.call(["service", "nginx", "start"])
122
subprocess.check_call(["service", "nginx", "reload"])
124
subprocess.check_call(["open-port", "80"])