Beispiel #1
0
def build_waptupgrade_package(waptconfigfile,
                              target_directory=None,
                              wapt_server_user=None,
                              wapt_server_passwd=None,
                              key_password=None,
                              sign_digests=None):
    if target_directory is None:
        target_directory = tempfile.gettempdir()

    if not wapt_server_user:
        wapt_server_user = raw_input('WAPT Server user :'******'WAPT Server password :'******'ascii')

    wapt = common.Wapt(config_filename=waptconfigfile,
                       disable_update_server_status=True)
    wapt.dbpath = r':memory:'
    wapt.use_hostpackages = False

    if sign_digests is None:
        sign_digests = wapt.sign_digests

    if not wapt.personal_certificate_path or not os.path.isfile(
            wapt.personal_certificate_path):
        raise Exception(
            u'No personal certificate provided or not found (%s) for signing waptupgrade package'
            % wapt.personal_certificate_path)

    waptget = get_file_properties('wapt-get.exe')
    entry = PackageEntry(waptfile=makepath(wapt.wapt_base_dir, 'waptupgrade'))
    patchs_dir = makepath(entry.sourcespath, 'patchs')
    mkdirs(patchs_dir)
    filecopyto(makepath(wapt.wapt_base_dir, 'waptdeploy.exe'),
               makepath(patchs_dir, 'waptdeploy.exe'))

    entry.package = '%s-waptupgrade' % wapt.config.get(
        'global', 'default_package_prefix')
    rev = entry.version.split('-')[1]
    entry.version = '%s-%s' % (waptget['FileVersion'], rev)
    entry.inc_build()
    entry.save_control_to_wapt()
    entry.build_package(target_directory=target_directory)
    certs = wapt.personal_certificate()
    key = wapt.private_key(private_key_password=key_password)
    if not certs[0].is_code_signing:
        raise Exception(u'%s is not a code signing certificate' %
                        wapt.personal_certificate_path)
    entry.sign_package(private_key=key,
                       certificate=certs,
                       private_key_password=key_password,
                       mds=ensure_list(sign_digests))

    wapt.http_upload_package(entry.localpath,
                             wapt_server_user=wapt_server_user,
                             wapt_server_passwd=wapt_server_passwd)
    return entry.as_dict()
Beispiel #2
0
def build_waptupgrade_package(waptconfigfile,target_directory=None,wapt_server_user=None,wapt_server_passwd=None,key_password=None,sign_digests=None,priority='critical'):
    if target_directory is None:
        target_directory = tempfile.gettempdir()

    if not wapt_server_user:
        wapt_server_user = raw_input('WAPT Server user :'******'WAPT Server password :'******'ascii')

    wapt = common.Wapt(config_filename=waptconfigfile,disable_update_server_status=True)
    wapt.dbpath = r':memory:'
    wapt.use_hostpackages = False

    # try to get a progress hook inside waptconsole
    try:
        import waptconsole
        progress_hook = waptconsole.UpdateProgress
    except ImportError:
        def print_progress(show=False,n=0,max=100,msg=''):
            if show:
                print('%s %s/%s\r' % (msg,n,max),end='')
            else:
                if not msg:
                    msg='Done'
                print("%s%s"%(msg,' '*(80-len(msg))))
        progress_hook = print_progress

    wapt.progress_hook = progress_hook

    if sign_digests is None:
        sign_digests = wapt.sign_digests

    if not wapt.personal_certificate_path or not os.path.isfile(wapt.personal_certificate_path):
        raise Exception(u'No personal certificate provided or not found (%s) for signing waptupgrade package' % wapt.personal_certificate_path)

    waptget = get_file_properties('wapt-get.exe')
    entry = PackageEntry(waptfile = makepath(wapt.wapt_base_dir,'waptupgrade'))
    patchs_dir = makepath(entry.sourcespath,'patchs')
    mkdirs(patchs_dir)
    filecopyto(makepath(wapt.wapt_base_dir,'waptdeploy.exe'),makepath(patchs_dir,'waptdeploy.exe'))

    entry.package = '%s-waptupgrade' % wapt.config.get('global','default_package_prefix')
    rev = entry.version.split('-')[1]
    entry.version = '%s-%s' % (waptget['FileVersion'],rev)
    entry.inc_build()
    entry.save_control_to_wapt()
    entry.build_package(target_directory=target_directory)
    entry.priority = priority
    certs = wapt.personal_certificate()
    key = wapt.private_key(private_key_password=key_password)
    if not certs[0].is_code_signing:
        raise Exception(u'%s is not a code signing certificate' % wapt.personal_certificate_path)
    entry.sign_package(private_key=key,certificate = certs,private_key_password=key_password,mds = ensure_list(sign_digests))

    wapt.http_upload_package(entry.localpath,wapt_server_user=wapt_server_user,wapt_server_passwd=wapt_server_passwd,progress_hook=progress_hook)
    return entry.as_dict()
