Esempio n. 1
0
def provision(path, environment, machineName, host):
    new_env = resetEnv(host, environment)
    # logger.debug('Running provision on {} with env {}'
    #            .format(path, environment))
    old_path = os.getcwd()
    jobid = get_current_job().id
    try:
        os.chdir(path)
        _open_console(jobid)
        if machineName != '':
            _l = lambda line: _log_console(jobid, str(line))
            sh.vagrant('provision', machineName,
                       _ok_code=[0, 1, 2],
                       _out=_l, _err=_l,
                       _env=new_env).wait()
        else:
            _l = lambda line: _log_console(jobid, str(line))
            sh.vagrant('provision',
                       _ok_code=[0, 1, 2],
                       _out=_l, _err=_l,
                       _env=new_env).wait()
    except:
        logger.error('Failed to provision machine at {}'.format(path),
                     exc_info=True)
    _close_console(jobid)
    os.chdir(old_path)
    return json.dumps(_get_status(path, host, environment))
Esempio n. 2
0
def stop(path, machineName, host, environment):
    new_env = resetEnv(host, environment)
    logger.debug('Bring down {}'.format(path))
    old_path = os.getcwd()
    jobid = get_current_job().id
    try:
        os.chdir(path)
        _open_console(jobid)
        if machineName != '':
            _l = lambda line: _log_console(jobid, str(line))
            sh.vagrant('halt', machineName,
                       _ok_code=[0, 1, 2],
                       _out=_l, _err=_l,
                       _env=new_env).wait()
        else:
            _l = lambda line: _log_console(jobid, str(line))
            sh.vagrant('halt',
                       _ok_code=[0, 1, 2],
                       _out=_l, _err=_l,
                       _env=new_env).wait()
    except:
        logger.error('Failed to shut down machine {}'.format(path),
                     exc_info=True)

    _close_console(jobid)
    os.chdir(old_path)
    # logger.debug('Done bring down {}'.format(path))
    return json.dumps(_get_status(path, host, environment))
Esempio n. 3
0
def stop(path, machineName, host, environment):
    new_env = resetEnv(host, environment)
    logger.debug('Bring down {}'.format(path))
    old_path = os.getcwd()
    jobid = get_current_job().id
    try:
        os.chdir(path)
        _open_console(jobid)
        if machineName != '':
            _l = lambda line: _log_console(jobid, str(line))
            sh.vagrant('halt',
                       machineName,
                       _ok_code=[0, 1, 2],
                       _out=_l,
                       _err=_l,
                       _env=new_env).wait()
        else:
            _l = lambda line: _log_console(jobid, str(line))
            sh.vagrant('halt',
                       _ok_code=[0, 1, 2],
                       _out=_l,
                       _err=_l,
                       _env=new_env).wait()
    except:
        logger.error('Failed to shut down machine {}'.format(path),
                     exc_info=True)

    _close_console(jobid)
    os.chdir(old_path)
    # logger.debug('Done bring down {}'.format(path))
    return json.dumps(_get_status(path, host, environment))
Esempio n. 4
0
def provision(path, environment, machineName, host):
    new_env = resetEnv(host, environment)
    # logger.debug('Running provision on {} with env {}'
    #            .format(path, environment))
    old_path = os.getcwd()
    jobid = get_current_job().id
    try:
        os.chdir(path)
        _open_console(jobid)
        if machineName != '':
            _l = lambda line: _log_console(jobid, str(line))
            sh.vagrant('provision',
                       machineName,
                       _ok_code=[0, 1, 2],
                       _out=_l,
                       _err=_l,
                       _env=new_env).wait()
        else:
            _l = lambda line: _log_console(jobid, str(line))
            sh.vagrant('provision',
                       _ok_code=[0, 1, 2],
                       _out=_l,
                       _err=_l,
                       _env=new_env).wait()
    except:
        logger.error('Failed to provision machine at {}'.format(path),
                     exc_info=True)
    _close_console(jobid)
    os.chdir(old_path)
    return json.dumps(_get_status(path, host, environment))
