예제 #1
0
파일: fabfile.py 프로젝트: anwen/anwen
def backup(c):
    c = Connection('aw')
    """ backup data from aw mongo and download"""
    with c.cd('/var/www/anwen/db'):
        c.run('. ~/.zshrc && python3 db_in_out.py -o')
        c.run('tar czf aw_yaml.tar.gz data')
    with c.cd('/var/www/anwen/docs/shares'):
        c.run('tar czf aw_md.tar.gz *.md')
    with c.cd('/var/www/anwen/static/upload/'):
        c.run('tar czf upload.tar.gz img')
    print('download yaml:')
    with CD(os.path.join(os.getcwd(), 'db/')):
        c.get('/var/www/anwen/db/aw_yaml.tar.gz', 'aw_yaml.tar.gz')
        c.local('tar zxf aw_yaml.tar.gz')
        c.local('rm aw_yaml.tar.gz')
    print('download md:')
    with CD(os.path.join(os.getcwd(), 'docs/shares/')):
        c.get('/var/www/anwen/docs/shares/aw_md.tar.gz', 'aw_md.tar.gz')
        c.local('tar zxf aw_md.tar.gz')
        c.local('rm aw_md.tar.gz')
    print('download img:')
    return
    with CD(os.path.join(os.getcwd(), 'static/upload/')):
        c.get('/var/www/anwen/static/upload/upload.tar.gz', 'upload.tar.gz')
        c.local('tar zxf upload.tar.gz img')
        c.local('rm upload.tar.gz')
def deploy():
    supervisor_conf_path = '/home/gmn/etc/'
    supervisor_program_name = 'hellodjango-blog-tutorial'

    project_root_path = '/home/gmn/apps/HelloDjango-blog-tutorial/'

    # 如果你的电脑配了ssh免密码登录,就不需要 connect_kwargs 来指定密码了。
    c = Connection(f"{server_username}@{server_host_ip}",
                   connect_kwargs={"password": server_password})

    # 先停止应用
    with c.cd(supervisor_conf_path):
        cmd = 'supervisorctl -c /home/gmn/etc/supervisord.conf stop {}'.format(
            supervisor_program_name)
        c.run(cmd)

    # 进入项目根目录,从 Git 拉取最新代码
    with c.cd(project_root_path):
        cmd = 'git pull'
        responders = _get_github_auth_responders()
        c.run(cmd, watchers=responders)

    # 安装依赖,迁移数据库,收集静态文件
    with c.cd(project_root_path):
        c.run('pipenv install --deploy --ignore-pipfile')
        c.run('pipenv run python manage.py migrate')
        c.run('pipenv run python manage.py collectstatic --noinput')

    # 重新启动应用
    with c.cd(supervisor_conf_path):
        cmd = 'supervisorctl -c /home/gmn/etc/supervisord.conf start {}'.format(
            supervisor_program_name)
        c.run(cmd)
예제 #3
0
def deploy(c):
    # 手动输入服务器地址、用户名及密码
    host = input('host:')
    user = input('user:'******'password:'******'22', user=user, connect_kwargs={'password': password})
    # 删除服务器上老版本的tar文件
    conn.run('rm -f %s' % _REMOTE_TMP_TAR)
    # 上传新版本的tar文件
    conn.put(os.path.join(_LOCAL_PKG_PATH, _TAR_FILE), _REMOTE_TMP_TAR)
    # 在服务器上创建新目录
    newdir = 'www-%s' % datetime.now().strftime('%y-%m-%d_%H.%M.%S')
    with conn.cd(_REMOTE_BASE_DIR):
        conn.run('mkdir %s' % newdir)
    # 解压tar文件至新目录
    with conn.cd('%s/%s' % (_REMOTE_BASE_DIR, newdir)):
        conn.run('tar -xzvf %s' % _REMOTE_TMP_TAR)
    # 重置软链接
    with conn.cd(_REMOTE_BASE_DIR):
        conn.run('rm -f www')
        conn.run('ln -s %s www' % newdir)
    # 将app.py设置为可执行
    conn.run('chmod a+x %s/www/app.py' % _REMOTE_BASE_DIR)
    # 重启Python服务和Nginx服务
    conn.run('supervisorctl stop pythonweb')
    conn.run('supervisorctl start pythonweb')
    conn.run('/etc/init.d/nginx reload')
