Mount the named image via qemu-nbd and return the mounted roots

    CLI Example:

    .. code-block:: bash

        salt '*' qemu_nbd.init /srv/image.qcow2
350828
def init(image, root=None):
    '''
    
    '''
    nbd = connect(image)
    if not nbd:
        return ''
    return mount(nbd, root)
705091
def __get_gui_handle(self, root_dir):
        
        gui_path = os.path.join(root_dir, '.gui')
        fh = open(gui_path, "w+")
        return (gui_path, fh)
538308
def add_to_qemu(self):
        
        device = self.device_info['ext_conf']
        node_prop = self.node['properties']
        hv_device = self.hypervisor[device]
        # QEMU HDD Images
        if 'hda_disk_image' not in node_prop:
            if 'image' in hv_device:
                node_prop['hda_disk_image'] = hv_device['image']
            elif 'image1' in hv_device:
                node_prop['hda_disk_image'] = hv_device['image1']
        if 'hdb_disk_image' not in node_prop and 'image2' in hv_device:
            node_prop['hdb_disk_image'] = hv_device['image2']
        # RAM
        if 'ram' not in node_prop and 'ram' in hv_device:
            node_prop['ram'] = hv_device['ram']
        else:
            node_prop['ram'] = 256
        # QEMU Options
        if 'options' not in node_prop and 'options' in hv_device:
            node_prop['options'] = hv_device['options']
        # Kernel Image
        if 'kernel_image' not in node_prop and 'kernel' in hv_device:
            node_prop['kernel_image'] = hv_device['kernel']
        # Kernel Command Line
        if 'kernel_command_line' not in node_prop and \
                'kernel_cmdline' in hv_device:
            node_prop['kernel_command_line'] = hv_device['kernel_cmdline']
        # initrd
        if 'initrd' not in node_prop and 'initrd' in hv_device:
            node_prop['initrd'] = hv_device['initrd']
        # Number of adapters
        if 'adapters' not in node_prop and 'nics' in hv_device:
            node_prop['adapters'] = hv_device['nics']
        elif 'adapters' not in node_prop and 'nics' not in hv_device:
            node_prop['adapters'] = 6
        # Adapter type
        if 'adapter_type' not in node_prop and 'netcard' in hv_device:
            node_prop['adapter_type'] = hv_device['netcard']
        # Console Port
        if 'console' not in node_prop:
            node_prop['console'] = self.base_ports['qemu_console'] + \
                self.node['qemu_id'] - 1
        # Qemu Path
        if 'qemu_path' not in node_prop:
            qemu_path = self.hypervisor['qemu_path']
            # Modify QEMU Path if flavor is specified
            if 'flavor' in hv_device:
                qemu_path = re.sub(r'qemu-system-.*',
                                   'qemu-system' + hv_device['flavor'],
                                   qemu_path)
            node_prop['qemu_path'] = qemu_path
750541
def _make_container_root(name):
    '''
    
    '''
    path = _root(name)
    if os.path.exists(path):
        __context__['retcode'] = salt.defaults.exitcodes.SALT_BUILD_FAIL
        raise CommandExecutionError(
            'Container {0} already exists'.format(name)
        )
    else:
        try:
            os.makedirs(path)
            return path
        except OSError as exc:
            raise CommandExecutionError(
                'Unable to make container root directory {0}: {1}'
                .format(name, exc)
            )
1119621
def _pull_image(pull_type, image, name, **kwargs):
    '''
    
    '''
    _ensure_systemd(219)
    if exists(name):
        raise SaltInvocationError(
            'Container \'{0}\' already exists'.format(name)
        )
    if pull_type in ('raw', 'tar'):
        valid_kwargs = ('verify',)
    elif pull_type == 'dkr':
        valid_kwargs = ('index',)
    else:
        raise SaltInvocationError(
            'Unsupported image type \'{0}\''.format(pull_type)
        )

    kwargs = salt.utils.args.clean_kwargs(**kwargs)
    bad_kwargs = dict(
        [(x, y) for x, y in six.iteritems(salt.utils.args.clean_kwargs(**kwargs))
         if x not in valid_kwargs]
    )

    if bad_kwargs:
        salt.utils.args.invalid_kwargs(bad_kwargs)

    pull_opts = []

    if pull_type in ('raw', 'tar'):
        verify = kwargs.get('verify', False)
        if not verify:
            pull_opts.append('--verify=no')
        else:
            def _bad_verify():
                raise SaltInvocationError(
                    '\'verify\' must be one of the following: '
                    'signature, checksum'
                )
            try:
                verify = verify.lower()
            except AttributeError:
                _bad_verify()
            else:
                if verify not in ('signature', 'checksum'):
                    _bad_verify()
                pull_opts.append('--verify={0}'.format(verify))

    elif pull_type == 'dkr':
        # No need to validate the index URL, machinectl will take care of this
        # for us.
        if 'index' in kwargs:
            pull_opts.append('--dkr-index-url={0}'.format(kwargs['index']))

    cmd = 'pull-{0} {1} {2} {3}'.format(
        pull_type, ' '.join(pull_opts), image, name
    )
    result = _machinectl(cmd, use_vt=True)
    if result['retcode'] != 0:
        msg = 'Error occurred pulling image. Stderr from the pull command ' \
              '(if any) follows: '
        if result['stderr']:
            msg += '\n\n{0}'.format(result['stderr'])
        raise CommandExecutionError(msg)
    return True
