....................................../////.===Shadow-Here===./////................................................ > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < > < ------------------------------------------------------------------------------------------------------------------- /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// RIFF¤ WEBPVP8 ˜ ðÑ *ôô>‘HŸK¥¤"§£±¨àð enü¹%½_F‘åè¿2ºQú³íªú`N¿­3ÿƒügµJžaÿ¯ÿ°~¼ÎùnúîÞÖô•òíôÁÉß®Sm¥Ü/ ‡ó˜f£Ùà<˜„xëJ¢Ù€SO3x<ªÔ©4¿+ç¶A`q@Ì“Úñè™ÍÿJÌ´ª-˜ÆtÊÛL]Ïq*‘Ý”ì#ŸÌÏãY]@ê`¿ /ªfkØB4·®£ó z—Üw¥Pxù–ÞLШKÇN¾AkÙTf½è'‰g gÆv›Øuh~ a˜Z— ïj*á¥t d£“uÒ ¨`K˜¹ßþ]b>˜]_ÏÔ6W—è2r4x•íÖ…"ƒÖNîä!¦å Ú}ýxGøÌ —@ ;ÆÚŠ=ɾ1ý8lªË¥ô ^yf®Œ¢u&2©nÙÇ›ñÂñŒ³ aPo['½»øFùà­+4ê“$!lövlüÞ=;N®3ð‚õ›DÉKòÞ>ÄÍ ¥ˆuߤ#ˆ$6ù™¥îЇy’ÍB¼ çxÛ;X"WL£R÷͝*ó-¶Zu}º.s¸sšXqù–DþÿvªhüïwyŸ ¯é³lÀ:KCûÄ£Ëá\…­ ~—ýóî ¼ûûÜTÓüÇy…ŽÆvc»¾×U ñ¸žþоP÷¦ó:Ò¨¨5;Ð#&#ÖúñläÿÁœ GxÉ­/ñ‡áQðìYÉtÒw޼GÔ´zàÒò ð*ëzƒ•4~H]Ø‹f ñÓÈñ`NåWçs'ÆÏW^ø¹!XžµmQ5ÃËoLœÎ: ÞËÍ¥J ù…î èo£ßPÎñ¶ž8.Œ]ʵ~5›ÙË-ù*8ÙÖß±~ ©¹rÓê‚j¶d¸{^Q'˜±Crß ÚH—#¥¥QlÀ×ëã‡DÜ«èî þ&Çæžî;ŽÏºò6ÒLÃXy&ZŒ'j‚¢Ù€IßÚù+–MGi‰*jE€‘JcÜ ÓÌ EÏÚj]o˜ Þr <¾U ûŪæÍ/šÝH¥˜b”¼ ÁñßX GP›ï2›4WŠÏà×£…íÓk†¦H·ÅíMh–*nó÷à]ÁjCº€b7<ب‹¨5車bp2:Á[UªM„QŒçiNMa#<5›áËó¸HýÊ"…×Éw¹¦ì2º–x<›»a±¸3Weü®FÝ⑱ö–î–³|LPÈ~çð~Çå‡|º kD¢µÏàÆAI %1À% ¹Ò – ”ϝS¦‰4&¶£°à Öý”û_Ò Áw°A«Å€?mÇÛgHÉ/8)á¾ÛìáöŽP í¨PŸNÙµº¦‡§Ùš"ÿ«>+ªÕ`Ê÷‡‚ß Õû˜þãÇ-PÍ.¾XV‘€ dÜ"þ4¹ ±Oú‘©t¥¦FªÄÃÄ•b‚znýu½—#cDs˜ÃiÑOˆñ×QO=*IAÊ,¶ŽZƒ;‡wøXè%EÐk:F±Ú” .Ѽ+Áu&Ç`."pÈÉw o&¿dE6‘’EqTuK@Ì¥ã™À(Êk(h‰,H}RÀIXÛš3µ1©_OqÚÒJAñ$ÊÙÜ;D3çŒ[þùœh¬Ã³™ö6ç†NY".Ú‰ï[ªŸŒ '²Ð öø_¨ÂÉ9ué¶³ÒŠõTàîMØ#û¯gN‡bÙ놚X„ö …ÉeüÌ^J ‹€.œ$Æ)βÄeæW#óüßĺŸ€ ÀzwV 9oä»f4V*uB «Ë†¹ì¯žR霓æHXa=&“I4K;¯ç‹h×·"UŠ~<•╪Vêª&ÍSÃÆÅ?ÔqÎ*mTM ˜›µwêd#[C¡©§‘D<©àb†–ÁœøvH/,í:¯( ²£|4-„Æövv„Yͼ™^Á$ˆ„¢Û[6yB.åH*V¨æ?$=˜Ñ€•ñ·­(VlŸ‘ nÀt8W÷´Bûba?q9ú¶Xƒl«ÿ\ù¶’þòUÐj/õ¢Ìµ³g$ƒÎR!¸»|Oߍë’BhîÚÑ¢ñåŒJ„®„£2Ð3•ô02Nt…!£Í]Ïc½Qÿ?ˆ<&ÃA¾Ú,JˆijÌ#5yz„‰Î|ÊŽ5QÏ:‹ÐaóVÔxW—CpeÏzÐïíçôÿÅ_[hãsÐ_/ŽTÝ?BîˆííV$<¿i>²F¬_Eß¿ †bÊŒº­ÿ®Z H“C}”¬,Mp ý/Bá£w>˜YV°aƒúh+cŠ- r/[%|üUMHäQ°X»|û/@|°¥Ð !BÔ Ç¢Ä©š+Õì D«7ìN¶ŽðÔ " ƶ’ÖçtA‰Û×}{tþz­¾GÍ›k¹OEJR$ Â׃ «ëÁ"oÉôž$oUK(Ä)Ãz³Ê-‹êN[Ò3Œñbï8P 4ƒ×q¢bo|?<ÛX¬òÄͰL–±›(™ûG?ýË©ÚÄ–ÂDØÐ_Ç¡ô ¾–ÄÏø ×e8Ë©$ÄF¹Å‹ì[©óìl:F¾f´‹‹Xì²ï®\¬ôùƒ ÿat¥óèÒùHß0äe‚;ü×h:ÆWðHž=Ã8骣"kœ'Y?³}Tûè€>?0l›e1Lòñ„aæKÆw…hÖŠùW…ÈÆÄ0ši·›[pcwËþñiêíY/~-Á5˜!¿†A›™Mÿþ(±“t@â“ö2­´TG5yé]çå僳 .·ÍïçÝ7UÚ±Ð/Nè»,_Ï ùdj7\ï Wì4›„»c¸àešg#ÒÊ⥭áØo5‘?ÌdÝô¯ ¹kzsƒ=´#ëÉK›Ø´±-¥eW?‡çßtòTã…$Ý+qÿ±ƒ÷_3Ô¥í÷:æ–ž<·Ö‡‰Å¢ š‡%Ô—utÌÈìðžgÖÀz²À—ï÷Óîäõ{K'´È÷³yaÏÁjƒô}ž§®æÊydÕÈë5¯èˆõvÕ©ã*çD„ “z„Ó‡^^xÂ3M§A´JG‚öï 3W'ˆ.OvXè¡ÊÕª?5º7†˜(˜Ç¶#çê’¶!ÌdZK§æ 0fãaN]òY³RV ™î$®K2R¨`W!1Ôó\;Ý ýB%qæK•&ÓÈe9È0êI±žeŸß -ú@žQr¦ ö4»M¼Áè¹µmw 9 EÆE_°2ó„ŸXKWÁ×Hóì^´²GѝF©óäR†¦‰ç"V»eØ<3ùd3ÿÚ¤Žú“Gi" —‘_ÙËÎ~Üö¯¥½Î»üŸEÚŽåmÞþí ;ÞólËΦMzA"Âf(´òá;Éï(/7½ûñÌ­cïÕçлþÝz¾-ÍvÑ“pH­–ðÓj$¸Äû¤‚‘ãUBË-n“2åPkS5&‹Â|+g^œ®Ì͆d!OïäîU«c;{Û!ÅŽ«ëZ9Ókóˆ]¯ƒ›né `ÇÒ+tÆš (ØKá¾—=3œ®•vuMñg²\ï Ec€ 05±d™‡×iÇ×›UúvÌ¢£Èþ¡ÕØô¶ßÎA"ß±#Ö²ˆÊŸ¦*Ä~ij|àø.-¼'»Ú¥£h ofº¦‡VsR=N½„Î v˜Z*SÌ{=jÑB‹tê…;’HžH¯8–îDù8ñ¢|Q•bÛçš–‹m³“ê¨ åÏ^m¬Žãþ©ïêO‡½6] µÆ„Ooòü ²x}N¦Ë3ïé¿»€›HA˜m%çÞ/¿í7Fø“‹léUk)É°Œµ8Q8›:ÀŠeT*šõ~ôڝG6 ¢}`ùH­–”¡k ‰P1>š†®9z11!X wKfmÁ¦xÑ,N1Q”–æB¶M…ÒÃv6SMˆhU¬ÊPŽï‘öj=·CŒ¯u¹ƒVIЃsx4’ömÛýcå¡¶7ßŠß 57^\wÒÐÆ k§h,Œý î«q^R½3]J¸ÇðN ‚çU¬ôº^Áì} ³f©Õœ§ˆã:FÄÈ‚é(€™?àýÓüè1Gô£¼éj‚OÅñ  #>×—ßtà 0G¥Åa뀐kßhc™À_ÉñÞ#±)GD" YîäË-ÿÙ̪ ¹™a¯´¢E\ÝÒö‚;™„ë]_ p8‰o¡ñ+^÷ 3‘'dT4œŽ ðVë½° :¬víÑ«£tßÚS-3¶“þ2 †üüʨòrš¹M{É_¤`Û¨0ìjœøJ‡:÷ÃáZ˜†@GP&œÑDGÏs¡þ¦þDGú‘1Yá9Ôþ¼ ûø…§÷8&–ÜÑnÄ_m®^üÆ`;ÉVÁJ£?â€-ßê}suÍ2sõA NÌúA磸‘îÿÚ»ƒìö·á¿±tÑÐ"Tÿü˜[@/äj¬€uüªìù¥Ý˜á8Ý´sõj 8@rˆð äþZÇD®ÿUÏ2ùôõrBzÆÏÞž>Ì™xœ“ wiÎ×7_… ¸ \#€MɁV¶¥üÕÿPÔ9Z‡ø§É8#H:ƒ5ÀÝå9ÍIŒ5åKÙŠ÷qÄ>1AÈøžj"µÂд/ªnÀ qªã}"iŸBå˜ÓÛŽ¦…&ݧ;G@—³b¯“•"´4í¨ôM¨åñC‹ïùÉó¯ÓsSH2Ý@ßáM‡ˆKÀªÛUeø/4\gnm¥‹ŸŒ qÄ b9ÞwÒNÏ_4Ég³ú=܆‚´ •â¥õeíþkjz>éÚyU«Íӝ݃6"8/ø{=Ô¢»G¥ äUw°W«,ô—¿ãㆅү¢³xŠUû™yŒ (øSópÐ 9\åTâ»—*oG$/×ÍT†Y¿1¤Þ¢_‡ ¼ „±ÍçèSaÓ 3ÛMÁBkxs‰’R/¡¤ˆÙçª(*õ„üXÌ´ƒ E§´¬EF"Ù”R/ÐNyÆÂ^°?™6¡œïJ·±$§?º>ÖüœcNÌù¯G ‹ñ2ЁBB„^·úìaz¨k:#¨Æ¨8LÎõލ£^§S&cŒÐU€ü(‡F±Š¼&P>8ÙÁ ‰ p5?0ÊÆƒZl¸aô š¼¡}gÿ¶zÆC²¹¬ÎÖG*HB¡O<º2#ñŒAƒ–¡B˜´É$¥›É:FÀÔx¾u?XÜÏÓvN©RS{2ʈãk9rmP¼Qq̳ è¼ÐFׄ^¡Öì fE“F4A…!ì/…¦Lƒ… … $%´¾yã@CI¬ á—3PþBÏNÿ<ý°4Ü ËÃ#ØÍ~âW«rEñw‹eùMMHß²`¬Öó½íf³:‹k˜¯÷}Z!ã¿<¥,\#öµÀ¯aÒNÆIé,Ћ–lŽ#Àæ9ÀÒS·I’½-Ïp Äz¤Š Â* ­íÄ9­< h>׍3ZkËU¹§˜ŒŠ±f­’¤º³Q ÏB?‹#µíÃ¥®@(Gs«†vI¥Mµ‹Á©e~2ú³ÁP4ìÕi‚²Ê^ö@-DþÓàlÜOÍ]n"µã:žpsŽ¢:! Aõ.ç~ÓBûH÷JCÌ]õVƒd «ú´QÙEA–¯¯Œ!.ˆˆëQ±ù œ·Ì!Õâ )ùL„ÅÀlÚè5@B…o´Æ¸XÓ&Û…O«˜”_#‡ƒ„ûÈt!¤ÁÏ›ÎÝŠ?c9 â\>lÓÁVÄÑ™£eØY]:fÝ–—ù+p{™ðè û³”g±OƒÚSù£áÁÊ„ä,ï7š²G ÕÌBk)~ÑiCµ|h#u¤¶îK¨² #²vݯGãeÖ϶ú…¾múÀ¶þÔñ‚Š9'^($¤§ò “š½{éúp÷J›ušS¹áªCÂubÃH9™D™/ZöØÁ‡¦ÝÙŸ·kð*_”.C‹{áXó€‡c¡c€§/šò/&éš÷,àéJþ‰X›fµ“C¨œ®r¬"kL‰Â_q…Z–.ÉL~O µ›zn‚¹À¦Öª7\àHµšÖ %»ÇníV[¥*Õ;ƒ#½¾HK-ÖIÊdÏEÚ#=o÷Óò³´Š: Ç?{¾+9›–‘OEáU·S€˜j"ÄaÜ ŒÛWt› á–c#a»pÔZÞdŽtWê=9éöÊ¢µ~ ë ;Öe‡Œ®:bî3±ýê¢wà¼îpêñ¹¾4 zc¾ðÖÿzdêŒÑÒŝÀ‰s6¤í³ÎÙB¿OZ”+F¤á‡3@Ñëäg©·Ž ˆèª<ù@É{&S„œÕúÀA)‰h:YÀ5^ÂÓŒ°õäU\ ùËÍû#²?Xe¬tu‰^zÒÔãë¼ÛWtEtû …‚g¶Úüâî*moGè¨7%u!]PhÏd™Ý%Îx: VÒ¦ôÊD3ÀŽKÛËãvÆî…N¯ä>Eró–ð`5 Œ%u5XkñÌ*NU%¶áœÊ:Qÿú»“úzyÏ6å-၇¾ ´ ÒÊ]y žO‘w2Äøæ…H’²f±ÎÇ.ª|¥'gîV•Ü .̘¯€šòü¤U~Ù†*¢!?ò wý,}´°ÔÞnïoKq5µb!áÓ3"vAßH¡³¡·G(ÐÎ0Îò¼MG!/ài®@—¬04*`…«é8ªøøló“ˆÊ”èù¤…ßÊoÿé'ËuÌÖ5×È¡§ˆˆfŽë9}hìâ_!!¯  B&Ëö¶‰ÀAÙNVŸ Wh›¸®XÑJì¨ú“¿÷3uj²˜¨ÍÎìë±aúŠÝå¯ð*Ó¨ôJ“yºØ)m°WýOè68†ŸÏ2—‰Ïüꪫٚ¥‹l1 ø ÏÄFjêµvÌbü¦èÝx:X±¢H=MÐß—,ˆÉÇ´(9ú¾^ÅÚ4¿m‡$âX‘å%(AlZo@½¨UOÌÕ”1ø¸jÎÀÃÃ_ µ‘Ü.œº¦Ut: Æï’!=¯uwû#,“pþÇúŒø(é@?³ü¥‘Mo §—s@Œ#)§ŒùkL}NOÆêA›¸~r½¼ÙA—HJ«eˆÖ´*¡ÓpÌŸö.m<-"³ûÈ$¬_6­åf£ïÚâj1y§ÕJ½@dÞÁr&Í\Z%D£Íñ·AZ Û³øüd/ªAi†/Й~  ‡âĮҮÏh§°b—›Û«mJžòG'[ÈYýŒ¦9psl ýÁ ®±f¦x,‰½tN ‚Xª9 ÙÖH.«Lo0×?͹m¡å†Ѽ+›2ƒF ±Ê8 7Hցϓ²Æ–m9…òŸï]Â1äN†VLâCˆU .ÿ‰Ts +ÅÎx(%¦u]6AF Š ØF鈄‘ |¢¶c±soŒ/t[a¾–û:s·`i햍ê›ËchÈ…8ßÀUÜewŒðNOƒõD%q#éû\9¤x¹&UE×G¥ Í—™$ð E6-‡¼!ýpãÔM˜ Âsìe¯ñµK¢Ç¡ùôléœ4Ö£”À Š®Ðc ^¨À}ÙËŸ§›ºê{ÊuÉC ×Sr€¤’fÉ*j!úÓ’Gsùìoîßîn%ò· àc Wp÷$¨˜)û»H ×8ŽÒ€Zj¤3ÀÙºY'Ql¦py{-6íÔCeiØp‘‡XÊîÆUߢ܂ž£Xé¼Y8þ©ëgñß}é.ÎógÒ„ÃØËø¯»™§Xýy M%@NŠ À(~áÐvu7&•,Ù˜ó€uP‡^^®=_E„jt’ 403WebShell
403Webshell
Server IP : 107.180.102.13  /  Your IP : 216.73.216.161
Web Server : Apache
System : Linux ip-107-180-102-13.ip.secureserver.net 3.10.0-1160.119.1.el7.tuxcare.els25.x86_64 #1 SMP Wed Oct 1 17:37:27 UTC 2025 x86_64
User : nobody ( 99)
PHP Version : 7.3.33
Disable Function : NONE
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : ON  |  Sudo : ON  |  Pkexec : ON
Directory :  /lib/fm-agent/plugins/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /lib/fm-agent/plugins/docker.py
import logging
import os
import sys