Esempio n. 5
0
def ip(path, host, environment, machineName='default'):
    logger.debug('Getting IP from vagrant machine {}'.format(machineName))
    new_env = resetEnv(host)
    ip = ''
    old_path = os.getcwd()
    os.chdir(path)

    try:
        machineType = sh.vagrant('status', machineName, _env=new_env)

        if 'stopped' not in machineType:
            if 'virtualbox' in machineType:
                ips = sh.vagrant('ssh', machineName, '-c', 'ip addr list eth1',
                                 _env=new_env)
                ips = str(ips)
                search = re.match(r'.* inet (.*)/24 brd',
                                  ips.stdout.replace('\n', ''))

                if search:
                    ip = search.group(1)
            elif 'lxc' in machineType or 'vsphere' in machineType:
                ips = sh.vagrant('ssh-config', machineName, _env=new_env)
                ips = str(ips)
                search = re.findall('HostName (.*)\n', ips, re.M)
                if search:
                    ip = search[0]
                # logger.debug(ip)

    except:
        logger.error('Unable to connect to machine to it\'s IP :: {}'
                     .format(path))

    os.chdir(old_path)
    return ip
Esempio n. 6
0
def rsync(path, host, environment, machineName=None):
    new_env = resetEnv(host, environment)
    old_path = os.getcwd()
    os.chdir(path)
    try:
        jobid = get_current_job().id
        _open_console(jobid)
        _log_console(
            jobid,
            'Running rsync on machine {}.\n'.format(machineName)
        )

        _l = lambda line: _log_console(jobid, str(line))

        if machineName is not None:
            sh.vagrant('rsync', machineName,
                       _out=_l,
                       _err=_l,
                       _ok_code=[0, 1, 2],
                       _env=new_env).wait()
        else:
            sh.vagrant('rsync',
                       _out=_l,
                       _err=_l,
                       _ok_code=[0, 1, 2],
                       _env=new_env).wait()
        _log_console(
            jobid,
            'rsync is done running on machine {}.\n'.format(machineName))
        _close_console(jobid)
    except:
        return json.dumps({'msg': 'error trying to run vagrant rsync'})
    os.chdir(old_path)
    return json.dumps({'msg': 'rsync done'})
Esempio n. 7
0
def destroy(path, host, environment):
    new_env = resetEnv(host, environment)
    old_path = os.getcwd()
    try:
        if os.path.isdir(path):
            os.chdir(path)
            sh.vagrant('destroy', _env=new_env)
            os.chdir(old_path)
            sh.rm('-rf', path)

    except:
        logger.error('Failed to destroy machine {}'.format(path),
                     exc_info=True)

    return json.dumps(_get_status(path, host, environment))
Esempio n. 8
0
def destroy(path, host, environment):
    new_env = resetEnv(host, environment)
    old_path = os.getcwd()
    try:
        if os.path.isdir(path):
            os.chdir(path)
            sh.vagrant('destroy', _env=new_env)
            os.chdir(old_path)
            sh.rm('-rf', path)

    except:
        logger.error('Failed to destroy machine {}'.format(path),
                     exc_info=True)

    return json.dumps(_get_status(path, host, environment))
def main():

    results = {
        'argv': sys.argv[:],
        'changed': False,
        'stdin': sys.stdin.read(),
        #'env': dict(os.environ)
    }

    argfile = sys.argv[1]
    with open(argfile, 'r') as f:
        args = f.read()
    args = split_args(args)
    results['args'] = args

    assert 'boxpath' in args, 'args must contain a boxpath'

    boxpath = args['boxpath']
    boxpath = boxpath.replace("'", "")
    boxpath = boxpath.replace('"', "")
    boxpath = os.path.expanduser(boxpath)
    boxpath = os.path.abspath(boxpath)
    pid = vagrant('ssh-config', _cwd=boxpath)
    pid.wait()
    results['ssh_config'] = split_ssh_config(pid.stdout)

    print(json.dumps(results))
def main():
    
    results = {
        'argv': sys.argv[:],
        'changed': False,
        'stdin': sys.stdin.read(),
        #'env': dict(os.environ)
    }

    argfile = sys.argv[1]
    with open(argfile, 'r') as f:
        args = f.read()
    args = split_args(args)
    results['args'] = args

    assert 'boxpath' in args, 'args must contain a boxpath'

    boxpath = args['boxpath']
    boxpath = boxpath.replace("'", "")
    boxpath = boxpath.replace('"', "")
    boxpath = os.path.expanduser(boxpath)
    boxpath = os.path.abspath(boxpath)
    pid = vagrant('ssh-config', _cwd=boxpath)
    pid.wait()
    results['ssh_config'] = split_ssh_config(pid.stdout)

    print(json.dumps(results))    
