Charm: precise/drupal6   Revision: 2   Hook: loadbalancer-relation-departed
#!/usr/bin/env python
#
#    reverseproxy-relation-changed - hook for when reverse proxy relation changes
#
#    Copyright (C) 2011  Canonical Ltd.
#    Author: Clint Byrum <clint.byrum@canonical.com>
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

import sys
import os
import subprocess
import json
import tempfile
import glob

from socket import getaddrinfo

remote_unit = os.environ.get("JUJU_REMOTE_UNIT")

service_name, _ = remote_unit.split("/")

# TODO: maybe load this from disk for easier customization
t1 = """
# Generated by juju

"""
# servers will go here
template = """
server {
  listen 80 default;
  location / {
    proxy_pass  http://backend;
  }
}
"""

units = []
p = subprocess.Popen("relation-list", stdout=subprocess.PIPE)
for unit in p.stdout:
    units.append(unit.strip())

print units

servers = """
upstream backend {
  server 127.0.0.1:8080;
"""
for unit in units:
    p = subprocess.Popen(["relation-get", "private-address", unit],
                         stdout=subprocess.PIPE, close_fds=True)
    paddress = p.stdout.read().strip()
    p.wait()
    # Add all configured units:
    servers += ("  server %s:8080;\n" % (paddress))
servers += '}'

print servers

with tempfile.NamedTemporaryFile(dir="/etc/nginx/sites-available/",prefix="loadbalancer", delete=False) as conf:
    conf.write(t1 + servers + template)
    try:
        os.unlink("/etc/nginx/sites-available/loadbalancer.old")
    except:
        pass
    try:
        os.rename("/etc/nginx/sites-available/loadbalancer","/etc/nginx/sites-available/loadbalancer.old")
    except:
        pass
    try:
      os.rename(conf.name, "/etc/nginx/sites-available/loadbalancer")
    except:
        os.unlink(conf.name)

# Just in case haproxy wouldn't start because of empty/bad configs before, start it now
subprocess.call(["service", "nginx", "start"])
subprocess.check_call(["service", "nginx", "reload"])

subprocess.check_call(["open-port", "80"])