def known_hosts(vagrant_root):
    vagrant_root = lookup_vagrant_root(vagrant_root)
    vagrant = Vagrant(vagrant_root)
    return {
        machine: vagrant.hostname(machine)
        for machine in list_machines(vagrant_root)
    }
def known_hosts(vagrant_root, name=None):
    vagrant_root = lookup_vagrant_root(vagrant_root)
    vagrant = Vagrant(vagrant_root)

    machines = list_machines(vagrant_root)
    name = name if name in machines else machines[0]

    return parse_content(
        vagrant._run_vagrant_command(('ssh', name, '-c', 'cat /etc/hosts')))
Exemplo n.º 3
0
    def execute_vagrant_command_on_minion(self, project_name, command):
        minion_path = self.parent.config['minions'][project_name]
        vagrant = Vagrant(minion_path, quiet_stdout=False, quiet_stderr=False)

        puts(
            colored.blue("Execute vagrant %s on minion %s" %
                         (command, project_name)))
        getattr(vagrant, command)()

        puts(colored.blue("Done"))
Exemplo n.º 4
0
 def main(self):
     for minion_name, minion_path in self.parent.config.get('minions',
                                                            {}).items():
         vagrant = Vagrant(minion_path)
         vagrant_status = vagrant.status()[0].state
         salt_status = self.parent.client.get_minion_status(minion_name)
         puts("%s:" % minion_name)
         with indent(4):
             puts("vagrant status: %s" % vagrant_status)
             puts("saltstack status: %s" % salt_status)
Exemplo n.º 5
0
 def __init__(self, *args, **kwargs):
     """Check that the vagrant_boxes attribute is not left empty, and is populated by all boxes if left blank"""
     self.vagrant = Vagrant(self.vagrant_root)
     if not self.vagrant_boxes:
         boxes = self.vagrant.status().keys()
         if len(boxes) == 1:
             self.vagrant_boxes = ['default']
         else:
             self.vagrant_boxes = boxes
     super(VagrantTestCase, self).__init__(*args, **kwargs)
Exemplo n.º 6
0
 def __init__(self, *args, **kwargs):
     """Check that the vagrant_boxes attribute is not left empty, and is populated by all boxes if left blank"""
     self.vagrant = Vagrant(self.vagrant_root, err_cm=stderr_cm)
     if not self.vagrant_boxes:
         boxes = [s.name for s in self.vagrant.status()]
         if len(boxes) == 1:
             self.vagrant_boxes = ["default"]
         else:
             self.vagrant_boxes = boxes
     super().__init__(*args, **kwargs)
Exemplo n.º 7
0
def vagrant():
    v = Vagrant(os.path.dirname(__file__))

    # Start remote VM first so local VM can copy its SSH key to it afterwards
    v.up(vm_name="remote")
    v.up(vm_name="local")

    yield v

    v.halt()
Exemplo n.º 8
0
 def __init__(self, host='default', vagrantDir=None, controlVagrant=True):
     global _defaultVagrantDir
     self.host = host
     self._controlVagrant = controlVagrant
     if vagrantDir is None:
         vagrantDir = _defaultVagrantDir
     self._vagrant = Vagrant(root=vagrantDir)
     self._startedVagrant = False
     self._sshClient = None
     self._sshConfigStr = None
     self._sshConfig = None
     self._sshHostConfig = None
Exemplo n.º 9
0
 def __enter__(self):
     # We want to start with a clean environment every time.
     if os.path.exists(SINGULARITY_VM_INPUT_DIR):
         rmtree(SINGULARITY_VM_INPUT_DIR)
     if os.path.exists(SINGULARITY_VM_OUTPUT_DIR):
         rmtree(SINGULARITY_VM_OUTPUT_DIR)
     makedirs(SINGULARITY_VM_OUTPUT_DIR)
     copytree(self.path_to_build, SINGULARITY_VM_INPUT_DIR, symlinks=True)
     self.vm = Vagrant(root=SINGULARITY_VM,
                       quiet_stdout=False,
                       quiet_stderr=False)
     return self
Exemplo n.º 10
0
    def __init__(self, vagrantfile):
        """ Configure logging. """

        # Use the logger object created by Client.
        self.p = logging.getLogger('qb')

        self.p.debug("Using Vagrant config:\n"
                     "     Vagrantfile: %s" % vagrantfile)

        # Create a Vagrant object.
        self.vagrant = Vagrant(vagrantfile)

        return
