性能调优之综合篇 - Linux系统性能监控和故障排查利器Sysdig
Sysdig绝对是可以跟SystemTap相媲美的工具,都是系统故障排查的利器,不论是开发人员还是运维人员都必须要掌握的一个工具。今天先介绍一下Sysdig的一些特性。官网上说Sysdig是Strace, Tcpdump, Lsof, Htop, Iftop等工具的合体,至于你信不信只有使用之后才能来惊叹我说的到底对不对。这里官网总结了sysdig命令对于strace, tcpdump, lsof, iftop的对比:https://sysdig.com/blog/linux-troubleshooting-cheatsheet/。所以Sysdig主要功能就是系统级别的探测,捕捉服务器上的应用程序对CPU, Memory, I/O, Network的状况。 Sysdig最新版提供了Docker容器镜像,可以很方便的直接拉取Docker镜像,另一方它提供容器级别的信息采集指令(sysdig -pc container.name=your_container_name),支持查询指定容器之间的网络流量、指定容器的CPU使用率等。 公司旗下的商用软件Sysdig Cloud则是容器级别的系统信息和网络流量监控、调试软件,这个在CoreOS Fest 大会上有介绍,它支持Real-Time Dashboard, Historical Replay, Dynamic Topology and Intelligent Alert, 可以想象成Nagios对系统的监控。 软件安装请参考官方文档:http://www.sysdig.org/install/相对于SystemTap的安装Sysdig更容易些,本篇文章有点长就不浪费在安装上了,熟悉Ansible的可以去直接用sysdig的Galaxy:https://galaxy.ansible.com/detail#/role/692 Sysdig的语法在record 和replay系统跟踪方面跟Tcpdump和perf很像;在系统性能分析方面的语法chisels又跟SystemTap和dstat的--top*很像,只不过SystemTap需要自己写tap(代码写好了,比Sysdig强大), Sysdig是已经帮你写好了;在交互式使用方面又跟htop很像。 不废话了,下面介绍一下基本的使用方法。 一,基础功能介绍: 最简单的使用方法是直接输入sysdig, 他会捕获系统的每一个事件并且直接输出到屏幕。 每一个event都是一行信息,输出的格式如下: *%evt.num %evt.time %evt.cpu %proc.name (%thread.tid) %evt.dir %evt.type %evt.args evt.num 是一个自动增长的event number evt.time 是时间戳 evt.cpu 是捕获到的在用的哪颗CPU proc.name 是process name thread.tid 是thread id,如果不是多线程,就是pid evt.dir 是event方向,>代表进入events,<代表退出events evt.type 是event的操作名称,e.g. open or read evt.args 是event 调用命令参数的列表 如果要保存信息的话,可以加上-w选项,限制捕捉行数用-n: sysdig-n100-wfirstcapture.scap 如果是按大小区分捕获文件的话,可以用-C 1 默认捕获1M文件就分割到下一个文件,-W 5 参数只捕获5个文件 sysdig-C1-W5-wsecondcapture.scap 生成的文件名是secondcapture.scap.{1..5}。 要阅读刚才捕获的文件,用-r参数: sysdig-rfirstcapture.scap 如果要对捕获的内容做具体的事件查询呢?请看下面 查询进程是mysqld的event: sysdig-rfirstcapture.scapproc.name=mysqld 看proc.name 是mysql 或者nginx的,并且event是read的event sysdig-rfirstcapture.scapproc.name=mysqldorproc.name=nginxandenv.type=read 筛选的关键字可以用sysdig -l 来获得,他支持以下12中Field Class: fd process evt user group syslog container fdlist k8s mesos span evtin #sysdig-l ---------------------- FieldClass:fd fd.numtheuniquenumberidentifyingthefiledescriptor. fd.typetypeofFD.Canbe'file','directory','ipv4','ipv6','unix', 'pipe','event','signalfd','eventpoll','inotify'or'signal fd'. fd.typechartypeofFDasasinglecharacter.Canbe'f'forfile,4forIP v4socket,6forIPv6socket,'u'forunixsocket,pforpipe, 'e'foreventfd,'s'forsignalfd,'l'foreventpoll,'i'fori notify,'o'foruknown. fd.nameFDfullname.Ifthefdisafile,thisfieldcontainsthefull path.IftheFDisasocket,thisfieldcontaintheconnection tuple. ---------------------- FieldClass:process proc.pidtheidoftheprocessgeneratingtheevent. proc.exethefirstcommandlineargument(usuallytheexecutablenameor acustomone). proc.namethename(excludingthepath)oftheexecutablegeneratingthe event. proc.argstheargumentspassedonthecommandlinewhenstartingtheproc essgeneratingtheevent. proc.envtheenvironmentvariablesoftheprocessgeneratingtheevent. proc.cmdlinefullprocesscommandline,i.e.proc.name+proc.args. proc.exelinefullprocesscommandline,withexeasfirstargument,i.e.pro c.exe+proc.args. proc.cwdthecurrentworkingdirectoryoftheevent. proc.nthreadsthenumberofthreadsthattheprocessgeneratingtheeventcur rentlyhas,includingthemainprocessthread. proc.nchildsthenumberofchildthreadsthattheprocessgeneratingtheeve ntcurrentlyhas.Thisexcludesthemainprocessthread. ---------------------- FieldClass:evt evt.numeventnumber. evt.timeeventtimestampasatimestringthatincludesthenanosecondp art. evt.time.seventtimestampasatimestringwithnonanoseconds. evt.datetimeeventtimestampasatimestringthatincludesthedate. evt.rawtimeabsoluteeventtimestamp,i.e.nanosecondsfromepoch. evt.rawtime.sintegerpartoftheeventtimestamp(e.g.secondssinceepoch). evt.rawtime.nsfractionalpartoftheabsoluteeventtimestamp. evt.reltimenumberofnanosecondsfromthebeginningofthecapture. evt.reltime.snumberofsecondsfromthebeginningofthecapture. evt.reltime.nsfractionalpart(inns)ofthetimefromthebeginningofthec apture. evt.latencydeltabetweenanexiteventandthecorrespondententerevent, innanoseconds. ---------------------- FieldClass:user user.uiduserID. user.nameusername. user.homedirhomedirectoryoftheuser. user.shelluser'sshell. ---------------------- FieldClass:group group.gidgroupID. group.namegroupname. ---------------------- FieldClass:syslog syslog.facility.str facilityasastring. syslog.facilityfacilityasanumber(0-23). syslog.severity.str severityasastring.Canhaveoneofthesevalues:emerg,aler t,crit,err,warn,notice,info,debug syslog.severityseverityasanumber(0-7). syslog.messagemessagesenttosyslog. ---------------------- FieldClass:container container.idthecontainerid. container.namethecontainername. container.p_w_picpaththecontainerp_w_picpath. container.typethecontainertype,eg:dockerorrkt ---------------------- FieldClass:fdlist fdlist.numsforpollevents,thisisacomma-separatedlistoftheFDnumbe rsinthe'fds'argument,returnedasastring. fdlist.namesforpollevents,thisisacomma-separatedlistoftheFDnames inthe'fds'argument,returnedasastring. fdlist.cipsforpollevents,thisisacomma-separatedlistoftheclientI Paddressesinthe'fds'argument,returnedasastring. fdlist.sipsforpollevents,thisisacomma-separatedlistoftheserverI Paddressesinthe'fds'argument,returnedasastring. fdlist.cportsforTCP/UDPFDs,forpollevents,thisisacomma-separatedlis toftheclientTCP/UDPportsinthe'fds'argument,returneda sastring. fdlist.sportsforpollevents,thisisacomma-separatedlistoftheserverT CP/UDPportsinthe'fds'argument,returnedasastring. ---------------------- FieldClass:k8s k8s.pod.nameKubernetespodname. k8s.pod.idKubernetespodid. k8s.pod.labelKubernetespodlabel.E.g.'k8s.pod.label.foo'. k8s.pod.labelsKubernetespodcomma-separatedkey/valuelabels.E.g.'foo1:bar 1,foo2:bar2'. k8s.rc.nameKubernetesreplicationcontrollername. k8s.rc.idKubernetesreplicationcontrollerid. k8s.rc.labelKubernetesreplicationcontrollerlabel.E.g.'k8s.rc.label.foo '. k8s.rc.labelsKubernetesreplicationcontrollercomma-separatedkey/valuelab els.E.g.'foo1:bar1,foo2:bar2'. k8s.svc.nameKubernetesservicename(canreturnmorethanonevalue,concat enated). k8s.svc.idKubernetesserviceid(canreturnmorethanonevalue,concaten ated). ---------------------- FieldClass:mesos mesos.task.nameMesostaskname. mesos.task.idMesostaskid. mesos.task.label Mesostasklabel.E.g.'mesos.task.label.foo'. mesos.task.labels Mesostaskcomma-separatedkey/valuelabels.E.g.'foo1:bar1,fo o2:bar2'. mesos.framework.name Mesosframeworkname. mesos.framework.id Mesosframeworkid. marathon.app.name Marathonappname. marathon.app.idMarathonappid. marathon.app.label Marathonapplabel.E.g.'marathon.app.label.foo'. ---------------------- FieldClass:span span.idtracerID.Thisisauniqueidentifierthatisusedtomatchth eenterandexittracereventsforthisspan.Itcanalsobeus edtomatchdifferentspansbelongingtoatrace. span.timetimeofthespanentertracerasatimestringthatincludesth enanosecondpart. span.ntagsnumberoftagsthatthisspanhas. span.nargsnumberofargumentsthatthisspanhas. span.tagsdot-separatedlistofthespan'stags. span.tagoneofthespan'stags,specifiedby0-basedoffset,e.g.'span .tag[1]'.Youcanuseanegativeoffsettopickelementsfromt heendofthetaglist.Forexample,'span.tag[-1]'returnsthe lasttag. ---------------------- FieldClass:evt evtin.span.id(FILTERONLY)theIDofthetracespancontainingtheevent. evtin.span.ntags (FILTERONLY)thenumberoftagsofthetracespancontainingt heevent. evtin.span.nargs (FILTERONLY)thenumberofargumentsofthetracespancontain ingtheevent. evtin.span.tags(FILTERONLY)thecomma-separatedlistoftagsofthetracespa ncontainingtheevent. evtin.span.tag(FILTERONLY)oneofthetagsofthetracespancontainingthe event,specifiedbyoffset.E.g.'evtin.span.tag[1]'.Youcanu seanegativeoffsettopickelementsfromtheendofthetagl ist.Forexample,'evtin.span.tag[-1]'returnsthelasttag. 如果不想要sysdig默认的输出格式,也可以自己定制,类似于top的定制。变量名必须用%开头。 #sysdig-rsysdigdump.sap-p"user:%user.namedir:%evt.arg.path"evt.type=chdir user:rootdir:/ user:rootdir:/ 输出一个程序正在被哪个用户使用,被调用的命令参数是怎样的: #sysdig-p"%user.name)%proc.name%proc.args"evt.type=execveandevt.arg.ptid=zsh root)gitconfig--getoh-my-zsh.hide-status root)gitsymbolic-refHEAD root)gitrev-parse--shortHEAD root)ls--color=tty--color=auto-hltr root)gitconfig--getoh-my-zsh.hide-status root)gitsymbolic-refHEAD root)gitrev-parse--shortHEAD 可以我在zsh的命令行上执行了ls 命令, 并且oh-my-zsh在后台悄悄地执行git config 命令,没有sysdig工具你是没法知道oh-my-zsh在没执行一次命令都在后台执行git config的,果断把oh-my-zsh自动更新给禁掉,以后可以每隔一段时间手动去更新oh-my-zsh。 查看哪个进程在/etc下写文件,同样效果lsof也可以实现,只是显示不如sysdig,而且sysdig还可以定制显示内容。 #rootatshankerin~/.oh-my-zshongit:mastero[9:22:59] #sysdig-p"user:%user.nameprocess:%proc.namefile:%fd.name""evt.type=writeandfd.namecontains/etc" user:rootprocess:vimfile:/etc/ansible/.hosts.swp user:rootprocess:vimfile:/etc/ansible/.hosts.swp user:rootprocess:vimfile:/etc/ansible/.hosts.swp ^C# #rootatshankerin~/.oh-my-zshongit:mastero[9:27:32] #lsof-cv/etc COMMANDPIDUSERFDTYPEDEVICESIZE/OFFNODENAME vmstat59rootcwdDIR202,140962/ vmstat59rootrtdDIR202,140962/ vmstat59roottxtunknown/proc/59/exe vim11547rootcwdDIR202,1409616386/root vim11547rootrtdDIR202,140962/ vim11547roottxtREG202,121917361026/usr/bin/vim.basic vim11547rootmemREG202,147712418583/lib/x86_64-linux-gnu/libnss_files-2.19.so vim11547rootmemREG202,147760418575/lib/x86_64-linux-gnu/libnss_nis-2.19.so vim11547rootmemREG202,197296418568/lib/x86_64-linux-gnu/libnsl-2.19.so vim11547rootmemREG202,139824418566/lib/x86_64-linux-gnu/libnss_compat-2.19.so vim11547rootmemREG202,110680418582/lib/x86_64-linux-gnu/libutil-2.19.so vim11547rootmemREG202,1100728396113/lib/x86_64-linux-gnu/libz.so.1.2.8 vim11547rootmemREG202,118624396035/lib/x86_64-linux-gnu/libattr.so.1.1.0 vim11547rootmemREG202,1252032397658/lib/x86_64-linux-gnu/libpcre.so.3.13.1 vim11547rootmemREG202,11840928418580/lib/x86_64-linux-gnu/libc-2.19.so vim11547rootmemREG202,1141574418570/lib/x86_64-linux-gnu/libpthread-2.19.so vim11547rootmemREG202,13480880895/usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0 vim11547rootmemREG202,114664418562/lib/x86_64-linux-gnu/libdl-2.19.so vim11547rootmemREG202,1270808084/usr/lib/x86_64-linux-gnu/libgpm.so.2 vim11547rootmemREG202,131168396033/lib/x86_64-linux-gnu/libacl.so.1.1.0 vim11547rootmemREG202,1134296396097/lib/x86_64-linux-gnu/libselinux.so.1 vim11547rootmemREG202,1167096396105/lib/x86_64-linux-gnu/libtinfo.so.5.9 vim11547rootmemREG202,11071552418560/lib/x86_64-linux-gnu/libm-2.19.so vim11547rootmemREG202,1149120418572/lib/x86_64-linux-gnu/ld-2.19.so vim11547rootmemREG202,116076641578/usr/lib/locale/locale-archive vim11547root0uCHR136,70t010/dev/pts/7 vim11547root1uCHR136,70t010/dev/pts/7 vim11547root2uCHR136,70t010/dev/pts/7 vim11547root4uREG202,112288131619/etc/ansible/.hosts.swp 想要看网络连接,使用文件描述法是ipv4即可: sysdigfd.type=ipv4andevt.type=write 如果使用container的情况下,输出格式需要重新格式化才能友好阅读,根据自己container的类型选择命令参数: Using-pcor-pcontainer,thedefaultformatwillbechangedtoacontainer-friendlyone: %evt.num%evt.outputtime%evt.cpu%container.name(%container.id)%proc.name(%thread.tid:%thread.vtid)%evt.dir%evt.type%evt.info Using-pkor-pkubernetes,thedefaultformatwillbechangedtoakubernetes-friendlyone: %evt.num%evt.outputtime%evt.cpu%k8s.pod.name(%container.id)%proc.name(%thread.tid:%thread.vtid)%evt.dir%evt.type%evt.info Using-pmor-pmesos,thedefaultformatwillbechangedtoamesos-friendlyone: %evt.num%evt.outputtime%evt.cpu%mesos.task.name(%container.id)%proc.name(%thread.tid:%thread.vtid)%evt.dir%evt.type%evt.info 二,Chisels用法简介: 因为sysdig的图标是铲子,这个Chisel字面翻译是凿子,铲子加上凿子可以帮你挖的更深。 用过SystemTap(Dtrace Solaris的叫法)工具的朋友一定熟悉他的stap脚本,这个脚本语言需要单独去学习,使用成本比较高,sysdig呢直接提供了很多chisels共大家使用,免去了自己开发脚本的时间,它是用Lua脚本语言开发的。他俩的功能都是挖掘系统层的调用事件,挖的很深很深...... 引用一下官网的“自吹”: Sysdig’s chisels are little scripts that analyze the sysdig event stream to perform useful actions. If you’ve used system tracing tools like dtrace, you’re probably familiar with running scripts that trace OS events. Usually, with dtrace-like tools you write your scripts using a domain-specific language that gets compiled into bytecode and injected in the kernel. Sysdig uses a different approach: events are efficiently brought to user-level, enriched with context, and then scripts can be applied to them. This brings several benefits: A well known scripting language can be used instead of a custom one. In fact, sysdig’s chisels are Lua scripts. Lua is well known, powerful, stable and extremely efficient. Chisels can leverage the broad collection of Lua libraries. Chisels work well on live systems, but can also be used with capture files for offline analysis. 下面是一个SystemTap的stap脚本,这个工具会单独开一篇文章来介绍,也是史诗级的。 #catnginx.stap globals; globalquit=0; probetimer.profile{ if(pid()==target()){ if(quit){ foreach(iins-){ print_ustack(i); printf("\t%d\n",@count(s[i])); } exit() }else{ s[ubacktrace()]<<<1; } } } probetimer.s(20){ quit=1 } 要使用sysdig的chisels, 用-cl参数来查看,如果想对其中的某一个感兴趣,使用-i来详细查看,sysdig源码在github上,您也可以自己去创造自己的chisel。 #sysdig-cl Category:Application --------------------- httplogHTTPrequestslog httptopTopHTTPrequests memcachelogmemcachedrequestslog Category:CPUUsage ------------------- spectrogramVisualizeOSlatencyinrealtime. subsecoffsetVisualizesubsecondoffsetexecutiontime. topcontainers_cpu TopcontainersbyCPUusage topprocs_cpuTopprocessesbyCPUusage Category:Errors ---------------- topcontainers_error Topcontainersbynumberoferrors topfiles_errorsTopfilesbynumberoferrors topprocs_errorstopprocessesbynumberoferrors Category:I/O ------------- echo_fdsPrintthedatareadandwrittenbyprocesses. ..... #rootatshankerin~[1:52:57] #sysdig-iecho_fds Category:I/O ------------- echo_fdsPrintthedatareadandwrittenbyprocesses. PrintthedatareadandwrittenforanyFD.Combinethisscriptwithafiltert orestrictwhatitshows.Thischiseliscompatiblewithcontainersusingthes ysdig-pcor-pcontainerargument,otherwisenocontainerinformationwillbes hown.(Bluerepresents[Write],andRedrepresents[Read]foralldataexcept whenthe-pcor-pcontainerargumentisused.Ifusedthecontainer.nameandco ntainer.idwillberepresentedas:Green[host],andCyan[container])Containe rinformationwillcontain'[]'aroundcontainer.nameandcontainer.id. Args: [string]disable_color-Setto'disable_colors'ifyouwantto disablecoloroutput 如果要运行某一个chisel,直接跟-c即可,比如查看top process by CPU, Network I/O, File I/O: sysdig-ctopprocs_cpu{topprocs_file,topprocs_net} BytesProcessPID -------------------------------------------------------------------------------- 488Bsshd18115 如何查询一个特定进程的所有网络流量呢?拿nginx为例,以ASCII字符显示nginx进程的所有网络流量,回显蓝色字体是写,红色字体是read: #rootatshankerin~[2:00:35] #sysdig-A-cecho_fdsproc.name=nginx ------Read73Bfrom127.0.0.1:54811->127.0.0.1:http(nginx) GET/HTTP/1.1 User-Agent:curl/7.35.0 Host:localhost Accept:*/* ------Write504Btoffff880007b07080->ffff880007b05640/var/run/php5-fpm.sock(nginx) QUERY_STRINGREQUEST_METHODGETCONTENT_TYPECONTENT_LENGTHSCRIPT_FILENAME/var/www/html/index.php SCRIPT_NAME/index.phpREQUEST_URI/ DOCUMENT_URI/index.php DOCUMENT_ROOT/var/www/htmlSERVER_PROTOCOLHTTP/1.1GATEWAY_INTERFACECGI/1.1SERVER_SOFTWAREnginx/1.4.6REMOTE_ADDR127.0.0.1REMOTE_PORT54811SERVER_ADDR127.0.0.1SERVER_PORT80SERVER_NAMEshanker.heyoa.comREDIRECT_STATUS200HTTP_USER_AGENTcurl/7.35.0HTTP_HOSTlocalhostHTTP_ACCEPT*/* ------Read4.00KBfromffff880007b07080->ffff880007b05640/var/run/php5-fpm.sock(nginx) X-Powered-By:PHP/5.5.9-1ubuntu4.16 Content-Type:text/html;charset=UTF-8 如果把proc.name=nginx换成fd.sport=80是一样的效果。 如果想查看sshd进程交互的,server ip 是172.31.23.95的流量: sysdig-A-s65000-n1000-cecho_fdsfd.sip=172.31.23.95andproc.name=sshd 我们在拿官网的topfiles_bytes chisel来学习一下。如果不接任何参数就显示的就是读写磁盘字节数最高的那些进程: $sysdig-ctopfiles_bytes BytesFilename ------------------------------ 23.32KB/proc/net/unix 9.11KB/usr/share/icons/hicolor/16x16/actions/terminator_receive_off.png 5.64KB/etc/localtime 4.92KB/proc/interrupts 4.38KB/dev/input/event2 4.37KB/etc/wgetrc 2.88KB/proc/stat 2.39KB/usr/share/locale/locale.alias 1.85KB/proc/18263/status 如果不想看访问/dev的进程,可以这样: sysdig-ctopfiles_bytes"notfd.namecontains/dev" 如果只想看/root目录下读写比较高的进程,可以这样: $sysdig-ctopfiles_bytes"fd.namecontains/root" BytesFilename ------------------------------ 1.29KB/root/agent/build/debug/test/index.html.93 1.10KB/root/.dropbox/PENDING_aWX7WU 1.10KB/root/.dropbox/UPDATED_UsxrsX 16B/root/.dropbox/filecache.dbx``` 如果想看某个进程对文件的读写,还可以这样: $sysdig-ctopfiles_bytes"proc.name=vi" BytesFilename ------------------------------ 4.00KB/root/agent/build/debug/test/.lo.txt.swp 3.36KB/usr/share/terminfo/x/xterm-256color 2.18KB/etc/passwd 1.98KB/root/agent/build/debug/test/lo.txt 1.92KB/etc/virc 1.66KB/etc/nsswitch.conf 832B/lib64/libpcre.so.1 832B/lib64/libc.so.6 832B/lib64/libnss_files.so.2 或者针对某个用户的: $sysdig-ctopfiles_bytes"user.name=loris" BytesFilename ------------------------------ 3.31KB/etc/nsswitch.conf 2.18KB/etc/passwd 1.62KB/lib64/libselinux.so.1 1.62KB/lib64/libc.so.6 1.62KB/lib64/libpcre.so.1 1.62KB/lib64/libdl.so.2 1.62KB/lib64/libnss_files.so.2 898B/etc/group 54B/proc/self/task/30414/attr/current 三,csysdig简介 csysdig的用法就有点类似htop了,是sysdig交互式的用户界面,在熟悉了sysdig的用法的基础上,用csysdig就轻车熟路了,在这里就不详细介绍了,大家可以参考官方文档http://www.sysdig.org/wiki/csysdig-overview/ https://github.com/draios/sysdig/blob/dev/userspace/sysdig/man/csysdig.md 和youtube上的视频介绍: https://www.youtube.com/watch?v=UJ4wVrbP-Q8 最后总结一下,sysdig真的是一款非常强大的系统分析工具,本文只是抛砖引玉,希望大家多多挖掘,分享更深层的东西来分析服务器的瓶颈和故障。 参考连接: http://www.sysdig.org/wiki/sysdig-user-guide/ http://www.sysdig.org/wiki/chisels-user-guide/ http://bencane.com/2014/04/18/using-sysdig-to-troubleshoot-like-a-boss/ http://xmodulo.com/monitor-troubleshoot-linux-server-sysdig.html