IPS Vagrant Management Utility
773783
def cli(ctx, verbose, config):
    
    assert isinstance(ctx, Context)
    # Set up the logger
    verbose = verbose if (verbose <= 3) else 3
    log_levels = {1: logging.WARN, 2: logging.INFO, 3: logging.DEBUG}
    log_level = log_levels[verbose]

    ctx.log = logging.getLogger('ipsv')
    ctx.log.setLevel(log_level)

    # Console logger
    console_format = logging.Formatter("[%(levelname)s] %(name)s: %(message)s")
    ch = logging.StreamHandler()
    ch.setLevel(log_level)
    ch.setFormatter(console_format)
    ctx.log.addHandler(ch)

    # File logger
    file_format = logging.Formatter("[%(asctime)s] [%(levelname)s] %(name)s: %(message)s")
    file_logger = logging.FileHandler(os.path.join(ctx.config.get('Paths', 'Log'), 'ipsv.log'))
    file_logger.setLevel(log_level)
    file_logger.setFormatter(file_format)
    ctx.log.addHandler(file_logger)

    # Load the configuration
    if os.path.isfile(config):
        ctx.config_path = config
        ctx.log.debug('Loading configuration: %s', ctx.config_path)
        ctx.load_config(config)
    else:
        ctx.config_path = os.path.join(ctx.basedir, 'config', 'ipsv.conf')
        ctx.log.debug('Loading default configuration: %s', ctx.config_path)

    ctx.setup()
141549
def process_configured_plugins
      return if !Vagrant.plugins_enabled?
      errors = vagrantfile.config.vagrant.validate(nil)
      if !errors["vagrant"].empty?
        raise Errors::ConfigInvalid,
          errors: Util::TemplateRenderer.render(
            "config/validation_failed",
            errors: errors)
      end
      # Check if defined plugins are installed
      installed = Plugin::Manager.instance.installed_plugins
      needs_install = []
      config_plugins = vagrantfile.config.vagrant.plugins
      config_plugins.each do |name, info|
        if !installed[name]
          needs_install << name
        end
      end
      if !needs_install.empty?
        ui.warn(I18n.t("vagrant.plugins.local.uninstalled_plugins",
          plugins: needs_install.sort.join(", ")))
        if !Vagrant.auto_install_local_plugins?
          answer = nil
          until ["y", "n"].include?(answer)
            answer = ui.ask(I18n.t("vagrant.plugins.local.request_plugin_install") + " [N]: ")
            answer = answer.strip.downcase
            answer = "n" if answer.to_s.empty?
          end
          if answer == "n"
            raise Errors::PluginMissingLocalError,
              plugins: needs_install.sort.join(", ")
          end
        end
        needs_install.each do |name|
          pconfig = Util::HashWithIndifferentAccess.new(config_plugins[name])
          ui.info(I18n.t("vagrant.commands.plugin.installing", name: name))

          options = {sources: Vagrant::Bundler::DEFAULT_GEM_SOURCES.dup, env_local: true}
          options[:sources] = pconfig[:sources] if pconfig[:sources]
          options[:require] = pconfig[:entry_point] if pconfig[:entry_point]
          options[:version] = pconfig[:version] if pconfig[:version]

          spec = Plugin::Manager.instance.install_plugin(name, options)

          ui.info(I18n.t("vagrant.commands.plugin.installed",
            name: spec.name, version: spec.version.to_s))
        end
        ui.info("\n")
        # Force halt after installation and require command to be run again. This
        # will proper load any new locally installed plugins which are now available.
        ui.warn(I18n.t("vagrant.plugins.local.install_rerun_command"))
        exit(-1)
      end
      Vagrant::Plugin::Manager.instance.local_file.installed_plugins
    end
1218204
def destroy(name):
    '''
    
    '''
    vm_ = get_vm_info(name)
    machine = vm_['machine']

    cmd = 'vagrant destroy -f {}'.format(machine)

    ret = __salt__['cmd.run_all'](cmd,
                                  runas=vm_.get('runas'),
                                  cwd=vm_.get('cwd'),
                                  output_loglevel='info')
    if ret['retcode'] == 0:
        _erase_vm_info(name)
        return 'Destroyed VM {0}'.format(name)
    return False