Exemplo n.º 11
0
    def do_clean(self, project_name):
        minion_path = self.parent.config['minions'][project_name]

        # Check if sahara is available
        minion_path = self.parent.config['minions'][project_name]
        try:
            plugins = Vagrant(minion_path).plugin_list()
        except Exception as e:
            raise

        sahara = bool([p for p in plugins if p.name == "sahara"])

        # Check sandbox status
        sandbox_status = 'off'
        if sahara:
            sandbox = SandboxVagrant(minion_path)
            sandbox_status = sandbox.sandbox_status()

        # If sandbox is activated, rollback only
        if sandbox_status == 'on' and not self.force_clean:
            message = "Rollback snapshot, if you will delete snapshot, use "\
                      "--force-clean option"
            puts(colored.blue(message))
            sandbox.sandbox_rollback()
            puts(colored.blue("Done"))

            command = "sudo /etc/init.d/salt-minion restart"
            result = get_output_cmd(command, minion_path)

            puts(colored.blue("Restarted salt-minion"))

            puts(colored.blue("Wait some time for salt-minion to connect"))
            sleep(10)
        # Else destroy and up
        else:
            # Destroy
            VagrantDestroy.parent = self.parent
            VagrantDestroy.run(['destroy', project_name], exit=False)

            # Up
            VagrantUp.parent = self.parent
            VagrantUp.run(['up', project_name], exit=False)
Exemplo n.º 12
0
 def __init__(self, root_dir, env):
     self.instance = Vagrant(root=root_dir)
     self.env = env
     self.target = GuestOS(env[:-2], env[-2:])
Exemplo n.º 13
0
    def main(self, project_name):
        minion_path = self.parent.config['minions'][project_name]
        self.execute_vagrant_command_on_minion(project_name, 'up')

        # Get back master IP
        puts(colored.blue("Check master ip"))
        command = "/sbin/ifconfig eth1 | grep 'inet addr:' | cut -d: -f2 | cut -d' ' -f 1"
        vm_ip = get_output_cmd(command, minion_path)

        vm_ip = vm_ip.split('.')
        vm_ip[-1] = '1'
        master_ip = ".".join(vm_ip)

        # Check declared master ip
        command = "grep master /etc/salt/minion"
        declared_master_ip = get_output_cmd(command, minion_path)
        declared_master_ip = declared_master_ip.split()[-1]

        change = False

        if declared_master_ip != master_ip:
            puts(
                colored.yellow(
                    "Master ip on minion is invalid, {0} instead of {1}".
                    format(declared_master_ip, master_ip)))

            # Replace master ip
            command = "sudo sed -i 's/{0}/{1}/g' /etc/salt/minion".format(
                declared_master_ip, master_ip)
            result = get_output_cmd(command, minion_path)

            # Reboot minion
            command = "sudo /etc/init.d/salt-minion restart"
            result = get_output_cmd(command, minion_path)

            # Change minion
            command = "sed -i 's/{0}/{1}/g' {2}".format(
                declared_master_ip, master_ip, join(minion_path, 'minion'))
            check_output(command, shell=True)

            # Wait for minion to connect
            sleep(10)

            puts(
                colored.blue(
                    "Master ip has been updated from {0} to {1}".format(
                        declared_master_ip, master_ip)))
            change = True
        else:
            puts(colored.blue("Master is good"))

        # Check if sahara is available
        minion_path = self.parent.config['minions'][project_name]
        try:
            plugins = Vagrant(minion_path).plugin_list()
        except Exception as e:
            raise

        sahara = bool([p for p in plugins if p.name == "sahara"])

        if not sahara:
            message = "Sandbox support is not available, please install sahara"\
                      " plugin with 'vagrant plugin install sahara'"
            puts(colored.yellow(message))
        else:
            sandbox = SandboxVagrant(minion_path,
                                     quiet_stdout=False,
                                     quiet_stderr=False)
            sandbox_status = sandbox.sandbox_status()

            if sandbox_status == 'on':
                puts(colored.blue("Snapshot is already enabled on VM"))
                if change:
                    puts(
                        colored.blue(
                            "Minion config has changes, would you like to redo the snapshot? It will save the VM in its current state"
                        ))
                    choice = bool_choice("Yes/No: ")
                    if choice:
                        sandbox.sandbox_commit()
            else:
                puts(colored.blue("Would you like to enable snapshot on VM?"))
                choice = bool_choice("Yes/No: ")

                if choice:
                    puts(colored.blue("Starting snapshot"))
                    sandbox.sandbox_on()
                    puts(colored.blue("Done"))
