Graceful exit of docker / k8s container (Python, go, Java)

Tencent Data Architect 2020-11-13 07:21:27
graceful exit docker k8s container


Full stack engineer development manual ( author : Luan Peng )
Architecture Series

Be careful :docker Normal exit and abnormal exit will not be initiated automatically SIGTERM,java Normal or abnormal exit ,jvm By the church SIGTERM The signal

docker kill Kill the container process directly
docker stop Send... To the container process SIGTERM The signal , This article introduces the process Capture in the container SIGTERM The signal , Exit gracefully .

github Address :https://github.com/626626cdllp/k8s/tree/master/test/docker-signal

Let's get to know the signal first

SIGINT

Termination of procedure (interrupt) The signal , Type... In the user INTR character ( Usually Ctrl-C) Issued at , Used to notify the foreground process group to terminate the process .

SIGQUIT

and SIGINT similar , But by QUIT character ( Usually Ctrl-) To control . The process is receiving SIGQUIT Exit will produce core file , In this sense, it is similar to a program error signal .

SIGTERM

Program end (terminate) The signal , And SIGKILL The difference is that the signal can be blocked and processed . It is usually used to ask the program to exit normally ,shell command kill This signal is generated by default . If the process doesn't stop , We will try SIGKILL.

SIGSTOP

stop it (stopped) Process execution . Pay attention to it and terminate as well as interrupt The difference between : The process is not over yet , Just suspended execution . This signal cannot be blocked , To deal with or ignore .

Add exit processing logic

Hypothetical source dockerfile As defined in entrypoint by python /app/server.py

Now you need to rewrite a script entrypoint.sh

#!/bin/sh
# The actual working procedure , Open the general background running situation of the source main program
nohup python /app/server.py &
# Interrupt signal processing function , close python The main program
prog_exit()
{
ps -ef| grep python |grep -v grep |awk '{print $2}'|xargs kill -15
}
# Register interrupt handler
trap "prog_exit" 15
flag=1
# Front end form of running sleep , And cross whether you can exit (python The process no longer exists , Can also be in python Close the container when the process exits by itself )
while [ $flag -ne 0 ];do
sleep 3;
flag=`ps -ef| grep atm |grep -v grep | wc -l`
done;

And then dockerfile Medium entrypoint Start a new script instead