Beispiel #3
0
def install_postgresql_service(options, conf=None):
    if conf is None:
        conf = waptserver.config.load_config(options.configfile)
    print("install postgres database")

    pgsql_root_dir = r'%s\waptserver\pgsql-9.6' % wapt_root_dir
    pgsql_data_dir = r'%s\waptserver\pgsql_data-9.6' % wapt_root_dir
    pgsql_data_dir = pgsql_data_dir.replace('\\', '/')

    print("build database directory")
    if not os.path.exists(os.path.join(pgsql_data_dir, 'postgresql.conf')):
        setuphelpers.mkdirs(pgsql_data_dir)

        # need to have specific write acls for current user otherwise initdb fails...
        setuphelpers.run(r'icacls "%s" /t /grant  "%s":(OI)(CI)(M)' %
                         (pgsql_data_dir, GetUserName()))

        setuphelpers.run(r'"%s\bin\initdb" -U postgres -E=UTF8 -D "%s"' %
                         (pgsql_root_dir, pgsql_data_dir))
        setuphelpers.run(r'icacls "%s" /t /grant  "*S-1-5-20":(OI)(CI)(M)' %
                         pgsql_data_dir)

        print("start postgresql database")

        if setuphelpers.service_installed('WaptPostgresql'):
            if setuphelpers.service_is_running('WaptPostgresql'):
                setuphelpers.service_stop('waptPostgresql')
            setuphelpers.service_delete('waptPostgresql')

        cmd = r'"%s\bin\pg_ctl" register -N WAPTPostgresql -U "nt authority\networkservice" -S auto -D "%s"  ' % (
            pgsql_root_dir, pgsql_data_dir)
        print cmd
        run(cmd)
        setuphelpers.run(r'icacls "%s" /grant  "*S-1-5-20":(OI)(CI)(M)' %
                         log_directory)
        setuphelpers.run(r'icacls "%s" /grant  "*S-1-5-20":(OI)(CI)(M)' %
                         pgsql_data_dir)
    else:
        print("database already instanciated, doing nothing")

    # try to migrate from old version (pg 9.4, wapt 1.5)
    old_pgsql_root_dir = r'%s\waptserver\pgsql' % wapt_root_dir
    old_pgsql_data_dir = r'%s\waptserver\pgsql_data' % wapt_root_dir
    old_pgsql_data_dir = old_pgsql_data_dir.replace('\\', '/')

    if os.path.isdir(old_pgsql_data_dir) and os.path.isdir(old_pgsql_root_dir):
        print('migrating database from previous postgresql DB')
        migrate_pg_db(old_pgsql_root_dir, old_pgsql_data_dir, pgsql_root_dir,
                      pgsql_data_dir)

    print('starting postgresql')
    if not setuphelpers.service_is_running('waptpostgresql'):
        setuphelpers.service_start('waptpostgresql')
        # waiting for postgres to be ready
        time.sleep(2)

    print("creating wapt database")
    import psycopg2
    from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
    conn = None
    cur = None
    try:
        conn = psycopg2.connect('dbname=template1 user=postgres')
        conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
        cur = conn.cursor()
        cur.execute("select 1 from pg_roles where rolname='%(db_user)s'" %
                    conf)
        val = cur.fetchone()
        if val is None:
            print(
                "%(db_user)s pgsql user does not exists, creating %(db_user)s user"
                % conf)
            cur.execute("create user %(db_user)s" % conf)

        cur.execute("select 1 from pg_database where datname='%(db_name)s'" %
                    conf)
        val = cur.fetchone()
        if val is None:
            print(
                "database %(db_name)s does not exists, creating %(db_name)s db"
                % conf)
            cur.execute("create database %(db_name)s owner %(db_user)s" % conf)

    finally:
        if cur:
            cur.close()
        if conn:
            conn.close()

    print("Creating/upgrading wapt tables")
    run(r'"%s\waptpython.exe" "%s\waptserver\model.py" init_db -c "%s"' %
        (wapt_root_dir, wapt_root_dir, options.configfile))
    print("Done")

    print('Import lcoal Packages data into database')

    repo = WaptLocalRepo(conf['wapt_folder'])
    load_db_config(conf)
    Packages.update_from_repo(repo)
