Reboot a container.


    path
        path to the container parent
        default: /var/lib/lxc (system default)

        .. versionadded:: 2015.8.0

    CLI Examples:

    .. code-block:: bash

        salt 'minion' lxc.reboot myvm
324806
def reboot(name, path=None):
    '''
    

    '''
    ret = {'result': True,
           'changes': {},
           'comment': '{0} rebooted'.format(name)}
    does_exist = exists(name, path=path)
    if does_exist and (state(name, path=path) == 'running'):
        try:
            stop(name, path=path)
        except (SaltInvocationError, CommandExecutionError) as exc:
            ret['comment'] = 'Unable to stop container: {0}'.format(exc)
            ret['result'] = False
            return ret
    if does_exist and (state(name, path=path) != 'running'):
        try:
            start(name, path=path)
        except (SaltInvocationError, CommandExecutionError) as exc:
            ret['comment'] = 'Unable to stop container: {0}'.format(exc)
            ret['result'] = False
            return ret
    ret['changes'][name] = 'rebooted'
    return ret
605082
def do_cli(function_identifier,  # pylint: disable=too-many-locals
           template,
           base_dir,
           build_dir,
           clean,
           use_container,
           manifest_path,
           docker_network,
           skip_pull_image,
           parameter_overrides,
           mode):
    

    LOG.debug("'build' command is called")

    if use_container:
        LOG.info("Starting Build inside a container")

    with BuildContext(function_identifier,
                      template,
                      base_dir,
                      build_dir,
                      clean=clean,
                      manifest_path=manifest_path,
                      use_container=use_container,
                      parameter_overrides=parameter_overrides,
                      docker_network=docker_network,
                      skip_pull_image=skip_pull_image,
                      mode=mode) as ctx:
        try:
            builder = ApplicationBuilder(ctx.functions_to_build,
                                         ctx.build_dir,
                                         ctx.base_dir,
                                         manifest_path_override=ctx.manifest_path_override,
                                         container_manager=ctx.container_manager,
                                         mode=ctx.mode)
        except FunctionNotFound as ex:
            raise UserException(str(ex))

        try:
            artifacts = builder.build()
            modified_template = builder.update_template(ctx.template_dict,
                                                        ctx.original_template_path,
                                                        artifacts)

            move_template(ctx.original_template_path,
                          ctx.output_template_path,
                          modified_template)

            click.secho("\nBuild Succeeded", fg="green")

            msg = gen_success_msg(os.path.relpath(ctx.build_dir),
                                  os.path.relpath(ctx.output_template_path),
                                  os.path.abspath(ctx.build_dir) == os.path.abspath(DEFAULT_BUILD_DIR))

            click.secho(msg, fg="yellow")

        except (UnsupportedRuntimeException, BuildError, UnsupportedBuilderLibraryVersionError,
                ContainerBuildNotSupported) as ex:
            click.secho("\nBuild Failed", fg="red")
            raise UserException(str(ex))
1149094
def get_dir(self, path, dest='', saltenv='base', gzip=None,
                cachedir=None):
        '''
        
        '''
        ret = []
        # Strip trailing slash
        path = self._check_proto(path).rstrip('/')
        # Break up the path into a list containing the bottom-level directory
        # (the one being recursively copied) and the directories preceding it
        separated = path.rsplit('/', 1)
        if len(separated) != 2:
            # No slashes in path. (This means all files in saltenv will be
            # copied)
            prefix = ''
        else:
            prefix = separated[0]

        # Copy files from master
        for fn_ in self.file_list(saltenv, prefix=path):
            # Prevent files in "salt://foobar/" (or salt://foo.sh) from
            # matching a path of "salt://foo"
            try:
                if fn_[len(path)] != '/':
                    continue
            except IndexError:
                continue
            # Remove the leading directories from path to derive
            # the relative path on the minion.
            minion_relpath = fn_[len(prefix):].lstrip('/')
            ret.append(
               self.get_file(
                  salt.utils.url.create(fn_),
                  '{0}/{1}'.format(dest, minion_relpath),
                  True, saltenv, gzip
               )
            )
        # Replicate empty dirs from master
        try:
            for fn_ in self.file_list_emptydirs(saltenv, prefix=path):
                # Prevent an empty dir "salt://foobar/" from matching a path of
                # "salt://foo"
                try:
                    if fn_[len(path)] != '/':
                        continue
                except IndexError:
                    continue
                # Remove the leading directories from path to derive
                # the relative path on the minion.
                minion_relpath = fn_[len(prefix):].lstrip('/')
                minion_mkdir = '{0}/{1}'.format(dest, minion_relpath)
                if not os.path.isdir(minion_mkdir):
                    os.makedirs(minion_mkdir)
                ret.append(minion_mkdir)
        except TypeError:
            pass
        ret.sort()
        return ret
