Exemplo n.º 1
0
def main(args):
    call('/scripts/create_data_links.sh')
    check_upgrade()
    os.chdir(installdir)
    call('service nginx start &')

    admin_pw = {
        'email': get_conf('SEAFILE_ADMIN_EMAIL', '*****@*****.**'),
        'password': get_conf('SEAFILE_ADMIN_PASSWORD', 'asecret'),
    }
    password_file = join(topdir, 'conf', 'admin.txt')
    with open(password_file, 'w+') as fp:
        json.dump(admin_pw, fp)


    try:
        call('{} start'.format(get_script('seafile.sh')))
        call('{} start'.format(get_script('seahub.sh')))
        if args.mode == 'backend':
            call('{} start'.format(get_script('seafile-background-tasks.sh')))
    finally:
        if exists(password_file):
            os.unlink(password_file)

    print 'seafile server is running now.'
    try:
        watch_controller()
    except KeyboardInterrupt:
        print 'Stopping seafile server.'
        sys.exit(0)
Exemplo n.º 2
0
def main():
    if not exists(shared_seafiledir):
        os.mkdir(shared_seafiledir)
    if not exists(generated_dir):
        os.makedirs(generated_dir)

    check_upgrade()
    os.chdir(installdir)

    admin_pw = {
        'email': get_conf('SEAFILE_ADMIN_EMAIL', '*****@*****.**'),
        'password': get_conf('SEAFILE_ADMIN_PASSWORD', 'asecret'),
    }
    password_file = join(topdir, 'conf', 'admin.txt')
    with open(password_file, 'w') as fp:
        json.dump(admin_pw, fp)

    try:
        call('{} start'.format(get_script('seafile.sh')))
        call('{} start'.format(get_script('seahub.sh')))
    finally:
        if exists(password_file):
            os.unlink(password_file)

    print 'seafile server is running now.'
    try:
        watch_controller()
    except KeyboardInterrupt:
        print 'Stopping seafile server.'
        sys.exit(0)
Exemplo n.º 3
0
def init_seafile_server():
    version_stamp_file = get_version_stamp_file()
    if exists(join(shared_seafiledir, 'seafile-data')):
        if not exists(version_stamp_file):
            update_version_stamp(os.environ['SEAFILE_VERSION'])
        # sysbol link unlink after docker finish.
        latest_version_dir='/opt/seafile/seafile-server-latest'
        current_version_dir='/opt/seafile/' + get_conf('SEAFILE_SERVER', 'seafile-server') + '-' +  read_version_stamp()
        if not exists(latest_version_dir):
            call('ln -sf ' + current_version_dir + ' ' + latest_version_dir)
        loginfo('Skip running setup-seafile-mysql.py because there is existing seafile-data folder.')
        return

    loginfo('Now running setup-seafile-mysql.py in auto mode.')
    env = {
        'SERVER_NAME': 'seafile',
        'SERVER_IP': get_conf('SEAFILE_SERVER_HOSTNAME', 'seafile.example.com'),
        'MYSQL_USER': '******',
        'MYSQL_USER_PASSWD': str(uuid.uuid4()),
        'MYSQL_USER_HOST': '127.0.0.1',
        # Default MariaDB root user has empty password and can only connect from localhost.
        'MYSQL_ROOT_PASSWD': '',
    }

    # Change the script to allow mysql root password to be empty
    call('''sed -i -e 's/if not mysql_root_passwd/if not mysql_root_passwd and "MYSQL_ROOT_PASSWD" not in os.environ/g' {}'''
         .format(get_script('setup-seafile-mysql.py')))

    setup_script = get_script('setup-seafile-mysql.sh')
    call('{} auto -n seafile'.format(setup_script), env=env)

    domain = get_conf('SEAFILE_SERVER_HOSTNAME', 'seafile.example.com')
    proto = 'https' if is_https() else 'http'
    with open(join(topdir, 'conf', 'seahub_settings.py'), 'a+') as fp:
        fp.write('\n')
        fp.write('FILE_SERVER_ROOT = "{proto}://{domain}/seafhttp"'.format(proto=proto, domain=domain))
        fp.write('\n')

    # By default ccnet-server binds to the unix socket file
    # "/opt/seafile/ccnet/ccnet.sock", but /opt/seafile/ccnet/ is a mounted
    # volume from the docker host, and on windows and some linux environment
    # it's not possible to create unix sockets in an external-mounted
    # directories. So we change the unix socket file path to
    # "/opt/seafile/ccnet.sock" to avoid this problem.
    with open(join(topdir, 'conf', 'ccnet.conf'), 'a+') as fp:
        fp.write('\n')
        fp.write('[Client]\n')
        fp.write('UNIX_SOCKET = /opt/seafile/ccnet.sock\n')
        fp.write('\n')

    files_to_copy = ['conf', 'ccnet', 'seafile-data', 'seahub-data', 'pro-data']
    for fn in files_to_copy:
        src = join(topdir, fn)
        dst = join(shared_seafiledir, fn)
        if not exists(dst) and exists(src):
            shutil.move(src, shared_seafiledir)
            call('ln -sf ' + join(shared_seafiledir, fn) + ' ' + src)

    loginfo('Updating version stamp')
    update_version_stamp(os.environ['SEAFILE_VERSION'])