Esempio n. 11
0
def run_script(path, host, script, machineName='default'):
    new_env = resetEnv(host)
    old_path = os.getcwd()
    try:
        logger.debug(
            'Running script {} on machine {}'.format(script, machineName)
        )
        jeto_infos = _read_jeto_file(path)
        all_scripts = jeto_infos.get('scripts')
        logger.debug(all_scripts)
        if all_scripts.get(script, None) and\
                all_scripts.get(script, None).get('command', None):
            os.chdir(path)
            jobid = get_current_job().id
            _open_console(jobid)
            _log_console(
                jobid,
                'Running {} on machine {}.\n'.format(script, machineName)
            )

            _l = lambda line: _log_console(jobid, str(line))

            sh.vagrant('ssh', '-c',
                       all_scripts.get(script).get('command'),
                       _out=_l,
                       _err=_l,
                       _ok_code=[0, 1, 2],
                       _env=new_env).wait()
            _log_console(
                jobid,
                '{} is done running on machine {}.\n'.format(
                    script, machineName))
            _close_console(jobid)
    except:
        e = sys.exc_info()
        logger.error(
            'Failed to run script {} of the machine {}'.format(script, path),
            exc_info=True
        )
        _log_console(
            jobid,
            'Failed to run script {} of the machine {}\n Exception: {}.\n'.format(
                script, machineName, e))
    _close_console(jobid)

    os.chdir(old_path)
Esempio n. 12
0
def destroy(path, host, environment):
    new_env = resetEnv(host, environment)
    # old current working dir won't exist after destroy
    # keep parent's path
    old_path = os.path.dirname(
                    os.path.dirname(os.getcwd()))
    try:
        if os.path.isdir(path):
            os.chdir(path)
            sh.vagrant('destroy', '--force', _env=new_env)
            os.chdir(old_path)
            sh.rm('-rf', path)

    except:
        logger.error('Failed to destroy machine {}'.format(path),
                     exc_info=True)

    return json.dumps(_get_status(path, host, environment))
Esempio n. 13
0
 def image_list(self):
     images = {}
     lines = vagrant("box", "list")
     for line in lines:
         (name, kind) = line.split("(")
         name = name.strip()
         kind = kind.split(")")[0].strip()
         images[name] = {"name": name, "kind": kind}
     return images
Esempio n. 14
0
 def image_list(self):
     images = {}
     lines = vagrant("box", "list")
     for line in lines:
         (name, kind) = line.split("(")
         name = name.strip()
         kind = kind.split(")")[0].strip()
         images[name] = {"name": name, "kind": kind}
     return images
Esempio n. 15
0
def main():

    print('Starting vagrant rsync auto service.')

    #INITIALIZE
    vagrant('global-status', _bg=True, _out=vagrant_status_out).wait()
    last = time.time()

    handler = VagrantEventHandler()
    observer = Observer()
    watchers = {}

    #START WATCHING
    try:
        observer.start()
        while True:

            vagrant_dirs = set(vagrant_rsync_dirs.keys())
            watched_dirs = set(watchers.keys())

            for d in (vagrant_dirs - watched_dirs):
                watchers[d] = observer.schedule(handler, d, recursive=True)
                print('Observer is watching {}'.format(d))

            for d in (watched_dirs - vagrant_dirs):
                w = watchers.pop(d)
                observer.unschedule(w)
                print('Observer has stopped watching {}'.format(d))


            time.sleep(SLEEP_INTERVAL)
            passed = time.time() - last
            if passed > CHECK_INTERVAL:
                vagrant('global-status', _bg=True, _out=vagrant_status_out)
                last = time.time()

    #SHUT DOWN
    except KeyboardInterrupt:
        print(' << (*) >> ')
        observer.stop()

    observer.join()
    print('Goodbye :-)')
Esempio n. 16
0
def run_script(path, host, script, machineName='default'):
    new_env = resetEnv(host)
    old_path = os.getcwd()
    try:
        logger.debug('Running script {} on machine {}'.format(
            script, machineName))
        jeto_infos = _read_jeto_file(path)
        all_scripts = jeto_infos.get('scripts')
        logger.debug(all_scripts)
        if all_scripts.get(script, None) and\
                all_scripts.get(script, None).get('command', None):
            os.chdir(path)
            jobid = get_current_job().id
            _open_console(jobid)
            _log_console(
                jobid,
                'Running {} on machine {}.\n'.format(script, machineName))

            _l = lambda line: _log_console(jobid, str(line))

            sh.vagrant('ssh',
                       '-c',
                       all_scripts.get(script).get('command'),
                       _out=_l,
                       _err=_l,
                       _ok_code=[0, 1, 2],
                       _env=new_env).wait()
            _log_console(
                jobid, '{} is done running on machine {}.\n'.format(
                    script, machineName))
            _close_console(jobid)
    except:
        e = sys.exc_info()
        logger.error('Failed to run script {} of the machine {}'.format(
            script, path),
                     exc_info=True)
        _log_console(
            jobid,
            'Failed to run script {} of the machine {}\n Exception: {}.\n'.
            format(script, machineName, e))
    _close_console(jobid)

    os.chdir(old_path)
