Example #1
0
def snapshot():
    """Takes a snapshot"""
    ignore = " ".join(['-e %s' % i for i in dump_ignores])
    run("workon %s; cd %s; python manage.py dumpdata --indent=2 %s > %s/dump.json" \
        % (env.venv, env.remote_app_dir, ignore, env.remote_root_dir))
    run("cd %s; gzip -9 -f dump.json" % env.remote_root_dir)
    get("%s/dump.json.gz" % env.remote_root_dir, "dump.json.gz")
Example #2
0
def sync():
    """Rysnc local states and pillar data to the master, and checkout margarita."""
    # Check for missing local secrets so that they don't get deleted
    # project.rsync_project fails if host is not set
    sudo("mkdir -p /srv")
    if not have_secrets():
        get_secrets()
    else:
        # Check for differences in the secrets files
        for environment in [env.environment]:
            remote_file = os.path.join('/srv/pillar/', environment, 'secrets.sls')
            with lcd(os.path.join(CONF_ROOT, 'pillar', environment)):
                if files.exists(remote_file):
                    get(remote_file, 'secrets.sls.remote')
                else:
                    local('touch secrets.sls.remote')
                with settings(warn_only=True):
                    result = local('diff -u secrets.sls.remote secrets.sls')
                    if result.failed and files.exists(remote_file) and not confirm(
                            red("Above changes will be made to secrets.sls. Continue?")):
                        abort("Aborted. File have been copied to secrets.sls.remote. " +
                              "Resolve conflicts, then retry.")
                    else:
                        local("rm secrets.sls.remote")
    salt_root = CONF_ROOT if CONF_ROOT.endswith('/') else CONF_ROOT + '/'
    project.rsync_project(local_dir=salt_root, remote_dir='/tmp/salt', delete=True)
    sudo('rm -rf /srv/salt /srv/pillar')
    sudo('mv /tmp/salt/* /srv/')
    sudo('rm -rf /tmp/salt/')
    execute(margarita)
Example #3
0
def fetch_logs():
    """
    Fetch logs from the web instances into ~/logs.
    """
    require("configuration")
    with cd(env.deploy_dir):
        get("codalab/var/*.log", "~/logs/%(host)s/%(path)s")
def get_secrets():
    "Get files that aren't in the checkout, such as sitesettings.py"
    with lcd(env.local_dir):
        # We get a copy of the production sitesettings.py, but we don't use it for local
        # development (hence it's not kept in seabirds/).
        get('%(remote_dir)s/seabirds/sitesettings.py' % env, local_path='sitesettings_production.py')
        get('%(remote_dir)s/seabirds/secrets.py' % env, local_path='seabirds/')
def download_file():
    print "Checking local disk space..."
    local("df -h")
    remote_path = prompt("Enter the remote file path:")
    local_path = prompt("Enter the local file path:")
    get(remote_path=remote_path, local_path=local_path)
    local("ls %s" %local_path)
Example #6
0
def syncdb():
    """Sync loacl db with remote db"""

    if not REMOTE_DB_USERNAME or not REMOTE_DB_PASSWORD or not REMOTE_DB_NAME:
        print "Please setup remote db configs"
        return

    if not LOCAL_DB_USERNAME or not LOCAL_DB_PASSWORD or not LOCAL_DB_NAME:
        print "Please setup local db configs"
        return

    with cd("/tmp"):
        run("mysqldump -u%s -p%s %s > latest_db.sql" % (REMOTE_DB_USERNAME,
                                                        REMOTE_DB_PASSWORD,
                                                        REMOTE_DB_NAME))
        run("tar cfz latest_db.sql.tgz latest_db.sql")

    # Download to local
    get("/tmp/latest_db.sql.tgz", "/tmp")

    with lcd("/tmp"):
        local("tar xfz latest_db.sql.tgz")
        local("mysql -u%s -p%s %s < latest_db.sql" % (LOCAL_DB_USERNAME,
                                                      LOCAL_DB_PASSWORD,
                                                      LOCAL_DB_NAME))
Example #7
0
    def _wrapped_env(*args, **kw):
        if args:
            environ = args[0]
        else:
            try:
                exp_repo = kw.get('exp_repo', '${ARCHIVE_OCEAN}/exp_repos')
                name = kw['name']
            except KeyError:
                raise NoEnvironmentSetException

            environ = {'exp_repo': exp_repo,
                       'name': name,
                       'expfiles': '${HOME}/.bosun_exps'}
            environ = _expand_config_vars(environ)
            with hide('running', 'stdout', 'stderr', 'warnings'):
                if exists(fmt('{expfiles}', environ)):
                    run(fmt('rm -rf {expfiles}', environ))
                run(fmt('hg clone {exp_repo} {expfiles}', environ))
