Restart a "service" on the ssh server

    .. versionadded:: 2015.8.2
170440
def service_restart(name):
    '''
    
    '''
    cmd = 'restart ' + name

    # Send the command to execute
    out, err = DETAILS['server'].sendline(cmd)

    # "scrape" the output and return the right fields as a dict
    return parse(out)
781563
def start(self):
        
        if self.is_alive:
            self.logger.warning('Already started!')
            return
        self._create_tunnels()
        if not self.is_active:
            self._raise(BaseSSHTunnelForwarderError,
                        reason='Could not establish session to SSH gateway')
        for _srv in self._server_list:
            thread = threading.Thread(
                target=self._serve_forever_wrapper,
                args=(_srv, ),
                name='Srv-{0}'.format(address_to_str(_srv.local_port))
            )
            thread.daemon = self.daemon_forward_servers
            thread.start()
            self._check_tunnel(_srv)
        self.is_alive = any(self.tunnel_is_up.values())
        if not self.is_alive:
            self._raise(HandlerSSHTunnelForwarderError,
                        'An error occurred while opening tunnels.')
653580
def setup(addr, user, remote_path, local_key=None):
    """"""
    port = find_port(addr, user)

    if not port or not is_alive(addr, user):
        port = new_port()

        scp(addr, user, __file__, '~/unixpipe', local_key)

        ssh_call = ['ssh', '-fL%d:127.0.0.1:12042' % port,
                    '-o', 'ExitOnForwardFailure=yes',
                    '-o', 'ControlPath=~/.ssh/unixpipe_%%r@%%h_%d' % port,
                    '-o', 'ControlMaster=auto',
                    '%s@%s' % (user, addr,), 'python', '~/unixpipe',
                    'server', remote_path]
        if local_key:
            ssh_call.insert(1, local_key)
            ssh_call.insert(1, '-i')

        subprocess.call(ssh_call)
        # XXX Sleep is a bad way to wait for the tunnel endpoint
        time.sleep(1)

    return port
636996
def start(self, *args, **kwargs):#pylint:disable=unused-argument
        
        restart = kwargs.get('restart', True)
        return self.run(restart)
811764
def _start_server(bindaddr, port, hostname, folder):
    """"""
    import asyncio
    from .httpserver import HttpProtocol
    loop = asyncio.get_event_loop()
    coroutine = loop.create_server(lambda: HttpProtocol(hostname, folder),
                                   bindaddr,
                                   port)
    server = loop.run_until_complete(coroutine)

    print('Starting server on {}'.format(server.sockets[0].getsockname()))
    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass
202648
def start_server(self, addr='', port=8000):
        
        if self._multiprocess_on:
            raise SanicPrometheusError(
                "start_server can not be used when multiprocessing " +
                "is turned on")
        start_http_server(addr=addr, port=port)
361645
def restart(self, *args, **kw):
        """"""
        self.stop()
        self.start(*args, **kw)
901880
async def start(self):
        """"""

        self._command_task.start()

        try:
            await self._cleanup_old_connections()
        except Exception:
            await self.stop()
            raise

        #FIXME: This is a temporary hack, get the actual device we are serving.
        iotile_id = next(iter(self.adapter.devices))
        self.device = self.adapter.devices[iotile_id]

        self._logger.info("Serving device 0x%04X over BLED112", iotile_id)
        await self._update_advertisement()

        self.setup_client(self.CLIENT_ID, scan=False, broadcast=True)
274551
def restart(ctx, **kwargs):
    
    update_context(ctx, kwargs)

    daemon = mk_daemon(ctx)
    daemon.stop()
    daemon.start()
1044260
def start(cmd, port=None, numRetries=10, label="default"):
    
    if port is None:
        port = sumolib.miscutils.getFreeSocketPort()
    sumoProcess = subprocess.Popen(cmd + ["--remote-port", str(port)])
    _connections[label] = connect(port, numRetries, "localhost", sumoProcess)
    switch(label)
    return getVersion()
1108193
def salt_ssh():
    '''
    
    '''
    import salt.cli.ssh
    if '' in sys.path:
        sys.path.remove('')
    try:
        client = salt.cli.ssh.SaltSSH()
        _install_signal_handlers(client)
        client.run()
    except SaltClientError as err:
        trace = traceback.format_exc()
        try:
            hardcrash = client.options.hard_crash
        except (AttributeError, KeyError):
            hardcrash = False
        _handle_interrupt(
            SystemExit(err),
            err,
            hardcrash, trace=trace)
