Handler to kill a topology
169675
@VisibleForTesting
  void killTopologyHandler(String topologyName) throws TopologyRuntimeManagementException {
    Scheduler.KillTopologyRequest killTopologyRequest = Scheduler.KillTopologyRequest.newBuilder()
        .setTopologyName(topologyName).build();

    if (!schedulerClient.killTopology(killTopologyRequest)) {
      throw new TopologyRuntimeManagementException(
          String.format("Failed to kill topology '%s' with scheduler, "
              + "please re-try the kill command later", topologyName));
    }

    // clean up the state of the topology in state manager
    cleanState(topologyName, Runtime.schedulerStateManagerAdaptor(runtime));

    if (potentialStaleExecutionData) {
      LOG.warning(String.format("Topology %s does not exist. Cleaned up potential stale state.",
          topologyName));
    } else {
      LOG.fine(String.format("Scheduler killed topology %s successfully.", topologyName));
    }
  }
529595
def close(self) -> Awaitable[None]:
        """"""
        for ev in self._throttle_dns_events.values():
            ev.cancel()

        return super().close()
294379
def terminate(self, nodes=None):
        
        if not self.is_connected():
            return None

        nodes = nodes or self.nodes
        failed_kill = []

        result = self.gce.ex_destroy_multiple_nodes(nodes, poll_interval=1, ignore_errors=False)

        # Verify whether all instances have been terminated.
        for i, success in enumerate(result):
            if success:
                logging.info('Successfully destroyed: %s', nodes[i].name)
            else:
                logging.error('Failed to destroy: %s', nodes[i].name)
                failed_kill.append(nodes[i])

        return failed_kill
1106184
def kill(name, signal):
    '''
    
    '''
    if not exists(name):
        raise ContainerNotExists("The container (%s) does not exist!" % name)
    cmd = ['lxc-kill', '--name=%s' % name, signal]
    subprocess.check_call(cmd)
125890
async def shutdown(self, timeout: Optional[float]=15.0) -> None:
        """"""
        self._force_close = True

        if self._keepalive_handle is not None:
            self._keepalive_handle.cancel()

        if self._waiter:
            self._waiter.cancel()

        # wait for handlers
        with suppress(asyncio.CancelledError, asyncio.TimeoutError):
            with CeilTimeout(timeout, loop=self._loop):
                if (self._error_handler is not None and
                        not self._error_handler.done()):
                    await self._error_handler

                if (self._task_handler is not None and
                        not self._task_handler.done()):
                    await self._task_handler

        # force-close non-idle handler
        if self._task_handler is not None:
            self._task_handler.cancel()

        if self.transport is not None:
            self.transport.close()
            self.transport = None
818534
def close(self):
        """"""
        with self._lock:
            for server in self._servers.values():
                server.close()

            # Mark all servers Unknown.
            self._description = self._description.reset()
            self._update_servers()
            self._opened = False

        # Publish only after releasing the lock.
        if self._publish_tp:
            self._events.put((self._listeners.publish_topology_closed,
                              (self._topology_id,)))
        if self._publish_server or self._publish_tp:
            self.__events_executor.close()
155512
function disposeOfSocket(apiBase) {
        return function (error) {
            loggingService.warn("Got disconnected from signalling server (" + apiBase + ")", error);

            var socket = connectedSockets[apiBase];
            if (socket) {
                stopConnectivityChecks();
                socket.removeAllListeners();
                socket.io.removeAllListeners();
                try {
                    socket.disconnect();
                }
                catch (ignore) {
                }
                deleteSocket(apiBase);

                if (!unloadInProgress) {
                    connectAndMonitor();
                }
            }
            else {
                throw new Error("BUG ::: Disconnected from a socket we're not connected to?!");
            }
        };
    }
1129613
public void destroy() {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(tc, "destroy");
        }

        // Go through the hashtable and destroy all long-lived, single instance,
        // resources related to a given TCP Channel type (NIO, AIO, etc...)
        for (ChannelTermination ct : this.terminationList.values()) {
            ct.terminate();
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(tc, "destroy");
        }
    }