Exemplo n.º 4
0
def from_environment():
    domain = get_conf('SEAFILE_SERVER_HOSTNAME', 'seafile.example.com')
    env = {
        'SERVER_NAME': 'seafile',
        'SERVER_IP': domain,
        'DOMAIN': domain,
        'MYSQL_USER': get_conf('DB_USER', 'seafile'),
        'MYSQL_USER_PASSWD': get_conf('DB_PASSWD', str(uuid.uuid4())),
        'MYSQL_USER_HOST': '%.%.%.%',
        'MYSQL_HOST': get_conf('DB_HOST', '127.0.0.1'),
        # Default MariaDB root user has empty password and can only connect from localhost.
        'MYSQL_ROOT_PASSWD': get_conf('DB_ROOT_PASSWD', ''),
        'MEMCACHED_HOST': get_conf('MEMCACHED_HOST', 'memcached'),
        'MEMCACHED_PORT': get_conf('MEMCACHED_PORT', '11211'),
        'TIME_ZONE': get_conf('TIME_ZONE', 'Etc/UTC'),
        'USE_EXISTING_DB': get_conf_bool('USE_EXISTING_DB')
    }

    for k in [
            'USE_EXISTING_DB', 'CCNET_DB', 'SEAHUB_DB', 'SEAFILE_DB',
            'ENABLE_WEBDAV'
    ]:
        v = get_conf(k, None)
        if v is not None:
            env[k] = v
    return env
Exemplo n.º 5
0
def generate_local_nginx_conf():
    # Now create the final nginx configuratin
    domain = get_conf('SEAFILE_SERVER_HOSTNAME', 'seafile.example.com')
    http_port = get_conf('SEAFILE_SERVER_HTTP_PORT', '80')
    https_port = get_conf('SEAFILE_SERVER_HTTPS_PORT', '443')
    context = {
        'https': is_https(),
        'domain': domain,
        'http_port': http_port,
        'https_port': https_port,
    }
    render_template('/templates/seafile.nginx.conf.template',
                    '/etc/nginx/sites-enabled/seafile.nginx.conf', context)
Exemplo n.º 6
0
def generate_local_nginx_conf():
    custom = get_conf('SEAFILE_SERVER_NGINX_CONF_CUSTOM', 'false')

    if custom:
        return

    # Now create the final nginx configuration
    domain = get_conf('SEAFILE_SERVER_HOSTNAME', 'seafile.example.com')
    context = {
        'https': is_https(),
        'domain': domain,
    }
    render_template('/templates/seafile.nginx.conf.template',
                    '/etc/nginx/sites-enabled/seafile.nginx.conf', context)