Beispiel #4
0
def make_nginx_config(wapt_root_dir, wapt_folder, force=False):
    """Create a nginx default config file to server wapt_folder and reverse proxy waptserver
    Create a key and self signed certificate.

    Args:
        wapt_root_dir (str)
        wapt_folder (str) : local path to wapt rdirectory for packages
                             wapt-host and waptwua are derived from this.

    Returns:
        str: path to nginx conf file
    """

    ap_conf_dir = os.path.join(wapt_root_dir, 'waptserver', '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_root_dir, 'waptserver', 'nginx', 'ssl')

    if os.path.isfile(ap_conf_file) and not force:
        if 'waptserver' in open(ap_conf_file, 'r').read():
            return ap_conf_file

    setuphelpers.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 != 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=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=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_root_dir, 'waptserver', 'scripts')))
    template = jinja_env.get_template('waptwindows.nginxconfig.j2')
    template_variables = {
        'wapt_repository_path':
        os.path.dirname(conf['wapt_folder']).replace('\\', '/'),
        'waptserver_port':
        conf['waptserver_port'],
        'windows':
        True,
        'ssl':
        True,
        'force_https':
        False,
        'use_kerberos':
        False,
        'wapt_ssl_key_file':
        key_fn.replace('\\', '/'),
        'wapt_ssl_cert_file':
        cert_fn.replace('\\', '/'),
        'log_dir':
        os.path.join(wapt_root_dir, 'waptserver', 'nginx',
                     'logs').replace('\\', '/'),
        'wapt_root_dir':
        wapt_root_dir.replace('\\', '/'),
        'nginx_http':
        conf['nginx_http'],
        'nginx_https':
        conf['nginx_https']
    }

    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
Beispiel #5
0
def build_waptupgrade_package(wapt,
                              mainrepo,
                              sources_directory=None,
                              target_directory=None,
                              wapt_server_user=None,
                              wapt_server_passwd=None,
                              key_password=None,
                              sign_digests=None,
                              priority='critical'):
    if target_directory is None:
        target_directory = tempfile.gettempdir()

    if not wapt_server_user:
        wapt_server_user = raw_input('WAPT Server user :'******'WAPT Server password :'******'ascii')

    if sign_digests is None:
        sign_digests = wapt.sign_digests

    if not wapt.personal_certificate_path or not os.path.isfile(
            wapt.personal_certificate_path):
        raise Exception(
            u'No personal certificate provided or not found (%s) for signing waptupgrade package'
            % wapt.personal_certificate_path)

    waptget = get_file_properties('wapt-get.exe')
    if sources_directory is None:
        sources_directory = makepath(wapt.wapt_base_dir, 'waptupgrade')
    entry = PackageEntry(waptfile=sources_directory)
    patchs_dir = makepath(entry.sourcespath, 'patchs')
    mkdirs(patchs_dir)
    filecopyto(makepath(wapt.wapt_base_dir, 'waptdeploy.exe'),
               makepath(patchs_dir, 'waptdeploy.exe'))
    mainrepo.update()
    entry.package = '%s-waptupgrade' % wapt.config.get(
        'global', 'default_package_prefix')
    existing = mainrepo.packages_matching(PackageRequest(entry.package))
    if existing:
        rev = sorted(existing)[-1].version.split('-')[1]
    else:
        rev = entry.version.split('-')[1]
    entry.version = '%s-%s' % (waptget['FileVersion'], rev)
    entry.inc_build()
    entry.priority = priority
    entry.save_control_to_wapt()
    entry.build_package(target_directory=target_directory)
    certs = wapt.personal_certificate()
    key = wapt.private_key(private_key_password=key_password)
    if not certs[0].is_code_signing:
        raise Exception(u'%s is not a code signing certificate' %
                        wapt.personal_certificate_path)
    entry.sign_package(private_key=key,
                       certificate=certs,
                       private_key_password=key_password,
                       mds=ensure_list(sign_digests))

    wapt.http_upload_package(entry.localpath,
                             wapt_server_user=wapt_server_user,
                             wapt_server_passwd=wapt_server_passwd,
                             progress_hook=wapt.progress_hook)
    mainrepo.update()
    return entry.as_dict()