1261027
def get_image(conn, vm_):
    '''
    
    '''
    images = conn.list_images()
    vm_image = config.get_cloud_config_value('image', vm_, __opts__)

    if not six.PY3:
        vm_image = vm_image.encode('ascii', 'salt-cloud-force-ascii')

    for img in images:
        if isinstance(img.id, six.string_types) and not six.PY3:
            img_id = img.id.encode('ascii', 'salt-cloud-force-ascii')
        else:
            img_id = str(img.id)  # future lint: disable=blacklisted-function

        if isinstance(img.name, six.string_types) and not six.PY3:
            img_name = img.name.encode('ascii', 'salt-cloud-force-ascii')
        else:
            img_name = str(img.name)  # future lint: disable=blacklisted-function

        if vm_image and vm_image in (img_id, img_name):
            return img

    raise SaltCloudNotFound(
        'The specified image, \'{0}\', could not be found.'.format(vm_image)
    )
478254
def name2mount(self, name):
        """"""
        if not self.is_module(name):
            raise ValueError('%r is not a supported module name' % (name, ))
        return name.replace(self.module_prefix, self.mount_prefix)
619365
def list_mount():
    '''
    

    '''
    ## List mounted filesystem
    res = __salt__['cmd.run_all'](
        __utils__['zfs.zfs_command'](
            command='mount',
        ),
        python_shell=False,
    )

    if res['retcode'] == 0:
        ret = OrderedDict()
        for mount in res['stdout'].splitlines():
            mount = mount.split()
            ret[mount[0]] = mount[-1]
        return ret
    else:
        return __utils__['zfs.parse_command_result'](res)
332309
def native(cmd, opts = [], chdir = true, redirect = '', &block)
      validate

      ENV['GIT_DIR'] = @git_dir
      ENV['GIT_INDEX_FILE'] = @git_index_file
      ENV['GIT_WORK_TREE'] = @git_work_dir
      path = @git_work_dir || @git_dir || @path

      opts = [opts].flatten.map {|s| escape(s) }.join(' ')
      git_cmd = "git #{cmd} #{opts} #{redirect} 2>&1"

      out = nil
      if chdir && (Dir.getwd != path)
        Dir.chdir(path) { out = run_command(git_cmd, &block) }
      else
        out = run_command(git_cmd, &block)
      end

      if @logger
        @logger.info(git_cmd)
        @logger.debug(out)
      end

      if $?.exitstatus > 0
        if $?.exitstatus == 1 && out == ''
          return ''
        end
        raise Git::CommandFailed.new(git_cmd, $?.exitstatus, out.to_s)
      end
      out
    end
523598
def initrd(self, initrd):
        

        initrd = self.manager.get_abs_image_path(initrd)

        log.info('QEMU VM "{name}" [{id}] has set the QEMU initrd path to {initrd}'.format(name=self._name,
                                                                                           id=self._id,
                                                                                           initrd=initrd))
        if "asa" in initrd:
            self.project.emit("log.warning", {"message": "Warning ASA 8 is not supported by GNS3 and Cisco, you need to use ASAv. Depending of your hardware and OS this could not work or you could be limited to one instance. If ASA 8 is not booting their is no GNS3 solution, you need to upgrade to ASAv."})
        self._initrd = initrd
