tis-remote-repo-nginx
1-1
Package for installing nginx on windows for remote repositories agent
6221 downloads

Description
- package : tis-remote-repo-nginx
- version : 1-1
- architecture : all
- categories :
- maintainer : Evan BLAUDY
- description : Package for installing nginx on windows for remote repositories agent
- locale :
- target_os : windows
- min_wapt_version :
- sources :
- installed_size :
- impacted_process :
- description_fr :
- description_pl :
- description_de :
- description_es :
- description_pt :
- description_it :
- description_nl :
- description_ru :
- editor :
- licence :
- signature_date : 2020-02-27T21:40:33.178940
- Depends :
Setup.py
# -*- coding: utf-8 -*-
from setuphelpers import *
import time
import jinja2
from waptcrypto import SSLPrivateKey,SSLCertificate
uninstallkey = []
service_name = 'WAPTRepoNginx'
def install():
nssm = os.path.join(WAPT.wapt_base_dir, 'waptservice', 'win64', 'nssm.exe')
def install_windows_nssm_service(service_binary,service_parameters,service_logfile):
datatypes = {
'dword': REG_DWORD,
'sz': REG_SZ,
'expand_sz': REG_EXPAND_SZ,
'multi_sz': REG_MULTI_SZ,
}
if service_installed(service_name):
if not service_is_stopped(service_name):
print('Stop running "%s"' % service_name)
run('net stop "%s" /yes' % service_name)
while not service_is_stopped(service_name):
print('Waiting for "%s" to terminate' % service_name)
time.sleep(2)
print('Unregister existing "%s"' % service_name)
run('sc delete "%s"' % service_name)
if not iswin64():
raise Exception('Windows 32bit install not supported')
print('Register service "%s" with nssm' % service_name)
cmd = '"{nssm}" install "{service_name}" "{service_binary}" {service_parameters}'.format(
nssm=nssm,
service_name=service_name,
service_binary=service_binary,
service_parameters=service_parameters
)
print('running command : %s' % cmd)
run(cmd)
# fix some parameters (quotes for path with spaces...
params = {
'Description': 'sz:%s' % service_name,
'DelayedAutostart': 1,
'DisplayName': 'sz:%s' % service_name,
'AppStdout': r'expand_sz:{}'.format(service_logfile),
'ObjectName': r'NT AUTHORITY\NetworkService',
'Parameters\\AppStderr': r'expand_sz:{}'.format(service_logfile),
'Parameters\\AppParameters': r'expand_sz:{}'.format(service_parameters),
'Parameters\\AppNoConsole': 1,
}
root = HKEY_LOCAL_MACHINE
base = r'SYSTEM\CurrentControlSet\services\%s' % service_name
for key in params:
if isinstance(params[key], int):
(valuetype, value) = ('dword', params[key])
elif ':' in params[key]:
(valuetype, value) = params[key].split(':', 1)
if valuetype == 'dword':
value = int(value)
else:
(valuetype, value) = ('sz', params[key])
fullpath = base + '\\' + key
(path, keyname) = fullpath.rsplit('\\', 1)
if keyname == '@' or keyname == '':
keyname = None
registry_set(root, path, keyname, value, type=datatypes[valuetype])
def make_nginx_config(local_repo):
ap_conf_dir = os.path.join(
WAPT.wapt_base_dir,
'waptservice',
'nginx',
'conf')
ap_file_name = 'nginx.conf'
ap_conf_file = os.path.join(ap_conf_dir, ap_file_name)
ap_ssl_dir = os.path.join(WAPT.wapt_base_dir,'waptservice','nginx','ssl')
if os.path.isfile(ap_conf_file):
if 'waptservice' in open(ap_conf_file,'r').read():
return ap_conf_file
mkdirs(ap_ssl_dir)
key_fn = os.path.join(ap_ssl_dir,'key.pem')
key = SSLPrivateKey(key_fn)
if not os.path.isfile(key_fn):
print('Create SSL RSA Key %s' % key_fn)
key.create()
key.save_as_pem()
cert_fn = os.path.join(ap_ssl_dir,'cert.pem')
if os.path.isfile(cert_fn):
crt = SSLCertificate(cert_fn)
if crt.cn != get_fqdn():
os.rename(cert_fn,"%s-%s.old" % (cert_fn,'{:%Y%m%d-%Hh%Mm%Ss}'.format(datetime.datetime.now())))
crt = key.build_sign_certificate(cn=get_fqdn(),dnsname=get_fqdn(),is_code_signing=False)
print('Create X509 cert %s' % cert_fn)
crt.save_as_pem(cert_fn)
else:
crt = key.build_sign_certificate(cn=get_fqdn(),dnsname=get_fqdn(),is_code_signing=False)
print('Create X509 cert %s' % cert_fn)
crt.save_as_pem(cert_fn)
# write config file
jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.join(WAPT.wapt_base_dir,'waptservice','scripts')))
template = jinja_env.get_template('waptwindows.nginxconfig.j2')
template_variables = {
'wapt_repository_path': local_repo.replace('\\','/'),
'ssl': True,
'force_https': True,
'wapt_ssl_key_file': key_fn.replace('\\','/'),
'wapt_ssl_cert_file': cert_fn.replace('\\','/'),
'log_dir': os.path.join(WAPT.wapt_base_dir,'waptservice','nginx','logs').replace('\\','/'),
'wapt_root_dir' : WAPT.wapt_base_dir.replace('\\','/'),
'nginx_http' : 80,
'nginx_https' : 443,
}
config_string = template.render(template_variables)
print('Create nginx conf file %s' % ap_conf_file)
with open(ap_conf_file, 'wt') as dst_file:
dst_file.write(config_string)
return ap_conf_file
def install_nginx_service(local_repo):
print("Register nginx frontend")
#rights
mkdirs(os.path.join(WAPT.wapt_base_dir,'waptservice','nginx','temp'))
for repo_path in ('wapt','wapt-host','waptwua'):
p=makepath(local_repo,repo_path)
mkdirs(p)
run(r'icacls "%s" /grant "*S-1-5-20":(OI)(CI)(M)' % (p))
run(r'icacls "%s" /grant "*S-1-5-20":(OI)(CI)(M)' % (os.path.join(WAPT.wapt_base_dir,'waptservice','nginx','temp')))
run(r'icacls "%s" /grant "*S-1-5-20":(OI)(CI)(M)' % os.path.join(WAPT.wapt_base_dir,'waptservice','nginx','logs'))
run(r'icacls "%s" /grant "*S-1-5-20":(OI)(CI)(M)' % os.path.join(WAPT.wapt_base_dir,'log'))
make_nginx_config(local_repo)
service_binary = os.path.abspath(os.path.join(WAPT.wapt_base_dir,'waptservice','nginx','nginx.exe'))
service_parameters = ''
service_logfile = os.path.join(WAPT.wapt_base_dir,'waptservice','nginx','logs', 'nssm_nginx.log')
if service_installed(service_name) and service_is_running(service_name):
service_stop(service_name)
install_windows_nssm_service(service_binary,service_parameters,service_logfile)
time.sleep(5)
if service_installed(service_name) and not service_is_running(service_name):
service_start(service_name)
print('installing %s' % control.asrequirement())
print('Install nginx to permit WAPTAgent to become a repository')
local_repo = inifile_readstring(WAPT.config_filename,'repo-sync','local_repo_path') or makepath(WAPT.wapt_base_dir,'repository')
print('Create WAPTService directories for nginx')
for dirname in ('nginx','scripts'):
mkdirs(makepath(WAPT.wapt_base_dir,'waptservice',dirname))
for dirname in ('logs','conf'):
mkdirs(makepath(WAPT.wapt_base_dir,'waptservice','nginx',dirname))
print('Copy conf file for nginx')
copytree2('scripts',makepath(WAPT.wapt_base_dir,'waptservice','scripts'))
filecopyto('nginx.exe',makepath(WAPT.wapt_base_dir,'waptservice','nginx'))
filecopyto('scripts/mime.types',makepath(WAPT.wapt_base_dir,'waptservice','nginx','conf'))
print('Install nginx')
install_nginx_service(local_repo)
print('Add firewall rule for nginx')
run('netsh advfirewall firewall add rule name="%s" dir=in action=allow program="%s" enable=yes' %(service_name,makepath(WAPT.wapt_base_dir,'waptservice','nginx','nginx.exe')))
def uninstall():
nssm = os.path.join(WAPT.wapt_base_dir, 'waptservice', 'win64', 'nssm.exe')
print('uninstalling %s' % control.asrequirement())
cmd = '"{nssm}" remove "{service_name}" confirm'.format(
nssm=nssm,
service_name=service_name
)
if not service_is_stopped(service_name):
service_stop(service_name)
while not service_is_stopped(service_name):
time.sleep(2)
print('Remove service %s with nssm' % service_name)
run(cmd)
print('Remove firewall rule')
run('netsh advfirewall firewall delete rule name="%s" program="%s"' % (service_name,makepath(WAPT.wapt_base_dir,'waptservice','nginx','nginx.exe')))
print('Remove nginx files')
remove_tree(makepath(WAPT.wapt_base_dir,'waptservice','nginx'))
remove_file(makepath(WAPT.wapt_base_dir,'waptservice','scripts','mime.types'))
def session_setup():
print('Session setup for %s' % control.asrequirement())
# put here what to do when package is configured inside a user session
# implicit context variables are WAPT, control, user, params
def update_package():
print('Update package content from upstream binary sources')
try:
from BeautifulSoup import BeautifulSoup
except:
from bs4 import BeautifulSoup
import urllib2
import zipfile
from urlparse import urljoin
url = 'https://nginx.org/'
content=urllib2.urlopen(urllib2.Request(urljoin(url,'en/download.html'))).read()
soup = BeautifulSoup(content,'html.parser')
for h4 in soup.findAll('h4'):
if h4.getText()=='Stable version':
apath=h4.findNext().findAll('a')[3].get('href')
zip_url = urljoin(url,apath)
with open('zip_nginx','wb') as f:
f.write(urllib2.urlopen(zip_url).read())
f.close()
with zipfile.ZipFile('zip_nginx','r') as zip_file:
for afile in zip_file.filelist:
if afile.filename.endswith('nginx.exe'):
nginx_exe=zip_file.extract(afile)
filecopyto(nginx_exe,'nginx.exe')
remove_tree(os.path.abspath(os.path.join(nginx_exe, os.pardir)))
remove_file('zip_nginx')
def audit():
print('Auditing %s' % control.asrequirement())
# put here code to check periodically that state is matching expectations
# return "OK", "WARNING" or "ERROR" to report status in console.
# all print statement are reported too
return "OK"
if __name__ == '__main__':
update_package()