github.com/niedbalski/juju@v0.0.0-20190215020005-8ff100488e47/acceptancetests/repository/xenial/wordpress/hooks/loadbalancer-relation-joined (about)

     1  #!/usr/bin/env python
     2  #
     3  #    reverseproxy-relation-changed - hook for when proxy relation changes
     4  #
     5  #    Copyright (C) 2011  Canonical Ltd.
     6  #    Author: Clint Byrum <clint.byrum@canonical.com>
     7  #
     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.
    12  #
    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.
    17  #
    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/>.
    20  #
    21  
    22  import sys
    23  import os
    24  import subprocess
    25  import tempfile
    26  
    27  rebuild = os.path.basename(sys.argv[0]) == 'loadbalancer-rebuild'
    28  
    29  pa = subprocess.Popen(["unit-get", "private-address"], stdout=subprocess.PIPE, 
    30      close_fds=True)
    31  unit_address = pa.stdout.read().strip()
    32  
    33  try:
    34      with open('.web-engine','r') as f:
    35          engine = f.readline().strip()
    36  except IOError:
    37      engine = 'nginx'
    38  
    39  if engine == 'apache2':
    40      conf_name = "loadbalancer"
    41      servers = """
    42  <Proxy balancer://backend>
    43    BalancerMember http://127.0.0.1:8080/
    44  """
    45      server_line = "  BalancerMember http://%s:8080/\n"
    46      server_end = """
    47    ProxySet lbmethod=bybusyness
    48  </Proxy>
    49  """
    50      t1 = '# Generated by juju'
    51      template = """
    52  <VirtualHost *:80>
    53  
    54  """
    55      template += "  ServerName %s\n" % unit_address
    56      template += """
    57    ServerAlias *
    58    LogLevel warn
    59    ErrorLog ${APACHE_LOG_DIR}/wordpress-balancer-error.log
    60    ProxyPreserveHost On
    61    <Location />
    62      Order allow,deny
    63      Allow from all
    64      ProxyPass balancer://backend/
    65      ProxyPassReverse balancer://backend/
    66    </Location>
    67  </VirtualHost>
    68  """
    69  else:
    70      conf_name = "loadbalancer"
    71      servers = """
    72  upstream backend {
    73    server 127.0.0.1:8080;
    74  """
    75      server_line = "  server %s:8080;\n"
    76      server_end = '}'
    77  
    78      t1 = """# Generated by juju
    79  proxy_cache_path /mnt/ramdisk/proxy-cache levels=1:2 keys_zone=proxycache:5m max_size=1000m;
    80  """
    81      # servers will go here
    82      template = """
    83  server {
    84    listen 80 default;
    85    server_name _;
    86  
    87    location / {
    88      set $no_cache "";
    89  
    90      if ($request_method !~ ^(GET|HEAD)$) {
    91        set $no_cache "1";
    92      }
    93  
    94      if ($no_cache = "1") {
    95        add_header Set-Cookie "_mcnc=1; Max-Age=30; Path=/";
    96        add_header X-Microcachable "0";
    97      }
    98  
    99      if ($http_cookie ~* "_mcnc") {
   100        set $no_cache "1";
   101      }
   102  
   103      proxy_no_cache $no_cache;
   104      proxy_cache_bypass $no_cache;
   105  
   106      proxy_redirect   http://backend  /;
   107      proxy_pass  http://backend;
   108      proxy_cache proxycache;
   109      proxy_cache_key $scheme$host$request_method$request_uri;
   110      proxy_cache_valid 200 60s;
   111      proxy_cache_use_stale updating;
   112  
   113      proxy_set_header Host $host;
   114      proxy_set_header X-Real-IP $remote_addr;
   115      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
   116      proxy_set_header X-UA-Compatible "IE=Edge,chrome=1";
   117  
   118      proxy_max_temp_file_size 1M;
   119    }
   120  }
   121  """
   122  
   123  if rebuild:
   124      try:
   125          with open('.loadbalancer-units') as units:
   126              for paddress in units:
   127                  servers += (server_line % (paddress.strip()))
   128      except IOError:
   129          pass
   130  else:
   131      units = []
   132      p = subprocess.Popen("relation-list", stdout=subprocess.PIPE)
   133      for unit in p.stdout:
   134          units.append(unit.strip())
   135  
   136      print units
   137  
   138      lb_file = open('.loadbalancer-units', 'w')
   139      for unit in units:
   140          p = subprocess.Popen(["relation-get", "private-address", unit],
   141                               stdout=subprocess.PIPE, close_fds=True)
   142          paddress = p.stdout.read().strip()
   143          p.wait()
   144          lb_file.write("%s\n" % paddress)
   145          # Add all configured units:
   146          servers += (server_line % (paddress))
   147  
   148      lb_file.close()
   149  servers += server_end
   150  
   151  print servers
   152  
   153  with tempfile.NamedTemporaryFile(dir="/etc/%s/sites-available/" % engine, 
   154          prefix='lb', delete=False) as conf:
   155      conf.write(t1 + servers + template)
   156      try:
   157          os.unlink("/etc/%s/sites-available/%s.old" % (engine, conf_name))
   158      except:
   159          pass
   160      try:
   161          os.rename("/etc/%s/sites-available/%s" % (engine, conf_name), 
   162              "/etc/%s/sites-available/%s.old" % (engine, conf_name))
   163      except:
   164          pass
   165      try:
   166          os.rename(conf.name, "/etc/%s/sites-available/%s" % (engine, conf_name))
   167      except:
   168          os.unlink(conf.name)
   169  
   170  subprocess.call(["service", engine, "start"])
   171  subprocess.check_call(["service", engine, "reload"])
   172  
   173  subprocess.check_call(["open-port", "80"])