Beispiel #6
0
def install_postgresql_service(options,conf=None):
    if conf is None:
        conf = waptserver.config.load_config(options.configfile)
    print ("install postgres database")

    pgsql_root_dir = r'%s\waptserver\pgsql-9.6' % wapt_root_dir
    pgsql_data_dir = r'%s\waptserver\pgsql_data-9.6' % wapt_root_dir
    pgsql_data_dir = pgsql_data_dir.replace('\\','/')


    print ("about to build database directory")
    if setuphelpers.service_installed('waptpostgresql') and setuphelpers.service_is_running('waptpostgresql'):
        print('stopping postgresql')
        setuphelpers.service_stop('waptpostgresql')
        # waiting for postgres to be ready
        time.sleep(2)

    if not os.path.exists(os.path.join(pgsql_data_dir,'postgresql.conf')):
        setuphelpers.mkdirs(pgsql_data_dir)

        # need to have specific write acls for current user otherwise initdb fails...
        setuphelpers.run(r'icacls "%s" /t /grant  "%s":(OI)(CI)(M)' % (pgsql_data_dir,GetUserName()))

        setuphelpers.run(r'"%s\bin\initdb" -U postgres -E=UTF8 -D "%s"' % (pgsql_root_dir,pgsql_data_dir))
        setuphelpers.run(r'icacls "%s" /t /grant  "*S-1-5-20":(OI)(CI)(M)' % pgsql_data_dir)
    else:
        print("database already instanciated, doing nothing")

    print("start postgresql database")

    if setuphelpers.service_installed('WaptPostgresql'):
        if setuphelpers.service_is_running('WaptPostgresql'):
            setuphelpers.service_stop('waptPostgresql')
        setuphelpers.service_delete('waptPostgresql')

    cmd = r'"%s\bin\pg_ctl" register -N WAPTPostgresql -U "nt authority\networkservice" -S auto -D "%s"  ' % (pgsql_root_dir ,pgsql_data_dir)
    run(cmd)
    setuphelpers.run(r'icacls "%s" /grant  "*S-1-5-20":(OI)(CI)(M)' % log_directory)
    setuphelpers.run(r'icacls "%s" /grant  "*S-1-5-20":(OI)(CI)(M)' % pgsql_data_dir)

    # try to migrate from old version (pg 9.4, wapt 1.5)
    old_pgsql_root_dir = r'%s\waptserver\pgsql' % wapt_root_dir
    old_pgsql_data_dir = r'%s\waptserver\pgsql_data' % wapt_root_dir
    old_pgsql_data_dir = old_pgsql_data_dir.replace('\\','/')

    if os.path.isdir(old_pgsql_data_dir) and os.path.isdir(old_pgsql_root_dir):
        print('migrating database from previous postgresql DB')
        migrate_pg_db(old_pgsql_root_dir,old_pgsql_data_dir,pgsql_root_dir,pgsql_data_dir)

    print('starting postgresql')
    if not setuphelpers.service_is_running('waptpostgresql'):
        setuphelpers.service_start('waptpostgresql')
        # waiting for postgres to be ready
        time.sleep(2)

    print("checking wapt database")
    import psycopg2
    from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
    conn = None
    cur = None
    try:
        conn = psycopg2.connect('dbname=template1 user=postgres')
        conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
        cur = conn.cursor()
        cur.execute("select 1 from pg_roles where rolname='%(db_user)s'" % conf)
        val = cur.fetchone()
        if val is None:
            print("%(db_user)s pgsql user does not exists, creating %(db_user)s user" % conf)
            cur.execute("create user %(db_user)s" % conf)

        cur.execute("select 1 from pg_database where datname='%(db_name)s'" % conf)
        val = cur.fetchone()
        if val is None:
            print ("database %(db_name)s does not exists, creating %(db_name)s db" % conf)
            cur.execute("create database %(db_name)s owner %(db_user)s" % conf)

    finally:
        if cur:
            cur.close()
        if conn:
            conn.close()

    print("Creating/upgrading wapt db tables")
    run(r'"%s\waptpython.exe" "%s\waptserver\model.py" init_db -c "%s"' % (wapt_root_dir, wapt_root_dir, options.configfile ))
    print("Done")

    print('Import lcoal Packages data into database')

    repo = WaptLocalRepo(conf['wapt_folder'])
    load_db_config(conf)
    Packages.update_from_repo(repo)