1041963
def generate_vagrant_set
      sets = [generate_builtin_set, generate_plugin_set]
      if env_plugin_gem_path && env_plugin_gem_path.exist?
        sets << generate_plugin_set(env_plugin_gem_path)
      end
      Gem::Resolver.compose_sets(*sets)
    end
1220685
def default_provider(**opts)
      opts[:exclude]       = Set.new(opts[:exclude]) if opts[:exclude]
      opts[:force_default] = true if !opts.key?(:force_default)
      opts[:check_usable] = true if !opts.key?(:check_usable)

      # Implement the algorithm from
      # https://www.vagrantup.com/docs/providers/basic_usage.html#default-provider
      # with additional steps 2.5 and 3.5 from
      # https://bugzilla.redhat.com/show_bug.cgi?id=1444492
      # to allow system-configured provider priorities.
      #
      # 1. The --provider flag on a vagrant up is chosen above all else, if it is
      #    present.
      #
      # (Step 1 is done by the caller; this method is only called if --provider
      # wasn't given.)
      #
      # 2. If the VAGRANT_DEFAULT_PROVIDER environmental variable is set, it
      #    takes next priority and will be the provider chosen.

      default = ENV["VAGRANT_DEFAULT_PROVIDER"].to_s
      if default.empty?
        default = nil
      else
        default = default.to_sym
        @logger.debug("Default provider: `#{default}`")
      end

      # If we're forcing the default, just short-circuit and return
      # that (the default behavior)
      if default && opts[:force_default]
        @logger.debug("Using forced default provider: `#{default}`")
        return default
      end

      # Determine the config to use to look for provider definitions. By
      # default it is the global but if we're targeting a specific machine,
      # then look there.
      root_config = vagrantfile.config
      if opts[:machine]
        machine_info = vagrantfile.machine_config(opts[:machine], nil, nil, nil)
        root_config = machine_info[:config]
      end

      # Get the list of providers within our configuration, in order.
      config = root_config.vm.__providers

      # Get the list of usable providers with their internally-declared
      # priorities.
      usable = []
      Vagrant.plugin("2").manager.providers.each do |key, data|
        impl  = data[0]
        popts = data[1]

        # Skip excluded providers
        next if opts[:exclude] && opts[:exclude].include?(key)

        # Skip providers that can't be defaulted, unless they're in our
        # config, in which case someone made our decision for us.
        if !config.include?(key)
          next if popts.key?(:defaultable) && !popts[:defaultable]
        end

        # Skip providers that aren't usable.
        next if opts[:check_usable] && !impl.usable?(false)

        # Each provider sets its own priority, defaulting to 5 so we can trust
        # it's always set.
        usable << [popts[:priority], key]
      end
      @logger.debug("Initial usable provider list: #{usable}")

      # Sort the usable providers by priority. Higher numbers are higher
      # priority, otherwise alpha sort.
      usable = usable.sort {|a, b| a[0] == b[0] ? a[1] <=> b[1] : b[0] <=> a[0]}
                      .map {|prio, key| key}
      @logger.debug("Priority sorted usable provider list: #{usable}")

      # If we're not forcing the default, but it's usable and hasn't been
      # otherwise excluded, return it now.
      if usable.include?(default)
        @logger.debug("Using default provider `#{default}` as it was found in usable list.")
        return default
      end

      # 2.5. Vagrant will go through all of the config.vm.provider calls in the
      #      Vagrantfile and try each in order. It will choose the first
      #      provider that is usable and listed in VAGRANT_PREFERRED_PROVIDERS.

      preferred = ENV.fetch('VAGRANT_PREFERRED_PROVIDERS', '')
                     .split(',')
                     .map {|s| s.strip}
                     .select {|s| !s.empty?}
                     .map {|s| s.to_sym}
      @logger.debug("Preferred provider list: #{preferred}")

      config.each do |key|
        if usable.include?(key) && preferred.include?(key)
          @logger.debug("Using preferred provider `#{key}` detected in configuration and usable.")
          return key
        end
      end

      # 3. Vagrant will go through all of the config.vm.provider calls in the
      #    Vagrantfile and try each in order. It will choose the first provider
      #    that is usable. For example, if you configure Hyper-V, it will never
      #    be chosen on Mac this way. It must be both configured and usable.

      config.each do |key|
        if usable.include?(key)
          @logger.debug("Using provider `#{key}` detected in configuration and usable.")
          return key
        end
      end

      # 3.5. Vagrant will go through VAGRANT_PREFERRED_PROVIDERS and find the
      #      first plugin that reports it is usable.

      preferred.each do |key|
        if usable.include?(key)
          @logger.debug("Using preferred provider `#{key}` found in usable list.")
          return key
        end
      end

      # 4. Vagrant will go through all installed provider plugins (including the
      #    ones that come with Vagrant), and find the first plugin that reports
      #    it is usable. There is a priority system here: systems that are known
      #    better have a higher priority than systems that are worse. For
      #    example, if you have the VMware provider installed, it will always
      #    take priority over VirtualBox.

      if !usable.empty?
        @logger.debug("Using provider `#{usable[0]}` as it is the highest priority in the usable list.")
        return usable[0]
      end

      # 5. If Vagrant still has not found any usable providers, it will error.

      # No providers available is a critical error for Vagrant.
      raise Errors::NoDefaultProvider
    end