#                else:
#                    with cd(fmt('{expfiles}', environ)):
#                        run('hg pull -u ')

                temp_exp = StringIO()
                get(fmt('{expfiles}/exp/{name}/namelist.yaml', environ),
                    temp_exp)

            kw['expfiles'] = environ['expfiles']
            environ = load_configuration(temp_exp.getvalue(), kw)
            kw.pop('expfiles', None)
            kw.pop('name', None)
            kw.pop('exp_repo', None)
            temp_exp.close()

        return func(environ, **kw)
Example #8
0
def crud_backup():
    with cd(env.PROJECT.current):
        with prefix('source bin/activate'):
            run('python manage.py dumpdata crud.Activity2 crud.Organization2 ' +
                'crud.Project2 crud.Investment2 --indent=4 --format=json ' +
                '> crud.json')
            get('crud.json', 'crud.json')
Example #9
0
def backup_php_site(server_name, site_name):
    """

    legalsecretaryjournal_com
    TODO Only really need to backup everything in the 'images' and 'sites'
    folder.
    """
    site_info = SiteInfo(server_name, site_name)
    backup_path = site_info.backup().get('path')
    print(green("Backup files on '{}'").format(env.host_string))
    path = Path(site_name, 'files')
    print(yellow(path.remote_folder()))
    run('mkdir -p {0}'.format(path.remote_folder()))
    # remove '.gz' from end of tar file
    #  tar_file = os.path.splitext(path.remote_file())[0]
    #  with cd('/home/legalsec/legalsecretaryjournal.com/'):
    #      first = True
    #      for folder in path.php_folders():
    #          if first:
    #              first = False
    #              run('tar cvf {} {}'.format(tar_file, folder))
    #          else:
    #              run('tar rvf {} {}'.format(tar_file, folder))
    #  run('gzip {}'.format(tar_file))
    #  # list the contents of the archive
    #  run('tar ztvf {}'.format(path.remote_file()))
    with cd(backup_path):
        run('tar -cvzf {} .'.format(path.remote_file()))
    get(path.remote_file(), path.local_file())
Example #10
0
def build():
    set_up_user("cpbuild")
    local("tar cpf workspace.tar --exclude workspace.tar ..")
    put("workspace.tar")
    put("build_cellprofiler.sh", "~", mode=0755)
    run("./build_cellprofiler.sh")
    get("cellprofiler.tar.gz", "cellprofiler.tar.gz")
Example #11
0
def update_yaml(path, predicate, update, use_sudo=False):
    """
    Load configuration from path and apply update.

    A yaml document at `path` is deserialized, and updated with the given
    `update` function if `predicate` holds.

    :param path: path to yaml document
    :type path: string
    :param predicate: function taking a python representation of the yaml
        document, and returns either `True` or `False`
    :type predicate: function
    :param update: function taking a python representation of the yaml
        document, and does in-place update
    """
    doc_in = io.BytesIO()
    get(path, local_path=doc_in, use_sudo=use_sudo)
    doc_in.seek(0)
    doc = yaml.safe_load(doc_in)
    if predicate(doc):
        update(doc)
        doc_out = io.BytesIO()
        yaml.safe_dump(doc, stream=doc_out)
        doc_out.seek(0)
        put(doc_out, path, use_sudo=use_sudo)
Example #12
0
def openvpn_download_visc():
    """
    Download OpenVPN configuration files for Viscosity
    """
    hostname = prompt("Host name of the client:")

    if not exists('/root/easy-rsa/keys/%s.crt' % (hostname)):
        abort('Create client keys first with: openvpn_create_client')

    # set up a new directory to create our .visc configruation
    tmp_dir = '/tmp/%s' % (hostname + '.visc')
    if exists(tmp_dir):
        run('rm -fR %s' % (tmp_dir))

    # vars for the configuration file
    client_conf = {
        "visc_name": hostname,
        "server": env.hosts[0]
    }

    # make tmp directory, copy required items into it
    run('mkdir %s' % (tmp_dir))
    run('cp /etc/openvpn/ca.crt %s/ca.crt' % (tmp_dir))
    run('cp /root/easy-rsa/keys/%s.crt %s/cert.crt' % (hostname, tmp_dir))
    run('cp /root/easy-rsa/keys/%s.key %s/key.key' % (hostname, tmp_dir))
    run('cp /etc/openvpn/ta.key %s/ta.key' % (tmp_dir))
    upload_template('devbox_openvpn/configs/client.visc/config.conf', '%s/config.conf' % (tmp_dir), client_conf)
    run('chmod -R a+r %s' % (tmp_dir))

    # download .vsic directory and then delete it from server
    get(tmp_dir, '.')
    run('rm -fR %s' % (tmp_dir))