Exemplo n.º 7
0
def try_connection():
    try:
        mysql.connector.connect(
            host=get_conf("mysql_creds")["host"][get_conf("ENV")],
            user=get_conf("mysql_creds")["user"],
            password=get_conf("mysql_creds")["password"],
            database=get_conf("mysql_creds")["database"],
            charset='utf8mb4',
            use_unicode=True)
        print("Connected")
    except Exception as err:
        print("Retry in 1 sec. err: {}".format(err))
        time.sleep(1)
        try_connection()
Exemplo n.º 8
0
def main():
    conf = utils.get_conf()

    host = conf["bottle"]["host"]
    port = conf["bottle"]["port"]
    route_statics = conf["bottle"]["route_statics"]
    statics_path = conf["bottle"]["statics_path"]
    video_paths = conf["bottle"]["video_paths"]

    app = Bottle()

    if route_statics is True:
        @app.route('/static/<filepath:path>')
        def server_static(filepath):
            return static_file(filepath, root=statics_path)

    @app.route('/')
    def index():
        return "Hello World!"

    @app.route('/videos')
    @view('views/videos.tpl')
    def videos():
        tpl_vars = dict()
        tpl_vars["video_paths"] = video_paths
        return tpl_vars

    return app, host, port
Exemplo n.º 9
0
def remove_cluster():
    data = utils.get_conf(dir + config_path)
    host_bl = data["storage"]["hostPath"]
    host_path = data["storage"]["pathDir"]
    os.system("chmod +x " + dir + "/remove-es.sh")
    pvc_list = os.popen(
        "/root/local/bin/kubectl get pvc --namespace=kube-efk | grep elasticsearch | awk '{print $3}'"
    ).readlines()
    arg = ""
    try:
        if (sys.argv[1] == "stop"):
            print("Keep data")
            arg = "stop"
    except:
        print("Remove all")
    if host_bl == "true":
        print("hostPath: " + str(host_path))
        remove_result = call_shell("sh " + dir + "/remove-es-hostpath.sh " +
                                   str(host_path))
    else:
        remove_result = call_shell("sh " + dir + "/remove-es.sh " +
                                   str(host_path))
    print("Message: " + str(remove_result["message"]))
    print("Remove_result is " + str(remove_result["code"]))
    if remove_result["code"] == 0:
        print("Remove es successfully!")
        return 0
    print("Failed to remove es")
    return 1
Exemplo n.º 10
0
 def __init__(self):
     super(Generator, self).__init__()
     self.cfg = get_conf("conf/model/generator")
     self.gen = nn.Sequential(
         # input is Z, going into a convolution
         nn.utils.spectral_norm(nn.ConvTranspose2d(self.cfg.nz, self.cfg.ngf * 8, 4, 1, 0, bias=False)),
         nn.ReLU(True),
         nn.BatchNorm2d(self.cfg.ngf * 8),
         # state size. (ngf*8) x 4 x 4
         nn.utils.spectral_norm(nn.ConvTranspose2d(self.cfg.ngf * 8, self.cfg.ngf * 4, 4, 2, 1, bias=False)),
         nn.ReLU(True),
         nn.BatchNorm2d(self.cfg.ngf * 4),
         # state size. (ngf*4) x 8 x 8
         nn.utils.spectral_norm(nn.ConvTranspose2d(self.cfg.ngf * 4, self.cfg.ngf * 2, 4, 2, 1, bias=False)),
         nn.ReLU(True),
         nn.BatchNorm2d(self.cfg.ngf * 2),
         # state size. (ngf*2) x 16 x 16
         nn.utils.spectral_norm(nn.ConvTranspose2d(self.cfg.ngf * 2, self.cfg.ngf, 4, 2, 1, bias=False)),
         nn.ReLU(True),
         nn.BatchNorm2d(self.cfg.ngf),
         # state size. (ngf) x 32 x 32
         nn.utils.spectral_norm(nn.ConvTranspose2d(self.cfg.ngf, self.cfg.nc, 4, 2, 1, bias=False)),
         nn.Tanh()
         # state size. (nc) x 64 x 64
     )
