/*
 * Copyright (c) 2018 無色眼镜
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package club.dawdler.server.shutdown;

import java.io.Closeable;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import club.dawdler.core.shutdown.ContainerGracefulShutdown;
import club.dawdler.server.bootstrap.ServerConnectionManager;
import club.dawdler.util.DawdlerConfig;

/**
 *
 * @author jackson.song
 * @version V1.0
 * dawdlerServer优雅停机 等待任务完成之后调用closeable.close();
 * 原有代码在DawdlerServer.java中实现,现在通过SPI接口方式统一实现.
 * 连接管理器经 {@link ServerConnectionManagerBinder} 获取(由DawdlerServer.start绑定),
 * 不再依赖ServerConnectionManager自身的静态单例.
 */
public class DawdlerServerGracefulShutdown implements ContainerGracefulShutdown {
	private static final Logger logger = LoggerFactory.getLogger(DawdlerServerGracefulShutdown.class);
	private static final long GRACEFUL_TIMEOUT_MILLIS = DawdlerConfig
			.getLong("dawdler.server.graceful.timeout", 30_000L);

	@Override
	public void shutdown(Closeable closeable) throws Exception {
		if (closeable != null) {
			ServerConnectionManager sm = ServerConnectionManagerBinder.getBound();
			if (sm != null) {
				awaitIdle(sm);
			}
			closeable.close();
		}
	}

	private static void awaitIdle(ServerConnectionManager sm) {
		boolean idle;
		try {
			idle = sm.awaitIdle(GRACEFUL_TIMEOUT_MILLIS);
		} catch (InterruptedException e) {
			Thread.currentThread().interrupt();
			logger.warn("Graceful shutdown interrupted, stop waiting for pending tasks.");
			return;
		}
		if (!idle) {
			logger.warn("Graceful shutdown timeout after {}ms, pending tasks remain, force closing.",
					GRACEFUL_TIMEOUT_MILLIS);
		}
	}

}