FROM ubuntu:18.04
RUN apt-get update && \
apt-get install -y python3.6 && \
rm -rf /var/lib/apt/lists/*
COPY ./server.py /data/
COPY ./entrypoint.sh /data/
WORKDIR /data/
# Use sh Do elegant exit
ENTRYPOINT ["/data/entrypoint.sh"]
CMD ["bash"]
# Direct to python Initiate an exit order
# ENTRYPOINT ["python3.6","/data/server.py"]

Add exit processing logic in business code (python)

The purpose of graceful exit is to deal with the unfinished business . In general, the exit signal needs to be processed in the business code . Like the one above server.py Add processing logic .

The first way ,
We use ps -ef| grep python |grep -v grep |awk '{print $2}'|xargs kill -15 The command to python The service started kill The signal , We can do it in python This is also received in the script bash Sponsored kill The signal .

The second way ,
We receive container initiated... Directly in the business code SIGTERM The signal ( The method is more direct ), such dockerfile The source entry point is still used in

ENTRYPOINT ["python3.6","/data/server.py"]

For example, we can write server.py

import signal
import time
is_running = True
def sigint_handler(num, stack):
print(num,stack)
print('receive sigint')
global is_running
is_running = False
def sigterm_handler(num, stack):
print(num,stack)
print('receive sigterm')
global is_running
is_running = False
def main():
signal.signal(signal.SIGINT, sigint_handler)
signal.signal(signal.SIGTERM, sigterm_handler)
signal.siginterrupt(signal.SIGINT, False)
signal.siginterrupt(signal.SIGTERM, False)
while is_running:
print('begin sleep')
# Start your business function
time.sleep(3)
print("prepare exit")
print("sleep 10")
time.sleep(10)
print("exit")
if __name__ == "__main__":
main()

perform python3.6 server.py You'll see a log like this

begin sleep
begin sleep
begin sleep
15 <frame object at 0x2371b18>
receive sigterm
prepare exit
sleep 10

go Language receive exit signal

About Go Language to system Signal To deal with , You can refer to 《Go System in Signal Handle 》 One article .

https://tonybai.com/2014/10/09/gracefully-shutdown-app-running-in-docker/

java Language receive exit signal

https://blog.csdn.net/zhangpeterx/article/details/89454050

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
// import com.lmax.disruptor.LifecycleAware;
// Pay attention to let java Process pid by 1, Otherwise docker stop The signal is not received
public class demo {

public static void main(String[] args) {

Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {

@Override
public void run() {

System.out.println("Exited!");
}
}));
System.out.println("begin!");
try{

Thread.sleep(1000*60);
} catch (Exception e) {

e.printStackTrace();
}
}
}

k8s Container life cycle hook

Reference resources https://kubernetes.io/zh/docs/concepts/containers/container-lifecycle-hooks/

There are two hooks exposed in the container :

PostStart

The hook executes immediately after the container is created . however , There is no guarantee that the hook will execute before the container entry point . There are no parameters passed to the handler .

PreStop

Whether to call this hook immediately before the container terminates , Depending on API Request or manage events , Similar to active probe failure 、 resource preemption 、 Resource competition and so on . If the container is already in a fully terminated or completed state , On the other hand preStop Hook call will fail . It's clogged , It's also synchronous , So it has to be done before the call to delete the container . There are no parameters passed to the handler

k8s Example

# Source: superset/templates/secret.yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: python-config
data:
pre_start.py: |-
import time
import os
if __name__=='__main__':
print('pre start process %s.' % os.getpid())
print('end')
time.sleep(10)
print('Process start.')
pre_stop.py: |-
import time
import os
if __name__=='__main__':
print('pre stop process %s.' % os.getpid())
print('end')
print('Process end.')
---
apiVersion: v1
kind: Pod
metadata:
labels:
app: python
name: python-pod
spec:
volumes:
- name: python-configmap
configMap:
name: python-config
items:
- key: pre_stop.py
path: pre_stop.py
- key: pre_start.py
path: pre_start.py
containers:
- command: ['xxxxx','xxxxx']
name: python
workingDir: /
image: xxxxxxxxx
lifecycle:
postStart:
exec:
command: ["/bin/bash","-c","python /pre_start.py >> pre_start.txt"]
preStop:
exec:
command: ["/bin/bash","-c","python /pre_stop.py >> pre_stop.txt"]
volumeMounts:
- name: python-configmap
mountPath: /pre_stop.py
subPath: pre_stop.py
- name: python-configmap
mountPath: /pre_start.py
subPath: pre_start.py

Implementation of hook handler ( May trigger repeatedly )

The container can access the hook by implementing and registering its handler . For containers , There are two types of hook handlers available :

  • Exec - To execute a specific order , for example pre-stop.sh, In the container cgroups And namespace . The resources consumed by the command are calculated according to the container .
  • HTTP - Execute... On a specific endpoint on the container HTTP request

about PostStart hook , Container entry point and hook are triggered asynchronously . Both are running , The container just enters running state .
about PreStop hook . If PreStop Hook is suspended during execution ,Pod The stage will remain at Terminating state , And in Pod The end of the terminationGracePeriodSeconds After being killed . in other words PreStop The maximum running time of the hook is terminationGracePeriodSeconds The value of the property configuration .

If PostStart or PreStop Hook failed , It will kill the container .

The hook handler's log will not be in Pod Open in the event . If the handler fails for some reason , It will play an event . about PostStart, This is a FailedPostStartHook event , about PreStop, This is a FailedPreStopHook event . You can run kubectl describe pod <pod_name> Command to view these events

版权声明
本文为[Tencent Data Architect]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database