Exemplo n.º 11
0
def on_notify(params):
    conf = utils.get_conf()
    log_file_path = conf['log_file_path']
    state_file_path = conf['state_file_path']
    fp = open(log_file_path, 'a')
    strftime = time.strftime("%Y-%m-%d %H:%M:%S")

    ntype = params['ntype']
    if (ntype == "finished"):
        node_id = params["node_id"]
        task = params["task"]
        time_used = params["time_used"]

        update_state(task, "finished", state_file_path)
        fp.write("%s %s %s finished, time used: %s(s)\n" %
                 (strftime, node_id, task, time_used))
    elif (ntype in ["pending", "terminated"]):
        node_id = params["node_id"]
        task = params["task"]

        update_state(task, ntype, state_file_path)
        fp.write("%s %s %s %s\n" % (strftime, node_id, task, ntype))
    else:
        return False

    fp.close()
    return True
Exemplo n.º 12
0
 def _IsNewPC(self):
     if sys.platform == 'win32':
         cur_name = md5(os.environ['COMPUTERNAME'])
         store_name = get_conf('perm', 'flag')
         if cur_name != store_name:
             clear_conf('db')
             set_conf('perm', 'flag', cur_name)
Exemplo n.º 13
0
def main():
    logdbg("Starting seafile container ...")
    if not exists(shared_seafiledir):
        os.mkdir(shared_seafiledir)
    if not exists(generated_dir):
        os.makedirs(generated_dir)

    if is_https():
        logdbg("Initializing letsencrypt ...")
        init_letsencrypt()
    
    logdbg("Generating nginx config ...")
    generate_local_nginx_conf()
    logdbg("Reloading nginx ...")
    call('nginx -s reload')


    logdbg("Waiting for mysql server ...")
    wait_for_mysql()
    init_seafile_server()

    check_upgrade()
    os.chdir(installdir)

    admin_pw = {
        'email': get_conf('SEAFILE_ADMIN_EMAIL', '*****@*****.**'),
        'password': get_conf('SEAFILE_ADMIN_PASSWORD', 'asecret'),
    }
    password_file = join(topdir, 'conf', 'admin.txt')
    with open(password_file, 'w') as fp:
        json.dump(admin_pw, fp)


    try:
        call('{} start'.format(get_script('seafile.sh')))
        call('{} start'.format(get_script('seahub.sh')))
    finally:
        if exists(password_file):
            os.unlink(password_file)

    loginfo("Seafile server is running now.")
    try:
        watch_controller()
    except KeyboardInterrupt:
        loginfo("Stopping seafile server.")
        sys.exit(0)
Exemplo n.º 14
0
def generate_local_dockerfile():
    loginfo('Generating local Dockerfile ...')
    context = {
        'seafile_version': seafile_version,
        'https': is_https(),
        'domain': get_conf('server.domain'),
    }
    render_template('/templates/Dockerfile.template', join(generated_dir, 'Dockerfile'), context)
Exemplo n.º 15
0
def generate_local_nginx_conf():
    # Now create the final nginx configuratin
    domain = get_conf('server.hostname')
    context = {
        'https': is_https(),
        'domain': domain,
    }
    render_template('/templates/seafile.nginx.conf.template',
                    '/etc/nginx/sites-enabled/seafile.nginx.conf', context)
Exemplo n.º 16
0
def generate_local_nginx_conf():
    # Now create the final nginx configuratin
    domain = get_conf('SEAFILE_SERVER_HOSTNAME', 'seafile.example.com')
    context = {
        'https': is_https(),
        'domain': domain,
    }
    render_template('/templates/seafile.nginx.conf.template',
                    '/etc/nginx/sites-enabled/default', context)
