Cancel Hadoop Tokens

@param logger logger handler
167356
public void cancelHadoopTokens(final Logger logger) {
    if (tokenFile == null) {
      return;
    }
    try {
      hadoopSecurityManager.cancelTokens(tokenFile, userToProxy, logger);
    } catch (HadoopSecurityManagerException e) {
      logger.error(e.getCause() + e.getMessage());
    } catch (Exception e) {
      logger.error(e.getCause() + e.getMessage());
    }
    if (tokenFile.exists()) {
      tokenFile.delete();
    }
  }
1370060
public static function removeLogger($logger)
    {
        if ($logger instanceof Logger) {
            if (false !== ($idx = array_search($logger, self::$loggers, true))) {
                unset(self::$loggers[$idx]);
            }
        } else {
            unset(self::$loggers[$logger]);
        }
    }
837523
public static void logReducedStackTrace(Logger logger, Exception exception) {
		Exception here = new Exception();
		String[] hereStrings = getStackFrames(here);
		String[] throwableStrings = getStackFrames(exception);
		
		int linesToSkip = 1;
		while (throwableStrings.length - linesToSkip > 0 && hereStrings.length - linesToSkip > 0) {
			if (!StringUtils.equals(hereStrings[hereStrings.length-linesToSkip], throwableStrings[throwableStrings.length-linesToSkip])) {
				break;
			}
			linesToSkip++;
		}
		for (int i = 0; i<=throwableStrings.length-linesToSkip; i++) {
			logger.log(Level.SEVERE, throwableStrings[i]);
		}
	}
1120608
def stop_logging():
    
    global __UTOOL_ROOT_LOGGER__
    global __UTOOL_PRINT__
    global __UTOOL_WRITE__
    global __UTOOL_FLUSH__
    if __UTOOL_ROOT_LOGGER__ is not None:
        # Flush remaining buffer
        if VERBOSE or LOGGING_VERBOSE:
            _utool_print()()('<__LOG_STOP__>')
        _utool_flush()()
        # Remove handlers
        for h in __UTOOL_ROOT_LOGGER__.handlers[:]:
            __UTOOL_ROOT_LOGGER__.removeHandler(h)
        # Reset objects
        __UTOOL_ROOT_LOGGER__ = None
        __UTOOL_PRINT__    = None
        __UTOOL_WRITE__    = None
        __UTOOL_FLUSH__    = None
138095
public void cancel() {
    List<CancellationTokenRegistration> registrations;
    synchronized (lock) {
      throwIfClosed();
      if (cancellationRequested) {
        return;
      }

      cancelScheduledCancellation();

      cancellationRequested = true;
      registrations = new ArrayList<>(this.registrations);
    }
    notifyListeners(registrations);
  }
