|
| 1 | +"""EasyEngine Hash bucket calculate function for Nginx""" |
| 2 | +from ee.core.fileutils import EEFileUtils |
| 3 | +import math |
| 4 | +import os |
| 5 | +import fileinput |
| 6 | +import re |
| 7 | +import subprocess |
| 8 | + |
| 9 | + |
| 10 | +def hashbucket(self): |
| 11 | + # Check Nginx Hashbucket error |
| 12 | + sub = subprocess.Popen('nginx -t', stdout=subprocess.PIPE, |
| 13 | + stderr=subprocess.PIPE, shell=True) |
| 14 | + output, error_output = sub.communicate() |
| 15 | + if 'server_names_hash_bucket_size' not in str(error_output): |
| 16 | + return True |
| 17 | + |
| 18 | + count = 0 |
| 19 | + # Get the list of sites-availble |
| 20 | + sites_list = os.listdir("/etc/nginx/sites-enabled/") |
| 21 | + |
| 22 | + # Count the number of characters in site names |
| 23 | + for site in sites_list: |
| 24 | + count = sum([count, len(site)]) |
| 25 | + |
| 26 | + # Calculate Nginx hash bucket size |
| 27 | + ngx_calc = math.trunc(sum([math.log(count, 2), 2])) |
| 28 | + ngx_hash = math.trunc(math.pow(2, ngx_calc)) |
| 29 | + |
| 30 | + # Replace hashbucket in Nginx.conf file |
| 31 | + if EEFileUtils.grep(self, "/etc/nginx/nginx.conf", |
| 32 | + "server_names_hash_bucket_size"): |
| 33 | + for line in fileinput.FileInput("/etc/nginx/nginx.conf", inplace=1): |
| 34 | + if "server_names_hash_bucket_size" in line: |
| 35 | + print("\tserver_names_hash_bucket_size {0};".format(ngx_hash)) |
| 36 | + else: |
| 37 | + print(line, end='') |
| 38 | + |
| 39 | + elif os.path.isfile('/etc/nginx/conf.d/ee-nginx.conf'): |
| 40 | + if EEFileUtils.grep(self, "/etc/nginx/conf.d/ee-nginx.conf", |
| 41 | + "server_names_hash_bucket_size"): |
| 42 | + for line in fileinput.FileInput("/etc/nginx/conf.d/ee-nginx.conf", |
| 43 | + inplace=1): |
| 44 | + if "server_names_hash_bucket_size" in line: |
| 45 | + print("server_names_hash_bucket_size {0};" |
| 46 | + .format(ngx_hash)) |
| 47 | + else: |
| 48 | + print(line, end='') |
| 49 | + |
| 50 | + else: |
| 51 | + with open('/etc/nginx/conf.d/ee-nginx.conf', 'a') as conf: |
| 52 | + conf.write("server_names_hash_bucket_size {0};\n" |
| 53 | + .format(ngx_hash)) |
| 54 | + else: |
| 55 | + EEFileUtils.searchreplace(self, '/etc/nginx/nginx.conf', |
| 56 | + "gzip_disable \"msie6\";", |
| 57 | + "gzip_disable \"msie6\";\n" |
| 58 | + "\tserver_names_hash_bucket_size {0};\n" |
| 59 | + .format(ngx_hash)) |
0 commit comments