847264
def rel_path(*file_path):
        '''
        
        '''
        if hasattr(sys, 'frozen'):
            if file_path[0] == '__file__':
                return sys.executable
            return os.path.join(os.path.dirname(sys.executable), *file_path)
        else:
            try:
                main_file = AppBuilder.main_file
            except AttributeError:
                # The first call setting up the instance
                main_file = inspect.stack()[1][1]
            if file_path[0] == '__file__':
                return os.path.realpath(main_file)
            return os.path.join(os.path.dirname(main_file), *file_path)
1340041
def reboot(at_time=None):
    '''
    
    '''
    cmd = ['shutdown', '-r', ('{0}'.format(at_time) if at_time else 'now')]
    ret = __salt__['cmd.run'](cmd, python_shell=False)
    return ret
187470
def monitor(name, callback):
    '''
     
    '''
    global _monitor 
    if not exists(name):
        raise ContainerNotExists("The container (%s) does not exist!" % name)
    if _monitor:
        if _monitor.is_monitored(name):
            raise Exception("You are already monitoring this container (%s)" % name)
    else:
        _monitor = _LXCMonitor()
        logging.info("Starting LXC Monitor")
        _monitor.start()
        def kill_handler(sg, fr):
            stop_monitor()
        signal.signal(signal.SIGTERM, kill_handler)
        signal.signal(signal.SIGINT, kill_handler)
    _monitor.add_monitor(name, callback)
1016118
def get_environ(environ, defaults, ve_path):
    
    # Copy the parent environment, add in defaults from .vexrc.
    env = environ.copy()
    env.update(defaults)

    # Leaving in existing PYTHONHOME can cause some errors
    if 'PYTHONHOME' in env:
        del env['PYTHONHOME']

    # Now we have to adjust PATH to find scripts for the virtualenv...
    # PATH being unset/empty is OK, but ve_path must be set
    # or there is nothing for us to do here and it's bad.
    if not ve_path:
        raise exceptions.BadConfig('ve_path must be set')
    if platform.system() == 'Windows':
        ve_bin = os.path.join(ve_path, 'Scripts')
    else:
        ve_bin = os.path.join(ve_path, 'bin')

    # If user is currently in a virtualenv, DON'T just prepend
    # to its path (vex foo; echo $PATH -> " /foo/bin:/bar/bin")
    # but don't incur this cost unless we're already in one.
    # activate handles this by running 'deactivate' first, we don't
    # have that so we have to use other ways.
    # This would not be necessary and things would be simpler if vex
    # did not have to interoperate with a ubiquitous existing tool.
    # virtualenv doesn't...
    current_ve = env.get('VIRTUAL_ENV', '')
    system_path = environ.get('PATH', '')
    segments = system_path.split(os.pathsep)
    if current_ve:
        # Since activate doesn't export _OLD_VIRTUAL_PATH, we are going to
        # manually remove the virtualenv's bin.
        # A virtualenv's bin should not normally be on PATH except
        # via activate or similar, so I'm OK with this solution.
        current_ve_bin = os.path.join(current_ve, 'bin')
        try:
            segments.remove(current_ve_bin)
        except ValueError:
            raise exceptions.BadConfig(
                "something set VIRTUAL_ENV prior to this vex execution, "
                "implying that a virtualenv is already activated "
                "and PATH should contain the virtualenv's bin directory. "
                "Unfortunately, it doesn't: it's {0!r}. "
                "You might want to check that PATH is not "
                "getting clobbered somewhere, e.g. in your shell's configs."
                .format(system_path)
            )

    segments.insert(0, ve_bin)
    env['PATH'] = os.pathsep.join(segments)
    env['VIRTUAL_ENV'] = ve_path
    return env
1026622
def create(path)
      raise ContainerError, "Container already exists." if exists?

      if path.is_a?(Hash)
        args = "-n #{name}"

        if !!path[:config_file]
          unless File.exists?(path[:config_file])
            raise ArgumentError, "File #{path[:config_file]} does not exist."
          end
          args += " -f #{path[:config_file]}"
        end

        if !!path[:template]
          template_dir =  path[:template_dir] || "/usr/lib/lxc/templates"
          template_path = File.join(template_dir,"lxc-#{path[:template]}")
          unless File.exists?(template_path)
            raise ArgumentError, "Template #{path[:template]} does not exist."
          end
          args += " -t #{path[:template]} "
        end

        args += " -B #{path[:backingstore]}" if !!path[:backingstore]
        args += " -- #{path[:template_options].join(" ")}".strip if !!path[:template_options]

        LXC.run("create", args)
        exists?
      else
        unless File.exists?(path)
          raise ArgumentError, "File #{path} does not exist."
        end

        LXC.run("create", "-n", name, "-f", path)
        exists?
      end
    end