예제 #4
0
def deploy(c):
    supervisor_conf_path = '~/etc/'
    supervisor_program_name = 'hellodjango-blog-tutorial'
    project_root_path = '~/apps/HelloDjango-blog-tutorial/'

    host_ip = c.host  # 服务器地址
    user_name = c.user  # 服务器用户名
    password = c.pwd  # 服务器密码
    #cmd = 'date' # shell 命令,查询服务器上的时间
    con = Connection(host_ip, user_name, connect_kwargs={'password': password})
    # 先停止应用
    with con.cd(supervisor_conf_path):
        cmd = 'supervisorctl stop {}'.format(supervisor_program_name)
        con.run(cmd)

    # 进入项目根目录,从 Git 拉取最新代码
    with con.cd(project_root_path):
        cmd = 'git pull'
        responders = _get_github_auth_responders(c)
        con.run(cmd, watchers=responders)

    # 安装依赖,迁移数据库,收集静态文件
    with con.cd(project_root_path):
        con.run('pipenv install --deploy --ignore-pipfile')
        con.run('pipenv run python manage.py migrate')
        con.run('pipenv run python manage.py collectstatic --noinput')

    # 重新启动应用
    with con.cd(supervisor_conf_path):
        cmd = 'supervisorctl start {}'.format(supervisor_program_name)
        con.run(cmd)
예제 #5
0
파일: fabfile.py 프로젝트: anwen/anwen
def backup(c):
    c = Connection('aw')
    """ backup data from aw mongo """
    with c.cd('/var/www/anwen/db'):
        c.run('. ~/.zshrc && python3 db_in_out.py -o')
        c.run('tar czf aw_yaml.tar.gz data')
    with c.cd('/var/www/anwen/docs/shares'):
        c.run('tar czf aw_md.tar.gz *.md')
    with c.cd('/var/www/anwen/static/upload/'):
        c.run('tar czf upload.tar.gz img')
    print('download yaml:')
    with CD(os.path.join(os.getcwd(), 'db/')):
        c.get('/var/www/anwen/db/aw_yaml.tar.gz', 'aw_yaml.tar.gz')
        c.local('tar zxf aw_yaml.tar.gz')
        c.local('rm aw_yaml.tar.gz')
    print('download md:')
    with CD(os.path.join(os.getcwd(), 'docs/shares/')):
        c.get('/var/www/anwen/docs/shares/aw_md.tar.gz', 'aw_md.tar.gz')
        c.local('tar zxf aw_md.tar.gz')
        c.local('rm aw_md.tar.gz')
    print('download img:')
    return
    with CD(os.path.join(os.getcwd(), 'static/upload/')):
        c.get('/var/www/anwen/static/upload/upload.tar.gz', 'upload.tar.gz')
        c.local('tar zxf upload.tar.gz img')
        c.local('rm upload.tar.gz')
예제 #6
0
파일: fabfile.py 프로젝트: anwen/anwen
def backol(c):
    c = Connection('aw')
    """ backup data from aw mongo """
    t = time.time()
    with c.cd('/var/www/anwen/db'):
        c.run('. ~/.zshrc && python3 db_in_out.py -o')
        c.run('tar czf aw_yaml_{}.tar.gz data'.format(t))
    with c.cd('/var/www/anwen/docs/shares'):
        c.run('tar czf aw_md_{}.tar.gz *.md'.format(t))
    with c.cd('/var/www/anwen/static/upload/'):
        c.run('tar czf upload_{}.tar.gz img'.format(t))