192355
def cli(env, identifier, price=False, guests=False):
    """"""
    dhost = SoftLayer.DedicatedHostManager(env.client)

    table = formatting.KeyValueTable(['name', 'value'])
    table.align['name'] = 'r'
    table.align['value'] = 'l'

    result = dhost.get_host(identifier)
    result = utils.NestedDict(result)

    table.add_row(['id', result['id']])
    table.add_row(['name', result['name']])
    table.add_row(['cpu count', result['cpuCount']])
    table.add_row(['memory capacity', result['memoryCapacity']])
    table.add_row(['disk capacity', result['diskCapacity']])
    table.add_row(['create date', result['createDate']])
    table.add_row(['modify date', result['modifyDate']])
    table.add_row(['router id', result['backendRouter']['id']])
    table.add_row(['router hostname', result['backendRouter']['hostname']])
    table.add_row(['owner', formatting.FormattedItem(
        utils.lookup(result, 'billingItem', 'orderItem', 'order', 'userRecord', 'username') or formatting.blank(),)])

    if price:
        total_price = utils.lookup(result,
                                   'billingItem',
                                   'nextInvoiceTotalRecurringAmount') or 0
        total_price += sum(p['nextInvoiceTotalRecurringAmount']
                           for p
                           in utils.lookup(result,
                                           'billingItem',
                                           'children') or [])
        table.add_row(['price_rate', total_price])

    table.add_row(['guest count', result['guestCount']])
    if guests:
        guest_table = formatting.Table(['id', 'hostname', 'domain', 'uuid'])
        for guest in result['guests']:
            guest_table.add_row([
                guest['id'], guest['hostname'], guest['domain'], guest['uuid']])
        table.add_row(['guests', guest_table])

    table.add_row(['datacenter', result['datacenter']['name']])

    env.fout(table)
535217
def get_command(self, ctx, name):
        
        try:
            mod = importlib.import_module('ips_vagrant.commands.{name}'.format(name=name))
            return mod.cli
        except (ImportError, AttributeError):
            return
1162306
def _set_static_ip(name, session, vm_):
    '''
    
    '''
    ipv4_cidr = ''
    ipv4_gw = ''
    if 'ipv4_gw' in vm_.keys():
        log.debug('ipv4_gw is found in keys')
        ipv4_gw = vm_['ipv4_gw']
    if 'ipv4_cidr' in vm_.keys():
        log.debug('ipv4_cidr is found in keys')
        ipv4_cidr = vm_['ipv4_cidr']
        log.debug('attempting to set IP in instance')
        set_vm_ip(name, ipv4_cidr, ipv4_gw, session, None)
980721
def list_active_vms(cwd=None):
    '''
    
    '''
    vms = []
    cmd = 'vagrant status'
    reply = __salt__['cmd.shell'](cmd, cwd=cwd)
    log.info('--->\n%s', reply)
    for line in reply.split('\n'):  # build a list of the text reply
        tokens = line.strip().split()
        if len(tokens) > 1:
            if tokens[1] == 'running':
                vms.append(tokens[0])
    return vms