Beispiel #7
0
def make_nginx_config(wapt_root_dir, wapt_folder, force = False):
    """Create a nginx default config file to server wapt_folder and reverse proxy waptserver
    Create a key and self signed certificate.

    Args:
        wapt_root_dir (str)
        wapt_folder (str) : local path to wapt rdirectory for packages
                             wapt-host and waptwua are derived from this.

    Returns:
        str: path to nginx conf file
    """

    ap_conf_dir = os.path.join(
        wapt_root_dir,
        'waptserver',
        '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_root_dir,'waptserver','nginx','ssl')

    if os.path.isfile(ap_conf_file) and not force:
        if 'waptserver' in open(ap_conf_file,'r').read():
            return ap_conf_file

    setuphelpers.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 != 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=fqdn(),dnsname=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=fqdn(),dnsname=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_root_dir,'waptserver','scripts')))
    template = jinja_env.get_template('waptwindows.nginxconfig.j2')
    template_variables = {
        'wapt_repository_path': os.path.dirname(conf['wapt_folder']).replace('\\','/'),
        'waptserver_port': conf['waptserver_port'],
        'windows': True,
        'ssl': True,
        'force_https': False,
        'use_kerberos': False,
        'wapt_ssl_key_file': key_fn.replace('\\','/'),
        'wapt_ssl_cert_file': cert_fn.replace('\\','/'),
        'log_dir': os.path.join(wapt_root_dir,'waptserver','nginx','logs').replace('\\','/'),
        'wapt_root_dir' : wapt_root_dir.replace('\\','/'),
        'nginx_http'  : conf['nginx_http'],
        'nginx_https' : conf['nginx_https'],
        'clients_signing_certificate' : conf.get('clients_signing_certificate') and conf.get('clients_signing_certificate').replace('\\','/'),
        'use_ssl_client_auth' : conf.get('use_ssl_client_auth',False)
    }

    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