1335104
def restart(at = Time.now, container_id: nil, started_at: nil)
      if container_id && @container.id != container_id
        debug "stale #{@service_pod} restart for container id=#{container_id}"
        return
      end
      if started_at && @container.started_at != started_at
        debug "stale #{@service_pod} restart for container started_at=#{started_at}"
        return
      end

      debug "mark #{@service_pod} for restart at #{at}"
      @restarting_at = at
      apply
    end
1288189
def do_ssh(self,args):
        """"""
        parser = CommandArgumentParser("ssh")
        parser.add_argument(dest='instance',help='instance index or name');
        parser.add_argument('-a','--address-number',default='0',dest='interface-number',help='instance id of the instance to ssh to');
        parser.add_argument('-ii','--ignore-host-key',dest='ignore-host-key',default=False,action='store_true',help='Ignore host key')
        parser.add_argument('-ne','--no-echo',dest='no-echo',default=False,action='store_true',help='Do not echo command')
        parser.add_argument('-L',dest='forwarding',nargs='*',help="port forwarding string of the form: {localport}:{host-visible-to-instance}:{remoteport} or {port}")
        parser.add_argument('-R','--replace-key',dest='replaceKey',default=False,action='store_true',help="Replace the host's key. This is useful when AWS recycles an IP address you've seen before.")
        parser.add_argument('-Y','--keyscan',dest='keyscan',default=False,action='store_true',help="Perform a keyscan to avoid having to say 'yes' for a new host. Implies -R.")
        parser.add_argument('-B','--background',dest='background',default=False,action='store_true',help="Run in the background. (e.g., forward an ssh session and then do other stuff in aws-shell).")
        parser.add_argument('-v',dest='verbosity',default=0,action=VAction,nargs='?',help='Verbosity. The more instances, the more verbose');        
        parser.add_argument('-m',dest='macro',default=False,action='store_true',help='{command} is a series of macros to execute, not the actual command to run on the host');
        parser.add_argument(dest='command',nargs='*',help="Command to run on all hosts.") # consider adding a filter option later
        args = vars(parser.parse_args(args))

        interfaceNumber = int(args['interface-number'])
        forwarding = args['forwarding']
        replaceKey = args['replaceKey']
        keyscan = args['keyscan']
        background = args['background']
        verbosity = args['verbosity']
        ignoreHostKey = args['ignore-host-key']
        noEcho = args['no-echo']

        # Figure out the host to connect to:
        target = args['instance']
        try:
            index = int(args['instance'])
            instances = self.scalingGroupDescription['AutoScalingGroups'][0]['Instances']
            instance = instances[index]
            target = instance['InstanceId']
        except ValueError: # if args['instance'] is not an int, for example.
            pass
        
        if args['macro']:
            if len(args['command']) > 1:
                print("Only one macro may be specified with the -m switch.")
                return
            else:
                macro = args['command'][0]
                print("Macro:{}".format(macro))
                command = Config.config['ssh-macros'][macro]
        else:
            command = ' '.join(args['command'])
            
        ssh(target,interfaceNumber,forwarding,replaceKey,keyscan,background,verbosity,command,ignoreHostKey=ignoreHostKey,echoCommand = not noEcho)
1181233
def launch_ssh(self, name, port):
        """"""
        if options.user:
            name = '%s@%s' % (options.user, name)
        evaluated = options.ssh % {'host': name, 'port': port}
        if evaluated == options.ssh:
            evaluated = '%s %s' % (evaluated, name)
        os.execlp('/bin/sh', 'sh', '-c', evaluated)
96926
def wait_for_ssh(host, port=22, timeout=600):
    
    log_yellow('waiting for ssh...')
    for iteration in xrange(1, timeout): #noqa
        sleep(1)
        if is_ssh_available(host, port):
            return True
        else:
            log_yellow('waiting for ssh...')
737565
def start_server(self):
        """"""
        if self.server is None:
            self.port = select_port(default_port=self.DEFAULT_PORT)
            self.set_home_url('http://localhost:%d/' % self.port)
        elif self.server.isRunning():
            self.server.server_started.disconnect(self.initialize_continued)
            self.server.quit()
        self.server = PydocServer(port=self.port)
        self.server.server_started.connect(self.initialize_continued)
        self.server.start()
520928
def restart(name):
    '''
    
    '''
    if _service_is_upstart(name):
        cmd = 'restart {0}'.format(name)
    else:
        cmd = '/sbin/service {0} restart'.format(name)
    return not __salt__['cmd.retcode'](cmd, python_shell=False)