예제 #7
0
def deploy(ctx, name):
    data = ctx[name]

    folder = data.pop("folder")
    c = Connection(**data.get('connection', {}))

    with c.prefix("source ~/.zshrc"):
        with c.cd(os.path.dirname(os.path.dirname(folder))):
            c.run("git pull")
        with c.cd(folder):
            c.run("jekyll build")
예제 #8
0
파일: fabfile.py 프로젝트: anwen/anwen
def backol(c):
    c = Connection('aw')
    """ backup data from aw mongo """
    t = time.time()
    with c.cd('/var/www/anwen/db'):
        c.run('. ~/.zshrc && python3 db_in_out.py -o')
        c.run('tar czf aw_yaml_{}.tar.gz data'.format(t))
    with c.cd('/var/www/anwen/docs/shares'):
        c.run('tar czf aw_md_{}.tar.gz *.md'.format(t))
    with c.cd('/var/www/anwen/static/upload/'):
        c.run('tar czf upload_{}.tar.gz img'.format(t))
예제 #9
0
def do_restart(connection: Connection, name: str, root: str) -> None:
    print("=> restarting {} ...".format(name))

    with connection.cd(root):
        connection.run("docker-compose -f docker-compose.traefik.yml restart")

    print("=> ok!")
예제 #10
0
def execute_on_remote_host(commands, hosts, warn_on_fail=False,
                           cwd=None, hide_output=False):
    """Execute commands remotely on a given list of hosts

    Args:
        commands (list): List of commands to execute
        hosts (list): List of hosts on which the commands will be executed
        warn_on_fail (bool): A flag used to determine whether to warn
                             only when a failure occurs and keep running
        cwd (str): the working directory where to execute the commands

    Returns:
        list: a list of results (fabric run results) for each executed command
    """
    results = []
    for host in hosts:
        c = Connection(host)
        for cmd in commands:
            try:
                if cwd:
                    with c.cd(cwd):
                        LOG.debug(crayons.red(
                            "Executing: {} in {}".format(cmd, cwd)))
                        res = c.run(cmd, warn=warn_on_fail, hide=hide_output)
                else:
                    LOG.debug(crayons.red("Executing: {}".format(cmd)))
                    res = c.run(cmd, warn=warn_on_fail, hide=hide_output)
                results.append(res)
            except invoke.exceptions.UnexpectedExit:
                LOG.error("Failed to execute: {}. Exiting now...".format(cmd))
                sys.exit(2)
    return results
예제 #11
0
def do_pull(connection: Connection, name: str, root: str) -> None:
    print("=> pulling {} ...".format(name))

    with connection.cd(root):
        connection.run("git pull")

    print("=> ok!")
예제 #12
0
def deploy_ccp_docs(
    ccp_doc_root="public_html/py/ciscoconfparse",
    ccp_bundle_name="ccp.tar.gz",
    doc_host="",
    password="",
):

    # Run 'make html' in directory: sphinx-doc/
    run("cd sphinx-doc && make clean && make html")  # local command

    run("cd sphinx-doc/_build/html && tar cvfz {0} *".format(
        os.path.expanduser("~/" + ccp_bundle_name)))

    # Run 'make clean' in directory: sphinx-doc/
    run("cd sphinx-doc && make clean")  # local command

    # ssh with a password...
    conn = Connection("mpenning@{}".format(doc_host),
                      connect_kwargs={"password": password})
    conn.put(
        local=os.path.expanduser("~/{0}".format(ccp_bundle_name)),
        remote=ccp_bundle_name,
    )

    # Delete all the old files
    conn.run("rm -rf {0}/*".format(ccp_doc_root))
    # Move the new files to ccp_doc_root
    conn.run("mv {0} {1}".format(ccp_bundle_name, ccp_doc_root))

    with conn.cd(ccp_doc_root):
        conn.run("tar xvfz {0}".format(ccp_bundle_name))
        conn.run("rm {0}".format(ccp_bundle_name))
