做服务器端开发的同学应该都对进程监控不会陌生,最近恰好要更换 uwsgi 为 gunicorn,而gunicorn又恰好有这么一章讲进程监控,所以多研究了下。
结合之前在腾讯工作的经验,也会讲讲腾讯的服务器监控是怎么做的。同时也会讲下小团队又该怎么敏捷的解决。
下面按照监控的方法依次介绍。
一、按照进程名监控
在腾讯内部所有server都是要打包发布的,而在打包过程中是需要填写要监控的进程名,然后在crontab中定时通过ps查询进程是否存在。
这种方法是比较简单的方法,但是考虑到很多进程会在启动之后改名,以及进程名存在各种特殊字符,多个进程同时存在的问题,实际操作起来并不是很舒服。
举个简单的例子,gunicorn启动之后的进程名类似这样 master: [wsgi:app],其中的方括号在grep时要记得转义,否则就会出问题。
不过不管怎么说,这种方法在很多其他方式用不了的时候反而是最简单的方法。
下面是用python的实现:
代码如下:
def monitor_process(key_word, cmd):
p1 = subprocess.Popen(['ps', '-ef'], stdout=subprocess.PIPE)
p2 = subprocess.Popen(['grep', key_word], stdin=p1.stdout, stdout=subprocess.PIPE)
p3 = subprocess.Popen(['grep', '-v', 'grep'], stdin=p2.stdout, stdout=subprocess.PIPE)
lines = p3.stdout.readlines()
if len(lines) > 0:
return
sys.stderr.write('process[%s] is lost, run [%s]\n' % (key_word, cmd))
subprocess.call(cmd, shell=True)
二、按照端口监控
这种方式之前在腾讯打包的时候也有用,但是可能是进程名更直观的原因吧,貌似一直没怎么用起来。
不过现在自己在做包部署的时候,反而觉得端口监控是个最靠谱的事情了。这个也没什么好多说的,直接上刚写完的python代码:
代码如下:
def monitor_port(protocol, port, cmd):
address = ('127.0.0.1', port)
socket_type = socket.SOCK_STREAM if protocol == 'tcp' else socket.SOCK_DGRAM
client = socket.socket(socket.AF_INET, socket_type)
try:
client.bind(address)
except Exception, e:
pass
else:
sys.stderr.write('port[%s-%s] is lost, run [%s]\n' % (protocol, port, cmd))
subprocess.call(cmd, shell=True)
finally:
client.close()
有的朋友可能说对于tcp端口检查,其实以client的方式来connect()看是否成功会不会更好?其实我觉得这种方式也挺好的,并且对于不同的协议可以再深入处理一下,比如对http协议可以用urllib2.urlopen确保返回正确的包才算正常。不过如果这么做的话,就有点偏黑盒监控 了,比如监控宝、阿里云监控之类的服务了。
三、通过监控server启动进程,并以监控子进程的方式监控
这个也是在gunicorn页面上看到的,说起来gunicorn很不厚道的把gaffer放到第一个,让我还以为是个很成熟的产品,结果发现连启动都是个问题。
相反排在后面的supervisor反而相当的好用,下面是截图:
supervisor可以很方便的管理进程,包括重启,停止等等,而且提供了web界面和用户验证,可以很方便的在线管理。
但是有好处就有坏处,用了supervisor之后,就不能自己随便的去自己重启服务了,否则会影响supervisor的监控,这对我这种喜欢自己执行 xx.sh restart 的人实在有点太痛苦了。当然,其实要是习惯了去supervisorctl 里面start/stop/reload 之后也就还好了。
用supervisor配置gunicorn的配置项如下:
代码如下:
[program:yuanzhaopin]
environment=PYTHON_EGG_CACHE=/tmp/.python-eggs/,PYTHONPATH=/data/release/yuanzhaopin
command=/usr/local/bin/gunicorn --debug --log-level debug --log-file /tmp/g.log wsgi:app
user=zny2008
autorestart=true
redirect_stderr=true
ok,目前自己常用的就是这几种模式了,大家如果有其他选择欢迎留言讨论。
完整代码如下:
代码如下:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#*/1 * * * * python /xxx/monitor.py >> /xxx/logs/monitor.log 2>&1 &
import sys
import subprocess
import os.path as op
import socket
def this_abs_path(script_name):
return op.abspath(op.join(op.dirname(__file__), script_name))
def monitor_process(key_word, cmd):
p1 = subprocess.Popen(['ps', '-ef'], stdout=subprocess.PIPE)
p2 = subprocess.Popen(['grep', key_word], stdin=p1.stdout, stdout=subprocess.PIPE)
p3 = subprocess.Popen(['grep', '-v', 'grep'], stdin=p2.stdout, stdout=subprocess.PIPE)
lines = p3.stdout.readlines()
if len(lines) > 0:
return
sys.stderr.write('process[%s] is lost, run [%s]\n' % (key_word, cmd))
subprocess.call(cmd, shell=True)
def monitor_port(protocol, port, cmd):
address = ('127.0.0.1', port)
socket_type = socket.SOCK_STREAM if protocol == 'tcp' else socket.SOCK_DGRAM
client = socket.socket(socket.AF_INET, socket_type)
try:
client.bind(address)
except Exception, e:
pass
else:
sys.stderr.write('port[%s-%s] is lost, run [%s]\n' % (protocol, port, cmd))
subprocess.call(cmd, shell=True)
finally:
client.close()
#=============================================================================
def yuanzhaopin():
cmd = '%s start' % this_abs_path('gun.sh')
#monitor_process('\[yuanzhaopin\]', cmd)
monitor_port('tcp', 8635, cmd)
def main():
yuanzhaopin()
if __name__ == '__main__':
main()

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.