gnu_parallel 239 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936
  1. #!/usr/bin/env perl
  2. # Copyright (C) 2007,2008,2009,2010,2011,2012,2013,2014 Ole Tange and
  3. # Free Software Foundation, Inc.
  4. #
  5. # This program is free software; you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation; either version 3 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful, but
  11. # WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13. # General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program; if not, see <http://www.gnu.org/licenses/>
  17. # or write to the Free Software Foundation, Inc., 51 Franklin St,
  18. # Fifth Floor, Boston, MA 02110-1301 USA
  19. # open3 used in Job::start
  20. use IPC::Open3;
  21. # &WNOHANG used in reaper
  22. use POSIX qw(:sys_wait_h setsid ceil :errno_h);
  23. # gensym used in Job::start
  24. use Symbol qw(gensym);
  25. # tempfile used in Job::start
  26. use File::Temp qw(tempfile tempdir);
  27. # mkpath used in openresultsfile
  28. use File::Path;
  29. # GetOptions used in get_options_from_array
  30. use Getopt::Long;
  31. # Used to ensure code quality
  32. use strict;
  33. use File::Basename;
  34. if(not $ENV{HOME}) {
  35. # $ENV{HOME} is sometimes not set if called from PHP
  36. ::warning("\$HOME not set. Using /tmp\n");
  37. $ENV{HOME} = "/tmp";
  38. }
  39. save_stdin_stdout_stderr();
  40. save_original_signal_handler();
  41. parse_options();
  42. ::debug("init", "Open file descriptors: ", join(" ",keys %Global::fd), "\n");
  43. my $number_of_args;
  44. if($Global::max_number_of_args) {
  45. $number_of_args=$Global::max_number_of_args;
  46. } elsif ($opt::X or $opt::m or $opt::xargs) {
  47. $number_of_args = undef;
  48. } else {
  49. $number_of_args = 1;
  50. }
  51. my @command;
  52. @command = @ARGV;
  53. my @fhlist;
  54. if($opt::pipepart) {
  55. @fhlist = map { open_or_exit($_) } "/dev/null";
  56. } else {
  57. @fhlist = map { open_or_exit($_) } @opt::a;
  58. if(not @fhlist and not $opt::pipe) {
  59. @fhlist = (*STDIN);
  60. }
  61. }
  62. if($opt::skip_first_line) {
  63. # Skip the first line for the first file handle
  64. my $fh = $fhlist[0];
  65. <$fh>;
  66. }
  67. if($opt::header and not $opt::pipe) {
  68. my $fh = $fhlist[0];
  69. # split with colsep or \t
  70. # $header force $colsep = \t if undef?
  71. my $delimiter = $opt::colsep;
  72. $delimiter ||= "\$";
  73. my $id = 1;
  74. for my $fh (@fhlist) {
  75. my $line = <$fh>;
  76. chomp($line);
  77. ::debug("init", "Delimiter: '$delimiter'");
  78. for my $s (split /$delimiter/o, $line) {
  79. ::debug("init", "Colname: '$s'");
  80. # Replace {colname} with {2}
  81. # TODO accept configurable short hands
  82. # TODO how to deal with headers in {=...=}
  83. for(@command) {
  84. s:\{$s(|/|//|\.|/\.)\}:\{$id$1\}:g;
  85. }
  86. $Global::input_source_header{$id} = $s;
  87. $id++;
  88. }
  89. }
  90. } else {
  91. my $id = 1;
  92. for my $fh (@fhlist) {
  93. $Global::input_source_header{$id} = $id;
  94. $id++;
  95. }
  96. }
  97. if($opt::filter_hosts and (@opt::sshlogin or @opt::sshloginfile)) {
  98. # Parallel check all hosts are up. Remove hosts that are down
  99. filter_hosts();
  100. }
  101. if($opt::nonall or $opt::onall) {
  102. onall(@command);
  103. wait_and_exit(min(undef_as_zero($Global::exitstatus),254));
  104. }
  105. # TODO --transfer foo/./bar --cleanup
  106. # multiple --transfer and --basefile with different /./
  107. $Global::JobQueue = JobQueue->new(
  108. \@command,\@fhlist,$Global::ContextReplace,$number_of_args,\@Global::ret_files);
  109. if($opt::eta or $opt::bar) {
  110. # Count the number of jobs before starting any
  111. $Global::JobQueue->total_jobs();
  112. }
  113. if($opt::pipepart) {
  114. @Global::cat_partials = map { pipe_part_files($_) } @opt::a;
  115. # Unget the command as many times as there are parts
  116. $Global::JobQueue->{'commandlinequeue'}->unget(
  117. map { $Global::JobQueue->{'commandlinequeue'}->get() } @Global::cat_partials
  118. );
  119. }
  120. for my $sshlogin (values %Global::host) {
  121. $sshlogin->max_jobs_running();
  122. }
  123. init_run_jobs();
  124. my $sem;
  125. if($Global::semaphore) {
  126. $sem = acquire_semaphore();
  127. }
  128. $SIG{TERM} = \&start_no_new_jobs;
  129. start_more_jobs();
  130. if(not $opt::pipepart) {
  131. if($opt::pipe) {
  132. spreadstdin();
  133. }
  134. }
  135. ::debug("init", "Start draining\n");
  136. drain_job_queue();
  137. ::debug("init", "Done draining\n");
  138. reaper();
  139. ::debug("init", "Done reaping\n");
  140. if($opt::pipe and @opt::a) {
  141. for my $job (@Global::tee_jobs) {
  142. unlink $job->fh(2,"name");
  143. $job->set_fh(2,"name","");
  144. $job->print();
  145. unlink $job->fh(1,"name");
  146. }
  147. }
  148. ::debug("init", "Cleaning\n");
  149. cleanup();
  150. if($Global::semaphore) {
  151. $sem->release();
  152. }
  153. for(keys %Global::sshmaster) {
  154. kill "TERM", $_;
  155. }
  156. ::debug("init", "Halt\n");
  157. if($opt::halt_on_error) {
  158. wait_and_exit($Global::halt_on_error_exitstatus);
  159. } else {
  160. wait_and_exit(min(undef_as_zero($Global::exitstatus),254));
  161. }
  162. sub __PIPE_MODE__ {}
  163. sub pipe_part_files {
  164. # Input:
  165. # $file = the file to read
  166. # Returns:
  167. # @commands that will cat_partial each part
  168. my ($file) = @_;
  169. my $buf = "";
  170. my $header = find_header(\$buf,open_or_exit($file));
  171. # find positions
  172. my @pos = find_split_positions($file,$opt::blocksize,length $header);
  173. # Make @cat_partials
  174. my @cat_partials = ();
  175. for(my $i=0; $i<$#pos; $i++) {
  176. push @cat_partials, cat_partial($file, 0, length($header), $pos[$i], $pos[$i+1]);
  177. }
  178. # Remote exec should look like:
  179. # ssh -oLogLevel=quiet lo 'eval `echo $SHELL | grep "/t\{0,1\}csh" > /dev/null && echo setenv PARALLEL_SEQ '$PARALLEL_SEQ'\; setenv PARALLEL_PID '$PARALLEL_PID' || echo PARALLEL_SEQ='$PARALLEL_SEQ'\;export PARALLEL_SEQ\; PARALLEL_PID='$PARALLEL_PID'\;export PARALLEL_PID` ;' tty\ \>/dev/null\ \&\&\ stty\ isig\ -onlcr\ -echo\;echo\ \$SHELL\ \|\ grep\ \"/t\\\{0,1\\\}csh\"\ \>\ /dev/null\ \&\&\ setenv\ FOO\ /tmp/foo\ \|\|\ export\ FOO=/tmp/foo\; \(wc\ -\ \$FOO\)
  180. # ssh -tt not allowed. Remote will die due to broken pipe anyway.
  181. # TODO test remote with --fifo / --cat
  182. return @cat_partials;
  183. }
  184. sub find_header {
  185. # Input:
  186. # $buf_ref = reference to read-in buffer
  187. # $fh = filehandle to read from
  188. # Uses:
  189. # $opt::header
  190. # $opt::blocksize
  191. # Returns:
  192. # $header string
  193. my ($buf_ref, $fh) = @_;
  194. my $header = "";
  195. if($opt::header) {
  196. if($opt::header eq ":") { $opt::header = "(.*\n)"; }
  197. # Number = number of lines
  198. $opt::header =~ s/^(\d+)$/"(.*\n)"x$1/e;
  199. while(read($fh,substr($$buf_ref,length $$buf_ref,0),$opt::blocksize)) {
  200. if($$buf_ref=~s/^($opt::header)//) {
  201. $header = $1;
  202. last;
  203. }
  204. }
  205. }
  206. return $header;
  207. }
  208. sub find_split_positions {
  209. # Input:
  210. # $file = the file to read
  211. # $block = (minimal) --block-size of each chunk
  212. # $headerlen = length of header to be skipped
  213. # Uses:
  214. # $opt::recstart
  215. # $opt::recend
  216. # Returns:
  217. # @positions of block start/end
  218. my($file, $block, $headerlen) = @_;
  219. my $size = -s $file;
  220. $block = int $block;
  221. # The optimal dd blocksize for mint, redhat, solaris, openbsd = 2^17..2^20
  222. # The optimal dd blocksize for freebsd = 2^15..2^17
  223. my $dd_block_size = 131072; # 2^17
  224. my @pos;
  225. my ($recstart,$recend) = recstartrecend();
  226. my $recendrecstart = $recend.$recstart;
  227. my $fh = ::open_or_exit($file);
  228. push(@pos,$headerlen);
  229. for(my $pos = $block+$headerlen; $pos < $size; $pos += $block) {
  230. my $buf;
  231. seek($fh, $pos, 0) || die;
  232. while(read($fh,substr($buf,length $buf,0),$dd_block_size)) {
  233. if($opt::regexp) {
  234. # If match /$recend$recstart/ => Record position
  235. if($buf =~ /(.*$recend)$recstart/os) {
  236. my $i = length($1);
  237. push(@pos,$pos+$i);
  238. # Start looking for next record _after_ this match
  239. $pos += $i;
  240. last;
  241. }
  242. } else {
  243. # If match $recend$recstart => Record position
  244. my $i = index($buf,$recendrecstart);
  245. if($i != -1) {
  246. push(@pos,$pos+$i);
  247. # Start looking for next record _after_ this match
  248. $pos += $i;
  249. last;
  250. }
  251. }
  252. }
  253. }
  254. push(@pos,$size);
  255. close $fh;
  256. return @pos;
  257. }
  258. sub cat_partial {
  259. # Input:
  260. # $file = the file to read
  261. # ($start, $end, [$start2, $end2, ...]) = start byte, end byte
  262. # Returns:
  263. # Efficient perl command to copy $start..$end, $start2..$end2, ... to stdout
  264. my($file, @start_end) = @_;
  265. my($start, $i);
  266. # Convert start_end to start_len
  267. my @start_len = map { if(++$i % 2) { $start = $_; } else { $_-$start } } @start_end;
  268. return "<". shell_quote_scalar($file) .
  269. q{ perl -e 'while(@ARGV) { sysseek(STDIN,shift,0) || die; $left = shift; while($read = sysread(STDIN,$buf, ($left > 32768 ? 32768 : $left))){ $left -= $read; syswrite(STDOUT,$buf); } }' } .
  270. " @start_len";
  271. }
  272. sub spreadstdin {
  273. # read a record
  274. # Spawn a job and print the record to it.
  275. # Uses:
  276. # $opt::blocksize
  277. # STDIN
  278. # $opr::r
  279. # $Global::max_lines
  280. # $Global::max_number_of_args
  281. # $opt::regexp
  282. # $Global::start_no_new_jobs
  283. # $opt::roundrobin
  284. # %Global::running
  285. my $buf = "";
  286. my ($recstart,$recend) = recstartrecend();
  287. my $recendrecstart = $recend.$recstart;
  288. my $chunk_number = 1;
  289. my $one_time_through;
  290. my $blocksize = $opt::blocksize;
  291. my $in = *STDIN;
  292. my $header = find_header(\$buf,$in);
  293. while(1) {
  294. my $anything_written = 0;
  295. if(not read($in,substr($buf,length $buf,0),$blocksize)) {
  296. # End-of-file
  297. $chunk_number != 1 and last;
  298. # Force the while-loop once if everything was read by header reading
  299. $one_time_through++ and last;
  300. }
  301. if($opt::r) {
  302. # Remove empty lines
  303. $buf =~ s/^\s*\n//gm;
  304. if(length $buf == 0) {
  305. next;
  306. }
  307. }
  308. if($Global::max_lines and not $Global::max_number_of_args) {
  309. # Read n-line records
  310. my $n_lines = $buf =~ tr/\n/\n/;
  311. my $last_newline_pos = rindex($buf,"\n");
  312. while($n_lines % $Global::max_lines) {
  313. $n_lines--;
  314. $last_newline_pos = rindex($buf,"\n",$last_newline_pos-1);
  315. }
  316. # Chop at $last_newline_pos as that is where n-line record ends
  317. $anything_written +=
  318. write_record_to_pipe($chunk_number++,\$header,\$buf,
  319. $recstart,$recend,$last_newline_pos+1);
  320. substr($buf,0,$last_newline_pos+1) = "";
  321. } elsif($opt::regexp) {
  322. if($Global::max_number_of_args) {
  323. # -N => (start..*?end){n}
  324. # -L -N => (start..*?end){n*l}
  325. my $read_n_lines = $Global::max_number_of_args * ($Global::max_lines || 1);
  326. while($buf =~ s/((?:$recstart.*?$recend){$read_n_lines})($recstart.*)$/$2/os) {
  327. # Copy to modifiable variable
  328. my $b = $1;
  329. $anything_written +=
  330. write_record_to_pipe($chunk_number++,\$header,\$b,
  331. $recstart,$recend,length $1);
  332. }
  333. } else {
  334. # Find the last recend-recstart in $buf
  335. if($buf =~ s/(.*$recend)($recstart.*?)$/$2/os) {
  336. # Copy to modifiable variable
  337. my $b = $1;
  338. $anything_written +=
  339. write_record_to_pipe($chunk_number++,\$header,\$b,
  340. $recstart,$recend,length $1);
  341. }
  342. }
  343. } else {
  344. if($Global::max_number_of_args) {
  345. # -N => (start..*?end){n}
  346. my $i = 0;
  347. my $read_n_lines = $Global::max_number_of_args * ($Global::max_lines || 1);
  348. while(($i = nindex(\$buf,$recendrecstart,$read_n_lines)) != -1) {
  349. $i += length $recend; # find the actual splitting location
  350. $anything_written +=
  351. write_record_to_pipe($chunk_number++,\$header,\$buf,
  352. $recstart,$recend,$i);
  353. substr($buf,0,$i) = "";
  354. }
  355. } else {
  356. # Find the last recend-recstart in $buf
  357. my $i = rindex($buf,$recendrecstart);
  358. if($i != -1) {
  359. $i += length $recend; # find the actual splitting location
  360. $anything_written +=
  361. write_record_to_pipe($chunk_number++,\$header,\$buf,
  362. $recstart,$recend,$i);
  363. substr($buf,0,$i) = "";
  364. }
  365. }
  366. }
  367. if(not $anything_written and not eof($in)) {
  368. # Nothing was written - maybe the block size < record size?
  369. # Increase blocksize exponentially
  370. my $old_blocksize = $blocksize;
  371. $blocksize = ceil($blocksize * 1.3 + 1);
  372. ::warning("A record was longer than $old_blocksize. " .
  373. "Increasing to --blocksize $blocksize\n");
  374. }
  375. }
  376. ::debug("init", "Done reading input\n");
  377. # If there is anything left in the buffer write it
  378. substr($buf,0,0) = "";
  379. write_record_to_pipe($chunk_number++,\$header,\$buf,$recstart,$recend,length $buf);
  380. $Global::start_no_new_jobs ||= 1;
  381. if($opt::roundrobin) {
  382. for my $job (values %Global::running) {
  383. close $job->fh(0,"w");
  384. }
  385. my %incomplete_jobs = %Global::running;
  386. my $sleep = 1;
  387. while(keys %incomplete_jobs) {
  388. my $something_written = 0;
  389. for my $pid (keys %incomplete_jobs) {
  390. my $job = $incomplete_jobs{$pid};
  391. if($job->stdin_buffer_length()) {
  392. $something_written += $job->non_block_write();
  393. } else {
  394. delete $incomplete_jobs{$pid}
  395. }
  396. }
  397. if($something_written) {
  398. $sleep = $sleep/2+0.001;
  399. }
  400. $sleep = ::reap_usleep($sleep);
  401. }
  402. }
  403. }
  404. sub recstartrecend {
  405. # Uses:
  406. # $opt::recstart
  407. # $opt::recend
  408. # Returns:
  409. # $recstart,$recend with default values and regexp conversion
  410. my($recstart,$recend);
  411. if(defined($opt::recstart) and defined($opt::recend)) {
  412. # If both --recstart and --recend is given then both must match
  413. $recstart = $opt::recstart;
  414. $recend = $opt::recend;
  415. } elsif(defined($opt::recstart)) {
  416. # If --recstart is given it must match start of record
  417. $recstart = $opt::recstart;
  418. $recend = "";
  419. } elsif(defined($opt::recend)) {
  420. # If --recend is given then it must match end of record
  421. $recstart = "";
  422. $recend = $opt::recend;
  423. }
  424. if($opt::regexp) {
  425. # If $recstart/$recend contains '|' this should only apply to the regexp
  426. $recstart = "(?:".$recstart.")";
  427. $recend = "(?:".$recend.")";
  428. } else {
  429. # $recstart/$recend = printf strings (\n)
  430. $recstart =~ s/\\([0rnt\'\"\\])/"qq|\\$1|"/gee;
  431. $recend =~ s/\\([0rnt\'\"\\])/"qq|\\$1|"/gee;
  432. }
  433. return ($recstart,$recend);
  434. }
  435. sub nindex {
  436. # See if string is in buffer N times
  437. # Returns:
  438. # the position where the Nth copy is found
  439. my ($buf_ref, $str, $n) = @_;
  440. my $i = 0;
  441. for(1..$n) {
  442. $i = index($$buf_ref,$str,$i+1);
  443. if($i == -1) { last }
  444. }
  445. return $i;
  446. }
  447. {
  448. my @robin_queue;
  449. sub round_robin_write {
  450. # Input:
  451. # $header_ref = ref to $header string
  452. # $block_ref = ref to $block to be written
  453. # $recstart = record start string
  454. # $recend = record end string
  455. # $endpos = end position of $block
  456. # Uses:
  457. # %Global::running
  458. my ($header_ref,$block_ref,$recstart,$recend,$endpos) = @_;
  459. my $something_written = 0;
  460. my $block_passed = 0;
  461. my $sleep = 1;
  462. while(not $block_passed) {
  463. # Continue flushing existing buffers
  464. # until one is empty and a new block is passed
  465. # Make a queue to spread the blocks evenly
  466. if(not @robin_queue) {
  467. push @robin_queue, values %Global::running;
  468. }
  469. while(my $job = shift @robin_queue) {
  470. if($job->stdin_buffer_length() > 0) {
  471. $something_written += $job->non_block_write();
  472. } else {
  473. $job->set_stdin_buffer($header_ref,$block_ref,$endpos,$recstart,$recend);
  474. $block_passed = 1;
  475. $job->set_virgin(0);
  476. $something_written += $job->non_block_write();
  477. last;
  478. }
  479. }
  480. $sleep = ::reap_usleep($sleep);
  481. }
  482. return $something_written;
  483. }
  484. }
  485. sub write_record_to_pipe {
  486. # Fork then
  487. # Write record from pos 0 .. $endpos to pipe
  488. # Input:
  489. # $chunk_number = sequence number - to see if already run
  490. # $header_ref = reference to header string to prepend
  491. # $record_ref = reference to record to write
  492. # $recstart = start string of record
  493. # $recend = end string of record
  494. # $endpos = position in $record_ref where record ends
  495. # Uses:
  496. # $Global::job_already_run
  497. # $opt::roundrobin
  498. # @Global::virgin_jobs
  499. # Returns:
  500. # Number of chunks written (0 or 1)
  501. my ($chunk_number,$header_ref,$record_ref,$recstart,$recend,$endpos) = @_;
  502. if($endpos == 0) { return 0; }
  503. if(vec($Global::job_already_run,$chunk_number,1)) { return 1; }
  504. if($opt::roundrobin) {
  505. return round_robin_write($header_ref,$record_ref,$recstart,$recend,$endpos);
  506. }
  507. # If no virgin found, backoff
  508. my $sleep = 0.0001; # 0.01 ms - better performance on highend
  509. while(not @Global::virgin_jobs) {
  510. ::debug("pipe", "No virgin jobs");
  511. $sleep = ::reap_usleep($sleep);
  512. # Jobs may not be started because of loadavg
  513. # or too little time between each ssh login.
  514. start_more_jobs();
  515. }
  516. my $job = shift @Global::virgin_jobs;
  517. # Job is no longer virgin
  518. $job->set_virgin(0);
  519. if(fork()) {
  520. # Skip
  521. } else {
  522. # Chop of at $endpos as we do not know how many rec_sep will
  523. # be removed.
  524. substr($$record_ref,$endpos,length $$record_ref) = "";
  525. # Remove rec_sep
  526. if($opt::remove_rec_sep) {
  527. Job::remove_rec_sep($record_ref,$recstart,$recend);
  528. }
  529. $job->write($header_ref);
  530. $job->write($record_ref);
  531. close $job->fh(0,"w");
  532. exit(0);
  533. }
  534. close $job->fh(0,"w");
  535. return 1;
  536. }
  537. sub __SEM_MODE__ {}
  538. sub acquire_semaphore {
  539. # Acquires semaphore. If needed: spawns to the background
  540. # Uses:
  541. # @Global::host
  542. # Returns:
  543. # The semaphore to be released when jobs is complete
  544. $Global::host{':'} = SSHLogin->new(":");
  545. my $sem = Semaphore->new($Semaphore::name,$Global::host{':'}->max_jobs_running());
  546. $sem->acquire();
  547. if($Semaphore::fg) {
  548. # skip
  549. } else {
  550. # If run in the background, the PID will change
  551. # therefore release and re-acquire the semaphore
  552. $sem->release();
  553. if(fork()) {
  554. exit(0);
  555. } else {
  556. # child
  557. # Get a semaphore for this pid
  558. ::die_bug("Can't start a new session: $!") if setsid() == -1;
  559. $sem = Semaphore->new($Semaphore::name,$Global::host{':'}->max_jobs_running());
  560. $sem->acquire();
  561. }
  562. }
  563. return $sem;
  564. }
  565. sub __PARSE_OPTIONS__ {}
  566. sub options_hash {
  567. # Returns:
  568. # %hash = the GetOptions config
  569. return
  570. ("debug|D=s" => \$opt::D,
  571. "xargs" => \$opt::xargs,
  572. "m" => \$opt::m,
  573. "X" => \$opt::X,
  574. "v" => \@opt::v,
  575. "joblog=s" => \$opt::joblog,
  576. "results|result|res=s" => \$opt::results,
  577. "resume" => \$opt::resume,
  578. "resume-failed|resumefailed" => \$opt::resume_failed,
  579. "silent" => \$opt::silent,
  580. #"silent-error|silenterror" => \$opt::silent_error,
  581. "keep-order|keeporder|k" => \$opt::keeporder,
  582. "group" => \$opt::group,
  583. "g" => \$opt::retired,
  584. "ungroup|u" => \$opt::ungroup,
  585. "linebuffer|linebuffered|line-buffer|line-buffered" => \$opt::linebuffer,
  586. "tmux" => \$opt::tmux,
  587. "null|0" => \$opt::0,
  588. "quote|q" => \$opt::q,
  589. # Replacement strings
  590. "parens=s" => \$opt::parens,
  591. "rpl=s" => \@opt::rpl,
  592. "plus" => \$opt::plus,
  593. "I=s" => \$opt::I,
  594. "extensionreplace|er=s" => \$opt::U,
  595. "U=s" => \$opt::retired,
  596. "basenamereplace|bnr=s" => \$opt::basenamereplace,
  597. "dirnamereplace|dnr=s" => \$opt::dirnamereplace,
  598. "basenameextensionreplace|bner=s" => \$opt::basenameextensionreplace,
  599. "seqreplace=s" => \$opt::seqreplace,
  600. "slotreplace=s" => \$opt::slotreplace,
  601. "jobs|j=s" => \$opt::jobs,
  602. "delay=f" => \$opt::delay,
  603. "sshdelay=f" => \$opt::sshdelay,
  604. "load=s" => \$opt::load,
  605. "noswap" => \$opt::noswap,
  606. "max-line-length-allowed" => \$opt::max_line_length_allowed,
  607. "number-of-cpus" => \$opt::number_of_cpus,
  608. "number-of-cores" => \$opt::number_of_cores,
  609. "use-cpus-instead-of-cores" => \$opt::use_cpus_instead_of_cores,
  610. "shellquote|shell_quote|shell-quote" => \$opt::shellquote,
  611. "nice=i" => \$opt::nice,
  612. "timeout=s" => \$opt::timeout,
  613. "tag" => \$opt::tag,
  614. "tagstring|tag-string=s" => \$opt::tagstring,
  615. "onall" => \$opt::onall,
  616. "nonall" => \$opt::nonall,
  617. "filter-hosts|filterhosts|filter-host" => \$opt::filter_hosts,
  618. "sshlogin|S=s" => \@opt::sshlogin,
  619. "sshloginfile|slf=s" => \@opt::sshloginfile,
  620. "controlmaster|M" => \$opt::controlmaster,
  621. "return=s" => \@opt::return,
  622. "trc=s" => \@opt::trc,
  623. "transfer" => \$opt::transfer,
  624. "cleanup" => \$opt::cleanup,
  625. "basefile|bf=s" => \@opt::basefile,
  626. "B=s" => \$opt::retired,
  627. "ctrlc|ctrl-c" => \$opt::ctrlc,
  628. "noctrlc|no-ctrlc|no-ctrl-c" => \$opt::noctrlc,
  629. "workdir|work-dir|wd=s" => \$opt::workdir,
  630. "W=s" => \$opt::retired,
  631. "tmpdir=s" => \$opt::tmpdir,
  632. "tempdir=s" => \$opt::tmpdir,
  633. "use-compress-program|compress-program=s" => \$opt::compress_program,
  634. "use-decompress-program|decompress-program=s" => \$opt::decompress_program,
  635. "compress" => \$opt::compress,
  636. "tty" => \$opt::tty,
  637. "T" => \$opt::retired,
  638. "halt-on-error|halt=s" => \$opt::halt_on_error,
  639. "H=i" => \$opt::retired,
  640. "retries=i" => \$opt::retries,
  641. "dry-run|dryrun" => \$opt::dryrun,
  642. "progress" => \$opt::progress,
  643. "eta" => \$opt::eta,
  644. "bar" => \$opt::bar,
  645. "arg-sep|argsep=s" => \$opt::arg_sep,
  646. "arg-file-sep|argfilesep=s" => \$opt::arg_file_sep,
  647. "trim=s" => \$opt::trim,
  648. "env=s" => \@opt::env,
  649. "recordenv|record-env" => \$opt::record_env,
  650. "plain" => \$opt::plain,
  651. "profile|J=s" => \@opt::profile,
  652. "pipe|spreadstdin" => \$opt::pipe,
  653. "robin|round-robin|roundrobin" => \$opt::roundrobin,
  654. "recstart=s" => \$opt::recstart,
  655. "recend=s" => \$opt::recend,
  656. "regexp|regex" => \$opt::regexp,
  657. "remove-rec-sep|removerecsep|rrs" => \$opt::remove_rec_sep,
  658. "files|output-as-files|outputasfiles" => \$opt::files,
  659. "block|block-size|blocksize=s" => \$opt::blocksize,
  660. "tollef" => \$opt::retired,
  661. "gnu" => \$opt::gnu,
  662. "xapply" => \$opt::xapply,
  663. "bibtex" => \$opt::bibtex,
  664. "nn|nonotice|no-notice" => \$opt::no_notice,
  665. # xargs-compatibility - implemented, man, testsuite
  666. "max-procs|P=s" => \$opt::jobs,
  667. "delimiter|d=s" => \$opt::d,
  668. "max-chars|s=i" => \$opt::max_chars,
  669. "arg-file|a=s" => \@opt::a,
  670. "no-run-if-empty|r" => \$opt::r,
  671. "replace|i:s" => \$opt::i,
  672. "E=s" => \$opt::eof,
  673. "eof|e:s" => \$opt::eof,
  674. "max-args|n=i" => \$opt::max_args,
  675. "max-replace-args|N=i" => \$opt::max_replace_args,
  676. "colsep|col-sep|C=s" => \$opt::colsep,
  677. "help|h" => \$opt::help,
  678. "L=f" => \$opt::L,
  679. "max-lines|l:f" => \$opt::max_lines,
  680. "interactive|p" => \$opt::p,
  681. "verbose|t" => \$opt::verbose,
  682. "version|V" => \$opt::version,
  683. "minversion|min-version=i" => \$opt::minversion,
  684. "show-limits|showlimits" => \$opt::show_limits,
  685. "exit|x" => \$opt::x,
  686. # Semaphore
  687. "semaphore" => \$opt::semaphore,
  688. "semaphoretimeout=i" => \$opt::semaphoretimeout,
  689. "semaphorename|id=s" => \$opt::semaphorename,
  690. "fg" => \$opt::fg,
  691. "bg" => \$opt::bg,
  692. "wait" => \$opt::wait,
  693. # Shebang #!/usr/bin/parallel --shebang
  694. "shebang|hashbang" => \$opt::shebang,
  695. "internal-pipe-means-argfiles" => \$opt::internal_pipe_means_argfiles,
  696. "Y" => \$opt::retired,
  697. "skip-first-line" => \$opt::skip_first_line,
  698. "header=s" => \$opt::header,
  699. "cat" => \$opt::cat,
  700. "fifo" => \$opt::fifo,
  701. "pipepart|pipe-part" => \$opt::pipepart,
  702. "hgrp|hostgroup|hostgroups" => \$opt::hostgroups,
  703. );
  704. }
  705. sub get_options_from_array {
  706. # Run GetOptions on @array
  707. # Input:
  708. # $array_ref = ref to @ARGV to parse
  709. # @keep_only = Keep only these options
  710. # Uses:
  711. # @ARGV
  712. # Returns:
  713. # true if parsing worked
  714. # false if parsing failed
  715. # @$array_ref is changed
  716. my ($array_ref, @keep_only) = @_;
  717. if(not @$array_ref) {
  718. # Empty array: No need to look more at that
  719. return 1;
  720. }
  721. # A bit of shuffling of @ARGV needed as GetOptionsFromArray is not
  722. # supported everywhere
  723. my @save_argv;
  724. my $this_is_ARGV = (\@::ARGV == $array_ref);
  725. if(not $this_is_ARGV) {
  726. @save_argv = @::ARGV;
  727. @::ARGV = @{$array_ref};
  728. }
  729. # If @keep_only set: Ignore all values except @keep_only
  730. my %options = options_hash();
  731. if(@keep_only) {
  732. my (%keep,@dummy);
  733. @keep{@keep_only} = @keep_only;
  734. for my $k (grep { not $keep{$_} } keys %options) {
  735. # Store the value of the option in @dummy
  736. $options{$k} = \@dummy;
  737. }
  738. }
  739. my $retval = GetOptions(%options);
  740. if(not $this_is_ARGV) {
  741. @{$array_ref} = @::ARGV;
  742. @::ARGV = @save_argv;
  743. }
  744. return $retval;
  745. }
  746. sub parse_options {
  747. # Returns: N/A
  748. # Defaults:
  749. $Global::version = 20141122;
  750. $Global::progname = 'parallel';
  751. $Global::infinity = 2**31;
  752. $Global::debug = 0;
  753. $Global::verbose = 0;
  754. $Global::quoting = 0;
  755. # Read only table with default --rpl values
  756. %Global::replace =
  757. (
  758. '{}' => '',
  759. '{#}' => '1 $_=$job->seq()',
  760. '{%}' => '1 $_=$job->slot()',
  761. '{/}' => 's:.*/::',
  762. '{//}' => '$Global::use{"File::Basename"} ||= eval "use File::Basename; 1;"; $_ = dirname($_);',
  763. '{/.}' => 's:.*/::; s:\.[^/.]+$::;',
  764. '{.}' => 's:\.[^/.]+$::',
  765. );
  766. %Global::plus =
  767. (
  768. # {} = {+/}/{/}
  769. # = {.}.{+.} = {+/}/{/.}.{+.}
  770. # = {..}.{+..} = {+/}/{/..}.{+..}
  771. # = {...}.{+...} = {+/}/{/...}.{+...}
  772. '{+/}' => 's:/[^/]*$::',
  773. '{+.}' => 's:.*\.::',
  774. '{+..}' => 's:.*\.([^.]*\.):$1:',
  775. '{+...}' => 's:.*\.([^.]*\.[^.]*\.):$1:',
  776. '{..}' => 's:\.[^/.]+$::; s:\.[^/.]+$::',
  777. '{...}' => 's:\.[^/.]+$::; s:\.[^/.]+$::; s:\.[^/.]+$::',
  778. '{/..}' => 's:.*/::; s:\.[^/.]+$::; s:\.[^/.]+$::',
  779. '{/...}' => 's:.*/::; s:\.[^/.]+$::; s:\.[^/.]+$::; s:\.[^/.]+$::',
  780. );
  781. # Modifiable copy of %Global::replace
  782. %Global::rpl = %Global::replace;
  783. $Global::parens = "{==}";
  784. $/="\n";
  785. $Global::ignore_empty = 0;
  786. $Global::interactive = 0;
  787. $Global::stderr_verbose = 0;
  788. $Global::default_simultaneous_sshlogins = 9;
  789. $Global::exitstatus = 0;
  790. $Global::halt_on_error_exitstatus = 0;
  791. $Global::arg_sep = ":::";
  792. $Global::arg_file_sep = "::::";
  793. $Global::trim = 'n';
  794. $Global::max_jobs_running = 0;
  795. $Global::job_already_run = '';
  796. $ENV{'TMPDIR'} ||= "/tmp";
  797. @ARGV=read_options();
  798. if(@opt::v) { $Global::verbose = $#opt::v+1; } # Convert -v -v to v=2
  799. $Global::debug = $opt::D;
  800. $Global::shell = $ENV{'PARALLEL_SHELL'} || parent_shell($$) || $ENV{'SHELL'} || "/bin/sh";
  801. if(defined $opt::X) { $Global::ContextReplace = 1; }
  802. if(defined $opt::silent) { $Global::verbose = 0; }
  803. if(defined $opt::0) { $/ = "\0"; }
  804. if(defined $opt::d) { my $e="sprintf \"$opt::d\""; $/ = eval $e; }
  805. if(defined $opt::p) { $Global::interactive = $opt::p; }
  806. if(defined $opt::q) { $Global::quoting = 1; }
  807. if(defined $opt::r) { $Global::ignore_empty = 1; }
  808. if(defined $opt::verbose) { $Global::stderr_verbose = 1; }
  809. # Deal with --rpl
  810. sub rpl {
  811. # Modify %Global::rpl
  812. # Replace $old with $new
  813. my ($old,$new) = @_;
  814. if($old ne $new) {
  815. $Global::rpl{$new} = $Global::rpl{$old};
  816. delete $Global::rpl{$old};
  817. }
  818. }
  819. if(defined $opt::parens) { $Global::parens = $opt::parens; }
  820. my $parenslen = 0.5*length $Global::parens;
  821. $Global::parensleft = substr($Global::parens,0,$parenslen);
  822. $Global::parensright = substr($Global::parens,$parenslen);
  823. if(defined $opt::plus) { %Global::rpl = (%Global::plus,%Global::rpl); }
  824. if(defined $opt::I) { rpl('{}',$opt::I); }
  825. if(defined $opt::U) { rpl('{.}',$opt::U); }
  826. if(defined $opt::i and $opt::i) { rpl('{}',$opt::i); }
  827. if(defined $opt::basenamereplace) { rpl('{/}',$opt::basenamereplace); }
  828. if(defined $opt::dirnamereplace) { rpl('{//}',$opt::dirnamereplace); }
  829. if(defined $opt::seqreplace) { rpl('{#}',$opt::seqreplace); }
  830. if(defined $opt::slotreplace) { rpl('{%}',$opt::slotreplace); }
  831. if(defined $opt::basenameextensionreplace) {
  832. rpl('{/.}',$opt::basenameextensionreplace);
  833. }
  834. for(@opt::rpl) {
  835. # Create $Global::rpl entries for --rpl options
  836. # E.g: "{..} s:\.[^.]+$:;s:\.[^.]+$:;"
  837. my ($shorthand,$long) = split/ /,$_,2;
  838. $Global::rpl{$shorthand} = $long;
  839. }
  840. if(defined $opt::eof) { $Global::end_of_file_string = $opt::eof; }
  841. if(defined $opt::max_args) { $Global::max_number_of_args = $opt::max_args; }
  842. if(defined $opt::timeout) { $Global::timeoutq = TimeoutQueue->new($opt::timeout); }
  843. if(defined $opt::tmpdir) { $ENV{'TMPDIR'} = $opt::tmpdir; }
  844. if(defined $opt::help) { die_usage(); }
  845. if(defined $opt::colsep) { $Global::trim = 'lr'; }
  846. if(defined $opt::header) { $opt::colsep = defined $opt::colsep ? $opt::colsep : "\t"; }
  847. if(defined $opt::trim) { $Global::trim = $opt::trim; }
  848. if(defined $opt::arg_sep) { $Global::arg_sep = $opt::arg_sep; }
  849. if(defined $opt::arg_file_sep) { $Global::arg_file_sep = $opt::arg_file_sep; }
  850. if(defined $opt::number_of_cpus) { print SSHLogin::no_of_cpus(),"\n"; wait_and_exit(0); }
  851. if(defined $opt::number_of_cores) {
  852. print SSHLogin::no_of_cores(),"\n"; wait_and_exit(0);
  853. }
  854. if(defined $opt::max_line_length_allowed) {
  855. print Limits::Command::real_max_length(),"\n"; wait_and_exit(0);
  856. }
  857. if(defined $opt::version) { version(); wait_and_exit(0); }
  858. if(defined $opt::bibtex) { bibtex(); wait_and_exit(0); }
  859. if(defined $opt::record_env) { record_env(); wait_and_exit(0); }
  860. if(defined $opt::show_limits) { show_limits(); }
  861. if(@opt::sshlogin) { @Global::sshlogin = @opt::sshlogin; }
  862. if(@opt::sshloginfile) { read_sshloginfiles(@opt::sshloginfile); }
  863. if(@opt::return) { push @Global::ret_files, @opt::return; }
  864. if(not defined $opt::recstart and
  865. not defined $opt::recend) { $opt::recend = "\n"; }
  866. if(not defined $opt::blocksize) { $opt::blocksize = "1M"; }
  867. $opt::blocksize = multiply_binary_prefix($opt::blocksize);
  868. if(defined $opt::controlmaster) { $opt::noctrlc = 1; }
  869. if(defined $opt::semaphore) { $Global::semaphore = 1; }
  870. if(defined $opt::semaphoretimeout) { $Global::semaphore = 1; }
  871. if(defined $opt::semaphorename) { $Global::semaphore = 1; }
  872. if(defined $opt::fg) { $Global::semaphore = 1; }
  873. if(defined $opt::bg) { $Global::semaphore = 1; }
  874. if(defined $opt::wait) { $Global::semaphore = 1; }
  875. if(defined $opt::halt_on_error and
  876. $opt::halt_on_error=~/%/) { $opt::halt_on_error /= 100; }
  877. if(defined $opt::timeout and $opt::timeout !~ /^\d+(\.\d+)?%?$/) {
  878. ::error("--timeout must be seconds or percentage\n");
  879. wait_and_exit(255);
  880. }
  881. if(defined $opt::minversion) {
  882. print $Global::version,"\n";
  883. if($Global::version < $opt::minversion) {
  884. wait_and_exit(255);
  885. } else {
  886. wait_and_exit(0);
  887. }
  888. }
  889. if(not defined $opt::delay) {
  890. # Set --delay to --sshdelay if not set
  891. $opt::delay = $opt::sshdelay;
  892. }
  893. if($opt::compress_program) {
  894. $opt::compress = 1;
  895. $opt::decompress_program ||= $opt::compress_program." -dc";
  896. }
  897. if($opt::compress) {
  898. my ($compress, $decompress) = find_compression_program();
  899. $opt::compress_program ||= $compress;
  900. $opt::decompress_program ||= $decompress;
  901. }
  902. if(defined $opt::nonall) {
  903. # Append a dummy empty argument
  904. push @ARGV, $Global::arg_sep, "";
  905. }
  906. if(defined $opt::tty) {
  907. # Defaults for --tty: -j1 -u
  908. # Can be overridden with -jXXX -g
  909. if(not defined $opt::jobs) {
  910. $opt::jobs = 1;
  911. }
  912. if(not defined $opt::group) {
  913. $opt::ungroup = 0;
  914. }
  915. }
  916. if(@opt::trc) {
  917. push @Global::ret_files, @opt::trc;
  918. $opt::transfer = 1;
  919. $opt::cleanup = 1;
  920. }
  921. if(defined $opt::max_lines) {
  922. if($opt::max_lines eq "-0") {
  923. # -l -0 (swallowed -0)
  924. $opt::max_lines = 1;
  925. $opt::0 = 1;
  926. $/ = "\0";
  927. } elsif ($opt::max_lines == 0) {
  928. # If not given (or if 0 is given) => 1
  929. $opt::max_lines = 1;
  930. }
  931. $Global::max_lines = $opt::max_lines;
  932. if(not $opt::pipe) {
  933. # --pipe -L means length of record - not max_number_of_args
  934. $Global::max_number_of_args ||= $Global::max_lines;
  935. }
  936. }
  937. # Read more than one arg at a time (-L, -N)
  938. if(defined $opt::L) {
  939. $Global::max_lines = $opt::L;
  940. if(not $opt::pipe) {
  941. # --pipe -L means length of record - not max_number_of_args
  942. $Global::max_number_of_args ||= $Global::max_lines;
  943. }
  944. }
  945. if(defined $opt::max_replace_args) {
  946. $Global::max_number_of_args = $opt::max_replace_args;
  947. $Global::ContextReplace = 1;
  948. }
  949. if((defined $opt::L or defined $opt::max_replace_args)
  950. and
  951. not ($opt::xargs or $opt::m)) {
  952. $Global::ContextReplace = 1;
  953. }
  954. if(defined $opt::tag and not defined $opt::tagstring) {
  955. $opt::tagstring = "\257<\257>"; # Default = {}
  956. }
  957. if(defined $opt::pipepart and
  958. (defined $opt::L or defined $opt::max_lines
  959. or defined $opt::max_replace_args)) {
  960. ::error("--pipepart is incompatible with --max-replace-args, ",
  961. "--max-lines, and -L.\n");
  962. wait_and_exit(255);
  963. }
  964. if(grep /^$Global::arg_sep$|^$Global::arg_file_sep$/o, @ARGV) {
  965. # Deal with ::: and ::::
  966. @ARGV=read_args_from_command_line();
  967. }
  968. # Semaphore defaults
  969. # Must be done before computing number of processes and max_line_length
  970. # because when running as a semaphore GNU Parallel does not read args
  971. $Global::semaphore ||= ($0 =~ m:(^|/)sem$:); # called as 'sem'
  972. if($Global::semaphore) {
  973. # A semaphore does not take input from neither stdin nor file
  974. @opt::a = ("/dev/null");
  975. push(@Global::unget_argv, [Arg->new("")]);
  976. $Semaphore::timeout = $opt::semaphoretimeout || 0;
  977. if(defined $opt::semaphorename) {
  978. $Semaphore::name = $opt::semaphorename;
  979. } else {
  980. $Semaphore::name = `tty`;
  981. chomp $Semaphore::name;
  982. }
  983. $Semaphore::fg = $opt::fg;
  984. $Semaphore::wait = $opt::wait;
  985. $Global::default_simultaneous_sshlogins = 1;
  986. if(not defined $opt::jobs) {
  987. $opt::jobs = 1;
  988. }
  989. if($Global::interactive and $opt::bg) {
  990. ::error("Jobs running in the ".
  991. "background cannot be interactive.\n");
  992. ::wait_and_exit(255);
  993. }
  994. }
  995. if(defined $opt::eta) {
  996. $opt::progress = $opt::eta;
  997. }
  998. if(defined $opt::bar) {
  999. $opt::progress = $opt::bar;
  1000. }
  1001. if(defined $opt::retired) {
  1002. ::error("-g has been retired. Use --group.\n");
  1003. ::error("-B has been retired. Use --bf.\n");
  1004. ::error("-T has been retired. Use --tty.\n");
  1005. ::error("-U has been retired. Use --er.\n");
  1006. ::error("-W has been retired. Use --wd.\n");
  1007. ::error("-Y has been retired. Use --shebang.\n");
  1008. ::error("-H has been retired. Use --halt.\n");
  1009. ::error("--tollef has been retired. Use -u -q --arg-sep -- and --load for -l.\n");
  1010. ::wait_and_exit(255);
  1011. }
  1012. citation_notice();
  1013. parse_sshlogin();
  1014. parse_env_var();
  1015. if(remote_hosts() and ($opt::X or $opt::m or $opt::xargs)) {
  1016. # As we do not know the max line length on the remote machine
  1017. # long commands generated by xargs may fail
  1018. # If opt_N is set, it is probably safe
  1019. ::warning("Using -X or -m with --sshlogin may fail.\n");
  1020. }
  1021. if(not defined $opt::jobs) {
  1022. $opt::jobs = "100%";
  1023. }
  1024. open_joblog();
  1025. }
  1026. sub env_quote {
  1027. # Input:
  1028. # $v = value to quote
  1029. # Returns:
  1030. # $v = value quoted as environment variable
  1031. my $v = $_[0];
  1032. $v =~ s/([\\])/\\$1/g;
  1033. $v =~ s/([\[\] \#\'\&\<\>\(\)\;\{\}\t\"\$\`\*\174\!\?\~])/\\$1/g;
  1034. $v =~ s/\n/"\n"/g;
  1035. return $v;
  1036. }
  1037. sub record_env {
  1038. # Record current %ENV-keys in ~/.parallel/ignored_vars
  1039. # Returns: N/A
  1040. my $ignore_filename = $ENV{'HOME'} . "/.parallel/ignored_vars";
  1041. if(open(my $vars_fh, ">", $ignore_filename)) {
  1042. print $vars_fh map { $_,"\n" } keys %ENV;
  1043. } else {
  1044. ::error("Cannot write to $ignore_filename\n");
  1045. ::wait_and_exit(255);
  1046. }
  1047. }
  1048. sub parse_env_var {
  1049. # Parse --env and set $Global::envvar, $Global::envwarn and $Global::envvarlen
  1050. #
  1051. # Bash functions must be parsed to export them remotely
  1052. # Pre-shellshock style bash function:
  1053. # myfunc=() {...
  1054. # Post-shellshock style bash function:
  1055. # BASH_FUNC_myfunc()=() {...
  1056. #
  1057. # Uses:
  1058. # $Global::envvar = eval string that will set variables in both bash and csh
  1059. # $Global::envwarn = If functions are used: Give warning in csh
  1060. # $Global::envvarlen = length of $Global::envvar
  1061. # @opt::env
  1062. # $Global::shell
  1063. # %ENV
  1064. # Returns: N/A
  1065. $Global::envvar = "";
  1066. $Global::envwarn = "";
  1067. my @vars = ('parallel_bash_environment');
  1068. for my $varstring (@opt::env) {
  1069. # Split up --env VAR1,VAR2
  1070. push @vars, split /,/, $varstring;
  1071. }
  1072. if(grep { /^_$/ } @vars) {
  1073. # --env _
  1074. # Include all vars that are not in a clean environment
  1075. if(open(my $vars_fh, "<", $ENV{'HOME'} . "/.parallel/ignored_vars")) {
  1076. my @ignore = <$vars_fh>;
  1077. chomp @ignore;
  1078. my %ignore;
  1079. @ignore{@ignore} = @ignore;
  1080. close $vars_fh;
  1081. push @vars, grep { not defined $ignore{$_} } keys %ENV;
  1082. @vars = grep { not /^_$/ } @vars;
  1083. } else {
  1084. ::error("Run '$Global::progname --record-env' in a clean environment first.\n");
  1085. ::wait_and_exit(255);
  1086. }
  1087. }
  1088. # Duplicate vars as BASH functions to include post-shellshock functions.
  1089. # So --env myfunc should also look for BASH_FUNC_myfunc()
  1090. @vars = map { $_, "BASH_FUNC_$_()" } @vars;
  1091. # Keep only defined variables
  1092. @vars = grep { defined($ENV{$_}) } @vars;
  1093. # Pre-shellshock style bash function:
  1094. # myfunc=() { echo myfunc
  1095. # }
  1096. # Post-shellshock style bash function:
  1097. # BASH_FUNC_myfunc()=() { echo myfunc
  1098. # }
  1099. my @bash_functions = grep { substr($ENV{$_},0,4) eq "() {" } @vars;
  1100. my @non_functions = grep { substr($ENV{$_},0,4) ne "() {" } @vars;
  1101. if(@bash_functions) {
  1102. # Functions are not supported for all shells
  1103. if($Global::shell !~ m:/(bash|rbash|zsh|rzsh|dash|ksh):) {
  1104. ::warning("Shell functions may not be supported in $Global::shell\n");
  1105. }
  1106. }
  1107. # Pre-shellschock names are without ()
  1108. my @bash_pre_shellshock = grep { not /\(\)/ } @bash_functions;
  1109. # Post-shellschock names are with ()
  1110. my @bash_post_shellshock = grep { /\(\)/ } @bash_functions;
  1111. my @qcsh = (map { my $a=$_; "setenv $a " . env_quote($ENV{$a}) }
  1112. grep { not /^parallel_bash_environment$/ } @non_functions);
  1113. my @qbash = (map { my $a=$_; "export $a=" . env_quote($ENV{$a}) }
  1114. @non_functions, @bash_pre_shellshock);
  1115. push @qbash, map { my $a=$_; "eval $a\"\$$a\"" } @bash_pre_shellshock;
  1116. push @qbash, map { /BASH_FUNC_(.*)\(\)/; "$1 $ENV{$_}" } @bash_post_shellshock;
  1117. #ssh -tt -oLogLevel=quiet lo 'eval `echo PARALLEL_SEQ='$PARALLEL_SEQ'\;export PARALLEL_SEQ\; PARALLEL_PID='$PARALLEL_PID'\;export PARALLEL_PID` ;' tty\ \>/dev/null\ \&\&\ stty\ isig\ -onlcr\ -echo\;echo\ \$SHELL\ \|\ grep\ \"/t\\\{0,1\\\}csh\"\ \>\ /dev/null\ \&\&\ setenv\ BASH_FUNC_myfunc\ \\\(\\\)\\\ \\\{\\\ \\\ echo\\\ a\"'
  1118. #'\"\\\}\ \|\|\ myfunc\(\)\ \{\ \ echo\ a'
  1119. #'\}\ \;myfunc\ 1;
  1120. # Check if any variables contain \n
  1121. if(my @v = map { s/BASH_FUNC_(.*)\(\)/$1/; $_ } grep { $ENV{$_}=~/\n/ } @vars) {
  1122. # \n is bad for csh and will cause it to fail.
  1123. $Global::envwarn = ::shell_quote_scalar(q{echo $SHELL | egrep "/t?csh" > /dev/null && echo CSH/TCSH DO NOT SUPPORT newlines IN VARIABLES/FUNCTIONS. Unset }."@v".q{ && exec false;}."\n\n") . $Global::envwarn;
  1124. }
  1125. if(not @qcsh) { push @qcsh, "true"; }
  1126. if(not @qbash) { push @qbash, "true"; }
  1127. # Create lines like:
  1128. # echo $SHELL | grep "/t\\{0,1\\}csh" >/dev/null && setenv V1 val1 && setenv V2 val2 || export V1=val1 && export V2=val2 ; echo "$V1$V2"
  1129. if(@vars) {
  1130. $Global::envvar .=
  1131. join"",
  1132. (q{echo $SHELL | grep "/t\\{0,1\\}csh" > /dev/null && }
  1133. . join(" && ", @qcsh)
  1134. . q{ || }
  1135. . join(" && ", @qbash)
  1136. .q{;});
  1137. if($ENV{'parallel_bash_environment'}) {
  1138. $Global::envvar .= 'eval "$parallel_bash_environment";'."\n";
  1139. }
  1140. }
  1141. $Global::envvarlen = length $Global::envvar;
  1142. }
  1143. sub open_joblog {
  1144. # Open joblog as specified by --joblog
  1145. # Uses:
  1146. # $opt::resume
  1147. # $opt::resume_failed
  1148. # $opt::joblog
  1149. # $opt::results
  1150. # $Global::job_already_run
  1151. # %Global::fd
  1152. my $append = 0;
  1153. if(($opt::resume or $opt::resume_failed)
  1154. and
  1155. not ($opt::joblog or $opt::results)) {
  1156. ::error("--resume and --resume-failed require --joblog or --results.\n");
  1157. ::wait_and_exit(255);
  1158. }
  1159. if($opt::joblog) {
  1160. if($opt::resume || $opt::resume_failed) {
  1161. if(open(my $joblog_fh, "<", $opt::joblog)) {
  1162. # Read the joblog
  1163. $append = <$joblog_fh>; # If there is a header: Open as append later
  1164. my $joblog_regexp;
  1165. if($opt::resume_failed) {
  1166. # Make a regexp that only matches commands with exit+signal=0
  1167. # 4 host 1360490623.067 3.445 1023 1222 0 0 command
  1168. $joblog_regexp='^(\d+)(?:\t[^\t]+){5}\t0\t0\t';
  1169. } else {
  1170. # Just match the job number
  1171. $joblog_regexp='^(\d+)';
  1172. }
  1173. while(<$joblog_fh>) {
  1174. if(/$joblog_regexp/o) {
  1175. # This is 30% faster than set_job_already_run($1);
  1176. vec($Global::job_already_run,($1||0),1) = 1;
  1177. } elsif(not /\d+\s+[^\s]+\s+([0-9.]+\s+){6}/) {
  1178. ::error("Format of '$opt::joblog' is wrong: $_");
  1179. ::wait_and_exit(255);
  1180. }
  1181. }
  1182. close $joblog_fh;
  1183. }
  1184. }
  1185. if($append) {
  1186. # Append to joblog
  1187. if(not open($Global::joblog, ">>", $opt::joblog)) {
  1188. ::error("Cannot append to --joblog $opt::joblog.\n");
  1189. ::wait_and_exit(255);
  1190. }
  1191. } else {
  1192. if($opt::joblog eq "-") {
  1193. # Use STDOUT as joblog
  1194. $Global::joblog = $Global::fd{1};
  1195. } elsif(not open($Global::joblog, ">", $opt::joblog)) {
  1196. # Overwrite the joblog
  1197. ::error("Cannot write to --joblog $opt::joblog.\n");
  1198. ::wait_and_exit(255);
  1199. }
  1200. print $Global::joblog
  1201. join("\t", "Seq", "Host", "Starttime", "JobRuntime",
  1202. "Send", "Receive", "Exitval", "Signal", "Command"
  1203. ). "\n";
  1204. }
  1205. }
  1206. }
  1207. sub find_compression_program {
  1208. # Find a fast compression program
  1209. # Returns:
  1210. # $compress_program = compress program with options
  1211. # $decompress_program = decompress program with options
  1212. # Search for these. Sorted by speed
  1213. my @prg = qw(lzop pigz pxz gzip plzip pbzip2 lzma xz lzip bzip2);
  1214. for my $p (@prg) {
  1215. if(which($p)) {
  1216. return ("$p -c -1","$p -dc");
  1217. }
  1218. }
  1219. # Fall back to cat
  1220. return ("cat","cat");
  1221. }
  1222. sub read_options {
  1223. # Read options from command line, profile and $PARALLEL
  1224. # Uses:
  1225. # $opt::shebang_wrap
  1226. # $opt::shebang
  1227. # @ARGV
  1228. # $opt::plain
  1229. # @opt::profile
  1230. # $ENV{'HOME'}
  1231. # $ENV{'PARALLEL'}
  1232. # Returns:
  1233. # @ARGV_no_opt = @ARGV without --options
  1234. # This must be done first as this may exec myself
  1235. if(defined $ARGV[0] and ($ARGV[0] =~ /^--shebang/ or
  1236. $ARGV[0] =~ /^--shebang-?wrap/ or
  1237. $ARGV[0] =~ /^--hashbang/)) {
  1238. # Program is called from #! line in script
  1239. # remove --shebang-wrap if it is set
  1240. $opt::shebang_wrap = ($ARGV[0] =~ s/^--shebang-?wrap *//);
  1241. # remove --shebang if it is set
  1242. $opt::shebang = ($ARGV[0] =~ s/^--shebang *//);
  1243. # remove --hashbang if it is set
  1244. $opt::shebang .= ($ARGV[0] =~ s/^--hashbang *//);
  1245. if($opt::shebang) {
  1246. my $argfile = shell_quote_scalar(pop @ARGV);
  1247. # exec myself to split $ARGV[0] into separate fields
  1248. exec "$0 --skip-first-line -a $argfile @ARGV";
  1249. }
  1250. if($opt::shebang_wrap) {
  1251. my @options;
  1252. my @parser;
  1253. if ($^O eq 'freebsd') {
  1254. # FreeBSD's #! puts different values in @ARGV than Linux' does.
  1255. my @nooptions = @ARGV;
  1256. get_options_from_array(\@nooptions);
  1257. while($#ARGV > $#nooptions) {
  1258. push @options, shift @ARGV;
  1259. }
  1260. while(@ARGV and $ARGV[0] ne ":::") {
  1261. push @parser, shift @ARGV;
  1262. }
  1263. if(@ARGV and $ARGV[0] eq ":::") {
  1264. shift @ARGV;
  1265. }
  1266. } else {
  1267. @options = shift @ARGV;
  1268. }
  1269. my $script = shell_quote_scalar(shift @ARGV);
  1270. # exec myself to split $ARGV[0] into separate fields
  1271. exec "$0 --internal-pipe-means-argfiles @options @parser $script ::: @ARGV";
  1272. }
  1273. }
  1274. Getopt::Long::Configure("bundling","require_order");
  1275. my @ARGV_copy = @ARGV;
  1276. # Check if there is a --profile to set @opt::profile
  1277. get_options_from_array(\@ARGV_copy,"profile|J=s","plain") || die_usage();
  1278. my @ARGV_profile = ();
  1279. my @ARGV_env = ();
  1280. if(not $opt::plain) {
  1281. # Add options from .parallel/config and other profiles
  1282. my @config_profiles = (
  1283. "/etc/parallel/config",
  1284. $ENV{'HOME'}."/.parallel/config",
  1285. $ENV{'HOME'}."/.parallelrc");
  1286. my @profiles = @config_profiles;
  1287. if(@opt::profile) {
  1288. # --profile overrides default profiles
  1289. @profiles = ();
  1290. for my $profile (@opt::profile) {
  1291. if(-r $profile) {
  1292. push @profiles, $profile;
  1293. } else {
  1294. push @profiles, $ENV{'HOME'}."/.parallel/".$profile;
  1295. }
  1296. }
  1297. }
  1298. for my $profile (@profiles) {
  1299. if(-r $profile) {
  1300. open (my $in_fh, "<", $profile) || ::die_bug("read-profile: $profile");
  1301. while(<$in_fh>) {
  1302. /^\s*\#/ and next;
  1303. chomp;
  1304. push @ARGV_profile, shellwords($_);
  1305. }
  1306. close $in_fh;
  1307. } else {
  1308. if(grep /^$profile$/, @config_profiles) {
  1309. # config file is not required to exist
  1310. } else {
  1311. ::error("$profile not readable.\n");
  1312. wait_and_exit(255);
  1313. }
  1314. }
  1315. }
  1316. # Add options from shell variable $PARALLEL
  1317. if($ENV{'PARALLEL'}) {
  1318. @ARGV_env = shellwords($ENV{'PARALLEL'});
  1319. }
  1320. }
  1321. Getopt::Long::Configure("bundling","require_order");
  1322. get_options_from_array(\@ARGV_profile) || die_usage();
  1323. get_options_from_array(\@ARGV_env) || die_usage();
  1324. get_options_from_array(\@ARGV) || die_usage();
  1325. # Prepend non-options to @ARGV (such as commands like 'nice')
  1326. unshift @ARGV, @ARGV_profile, @ARGV_env;
  1327. return @ARGV;
  1328. }
  1329. sub read_args_from_command_line {
  1330. # Arguments given on the command line after:
  1331. # ::: ($Global::arg_sep)
  1332. # :::: ($Global::arg_file_sep)
  1333. # Removes the arguments from @ARGV and:
  1334. # - puts filenames into -a
  1335. # - puts arguments into files and add the files to -a
  1336. # Input:
  1337. # @::ARGV = command option ::: arg arg arg :::: argfiles
  1338. # Uses:
  1339. # $Global::arg_sep
  1340. # $Global::arg_file_sep
  1341. # $opt::internal_pipe_means_argfiles
  1342. # $opt::pipe
  1343. # @opt::a
  1344. # Returns:
  1345. # @argv_no_argsep = @::ARGV without ::: and :::: and following args
  1346. my @new_argv = ();
  1347. for(my $arg = shift @ARGV; @ARGV; $arg = shift @ARGV) {
  1348. if($arg eq $Global::arg_sep
  1349. or
  1350. $arg eq $Global::arg_file_sep) {
  1351. my $group = $arg; # This group of arguments is args or argfiles
  1352. my @group;
  1353. while(defined ($arg = shift @ARGV)) {
  1354. if($arg eq $Global::arg_sep
  1355. or
  1356. $arg eq $Global::arg_file_sep) {
  1357. # exit while loop if finding new separator
  1358. last;
  1359. } else {
  1360. # If not hitting ::: or ::::
  1361. # Append it to the group
  1362. push @group, $arg;
  1363. }
  1364. }
  1365. if($group eq $Global::arg_file_sep
  1366. or ($opt::internal_pipe_means_argfiles and $opt::pipe)
  1367. ) {
  1368. # Group of file names on the command line.
  1369. # Append args into -a
  1370. push @opt::a, @group;
  1371. } elsif($group eq $Global::arg_sep) {
  1372. # Group of arguments on the command line.
  1373. # Put them into a file.
  1374. # Create argfile
  1375. my ($outfh,$name) = ::tmpfile(SUFFIX => ".arg");
  1376. unlink($name);
  1377. # Put args into argfile
  1378. print $outfh map { $_,$/ } @group;
  1379. seek $outfh, 0, 0;
  1380. # Append filehandle to -a
  1381. push @opt::a, $outfh;
  1382. } else {
  1383. ::die_bug("Unknown command line group: $group");
  1384. }
  1385. if(defined($arg)) {
  1386. # $arg is ::: or ::::
  1387. redo;
  1388. } else {
  1389. # $arg is undef -> @ARGV empty
  1390. last;
  1391. }
  1392. }
  1393. push @new_argv, $arg;
  1394. }
  1395. # Output: @ARGV = command to run with options
  1396. return @new_argv;
  1397. }
  1398. sub cleanup {
  1399. # Returns: N/A
  1400. if(@opt::basefile) { cleanup_basefile(); }
  1401. }
  1402. sub __QUOTING_ARGUMENTS_FOR_SHELL__ {}
  1403. sub shell_quote {
  1404. # Input:
  1405. # @strings = strings to be quoted
  1406. # Output:
  1407. # @shell_quoted_strings = string quoted with \ as needed by the shell
  1408. my @strings = (@_);
  1409. for my $a (@strings) {
  1410. $a =~ s/([\002-\011\013-\032\\\#\?\`\(\)\{\}\[\]\*\>\<\~\|\; \"\!\$\&\'\202-\377])/\\$1/g;
  1411. $a =~ s/[\n]/'\n'/g; # filenames with '\n' is quoted using \'
  1412. }
  1413. return wantarray ? @strings : "@strings";
  1414. }
  1415. sub shell_quote_empty {
  1416. # Inputs:
  1417. # @strings = strings to be quoted
  1418. # Returns:
  1419. # @quoted_strings = empty strings quoted as ''.
  1420. my @strings = shell_quote(@_);
  1421. for my $a (@strings) {
  1422. if($a eq "") {
  1423. $a = "''";
  1424. }
  1425. }
  1426. return wantarray ? @strings : "@strings";
  1427. }
  1428. sub shell_quote_scalar {
  1429. # Quote the string so shell will not expand any special chars
  1430. # Inputs:
  1431. # $string = string to be quoted
  1432. # Returns:
  1433. # $shell_quoted = string quoted with \ as needed by the shell
  1434. my $a = $_[0];
  1435. if(defined $a) {
  1436. # $a =~ s/([\002-\011\013-\032\\\#\?\`\(\)\{\}\[\]\*\>\<\~\|\; \"\!\$\&\'\202-\377])/\\$1/g;
  1437. # This is 1% faster than the above
  1438. $a =~ s/[\002-\011\013-\032\\\#\?\`\(\)\{\}\[\]\*\>\<\~\|\; \"\!\$\&\'\202-\377]/\\$&/go;
  1439. $a =~ s/[\n]/'\n'/go; # filenames with '\n' is quoted using \'
  1440. }
  1441. return $a;
  1442. }
  1443. sub shell_quote_file {
  1444. # Quote the string so shell will not expand any special chars and prepend ./ if needed
  1445. # Input:
  1446. # $filename = filename to be shell quoted
  1447. # Returns:
  1448. # $quoted_filename = filename quoted with \ as needed by the shell and ./ if needed
  1449. my $a = shell_quote_scalar(shift);
  1450. if(defined $a) {
  1451. if($a =~ m:^/: or $a =~ m:^\./:) {
  1452. # /abs/path or ./rel/path => skip
  1453. } else {
  1454. # rel/path => ./rel/path
  1455. $a = "./".$a;
  1456. }
  1457. }
  1458. return $a;
  1459. }
  1460. sub shellwords {
  1461. # Input:
  1462. # $string = shell line
  1463. # Returns:
  1464. # @shell_words = $string split into words as shell would do
  1465. $Global::use{"Text::ParseWords"} ||= eval "use Text::ParseWords; 1;";
  1466. return Text::ParseWords::shellwords(@_);
  1467. }
  1468. sub __FILEHANDLES__ {}
  1469. sub save_stdin_stdout_stderr {
  1470. # Remember the original STDIN, STDOUT and STDERR
  1471. # and file descriptors opened by the shell (e.g. 3>/tmp/foo)
  1472. # Uses:
  1473. # %Global::fd
  1474. # $Global::original_stderr
  1475. # $Global::original_stdin
  1476. # Returns: N/A
  1477. # Find file descriptors that are already opened (by the shell)
  1478. for my $fdno (1..61) {
  1479. # /dev/fd/62 and above are used by bash for <(cmd)
  1480. my $fh;
  1481. # 2-argument-open is used to be compatible with old perl 5.8.0
  1482. # bug #43570: Perl 5.8.0 creates 61 files
  1483. if(open($fh,">&=$fdno")) {
  1484. $Global::fd{$fdno}=$fh;
  1485. }
  1486. }
  1487. open $Global::original_stderr, ">&", "STDERR" or
  1488. ::die_bug("Can't dup STDERR: $!");
  1489. open $Global::original_stdin, "<&", "STDIN" or
  1490. ::die_bug("Can't dup STDIN: $!");
  1491. }
  1492. sub enough_file_handles {
  1493. # Check that we have enough filehandles available for starting
  1494. # another job
  1495. # Uses:
  1496. # $opt::ungroup
  1497. # %Global::fd
  1498. # Returns:
  1499. # 1 if ungrouped (thus not needing extra filehandles)
  1500. # 0 if too few filehandles
  1501. # 1 if enough filehandles
  1502. if(not $opt::ungroup) {
  1503. my %fh;
  1504. my $enough_filehandles = 1;
  1505. # perl uses 7 filehandles for something?
  1506. # open3 uses 2 extra filehandles temporarily
  1507. # We need a filehandle for each redirected file descriptor
  1508. # (normally just STDOUT and STDERR)
  1509. for my $i (1..(7+2+keys %Global::fd)) {
  1510. $enough_filehandles &&= open($fh{$i}, "<", "/dev/null");
  1511. }
  1512. for (values %fh) { close $_; }
  1513. return $enough_filehandles;
  1514. } else {
  1515. # Ungrouped does not need extra file handles
  1516. return 1;
  1517. }
  1518. }
  1519. sub open_or_exit {
  1520. # Open a file name or exit if the file cannot be opened
  1521. # Inputs:
  1522. # $file = filehandle or filename to open
  1523. # Uses:
  1524. # $Global::stdin_in_opt_a
  1525. # $Global::original_stdin
  1526. # Returns:
  1527. # $fh = file handle to read-opened file
  1528. my $file = shift;
  1529. if($file eq "-") {
  1530. $Global::stdin_in_opt_a = 1;
  1531. return ($Global::original_stdin || *STDIN);
  1532. }
  1533. if(ref $file eq "GLOB") {
  1534. # This is an open filehandle
  1535. return $file;
  1536. }
  1537. my $fh = gensym;
  1538. if(not open($fh, "<", $file)) {
  1539. ::error("Cannot open input file `$file': No such file or directory.\n");
  1540. wait_and_exit(255);
  1541. }
  1542. return $fh;
  1543. }
  1544. sub __RUNNING_THE_JOBS_AND_PRINTING_PROGRESS__ {}
  1545. # Variable structure:
  1546. #
  1547. # $Global::running{$pid} = Pointer to Job-object
  1548. # @Global::virgin_jobs = Pointer to Job-object that have received no input
  1549. # $Global::host{$sshlogin} = Pointer to SSHLogin-object
  1550. # $Global::total_running = total number of running jobs
  1551. # $Global::total_started = total jobs started
  1552. sub init_run_jobs {
  1553. $Global::total_running = 0;
  1554. $Global::total_started = 0;
  1555. $Global::tty_taken = 0;
  1556. $SIG{USR1} = \&list_running_jobs;
  1557. $SIG{USR2} = \&toggle_progress;
  1558. if(@opt::basefile) { setup_basefile(); }
  1559. }
  1560. {
  1561. my $last_time;
  1562. my %last_mtime;
  1563. sub start_more_jobs {
  1564. # Run start_another_job() but only if:
  1565. # * not $Global::start_no_new_jobs set
  1566. # * not JobQueue is empty
  1567. # * not load on server is too high
  1568. # * not server swapping
  1569. # * not too short time since last remote login
  1570. # Uses:
  1571. # $Global::max_procs_file
  1572. # $Global::max_procs_file_last_mod
  1573. # %Global::host
  1574. # @opt::sshloginfile
  1575. # $Global::start_no_new_jobs
  1576. # $opt::filter_hosts
  1577. # $Global::JobQueue
  1578. # $opt::pipe
  1579. # $opt::load
  1580. # $opt::noswap
  1581. # $opt::delay
  1582. # $Global::newest_starttime
  1583. # Returns:
  1584. # $jobs_started = number of jobs started
  1585. my $jobs_started = 0;
  1586. my $jobs_started_this_round = 0;
  1587. if($Global::start_no_new_jobs) {
  1588. return $jobs_started;
  1589. }
  1590. if(time - ($last_time||0) > 1) {
  1591. # At most do this every second
  1592. $last_time = time;
  1593. if($Global::max_procs_file) {
  1594. # --jobs filename
  1595. my $mtime = (stat($Global::max_procs_file))[9];
  1596. if($mtime > $Global::max_procs_file_last_mod) {
  1597. # file changed: Force re-computing max_jobs_running
  1598. $Global::max_procs_file_last_mod = $mtime;
  1599. for my $sshlogin (values %Global::host) {
  1600. $sshlogin->set_max_jobs_running(undef);
  1601. }
  1602. }
  1603. }
  1604. if(@opt::sshloginfile) {
  1605. # Is --sshloginfile changed?
  1606. for my $slf (@opt::sshloginfile) {
  1607. my $actual_file = expand_slf_shorthand($slf);
  1608. my $mtime = (stat($actual_file))[9];
  1609. $last_mtime{$actual_file} ||= $mtime;
  1610. if($mtime - $last_mtime{$actual_file} > 1) {
  1611. ::debug("run","--sshloginfile $actual_file changed. reload\n");
  1612. $last_mtime{$actual_file} = $mtime;
  1613. # Reload $slf
  1614. # Empty sshlogins
  1615. @Global::sshlogin = ();
  1616. for (values %Global::host) {
  1617. # Don't start new jobs on any host
  1618. # except the ones added back later
  1619. $_->set_max_jobs_running(0);
  1620. }
  1621. # This will set max_jobs_running on the SSHlogins
  1622. read_sshloginfile($actual_file);
  1623. parse_sshlogin();
  1624. $opt::filter_hosts and filter_hosts();
  1625. setup_basefile();
  1626. }
  1627. }
  1628. }
  1629. }
  1630. do {
  1631. $jobs_started_this_round = 0;
  1632. # This will start 1 job on each --sshlogin (if possible)
  1633. # thus distribute the jobs on the --sshlogins round robin
  1634. for my $sshlogin (values %Global::host) {
  1635. if($Global::JobQueue->empty() and not $opt::pipe) {
  1636. # No more jobs in the queue
  1637. last;
  1638. }
  1639. debug("run", "Running jobs before on ", $sshlogin->string(), ": ",
  1640. $sshlogin->jobs_running(), "\n");
  1641. if ($sshlogin->jobs_running() < $sshlogin->max_jobs_running()) {
  1642. if($opt::load and $sshlogin->loadavg_too_high()) {
  1643. # The load is too high or unknown
  1644. next;
  1645. }
  1646. if($opt::noswap and $sshlogin->swapping()) {
  1647. # The server is swapping
  1648. next;
  1649. }
  1650. if($sshlogin->too_fast_remote_login()) {
  1651. # It has been too short since
  1652. next;
  1653. }
  1654. if($opt::delay and $opt::delay > ::now() - $Global::newest_starttime) {
  1655. # It has been too short since last start
  1656. next;
  1657. }
  1658. debug("run", $sshlogin->string(), " has ", $sshlogin->jobs_running(),
  1659. " out of ", $sshlogin->max_jobs_running(),
  1660. " jobs running. Start another.\n");
  1661. if(start_another_job($sshlogin) == 0) {
  1662. # No more jobs to start on this $sshlogin
  1663. debug("run","No jobs started on ", $sshlogin->string(), "\n");
  1664. next;
  1665. }
  1666. $sshlogin->inc_jobs_running();
  1667. $sshlogin->set_last_login_at(::now());
  1668. $jobs_started++;
  1669. $jobs_started_this_round++;
  1670. }
  1671. debug("run","Running jobs after on ", $sshlogin->string(), ": ",
  1672. $sshlogin->jobs_running(), " of ",
  1673. $sshlogin->max_jobs_running(), "\n");
  1674. }
  1675. } while($jobs_started_this_round);
  1676. return $jobs_started;
  1677. }
  1678. }
  1679. {
  1680. my $no_more_file_handles_warned;
  1681. sub start_another_job {
  1682. # If there are enough filehandles
  1683. # and JobQueue not empty
  1684. # and not $job is in joblog
  1685. # Then grab a job from Global::JobQueue,
  1686. # start it at sshlogin
  1687. # mark it as virgin_job
  1688. # Inputs:
  1689. # $sshlogin = the SSHLogin to start the job on
  1690. # Uses:
  1691. # $Global::JobQueue
  1692. # $opt::pipe
  1693. # $opt::results
  1694. # $opt::resume
  1695. # @Global::virgin_jobs
  1696. # Returns:
  1697. # 1 if another jobs was started
  1698. # 0 otherwise
  1699. my $sshlogin = shift;
  1700. # Do we have enough file handles to start another job?
  1701. if(enough_file_handles()) {
  1702. if($Global::JobQueue->empty() and not $opt::pipe) {
  1703. # No more commands to run
  1704. debug("start", "Not starting: JobQueue empty\n");
  1705. return 0;
  1706. } else {
  1707. my $job;
  1708. # Skip jobs already in job log
  1709. # Skip jobs already in results
  1710. do {
  1711. $job = get_job_with_sshlogin($sshlogin);
  1712. if(not defined $job) {
  1713. # No command available for that sshlogin
  1714. debug("start", "Not starting: no jobs available for ",
  1715. $sshlogin->string(), "\n");
  1716. return 0;
  1717. }
  1718. } while ($job->is_already_in_joblog()
  1719. or
  1720. ($opt::results and $opt::resume and $job->is_already_in_results()));
  1721. debug("start", "Command to run on '", $job->sshlogin()->string(), "': '",
  1722. $job->replaced(),"'\n");
  1723. if($job->start()) {
  1724. if($opt::pipe) {
  1725. push(@Global::virgin_jobs,$job);
  1726. }
  1727. debug("start", "Started as seq ", $job->seq(),
  1728. " pid:", $job->pid(), "\n");
  1729. return 1;
  1730. } else {
  1731. # Not enough processes to run the job.
  1732. # Put it back on the queue.
  1733. $Global::JobQueue->unget($job);
  1734. # Count down the number of jobs to run for this SSHLogin.
  1735. my $max = $sshlogin->max_jobs_running();
  1736. if($max > 1) { $max--; } else {
  1737. ::error("No more processes: cannot run a single job. Something is wrong.\n");
  1738. ::wait_and_exit(255);
  1739. }
  1740. $sshlogin->set_max_jobs_running($max);
  1741. # Sleep up to 300 ms to give other processes time to die
  1742. ::usleep(rand()*300);
  1743. ::warning("No more processes: ",
  1744. "Decreasing number of running jobs to $max. ",
  1745. "Raising ulimit -u or /etc/security/limits.conf may help.\n");
  1746. return 0;
  1747. }
  1748. }
  1749. } else {
  1750. # No more file handles
  1751. $no_more_file_handles_warned++ or
  1752. ::warning("No more file handles. ",
  1753. "Raising ulimit -n or /etc/security/limits.conf may help.\n");
  1754. return 0;
  1755. }
  1756. }
  1757. }
  1758. sub init_progress {
  1759. # Uses:
  1760. # $opt::bar
  1761. # Returns:
  1762. # list of computers for progress output
  1763. $|=1;
  1764. if($opt::bar) {
  1765. return("","");
  1766. }
  1767. my %progress = progress();
  1768. return ("\nComputers / CPU cores / Max jobs to run\n",
  1769. $progress{'workerlist'});
  1770. }
  1771. sub drain_job_queue {
  1772. # Uses:
  1773. # $opt::progress
  1774. # $Global::original_stderr
  1775. # $Global::total_running
  1776. # $Global::max_jobs_running
  1777. # %Global::running
  1778. # $Global::JobQueue
  1779. # %Global::host
  1780. # $Global::start_no_new_jobs
  1781. # Returns: N/A
  1782. if($opt::progress) {
  1783. print $Global::original_stderr init_progress();
  1784. }
  1785. my $last_header="";
  1786. my $sleep = 0.2;
  1787. do {
  1788. while($Global::total_running > 0) {
  1789. debug($Global::total_running, "==", scalar
  1790. keys %Global::running," slots: ", $Global::max_jobs_running);
  1791. if($opt::pipe) {
  1792. # When using --pipe sometimes file handles are not closed properly
  1793. for my $job (values %Global::running) {
  1794. close $job->fh(0,"w");
  1795. }
  1796. }
  1797. if($opt::progress) {
  1798. my %progress = progress();
  1799. if($last_header ne $progress{'header'}) {
  1800. print $Global::original_stderr "\n", $progress{'header'}, "\n";
  1801. $last_header = $progress{'header'};
  1802. }
  1803. print $Global::original_stderr "\r",$progress{'status'};
  1804. flush $Global::original_stderr;
  1805. }
  1806. if($Global::total_running < $Global::max_jobs_running
  1807. and not $Global::JobQueue->empty()) {
  1808. # These jobs may not be started because of loadavg
  1809. # or too little time between each ssh login.
  1810. if(start_more_jobs() > 0) {
  1811. # Exponential back-on if jobs were started
  1812. $sleep = $sleep/2+0.001;
  1813. }
  1814. }
  1815. # Sometimes SIGCHLD is not registered, so force reaper
  1816. $sleep = ::reap_usleep($sleep);
  1817. }
  1818. if(not $Global::JobQueue->empty()) {
  1819. # These jobs may not be started:
  1820. # * because there the --filter-hosts has removed all
  1821. if(not %Global::host) {
  1822. ::error("There are no hosts left to run on.\n");
  1823. ::wait_and_exit(255);
  1824. }
  1825. # * because of loadavg
  1826. # * because of too little time between each ssh login.
  1827. start_more_jobs();
  1828. $sleep = ::reap_usleep($sleep);
  1829. if($Global::max_jobs_running == 0) {
  1830. ::warning("There are no job slots available. Increase --jobs.\n");
  1831. }
  1832. }
  1833. } while ($Global::total_running > 0
  1834. or
  1835. not $Global::start_no_new_jobs and not $Global::JobQueue->empty());
  1836. if($opt::progress) {
  1837. my %progress = progress();
  1838. print $Global::original_stderr "\r", $progress{'status'}, "\n";
  1839. flush $Global::original_stderr;
  1840. }
  1841. }
  1842. sub toggle_progress {
  1843. # Turn on/off progress view
  1844. # Uses:
  1845. # $opt::progress
  1846. # $Global::original_stderr
  1847. # Returns: N/A
  1848. $opt::progress = not $opt::progress;
  1849. if($opt::progress) {
  1850. print $Global::original_stderr init_progress();
  1851. }
  1852. }
  1853. sub progress {
  1854. # Uses:
  1855. # $opt::bar
  1856. # $opt::eta
  1857. # %Global::host
  1858. # $Global::total_started
  1859. # Returns:
  1860. # $workerlist = list of workers
  1861. # $header = that will fit on the screen
  1862. # $status = message that will fit on the screen
  1863. if($opt::bar) {
  1864. return ("workerlist" => "", "header" => "", "status" => bar());
  1865. }
  1866. my $eta = "";
  1867. my ($status,$header)=("","");
  1868. if($opt::eta) {
  1869. my($total, $completed, $left, $pctcomplete, $avgtime, $this_eta) =
  1870. compute_eta();
  1871. $eta = sprintf("ETA: %ds Left: %d AVG: %.2fs ",
  1872. $this_eta, $left, $avgtime);
  1873. }
  1874. my $termcols = terminal_columns();
  1875. my @workers = sort keys %Global::host;
  1876. my %sshlogin = map { $_ eq ":" ? ($_=>"local") : ($_=>$_) } @workers;
  1877. my $workerno = 1;
  1878. my %workerno = map { ($_=>$workerno++) } @workers;
  1879. my $workerlist = "";
  1880. for my $w (@workers) {
  1881. $workerlist .=
  1882. $workerno{$w}.":".$sshlogin{$w} ." / ".
  1883. ($Global::host{$w}->ncpus() || "-")." / ".
  1884. $Global::host{$w}->max_jobs_running()."\n";
  1885. }
  1886. $status = "x"x($termcols+1);
  1887. if(length $status > $termcols) {
  1888. # sshlogin1:XX/XX/XX%/XX.Xs sshlogin2:XX/XX/XX%/XX.Xs sshlogin3:XX/XX/XX%/XX.Xs
  1889. $header = "Computer:jobs running/jobs completed/%of started jobs/Average seconds to complete";
  1890. $status = $eta .
  1891. join(" ",map
  1892. {
  1893. if($Global::total_started) {
  1894. my $completed = ($Global::host{$_}->jobs_completed()||0);
  1895. my $running = $Global::host{$_}->jobs_running();
  1896. my $time = $completed ? (time-$^T)/($completed) : "0";
  1897. sprintf("%s:%d/%d/%d%%/%.1fs ",
  1898. $sshlogin{$_}, $running, $completed,
  1899. ($running+$completed)*100
  1900. / $Global::total_started, $time);
  1901. }
  1902. } @workers);
  1903. }
  1904. if(length $status > $termcols) {
  1905. # 1:XX/XX/XX%/XX.Xs 2:XX/XX/XX%/XX.Xs 3:XX/XX/XX%/XX.Xs 4:XX/XX/XX%/XX.Xs
  1906. $header = "Computer:jobs running/jobs completed/%of started jobs";
  1907. $status = $eta .
  1908. join(" ",map
  1909. {
  1910. my $completed = ($Global::host{$_}->jobs_completed()||0);
  1911. my $running = $Global::host{$_}->jobs_running();
  1912. my $time = $completed ? (time-$^T)/($completed) : "0";
  1913. sprintf("%s:%d/%d/%d%%/%.1fs ",
  1914. $workerno{$_}, $running, $completed,
  1915. ($running+$completed)*100
  1916. / $Global::total_started, $time);
  1917. } @workers);
  1918. }
  1919. if(length $status > $termcols) {
  1920. # sshlogin1:XX/XX/XX% sshlogin2:XX/XX/XX% sshlogin3:XX/XX/XX%
  1921. $header = "Computer:jobs running/jobs completed/%of started jobs";
  1922. $status = $eta .
  1923. join(" ",map
  1924. { sprintf("%s:%d/%d/%d%%",
  1925. $sshlogin{$_},
  1926. $Global::host{$_}->jobs_running(),
  1927. ($Global::host{$_}->jobs_completed()||0),
  1928. ($Global::host{$_}->jobs_running()+
  1929. ($Global::host{$_}->jobs_completed()||0))*100
  1930. / $Global::total_started) }
  1931. @workers);
  1932. }
  1933. if(length $status > $termcols) {
  1934. # 1:XX/XX/XX% 2:XX/XX/XX% 3:XX/XX/XX% 4:XX/XX/XX% 5:XX/XX/XX% 6:XX/XX/XX%
  1935. $header = "Computer:jobs running/jobs completed/%of started jobs";
  1936. $status = $eta .
  1937. join(" ",map
  1938. { sprintf("%s:%d/%d/%d%%",
  1939. $workerno{$_},
  1940. $Global::host{$_}->jobs_running(),
  1941. ($Global::host{$_}->jobs_completed()||0),
  1942. ($Global::host{$_}->jobs_running()+
  1943. ($Global::host{$_}->jobs_completed()||0))*100
  1944. / $Global::total_started) }
  1945. @workers);
  1946. }
  1947. if(length $status > $termcols) {
  1948. # sshlogin1:XX/XX/XX% sshlogin2:XX/XX/XX% sshlogin3:XX/XX sshlogin4:XX/XX
  1949. $header = "Computer:jobs running/jobs completed";
  1950. $status = $eta .
  1951. join(" ",map
  1952. { sprintf("%s:%d/%d",
  1953. $sshlogin{$_}, $Global::host{$_}->jobs_running(),
  1954. ($Global::host{$_}->jobs_completed()||0)) }
  1955. @workers);
  1956. }
  1957. if(length $status > $termcols) {
  1958. # sshlogin1:XX/XX sshlogin2:XX/XX sshlogin3:XX/XX sshlogin4:XX/XX
  1959. $header = "Computer:jobs running/jobs completed";
  1960. $status = $eta .
  1961. join(" ",map
  1962. { sprintf("%s:%d/%d",
  1963. $sshlogin{$_}, $Global::host{$_}->jobs_running(),
  1964. ($Global::host{$_}->jobs_completed()||0)) }
  1965. @workers);
  1966. }
  1967. if(length $status > $termcols) {
  1968. # 1:XX/XX 2:XX/XX 3:XX/XX 4:XX/XX 5:XX/XX 6:XX/XX
  1969. $header = "Computer:jobs running/jobs completed";
  1970. $status = $eta .
  1971. join(" ",map
  1972. { sprintf("%s:%d/%d",
  1973. $workerno{$_}, $Global::host{$_}->jobs_running(),
  1974. ($Global::host{$_}->jobs_completed()||0)) }
  1975. @workers);
  1976. }
  1977. if(length $status > $termcols) {
  1978. # sshlogin1:XX sshlogin2:XX sshlogin3:XX sshlogin4:XX sshlogin5:XX
  1979. $header = "Computer:jobs completed";
  1980. $status = $eta .
  1981. join(" ",map
  1982. { sprintf("%s:%d",
  1983. $sshlogin{$_},
  1984. ($Global::host{$_}->jobs_completed()||0)) }
  1985. @workers);
  1986. }
  1987. if(length $status > $termcols) {
  1988. # 1:XX 2:XX 3:XX 4:XX 5:XX 6:XX
  1989. $header = "Computer:jobs completed";
  1990. $status = $eta .
  1991. join(" ",map
  1992. { sprintf("%s:%d",
  1993. $workerno{$_},
  1994. ($Global::host{$_}->jobs_completed()||0)) }
  1995. @workers);
  1996. }
  1997. return ("workerlist" => $workerlist, "header" => $header, "status" => $status);
  1998. }
  1999. {
  2000. my ($total, $first_completed, $smoothed_avg_time);
  2001. sub compute_eta {
  2002. # Calculate important numbers for ETA
  2003. # Returns:
  2004. # $total = number of jobs in total
  2005. # $completed = number of jobs completed
  2006. # $left = number of jobs left
  2007. # $pctcomplete = percent of jobs completed
  2008. # $avgtime = averaged time
  2009. # $eta = smoothed eta
  2010. $total ||= $Global::JobQueue->total_jobs();
  2011. my $completed = 0;
  2012. for(values %Global::host) { $completed += $_->jobs_completed() }
  2013. my $left = $total - $completed;
  2014. if(not $completed) {
  2015. return($total, $completed, $left, 0, 0, 0);
  2016. }
  2017. my $pctcomplete = $completed / $total;
  2018. $first_completed ||= time;
  2019. my $timepassed = (time - $first_completed);
  2020. my $avgtime = $timepassed / $completed;
  2021. $smoothed_avg_time ||= $avgtime;
  2022. # Smooth the eta so it does not jump wildly
  2023. $smoothed_avg_time = (1 - $pctcomplete) * $smoothed_avg_time +
  2024. $pctcomplete * $avgtime;
  2025. my $eta = int($left * $smoothed_avg_time);
  2026. return($total, $completed, $left, $pctcomplete, $avgtime, $eta);
  2027. }
  2028. }
  2029. {
  2030. my ($rev,$reset);
  2031. sub bar {
  2032. # Return:
  2033. # $status = bar with eta, completed jobs, arg and pct
  2034. $rev ||= "\033[7m";
  2035. $reset ||= "\033[0m";
  2036. my($total, $completed, $left, $pctcomplete, $avgtime, $eta) =
  2037. compute_eta();
  2038. my $arg = $Global::newest_job ?
  2039. $Global::newest_job->{'commandline'}->replace_placeholders(["\257<\257>"],0,0) : "";
  2040. # These chars mess up display in the terminal
  2041. $arg =~ tr/[\011-\016\033\302-\365]//d;
  2042. my $bar_text =
  2043. sprintf("%d%% %d:%d=%ds %s",
  2044. $pctcomplete*100, $completed, $left, $eta, $arg);
  2045. my $terminal_width = terminal_columns();
  2046. my $s = sprintf("%-${terminal_width}s",
  2047. substr($bar_text." "x$terminal_width,
  2048. 0,$terminal_width));
  2049. my $width = int($terminal_width * $pctcomplete);
  2050. substr($s,$width,0) = $reset;
  2051. my $zenity = sprintf("%-${terminal_width}s",
  2052. substr("# $eta sec $arg",
  2053. 0,$terminal_width));
  2054. $s = "\r" . $zenity . "\r" . $pctcomplete*100 . # Prefix with zenity header
  2055. "\r" . $rev . $s . $reset;
  2056. return $s;
  2057. }
  2058. }
  2059. {
  2060. my ($columns,$last_column_time);
  2061. sub terminal_columns {
  2062. # Get the number of columns of the display
  2063. # Returns:
  2064. # number of columns of the screen
  2065. if(not $columns or $last_column_time < time) {
  2066. $last_column_time = time;
  2067. $columns = $ENV{'COLUMNS'};
  2068. if(not $columns) {
  2069. my $resize = qx{ resize 2>/dev/null };
  2070. $resize =~ /COLUMNS=(\d+);/ and do { $columns = $1; };
  2071. }
  2072. $columns ||= 80;
  2073. }
  2074. return $columns;
  2075. }
  2076. }
  2077. sub get_job_with_sshlogin {
  2078. # Returns:
  2079. # next job object for $sshlogin if any available
  2080. my $sshlogin = shift;
  2081. my $job = undef;
  2082. if ($opt::hostgroups) {
  2083. my @other_hostgroup_jobs = ();
  2084. while($job = $Global::JobQueue->get()) {
  2085. if($sshlogin->in_hostgroups($job->hostgroups())) {
  2086. # Found a job for this hostgroup
  2087. last;
  2088. } else {
  2089. # This job was not in the hostgroups of $sshlogin
  2090. push @other_hostgroup_jobs, $job;
  2091. }
  2092. }
  2093. $Global::JobQueue->unget(@other_hostgroup_jobs);
  2094. if(not defined $job) {
  2095. # No more jobs
  2096. return undef;
  2097. }
  2098. } else {
  2099. $job = $Global::JobQueue->get();
  2100. if(not defined $job) {
  2101. # No more jobs
  2102. ::debug("start", "No more jobs: JobQueue empty\n");
  2103. return undef;
  2104. }
  2105. }
  2106. my $clean_command = $job->replaced();
  2107. if($clean_command =~ /^\s*$/) {
  2108. # Do not run empty lines
  2109. if(not $Global::JobQueue->empty()) {
  2110. return get_job_with_sshlogin($sshlogin);
  2111. } else {
  2112. return undef;
  2113. }
  2114. }
  2115. $job->set_sshlogin($sshlogin);
  2116. if($opt::retries and $clean_command and
  2117. $job->failed_here()) {
  2118. # This command with these args failed for this sshlogin
  2119. my ($no_of_failed_sshlogins,$min_failures) = $job->min_failed();
  2120. # Only look at the Global::host that have > 0 jobslots
  2121. if($no_of_failed_sshlogins == grep { $_->max_jobs_running() > 0 } values %Global::host
  2122. and $job->failed_here() == $min_failures) {
  2123. # It failed the same or more times on another host:
  2124. # run it on this host
  2125. } else {
  2126. # If it failed fewer times on another host:
  2127. # Find another job to run
  2128. my $nextjob;
  2129. if(not $Global::JobQueue->empty()) {
  2130. # This can potentially recurse for all args
  2131. no warnings 'recursion';
  2132. $nextjob = get_job_with_sshlogin($sshlogin);
  2133. }
  2134. # Push the command back on the queue
  2135. $Global::JobQueue->unget($job);
  2136. return $nextjob;
  2137. }
  2138. }
  2139. return $job;
  2140. }
  2141. sub __REMOTE_SSH__ {}
  2142. sub read_sshloginfiles {
  2143. # Returns: N/A
  2144. for my $s (@_) {
  2145. read_sshloginfile(expand_slf_shorthand($s));
  2146. }
  2147. }
  2148. sub expand_slf_shorthand {
  2149. my $file = shift;
  2150. if($file eq "-") {
  2151. # skip: It is stdin
  2152. } elsif($file eq "..") {
  2153. $file = $ENV{'HOME'}."/.parallel/sshloginfile";
  2154. } elsif($file eq ".") {
  2155. $file = "/etc/parallel/sshloginfile";
  2156. } elsif(not -r $file) {
  2157. if(not -r $ENV{'HOME'}."/.parallel/".$file) {
  2158. # Try prepending ~/.parallel
  2159. ::error("Cannot open $file.\n");
  2160. ::wait_and_exit(255);
  2161. } else {
  2162. $file = $ENV{'HOME'}."/.parallel/".$file;
  2163. }
  2164. }
  2165. return $file;
  2166. }
  2167. sub read_sshloginfile {
  2168. # Returns: N/A
  2169. my $file = shift;
  2170. my $close = 1;
  2171. my $in_fh;
  2172. ::debug("init","--slf ",$file);
  2173. if($file eq "-") {
  2174. $in_fh = *STDIN;
  2175. $close = 0;
  2176. } else {
  2177. if(not open($in_fh, "<", $file)) {
  2178. # Try the filename
  2179. ::error("Cannot open $file.\n");
  2180. ::wait_and_exit(255);
  2181. }
  2182. }
  2183. while(<$in_fh>) {
  2184. chomp;
  2185. /^\s*#/ and next;
  2186. /^\s*$/ and next;
  2187. push @Global::sshlogin, $_;
  2188. }
  2189. if($close) {
  2190. close $in_fh;
  2191. }
  2192. }
  2193. sub parse_sshlogin {
  2194. # Returns: N/A
  2195. my @login;
  2196. if(not @Global::sshlogin) { @Global::sshlogin = (":"); }
  2197. for my $sshlogin (@Global::sshlogin) {
  2198. # Split up -S sshlogin,sshlogin
  2199. for my $s (split /,/, $sshlogin) {
  2200. if ($s eq ".." or $s eq "-") {
  2201. # This may add to @Global::sshlogin - possibly bug
  2202. read_sshloginfile(expand_slf_shorthand($s));
  2203. } else {
  2204. push (@login, $s);
  2205. }
  2206. }
  2207. }
  2208. $Global::minimal_command_line_length = 8_000_000;
  2209. my @allowed_hostgroups;
  2210. for my $ncpu_sshlogin_string (::uniq(@login)) {
  2211. my $sshlogin = SSHLogin->new($ncpu_sshlogin_string);
  2212. my $sshlogin_string = $sshlogin->string();
  2213. if($sshlogin_string eq "") {
  2214. # This is an ssh group: -S @webservers
  2215. push @allowed_hostgroups, $sshlogin->hostgroups();
  2216. next;
  2217. }
  2218. if($Global::host{$sshlogin_string}) {
  2219. # This sshlogin has already been added:
  2220. # It is probably a host that has come back
  2221. # Set the max_jobs_running back to the original
  2222. debug("run","Already seen $sshlogin_string\n");
  2223. if($sshlogin->{'ncpus'}) {
  2224. # If ncpus set by '#/' of the sshlogin, overwrite it:
  2225. $Global::host{$sshlogin_string}->set_ncpus($sshlogin->ncpus());
  2226. }
  2227. $Global::host{$sshlogin_string}->set_max_jobs_running(undef);
  2228. next;
  2229. }
  2230. if($sshlogin_string eq ":") {
  2231. $sshlogin->set_maxlength(Limits::Command::max_length());
  2232. } else {
  2233. # If all chars needs to be quoted, every other character will be \
  2234. $sshlogin->set_maxlength(int(Limits::Command::max_length()/2));
  2235. }
  2236. $Global::minimal_command_line_length =
  2237. ::min($Global::minimal_command_line_length, $sshlogin->maxlength());
  2238. $Global::host{$sshlogin_string} = $sshlogin;
  2239. }
  2240. if(@allowed_hostgroups) {
  2241. # Remove hosts that are not in these groups
  2242. while (my ($string, $sshlogin) = each %Global::host) {
  2243. if(not $sshlogin->in_hostgroups(@allowed_hostgroups)) {
  2244. delete $Global::host{$string};
  2245. }
  2246. }
  2247. }
  2248. # debug("start", "sshlogin: ", my_dump(%Global::host),"\n");
  2249. if($opt::transfer or @opt::return or $opt::cleanup or @opt::basefile) {
  2250. if(not remote_hosts()) {
  2251. # There are no remote hosts
  2252. if(@opt::trc) {
  2253. ::warning("--trc ignored as there are no remote --sshlogin.\n");
  2254. } elsif (defined $opt::transfer) {
  2255. ::warning("--transfer ignored as there are no remote --sshlogin.\n");
  2256. } elsif (@opt::return) {
  2257. ::warning("--return ignored as there are no remote --sshlogin.\n");
  2258. } elsif (defined $opt::cleanup) {
  2259. ::warning("--cleanup ignored as there are no remote --sshlogin.\n");
  2260. } elsif (@opt::basefile) {
  2261. ::warning("--basefile ignored as there are no remote --sshlogin.\n");
  2262. }
  2263. }
  2264. }
  2265. }
  2266. sub remote_hosts {
  2267. # Return sshlogins that are not ':'
  2268. # Returns:
  2269. # list of sshlogins with ':' removed
  2270. return grep !/^:$/, keys %Global::host;
  2271. }
  2272. sub setup_basefile {
  2273. # Transfer basefiles to each $sshlogin
  2274. # This needs to be done before first jobs on $sshlogin is run
  2275. # Returns: N/A
  2276. my $cmd = "";
  2277. my $rsync_destdir;
  2278. my $workdir;
  2279. for my $sshlogin (values %Global::host) {
  2280. if($sshlogin->string() eq ":") { next }
  2281. for my $file (@opt::basefile) {
  2282. if($file !~ m:^/: and $opt::workdir eq "...") {
  2283. ::error("Work dir '...' will not work with relative basefiles\n");
  2284. ::wait_and_exit(255);
  2285. }
  2286. $workdir ||= Job->new("")->workdir();
  2287. $cmd .= $sshlogin->rsync_transfer_cmd($file,$workdir) . "&";
  2288. }
  2289. }
  2290. $cmd .= "wait;";
  2291. debug("init", "basesetup: $cmd\n");
  2292. print `$cmd`;
  2293. }
  2294. sub cleanup_basefile {
  2295. # Remove the basefiles transferred
  2296. # Returns: N/A
  2297. my $cmd="";
  2298. my $workdir = Job->new("")->workdir();
  2299. for my $sshlogin (values %Global::host) {
  2300. if($sshlogin->string() eq ":") { next }
  2301. for my $file (@opt::basefile) {
  2302. $cmd .= $sshlogin->cleanup_cmd($file,$workdir)."&";
  2303. }
  2304. }
  2305. $cmd .= "wait;";
  2306. debug("init", "basecleanup: $cmd\n");
  2307. print `$cmd`;
  2308. }
  2309. sub filter_hosts {
  2310. my(@cores, @cpus, @maxline, @echo);
  2311. my $envvar = ::shell_quote_scalar($Global::envvar);
  2312. while (my ($host, $sshlogin) = each %Global::host) {
  2313. if($host eq ":") { next }
  2314. # The 'true' is used to get the $host out later
  2315. my $sshcmd = "true $host;" . $sshlogin->sshcommand()." ".$sshlogin->serverlogin();
  2316. push(@cores, $host."\t".$sshcmd." ".$envvar." parallel --number-of-cores\n\0");
  2317. push(@cpus, $host."\t".$sshcmd." ".$envvar." parallel --number-of-cpus\n\0");
  2318. push(@maxline, $host."\t".$sshcmd." ".$envvar." parallel --max-line-length-allowed\n\0");
  2319. # 'echo' is used to get the best possible value for an ssh login time
  2320. push(@echo, $host."\t".$sshcmd." echo\n\0");
  2321. }
  2322. my ($fh, $tmpfile) = ::tmpfile(SUFFIX => ".ssh");
  2323. print $fh @cores, @cpus, @maxline, @echo;
  2324. close $fh;
  2325. # --timeout 5: Setting up an SSH connection and running a simple
  2326. # command should never take > 5 sec.
  2327. # --delay 0.1: If multiple sshlogins use the same proxy the delay
  2328. # will make it less likely to overload the ssh daemon.
  2329. # --retries 3: If the ssh daemon it overloaded, try 3 times
  2330. # -s 16000: Half of the max line on UnixWare
  2331. my $cmd = "cat $tmpfile | $0 -j0 --timeout 5 -s 16000 --joblog - --plain --delay 0.1 --retries 3 --tag --tagstring {1} -0 --colsep '\t' -k eval {2} 2>/dev/null";
  2332. ::debug("init", $cmd, "\n");
  2333. open(my $host_fh, "-|", $cmd) || ::die_bug("parallel host check: $cmd");
  2334. my (%ncores, %ncpus, %time_to_login, %maxlen, %echo, @down_hosts);
  2335. my $prepend = "";
  2336. while(<$host_fh>) {
  2337. if(/\'$/) {
  2338. # if last char = ' then append next line
  2339. # This may be due to quoting of $Global::envvar
  2340. $prepend .= $_;
  2341. next;
  2342. }
  2343. $_ = $prepend . $_;
  2344. $prepend = "";
  2345. chomp;
  2346. my @col = split /\t/, $_;
  2347. if(defined $col[6]) {
  2348. # This is a line from --joblog
  2349. # seq host time spent sent received exit signal command
  2350. # 2 : 1372607672.654 0.675 0 0 0 0 eval true\ m\;ssh\ m\ parallel\ --number-of-cores
  2351. if($col[0] eq "Seq" and $col[1] eq "Host" and
  2352. $col[2] eq "Starttime") {
  2353. # Header => skip
  2354. next;
  2355. }
  2356. # Get server from: eval true server\;
  2357. $col[8] =~ /eval true..([^;]+).;/ or ::die_bug("col8 does not contain host: $col[8]");
  2358. my $host = $1;
  2359. $host =~ tr/\\//d;
  2360. $Global::host{$host} or next;
  2361. if($col[6] eq "255" or $col[7] eq "15") {
  2362. # exit == 255 or signal == 15: ssh failed
  2363. # Remove sshlogin
  2364. ::debug("init", "--filtered $host\n");
  2365. push(@down_hosts, $host);
  2366. @down_hosts = uniq(@down_hosts);
  2367. } elsif($col[6] eq "127") {
  2368. # signal == 127: parallel not installed remote
  2369. # Set ncpus and ncores = 1
  2370. ::warning("Could not figure out ",
  2371. "number of cpus on $host. Using 1.\n");
  2372. $ncores{$host} = 1;
  2373. $ncpus{$host} = 1;
  2374. $maxlen{$host} = Limits::Command::max_length();
  2375. } elsif($col[0] =~ /^\d+$/ and $Global::host{$host}) {
  2376. # Remember how log it took to log in
  2377. # 2 : 1372607672.654 0.675 0 0 0 0 eval true\ m\;ssh\ m\ echo
  2378. $time_to_login{$host} = ::min($time_to_login{$host},$col[3]);
  2379. } else {
  2380. ::die_bug("host check unmatched long jobline: $_");
  2381. }
  2382. } elsif($Global::host{$col[0]}) {
  2383. # This output from --number-of-cores, --number-of-cpus,
  2384. # --max-line-length-allowed
  2385. # ncores: server 8
  2386. # ncpus: server 2
  2387. # maxlen: server 131071
  2388. if(not $ncores{$col[0]}) {
  2389. $ncores{$col[0]} = $col[1];
  2390. } elsif(not $ncpus{$col[0]}) {
  2391. $ncpus{$col[0]} = $col[1];
  2392. } elsif(not $maxlen{$col[0]}) {
  2393. $maxlen{$col[0]} = $col[1];
  2394. } elsif(not $echo{$col[0]}) {
  2395. $echo{$col[0]} = $col[1];
  2396. } elsif(m/perl: warning:|LANGUAGE =|LC_ALL =|LANG =|are supported and installed/) {
  2397. # Skip these:
  2398. # perl: warning: Setting locale failed.
  2399. # perl: warning: Please check that your locale settings:
  2400. # LANGUAGE = (unset),
  2401. # LC_ALL = (unset),
  2402. # LANG = "en_US.UTF-8"
  2403. # are supported and installed on your system.
  2404. # perl: warning: Falling back to the standard locale ("C").
  2405. } else {
  2406. ::die_bug("host check too many col0: $_");
  2407. }
  2408. } else {
  2409. ::die_bug("host check unmatched short jobline ($col[0]): $_");
  2410. }
  2411. }
  2412. close $host_fh;
  2413. $Global::debug or unlink $tmpfile;
  2414. delete @Global::host{@down_hosts};
  2415. @down_hosts and ::warning("Removed @down_hosts\n");
  2416. $Global::minimal_command_line_length = 8_000_000;
  2417. while (my ($sshlogin, $obj) = each %Global::host) {
  2418. if($sshlogin eq ":") { next }
  2419. $ncpus{$sshlogin} or ::die_bug("ncpus missing: ".$obj->serverlogin());
  2420. $ncores{$sshlogin} or ::die_bug("ncores missing: ".$obj->serverlogin());
  2421. $time_to_login{$sshlogin} or ::die_bug("time_to_login missing: ".$obj->serverlogin());
  2422. $maxlen{$sshlogin} or ::die_bug("maxlen missing: ".$obj->serverlogin());
  2423. if($opt::use_cpus_instead_of_cores) {
  2424. $obj->set_ncpus($ncpus{$sshlogin});
  2425. } else {
  2426. $obj->set_ncpus($ncores{$sshlogin});
  2427. }
  2428. $obj->set_time_to_login($time_to_login{$sshlogin});
  2429. $obj->set_maxlength($maxlen{$sshlogin});
  2430. $Global::minimal_command_line_length =
  2431. ::min($Global::minimal_command_line_length,
  2432. int($maxlen{$sshlogin}/2));
  2433. ::debug("init", "Timing from -S:$sshlogin ncpus:",$ncpus{$sshlogin},
  2434. " ncores:", $ncores{$sshlogin},
  2435. " time_to_login:", $time_to_login{$sshlogin},
  2436. " maxlen:", $maxlen{$sshlogin},
  2437. " min_max_len:", $Global::minimal_command_line_length,"\n");
  2438. }
  2439. }
  2440. sub onall {
  2441. sub tmp_joblog {
  2442. my $joblog = shift;
  2443. if(not defined $joblog) {
  2444. return undef;
  2445. }
  2446. my ($fh, $tmpfile) = ::tmpfile(SUFFIX => ".log");
  2447. close $fh;
  2448. return $tmpfile;
  2449. }
  2450. my @command = @_;
  2451. if($Global::quoting) {
  2452. @command = shell_quote_empty(@command);
  2453. }
  2454. # Copy all @fhlist into tempfiles
  2455. my @argfiles = ();
  2456. for my $fh (@fhlist) {
  2457. my ($outfh, $name) = ::tmpfile(SUFFIX => ".all", UNLINK => 1);
  2458. print $outfh (<$fh>);
  2459. close $outfh;
  2460. push @argfiles, $name;
  2461. }
  2462. if(@opt::basefile) { setup_basefile(); }
  2463. # for each sshlogin do:
  2464. # parallel -S $sshlogin $command :::: @argfiles
  2465. #
  2466. # Pass some of the options to the sub-parallels, not all of them as
  2467. # -P should only go to the first, and -S should not be copied at all.
  2468. my $options =
  2469. join(" ",
  2470. ((defined $opt::jobs) ? "-P $opt::jobs" : ""),
  2471. ((defined $opt::linebuffer) ? "--linebuffer" : ""),
  2472. ((defined $opt::ungroup) ? "-u" : ""),
  2473. ((defined $opt::group) ? "-g" : ""),
  2474. ((defined $opt::keeporder) ? "--keeporder" : ""),
  2475. ((defined $opt::D) ? "-D $opt::D" : ""),
  2476. ((defined $opt::plain) ? "--plain" : ""),
  2477. ((defined $opt::max_chars) ? "--max-chars ".$opt::max_chars : ""),
  2478. );
  2479. my $suboptions =
  2480. join(" ",
  2481. ((defined $opt::ungroup) ? "-u" : ""),
  2482. ((defined $opt::linebuffer) ? "--linebuffer" : ""),
  2483. ((defined $opt::group) ? "-g" : ""),
  2484. ((defined $opt::files) ? "--files" : ""),
  2485. ((defined $opt::keeporder) ? "--keeporder" : ""),
  2486. ((defined $opt::colsep) ? "--colsep ".shell_quote($opt::colsep) : ""),
  2487. ((@opt::v) ? "-vv" : ""),
  2488. ((defined $opt::D) ? "-D $opt::D" : ""),
  2489. ((defined $opt::timeout) ? "--timeout ".$opt::timeout : ""),
  2490. ((defined $opt::plain) ? "--plain" : ""),
  2491. ((defined $opt::retries) ? "--retries ".$opt::retries : ""),
  2492. ((defined $opt::max_chars) ? "--max-chars ".$opt::max_chars : ""),
  2493. ((defined $opt::arg_sep) ? "--arg-sep ".$opt::arg_sep : ""),
  2494. ((defined $opt::arg_file_sep) ? "--arg-file-sep ".$opt::arg_file_sep : ""),
  2495. (@opt::env ? map { "--env ".::shell_quote_scalar($_) } @opt::env : ""),
  2496. );
  2497. ::debug("init", "| $0 $options\n");
  2498. open(my $parallel_fh, "|-", "$0 --no-notice -j0 $options") ||
  2499. ::die_bug("This does not run GNU Parallel: $0 $options");
  2500. my @joblogs;
  2501. for my $host (sort keys %Global::host) {
  2502. my $sshlogin = $Global::host{$host};
  2503. my $joblog = tmp_joblog($opt::joblog);
  2504. if($joblog) {
  2505. push @joblogs, $joblog;
  2506. $joblog = "--joblog $joblog";
  2507. }
  2508. my $quad = $opt::arg_file_sep || "::::";
  2509. ::debug("init", "$0 $suboptions -j1 $joblog ",
  2510. ((defined $opt::tag) ?
  2511. "--tagstring ".shell_quote_scalar($sshlogin->string()) : ""),
  2512. " -S ", shell_quote_scalar($sshlogin->string())," ",
  2513. join(" ",shell_quote(@command))," $quad @argfiles\n");
  2514. print $parallel_fh "$0 $suboptions -j1 $joblog ",
  2515. ((defined $opt::tag) ?
  2516. "--tagstring ".shell_quote_scalar($sshlogin->string()) : ""),
  2517. " -S ", shell_quote_scalar($sshlogin->string())," ",
  2518. join(" ",shell_quote(@command))," $quad @argfiles\n";
  2519. }
  2520. close $parallel_fh;
  2521. $Global::exitstatus = $? >> 8;
  2522. debug("init", "--onall exitvalue ", $?);
  2523. if(@opt::basefile) { cleanup_basefile(); }
  2524. $Global::debug or unlink(@argfiles);
  2525. my %seen;
  2526. for my $joblog (@joblogs) {
  2527. # Append to $joblog
  2528. open(my $fh, "<", $joblog) || ::die_bug("Cannot open tmp joblog $joblog");
  2529. # Skip first line (header);
  2530. <$fh>;
  2531. print $Global::joblog (<$fh>);
  2532. close $fh;
  2533. unlink($joblog);
  2534. }
  2535. }
  2536. sub __SIGNAL_HANDLING__ {}
  2537. sub save_original_signal_handler {
  2538. # Remember the original signal handler
  2539. # Returns: N/A
  2540. $SIG{TERM} ||= sub { exit 0; }; # $SIG{TERM} is not set on Mac OS X
  2541. $SIG{INT} = sub { if($opt::tmux) { qx { tmux kill-session -t p$$ }; }
  2542. unlink keys %Global::unlink; exit -1 };
  2543. $SIG{TERM} = sub { if($opt::tmux) { qx { tmux kill-session -t p$$ }; }
  2544. unlink keys %Global::unlink; exit -1 };
  2545. %Global::original_sig = %SIG;
  2546. $SIG{TERM} = sub {}; # Dummy until jobs really start
  2547. }
  2548. sub list_running_jobs {
  2549. # Returns: N/A
  2550. for my $v (values %Global::running) {
  2551. print $Global::original_stderr "$Global::progname: ",$v->replaced(),"\n";
  2552. }
  2553. }
  2554. sub start_no_new_jobs {
  2555. # Returns: N/A
  2556. $SIG{TERM} = $Global::original_sig{TERM};
  2557. print $Global::original_stderr
  2558. ("$Global::progname: SIGTERM received. No new jobs will be started.\n",
  2559. "$Global::progname: Waiting for these ", scalar(keys %Global::running),
  2560. " jobs to finish. Send SIGTERM again to stop now.\n");
  2561. list_running_jobs();
  2562. $Global::start_no_new_jobs ||= 1;
  2563. }
  2564. sub reaper {
  2565. # A job finished.
  2566. # Print the output.
  2567. # Start another job
  2568. # Returns: N/A
  2569. my $stiff;
  2570. my $children_reaped = 0;
  2571. debug("run", "Reaper ");
  2572. while (($stiff = waitpid(-1, &WNOHANG)) > 0) {
  2573. $children_reaped++;
  2574. if($Global::sshmaster{$stiff}) {
  2575. # This is one of the ssh -M: ignore
  2576. next;
  2577. }
  2578. my $job = $Global::running{$stiff};
  2579. # '-a <(seq 10)' will give us a pid not in %Global::running
  2580. $job or next;
  2581. $job->set_exitstatus($? >> 8);
  2582. $job->set_exitsignal($? & 127);
  2583. debug("run", "died (", $job->exitstatus(), "): ", $job->seq());
  2584. $job->set_endtime(::now());
  2585. if($stiff == $Global::tty_taken) {
  2586. # The process that died had the tty => release it
  2587. $Global::tty_taken = 0;
  2588. }
  2589. if(not $job->should_be_retried()) {
  2590. # The job is done
  2591. # Free the jobslot
  2592. push @Global::slots, $job->slot();
  2593. if($opt::timeout) {
  2594. # Update average runtime for timeout
  2595. $Global::timeoutq->update_delta_time($job->runtime());
  2596. }
  2597. # Force printing now if the job failed and we are going to exit
  2598. my $print_now = ($opt::halt_on_error and $opt::halt_on_error == 2
  2599. and $job->exitstatus());
  2600. if($opt::keeporder and not $print_now) {
  2601. print_earlier_jobs($job);
  2602. } else {
  2603. $job->print();
  2604. }
  2605. if($job->exitstatus()) {
  2606. process_failed_job($job);
  2607. }
  2608. }
  2609. my $sshlogin = $job->sshlogin();
  2610. $sshlogin->dec_jobs_running();
  2611. $sshlogin->inc_jobs_completed();
  2612. $Global::total_running--;
  2613. delete $Global::running{$stiff};
  2614. start_more_jobs();
  2615. }
  2616. debug("run", "done ");
  2617. return $children_reaped;
  2618. }
  2619. sub process_failed_job {
  2620. # The jobs had a exit status <> 0, so error
  2621. # Returns: N/A
  2622. my $job = shift;
  2623. $Global::exitstatus++;
  2624. $Global::total_failed++;
  2625. if($opt::halt_on_error) {
  2626. if($opt::halt_on_error == 1
  2627. or
  2628. ($opt::halt_on_error < 1 and $Global::total_failed > 3
  2629. and
  2630. $Global::total_failed / $Global::total_started > $opt::halt_on_error)) {
  2631. # If halt on error == 1 or --halt 10%
  2632. # we should gracefully exit
  2633. print $Global::original_stderr
  2634. ("$Global::progname: Starting no more jobs. ",
  2635. "Waiting for ", scalar(keys %Global::running),
  2636. " jobs to finish. This job failed:\n",
  2637. $job->replaced(),"\n");
  2638. $Global::start_no_new_jobs ||= 1;
  2639. $Global::halt_on_error_exitstatus = $job->exitstatus();
  2640. } elsif($opt::halt_on_error == 2) {
  2641. # If halt on error == 2 we should exit immediately
  2642. print $Global::original_stderr
  2643. ("$Global::progname: This job failed:\n",
  2644. $job->replaced(),"\n");
  2645. exit ($job->exitstatus());
  2646. }
  2647. }
  2648. }
  2649. {
  2650. my (%print_later,$job_end_sequence);
  2651. sub print_earlier_jobs {
  2652. # Print jobs completed earlier
  2653. # Returns: N/A
  2654. my $job = shift;
  2655. $print_later{$job->seq()} = $job;
  2656. $job_end_sequence ||= 1;
  2657. debug("run", "Looking for: $job_end_sequence ",
  2658. "Current: ", $job->seq(), "\n");
  2659. for(my $j = $print_later{$job_end_sequence};
  2660. $j or vec($Global::job_already_run,$job_end_sequence,1);
  2661. $job_end_sequence++,
  2662. $j = $print_later{$job_end_sequence}) {
  2663. debug("run", "Found job end $job_end_sequence");
  2664. if($j) {
  2665. $j->print();
  2666. delete $print_later{$job_end_sequence};
  2667. }
  2668. }
  2669. }
  2670. }
  2671. sub __USAGE__ {}
  2672. sub wait_and_exit {
  2673. # If we do not wait, we sometimes get segfault
  2674. # Returns: N/A
  2675. my $error = shift;
  2676. if($error) {
  2677. # Kill all without printing
  2678. for my $job (values %Global::running) {
  2679. $job->kill("TERM");
  2680. $job->kill("TERM");
  2681. }
  2682. }
  2683. for (keys %Global::unkilled_children) {
  2684. kill 9, $_;
  2685. waitpid($_,0);
  2686. delete $Global::unkilled_children{$_};
  2687. }
  2688. wait();
  2689. exit($error);
  2690. }
  2691. sub die_usage {
  2692. # Returns: N/A
  2693. usage();
  2694. wait_and_exit(255);
  2695. }
  2696. sub usage {
  2697. # Returns: N/A
  2698. print join
  2699. ("\n",
  2700. "Usage:",
  2701. "",
  2702. "$Global::progname [options] [command [arguments]] < list_of_arguments",
  2703. "$Global::progname [options] [command [arguments]] (::: arguments|:::: argfile(s))...",
  2704. "cat ... | $Global::progname --pipe [options] [command [arguments]]",
  2705. "",
  2706. "-j n Run n jobs in parallel",
  2707. "-k Keep same order",
  2708. "-X Multiple arguments with context replace",
  2709. "--colsep regexp Split input on regexp for positional replacements",
  2710. "{} {.} {/} {/.} {#} {%} {= perl code =} Replacement strings",
  2711. "{3} {3.} {3/} {3/.} {=3 perl code =} Positional replacement strings",
  2712. "With --plus: {} = {+/}/{/} = {.}.{+.} = {+/}/{/.}.{+.} = {..}.{+..} =",
  2713. " {+/}/{/..}.{+..} = {...}.{+...} = {+/}/{/...}.{+...}",
  2714. "",
  2715. "-S sshlogin Example: foo\@server.example.com",
  2716. "--slf .. Use ~/.parallel/sshloginfile as the list of sshlogins",
  2717. "--trc {}.bar Shorthand for --transfer --return {}.bar --cleanup",
  2718. "--onall Run the given command with argument on all sshlogins",
  2719. "--nonall Run the given command with no arguments on all sshlogins",
  2720. "",
  2721. "--pipe Split stdin (standard input) to multiple jobs.",
  2722. "--recend str Record end separator for --pipe.",
  2723. "--recstart str Record start separator for --pipe.",
  2724. "",
  2725. "See 'man $Global::progname' for details",
  2726. "",
  2727. "When using programs that use GNU Parallel to process data for publication please cite:",
  2728. "",
  2729. "O. Tange (2011): GNU Parallel - The Command-Line Power Tool,",
  2730. ";login: The USENIX Magazine, February 2011:42-47.",
  2731. "",
  2732. "Or you can get GNU Parallel without this requirement by paying 10000 EUR.",
  2733. "");
  2734. }
  2735. sub citation_notice {
  2736. # if --no-notice or --plain: do nothing
  2737. # if stderr redirected: do nothing
  2738. # if ~/.parallel/will-cite: do nothing
  2739. # else: print citation notice to stderr
  2740. if($opt::no_notice
  2741. or
  2742. $opt::plain
  2743. or
  2744. not -t $Global::original_stderr
  2745. or
  2746. -e $ENV{'HOME'}."/.parallel/will-cite") {
  2747. # skip
  2748. } else {
  2749. print $Global::original_stderr
  2750. ("When using programs that use GNU Parallel to process data for publication please cite:\n",
  2751. "\n",
  2752. " O. Tange (2011): GNU Parallel - The Command-Line Power Tool,\n",
  2753. " ;login: The USENIX Magazine, February 2011:42-47.\n",
  2754. "\n",
  2755. "This helps funding further development; and it won't cost you a cent.\n",
  2756. "Or you can get GNU Parallel without this requirement by paying 10000 EUR.\n",
  2757. "\n",
  2758. "To silence this citation notice run 'parallel --bibtex' once or use '--no-notice'.\n\n",
  2759. );
  2760. flush $Global::original_stderr;
  2761. }
  2762. }
  2763. sub warning {
  2764. my @w = @_;
  2765. my $fh = $Global::original_stderr || *STDERR;
  2766. my $prog = $Global::progname || "parallel";
  2767. print $fh $prog, ": Warning: ", @w;
  2768. }
  2769. sub error {
  2770. my @w = @_;
  2771. my $fh = $Global::original_stderr || *STDERR;
  2772. my $prog = $Global::progname || "parallel";
  2773. print $fh $prog, ": Error: ", @w;
  2774. }
  2775. sub die_bug {
  2776. my $bugid = shift;
  2777. print STDERR
  2778. ("$Global::progname: This should not happen. You have found a bug.\n",
  2779. "Please contact <parallel\@gnu.org> and include:\n",
  2780. "* The version number: $Global::version\n",
  2781. "* The bugid: $bugid\n",
  2782. "* The command line being run\n",
  2783. "* The files being read (put the files on a webserver if they are big)\n",
  2784. "\n",
  2785. "If you get the error on smaller/fewer files, please include those instead.\n");
  2786. ::wait_and_exit(255);
  2787. }
  2788. sub version {
  2789. # Returns: N/A
  2790. if($opt::tollef and not $opt::gnu) {
  2791. print "WARNING: YOU ARE USING --tollef. IF THINGS ARE ACTING WEIRD USE --gnu.\n";
  2792. }
  2793. print join("\n",
  2794. "GNU $Global::progname $Global::version",
  2795. "Copyright (C) 2007,2008,2009,2010,2011,2012,2013,2014 Ole Tange and Free Software Foundation, Inc.",
  2796. "License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>",
  2797. "This is free software: you are free to change and redistribute it.",
  2798. "GNU $Global::progname comes with no warranty.",
  2799. "",
  2800. "Web site: http://www.gnu.org/software/${Global::progname}\n",
  2801. "When using programs that use GNU Parallel to process data for publication please cite:\n",
  2802. "O. Tange (2011): GNU Parallel - The Command-Line Power Tool, ",
  2803. ";login: The USENIX Magazine, February 2011:42-47.\n",
  2804. "Or you can get GNU Parallel without this requirement by paying 10000 EUR.\n",
  2805. );
  2806. }
  2807. sub bibtex {
  2808. # Returns: N/A
  2809. if($opt::tollef and not $opt::gnu) {
  2810. print "WARNING: YOU ARE USING --tollef. IF THINGS ARE ACTING WEIRD USE --gnu.\n";
  2811. }
  2812. print join("\n",
  2813. "When using programs that use GNU Parallel to process data for publication please cite:",
  2814. "",
  2815. "\@article{Tange2011a,",
  2816. " title = {GNU Parallel - The Command-Line Power Tool},",
  2817. " author = {O. Tange},",
  2818. " address = {Frederiksberg, Denmark},",
  2819. " journal = {;login: The USENIX Magazine},",
  2820. " month = {Feb},",
  2821. " number = {1},",
  2822. " volume = {36},",
  2823. " url = {http://www.gnu.org/s/parallel},",
  2824. " year = {2011},",
  2825. " pages = {42-47}",
  2826. "}",
  2827. "",
  2828. "(Feel free to use \\nocite{Tange2011a})",
  2829. "",
  2830. "This helps funding further development.",
  2831. "",
  2832. "Or you can get GNU Parallel without this requirement by paying 10000 EUR.",
  2833. ""
  2834. );
  2835. while(not -e $ENV{'HOME'}."/.parallel/will-cite") {
  2836. print "\nType: 'will cite' and press enter.\n> ";
  2837. my $input = <STDIN>;
  2838. if($input =~ /will cite/i) {
  2839. mkdir $ENV{'HOME'}."/.parallel";
  2840. open (my $fh, ">", $ENV{'HOME'}."/.parallel/will-cite")
  2841. || ::die_bug("Cannot write: ".$ENV{'HOME'}."/.parallel/will-cite");
  2842. close $fh;
  2843. print "\nThank you for your support. It is much appreciated. The citation\n",
  2844. "notice is now silenced.\n";
  2845. }
  2846. }
  2847. }
  2848. sub show_limits {
  2849. # Returns: N/A
  2850. print("Maximal size of command: ",Limits::Command::real_max_length(),"\n",
  2851. "Maximal used size of command: ",Limits::Command::max_length(),"\n",
  2852. "\n",
  2853. "Execution of will continue now, and it will try to read its input\n",
  2854. "and run commands; if this is not what you wanted to happen, please\n",
  2855. "press CTRL-D or CTRL-C\n");
  2856. }
  2857. sub __GENERIC_COMMON_FUNCTION__ {}
  2858. sub uniq {
  2859. # Remove duplicates and return unique values
  2860. return keys %{{ map { $_ => 1 } @_ }};
  2861. }
  2862. sub min {
  2863. # Returns:
  2864. # Minimum value of array
  2865. my $min;
  2866. for (@_) {
  2867. # Skip undefs
  2868. defined $_ or next;
  2869. defined $min or do { $min = $_; next; }; # Set $_ to the first non-undef
  2870. $min = ($min < $_) ? $min : $_;
  2871. }
  2872. return $min;
  2873. }
  2874. sub max {
  2875. # Returns:
  2876. # Maximum value of array
  2877. my $max;
  2878. for (@_) {
  2879. # Skip undefs
  2880. defined $_ or next;
  2881. defined $max or do { $max = $_; next; }; # Set $_ to the first non-undef
  2882. $max = ($max > $_) ? $max : $_;
  2883. }
  2884. return $max;
  2885. }
  2886. sub sum {
  2887. # Returns:
  2888. # Sum of values of array
  2889. my @args = @_;
  2890. my $sum = 0;
  2891. for (@args) {
  2892. # Skip undefs
  2893. $_ and do { $sum += $_; }
  2894. }
  2895. return $sum;
  2896. }
  2897. sub undef_as_zero {
  2898. my $a = shift;
  2899. return $a ? $a : 0;
  2900. }
  2901. sub undef_as_empty {
  2902. my $a = shift;
  2903. return $a ? $a : "";
  2904. }
  2905. {
  2906. my $hostname;
  2907. sub hostname {
  2908. if(not $hostname) {
  2909. $hostname = `hostname`;
  2910. chomp($hostname);
  2911. $hostname ||= "nohostname";
  2912. }
  2913. return $hostname;
  2914. }
  2915. }
  2916. sub which {
  2917. # Input:
  2918. # @programs = programs to find the path to
  2919. # Returns:
  2920. # @full_path = full paths to @programs. Nothing if not found
  2921. my @which;
  2922. for my $prg (@_) {
  2923. push @which, map { $_."/".$prg } grep { -x $_."/".$prg } split(":",$ENV{'PATH'});
  2924. }
  2925. return @which;
  2926. }
  2927. {
  2928. my ($regexp,%fakename);
  2929. sub parent_shell {
  2930. # Input:
  2931. # $pid = pid to see if (grand)*parent is a shell
  2932. # Returns:
  2933. # $shellpath = path to shell - undef if no shell found
  2934. my $pid = shift;
  2935. if(not $regexp) {
  2936. # All shells known to mankind
  2937. #
  2938. # ash bash csh dash fdsh fish fizsh ksh ksh93 mksh pdksh
  2939. # posh rbash rush rzsh sash sh static-sh tcsh yash zsh
  2940. my @shells = qw(ash bash csh dash fdsh fish fizsh ksh
  2941. ksh93 mksh pdksh posh rbash rush rzsh
  2942. sash sh static-sh tcsh yash zsh -sh -csh);
  2943. # Can be formatted as:
  2944. # [sh] -sh sh busybox sh
  2945. # /bin/sh /sbin/sh /opt/csw/sh
  2946. # NOT: foo.sh sshd crash flush pdflush scosh fsflush ssh
  2947. my $shell = "(?:".join("|",@shells).")";
  2948. $regexp = '^((\[)('. $shell. ')(\])|(|\S+/|busybox )('. $shell. '))($| )';
  2949. %fakename = (
  2950. # csh and tcsh disguise themselves as -sh/-csh
  2951. "-sh" => ["csh", "tcsh"],
  2952. "-csh" => ["tcsh", "csh"],
  2953. );
  2954. }
  2955. my ($children_of_ref, $parent_of_ref, $name_of_ref) = pid_table();
  2956. my $shellpath;
  2957. my $testpid = $pid;
  2958. while($testpid) {
  2959. ::debug("init", "shell? ". $name_of_ref->{$testpid}."\n");
  2960. if($name_of_ref->{$testpid} =~ /$regexp/o) {
  2961. ::debug("init", "which ".($3||$6)." => ");
  2962. $shellpath = (which($3 || $6,@{$fakename{$3 || $6}}))[0];
  2963. ::debug("init", "shell path $shellpath\n");
  2964. $shellpath and last;
  2965. }
  2966. $testpid = $parent_of_ref->{$testpid};
  2967. }
  2968. return $shellpath;
  2969. }
  2970. }
  2971. {
  2972. my %pid_parentpid_cmd;
  2973. sub pid_table {
  2974. # Returns:
  2975. # %children_of = { pid -> children of pid }
  2976. # %parent_of = { pid -> pid of parent }
  2977. # %name_of = { pid -> commandname }
  2978. if(not %pid_parentpid_cmd) {
  2979. # Filter for SysV-style `ps`
  2980. my $sysv = q( ps -ef | perl -ane '1..1 and /^(.*)CO?MM?A?N?D/ and $s=length $1;).
  2981. q(s/^.{$s}//; print "@F[1,2] $_"' );
  2982. # BSD-style `ps`
  2983. my $bsd = q(ps -o pid,ppid,command -ax);
  2984. %pid_parentpid_cmd =
  2985. (
  2986. 'aix' => $sysv,
  2987. 'cygwin' => $sysv,
  2988. 'msys' => $sysv,
  2989. 'dec_osf' => $sysv,
  2990. 'darwin' => $bsd,
  2991. 'dragonfly' => $bsd,
  2992. 'freebsd' => $bsd,
  2993. 'gnu' => $sysv,
  2994. 'hpux' => $sysv,
  2995. 'linux' => $sysv,
  2996. 'mirbsd' => $bsd,
  2997. 'netbsd' => $bsd,
  2998. 'nto' => $sysv,
  2999. 'openbsd' => $bsd,
  3000. 'solaris' => $sysv,
  3001. 'svr5' => $sysv,
  3002. );
  3003. }
  3004. $pid_parentpid_cmd{$^O} or ::die_bug("pid_parentpid_cmd for $^O missing");
  3005. my (@pidtable,%parent_of,%children_of,%name_of);
  3006. # Table with pid -> children of pid
  3007. @pidtable = `$pid_parentpid_cmd{$^O}`;
  3008. my $p=$$;
  3009. for (@pidtable) {
  3010. # must match: 24436 21224 busybox ash
  3011. /(\S+)\s+(\S+)\s+(\S+.*)/ or ::die_bug("pidtable format: $_");
  3012. $parent_of{$1} = $2;
  3013. push @{$children_of{$2}}, $1;
  3014. $name_of{$1} = $3;
  3015. }
  3016. return(\%children_of, \%parent_of, \%name_of);
  3017. }
  3018. }
  3019. sub reap_usleep {
  3020. # Reap dead children.
  3021. # If no dead children: Sleep specified amount with exponential backoff
  3022. # Input:
  3023. # $ms = milliseconds to sleep
  3024. # Returns:
  3025. # $ms/2+0.001 if children reaped
  3026. # $ms*1.1 if no children reaped
  3027. my $ms = shift;
  3028. if(reaper()) {
  3029. # Sleep exponentially shorter (1/2^n) if a job finished
  3030. return $ms/2+0.001;
  3031. } else {
  3032. if($opt::timeout) {
  3033. $Global::timeoutq->process_timeouts();
  3034. }
  3035. usleep($ms);
  3036. Job::exit_if_disk_full();
  3037. if($opt::linebuffer) {
  3038. for my $job (values %Global::running) {
  3039. $job->print();
  3040. }
  3041. }
  3042. # Sleep exponentially longer (1.1^n) if a job did not finish
  3043. # though at most 1000 ms.
  3044. return (($ms < 1000) ? ($ms * 1.1) : ($ms));
  3045. }
  3046. }
  3047. sub usleep {
  3048. # Sleep this many milliseconds.
  3049. # Input:
  3050. # $ms = milliseconds to sleep
  3051. my $ms = shift;
  3052. ::debug(int($ms),"ms ");
  3053. select(undef, undef, undef, $ms/1000);
  3054. }
  3055. sub now {
  3056. # Returns time since epoch as in seconds with 3 decimals
  3057. # Uses:
  3058. # @Global::use
  3059. # Returns:
  3060. # $time = time now with millisecond accuracy
  3061. if(not $Global::use{"Time::HiRes"}) {
  3062. if(eval "use Time::HiRes qw ( time );") {
  3063. eval "sub TimeHiRestime { return Time::HiRes::time };";
  3064. } else {
  3065. eval "sub TimeHiRestime { return time() };";
  3066. }
  3067. $Global::use{"Time::HiRes"} = 1;
  3068. }
  3069. return (int(TimeHiRestime()*1000))/1000;
  3070. }
  3071. sub multiply_binary_prefix {
  3072. # Evalualte numbers with binary prefix
  3073. # Ki=2^10, Mi=2^20, Gi=2^30, Ti=2^40, Pi=2^50, Ei=2^70, Zi=2^80, Yi=2^80
  3074. # ki=2^10, mi=2^20, gi=2^30, ti=2^40, pi=2^50, ei=2^70, zi=2^80, yi=2^80
  3075. # K =2^10, M =2^20, G =2^30, T =2^40, P =2^50, E =2^70, Z =2^80, Y =2^80
  3076. # k =10^3, m =10^6, g =10^9, t=10^12, p=10^15, e=10^18, z=10^21, y=10^24
  3077. # 13G = 13*1024*1024*1024 = 13958643712
  3078. # Input:
  3079. # $s = string with prefixes
  3080. # Returns:
  3081. # $value = int with prefixes multiplied
  3082. my $s = shift;
  3083. $s =~ s/ki/*1024/gi;
  3084. $s =~ s/mi/*1024*1024/gi;
  3085. $s =~ s/gi/*1024*1024*1024/gi;
  3086. $s =~ s/ti/*1024*1024*1024*1024/gi;
  3087. $s =~ s/pi/*1024*1024*1024*1024*1024/gi;
  3088. $s =~ s/ei/*1024*1024*1024*1024*1024*1024/gi;
  3089. $s =~ s/zi/*1024*1024*1024*1024*1024*1024*1024/gi;
  3090. $s =~ s/yi/*1024*1024*1024*1024*1024*1024*1024*1024/gi;
  3091. $s =~ s/xi/*1024*1024*1024*1024*1024*1024*1024*1024*1024/gi;
  3092. $s =~ s/K/*1024/g;
  3093. $s =~ s/M/*1024*1024/g;
  3094. $s =~ s/G/*1024*1024*1024/g;
  3095. $s =~ s/T/*1024*1024*1024*1024/g;
  3096. $s =~ s/P/*1024*1024*1024*1024*1024/g;
  3097. $s =~ s/E/*1024*1024*1024*1024*1024*1024/g;
  3098. $s =~ s/Z/*1024*1024*1024*1024*1024*1024*1024/g;
  3099. $s =~ s/Y/*1024*1024*1024*1024*1024*1024*1024*1024/g;
  3100. $s =~ s/X/*1024*1024*1024*1024*1024*1024*1024*1024*1024/g;
  3101. $s =~ s/k/*1000/g;
  3102. $s =~ s/m/*1000*1000/g;
  3103. $s =~ s/g/*1000*1000*1000/g;
  3104. $s =~ s/t/*1000*1000*1000*1000/g;
  3105. $s =~ s/p/*1000*1000*1000*1000*1000/g;
  3106. $s =~ s/e/*1000*1000*1000*1000*1000*1000/g;
  3107. $s =~ s/z/*1000*1000*1000*1000*1000*1000*1000/g;
  3108. $s =~ s/y/*1000*1000*1000*1000*1000*1000*1000*1000/g;
  3109. $s =~ s/x/*1000*1000*1000*1000*1000*1000*1000*1000*1000/g;
  3110. $s = eval $s;
  3111. ::debug($s);
  3112. return $s;
  3113. }
  3114. sub tmpfile {
  3115. # Create tempfile as $TMPDIR/parXXXXX
  3116. # Returns:
  3117. # $filename = file name created
  3118. return ::tempfile(DIR=>$ENV{'TMPDIR'}, TEMPLATE => 'parXXXXX', @_);
  3119. }
  3120. sub __DEBUGGING__ {}
  3121. sub debug {
  3122. # Uses:
  3123. # $Global::debug
  3124. # %Global::fd
  3125. # Returns: N/A
  3126. $Global::debug or return;
  3127. @_ = grep { defined $_ ? $_ : "" } @_;
  3128. if($Global::debug eq "all" or $Global::debug eq $_[0]) {
  3129. if($Global::fd{1}) {
  3130. # Original stdout was saved
  3131. my $stdout = $Global::fd{1};
  3132. print $stdout @_[1..$#_];
  3133. } else {
  3134. print @_[1..$#_];
  3135. }
  3136. }
  3137. }
  3138. sub my_memory_usage {
  3139. # Returns:
  3140. # memory usage if found
  3141. # 0 otherwise
  3142. use strict;
  3143. use FileHandle;
  3144. my $pid = $$;
  3145. if(-e "/proc/$pid/stat") {
  3146. my $fh = FileHandle->new("</proc/$pid/stat");
  3147. my $data = <$fh>;
  3148. chomp $data;
  3149. $fh->close;
  3150. my @procinfo = split(/\s+/,$data);
  3151. return undef_as_zero($procinfo[22]);
  3152. } else {
  3153. return 0;
  3154. }
  3155. }
  3156. sub my_size {
  3157. # Returns:
  3158. # $size = size of object if Devel::Size is installed
  3159. # -1 otherwise
  3160. my @size_this = (@_);
  3161. eval "use Devel::Size qw(size total_size)";
  3162. if ($@) {
  3163. return -1;
  3164. } else {
  3165. return total_size(@_);
  3166. }
  3167. }
  3168. sub my_dump {
  3169. # Returns:
  3170. # ascii expression of object if Data::Dump(er) is installed
  3171. # error code otherwise
  3172. my @dump_this = (@_);
  3173. eval "use Data::Dump qw(dump);";
  3174. if ($@) {
  3175. # Data::Dump not installed
  3176. eval "use Data::Dumper;";
  3177. if ($@) {
  3178. my $err = "Neither Data::Dump nor Data::Dumper is installed\n".
  3179. "Not dumping output\n";
  3180. print $Global::original_stderr $err;
  3181. return $err;
  3182. } else {
  3183. return Dumper(@dump_this);
  3184. }
  3185. } else {
  3186. # Create a dummy Data::Dump:dump as Hans Schou sometimes has
  3187. # it undefined
  3188. eval "sub Data::Dump:dump {}";
  3189. eval "use Data::Dump qw(dump);";
  3190. return (Data::Dump::dump(@dump_this));
  3191. }
  3192. }
  3193. sub my_croak {
  3194. eval "use Carp; 1";
  3195. $Carp::Verbose = 1;
  3196. croak(@_);
  3197. }
  3198. sub my_carp {
  3199. eval "use Carp; 1";
  3200. $Carp::Verbose = 1;
  3201. carp(@_);
  3202. }
  3203. sub __OBJECT_ORIENTED_PARTS__ {}
  3204. package SSHLogin;
  3205. sub new {
  3206. my $class = shift;
  3207. my $sshlogin_string = shift;
  3208. my $ncpus;
  3209. my %hostgroups;
  3210. # SSHLogins can have these formats:
  3211. # @grp+grp/ncpu//usr/bin/ssh user@server
  3212. # ncpu//usr/bin/ssh user@server
  3213. # /usr/bin/ssh user@server
  3214. # user@server
  3215. # ncpu/user@server
  3216. # @grp+grp/user@server
  3217. if($sshlogin_string =~ s:^\@([^/]+)/?::) {
  3218. # Look for SSHLogin hostgroups
  3219. %hostgroups = map { $_ => 1 } split(/\+/, $1);
  3220. }
  3221. if ($sshlogin_string =~ s:^(\d+)/::) {
  3222. # Override default autodetected ncpus unless missing
  3223. $ncpus = $1;
  3224. }
  3225. my $string = $sshlogin_string;
  3226. # An SSHLogin is always in the hostgroup of its $string-name
  3227. $hostgroups{$string} = 1;
  3228. @Global::hostgroups{keys %hostgroups} = values %hostgroups;
  3229. my @unget = ();
  3230. my $no_slash_string = $string;
  3231. $no_slash_string =~ s/[^-a-z0-9:]/_/gi;
  3232. return bless {
  3233. 'string' => $string,
  3234. 'jobs_running' => 0,
  3235. 'jobs_completed' => 0,
  3236. 'maxlength' => undef,
  3237. 'max_jobs_running' => undef,
  3238. 'orig_max_jobs_running' => undef,
  3239. 'ncpus' => $ncpus,
  3240. 'hostgroups' => \%hostgroups,
  3241. 'sshcommand' => undef,
  3242. 'serverlogin' => undef,
  3243. 'control_path_dir' => undef,
  3244. 'control_path' => undef,
  3245. 'time_to_login' => undef,
  3246. 'last_login_at' => undef,
  3247. 'loadavg_file' => $ENV{'HOME'} . "/.parallel/tmp/loadavg-" .
  3248. $no_slash_string,
  3249. 'loadavg' => undef,
  3250. 'last_loadavg_update' => 0,
  3251. 'swap_activity_file' => $ENV{'HOME'} . "/.parallel/tmp/swap_activity-" .
  3252. $no_slash_string,
  3253. 'swap_activity' => undef,
  3254. }, ref($class) || $class;
  3255. }
  3256. sub DESTROY {
  3257. my $self = shift;
  3258. # Remove temporary files if they are created.
  3259. unlink $self->{'loadavg_file'};
  3260. unlink $self->{'swap_activity_file'};
  3261. }
  3262. sub string {
  3263. my $self = shift;
  3264. return $self->{'string'};
  3265. }
  3266. sub jobs_running {
  3267. my $self = shift;
  3268. return ($self->{'jobs_running'} || "0");
  3269. }
  3270. sub inc_jobs_running {
  3271. my $self = shift;
  3272. $self->{'jobs_running'}++;
  3273. }
  3274. sub dec_jobs_running {
  3275. my $self = shift;
  3276. $self->{'jobs_running'}--;
  3277. }
  3278. sub set_maxlength {
  3279. my $self = shift;
  3280. $self->{'maxlength'} = shift;
  3281. }
  3282. sub maxlength {
  3283. my $self = shift;
  3284. return $self->{'maxlength'};
  3285. }
  3286. sub jobs_completed {
  3287. my $self = shift;
  3288. return $self->{'jobs_completed'};
  3289. }
  3290. sub in_hostgroups {
  3291. # Input:
  3292. # @hostgroups = the hostgroups to look for
  3293. # Returns:
  3294. # true if intersection of @hostgroups and the hostgroups of this
  3295. # SSHLogin is non-empty
  3296. my $self = shift;
  3297. return grep { defined $self->{'hostgroups'}{$_} } @_;
  3298. }
  3299. sub hostgroups {
  3300. my $self = shift;
  3301. return keys %{$self->{'hostgroups'}};
  3302. }
  3303. sub inc_jobs_completed {
  3304. my $self = shift;
  3305. $self->{'jobs_completed'}++;
  3306. }
  3307. sub set_max_jobs_running {
  3308. my $self = shift;
  3309. if(defined $self->{'max_jobs_running'}) {
  3310. $Global::max_jobs_running -= $self->{'max_jobs_running'};
  3311. }
  3312. $self->{'max_jobs_running'} = shift;
  3313. if(defined $self->{'max_jobs_running'}) {
  3314. # max_jobs_running could be resat if -j is a changed file
  3315. $Global::max_jobs_running += $self->{'max_jobs_running'};
  3316. }
  3317. # Initialize orig to the first non-zero value that comes around
  3318. $self->{'orig_max_jobs_running'} ||= $self->{'max_jobs_running'};
  3319. }
  3320. sub swapping {
  3321. my $self = shift;
  3322. my $swapping = $self->swap_activity();
  3323. return (not defined $swapping or $swapping)
  3324. }
  3325. sub swap_activity {
  3326. # If the currently known swap activity is too old:
  3327. # Recompute a new one in the background
  3328. # Returns:
  3329. # last swap activity computed
  3330. my $self = shift;
  3331. # Should we update the swap_activity file?
  3332. my $update_swap_activity_file = 0;
  3333. if(-r $self->{'swap_activity_file'}) {
  3334. open(my $swap_fh, "<", $self->{'swap_activity_file'}) || ::die_bug("swap_activity_file-r");
  3335. my $swap_out = <$swap_fh>;
  3336. close $swap_fh;
  3337. if($swap_out =~ /^(\d+)$/) {
  3338. $self->{'swap_activity'} = $1;
  3339. ::debug("swap", "New swap_activity: ", $self->{'swap_activity'});
  3340. }
  3341. ::debug("swap", "Last update: ", $self->{'last_swap_activity_update'});
  3342. if(time - $self->{'last_swap_activity_update'} > 10) {
  3343. # last swap activity update was started 10 seconds ago
  3344. ::debug("swap", "Older than 10 sec: ", $self->{'swap_activity_file'});
  3345. $update_swap_activity_file = 1;
  3346. }
  3347. } else {
  3348. ::debug("swap", "No swap_activity file: ", $self->{'swap_activity_file'});
  3349. $self->{'swap_activity'} = undef;
  3350. $update_swap_activity_file = 1;
  3351. }
  3352. if($update_swap_activity_file) {
  3353. ::debug("swap", "Updating swap_activity file ", $self->{'swap_activity_file'});
  3354. $self->{'last_swap_activity_update'} = time;
  3355. -e $ENV{'HOME'}."/.parallel" or mkdir $ENV{'HOME'}."/.parallel";
  3356. -e $ENV{'HOME'}."/.parallel/tmp" or mkdir $ENV{'HOME'}."/.parallel/tmp";
  3357. my $swap_activity;
  3358. $swap_activity = swapactivityscript();
  3359. if($self->{'string'} ne ":") {
  3360. $swap_activity = $self->sshcommand() . " " . $self->serverlogin() . " " .
  3361. ::shell_quote_scalar($swap_activity);
  3362. }
  3363. # Run swap_activity measuring.
  3364. # As the command can take long to run if run remote
  3365. # save it to a tmp file before moving it to the correct file
  3366. my $file = $self->{'swap_activity_file'};
  3367. my ($dummy_fh, $tmpfile) = ::tmpfile(SUFFIX => ".swp");
  3368. ::debug("swap", "\n", $swap_activity, "\n");
  3369. qx{ ($swap_activity > $tmpfile && mv $tmpfile $file || rm $tmpfile) & };
  3370. }
  3371. return $self->{'swap_activity'};
  3372. }
  3373. {
  3374. my $script;
  3375. sub swapactivityscript {
  3376. # Returns:
  3377. # shellscript for detecting swap activity
  3378. #
  3379. # arguments for vmstat are OS dependant
  3380. # swap_in and swap_out are in different columns depending on OS
  3381. #
  3382. if(not $script) {
  3383. my %vmstat = (
  3384. # linux: $7*$8
  3385. # $ vmstat 1 2
  3386. # procs -----------memory---------- ---swap-- -----io---- -system-- ----cpu----
  3387. # r b swpd free buff cache si so bi bo in cs us sy id wa
  3388. # 5 0 51208 1701096 198012 18857888 0 0 37 153 28 19 56 11 33 1
  3389. # 3 0 51208 1701288 198012 18857972 0 0 0 0 3638 10412 15 3 82 0
  3390. 'linux' => ['vmstat 1 2 | tail -n1', '$7*$8'],
  3391. # solaris: $6*$7
  3392. # $ vmstat -S 1 2
  3393. # kthr memory page disk faults cpu
  3394. # r b w swap free si so pi po fr de sr s3 s4 -- -- in sy cs us sy id
  3395. # 0 0 0 4628952 3208408 0 0 3 1 1 0 0 -0 2 0 0 263 613 246 1 2 97
  3396. # 0 0 0 4552504 3166360 0 0 0 0 0 0 0 0 0 0 0 246 213 240 1 1 98
  3397. 'solaris' => ['vmstat -S 1 2 | tail -1', '$6*$7'],
  3398. # darwin (macosx): $21*$22
  3399. # $ vm_stat -c 2 1
  3400. # Mach Virtual Memory Statistics: (page size of 4096 bytes)
  3401. # free active specul inactive throttle wired prgable faults copy 0fill reactive purged file-backed anonymous cmprssed cmprssor dcomprs comprs pageins pageout swapins swapouts
  3402. # 346306 829050 74871 606027 0 240231 90367 544858K 62343596 270837K 14178 415070 570102 939846 356 370 116 922 4019813 4 0 0
  3403. # 345740 830383 74875 606031 0 239234 90369 2696 359 553 0 0 570110 941179 356 370 0 0 0 0 0 0
  3404. 'darwin' => ['vm_stat -c 2 1 | tail -n1', '$21*$22'],
  3405. # ultrix: $12*$13
  3406. # $ vmstat -S 1 2
  3407. # procs faults cpu memory page disk
  3408. # r b w in sy cs us sy id avm fre si so pi po fr de sr s0
  3409. # 1 0 0 4 23 2 3 0 97 7743 217k 0 0 0 0 0 0 0 0
  3410. # 1 0 0 6 40 8 0 1 99 7743 217k 0 0 3 0 0 0 0 0
  3411. 'ultrix' => ['vmstat -S 1 2 | tail -1', '$12*$13'],
  3412. # aix: $6*$7
  3413. # $ vmstat 1 2
  3414. # System configuration: lcpu=1 mem=2048MB
  3415. #
  3416. # kthr memory page faults cpu
  3417. # ----- ----------- ------------------------ ------------ -----------
  3418. # r b avm fre re pi po fr sr cy in sy cs us sy id wa
  3419. # 0 0 333933 241803 0 0 0 0 0 0 10 143 90 0 0 99 0
  3420. # 0 0 334125 241569 0 0 0 0 0 0 37 5368 184 0 9 86 5
  3421. 'aix' => ['vmstat 1 2 | tail -n1', '$6*$7'],
  3422. # freebsd: $8*$9
  3423. # $ vmstat -H 1 2
  3424. # procs memory page disks faults cpu
  3425. # r b w avm fre flt re pi po fr sr ad0 ad1 in sy cs us sy id
  3426. # 1 0 0 596716 19560 32 0 0 0 33 8 0 0 11 220 277 0 0 99
  3427. # 0 0 0 596716 19560 2 0 0 0 0 0 0 0 11 144 263 0 1 99
  3428. 'freebsd' => ['vmstat -H 1 2 | tail -n1', '$8*$9'],
  3429. # mirbsd: $8*$9
  3430. # $ vmstat 1 2
  3431. # procs memory page disks traps cpu
  3432. # r b w avm fre flt re pi po fr sr wd0 cd0 int sys cs us sy id
  3433. # 0 0 0 25776 164968 34 0 0 0 0 0 0 0 230 259 38 4 0 96
  3434. # 0 0 0 25776 164968 24 0 0 0 0 0 0 0 237 275 37 0 0 100
  3435. 'mirbsd' => ['vmstat 1 2 | tail -n1', '$8*$9'],
  3436. # netbsd: $7*$8
  3437. # $ vmstat 1 2
  3438. # procs memory page disks faults cpu
  3439. # r b avm fre flt re pi po fr sr w0 w1 in sy cs us sy id
  3440. # 0 0 138452 6012 54 0 0 0 1 2 3 0 4 100 23 0 0 100
  3441. # 0 0 138456 6008 1 0 0 0 0 0 0 0 7 26 19 0 0 100
  3442. 'netbsd' => ['vmstat 1 2 | tail -n1', '$7*$8'],
  3443. # openbsd: $8*$9
  3444. # $ vmstat 1 2
  3445. # procs memory page disks traps cpu
  3446. # r b w avm fre flt re pi po fr sr wd0 wd1 int sys cs us sy id
  3447. # 0 0 0 76596 109944 73 0 0 0 0 0 0 1 5 259 22 0 1 99
  3448. # 0 0 0 76604 109936 24 0 0 0 0 0 0 0 7 114 20 0 1 99
  3449. 'openbsd' => ['vmstat 1 2 | tail -n1', '$8*$9'],
  3450. # hpux: $8*$9
  3451. # $ vmstat 1 2
  3452. # procs memory page faults cpu
  3453. # r b w avm free re at pi po fr de sr in sy cs us sy id
  3454. # 1 0 0 247211 216476 4 1 0 0 0 0 0 102 73005 54 6 11 83
  3455. # 1 0 0 247211 216421 43 9 0 0 0 0 0 144 1675 96 25269512791222387000 25269512791222387000 105
  3456. 'hpux' => ['vmstat 1 2 | tail -n1', '$8*$9'],
  3457. # dec_osf (tru64): $11*$12
  3458. # $ vmstat 1 2
  3459. # Virtual Memory Statistics: (pagesize = 8192)
  3460. # procs memory pages intr cpu
  3461. # r w u act free wire fault cow zero react pin pout in sy cs us sy id
  3462. # 3 181 36 51K 1895 8696 348M 59M 122M 259 79M 0 5 218 302 4 1 94
  3463. # 3 181 36 51K 1893 8696 3 15 21 0 28 0 4 81 321 1 1 98
  3464. 'dec_osf' => ['vmstat 1 2 | tail -n1', '$11*$12'],
  3465. # gnu (hurd): $7*$8
  3466. # $ vmstat -k 1 2
  3467. # (pagesize: 4, size: 512288, swap size: 894972)
  3468. # free actv inact wired zeroed react pgins pgouts pfaults cowpfs hrat caobj cache swfree
  3469. # 371940 30844 89228 20276 298348 0 48192 19016 756105 99808 98% 876 20628 894972
  3470. # 371940 30844 89228 20276 +0 +0 +0 +0 +42 +2 98% 876 20628 894972
  3471. 'gnu' => ['vmstat -k 1 2 | tail -n1', '$7*$8'],
  3472. # -nto (qnx has no swap)
  3473. #-irix
  3474. #-svr5 (scosysv)
  3475. );
  3476. my $perlscript = "";
  3477. for my $os (keys %vmstat) {
  3478. #q[ { vmstat 1 2 2> /dev/null || vmstat -c 1 2; } | ].
  3479. # q[ awk 'NR!=4{next} NF==17||NF==16{print $7*$8} NF==22{print $21*$22} {exit}' ];
  3480. $vmstat{$os}[1] =~ s/\$/\\\\\\\$/g; # $ => \\\$
  3481. $perlscript .= 'if($^O eq "'.$os.'") { print `'.$vmstat{$os}[0].' | awk "{print ' .
  3482. $vmstat{$os}[1] . '}"` }';
  3483. }
  3484. $perlscript = "perl -e " . ::shell_quote_scalar($perlscript);
  3485. $script = $Global::envvar. " " .$perlscript;
  3486. }
  3487. return $script;
  3488. }
  3489. }
  3490. sub too_fast_remote_login {
  3491. my $self = shift;
  3492. if($self->{'last_login_at'} and $self->{'time_to_login'}) {
  3493. # sshd normally allows 10 simultaneous logins
  3494. # A login takes time_to_login
  3495. # So time_to_login/5 should be safe
  3496. # If now <= last_login + time_to_login/5: Then it is too soon.
  3497. my $too_fast = (::now() <= $self->{'last_login_at'}
  3498. + $self->{'time_to_login'}/5);
  3499. ::debug("run", "Too fast? $too_fast ");
  3500. return $too_fast;
  3501. } else {
  3502. # No logins so far (or time_to_login not computed): it is not too fast
  3503. return 0;
  3504. }
  3505. }
  3506. sub last_login_at {
  3507. my $self = shift;
  3508. return $self->{'last_login_at'};
  3509. }
  3510. sub set_last_login_at {
  3511. my $self = shift;
  3512. $self->{'last_login_at'} = shift;
  3513. }
  3514. sub loadavg_too_high {
  3515. my $self = shift;
  3516. my $loadavg = $self->loadavg();
  3517. return (not defined $loadavg or
  3518. $loadavg > $self->max_loadavg());
  3519. }
  3520. sub loadavg {
  3521. # If the currently know loadavg is too old:
  3522. # Recompute a new one in the background
  3523. # The load average is computed as the number of processes waiting for disk
  3524. # or CPU right now. So it is the server load this instant and not averaged over
  3525. # several minutes. This is needed so GNU Parallel will at most start one job
  3526. # that will push the load over the limit.
  3527. #
  3528. # Returns:
  3529. # $last_loadavg = last load average computed (undef if none)
  3530. my $self = shift;
  3531. # Should we update the loadavg file?
  3532. my $update_loadavg_file = 0;
  3533. if(open(my $load_fh, "<", $self->{'loadavg_file'})) {
  3534. local $/ = undef;
  3535. my $load_out = <$load_fh>;
  3536. close $load_fh;
  3537. my $load =()= ($load_out=~/(^[DR]....[^\[])/gm);
  3538. if($load > 0) {
  3539. # load is overestimated by 1
  3540. $self->{'loadavg'} = $load - 1;
  3541. ::debug("load", "New loadavg: ", $self->{'loadavg'});
  3542. } else {
  3543. ::die_bug("loadavg_invalid_content: $load_out");
  3544. }
  3545. ::debug("load", "Last update: ", $self->{'last_loadavg_update'});
  3546. if(time - $self->{'last_loadavg_update'} > 10) {
  3547. # last loadavg was started 10 seconds ago
  3548. ::debug("load", time - $self->{'last_loadavg_update'}, " secs old: ",
  3549. $self->{'loadavg_file'});
  3550. $update_loadavg_file = 1;
  3551. }
  3552. } else {
  3553. ::debug("load", "No loadavg file: ", $self->{'loadavg_file'});
  3554. $self->{'loadavg'} = undef;
  3555. $update_loadavg_file = 1;
  3556. }
  3557. if($update_loadavg_file) {
  3558. ::debug("load", "Updating loadavg file", $self->{'loadavg_file'}, "\n");
  3559. $self->{'last_loadavg_update'} = time;
  3560. -e $ENV{'HOME'}."/.parallel" or mkdir $ENV{'HOME'}."/.parallel";
  3561. -e $ENV{'HOME'}."/.parallel/tmp" or mkdir $ENV{'HOME'}."/.parallel/tmp";
  3562. my $cmd = "";
  3563. if($self->{'string'} ne ":") {
  3564. $cmd = $self->sshcommand() . " " . $self->serverlogin() . " ";
  3565. }
  3566. # TODO Is is called 'ps ax -o state,command' on other platforms?
  3567. $cmd .= "ps ax -o state,command";
  3568. # As the command can take long to run if run remote
  3569. # save it to a tmp file before moving it to the correct file
  3570. my $file = $self->{'loadavg_file'};
  3571. my ($dummy_fh, $tmpfile) = ::tmpfile(SUFFIX => ".loa");
  3572. qx{ ($cmd > $tmpfile && mv $tmpfile $file || rm $tmpfile) & };
  3573. }
  3574. return $self->{'loadavg'};
  3575. }
  3576. sub max_loadavg {
  3577. my $self = shift;
  3578. # If --load is a file it might be changed
  3579. if($Global::max_load_file) {
  3580. my $mtime = (stat($Global::max_load_file))[9];
  3581. if($mtime > $Global::max_load_file_last_mod) {
  3582. $Global::max_load_file_last_mod = $mtime;
  3583. for my $sshlogin (values %Global::host) {
  3584. $sshlogin->set_max_loadavg(undef);
  3585. }
  3586. }
  3587. }
  3588. if(not defined $self->{'max_loadavg'}) {
  3589. $self->{'max_loadavg'} =
  3590. $self->compute_max_loadavg($opt::load);
  3591. }
  3592. ::debug("load", "max_loadavg: ", $self->string(), " ", $self->{'max_loadavg'});
  3593. return $self->{'max_loadavg'};
  3594. }
  3595. sub set_max_loadavg {
  3596. my $self = shift;
  3597. $self->{'max_loadavg'} = shift;
  3598. }
  3599. sub compute_max_loadavg {
  3600. # Parse the max loadaverage that the user asked for using --load
  3601. # Returns:
  3602. # max loadaverage
  3603. my $self = shift;
  3604. my $loadspec = shift;
  3605. my $load;
  3606. if(defined $loadspec) {
  3607. if($loadspec =~ /^\+(\d+)$/) {
  3608. # E.g. --load +2
  3609. my $j = $1;
  3610. $load =
  3611. $self->ncpus() + $j;
  3612. } elsif ($loadspec =~ /^-(\d+)$/) {
  3613. # E.g. --load -2
  3614. my $j = $1;
  3615. $load =
  3616. $self->ncpus() - $j;
  3617. } elsif ($loadspec =~ /^(\d+)\%$/) {
  3618. my $j = $1;
  3619. $load =
  3620. $self->ncpus() * $j / 100;
  3621. } elsif ($loadspec =~ /^(\d+(\.\d+)?)$/) {
  3622. $load = $1;
  3623. } elsif (-f $loadspec) {
  3624. $Global::max_load_file = $loadspec;
  3625. $Global::max_load_file_last_mod = (stat($Global::max_load_file))[9];
  3626. if(open(my $in_fh, "<", $Global::max_load_file)) {
  3627. my $opt_load_file = join("",<$in_fh>);
  3628. close $in_fh;
  3629. $load = $self->compute_max_loadavg($opt_load_file);
  3630. } else {
  3631. print $Global::original_stderr "Cannot open $loadspec\n";
  3632. ::wait_and_exit(255);
  3633. }
  3634. } else {
  3635. print $Global::original_stderr "Parsing of --load failed\n";
  3636. ::die_usage();
  3637. }
  3638. if($load < 0.01) {
  3639. $load = 0.01;
  3640. }
  3641. }
  3642. return $load;
  3643. }
  3644. sub time_to_login {
  3645. my $self = shift;
  3646. return $self->{'time_to_login'};
  3647. }
  3648. sub set_time_to_login {
  3649. my $self = shift;
  3650. $self->{'time_to_login'} = shift;
  3651. }
  3652. sub max_jobs_running {
  3653. my $self = shift;
  3654. if(not defined $self->{'max_jobs_running'}) {
  3655. my $nproc = $self->compute_number_of_processes($opt::jobs);
  3656. $self->set_max_jobs_running($nproc);
  3657. }
  3658. return $self->{'max_jobs_running'};
  3659. }
  3660. sub orig_max_jobs_running {
  3661. my $self = shift;
  3662. return $self->{'orig_max_jobs_running'};
  3663. }
  3664. sub compute_number_of_processes {
  3665. # Number of processes wanted and limited by system resources
  3666. # Returns:
  3667. # Number of processes
  3668. my $self = shift;
  3669. my $opt_P = shift;
  3670. my $wanted_processes = $self->user_requested_processes($opt_P);
  3671. if(not defined $wanted_processes) {
  3672. $wanted_processes = $Global::default_simultaneous_sshlogins;
  3673. }
  3674. ::debug("load", "Wanted procs: $wanted_processes\n");
  3675. my $system_limit =
  3676. $self->processes_available_by_system_limit($wanted_processes);
  3677. ::debug("load", "Limited to procs: $system_limit\n");
  3678. return $system_limit;
  3679. }
  3680. sub processes_available_by_system_limit {
  3681. # If the wanted number of processes is bigger than the system limits:
  3682. # Limit them to the system limits
  3683. # Limits are: File handles, number of input lines, processes,
  3684. # and taking > 1 second to spawn 10 extra processes
  3685. # Returns:
  3686. # Number of processes
  3687. my $self = shift;
  3688. my $wanted_processes = shift;
  3689. my $system_limit = 0;
  3690. my @jobs = ();
  3691. my $job;
  3692. my @args = ();
  3693. my $arg;
  3694. my $more_filehandles = 1;
  3695. my $max_system_proc_reached = 0;
  3696. my $slow_spawining_warning_printed = 0;
  3697. my $time = time;
  3698. my %fh;
  3699. my @children;
  3700. # Reserve filehandles
  3701. # perl uses 7 filehandles for something?
  3702. # parallel uses 1 for memory_usage
  3703. # parallel uses 4 for ?
  3704. for my $i (1..12) {
  3705. open($fh{"init-$i"}, "<", "/dev/null");
  3706. }
  3707. for(1..2) {
  3708. # System process limit
  3709. my $child;
  3710. if($child = fork()) {
  3711. push (@children,$child);
  3712. $Global::unkilled_children{$child} = 1;
  3713. } elsif(defined $child) {
  3714. # The child takes one process slot
  3715. # It will be killed later
  3716. $SIG{TERM} = $Global::original_sig{TERM};
  3717. sleep 10000000;
  3718. exit(0);
  3719. } else {
  3720. $max_system_proc_reached = 1;
  3721. }
  3722. }
  3723. my $count_jobs_already_read = $Global::JobQueue->next_seq();
  3724. my $wait_time_for_getting_args = 0;
  3725. my $start_time = time;
  3726. while(1) {
  3727. $system_limit >= $wanted_processes and last;
  3728. not $more_filehandles and last;
  3729. $max_system_proc_reached and last;
  3730. my $before_getting_arg = time;
  3731. if($Global::semaphore or $opt::pipe) {
  3732. # Skip: No need to get args
  3733. } elsif(defined $opt::retries and $count_jobs_already_read) {
  3734. # For retries we may need to run all jobs on this sshlogin
  3735. # so include the already read jobs for this sshlogin
  3736. $count_jobs_already_read--;
  3737. } else {
  3738. if($opt::X or $opt::m) {
  3739. # The arguments may have to be re-spread over several jobslots
  3740. # So pessimistically only read one arg per jobslot
  3741. # instead of a full commandline
  3742. if($Global::JobQueue->{'commandlinequeue'}->{'arg_queue'}->empty()) {
  3743. if($Global::JobQueue->empty()) {
  3744. last;
  3745. } else {
  3746. ($job) = $Global::JobQueue->get();
  3747. push(@jobs, $job);
  3748. }
  3749. } else {
  3750. ($arg) = $Global::JobQueue->{'commandlinequeue'}->{'arg_queue'}->get();
  3751. push(@args, $arg);
  3752. }
  3753. } else {
  3754. # If there are no more command lines, then we have a process
  3755. # per command line, so no need to go further
  3756. $Global::JobQueue->empty() and last;
  3757. ($job) = $Global::JobQueue->get();
  3758. push(@jobs, $job);
  3759. }
  3760. }
  3761. $wait_time_for_getting_args += time - $before_getting_arg;
  3762. $system_limit++;
  3763. # Every simultaneous process uses 2 filehandles when grouping
  3764. # Every simultaneous process uses 2 filehandles when compressing
  3765. $more_filehandles = open($fh{$system_limit*10}, "<", "/dev/null")
  3766. && open($fh{$system_limit*10+2}, "<", "/dev/null")
  3767. && open($fh{$system_limit*10+3}, "<", "/dev/null")
  3768. && open($fh{$system_limit*10+4}, "<", "/dev/null");
  3769. # System process limit
  3770. my $child;
  3771. if($child = fork()) {
  3772. push (@children,$child);
  3773. $Global::unkilled_children{$child} = 1;
  3774. } elsif(defined $child) {
  3775. # The child takes one process slot
  3776. # It will be killed later
  3777. $SIG{TERM} = $Global::original_sig{TERM};
  3778. sleep 10000000;
  3779. exit(0);
  3780. } else {
  3781. $max_system_proc_reached = 1;
  3782. }
  3783. my $forktime = time - $time - $wait_time_for_getting_args;
  3784. ::debug("run", "Time to fork $system_limit procs: $wait_time_for_getting_args ",
  3785. $forktime,
  3786. " (processes so far: ", $system_limit,")\n");
  3787. if($system_limit > 10 and
  3788. $forktime > 1 and
  3789. $forktime > $system_limit * 0.01
  3790. and not $slow_spawining_warning_printed) {
  3791. # It took more than 0.01 second to fork a processes on avg.
  3792. # Give the user a warning. He can press Ctrl-C if this
  3793. # sucks.
  3794. print $Global::original_stderr
  3795. ("parallel: Warning: Starting $system_limit processes took > $forktime sec.\n",
  3796. "Consider adjusting -j. Press CTRL-C to stop.\n");
  3797. $slow_spawining_warning_printed = 1;
  3798. }
  3799. }
  3800. # Cleanup: Close the files
  3801. for (values %fh) { close $_ }
  3802. # Cleanup: Kill the children
  3803. for my $pid (@children) {
  3804. kill 9, $pid;
  3805. waitpid($pid,0);
  3806. delete $Global::unkilled_children{$pid};
  3807. }
  3808. # Cleanup: Unget the command_lines or the @args
  3809. $Global::JobQueue->{'commandlinequeue'}->{'arg_queue'}->unget(@args);
  3810. $Global::JobQueue->unget(@jobs);
  3811. if($system_limit < $wanted_processes) {
  3812. # The system_limit is less than the wanted_processes
  3813. if($system_limit < 1 and not $Global::JobQueue->empty()) {
  3814. ::warning("Cannot spawn any jobs. Raising ulimit -u or /etc/security/limits.conf\n",
  3815. "or /proc/sys/kernel/pid_max may help.\n");
  3816. ::wait_and_exit(255);
  3817. }
  3818. if(not $more_filehandles) {
  3819. ::warning("Only enough file handles to run ", $system_limit, " jobs in parallel.\n",
  3820. "Running 'parallel -j0 -N", $system_limit, " --pipe parallel -j0' or ",
  3821. "raising ulimit -n or /etc/security/limits.conf may help.\n");
  3822. }
  3823. if($max_system_proc_reached) {
  3824. ::warning("Only enough available processes to run ", $system_limit,
  3825. " jobs in parallel. Raising ulimit -u or /etc/security/limits.conf\n",
  3826. "or /proc/sys/kernel/pid_max may help.\n");
  3827. }
  3828. }
  3829. if($] == 5.008008 and $system_limit > 1000) {
  3830. # https://savannah.gnu.org/bugs/?36942
  3831. $system_limit = 1000;
  3832. }
  3833. if($Global::JobQueue->empty()) {
  3834. $system_limit ||= 1;
  3835. }
  3836. if($self->string() ne ":" and
  3837. $system_limit > $Global::default_simultaneous_sshlogins) {
  3838. $system_limit =
  3839. $self->simultaneous_sshlogin_limit($system_limit);
  3840. }
  3841. return $system_limit;
  3842. }
  3843. sub simultaneous_sshlogin_limit {
  3844. # Test by logging in wanted number of times simultaneously
  3845. # Returns:
  3846. # min($wanted_processes,$working_simultaneous_ssh_logins-1)
  3847. my $self = shift;
  3848. my $wanted_processes = shift;
  3849. if($self->{'time_to_login'}) {
  3850. return $wanted_processes;
  3851. }
  3852. # Try twice because it guesses wrong sometimes
  3853. # Choose the minimal
  3854. my $ssh_limit =
  3855. ::min($self->simultaneous_sshlogin($wanted_processes),
  3856. $self->simultaneous_sshlogin($wanted_processes));
  3857. if($ssh_limit < $wanted_processes) {
  3858. my $serverlogin = $self->serverlogin();
  3859. ::warning("ssh to $serverlogin only allows ",
  3860. "for $ssh_limit simultaneous logins.\n",
  3861. "You may raise this by changing ",
  3862. "/etc/ssh/sshd_config:MaxStartups and MaxSessions on $serverlogin.\n",
  3863. "Using only ",$ssh_limit-1," connections ",
  3864. "to avoid race conditions.\n");
  3865. }
  3866. # Race condition can cause problem if using all sshs.
  3867. if($ssh_limit > 1) { $ssh_limit -= 1; }
  3868. return $ssh_limit;
  3869. }
  3870. sub simultaneous_sshlogin {
  3871. # Using $sshlogin try to see if we can do $wanted_processes
  3872. # simultaneous logins
  3873. # (ssh host echo simultaneouslogin & ssh host echo simultaneouslogin & ...)|grep simul|wc -l
  3874. # Returns:
  3875. # Number of succesful logins
  3876. my $self = shift;
  3877. my $wanted_processes = shift;
  3878. my $sshcmd = $self->sshcommand();
  3879. my $serverlogin = $self->serverlogin();
  3880. my $sshdelay = $opt::sshdelay ? "sleep $opt::sshdelay;" : "";
  3881. my $cmd = "$sshdelay$sshcmd $serverlogin echo simultaneouslogin </dev/null 2>&1 &"x$wanted_processes;
  3882. ::debug("init", "Trying $wanted_processes logins at $serverlogin\n");
  3883. open (my $simul_fh, "-|", "($cmd)|grep simultaneouslogin | wc -l") or
  3884. ::die_bug("simultaneouslogin");
  3885. my $ssh_limit = <$simul_fh>;
  3886. close $simul_fh;
  3887. chomp $ssh_limit;
  3888. return $ssh_limit;
  3889. }
  3890. sub set_ncpus {
  3891. my $self = shift;
  3892. $self->{'ncpus'} = shift;
  3893. }
  3894. sub user_requested_processes {
  3895. # Parse the number of processes that the user asked for using -j
  3896. # Returns:
  3897. # the number of processes to run on this sshlogin
  3898. my $self = shift;
  3899. my $opt_P = shift;
  3900. my $processes;
  3901. if(defined $opt_P) {
  3902. if($opt_P =~ /^\+(\d+)$/) {
  3903. # E.g. -P +2
  3904. my $j = $1;
  3905. $processes =
  3906. $self->ncpus() + $j;
  3907. } elsif ($opt_P =~ /^-(\d+)$/) {
  3908. # E.g. -P -2
  3909. my $j = $1;
  3910. $processes =
  3911. $self->ncpus() - $j;
  3912. } elsif ($opt_P =~ /^(\d+(\.\d+)?)\%$/) {
  3913. # E.g. -P 10.5%
  3914. my $j = $1;
  3915. $processes =
  3916. $self->ncpus() * $j / 100;
  3917. } elsif ($opt_P =~ /^(\d+)$/) {
  3918. $processes = $1;
  3919. if($processes == 0) {
  3920. # -P 0 = infinity (or at least close)
  3921. $processes = $Global::infinity;
  3922. }
  3923. } elsif (-f $opt_P) {
  3924. $Global::max_procs_file = $opt_P;
  3925. $Global::max_procs_file_last_mod = (stat($Global::max_procs_file))[9];
  3926. if(open(my $in_fh, "<", $Global::max_procs_file)) {
  3927. my $opt_P_file = join("",<$in_fh>);
  3928. close $in_fh;
  3929. $processes = $self->user_requested_processes($opt_P_file);
  3930. } else {
  3931. ::error("Cannot open $opt_P.\n");
  3932. ::wait_and_exit(255);
  3933. }
  3934. } else {
  3935. ::error("Parsing of --jobs/-j/--max-procs/-P failed.\n");
  3936. ::die_usage();
  3937. }
  3938. $processes = ::ceil($processes);
  3939. }
  3940. return $processes;
  3941. }
  3942. sub ncpus {
  3943. my $self = shift;
  3944. if(not defined $self->{'ncpus'}) {
  3945. my $sshcmd = $self->sshcommand();
  3946. my $serverlogin = $self->serverlogin();
  3947. if($serverlogin eq ":") {
  3948. if($opt::use_cpus_instead_of_cores) {
  3949. $self->{'ncpus'} = no_of_cpus();
  3950. } else {
  3951. $self->{'ncpus'} = no_of_cores();
  3952. }
  3953. } else {
  3954. my $ncpu;
  3955. my $sqe = ::shell_quote_scalar($Global::envvar);
  3956. if($opt::use_cpus_instead_of_cores) {
  3957. $ncpu = qx(echo|$sshcmd $serverlogin $sqe parallel --number-of-cpus);
  3958. } else {
  3959. ::debug("init",qq(echo|$sshcmd $serverlogin $sqe parallel --number-of-cores\n));
  3960. $ncpu = qx(echo|$sshcmd $serverlogin $sqe parallel --number-of-cores);
  3961. }
  3962. chomp $ncpu;
  3963. if($ncpu =~ /^\s*[0-9]+\s*$/s) {
  3964. $self->{'ncpus'} = $ncpu;
  3965. } else {
  3966. ::warning("Could not figure out ",
  3967. "number of cpus on $serverlogin ($ncpu). Using 1.\n");
  3968. $self->{'ncpus'} = 1;
  3969. }
  3970. }
  3971. }
  3972. return $self->{'ncpus'};
  3973. }
  3974. sub no_of_cpus {
  3975. # Returns:
  3976. # Number of physical CPUs
  3977. local $/="\n"; # If delimiter is set, then $/ will be wrong
  3978. my $no_of_cpus;
  3979. if ($^O eq 'linux') {
  3980. $no_of_cpus = no_of_cpus_gnu_linux() || no_of_cores_gnu_linux();
  3981. } elsif ($^O eq 'freebsd') {
  3982. $no_of_cpus = no_of_cpus_freebsd();
  3983. } elsif ($^O eq 'netbsd') {
  3984. $no_of_cpus = no_of_cpus_netbsd();
  3985. } elsif ($^O eq 'openbsd') {
  3986. $no_of_cpus = no_of_cpus_openbsd();
  3987. } elsif ($^O eq 'gnu') {
  3988. $no_of_cpus = no_of_cpus_hurd();
  3989. } elsif ($^O eq 'darwin') {
  3990. $no_of_cpus = no_of_cpus_darwin();
  3991. } elsif ($^O eq 'solaris') {
  3992. $no_of_cpus = no_of_cpus_solaris();
  3993. } elsif ($^O eq 'aix') {
  3994. $no_of_cpus = no_of_cpus_aix();
  3995. } elsif ($^O eq 'hpux') {
  3996. $no_of_cpus = no_of_cpus_hpux();
  3997. } elsif ($^O eq 'nto') {
  3998. $no_of_cpus = no_of_cpus_qnx();
  3999. } elsif ($^O eq 'svr5') {
  4000. $no_of_cpus = no_of_cpus_openserver();
  4001. } elsif ($^O eq 'irix') {
  4002. $no_of_cpus = no_of_cpus_irix();
  4003. } elsif ($^O eq 'dec_osf') {
  4004. $no_of_cpus = no_of_cpus_tru64();
  4005. } else {
  4006. $no_of_cpus = (no_of_cpus_gnu_linux()
  4007. || no_of_cpus_freebsd()
  4008. || no_of_cpus_netbsd()
  4009. || no_of_cpus_openbsd()
  4010. || no_of_cpus_hurd()
  4011. || no_of_cpus_darwin()
  4012. || no_of_cpus_solaris()
  4013. || no_of_cpus_aix()
  4014. || no_of_cpus_hpux()
  4015. || no_of_cpus_qnx()
  4016. || no_of_cpus_openserver()
  4017. || no_of_cpus_irix()
  4018. || no_of_cpus_tru64()
  4019. # Number of cores is better than no guess for #CPUs
  4020. || nproc()
  4021. );
  4022. }
  4023. if($no_of_cpus) {
  4024. chomp $no_of_cpus;
  4025. return $no_of_cpus;
  4026. } else {
  4027. ::warning("Cannot figure out number of cpus. Using 1.\n");
  4028. return 1;
  4029. }
  4030. }
  4031. sub no_of_cores {
  4032. # Returns:
  4033. # Number of CPU cores
  4034. local $/="\n"; # If delimiter is set, then $/ will be wrong
  4035. my $no_of_cores;
  4036. if ($^O eq 'linux') {
  4037. $no_of_cores = no_of_cores_gnu_linux();
  4038. } elsif ($^O eq 'freebsd') {
  4039. $no_of_cores = no_of_cores_freebsd();
  4040. } elsif ($^O eq 'netbsd') {
  4041. $no_of_cores = no_of_cores_netbsd();
  4042. } elsif ($^O eq 'openbsd') {
  4043. $no_of_cores = no_of_cores_openbsd();
  4044. } elsif ($^O eq 'gnu') {
  4045. $no_of_cores = no_of_cores_hurd();
  4046. } elsif ($^O eq 'darwin') {
  4047. $no_of_cores = no_of_cores_darwin();
  4048. } elsif ($^O eq 'solaris') {
  4049. $no_of_cores = no_of_cores_solaris();
  4050. } elsif ($^O eq 'aix') {
  4051. $no_of_cores = no_of_cores_aix();
  4052. } elsif ($^O eq 'hpux') {
  4053. $no_of_cores = no_of_cores_hpux();
  4054. } elsif ($^O eq 'nto') {
  4055. $no_of_cores = no_of_cores_qnx();
  4056. } elsif ($^O eq 'svr5') {
  4057. $no_of_cores = no_of_cores_openserver();
  4058. } elsif ($^O eq 'irix') {
  4059. $no_of_cores = no_of_cores_irix();
  4060. } elsif ($^O eq 'dec_osf') {
  4061. $no_of_cores = no_of_cores_tru64();
  4062. } else {
  4063. $no_of_cores = (no_of_cores_gnu_linux()
  4064. || no_of_cores_freebsd()
  4065. || no_of_cores_netbsd()
  4066. || no_of_cores_openbsd()
  4067. || no_of_cores_hurd()
  4068. || no_of_cores_darwin()
  4069. || no_of_cores_solaris()
  4070. || no_of_cores_aix()
  4071. || no_of_cores_hpux()
  4072. || no_of_cores_qnx()
  4073. || no_of_cores_openserver()
  4074. || no_of_cores_irix()
  4075. || no_of_cores_tru64()
  4076. || nproc()
  4077. );
  4078. }
  4079. if($no_of_cores) {
  4080. chomp $no_of_cores;
  4081. return $no_of_cores;
  4082. } else {
  4083. ::warning("Cannot figure out number of CPU cores. Using 1.\n");
  4084. return 1;
  4085. }
  4086. }
  4087. sub nproc {
  4088. # Returns:
  4089. # Number of cores using `nproc`
  4090. my $no_of_cores = `nproc 2>/dev/null`;
  4091. return $no_of_cores;
  4092. }
  4093. sub no_of_cpus_gnu_linux {
  4094. # Returns:
  4095. # Number of physical CPUs on GNU/Linux
  4096. # undef if not GNU/Linux
  4097. my $no_of_cpus;
  4098. my $no_of_cores;
  4099. if(-e "/proc/cpuinfo") {
  4100. $no_of_cpus = 0;
  4101. $no_of_cores = 0;
  4102. my %seen;
  4103. open(my $in_fh, "<", "/proc/cpuinfo") || return undef;
  4104. while(<$in_fh>) {
  4105. if(/^physical id.*[:](.*)/ and not $seen{$1}++) {
  4106. $no_of_cpus++;
  4107. }
  4108. /^processor.*[:]/i and $no_of_cores++;
  4109. }
  4110. close $in_fh;
  4111. }
  4112. return ($no_of_cpus||$no_of_cores);
  4113. }
  4114. sub no_of_cores_gnu_linux {
  4115. # Returns:
  4116. # Number of CPU cores on GNU/Linux
  4117. # undef if not GNU/Linux
  4118. my $no_of_cores;
  4119. if(-e "/proc/cpuinfo") {
  4120. $no_of_cores = 0;
  4121. open(my $in_fh, "<", "/proc/cpuinfo") || return undef;
  4122. while(<$in_fh>) {
  4123. /^processor.*[:]/i and $no_of_cores++;
  4124. }
  4125. close $in_fh;
  4126. }
  4127. return $no_of_cores;
  4128. }
  4129. sub no_of_cpus_freebsd {
  4130. # Returns:
  4131. # Number of physical CPUs on FreeBSD
  4132. # undef if not FreeBSD
  4133. my $no_of_cpus =
  4134. (`sysctl -a dev.cpu 2>/dev/null | grep \%parent | awk '{ print \$2 }' | uniq | wc -l | awk '{ print \$1 }'`
  4135. or
  4136. `sysctl hw.ncpu 2>/dev/null | awk '{ print \$2 }'`);
  4137. chomp $no_of_cpus;
  4138. return $no_of_cpus;
  4139. }
  4140. sub no_of_cores_freebsd {
  4141. # Returns:
  4142. # Number of CPU cores on FreeBSD
  4143. # undef if not FreeBSD
  4144. my $no_of_cores =
  4145. (`sysctl hw.ncpu 2>/dev/null | awk '{ print \$2 }'`
  4146. or
  4147. `sysctl -a hw 2>/dev/null | grep [^a-z]logicalcpu[^a-z] | awk '{ print \$2 }'`);
  4148. chomp $no_of_cores;
  4149. return $no_of_cores;
  4150. }
  4151. sub no_of_cpus_netbsd {
  4152. # Returns:
  4153. # Number of physical CPUs on NetBSD
  4154. # undef if not NetBSD
  4155. my $no_of_cpus = `sysctl -n hw.ncpu 2>/dev/null`;
  4156. chomp $no_of_cpus;
  4157. return $no_of_cpus;
  4158. }
  4159. sub no_of_cores_netbsd {
  4160. # Returns:
  4161. # Number of CPU cores on NetBSD
  4162. # undef if not NetBSD
  4163. my $no_of_cores = `sysctl -n hw.ncpu 2>/dev/null`;
  4164. chomp $no_of_cores;
  4165. return $no_of_cores;
  4166. }
  4167. sub no_of_cpus_openbsd {
  4168. # Returns:
  4169. # Number of physical CPUs on OpenBSD
  4170. # undef if not OpenBSD
  4171. my $no_of_cpus = `sysctl -n hw.ncpu 2>/dev/null`;
  4172. chomp $no_of_cpus;
  4173. return $no_of_cpus;
  4174. }
  4175. sub no_of_cores_openbsd {
  4176. # Returns:
  4177. # Number of CPU cores on OpenBSD
  4178. # undef if not OpenBSD
  4179. my $no_of_cores = `sysctl -n hw.ncpu 2>/dev/null`;
  4180. chomp $no_of_cores;
  4181. return $no_of_cores;
  4182. }
  4183. sub no_of_cpus_hurd {
  4184. # Returns:
  4185. # Number of physical CPUs on HURD
  4186. # undef if not HURD
  4187. my $no_of_cpus = `nproc`;
  4188. chomp $no_of_cpus;
  4189. return $no_of_cpus;
  4190. }
  4191. sub no_of_cores_hurd {
  4192. # Returns:
  4193. # Number of physical CPUs on HURD
  4194. # undef if not HURD
  4195. my $no_of_cores = `nproc`;
  4196. chomp $no_of_cores;
  4197. return $no_of_cores;
  4198. }
  4199. sub no_of_cpus_darwin {
  4200. # Returns:
  4201. # Number of physical CPUs on Mac Darwin
  4202. # undef if not Mac Darwin
  4203. my $no_of_cpus =
  4204. (`sysctl -n hw.physicalcpu 2>/dev/null`
  4205. or
  4206. `sysctl -a hw 2>/dev/null | grep [^a-z]physicalcpu[^a-z] | awk '{ print \$2 }'`);
  4207. return $no_of_cpus;
  4208. }
  4209. sub no_of_cores_darwin {
  4210. # Returns:
  4211. # Number of CPU cores on Mac Darwin
  4212. # undef if not Mac Darwin
  4213. my $no_of_cores =
  4214. (`sysctl -n hw.logicalcpu 2>/dev/null`
  4215. or
  4216. `sysctl -a hw 2>/dev/null | grep [^a-z]logicalcpu[^a-z] | awk '{ print \$2 }'`);
  4217. return $no_of_cores;
  4218. }
  4219. sub no_of_cpus_solaris {
  4220. # Returns:
  4221. # Number of physical CPUs on Solaris
  4222. # undef if not Solaris
  4223. if(-x "/usr/sbin/psrinfo") {
  4224. my @psrinfo = `/usr/sbin/psrinfo`;
  4225. if($#psrinfo >= 0) {
  4226. return $#psrinfo +1;
  4227. }
  4228. }
  4229. if(-x "/usr/sbin/prtconf") {
  4230. my @prtconf = `/usr/sbin/prtconf | grep cpu..instance`;
  4231. if($#prtconf >= 0) {
  4232. return $#prtconf +1;
  4233. }
  4234. }
  4235. return undef;
  4236. }
  4237. sub no_of_cores_solaris {
  4238. # Returns:
  4239. # Number of CPU cores on Solaris
  4240. # undef if not Solaris
  4241. if(-x "/usr/sbin/psrinfo") {
  4242. my @psrinfo = `/usr/sbin/psrinfo`;
  4243. if($#psrinfo >= 0) {
  4244. return $#psrinfo +1;
  4245. }
  4246. }
  4247. if(-x "/usr/sbin/prtconf") {
  4248. my @prtconf = `/usr/sbin/prtconf | grep cpu..instance`;
  4249. if($#prtconf >= 0) {
  4250. return $#prtconf +1;
  4251. }
  4252. }
  4253. return undef;
  4254. }
  4255. sub no_of_cpus_aix {
  4256. # Returns:
  4257. # Number of physical CPUs on AIX
  4258. # undef if not AIX
  4259. my $no_of_cpus = 0;
  4260. if(-x "/usr/sbin/lscfg") {
  4261. open(my $in_fh, "-|", "/usr/sbin/lscfg -vs |grep proc | wc -l|tr -d ' '")
  4262. || return undef;
  4263. $no_of_cpus = <$in_fh>;
  4264. chomp ($no_of_cpus);
  4265. close $in_fh;
  4266. }
  4267. return $no_of_cpus;
  4268. }
  4269. sub no_of_cores_aix {
  4270. # Returns:
  4271. # Number of CPU cores on AIX
  4272. # undef if not AIX
  4273. my $no_of_cores;
  4274. if(-x "/usr/bin/vmstat") {
  4275. open(my $in_fh, "-|", "/usr/bin/vmstat 1 1") || return undef;
  4276. while(<$in_fh>) {
  4277. /lcpu=([0-9]*) / and $no_of_cores = $1;
  4278. }
  4279. close $in_fh;
  4280. }
  4281. return $no_of_cores;
  4282. }
  4283. sub no_of_cpus_hpux {
  4284. # Returns:
  4285. # Number of physical CPUs on HP-UX
  4286. # undef if not HP-UX
  4287. my $no_of_cpus =
  4288. (`/usr/bin/mpsched -s 2>&1 | grep 'Locality Domain Count' | awk '{ print \$4 }'`);
  4289. return $no_of_cpus;
  4290. }
  4291. sub no_of_cores_hpux {
  4292. # Returns:
  4293. # Number of CPU cores on HP-UX
  4294. # undef if not HP-UX
  4295. my $no_of_cores =
  4296. (`/usr/bin/mpsched -s 2>&1 | grep 'Processor Count' | awk '{ print \$3 }'`);
  4297. return $no_of_cores;
  4298. }
  4299. sub no_of_cpus_qnx {
  4300. # Returns:
  4301. # Number of physical CPUs on QNX
  4302. # undef if not QNX
  4303. # BUG: It is now known how to calculate this.
  4304. my $no_of_cpus = 0;
  4305. return $no_of_cpus;
  4306. }
  4307. sub no_of_cores_qnx {
  4308. # Returns:
  4309. # Number of CPU cores on QNX
  4310. # undef if not QNX
  4311. # BUG: It is now known how to calculate this.
  4312. my $no_of_cores = 0;
  4313. return $no_of_cores;
  4314. }
  4315. sub no_of_cpus_openserver {
  4316. # Returns:
  4317. # Number of physical CPUs on SCO OpenServer
  4318. # undef if not SCO OpenServer
  4319. my $no_of_cpus = 0;
  4320. if(-x "/usr/sbin/psrinfo") {
  4321. my @psrinfo = `/usr/sbin/psrinfo`;
  4322. if($#psrinfo >= 0) {
  4323. return $#psrinfo +1;
  4324. }
  4325. }
  4326. return $no_of_cpus;
  4327. }
  4328. sub no_of_cores_openserver {
  4329. # Returns:
  4330. # Number of CPU cores on SCO OpenServer
  4331. # undef if not SCO OpenServer
  4332. my $no_of_cores = 0;
  4333. if(-x "/usr/sbin/psrinfo") {
  4334. my @psrinfo = `/usr/sbin/psrinfo`;
  4335. if($#psrinfo >= 0) {
  4336. return $#psrinfo +1;
  4337. }
  4338. }
  4339. return $no_of_cores;
  4340. }
  4341. sub no_of_cpus_irix {
  4342. # Returns:
  4343. # Number of physical CPUs on IRIX
  4344. # undef if not IRIX
  4345. my $no_of_cpus = `hinv | grep HZ | grep Processor | awk '{print \$1}'`;
  4346. return $no_of_cpus;
  4347. }
  4348. sub no_of_cores_irix {
  4349. # Returns:
  4350. # Number of CPU cores on IRIX
  4351. # undef if not IRIX
  4352. my $no_of_cores = `hinv | grep HZ | grep Processor | awk '{print \$1}'`;
  4353. return $no_of_cores;
  4354. }
  4355. sub no_of_cpus_tru64 {
  4356. # Returns:
  4357. # Number of physical CPUs on Tru64
  4358. # undef if not Tru64
  4359. my $no_of_cpus = `sizer -pr`;
  4360. return $no_of_cpus;
  4361. }
  4362. sub no_of_cores_tru64 {
  4363. # Returns:
  4364. # Number of CPU cores on Tru64
  4365. # undef if not Tru64
  4366. my $no_of_cores = `sizer -pr`;
  4367. return $no_of_cores;
  4368. }
  4369. sub sshcommand {
  4370. my $self = shift;
  4371. if (not defined $self->{'sshcommand'}) {
  4372. $self->sshcommand_of_sshlogin();
  4373. }
  4374. return $self->{'sshcommand'};
  4375. }
  4376. sub serverlogin {
  4377. my $self = shift;
  4378. if (not defined $self->{'serverlogin'}) {
  4379. $self->sshcommand_of_sshlogin();
  4380. }
  4381. return $self->{'serverlogin'};
  4382. }
  4383. sub sshcommand_of_sshlogin {
  4384. # 'server' -> ('ssh -S /tmp/parallel-ssh-RANDOM/host-','server')
  4385. # 'user@server' -> ('ssh','user@server')
  4386. # 'myssh user@server' -> ('myssh','user@server')
  4387. # 'myssh -l user server' -> ('myssh -l user','server')
  4388. # '/usr/bin/myssh -l user server' -> ('/usr/bin/myssh -l user','server')
  4389. # Returns:
  4390. # sshcommand - defaults to 'ssh'
  4391. # login@host
  4392. my $self = shift;
  4393. my ($sshcmd, $serverlogin);
  4394. if($self->{'string'} =~ /(.+) (\S+)$/) {
  4395. # Own ssh command
  4396. $sshcmd = $1; $serverlogin = $2;
  4397. } else {
  4398. # Normal ssh
  4399. if($opt::controlmaster) {
  4400. # Use control_path to make ssh faster
  4401. my $control_path = $self->control_path_dir()."/ssh-%r@%h:%p";
  4402. $sshcmd = "ssh -S ".$control_path;
  4403. $serverlogin = $self->{'string'};
  4404. if(not $self->{'control_path'}{$control_path}++) {
  4405. # Master is not running for this control_path
  4406. # Start it
  4407. my $pid = fork();
  4408. if($pid) {
  4409. $Global::sshmaster{$pid} ||= 1;
  4410. } else {
  4411. $SIG{'TERM'} = undef;
  4412. # Ignore the 'foo' being printed
  4413. open(STDOUT,">","/dev/null");
  4414. # OpenSSH_3.6.1p2 gives 'tcgetattr: Invalid argument' with -tt
  4415. # STDERR >/dev/null to ignore "process_mux_new_session: tcgetattr: Invalid argument"
  4416. open(STDERR,">","/dev/null");
  4417. open(STDIN,"<","/dev/null");
  4418. # Run a sleep that outputs data, so it will discover if the ssh connection closes.
  4419. my $sleep = ::shell_quote_scalar('$|=1;while(1){sleep 1;print "foo\n"}');
  4420. my @master = ("ssh", "-tt", "-MTS", $control_path, $serverlogin, "perl", "-e", $sleep);
  4421. exec(@master);
  4422. }
  4423. }
  4424. } else {
  4425. $sshcmd = "ssh"; $serverlogin = $self->{'string'};
  4426. }
  4427. }
  4428. $self->{'sshcommand'} = $sshcmd;
  4429. $self->{'serverlogin'} = $serverlogin;
  4430. }
  4431. sub control_path_dir {
  4432. # Returns:
  4433. # path to directory
  4434. my $self = shift;
  4435. if(not defined $self->{'control_path_dir'}) {
  4436. -e $ENV{'HOME'}."/.parallel" or mkdir $ENV{'HOME'}."/.parallel";
  4437. -e $ENV{'HOME'}."/.parallel/tmp" or mkdir $ENV{'HOME'}."/.parallel/tmp";
  4438. $self->{'control_path_dir'} =
  4439. File::Temp::tempdir($ENV{'HOME'}
  4440. . "/.parallel/tmp/control_path_dir-XXXX",
  4441. CLEANUP => 1);
  4442. }
  4443. return $self->{'control_path_dir'};
  4444. }
  4445. sub rsync_transfer_cmd {
  4446. # Command to run to transfer a file
  4447. # Input:
  4448. # $file = filename of file to transfer
  4449. # $workdir = destination dir
  4450. # Returns:
  4451. # $cmd = rsync command to run to transfer $file ("" if unreadable)
  4452. my $self = shift;
  4453. my $file = shift;
  4454. my $workdir = shift;
  4455. if(not -r $file) {
  4456. ::warning($file, " is not readable and will not be transferred.\n");
  4457. return "true";
  4458. }
  4459. my $rsync_destdir;
  4460. if($file =~ m:^/:) {
  4461. # rsync /foo/bar /
  4462. $rsync_destdir = "/";
  4463. } else {
  4464. $rsync_destdir = ::shell_quote_file($workdir);
  4465. }
  4466. $file = ::shell_quote_file($file);
  4467. my $sshcmd = $self->sshcommand();
  4468. my $rsync_opt = "-rlDzR -e" . ::shell_quote_scalar($sshcmd);
  4469. my $serverlogin = $self->serverlogin();
  4470. # Make dir if it does not exist
  4471. return "( $sshcmd $serverlogin mkdir -p $rsync_destdir;" .
  4472. rsync()." $rsync_opt $file $serverlogin:$rsync_destdir )";
  4473. }
  4474. sub cleanup_cmd {
  4475. # Command to run to remove the remote file
  4476. # Input:
  4477. # $file = filename to remove
  4478. # $workdir = destination dir
  4479. # Returns:
  4480. # $cmd = ssh command to run to remove $file and empty parent dirs
  4481. my $self = shift;
  4482. my $file = shift;
  4483. my $workdir = shift;
  4484. my $f = $file;
  4485. if($f =~ m:/\./:) {
  4486. # foo/bar/./baz/quux => workdir/baz/quux
  4487. # /foo/bar/./baz/quux => workdir/baz/quux
  4488. $f =~ s:.*/\./:$workdir/:;
  4489. } elsif($f =~ m:^[^/]:) {
  4490. # foo/bar => workdir/foo/bar
  4491. $f = $workdir."/".$f;
  4492. }
  4493. my @subdirs = split m:/:, ::dirname($f);
  4494. my @rmdir;
  4495. my $dir = "";
  4496. for(@subdirs) {
  4497. $dir .= $_."/";
  4498. unshift @rmdir, ::shell_quote_file($dir);
  4499. }
  4500. my $rmdir = @rmdir ? "rmdir @rmdir 2>/dev/null;" : "";
  4501. if(defined $opt::workdir and $opt::workdir eq "...") {
  4502. $rmdir .= "rm -rf " . ::shell_quote_file($workdir).';';
  4503. }
  4504. $f = ::shell_quote_file($f);
  4505. my $sshcmd = $self->sshcommand();
  4506. my $serverlogin = $self->serverlogin();
  4507. return "$sshcmd $serverlogin ".::shell_quote_scalar("(rm -f $f; $rmdir)");
  4508. }
  4509. {
  4510. my $rsync;
  4511. sub rsync {
  4512. # rsync 3.1.x uses protocol 31 which is unsupported by 2.5.7.
  4513. # If the version >= 3.1.0: downgrade to protocol 30
  4514. if(not $rsync) {
  4515. my @out = `rsync --version`;
  4516. for (@out) {
  4517. if(/version (\d+.\d+)(.\d+)?/) {
  4518. if($1 >= 3.1) {
  4519. # Version 3.1.0 or later: Downgrade to protocol 30
  4520. $rsync = "rsync --protocol 30";
  4521. } else {
  4522. $rsync = "rsync";
  4523. }
  4524. }
  4525. }
  4526. $rsync or ::die_bug("Cannot figure out version of rsync: @out");
  4527. }
  4528. return $rsync;
  4529. }
  4530. }
  4531. package JobQueue;
  4532. sub new {
  4533. my $class = shift;
  4534. my $commandref = shift;
  4535. my $read_from = shift;
  4536. my $context_replace = shift;
  4537. my $max_number_of_args = shift;
  4538. my $return_files = shift;
  4539. my $commandlinequeue = CommandLineQueue->new
  4540. ($commandref, $read_from, $context_replace, $max_number_of_args,
  4541. $return_files);
  4542. my @unget = ();
  4543. return bless {
  4544. 'unget' => \@unget,
  4545. 'commandlinequeue' => $commandlinequeue,
  4546. 'total_jobs' => undef,
  4547. }, ref($class) || $class;
  4548. }
  4549. sub get {
  4550. my $self = shift;
  4551. if(@{$self->{'unget'}}) {
  4552. my $job = shift @{$self->{'unget'}};
  4553. return ($job);
  4554. } else {
  4555. my $commandline = $self->{'commandlinequeue'}->get();
  4556. if(defined $commandline) {
  4557. my $job = Job->new($commandline);
  4558. return $job;
  4559. } else {
  4560. return undef;
  4561. }
  4562. }
  4563. }
  4564. sub unget {
  4565. my $self = shift;
  4566. unshift @{$self->{'unget'}}, @_;
  4567. }
  4568. sub empty {
  4569. my $self = shift;
  4570. my $empty = (not @{$self->{'unget'}})
  4571. && $self->{'commandlinequeue'}->empty();
  4572. ::debug("run", "JobQueue->empty $empty ");
  4573. return $empty;
  4574. }
  4575. sub total_jobs {
  4576. my $self = shift;
  4577. if(not defined $self->{'total_jobs'}) {
  4578. my $job;
  4579. my @queue;
  4580. my $start = time;
  4581. while($job = $self->get()) {
  4582. if(time - $start > 10) {
  4583. ::warning("Reading all arguments takes longer than 10 seconds.\n");
  4584. $opt::eta && ::warning("Consider removing --eta.\n");
  4585. $opt::bar && ::warning("Consider removing --bar.\n");
  4586. last;
  4587. }
  4588. push @queue, $job;
  4589. }
  4590. while($job = $self->get()) {
  4591. push @queue, $job;
  4592. }
  4593. $self->unget(@queue);
  4594. $self->{'total_jobs'} = $#queue+1;
  4595. }
  4596. return $self->{'total_jobs'};
  4597. }
  4598. sub next_seq {
  4599. my $self = shift;
  4600. return $self->{'commandlinequeue'}->seq();
  4601. }
  4602. sub quote_args {
  4603. my $self = shift;
  4604. return $self->{'commandlinequeue'}->quote_args();
  4605. }
  4606. package Job;
  4607. sub new {
  4608. my $class = shift;
  4609. my $commandlineref = shift;
  4610. return bless {
  4611. 'commandline' => $commandlineref, # CommandLine object
  4612. 'workdir' => undef, # --workdir
  4613. 'stdin' => undef, # filehandle for stdin (used for --pipe)
  4614. # filename for writing stdout to (used for --files)
  4615. 'remaining' => "", # remaining data not sent to stdin (used for --pipe)
  4616. 'datawritten' => 0, # amount of data sent via stdin (used for --pipe)
  4617. 'transfersize' => 0, # size of files using --transfer
  4618. 'returnsize' => 0, # size of files using --return
  4619. 'pid' => undef,
  4620. # hash of { SSHLogins => number of times the command failed there }
  4621. 'failed' => undef,
  4622. 'sshlogin' => undef,
  4623. # The commandline wrapped with rsync and ssh
  4624. 'sshlogin_wrap' => undef,
  4625. 'exitstatus' => undef,
  4626. 'exitsignal' => undef,
  4627. # Timestamp for timeout if any
  4628. 'timeout' => undef,
  4629. 'virgin' => 1,
  4630. }, ref($class) || $class;
  4631. }
  4632. sub replaced {
  4633. my $self = shift;
  4634. $self->{'commandline'} or ::die_bug("commandline empty");
  4635. return $self->{'commandline'}->replaced();
  4636. }
  4637. sub seq {
  4638. my $self = shift;
  4639. return $self->{'commandline'}->seq();
  4640. }
  4641. sub slot {
  4642. my $self = shift;
  4643. return $self->{'commandline'}->slot();
  4644. }
  4645. {
  4646. my($cattail);
  4647. sub cattail {
  4648. # Returns:
  4649. # $cattail = perl program for: cattail "decompress program" writerpid [file_to_decompress or stdin] [file_to_unlink]
  4650. if(not $cattail) {
  4651. $cattail = q{
  4652. # cat followed by tail.
  4653. # If $writerpid dead: finish after this round
  4654. use Fcntl;
  4655. $|=1;
  4656. my ($cmd, $writerpid, $read_file, $unlink_file) = @ARGV;
  4657. if($read_file) {
  4658. open(IN,"<",$read_file) || die("cattail: Cannot open $read_file");
  4659. } else {
  4660. *IN = *STDIN;
  4661. }
  4662. my $flags;
  4663. fcntl(IN, F_GETFL, $flags) || die $!; # Get the current flags on the filehandle
  4664. $flags |= O_NONBLOCK; # Add non-blocking to the flags
  4665. fcntl(IN, F_SETFL, $flags) || die $!; # Set the flags on the filehandle
  4666. open(OUT,"|-",$cmd) || die("cattail: Cannot run $cmd");
  4667. while(1) {
  4668. # clear EOF
  4669. seek(IN,0,1);
  4670. my $writer_running = kill 0, $writerpid;
  4671. $read = sysread(IN,$buf,32768);
  4672. if($read) {
  4673. # We can unlink the file now: The writer has written something
  4674. -e $unlink_file and unlink $unlink_file;
  4675. # Blocking print
  4676. while($buf) {
  4677. my $bytes_written = syswrite(OUT,$buf);
  4678. # syswrite may be interrupted by SIGHUP
  4679. substr($buf,0,$bytes_written) = "";
  4680. }
  4681. # Something printed: Wait less next time
  4682. $sleep /= 2;
  4683. } else {
  4684. if(eof(IN) and not $writer_running) {
  4685. # Writer dead: There will never be more to read => exit
  4686. exit;
  4687. }
  4688. # TODO This could probably be done more efficiently using select(2)
  4689. # Nothing read: Wait longer before next read
  4690. # Up to 30 milliseconds
  4691. $sleep = ($sleep < 30) ? ($sleep * 1.001 + 0.01) : ($sleep);
  4692. usleep($sleep);
  4693. }
  4694. }
  4695. sub usleep {
  4696. # Sleep this many milliseconds.
  4697. my $secs = shift;
  4698. select(undef, undef, undef, $secs/1000);
  4699. }
  4700. };
  4701. $cattail =~ s/#.*//mg;
  4702. $cattail =~ s/\s+/ /g;
  4703. }
  4704. return $cattail;
  4705. }
  4706. }
  4707. sub openoutputfiles {
  4708. # Open files for STDOUT and STDERR
  4709. # Set file handles in $self->fh
  4710. my $self = shift;
  4711. my ($outfhw, $errfhw, $outname, $errname);
  4712. if($opt::results) {
  4713. my $args_as_dirname = $self->{'commandline'}->args_as_dirname();
  4714. # Output in: prefix/name1/val1/name2/val2/stdout
  4715. my $dir = $opt::results."/".$args_as_dirname;
  4716. if(eval{ File::Path::mkpath($dir); }) {
  4717. # OK
  4718. } else {
  4719. # mkpath failed: Argument probably too long.
  4720. # Set $Global::max_file_length, which will keep the individual
  4721. # dir names shorter than the max length
  4722. max_file_name_length($opt::results);
  4723. $args_as_dirname = $self->{'commandline'}->args_as_dirname();
  4724. # prefix/name1/val1/name2/val2/
  4725. $dir = $opt::results."/".$args_as_dirname;
  4726. File::Path::mkpath($dir);
  4727. }
  4728. # prefix/name1/val1/name2/val2/stdout
  4729. $outname = "$dir/stdout";
  4730. if(not open($outfhw, "+>", $outname)) {
  4731. ::error("Cannot write to `$outname'.\n");
  4732. ::wait_and_exit(255);
  4733. }
  4734. # prefix/name1/val1/name2/val2/stderr
  4735. $errname = "$dir/stderr";
  4736. if(not open($errfhw, "+>", $errname)) {
  4737. ::error("Cannot write to `$errname'.\n");
  4738. ::wait_and_exit(255);
  4739. }
  4740. $self->set_fh(1,"unlink","");
  4741. $self->set_fh(2,"unlink","");
  4742. } elsif(not $opt::ungroup) {
  4743. # To group we create temporary files for STDOUT and STDERR
  4744. # To avoid the cleanup unlink the files immediately (but keep them open)
  4745. if(@Global::tee_jobs) {
  4746. # files must be removed when the tee is done
  4747. } elsif($opt::files) {
  4748. ($outfhw, $outname) = ::tmpfile(SUFFIX => ".par");
  4749. ($errfhw, $errname) = ::tmpfile(SUFFIX => ".par");
  4750. # --files => only remove stderr
  4751. $self->set_fh(1,"unlink","");
  4752. $self->set_fh(2,"unlink",$errname);
  4753. } else {
  4754. ($outfhw, $outname) = ::tmpfile(SUFFIX => ".par");
  4755. ($errfhw, $errname) = ::tmpfile(SUFFIX => ".par");
  4756. $self->set_fh(1,"unlink",$outname);
  4757. $self->set_fh(2,"unlink",$errname);
  4758. }
  4759. } else {
  4760. # --ungroup
  4761. open($outfhw,">&",$Global::fd{1}) || die;
  4762. open($errfhw,">&",$Global::fd{2}) || die;
  4763. # File name must be empty as it will otherwise be printed
  4764. $outname = "";
  4765. $errname = "";
  4766. $self->set_fh(1,"unlink",$outname);
  4767. $self->set_fh(2,"unlink",$errname);
  4768. }
  4769. # Set writing FD
  4770. $self->set_fh(1,'w',$outfhw);
  4771. $self->set_fh(2,'w',$errfhw);
  4772. $self->set_fh(1,'name',$outname);
  4773. $self->set_fh(2,'name',$errname);
  4774. if($opt::compress) {
  4775. # Send stdout to stdin for $opt::compress_program(1)
  4776. # Send stderr to stdin for $opt::compress_program(2)
  4777. # cattail get pid: $pid = $self->fh($fdno,'rpid');
  4778. my $cattail = cattail();
  4779. for my $fdno (1,2) {
  4780. my $wpid = open(my $fdw,"|-","$opt::compress_program >>".
  4781. $self->fh($fdno,'name')) || die $?;
  4782. $self->set_fh($fdno,'w',$fdw);
  4783. $self->set_fh($fdno,'wpid',$wpid);
  4784. my $rpid = open(my $fdr, "-|", "perl", "-e", $cattail,
  4785. $opt::decompress_program, $wpid,
  4786. $self->fh($fdno,'name'),$self->fh($fdno,'unlink')) || die $?;
  4787. $self->set_fh($fdno,'r',$fdr);
  4788. $self->set_fh($fdno,'rpid',$rpid);
  4789. }
  4790. } elsif(not $opt::ungroup) {
  4791. # Set reading FD if using --group (--ungroup does not need)
  4792. for my $fdno (1,2) {
  4793. # Re-open the file for reading
  4794. # so fdw can be closed separately
  4795. # and fdr can be seeked separately (for --line-buffer)
  4796. open(my $fdr,"<", $self->fh($fdno,'name')) ||
  4797. ::die_bug("fdr: Cannot open ".$self->fh($fdno,'name'));
  4798. $self->set_fh($fdno,'r',$fdr);
  4799. # Unlink if required
  4800. $Global::debug or unlink $self->fh($fdno,"unlink");
  4801. }
  4802. }
  4803. if($opt::linebuffer) {
  4804. # Set non-blocking when using --linebuffer
  4805. $Global::use{"Fcntl"} ||= eval "use Fcntl qw(:DEFAULT :flock); 1;";
  4806. for my $fdno (1,2) {
  4807. my $fdr = $self->fh($fdno,'r');
  4808. my $flags;
  4809. fcntl($fdr, &F_GETFL, $flags) || die $!; # Get the current flags on the filehandle
  4810. $flags |= &O_NONBLOCK; # Add non-blocking to the flags
  4811. fcntl($fdr, &F_SETFL, $flags) || die $!; # Set the flags on the filehandle
  4812. }
  4813. }
  4814. }
  4815. sub max_file_name_length {
  4816. # Figure out the max length of a subdir
  4817. # TODO and the max total length
  4818. # Ext4 = 255,130816
  4819. my $testdir = shift;
  4820. my $upper = 8_000_000;
  4821. my $len = 8;
  4822. my $dir="x"x$len;
  4823. do {
  4824. rmdir($testdir."/".$dir);
  4825. $len *= 16;
  4826. $dir="x"x$len;
  4827. } while (mkdir $testdir."/".$dir);
  4828. # Then search for the actual max length between $len/16 and $len
  4829. my $min = $len/16;
  4830. my $max = $len;
  4831. while($max-$min > 5) {
  4832. # If we are within 5 chars of the exact value:
  4833. # it is not worth the extra time to find the exact value
  4834. my $test = int(($min+$max)/2);
  4835. $dir="x"x$test;
  4836. if(mkdir $testdir."/".$dir) {
  4837. rmdir($testdir."/".$dir);
  4838. $min = $test;
  4839. } else {
  4840. $max = $test;
  4841. }
  4842. }
  4843. $Global::max_file_length = $min;
  4844. return $min;
  4845. }
  4846. sub set_fh {
  4847. # Set file handle
  4848. my ($self, $fd_no, $key, $fh) = @_;
  4849. $self->{'fd'}{$fd_no,$key} = $fh;
  4850. }
  4851. sub fh {
  4852. # Get file handle
  4853. my ($self, $fd_no, $key) = @_;
  4854. return $self->{'fd'}{$fd_no,$key};
  4855. }
  4856. sub write {
  4857. my $self = shift;
  4858. my $remaining_ref = shift;
  4859. my $stdin_fh = $self->fh(0,"w");
  4860. syswrite($stdin_fh,$$remaining_ref);
  4861. }
  4862. sub set_stdin_buffer {
  4863. # Copy stdin buffer from $block_ref up to $endpos
  4864. # Prepend with $header_ref
  4865. # Remove $recstart and $recend if needed
  4866. # Input:
  4867. # $header_ref = ref to $header to prepend
  4868. # $block_ref = ref to $block to pass on
  4869. # $endpos = length of $block to pass on
  4870. # $recstart = --recstart regexp
  4871. # $recend = --recend regexp
  4872. # Returns:
  4873. # N/A
  4874. my $self = shift;
  4875. my ($header_ref,$block_ref,$endpos,$recstart,$recend) = @_;
  4876. $self->{'stdin_buffer'} = ($self->virgin() ? $$header_ref : "").substr($$block_ref,0,$endpos);
  4877. if($opt::remove_rec_sep) {
  4878. remove_rec_sep(\$self->{'stdin_buffer'},$recstart,$recend);
  4879. }
  4880. $self->{'stdin_buffer_length'} = length $self->{'stdin_buffer'};
  4881. $self->{'stdin_buffer_pos'} = 0;
  4882. }
  4883. sub stdin_buffer_length {
  4884. my $self = shift;
  4885. return $self->{'stdin_buffer_length'};
  4886. }
  4887. sub remove_rec_sep {
  4888. my ($block_ref,$recstart,$recend) = @_;
  4889. # Remove record separator
  4890. $$block_ref =~ s/$recend$recstart//gos;
  4891. $$block_ref =~ s/^$recstart//os;
  4892. $$block_ref =~ s/$recend$//os;
  4893. }
  4894. sub non_block_write {
  4895. my $self = shift;
  4896. my $something_written = 0;
  4897. use POSIX qw(:errno_h);
  4898. # use Fcntl;
  4899. # my $flags = '';
  4900. for my $buf (substr($self->{'stdin_buffer'},$self->{'stdin_buffer_pos'})) {
  4901. my $in = $self->fh(0,"w");
  4902. # fcntl($in, F_GETFL, $flags)
  4903. # or die "Couldn't get flags for HANDLE : $!\n";
  4904. # $flags |= O_NONBLOCK;
  4905. # fcntl($in, F_SETFL, $flags)
  4906. # or die "Couldn't set flags for HANDLE: $!\n";
  4907. my $rv = syswrite($in, $buf);
  4908. if (!defined($rv) && $! == EAGAIN) {
  4909. # would block
  4910. $something_written = 0;
  4911. } elsif ($self->{'stdin_buffer_pos'}+$rv != $self->{'stdin_buffer_length'}) {
  4912. # incomplete write
  4913. # Remove the written part
  4914. $self->{'stdin_buffer_pos'} += $rv;
  4915. $something_written = $rv;
  4916. } else {
  4917. # successfully wrote everything
  4918. my $a="";
  4919. $self->set_stdin_buffer(\$a,\$a,"","");
  4920. $something_written = $rv;
  4921. }
  4922. }
  4923. ::debug("pipe", "Non-block: ", $something_written);
  4924. return $something_written;
  4925. }
  4926. sub virgin {
  4927. my $self = shift;
  4928. return $self->{'virgin'};
  4929. }
  4930. sub set_virgin {
  4931. my $self = shift;
  4932. $self->{'virgin'} = shift;
  4933. }
  4934. sub pid {
  4935. my $self = shift;
  4936. return $self->{'pid'};
  4937. }
  4938. sub set_pid {
  4939. my $self = shift;
  4940. $self->{'pid'} = shift;
  4941. }
  4942. sub starttime {
  4943. # Returns:
  4944. # UNIX-timestamp this job started
  4945. my $self = shift;
  4946. return sprintf("%.3f",$self->{'starttime'});
  4947. }
  4948. sub set_starttime {
  4949. my $self = shift;
  4950. my $starttime = shift || ::now();
  4951. $self->{'starttime'} = $starttime;
  4952. }
  4953. sub runtime {
  4954. # Returns:
  4955. # Run time in seconds
  4956. my $self = shift;
  4957. return sprintf("%.3f",int(($self->endtime() - $self->starttime())*1000)/1000);
  4958. }
  4959. sub endtime {
  4960. # Returns:
  4961. # UNIX-timestamp this job ended
  4962. # 0 if not ended yet
  4963. my $self = shift;
  4964. return ($self->{'endtime'} || 0);
  4965. }
  4966. sub set_endtime {
  4967. my $self = shift;
  4968. my $endtime = shift;
  4969. $self->{'endtime'} = $endtime;
  4970. }
  4971. sub timedout {
  4972. # Is the job timedout?
  4973. # Input:
  4974. # $delta_time = time that the job may run
  4975. # Returns:
  4976. # True or false
  4977. my $self = shift;
  4978. my $delta_time = shift;
  4979. return time > $self->{'starttime'} + $delta_time;
  4980. }
  4981. sub kill {
  4982. # Kill the job.
  4983. # Send the signals to (grand)*children and pid.
  4984. # If no signals: TERM TERM KILL
  4985. # Wait 200 ms after each TERM.
  4986. # Input:
  4987. # @signals = signals to send
  4988. my $self = shift;
  4989. my @signals = @_;
  4990. my @family_pids = $self->family_pids();
  4991. # Record this jobs as failed
  4992. $self->set_exitstatus(-1);
  4993. # Send two TERMs to give time to clean up
  4994. ::debug("run", "Kill seq ", $self->seq(), "\n");
  4995. my @send_signals = @signals || ("TERM", "TERM", "KILL");
  4996. for my $signal (@send_signals) {
  4997. my $alive = 0;
  4998. for my $pid (@family_pids) {
  4999. if(kill 0, $pid) {
  5000. # The job still running
  5001. kill $signal, $pid;
  5002. $alive = 1;
  5003. }
  5004. }
  5005. # If a signal was given as input, do not do the sleep below
  5006. @signals and next;
  5007. if($signal eq "TERM" and $alive) {
  5008. # Wait up to 200 ms between TERMs - but only if any pids are alive
  5009. my $sleep = 1;
  5010. for (my $sleepsum = 0; kill 0, $family_pids[0] and $sleepsum < 200;
  5011. $sleepsum += $sleep) {
  5012. $sleep = ::reap_usleep($sleep);
  5013. }
  5014. }
  5015. }
  5016. }
  5017. sub family_pids {
  5018. # Find the pids with this->pid as (grand)*parent
  5019. # Returns:
  5020. # @pids = pids of (grand)*children
  5021. my $self = shift;
  5022. my $pid = $self->pid();
  5023. my @pids;
  5024. my ($children_of_ref, $parent_of_ref, $name_of_ref) = ::pid_table();
  5025. my @more = ($pid);
  5026. # While more (grand)*children
  5027. while(@more) {
  5028. my @m;
  5029. push @pids, @more;
  5030. for my $parent (@more) {
  5031. if($children_of_ref->{$parent}) {
  5032. # add the children of this parent
  5033. push @m, @{$children_of_ref->{$parent}};
  5034. }
  5035. }
  5036. @more = @m;
  5037. }
  5038. return (@pids);
  5039. }
  5040. sub failed {
  5041. # return number of times failed for this $sshlogin
  5042. # Input:
  5043. # $sshlogin
  5044. # Returns:
  5045. # Number of times failed for $sshlogin
  5046. my $self = shift;
  5047. my $sshlogin = shift;
  5048. return $self->{'failed'}{$sshlogin};
  5049. }
  5050. sub failed_here {
  5051. # return number of times failed for the current $sshlogin
  5052. # Returns:
  5053. # Number of times failed for this sshlogin
  5054. my $self = shift;
  5055. return $self->{'failed'}{$self->sshlogin()};
  5056. }
  5057. sub add_failed {
  5058. # increase the number of times failed for this $sshlogin
  5059. my $self = shift;
  5060. my $sshlogin = shift;
  5061. $self->{'failed'}{$sshlogin}++;
  5062. }
  5063. sub add_failed_here {
  5064. # increase the number of times failed for the current $sshlogin
  5065. my $self = shift;
  5066. $self->{'failed'}{$self->sshlogin()}++;
  5067. }
  5068. sub reset_failed {
  5069. # increase the number of times failed for this $sshlogin
  5070. my $self = shift;
  5071. my $sshlogin = shift;
  5072. delete $self->{'failed'}{$sshlogin};
  5073. }
  5074. sub reset_failed_here {
  5075. # increase the number of times failed for this $sshlogin
  5076. my $self = shift;
  5077. delete $self->{'failed'}{$self->sshlogin()};
  5078. }
  5079. sub min_failed {
  5080. # Returns:
  5081. # the number of sshlogins this command has failed on
  5082. # the minimal number of times this command has failed
  5083. my $self = shift;
  5084. my $min_failures =
  5085. ::min(map { $self->{'failed'}{$_} } keys %{$self->{'failed'}});
  5086. my $number_of_sshlogins_failed_on = scalar keys %{$self->{'failed'}};
  5087. return ($number_of_sshlogins_failed_on,$min_failures);
  5088. }
  5089. sub total_failed {
  5090. # Returns:
  5091. # $total_failures = the number of times this command has failed
  5092. my $self = shift;
  5093. my $total_failures = 0;
  5094. for (values %{$self->{'failed'}}) {
  5095. $total_failures += $_;
  5096. }
  5097. return $total_failures;
  5098. }
  5099. sub wrapped {
  5100. # Wrap command with:
  5101. # * --shellquote
  5102. # * --nice
  5103. # * --cat
  5104. # * --fifo
  5105. # * --sshlogin
  5106. # * --pipepart (@Global::cat_partials)
  5107. # * --pipe
  5108. # * --tmux
  5109. # The ordering of the wrapping is important:
  5110. # * --nice/--cat/--fifo should be done on the remote machine
  5111. # * --pipepart/--pipe should be done on the local machine inside --tmux
  5112. # Uses:
  5113. # $Global::envvar
  5114. # $opt::shellquote
  5115. # $opt::nice
  5116. # $Global::shell
  5117. # $opt::cat
  5118. # $opt::fifo
  5119. # @Global::cat_partials
  5120. # $opt::pipe
  5121. # $opt::tmux
  5122. # Returns:
  5123. # $self->{'wrapped'} = the command wrapped with the above
  5124. my $self = shift;
  5125. if(not defined $self->{'wrapped'}) {
  5126. my $command = $Global::envvar.$self->replaced();
  5127. if($opt::shellquote) {
  5128. # Prepend echo
  5129. # and quote twice
  5130. $command = "echo " .
  5131. ::shell_quote_scalar(::shell_quote_scalar($command));
  5132. }
  5133. if($opt::nice) {
  5134. # Prepend \nice -n19 $SHELL -c
  5135. # and quote.
  5136. # The '\' before nice is needed to avoid tcsh's built-in
  5137. $command = '\nice'. " -n". $opt::nice. " ".
  5138. $Global::shell. " -c ".
  5139. ::shell_quote_scalar($command);
  5140. }
  5141. if($opt::cat) {
  5142. # Prepend 'cat > {};'
  5143. # Append '_EXIT=$?;(rm {};exit $_EXIT)'
  5144. $command =
  5145. $self->{'commandline'}->replace_placeholders(["cat > \257<\257>; "], 0, 0).
  5146. $command.
  5147. $self->{'commandline'}->replace_placeholders(
  5148. ["; _EXIT=\$?; rm \257<\257>; exit \$_EXIT"], 0, 0);
  5149. } elsif($opt::fifo) {
  5150. # Prepend 'mkfifo {}; ('
  5151. # Append ') & _PID=$!; cat > {}; wait $_PID; _EXIT=$?;(rm {};exit $_EXIT)'
  5152. $command =
  5153. $self->{'commandline'}->replace_placeholders(["mkfifo \257<\257>; ("], 0, 0).
  5154. $command.
  5155. $self->{'commandline'}->replace_placeholders([") & _PID=\$!; cat > \257<\257>; ",
  5156. "wait \$_PID; _EXIT=\$?; ",
  5157. "rm \257<\257>; exit \$_EXIT"],
  5158. 0,0);
  5159. }
  5160. # Wrap with ssh + tranferring of files
  5161. $command = $self->sshlogin_wrap($command);
  5162. if(@Global::cat_partials) {
  5163. # Prepend:
  5164. # < /tmp/foo perl -e 'while(@ARGV) { sysseek(STDIN,shift,0) || die; $left = shift; while($read = sysread(STDIN,$buf, ($left > 32768 ? 32768 : $left))){ $left -= $read; syswrite(STDOUT,$buf); } }' 0 0 0 11 |
  5165. $command = (shift @Global::cat_partials). "|". "(". $command. ")";
  5166. } elsif($opt::pipe) {
  5167. # Prepend EOF-detector to avoid starting $command if EOF.
  5168. # The $tmpfile might exist if run on a remote system - we accept that risk
  5169. my ($dummy_fh, $tmpfile) = ::tmpfile(SUFFIX => ".chr");
  5170. # Unlink to avoid leaving files if --dry-run or --sshlogin
  5171. unlink $tmpfile;
  5172. $command =
  5173. # Exit value:
  5174. # empty input = true
  5175. # some input = exit val from command
  5176. qq{ sh -c 'dd bs=1 count=1 of=$tmpfile 2>/dev/null'; }.
  5177. qq{ test \! -s "$tmpfile" && rm -f "$tmpfile" && exec true; }.
  5178. qq{ (cat $tmpfile; rm $tmpfile; cat - ) | }.
  5179. "($command);";
  5180. }
  5181. if($opt::tmux) {
  5182. # Wrap command with 'tmux'
  5183. $command = $self->tmux_wrap($command);
  5184. }
  5185. $self->{'wrapped'} = $command;
  5186. }
  5187. return $self->{'wrapped'};
  5188. }
  5189. sub set_sshlogin {
  5190. my $self = shift;
  5191. my $sshlogin = shift;
  5192. $self->{'sshlogin'} = $sshlogin;
  5193. delete $self->{'sshlogin_wrap'}; # If sshlogin is changed the wrap is wrong
  5194. delete $self->{'wrapped'};
  5195. }
  5196. sub sshlogin {
  5197. my $self = shift;
  5198. return $self->{'sshlogin'};
  5199. }
  5200. sub sshlogin_wrap {
  5201. # Wrap the command with the commands needed to run remotely
  5202. # Returns:
  5203. # $self->{'sshlogin_wrap'} = command wrapped with ssh+transfer commands
  5204. my $self = shift;
  5205. my $command = shift;
  5206. if(not defined $self->{'sshlogin_wrap'}) {
  5207. my $sshlogin = $self->sshlogin();
  5208. my $sshcmd = $sshlogin->sshcommand();
  5209. my $serverlogin = $sshlogin->serverlogin();
  5210. my ($pre,$post,$cleanup)=("","","");
  5211. if($serverlogin eq ":") {
  5212. # No transfer neeeded
  5213. $self->{'sshlogin_wrap'} = $command;
  5214. } else {
  5215. # --transfer
  5216. $pre .= $self->sshtransfer();
  5217. # --return
  5218. $post .= $self->sshreturn();
  5219. # --cleanup
  5220. $post .= $self->sshcleanup();
  5221. if($post) {
  5222. # We need to save the exit status of the job
  5223. $post = '_EXIT_status=$?; ' . $post . ' exit $_EXIT_status;';
  5224. }
  5225. # If the remote login shell is (t)csh then use 'setenv'
  5226. # otherwise use 'export'
  5227. # We cannot use parse_env_var(), as PARALLEL_SEQ changes
  5228. # for each command
  5229. my $parallel_env =
  5230. ($Global::envwarn
  5231. . q{ 'eval `echo $SHELL | grep "/t\\{0,1\\}csh" > /dev/null }
  5232. . q{ && echo setenv PARALLEL_SEQ '$PARALLEL_SEQ'\; }
  5233. . q{ setenv PARALLEL_PID '$PARALLEL_PID' }
  5234. . q{ || echo PARALLEL_SEQ='$PARALLEL_SEQ'\;export PARALLEL_SEQ\; }
  5235. . q{ PARALLEL_PID='$PARALLEL_PID'\;export PARALLEL_PID` ;' });
  5236. my $remote_pre = "";
  5237. my $ssh_options = "";
  5238. if(($opt::pipe or $opt::pipepart) and $opt::ctrlc
  5239. or
  5240. not ($opt::pipe or $opt::pipepart) and not $opt::noctrlc) {
  5241. # TODO Determine if this is needed
  5242. # Propagating CTRL-C to kill remote jobs requires
  5243. # remote jobs to be run with a terminal.
  5244. $ssh_options = "-tt -oLogLevel=quiet";
  5245. # $ssh_options = "";
  5246. # tty - check if we have a tty.
  5247. # stty:
  5248. # -onlcr - make output 8-bit clean
  5249. # isig - pass CTRL-C as signal
  5250. # -echo - do not echo input
  5251. $remote_pre .= ::shell_quote_scalar('tty >/dev/null && stty isig -onlcr -echo;');
  5252. }
  5253. if($opt::workdir) {
  5254. my $wd = ::shell_quote_file($self->workdir());
  5255. $remote_pre .= ::shell_quote_scalar("mkdir -p ") . $wd .
  5256. ::shell_quote_scalar("; cd ") . $wd .
  5257. # exit 255 (instead of exec false) would be the correct thing,
  5258. # but that fails on tcsh
  5259. ::shell_quote_scalar(qq{ || exec false;});
  5260. }
  5261. # This script is to solve the problem of
  5262. # * not mixing STDERR and STDOUT
  5263. # * terminating with ctrl-c
  5264. # It works on Linux but not Solaris
  5265. # Finishes on Solaris, but wrong exit code:
  5266. # $SIG{CHLD} = sub {exit ($?&127 ? 128+($?&127) : 1+$?>>8)};
  5267. # Hangs on Solaris, but correct exit code on Linux:
  5268. # $SIG{CHLD} = sub { $done = 1 };
  5269. # $p->poll;
  5270. my $signal_script = "perl -e '".
  5271. q{
  5272. use IO::Poll;
  5273. $SIG{CHLD} = sub { $done = 1 };
  5274. $p = IO::Poll->new;
  5275. $p->mask(STDOUT, POLLHUP);
  5276. $pid=fork; unless($pid) {setpgrp; exec $ENV{SHELL}, "-c", @ARGV; die "exec: $!\n"}
  5277. $p->poll;
  5278. kill SIGHUP, -${pid} unless $done;
  5279. wait; exit ($?&127 ? 128+($?&127) : 1+$?>>8)
  5280. } . "' ";
  5281. $signal_script =~ s/\s+/ /g;
  5282. $self->{'sshlogin_wrap'} =
  5283. ($pre
  5284. . "$sshcmd $ssh_options $serverlogin $parallel_env "
  5285. . $remote_pre
  5286. # . ::shell_quote_scalar($signal_script . ::shell_quote_scalar($command))
  5287. . ::shell_quote_scalar($command)
  5288. . ";"
  5289. . $post);
  5290. }
  5291. }
  5292. return $self->{'sshlogin_wrap'};
  5293. }
  5294. sub transfer {
  5295. # Files to transfer
  5296. # Returns:
  5297. # @transfer - File names of files to transfer
  5298. my $self = shift;
  5299. my @transfer = ();
  5300. $self->{'transfersize'} = 0;
  5301. if($opt::transfer) {
  5302. for my $record (@{$self->{'commandline'}{'arg_list'}}) {
  5303. # Merge arguments from records into args
  5304. for my $arg (@$record) {
  5305. CORE::push @transfer, $arg->orig();
  5306. # filesize
  5307. if(-e $arg->orig()) {
  5308. $self->{'transfersize'} += (stat($arg->orig()))[7];
  5309. }
  5310. }
  5311. }
  5312. }
  5313. return @transfer;
  5314. }
  5315. sub transfersize {
  5316. my $self = shift;
  5317. return $self->{'transfersize'};
  5318. }
  5319. sub sshtransfer {
  5320. # Returns for each transfer file:
  5321. # rsync $file remote:$workdir
  5322. my $self = shift;
  5323. my @pre;
  5324. my $sshlogin = $self->sshlogin();
  5325. my $workdir = $self->workdir();
  5326. for my $file ($self->transfer()) {
  5327. push @pre, $sshlogin->rsync_transfer_cmd($file,$workdir).";";
  5328. }
  5329. return join("",@pre);
  5330. }
  5331. sub return {
  5332. # Files to return
  5333. # Non-quoted and with {...} substituted
  5334. # Returns:
  5335. # @non_quoted_filenames
  5336. my $self = shift;
  5337. return $self->{'commandline'}->
  5338. replace_placeholders($self->{'commandline'}{'return_files'},0,0);
  5339. }
  5340. sub returnsize {
  5341. # This is called after the job has finished
  5342. # Returns:
  5343. # $number_of_bytes transferred in return
  5344. my $self = shift;
  5345. for my $file ($self->return()) {
  5346. if(-e $file) {
  5347. $self->{'returnsize'} += (stat($file))[7];
  5348. }
  5349. }
  5350. return $self->{'returnsize'};
  5351. }
  5352. sub sshreturn {
  5353. # Returns for each return-file:
  5354. # rsync remote:$workdir/$file .
  5355. my $self = shift;
  5356. my $sshlogin = $self->sshlogin();
  5357. my $sshcmd = $sshlogin->sshcommand();
  5358. my $serverlogin = $sshlogin->serverlogin();
  5359. my $rsync_opt = "-rlDzR -e".::shell_quote_scalar($sshcmd);
  5360. my $pre = "";
  5361. for my $file ($self->return()) {
  5362. $file =~ s:^\./::g; # Remove ./ if any
  5363. my $relpath = ($file !~ m:^/:); # Is the path relative?
  5364. my $cd = "";
  5365. my $wd = "";
  5366. if($relpath) {
  5367. # rsync -avR /foo/./bar/baz.c remote:/tmp/
  5368. # == (on old systems)
  5369. # rsync -avR --rsync-path="cd /foo; rsync" remote:bar/baz.c /tmp/
  5370. $wd = ::shell_quote_file($self->workdir()."/");
  5371. }
  5372. # Only load File::Basename if actually needed
  5373. $Global::use{"File::Basename"} ||= eval "use File::Basename; 1;";
  5374. # dir/./file means relative to dir, so remove dir on remote
  5375. $file =~ m:(.*)/\./:;
  5376. my $basedir = $1 ? ::shell_quote_file($1."/") : "";
  5377. my $nobasedir = $file;
  5378. $nobasedir =~ s:.*/\./::;
  5379. $cd = ::shell_quote_file(::dirname($nobasedir));
  5380. my $rsync_cd = '--rsync-path='.::shell_quote_scalar("cd $wd$cd; rsync");
  5381. my $basename = ::shell_quote_scalar(::shell_quote_file(basename($file)));
  5382. # --return
  5383. # mkdir -p /home/tange/dir/subdir/;
  5384. # rsync (--protocol 30) -rlDzR --rsync-path="cd /home/tange/dir/subdir/; rsync"
  5385. # server:file.gz /home/tange/dir/subdir/
  5386. $pre .= "mkdir -p $basedir$cd; ".$sshlogin->rsync()." $rsync_cd $rsync_opt $serverlogin:".
  5387. $basename . " ".$basedir.$cd.";";
  5388. }
  5389. return $pre;
  5390. }
  5391. sub sshcleanup {
  5392. # Return the sshcommand needed to remove the file
  5393. # Returns:
  5394. # ssh command needed to remove files from sshlogin
  5395. my $self = shift;
  5396. my $sshlogin = $self->sshlogin();
  5397. my $sshcmd = $sshlogin->sshcommand();
  5398. my $serverlogin = $sshlogin->serverlogin();
  5399. my $workdir = $self->workdir();
  5400. my $cleancmd = "";
  5401. for my $file ($self->cleanup()) {
  5402. my @subworkdirs = parentdirs_of($file);
  5403. $cleancmd .= $sshlogin->cleanup_cmd($file,$workdir).";";
  5404. }
  5405. if(defined $opt::workdir and $opt::workdir eq "...") {
  5406. $cleancmd .= "$sshcmd $serverlogin rm -rf " . ::shell_quote_scalar($workdir).';';
  5407. }
  5408. return $cleancmd;
  5409. }
  5410. sub cleanup {
  5411. # Returns:
  5412. # Files to remove at cleanup
  5413. my $self = shift;
  5414. if($opt::cleanup) {
  5415. my @transfer = $self->transfer();
  5416. my @return = $self->return();
  5417. return (@transfer,@return);
  5418. } else {
  5419. return ();
  5420. }
  5421. }
  5422. sub workdir {
  5423. # Returns:
  5424. # the workdir on a remote machine
  5425. my $self = shift;
  5426. if(not defined $self->{'workdir'}) {
  5427. my $workdir;
  5428. if(defined $opt::workdir) {
  5429. if($opt::workdir eq ".") {
  5430. # . means current dir
  5431. my $home = $ENV{'HOME'};
  5432. eval 'use Cwd';
  5433. my $cwd = cwd();
  5434. $workdir = $cwd;
  5435. if($home) {
  5436. # If homedir exists: remove the homedir from
  5437. # workdir if cwd starts with homedir
  5438. # E.g. /home/foo/my/dir => my/dir
  5439. # E.g. /tmp/my/dir => /tmp/my/dir
  5440. my ($home_dev, $home_ino) = (stat($home))[0,1];
  5441. my $parent = "";
  5442. my @dir_parts = split(m:/:,$cwd);
  5443. my $part;
  5444. while(defined ($part = shift @dir_parts)) {
  5445. $part eq "" and next;
  5446. $parent .= "/".$part;
  5447. my ($parent_dev, $parent_ino) = (stat($parent))[0,1];
  5448. if($parent_dev == $home_dev and $parent_ino == $home_ino) {
  5449. # dev and ino is the same: We found the homedir.
  5450. $workdir = join("/",@dir_parts);
  5451. last;
  5452. }
  5453. }
  5454. }
  5455. if($workdir eq "") {
  5456. $workdir = ".";
  5457. }
  5458. } elsif($opt::workdir eq "...") {
  5459. $workdir = ".parallel/tmp/" . ::hostname() . "-" . $$
  5460. . "-" . $self->seq();
  5461. } else {
  5462. $workdir = $opt::workdir;
  5463. # Rsync treats /./ special. We dont want that
  5464. $workdir =~ s:/\./:/:g; # Remove /./
  5465. $workdir =~ s:/+$::; # Remove ending / if any
  5466. $workdir =~ s:^\./::g; # Remove starting ./ if any
  5467. }
  5468. } else {
  5469. $workdir = ".";
  5470. }
  5471. $self->{'workdir'} = ::shell_quote_scalar($workdir);
  5472. }
  5473. return $self->{'workdir'};
  5474. }
  5475. sub parentdirs_of {
  5476. # Return:
  5477. # all parentdirs except . of this dir or file - sorted desc by length
  5478. my $d = shift;
  5479. my @parents = ();
  5480. while($d =~ s:/[^/]+$::) {
  5481. if($d ne ".") {
  5482. push @parents, $d;
  5483. }
  5484. }
  5485. return @parents;
  5486. }
  5487. sub start {
  5488. # Setup STDOUT and STDERR for a job and start it.
  5489. # Returns:
  5490. # job-object or undef if job not to run
  5491. my $job = shift;
  5492. # Get the shell command to be executed (possibly with ssh infront).
  5493. my $command = $job->wrapped();
  5494. if($Global::interactive or $Global::stderr_verbose) {
  5495. if($Global::interactive) {
  5496. print $Global::original_stderr "$command ?...";
  5497. open(my $tty_fh, "<", "/dev/tty") || ::die_bug("interactive-tty");
  5498. my $answer = <$tty_fh>;
  5499. close $tty_fh;
  5500. my $run_yes = ($answer =~ /^\s*y/i);
  5501. if (not $run_yes) {
  5502. $command = "true"; # Run the command 'true'
  5503. }
  5504. } else {
  5505. print $Global::original_stderr "$command\n";
  5506. }
  5507. }
  5508. my $pid;
  5509. $job->openoutputfiles();
  5510. my($stdout_fh,$stderr_fh) = ($job->fh(1,"w"),$job->fh(2,"w"));
  5511. local (*IN,*OUT,*ERR);
  5512. open OUT, '>&', $stdout_fh or ::die_bug("Can't redirect STDOUT: $!");
  5513. open ERR, '>&', $stderr_fh or ::die_bug("Can't dup STDOUT: $!");
  5514. if(($opt::dryrun or $Global::verbose) and $opt::ungroup) {
  5515. if($Global::verbose <= 1) {
  5516. print $stdout_fh $job->replaced(),"\n";
  5517. } else {
  5518. # Verbose level > 1: Print the rsync and stuff
  5519. print $stdout_fh $command,"\n";
  5520. }
  5521. }
  5522. if($opt::dryrun) {
  5523. $command = "true";
  5524. }
  5525. $ENV{'PARALLEL_SEQ'} = $job->seq();
  5526. $ENV{'PARALLEL_PID'} = $$;
  5527. ::debug("run", $Global::total_running, " processes . Starting (",
  5528. $job->seq(), "): $command\n");
  5529. if($opt::pipe) {
  5530. my ($stdin_fh);
  5531. # The eval is needed to catch exception from open3
  5532. eval {
  5533. $pid = ::open3($stdin_fh, ">&OUT", ">&ERR", $Global::shell, "-c", $command) ||
  5534. ::die_bug("open3-pipe");
  5535. 1;
  5536. };
  5537. $job->set_fh(0,"w",$stdin_fh);
  5538. } elsif(@opt::a and not $Global::stdin_in_opt_a and $job->seq() == 1
  5539. and $job->sshlogin()->string() eq ":") {
  5540. # Give STDIN to the first job if using -a (but only if running
  5541. # locally - otherwise CTRL-C does not work for other jobs Bug#36585)
  5542. *IN = *STDIN;
  5543. # The eval is needed to catch exception from open3
  5544. eval {
  5545. $pid = ::open3("<&IN", ">&OUT", ">&ERR", $Global::shell, "-c", $command) ||
  5546. ::die_bug("open3-a");
  5547. 1;
  5548. };
  5549. # Re-open to avoid complaining
  5550. open(STDIN, "<&", $Global::original_stdin)
  5551. or ::die_bug("dup-\$Global::original_stdin: $!");
  5552. } elsif ($opt::tty and not $Global::tty_taken and -c "/dev/tty" and
  5553. open(my $devtty_fh, "<", "/dev/tty")) {
  5554. # Give /dev/tty to the command if no one else is using it
  5555. *IN = $devtty_fh;
  5556. # The eval is needed to catch exception from open3
  5557. eval {
  5558. $pid = ::open3("<&IN", ">&OUT", ">&ERR", $Global::shell, "-c", $command) ||
  5559. ::die_bug("open3-/dev/tty");
  5560. $Global::tty_taken = $pid;
  5561. close $devtty_fh;
  5562. 1;
  5563. };
  5564. } else {
  5565. # The eval is needed to catch exception from open3
  5566. eval {
  5567. $pid = ::open3(::gensym, ">&OUT", ">&ERR", $Global::shell, "-c", $command) ||
  5568. ::die_bug("open3-gensym");
  5569. 1;
  5570. };
  5571. }
  5572. if($pid) {
  5573. # A job was started
  5574. $Global::total_running++;
  5575. $Global::total_started++;
  5576. $job->set_pid($pid);
  5577. $job->set_starttime();
  5578. $Global::running{$job->pid()} = $job;
  5579. if($opt::timeout) {
  5580. $Global::timeoutq->insert($job);
  5581. }
  5582. $Global::newest_job = $job;
  5583. $Global::newest_starttime = ::now();
  5584. return $job;
  5585. } else {
  5586. # No more processes
  5587. ::debug("run", "Cannot spawn more jobs.\n");
  5588. return undef;
  5589. }
  5590. }
  5591. sub tmux_wrap {
  5592. # Wrap command with tmux for session pPID
  5593. # Input:
  5594. # $actual_command = the actual command being run (incl ssh wrap)
  5595. my $self = shift;
  5596. my $actual_command = shift;
  5597. # Temporary file name. Used for fifo to communicate exit val
  5598. my ($fh, $tmpfile) = ::tmpfile(SUFFIX => ".tmx");
  5599. $Global::unlink{$tmpfile}=1;
  5600. close $fh;
  5601. unlink $tmpfile;
  5602. my $visual_command = $self->replaced();
  5603. my $title = $visual_command;
  5604. # ; causes problems
  5605. # ascii 194-245 annoys tmux
  5606. $title =~ tr/[\011-\016;\302-\365]//d;
  5607. my $tmux;
  5608. if($Global::total_running == 0) {
  5609. $tmux = "tmux new-session -s p$$ -d -n ".
  5610. ::shell_quote_scalar($title);
  5611. print $Global::original_stderr "See output with: tmux attach -t p$$\n";
  5612. } else {
  5613. $tmux = "tmux new-window -t p$$ -n ".::shell_quote_scalar($title);
  5614. }
  5615. return "mkfifo $tmpfile; $tmux ".
  5616. # Run in tmux
  5617. ::shell_quote_scalar(
  5618. "(".$actual_command.');(echo $?$status;echo 255) >'.$tmpfile."&".
  5619. "echo ".::shell_quote_scalar($visual_command).";".
  5620. "echo \007Job finished at: `date`;sleep 10").
  5621. # Run outside tmux
  5622. # Read the first line from the fifo and use that as status code
  5623. "; exit `perl -ne 'unlink \$ARGV; 1..1 and print' $tmpfile` ";
  5624. }
  5625. sub is_already_in_results {
  5626. # Do we already have results for this job?
  5627. # Returns:
  5628. # $job_already_run = bool whether there is output for this or not
  5629. my $job = $_[0];
  5630. my $args_as_dirname = $job->{'commandline'}->args_as_dirname();
  5631. # prefix/name1/val1/name2/val2/
  5632. my $dir = $opt::results."/".$args_as_dirname;
  5633. ::debug("run", "Test $dir/stdout", -e "$dir/stdout", "\n");
  5634. return -e "$dir/stdout";
  5635. }
  5636. sub is_already_in_joblog {
  5637. my $job = shift;
  5638. return vec($Global::job_already_run,$job->seq(),1);
  5639. }
  5640. sub set_job_in_joblog {
  5641. my $job = shift;
  5642. vec($Global::job_already_run,$job->seq(),1) = 1;
  5643. }
  5644. sub should_be_retried {
  5645. # Should this job be retried?
  5646. # Returns
  5647. # 0 - do not retry
  5648. # 1 - job queued for retry
  5649. my $self = shift;
  5650. if (not $opt::retries) {
  5651. return 0;
  5652. }
  5653. if(not $self->exitstatus()) {
  5654. # Completed with success. If there is a recorded failure: forget it
  5655. $self->reset_failed_here();
  5656. return 0
  5657. } else {
  5658. # The job failed. Should it be retried?
  5659. $self->add_failed_here();
  5660. if($self->total_failed() == $opt::retries) {
  5661. # This has been retried enough
  5662. return 0;
  5663. } else {
  5664. # This command should be retried
  5665. $self->set_endtime(undef);
  5666. $Global::JobQueue->unget($self);
  5667. ::debug("run", "Retry ", $self->seq(), "\n");
  5668. return 1;
  5669. }
  5670. }
  5671. }
  5672. sub print {
  5673. # Print the output of the jobs
  5674. # Returns: N/A
  5675. my $self = shift;
  5676. ::debug("print", ">>joboutput ", $self->replaced(), "\n");
  5677. if($opt::dryrun) {
  5678. # Nothing was printed to this job:
  5679. # cleanup tmp files if --files was set
  5680. unlink $self->fh(1,"name");
  5681. }
  5682. if($opt::pipe and $self->virgin()) {
  5683. # Skip --joblog, --dryrun, --verbose
  5684. } else {
  5685. if($Global::joblog and defined $self->{'exitstatus'}) {
  5686. # Add to joblog when finished
  5687. $self->print_joblog();
  5688. }
  5689. # Printing is only relevant for grouped/--line-buffer output.
  5690. $opt::ungroup and return;
  5691. # Check for disk full
  5692. exit_if_disk_full();
  5693. if(($opt::dryrun or $Global::verbose)
  5694. and
  5695. not $self->{'verbose_printed'}) {
  5696. $self->{'verbose_printed'}++;
  5697. if($Global::verbose <= 1) {
  5698. print STDOUT $self->replaced(),"\n";
  5699. } else {
  5700. # Verbose level > 1: Print the rsync and stuff
  5701. print STDOUT $self->wrapped(),"\n";
  5702. }
  5703. # If STDOUT and STDERR are merged,
  5704. # we want the command to be printed first
  5705. # so flush to avoid STDOUT being buffered
  5706. flush STDOUT;
  5707. }
  5708. }
  5709. for my $fdno (sort { $a <=> $b } keys %Global::fd) {
  5710. # Sort by file descriptor numerically: 1,2,3,..,9,10,11
  5711. $fdno == 0 and next;
  5712. my $out_fd = $Global::fd{$fdno};
  5713. my $in_fh = $self->fh($fdno,"r");
  5714. if(not $in_fh) {
  5715. if(not $Job::file_descriptor_warning_printed{$fdno}++) {
  5716. # ::warning("File descriptor $fdno not defined\n");
  5717. }
  5718. next;
  5719. }
  5720. ::debug("print", "File descriptor $fdno (", $self->fh($fdno,"name"), "):");
  5721. if($opt::files) {
  5722. # If --compress: $in_fh must be closed first.
  5723. close $self->fh($fdno,"w");
  5724. close $in_fh;
  5725. if($opt::pipe and $self->virgin()) {
  5726. # Nothing was printed to this job:
  5727. # cleanup unused tmp files if --files was set
  5728. for my $fdno (1,2) {
  5729. unlink $self->fh($fdno,"name");
  5730. unlink $self->fh($fdno,"unlink");
  5731. }
  5732. } elsif($fdno == 1 and $self->fh($fdno,"name")) {
  5733. print $out_fd $self->fh($fdno,"name"),"\n";
  5734. }
  5735. } elsif($opt::linebuffer) {
  5736. # Line buffered print out
  5737. $self->linebuffer_print($fdno,$in_fh,$out_fd);
  5738. } else {
  5739. my $buf;
  5740. close $self->fh($fdno,"w");
  5741. seek $in_fh, 0, 0;
  5742. # $in_fh is now ready for reading at position 0
  5743. if($opt::tag or defined $opt::tagstring) {
  5744. my $tag = $self->tag();
  5745. if($fdno == 2) {
  5746. # OpenSSH_3.6.1p2 gives 'tcgetattr: Invalid argument' with -tt
  5747. # This is a crappy way of ignoring it.
  5748. while(<$in_fh>) {
  5749. if(/^(client_process_control: )?tcgetattr: Invalid argument\n/) {
  5750. # Skip
  5751. } else {
  5752. print $out_fd $tag,$_;
  5753. }
  5754. # At most run the loop once
  5755. last;
  5756. }
  5757. }
  5758. while(<$in_fh>) {
  5759. print $out_fd $tag,$_;
  5760. }
  5761. } else {
  5762. my $buf;
  5763. if($fdno == 2) {
  5764. # OpenSSH_3.6.1p2 gives 'tcgetattr: Invalid argument' with -tt
  5765. # This is a crappy way of ignoring it.
  5766. sysread($in_fh,$buf,1_000);
  5767. $buf =~ s/^(client_process_control: )?tcgetattr: Invalid argument\n//;
  5768. print $out_fd $buf;
  5769. }
  5770. while(sysread($in_fh,$buf,32768)) {
  5771. print $out_fd $buf;
  5772. }
  5773. }
  5774. close $in_fh;
  5775. }
  5776. flush $out_fd;
  5777. }
  5778. ::debug("print", "<<joboutput @command\n");
  5779. }
  5780. sub linebuffer_print {
  5781. my $self = shift;
  5782. my ($fdno,$in_fh,$out_fd) = @_;
  5783. my $partial = \$self->{'partial_line',$fdno};
  5784. if(defined $self->{'exitstatus'}) {
  5785. # If the job is dead: close printing fh. Needed for --compress
  5786. close $self->fh($fdno,"w");
  5787. if($opt::compress) {
  5788. # Blocked reading in final round
  5789. $Global::use{"Fcntl"} ||= eval "use Fcntl qw(:DEFAULT :flock); 1;";
  5790. for my $fdno (1,2) {
  5791. my $fdr = $self->fh($fdno,'r');
  5792. my $flags;
  5793. fcntl($fdr, &F_GETFL, $flags) || die $!; # Get the current flags on the filehandle
  5794. $flags &= ~&O_NONBLOCK; # Remove non-blocking to the flags
  5795. fcntl($fdr, &F_SETFL, $flags) || die $!; # Set the flags on the filehandle
  5796. }
  5797. }
  5798. }
  5799. # This seek will clear EOF
  5800. seek $in_fh, tell($in_fh), 0;
  5801. # The read is non-blocking: The $in_fh is set to non-blocking.
  5802. # 32768 --tag = 5.1s
  5803. # 327680 --tag = 4.4s
  5804. # 1024000 --tag = 4.4s
  5805. # 3276800 --tag = 4.3s
  5806. # 32768000 --tag = 4.7s
  5807. # 10240000 --tag = 4.3s
  5808. while(read($in_fh,substr($$partial,length $$partial),3276800)) {
  5809. # Append to $$partial
  5810. # Find the last \n
  5811. my $i = rindex($$partial,"\n");
  5812. if($i != -1) {
  5813. # One or more complete lines were found
  5814. if($fdno == 2 and not $self->{'printed_first_line',$fdno}++) {
  5815. # OpenSSH_3.6.1p2 gives 'tcgetattr: Invalid argument' with -tt
  5816. # This is a crappy way of ignoring it.
  5817. $$partial =~ s/^(client_process_control: )?tcgetattr: Invalid argument\n//;
  5818. # Length of partial line has changed: Find the last \n again
  5819. $i = rindex($$partial,"\n");
  5820. }
  5821. if($opt::tag or defined $opt::tagstring) {
  5822. # Replace ^ with $tag within the full line
  5823. my $tag = $self->tag();
  5824. substr($$partial,0,$i+1) =~ s/^/$tag/gm;
  5825. # Length of partial line has changed: Find the last \n again
  5826. $i = rindex($$partial,"\n");
  5827. }
  5828. # Print up to and including the last \n
  5829. print $out_fd substr($$partial,0,$i+1);
  5830. # Remove the printed part
  5831. substr($$partial,0,$i+1)="";
  5832. }
  5833. }
  5834. if(defined $self->{'exitstatus'}) {
  5835. # If the job is dead: print the remaining partial line
  5836. # read remaining
  5837. if($$partial and ($opt::tag or defined $opt::tagstring)) {
  5838. my $tag = $self->tag();
  5839. $$partial =~ s/^/$tag/gm;
  5840. }
  5841. print $out_fd $$partial;
  5842. # Release the memory
  5843. $$partial = undef;
  5844. if($self->fh($fdno,"rpid") and CORE::kill 0, $self->fh($fdno,"rpid")) {
  5845. # decompress still running
  5846. } else {
  5847. # decompress done: close fh
  5848. close $in_fh;
  5849. }
  5850. }
  5851. }
  5852. sub print_joblog {
  5853. my $self = shift;
  5854. my $cmd;
  5855. if($Global::verbose <= 1) {
  5856. $cmd = $self->replaced();
  5857. } else {
  5858. # Verbose level > 1: Print the rsync and stuff
  5859. $cmd = "@command";
  5860. }
  5861. print $Global::joblog
  5862. join("\t", $self->seq(), $self->sshlogin()->string(),
  5863. $self->starttime(), sprintf("%10.3f",$self->runtime()),
  5864. $self->transfersize(), $self->returnsize(),
  5865. $self->exitstatus(), $self->exitsignal(), $cmd
  5866. ). "\n";
  5867. flush $Global::joblog;
  5868. $self->set_job_in_joblog();
  5869. }
  5870. sub tag {
  5871. my $self = shift;
  5872. if(not defined $self->{'tag'}) {
  5873. $self->{'tag'} = $self->{'commandline'}->
  5874. replace_placeholders([$opt::tagstring],0,0)."\t";
  5875. }
  5876. return $self->{'tag'};
  5877. }
  5878. sub hostgroups {
  5879. my $self = shift;
  5880. if(not defined $self->{'hostgroups'}) {
  5881. $self->{'hostgroups'} = $self->{'commandline'}->{'arg_list'}[0][0]->{'hostgroups'};
  5882. }
  5883. return @{$self->{'hostgroups'}};
  5884. }
  5885. sub exitstatus {
  5886. my $self = shift;
  5887. return $self->{'exitstatus'};
  5888. }
  5889. sub set_exitstatus {
  5890. my $self = shift;
  5891. my $exitstatus = shift;
  5892. if($exitstatus) {
  5893. # Overwrite status if non-zero
  5894. $self->{'exitstatus'} = $exitstatus;
  5895. } else {
  5896. # Set status but do not overwrite
  5897. # Status may have been set by --timeout
  5898. $self->{'exitstatus'} ||= $exitstatus;
  5899. }
  5900. }
  5901. sub exitsignal {
  5902. my $self = shift;
  5903. return $self->{'exitsignal'};
  5904. }
  5905. sub set_exitsignal {
  5906. my $self = shift;
  5907. my $exitsignal = shift;
  5908. $self->{'exitsignal'} = $exitsignal;
  5909. }
  5910. {
  5911. my ($disk_full_fh, $b8193, $name);
  5912. sub exit_if_disk_full {
  5913. # Checks if $TMPDIR is full by writing 8kb to a tmpfile
  5914. # If the disk is full: Exit immediately.
  5915. # Returns:
  5916. # N/A
  5917. if(not $disk_full_fh) {
  5918. ($disk_full_fh, $name) = ::tmpfile(SUFFIX => ".df");
  5919. unlink $name;
  5920. $b8193 = "x"x8193;
  5921. }
  5922. # Linux does not discover if a disk is full if writing <= 8192
  5923. # Tested on:
  5924. # bfs btrfs cramfs ext2 ext3 ext4 ext4dev jffs2 jfs minix msdos
  5925. # ntfs reiserfs tmpfs ubifs vfat xfs
  5926. # TODO this should be tested on different OS similar to this:
  5927. #
  5928. # doit() {
  5929. # sudo mount /dev/ram0 /mnt/loop; sudo chmod 1777 /mnt/loop
  5930. # seq 100000 | parallel --tmpdir /mnt/loop/ true &
  5931. # seq 6900000 > /mnt/loop/i && echo seq OK
  5932. # seq 6980868 > /mnt/loop/i
  5933. # seq 10000 > /mnt/loop/ii
  5934. # sleep 3
  5935. # sudo umount /mnt/loop/ || sudo umount -l /mnt/loop/
  5936. # echo >&2
  5937. # }
  5938. print $disk_full_fh $b8193;
  5939. if(not $disk_full_fh
  5940. or
  5941. tell $disk_full_fh == 0) {
  5942. ::error("Output is incomplete. Cannot append to buffer file in $ENV{'TMPDIR'}. Is the disk full?\n");
  5943. ::error("Change \$TMPDIR with --tmpdir or use --compress.\n");
  5944. ::wait_and_exit(255);
  5945. }
  5946. truncate $disk_full_fh, 0;
  5947. seek($disk_full_fh, 0, 0) || die;
  5948. }
  5949. }
  5950. package CommandLine;
  5951. sub new {
  5952. my $class = shift;
  5953. my $seq = shift;
  5954. my $commandref = shift;
  5955. $commandref || die;
  5956. my $arg_queue = shift;
  5957. my $context_replace = shift;
  5958. my $max_number_of_args = shift; # for -N and normal (-n1)
  5959. my $return_files = shift;
  5960. my $replacecount_ref = shift;
  5961. my $len_ref = shift;
  5962. my %replacecount = %$replacecount_ref;
  5963. my %len = %$len_ref;
  5964. for (keys %$replacecount_ref) {
  5965. # Total length of this replacement string {} replaced with all args
  5966. $len{$_} = 0;
  5967. }
  5968. return bless {
  5969. 'command' => $commandref,
  5970. 'seq' => $seq,
  5971. 'len' => \%len,
  5972. 'arg_list' => [],
  5973. 'arg_queue' => $arg_queue,
  5974. 'max_number_of_args' => $max_number_of_args,
  5975. 'replacecount' => \%replacecount,
  5976. 'context_replace' => $context_replace,
  5977. 'return_files' => $return_files,
  5978. 'replaced' => undef,
  5979. }, ref($class) || $class;
  5980. }
  5981. sub seq {
  5982. my $self = shift;
  5983. return $self->{'seq'};
  5984. }
  5985. {
  5986. my $max_slot_number;
  5987. sub slot {
  5988. # Find the number of a free job slot and return it
  5989. # Uses:
  5990. # @Global::slots
  5991. # Returns:
  5992. # $jobslot = number of jobslot
  5993. my $self = shift;
  5994. if(not $self->{'slot'}) {
  5995. if(not @Global::slots) {
  5996. # $Global::max_slot_number will typically be $Global::max_jobs_running
  5997. push @Global::slots, ++$max_slot_number;
  5998. }
  5999. $self->{'slot'} = shift @Global::slots;
  6000. }
  6001. return $self->{'slot'};
  6002. }
  6003. }
  6004. sub populate {
  6005. # Add arguments from arg_queue until the number of arguments or
  6006. # max line length is reached
  6007. # Uses:
  6008. # $Global::minimal_command_line_length
  6009. # $opt::cat
  6010. # $opt::fifo
  6011. # $Global::JobQueue
  6012. # $opt::m
  6013. # $opt::X
  6014. # $CommandLine::already_spread
  6015. # $Global::max_jobs_running
  6016. # Returns: N/A
  6017. my $self = shift;
  6018. my $next_arg;
  6019. my $max_len = $Global::minimal_command_line_length || Limits::Command::max_length();
  6020. if($opt::cat or $opt::fifo) {
  6021. # Generate a tempfile name that will be used as {}
  6022. my($outfh,$name) = ::tmpfile(SUFFIX => ".pip");
  6023. close $outfh;
  6024. # Unlink is needed if: ssh otheruser@localhost
  6025. unlink $name;
  6026. $Global::JobQueue->{'commandlinequeue'}->{'arg_queue'}->unget([Arg->new($name)]);
  6027. }
  6028. while (not $self->{'arg_queue'}->empty()) {
  6029. $next_arg = $self->{'arg_queue'}->get();
  6030. if(not defined $next_arg) {
  6031. next;
  6032. }
  6033. $self->push($next_arg);
  6034. if($self->len() >= $max_len) {
  6035. # Command length is now > max_length
  6036. # If there are arguments: remove the last
  6037. # If there are no arguments: Error
  6038. # TODO stuff about -x opt_x
  6039. if($self->number_of_args() > 1) {
  6040. # There is something to work on
  6041. $self->{'arg_queue'}->unget($self->pop());
  6042. last;
  6043. } else {
  6044. my $args = join(" ", map { $_->orig() } @$next_arg);
  6045. ::error("Command line too long (",
  6046. $self->len(), " >= ",
  6047. $max_len,
  6048. ") at number ",
  6049. $self->{'arg_queue'}->arg_number(),
  6050. ": ".
  6051. (substr($args,0,50))."...\n");
  6052. $self->{'arg_queue'}->unget($self->pop());
  6053. ::wait_and_exit(255);
  6054. }
  6055. }
  6056. if(defined $self->{'max_number_of_args'}) {
  6057. if($self->number_of_args() >= $self->{'max_number_of_args'}) {
  6058. last;
  6059. }
  6060. }
  6061. }
  6062. if(($opt::m or $opt::X) and not $CommandLine::already_spread
  6063. and $self->{'arg_queue'}->empty() and $Global::max_jobs_running) {
  6064. # -m or -X and EOF => Spread the arguments over all jobslots
  6065. # (unless they are already spread)
  6066. $CommandLine::already_spread ||= 1;
  6067. if($self->number_of_args() > 1) {
  6068. $self->{'max_number_of_args'} =
  6069. ::ceil($self->number_of_args()/$Global::max_jobs_running);
  6070. $Global::JobQueue->{'commandlinequeue'}->{'max_number_of_args'} =
  6071. $self->{'max_number_of_args'};
  6072. $self->{'arg_queue'}->unget($self->pop_all());
  6073. while($self->number_of_args() < $self->{'max_number_of_args'}) {
  6074. $self->push($self->{'arg_queue'}->get());
  6075. }
  6076. }
  6077. }
  6078. }
  6079. sub push {
  6080. # Add one or more records as arguments
  6081. # Returns: N/A
  6082. my $self = shift;
  6083. my $record = shift;
  6084. push @{$self->{'arg_list'}}, $record;
  6085. my $quote_arg = $Global::noquote ? 0 : not $Global::quoting;
  6086. my $rep;
  6087. for my $arg (@$record) {
  6088. if(defined $arg) {
  6089. for my $perlexpr (keys %{$self->{'replacecount'}}) {
  6090. # 50% faster than below
  6091. $self->{'len'}{$perlexpr} += length $arg->replace($perlexpr,$quote_arg,$self);
  6092. # $rep = $arg->replace($perlexpr,$quote_arg,$self);
  6093. # $self->{'len'}{$perlexpr} += length $rep;
  6094. # ::debug("length", "Length: ", length $rep,
  6095. # "(", $perlexpr, "=>", $rep, ")\n");
  6096. }
  6097. }
  6098. }
  6099. }
  6100. sub pop {
  6101. # Remove last argument
  6102. # Returns:
  6103. # the last record
  6104. my $self = shift;
  6105. my $record = pop @{$self->{'arg_list'}};
  6106. my $quote_arg = $Global::noquote ? 0 : not $Global::quoting;
  6107. for my $arg (@$record) {
  6108. if(defined $arg) {
  6109. for my $perlexpr (keys %{$self->{'replacecount'}}) {
  6110. $self->{'len'}{$perlexpr} -=
  6111. length $arg->replace($perlexpr,$quote_arg,$self);
  6112. }
  6113. }
  6114. }
  6115. return $record;
  6116. }
  6117. sub pop_all {
  6118. # Remove all arguments and zeros the length of replacement strings
  6119. # Returns:
  6120. # all records
  6121. my $self = shift;
  6122. my @popped = @{$self->{'arg_list'}};
  6123. for my $replacement_string (keys %{$self->{'replacecount'}}) {
  6124. $self->{'len'}{$replacement_string} = 0;
  6125. }
  6126. $self->{'arg_list'} = [];
  6127. return @popped;
  6128. }
  6129. sub number_of_args {
  6130. # The number of records
  6131. # Returns:
  6132. # number of records
  6133. my $self = shift;
  6134. # Ftq rudef oaawuq ime dqxqmeqp az 2011-01-24 mzp ime iaz nk MQhmd
  6135. # Mdzrvadp Nvmdymeaz az 2011-04-10. Ftue oaawuq dqxqmeqp az
  6136. # 2013-08-18 ue m nuf tmdpqd me kag tmhq fa geq daf14. Bxqmeq
  6137. # qymux oaawuq@fmzsq.pw itqz kag dqmp ftue.
  6138. #
  6139. # U my ftq ymuzfmuzqd ar m buqoq ar rdqq earfimdq omxxqp SZG
  6140. # Bmdmxxqx. Rdqq earfimdq sgmdmzfqqe kag mooqee fa ftq eagdoq
  6141. # oapq, ngf U tmhq nqqz iazpqduzs tai ymzk mofgmxxk _dqmp_ ftq
  6142. # eagdoq oapq.
  6143. #
  6144. # Fa fqef ftue U bgf uz m oayyqzf fqxxuzs bqabxq fa qymux yq itqz
  6145. # ftqk dqmp ftue. Ftq oayyqzf ime bgf uz m eqofuaz ar ftq oapq
  6146. # ftmf za azq iagxp xaaw fa ruj ad uybdahq ftq earfimdq - ea ftq
  6147. # eagdoq oapq qcguhmxqzf fa m pgefk oadzqd. Fa ymwq egdq ftq
  6148. # oayyqzf iagxp zaf etai gb ur eayq azq vgef sdqbbqp ftdagst ftq
  6149. # eagdoq oapq U daf13'qp ftq eagdoq oapq
  6150. # tffb://qz.iuwubqpum.ads/iuwu/DAF13
  6151. #
  6152. # 2.5 yazfte xmfqd U dqoquhqp mz qymux rday eayqazq ita zaf azxk
  6153. # ymzmsqp fa ruzp ftq oayyqzf, ngf mxea ymzmsqp fa sgqee ftq oapq
  6154. # tmp fa nq daf13'qp.
  6155. #
  6156. # Ftue nduzse yq fa ftq oazoxgeuaz ftmf ftqdq _mdq_ bqabxq, ita
  6157. # mdq zaf mrruxumfqp iuft ftq bdavqof, ftmf iuxx dqmp ftq eagdoq
  6158. # oapq - ftagst uf ymk zaf tmbbqz hqdk arfqz.
  6159. #
  6160. # This is really the number of records
  6161. return $#{$self->{'arg_list'}}+1;
  6162. }
  6163. sub number_of_recargs {
  6164. # The number of args in records
  6165. # Returns:
  6166. # number of args records
  6167. my $self = shift;
  6168. my $sum = 0;
  6169. my $nrec = scalar @{$self->{'arg_list'}};
  6170. if($nrec) {
  6171. $sum = $nrec * (scalar @{$self->{'arg_list'}[0]});
  6172. }
  6173. return $sum;
  6174. }
  6175. sub args_as_string {
  6176. # Returns:
  6177. # all unmodified arguments joined with ' ' (similar to {})
  6178. my $self = shift;
  6179. return (join " ", map { $_->orig() }
  6180. map { @$_ } @{$self->{'arg_list'}});
  6181. }
  6182. sub args_as_dirname {
  6183. # Returns:
  6184. # all unmodified arguments joined with '/' (similar to {})
  6185. # \t \0 \\ and / are quoted as: \t \0 \\ \_
  6186. # If $Global::max_file_length: Keep subdirs < $Global::max_file_length
  6187. my $self = shift;
  6188. my @res = ();
  6189. for my $rec_ref (@{$self->{'arg_list'}}) {
  6190. # If headers are used, sort by them.
  6191. # Otherwise keep the order from the command line.
  6192. my @header_indexes_sorted = header_indexes_sorted($#$rec_ref+1);
  6193. for my $n (@header_indexes_sorted) {
  6194. CORE::push(@res,
  6195. $Global::input_source_header{$n},
  6196. map { my $s = $_;
  6197. # \t \0 \\ and / are quoted as: \t \0 \\ \_
  6198. $s =~ s/\\/\\\\/g;
  6199. $s =~ s/\t/\\t/g;
  6200. $s =~ s/\0/\\0/g;
  6201. $s =~ s:/:\\_:g;
  6202. if($Global::max_file_length) {
  6203. # Keep each subdir shorter than the longest
  6204. # allowed file name
  6205. $s = substr($s,0,$Global::max_file_length);
  6206. }
  6207. $s; }
  6208. $rec_ref->[$n-1]->orig());
  6209. }
  6210. }
  6211. return join "/", @res;
  6212. }
  6213. sub header_indexes_sorted {
  6214. # Sort headers first by number then by name.
  6215. # E.g.: 1a 1b 11a 11b
  6216. # Returns:
  6217. # Indexes of %Global::input_source_header sorted
  6218. my $max_col = shift;
  6219. no warnings 'numeric';
  6220. for my $col (1 .. $max_col) {
  6221. # Make sure the header is defined. If it is not: use column number
  6222. if(not defined $Global::input_source_header{$col}) {
  6223. $Global::input_source_header{$col} = $col;
  6224. }
  6225. }
  6226. my @header_indexes_sorted = sort {
  6227. # Sort headers numerically then asciibetically
  6228. $Global::input_source_header{$a} <=> $Global::input_source_header{$b}
  6229. or
  6230. $Global::input_source_header{$a} cmp $Global::input_source_header{$b}
  6231. } 1 .. $max_col;
  6232. return @header_indexes_sorted;
  6233. }
  6234. sub len {
  6235. # Uses:
  6236. # $opt::shellquote
  6237. # The length of the command line with args substituted
  6238. my $self = shift;
  6239. my $len = 0;
  6240. # Add length of the original command with no args
  6241. # Length of command w/ all replacement args removed
  6242. $len += $self->{'len'}{'noncontext'} + @{$self->{'command'}} -1;
  6243. ::debug("length", "noncontext + command: $len\n");
  6244. my $recargs = $self->number_of_recargs();
  6245. if($self->{'context_replace'}) {
  6246. # Context is duplicated for each arg
  6247. $len += $recargs * $self->{'len'}{'context'};
  6248. for my $replstring (keys %{$self->{'replacecount'}}) {
  6249. # If the replacements string is more than once: mulitply its length
  6250. $len += $self->{'len'}{$replstring} *
  6251. $self->{'replacecount'}{$replstring};
  6252. ::debug("length", $replstring, " ", $self->{'len'}{$replstring}, "*",
  6253. $self->{'replacecount'}{$replstring}, "\n");
  6254. }
  6255. # echo 11 22 33 44 55 66 77 88 99 1010
  6256. # echo 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10
  6257. # 5 + ctxgrp*arg
  6258. ::debug("length", "Ctxgrp: ", $self->{'len'}{'contextgroups'},
  6259. " Groups: ", $self->{'len'}{'noncontextgroups'}, "\n");
  6260. # Add space between context groups
  6261. $len += ($recargs-1) * ($self->{'len'}{'contextgroups'});
  6262. } else {
  6263. # Each replacement string may occur several times
  6264. # Add the length for each time
  6265. $len += 1*$self->{'len'}{'context'};
  6266. ::debug("length", "context+noncontext + command: $len\n");
  6267. for my $replstring (keys %{$self->{'replacecount'}}) {
  6268. # (space between regargs + length of replacement)
  6269. # * number this replacement is used
  6270. $len += ($recargs -1 + $self->{'len'}{$replstring}) *
  6271. $self->{'replacecount'}{$replstring};
  6272. }
  6273. }
  6274. if($opt::nice) {
  6275. # Pessimistic length if --nice is set
  6276. # Worse than worst case: every char needs to be quoted with \
  6277. $len *= 2;
  6278. }
  6279. if($Global::quoting) {
  6280. # Pessimistic length if -q is set
  6281. # Worse than worst case: every char needs to be quoted with \
  6282. $len *= 2;
  6283. }
  6284. if($opt::shellquote) {
  6285. # Pessimistic length if --shellquote is set
  6286. # Worse than worst case: every char needs to be quoted with \ twice
  6287. $len *= 4;
  6288. }
  6289. # If we are using --env, add the prefix for that, too.
  6290. $len += $Global::envvarlen;
  6291. return $len;
  6292. }
  6293. sub replaced {
  6294. # Uses:
  6295. # $Global::noquote
  6296. # $Global::quoting
  6297. # Returns:
  6298. # $replaced = command with place holders replaced and prepended
  6299. my $self = shift;
  6300. if(not defined $self->{'replaced'}) {
  6301. # Don't quote arguments if the input is the full command line
  6302. my $quote_arg = $Global::noquote ? 0 : not $Global::quoting;
  6303. $self->{'replaced'} = $self->replace_placeholders($self->{'command'},$Global::quoting,$quote_arg);
  6304. my $len = length $self->{'replaced'};
  6305. if ($len != $self->len()) {
  6306. ::debug("length", $len, " != ", $self->len(), " ", $self->{'replaced'}, "\n");
  6307. } else {
  6308. ::debug("length", $len, " == ", $self->len(), " ", $self->{'replaced'}, "\n");
  6309. }
  6310. }
  6311. return $self->{'replaced'};
  6312. }
  6313. sub replace_placeholders {
  6314. # Replace foo{}bar with fooargbar
  6315. # Input:
  6316. # $targetref = command as shell words
  6317. # $quote = should everything be quoted?
  6318. # $quote_arg = should replaced arguments be quoted?
  6319. # Returns:
  6320. # @target with placeholders replaced
  6321. my $self = shift;
  6322. my $targetref = shift;
  6323. my $quote = shift;
  6324. my $quote_arg = shift;
  6325. my $context_replace = $self->{'context_replace'};
  6326. my @target = @$targetref;
  6327. ::debug("replace", "Replace @target\n");
  6328. # -X = context replace
  6329. # maybe multiple input sources
  6330. # maybe --xapply
  6331. if(not @target) {
  6332. # @target is empty: Return empty array
  6333. return @target;
  6334. }
  6335. # Fish out the words that have replacement strings in them
  6336. my %word;
  6337. for (@target) {
  6338. my $tt = $_;
  6339. ::debug("replace", "Target: $tt");
  6340. # a{1}b{}c{}d
  6341. # a{=1 $_=$_ =}b{= $_=$_ =}c{= $_=$_ =}d
  6342. # a\257<1 $_=$_ \257>b\257< $_=$_ \257>c\257< $_=$_ \257>d
  6343. # A B C => aAbA B CcA B Cd
  6344. # -X A B C => aAbAcAd aAbBcBd aAbCcCd
  6345. if($context_replace) {
  6346. while($tt =~ s/([^\s\257]* # before {=
  6347. (?:
  6348. \257< # {=
  6349. [^\257]*? # The perl expression
  6350. \257> # =}
  6351. [^\s\257]* # after =}
  6352. )+)/ /x) {
  6353. # $1 = pre \257 perlexpr \257 post
  6354. $word{"$1"} ||= 1;
  6355. }
  6356. } else {
  6357. while($tt =~ s/( (?: \257<([^\257]*?)\257>) )//x) {
  6358. # $f = \257 perlexpr \257
  6359. $word{$1} ||= 1;
  6360. }
  6361. }
  6362. }
  6363. my @word = keys %word;
  6364. my %replace;
  6365. my @arg;
  6366. for my $record (@{$self->{'arg_list'}}) {
  6367. # $self->{'arg_list'} = [ [Arg11, Arg12], [Arg21, Arg22], [Arg31, Arg32] ]
  6368. # Merge arg-objects from records into @arg for easy access
  6369. CORE::push @arg, @$record;
  6370. }
  6371. # Add one arg if empty to allow {#} and {%} to be computed only once
  6372. if(not @arg) { @arg = (Arg->new("")); }
  6373. # Number of arguments - used for positional arguments
  6374. my $n = $#_+1;
  6375. # This is actually a CommandLine-object,
  6376. # but it looks nice to be able to say {= $job->slot() =}
  6377. my $job = $self;
  6378. for my $word (@word) {
  6379. # word = AB \257< perlexpr \257> CD \257< perlexpr \257> EF
  6380. my $w = $word;
  6381. ::debug("replace", "Replacing in $w\n");
  6382. # Replace positional arguments
  6383. $w =~ s< ([^\s\257]*) # before {=
  6384. \257< # {=
  6385. (-?\d+) # Position (eg. -2 or 3)
  6386. ([^\257]*?) # The perl expression
  6387. \257> # =}
  6388. ([^\s\257]*) # after =}
  6389. >
  6390. { $1. # Context (pre)
  6391. (
  6392. $arg[$2 > 0 ? $2-1 : $n+$2] ? # If defined: replace
  6393. $arg[$2 > 0 ? $2-1 : $n+$2]->replace($3,$quote_arg,$self)
  6394. : "")
  6395. .$4 }egx;# Context (post)
  6396. ::debug("replace", "Positional replaced $word with: $w\n");
  6397. if($w !~ /\257/) {
  6398. # No more replacement strings in $w: No need to do more
  6399. if($quote) {
  6400. CORE::push(@{$replace{::shell_quote($word)}}, $w);
  6401. } else {
  6402. CORE::push(@{$replace{$word}}, $w);
  6403. }
  6404. next;
  6405. }
  6406. # for each arg:
  6407. # compute replacement for each string
  6408. # replace replacement strings with replacement in the word value
  6409. # push to replace word value
  6410. ::debug("replace", "Positional done: $w\n");
  6411. for my $arg (@arg) {
  6412. my $val = $w;
  6413. my $number_of_replacements = 0;
  6414. for my $perlexpr (keys %{$self->{'replacecount'}}) {
  6415. # Replace {= perl expr =} with value for each arg
  6416. $number_of_replacements +=
  6417. $val =~ s{\257<\Q$perlexpr\E\257>}
  6418. {$arg ? $arg->replace($perlexpr,$quote_arg,$self) : ""}eg;
  6419. }
  6420. my $ww = $word;
  6421. if($quote) {
  6422. $ww = ::shell_quote_scalar($word);
  6423. $val = ::shell_quote_scalar($val);
  6424. }
  6425. if($number_of_replacements) {
  6426. CORE::push(@{$replace{$ww}}, $val);
  6427. }
  6428. }
  6429. }
  6430. if($quote) {
  6431. @target = ::shell_quote(@target);
  6432. }
  6433. # ::debug("replace", "%replace=",::my_dump(%replace),"\n");
  6434. if(%replace) {
  6435. # Substitute the replace strings with the replacement values
  6436. # Must be sorted by length if a short word is a substring of a long word
  6437. my $regexp = join('|', map { my $s = $_; $s =~ s/(\W)/\\$1/g; $s }
  6438. sort { length $b <=> length $a } keys %replace);
  6439. for(@target) {
  6440. s/($regexp)/join(" ",@{$replace{$1}})/ge;
  6441. }
  6442. }
  6443. ::debug("replace", "Return @target\n");
  6444. return wantarray ? @target : "@target";
  6445. }
  6446. package CommandLineQueue;
  6447. sub new {
  6448. my $class = shift;
  6449. my $commandref = shift;
  6450. my $read_from = shift;
  6451. my $context_replace = shift;
  6452. my $max_number_of_args = shift;
  6453. my $return_files = shift;
  6454. my @unget = ();
  6455. my ($count,%replacecount,$posrpl,$perlexpr,%len);
  6456. my @command = @$commandref;
  6457. # If the first command start with '-' it is probably an option
  6458. if($command[0] =~ /^\s*(-\S+)/) {
  6459. # Is this really a command in $PATH starting with '-'?
  6460. my $cmd = $1;
  6461. if(not ::which($cmd)) {
  6462. ::error("Command ($cmd) starts with '-'. Is this a wrong option?\n");
  6463. ::wait_and_exit(255);
  6464. }
  6465. }
  6466. # Replace replacement strings with {= perl expr =}
  6467. # Protect matching inside {= perl expr =}
  6468. # by replacing {= and =} with \257< and \257>
  6469. for(@command) {
  6470. if(/\257/) {
  6471. ::error("Command cannot contain the character \257. Use a function for that.\n");
  6472. ::wait_and_exit(255);
  6473. }
  6474. s/\Q$Global::parensleft\E(.*?)\Q$Global::parensright\E/\257<$1\257>/gx;
  6475. }
  6476. for my $rpl (keys %Global::rpl) {
  6477. # Replace the short hand string with the {= perl expr =} in $command and $opt::tagstring
  6478. # Avoid replacing inside existing {= perl expr =}
  6479. for(@command,@Global::ret_files) {
  6480. while(s/((^|\257>)[^\257]*?) # Don't replace after \257 unless \257>
  6481. \Q$rpl\E/$1\257<$Global::rpl{$rpl}\257>/xg) {
  6482. }
  6483. }
  6484. if(defined $opt::tagstring) {
  6485. for($opt::tagstring) {
  6486. while(s/((^|\257>)[^\257]*?) # Don't replace after \257 unless \257>
  6487. \Q$rpl\E/$1\257<$Global::rpl{$rpl}\257>/x) {}
  6488. }
  6489. }
  6490. # Do the same for the positional replacement strings
  6491. # A bit harder as we have to put in the position number
  6492. $posrpl = $rpl;
  6493. if($posrpl =~ s/^\{//) {
  6494. # Only do this if the shorthand start with {
  6495. for(@command,@Global::ret_files) {
  6496. s/\{(-?\d+)\Q$posrpl\E/\257<$1 $Global::rpl{$rpl}\257>/g;
  6497. }
  6498. if(defined $opt::tagstring) {
  6499. $opt::tagstring =~ s/\{(-?\d+)\Q$posrpl\E/\257<$1 $perlexpr\257>/g;
  6500. }
  6501. }
  6502. }
  6503. my $sum = 0;
  6504. while($sum == 0) {
  6505. # Count how many times each replacement string is used
  6506. my @cmd = @command;
  6507. my $contextlen = 0;
  6508. my $noncontextlen = 0;
  6509. my $contextgroups = 0;
  6510. for my $c (@cmd) {
  6511. while($c =~ s/ \257<([^\257]*?)\257> /\000/x) {
  6512. # %replacecount = { "perlexpr" => number of times seen }
  6513. # e.g { "$_++" => 2 }
  6514. $replacecount{$1} ++;
  6515. $sum++;
  6516. }
  6517. # Measure the length of the context around the {= perl expr =}
  6518. # Use that {=...=} has been replaced with \000 above
  6519. # So there is no need to deal with \257<
  6520. while($c =~ s/ (\S*\000\S*) //x) {
  6521. my $w = $1;
  6522. $w =~ tr/\000//d; # Remove all \000's
  6523. $contextlen += length($w);
  6524. $contextgroups++;
  6525. }
  6526. # All {= perl expr =} have been removed: The rest is non-context
  6527. $noncontextlen += length $c;
  6528. }
  6529. if($opt::tagstring) {
  6530. my $t = $opt::tagstring;
  6531. while($t =~ s/ \257<([^\257]*)\257> //x) {
  6532. # %replacecount = { "perlexpr" => number of times seen }
  6533. # e.g { "$_++" => 2 }
  6534. # But for tagstring we just need to mark it as seen
  6535. $replacecount{$1}||=1;
  6536. }
  6537. }
  6538. $len{'context'} = 0+$contextlen;
  6539. $len{'noncontext'} = $noncontextlen;
  6540. $len{'contextgroups'} = $contextgroups;
  6541. $len{'noncontextgroups'} = @cmd-$contextgroups;
  6542. ::debug("length", "@command Context: ", $len{'context'},
  6543. " Non: ", $len{'noncontext'}, " Ctxgrp: ", $len{'contextgroups'},
  6544. " NonCtxGrp: ", $len{'noncontextgroups'}, "\n");
  6545. if($sum == 0) {
  6546. # Default command = {}
  6547. # If not replacement string: append {}
  6548. if(not @command) {
  6549. @command = ("\257<\257>");
  6550. $Global::noquote = 1;
  6551. } elsif(($opt::pipe or $opt::pipepart)
  6552. and not $opt::fifo and not $opt::cat) {
  6553. # With --pipe / --pipe-part you can have no replacement
  6554. last;
  6555. } else {
  6556. # Append {} to the command if there are no {...}'s and no {=...=}
  6557. push @command, ("\257<\257>");
  6558. }
  6559. }
  6560. }
  6561. return bless {
  6562. 'unget' => \@unget,
  6563. 'command' => \@command,
  6564. 'replacecount' => \%replacecount,
  6565. 'arg_queue' => RecordQueue->new($read_from,$opt::colsep),
  6566. 'context_replace' => $context_replace,
  6567. 'len' => \%len,
  6568. 'max_number_of_args' => $max_number_of_args,
  6569. 'size' => undef,
  6570. 'return_files' => $return_files,
  6571. 'seq' => 1,
  6572. }, ref($class) || $class;
  6573. }
  6574. sub get {
  6575. my $self = shift;
  6576. if(@{$self->{'unget'}}) {
  6577. my $cmd_line = shift @{$self->{'unget'}};
  6578. return ($cmd_line);
  6579. } else {
  6580. my $cmd_line;
  6581. $cmd_line = CommandLine->new($self->seq(),
  6582. $self->{'command'},
  6583. $self->{'arg_queue'},
  6584. $self->{'context_replace'},
  6585. $self->{'max_number_of_args'},
  6586. $self->{'return_files'},
  6587. $self->{'replacecount'},
  6588. $self->{'len'},
  6589. );
  6590. $cmd_line->populate();
  6591. ::debug("init","cmd_line->number_of_args ",
  6592. $cmd_line->number_of_args(), "\n");
  6593. if($opt::pipe or $opt::pipepart) {
  6594. if($cmd_line->replaced() eq "") {
  6595. # Empty command - pipe requires a command
  6596. ::error("--pipe must have a command to pipe into (e.g. 'cat').\n");
  6597. ::wait_and_exit(255);
  6598. }
  6599. } else {
  6600. if($cmd_line->number_of_args() == 0) {
  6601. # We did not get more args - maybe at EOF string?
  6602. return undef;
  6603. } elsif($cmd_line->replaced() eq "") {
  6604. # Empty command - get the next instead
  6605. return $self->get();
  6606. }
  6607. }
  6608. $self->set_seq($self->seq()+1);
  6609. return $cmd_line;
  6610. }
  6611. }
  6612. sub unget {
  6613. my $self = shift;
  6614. unshift @{$self->{'unget'}}, @_;
  6615. }
  6616. sub empty {
  6617. my $self = shift;
  6618. my $empty = (not @{$self->{'unget'}}) && $self->{'arg_queue'}->empty();
  6619. ::debug("run", "CommandLineQueue->empty $empty");
  6620. return $empty;
  6621. }
  6622. sub seq {
  6623. my $self = shift;
  6624. return $self->{'seq'};
  6625. }
  6626. sub set_seq {
  6627. my $self = shift;
  6628. $self->{'seq'} = shift;
  6629. }
  6630. sub quote_args {
  6631. my $self = shift;
  6632. # If there is not command emulate |bash
  6633. return $self->{'command'};
  6634. }
  6635. sub size {
  6636. my $self = shift;
  6637. if(not $self->{'size'}) {
  6638. my @all_lines = ();
  6639. while(not $self->{'arg_queue'}->empty()) {
  6640. push @all_lines, CommandLine->new($self->{'command'},
  6641. $self->{'arg_queue'},
  6642. $self->{'context_replace'},
  6643. $self->{'max_number_of_args'});
  6644. }
  6645. $self->{'size'} = @all_lines;
  6646. $self->unget(@all_lines);
  6647. }
  6648. return $self->{'size'};
  6649. }
  6650. package Limits::Command;
  6651. # Maximal command line length (for -m and -X)
  6652. sub max_length {
  6653. # Find the max_length of a command line and cache it
  6654. # Returns:
  6655. # number of chars on the longest command line allowed
  6656. if(not $Limits::Command::line_max_len) {
  6657. # Disk cache of max command line length
  6658. my $len_cache = $ENV{'HOME'} . "/.parallel/tmp/linelen-" . ::hostname();
  6659. my $cached_limit;
  6660. if(-e $len_cache) {
  6661. open(my $fh, "<", $len_cache) || ::die_bug("Cannot read $len_cache");
  6662. $cached_limit = <$fh>;
  6663. close $fh;
  6664. } else {
  6665. $cached_limit = real_max_length();
  6666. # If $HOME is write protected: Do not fail
  6667. mkdir($ENV{'HOME'} . "/.parallel");
  6668. mkdir($ENV{'HOME'} . "/.parallel/tmp");
  6669. open(my $fh, ">", $len_cache);
  6670. print $fh $cached_limit;
  6671. close $fh;
  6672. }
  6673. $Limits::Command::line_max_len = $cached_limit;
  6674. if($opt::max_chars) {
  6675. if($opt::max_chars <= $cached_limit) {
  6676. $Limits::Command::line_max_len = $opt::max_chars;
  6677. } else {
  6678. ::warning("Value for -s option ",
  6679. "should be < $cached_limit.\n");
  6680. }
  6681. }
  6682. }
  6683. return $Limits::Command::line_max_len;
  6684. }
  6685. sub real_max_length {
  6686. # Find the max_length of a command line
  6687. # Returns:
  6688. # The maximal command line length
  6689. # Use an upper bound of 8 MB if the shell allows for for infinite long lengths
  6690. my $upper = 8_000_000;
  6691. my $len = 8;
  6692. do {
  6693. if($len > $upper) { return $len };
  6694. $len *= 16;
  6695. } while (is_acceptable_command_line_length($len));
  6696. # Then search for the actual max length between 0 and upper bound
  6697. return binary_find_max_length(int($len/16),$len);
  6698. }
  6699. sub binary_find_max_length {
  6700. # Given a lower and upper bound find the max_length of a command line
  6701. # Returns:
  6702. # number of chars on the longest command line allowed
  6703. my ($lower, $upper) = (@_);
  6704. if($lower == $upper or $lower == $upper-1) { return $lower; }
  6705. my $middle = int (($upper-$lower)/2 + $lower);
  6706. ::debug("init", "Maxlen: $lower,$upper,$middle : ");
  6707. if (is_acceptable_command_line_length($middle)) {
  6708. return binary_find_max_length($middle,$upper);
  6709. } else {
  6710. return binary_find_max_length($lower,$middle);
  6711. }
  6712. }
  6713. sub is_acceptable_command_line_length {
  6714. # Test if a command line of this length can run
  6715. # Returns:
  6716. # 0 if the command line length is too long
  6717. # 1 otherwise
  6718. my $len = shift;
  6719. local *STDERR;
  6720. open (STDERR, ">", "/dev/null");
  6721. system "true "."x"x$len;
  6722. close STDERR;
  6723. ::debug("init", "$len=$? ");
  6724. return not $?;
  6725. }
  6726. package RecordQueue;
  6727. sub new {
  6728. my $class = shift;
  6729. my $fhs = shift;
  6730. my $colsep = shift;
  6731. my @unget = ();
  6732. my $arg_sub_queue;
  6733. if($colsep) {
  6734. # Open one file with colsep
  6735. $arg_sub_queue = RecordColQueue->new($fhs);
  6736. } else {
  6737. # Open one or more files if multiple -a
  6738. $arg_sub_queue = MultifileQueue->new($fhs);
  6739. }
  6740. return bless {
  6741. 'unget' => \@unget,
  6742. 'arg_number' => 0,
  6743. 'arg_sub_queue' => $arg_sub_queue,
  6744. }, ref($class) || $class;
  6745. }
  6746. sub get {
  6747. # Returns:
  6748. # reference to array of Arg-objects
  6749. my $self = shift;
  6750. if(@{$self->{'unget'}}) {
  6751. $self->{'arg_number'}++;
  6752. return shift @{$self->{'unget'}};
  6753. }
  6754. my $ret = $self->{'arg_sub_queue'}->get();
  6755. if(defined $Global::max_number_of_args
  6756. and $Global::max_number_of_args == 0) {
  6757. ::debug("run", "Read 1 but return 0 args\n");
  6758. return [Arg->new("")];
  6759. } else {
  6760. return $ret;
  6761. }
  6762. }
  6763. sub unget {
  6764. my $self = shift;
  6765. ::debug("run", "RecordQueue-unget '@_'\n");
  6766. $self->{'arg_number'} -= @_;
  6767. unshift @{$self->{'unget'}}, @_;
  6768. }
  6769. sub empty {
  6770. my $self = shift;
  6771. my $empty = not @{$self->{'unget'}};
  6772. $empty &&= $self->{'arg_sub_queue'}->empty();
  6773. ::debug("run", "RecordQueue->empty $empty");
  6774. return $empty;
  6775. }
  6776. sub arg_number {
  6777. my $self = shift;
  6778. return $self->{'arg_number'};
  6779. }
  6780. package RecordColQueue;
  6781. sub new {
  6782. my $class = shift;
  6783. my $fhs = shift;
  6784. my @unget = ();
  6785. my $arg_sub_queue = MultifileQueue->new($fhs);
  6786. return bless {
  6787. 'unget' => \@unget,
  6788. 'arg_sub_queue' => $arg_sub_queue,
  6789. }, ref($class) || $class;
  6790. }
  6791. sub get {
  6792. # Returns:
  6793. # reference to array of Arg-objects
  6794. my $self = shift;
  6795. if(@{$self->{'unget'}}) {
  6796. return shift @{$self->{'unget'}};
  6797. }
  6798. my $unget_ref=$self->{'unget'};
  6799. if($self->{'arg_sub_queue'}->empty()) {
  6800. return undef;
  6801. }
  6802. my $in_record = $self->{'arg_sub_queue'}->get();
  6803. if(defined $in_record) {
  6804. my @out_record = ();
  6805. for my $arg (@$in_record) {
  6806. ::debug("run", "RecordColQueue::arg $arg\n");
  6807. my $line = $arg->orig();
  6808. ::debug("run", "line='$line'\n");
  6809. if($line ne "") {
  6810. for my $s (split /$opt::colsep/o, $line, -1) {
  6811. push @out_record, Arg->new($s);
  6812. }
  6813. } else {
  6814. push @out_record, Arg->new("");
  6815. }
  6816. }
  6817. return \@out_record;
  6818. } else {
  6819. return undef;
  6820. }
  6821. }
  6822. sub unget {
  6823. my $self = shift;
  6824. ::debug("run", "RecordColQueue-unget '@_'\n");
  6825. unshift @{$self->{'unget'}}, @_;
  6826. }
  6827. sub empty {
  6828. my $self = shift;
  6829. my $empty = (not @{$self->{'unget'}} and $self->{'arg_sub_queue'}->empty());
  6830. ::debug("run", "RecordColQueue->empty $empty");
  6831. return $empty;
  6832. }
  6833. package MultifileQueue;
  6834. @Global::unget_argv=();
  6835. sub new {
  6836. my $class = shift;
  6837. my $fhs = shift;
  6838. for my $fh (@$fhs) {
  6839. if(-t $fh) {
  6840. ::warning("Input is read from the terminal. ".
  6841. "Only experts do this on purpose. ".
  6842. "Press CTRL-D to exit.\n");
  6843. }
  6844. }
  6845. return bless {
  6846. 'unget' => \@Global::unget_argv,
  6847. 'fhs' => $fhs,
  6848. 'arg_matrix' => undef,
  6849. }, ref($class) || $class;
  6850. }
  6851. sub get {
  6852. my $self = shift;
  6853. if($opt::xapply) {
  6854. return $self->xapply_get();
  6855. } else {
  6856. return $self->nest_get();
  6857. }
  6858. }
  6859. sub unget {
  6860. my $self = shift;
  6861. ::debug("run", "MultifileQueue-unget '@_'\n");
  6862. unshift @{$self->{'unget'}}, @_;
  6863. }
  6864. sub empty {
  6865. my $self = shift;
  6866. my $empty = (not @Global::unget_argv
  6867. and not @{$self->{'unget'}});
  6868. for my $fh (@{$self->{'fhs'}}) {
  6869. $empty &&= eof($fh);
  6870. }
  6871. ::debug("run", "MultifileQueue->empty $empty ");
  6872. return $empty;
  6873. }
  6874. sub xapply_get {
  6875. my $self = shift;
  6876. if(@{$self->{'unget'}}) {
  6877. return shift @{$self->{'unget'}};
  6878. }
  6879. my @record = ();
  6880. my $prepend = undef;
  6881. my $empty = 1;
  6882. for my $fh (@{$self->{'fhs'}}) {
  6883. my $arg = read_arg_from_fh($fh);
  6884. if(defined $arg) {
  6885. # Record $arg for recycling at end of file
  6886. push @{$self->{'arg_matrix'}{$fh}}, $arg;
  6887. push @record, $arg;
  6888. $empty = 0;
  6889. } else {
  6890. ::debug("run", "EOA ");
  6891. # End of file: Recycle arguments
  6892. push @{$self->{'arg_matrix'}{$fh}}, shift @{$self->{'arg_matrix'}{$fh}};
  6893. # return last @{$args->{'args'}{$fh}};
  6894. push @record, @{$self->{'arg_matrix'}{$fh}}[-1];
  6895. }
  6896. }
  6897. if($empty) {
  6898. return undef;
  6899. } else {
  6900. return \@record;
  6901. }
  6902. }
  6903. sub nest_get {
  6904. my $self = shift;
  6905. if(@{$self->{'unget'}}) {
  6906. return shift @{$self->{'unget'}};
  6907. }
  6908. my @record = ();
  6909. my $prepend = undef;
  6910. my $empty = 1;
  6911. my $no_of_inputsources = $#{$self->{'fhs'}} + 1;
  6912. if(not $self->{'arg_matrix'}) {
  6913. # Initialize @arg_matrix with one arg from each file
  6914. # read one line from each file
  6915. my @first_arg_set;
  6916. my $all_empty = 1;
  6917. for (my $fhno = 0; $fhno < $no_of_inputsources ; $fhno++) {
  6918. my $arg = read_arg_from_fh($self->{'fhs'}[$fhno]);
  6919. if(defined $arg) {
  6920. $all_empty = 0;
  6921. }
  6922. $self->{'arg_matrix'}[$fhno][0] = $arg || Arg->new("");
  6923. push @first_arg_set, $self->{'arg_matrix'}[$fhno][0];
  6924. }
  6925. if($all_empty) {
  6926. # All filehandles were at eof or eof-string
  6927. return undef;
  6928. }
  6929. return [@first_arg_set];
  6930. }
  6931. # Treat the case with one input source special. For multiple
  6932. # input sources we need to remember all previously read values to
  6933. # generate all combinations. But for one input source we can
  6934. # forget the value after first use.
  6935. if($no_of_inputsources == 1) {
  6936. my $arg = read_arg_from_fh($self->{'fhs'}[0]);
  6937. if(defined($arg)) {
  6938. return [$arg];
  6939. }
  6940. return undef;
  6941. }
  6942. for (my $fhno = $no_of_inputsources - 1; $fhno >= 0; $fhno--) {
  6943. if(eof($self->{'fhs'}[$fhno])) {
  6944. next;
  6945. } else {
  6946. # read one
  6947. my $arg = read_arg_from_fh($self->{'fhs'}[$fhno]);
  6948. defined($arg) || next; # If we just read an EOF string: Treat this as EOF
  6949. my $len = $#{$self->{'arg_matrix'}[$fhno]} + 1;
  6950. $self->{'arg_matrix'}[$fhno][$len] = $arg;
  6951. # make all new combinations
  6952. my @combarg = ();
  6953. for (my $fhn = 0; $fhn < $no_of_inputsources; $fhn++) {
  6954. push @combarg, [0, $#{$self->{'arg_matrix'}[$fhn]}];
  6955. }
  6956. $combarg[$fhno] = [$len,$len]; # Find only combinations with this new entry
  6957. # map combinations
  6958. # [ 1, 3, 7 ], [ 2, 4, 1 ]
  6959. # =>
  6960. # [ m[0][1], m[1][3], m[3][7] ], [ m[0][2], m[1][4], m[2][1] ]
  6961. my @mapped;
  6962. for my $c (expand_combinations(@combarg)) {
  6963. my @a;
  6964. for my $n (0 .. $no_of_inputsources - 1 ) {
  6965. push @a, $self->{'arg_matrix'}[$n][$$c[$n]];
  6966. }
  6967. push @mapped, \@a;
  6968. }
  6969. # append the mapped to the ungotten arguments
  6970. push @{$self->{'unget'}}, @mapped;
  6971. # get the first
  6972. return shift @{$self->{'unget'}};
  6973. }
  6974. }
  6975. # all are eof or at EOF string; return from the unget queue
  6976. return shift @{$self->{'unget'}};
  6977. }
  6978. sub read_arg_from_fh {
  6979. # Read one Arg from filehandle
  6980. # Returns:
  6981. # Arg-object with one read line
  6982. # undef if end of file
  6983. my $fh = shift;
  6984. my $prepend = undef;
  6985. my $arg;
  6986. do {{
  6987. # This makes 10% faster
  6988. if(not ($arg = <$fh>)) {
  6989. if(defined $prepend) {
  6990. return Arg->new($prepend);
  6991. } else {
  6992. return undef;
  6993. }
  6994. }
  6995. # ::debug("run", "read $arg\n");
  6996. # Remove delimiter
  6997. $arg =~ s:$/$::;
  6998. if($Global::end_of_file_string and
  6999. $arg eq $Global::end_of_file_string) {
  7000. # Ignore the rest of input file
  7001. close $fh;
  7002. ::debug("run", "EOF-string ($arg) met\n");
  7003. if(defined $prepend) {
  7004. return Arg->new($prepend);
  7005. } else {
  7006. return undef;
  7007. }
  7008. }
  7009. if(defined $prepend) {
  7010. $arg = $prepend.$arg; # For line continuation
  7011. $prepend = undef; #undef;
  7012. }
  7013. if($Global::ignore_empty) {
  7014. if($arg =~ /^\s*$/) {
  7015. redo; # Try the next line
  7016. }
  7017. }
  7018. if($Global::max_lines) {
  7019. if($arg =~ /\s$/) {
  7020. # Trailing space => continued on next line
  7021. $prepend = $arg;
  7022. redo;
  7023. }
  7024. }
  7025. }} while (1 == 0); # Dummy loop {{}} for redo
  7026. if(defined $arg) {
  7027. return Arg->new($arg);
  7028. } else {
  7029. ::die_bug("multiread arg undefined");
  7030. }
  7031. }
  7032. sub expand_combinations {
  7033. # Input:
  7034. # ([xmin,xmax], [ymin,ymax], ...)
  7035. # Returns: ([x,y,...],[x,y,...])
  7036. # where xmin <= x <= xmax and ymin <= y <= ymax
  7037. my $minmax_ref = shift;
  7038. my $xmin = $$minmax_ref[0];
  7039. my $xmax = $$minmax_ref[1];
  7040. my @p;
  7041. if(@_) {
  7042. # If there are more columns: Compute those recursively
  7043. my @rest = expand_combinations(@_);
  7044. for(my $x = $xmin; $x <= $xmax; $x++) {
  7045. push @p, map { [$x, @$_] } @rest;
  7046. }
  7047. } else {
  7048. for(my $x = $xmin; $x <= $xmax; $x++) {
  7049. push @p, [$x];
  7050. }
  7051. }
  7052. return @p;
  7053. }
  7054. package Arg;
  7055. sub new {
  7056. my $class = shift;
  7057. my $orig = shift;
  7058. my @hostgroups;
  7059. if($opt::hostgroups) {
  7060. if($orig =~ s:@(.+)::) {
  7061. # We found hostgroups on the arg
  7062. @hostgroups = split(/\+/, $1);
  7063. if(not grep { defined $Global::hostgroups{$_} } @hostgroups) {
  7064. ::warning("No such hostgroup (@hostgroups)\n");
  7065. @hostgroups = (keys %Global::hostgroups);
  7066. }
  7067. } else {
  7068. @hostgroups = (keys %Global::hostgroups);
  7069. }
  7070. }
  7071. return bless {
  7072. 'orig' => $orig,
  7073. 'hostgroups' => \@hostgroups,
  7074. }, ref($class) || $class;
  7075. }
  7076. sub replace {
  7077. # Calculates the corresponding value for a given perl expression
  7078. # Returns:
  7079. # The calculated string (quoted if asked for)
  7080. my $self = shift;
  7081. my $perlexpr = shift; # E.g. $_=$_ or s/.gz//
  7082. my $quote = (shift) ? 1 : 0; # should the string be quoted?
  7083. # This is actually a CommandLine-object,
  7084. # but it looks nice to be able to say {= $job->slot() =}
  7085. my $job = shift;
  7086. $perlexpr =~ s/^-?\d+ //; # Positional replace treated as normal replace
  7087. if(not defined $self->{"rpl",0,$perlexpr}) {
  7088. local $_;
  7089. if($Global::trim eq "n") {
  7090. $_ = $self->{'orig'};
  7091. } else {
  7092. $_ = trim_of($self->{'orig'});
  7093. }
  7094. ::debug("replace", "eval ", $perlexpr, " ", $_, "\n");
  7095. if(not $Global::perleval{$perlexpr}) {
  7096. # Make an anonymous function of the $perlexpr
  7097. # And more importantly: Compile it only once
  7098. if($Global::perleval{$perlexpr} =
  7099. eval('sub { no strict; no warnings; my $job = shift; '.
  7100. $perlexpr.' }')) {
  7101. # All is good
  7102. } else {
  7103. # The eval failed. Maybe $perlexpr is invalid perl?
  7104. ::error("Cannot use $perlexpr: $@\n");
  7105. ::wait_and_exit(255);
  7106. }
  7107. }
  7108. # Execute the function
  7109. $Global::perleval{$perlexpr}->($job);
  7110. $self->{"rpl",0,$perlexpr} = $_;
  7111. }
  7112. if(not defined $self->{"rpl",$quote,$perlexpr}) {
  7113. $self->{"rpl",1,$perlexpr} =
  7114. ::shell_quote_scalar($self->{"rpl",0,$perlexpr});
  7115. }
  7116. return $self->{"rpl",$quote,$perlexpr};
  7117. }
  7118. sub orig {
  7119. my $self = shift;
  7120. return $self->{'orig'};
  7121. }
  7122. sub trim_of {
  7123. # Removes white space as specifed by --trim:
  7124. # n = nothing
  7125. # l = start
  7126. # r = end
  7127. # lr|rl = both
  7128. # Returns:
  7129. # string with white space removed as needed
  7130. my @strings = map { defined $_ ? $_ : "" } (@_);
  7131. my $arg;
  7132. if($Global::trim eq "n") {
  7133. # skip
  7134. } elsif($Global::trim eq "l") {
  7135. for my $arg (@strings) { $arg =~ s/^\s+//; }
  7136. } elsif($Global::trim eq "r") {
  7137. for my $arg (@strings) { $arg =~ s/\s+$//; }
  7138. } elsif($Global::trim eq "rl" or $Global::trim eq "lr") {
  7139. for my $arg (@strings) { $arg =~ s/^\s+//; $arg =~ s/\s+$//; }
  7140. } else {
  7141. ::error("--trim must be one of: r l rl lr.\n");
  7142. ::wait_and_exit(255);
  7143. }
  7144. return wantarray ? @strings : "@strings";
  7145. }
  7146. package TimeoutQueue;
  7147. sub new {
  7148. my $class = shift;
  7149. my $delta_time = shift;
  7150. my ($pct);
  7151. if($delta_time =~ /(\d+(\.\d+)?)%/) {
  7152. # Timeout in percent
  7153. $pct = $1/100;
  7154. $delta_time = 1_000_000;
  7155. }
  7156. return bless {
  7157. 'queue' => [],
  7158. 'delta_time' => $delta_time,
  7159. 'pct' => $pct,
  7160. 'remedian_idx' => 0,
  7161. 'remedian_arr' => [],
  7162. 'remedian' => undef,
  7163. }, ref($class) || $class;
  7164. }
  7165. sub delta_time {
  7166. my $self = shift;
  7167. return $self->{'delta_time'};
  7168. }
  7169. sub set_delta_time {
  7170. my $self = shift;
  7171. $self->{'delta_time'} = shift;
  7172. }
  7173. sub remedian {
  7174. my $self = shift;
  7175. return $self->{'remedian'};
  7176. }
  7177. sub set_remedian {
  7178. # Set median of the last 999^3 (=997002999) values using Remedian
  7179. #
  7180. # Rousseeuw, Peter J., and Gilbert W. Bassett Jr. "The remedian: A
  7181. # robust averaging method for large data sets." Journal of the
  7182. # American Statistical Association 85.409 (1990): 97-104.
  7183. my $self = shift;
  7184. my $val = shift;
  7185. my $i = $self->{'remedian_idx'}++;
  7186. my $rref = $self->{'remedian_arr'};
  7187. $rref->[0][$i%999] = $val;
  7188. $rref->[1][$i/999%999] = (sort @{$rref->[0]})[$#{$rref->[0]}/2];
  7189. $rref->[2][$i/999/999%999] = (sort @{$rref->[1]})[$#{$rref->[1]}/2];
  7190. $self->{'remedian'} = (sort @{$rref->[2]})[$#{$rref->[2]}/2];
  7191. }
  7192. sub update_delta_time {
  7193. # Update delta_time based on runtime of finished job if timeout is
  7194. # a percentage
  7195. my $self = shift;
  7196. my $runtime = shift;
  7197. if($self->{'pct'}) {
  7198. $self->set_remedian($runtime);
  7199. $self->{'delta_time'} = $self->{'pct'} * $self->remedian();
  7200. ::debug("run", "Timeout: $self->{'delta_time'}s ");
  7201. }
  7202. }
  7203. sub process_timeouts {
  7204. # Check if there was a timeout
  7205. my $self = shift;
  7206. # $self->{'queue'} is sorted by start time
  7207. while (@{$self->{'queue'}}) {
  7208. my $job = $self->{'queue'}[0];
  7209. if($job->endtime()) {
  7210. # Job already finished. No need to timeout the job
  7211. # This could be because of --keep-order
  7212. shift @{$self->{'queue'}};
  7213. } elsif($job->timedout($self->{'delta_time'})) {
  7214. # Need to shift off queue before kill
  7215. # because kill calls usleep that calls process_timeouts
  7216. shift @{$self->{'queue'}};
  7217. $job->kill();
  7218. } else {
  7219. # Because they are sorted by start time the rest are later
  7220. last;
  7221. }
  7222. }
  7223. }
  7224. sub insert {
  7225. my $self = shift;
  7226. my $in = shift;
  7227. push @{$self->{'queue'}}, $in;
  7228. }
  7229. package Semaphore;
  7230. # This package provides a counting semaphore
  7231. #
  7232. # If a process dies without releasing the semaphore the next process
  7233. # that needs that entry will clean up dead semaphores
  7234. #
  7235. # The semaphores are stored in ~/.parallel/semaphores/id-<name> Each
  7236. # file in ~/.parallel/semaphores/id-<name>/ is the process ID of the
  7237. # process holding the entry. If the process dies, the entry can be
  7238. # taken by another process.
  7239. sub new {
  7240. my $class = shift;
  7241. my $id = shift;
  7242. my $count = shift;
  7243. $id=~s/([^-_a-z0-9])/unpack("H*",$1)/ige; # Convert non-word chars to hex
  7244. $id="id-".$id; # To distinguish it from a process id
  7245. my $parallel_dir = $ENV{'HOME'}."/.parallel";
  7246. -d $parallel_dir or mkdir_or_die($parallel_dir);
  7247. my $parallel_locks = $parallel_dir."/semaphores";
  7248. -d $parallel_locks or mkdir_or_die($parallel_locks);
  7249. my $lockdir = "$parallel_locks/$id";
  7250. my $lockfile = $lockdir.".lock";
  7251. if($count < 1) { ::die_bug("semaphore-count: $count"); }
  7252. return bless {
  7253. 'lockfile' => $lockfile,
  7254. 'lockfh' => Symbol::gensym(),
  7255. 'lockdir' => $lockdir,
  7256. 'id' => $id,
  7257. 'idfile' => $lockdir."/".$id,
  7258. 'pid' => $$,
  7259. 'pidfile' => $lockdir."/".$$.'@'.::hostname(),
  7260. 'count' => $count + 1 # nlinks returns a link for the 'id-' as well
  7261. }, ref($class) || $class;
  7262. }
  7263. sub acquire {
  7264. my $self = shift;
  7265. my $sleep = 1; # 1 ms
  7266. my $start_time = time;
  7267. while(1) {
  7268. $self->atomic_link_if_count_less_than() and last;
  7269. ::debug("sem", "Remove dead locks");
  7270. my $lockdir = $self->{'lockdir'};
  7271. for my $d (glob "$lockdir/*") {
  7272. ::debug("sem", "Lock $d $lockdir\n");
  7273. $d =~ m:$lockdir/([0-9]+)\@([-\._a-z0-9]+)$:o or next;
  7274. my ($pid, $host) = ($1, $2);
  7275. if($host eq ::hostname()) {
  7276. if(not kill 0, $1) {
  7277. ::debug("sem", "Dead: $d");
  7278. unlink $d;
  7279. } else {
  7280. ::debug("sem", "Alive: $d");
  7281. }
  7282. }
  7283. }
  7284. # try again
  7285. $self->atomic_link_if_count_less_than() and last;
  7286. # Retry slower and slower up to 1 second
  7287. $sleep = ($sleep < 1000) ? ($sleep * 1.1) : ($sleep);
  7288. # Random to avoid every sleeping job waking up at the same time
  7289. ::usleep(rand()*$sleep);
  7290. if(defined($opt::timeout) and
  7291. $start_time + $opt::timeout > time) {
  7292. # Acquire the lock anyway
  7293. if(not -e $self->{'idfile'}) {
  7294. open (my $fh, ">", $self->{'idfile'}) or
  7295. ::die_bug("timeout_write_idfile: $self->{'idfile'}");
  7296. close $fh;
  7297. }
  7298. link $self->{'idfile'}, $self->{'pidfile'};
  7299. last;
  7300. }
  7301. }
  7302. ::debug("sem", "acquired $self->{'pid'}\n");
  7303. }
  7304. sub release {
  7305. my $self = shift;
  7306. unlink $self->{'pidfile'};
  7307. if($self->nlinks() == 1) {
  7308. # This is the last link, so atomic cleanup
  7309. $self->lock();
  7310. if($self->nlinks() == 1) {
  7311. unlink $self->{'idfile'};
  7312. rmdir $self->{'lockdir'};
  7313. }
  7314. $self->unlock();
  7315. }
  7316. ::debug("run", "released $self->{'pid'}\n");
  7317. }
  7318. sub _release {
  7319. my $self = shift;
  7320. unlink $self->{'pidfile'};
  7321. $self->lock();
  7322. my $nlinks = $self->nlinks();
  7323. ::debug("sem", $nlinks, "<", $self->{'count'});
  7324. if($nlinks-- > 1) {
  7325. unlink $self->{'idfile'};
  7326. open (my $fh, ">", $self->{'idfile'}) or
  7327. ::die_bug("write_idfile: $self->{'idfile'}");
  7328. print $fh "#"x$nlinks;
  7329. close $fh;
  7330. } else {
  7331. unlink $self->{'idfile'};
  7332. rmdir $self->{'lockdir'};
  7333. }
  7334. $self->unlock();
  7335. ::debug("sem", "released $self->{'pid'}\n");
  7336. }
  7337. sub atomic_link_if_count_less_than {
  7338. # Link $file1 to $file2 if nlinks to $file1 < $count
  7339. my $self = shift;
  7340. my $retval = 0;
  7341. $self->lock();
  7342. ::debug($self->nlinks(), "<", $self->{'count'});
  7343. if($self->nlinks() < $self->{'count'}) {
  7344. -d $self->{'lockdir'} or mkdir_or_die($self->{'lockdir'});
  7345. if(not -e $self->{'idfile'}) {
  7346. open (my $fh, ">", $self->{'idfile'}) or
  7347. ::die_bug("write_idfile: $self->{'idfile'}");
  7348. close $fh;
  7349. }
  7350. $retval = link $self->{'idfile'}, $self->{'pidfile'};
  7351. }
  7352. $self->unlock();
  7353. ::debug("run", "atomic $retval");
  7354. return $retval;
  7355. }
  7356. sub _atomic_link_if_count_less_than {
  7357. # Link $file1 to $file2 if nlinks to $file1 < $count
  7358. my $self = shift;
  7359. my $retval = 0;
  7360. $self->lock();
  7361. my $nlinks = $self->nlinks();
  7362. ::debug("sem", $nlinks, "<", $self->{'count'});
  7363. if($nlinks++ < $self->{'count'}) {
  7364. -d $self->{'lockdir'} or mkdir_or_die($self->{'lockdir'});
  7365. if(not -e $self->{'idfile'}) {
  7366. open (my $fh, ">", $self->{'idfile'}) or
  7367. ::die_bug("write_idfile: $self->{'idfile'}");
  7368. close $fh;
  7369. }
  7370. open (my $fh, ">", $self->{'idfile'}) or
  7371. ::die_bug("write_idfile: $self->{'idfile'}");
  7372. print $fh "#"x$nlinks;
  7373. close $fh;
  7374. $retval = link $self->{'idfile'}, $self->{'pidfile'};
  7375. }
  7376. $self->unlock();
  7377. ::debug("sem", "atomic $retval");
  7378. return $retval;
  7379. }
  7380. sub nlinks {
  7381. my $self = shift;
  7382. if(-e $self->{'idfile'}) {
  7383. ::debug("sem", "nlinks", (stat(_))[3], "size", (stat(_))[7], "\n");
  7384. return (stat(_))[3];
  7385. } else {
  7386. return 0;
  7387. }
  7388. }
  7389. sub lock {
  7390. my $self = shift;
  7391. my $sleep = 100; # 100 ms
  7392. my $total_sleep = 0;
  7393. $Global::use{"Fcntl"} ||= eval "use Fcntl qw(:DEFAULT :flock); 1;";
  7394. my $locked = 0;
  7395. while(not $locked) {
  7396. if(tell($self->{'lockfh'}) == -1) {
  7397. # File not open
  7398. open($self->{'lockfh'}, ">", $self->{'lockfile'})
  7399. or ::debug("run", "Cannot open $self->{'lockfile'}");
  7400. }
  7401. if($self->{'lockfh'}) {
  7402. # File is open
  7403. chmod 0666, $self->{'lockfile'}; # assuming you want it a+rw
  7404. if(flock($self->{'lockfh'}, LOCK_EX()|LOCK_NB())) {
  7405. # The file is locked: No need to retry
  7406. $locked = 1;
  7407. last;
  7408. } else {
  7409. if ($! =~ m/Function not implemented/) {
  7410. ::warning("flock: $!");
  7411. ::warning("Will wait for a random while\n");
  7412. ::usleep(rand(5000));
  7413. # File cannot be locked: No need to retry
  7414. $locked = 2;
  7415. last;
  7416. }
  7417. }
  7418. }
  7419. # Locking failed in first round
  7420. # Sleep and try again
  7421. $sleep = ($sleep < 1000) ? ($sleep * 1.1) : ($sleep);
  7422. # Random to avoid every sleeping job waking up at the same time
  7423. ::usleep(rand()*$sleep);
  7424. $total_sleep += $sleep;
  7425. if($opt::semaphoretimeout) {
  7426. if($total_sleep/1000 > $opt::semaphoretimeout) {
  7427. # Timeout: bail out
  7428. ::warning("Semaphore timed out. Ignoring timeout.");
  7429. $locked = 3;
  7430. last;
  7431. }
  7432. } else {
  7433. if($total_sleep/1000 > 30) {
  7434. ::warning("Semaphore stuck for 30 seconds. Consider using --semaphoretimeout.");
  7435. }
  7436. }
  7437. }
  7438. ::debug("run", "locked $self->{'lockfile'}");
  7439. }
  7440. sub unlock {
  7441. my $self = shift;
  7442. unlink $self->{'lockfile'};
  7443. close $self->{'lockfh'};
  7444. ::debug("run", "unlocked\n");
  7445. }
  7446. sub mkdir_or_die {
  7447. # If dir is not writable: die
  7448. my $dir = shift;
  7449. my @dir_parts = split(m:/:,$dir);
  7450. my ($ddir,$part);
  7451. while(defined ($part = shift @dir_parts)) {
  7452. $part eq "" and next;
  7453. $ddir .= "/".$part;
  7454. -d $ddir and next;
  7455. mkdir $ddir;
  7456. }
  7457. if(not -w $dir) {
  7458. ::error("Cannot write to $dir: $!\n");
  7459. ::wait_and_exit(255);
  7460. }
  7461. }
  7462. # Keep perl -w happy
  7463. $opt::x = $Semaphore::timeout = $Semaphore::wait =
  7464. $Job::file_descriptor_warning_printed = 0;