Exemplo n.º 14
0
def test_vagrant(temp_repo_func, destroy=False):
    if os.environ.get("TRAVIS", False):
        pytest.skip("Vagrant doesn't work on Travis")

    backend = VagrantBackend(verbosity=2,
                             use_registry_name="docker.io/mikicz/arca-test",
                             keep_vm_running=True)
    arca = Arca(backend=backend, base_dir=BASE_DIR)

    if destroy:
        vagrant_location = backend.get_vm_location()
        if vagrant_location.exists():
            vagrant = Vagrant(vagrant_location)
            vagrant.destroy()
        shutil.rmtree(vagrant_location)

    # master branch - return colorama version
    temp_repo_func.file_path.write_text(RETURN_COLORAMA_VERSION_FUNCTION)
    requirements_path = temp_repo_func.repo_path / backend.requirements_location
    requirements_path.write_text("colorama==0.3.9")
    temp_repo_func.repo.index.add(
        [str(temp_repo_func.file_path),
         str(requirements_path)])
    temp_repo_func.repo.index.commit("Initial")

    # branch branch - return unicode
    temp_repo_func.repo.create_head("branch")
    temp_repo_func.repo.branches.branch.checkout()
    temp_repo_func.file_path.write_text(SECOND_RETURN_STR_FUNCTION)
    temp_repo_func.repo.index.add([str(temp_repo_func.file_path)])
    temp_repo_func.repo.index.commit("Test unicode on a separate branch")

    task = Task("test_file:return_str_function")

    assert arca.run(temp_repo_func.url, temp_repo_func.branch,
                    task).output == "0.3.9"

    # halt the VM, checks that the VM can be booted when stopped with the vagrant attribute set
    backend.stop_vm()
    assert arca.run(temp_repo_func.url, temp_repo_func.branch,
                    task).output == "0.3.9"

    # halt the vm and create a new instance of the backend, to check that the vagrant attribute can be set from existing
    backend.stop_vm()
    backend = VagrantBackend(verbosity=2,
                             use_registry_name="docker.io/mikicz/arca-test",
                             keep_vm_running=True)
    arca = Arca(backend=backend, base_dir=BASE_DIR)
    assert arca.run(temp_repo_func.url, temp_repo_func.branch,
                    task).output == "0.3.9"

    # test that two branches can work next to each other
    assert arca.run(temp_repo_func.url, temp_repo_func.branch,
                    task).output == "0.3.9"
    assert arca.run(temp_repo_func.url, "branch", task).output == TEST_UNICODE

    # test timeout
    temp_repo_func.repo.branches.master.checkout()
    temp_repo_func.file_path.write_text(WAITING_FUNCTION)
    temp_repo_func.repo.index.add([str(temp_repo_func.file_path)])
    temp_repo_func.repo.index.commit("Waiting function")

    task_1_second = Task("test_file:return_str_function", timeout=1)
    task_3_seconds = Task("test_file:return_str_function", timeout=3)

    with pytest.raises(BuildTimeoutError):
        assert arca.run(temp_repo_func.url, temp_repo_func.branch,
                        task_1_second).output == "Some string"

    assert arca.run(temp_repo_func.url, temp_repo_func.branch,
                    task_3_seconds).output == "Some string"

    backend.stop_vm()

    if destroy:
        backend.destroy = True
        backend.stop_vm()
Exemplo n.º 15
0
from __future__ import print_function

from vagrant import Vagrant

v = Vagrant()


def mock_create(config):
    try:
        if config:
            v.init(box_name=config['box_name'], box_url=config['box_url'])
        else:
            v.init()

        return "SUCCESS"

    except Exception as e:
        return "FAILED"


def mock_vagrantfile():
    with open('Vagrantfile', 'r') as myfile:
        vagrantfile = myfile.read()
    return vagrantfile


def mock_deploy(config):
    with open('./src/mockdata/create_instance') as myfile:
        status_file = myfile.read()
    return status_file