1258715
def handle(self):
        """"""
        rv = None
        try:
            rv = BaseHTTPRequestHandler.handle(self)
        except (_ConnectionError, socket.timeout) as e:
            self.connection_dropped(e)
        except Exception as e:
            if self.server.ssl_context is None or not is_ssl_error(e):
                raise
        if self.server.shutdown_signal:
            self.initiate_shutdown()
        return rv
356554
def kill(self, dwExitCode = 0):
        
        hProcess = self.get_handle(win32.PROCESS_TERMINATE)
        win32.TerminateProcess(hProcess, dwExitCode)
494931
def on_close(self):
        '''
        
        '''

        if self.id in self.funcserver.websocks:
            self.funcserver.websocks[self.id] = None
            ioloop = tornado.ioloop.IOLoop.instance()
            ioloop.add_callback(lambda: self.funcserver.websocks.pop(self.id, None))

        psession = self.funcserver.pysessions.get(self.pysession_id, None)
        if psession:
            psession['socks'].remove(self.id)
            if not psession['socks']:
                del self.funcserver.pysessions[self.pysession_id]
729139
def kill_process(process):
    """"""
    logger = logging.getLogger('xenon')
    logger.info('Terminating Xenon-GRPC server.')
    os.kill(process.pid, signal.SIGINT)
    process.wait()
730473
function signalKill(childProcess, callback) {
  childProcess.emit('signalKill');
  if (IS_WINDOWS) {
    const taskkill = spawn('taskkill', ['/F', '/T', '/PID', childProcess.pid]);
    taskkill.on('exit', (exitStatus) => {
      if (exitStatus) {
        return callback(
          new Error(`Unable to forcefully terminate process ${childProcess.pid}`)
        );
      }
      callback();
    });
  } else {
    childProcess.kill('SIGKILL');
    process.nextTick(callback);
  }
}
211301
@VisibleForTesting
  void restartTopologyHandler(String topologyName) throws TopologyRuntimeManagementException {
    assert !potentialStaleExecutionData;
    Integer containerId = Context.topologyContainerId(config);
    Scheduler.RestartTopologyRequest restartTopologyRequest =
        Scheduler.RestartTopologyRequest.newBuilder()
            .setTopologyName(topologyName)
            .setContainerIndex(containerId)
            .build();
    // If we restart the container including TMaster, wee need to clean TMasterLocation,
    // since when starting up, TMaster expects no other existing TMaster,
    // i.e. TMasterLocation does not exist
    if (containerId == -1 || containerId == 0) {
      // get the instance of state manager to clean state
      SchedulerStateManagerAdaptor stateManager = Runtime.schedulerStateManagerAdaptor(runtime);
      Boolean result = stateManager.deleteTMasterLocation(topologyName);
      if (result == null || !result) {
        throw new TopologyRuntimeManagementException(
            "Failed to clear TMaster location. Check whether TMaster set it correctly.");
      }
    }

    if (!schedulerClient.restartTopology(restartTopologyRequest)) {
      throw new TopologyRuntimeManagementException(String.format(
          "Failed to restart topology '%s'", topologyName));
    }
    // Clean the connection when we are done.
    LOG.fine("Scheduler restarted topology successfully.");
  }