29622
protected void stopThreads(ClassLoaderLeakPreventor preventor) {
    final Class<?> workerClass = preventor.findClass("java.util.concurrent.ThreadPoolExecutor$Worker");

    final boolean waitForThreads = threadWaitMs > 0;
    for(Thread thread : preventor.getAllThreads()) {
      final Runnable runnable = getRunnable(preventor, thread);

      final boolean threadLoadedByClassLoader = preventor.isLoadedInClassLoader(thread);
      final boolean threadGroupLoadedByClassLoader = preventor.isLoadedInClassLoader(thread.getThreadGroup());
      final boolean runnableLoadedByClassLoader = preventor.isLoadedInClassLoader(runnable);
      final boolean hasContextClassLoader = preventor.isClassLoaderOrChild(thread.getContextClassLoader());
      if(thread != Thread.currentThread() && // Ignore current thread
         (threadLoadedByClassLoader || threadGroupLoadedByClassLoader || hasContextClassLoader || // = preventor.isThreadInClassLoader(thread) 
          runnableLoadedByClassLoader)) {

        if (thread.getClass().getName().startsWith(StopThreadsCleanUp.JURT_ASYNCHRONOUS_FINALIZER)) {
          // Note, the thread group of this thread may be "system" if it is triggered by the Garbage Collector
          // however if triggered by us in forceStartOpenOfficeJurtCleanup() it may depend on the application server
          if(stopThreads) {
            preventor.info("Found JURT thread " + thread.getName() + "; starting " + JURTKiller.class.getSimpleName());
            new JURTKiller(preventor, thread).start();
          }
          else
            preventor.warn("JURT thread " + thread.getName() + " is still running in protected ClassLoader");
        }
        else if(thread.getThreadGroup() != null && 
           ("system".equals(thread.getThreadGroup().getName()) ||  // System thread
            "RMI Runtime".equals(thread.getThreadGroup().getName()))) { // RMI thread (honestly, just copied from Tomcat)
          
          if("Keep-Alive-Timer".equals(thread.getName())) {
            thread.setContextClassLoader(preventor.getLeakSafeClassLoader());
            preventor.debug("Changed contextClassLoader of HTTP keep alive thread");
          }
        }
        else if(thread.isAlive()) { // Non-system, running in protected ClassLoader

          if(thread.getClass().getName().startsWith("java.util.Timer")) { // Sun/Oracle = "java.util.TimerThread"; IBM = "java.util.Timer$TimerImpl"
            if(thread.getName() != null && thread.getName().startsWith("PostgreSQL-JDBC-SharedTimer-")) { // Postgresql JDBC timer thread
              // Replace contextClassLoader, if needed
              if(hasContextClassLoader) {
                final Class<?> postgresqlDriver = preventor.findClass("org.postgresql.Driver");
                final ClassLoader postgresqlCL = (postgresqlDriver != null && ! preventor.isLoadedByClassLoader(postgresqlDriver)) ?
                    postgresqlDriver.getClassLoader() : // Postgresql driver loaded by other classloader than we want to protect
                    preventor.getLeakSafeClassLoader();
                thread.setContextClassLoader(postgresqlCL);
                preventor.warn("Changing contextClassLoader of " + thread + " to " + postgresqlCL);
              }

              // Replace AccessControlContext
              final Field inheritedAccessControlContext = preventor.findField(Thread.class, "inheritedAccessControlContext");
              if(inheritedAccessControlContext != null) {
                try {
                  final AccessControlContext acc = preventor.createAccessControlContext();
                  inheritedAccessControlContext.set(thread, acc);
                  preventor.removeDomainCombiner("thread " + thread, acc);
                }
                catch (Exception e) {
                  preventor.error(e);
                }
              }
            }
            else if(stopTimerThreads) {
              preventor.warn("Stopping Timer thread '" + thread.getName() + "' running in protected ClassLoader. " +
                  preventor.getStackTrace(thread));
              stopTimerThread(preventor, thread);
            }
            else {
              preventor.info("Timer thread is running in protected ClassLoader, but will not be stopped. " + 
                  preventor.getStackTrace(thread));
            }
          }
          else {
            final String displayString = "Thread '" + thread + "'" + 
                (threadLoadedByClassLoader ? " of type " + thread.getClass().getName() + " loaded by protected ClassLoader" : "") +
                (runnableLoadedByClassLoader ? " with Runnable of type " + runnable.getClass().getName() + " loaded by protected ClassLoader" : "") +
                (threadGroupLoadedByClassLoader ? " with ThreadGroup of type " + thread.getThreadGroup().getClass().getName() + " loaded by protected ClassLoader" : "") +
                (hasContextClassLoader ? " with contextClassLoader = protected ClassLoader or child" : "");

            // If threads is running an java.util.concurrent.ThreadPoolExecutor.Worker try shutting down the executor
            if(workerClass != null && workerClass.isInstance(runnable)) {
              try {
                // java.util.concurrent.ThreadPoolExecutor, introduced in Java 1.5
                final Field workerExecutor = preventor.findField(workerClass, "this$0");
                final ThreadPoolExecutor executor = preventor.getFieldValue(workerExecutor, runnable);
                if(executor != null) {
                  if("org.apache.tomcat.util.threads.ThreadPoolExecutor".equals(executor.getClass().getName())) {
                    // Tomcat pooled thread
                    preventor.debug(displayString + " is worker of " + executor.getClass().getName());
                  }
                  else if(preventor.isLoadedInClassLoader(executor) || preventor.isLoadedInClassLoader(executor.getThreadFactory())) {
                    if(stopThreads) {
                      preventor.warn("Shutting down ThreadPoolExecutor of type " + executor.getClass().getName());
                      executor.shutdownNow();
                    }
                    else {
                      preventor.warn("ThreadPoolExecutor of type " + executor.getClass().getName() +
                          " should be shut down.");
                    }
                  }
                  else {
                    preventor.info(displayString + " is a ThreadPoolExecutor.Worker of " + executor.getClass().getName() +
                        " but found no reason to shut down ThreadPoolExecutor.");
                  }
                }
              }
              catch (Exception ex) {
                preventor.error(ex);
              }
            }

            if(! threadLoadedByClassLoader && ! runnableLoadedByClassLoader && ! threadGroupLoadedByClassLoader) { // Not loaded in protected ClassLoader - just running there
              // This would for example be the case with org.apache.tomcat.util.threads.TaskThread
              if(waitForThreads) {
                preventor.warn(displayString + "; waiting " + threadWaitMs + 
                    " ms. " + preventor.getStackTrace(thread));
                preventor.waitForThread(thread, threadWaitMs, false /* No interrupt */);
              }
              
              if(thread.isAlive() && preventor.isClassLoaderOrChild(thread.getContextClassLoader())) { // Still running in ClassLoader
                preventor.warn(displayString + (waitForThreads ? " still" : "") + 
                    " alive; changing context ClassLoader to leak safe (" + 
                    preventor.getLeakSafeClassLoader() + "). " + preventor.getStackTrace(thread));
                thread.setContextClassLoader(preventor.getLeakSafeClassLoader());
              }
            }
            else if(stopThreads) { // Thread/Runnable/ThreadGroup loaded by protected ClassLoader
              if(waitForThreads) {
                preventor.warn("Waiting for " + displayString + " for " + threadWaitMs + " ms. " +
                    preventor.getStackTrace(thread));

                preventor.waitForThread(thread, threadWaitMs, true /* Interrupt if needed */);
              }

              // Normally threads should not be stopped (method is deprecated), since it may cause an inconsistent state.
              // In this case however, the alternative is a classloader leak, which may or may not be considered worse.
              if(thread.isAlive()) {
                preventor.warn("Stopping " + displayString + ". " + preventor.getStackTrace(thread));
                //noinspection deprecation
                thread.stop();
              }
              else {
                preventor.info(displayString + " no longer alive - no action needed.");
              }
            }
            else {
              preventor.warn(displayString + " would cause leak. " + preventor.getStackTrace(thread));
            }
              
          }
        }
      }
    }
  }