Exemplo n.º 17
0
def main():
    if not exists(shared_seafiledir):
        os.mkdir(shared_seafiledir)
    if not exists(generated_dir):
        os.makedirs(generated_dir)

    if listen_on_https():
        init_letsencrypt()

    utils.nginx.change_nginx_config()

    wait_for_mysql()
    init_seafile_server()

    check_upgrade()

    apply_code_fixes()
    update_settings()
    update_seafdav_config()

    os.chdir(installdir)

    admin_pw = {
        'email': get_conf('SEAFILE_ADMIN_EMAIL', '*****@*****.**'),
        'password': get_conf('SEAFILE_ADMIN_PASSWORD', 'asecret'),
    }
    password_file = join(topdir, 'conf', 'admin.txt')
    with open(password_file, 'w') as fp:
        json.dump(admin_pw, fp)

    try:
        call('{} start'.format(get_script('seafile.sh')))
        call('{} start'.format(get_script('seahub.sh')))
    finally:
        if exists(password_file):
            os.unlink(password_file)

    print 'seafile server is running now.'
    try:
        watch_controller()
    except KeyboardInterrupt:
        print 'Stopping seafile server.'
        sys.exit(0)
Exemplo n.º 18
0
def init_selfsigned():
    loginfo('Preparing for self signed ssl ...')
    wait_for_nginx()

    if not exists(ssl_dir):
        os.mkdir(ssl_dir)

    domain = get_conf('SEAFILE_SERVER_HOSTNAME', 'seafile.example.com')

    call('/scripts/ssl.selfsigned.sh {0} {1}'.format(ssl_dir, domain))
Exemplo n.º 19
0
def do_parse_ports():
    """
    Parse the server.port_mappings option and print docker command line port
    mapping flags like "-p 80:80 -p 443:443"
    """
    # conf is like '80:80,443:443'
    conf = get_conf('server.port_mappings', '').strip()
    if conf:
        sys.stdout.write(' '.join(['-p {}'.format(part.strip()) for part in conf.split(',')]))
        sys.stdout.flush()
Exemplo n.º 20
0
def produce_yaml():
    data = utils.get_conf(dir + config_path)
    es_data = data["elasticsearch"]
    node_ips = es_data["node_ips"]
    host_path = data["storage"]["hostPath"]
    print("node_ips:")
    print(node_ips)
    node_str = ""
    for node_ip in node_ips:
        ip = '"' + node_ip + '"'
        node_str = node_str + ip + ","
        print("node_str::::" + node_str)
        os.system("/root/local/bin/kubectl label node " + node_ip +
                  " es=elasticsearch --overwrite=true 2>&1")

    replicas = len(node_ips)
    storage_data = data["storage"]
    size = storage_data["size"]
    es_lines = []
    if str(host_path) == "true":
        es_yaml = open(dir + "/yaml/elasticsearch-hostpath-template.yaml", "r")
        path_dir = data["storage"]["pathDir"]
    elif str(host_path) == "false":
        es_yaml = open(dir + "/yaml/elasticsearch-template.yaml", "r")
    for line in es_yaml:
        if "replicas_num" in line:
            line = line.replace("replicas_num", str(replicas))
        elif "HOST_PATH_VALUE" in line:
            line = line.replace("HOST_PATH_VALUE", str(path_dir))
        elif "storage: 1Gi" in line:
            line = line.replace("1", str(size))
        es_lines.append(line)
    es_yaml.close()
    es_join = "".join(es_lines)
    elasticsearch_yaml = open(dir + "/yaml/elasticsearch.yaml", "w+")
    elasticsearch_yaml.write(es_join)
    elasticsearch_yaml.close()

    es_lines = []
    es_yml = open(dir + "/configmap/elasticsearch-template.yml", "r")
    for line in es_yml:
        if "[CLUSTER_IP]" in line:
            print("node_str: " + node_str)
            line = line.replace("CLUSTER_IP", node_str)
        elif "MASTER_NODES_VALUE" in line:
            master_nodes_num = int(replicas) / 2 + 1
            line = line.replace("MASTER_NODES_VALUE", str(master_nodes_num))
        elif "EXPECTED_NODES_VALUE" in line:
            line = line.replace("EXPECTED_NODES_VALUE", str(replicas))
        es_lines.append(line)
    es_yml.close()
    es_join = "".join(es_lines)
    elasticsearch_yml = open(dir + "/configmap/elasticsearch.yml", "w+")
    elasticsearch_yml.write(es_join)
    elasticsearch_yml.close()