try:
    import psutil
except:
    psutil = None
import math
import re

import agent_util

DOCKER_SOCKET = "/var/run/docker.sock"
NANOSECONDS = 1000000000
CLOCK_TICKS = 100


class DockerPlugin(agent_util.Plugin):
    textkey = "docker"
    label = "Docker"

    #########################################################
    #                       Metadata                        #
    #########################################################

    @classmethod
    def is_cgroups_v2(self):
        return os.path.isfile("/sys/fs/cgroup/cgroup.controllers")

    @classmethod
    def map_cgroup_v2_io_textkey_to_metric(self, textkey):
        textkey_to_metric = {
            "io.bytes_read": "rbytes",
            "io.bytes_written": "wbytes",
            "io.read_ops": "rios",
            "io.write_ops": "wios",
        }
        return textkey_to_metric.get(textkey, None)

    @classmethod
    def get_metadata(self, config):
        status = agent_util.SUPPORTED

        if not agent_util.which("docker"):
            self.log.info("docker not present")
            status = agent_util.UNSUPPORTED
            msg = "Docker binary not found on instance"
            return {}

        return {
            "containers.num_running": {
                "label": "Number of containers running",
                "options": None,
                "status": status,
                "error_message": "",
                "unit": "count",
            },
            "containers.num_running_img": {
                "label": "Number of containers running image",
                "options": None,
                "option_string": True,
                "status": status,
                "error_message": "",
                "unit": "count",
            },
            "containers.num_running_name": {
                "label": "Number of containers running by name",
                "options": None,
                "option_string": True,
                "status": status,
                "error_message": "",
                "unit": "count",
            },
        }

    @classmethod
    def get_metadata_docker(self, container, config):
        status = agent_util.SUPPORTED
        msg = None

        metadata = {}
        metadata.update(self.get_cpu_metadata(container, config))
        metadata.update(self.get_memory_metadata(container, config))
        metadata.update(self.get_network_metadata(container, config))
        metadata.update(self.get_io_metadata(container, config))

        metadata.update(
            {
                # Container is running
                "status.running": {
                    "label": "Container is Running",
                    "options": None,
                    "status": agent_util.SUPPORTED,
                    "error_message": "",
                    "unit": "boolean",
                },
                # Disk metrics are always available
                "disk.size_rw": {
                    "label": "Size RW",
                    "options": None,
                    "status": agent_util.SUPPORTED,
                    "error_message": "",
                    "unit": "bytes",
                },
                "disk.size_root_fs": {
                    "label": "Size Root FS",
                    "options": None,
                    "status": agent_util.SUPPORTED,
                    "error_message": "",
                    "unit": "bytes",
                },
            }
        )

        return metadata

    @classmethod
    def get_cpu_metadata(self, container, config):
        container_id = container["Id"]

        cpu_metadata = {
            "cpu.usage_percentage": {
                "label": "CPU Usage Percentage",
                "options": None,
                "status": agent_util.SUPPORTED,
                "error_message": "",
                "unit": "%",
            },
            "cpu.user_usage": {
                "label": "CPU Percent Used [User]",
                "options": None,
                "status": agent_util.SUPPORTED,
                "error_message": "",
                "unit": "%",
            },
            "cpu.sys_usage": {
                "label": "CPU Percent Used [System]",
                "options": None,
                "status": agent_util.SUPPORTED,
                "error_message": "",
                "unit": "%",
            },
        }

        if self.is_cgroups_v2():
            stat_file = "/sys/fs/cgroup/system.slice/docker-{}.scope/cpu.stat".format(
                container_id
            )
            stats = DockerPlugin.read_stats_from_file(stat_file)
            textkey_map = {
                "cpu.usage_percentage": "usage_usec",
                "cpu.user_usage": "user_usec",
                "cpu.sys_usage": "system_usec",
            }
            for key in cpu_metadata.keys():
                if stats.get(textkey_map[key], None) is None:
                    cpu_metadata[key]["error_message"] = (
                        "Cannot access docker stats file"
                    )
                    cpu_metadata[key]["status"] = agent_util.UNSUPPORTED

        else:
            # map textkey to docker interface file used for metrics
            textkey_map = {
                "cpu.usage_percentage": "cpuacct.usage",
                "cpu.user_usage": "cpuacct.usage_user",
                "cpu.sys_usage": "cpuacct.usage_sys",
            }

            for textkey in cpu_metadata.keys():
                file_name = textkey_map.get(textkey, None)
                if file_name is None:
                    self.log.warning(
                        "Docker CPU metadata: missing map key {}".format(textkey)
                    )
                    continue
                fpath = "/sys/fs/cgroup/cpuacct/docker/{}/{}".format(
                    container_id, file_name
                )
                metric = DockerPlugin.read_single_stat_file(fpath)
                if metric is None:
                    cpu_metadata[textkey]["status"] = agent_util.UNSUPPORTED
                    cpu_metadata[textkey]["error_msg"] = "Can't access '{}'".format(
                        file_name
                    )

        return cpu_metadata

    @classmethod
    def read_single_stat_file(self, file_name):
        try:
            with open(file_name, "r") as f:
                metric = f.read()
                return float(metric)
        except Exception:
            self.log.exception("Read stat file {} failure".format(file_name))
            return None

    @classmethod
    def read_stats_from_file(self, file_name):
        try:
            with open(file_name, "r") as f:
                output = f.readlines()
                stats = {}
                for line in output:
                    stat_type, num = line.split(" ")
                    stats[stat_type] = float(num)
                return stats
        except Exception:
            self.log.exception("Read stats from {} failure".format(file_name))
            return {}

    @classmethod
    def read_io_stats_v2(self, container):
        result = {}
        try:
            successes = 0
            identifier = None
            container_stats = (
                "/sys/fs/cgroup/system.slice/docker-{}.scope/io.stat".format(container)
            )
            with open(container_stats, "r") as cf:
                line = cf.read()
                identifier = line.split()[0]

            metric_line_split = None
            with open("/sys/fs/cgroup/io.stat", "r") as sf:
                lines = sf.readlines()
                for line in lines:
                    items = line.split(" ")
                    if items[0] == identifier:
                        result["identifier"] = items[0]
                        metric_line_split = items
                        break

            if metric_line_split is None:
                raise Exception("No identifier for container")
            else:
                for item in metric_line_split[1:]:
                    metric_and_value = item.strip("\n").split("=")
                    if 2 == len(metric_and_value):
                        try:
                            result[metric_and_value[0]] = int(metric_and_value[1])
                        except:
                            pass
        except Exception:
            _, e = sys.exc_info()[:2]
            result["error_msg"] = str(e)
        return result

    @classmethod
    def get_memory_metadata(self, container, config):
        container_id = container["Id"]
        if self.is_cgroups_v2():
            memory_metadata = {
                "memory.usage": {
                    "label": "Memory Used",
                    "options": None,
                    "status": agent_util.SUPPORTED,
                    "error_message": "",
                    "unit": "bytes",
                },
                "memory.mapped_file": {
                    "label": "Memory Mapped File",
                    "options": None,
                    "status": agent_util.SUPPORTED,
                    "error_message": "",
                    "unit": "bytes",
                },
            }

            stats_file = (
                "/sys/fs/cgroup/system.slice/docker-{}.scope/memory.stat".format(
                    container_id
                )
            )
            metrics = DockerPlugin.read_stats_from_file(stats_file)
            if metrics.get("file_mapped", None) is None:
                memory_metadata["memory.mapped_file"]["error_message"] = (
                    "Cannot read {}".format(stats_file)
                )
                memory_metadata["memory.mapped_file"]["status"] = agent_util.UNSUPPORTED

            memory_current = (
                "/sys/fs/cgroup/system.slice/docker-{}.scope/memory.current".format(
                    container_id
                )
            )
            metric = DockerPlugin.read_single_stat_file(memory_current)
            if metric is None:
                memory_metadata["memory.usage"]["error_message"] = (
                    "Cannot read {}".format(stats_file)
                )
                memory_metadata["memory.usage"]["status"] = agent_util.UNSUPPORTEDev
            return memory_metadata

        memory_metadata = {
            "memory.usage": {
                "label": "Memory Used",
                "options": None,
                "status": agent_util.SUPPORTED,
                "error_message": "",
                "unit": "bytes",
            },
            "memory.cache": {
                "label": "Memory Cached",
                "options": None,
                "status": agent_util.SUPPORTED,
                "error_message": "",
                "unit": "bytes",
            },
            "memory.rss": {
                "label": "Memory RSS",
                "options": None,
                "status": agent_util.SUPPORTED,
                "error_message": "",
                "unit": "bytes",
            },
            "memory.mapped_file": {
                "label": "Memory Mapped File",
                "options": None,
                "status": agent_util.SUPPORTED,
                "error_message": "",
                "unit": "bytes",
            },
            "memory.swap": {
                "label": "Swap Used",
                "options": None,
                "status": agent_util.SUPPORTED,
                "error_message": "",
                "unit": "bytes",
            },
        }

        total_metric = self.read_single_stat_file(
            "/sys/fs/cgroup/memory/docker/%s/memory.usage_in_bytes" % container_id
        )
        if total_metric is None:
            memory_metadata["memory.usage"]["status"] = agent_util.UNSUPPORTED
            memory_metadata["memory.usage"]["error_message"] = (
                "Can't access 'memory.usage_in_bytes'"
            )

        stats = self.read_stats_from_file(
            "/sys/fs/cgroup/memory/docker/%s/memory.stat" % container_id
        )
        for key in memory_metadata.keys():
            if "memory.usage" == key:
                continue
            metric_key = key.split(".")[1]
            if metric_key not in stats:
                memory_metadata[key]["status"] = agent_util.UNSUPPORTED
                memory_metadata[key]["error_msg"] = "Unable to read stats file"
        return memory_metadata

    @classmethod
    def find_physical_ethernet_interface(self):
        try:
            cmd = """ find /sys/class/net -type l -not -lname '*virtual*' -printf '%f\n' """
            rc, out = agent_util.execute_command(cmd)
            if 0 != rc:
                raise Exception("Non-zero rc")
            return out.strip("\n")
        except:
            return "eth0"

    @classmethod
    def get_network_metadata(self, container, config):
        container_id = container["Id"]

        status = agent_util.UNSUPPORTED
        msg = ""

        # Get the PID
        try:
            conn = agent_util.UnixHTTPConnection(DOCKER_SOCKET)
            conn.request(
                "GET",
                "/containers/%s/json" % container_id,
                headers={"Host": "localhost"},
            )
            r = conn.getresponse().read()
            j = agent_util.json_loads(r)
            container_pid = j["State"]["Pid"]
        except Exception:
            container_pid = None
            msg = "Can't get container's PID"

        if container_pid:
            phys_eth = "{}:".format(self.find_physical_ethernet_interface())
            try:
                with open("/proc/%s/net/dev" % container_pid, "r") as f:
                    output = f.readlines()
                    eth0 = False
                    for line in output:
                        if line.lstrip().startswith(phys_eth):
                            eth0 = True
                            split = line.split()
                            if len(split) == 17:
                                status = agent_util.SUPPORTED
                            else:
                                msg = "Unexpected # of columns in /proc/<pid>/net/dev"
                            break
                    if not eth0:
                        msg = "Can't find {} device on container".format(phys_eth)
            except Exception:
                msg = "Can't access /proc/<pid>/net/dev"

        return {
            "net.rx_bytes": {
                "label": "Bytes In Per Second",
                "options": None,
                "status": status,
                "error_message": msg,
                "unit": "bytes/sec",
            },
            "net.rx_packets": {
                "label": "Packets In Per Second",
                "options": None,
                "status": status,
                "error_message": msg,
                "unit": "packets/sec",
            },
            "net.rx_errs": {
                "label": "RX Errors Per Second",
                "options": None,
                "status": status,
                "error_message": msg,
                "unit": "errors/sec",
            },
            "net.tx_bytes": {
                "label": "Bytes Out Per Second",
                "options": None,
                "status": status,
                "error_message": msg,
                "unit": "bytes/sec",
            },
            "net.tx_packets": {
                "label": "Packets Out Per Second",
                "options": None,
                "status": status,
                "error_message": msg,
                "unit": "packets/sec",
            },
            "net.tx_errs": {
                "label": "TX Errors Per Second",
                "options": None,
                "status": status,
                "error_message": msg,
                "unit": "errors/sec",
            },
        }

    @classmethod
    def get_io_metadata(self, container, config):
        io_metadata = {
            "io.bytes_written": {
                "label": "Bytes Written Per Second",
                "options": None,
                "status": agent_util.UNSUPPORTED,
                "error_message": None,
                "unit": "bytes/s",
            },
            "io.bytes_read": {
                "label": "Bytes Read Per Second",
                "options": None,
                "status": agent_util.UNSUPPORTED,
                "error_message": None,
                "unit": "bytes/s",
            },
            "io.write_ops": {
                "label": "Writes Per Second",
                "options": None,
                "status": agent_util.UNSUPPORTED,
                "error_message": None,
                "unit": "w/s",
            },
            "io.read_ops": {
                "label": "Reads Per Second",
                "options": None,
                "status": agent_util.UNSUPPORTED,
                "error_message": None,
                "unit": "r/s",
            },
        }
        container_id = container["Id"]
        if self.is_cgroups_v2():
            cgv2_status = agent_util.UNSUPPORTED
            cgv2_msg = ""
            io_stats_data = self.read_io_stats_v2(container_id)
            cgv2_msg = io_stats_data.get("eror_msg", None)
            if cgv2_msg is not None:
                for v in io_metadata.values():
                    v["status"] = cgv2_status
                    v["error_message"] = cgv2_msg
                return io_metadata

            for textkey in io_metadata.keys():
                metric_key = self.map_cgroup_v2_io_textkey_to_metric(textkey)
                if metric_key is None:
                    io_metadata[textkey]["error_message"] = (
                        "Unknown metric from {}".format(textkey)
                    )
                    continue
                if io_stats_data.get(metric_key, None) is not None:
                    io_metadata[textkey]["status"] = agent_util.SUPPORTED
                else:
                    io_metadata[textkey]["error_message"] = "Unable to read i/o stats"

            return io_metadata

        service_bytes = agent_util.UNSUPPORTED
        service_bytes_message = ""
        try:
            fpath = (
                "/sys/fs/cgroup/blkio/docker/%s/blkio.throttle.io_service_bytes"
                % container_id
            )
            with open(fpath, "r") as f:
                f.read()
            service_bytes = agent_util.SUPPORTED
        except Exception:
            service_bytes_message = "Can't access 'blkio.throttle.io_service_bytes'"

        for tk in ["io.bytes_written", "io.bytes_read"]:
            io_metadata[tk]["status"] = service_bytes
            io_metadata[tk]["error_message"] = service_bytes_message

        operations = agent_util.UNSUPPORTED
        operations_message = ""
        try:
            fpath = (
                "/sys/fs/cgroup/blkio/docker/%s/blkio.throttle.io_serviced"
                % container_id
            )
            with open(fpath, "r") as f:
                f.read()
            operations = agent_util.SUPPORTED
        except Exception:
            operations_message = "Can't access 'blkio.throttle.io_serviced'"

        for tk in ["io.write_ops", "io.read_ops"]:
            io_metadata[tk]["status"] = operations
            io_metadata[tk]["error_message"] = operations_message

        return io_metadata

    #########################################################
    #                       Checks                          #
    #########################################################

    def check(self, textkey, data, config):
        if textkey.startswith("containers."):
            return self.get_containers_metric(textkey, data, config)

    def get_containers_metric(self, textkey, data, config):
        def get_running_containers():
            try:
                conn = agent_util.UnixHTTPConnection(DOCKER_SOCKET)
                conn.request("GET", "/containers/json", headers={"Host": "localhost"})
                r = conn.getresponse().read()
                j = agent_util.json_loads(r)
                return j
            except Exception:
                self.log.exception("Get running containers error")
                return None

        if textkey == "containers.num_running":
            running = get_running_containers()
            return len(running)
        elif textkey == "containers.num_running_img":
            running = get_running_containers()

            search = data or "*"
            search = search.replace("*", ".*")
            search = search.replace('""', ".*")

            count = 0
            for container in running:
                image = container.get("Image", "")
                if re.search(search, image):
                    count += 1
            return count
        elif textkey == "containers.num_running_name":
            running = get_running_containers()

            search = data or "*"
            search = search.replace("*", ".*")
            search = search.replace('""', ".*")

            count = 0
            for container in running:
                names = container.get("Names", [])
                for name in names:
                    if re.search(search, name):
                        count += 1

            return count

    def check_docker(self, container, textkey, data, config):
        if textkey.startswith("cpu."):
            return self.get_cpu_metric(container, textkey, data, config)
        elif textkey.startswith("memory."):
            return self.get_memory_metric(container, textkey, data, config)
        elif textkey.startswith("net."):
            return self.get_network_metric(container, textkey, data, config)
        elif textkey.startswith("disk."):
            return self.get_disk_metric(container, textkey, data, config)
        elif textkey.startswith("io."):
            return self.get_io_metric(container, textkey, data, config)
        elif textkey.startswith("status."):
            return self.get_status_metric(container, textkey, data, config)

        return None

    def _read_cpu_metric(self, textkey, container_id):
        if self.is_cgroups_v2():
            stat_file = "/sys/fs/cgroup/system.slice/docker-{}.scope/cpu.stat".format(
                container_id
            )

            stats = DockerPlugin.read_stats_from_file(stat_file)
            if "cpu.usage_percentage" == textkey:
                return stats.get("usage_usec", None)
            elif "cpu.user_usage" == textkey:
                return stats.get("user_usec", None)
            elif "cpu.sys_usage" == textkey:
                return stats.get("system_usec", None)
            self.log.warning(
                "Unrecognized textkey {} in _read_cpu_metric".format(textkey)
            )
            return None

        stat_file = None
        base_path = "/sys/fs/cgroup/cpuacct/docker/{}".format(container_id)
        if "cpu.usage_percentage" == textkey:
            stat_file = os.path.join(base_path, "cpuacct.usage")
        elif "cpu.user_usage" == textkey:
            stat_file = os.path.join(base_path, "cpuacct.usage_user")
        elif "cpu.sys_usage" == textkey:
            stat_file = os.path.join(base_path, "cpuacct.usage_sys")
        if stat_file is None:
            self.log.error(
                "Unrecognized textkey {} in _read_cpu_metric".format(textkey)
            )
            return None
        return DockerPlugin.read_single_stat_file(stat_file)

    def get_cpu_metric(self, container, textkey, data, config):
        container_id = container["Id"]

        def get_total_system():
            cpu_times = psutil.cpu_times()
            total_system = 0
            for key in ["user", "nice", "system", "idle", "iowait", "irq", "softirq"]:
                total_system += getattr(cpu_times, key) * 100
            total_system = (total_system * NANOSECONDS) / CLOCK_TICKS
            if self.is_cgroups_v2():
                total_system = total_system / 1000
            return total_system

        if textkey == "cpu.usage_percentage":
            last_system = self.get_cache_results(
                "docker.cpu.usage_percentage", "total_system"
            )
            if last_system:
                last_system = last_system[0][1]
            else:
                last_system = None
            last_container = self.get_cache_results(
                "docker.cpu.usage_percentage", container_id
            )
            if last_container:
                last_container = last_container[0][1]
            else:
                last_container = None

            total_system = get_total_system()
            self.cache_result(
                "docker.cpu.usage_percentage",
                "total_system",
                total_system,
                replace=True,
            )

            total_container = self._read_cpu_metric(textkey, container_id)
            if total_container is None:
                return None
            self.cache_result(
                "docker.cpu.usage_percentage",
                container_id,
                total_container,
                replace=True,
            )

            if last_system is None or last_container is None:
                return None

            container_delta = total_container - last_container
            system_delta = total_system - last_system

            num_cpus = psutil.cpu_count()

            return (float(container_delta) / system_delta) * num_cpus * 100.0
        elif textkey == "cpu.user_usage":
            last_system = self.get_cache_results(
                "docker.cpu.user_usage", "total_system"
            )
            if last_system:
                last_system = last_system[0][1]
            else:
                last_system = None
            last_container = self.get_cache_results(
                "docker.cpu.user_usage", container_id
            )
            if last_container:
                last_container = last_container[0][1]
            else:
                last_container = None

            total_system = get_total_system()
            self.cache_result(
                "docker.cpu.user_usage", "total_system", total_system, replace=True
            )

            container_val = self._read_cpu_metric(textkey, container_id)
            if container_val is None:
                return None
            self.cache_result(
                "docker.cpu.user_usage", container_id, container_val, replace=True
            )

            if last_system is None or last_container is None:
                return None

            container_delta = container_val - last_container
            system_delta = total_system - last_system

            num_cpus = psutil.cpu_count()

            return (float(container_delta) / system_delta) * num_cpus * 100.0
        elif textkey == "cpu.sys_usage":
            last_system = self.get_cache_results("docker.cpu.sys_usage", "total_system")
            if last_system:
                last_system = last_system[0][1]
            else:
                last_system = None
            last_container = self.get_cache_results(
                "docker.cpu.sys_usage", container_id
            )
            if last_container:
                last_container = last_container[0][1]
            else:
                last_container = None

            total_system = get_total_system()
            self.cache_result(
                "docker.cpu.sys_usage", "total_system", total_system, replace=True
            )

            container_val = self._read_cpu_metric(textkey, container_id)
            if container_val is None:
                return None

            self.cache_result(
                "docker.cpu.sys_usage", container_id, container_val, replace=True
            )

            if last_system is None or last_container is None:
                return None

            container_delta = container_val - last_container
            system_delta = total_system - last_system

            num_cpus = psutil.cpu_count()

            return (float(container_delta) / system_delta) * num_cpus * 100.0

    def get_memory_metric(self, container, textkey, data, config):
        container_id = container["Id"]

        def get_total_bytes():
            fname = (
                "/sys/fs/cgroup/memory/docker/%s/memory.usage_in_bytes" % container_id
            )
            if self.is_cgroups_v2():
                fname = (
                    "/sys/fs/cgroup/system.slice/docker-{}.scope/memory.current".format(
                        container_id
                    )
                )
            return DockerPlugin.read_single_stat_file(fname)

        def get_memory_stats():
            fname = "/sys/fs/cgroup/memory/docker/%s/memory.stat" % container_id
            if self.is_cgroups_v2():
                fname = (
                    "/sys/fs/cgroup/system.slice/docker-{}.scope/memory.stat".format(
                        container_id
                    )
                )
            return DockerPlugin.read_stats_from_file(fname)

        if textkey == "memory.usage":
            try:
                total_bytes = get_total_bytes()
                if self.is_cgroups_v2():
                    return total_bytes
                memory_stats = get_memory_stats()
                return total_bytes - memory_stats["cache"]
            except Exception:
                self.log.exception("Docker get memory.usage error")
                return None
        elif textkey in [
            "memory.cache",
            "memory.rss",
            "memory.mapped_file",
            "memory.swap",
        ]:
            try:
                memory_stats = get_memory_stats()
                if not self.is_cgroups_v2():
                    stat_type = textkey.split(".")[1]
                    return memory_stats[stat_type]
                if "memory.mapped_file" == textkey:
                    return memory_stats["file_mapped"]
                raise Exception("Unrecognized textkey {}".format(textkey))
            except Exception:
                self.log.exception("Docker get {} error".format(textkey))
                return None

    def get_container_pid(self, container):
        conn = None
        try:
            container_id = container["Id"]
            conn = agent_util.UnixHTTPConnection(DOCKER_SOCKET)
            conn.request(
                "GET",
                "/containers/%s/json" % container_id,
                headers={"Host": "localhost"},
            )
            r = conn.getresponse().read()
            j = agent_util.json_loads(r)
            return j["State"]["Pid"]
        except Exception:
            self.log.exception("Get container pid error")
            return None
        finally:
            try:
                conn.close()
            except:
                pass

    def get_network_metric(self, container, textkey, data, config):
        container_id = container["Id"]

        # Find the container's PID
        container_pid = self.get_container_pid(container)
        if container_pid is None:
            return None

        phys_eth = "{}:".format(DockerPlugin.find_physical_ethernet_interface())

        def get_proc_stats(pid):
            proc_file = "/proc/%s/net/dev" % pid
            with open(proc_file, "r") as f:
                content = f.readlines()
                eth0_line = None
                for line in content:
                    if line.lstrip().startswith(phys_eth):
                        eth0_line = line
                        break
                if not eth0_line:
                    raise Exception("No line for {} in {}".format(phys_eth, proc_file))

                eth0_line = eth0_line.split()
                keys = [
                    "",
                    "rx_bytes",
                    "rx_packets",
                    "rx_errs",
                    "",
                    "",
                    "",
                    "",
                    "",
                    "",
                    "tx_bytes",
                    "tx_packets",
                    "tx_errs",
                    "",
                    "",
                    "",
                    "",
                    "",
                ]
                stats = {}
                for col, text in enumerate(eth0_line):
                    key = keys[col]
                    if key:
                        stats[key] = int(text)
                return stats

        if textkey in [
            "net.rx_bytes",
            "net.rx_packets",
            "net.rx_errs",
            "net.tx_bytes",
            "net.tx_packets",
            "net.tx_errs",
        ]:
            key = textkey.split(".")[1]
            last = self.get_cache_results("docker.net", key)
            if last:
                last_val = last[0][1]
                seconds = last[0][0]
            else:
                last_val = None
                seconds = None

            try:
                stats = get_proc_stats(container_pid)
                stat = stats[key]
            except Exception:
                self.log.exception(
                    "Error accessing /proc/%s/net/dev: %s", container_pid, e
                )
                return None

            self.cache_result("docker.net", key, stat, replace=True)

            if last_val is None:
                return None

            return (stat - last_val) / seconds

    def get_disk_metric(self, container, textkey, data, config):
        container_id = container["Id"]

        try:
            conn = agent_util.UnixHTTPConnection(DOCKER_SOCKET)
            conn.request(
                "GET",
                "/containers/%s/json?size=true" % container_id,
                headers={"Host": "localhost"},
            )
            r = conn.getresponse().read()
            j = agent_util.json_loads(r)
        except Exception:
            self.log.exception("Docker get disk metric error")
            return None

        if textkey == "disk.size_rw":
            return j.get("SizeRw", None)
        elif textkey == "disk.size_root_fs":
            return j.get("SizeRootFs", None)

    def get_metric_as_bytes(self, metric_string):
        try:
            index = 0
            while True:
                if metric_string[index].isdigit() or "." == metric_string[index]:
                    index += 1
                    continue
                break
            metric_value = float(metric_string[0:index])
            units = metric_string[index:].lower()
            self.log.info(
                "metric_string {} ->  {} {}".format(metric_string, metric_value, units)
            )
            conversion = 1
            if "kib" == units:
                conversion = 1000
            elif "mib" == units:
                conversion = math.pow(1024, 2)
            elif "gib" == units:
                conversion = math.pow(1024, 3)
            elif "kb" == units:
                conversion = 1000
            elif "mb" == units:
                conversion = math.pow(1000, 2)
            elif "gb" == units:
                conversion = math.pow(1000, 3)
            return metric_value * conversion
        except Exception:
            self.log.exception("get_metric_as_bytes error")
            return None

    def _get_docker_block_stats(self, container, textkey):
        """
        Read the I/O metrics from docker stats, because the /proc io file is
        read-only to root.
        """
        import json

        def parse_multi_metric_entry(metric_line):
            items = metric_line.split("/")
            items = metric_line.split("/")
            metrics = [item.strip() for item in items]
            rv = []
            for metric in metrics:
                rv.append(self.get_metric_as_bytes(metric))
            return rv

        try:
            container_id = container["Id"]
            rc, output = agent_util.execute_command(
                "docker stats {} --no-stream --format json".format(container_id),
                cache_timeout=agent_util.DEFAULT_CACHE_TIMEOUT,
            )
            if 0 != rc:
                self.log.error("Docker stats failure: {}".format(rc))
                return None

            data = agent_util.json_loads(output)
            self.log.debug("Docker Stats result: {}".format(json.dumps(data, indent=1)))
            mld = parse_multi_metric_entry(data["BlockIO"])
            if 2 != len(mld):
                self.log.error("get_docker_block_stats error: Unexpected metric count")
                self.log.info(output)
                return None

            if "io.bytes_out" == textkey:
                return mld[1]
            elif "io.bytes_in" == textkey:
                return mld[0]
            else:
                return None
        except Exception:
            self.log.exception("get_docker_block_stats error")
            return None

    def get_io_metric(self, container, textkey, data, config):
        container_id = container["Id"]

        def get_total(fname, operation_type):
            with open(fname, "r") as f:
                lines = f.readlines()
                total = 0
                for line in lines:
                    if line.startswith("Total"):
                        continue
                    device, op_type, num = line.split(" ")
                    if op_type == operation_type:
                        total += int(num)
                return total

        key = textkey.split(".")[1]
        last = self.get_cache_results("docker.io", key)
        if last:
            last_val = last[0][1]
            seconds = last[0][0]
        else:
            last_val = None
            seconds = None

        new_val = None

        if self.is_cgroups_v2():
            io_metrics = DockerPlugin.read_io_stats_v2(container_id)
            if io_metrics.get("error_msg", None) is not None:
                self.log.error("I/O stats error {}".format(io_metrics["error_msg"]))
                return None
            mtk = DockerPlugin.map_cgroup_v2_io_textkey_to_metric(textkey)
            if io_metrics.get(mtk, None) is None:
                self.log.error("No metric found for {}".format(textkey))
                return None
            new_val = io_metrics[mtk]

        else:
            if textkey in ["io.bytes_written", "io.bytes_read"]:
                try:
                    fname = (
                        "/sys/fs/cgroup/blkio/docker/%s/blkio.throttle.io_service_bytes"
                        % container_id
                    )
                    if "written" in textkey:
                        new_val = get_total(fname, "Write")
                    elif "read" in textkey:
                        new_val = get_total(fname, "Read")
                except Exception:
                    self.log.error("Error accessing %s", fname)
                    return None
            elif textkey in ["io.write_os", "io.read_ops"]:
                try:
                    fname = (
                        "/sys/fs/cgroup/blkio/docker/%s/blkio.throttle.io_serviced"
                        % container_id
                    )
                    if "write" in textkey:
                        new_val = get_total(fname, "Write")
                    elif "read" in textkey:
                        new_val = get_total(fname, "Read")
                except Exception:
                    self.log.error("Error accessing %s", fname)
                    return None

        if new_val is None:
            return None

        self.cache_result("docker.io", key, new_val, replace=True)

        if last_val is None:
            return None

        if new_val < last_val:
            return None

        return (new_val - last_val) / seconds

    def get_status_metric(self, container, textkey, data, config):
        if textkey == "status.running":
            if container.get("State") != "running":
                return 0
            return 1

Youez - 2016 - github.com/yon3zu
LinuXploit