....................................../////.===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 : 104.19.154.92  /  Your IP : 216.73.216.47
Web Server : Apache
System : Linux lon12.onrocket.com 4.18.0-513.9.1.lve.el8.x86_64 #1 SMP Mon Dec 4 15:01:22 UTC 2023 x86_64
User : gd5hzp4 ( 1069)
PHP Version : 7.4.33
Disable Function : NONE
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : ON  |  Sudo : OFF  |  Pkexec : OFF
Directory :  /proc/4160872/root/opt/cloudlinux/venv/lib64/python3.11/site-packages/clwpos/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /proc/4160872/root/opt/cloudlinux/venv/lib64/python3.11/site-packages/clwpos/report_generator.py
# -*- coding: utf-8 -*-
#
# Copyright © Cloud Linux GmbH & Cloud Linux Software, Inc 2010-2021 All Rights Reserved
#
# Licensed under CLOUD LINUX LICENSE AGREEMENT
# http://cloudlinux.com/docs/LICENSE.TXT

from __future__ import absolute_import

import os
import sys
import time
import fcntl
import json
from psutil import pid_exists
from typing import Optional, Dict, TextIO, Union, List, Tuple
from secureio import write_file_via_tempfile, disable_quota

from clwpos.data_collector_utils import _add_wp_path_info
from clcommon.clpwd import ClPwd, drop_privileges

from clwpos.feature_suites.configurations import FeatureStatusEnum, extract_suites
from clwpos.utils import acquire_lock, get_server_wide_options
from clcommon.cpapi import userdomains, cpusers
from clwpos.optimization_features import convert_features_dict_to_interface
from clwpos.feature_suites import (
    get_admin_suites_config,
    extract_features,
    AWPSuite,
    PremiumSuite,
    CDNSuite,
    CDNSuitePro
)
from clwpos.user.config import UserConfig
from clwpos.logsetup import setup_logging
from clwpos.cl_wpos_exceptions import WposError
from clwpos import gettext as _

from clwpos.constants import (
    SCANNING_STATUS,
    LAST_SCANNED_TS,
    SCAN_CACHE
)


logger = setup_logging(__name__)


class ReportGeneratorError(WposError):
    """
    Raised when some bad happened during report generating/getting
    """
    pass


class ScanStatus:
    """
    Type for handly scan status manipulations
    """
    def __init__(self, status, pid: Optional[int] = None):
        self.pid = pid
        try:
            if isinstance(status, str):
                self.current, self.total = map(int, status.split('/'))
            elif isinstance(status, tuple):
                self.current, self.total = map(int, status)
            else:
                raise ReportGeneratorError(
                    message=_('Unable to parse scan status: %(status)s, type of: %(type)s'),
                    context={'status': str(status), 'type': type(status)},
                )
        except ValueError:
            raise ReportGeneratorError(
                message=_('Unable to parse scan status: %(status)s'),
                context={'status': str(status)},
            )

    def __hash__(self):
        return hash((self.current, self.total))

    def __eq__(self, other):
        if isinstance(other, ScanStatus):
            return self.current, self.total == other.current, other.total
        elif isinstance(other, str):
            return str(self) == other.strip()
        elif isinstance(other, tuple):
            return tuple(self) == other
        return False

    def __str__(self):
        return f'{self.current}/{self.total}'

    def __iter__(self):
        for i in self.current, self.total:
            yield i

    @staticmethod
    def read() -> Optional['ScanStatus']:
        """
        Read status file, with shared blocking flock
        """
        st = None
        if os.path.exists(SCANNING_STATUS):
            with open(SCANNING_STATUS, 'r') as f:
                fcntl.flock(f.fileno(), fcntl.LOCK_SH)
                data = f.read()
                fcntl.flock(f.fileno(), fcntl.LOCK_UN)

                # status file was created, but not written with data yet
                if not data:
                    return st

                try:
                    data = json.loads(data)
                    pid = data.get('pid')
                    st = ScanStatus(
                        (data['current'], data['total']),
                        int(pid) if pid else None,
                    )
                except Exception as e:
                    logger.error('Can\'t parse scan status json: %s', e)
        return st

    def to_json(self) -> str:
        """
        Status JSON representation to write
        """
        return json.dumps({
            'current': self.current,
            'total': self.total,
            'pid': self.pid,
        })

    def check_pid(self) -> bool:
        """
        Return True if scan process is still alive
        """
        return bool(self.pid) and pid_exists(self.pid)