Exemplo n.º 21
0
def generate_local_nginx_conf():
    # Now create the final nginx configuratin
    domain = get_conf('server.hostname')
    context = {
        'https': is_https(),
        'domain': domain,
    }
    render_template(
        '/templates/seafile.nginx.conf.template',
        join(generated_dir, 'seafile.nginx.conf'),
        context
    )
Exemplo n.º 22
0
    def __init__(self):
        config = utils.get_conf()

        manager_url = config["manager_url"]

        self.node_id = config["node"]["node_id"]
        self.node_key = config["node"]["node_key"]

        self.get_next_task_url = utils.url_join([manager_url, "get_next_task"])
        self.notify_task_state_url = utils.url_join(
            [manager_url, "notify_task_state"])
        self.auth_node_url = utils.url_join([manager_url, "auth_node"])
Exemplo n.º 23
0
def update_seafdav_config():
    f = os.path.join(topdir, 'conf', 'seafdav.conf')
    if os.path.exists(f):
        cp = ConfigParser.ConfigParser()
        cp.read(f)
        section_name = 'WEBDAV'
        cp.set(section_name, 'share_name', '/seafdav')
        cp.set(section_name, 'fastcgi', 'false')
        cp.set(section_name, 'port', '8080')
        cp.set(section_name, 'enabled', "true" if
               (get_conf('ENABLE_WEBDAV', '0') != '0') else "false")
        with open(f, "w") as fp:
            cp.write(fp)
Exemplo n.º 24
0
    def OnConfig(self, event):
        conf = utils.get_conf()

        dlg = wx.TextEntryDialog(self.pnl,
                                 'Token de acesso do bot:',
                                 "acesso",
                                 "",
                                 style=wx.OK)
        dlg.SetValue(conf['token'])
        dlg.ShowModal()

        conf['token'] = dlg.GetValue()
        utils.save_conf(conf)
        dlg.Destroy()
Exemplo n.º 25
0
def generate_seafevents_conf():
    user = get_conf('MYSQL_USER', 'root')
    passwd = get_conf('DB_ROOT_PASSWD', '')
    if user != 'root':
        passwd = get_conf('DB_USER_PASSWD', '123')
    host = get_conf('DB_HOST', '127.0.0.1')

    context = """
[DATABASE]
type=mysql
username=%s
password=%s
name=seahub_db
host=%s

[FILE HISTORY]
enabled = true
suffix=txt,pdf,md,doc,docs
""" % (user, passwd, host)
    with open(join(topdir, 'conf', 'seafevents.conf'), 'a+') as fp:
        fp.write('\n')
        fp.write(context)
        fp.write('\n')
Exemplo n.º 26
0
def main():
    admin_pw = {
        'email': get_conf('admin.email'),
        'password': get_conf('admin.password'),
    }
    password_file = join(topdir, 'conf', 'admin.txt')
    with open(password_file, 'w') as fp:
        json.dump(admin_pw, fp)

    wait_for_mysql()

    try:
        call('{} start'.format(get_script('seafile.sh')))
        call('{} start'.format(get_script('seahub.sh')))
    finally:
        if exists(password_file):
            os.unlink(password_file)

    print 'seafile server is running now.'
    try:
        watch_controller()
    except KeyboardInterrupt:
        print 'Stopping seafile server.'
        sys.exit(0)
Exemplo n.º 27
0
def generate_local_nginx_conf():
    # Now create the final nginx configuratin
    domain = get_conf('SEAFILE_SERVER_HOSTNAME', 'seafile.example.com')
    context = {
        'https': is_https(),
        'domain': domain,
    }

    if not os.path.isfile('/shared/nginx/conf/seafile.nginx.conf'):
        render_template('/templates/seafile.nginx.conf.template',
                        '/etc/nginx/sites-enabled/seafile.nginx.conf', context)
        nginx_etc_file = '/etc/nginx/sites-enabled/seafile.nginx.conf'
        nginx_shared_file = '/shared/nginx/conf/seafile.nginx.conf'
        call('mv {0} {1} && ln -sf {1} {0}'.format(nginx_etc_file,
                                                   nginx_shared_file))