Esempio n. 17
0
def get_boxes(kind):
    lines = vagrant("box", "list")

    boxes = []
    for line in lines:
        (OS, KIND) = line.split("(")
        OS = OS.strip()
        (KIND, rest) = KIND.split(")")
        if kind == KIND:
            boxes.append(OS)
    return boxes
Esempio n. 18
0
def get_boxes(kind):
    lines = vagrant("box","list")

    boxes = []
    for line in lines:
        (OS, KIND) = line.split("(")
        OS = OS.strip()
        (KIND, rest) = KIND.split(")")
        if kind == KIND:
            boxes.append(OS)
    return boxes
Esempio n. 19
0
def _get_status(path, host, environment):
    new_env = resetEnv(host, environment)
    old_path = os.getcwd()
    statuses = None
    try:
        jobid = get_current_job().id
        os.chdir(path)
        _open_console(jobid, private=True)
        _l = lambda line: _log_console(jobid, str(line), private=True)
        sh.vagrant('status', '--machine-readable', '--debug',
                   _out=_l,
                   _ok_code=[0, 1, 2],
                   _env=new_env).wait()
        _close_console(jobid, private=True)

        statuses = _read_console(jobid, private=True)
    except:
        logger.error('Failed to get status of the machine {}'.format(path),
                     exc_info=True)

    os.chdir(old_path)
    return statuses
Esempio n. 20
0
def ip(path, host, environment, machineName='default'):
    logger.debug('Getting IP from vagrant machine {}'.format(machineName))
    new_env = resetEnv(host)
    ip = ''
    old_path = os.getcwd()
    os.chdir(path)

    try:
        machineType = sh.vagrant('status', machineName, _env=new_env)

        if 'stopped' not in machineType:
            if 'virtualbox' in machineType:
                ips = sh.vagrant('ssh',
                                 machineName,
                                 '-c',
                                 'ip addr list eth1',
                                 _env=new_env)
                ips = str(ips)
                search = re.match(r'.* inet (.*)/24 brd',
                                  ips.stdout.replace('\n', ''))

                if search:
                    ip = search.group(1)
            elif 'lxc' in machineType or 'vsphere' in machineType:
                ips = sh.vagrant('ssh-config', machineName, _env=new_env)
                ips = str(ips)
                search = re.findall('HostName (.*)\n', ips, re.M)
                if search:
                    ip = search[0]
                # logger.debug(ip)

    except:
        logger.error(
            'Unable to connect to machine to it\'s IP :: {}'.format(path))

    os.chdir(old_path)
    return ip
Esempio n. 21
0
def _get_status(path, host, environment):
    new_env = resetEnv(host, environment)
    old_path = os.getcwd()
    statuses = None
    try:
        jobid = get_current_job().id
        os.chdir(path)
        _open_console(jobid, private=True)
        _l = lambda line: _log_console(jobid, str(line), private=True)
        sh.vagrant('status',
                   '--machine-readable',
                   '--debug',
                   _out=_l,
                   _ok_code=[0, 1, 2],
                   _env=new_env).wait()
        _close_console(jobid, private=True)

        statuses = _read_console(jobid, private=True)
    except:
        logger.error('Failed to get status of the machine {}'.format(path),
                     exc_info=True)

    os.chdir(old_path)
    return statuses
Esempio n. 22
0
def setenv():
    if 'Docker version 1.1.2' not in sh.docker(version=True):
        raise RuntimeError('Tested with docker 1.1.2 only. If you know this will work with other versions, '
                           'Update this code to be more flexible')
    if 'Vagrant 1.6.3' not in sh.vagrant(version=True):
        raise RuntimeError('Tested with vagrant 1.6.3 only. If you know this will work with other versions, '
                           'Update this code to be more flexible')
    for env_var, default_value in env_variables.items():
        if default_value and not os.environ.get(env_var):
            os.environ[env_var] = default_value
    cloudify_enviroment_varaible_names = ':'.join(env_variables.keys())
    os.environ['CLOUDIFY_ENVIRONMENT_VARIABLE_NAMES'] = cloudify_enviroment_varaible_names
    if not os.environ.get('TEST_SUITES_PATH'):
        suite_json_path = build_suites_json('suites/suites.json')
        os.environ['TEST_SUITES_PATH'] = suite_json_path