258568
def destroy(name, conn=None, call=None):
    '''
    
    '''
    if call == 'function':
        raise SaltCloudSystemExit(
            'The destroy action must be called with -d, --destroy, '
            '-a or --action.'
        )

    __utils__['cloud.fire_event'](
        'event',
        'destroying instance',
        'salt/cloud/{0}/destroying'.format(name),
        args={'name': name},
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    if not conn:
        conn = get_conn()
    node = show_instance(name, conn=conn, call='action')
    log.info('Destroying VM: %s', name)
    ret = conn.delete_server(name)
    if ret:
        log.info('Destroyed VM: %s', name)
        # Fire destroy action
        __utils__['cloud.fire_event'](
            'event',
            'destroyed instance',
            'salt/cloud/{0}/destroyed'.format(name),
            args={'name': name},
            sock_dir=__opts__['sock_dir'],
            transport=__opts__['transport']
        )
        if __opts__.get('delete_sshkeys', False) is True:
            __utils__['cloud.remove_sshkey'](getattr(node, __opts__.get('ssh_interface', 'public_ips'))[0])
        if __opts__.get('update_cachedir', False) is True:
            __utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
        __utils__['cloud.cachedir_index_del'](name)
        return True

    log.error('Failed to Destroy VM: %s', name)
    return False
1221204
def clean_process_tree(*signal_handler_args):
    """"""
    parent = psutil.Process()
    procs = parent.children(recursive=True)
    if procs:
        print(f"[ZProc] Cleaning up {parent.name()!r} ({os.getpid()})...")

    for p in procs:
        with suppress(psutil.NoSuchProcess):
            p.terminate()
    _, alive = psutil.wait_procs(procs, timeout=0.5)  # 0.5 seems to work
    for p in alive:
        with suppress(psutil.NoSuchProcess):
            p.kill()

    try:
        signum = signal_handler_args[0]
    except IndexError:
        pass
    else:
        os._exit(signum)
1357202
def destroy(name, conn=None, call=None):
    '''
    
    '''
    if call == 'function':
        raise SaltCloudSystemExit(
            'The destroy action must be called with -d, --destroy, '
            '-a or --action.'
        )

    __utils__['cloud.fire_event'](
        'event',
        'destroying instance',
        'salt/cloud/{0}/destroying'.format(name),
        sock_dir=__opts__['sock_dir'],
        args={'name': name},
    )

    if not conn:
        conn = get_conn()   # pylint: disable=E0602

    node = get_node(conn, name)
    if node is None:
        log.error('Unable to find the VM %s', name)
    volumes = conn.list_volumes(node)
    if volumes is None:
        log.error('Unable to find volumes of the VM %s', name)
    # TODO add an option like 'delete_sshkeys' below
    for volume in volumes:
        if volume.extra['volume_type'] != 'DATADISK':
            log.info(
                'Ignoring volume type %s: %s',
                volume.extra['volume_type'], volume.name
            )
            continue
        log.info('Detaching volume: %s', volume.name)
        __utils__['cloud.fire_event'](
            'event',
            'detaching volume',
            'salt/cloud/{0}/detaching'.format(volume.name),
            sock_dir=__opts__['sock_dir'],
            args={'name': volume.name},
        )
        if not conn.detach_volume(volume):
            log.error('Failed to Detach volume: %s', volume.name)
            return False
        log.info('Detached volume: %s', volume.name)
        __utils__['cloud.fire_event'](
            'event',
            'detached volume',
            'salt/cloud/{0}/detached'.format(volume.name),
            sock_dir=__opts__['sock_dir'],
            args={'name': volume.name},
        )

        log.info('Destroying volume: %s', volume.name)
        __utils__['cloud.fire_event'](
            'event',
            'destroying volume',
            'salt/cloud/{0}/destroying'.format(volume.name),
            sock_dir=__opts__['sock_dir'],
            args={'name': volume.name},
        )
        if not conn.destroy_volume(volume):
            log.error('Failed to Destroy volume: %s', volume.name)
            return False
        log.info('Destroyed volume: %s', volume.name)
        __utils__['cloud.fire_event'](
            'event',
            'destroyed volume',
            'salt/cloud/{0}/destroyed'.format(volume.name),
            sock_dir=__opts__['sock_dir'],
            args={'name': volume.name},
        )
    log.info('Destroying VM: %s', name)
    ret = conn.destroy_node(node)
    if not ret:
        log.error('Failed to Destroy VM: %s', name)
        return False
    log.info('Destroyed VM: %s', name)
    # Fire destroy action
    event = salt.utils.event.SaltEvent('master', __opts__['sock_dir'])
    __utils__['cloud.fire_event'](
        'event',
        'destroyed instance',
        'salt/cloud/{0}/destroyed'.format(name),
        sock_dir=__opts__['sock_dir'],
        args={'name': name},
    )
    if __opts__['delete_sshkeys'] is True:
        salt.utils.cloud.remove_sshkey(node.public_ips[0])
    return True