Exemplo n.º 28
0
def auth_node(node_id, node_key):
    conf = utils.get_conf()
    secret_file_path = conf['secret_file_path']
    if not os.path.exists(secret_file_path):
        utils.log('no such file: ' + secret_file_path)
        return False
    fp = open(secret_file_path, 'r')
    for line in fp.readlines():
        f = line.strip().split()
        if (f[0] == node_id and f[1] == node_key):
            fp.close()
            return True

    fp.close()
    return False
Exemplo n.º 29
0
def anidex(file, subcat_id, lang_id, torrent_name):
    """
        Subir a anidex, por default subcat_id=1 lang_id=29

    """
    params = get_conf("anidex")
    if not torrent_name:
        name = os.path.basename(file).replace(".torrent", "")
        params.update({'torrent_name': name})
    success, resp = anidex_upload_file(file, subcat_id=subcat_id, 
                                       lang_id=lang_id, **params)
    if success:
        click.secho("anidex success {}".format(resp), fg="blue")
    else:
        click.secho("anidex FAILED {}".format(resp), fg="red")
Exemplo n.º 30
0
def init_letsencrypt():
    loginfo('Preparing for letsencrypt ...')
    wait_for_nginx()

    if not exists(ssl_dir):
        os.mkdir(ssl_dir)

    domain = get_conf('SEAFILE_SERVER_HOSTNAME', 'seafile.example.com')
    context = {
        'ssl_dir': ssl_dir,
        'domain': domain,
    }
    render_template('/templates/letsencrypt.cron.template',
                    join(generated_dir, 'letsencrypt.cron'), context)

    ssl_crt = '/shared/ssl/{}.crt'.format(domain)
    if exists(ssl_crt):
        loginfo('Found existing cert file {}'.format(ssl_crt))
        if cert_has_valid_days(ssl_crt, 30):
            loginfo(
                'Skip letsencrypt verification since we have a valid certificate'
            )
            if exists(join(ssl_dir, 'letsencrypt')):
                # Create a crontab to auto renew the cert for letsencrypt.
                call('/scripts/auto_renew_crt.sh {0} {1}'.format(
                    ssl_dir, domain))
            return

    loginfo('Starting letsencrypt verification')
    # Create a temporary nginx conf to start a server, which would accessed by letsencrypt
    context = {
        'https': False,
        'domain': domain,
    }
    if not os.path.isfile('/shared/nginx/conf/seafile.nginx.conf'):
        render_template('/templates/seafile.nginx.conf.template',
                        '/etc/nginx/sites-enabled/seafile.nginx.conf', context)

    call('nginx -s reload')
    time.sleep(2)

    call('/scripts/ssl.sh {0} {1}'.format(ssl_dir, domain))
    # if call('/scripts/ssl.sh {0} {1}'.format(ssl_dir, domain), check_call=False) != 0:
    #     eprint('Now waiting 1000s for postmortem')
    #     time.sleep(1000)
    #     sys.exit(1)

    call('/scripts/auto_renew_crt.sh {0} {1}'.format(ssl_dir, domain))
Exemplo n.º 31
0
Arquivo: nyaa.py Projeto: zodman/rilis
def upload_torrent(file):
    click.echo("upload to nyaa")
    u, p = _get_login()
    nyaa_cfg = get_conf("nyaa")
    info = nyaa_cfg.get("info")
    hidden = nyaa_cfg.get("hidden", False)
    filename = os.path.basename(file).replace(".torrent", "")
    desc = nyaa_cfg.get("description")
    category = nyaa_cfg.get("category", "1_3")
    remake = nyaa_cfg.get("remake", False)
    anonymous = nyaa_cfg.get("anonymous", False)
    data = {
        'category': category,
        'information': info,
        'description': desc,
        'name': filename,
        'remake': remake,
        'anonymous': anonymous,
        'hidden': hidden,
    }
    encoded_data = {'torrent_data': json.dumps(data)}
    f = open(file, "rb")
    files = {'torrent': f}
    res = requests.post(NYAA_DOMAIN + 'api/upload',
                        data=encoded_data,
                        files=files,
                        auth=(u, p))
    click.echo("upload nyaa status_code: {}".format(res.status_code))
    if "Upload failed" in str(res.content):
        click.secho("failed to nyaa upload", fg="red")
        click.echo(str(res.content))
        return

    if res.status_code != 200:
        click.secho("failed to upload nyaa status_code {}".format(
            res.status_code),
                    fg="red")
        errors = res.json()
        click.secho("{}".format(errors), fg="red")
        return
    elif res.status_code == 461:
        click.secho("Torrent exists on nyaa", fg="red")
        return
    else:
        id = res.json().get("id")
        click.secho("nyaa upload success https://nyaa.si/view/{}".format(id),
                    fg="blue")
        return id