예제 #13
0
def main():
    # ip ����������
    # �����ĵ�������ssh�������¼���Ͳ���Ҫ connect_kwargs ��ָ�������ˡ�
    c = Connection("[email protected]", connect_kwargs={"password": "******"})
    with c.cd('/var/www/youproject'):
        c.run("git pull origin master")
        c.run("/usr/bin/supervisorctl -c ../supervisor/supervisord.conf restart youproject")
예제 #14
0
def install_requirements(conn: Connection):
    """Install Python requirements on remote server"""
    logger.info("Ensuring latest Python requirements are installed.")
    with conn.cd(CODE_PATH):
        conn.run("./env/bin/pip install --quiet -r requirements.txt",
                 echo=True)
    logger.info("Finished installing requirements.")
예제 #15
0
def deploy(connection: fabric.Connection, filename: typing.Optional[str] = None) -> None:
    upload(connection, filename)

    with connection.cd(GlobalConfig.project_name):
        execute(connection, 'eval "$(pyenv init -)" && poetry install --no-dev', {
            'PATH': '$HOME/.pyenv/bin:$HOME/.poetry/bin:$PATH'
        })
예제 #16
0
def rollback():
    '''回滚版本'''
    # 配置sudo命令的密码
    config = Config(overrides={'sudo': {'password': remote_su_pass}})
    # 以明文方式配置用户登录密码
    conn = Connection(ip,
                      user=remote_user,
                      config=config,
                      connect_kwargs={
                          "allow_agent": False,
                          "password": remote_pass
                      })
    with conn.cd(remote_wwwroot):
        r = conn.run("ls -p -1", hide=True)  # hide禁用服务器将输出复制到中断的行为
        files = [
            s[:-1] for s in RE_FILES.split(r.stdout)
            if s.startswith('www-') and s.endswith('/')
        ]
        files.sort(reverse=True)
        r = conn.run('ls -l www', hide=True)
        ss = r.stdout.split(' -> ')
        if len(ss) != 2:
            print('ERROR: \'www\' is not a symbol link.')
            return
        current = ss[1].split('/')[-1].strip()
        print('Found current symbol link points to: %s\n' % current)
        try:
            print(files, "*", current, "*")
            index = files.index(current)
        except ValueError as e:
            print('ERROR: symbol link is invalid.')
            return
        if len(files) == index + 1:
            print('ERROR: already the oldest version.')
            return
        old = files[index + 1]
        print('==================================================')
        for f in files:
            if f == current:
                print('      Current ---> %s' % current)
            elif f == old:
                print('  Rollback to ---> %s' % old)
            else:
                print('                   %s' % f)
        print('==================================================')
        print('')
        yn = input('continue? y/N ')
        if yn != 'y' and yn != 'Y':
            print('Rollback cancelled.')
            return
        print('Start rollback...')
    conn.sudo('rm -f {}/www'.format(remote_wwwroot))
    conn.sudo('ln -s {}/{} {}/www'.format(remote_wwwroot, old, remote_wwwroot))
    conn.sudo('chown -h www-data:www-data {}/www'.format(remote_wwwroot))
    conn.sudo('chown -H -R www-data:www-data {}/www'.format(remote_wwwroot))
    conn.sudo('supervisorctl stop awesome')
    conn.sudo('supervisorctl start awesome')
    conn.sudo('/etc/init.d/nginx reload')
    print('ROLLBACKED OK.')