Example #13
0
def deploy():
    with cd(remote_repo):
        sudo('git pull --ff-only origin master', user=remote_user)
        run('pip install -r requirements.txt')
        get('production/*.cfg', 'production/%(basename)s.cfg.last')
        put('production/*.cfg', 'production/', use_sudo=True)
    sudo('supervisorctl restart %s' % remote_proc)
Example #14
0
def download():
    """Download backup file locally"""
    """Run backup script on remote"""
    require('environment', provided_by=[stage])

    get('%(application_tmp_path)s/%(application_backup_filename)s' % env['application'],
        '%(project_backup_path)s' % env['project'])
Example #15
0
def build_ssh2(src, dest):
    """建立从src到dest的信任关系"""
    env.host_string = src['host']
    env.user = src['user']
    env.password = src['passwd']
    cmd="[ -d ~/.ssh ] || mkdir ~/.ssh; "
    run(cmd)
    cmd='if [ ! -f ~/.ssh/id_rsa.pub ]; then ssh-keygen -N "" -f ~/.ssh/id_rsa ; fi'
    run(cmd)
    id_rsa_pub_file = '~/.ssh/{user}@{host}_id_rsa.pub'.format(
            user=src['user'], host=src['host'])
    get('~/.ssh/id_rsa.pub', id_rsa_pub_file)
    env.host_string = dest['host']
    env.user = dest['user']
    env.password = dest['passwd']
    run('[ -d ~/.ssh ] || mkdir ~/.ssh')
    put(id_rsa_pub_file, id_rsa_pub_file)
    cmd = 'existed=0;content=`cat {pubkey}`; if [ -f ~/.ssh/authorized_keys ];then grep "$content" ~/.ssh/authorized_keys >/dev/null 2>&1; if [ $? -eq 0 ];then existed=1;fi;fi; '
    cmd = cmd + ' if [ $existed -eq 0 ]; then cat {pubkey} >> ~/.ssh/authorized_keys ; fi && rm {pubkey} && chmod 600 ~/.ssh/authorized_keys &&  chmod og-w ~; chmod og-w ~/.ssh'
    cmd = cmd.format(pubkey=id_rsa_pub_file)
    run(cmd)

    #进行测试,并且消除第一次连接要敲回车的问题
    env.host_string = src['host']
    env.user = src['user']
    env.password = src['passwd']
    cmd='ssh {user}@{host} "ls"'.format(user=dest['user'], host=dest['host'])
    run(cmd)
Example #16
0
def write_configfile(remote_path, content=None, filename=None):
    _info('attempting to write {}...'.format(remote_path))

    rm_file = False
    if not filename:
        _, filename = tempfile.mkstemp()
        rm_file = True
        with open(filename, 'w') as f:
            f.write(content)

    _, old = tempfile.mkstemp()

    with hide('running', 'stdout', 'stderr'):
        if exists(remote_path):
            get(remote_path, old)
            with settings(hide('warnings'), warn_only=True):
                res = local('diff {} {}'.format(old, filename), capture=True)
            if res.failed:
                _bad('files differ')
                puts(res, show_prefix=False)
                if prompt('update file? [y/n]') == 'y':
                    _info('writing new {}...'.format(remote_path))
                    put(filename, remote_path, use_sudo=True, mode=0644)
            else:
                _good('files already match')
        else:
            _good('no remote file exists, writing now')
            put(filename, remote_path, use_sudo=True, mode=0644)

    # remove files
    os.remove(old)
    if rm_file:
        os.remove(filename)
Example #17
0
def get_htaccess():
    if not env.path:
        env.path = ''
    htaccess = StringIO()
    get(remote_path='%s/.htaccess' % env.path, local_path=htaccess)
    htaccess.seek(0)
    return htaccess