Beispiel #8
0
def install_postgresql_service():
    print("install postgres database")

    pgsql_root_dir = r'%s\waptserver\pgsql' % wapt_root_dir
    pgsql_data_dir = r'%s\waptserver\pgsql_data' % wapt_root_dir
    pgsql_data_dir = pgsql_data_dir.replace('\\', '/')

    print("build database directory")
    if os.path.exists(os.path.join(pgsql_data_dir, 'postgresql.conf')):
        print("database already instanciated, doing nothing")
        # TODO: check that database is fully working and up to date
        # TODO: add a force option
        return

    print("init pgsql data directory")
    pg_data_dir = os.path.join(wapt_root_dir, 'waptserver', 'pgsql_data')

    setuphelpers.mkdirs(pg_data_dir)

    # need to have specific write acls for current user otherwise initdb fails...
    setuphelpers.run(r'icacls "%s" /t /grant  "%s":(OI)(CI)(M)' %
                     (pg_data_dir, GetUserName()))
    setuphelpers.run(
        r'"%s\waptserver\pgsql\bin\initdb" -U postgres -E=UTF8 -D "%s\waptserver\pgsql_data"'
        % (wapt_root_dir, wapt_root_dir))

    setuphelpers.run(r'icacls "%s" /t /grant  "*S-1-5-20":(OI)(CI)(M)' %
                     pg_data_dir)

    print("start postgresql database")

    if setuphelpers.service_installed('WaptPostgresql'):
        if setuphelpers.service_is_running('WaptPostgresql'):
            setuphelpers.service_stop('waptPostgresql')
        setuphelpers.service_delete('waptPostgresql')

    cmd = r'"%s\bin\pg_ctl" register -N WAPTPostgresql -U "nt authority\networkservice" -S auto -D "%s"  ' % (
        pgsql_root_dir, os.path.join(wapt_root_dir, 'waptserver',
                                     'pgsql_data'))
    print cmd
    run(cmd)
    setuphelpers.run(r'icacls "%s" /grant  "*S-1-5-20":(OI)(CI)(M)' %
                     log_directory)
    setuphelpers.run(r'icacls "%s" /grant  "*S-1-5-20":(OI)(CI)(M)' %
                     pgsql_data_dir)

    print('starting postgresql')
    run('net start waptpostgresql')

    #cmd = r"%s\bin\pg_ctl.exe -D %s start" % (pgsql_root_dir, pgsql_data_dir)
    #devnull = open(os.devnull,'wb')
    #print(subprocess.Popen(cmd,shell=True))

    # waiting for postgres to be ready
    time.sleep(1)

    print("creating wapt database")
    import psycopg2
    from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
    conn = psycopg2.connect('dbname=template1 user=postgres')
    conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
    cur = conn.cursor()
    cur.execute("select 1 from pg_roles where rolname='wapt'")
    val = cur.fetchone()
    if val != 1:
        print("wapt pgsql user does not exists, creating wapt user")
        cur.execute("create user wapt")
    val = cur.execute("select 1 from pg_database where datname='wapt'")
    if val != 1:
        print("database wapt does not exists, creating wapt db")
        cur.execute(r"create extension hstore")
        cur.execute("create database wapt owner wapt")
    cur.close()
    conn.close()

    run(r'"%s\waptpython.exe" "%s\waptserver\waptserver_model.py" init_db' %
        (wapt_root_dir, wapt_root_dir))
    time.sleep(1)
    setuphelpers.service_stop('waptpostgresql')
Beispiel #9
0
def make_nginx_config(wapt_root_dir, wapt_folder):

    if conf['wapt_folder'].endswith('\\') or conf['wapt_folder'].endswith('/'):
        conf['wapt_folder'] = conf['wapt_folder'][:-1]

    ap_conf_dir = os.path.join(wapt_root_dir, 'waptserver', '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_root_dir, 'waptserver', 'nginx', 'ssl')

    setuphelpers.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 != 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=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=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_root_dir, 'waptserver', 'scripts')))
    template = jinja_env.get_template('waptwindows.nginxconfig.j2')
    template_variables = {
        'wapt_repository_path':
        os.path.dirname(conf['wapt_folder']).replace('\\', '/'),
        'windows':
        True,
        'ssl':
        True,
        'force_https':
        False,
        'use_kerberos':
        False,
        'wapt_ssl_key_file':
        key_fn.replace('\\', '/'),
        'wapt_ssl_cert_file':
        cert_fn.replace('\\', '/'),
        'log_dir':
        os.path.join(wapt_root_dir, 'waptserver', 'nginx',
                     'logs').replace('\\', '/'),
        'wapt_root_dir':
        wapt_root_dir.replace('\\', '/'),
    }

    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)