211734
public void setLogger(String logger)
    {
        if(logger != null && logger.trim().length() > 0)
            this.logger = LoggerFactory.getLogger(logger);
    }
462862
@Override
    public void close() {
        if (!this.closed.getAndSet(true)) {
            this.metricReporter.cancel(true);
            this.metrics.close();
            this.rolloverProcessor.close();
            this.writeProcessor.close();

            // Close active ledger.
            WriteLedger writeLedger;
            synchronized (this.lock) {
                writeLedger = this.writeLedger;
                this.writeLedger = null;
                this.logMetadata = null;
            }

            // Close the write queue and cancel the pending writes.
            this.writes.close().forEach(w -> w.fail(new CancellationException("BookKeeperLog has been closed."), true));

            if (writeLedger != null) {
                try {
                    Ledgers.close(writeLedger.ledger);
                } catch (DurableDataLogException bkEx) {
                    log.error("{}: Unable to close LedgerHandle for Ledger {}.", this.traceObjectId, writeLedger.ledger.getId(), bkEx);
                }
            }

            log.info("{}: Closed.", this.traceObjectId);
        }
    }
384286
def disable_logger(self, disabled=True):
        
        # Disable standard IO streams
        if disabled:
            sys.stdout = _original_stdout
            sys.stderr = _original_stderr
        else:
            sys.stdout = self.__stdout_stream
            sys.stderr = self.__stderr_stream

        # Disable handlers
        self.logger.disabled = disabled
189430
public BlockingListMaker<K, E> log(Logger logger) {
        this.logger = logger == null ? NULL_LOGGER : logger;
        return this;
    }
699676
def remove_stream_handlers(logger=None):
    
    if not isinstance(logger, logging.Logger):
        logger = logging.getLogger(logger)

    new_handlers = []
    for handler in logger.handlers:
        # FileHandler is a subclass of StreamHandler so
        # 'if not a StreamHandler' does not work
        if (isinstance(handler, logging.FileHandler) or
            isinstance(handler, logging.NullHandler) or
            (isinstance(handler, logging.Handler) and not
                isinstance(handler, logging.StreamHandler))):
            new_handlers.append(handler)
    logger.handlers = new_handlers
775076
public void removeLoggerRepositoryEventListener(
    final LoggerRepositoryEventListener listener) {
    synchronized (repositoryEventListeners) {
      if (!repositoryEventListeners.contains(listener)) {
        LogLog.warn(
          "Ignoring attempt to remove a "
                  + "non-registered LoggerRepositoryEventListener.");
      } else {
        repositoryEventListeners.remove(listener);
      }
    }
  }
31043
def cleanup_logger(self):
        
        self.log_handler.close()
        self.log.removeHandler(self.log_handler)
1342791
public static List<ILoggingEvent> capture(Logger logger) {
        CaptureAppender capture = new CaptureAppender();
        ((ch.qos.logback.classic.Logger) logger).addAppender(capture);
        capture.start();
        return capture.captured;
    }
910899
public synchronized void stop() {
		if (timer != null) {
			timer.keepRunning = false;
			timer.interrupt();
			timer = null;
		}
		// Remove this manager from the space alert list
		LogRepositorySpaceAlert.getInstance().removeRepositoryInfo(this);
	}
163534
def disable_logging(logger=None):
    
    logger = logger or logging.getLogger()
    disabled = logger.disabled
    logger.disabled = True
    yield
    logger.disabled = disabled
820150
private synchronized void ungetLogService() {
        doWarnIfClosed = doDebug();
        if (log != null) {
            bc.ungetService(logSR);
            logSR = null;
            log = null;
        }
    }