/*
 * Copyright 2012-2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.boot.web.embedded.tomcat;

import java.lang.reflect.Field;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

import org.apache.catalina.Container;
import org.apache.catalina.Service;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.StandardWrapper;
import org.apache.catalina.startup.Tomcat;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.boot.web.server.GracefulShutdown;
import org.springframework.util.ReflectionUtils;

/**
 * {@link GracefulShutdown} for {@link Tomcat}.
 *
 * @author Andy Wilkinson
 */
class TomcatGracefulShutdown implements GracefulShutdown {

	private static final Log logger = LogFactory.getLog(TomcatGracefulShutdown.class);

	private final Tomcat tomcat;

	private final Duration period;

	private volatile boolean shuttingDown = false;

	TomcatGracefulShutdown(Tomcat tomcat, Duration period) {
		this.tomcat = tomcat;
		this.period = period;
	}

	@Override
	public boolean shutDownGracefully() {
		logger.info("Commencing graceful shutdown, allowing up to " + this.period.getSeconds()
				+ "s for active requests to complete");
		List<Connector> connectors = getConnectors();
		for (Connector connector : connectors) {
			connector.pause();
			connector.getProtocolHandler().closeServerSocketGraceful();
		}
		this.shuttingDown = true;
		try {
			long end = System.currentTimeMillis() + this.period.toMillis();
			for (Container host : this.tomcat.getEngine().findChildren()) {
				for (Container context : host.findChildren()) {
					while (active(context)) {
						if (System.currentTimeMillis() > end) {
							logger.info("Grace period elapsed with one or more requests still active");
							return false;
						}
						Thread.sleep(50);
					}
				}
			}

		}
		catch (InterruptedException ex) {
			Thread.currentThread().interrupt();
		}
		finally {
			this.shuttingDown = false;
		}
		logger.info("Graceful shutdown complete");
		return true;
	}

	private boolean active(Container context) {
		try {
			Field field = ReflectionUtils.findField(context.getClass(), "inProgressAsyncCount");
			field.setAccessible(true);
			AtomicLong inProgressAsyncCount = (AtomicLong) field.get(context);
			if (inProgressAsyncCount.get() > 0) {
				return true;
			}
			for (Container wrapper : context.findChildren()) {
				if (((StandardWrapper) wrapper).getCountAllocated() > 0) {
					return true;
				}
			}
			return false;
		}
		catch (Exception ex) {
			throw new RuntimeException(ex);
		}
	}

	private List<Connector> getConnectors() {
		List<Connector> connectors = new ArrayList<>();
		for (Service service : this.tomcat.getServer().findServices()) {
			for (Connector connector : service.findConnectors()) {
				connectors.add(connector);
			}
		}
		return connectors;
	}

	@Override
	public boolean isShuttingDown() {
		return this.shuttingDown;
	}

}

@@ -675,40 +675,8 @@
 t;%0A%0A
-import java.lang.reflect.Field;%0A
 impo
@@ -698,16 +698,16 @@
 ration;%0A
+
 import j
@@ -752,55 +752,8 @@
 ist;
-%0Aimport java.util.concurrent.atomic.AtomicLong;
 %0A%0Aim
@@ -872,16 +872,65 @@
 nector;%0A
+import org.apache.catalina.core.StandardContext;%0A
 import o
@@ -1099,16 +1099,16 @@
 ctory;%0A%0A
+
 import o
@@ -1163,57 +1163,8 @@
 own;
-%0Aimport org.springframework.util.ReflectionUtils;
 %0A%0A/*
@@ -2684,201 +2684,44 @@
 %0A%09%09%09
-Field field = ReflectionUtils.findField(context.getClass(), %22inProgressAsyncCount%22);%0A%09%09%09field.setAccessible(true);%0A%09%09%09AtomicLong inProgressAsyncCount = (AtomicLong) field.get(context);%0A%09%09%09if (i
+if (((StandardContext) context).getI
 nPro
@@ -2735,20 +2735,16 @@
 yncCount
-.get
 () %3E 0) 

Use accessor for in-progress async count added in Tomcat 9.0.33