320622
def red_get_mount_connectors(red_data, ignore_outputs):
    

    keys = []

    batches = red_data.get('batches')
    inputs = red_data.get('inputs')
    if batches:
        for batch in batches:
            keys.extend(red_get_mount_connectors_from_inputs(batch['inputs']))
    elif inputs:
        keys.extend(red_get_mount_connectors_from_inputs(inputs))

    if not ignore_outputs:
        outputs = red_data.get('outputs')
        if batches:
            for batch in batches:
                batch_outputs = batch.get('outputs')
                if batch_outputs:
                    keys.extend(red_get_mount_connectors_from_outputs(batch_outputs))

        elif outputs:
            keys.extend(red_get_mount_connectors_from_outputs(outputs))

    return keys
843452
def mount(self, source, target, options=[]):
        

        if len(options) == 0:
            options = ['']

        args = {
            'options': ','.join(options),
            'source': source,
            'target': target,
        }

        self._mount_chk.check(args)
        response = self._client.raw('disk.mount', args)

        result = response.get()

        if result.state != 'SUCCESS':
            raise RuntimeError('failed to mount partition: %s' % result.stderr)
49709
def preview_unmount(self):
        

        commands = []
        for mountpoint in self.find_bindmounts():
            commands.append('umount {0}'.format(mountpoint))
        for mountpoint in self.find_mounts():
            commands.append('umount {0}'.format(mountpoint))
            commands.append('rm -Rf {0}'.format(mountpoint))
        for vgname, pvname in self.find_volume_groups():
            commands.append('lvchange -a n {0}'.format(vgname))
            commands.append('losetup -d {0}'.format(pvname))
        for device in self.find_loopbacks():
            commands.append('losetup -d {0}'.format(device))
        for mountpoint in self.find_base_images():
            commands.append('fusermount -u {0}'.format(mountpoint))
            commands.append('rm -Rf {0}'.format(mountpoint))
        for folder in self.find_clean_dirs():
            cmd = 'rm -Rf {0}'.format(folder)
            if cmd not in commands:
                commands.append(cmd)
        return commands
408372
def binary_list(archs=None):
        

        qemus = []
        for path in Qemu.paths_list():
            try:
                for f in os.listdir(path):
                    if f.endswith("-spice"):
                        continue
                    if (f.startswith("qemu-system") or f.startswith("qemu-kvm") or f == "qemu" or f == "qemu.exe") and \
                            os.access(os.path.join(path, f), os.X_OK) and \
                            os.path.isfile(os.path.join(path, f)):
                        if archs is not None:
                            for arch in archs:
                                if f.endswith(arch) or f.endswith("{}.exe".format(arch)) or f.endswith("{}w.exe".format(arch)):
                                    qemu_path = os.path.join(path, f)
                                    version = yield from Qemu.get_qemu_version(qemu_path)
                                    qemus.append({"path": qemu_path, "version": version})
                        else:
                            qemu_path = os.path.join(path, f)
                            version = yield from Qemu.get_qemu_version(qemu_path)
                            qemus.append({"path": qemu_path, "version": version})

            except OSError:
                continue

        return qemus
812591
def mount(self,
              fstype=None,
              options=None,
              auth_no_user_interaction=None):
        """"""
        return self._M.Filesystem.Mount(
            '(a{sv})',
            filter_opt({
                'fstype': ('s', fstype),
                'options': ('s', ','.join(options or [])),
                'auth.no_user_interaction': ('b', auth_no_user_interaction),
            })
        )
1344836
def _get_mount_methods(self, disk_type):
        
        if self.disk_mounter == 'auto':
            methods = []

            def add_method_if_exists(method):
                if (method == 'avfs' and _util.command_exists('avfsd')) or \
                        _util.command_exists(method):
                    methods.append(method)

            if self.read_write:
                add_method_if_exists('xmount')
            else:
                if disk_type == 'encase':
                    add_method_if_exists('ewfmount')
                elif disk_type == 'vmdk':
                    add_method_if_exists('vmware-mount')
                    add_method_if_exists('affuse')
                elif disk_type == 'dd':
                    add_method_if_exists('affuse')
                elif disk_type == 'compressed':
                    add_method_if_exists('avfs')
                elif disk_type == 'qcow2':
                    add_method_if_exists('qemu-nbd')
                elif disk_type == 'vdi':
                    add_method_if_exists('qemu-nbd')
                add_method_if_exists('xmount')
        else:
            methods = [self.disk_mounter]
        return methods
798178
def mounted(cls, unmounted):  # noqa: N802
        
        assert isinstance(unmounted, UnmountedType), ("{} can't mount {}").format(
            cls.__name__, repr(unmounted)
        )

        return cls(
            unmounted.get_type(),
            *unmounted.args,
            _creation_counter=unmounted.creation_counter,
            **unmounted.kwargs
        )