553394
def _resolve_path(self, container: Container, filepath: str) -> str:
        
        bug = self.__mgr_bug[container.bug]
        filepath_orig = filepath

        if not os.path.isabs(filepath):
            filepath = os.path.join(bug.source_dir, filepath)
            logger.debug("converted relative path to absolute path: %s -> %s",
                         filepath_orig, filepath)

        return filepath
853740
def _get_container_path(container):
    '''
    
    '''
    root = os.path.join(__opts__['cachedir'], 'azurefs')
    container_dir = '{0}_{1}_{2}'.format(container.get('account_name', ''),
                                         container.get('container_name', ''),
                                         container.get('saltenv', 'base'))
    return os.path.join(root, container_dir)
1262552
def reboot(*args):
    
    args = list(sys.argv) + list(args)
    if args[0] == 'python' or not args[0]:
        args[0] = BIN_PYTHON
    elif os.path.basename(sys.argv[0]) in ['lore', 'lore.exe']:
        args[0] = BIN_LORE
    try:
        os.execv(args[0], args)
    except Exception as e:
        if args[0] == BIN_LORE and args[1] == 'console' and JUPYTER_KERNEL_PATH:
            print(ansi.error() + ' Your jupyter kernel may be corrupt. Please remove it so lore can reinstall:\n $ rm ' + JUPYTER_KERNEL_PATH)
        raise e
745396
def node_ls(server=str):
    '''
    
    '''
    try:
        salt_return = {}
        client = docker.APIClient(base_url='unix://var/run/docker.sock')
        service = client.nodes(filters=({'name': server}))
        getdata = salt.utils.json.dumps(service)
        dump = salt.utils.json.loads(getdata)
        for items in dump:
            docker_version = items['Description']['Engine']['EngineVersion']
            platform = items['Description']['Platform']
            hostnames = items['Description']['Hostname']
            ids = items['ID']
            role = items['Spec']['Role']
            availability = items['Spec']['Availability']
            status = items['Status']
            version = items['Version']['Index']
            salt_return.update({'Docker Version': docker_version,
                                'Platform': platform,
                                'Hostname': hostnames,
                                'ID': ids,
                                'Roles': role,
                                'Availability': availability,
                                'Status': status,
                                'Version': version})
    except TypeError:
        salt_return = {}
        salt_return.update({'Error': 'The server arg is missing or you not targeting a Manager node?'})
    return salt_return
622176
def mount_path(source, target, bind=False):
        
        cmd = ['mount']
        if bind:
            cmd.append('--bind')
        cmd.append(source)
        cmd.append(target)
        r = util.subp(cmd)
        if r.return_code != 0:
            raise MountError('Could not mount docker container:\n' +
                             ' '.join(cmd) + '\n%s' %
                             r.stderr.decode(sys.getdefaultencoding()))
1265212
def _bootstrap_arch(name, **kwargs):
    '''
    
    '''
    if not salt.utils.path.which('pacstrap'):
        raise CommandExecutionError(
            'pacstrap not found, is the arch-install-scripts package '
            'installed?'
        )
    dst = _make_container_root(name)
    cmd = 'pacstrap -c -d {0} base'.format(dst)
    ret = __salt__['cmd.run_all'](cmd, python_shell=False)
    if ret['retcode'] != 0:
        _build_failed(dst, name)
    return ret
485440
def _rel(self, path):
        
        return os.path.relpath(
            str(path), self._parent).replace(os.path.sep, '/')
651916
def reset(name):
    '''
    
    '''
    ret = {}
    client = salt.client.get_local_client(__opts__['conf_file'])
    data = vm_info(name, quiet=True)
    if not data:
        __jid_event__.fire_event({'message': 'Failed to find VM {0} to reset'.format(name)}, 'progress')
        return 'fail'
    host = next(six.iterkeys(data))
    try:
        cmd_ret = client.cmd_iter(
                host,
                'virt.reset',
                [name],
                timeout=600)
        for comp in cmd_ret:
            ret.update(comp)
        __jid_event__.fire_event({'message': 'Reset VM {0}'.format(name)}, 'progress')
    except SaltClientError as client_error:
        print(client_error)
    return ret
189013
def app_restart(cls):
        '''
        
        '''
        logging.debug('In restarter')
        executable = sys.executable.split(os.sep)[-1]
        if os.name == 'nt':
            logging.info('executable is is %s' % executable)
            # restart works here when testing compiled version only
            if executable != 'python.exe':
                boot_strap_path = cls.esky_bootstrap_path()
                bootstrap_file = os.path.join(boot_strap_path, executable)
                logging.info('Bootstrap file for restart: %s' % bootstrap_file)

                subprocess.Popen(
                    [os.path.join(bootstrap_file, bootstrap_file), 'restarted'])