예제 #17
0
def rollback(c):
    # 手动输入服务器地址、用户名及密码
    host = input('host:')
    user = input('user:'******'password:'******'22', user=user, connect_kwargs={'password': password})
    # 回退
    with conn.cd(_REMOTE_BASE_DIR):
        # 获取所有名称以"www-"开头的目录列表,列表按目录名称倒排序
        r = conn.run('ls -p -1').stdout
        files = [s[:-1] for s in _RE_LINE_BREAK.split(r) if s.startswith('www-') and s.endswith('/')]
        files.sort(reverse=True)

        # 获取当前"www"软链接指向的目录
        r = conn.run('ls -l www').stdout
        L = r.replace("\n", '').split(' -> ')
        if len(L) != 2:
            print('Error: \'www\' is not a symbol link.')
            return
        current = L[1]
        print('Found current symbol link points to %s' % current)

        # 获取上一个版本对应的目录
        try:
             index = files.index(current)
        except ValueError:
            print('Error: symbol link is invalid.')
            return
        if len(files) == index + 1:
            print('Error: alreay the oldest version.')
            return
        old = files[index + 1]

        # 要求确认是否进行回退操作
        print ('==================================================')
        for f in files:
            if f == current:
                print ('Current        ---> %s' % current)
            elif f == old:
                print ('Rollback to    ---> %s' % old)
        print ('==================================================')
        yn = input('continue? Y/N ')
        if yn != 'y' and yn != 'Y':
            print ('Rollback cancelled.')
            return
        
        # 重置软链接
        print ('Rollbacking...')
        conn.run('rm -f www')
        conn.run('ln -s %s www' % old)
        # 将app.py设置为可执行
        conn.run('chmod a+x %s/www/app.py' % _REMOTE_BASE_DIR)

        # 重启Python服务和Nginx服务
        conn.run('supervisorctl stop pythonweb')
        conn.run('supervisorctl start pythonweb')
        conn.run('/etc/init.d/nginx reload')
        print ('Rollback OK.')
예제 #18
0
def backup(connection: fabric.Connection, filename: str) -> None:
    current_date = datetime.datetime.now().strftime(
        src.constants.GENERIC_DATE_FORMAT)
    name, extension = os.path.splitext(filename)

    with connection.cd(GlobalConfig.project_name):
        connection.get(f'{GlobalConfig.project_name}/{filename}',
                       f'backup_{name}_{current_date}{extension}')
예제 #19
0
def deploy(c):
    conn = Connection("trotsky")
    with conn.cd("~/src/untitled-incremental"):
        conn.run("git fetch")
        conn.run("git stash")
        conn.run("git pull")
        conn.run("git stash pop")
        conn.put("main.wasm")
예제 #20
0
def compose(c, version):
    captain = Connection(f"{SSH_USER}@{SSH_HOST}")
    with captain.cd("/apps/deneb/"):
        captain.run("git reset --hard HEAD")
        captain.run("git fetch -ap")
        captain.run("git fetch --tags")
        captain.run(f"git checkout {version}")
        captain.run(f"git pull origin {version}")
        captain.run("make compose")
예제 #21
0
def update_repo(conn: Connection, branch: str = "master"):
    """Update remote Git repo to use the latest code"""
    logger.info("Updating git repository to run the latest code.")
    conn.sudo(f"chown -R ubuntu:ubuntu {CODE_PATH}", echo=True)
    with conn.cd(CODE_PATH):
        conn.run("git fetch --quiet", echo=True)
        conn.run(f"git checkout --quiet {branch}", echo=True)
        conn.run("git pull --quiet", echo=True)
    logger.info("Done updating repo.")
예제 #22
0
def run_task_pipeline(conn: Connection, pipeline_name: str, pipeline_args: dict):
    """Run a task pipeline on the remote machine"""
    logger.info("Running task pipleine %s", pipeline_name)
    pipeline_args_str = " ".join([f"--{k} {v}" for k, v in pipeline_args.items()])
    cmd_str = f"./env/bin/python -m tasks {pipeline_name} {pipeline_args_str}"
    with conn.cd(CODE_PATH):
        conn.run(cmd_str, echo=True)

    logger.info("Finished running task pipleine %s", pipeline_name)