Example #18
0
def download_data():
    """Download Zope's Data.fs from the server."""

    if not env.get('confirm'):
        confirm("This will destroy all current Zope data on your local machine. " \
                "Are you sure you want to continue?")

    with cd('/home/%(prod_user)s/niteoweb.%(shortname)s/var' % env):

        ### Downlaod Data.fs ###
        # backup current Data.fs
        if os.path.exists('filestorage/Data.fs'):
            local('mv %(path)s/var/filestorage/Data.fs %(path)s/var/filestorage/Data.fs.bak' % env)

        # remove temporary Data.fs file from previous downloads
        if exists('/tmp/Data.fs', use_sudo=True):
            sudo('rm -rf /tmp/Data.fs')

        # downlaod Data.fs from server
        sudo('rsync -a filestorage/Data.fs /tmp/Data.fs')
        get('/tmp/Data.fs', '%(path)s/var/filestorage/Data.fs' % env)

        ### Download Blobs ###
        # backup current Blobs
        if os.path.exists('%(path)s/var/blobstorage' % env):
            local('mv %(path)s/var/blobstorage %(path)s/var/blobstorage_bak' % env)

        # remove temporary Blobs from previous downloads
        if exists('/tmp/blobstorage', use_sudo=True):
            sudo('rm -rf /tmp/blobstorage')

        # download Blobs from server -> use maintenance user for transfer
        sudo('rsync -a blobstorage /tmp/')
        sudo('chown -R %(user)s /tmp/blobstorage' % env)
        local('rsync -az %(user)[email protected]%(server)s:/tmp/blobstorage %(path)s/var/' % env)
Example #19
0
def setup_capsules(path):
    """Reads the configuration, create capsules and start content sync on
    them.
    """
    load_capsule_config(path)
    config = env.capsule_config
    server = config.server.host_string

    # Let Fabric know how to log into the hosts
    env.passwords = config.passwords
    env.key_filename = config.key_filenames

    # The oauth information is needed for every capsule register. Cache this
    # information.
    with settings(host_string=server):
        oauth_info = get_oauth_info()

    # Register each capsule on the server
    for capsule in config.capsules:
        with settings(host_string=server):
            cert_path = generate_capsule_certs(capsule.hostname)
            get(remote_path=cert_path, local_path=cert_path)

        with settings(host_string=capsule.host_string):
            register_capsule()
            put(local_path=cert_path)
            capsule_installer(capsule.hostname, cert_path, *oauth_info)
Example #20
0
def get_postgres_dump(dbname, ignore_permissions=False, file_name=None):
    """Get a dump of the database from the server.

    :param dbname: name of the database to restore the dump into.
    :type dbname: str

    :param ignore_permissions: whether permissions in the created dump
        should be preserved.
    :type ignore_permissions: bool (default False)

    :param file_name: optional file name for the dump. The file name should
        exclude any path. If file_name is ommitted, the dump will be written to
        fabgis_resources/sql/dumps/<dbname>->date>.dmp
        where date is in the form dd-mm-yyyy. This is the default naming
        convention used by the :func:`restore_postgres_dump` function below.
    :type file_name: str
    """
    setup_env()

    if file_name is None or file_name == '':
        date = run('date +%d-%B-%Y')
        my_file = '%s-%s.dmp' % (dbname, date)
    else:
        my_file = os.path.split(file_name)[1]
        put(file_name, '/tmp/%s' % my_file)

    if not ignore_permissions:
        extra_args = ''
    else:
        extra_args = '-x -O'

    run('pg_dump %s -Fc -f /tmp/%s %s' % (extra_args, my_file, dbname))
    get('/tmp/%s' % my_file, 'fabgis_resources/sql/dumps/%s' % my_file)