Esempio n. 23
0
    def on_any_event(self, event):
        if event.is_directory:
            return

        directory, names = self.get_names(event.src_path)

        if directory is None and names is None:
            error = 'Unable to find appropriate machine name\
            for event in {}'
            print(error.format(event.src_path))
            return

        os.chdir(directory)
        for name in names:
            t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            print('{} >>"vagrant rsync {}" in {}'.format(t, name, directory))
            try:
                vagrant('rsync', name,
                    _bg=True,
                    _tty_in=True,
                    _out=vagrant_rsync_out).wait()
            except Exception as e:
                error = '  >> ERROR: Could not sync {} in {}'
                print(error.format(name, directory))
Esempio n. 24
0
def run(path, environment, host, machineName):
    old_path = os.getcwd()
    new_env = resetEnv(host=host, environment=environment)

    jobid = get_current_job().id
    _open_console(jobid)

    status = _get_status(path, host, environment)
    _l = lambda line: _log_console(jobid, str(line))
    if 'not created' not in status and host.provider not in status:
        try:
            logger.debug('Destroying machine {} for provider {}'.format(
                path, host.provider))
            os.chdir(path)
            sh.vagrant('destroy',
                       _ok_code=[0, 1, 2],
                       _out=_l,
                       _err=_l,
                       _env=new_env).wait()
            os.chdir(old_path)

        except:
            logger.error('Failed to destroy machine {}'.format(path))

    try:
        os.chdir(path)

        if machineName != '':
            sh.vagrant('up',
                       machineName,
                       _ok_code=[0, 1, 2],
                       _out=_l,
                       _err=_l,
                       _env=new_env).wait()
        else:
            sh.vagrant('up',
                       _env=new_env,
                       _ok_code=[0, 1, 2],
                       _out=_l,
                       _err=_l).wait()
        os.chdir(old_path)

    except ErrorReturnCode, e:
        for line in e.message.splitlines():
            logger.debug(line)
            _log_console(jobid, line)
Esempio n. 25
0
def run(path, environment, host, machineName):
    old_path = os.getcwd()
    new_env = resetEnv(host=host, environment=environment)

    jobid = get_current_job().id
    _open_console(jobid)

    status = _get_status(path, host, environment)
    _l = lambda line: _log_console(jobid, str(line))
    if 'not created' not in status and host.provider not in status:
        try:
            logger.debug('Destroying machine {} for provider {}'
                         .format(path, host.provider))
            os.chdir(path)
            sh.vagrant('destroy', _ok_code=[0, 1, 2],
                       _out=_l, _err=_l,
                       _env=new_env).wait()
            os.chdir(old_path)

        except:
            logger.error('Failed to destroy machine {}'.format(path))

    try:
        os.chdir(path)

        if machineName != '':
            sh.vagrant('up', machineName,
                       _ok_code=[0, 1, 2],
                       _out=_l, _err=_l,
                       _env=new_env).wait()
        else:
            sh.vagrant('up', _env=new_env,
                       _ok_code=[0, 1, 2],
                       _out=_l, _err=_l).wait()
        os.chdir(old_path)

    except ErrorReturnCode, e:
        for line in e.message.splitlines():
            logger.debug(line)
            _log_console(jobid, line)
Esempio n. 26
0
def version():
    try:
        from sh import vagrant
        return str(vagrant('--version'))[8:].rstrip()
    except ImportError:
        return None
Esempio n. 27
0
 def global_status(self):
     """Return vagrant machine status."""
     ret = vagrant("global-status")
     return ret
Esempio n. 28
0
 def info(self):
     """Return vagrant machine status."""
     ret = vagrant("ssh-config",self._hostname)
     return ret
Esempio n. 29
0
 def terminate(self, worker):
     sh.vagrant('halt', 'worker')
Esempio n. 30
0
 def global_status(self):
     """Return vagrant machine status."""
     ret = vagrant("global-status")
     return ret
Esempio n. 31
0
 def info(self):
     """Return vagrant machine status."""
     ret = vagrant("ssh-config", self._hostname)
     return ret