예제 #23
0
def compose_test(c, branch):
    captain = Connection(f"{SSH_USER}@{SSH_HOST}")
    with captain.cd("/apps/deneb-test/"):
        captain.run("git reset --hard HEAD")
        captain.run("git fetch -ap")
        captain.run("git fetch --tags")
        captain.run(f"git checkout {branch}")
        captain.run(f"git pull origin {branch}")
        captain.run("make compose")
예제 #24
0
def deploy_production(c, file_type, package_name):
    #current_day = time.strftime("%y%m%d")
    # print(current_day)
    local_update_files_folder = 'e:/release_files/'
    remote_update_files_folder = '/cygdrive/c/update_files/'
    remote_backup_folder = '/cygdrive/c/update_files/production_web_backup/'
    remote_web_site_folder = '/cygdrive/c/progra~2/THC/'
    conn = Connection(host='11.11.11.10', user='******',
                      connect_kwargs={'password': "******"})
    with conn.cd(remote_update_files_folder):
        logger.info('begin to upload file...')
        begin_time = time.time()
        cbk, pbar = show_progress_bar(ascii=True, unit='b', unit_scale=True)
        result = conn.sftp().put("{0}{1}.zip".format(local_update_files_folder, package_name), "%s%s.zip" % (
            remote_update_files_folder, package_name), callback=cbk)
        pbar.close()
        # conn.sftp().put("{0}{1}.zip".format( local_update_files_folder, package_name), remote_update_files_folder + package_name + ".zip", callback=progress_bar)
        end_time = time.time()
        logger.info('file upload finished...')
        logger.info("Uploaded {0}{1}.zip -> {2}{1}.zip".format(
            local_update_files_folder, package_name, remote_update_files_folder))
        logger.info("used {:.5}s".format(end_time - begin_time))
        time.sleep(1)
        logger.info('unzip the uploaded files...')
        conn.run("unzip -o {0}.zip -d .".format(package_name))
    with conn.cd(remote_backup_folder):
        conn.run('rm -rf ./thc/*')
        logger.info('copy files to the backup folder...')
        conn.run("cp -a -f -v ../{0}/* ./thc/".format(package_name))
        logger.info('backup the files ...')
        conn.run("./backup_thc.bat")
        if file_type == 'dll':
            logger.info('stopping service...')
            conn.run('{0}stop.bat'.format(remote_web_site_folder))
            logger.info('update release files ...')
            #conn.run('cp -a -f -v ./thc/* {0}'.format(remote_web_site_folder))
            conn.run("./copy_to_thc.bat")
            logger.info('starting service ...')
            conn.run('{0}start.bat'.format(remote_web_site_folder))
        else:
            logger.info('update release files ...')
            #conn.run('cp -a -f -v ./thc/* {0}'.format(remote_web_site_folder))
            conn.run("./copy_to_thc.bat")
        logger.info('deploy finished.')