Example #21
0
def clone_repo():
    """Clone the wonderhop repo on the server"""
    # Add known hosts for Github
    append("~/.ssh/known_hosts", [
        "|1|AxYrTZcwBIPIFSdy29CGanv85ZE=|D0Xa0QCz1anXJ9JrH4eJI3EORH8= ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAq2A7hRGmdnm9tUDbO9IDSwBK6TbQa+PXYPCPy6rbTrTtw7PHkccKrpp0yVhp5HdEIcKr6pLlVDBfOLX9QUsyCOV0wzfjIJNlGEYsdlLJizHhbn2mUjvSAHQqZETYP81eFzLQNnPHt4EVVUh7VfDESU84KezmD5QlWpXLmvU31/yMf+Se8xhHTvKSCZIFImWwoG6mbUoWf9nzpIoaSjB+weqqUUmpaaasXVal72J+UX2B+2RPW3RcT0eOzQgqlJL3RKrTJvdsjE3JEAvGq3lGHSZXy28G3skua2SmVi/w4yCE6gbODqnTWlg7+wC604ydGXA8VJiS5ap43JXiUFFAaQ==",
        "|1|ErT4pRs4faesbyNw+WB0hWuIycs=|9+4iN3FDijMOl1Z+2PNB9O9wXjw= ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAq2A7hRGmdnm9tUDbO9IDSwBK6TbQa+PXYPCPy6rbTrTtw7PHkccKrpp0yVhp5HdEIcKr6pLlVDBfOLX9QUsyCOV0wzfjIJNlGEYsdlLJizHhbn2mUjvSAHQqZETYP81eFzLQNnPHt4EVVUh7VfDESU84KezmD5QlWpXLmvU31/yMf+Se8xhHTvKSCZIFImWwoG6mbUoWf9nzpIoaSjB+weqqUUmpaaasXVal72J+UX2B+2RPW3RcT0eOzQgqlJL3RKrTJvdsjE3JEAvGq3lGHSZXy28G3skua2SmVi/w4yCE6gbODqnTWlg7+wC604ydGXA8VJiS5ap43JXiUFFAaQ==",
    ])
    
    if not exists("~/.ssh/id_github_deploy"):
        # Generate a public/private key pair
        run("ssh-keygen -q -t rsa -f ~/.ssh/id_github_deploy -N ''")
        
        ssh_pub_key = StringIO()
        get("~/.ssh/id_github_deploy.pub", ssh_pub_key)
        ssh_pub_key = ssh_pub_key.getvalue().strip()
        
        # Add it to Github
        gh_user = prompt("Github username?")
        gh_pass = getpass("Github password? ")
        urllib2.urlopen(urllib2.Request("https://api.github.com/repos/wonderhop/wonderhop/keys", json.dumps({
            "title": "[email protected]{0}".format(env.host),
            "key": ssh_pub_key,
        }), {
            "Content-Type": "application/json",
            "Authorization": "Basic {0}".format(base64.b64encode("{0}:{1}".format(gh_user, gh_pass))),
        }))
        
        # Specify that we should use the given key for Github
        append("~/.ssh/config", "Host github.com\nIdentityFile ~/.ssh/id_github_deploy")
    
    run("git clone [email protected]:wonderhop/wonderhop.git")
    def run(self):
        if self.stderr_temp:
            stderr_tuple = tempfile.mkstemp()
            os.close(stderr_tuple[0])
            self.stderr_file = stderr_tuple[1]

        # We will manually check return code
        remote_stdout = run("mktemp /tmp/collectoutput.XXXXXXXXXX").strip()
        remote_stderr = run("mktemp /tmp/collecterror.XXXXXXXXXX").strip()
        remote_rawp = "/tmp/%s" % os.path.basename(self.rawp_file)
        put(self.rawp_file, remote_rawp)

        with settings(warn_only=True):
            collectl_command_line_builder = CollectlCommandLineBuilder(self.collectl_path)
            command_line = collectl_command_line_builder.get(remote_rawp)
            command_output = run("%s > %s 2> %s" % (command_line, remote_stdout, remote_stderr))
            return_code = command_output.return_code

        local("rm %s" % self.collectl_output_file)
        local("rm %s" % self.stderr_file)
        get(remote_stdout, self.collectl_output_file)
        get(remote_stderr, self.stderr_file)

        if return_code != 0:
            stderr_contents = self.__read_stderr()
            raise RuntimeError("collectl did not return a status code of 0, process standard error was %s" % stderr_contents)

        if self.stderr_temp:
            os.remove(self.stderr_file)
Example #23
0
def copy_resource(container, resource, local_filename, contents_only=True):
    """
    Copies a resource from a container to a compressed tarball and downloads it.

    :param container: Container name or id.
    :type container: unicode
    :param resource: Name of resource to copy.
    :type resource: unicode
    :param local_filename: Path to store the tarball locally.
    :type local_filename: unicode
    :param contents_only: In case ``resource`` is a directory, put all contents at the root of the tar file. If this is
      set to ``False``, the directory itself will be at the root instead.
    :type contents_only: bool
    """
    with temp_dir() as remote_tmp:
        base_name = os.path.basename(resource)
        copy_path = posixpath.join(remote_tmp, 'copy_tmp')
        run(mkdir(copy_path, check_if_exists=True))
        remote_name = posixpath.join(copy_path, base_name)
        archive_name = 'container_{0}.tar.gz'.format(container)
        archive_path = posixpath.join(remote_tmp, archive_name)
        run('docker cp {0}:{1} {2}'.format(container, resource, copy_path), shell=False)
        if contents_only and is_directory(remote_name):
            src_dir = remote_name
            src_files = '*'
        else:
            src_dir = copy_path
            src_files = base_name
        with cd(src_dir):
            run(targz(archive_path, src_files))
        get(archive_path, local_filename)