1091238
def cli(env, volume_id, hardware_id, virtual_id, ip_address_id, ip_address):
    """"""
    block_manager = SoftLayer.BlockStorageManager(env.client)
    ip_address_id_list = list(ip_address_id)

    # Convert actual IP Addresses to their SoftLayer ids
    if ip_address is not None:
        network_manager = SoftLayer.NetworkManager(env.client)
        for ip_address_value in ip_address:
            ip_address_object = network_manager.ip_lookup(ip_address_value)
            ip_address_id_list.append(ip_address_object['id'])

    block_manager.deauthorize_host_to_volume(volume_id,
                                             hardware_id,
                                             virtual_id,
                                             ip_address_id_list)

    # If no exception was raised, the command succeeded
    click.echo('Access to %s was revoked for the specified hosts' % volume_id)
722553
def output_vhost(gandi, vhost, paas, output_keys, justify=14):
    
    output_generic(gandi, vhost, output_keys, justify)

    if 'paas_name' in output_keys:
        output_line(gandi, 'paas_name', paas, justify)
370723
def vagrant_box_exist?(node)
      vagrant_boxes = `cd #{node.project_root} && vagrant box list`
      project_name = Bebox::Project.name_from_file(node.project_root)
      vagrant_box_provider = Bebox::Project.vagrant_box_provider_from_file(node.project_root)
      (vagrant_boxes =~ /#{project_name}-#{node.hostname}\s+\(#{vagrant_box_provider}/) ? true : false
    end
527577
def _call_vagrant_command(self, args):
        '''
        

        '''
        # Make subprocess command
        command = self._make_vagrant_command(args)
        with self.out_cm() as out_fh, self.err_cm() as err_fh:
            subprocess.check_call(command, cwd=self.root, stdout=out_fh,
                                  stderr=err_fh, env=self.env)
952151
async def manage(self):
        
        self._vms = await self.iaas.list_vms(self.name)

        vms_stat = Counter([vm.get_state() for vm in self._vms])
        missing = self.count - len(self._vms) if len(self._vms) < self.count else 0
        logging.info(
            'VMs Status: %s expected, %s in iaas, %s running, %s nearby shutdown, %s pending, %s after time shutdown, '
            '%s terminated, %s error, %s unknown, %s missing',
            self.count, len(self._vms), vms_stat[VmState.RUNNING.value], vms_stat[VmState.NEARBY_SHUTDOWN.value],
            vms_stat[VmState.PENDING.value], vms_stat[VmState.AFTER_TIME_SHUTDOWN.value],
            vms_stat[VmState.TERMINATED.value], vms_stat[VmState.ERROR.value], vms_stat[VmState.UNKNOWN.value], missing, extra=self._extra
        )
        for vm in self._vms:
            if vm.is_dead():
                logging.info("Terminate %s", vm, extra=self._extra)
                await vm.terminate()
                self.terminated += 1
        to_create = self.count - (len(self._vms) - self.terminated - vms_stat[VmState.NEARBY_SHUTDOWN.value])
        to_create = to_create if to_create > 0 else 0
        logging.debug("Create %s Vm", to_create, extra=self._extra)
        await self._create_vms(to_create)
        await self._healthcheck(self._vms)
        logging.info(
            'VMs Status update: %s terminated, %s terminated by healthcheck, %s created, %s failed healthcheck',
            self.terminated, self.healthcheck_terminated, to_create, len(self.runtime.failed_checks),
            extra=self._extra
        )
83433
def init(self, force_deploy=False):
        
        machines = self.provider_conf.machines
        networks = self.provider_conf.networks
        _networks = []
        for network in networks:
            ipnet = IPNetwork(network.cidr)
            _networks.append({
                "netpool": list(ipnet)[10:-10],
                "cidr": network.cidr,
                "roles": network.roles,
                "gateway": ipnet.ip
            })

        vagrant_machines = []
        vagrant_roles = {}
        j = 0
        for machine in machines:
            for _ in range(machine.number):
                vagrant_machine = {
                    "name": "enos-%s" % j,
                    "cpu": machine.flavour_desc["core"],
                    "mem": machine.flavour_desc["mem"],
                    "ips": [n["netpool"].pop() for n in _networks],
                }
                vagrant_machines.append(vagrant_machine)
                # Assign the machines to the right roles
                for role in machine.roles:
                    vagrant_roles.setdefault(role, []).append(vagrant_machine)
                j = j + 1

        logger.debug(vagrant_roles)

        loader = FileSystemLoader(searchpath=TEMPLATE_DIR)
        env = Environment(loader=loader, autoescape=True)
        template = env.get_template('Vagrantfile.j2')
        vagrantfile = template.render(machines=vagrant_machines,
                                      provider_conf=self.provider_conf)
        vagrantfile_path = os.path.join(os.getcwd(), "Vagrantfile")
        with open(vagrantfile_path, 'w') as f:
            f.write(vagrantfile)

        # Build env for Vagrant with a copy of env variables (needed by
        # subprocess opened by vagrant
        v_env = dict(os.environ)
        v_env['VAGRANT_DEFAULT_PROVIDER'] = self.provider_conf.backend

        v = vagrant.Vagrant(root=os.getcwd(),
                            quiet_stdout=False,
                            quiet_stderr=False,
                            env=v_env)
        if force_deploy:
            v.destroy()
        v.up()
        v.provision()
        roles = {}
        for role, machines in vagrant_roles.items():
            for machine in machines:
                keyfile = v.keyfile(vm_name=machine['name'])
                port = v.port(vm_name=machine['name'])
                address = v.hostname(vm_name=machine['name'])
                roles.setdefault(role, []).append(
                    Host(address,
                         alias=machine['name'],
                         user=self.provider_conf.user,
                         port=port,
                         keyfile=keyfile))

        networks = [{
            'cidr': str(n["cidr"]),
            'start': str(n["netpool"][0]),
            'end': str(n["netpool"][-1]),
            'dns': '8.8.8.8',
            'gateway': str(n["gateway"]),
            'roles': n["roles"]
            } for n in _networks]
        logger.debug(roles)
        logger.debug(networks)

        return (roles, networks)
1365795
def validate_configuration(self):
        
        super().validate_configuration()

        if self.use_registry_name is None:
            raise ArcaMisconfigured("Use registry name setting is required for VagrantBackend")

        if not re.match(r"^[a-z]+/[a-zA-Z0-9\-_]+$", self.box):
            raise ArcaMisconfigured("Provided Vagrant box is not valid")

        if not re.match(r"^[a-z_]+$", self.provider):
            raise ArcaMisconfigured("Provided Vagrant provider is not valid")

        if self.registry_pull_only:
            raise ArcaMisconfigured("Push must be enabled for VagrantBackend")
998116
def vagrant(dir = Dir.pwd, options = {})
      info "Initialize Vagrant (see https://www.vagrantup.com/)"
      path = normalized_path(dir)
      use_git = FalkorLib::Git.init?(path)
      rootdir = (use_git) ? FalkorLib::Git.rootdir(path) : path
      templatedir = File.join( FalkorLib.templates, 'vagrant')
      config = FalkorLib::Config::Bootstrap::DEFAULTS[:vagrant].clone
      if options[:os]
        config[:os] = options[:os]
      else
        config[:os] = select_from(config[:boxes].keys,
                    "Select OS to configure within your vagrant boxes by default",
                    (config[:boxes].keys.find_index(config[:os]) + 1))
      end
      [ :ram, :vcpus, :domain, :range ].each do |k|
        config[k.to_sym] = ask("\tDefault #{k.capitalize}:", config[k.to_sym])
      end
      puts config.to_yaml
      FalkorLib::GitFlow.start('feature', 'vagrant', rootdir) if (use_git && FalkorLib::GitFlow.init?(rootdir))
      init_from_template(templatedir, rootdir, config,
                         :no_interaction => true,
                         :no_commit => true)
      [ 'bootstrap.sh', 'config.yaml.sample' ].each do |f|
        FalkorLib::Git.add(File.join(rootdir, 'vagrant', "#{f}")) if use_git
      end
      Dir.chdir( rootdir ) do
        run %(git ignore '.vagrant/' )
        #   run %(ln -s README.md index.md )
      #   run %(ln -s README.md contributing/index.md )
      #   run %(ln -s README.md setup/index.md )
      end
      FalkorLib::Git.add(File.join(rootdir, '.gitignore')) if use_git

      #exit_status.to_i
    end