예제 #25
0
파일: admin.py 프로젝트: huixt/fabric
    def check_info(self, request, queryset):
        qs = queryset[0]
        user_flag = qs.user_flag
        # pyer用户
        if user_flag == 1:
            ssh_user = '******'
            # 测试环境
            if qs.server_flag == 1:
                ssh_pwd = settings.TST_PYER_PWD
                # 生产环境
            elif qs.server_flag == 2:
                ssh_pwd = settings.PRD_PYER_PWD
        # root 用户
        elif user_flag == 2:
            ssh_user = '******'
            if qs.server_flag == 1:  # 测试环境
                ssh_pwd = settings.TST_ROOT_PWD
            elif qs.server_flag == 2:  # 生产环境
                ssh_pwd = settings.PRD_ROOT_PWD

        ssh_ip = qs.server_ip
        tmp_code_path = qs.tmp_code_path
        git_url = qs.git_url
        git_list = git_url.split('/')
        git_name = git_list[-1]
        if '.' in git_name:
            git_name = git_name.split('.')[0]
        message_bit, ssh_flag, git_flag = '', False, False

        try:
            log.info('检测项目状态...')

            # 连接服务器
            con = Connection(ssh_user + '@' + ssh_ip,
                             connect_kwargs={'password': ssh_pwd})
            with con.cd('~'):
                con.run('ls')
            ret = con.is_connected
            if ret:
                log.info('1.连接服务器完成....')
                ssh_flag = True
            os.system('rm -rf ' + tmp_code_path + '/' + git_name)
            log.info('rm -rf ' + tmp_code_path + '/' + git_name)
            os.system('git clone ' + git_url + ' ' + tmp_code_path + '/' +
                      git_name)
            log.info('git clone ' + git_url + ' ' + tmp_code_path + '/' +
                     git_name)
            log.info('2.拉取代码完成....')
            git_flag = True
        except Exception as e:
            log.info('检查配置出错error:%s', str(e))
        if ssh_flag and git_flag:
            message_bit = '服务器连接正常'
        else:
            message_bit = '服务器连接异常,请查看日志'
        self.message_user(request, '%s' % message_bit)
예제 #26
0
def get_run_id(conn: Connection, app_name: str, region_name: str):
    """Get the run ID for a given job name name"""
    logger.info("Building run id.")
    with conn.cd(CODE_PATH):
        git_commit = conn.run("git rev-parse HEAD", hide="out").stdout.strip()

    git_commit = git_commit[:7]
    run_id = build_run_id(app_name, region_name, git_commit)
    logger.info("Using run id %s", run_id)
    return run_id
예제 #27
0
def set_run_id(conn: Connection, run_id: str):
    """Set git to use the commit for a given run ID"""
    logger.info("Setting up repo using a run id %s", run_id)
    conn.sudo(f"chown -R ubuntu:ubuntu {CODE_PATH}", echo=True)
    _, _, _, commit = read_run_id(run_id)
    with conn.cd(CODE_PATH):
        conn.run("git fetch --quiet", echo=True)
        conn.run(f"git checkout --quiet {commit}", echo=True)

    logger.info("Done updating repo.")
예제 #28
0
def main():
    print("{}@{}".format(mach['u'], mach['h']))
    c = Connection("{}@{}".format(mach['u'], mach['h']),
                   port=11022,
                   connect_kwargs={"password": mach['p']})

    with c.cd(mach['ws']):
        c.run('git reset --hard')
        c.run('git pull')
        c.run('python3 deploy.py')
예제 #29
0
def main():
    # ip 我是随便填的
    # 如果你的电脑配了ssh免密码登录,就不需要 connect_kwargs 来指定密码了。
    c = Connection("[email protected]", connect_kwargs={"password": "******"})

    with c.cd("/var/www/youproject"):
        c.run("git pull origin master")
        c.run(
            "/usr/bin/supervisorctl -c ../supervisor/supervisord.conf restart youproject"
        )
