ÿØÿà JFIF    ÿÛ „ !.%+&8&+/1555$;@;4?.451 4,$,44444444444414444444444444444444444444444444444444ÿÀ  á á" ÿÄ     ÿÄ ?    !1AQaq"2‘¡±ÁðBRbrÑá#‚’¢²3S CñÿÄ   ÿÄ !    !1QAa‘2ÿÚ   ? 5˜Z¯V¦cø)›t/? z¨±>Õ5€¶‹Á¤·¼z¼Ü¬+ñ®v¤¨_ˆR­BFn©—˜ý®ç̝P8gýt·ÉSTŦˆìät?þé¼íìN/Þa)ì–í6ô… Ï¿øÃj´¿KÇü]ÿ ªô¹-eKànëÕHTx}ýSÜ›ÿ ”7Ø×&µ<¦  ¥ÑO¶[Ù¯ä¨ÞÃÿ PZ-¬;#õ|•oaÿ ©CìÞz3˜öː/¤­ñTûIØ}š^ mÓ%ªxˆ¥ÉŸu=Z+ISe¿45™¼u;ú&WØ÷€æßQ™®{|íx*TC“#ZŠìZ§²‹ 6pv…³¿¡äª*áZÐ%ÒOáˆo"x«OHk w±æ+¬V(kMúŸ5Vö«$ ÁrÏbàb57/luR ¸ÑÛj Òµì`Мq­û žICÀÊ•©4€Âcà¨Ï€O´<èÐ:›ù(Ë^L8þ‘ÍÌ#¸Ð_Ì©ÙK(Öz 4¬û+¸;ü’V’84‘¬ÃŽ:[â‡ÔÌáõp¢~§ªlæ£ö{®G>J¼"°‡7¯ÆÉèßû ‹É‹§ÁòÃýâßî ^ƾÙõ‹×óH#«LP½ïX=xÑÍ$|W?•~• îëÔ©ª‹ {ÝT…Kÿ ”hûâá)J*ö˜–ÔU;iÇ€/ ÆþjóZ\ýwØ=Ìm ºèËL9 ýèÆð/¨’¥öo=nË.%Îì ŽÕ¯È|{Oj²ƒE6e/ßdÄõ²Ìâ1O®ò×TsəԸhOMýíMˆ¿¼H˜l²,7Â¥#MF/Úf°Ö½± ¸–dr‹NýÊ íjqx{œÉ ä-È ¦ øÄër¨q°ð †nцýÑÄÆ’mä…n<0È™;ÁÝá¯ÁZƒ7FÀmì­ É&9ˆîéi¶ùN§Y• ÃZãAâ?•‡©‰ , ó¾IŸŠc1 4â&y­&pŠ­6;M À 0¹qç»p.á …ŸÅáK@%6·y6ƒ‰3?”úºŽ‰éX5ªPT §µ!=Mž«Ú½‹ÅgÂSâÉaþÓoö–¯ÁÔìR>5éÿ üs¶ÆUcÌ kÇR ]ÿ ù¬¼«VŽ;Â|‡~¢¦”ÏŰæ {L™Õ°Óv¹ò¸írޡעCÃ!íVÕ {¶»sŒNPg/ "uÕbkm²“$ďå¿é¹§°½æz¯6 †s¿!s–wÚÝ“™Œ °.ûj>·+™Òa…©Œ&rÝÎtÛë긪Ît’LAVp%c Úý[ÄzJ¾ÇàXXç@˜ó<êL]·T˜¾¥1Ó©V‡g´æ½¦Ý@¹óø!_@´ÞâSÁ —S3™•& ]@JHÚý©ZŽ €×æÔr»Áf!‡yÞ4Mv*èÓã_{‘åóUuљØ«Oïé*®EvÑ Œ÷‡U \"㪒ÍK+À 4“M¡ï:0¥5í!'<@î´”>Ç»&Z–ïCCV˜Ì5Šo&îhè.žû |ÓK©h$s6KìŒëã)¹hI¦GïOåóI;ììü#É$Š0…Ææ¥TØ.5­¾gn´ “ÂÖ\:hœ89G)J@„}œ:’Ò{/Š"¦_Æ×7Æ3VÇŠÊa]ÚŒÙ€Ä–=®uÁßâACZƒ§§£ Qnâ:«,×{tyø¬iÛcœÜÄ€H½ÄÍCk´÷šß .W'b¤Íåh]÷€=,Žv×cÚEÚHXJX¶îo¨FÒtèöŸ>ªª6[J®Fµ£sGÁeqõfe\íjÒÐïÄÐGˆe1Ø‹.Ø”‘Ëuø Y­ˆÜ ŽG|zùªüMpDnQWÄ”%JŠ™)â*p@Örš«ÕT2Ð%ˆG#ª„ ·¤!°ŸOTÂT¸aÚ%4&h™LµšØüÐ.F¿²ÐÞ_Ç‚¾ÅÃaÜ÷09Æ q€öy˜v‡85õN÷]¬äѼóS{°_MެúÔ#°Ç¸0åÞè2ëôPcvÆw9®ií1Ä8F™˜à‰´+‰Ik1òÝ7“Ñ×ÒsÝ\x‚h`ÞÑ`ó"|µEcý£n˜h`}GÞ !±ù²Ápü²ß6 0ïi󜵩SÈÇ7˜-ÕURO˜¦´f$ªž-Í6(œ}<„ éc øs]ŽŽ„*—¾ ìdŽ„)méª\¿êÎIg¾ØÞ~I#C/¼¼´EÁÈŽi8“©õådô·>euä ƒ'Ê×लR1ÉJE1ÐAát`t;ÇР%Ý<‡¥„ÍÆ`×Oyó)õiI€ñQaŸ4Ûù\áàaÃÔ¹HÃu¹*k€¦<„e S‡&õÏ B!ŽhüÞ`yj}mªf×\¿ Ç~æ­9‡û\՞Ǖg²1Žû5V7 !àöšm° c`ܬøÇìµÒ'P"?…´Ö,"§^•õލsÔ)6˜sæéÍR¼ ò|Sl”‹7 nPW Gòú÷½§O¯‡„l¡kSÞŒr½PÊ@æ¢pŽ-mÿ #Ÿ˜Àº¶Áä¦;ïÔæ$1££`“Õ>„—·ž)ßð³ñ#Ï Ô$¶œ‰ÊE‹À;÷º ¯«P:Ñ”8–IÊtpÞ3ª“>ê“þës4ò2OÏÕ­±zô†Õ§‰.÷ä¸;¿˜“'œ›žª}«Œ{ª±Ì 9ÔóÞÕ‡0 $íWV3Üì¬ —@kÝ4@¿r¼±½¬™›?øØæ´'Áé®CË3-g$˜ö‡×auÚi´Žp/êÛ æF›Ú2v‹ã¿¿,nB1̨ƃqÞa5͝@&Æû“él÷ \C²½UÍc ¯k×¢U ÖéQå™—-r wô ÞÏ<Ò=&=ÿ Ôê Òêˈt,i—;LîÜ á¸*ÚÃ1$êL•LÍ <É)ýÐà’ ;F™{ƒ™˜€&'}‚ãÄK`¡ÞT@I;®žZóè‚s’7®°›+§O­Åq©é»²9<Ô J ¼9O’HL»Ùïì¸rk¼Ž_ý‘TŸu[²ßÚŒ·ü÷B%¯E ŸÔX5êO´ Ç•€’I0 ÉJX` ñ¹õ%;µŸD‘«´€àwÒ™U ûئžÖö\×®×´8 ½‡ºÐÆÓ§?Àkmœ=;d5*@-ì0F Rªýš[Ü6âö̃ڸr*KA9· u*µæ£?U¸Âêí†8@¦X4 e-ò„0s{ HâUpU?¼mñRa°®a%Ð'tÉ×’\¾ÊÉ]t›h>·(Ë@R¼¡Ãt h}’O÷au<+nT…Ö…MӐ??Óe95 q>í/;&JSû °¯ÊéÞ øƒ*Ã2½Ài&:nôUl=¾¿5eˆ3”ñc|Ú2V”>„»&eE;«ÚäC p¢Û úy 9š[ŒÌx¼擼A&DåÒ¯ˆ¤ÀÌ;"˜ ÏQä¸åhÊ}Ûq«Û0WžÒ|»€ø®öCm5•\ÇÀ§Pe3£]0ÃàLDÉ‰1øªxjgwT‚÷¿LΨK‹›ùs—xˆÜ±µ kæ¸f‰‰ÜGk/LÛØ6d9ò¶ùA{ƒA3š/¬D¬khÓk‰`˜"㯒r¿±Óã jx‡°e}<Ñø\3y:'À•/h½Í€Ç4~g ?Û(¼]v‘ªlKÎâ~?O‚W%{Ì:“'©úNq¾›úo(X’¥¯ˆ nFê{Ç€ü?º'ë ø‹ì Þ09ŒÌç9Æ —ËC`j@ÓÄ(+a‹un¸#ÂꟋ{K`‘ÑÍÍ'à´»/Û,KW;Þ4²þð ï Nm|~fGÏ(…³Ã)«1ö­Õ ¥‡¨©ƒÃ™ü-s=à=U66Ï«Ýc蓦W¹íž®›nÔ%êÇìŒ<#Ü×84ån®Ð ÒåOC` ñânÑs‡¢ç 1õ%Îhì½Ã½® e:ݼUZo™`  ÅZŸŒÊ«ê1ÏÄo$q¹Þ€©ˆhÐÉä¯ñ[!…Ú˜àJ:x2$Íß&PåT£6ç— ‡Í*4Ýšçjÿ ‰É nófÐ ó(L5C•åÆ\rMÒ@ò }y-W}™üýVù—ú¢=Ù”c®‘< M ž ´Phr ¦©TD ‘ù.$´÷O‡‘V2Æò.=IUŒ=ž‡â¬i™aþÓåÙ?òUø'ØÖ•.~* šTŒ!•-×áºTâ®ä#õü'´ eýlYÅÓeÕKÂrT"CÚ@u!Óxƒ{š3€}1¿(r}%«nËamjÑ%ÑNEò v ˜à  σöK³,*º.àzù¨™Ó ÚçâU¦*¿ 9{%Ö¹ njûdaXöb) kÛÆ±ûÓ\°M7ˆÂ=û›ç¿Ã‚­V»Cg–8ÙêE- j)k$º`Ã-ùEýeBÆÇ]c¡°ñty&Òd0nõ'¡W+ƒ*|–øµFa\GQªEAÔp5\Ǽ·¼Ç8·õ -â§Ú[ ‡ uZeÖ 3}×d'+¹:ð+K†Û®s!Ï$úe€<Û”x)1»a­¡LC]¸µík…ÚàA»AYº{†ªS[¦5HÒ7ù --,ísòDØ€èk ÞÀîÜ ò@â( ËNˆë›4ô½•/¦o‡€Û7 ê•ÆêòðÜy'Án½µ á˜ݦ ndeo…[ì¶Ê,¥R³Ä=À±—–ß;£™´ñSâ*g§”ïaið‘Jå~™ÓÞ ß³Õ¢»8x埒²52>AÊb&-÷\7´éÄù€T˜,w;3{ï˜k…à¹ÄqÀ«œ{€\ ˆ¾[´¨јr &Úé„Ívˆ±8†¿]|¬ņ4I×pÞS1ÈÖz‰#Ìv‡G!YNògñ:màTz¢Ý1ô©^O=~ë|5Bã™ç•¼µõ•bÆ@úÕS¬ÈŒ#¬zünrŸ û” Z²•èðV"ÁHÚý©wÝ €7¼Ìu1hÑa3Éä û f$o¿É ™Ú›ÝçnpÒ3äÌ3†Í§,Äï]$‰/pê †«À¼¸e9­Æê_C]žƒ·ý·frÁN«, E=›Çq -‰öŒ:aÏ¿±í&£Í:-} 84‘ÿ eƒQÑeëSsuiA ³g㟥ú£?ÿ ʼn*”“÷aühe:ÊWa@ÒÞk±eØ] F Ô—r.åä˜ @ö¥ªZoÐýYL·¥S²G/‡ñ <~*ZÆ´è>JlòàÛÆ½ÿ 窘ìGN¢:I®KšJp/`íIÁÀõ#Ä-€ö­šµŒoF4|ÆQØÆ@Ì|£Ô…¢À{9˜è½Üó›€ôYÒÎYsið;ís¤€à²ˆ‚4qÉVŒI$ ‰"° æµ8cXGjœˏ¡Aâý•ËÜ¢ûï e·çLx']á"oÅÎê3¯Ç—¹”ó0nå‚âg{Œñ> S´˜îè°g238‚ãköÝfÚd´6Ò€;ò÷±¢™¼›º ¢Æ'¥Ðx'e¬ç ]bÈÆV¢ó‹kýBO ðÊâ$Ÿ!×T 3Mýמ žìٍàÌü‘8÷€àæØ8æ©6‰©L´«…oãpð„~Çk‰!ñ;‹”ÛžÍ àž±z Ÿôû øŸÝužÏ;ÿ #|u6™Þ¬ÚˆÐõA4¶â|ôl|Ê2ŽÇ¤ÝÅÇY.<#Aí.k§hóF‚”Y; M½Ö4hŸ4&›­¿tès´%FìL¥£Ãk‰ÇT¤haÁ¤ÚxfÉ`ÑìË›>i 3t‚:,–+^÷´–{Û–Nxi"x‘Ûg î¨>¥Õ܁ùZH,2Û“:8xÊ¢Çí9.É-Ìâã-=çjwµS˜dütžçwýGòú®®ûº_ˆýx$–¡ãøO EÚÛÏ÷R„×w+3£Á£öUMyR²¹âŒ°š›¸Ñãò9§Ó_Dl+Ùßc›úšGÅÌc†Ž!Ko=¶.‘Îÿ c²(2®V mª.ÿ ¹B›¹å ù„öŸSV>™ü¯$y:G¢Z×àøúdî¹û­·ýÇ´:•c LÍõi_‹ö+ÎæGÊè>OŠ•äž´§Þ{X}¨1ÚTc›»Qþ•êô°t¿OP?eæ~É{5]•ÙR£r5†nZ\ã@ &îJõ ¾àC°þV>fé¥/ü5ñÊIº_é5 ;e­h<@ Ä&æÃëE%;X,ÒãÆÞ`Oò¦kŸm#˜!ÀyÄ¢| óLšò¥Ä` ¶R=|ÈCâh5ò3DˆïF†ðÒ#ÅìÛœ?¸yhBãœí ZxßÎÄhºRK„`Þödvײ™ÀÈÑÒgŒuY w³%†ƒÓzõ ÖÏp‚dH®¦A´ù§»ÓÇMæ~)ˆð‡û:ù&Ä •vGD´À n ݇¼Ö8Fö óáà£~Ë¥x`oK|Ä?fxiØü%pìR>éò+Û±éÎ>núlFŤ'tq8LZÏvÃ?„¡ß±È⽆¯³íü@x|PöUäèØã¡ð‚ŒAìÏ"vÍwóŸÍ{ ý0.z È•Ö{,N¡£¡ŸKÕÙž>Ýœþ ÍÀ°<×EA!Å‚D™IúOÍ¡>ôG}Â` ÍßkÜL™Ž Þð™ {IøF²¹òQ3&!ÃÂÞz.d&Ï-sH¸,Ôõ˜ŽP€ 77ˆÝ¼ÊëÜw =cÕ Ú,ØÐ5ÎYÐ)ì´öœgŒ[¤ßv㙑8心>h]§µháYš£²ºÑ.{Ï7Sð•?´~×SÃKýJÛ˜ ™Íäiúu<µX¶1õ^kâçIÑ£sZ4h>j*ÔšD:4­¿_ ÷¸ Õxæÿ ¸?Mù _•­ÊÐ ä ÷ý ÑwL œ­ïnTkÛUÍN©ë:¦fV ¶ÜÔÜMªÅâA½–¿R×TXš-%iTÊT•‡Ù‚JôϐZxWÑè‰f‰òG º ×Õû2aZ7OU3[“×AT–ÞŒ…-‘¤”Ì ì&(ˆ¿­•ƒkï’:ðY¦W‘ Å)“†‘˜³Åtcø˜ñTÂwÚÇ4|üLÇªí–v- qˆèU qPE.†â‘˜µ Æ,ÐÅs]8¾„oúÑ i>ÜxxÈó)ƒ ´æÁâØ$À‰vžŸf$Ž |ãw;ÀÁIJ»b` {¦Ó¤Ú$©YÀ‘n@Óïž«9J¼êG m¤ ܯ¹ÌW4€ÐÒÅÛ‡#褕Ÿn-?í|с¥÷Ú¹¬'´ÞÜ9ÓK `hê£SÄSà?7—Wí_´…óB›»:=Ãïq`<8ñÓŒÑlú2d¬ê³£hÖ[l|$vÝro~'R®‰§°ñmY ͧäP |PUª¹·:3Œ[Û{Xÿ ºâ@‚W–Äé u‚ ¯´*=íή.pûÒdt @G‰¬ s¸ ëÉücr ÞæÑ¨Ê@>¤¢Ö±. Þ'¯°ÌME[YéïĵÂCå½ Ué©Áû'Ê9%eÔðNU”ë‘ÌsD3/®+UI˜9h.WC”빓$#:pz:YÓ ¿xž* ³$Í +$kñAŠ‹†¢ Uê>¸)_š¬÷©ßAÂÔb9ÇU ¯¾á•9¯ÏÏ÷O÷¼¼Fähal1‰3Ì[Ïr•´UCksNÐ] R‘¸¥H+§Šé†c©vÖÞ0iÓ76s†î!§=ß ¼~Ô'°Ãmäoäš³ªøi1úÉ)³yV8 CLÄØÁ‘WYïi€H6ÖÑiámø^ÈY´°Ñ7¥Û*—Ñ©L«Qƒï—Ùrÿ ›£Ð*š¸ˆL©ˆ$ˆ ÷¾D§9È®«qbqC)–ˆïv´çñsÑVT­Ø, <àïºÀO«Jý·õ àfPìð .wFšir´þ’2_Y *Æ€x\« ì€9š@ Ž|F⇥ˆkZ@hÖÄ0t¿-<“‹qµ¾*ZL¤Ú)&BJpÓF5=$„at*Zš$’ÑtdûÝRI1 2މ$€$I$#‰SÞ’Hë¬ï;Á$¡t$’`<(ñÇt)$‡Ð.Êf¢X’Kt=Éé$‚ˆªè¢oÝëòI%Rgcª÷ŠyI%¡‰ÿ !ñ)´õ $¤ Ô’IIGÿÙ# -*- coding: utf-8 -*- import logging import os import sys import subprocess import tempfile from pathlib import Path from typing import Any, Tuple, Union, List from subprocess import list2cmdline from customer_local_ops.util import fmap from .sizes import ByteSize DEFAULT_MAX_SEGMENT_SIZE = ByteSize(KiBytes=32) LOG = logging.getLogger(__name__) MAX_COMMAND_RESPONSE_BUFFER_SIZE = 2 * DEFAULT_MAX_SEGMENT_SIZE # Type aliases RunCommandResult = Tuple[int, str, str] # pylint: disable=import-error if sys.platform == 'win32': import win32con from win32com.shell import shellcon from win32com.shell import shell HANDLE = int HWND = int HKEY = int DWORD = int def shell_start(file_name: str, params: str = None, verb: str = "open", show: int = win32con.SW_SHOWNORMAL, mask: int = shellcon.SEE_MASK_FLAG_DDEWAIT, dir_name: str = None, id_list: Any = None, class_id: str = None, class_key: HKEY = None, hot_key: DWORD = None, monitor: HANDLE = None, window: HWND = None) -> bool: """ Wrapper for the Win32 API call ShellExecuteEx. This function can be used on Windows platforms any time Nydus needs to restart itself for any reason because ShellExecuteEx allows the child process to survive after its parent process stops. Initially added to resolve a DLL conflict issue, this could also be useful for upgrading Nydus, for example. Further information for ShellExecuteEx can be found at https://docs.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-shellexecuteexa :param file_name: The name of the executable to be started. ShellExecuteEx also handles file associations, so this could also be the name of a document, for example, to be opened with the associated application, or a URL to be opened by the user's default browser. :param params: Parameters to be passed to the application. Should not be specified if file_name is NOT an executable file. :param verb: Action to take. May be one of 'edit', 'explore', 'find', 'open', 'print', 'properties' or 'runas'. Defaults to 'open' :param show: Specify how an application is to be shown :param mask: Flags that indicate content and validity of other parameters :param dir_name: Name of the working directory. If None, the current directory is used :param id_list: See Microsoft documentation at the URL above :param class_id: See Microsoft documentation at the URL above :param class_key: See Microsoft documentation at the URL above :param hot_key: See Microsoft documentation at the URL above :param monitor: See Microsoft documentation at the URL above :param window: See Microsoft documentation at the URL above :return: True if the file/application is successfully launched; otherwise, False """ def add_field(key: str, val: Any) -> None: """ It is an error to include a field with a value of None in the structure passed to ShellExecuteEx, so this function only adds a key to the dictionary if the value is not None. :param key: The name of the SHELLEXECUTEINFO field :param val: The value of the field """ if val is not None: shell_execute_info[key] = val shell_execute_info = {} add_field('fMask', mask) add_field('hwnd', window) add_field('lpVerb', verb) add_field('lpFile', file_name) add_field('lpParameters', params) add_field('lpDirectory', dir_name) add_field('nShow', show) add_field('lpIDList', id_list) add_field('lpClass', class_id) add_field('hkeyClass', class_key) add_field('dwHotKey', hot_key) add_field('hMonitor', monitor) return shell.ShellExecuteEx(**shell_execute_info) else: def shell_start(**kwargs) -> bool: return True def pfx(line): return '| ' + line def pfxs(lines): return list(map(pfx, lines)) def trim_visible_output_to_lines(inp, out): """Converts input blob to lines... but not too many""" if inp is not None: out = out.replace(inp, '<>', 1) outl = out.strip().split('\n') if not outl: return outl if len(outl) == 1 and not outl[0].strip(): return [] # no single blank lines please if len(outl) < 11: return pfxs(outl) return pfxs(outl[:5] + ['...elided %d lines...' % (len(outl) - 10)] + outl[-5:]) def mark_error_output(errOut): "Converts error blob into lines with prefix marks" se = errOut.strip() if se: for L in se.split('\n'): yield 'ERR: ' + L class EndsBuffer: """String buffer that maintains two segments: a first segment and a last segment (i.e. the two ends), where each has a maximum size limit. Any extra output in between these is discarded. The assumption is that if there is a huge amount of output that some must be discarded to avoid memory overflows and that generally the first and last stuff is the most relevant. """ def __init__(self, max_segment_size=None): self._mss = ByteSize(max(0, max_segment_size or 0)) or DEFAULT_MAX_SEGMENT_SIZE self._data = '' self._elided = False def add_str(self, data): self._data += data if len(self._data) > self._mss * 2: self._data = self._data[:self._mss] + self._data[-int(self._mss):] self._elided = True def get_bufstr(self): if self._elided: return '\n'.join([ self._data[:self._mss], '...[elided]...', self._data[-int(self._mss):], ]) return self._data def str_form(bytestr): try: return bytestr.decode('utf-8', errors='backslashreplace') except UnicodeDecodeError: try: import chardet # pylint: disable=import-outside-toplevel try: return bytestr.decode(chardet.detect(bytestr)['encoding']) except UnicodeDecodeError: pass except ImportError: pass except AttributeError: return bytestr # already a string class RunningCommand: def __init__(self, popen_obj, tag, stdInput, errorOK, logger, max_buffer_size=MAX_COMMAND_RESPONSE_BUFFER_SIZE): self.p = popen_obj self.tag = tag self.stdInput = stdInput self.logger = (lambda r, _l=logger or LOG, e=errorOK: getattr(_l, "error" if r and not e else "info")) self._bufsize = max_buffer_size self._output = EndsBuffer(self._bufsize / 2) self._errors = EndsBuffer(self._bufsize / 2) self._partial = False self._completed = False def checkIfCompleted(self): self._output.add_str(str_form(self.p.stdout.read())) self._errors.add_str(str_form(self.p.stderr.read())) return self.p.poll() is not None def outputToDate(self): o = self._output.get_bufstr() e = self._errors.get_bufstr() self._output = EndsBuffer(self._bufsize / 2) self._errors = EndsBuffer(self._bufsize / 2) self._partial = True return o, e def waitForCompletion(self): # n.b. communicate returns byte strings, in an unknown encoding, although # with older python, they could also be strings o, e = fmap(str_form, self.p.communicate()) self._output.add_str(o) self._errors.add_str(e) self._completed = True return self def getResult(self, omitOutput=False): if not self._completed: self.waitForCompletion() outs, errs = self._output.get_bufstr(), self._errors.get_bufstr() output_lines = trim_visible_output_to_lines(self.stdInput, outs) if omitOutput: output_lines = [line if line.startswith("<>") else "<>" for line in output_lines] for line in (output_lines + list(mark_error_output(errs)) + ["ExitCode: %d" % self.p.returncode]): lstr = self.tag + ' ' + line self.logger(self.p.returncode)(lstr) # NOTE This is not a Nydus Result; it must be converted return self.p.returncode, outs.strip(), errs.strip() def startCommand(cmd, tag, useShell=False, stdInput=None, errorOK=False, logger=None, omitString=None, env=None): """Starts the specified command; no Shell. The cmd is expected to be an array of strings, although it is also possible to specify simply a string if there are no arguments to the command. The tag value is only used to annotate log lines for distinctive tagging in the logging output. If errorOK is True then a non-zero return code is still only logged as "info" instead of "error". The ProcOpResult will accurately reflect the result of the operation regardless of the errorOK argument. If omitString is specified, it is removed from any logging output. The command is run asynchronously in a separate process. The return value is a RunningCommand object that supports a .checkIfCompleted() method to test for subprocess completion (non-blocking) and a .getResult() to get the ProcOpResult of a completed process (will block until completion if not already completed). """ # if cmd is a string, leave as is to correctly obfuscate omitString # If cmd is a bytestring, make sure omitString and the replacement text are also bytestrings log_cmd = ' '.join(cmd) if isinstance(cmd, list) else cmd replace_text = "<>" if isinstance(log_cmd, bytes): if omitString is not None and isinstance(omitString, str): omitString = omitString.encode('utf-8') replace_text = b'<>' if omitString: log_cmd = log_cmd.replace(omitString, replace_text) if logger is None: logger = LOG logger.info(tag + " RUN: " + str(log_cmd)) # pylint: disable=logging-not-lazy # pylint: disable=consider-using-with p = subprocess.Popen(cmd, shell=useShell, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE, env=env) if stdInput: p.stdin.write(stdInput.encode()) return RunningCommand(p, tag, stdInput, errorOK, logger) def runCommand(cmd, tag, useShell=False, stdInput=None, errorOK=False, logger=None, omitString=None, omitOutput=False, env=None): """Runs the specified command and waits for completion; no Shell. The cmd is expected to be an array of strings, although it is also possible to specify simply a string if there are no arguments to the command. The tag value is only used to annotate log lines for distinctive tagging in the logging output. If errorOK is True then a non-zero return code is still only logged as "info" instead of "error". The ProcOpResult will accurately reflect the result of the operation regardless of the errorOK argument. If omitString is specified, it is removed from any logging output. """ return startCommand(cmd, tag, useShell=useShell, stdInput=stdInput, errorOK=errorOK, logger=logger, omitString=omitString, env=env) \ .waitForCompletion() \ .getResult(omitOutput=omitOutput) def run_command_pipe(cmd, useShell=False): """Used to run commands that make use of | """ p = subprocess.Popen(cmd, shell=useShell, stdout=subprocess.PIPE) with p: o, e = p.communicate() return p.returncode, o, e def run_powershell(command: str, tag: str, quiet: bool = False) -> Tuple[int, str, str]: """Execute the code in ``command`` using PowerShell. :param command: Code to execute :param tag: Short string that will be added to logs to improve searchability. :param quiet: Omit the output of the command from the result. :return: Tuple containing (exit_code, stdout, stderr) """ # 1. Python 3.5 Windows: cannot use context manager - it does not unlink the file on exit. # 2. Encode in UTF-8 with byte order mark (BOM) so PowerShell 5.1 (Windows 2016) sees the file is UTF-8. Without # this, the file will be encoded with the default system encoding which can be changed by administrators and # which, by default, cannot encode all Unicode characters properly. Encoding as UTF-8 without BOM does not work # because standard output cannot be decoded as UTF-8. # - Encoding PowerShell scripts: # https://docs.microsoft.com/en-us/powershell/scripting/dev-cross-plat/ # vscode/understanding-file-encoding?view=powershell-7.1 # - utf-8-sig encoding: https://docs.python.org/3.5/library/codecs.html#encodings-and-unicode # - Default encoding (locale.getpreferredencoding()): https://docs.python.org/3.5/library/functions.html#open # pylint: disable=consider-using-with temp = tempfile.NamedTemporaryFile(mode='w+t', encoding='utf-8-sig', suffix='.ps1', delete=False) try: temp.write(command) temp.close() if not quiet: LOG.debug("Running PowerShell command: %s", command) return run_powershell_file(temp.name, tag, quiet) finally: os.unlink(temp.name) def run_shell_script_file(script_file: Union[str, Path], tag: str, quiet: bool = False, script_file_args: List[str] = None, stdin: str = None) -> Tuple[int, str, str]: """Invoke Shell script, passing just ``filename`` or ``filepath`` and a list of arguments for execution of the file :param script_file: The path of the script file to execute :param tag: Short string that will be added to logs to improve searchability. :param quiet: Omit the output of the command from the result. :param script_file_args: List of string arguments if required while execution of the file :param stdin: string to pass through standard input :return: Tuple containing (exit_code, stdout, stderr) """ command = ['bash', str(script_file)] if script_file_args: for arg in script_file_args: command.append(str(arg)) return runCommand(command, tag, stdInput=stdin, omitOutput=quiet) def run_powershell_file(script_file: Union[str, Path], tag: str, quiet: bool = False, script_file_args: List[str] = None, stdin: str = None) -> Tuple[int, str, str]: """Invoke PowerShell, passing just ``filename`` or ``filename`` and a list of arguments for execution of the file :param script_file: The path of the script file to execute :param tag: Short string that will be added to logs to improve searchability. :param quiet: Omit the output of the command from the result. :param script_file_args: List of string arguments if required while execution of the file :param stdin: string to pass through standard input :return: Tuple containing (exit_code, stdout, stderr) """ command = ['powershell.exe', '-ExecutionPolicy', 'Unrestricted', '-File', str(script_file)] if script_file_args: for arg in script_file_args: command.append(str(arg)) return runCommand(command, tag, stdInput=stdin, omitOutput=quiet) def run_uapi_command(cmd_list: Union[str, List[str]], description: str, op_name: str, use_shell: bool = False, omit_string: str = None) -> Tuple[bool, str, str]: """Run a command on the target machine :param cmd_list: string or list of strings that represents a command to be executed :param description: short description of what the command is doing :param op_name: name of the operation that is running the command :param use_shell: indicator that the command should be executed in a shell :param omit_string: a string to be removed from any logging output. :return: Tuple containing (exit_code, stdout, stderr) """ cmd_list_str = str(cmd_list) if omit_string: cmd_list_str = cmd_list_str.replace(omit_string, "<>") LOG.debug("run_uapi_command %s cmd_list: %s", op_name, cmd_list_str) exit_code, outs, errs = runCommand(cmd_list, description, useShell=use_shell, omitString=omit_string) LOG.debug("%s_result- %s - %s - %s", description, exit_code, outs, errs) return exit_code, outs, errs def run_multiple_uapi_commands(cmds_list: List[Tuple[str, Union[str, List[str]]]], op_name: str, use_shell: bool = False, omit_string: str = None) -> Tuple[bool, str, str]: """Run a command on the target machine :param cmds_list: List of tuples with description-command pairs :param op_name: name of the operation that is running the command :param use_shell: indicator that the command should be executed in a shell :param omit_string: a string to be removed from any logging output. :return: Tuple containing (exit_code, stdout, stderr) """ exit_code, outs, errs = 0, '', '' for description, cmd in cmds_list: exit_code, outs, errs = run_uapi_command(cmd, description, op_name, use_shell=use_shell, omit_string=omit_string) if exit_code != 0: return exit_code, outs, errs return exit_code, outs, errs def start_powershell_file(script_file: Union[str, Path]) -> Tuple[int, str, str]: """ Invoke PowerShell, passing just ``filename`` or ``filename`` and a list of arguments for execution of the file. Do not wait for the sub-process to complete. The exit code returned in the tuple only indicates whether or not the process was successfully started. :param script_file: The path of the script file to execute :param tag: Short string that will be added to logs to improve searchability. :param quiet: Omit the output of the command from the result. :param script_file_args: List of string arguments if required while execution of the file :return: Tuple containing (exit_code, stdout, stderr) """ params = list2cmdline(['-ExecutionPolicy', 'Unrestricted', '-File', str(script_file)]) LOG.info("Staring PowerShell: powershell.exe %s", params) code = 0 if shell_start('powershell.exe', params=params) else 1 return code, '', '' def start_powershell(command: str) -> Tuple[int, str, str]: """Execute the code in ``command`` using PowerShell. :param command: Code to execute :param tag: Short string that will be added to logs to improve searchability. :param quiet: Omit the output of the command from the result. :return: Tuple containing (exit_code, stdout, stderr) """ # Because the process started by this command could (and probably will) survive after this process has exited, # we can't delete the temporary file, here. # pylint: disable=consider-using-with temp = tempfile.NamedTemporaryFile(mode='w+t', suffix='.ps1', delete=False) temp.write(command) temp.close() LOG.debug("Running Powershell command: %s", command) return start_powershell_file(temp.name)