Example #24
0
    def fetch_compressed(self, src, dest=None):
        """Create a tarball and fetch it locally"""
        self.logger.debug("Creating tarball of %s" % src)
        basename = os.path.basename(src)
        tar_file = basename + ".tgz"
        cmd = "tar czf %s %s" % (tar_file, src)
        _run(cmd, False)
        if not os.path.exists(dest):
            os.makedirs(dest)

        tmp_dir = tempfile.mkdtemp()
        fabric.get(tar_file, tmp_dir)

        dest_file = os.path.join(tmp_dir, tar_file)
        self._check_hash_sum(dest_file, tar_file)
        self.logger.debug("Untar packages file %s" % dest_file)
        cmd = """
        cd %s
        tar xzf %s
        cp -r %s/* %s
        rm -r %s
        """ % (tmp_dir, tar_file, src, dest, tmp_dir)
        os.system(cmd)
        self.logger.info("Downloaded %s to %s" %
                         (src, _green(dest)))
Example #25
0
def pull():
    """ updates development environment """

    x = prompt(blue('Reset local database (r) or flush (f)?'), default="f")

    if x == 'r':
        reset_local_db()
    elif x == 'f':
        print(red(" * flushing database..."))
        local('cd %s '
              '&& . %s '
              '&& python manage.py flush' % (PROJECT_PATH, VIRTUAL_ENVIRONMENT))

    print(red(" * creating database dump..."))
    run('cd %s '
        '&& source venv/bin/activate '
        '&& python manage.py dumpdata --natural-foreign -e contenttypes -e auth.Permission > data.json' % env.path)

    print(red(" * downloading dump..."))
    get('%s/data.json' % env.path, '/tmp/data.json')

    print(red(" * importing the dump locally..."))
    local('cd %s '
          '&& . %s '
          '&& python manage.py loaddata /tmp/data.json' % (PROJECT_PATH, VIRTUAL_ENVIRONMENT), capture=False)

    print(red(" * removing database dump..."))
    run('rm %s/data.json' % env.path)

    print(red(" * syncing media files..."))
    rsync_project('%s/' % env.media_path, settings.MEDIA_ROOT, upload=False, delete=True)
Example #26
0
 def test_abort_returns_nonzero_exit_code(self):
     from datetime import datetime
     error_msg = 'oops_we_got_an_error'
     timestamp = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
     output_file_path = \
         '/tmp/{0}-{1}.log'.format(self._testMethodName, timestamp)
     try:
         self._execute(
             'test.run_script',
             script_path='scripts/script.sh',
             process={
                 'env': {
                     'test_operation': self._testMethodName,
                     'error_msg': error_msg,
                     'output_file': output_file_path
                 }
             })
         self.fail('expected to raise an exception')
     except NonRecoverableError as e:
         self.assertEquals(error_msg, e.message)
         # verify that ctx outputs error message to stderr
         _, output_local_copy_path = tempfile.mkstemp()
         with context_managers.settings(**self.default_fabric_env):
             api.get(remote_path=output_file_path,
                     local_path=output_local_copy_path)
             with open(output_local_copy_path, 'r') as output_file:
                 self.assertEquals(error_msg, output_file.read().strip())
Example #27
0
def get(file, target=None):
    """Download the specified files from the remote buildout folder"""
    if not target:
        target = file
    if not file.startswith('/'):
        file = api.env.path + '/' + file
    api.get(file, target)
Example #28
0
def fetch_conf(output=None, stagedir=None, local_exe=None):
    remote_output = "%s/bootout.json" % (stagedir)

    if local_exe:
        shutil.copy(remote_output, output)
    else:
        get(remote_output, output)
Example #29
0
 def test_get_with_format_chars_on_server(self):
     """
     get('*') with format symbols (%) on remote paths should not break
     """
     remote = '*'
     with hide('everything'):
         get(remote, self.path())
Example #30
0
def collect_reports(worker_root, project_name):
    """docstring for collect_reports"""
    results_path = os.path.join(worker_root, project_name, 'results')
    with cd(results_path):
        print "\nStart to collect result files"
        get('*.xml', './')
        run('rm -rf *.xml')