예제 #30
0
    def check_info(self, request, queryset):
        channel, connection = rabbit_connect()
        qs = queryset[0]
        user_flag = qs.user_flag
        # pyer用户
        if user_flag == 1:
            ssh_user = '******'
            # 测试环境
            if qs.server_flag == 1:
                ssh_pwd = settings.TST_PYER_PWD
                # 生产环境
            elif qs.server_flag == 2:
                ssh_pwd = settings.PRD_PYER_PWD
        # root 用户
        elif user_flag == 2:
            ssh_user = '******'
            if qs.server_flag == 1:  # 测试环境
                ssh_pwd = settings.TST_ROOT_PWD
            elif qs.server_flag == 2:  # 生产环境
                ssh_pwd = settings.PRD_ROOT_PWD
        log.info('开启后端发布...%s', str(qs.git_branch))
        create_msg(channel, '开启后端发布...' + str(qs.git_branch))
        ssh_ip = qs.server_ip
        tmp_code_path = qs.tmp_code_path
        message_bit, ssh_flag, git_flag = '', False, False

        try:
            # 连接服务器
            con = Connection(ssh_user + '@' + ssh_ip,
                             connect_kwargs={'password': ssh_pwd})
            git_url = qs.git_url
            # 检测git连接
            with con.cd(tmp_code_path):
                git_list = git_url.split('/')
                git_name = git_list[-1]
                if '.' in git_name:
                    git_name = git_name.split('.')[0]
                con.run('rm -rf ' + git_name)
                res = con.run('git clone ' + git_url)
                git_flag = True
                message_bit += '2.' + res.stdout
            ret = con.is_connected
            if ret:
                log.info('1.连接服务器成功....')
                create_msg(channel, '1.连接服务器成功....')
                ssh_flag = True
        except Exception as e:
            log.info('检查配置出错error:%s' % str(e))
            create_msg(channel, '检查配置出错error:' + str(e))
        if ssh_flag and git_flag:
            message_bit = '服务器连接正常'
        else:
            message_bit = '服务器连接异常,请查看日志'
        rabbit_close(connection)
        self.message_user(request, '%s' % message_bit)
예제 #31
0
def deploy(ctx):
    timestr = time.strftime("%Y%m%d-%H%M%S")
    # print("Hello world!")

    sudo_pass = getpass.getpass("What's your sudo password?")
    config = Config(overrides={"sudo": {"password": sudo_pass}})
    c = Connection("*****@*****.**", config=config)

    # c.run(
    #     "mysqldump -u root -p'"
    #     + sudo_pass
    #     + "' meal_project > ~/mysql_backups/meal_project_"
    #     + timestr
    #     + ".sql"
    # )

    c.sudo("docker exec mysql mysqldump -u root -p'" + sudo_pass +
           "' meal_project > ~/mysql_backups/meal_project_" + timestr + ".sql")

    ## from mysql docker site:
    ##$ docker exec some-mysql sh -c 'exec mysqldump --all-databases -uroot -p"$MYSQL_ROOT_PASSWORD"' > /some/path/on/your/host/all-databases.sql

    site_folder = "/home/odroid/meal_project"
    c.run(f"mkdir -p {site_folder}")

    # current_commit = c.local("HOME=~ git log -n 1 --format=%H")
    with c.cd(site_folder):
        if c.run("test -d .git", warn=True).failed:
            c.run(f"git clone {REPO_URL} .")
        else:
            # c.run("git pull origin master --force")
            c.run("git fetch")
        c.run("git reset --hard origin/master")

        # PIP load from requirements.txt
        venv_command = "source venv/bin/activate"
        pip_command = "venv/bin/pip3 install -r requirements.txt"
        c.run(venv_command + " && " + pip_command)

        # Reload static files
        static_cmd = "python manage.py collectstatic --noinput"
        c.run(venv_command + " && " + static_cmd)

        # Database Make Migration
        makem_cmd = "python manage.py makemigrations --settings=meal_project.settings.production"
        c.run(venv_command + " && " + makem_cmd)

        # Database Migrate
        migrate_cmd = (
            "python manage.py migrate --settings=meal_project.settings.production"
        )
        c.run(venv_command + " && " + migrate_cmd)

    # Restart Apache
    c.sudo("service apache2 restart")
예제 #32
0
def get_run_id(conn: Connection, job_name: str):
    """Get the run ID for a given job name name"""
    logger.info("Building run id.")
    with conn.cd(CODE_PATH):
        git_commit = conn.run("git rev-parse HEAD", hide="out").stdout.strip()

    git_commit_short = git_commit[:7]
    timestamp = int(time.time())
    run_id = f"{job_name}-{timestamp}-{git_commit_short}"
    logger.info("Using run id %s", run_id)
    return run_id