class ReportGenerator:
    """
    Class for admin report generation/getting
    """
    def __init__(self):
        self._clpwd = ClPwd()
        self.status = ScanStatus((0, 0))
        self.result = {
            'version': '1',
            'users': {},
        }
        self.scan_status_fd = None
        self.logger = logger

    @staticmethod
    def is_scan_running() -> bool:
        """
        Checks:
            1) SCANNING_STATUS file exists
            2) SCANNING_STATUS has the scan process pid and it is still alive
        """
        status = ScanStatus.read()
        if status:
            if status.check_pid():
                return True
        return False

    @staticmethod
    def get_scan_status() -> Optional[ScanStatus]:
        """
        Read status file and get status
        """
        return ScanStatus.read()

    def scan(self, user_list: Optional[List[str]] = None) -> Dict[str, int]:
        """
        Public entry point for the scan procedure
        Do some checks, prepare users list, fork process to actually do scan, and return initial scan progress

        `user_list` - users to scan; if None - scan all
        """
        if self.is_scan_running():
            raise ReportGeneratorError(message=_('Another scan in progress: %(status)s'),
                                       context={'status': str(self.get_scan_status())})

        usernames = self.__get_usernames()
        self.logger.debug('Found usernames: %s', usernames)
        if user_list:
            usernames = self.__filter_usernames(user_list, usernames)
            self.logger.debug('Filtered usernames: %s', usernames)
        self.status.total = len(usernames)

        # fork the scan to another process and return initial status immediately
        fp = os.fork()
        if fp:
            self.logger.debug('Scan forked to: %d', fp)
            return {'total_users_scanned': 0, 'total_users_to_scan': self.status.total}
        else:
            try:
                self._scan(usernames)
                sys.exit(0)
            except Exception as e:
                self.logger.exception('Error during user sites scan: %s', e)
                sys.exit(1)

    def _scan(self, usernames: List[str]) -> None:
        """
        Executes in forked process
        Get domain and docroots list for usernames
        Count user sites, write to SCAN_CACHE
        Create and remove SCANNING_STATUS file

        `userdomains` examples:
            [{'domain': 'res1.com', 'docroot': '/home/res1/public_html'}],
            [{'domain': 'cltest1.com', 'docroot': '/home/cltest1/public_html'},
                {'domain': 'mk.cltest1.com', 'docroot': '/home/cltest1/public_html/mk'}]
        """
        self.scan_status_fd = open(SCANNING_STATUS, 'w')
        self.status.pid = os.getpid()
        self.logger.debug('Set status pid to: %d', self.status.pid)
        for username in usernames:
            user_data = {}
            self.status.current += 1
            self.__update_scan_status()
            for domain_name, doc_root in userdomains(username):
                user_data.setdefault(doc_root, []).append(domain_name)
            with drop_privileges(username):
                user_data = _add_wp_path_info(user_data)
            # set-comprehension and rstrip() used to delete duplicated paths in case of subdomains
            # ex: {'/dr1': {'wp_paths': ['', 'wordpress', 'sub']}, '/dr1/sub': {'wp_paths': ['']}}
            wp_paths = {
                os.path.join(_doc_root, _wp_path).rstrip('/') for _doc_root, values in user_data.items()
                for _wp_path in values.get('wp_paths', [])
            }
            self.result['users'].update({
                username: {'wp_sites_count': len(wp_paths)},
            })
        self.__write_scan_result()
        self.scan_status_fd.close()
        os.unlink(SCANNING_STATUS)
        _ts = self.__update_scan_timestamp()
        self.logger.debug('New scan timestamp: %d', _ts)

    def get_status(self) -> dict:
        """
        CLI command to get scan status
        Cases:
            1) no previous scans
            2) scan in progress
            3) scan finished (success)
            4) scan process crashed
        """
        result = {
            'scan_status': 'idle',
            'total_users_scanned': 0,
            'total_users_to_scan': None,
            'last_scan_time': None,
        }
        if not os.path.exists(SCAN_CACHE):
            result.update({'total_users_to_scan': len(cpusers())})
            return result

        if self.is_scan_running():
            status = self.get_scan_status()
            result.update({
                'scan_status': 'in_progress',
                'total_users_scanned': status.current,
                'total_users_to_scan': status.total,
            })
        else:
            if not os.path.exists(SCANNING_STATUS):
                result.update({
                    'total_users_to_scan': len(cpusers()),
                    'last_scan_time': self._get_scan_timestamp(),
                })
            else:
                result.update({
                    'scan_status': 'error',
                    'scan_error': _('Failed to generate report'),
                    'total_users_to_scan': len(cpusers()),
                    'last_scan_time': self._get_scan_timestamp(),
                })
                os.unlink(SCANNING_STATUS)
        return result

    @staticmethod
    def _get_scan_timestamp() -> Optional[int]:
        """
        Read timestamp from LAST_SCANNED_TS
        Returns None in case of any error
        """
        try:
            with open(LAST_SCANNED_TS, 'rt') as f:
                t = f.read().strip()
                return int(t)
        except Exception as e:
            logger.error('Can\'t read last scan timestamp: %s', e)
        return None

    @staticmethod
    def __filter_usernames(to_scan, usernames: List[str]) -> List[str]:
        """
        Return usernames from --users cli argument
        """
        return list(filter(lambda x: x in to_scan, usernames))

    @staticmethod
    def __get_usernames() -> List[str]:
        """
        Get usernames from cpapi
        """
        return list(cpusers())

    @staticmethod
    def __update_scan_timestamp() -> int:
        """
        Write current timestamp to LAST_SCANNED_TS
        Return timestamp for the later use, if needed
        """
        ts = int(time.time())
        write_file_via_tempfile(str(ts), LAST_SCANNED_TS, 0o600)
        return ts

    def __update_scan_status(self) -> None:
        """
        Write current status to SCANNING_STATUS
        Data example: "0/10", without any other symbols
        """
        f = self.scan_status_fd     # type: TextIO
        f_no = f.fileno()
        f.seek(0)
        fcntl.flock(f_no, fcntl.LOCK_EX | fcntl.LOCK_NB)
        f.write(self.status.to_json())
        f.flush()
        fcntl.flock(f_no, fcntl.LOCK_UN)

    def __write_scan_result(self) -> None:
        """
        Write final scan result to SCANNING_STATUS via temp file
        """
        write_file_via_tempfile(json.dumps(self.result), SCAN_CACHE, 0o600)

    # get-report part
    def get(self, target_users=None):
        """
         1. get-report when there is no cache file:
          - start generating report
          - return total_users_scanned, total_users_to_scan keys
        2. get-report when there is no cache file, but scanning
           in progress:
           - return total_users_scanned, total_users_to_scan keys
        3. get-report when cache present, no scanning running
          - return data from cache
          - no keys total_users_scanned, total_users_to_scan in response
        4. get-report when cache present, scanning is running
          - return data from cache
          - return total_users_scanned, total_users_to_scan keys
        """
        report = {}
        scanned_cache = self._get_from_file_with_locking(SCAN_CACHE, is_json=True)
        scanning_status = self.get_scan_status()

        # no cache and scanning is not running right now ->
        # run scanning
        if not scanned_cache and not scanning_status:
            scan = self.scan()
            return scan

        # no cache, but scanning is running right now ->
        # returns status from status file
        if scanning_status:
            report['total_users_scanned'] = scanning_status.current
            report['total_users_to_scan'] = scanning_status.total

        # if scanned cache -> append it to report
        if scanned_cache:
            report['last_scan_time'] = self._get_scan_timestamp()

            # cache already generated, let`s read it
            users_cache = scanned_cache['users']
            (
                report['users'],
                report['total_wordpress_count'],
                report['total_users_count'],
                total_users_with_active_awp,
                total_users_with_active_premium,
                total_users_with_active_cdn,
                total_users_with_active_cdn_pro,
                total_sites_with_active_awp,
                total_sites_with_active_premium,
                total_sites_with_active_cdn,
                total_sites_with_active_cdn_pro
            ) = self._get_users_report(users_cache, target_users)

            report['total_users_count_active'] = {
                AWPSuite.name: total_users_with_active_awp,
                PremiumSuite.name: total_users_with_active_premium,
                CDNSuite.name: total_users_with_active_cdn,
                CDNSuitePro.name: total_users_with_active_cdn_pro
            }
            report['total_sites_count_active'] = {
                AWPSuite.name: total_sites_with_active_awp,
                PremiumSuite.name: total_sites_with_active_premium,
                CDNSuite.name: total_sites_with_active_cdn,
                CDNSuitePro.name: total_sites_with_active_cdn_pro
            }
        return report

    @staticmethod
    def _is_allowed_suite(user_suites_data, user_features_data, suite):
        is_suite_allowed = user_suites_data.get(suite.name).status == FeatureStatusEnum.ALLOWED
        return is_suite_allowed and any([user_features_data.get(feature.NAME.lower()) and
                    user_features_data.get(feature.NAME.lower()).status == FeatureStatusEnum.ALLOWED
                    for feature in suite.features])

    @staticmethod
    def _sites_with_active_features(username):
        with drop_privileges(username), disable_quota():
            wps_with_enabled_awp_features = UserConfig(username). \
                wp_paths_with_active_suite_features(AWPSuite.features)
            wps_with_enabled_awp_premium_features = UserConfig(username). \
                wp_paths_with_active_suite_features(PremiumSuite.features)
            wps_with_enabled_cdn_features = UserConfig(username). \
                wp_paths_with_active_suite_features(CDNSuite.primary)
        return wps_with_enabled_awp_features, wps_with_enabled_awp_premium_features, wps_with_enabled_cdn_features

    def _get_users_report(
            self,
            user_scanned_data: Dict,
            target_users: Union[None, List]
    ) -> Tuple[List, int, int, int, int, int, int, int, int, int, int]:
        """
        Returns list of final users data:
        example:
        [
        {"username": "user1", "features": {"object_cache": true}, "wp_sites_count": "1"},
        ....
        ]

        """
        all_users_info = []
        total_wp_sites_count, total_users_count = 0, 0
        total_users_with_active_awp = 0
        total_users_with_active_premium = 0
        total_users_with_active_cdn = 0
        total_users_with_active_cdn_pro = 0

        total_sites_with_active_awp = 0
        total_sites_with_active_premium = 0
        total_sites_with_active_cdn = 0
        total_sites_with_active_cdn_pro = 0

        default_config = get_server_wide_options()

        for username, scanned_data in user_scanned_data.items():

            wps_per_user_with_enabled_awp_features = 0
            wps_per_user_with_enabled_awp_premium_features = 0
            wps_per_user_with_enabled_cdn = 0
            wps_per_user_with_enabled_cdn_pro = 0

            if target_users and username not in target_users:
                continue
            uid = self._uid_by_name(username)
            if not uid:
                self.logger.warning('Cannot get user %s uid', username)
                continue

            # let`s not break report collection for all users
            try:
                user_features_data = extract_features(uid, get_admin_suites_config(uid),
                                                      server_wide_options=default_config)
                user_suites_data = extract_suites(get_admin_suites_config(uid),
                                                  server_wide_options=default_config)
            except Exception:
                self.logger.exception('Unable to get features data from admin config')
                user_suites_data = {}
                user_features_data = {}

            # broken users must not fail whole report
            try:
                wps_with_enabled_awp_features, wps_with_enabled_awp_premium_features, wps_with_enabled_cdn_features = \
                    self._sites_with_active_features(username)
            except Exception as e:
                self.logger.warning('Unable to get information for report from user config: %s', str(e))
                wps_with_enabled_awp_features, wps_with_enabled_awp_premium_features, wps_with_enabled_cdn_features = \
                    [], [], []

            total_users_count += 1
            total_wp_sites_count += int(scanned_data['wp_sites_count'])

            # if feature is allowed and activated by end-user
            if self._is_allowed_suite(user_suites_data, user_features_data, AWPSuite) and wps_with_enabled_awp_features:
                total_users_with_active_awp += 1
                total_sites_with_active_awp += len(wps_with_enabled_awp_features)
                wps_per_user_with_enabled_awp_features = len(wps_with_enabled_awp_features)

            if self._is_allowed_suite(user_suites_data, user_features_data, PremiumSuite) and wps_with_enabled_awp_premium_features:
                total_users_with_active_premium += 1
                total_sites_with_active_premium += len(wps_with_enabled_awp_premium_features)
                wps_per_user_with_enabled_awp_premium_features = len(wps_with_enabled_awp_premium_features)

            if wps_with_enabled_cdn_features:
                if self._is_allowed_suite(user_suites_data, user_features_data, CDNSuitePro):
                    total_users_with_active_cdn_pro += 1
                    total_sites_with_active_cdn_pro += len(wps_with_enabled_cdn_features)
                    wps_per_user_with_enabled_cdn_pro = len(wps_with_enabled_cdn_features)
                elif self._is_allowed_suite(user_suites_data, user_features_data, CDNSuite):
                    total_users_with_active_cdn += 1
                    total_sites_with_active_cdn += len(wps_with_enabled_cdn_features)
                    wps_per_user_with_enabled_cdn = len(wps_with_enabled_cdn_features)

            all_users_info.append({
                'username': username,
                'suites': user_suites_data,
                'wp_sites_count': scanned_data['wp_sites_count'],
                'accelerate_wp_active_sites_count': wps_per_user_with_enabled_awp_features,
                'accelerate_wp_premium_sites_count': wps_per_user_with_enabled_awp_premium_features,
                'accelerate_wp_cdn_sites_count': wps_per_user_with_enabled_cdn,
                'accelerate_wp_cdn_pro_sites_count': wps_per_user_with_enabled_cdn_pro,
            })

            # stop iterating through users if targets already found
            if target_users and len(target_users) == len(all_users_info):
                break

        return (all_users_info, total_wp_sites_count, total_users_count,
                total_users_with_active_awp, total_users_with_active_premium,
                total_users_with_active_cdn, total_users_with_active_cdn_pro,
                total_sites_with_active_awp, total_sites_with_active_premium,
                total_sites_with_active_cdn, total_sites_with_active_cdn_pro)

    def _get_from_file_with_locking(self, path: str, is_json: bool, with_lock: bool = False) -> Union[Dict, str, None]:
        """
        Reads file with locking if needed
        """
        if not os.path.exists(path):
            return None
        try:
            if with_lock:
                with acquire_lock(path):
                    return self._read_report_file(path, is_json)
            else:
                return self._read_report_file(path, is_json)
        except Exception as e:
            raise ReportGeneratorError(message=_('Can`t read %(file)s. Reason: %(error)s'),
                                       context={'file': path, 'error': str(e)})

    @staticmethod
    def _read_report_file(path: str, is_json: bool) -> Union[Dict, str, None]:
        """
        Reads file for report
        """
        with open(path, "r") as file:
            if is_json:
                return json.load(file)
            else:
                return file.read().strip()

    def _uid_by_name(self, name):
        try:
            return self._clpwd.get_uid(name)
        except ClPwd.NoSuchUserException:
            return None

Youez - 2016 - github.com/yon3zu
LinuXploit