Exemplo n.º 32
0
    def __init__(self, conf_file=""):
        """ init conf 
            TODO: flat to 'ins.attr'
        """
        
        conf = get_conf(conf_file)
        
        for item in conf["client"]:
            #print item
            setattr(self, item, conf["client"][item])    
            
        for item in conf["redis"]:
            #print item
            setattr(self, "redis_%s" %(item), conf["redis"][item])                

        for item in conf["logging"]:
            #print item
            setattr(self, item, conf["logging"][item])      
Exemplo n.º 33
0
def change_nginx_config(https=None):
    if https is None:
        https = listen_on_https()

    domain = get_conf('SEAFILE_SERVER_HOSTNAME', 'seafile.example.com')

    context = {
        'https': False,
        'behind_ssl_termination': behind_ssl_termination(),
        'domain': domain,
        'enable_webdav': get_conf_bool('ENABLE_WEBDAV')
    }
    if not os.path.isfile('/shared/nginx/conf/seafile.nginx.conf'):
        render_template('/templates/seafile.nginx.conf.template',
                        '/etc/nginx/sites-enabled/seafile.nginx.conf', context)

    call('nginx -s reload')
    time.sleep(2)
Exemplo n.º 34
0
def server(): 
    
    """ server """
    conf = get_conf("config/ak_server.toml")
    
    logger.info("start AK simulator server")
    host = conf["server"]["host"]
    
    port = conf["server"]["port"]
     
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    
    logger.debug('Socket created %s:%s' % (host, port) )
     
    #Bind socket to local host and port
    try:
        sock.bind((host, port))
        
    except socket.error as msg:
        
        logger.debug('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1] )
        sys.exit()
         
    logger.debug('Socket bind complete')
     
    #Start listening on socket
    sock.listen(10)
    logger.debug('Socket now listening')
     
    #Function for handling connections. This will be used to create threads

    #now keep talking with the client  

    
    while 1:
        #wait to accept a connection - blocking call
        conn, addr = sock.accept()
        logger.debug( 'Connected with ' + addr[0] + ':' + str(addr[1]) )
         
        # start new thread takes 1st argument as a function name to be run, 
        # second is the tuple of arguments to the function.
        thread.start_new_thread(clientthread ,(conn,))
    
    sock.close()
Exemplo n.º 35
0
#!/usr/bin/env python
from daemon import runner
import commands
import time
from tools.logger import FILE_LOG as LOG 
from tools.logger import STREAM
import utils
import sys

SERVICE = utils.get_conf()
class MyDaemon(object):
    def __init__(self,service):
        self.stdin_path = '/dev/null'
	self.stdout_path = '/dev/null'
	self.stderr_path = '/dev/null'
	self.pidfile_path = '/tmp/%s.pid' % service
	self.pidfile_timeout = 5
        self.service = service
    def run(self):
        eval('Services.'+self.service+'()')

class Services(object):
    @staticmethod
    def memory_monitor():
        service_conf = SERVICE['memory_monitor']
        log_path = service_conf['log_path']
        limit_memory = service_conf['limit_memory']
        latest_log = ''
        while True:
            (status,info) = commands.getstatusoutput('top -b -n 1 > %s' %log_path)
            if not status: