123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497 |
- /*
- Copyright 2014 The Kubernetes Authors.
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
- http://www.apache.org/licenses/LICENSE-2.0
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- */
- package validation
- import (
- "bytes"
- "math"
- "reflect"
- "strings"
- "testing"
- "k8s.io/api/core/v1"
- "k8s.io/apimachinery/pkg/api/resource"
- metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
- "k8s.io/apimachinery/pkg/util/intstr"
- "k8s.io/apimachinery/pkg/util/validation"
- "k8s.io/apimachinery/pkg/util/validation/field"
- utilfeature "k8s.io/apiserver/pkg/util/feature"
- featuregatetesting "k8s.io/component-base/featuregate/testing"
- _ "k8s.io/kubernetes/pkg/api/testapi"
- "k8s.io/kubernetes/pkg/apis/core"
- "k8s.io/kubernetes/pkg/capabilities"
- "k8s.io/kubernetes/pkg/features"
- "k8s.io/kubernetes/pkg/security/apparmor"
- utilpointer "k8s.io/utils/pointer"
- )
- const (
- dnsLabelErrMsg = "a DNS-1123 label must consist of"
- dnsSubdomainLabelErrMsg = "a DNS-1123 subdomain"
- envVarNameErrMsg = "a valid environment variable name must consist of"
- )
- func newHostPathType(pathType string) *core.HostPathType {
- hostPathType := new(core.HostPathType)
- *hostPathType = core.HostPathType(pathType)
- return hostPathType
- }
- func testVolume(name string, namespace string, spec core.PersistentVolumeSpec) *core.PersistentVolume {
- objMeta := metav1.ObjectMeta{Name: name}
- if namespace != "" {
- objMeta.Namespace = namespace
- }
- return &core.PersistentVolume{
- ObjectMeta: objMeta,
- Spec: spec,
- }
- }
- func TestValidatePersistentVolumes(t *testing.T) {
- validMode := core.PersistentVolumeFilesystem
- invalidMode := core.PersistentVolumeMode("fakeVolumeMode")
- scenarios := map[string]struct {
- isExpectedFailure bool
- volume *core.PersistentVolume
- }{
- "good-volume": {
- isExpectedFailure: false,
- volume: testVolume("foo", "", core.PersistentVolumeSpec{
- Capacity: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce},
- PersistentVolumeSource: core.PersistentVolumeSource{
- HostPath: &core.HostPathVolumeSource{
- Path: "/foo",
- Type: newHostPathType(string(core.HostPathDirectory)),
- },
- },
- }),
- },
- "good-volume-with-capacity-unit": {
- isExpectedFailure: false,
- volume: testVolume("foo", "", core.PersistentVolumeSpec{
- Capacity: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10Gi"),
- },
- AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce},
- PersistentVolumeSource: core.PersistentVolumeSource{
- HostPath: &core.HostPathVolumeSource{
- Path: "/foo",
- Type: newHostPathType(string(core.HostPathDirectory)),
- },
- },
- }),
- },
- "good-volume-without-capacity-unit": {
- isExpectedFailure: false,
- volume: testVolume("foo", "", core.PersistentVolumeSpec{
- Capacity: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10"),
- },
- AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce},
- PersistentVolumeSource: core.PersistentVolumeSource{
- HostPath: &core.HostPathVolumeSource{
- Path: "/foo",
- Type: newHostPathType(string(core.HostPathDirectory)),
- },
- },
- }),
- },
- "good-volume-with-storage-class": {
- isExpectedFailure: false,
- volume: testVolume("foo", "", core.PersistentVolumeSpec{
- Capacity: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce},
- PersistentVolumeSource: core.PersistentVolumeSource{
- HostPath: &core.HostPathVolumeSource{
- Path: "/foo",
- Type: newHostPathType(string(core.HostPathDirectory)),
- },
- },
- StorageClassName: "valid",
- }),
- },
- "good-volume-with-retain-policy": {
- isExpectedFailure: false,
- volume: testVolume("foo", "", core.PersistentVolumeSpec{
- Capacity: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce},
- PersistentVolumeSource: core.PersistentVolumeSource{
- HostPath: &core.HostPathVolumeSource{
- Path: "/foo",
- Type: newHostPathType(string(core.HostPathDirectory)),
- },
- },
- PersistentVolumeReclaimPolicy: core.PersistentVolumeReclaimRetain,
- }),
- },
- "good-volume-with-volume-mode": {
- isExpectedFailure: false,
- volume: testVolume("foo", "", core.PersistentVolumeSpec{
- Capacity: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce},
- PersistentVolumeSource: core.PersistentVolumeSource{
- HostPath: &core.HostPathVolumeSource{
- Path: "/foo",
- Type: newHostPathType(string(core.HostPathDirectory)),
- },
- },
- VolumeMode: &validMode,
- }),
- },
- "invalid-accessmode": {
- isExpectedFailure: true,
- volume: testVolume("foo", "", core.PersistentVolumeSpec{
- Capacity: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- AccessModes: []core.PersistentVolumeAccessMode{"fakemode"},
- PersistentVolumeSource: core.PersistentVolumeSource{
- HostPath: &core.HostPathVolumeSource{
- Path: "/foo",
- Type: newHostPathType(string(core.HostPathDirectory)),
- },
- },
- }),
- },
- "invalid-reclaimpolicy": {
- isExpectedFailure: true,
- volume: testVolume("foo", "", core.PersistentVolumeSpec{
- Capacity: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce},
- PersistentVolumeSource: core.PersistentVolumeSource{
- HostPath: &core.HostPathVolumeSource{
- Path: "/foo",
- Type: newHostPathType(string(core.HostPathDirectory)),
- },
- },
- PersistentVolumeReclaimPolicy: "fakeReclaimPolicy",
- }),
- },
- "invalid-volume-mode": {
- isExpectedFailure: true,
- volume: testVolume("foo", "", core.PersistentVolumeSpec{
- Capacity: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce},
- PersistentVolumeSource: core.PersistentVolumeSource{
- HostPath: &core.HostPathVolumeSource{
- Path: "/foo",
- Type: newHostPathType(string(core.HostPathDirectory)),
- },
- },
- VolumeMode: &invalidMode,
- }),
- },
- "unexpected-namespace": {
- isExpectedFailure: true,
- volume: testVolume("foo", "unexpected-namespace", core.PersistentVolumeSpec{
- Capacity: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce},
- PersistentVolumeSource: core.PersistentVolumeSource{
- HostPath: &core.HostPathVolumeSource{
- Path: "/foo",
- Type: newHostPathType(string(core.HostPathDirectory)),
- },
- },
- }),
- },
- "missing-volume-source": {
- isExpectedFailure: true,
- volume: testVolume("foo", "", core.PersistentVolumeSpec{
- Capacity: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce},
- }),
- },
- "bad-name": {
- isExpectedFailure: true,
- volume: testVolume("123*Bad(Name", "unexpected-namespace", core.PersistentVolumeSpec{
- Capacity: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce},
- PersistentVolumeSource: core.PersistentVolumeSource{
- HostPath: &core.HostPathVolumeSource{
- Path: "/foo",
- Type: newHostPathType(string(core.HostPathDirectory)),
- },
- },
- }),
- },
- "missing-name": {
- isExpectedFailure: true,
- volume: testVolume("", "", core.PersistentVolumeSpec{
- Capacity: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce},
- PersistentVolumeSource: core.PersistentVolumeSource{
- HostPath: &core.HostPathVolumeSource{
- Path: "/foo",
- Type: newHostPathType(string(core.HostPathDirectory)),
- },
- },
- }),
- },
- "missing-capacity": {
- isExpectedFailure: true,
- volume: testVolume("foo", "", core.PersistentVolumeSpec{
- AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce},
- PersistentVolumeSource: core.PersistentVolumeSource{
- HostPath: &core.HostPathVolumeSource{
- Path: "/foo",
- Type: newHostPathType(string(core.HostPathDirectory)),
- },
- },
- }),
- },
- "bad-volume-zero-capacity": {
- isExpectedFailure: true,
- volume: testVolume("foo", "", core.PersistentVolumeSpec{
- Capacity: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("0"),
- },
- AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce},
- PersistentVolumeSource: core.PersistentVolumeSource{
- HostPath: &core.HostPathVolumeSource{
- Path: "/foo",
- Type: newHostPathType(string(core.HostPathDirectory)),
- },
- },
- }),
- },
- "missing-accessmodes": {
- isExpectedFailure: true,
- volume: testVolume("goodname", "missing-accessmodes", core.PersistentVolumeSpec{
- Capacity: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- PersistentVolumeSource: core.PersistentVolumeSource{
- HostPath: &core.HostPathVolumeSource{
- Path: "/foo",
- Type: newHostPathType(string(core.HostPathDirectory)),
- },
- },
- }),
- },
- "too-many-sources": {
- isExpectedFailure: true,
- volume: testVolume("foo", "", core.PersistentVolumeSpec{
- Capacity: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("5G"),
- },
- PersistentVolumeSource: core.PersistentVolumeSource{
- HostPath: &core.HostPathVolumeSource{
- Path: "/foo",
- Type: newHostPathType(string(core.HostPathDirectory)),
- },
- GCEPersistentDisk: &core.GCEPersistentDiskVolumeSource{PDName: "foo", FSType: "ext4"},
- },
- }),
- },
- "host mount of / with recycle reclaim policy": {
- isExpectedFailure: true,
- volume: testVolume("bad-recycle-do-not-want", "", core.PersistentVolumeSpec{
- Capacity: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce},
- PersistentVolumeSource: core.PersistentVolumeSource{
- HostPath: &core.HostPathVolumeSource{
- Path: "/",
- Type: newHostPathType(string(core.HostPathDirectory)),
- },
- },
- PersistentVolumeReclaimPolicy: core.PersistentVolumeReclaimRecycle,
- }),
- },
- "host mount of / with recycle reclaim policy 2": {
- isExpectedFailure: true,
- volume: testVolume("bad-recycle-do-not-want", "", core.PersistentVolumeSpec{
- Capacity: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce},
- PersistentVolumeSource: core.PersistentVolumeSource{
- HostPath: &core.HostPathVolumeSource{
- Path: "/a/..",
- Type: newHostPathType(string(core.HostPathDirectory)),
- },
- },
- PersistentVolumeReclaimPolicy: core.PersistentVolumeReclaimRecycle,
- }),
- },
- "invalid-storage-class-name": {
- isExpectedFailure: true,
- volume: testVolume("invalid-storage-class-name", "", core.PersistentVolumeSpec{
- Capacity: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce},
- PersistentVolumeSource: core.PersistentVolumeSource{
- HostPath: &core.HostPathVolumeSource{
- Path: "/foo",
- Type: newHostPathType(string(core.HostPathDirectory)),
- },
- },
- StorageClassName: "-invalid-",
- }),
- },
- "bad-hostpath-volume-backsteps": {
- isExpectedFailure: true,
- volume: testVolume("foo", "", core.PersistentVolumeSpec{
- Capacity: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce},
- PersistentVolumeSource: core.PersistentVolumeSource{
- HostPath: &core.HostPathVolumeSource{
- Path: "/foo/..",
- Type: newHostPathType(string(core.HostPathDirectory)),
- },
- },
- StorageClassName: "backstep-hostpath",
- }),
- },
- "volume-node-affinity": {
- isExpectedFailure: false,
- volume: testVolumeWithNodeAffinity(simpleVolumeNodeAffinity("foo", "bar")),
- },
- "volume-empty-node-affinity": {
- isExpectedFailure: true,
- volume: testVolumeWithNodeAffinity(&core.VolumeNodeAffinity{}),
- },
- "volume-bad-node-affinity": {
- isExpectedFailure: true,
- volume: testVolumeWithNodeAffinity(
- &core.VolumeNodeAffinity{
- Required: &core.NodeSelector{
- NodeSelectorTerms: []core.NodeSelectorTerm{
- {
- MatchExpressions: []core.NodeSelectorRequirement{
- {
- Operator: core.NodeSelectorOpIn,
- Values: []string{"test-label-value"},
- },
- },
- },
- },
- },
- }),
- },
- }
- for name, scenario := range scenarios {
- t.Run(name, func(t *testing.T) {
- errs := ValidatePersistentVolume(scenario.volume)
- if len(errs) == 0 && scenario.isExpectedFailure {
- t.Errorf("Unexpected success for scenario: %s", name)
- }
- if len(errs) > 0 && !scenario.isExpectedFailure {
- t.Errorf("Unexpected failure for scenario: %s - %+v", name, errs)
- }
- })
- }
- }
- func TestValidatePersistentVolumeSpec(t *testing.T) {
- fsmode := core.PersistentVolumeFilesystem
- blockmode := core.PersistentVolumeBlock
- scenarios := map[string]struct {
- isExpectedFailure bool
- isInlineSpec bool
- pvSpec *core.PersistentVolumeSpec
- }{
- "pv-pvspec-valid": {
- isExpectedFailure: false,
- isInlineSpec: false,
- pvSpec: &core.PersistentVolumeSpec{
- Capacity: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- StorageClassName: "testclass",
- PersistentVolumeReclaimPolicy: core.PersistentVolumeReclaimRecycle,
- AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce},
- PersistentVolumeSource: core.PersistentVolumeSource{
- HostPath: &core.HostPathVolumeSource{
- Path: "/foo",
- Type: newHostPathType(string(core.HostPathDirectory)),
- },
- },
- VolumeMode: &fsmode,
- NodeAffinity: simpleVolumeNodeAffinity("foo", "bar"),
- },
- },
- "inline-pvspec-with-capacity": {
- isExpectedFailure: true,
- isInlineSpec: true,
- pvSpec: &core.PersistentVolumeSpec{
- Capacity: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- PersistentVolumeSource: core.PersistentVolumeSource{
- CSI: &core.CSIPersistentVolumeSource{Driver: "test-driver", VolumeHandle: "test-123", ReadOnly: true},
- },
- AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce},
- },
- },
- "inline-pvspec-with-sc": {
- isExpectedFailure: true,
- isInlineSpec: true,
- pvSpec: &core.PersistentVolumeSpec{
- PersistentVolumeSource: core.PersistentVolumeSource{
- CSI: &core.CSIPersistentVolumeSource{Driver: "test-driver", VolumeHandle: "test-123", ReadOnly: true},
- },
- AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce},
- StorageClassName: "testclass",
- },
- },
- "inline-pvspec-with-non-fs-volume-mode": {
- isExpectedFailure: true,
- isInlineSpec: true,
- pvSpec: &core.PersistentVolumeSpec{
- PersistentVolumeSource: core.PersistentVolumeSource{
- CSI: &core.CSIPersistentVolumeSource{Driver: "test-driver", VolumeHandle: "test-123", ReadOnly: true},
- },
- AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce},
- VolumeMode: &blockmode,
- },
- },
- "inline-pvspec-with-non-retain-reclaim-policy": {
- isExpectedFailure: true,
- isInlineSpec: true,
- pvSpec: &core.PersistentVolumeSpec{
- PersistentVolumeReclaimPolicy: core.PersistentVolumeReclaimRecycle,
- PersistentVolumeSource: core.PersistentVolumeSource{
- CSI: &core.CSIPersistentVolumeSource{Driver: "test-driver", VolumeHandle: "test-123", ReadOnly: true},
- },
- AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce},
- },
- },
- "inline-pvspec-with-node-affinity": {
- isExpectedFailure: true,
- isInlineSpec: true,
- pvSpec: &core.PersistentVolumeSpec{
- PersistentVolumeSource: core.PersistentVolumeSource{
- CSI: &core.CSIPersistentVolumeSource{Driver: "test-driver", VolumeHandle: "test-123", ReadOnly: true},
- },
- AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce},
- NodeAffinity: simpleVolumeNodeAffinity("foo", "bar"),
- },
- },
- "inline-pvspec-with-non-csi-source": {
- isExpectedFailure: true,
- isInlineSpec: true,
- pvSpec: &core.PersistentVolumeSpec{
- PersistentVolumeSource: core.PersistentVolumeSource{
- HostPath: &core.HostPathVolumeSource{
- Path: "/foo",
- Type: newHostPathType(string(core.HostPathDirectory)),
- },
- },
- AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce},
- },
- },
- "inline-pvspec-valid-with-access-modes-and-mount-options": {
- isExpectedFailure: false,
- isInlineSpec: true,
- pvSpec: &core.PersistentVolumeSpec{
- PersistentVolumeSource: core.PersistentVolumeSource{
- CSI: &core.CSIPersistentVolumeSource{Driver: "test-driver", VolumeHandle: "test-123", ReadOnly: true},
- },
- AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce},
- MountOptions: []string{"soft", "read-write"},
- },
- },
- "inline-pvspec-valid-with-access-modes": {
- isExpectedFailure: false,
- isInlineSpec: true,
- pvSpec: &core.PersistentVolumeSpec{
- PersistentVolumeSource: core.PersistentVolumeSource{
- CSI: &core.CSIPersistentVolumeSource{Driver: "test-driver", VolumeHandle: "test-123", ReadOnly: true},
- },
- AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce},
- },
- },
- "inline-pvspec-with-missing-acess-modes": {
- isExpectedFailure: true,
- isInlineSpec: true,
- pvSpec: &core.PersistentVolumeSpec{
- PersistentVolumeSource: core.PersistentVolumeSource{
- CSI: &core.CSIPersistentVolumeSource{Driver: "test-driver", VolumeHandle: "test-123", ReadOnly: true},
- },
- MountOptions: []string{"soft", "read-write"},
- },
- },
- }
- for name, scenario := range scenarios {
- errs := ValidatePersistentVolumeSpec(scenario.pvSpec, "", scenario.isInlineSpec, field.NewPath("field"))
- if len(errs) == 0 && scenario.isExpectedFailure {
- t.Errorf("Unexpected success for scenario: %s", name)
- }
- if len(errs) > 0 && !scenario.isExpectedFailure {
- t.Errorf("Unexpected failure for scenario: %s - %+v", name, errs)
- }
- }
- }
- func TestValidatePersistentVolumeSourceUpdate(t *testing.T) {
- validVolume := testVolume("foo", "", core.PersistentVolumeSpec{
- Capacity: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("1G"),
- },
- AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce},
- PersistentVolumeSource: core.PersistentVolumeSource{
- HostPath: &core.HostPathVolumeSource{
- Path: "/foo",
- Type: newHostPathType(string(core.HostPathDirectory)),
- },
- },
- StorageClassName: "valid",
- })
- validPvSourceNoUpdate := validVolume.DeepCopy()
- invalidPvSourceUpdateType := validVolume.DeepCopy()
- invalidPvSourceUpdateType.Spec.PersistentVolumeSource = core.PersistentVolumeSource{
- FlexVolume: &core.FlexPersistentVolumeSource{
- Driver: "kubernetes.io/blue",
- FSType: "ext4",
- },
- }
- invalidPvSourceUpdateDeep := validVolume.DeepCopy()
- invalidPvSourceUpdateDeep.Spec.PersistentVolumeSource = core.PersistentVolumeSource{
- HostPath: &core.HostPathVolumeSource{
- Path: "/updated",
- Type: newHostPathType(string(core.HostPathDirectory)),
- },
- }
- validCSIVolume := testVolume("csi-volume", "", core.PersistentVolumeSpec{
- Capacity: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("1G"),
- },
- AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce},
- PersistentVolumeSource: core.PersistentVolumeSource{
- CSI: &core.CSIPersistentVolumeSource{
- Driver: "come.google.gcepd",
- VolumeHandle: "foobar",
- },
- },
- StorageClassName: "gp2",
- })
- expandSecretRef := &core.SecretReference{
- Name: "expansion-secret",
- Namespace: "default",
- }
- scenarios := map[string]struct {
- isExpectedFailure bool
- csiExpansionEnabled bool
- oldVolume *core.PersistentVolume
- newVolume *core.PersistentVolume
- }{
- "condition-no-update": {
- isExpectedFailure: false,
- oldVolume: validVolume,
- newVolume: validPvSourceNoUpdate,
- },
- "condition-update-source-type": {
- isExpectedFailure: true,
- oldVolume: validVolume,
- newVolume: invalidPvSourceUpdateType,
- },
- "condition-update-source-deep": {
- isExpectedFailure: true,
- oldVolume: validVolume,
- newVolume: invalidPvSourceUpdateDeep,
- },
- "csi-expansion-enabled-with-pv-secret": {
- csiExpansionEnabled: true,
- isExpectedFailure: false,
- oldVolume: validCSIVolume,
- newVolume: getCSIVolumeWithSecret(validCSIVolume, expandSecretRef),
- },
- "csi-expansion-enabled-with-old-pv-secret": {
- csiExpansionEnabled: true,
- isExpectedFailure: true,
- oldVolume: getCSIVolumeWithSecret(validCSIVolume, expandSecretRef),
- newVolume: getCSIVolumeWithSecret(validCSIVolume, &core.SecretReference{
- Name: "foo-secret",
- Namespace: "default",
- }),
- },
- }
- for name, scenario := range scenarios {
- errs := ValidatePersistentVolumeUpdate(scenario.newVolume, scenario.oldVolume)
- if len(errs) == 0 && scenario.isExpectedFailure {
- t.Errorf("Unexpected success for scenario: %s", name)
- }
- if len(errs) > 0 && !scenario.isExpectedFailure {
- t.Errorf("Unexpected failure for scenario: %s - %+v", name, errs)
- }
- }
- }
- func getCSIVolumeWithSecret(pv *core.PersistentVolume, secret *core.SecretReference) *core.PersistentVolume {
- pvCopy := pv.DeepCopy()
- if secret != nil {
- pvCopy.Spec.CSI.ControllerExpandSecretRef = secret
- }
- return pvCopy
- }
- func testLocalVolume(path string, affinity *core.VolumeNodeAffinity) core.PersistentVolumeSpec {
- return core.PersistentVolumeSpec{
- Capacity: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce},
- PersistentVolumeSource: core.PersistentVolumeSource{
- Local: &core.LocalVolumeSource{
- Path: path,
- },
- },
- NodeAffinity: affinity,
- StorageClassName: "test-storage-class",
- }
- }
- func TestValidateLocalVolumes(t *testing.T) {
- scenarios := map[string]struct {
- isExpectedFailure bool
- volume *core.PersistentVolume
- }{
- "alpha invalid local volume nil annotations": {
- isExpectedFailure: true,
- volume: testVolume(
- "invalid-local-volume-nil-annotations",
- "",
- testLocalVolume("/foo", nil)),
- },
- "valid local volume": {
- isExpectedFailure: false,
- volume: testVolume("valid-local-volume", "",
- testLocalVolume("/foo", simpleVolumeNodeAffinity("foo", "bar"))),
- },
- "invalid local volume no node affinity": {
- isExpectedFailure: true,
- volume: testVolume("invalid-local-volume-no-node-affinity", "",
- testLocalVolume("/foo", nil)),
- },
- "invalid local volume empty path": {
- isExpectedFailure: true,
- volume: testVolume("invalid-local-volume-empty-path", "",
- testLocalVolume("", simpleVolumeNodeAffinity("foo", "bar"))),
- },
- "invalid-local-volume-backsteps": {
- isExpectedFailure: true,
- volume: testVolume("foo", "",
- testLocalVolume("/foo/..", simpleVolumeNodeAffinity("foo", "bar"))),
- },
- "valid-local-volume-relative-path": {
- isExpectedFailure: false,
- volume: testVolume("foo", "",
- testLocalVolume("foo", simpleVolumeNodeAffinity("foo", "bar"))),
- },
- }
- for name, scenario := range scenarios {
- errs := ValidatePersistentVolume(scenario.volume)
- if len(errs) == 0 && scenario.isExpectedFailure {
- t.Errorf("Unexpected success for scenario: %s", name)
- }
- if len(errs) > 0 && !scenario.isExpectedFailure {
- t.Errorf("Unexpected failure for scenario: %s - %+v", name, errs)
- }
- }
- }
- func testVolumeWithNodeAffinity(affinity *core.VolumeNodeAffinity) *core.PersistentVolume {
- return testVolume("test-affinity-volume", "",
- core.PersistentVolumeSpec{
- Capacity: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce},
- PersistentVolumeSource: core.PersistentVolumeSource{
- GCEPersistentDisk: &core.GCEPersistentDiskVolumeSource{
- PDName: "foo",
- },
- },
- StorageClassName: "test-storage-class",
- NodeAffinity: affinity,
- })
- }
- func simpleVolumeNodeAffinity(key, value string) *core.VolumeNodeAffinity {
- return &core.VolumeNodeAffinity{
- Required: &core.NodeSelector{
- NodeSelectorTerms: []core.NodeSelectorTerm{
- {
- MatchExpressions: []core.NodeSelectorRequirement{
- {
- Key: key,
- Operator: core.NodeSelectorOpIn,
- Values: []string{value},
- },
- },
- },
- },
- },
- }
- }
- func TestValidateVolumeNodeAffinityUpdate(t *testing.T) {
- scenarios := map[string]struct {
- isExpectedFailure bool
- oldPV *core.PersistentVolume
- newPV *core.PersistentVolume
- }{
- "nil-nothing-changed": {
- isExpectedFailure: false,
- oldPV: testVolumeWithNodeAffinity(nil),
- newPV: testVolumeWithNodeAffinity(nil),
- },
- "affinity-nothing-changed": {
- isExpectedFailure: false,
- oldPV: testVolumeWithNodeAffinity(simpleVolumeNodeAffinity("foo", "bar")),
- newPV: testVolumeWithNodeAffinity(simpleVolumeNodeAffinity("foo", "bar")),
- },
- "affinity-changed": {
- isExpectedFailure: true,
- oldPV: testVolumeWithNodeAffinity(simpleVolumeNodeAffinity("foo", "bar")),
- newPV: testVolumeWithNodeAffinity(simpleVolumeNodeAffinity("foo", "bar2")),
- },
- "nil-to-obj": {
- isExpectedFailure: false,
- oldPV: testVolumeWithNodeAffinity(nil),
- newPV: testVolumeWithNodeAffinity(simpleVolumeNodeAffinity("foo", "bar")),
- },
- "obj-to-nil": {
- isExpectedFailure: true,
- oldPV: testVolumeWithNodeAffinity(simpleVolumeNodeAffinity("foo", "bar")),
- newPV: testVolumeWithNodeAffinity(nil),
- },
- }
- for name, scenario := range scenarios {
- errs := ValidatePersistentVolumeUpdate(scenario.newPV, scenario.oldPV)
- if len(errs) == 0 && scenario.isExpectedFailure {
- t.Errorf("Unexpected success for scenario: %s", name)
- }
- if len(errs) > 0 && !scenario.isExpectedFailure {
- t.Errorf("Unexpected failure for scenario: %s - %+v", name, errs)
- }
- }
- }
- func testVolumeClaim(name string, namespace string, spec core.PersistentVolumeClaimSpec) *core.PersistentVolumeClaim {
- return &core.PersistentVolumeClaim{
- ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: namespace},
- Spec: spec,
- }
- }
- func testVolumeClaimWithStatus(
- name, namespace string,
- spec core.PersistentVolumeClaimSpec,
- status core.PersistentVolumeClaimStatus) *core.PersistentVolumeClaim {
- return &core.PersistentVolumeClaim{
- ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: namespace},
- Spec: spec,
- Status: status,
- }
- }
- func testVolumeClaimStorageClass(name string, namespace string, annval string, spec core.PersistentVolumeClaimSpec) *core.PersistentVolumeClaim {
- annotations := map[string]string{
- v1.BetaStorageClassAnnotation: annval,
- }
- return &core.PersistentVolumeClaim{
- ObjectMeta: metav1.ObjectMeta{
- Name: name,
- Namespace: namespace,
- Annotations: annotations,
- },
- Spec: spec,
- }
- }
- func testVolumeClaimAnnotation(name string, namespace string, ann string, annval string, spec core.PersistentVolumeClaimSpec) *core.PersistentVolumeClaim {
- annotations := map[string]string{
- ann: annval,
- }
- return &core.PersistentVolumeClaim{
- ObjectMeta: metav1.ObjectMeta{
- Name: name,
- Namespace: namespace,
- Annotations: annotations,
- },
- Spec: spec,
- }
- }
- func testVolumeClaimStorageClassInSpec(name, namespace, scName string, spec core.PersistentVolumeClaimSpec) *core.PersistentVolumeClaim {
- spec.StorageClassName = &scName
- return &core.PersistentVolumeClaim{
- ObjectMeta: metav1.ObjectMeta{
- Name: name,
- Namespace: namespace,
- },
- Spec: spec,
- }
- }
- func testVolumeSnapshotDataSourceInSpec(name string, kind string, apiGroup string) *core.PersistentVolumeClaimSpec {
- scName := "csi-plugin"
- dataSourceInSpec := core.PersistentVolumeClaimSpec{
- AccessModes: []core.PersistentVolumeAccessMode{
- core.ReadOnlyMany,
- },
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- },
- StorageClassName: &scName,
- DataSource: &core.TypedLocalObjectReference{
- APIGroup: &apiGroup,
- Kind: kind,
- Name: name,
- },
- }
- return &dataSourceInSpec
- }
- func TestAlphaVolumeSnapshotDataSource(t *testing.T) {
- successTestCases := []core.PersistentVolumeClaimSpec{
- *testVolumeSnapshotDataSourceInSpec("test_snapshot", "VolumeSnapshot", "snapshot.storage.k8s.io"),
- }
- failedTestCases := []core.PersistentVolumeClaimSpec{
- *testVolumeSnapshotDataSourceInSpec("", "VolumeSnapshot", "snapshot.storage.k8s.io"),
- *testVolumeSnapshotDataSourceInSpec("test_snapshot", "PersistentVolumeClaim", "snapshot.storage.k8s.io"),
- *testVolumeSnapshotDataSourceInSpec("test_snapshot", "VolumeSnapshot", "storage.k8s.io"),
- }
- for _, tc := range successTestCases {
- if errs := ValidatePersistentVolumeClaimSpec(&tc, field.NewPath("spec")); len(errs) != 0 {
- t.Errorf("expected success: %v", errs)
- }
- }
- for _, tc := range failedTestCases {
- if errs := ValidatePersistentVolumeClaimSpec(&tc, field.NewPath("spec")); len(errs) == 0 {
- t.Errorf("expected failure: %v", errs)
- }
- }
- }
- func testVolumeClaimStorageClassInAnnotationAndSpec(name, namespace, scNameInAnn, scName string, spec core.PersistentVolumeClaimSpec) *core.PersistentVolumeClaim {
- spec.StorageClassName = &scName
- return &core.PersistentVolumeClaim{
- ObjectMeta: metav1.ObjectMeta{
- Name: name,
- Namespace: namespace,
- Annotations: map[string]string{v1.BetaStorageClassAnnotation: scNameInAnn},
- },
- Spec: spec,
- }
- }
- func TestValidatePersistentVolumeClaim(t *testing.T) {
- invalidClassName := "-invalid-"
- validClassName := "valid"
- invalidMode := core.PersistentVolumeMode("fakeVolumeMode")
- validMode := core.PersistentVolumeFilesystem
- scenarios := map[string]struct {
- isExpectedFailure bool
- claim *core.PersistentVolumeClaim
- }{
- "good-claim": {
- isExpectedFailure: false,
- claim: testVolumeClaim("foo", "ns", core.PersistentVolumeClaimSpec{
- Selector: &metav1.LabelSelector{
- MatchExpressions: []metav1.LabelSelectorRequirement{
- {
- Key: "key2",
- Operator: "Exists",
- },
- },
- },
- AccessModes: []core.PersistentVolumeAccessMode{
- core.ReadWriteOnce,
- core.ReadOnlyMany,
- },
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- },
- StorageClassName: &validClassName,
- VolumeMode: &validMode,
- }),
- },
- "invalid-claim-zero-capacity": {
- isExpectedFailure: true,
- claim: testVolumeClaim("foo", "ns", core.PersistentVolumeClaimSpec{
- Selector: &metav1.LabelSelector{
- MatchExpressions: []metav1.LabelSelectorRequirement{
- {
- Key: "key2",
- Operator: "Exists",
- },
- },
- },
- AccessModes: []core.PersistentVolumeAccessMode{
- core.ReadWriteOnce,
- core.ReadOnlyMany,
- },
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("0G"),
- },
- },
- StorageClassName: &validClassName,
- }),
- },
- "invalid-label-selector": {
- isExpectedFailure: true,
- claim: testVolumeClaim("foo", "ns", core.PersistentVolumeClaimSpec{
- Selector: &metav1.LabelSelector{
- MatchExpressions: []metav1.LabelSelectorRequirement{
- {
- Key: "key2",
- Operator: "InvalidOp",
- Values: []string{"value1", "value2"},
- },
- },
- },
- AccessModes: []core.PersistentVolumeAccessMode{
- core.ReadWriteOnce,
- core.ReadOnlyMany,
- },
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- },
- }),
- },
- "invalid-accessmode": {
- isExpectedFailure: true,
- claim: testVolumeClaim("foo", "ns", core.PersistentVolumeClaimSpec{
- AccessModes: []core.PersistentVolumeAccessMode{"fakemode"},
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- },
- }),
- },
- "missing-namespace": {
- isExpectedFailure: true,
- claim: testVolumeClaim("foo", "", core.PersistentVolumeClaimSpec{
- AccessModes: []core.PersistentVolumeAccessMode{
- core.ReadWriteOnce,
- core.ReadOnlyMany,
- },
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- },
- }),
- },
- "no-access-modes": {
- isExpectedFailure: true,
- claim: testVolumeClaim("foo", "ns", core.PersistentVolumeClaimSpec{
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- },
- }),
- },
- "no-resource-requests": {
- isExpectedFailure: true,
- claim: testVolumeClaim("foo", "ns", core.PersistentVolumeClaimSpec{
- AccessModes: []core.PersistentVolumeAccessMode{
- core.ReadWriteOnce,
- },
- }),
- },
- "invalid-resource-requests": {
- isExpectedFailure: true,
- claim: testVolumeClaim("foo", "ns", core.PersistentVolumeClaimSpec{
- AccessModes: []core.PersistentVolumeAccessMode{
- core.ReadWriteOnce,
- },
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName(core.ResourceMemory): resource.MustParse("10G"),
- },
- },
- }),
- },
- "negative-storage-request": {
- isExpectedFailure: true,
- claim: testVolumeClaim("foo", "ns", core.PersistentVolumeClaimSpec{
- Selector: &metav1.LabelSelector{
- MatchExpressions: []metav1.LabelSelectorRequirement{
- {
- Key: "key2",
- Operator: "Exists",
- },
- },
- },
- AccessModes: []core.PersistentVolumeAccessMode{
- core.ReadWriteOnce,
- core.ReadOnlyMany,
- },
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("-10G"),
- },
- },
- }),
- },
- "zero-storage-request": {
- isExpectedFailure: true,
- claim: testVolumeClaim("foo", "ns", core.PersistentVolumeClaimSpec{
- Selector: &metav1.LabelSelector{
- MatchExpressions: []metav1.LabelSelectorRequirement{
- {
- Key: "key2",
- Operator: "Exists",
- },
- },
- },
- AccessModes: []core.PersistentVolumeAccessMode{
- core.ReadWriteOnce,
- core.ReadOnlyMany,
- },
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("0G"),
- },
- },
- }),
- },
- "invalid-storage-class-name": {
- isExpectedFailure: true,
- claim: testVolumeClaim("foo", "ns", core.PersistentVolumeClaimSpec{
- Selector: &metav1.LabelSelector{
- MatchExpressions: []metav1.LabelSelectorRequirement{
- {
- Key: "key2",
- Operator: "Exists",
- },
- },
- },
- AccessModes: []core.PersistentVolumeAccessMode{
- core.ReadWriteOnce,
- core.ReadOnlyMany,
- },
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- },
- StorageClassName: &invalidClassName,
- }),
- },
- "invalid-volume-mode": {
- isExpectedFailure: true,
- claim: testVolumeClaim("foo", "ns", core.PersistentVolumeClaimSpec{
- AccessModes: []core.PersistentVolumeAccessMode{
- core.ReadWriteOnce,
- core.ReadOnlyMany,
- },
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- },
- VolumeMode: &invalidMode,
- }),
- },
- }
- for name, scenario := range scenarios {
- t.Run(name, func(t *testing.T) {
- errs := ValidatePersistentVolumeClaim(scenario.claim)
- if len(errs) == 0 && scenario.isExpectedFailure {
- t.Errorf("Unexpected success for scenario: %s", name)
- }
- if len(errs) > 0 && !scenario.isExpectedFailure {
- t.Errorf("Unexpected failure for scenario: %s - %+v", name, errs)
- }
- })
- }
- }
- func TestAlphaPVVolumeModeUpdate(t *testing.T) {
- block := core.PersistentVolumeBlock
- file := core.PersistentVolumeFilesystem
- scenarios := map[string]struct {
- isExpectedFailure bool
- oldPV *core.PersistentVolume
- newPV *core.PersistentVolume
- }{
- "valid-update-volume-mode-block-to-block": {
- isExpectedFailure: false,
- oldPV: createTestVolModePV(&block),
- newPV: createTestVolModePV(&block),
- },
- "valid-update-volume-mode-file-to-file": {
- isExpectedFailure: false,
- oldPV: createTestVolModePV(&file),
- newPV: createTestVolModePV(&file),
- },
- "invalid-update-volume-mode-to-block": {
- isExpectedFailure: true,
- oldPV: createTestVolModePV(&file),
- newPV: createTestVolModePV(&block),
- },
- "invalid-update-volume-mode-to-file": {
- isExpectedFailure: true,
- oldPV: createTestVolModePV(&block),
- newPV: createTestVolModePV(&file),
- },
- "invalid-update-volume-mode-nil-to-file": {
- isExpectedFailure: true,
- oldPV: createTestVolModePV(nil),
- newPV: createTestVolModePV(&file),
- },
- "invalid-update-volume-mode-nil-to-block": {
- isExpectedFailure: true,
- oldPV: createTestVolModePV(nil),
- newPV: createTestVolModePV(&block),
- },
- "invalid-update-volume-mode-file-to-nil": {
- isExpectedFailure: true,
- oldPV: createTestVolModePV(&file),
- newPV: createTestVolModePV(nil),
- },
- "invalid-update-volume-mode-block-to-nil": {
- isExpectedFailure: true,
- oldPV: createTestVolModePV(&block),
- newPV: createTestVolModePV(nil),
- },
- "invalid-update-volume-mode-nil-to-nil": {
- isExpectedFailure: false,
- oldPV: createTestVolModePV(nil),
- newPV: createTestVolModePV(nil),
- },
- "invalid-update-volume-mode-empty-to-mode": {
- isExpectedFailure: true,
- oldPV: createTestPV(),
- newPV: createTestVolModePV(&block),
- },
- }
- for name, scenario := range scenarios {
- t.Run(name, func(t *testing.T) {
- // ensure we have a resource version specified for updates
- errs := ValidatePersistentVolumeUpdate(scenario.newPV, scenario.oldPV)
- if len(errs) == 0 && scenario.isExpectedFailure {
- t.Errorf("Unexpected success for scenario: %s", name)
- }
- if len(errs) > 0 && !scenario.isExpectedFailure {
- t.Errorf("Unexpected failure for scenario: %s - %+v", name, errs)
- }
- })
- }
- }
- func TestValidatePersistentVolumeClaimUpdate(t *testing.T) {
- block := core.PersistentVolumeBlock
- file := core.PersistentVolumeFilesystem
- validClaim := testVolumeClaimWithStatus("foo", "ns", core.PersistentVolumeClaimSpec{
- AccessModes: []core.PersistentVolumeAccessMode{
- core.ReadWriteOnce,
- core.ReadOnlyMany,
- },
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- },
- }, core.PersistentVolumeClaimStatus{
- Phase: core.ClaimBound,
- })
- validClaimStorageClass := testVolumeClaimStorageClass("foo", "ns", "fast", core.PersistentVolumeClaimSpec{
- AccessModes: []core.PersistentVolumeAccessMode{
- core.ReadOnlyMany,
- },
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- },
- })
- validClaimAnnotation := testVolumeClaimAnnotation("foo", "ns", "description", "foo-description", core.PersistentVolumeClaimSpec{
- AccessModes: []core.PersistentVolumeAccessMode{
- core.ReadOnlyMany,
- },
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- },
- })
- validUpdateClaim := testVolumeClaim("foo", "ns", core.PersistentVolumeClaimSpec{
- AccessModes: []core.PersistentVolumeAccessMode{
- core.ReadWriteOnce,
- core.ReadOnlyMany,
- },
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- },
- VolumeName: "volume",
- })
- invalidUpdateClaimResources := testVolumeClaim("foo", "ns", core.PersistentVolumeClaimSpec{
- AccessModes: []core.PersistentVolumeAccessMode{
- core.ReadWriteOnce,
- core.ReadOnlyMany,
- },
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("20G"),
- },
- },
- VolumeName: "volume",
- })
- invalidUpdateClaimAccessModes := testVolumeClaim("foo", "ns", core.PersistentVolumeClaimSpec{
- AccessModes: []core.PersistentVolumeAccessMode{
- core.ReadWriteOnce,
- },
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- },
- VolumeName: "volume",
- })
- validClaimVolumeModeFile := testVolumeClaim("foo", "ns", core.PersistentVolumeClaimSpec{
- AccessModes: []core.PersistentVolumeAccessMode{
- core.ReadWriteOnce,
- },
- VolumeMode: &file,
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- },
- VolumeName: "volume",
- })
- validClaimVolumeModeBlock := testVolumeClaim("foo", "ns", core.PersistentVolumeClaimSpec{
- AccessModes: []core.PersistentVolumeAccessMode{
- core.ReadWriteOnce,
- },
- VolumeMode: &block,
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- },
- VolumeName: "volume",
- })
- invalidClaimVolumeModeNil := testVolumeClaim("foo", "ns", core.PersistentVolumeClaimSpec{
- AccessModes: []core.PersistentVolumeAccessMode{
- core.ReadWriteOnce,
- },
- VolumeMode: nil,
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- },
- VolumeName: "volume",
- })
- invalidUpdateClaimStorageClass := testVolumeClaimStorageClass("foo", "ns", "fast2", core.PersistentVolumeClaimSpec{
- AccessModes: []core.PersistentVolumeAccessMode{
- core.ReadOnlyMany,
- },
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- },
- VolumeName: "volume",
- })
- validUpdateClaimMutableAnnotation := testVolumeClaimAnnotation("foo", "ns", "description", "updated-or-added-foo-description", core.PersistentVolumeClaimSpec{
- AccessModes: []core.PersistentVolumeAccessMode{
- core.ReadOnlyMany,
- },
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- },
- VolumeName: "volume",
- })
- validAddClaimAnnotation := testVolumeClaimAnnotation("foo", "ns", "description", "updated-or-added-foo-description", core.PersistentVolumeClaimSpec{
- AccessModes: []core.PersistentVolumeAccessMode{
- core.ReadWriteOnce,
- core.ReadOnlyMany,
- },
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- },
- VolumeName: "volume",
- })
- validSizeUpdate := testVolumeClaimWithStatus("foo", "ns", core.PersistentVolumeClaimSpec{
- AccessModes: []core.PersistentVolumeAccessMode{
- core.ReadWriteOnce,
- core.ReadOnlyMany,
- },
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("15G"),
- },
- },
- }, core.PersistentVolumeClaimStatus{
- Phase: core.ClaimBound,
- })
- invalidSizeUpdate := testVolumeClaimWithStatus("foo", "ns", core.PersistentVolumeClaimSpec{
- AccessModes: []core.PersistentVolumeAccessMode{
- core.ReadWriteOnce,
- core.ReadOnlyMany,
- },
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("5G"),
- },
- },
- }, core.PersistentVolumeClaimStatus{
- Phase: core.ClaimBound,
- })
- unboundSizeUpdate := testVolumeClaimWithStatus("foo", "ns", core.PersistentVolumeClaimSpec{
- AccessModes: []core.PersistentVolumeAccessMode{
- core.ReadWriteOnce,
- core.ReadOnlyMany,
- },
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("12G"),
- },
- },
- }, core.PersistentVolumeClaimStatus{
- Phase: core.ClaimPending,
- })
- validClaimStorageClassInSpec := testVolumeClaimStorageClassInSpec("foo", "ns", "fast", core.PersistentVolumeClaimSpec{
- AccessModes: []core.PersistentVolumeAccessMode{
- core.ReadOnlyMany,
- },
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- },
- })
- invalidClaimStorageClassInSpec := testVolumeClaimStorageClassInSpec("foo", "ns", "fast2", core.PersistentVolumeClaimSpec{
- AccessModes: []core.PersistentVolumeAccessMode{
- core.ReadOnlyMany,
- },
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- },
- })
- validClaimStorageClassInAnnotationAndSpec := testVolumeClaimStorageClassInAnnotationAndSpec(
- "foo", "ns", "fast", "fast", core.PersistentVolumeClaimSpec{
- AccessModes: []core.PersistentVolumeAccessMode{
- core.ReadOnlyMany,
- },
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- },
- })
- invalidClaimStorageClassInAnnotationAndSpec := testVolumeClaimStorageClassInAnnotationAndSpec(
- "foo", "ns", "fast2", "fast", core.PersistentVolumeClaimSpec{
- AccessModes: []core.PersistentVolumeAccessMode{
- core.ReadOnlyMany,
- },
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- },
- })
- scenarios := map[string]struct {
- isExpectedFailure bool
- oldClaim *core.PersistentVolumeClaim
- newClaim *core.PersistentVolumeClaim
- enableResize bool
- enableBlock bool
- }{
- "valid-update-volumeName-only": {
- isExpectedFailure: false,
- oldClaim: validClaim,
- newClaim: validUpdateClaim,
- enableResize: false,
- enableBlock: false,
- },
- "valid-no-op-update": {
- isExpectedFailure: false,
- oldClaim: validUpdateClaim,
- newClaim: validUpdateClaim,
- enableResize: false,
- enableBlock: false,
- },
- "invalid-update-change-resources-on-bound-claim": {
- isExpectedFailure: true,
- oldClaim: validUpdateClaim,
- newClaim: invalidUpdateClaimResources,
- enableResize: false,
- enableBlock: false,
- },
- "invalid-update-change-access-modes-on-bound-claim": {
- isExpectedFailure: true,
- oldClaim: validUpdateClaim,
- newClaim: invalidUpdateClaimAccessModes,
- enableResize: false,
- enableBlock: false,
- },
- "valid-update-volume-mode-block-to-block": {
- isExpectedFailure: false,
- oldClaim: validClaimVolumeModeBlock,
- newClaim: validClaimVolumeModeBlock,
- enableResize: false,
- enableBlock: true,
- },
- "valid-update-volume-mode-file-to-file": {
- isExpectedFailure: false,
- oldClaim: validClaimVolumeModeFile,
- newClaim: validClaimVolumeModeFile,
- enableResize: false,
- enableBlock: true,
- },
- "invalid-update-volume-mode-to-block": {
- isExpectedFailure: true,
- oldClaim: validClaimVolumeModeFile,
- newClaim: validClaimVolumeModeBlock,
- enableResize: false,
- enableBlock: true,
- },
- "invalid-update-volume-mode-to-file": {
- isExpectedFailure: true,
- oldClaim: validClaimVolumeModeBlock,
- newClaim: validClaimVolumeModeFile,
- enableResize: false,
- enableBlock: true,
- },
- "invalid-update-volume-mode-nil-to-file": {
- isExpectedFailure: true,
- oldClaim: invalidClaimVolumeModeNil,
- newClaim: validClaimVolumeModeFile,
- enableResize: false,
- enableBlock: true,
- },
- "invalid-update-volume-mode-nil-to-block": {
- isExpectedFailure: true,
- oldClaim: invalidClaimVolumeModeNil,
- newClaim: validClaimVolumeModeBlock,
- enableResize: false,
- enableBlock: true,
- },
- "invalid-update-volume-mode-block-to-nil": {
- isExpectedFailure: true,
- oldClaim: validClaimVolumeModeBlock,
- newClaim: invalidClaimVolumeModeNil,
- enableResize: false,
- enableBlock: true,
- },
- "invalid-update-volume-mode-file-to-nil": {
- isExpectedFailure: true,
- oldClaim: validClaimVolumeModeFile,
- newClaim: invalidClaimVolumeModeNil,
- enableResize: false,
- enableBlock: true,
- },
- "invalid-update-volume-mode-empty-to-mode": {
- isExpectedFailure: true,
- oldClaim: validClaim,
- newClaim: validClaimVolumeModeBlock,
- enableResize: false,
- enableBlock: true,
- },
- "invalid-update-volume-mode-mode-to-empty": {
- isExpectedFailure: true,
- oldClaim: validClaimVolumeModeBlock,
- newClaim: validClaim,
- enableResize: false,
- enableBlock: true,
- },
- // with the new validation changes this test should not fail
- "noop-update-volumemode-allowed": {
- isExpectedFailure: false,
- oldClaim: validClaimVolumeModeFile,
- newClaim: validClaimVolumeModeFile,
- enableResize: false,
- enableBlock: false,
- },
- "invalid-update-change-storage-class-annotation-after-creation": {
- isExpectedFailure: true,
- oldClaim: validClaimStorageClass,
- newClaim: invalidUpdateClaimStorageClass,
- enableResize: false,
- enableBlock: false,
- },
- "valid-update-mutable-annotation": {
- isExpectedFailure: false,
- oldClaim: validClaimAnnotation,
- newClaim: validUpdateClaimMutableAnnotation,
- enableResize: false,
- enableBlock: false,
- },
- "valid-update-add-annotation": {
- isExpectedFailure: false,
- oldClaim: validClaim,
- newClaim: validAddClaimAnnotation,
- enableResize: false,
- enableBlock: false,
- },
- "valid-size-update-resize-disabled": {
- isExpectedFailure: true,
- oldClaim: validClaim,
- newClaim: validSizeUpdate,
- enableResize: false,
- enableBlock: false,
- },
- "valid-size-update-resize-enabled": {
- isExpectedFailure: false,
- oldClaim: validClaim,
- newClaim: validSizeUpdate,
- enableResize: true,
- enableBlock: false,
- },
- "invalid-size-update-resize-enabled": {
- isExpectedFailure: true,
- oldClaim: validClaim,
- newClaim: invalidSizeUpdate,
- enableResize: true,
- enableBlock: false,
- },
- "unbound-size-update-resize-enabled": {
- isExpectedFailure: true,
- oldClaim: validClaim,
- newClaim: unboundSizeUpdate,
- enableResize: true,
- enableBlock: false,
- },
- "valid-upgrade-storage-class-annotation-to-spec": {
- isExpectedFailure: false,
- oldClaim: validClaimStorageClass,
- newClaim: validClaimStorageClassInSpec,
- enableResize: false,
- enableBlock: false,
- },
- "invalid-upgrade-storage-class-annotation-to-spec": {
- isExpectedFailure: true,
- oldClaim: validClaimStorageClass,
- newClaim: invalidClaimStorageClassInSpec,
- enableResize: false,
- enableBlock: false,
- },
- "valid-upgrade-storage-class-annotation-to-annotation-and-spec": {
- isExpectedFailure: false,
- oldClaim: validClaimStorageClass,
- newClaim: validClaimStorageClassInAnnotationAndSpec,
- enableResize: false,
- enableBlock: false,
- },
- "invalid-upgrade-storage-class-annotation-to-annotation-and-spec": {
- isExpectedFailure: true,
- oldClaim: validClaimStorageClass,
- newClaim: invalidClaimStorageClassInAnnotationAndSpec,
- enableResize: false,
- enableBlock: false,
- },
- "invalid-upgrade-storage-class-in-spec": {
- isExpectedFailure: true,
- oldClaim: validClaimStorageClassInSpec,
- newClaim: invalidClaimStorageClassInSpec,
- enableResize: false,
- enableBlock: false,
- },
- "invalid-downgrade-storage-class-spec-to-annotation": {
- isExpectedFailure: true,
- oldClaim: validClaimStorageClassInSpec,
- newClaim: validClaimStorageClass,
- enableResize: false,
- enableBlock: false,
- },
- }
- for name, scenario := range scenarios {
- t.Run(name, func(t *testing.T) {
- // ensure we have a resource version specified for updates
- defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.ExpandPersistentVolumes, scenario.enableResize)()
- defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.BlockVolume, scenario.enableBlock)()
- scenario.oldClaim.ResourceVersion = "1"
- scenario.newClaim.ResourceVersion = "1"
- errs := ValidatePersistentVolumeClaimUpdate(scenario.newClaim, scenario.oldClaim)
- if len(errs) == 0 && scenario.isExpectedFailure {
- t.Errorf("Unexpected success for scenario: %s", name)
- }
- if len(errs) > 0 && !scenario.isExpectedFailure {
- t.Errorf("Unexpected failure for scenario: %s - %+v", name, errs)
- }
- })
- }
- }
- func TestValidateKeyToPath(t *testing.T) {
- testCases := []struct {
- kp core.KeyToPath
- ok bool
- errtype field.ErrorType
- }{
- {
- kp: core.KeyToPath{Key: "k", Path: "p"},
- ok: true,
- },
- {
- kp: core.KeyToPath{Key: "k", Path: "p/p/p/p"},
- ok: true,
- },
- {
- kp: core.KeyToPath{Key: "k", Path: "p/..p/p../p..p"},
- ok: true,
- },
- {
- kp: core.KeyToPath{Key: "k", Path: "p", Mode: utilpointer.Int32Ptr(0644)},
- ok: true,
- },
- {
- kp: core.KeyToPath{Key: "", Path: "p"},
- ok: false,
- errtype: field.ErrorTypeRequired,
- },
- {
- kp: core.KeyToPath{Key: "k", Path: ""},
- ok: false,
- errtype: field.ErrorTypeRequired,
- },
- {
- kp: core.KeyToPath{Key: "k", Path: "..p"},
- ok: false,
- errtype: field.ErrorTypeInvalid,
- },
- {
- kp: core.KeyToPath{Key: "k", Path: "../p"},
- ok: false,
- errtype: field.ErrorTypeInvalid,
- },
- {
- kp: core.KeyToPath{Key: "k", Path: "p/../p"},
- ok: false,
- errtype: field.ErrorTypeInvalid,
- },
- {
- kp: core.KeyToPath{Key: "k", Path: "p/.."},
- ok: false,
- errtype: field.ErrorTypeInvalid,
- },
- {
- kp: core.KeyToPath{Key: "k", Path: "p", Mode: utilpointer.Int32Ptr(01000)},
- ok: false,
- errtype: field.ErrorTypeInvalid,
- },
- {
- kp: core.KeyToPath{Key: "k", Path: "p", Mode: utilpointer.Int32Ptr(-1)},
- ok: false,
- errtype: field.ErrorTypeInvalid,
- },
- }
- for i, tc := range testCases {
- errs := validateKeyToPath(&tc.kp, field.NewPath("field"))
- if tc.ok && len(errs) > 0 {
- t.Errorf("[%d] unexpected errors: %v", i, errs)
- } else if !tc.ok && len(errs) == 0 {
- t.Errorf("[%d] expected error type %v", i, tc.errtype)
- } else if len(errs) > 1 {
- t.Errorf("[%d] expected only one error, got %d", i, len(errs))
- } else if !tc.ok {
- if errs[0].Type != tc.errtype {
- t.Errorf("[%d] expected error type %v, got %v", i, tc.errtype, errs[0].Type)
- }
- }
- }
- }
- func TestValidateNFSVolumeSource(t *testing.T) {
- testCases := []struct {
- name string
- nfs *core.NFSVolumeSource
- errtype field.ErrorType
- errfield string
- errdetail string
- }{
- {
- name: "missing server",
- nfs: &core.NFSVolumeSource{Server: "", Path: "/tmp"},
- errtype: field.ErrorTypeRequired,
- errfield: "server",
- },
- {
- name: "missing path",
- nfs: &core.NFSVolumeSource{Server: "my-server", Path: ""},
- errtype: field.ErrorTypeRequired,
- errfield: "path",
- },
- {
- name: "abs path",
- nfs: &core.NFSVolumeSource{Server: "my-server", Path: "tmp"},
- errtype: field.ErrorTypeInvalid,
- errfield: "path",
- errdetail: "must be an absolute path",
- },
- }
- for i, tc := range testCases {
- errs := validateNFSVolumeSource(tc.nfs, field.NewPath("field"))
- if len(errs) > 0 && tc.errtype == "" {
- t.Errorf("[%d: %q] unexpected error(s): %v", i, tc.name, errs)
- } else if len(errs) == 0 && tc.errtype != "" {
- t.Errorf("[%d: %q] expected error type %v", i, tc.name, tc.errtype)
- } else if len(errs) >= 1 {
- if errs[0].Type != tc.errtype {
- t.Errorf("[%d: %q] expected error type %v, got %v", i, tc.name, tc.errtype, errs[0].Type)
- } else if !strings.HasSuffix(errs[0].Field, "."+tc.errfield) {
- t.Errorf("[%d: %q] expected error on field %q, got %q", i, tc.name, tc.errfield, errs[0].Field)
- } else if !strings.Contains(errs[0].Detail, tc.errdetail) {
- t.Errorf("[%d: %q] expected error detail %q, got %q", i, tc.name, tc.errdetail, errs[0].Detail)
- }
- }
- }
- }
- func TestValidateGlusterfs(t *testing.T) {
- testCases := []struct {
- name string
- gfs *core.GlusterfsVolumeSource
- errtype field.ErrorType
- errfield string
- }{
- {
- name: "missing endpointname",
- gfs: &core.GlusterfsVolumeSource{EndpointsName: "", Path: "/tmp"},
- errtype: field.ErrorTypeRequired,
- errfield: "endpoints",
- },
- {
- name: "missing path",
- gfs: &core.GlusterfsVolumeSource{EndpointsName: "my-endpoint", Path: ""},
- errtype: field.ErrorTypeRequired,
- errfield: "path",
- },
- {
- name: "missing endpointname and path",
- gfs: &core.GlusterfsVolumeSource{EndpointsName: "", Path: ""},
- errtype: field.ErrorTypeRequired,
- errfield: "endpoints",
- },
- }
- for i, tc := range testCases {
- errs := validateGlusterfsVolumeSource(tc.gfs, field.NewPath("field"))
- if len(errs) > 0 && tc.errtype == "" {
- t.Errorf("[%d: %q] unexpected error(s): %v", i, tc.name, errs)
- } else if len(errs) == 0 && tc.errtype != "" {
- t.Errorf("[%d: %q] expected error type %v", i, tc.name, tc.errtype)
- } else if len(errs) >= 1 {
- if errs[0].Type != tc.errtype {
- t.Errorf("[%d: %q] expected error type %v, got %v", i, tc.name, tc.errtype, errs[0].Type)
- } else if !strings.HasSuffix(errs[0].Field, "."+tc.errfield) {
- t.Errorf("[%d: %q] expected error on field %q, got %q", i, tc.name, tc.errfield, errs[0].Field)
- }
- }
- }
- }
- func TestValidateGlusterfsPersistentVolumeSource(t *testing.T) {
- var epNs *string
- namespace := ""
- epNs = &namespace
- testCases := []struct {
- name string
- gfs *core.GlusterfsPersistentVolumeSource
- errtype field.ErrorType
- errfield string
- }{
- {
- name: "missing endpointname",
- gfs: &core.GlusterfsPersistentVolumeSource{EndpointsName: "", Path: "/tmp"},
- errtype: field.ErrorTypeRequired,
- errfield: "endpoints",
- },
- {
- name: "missing path",
- gfs: &core.GlusterfsPersistentVolumeSource{EndpointsName: "my-endpoint", Path: ""},
- errtype: field.ErrorTypeRequired,
- errfield: "path",
- },
- {
- name: "non null endpointnamespace with empty string",
- gfs: &core.GlusterfsPersistentVolumeSource{EndpointsName: "my-endpoint", Path: "/tmp", EndpointsNamespace: epNs},
- errtype: field.ErrorTypeInvalid,
- errfield: "endpointsNamespace",
- },
- {
- name: "missing endpointname and path",
- gfs: &core.GlusterfsPersistentVolumeSource{EndpointsName: "", Path: ""},
- errtype: field.ErrorTypeRequired,
- errfield: "endpoints",
- },
- }
- for i, tc := range testCases {
- errs := validateGlusterfsPersistentVolumeSource(tc.gfs, field.NewPath("field"))
- if len(errs) > 0 && tc.errtype == "" {
- t.Errorf("[%d: %q] unexpected error(s): %v", i, tc.name, errs)
- } else if len(errs) == 0 && tc.errtype != "" {
- t.Errorf("[%d: %q] expected error type %v", i, tc.name, tc.errtype)
- } else if len(errs) >= 1 {
- if errs[0].Type != tc.errtype {
- t.Errorf("[%d: %q] expected error type %v, got %v", i, tc.name, tc.errtype, errs[0].Type)
- } else if !strings.HasSuffix(errs[0].Field, "."+tc.errfield) {
- t.Errorf("[%d: %q] expected error on field %q, got %q", i, tc.name, tc.errfield, errs[0].Field)
- }
- }
- }
- }
- func TestValidateCSIVolumeSource(t *testing.T) {
- testCases := []struct {
- name string
- csi *core.CSIPersistentVolumeSource
- errtype field.ErrorType
- errfield string
- }{
- {
- name: "all required fields ok",
- csi: &core.CSIPersistentVolumeSource{Driver: "test-driver", VolumeHandle: "test-123", ReadOnly: true},
- },
- {
- name: "with default values ok",
- csi: &core.CSIPersistentVolumeSource{Driver: "test-driver", VolumeHandle: "test-123"},
- },
- {
- name: "missing driver name",
- csi: &core.CSIPersistentVolumeSource{VolumeHandle: "test-123"},
- errtype: field.ErrorTypeRequired,
- errfield: "driver",
- },
- {
- name: "missing volume handle",
- csi: &core.CSIPersistentVolumeSource{Driver: "my-driver"},
- errtype: field.ErrorTypeRequired,
- errfield: "volumeHandle",
- },
- {
- name: "driver name: ok no punctuations",
- csi: &core.CSIPersistentVolumeSource{Driver: "comgooglestoragecsigcepd", VolumeHandle: "test-123"},
- },
- {
- name: "driver name: ok dot only",
- csi: &core.CSIPersistentVolumeSource{Driver: "io.kubernetes.storage.csi.flex", VolumeHandle: "test-123"},
- },
- {
- name: "driver name: ok dash only",
- csi: &core.CSIPersistentVolumeSource{Driver: "io-kubernetes-storage-csi-flex", VolumeHandle: "test-123"},
- },
- {
- name: "driver name: invalid underscore",
- csi: &core.CSIPersistentVolumeSource{Driver: "io_kubernetes_storage_csi_flex", VolumeHandle: "test-123"},
- errtype: field.ErrorTypeInvalid,
- errfield: "driver",
- },
- {
- name: "driver name: invalid dot underscores",
- csi: &core.CSIPersistentVolumeSource{Driver: "io.kubernetes.storage_csi.flex", VolumeHandle: "test-123"},
- errtype: field.ErrorTypeInvalid,
- errfield: "driver",
- },
- {
- name: "driver name: ok beginnin with number",
- csi: &core.CSIPersistentVolumeSource{Driver: "2io.kubernetes.storage-csi.flex", VolumeHandle: "test-123"},
- },
- {
- name: "driver name: ok ending with number",
- csi: &core.CSIPersistentVolumeSource{Driver: "io.kubernetes.storage-csi.flex2", VolumeHandle: "test-123"},
- },
- {
- name: "driver name: invalid dot dash underscores",
- csi: &core.CSIPersistentVolumeSource{Driver: "io.kubernetes-storage.csi_flex", VolumeHandle: "test-123"},
- errtype: field.ErrorTypeInvalid,
- errfield: "driver",
- },
- {
- name: "driver name: invalid length 0",
- csi: &core.CSIPersistentVolumeSource{Driver: "", VolumeHandle: "test-123"},
- errtype: field.ErrorTypeRequired,
- errfield: "driver",
- },
- {
- name: "driver name: ok length 1",
- csi: &core.CSIPersistentVolumeSource{Driver: "a", VolumeHandle: "test-123"},
- },
- {
- name: "driver name: invalid length > 63",
- csi: &core.CSIPersistentVolumeSource{Driver: "comgooglestoragecsigcepdcomgooglestoragecsigcepdcomgooglestoragecsigcepdcomgooglestoragecsigcepd", VolumeHandle: "test-123"},
- errtype: field.ErrorTypeTooLong,
- errfield: "driver",
- },
- {
- name: "driver name: invalid start char",
- csi: &core.CSIPersistentVolumeSource{Driver: "_comgooglestoragecsigcepd", VolumeHandle: "test-123"},
- errtype: field.ErrorTypeInvalid,
- errfield: "driver",
- },
- {
- name: "driver name: invalid end char",
- csi: &core.CSIPersistentVolumeSource{Driver: "comgooglestoragecsigcepd/", VolumeHandle: "test-123"},
- errtype: field.ErrorTypeInvalid,
- errfield: "driver",
- },
- {
- name: "driver name: invalid separators",
- csi: &core.CSIPersistentVolumeSource{Driver: "com/google/storage/csi~gcepd", VolumeHandle: "test-123"},
- errtype: field.ErrorTypeInvalid,
- errfield: "driver",
- },
- {
- name: "controllerExpandSecretRef: invalid name missing",
- csi: &core.CSIPersistentVolumeSource{Driver: "com.google.gcepd", VolumeHandle: "foobar", ControllerExpandSecretRef: &core.SecretReference{Namespace: "default"}},
- errtype: field.ErrorTypeRequired,
- errfield: "controllerExpandSecretRef.name",
- },
- {
- name: "controllerExpandSecretRef: invalid namespace missing",
- csi: &core.CSIPersistentVolumeSource{Driver: "com.google.gcepd", VolumeHandle: "foobar", ControllerExpandSecretRef: &core.SecretReference{Name: "foobar"}},
- errtype: field.ErrorTypeRequired,
- errfield: "controllerExpandSecretRef.namespace",
- },
- {
- name: "valid controllerExpandSecretRef",
- csi: &core.CSIPersistentVolumeSource{Driver: "com.google.gcepd", VolumeHandle: "foobar", ControllerExpandSecretRef: &core.SecretReference{Name: "foobar", Namespace: "default"}},
- },
- }
- defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.CSIPersistentVolume, true)()
- for i, tc := range testCases {
- errs := validateCSIPersistentVolumeSource(tc.csi, field.NewPath("field"))
- if len(errs) > 0 && tc.errtype == "" {
- t.Errorf("[%d: %q] unexpected error(s): %v", i, tc.name, errs)
- } else if len(errs) == 0 && tc.errtype != "" {
- t.Errorf("[%d: %q] expected error type %v", i, tc.name, tc.errtype)
- } else if len(errs) >= 1 {
- if errs[0].Type != tc.errtype {
- t.Errorf("[%d: %q] expected error type %v, got %v", i, tc.name, tc.errtype, errs[0].Type)
- } else if !strings.HasSuffix(errs[0].Field, "."+tc.errfield) {
- t.Errorf("[%d: %q] expected error on field %q, got %q", i, tc.name, tc.errfield, errs[0].Field)
- }
- }
- }
- }
- // This test is a little too top-to-bottom. Ideally we would test each volume
- // type on its own, but we want to also make sure that the logic works through
- // the one-of wrapper, so we just do it all in one place.
- func TestValidateVolumes(t *testing.T) {
- validInitiatorName := "iqn.2015-02.example.com:init"
- invalidInitiatorName := "2015-02.example.com:init"
- type verr struct {
- etype field.ErrorType
- field string
- detail string
- }
- testCases := []struct {
- name string
- vol core.Volume
- errs []verr
- }{
- // EmptyDir and basic volume names
- {
- name: "valid alpha name",
- vol: core.Volume{
- Name: "empty",
- VolumeSource: core.VolumeSource{
- EmptyDir: &core.EmptyDirVolumeSource{},
- },
- },
- },
- {
- name: "valid num name",
- vol: core.Volume{
- Name: "123",
- VolumeSource: core.VolumeSource{
- EmptyDir: &core.EmptyDirVolumeSource{},
- },
- },
- },
- {
- name: "valid alphanum name",
- vol: core.Volume{
- Name: "empty-123",
- VolumeSource: core.VolumeSource{
- EmptyDir: &core.EmptyDirVolumeSource{},
- },
- },
- },
- {
- name: "valid numalpha name",
- vol: core.Volume{
- Name: "123-empty",
- VolumeSource: core.VolumeSource{
- EmptyDir: &core.EmptyDirVolumeSource{},
- },
- },
- },
- {
- name: "zero-length name",
- vol: core.Volume{
- Name: "",
- VolumeSource: core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{}},
- },
- errs: []verr{{
- etype: field.ErrorTypeRequired,
- field: "name",
- }},
- },
- {
- name: "name > 63 characters",
- vol: core.Volume{
- Name: strings.Repeat("a", 64),
- VolumeSource: core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{}},
- },
- errs: []verr{{
- etype: field.ErrorTypeInvalid,
- field: "name",
- detail: "must be no more than",
- }},
- },
- {
- name: "name not a DNS label",
- vol: core.Volume{
- Name: "a.b.c",
- VolumeSource: core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{}},
- },
- errs: []verr{{
- etype: field.ErrorTypeInvalid,
- field: "name",
- detail: dnsLabelErrMsg,
- }},
- },
- // More than one source field specified.
- {
- name: "more than one source",
- vol: core.Volume{
- Name: "dups",
- VolumeSource: core.VolumeSource{
- EmptyDir: &core.EmptyDirVolumeSource{},
- HostPath: &core.HostPathVolumeSource{
- Path: "/mnt/path",
- Type: newHostPathType(string(core.HostPathDirectory)),
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeForbidden,
- field: "hostPath",
- detail: "may not specify more than 1 volume",
- }},
- },
- // HostPath Default
- {
- name: "default HostPath",
- vol: core.Volume{
- Name: "hostpath",
- VolumeSource: core.VolumeSource{
- HostPath: &core.HostPathVolumeSource{
- Path: "/mnt/path",
- Type: newHostPathType(string(core.HostPathDirectory)),
- },
- },
- },
- },
- // HostPath Supported
- {
- name: "valid HostPath",
- vol: core.Volume{
- Name: "hostpath",
- VolumeSource: core.VolumeSource{
- HostPath: &core.HostPathVolumeSource{
- Path: "/mnt/path",
- Type: newHostPathType(string(core.HostPathSocket)),
- },
- },
- },
- },
- // HostPath Invalid
- {
- name: "invalid HostPath",
- vol: core.Volume{
- Name: "hostpath",
- VolumeSource: core.VolumeSource{
- HostPath: &core.HostPathVolumeSource{
- Path: "/mnt/path",
- Type: newHostPathType("invalid"),
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeNotSupported,
- field: "type",
- }},
- },
- {
- name: "invalid HostPath backsteps",
- vol: core.Volume{
- Name: "hostpath",
- VolumeSource: core.VolumeSource{
- HostPath: &core.HostPathVolumeSource{
- Path: "/mnt/path/..",
- Type: newHostPathType(string(core.HostPathDirectory)),
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeInvalid,
- field: "path",
- detail: "must not contain '..'",
- }},
- },
- // GcePersistentDisk
- {
- name: "valid GcePersistentDisk",
- vol: core.Volume{
- Name: "gce-pd",
- VolumeSource: core.VolumeSource{
- GCEPersistentDisk: &core.GCEPersistentDiskVolumeSource{
- PDName: "my-PD",
- FSType: "ext4",
- Partition: 1,
- ReadOnly: false,
- },
- },
- },
- },
- // AWSElasticBlockStore
- {
- name: "valid AWSElasticBlockStore",
- vol: core.Volume{
- Name: "aws-ebs",
- VolumeSource: core.VolumeSource{
- AWSElasticBlockStore: &core.AWSElasticBlockStoreVolumeSource{
- VolumeID: "my-PD",
- FSType: "ext4",
- Partition: 1,
- ReadOnly: false,
- },
- },
- },
- },
- // GitRepo
- {
- name: "valid GitRepo",
- vol: core.Volume{
- Name: "git-repo",
- VolumeSource: core.VolumeSource{
- GitRepo: &core.GitRepoVolumeSource{
- Repository: "my-repo",
- Revision: "hashstring",
- Directory: "target",
- },
- },
- },
- },
- {
- name: "valid GitRepo in .",
- vol: core.Volume{
- Name: "git-repo-dot",
- VolumeSource: core.VolumeSource{
- GitRepo: &core.GitRepoVolumeSource{
- Repository: "my-repo",
- Directory: ".",
- },
- },
- },
- },
- {
- name: "valid GitRepo with .. in name",
- vol: core.Volume{
- Name: "git-repo-dot-dot-foo",
- VolumeSource: core.VolumeSource{
- GitRepo: &core.GitRepoVolumeSource{
- Repository: "my-repo",
- Directory: "..foo",
- },
- },
- },
- },
- {
- name: "GitRepo starts with ../",
- vol: core.Volume{
- Name: "gitrepo",
- VolumeSource: core.VolumeSource{
- GitRepo: &core.GitRepoVolumeSource{
- Repository: "foo",
- Directory: "../dots/bar",
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeInvalid,
- field: "gitRepo.directory",
- detail: `must not contain '..'`,
- }},
- },
- {
- name: "GitRepo contains ..",
- vol: core.Volume{
- Name: "gitrepo",
- VolumeSource: core.VolumeSource{
- GitRepo: &core.GitRepoVolumeSource{
- Repository: "foo",
- Directory: "dots/../bar",
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeInvalid,
- field: "gitRepo.directory",
- detail: `must not contain '..'`,
- }},
- },
- {
- name: "GitRepo absolute target",
- vol: core.Volume{
- Name: "gitrepo",
- VolumeSource: core.VolumeSource{
- GitRepo: &core.GitRepoVolumeSource{
- Repository: "foo",
- Directory: "/abstarget",
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeInvalid,
- field: "gitRepo.directory",
- }},
- },
- // ISCSI
- {
- name: "valid ISCSI",
- vol: core.Volume{
- Name: "iscsi",
- VolumeSource: core.VolumeSource{
- ISCSI: &core.ISCSIVolumeSource{
- TargetPortal: "127.0.0.1",
- IQN: "iqn.2015-02.example.com:test",
- Lun: 1,
- FSType: "ext4",
- ReadOnly: false,
- },
- },
- },
- },
- {
- name: "valid IQN: eui format",
- vol: core.Volume{
- Name: "iscsi",
- VolumeSource: core.VolumeSource{
- ISCSI: &core.ISCSIVolumeSource{
- TargetPortal: "127.0.0.1",
- IQN: "eui.0123456789ABCDEF",
- Lun: 1,
- FSType: "ext4",
- ReadOnly: false,
- },
- },
- },
- },
- {
- name: "valid IQN: naa format",
- vol: core.Volume{
- Name: "iscsi",
- VolumeSource: core.VolumeSource{
- ISCSI: &core.ISCSIVolumeSource{
- TargetPortal: "127.0.0.1",
- IQN: "naa.62004567BA64678D0123456789ABCDEF",
- Lun: 1,
- FSType: "ext4",
- ReadOnly: false,
- },
- },
- },
- },
- {
- name: "empty portal",
- vol: core.Volume{
- Name: "iscsi",
- VolumeSource: core.VolumeSource{
- ISCSI: &core.ISCSIVolumeSource{
- TargetPortal: "",
- IQN: "iqn.2015-02.example.com:test",
- Lun: 1,
- FSType: "ext4",
- ReadOnly: false,
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeRequired,
- field: "iscsi.targetPortal",
- }},
- },
- {
- name: "empty iqn",
- vol: core.Volume{
- Name: "iscsi",
- VolumeSource: core.VolumeSource{
- ISCSI: &core.ISCSIVolumeSource{
- TargetPortal: "127.0.0.1",
- IQN: "",
- Lun: 1,
- FSType: "ext4",
- ReadOnly: false,
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeRequired,
- field: "iscsi.iqn",
- }},
- },
- {
- name: "invalid IQN: iqn format",
- vol: core.Volume{
- Name: "iscsi",
- VolumeSource: core.VolumeSource{
- ISCSI: &core.ISCSIVolumeSource{
- TargetPortal: "127.0.0.1",
- IQN: "iqn.2015-02.example.com:test;ls;",
- Lun: 1,
- FSType: "ext4",
- ReadOnly: false,
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeInvalid,
- field: "iscsi.iqn",
- }},
- },
- {
- name: "invalid IQN: eui format",
- vol: core.Volume{
- Name: "iscsi",
- VolumeSource: core.VolumeSource{
- ISCSI: &core.ISCSIVolumeSource{
- TargetPortal: "127.0.0.1",
- IQN: "eui.0123456789ABCDEFGHIJ",
- Lun: 1,
- FSType: "ext4",
- ReadOnly: false,
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeInvalid,
- field: "iscsi.iqn",
- }},
- },
- {
- name: "invalid IQN: naa format",
- vol: core.Volume{
- Name: "iscsi",
- VolumeSource: core.VolumeSource{
- ISCSI: &core.ISCSIVolumeSource{
- TargetPortal: "127.0.0.1",
- IQN: "naa.62004567BA_4-78D.123456789ABCDEF",
- Lun: 1,
- FSType: "ext4",
- ReadOnly: false,
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeInvalid,
- field: "iscsi.iqn",
- }},
- },
- {
- name: "valid initiatorName",
- vol: core.Volume{
- Name: "iscsi",
- VolumeSource: core.VolumeSource{
- ISCSI: &core.ISCSIVolumeSource{
- TargetPortal: "127.0.0.1",
- IQN: "iqn.2015-02.example.com:test",
- Lun: 1,
- InitiatorName: &validInitiatorName,
- FSType: "ext4",
- ReadOnly: false,
- },
- },
- },
- },
- {
- name: "invalid initiatorName",
- vol: core.Volume{
- Name: "iscsi",
- VolumeSource: core.VolumeSource{
- ISCSI: &core.ISCSIVolumeSource{
- TargetPortal: "127.0.0.1",
- IQN: "iqn.2015-02.example.com:test",
- Lun: 1,
- InitiatorName: &invalidInitiatorName,
- FSType: "ext4",
- ReadOnly: false,
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeInvalid,
- field: "iscsi.initiatorname",
- }},
- },
- {
- name: "empty secret",
- vol: core.Volume{
- Name: "iscsi",
- VolumeSource: core.VolumeSource{
- ISCSI: &core.ISCSIVolumeSource{
- TargetPortal: "127.0.0.1",
- IQN: "iqn.2015-02.example.com:test",
- Lun: 1,
- FSType: "ext4",
- ReadOnly: false,
- DiscoveryCHAPAuth: true,
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeRequired,
- field: "iscsi.secretRef",
- }},
- },
- {
- name: "empty secret",
- vol: core.Volume{
- Name: "iscsi",
- VolumeSource: core.VolumeSource{
- ISCSI: &core.ISCSIVolumeSource{
- TargetPortal: "127.0.0.1",
- IQN: "iqn.2015-02.example.com:test",
- Lun: 1,
- FSType: "ext4",
- ReadOnly: false,
- SessionCHAPAuth: true,
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeRequired,
- field: "iscsi.secretRef",
- }},
- },
- // Secret
- {
- name: "valid Secret",
- vol: core.Volume{
- Name: "secret",
- VolumeSource: core.VolumeSource{
- Secret: &core.SecretVolumeSource{
- SecretName: "my-secret",
- },
- },
- },
- },
- {
- name: "valid Secret with defaultMode",
- vol: core.Volume{
- Name: "secret",
- VolumeSource: core.VolumeSource{
- Secret: &core.SecretVolumeSource{
- SecretName: "my-secret",
- DefaultMode: utilpointer.Int32Ptr(0644),
- },
- },
- },
- },
- {
- name: "valid Secret with projection and mode",
- vol: core.Volume{
- Name: "secret",
- VolumeSource: core.VolumeSource{
- Secret: &core.SecretVolumeSource{
- SecretName: "my-secret",
- Items: []core.KeyToPath{{
- Key: "key",
- Path: "filename",
- Mode: utilpointer.Int32Ptr(0644),
- }},
- },
- },
- },
- },
- {
- name: "valid Secret with subdir projection",
- vol: core.Volume{
- Name: "secret",
- VolumeSource: core.VolumeSource{
- Secret: &core.SecretVolumeSource{
- SecretName: "my-secret",
- Items: []core.KeyToPath{{
- Key: "key",
- Path: "dir/filename",
- }},
- },
- },
- },
- },
- {
- name: "secret with missing path",
- vol: core.Volume{
- Name: "secret",
- VolumeSource: core.VolumeSource{
- Secret: &core.SecretVolumeSource{
- SecretName: "s",
- Items: []core.KeyToPath{{Key: "key", Path: ""}},
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeRequired,
- field: "secret.items[0].path",
- }},
- },
- {
- name: "secret with leading ..",
- vol: core.Volume{
- Name: "secret",
- VolumeSource: core.VolumeSource{
- Secret: &core.SecretVolumeSource{
- SecretName: "s",
- Items: []core.KeyToPath{{Key: "key", Path: "../foo"}},
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeInvalid,
- field: "secret.items[0].path",
- }},
- },
- {
- name: "secret with .. inside",
- vol: core.Volume{
- Name: "secret",
- VolumeSource: core.VolumeSource{
- Secret: &core.SecretVolumeSource{
- SecretName: "s",
- Items: []core.KeyToPath{{Key: "key", Path: "foo/../bar"}},
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeInvalid,
- field: "secret.items[0].path",
- }},
- },
- {
- name: "secret with invalid positive defaultMode",
- vol: core.Volume{
- Name: "secret",
- VolumeSource: core.VolumeSource{
- Secret: &core.SecretVolumeSource{
- SecretName: "s",
- DefaultMode: utilpointer.Int32Ptr(01000),
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeInvalid,
- field: "secret.defaultMode",
- }},
- },
- {
- name: "secret with invalid negative defaultMode",
- vol: core.Volume{
- Name: "secret",
- VolumeSource: core.VolumeSource{
- Secret: &core.SecretVolumeSource{
- SecretName: "s",
- DefaultMode: utilpointer.Int32Ptr(-1),
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeInvalid,
- field: "secret.defaultMode",
- }},
- },
- // ConfigMap
- {
- name: "valid ConfigMap",
- vol: core.Volume{
- Name: "cfgmap",
- VolumeSource: core.VolumeSource{
- ConfigMap: &core.ConfigMapVolumeSource{
- LocalObjectReference: core.LocalObjectReference{
- Name: "my-cfgmap",
- },
- },
- },
- },
- },
- {
- name: "valid ConfigMap with defaultMode",
- vol: core.Volume{
- Name: "cfgmap",
- VolumeSource: core.VolumeSource{
- ConfigMap: &core.ConfigMapVolumeSource{
- LocalObjectReference: core.LocalObjectReference{
- Name: "my-cfgmap",
- },
- DefaultMode: utilpointer.Int32Ptr(0644),
- },
- },
- },
- },
- {
- name: "valid ConfigMap with projection and mode",
- vol: core.Volume{
- Name: "cfgmap",
- VolumeSource: core.VolumeSource{
- ConfigMap: &core.ConfigMapVolumeSource{
- LocalObjectReference: core.LocalObjectReference{
- Name: "my-cfgmap"},
- Items: []core.KeyToPath{{
- Key: "key",
- Path: "filename",
- Mode: utilpointer.Int32Ptr(0644),
- }},
- },
- },
- },
- },
- {
- name: "valid ConfigMap with subdir projection",
- vol: core.Volume{
- Name: "cfgmap",
- VolumeSource: core.VolumeSource{
- ConfigMap: &core.ConfigMapVolumeSource{
- LocalObjectReference: core.LocalObjectReference{
- Name: "my-cfgmap"},
- Items: []core.KeyToPath{{
- Key: "key",
- Path: "dir/filename",
- }},
- },
- },
- },
- },
- {
- name: "configmap with missing path",
- vol: core.Volume{
- Name: "cfgmap",
- VolumeSource: core.VolumeSource{
- ConfigMap: &core.ConfigMapVolumeSource{
- LocalObjectReference: core.LocalObjectReference{Name: "c"},
- Items: []core.KeyToPath{{Key: "key", Path: ""}},
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeRequired,
- field: "configMap.items[0].path",
- }},
- },
- {
- name: "configmap with leading ..",
- vol: core.Volume{
- Name: "cfgmap",
- VolumeSource: core.VolumeSource{
- ConfigMap: &core.ConfigMapVolumeSource{
- LocalObjectReference: core.LocalObjectReference{Name: "c"},
- Items: []core.KeyToPath{{Key: "key", Path: "../foo"}},
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeInvalid,
- field: "configMap.items[0].path",
- }},
- },
- {
- name: "configmap with .. inside",
- vol: core.Volume{
- Name: "cfgmap",
- VolumeSource: core.VolumeSource{
- ConfigMap: &core.ConfigMapVolumeSource{
- LocalObjectReference: core.LocalObjectReference{Name: "c"},
- Items: []core.KeyToPath{{Key: "key", Path: "foo/../bar"}},
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeInvalid,
- field: "configMap.items[0].path",
- }},
- },
- {
- name: "configmap with invalid positive defaultMode",
- vol: core.Volume{
- Name: "cfgmap",
- VolumeSource: core.VolumeSource{
- ConfigMap: &core.ConfigMapVolumeSource{
- LocalObjectReference: core.LocalObjectReference{Name: "c"},
- DefaultMode: utilpointer.Int32Ptr(01000),
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeInvalid,
- field: "configMap.defaultMode",
- }},
- },
- {
- name: "configmap with invalid negative defaultMode",
- vol: core.Volume{
- Name: "cfgmap",
- VolumeSource: core.VolumeSource{
- ConfigMap: &core.ConfigMapVolumeSource{
- LocalObjectReference: core.LocalObjectReference{Name: "c"},
- DefaultMode: utilpointer.Int32Ptr(-1),
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeInvalid,
- field: "configMap.defaultMode",
- }},
- },
- // Glusterfs
- {
- name: "valid Glusterfs",
- vol: core.Volume{
- Name: "glusterfs",
- VolumeSource: core.VolumeSource{
- Glusterfs: &core.GlusterfsVolumeSource{
- EndpointsName: "host1",
- Path: "path",
- ReadOnly: false,
- },
- },
- },
- },
- {
- name: "empty hosts",
- vol: core.Volume{
- Name: "glusterfs",
- VolumeSource: core.VolumeSource{
- Glusterfs: &core.GlusterfsVolumeSource{
- EndpointsName: "",
- Path: "path",
- ReadOnly: false,
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeRequired,
- field: "glusterfs.endpoints",
- }},
- },
- {
- name: "empty path",
- vol: core.Volume{
- Name: "glusterfs",
- VolumeSource: core.VolumeSource{
- Glusterfs: &core.GlusterfsVolumeSource{
- EndpointsName: "host",
- Path: "",
- ReadOnly: false,
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeRequired,
- field: "glusterfs.path",
- }},
- },
- // Flocker
- {
- name: "valid Flocker -- datasetUUID",
- vol: core.Volume{
- Name: "flocker",
- VolumeSource: core.VolumeSource{
- Flocker: &core.FlockerVolumeSource{
- DatasetUUID: "d846b09d-223d-43df-ab5b-d6db2206a0e4",
- },
- },
- },
- },
- {
- name: "valid Flocker -- datasetName",
- vol: core.Volume{
- Name: "flocker",
- VolumeSource: core.VolumeSource{
- Flocker: &core.FlockerVolumeSource{
- DatasetName: "datasetName",
- },
- },
- },
- },
- {
- name: "both empty",
- vol: core.Volume{
- Name: "flocker",
- VolumeSource: core.VolumeSource{
- Flocker: &core.FlockerVolumeSource{
- DatasetName: "",
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeRequired,
- field: "flocker",
- }},
- },
- {
- name: "both specified",
- vol: core.Volume{
- Name: "flocker",
- VolumeSource: core.VolumeSource{
- Flocker: &core.FlockerVolumeSource{
- DatasetName: "datasetName",
- DatasetUUID: "d846b09d-223d-43df-ab5b-d6db2206a0e4",
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeInvalid,
- field: "flocker",
- }},
- },
- {
- name: "slash in flocker datasetName",
- vol: core.Volume{
- Name: "flocker",
- VolumeSource: core.VolumeSource{
- Flocker: &core.FlockerVolumeSource{
- DatasetName: "foo/bar",
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeInvalid,
- field: "flocker.datasetName",
- detail: "must not contain '/'",
- }},
- },
- // RBD
- {
- name: "valid RBD",
- vol: core.Volume{
- Name: "rbd",
- VolumeSource: core.VolumeSource{
- RBD: &core.RBDVolumeSource{
- CephMonitors: []string{"foo"},
- RBDImage: "bar",
- FSType: "ext4",
- },
- },
- },
- },
- {
- name: "empty rbd monitors",
- vol: core.Volume{
- Name: "rbd",
- VolumeSource: core.VolumeSource{
- RBD: &core.RBDVolumeSource{
- CephMonitors: []string{},
- RBDImage: "bar",
- FSType: "ext4",
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeRequired,
- field: "rbd.monitors",
- }},
- },
- {
- name: "empty image",
- vol: core.Volume{
- Name: "rbd",
- VolumeSource: core.VolumeSource{
- RBD: &core.RBDVolumeSource{
- CephMonitors: []string{"foo"},
- RBDImage: "",
- FSType: "ext4",
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeRequired,
- field: "rbd.image",
- }},
- },
- // Cinder
- {
- name: "valid Cinder",
- vol: core.Volume{
- Name: "cinder",
- VolumeSource: core.VolumeSource{
- Cinder: &core.CinderVolumeSource{
- VolumeID: "29ea5088-4f60-4757-962e-dba678767887",
- FSType: "ext4",
- ReadOnly: false,
- },
- },
- },
- },
- // CephFS
- {
- name: "valid CephFS",
- vol: core.Volume{
- Name: "cephfs",
- VolumeSource: core.VolumeSource{
- CephFS: &core.CephFSVolumeSource{
- Monitors: []string{"foo"},
- },
- },
- },
- },
- {
- name: "empty cephfs monitors",
- vol: core.Volume{
- Name: "cephfs",
- VolumeSource: core.VolumeSource{
- CephFS: &core.CephFSVolumeSource{
- Monitors: []string{},
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeRequired,
- field: "cephfs.monitors",
- }},
- },
- // DownwardAPI
- {
- name: "valid DownwardAPI",
- vol: core.Volume{
- Name: "downwardapi",
- VolumeSource: core.VolumeSource{
- DownwardAPI: &core.DownwardAPIVolumeSource{
- Items: []core.DownwardAPIVolumeFile{
- {
- Path: "labels",
- FieldRef: &core.ObjectFieldSelector{
- APIVersion: "v1",
- FieldPath: "metadata.labels",
- },
- },
- {
- Path: "labels with subscript",
- FieldRef: &core.ObjectFieldSelector{
- APIVersion: "v1",
- FieldPath: "metadata.labels['key']",
- },
- },
- {
- Path: "labels with complex subscript",
- FieldRef: &core.ObjectFieldSelector{
- APIVersion: "v1",
- FieldPath: "metadata.labels['test.example.com/key']",
- },
- },
- {
- Path: "annotations",
- FieldRef: &core.ObjectFieldSelector{
- APIVersion: "v1",
- FieldPath: "metadata.annotations",
- },
- },
- {
- Path: "annotations with subscript",
- FieldRef: &core.ObjectFieldSelector{
- APIVersion: "v1",
- FieldPath: "metadata.annotations['key']",
- },
- },
- {
- Path: "annotations with complex subscript",
- FieldRef: &core.ObjectFieldSelector{
- APIVersion: "v1",
- FieldPath: "metadata.annotations['TEST.EXAMPLE.COM/key']",
- },
- },
- {
- Path: "namespace",
- FieldRef: &core.ObjectFieldSelector{
- APIVersion: "v1",
- FieldPath: "metadata.namespace",
- },
- },
- {
- Path: "name",
- FieldRef: &core.ObjectFieldSelector{
- APIVersion: "v1",
- FieldPath: "metadata.name",
- },
- },
- {
- Path: "path/with/subdirs",
- FieldRef: &core.ObjectFieldSelector{
- APIVersion: "v1",
- FieldPath: "metadata.labels",
- },
- },
- {
- Path: "path/./withdot",
- FieldRef: &core.ObjectFieldSelector{
- APIVersion: "v1",
- FieldPath: "metadata.labels",
- },
- },
- {
- Path: "path/with/embedded..dotdot",
- FieldRef: &core.ObjectFieldSelector{
- APIVersion: "v1",
- FieldPath: "metadata.labels",
- },
- },
- {
- Path: "path/with/leading/..dotdot",
- FieldRef: &core.ObjectFieldSelector{
- APIVersion: "v1",
- FieldPath: "metadata.labels",
- },
- },
- {
- Path: "cpu_limit",
- ResourceFieldRef: &core.ResourceFieldSelector{
- ContainerName: "test-container",
- Resource: "limits.cpu",
- },
- },
- {
- Path: "cpu_request",
- ResourceFieldRef: &core.ResourceFieldSelector{
- ContainerName: "test-container",
- Resource: "requests.cpu",
- },
- },
- {
- Path: "memory_limit",
- ResourceFieldRef: &core.ResourceFieldSelector{
- ContainerName: "test-container",
- Resource: "limits.memory",
- },
- },
- {
- Path: "memory_request",
- ResourceFieldRef: &core.ResourceFieldSelector{
- ContainerName: "test-container",
- Resource: "requests.memory",
- },
- },
- },
- },
- },
- },
- },
- {
- name: "downapi valid defaultMode",
- vol: core.Volume{
- Name: "downapi",
- VolumeSource: core.VolumeSource{
- DownwardAPI: &core.DownwardAPIVolumeSource{
- DefaultMode: utilpointer.Int32Ptr(0644),
- },
- },
- },
- },
- {
- name: "downapi valid item mode",
- vol: core.Volume{
- Name: "downapi",
- VolumeSource: core.VolumeSource{
- DownwardAPI: &core.DownwardAPIVolumeSource{
- Items: []core.DownwardAPIVolumeFile{{
- Mode: utilpointer.Int32Ptr(0644),
- Path: "path",
- FieldRef: &core.ObjectFieldSelector{
- APIVersion: "v1",
- FieldPath: "metadata.labels",
- },
- }},
- },
- },
- },
- },
- {
- name: "downapi invalid positive item mode",
- vol: core.Volume{
- Name: "downapi",
- VolumeSource: core.VolumeSource{
- DownwardAPI: &core.DownwardAPIVolumeSource{
- Items: []core.DownwardAPIVolumeFile{{
- Mode: utilpointer.Int32Ptr(01000),
- Path: "path",
- FieldRef: &core.ObjectFieldSelector{
- APIVersion: "v1",
- FieldPath: "metadata.labels",
- },
- }},
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeInvalid,
- field: "downwardAPI.mode",
- }},
- },
- {
- name: "downapi invalid negative item mode",
- vol: core.Volume{
- Name: "downapi",
- VolumeSource: core.VolumeSource{
- DownwardAPI: &core.DownwardAPIVolumeSource{
- Items: []core.DownwardAPIVolumeFile{{
- Mode: utilpointer.Int32Ptr(-1),
- Path: "path",
- FieldRef: &core.ObjectFieldSelector{
- APIVersion: "v1",
- FieldPath: "metadata.labels",
- },
- }},
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeInvalid,
- field: "downwardAPI.mode",
- }},
- },
- {
- name: "downapi empty metatada path",
- vol: core.Volume{
- Name: "downapi",
- VolumeSource: core.VolumeSource{
- DownwardAPI: &core.DownwardAPIVolumeSource{
- Items: []core.DownwardAPIVolumeFile{{
- Path: "",
- FieldRef: &core.ObjectFieldSelector{
- APIVersion: "v1",
- FieldPath: "metadata.labels",
- },
- }},
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeRequired,
- field: "downwardAPI.path",
- }},
- },
- {
- name: "downapi absolute path",
- vol: core.Volume{
- Name: "downapi",
- VolumeSource: core.VolumeSource{
- DownwardAPI: &core.DownwardAPIVolumeSource{
- Items: []core.DownwardAPIVolumeFile{{
- Path: "/absolutepath",
- FieldRef: &core.ObjectFieldSelector{
- APIVersion: "v1",
- FieldPath: "metadata.labels",
- },
- }},
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeInvalid,
- field: "downwardAPI.path",
- }},
- },
- {
- name: "downapi dot dot path",
- vol: core.Volume{
- Name: "downapi",
- VolumeSource: core.VolumeSource{
- DownwardAPI: &core.DownwardAPIVolumeSource{
- Items: []core.DownwardAPIVolumeFile{{
- Path: "../../passwd",
- FieldRef: &core.ObjectFieldSelector{
- APIVersion: "v1",
- FieldPath: "metadata.labels",
- },
- }},
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeInvalid,
- field: "downwardAPI.path",
- detail: `must not contain '..'`,
- }},
- },
- {
- name: "downapi dot dot file name",
- vol: core.Volume{
- Name: "downapi",
- VolumeSource: core.VolumeSource{
- DownwardAPI: &core.DownwardAPIVolumeSource{
- Items: []core.DownwardAPIVolumeFile{{
- Path: "..badFileName",
- FieldRef: &core.ObjectFieldSelector{
- APIVersion: "v1",
- FieldPath: "metadata.labels",
- },
- }},
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeInvalid,
- field: "downwardAPI.path",
- detail: `must not start with '..'`,
- }},
- },
- {
- name: "downapi dot dot first level dirent",
- vol: core.Volume{
- Name: "downapi",
- VolumeSource: core.VolumeSource{
- DownwardAPI: &core.DownwardAPIVolumeSource{
- Items: []core.DownwardAPIVolumeFile{{
- Path: "..badDirName/goodFileName",
- FieldRef: &core.ObjectFieldSelector{
- APIVersion: "v1",
- FieldPath: "metadata.labels",
- },
- }},
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeInvalid,
- field: "downwardAPI.path",
- detail: `must not start with '..'`,
- }},
- },
- {
- name: "downapi fieldRef and ResourceFieldRef together",
- vol: core.Volume{
- Name: "downapi",
- VolumeSource: core.VolumeSource{
- DownwardAPI: &core.DownwardAPIVolumeSource{
- Items: []core.DownwardAPIVolumeFile{{
- Path: "test",
- FieldRef: &core.ObjectFieldSelector{
- APIVersion: "v1",
- FieldPath: "metadata.labels",
- },
- ResourceFieldRef: &core.ResourceFieldSelector{
- ContainerName: "test-container",
- Resource: "requests.memory",
- },
- }},
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeInvalid,
- field: "downwardAPI",
- detail: "fieldRef and resourceFieldRef can not be specified simultaneously",
- }},
- },
- {
- name: "downapi invalid positive defaultMode",
- vol: core.Volume{
- Name: "downapi",
- VolumeSource: core.VolumeSource{
- DownwardAPI: &core.DownwardAPIVolumeSource{
- DefaultMode: utilpointer.Int32Ptr(01000),
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeInvalid,
- field: "downwardAPI.defaultMode",
- }},
- },
- {
- name: "downapi invalid negative defaultMode",
- vol: core.Volume{
- Name: "downapi",
- VolumeSource: core.VolumeSource{
- DownwardAPI: &core.DownwardAPIVolumeSource{
- DefaultMode: utilpointer.Int32Ptr(-1),
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeInvalid,
- field: "downwardAPI.defaultMode",
- }},
- },
- // FC
- {
- name: "FC valid targetWWNs and lun",
- vol: core.Volume{
- Name: "fc",
- VolumeSource: core.VolumeSource{
- FC: &core.FCVolumeSource{
- TargetWWNs: []string{"some_wwn"},
- Lun: utilpointer.Int32Ptr(1),
- FSType: "ext4",
- ReadOnly: false,
- },
- },
- },
- },
- {
- name: "FC valid wwids",
- vol: core.Volume{
- Name: "fc",
- VolumeSource: core.VolumeSource{
- FC: &core.FCVolumeSource{
- WWIDs: []string{"some_wwid"},
- FSType: "ext4",
- ReadOnly: false,
- },
- },
- },
- },
- {
- name: "FC empty targetWWNs and wwids",
- vol: core.Volume{
- Name: "fc",
- VolumeSource: core.VolumeSource{
- FC: &core.FCVolumeSource{
- TargetWWNs: []string{},
- Lun: utilpointer.Int32Ptr(1),
- WWIDs: []string{},
- FSType: "ext4",
- ReadOnly: false,
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeRequired,
- field: "fc.targetWWNs",
- detail: "must specify either targetWWNs or wwids",
- }},
- },
- {
- name: "FC invalid: both targetWWNs and wwids simultaneously",
- vol: core.Volume{
- Name: "fc",
- VolumeSource: core.VolumeSource{
- FC: &core.FCVolumeSource{
- TargetWWNs: []string{"some_wwn"},
- Lun: utilpointer.Int32Ptr(1),
- WWIDs: []string{"some_wwid"},
- FSType: "ext4",
- ReadOnly: false,
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeInvalid,
- field: "fc.targetWWNs",
- detail: "targetWWNs and wwids can not be specified simultaneously",
- }},
- },
- {
- name: "FC valid targetWWNs and empty lun",
- vol: core.Volume{
- Name: "fc",
- VolumeSource: core.VolumeSource{
- FC: &core.FCVolumeSource{
- TargetWWNs: []string{"wwn"},
- Lun: nil,
- FSType: "ext4",
- ReadOnly: false,
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeRequired,
- field: "fc.lun",
- detail: "lun is required if targetWWNs is specified",
- }},
- },
- {
- name: "FC valid targetWWNs and invalid lun",
- vol: core.Volume{
- Name: "fc",
- VolumeSource: core.VolumeSource{
- FC: &core.FCVolumeSource{
- TargetWWNs: []string{"wwn"},
- Lun: utilpointer.Int32Ptr(256),
- FSType: "ext4",
- ReadOnly: false,
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeInvalid,
- field: "fc.lun",
- detail: validation.InclusiveRangeError(0, 255),
- }},
- },
- // FlexVolume
- {
- name: "valid FlexVolume",
- vol: core.Volume{
- Name: "flex-volume",
- VolumeSource: core.VolumeSource{
- FlexVolume: &core.FlexVolumeSource{
- Driver: "kubernetes.io/blue",
- FSType: "ext4",
- },
- },
- },
- },
- // AzureFile
- {
- name: "valid AzureFile",
- vol: core.Volume{
- Name: "azure-file",
- VolumeSource: core.VolumeSource{
- AzureFile: &core.AzureFileVolumeSource{
- SecretName: "key",
- ShareName: "share",
- ReadOnly: false,
- },
- },
- },
- },
- {
- name: "AzureFile empty secret",
- vol: core.Volume{
- Name: "azure-file",
- VolumeSource: core.VolumeSource{
- AzureFile: &core.AzureFileVolumeSource{
- SecretName: "",
- ShareName: "share",
- ReadOnly: false,
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeRequired,
- field: "azureFile.secretName",
- }},
- },
- {
- name: "AzureFile empty share",
- vol: core.Volume{
- Name: "azure-file",
- VolumeSource: core.VolumeSource{
- AzureFile: &core.AzureFileVolumeSource{
- SecretName: "name",
- ShareName: "",
- ReadOnly: false,
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeRequired,
- field: "azureFile.shareName",
- }},
- },
- // Quobyte
- {
- name: "valid Quobyte",
- vol: core.Volume{
- Name: "quobyte",
- VolumeSource: core.VolumeSource{
- Quobyte: &core.QuobyteVolumeSource{
- Registry: "registry:7861",
- Volume: "volume",
- ReadOnly: false,
- User: "root",
- Group: "root",
- Tenant: "ThisIsSomeTenantUUID",
- },
- },
- },
- },
- {
- name: "empty registry quobyte",
- vol: core.Volume{
- Name: "quobyte",
- VolumeSource: core.VolumeSource{
- Quobyte: &core.QuobyteVolumeSource{
- Volume: "/test",
- Tenant: "ThisIsSomeTenantUUID",
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeRequired,
- field: "quobyte.registry",
- }},
- },
- {
- name: "wrong format registry quobyte",
- vol: core.Volume{
- Name: "quobyte",
- VolumeSource: core.VolumeSource{
- Quobyte: &core.QuobyteVolumeSource{
- Registry: "registry7861",
- Volume: "/test",
- Tenant: "ThisIsSomeTenantUUID",
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeInvalid,
- field: "quobyte.registry",
- }},
- },
- {
- name: "wrong format multiple registries quobyte",
- vol: core.Volume{
- Name: "quobyte",
- VolumeSource: core.VolumeSource{
- Quobyte: &core.QuobyteVolumeSource{
- Registry: "registry:7861,reg2",
- Volume: "/test",
- Tenant: "ThisIsSomeTenantUUID",
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeInvalid,
- field: "quobyte.registry",
- }},
- },
- {
- name: "empty volume quobyte",
- vol: core.Volume{
- Name: "quobyte",
- VolumeSource: core.VolumeSource{
- Quobyte: &core.QuobyteVolumeSource{
- Registry: "registry:7861",
- Tenant: "ThisIsSomeTenantUUID",
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeRequired,
- field: "quobyte.volume",
- }},
- },
- {
- name: "empty tenant quobyte",
- vol: core.Volume{
- Name: "quobyte",
- VolumeSource: core.VolumeSource{
- Quobyte: &core.QuobyteVolumeSource{
- Registry: "registry:7861",
- Volume: "/test",
- Tenant: "",
- },
- },
- },
- },
- {
- name: "too long tenant quobyte",
- vol: core.Volume{
- Name: "quobyte",
- VolumeSource: core.VolumeSource{
- Quobyte: &core.QuobyteVolumeSource{
- Registry: "registry:7861",
- Volume: "/test",
- Tenant: "this is too long to be a valid uuid so this test has to fail on the maximum length validation of the tenant.",
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeRequired,
- field: "quobyte.tenant",
- }},
- },
- // AzureDisk
- {
- name: "valid AzureDisk",
- vol: core.Volume{
- Name: "azure-disk",
- VolumeSource: core.VolumeSource{
- AzureDisk: &core.AzureDiskVolumeSource{
- DiskName: "foo",
- DataDiskURI: "https://blob/vhds/bar.vhd",
- },
- },
- },
- },
- {
- name: "AzureDisk empty disk name",
- vol: core.Volume{
- Name: "azure-disk",
- VolumeSource: core.VolumeSource{
- AzureDisk: &core.AzureDiskVolumeSource{
- DiskName: "",
- DataDiskURI: "https://blob/vhds/bar.vhd",
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeRequired,
- field: "azureDisk.diskName",
- }},
- },
- {
- name: "AzureDisk empty disk uri",
- vol: core.Volume{
- Name: "azure-disk",
- VolumeSource: core.VolumeSource{
- AzureDisk: &core.AzureDiskVolumeSource{
- DiskName: "foo",
- DataDiskURI: "",
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeRequired,
- field: "azureDisk.diskURI",
- }},
- },
- // ScaleIO
- {
- name: "valid scaleio volume",
- vol: core.Volume{
- Name: "scaleio-volume",
- VolumeSource: core.VolumeSource{
- ScaleIO: &core.ScaleIOVolumeSource{
- Gateway: "http://abcd/efg",
- System: "test-system",
- VolumeName: "test-vol-1",
- },
- },
- },
- },
- {
- name: "ScaleIO with empty name",
- vol: core.Volume{
- Name: "scaleio-volume",
- VolumeSource: core.VolumeSource{
- ScaleIO: &core.ScaleIOVolumeSource{
- Gateway: "http://abcd/efg",
- System: "test-system",
- VolumeName: "",
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeRequired,
- field: "scaleIO.volumeName",
- }},
- },
- {
- name: "ScaleIO with empty gateway",
- vol: core.Volume{
- Name: "scaleio-volume",
- VolumeSource: core.VolumeSource{
- ScaleIO: &core.ScaleIOVolumeSource{
- Gateway: "",
- System: "test-system",
- VolumeName: "test-vol-1",
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeRequired,
- field: "scaleIO.gateway",
- }},
- },
- {
- name: "ScaleIO with empty system",
- vol: core.Volume{
- Name: "scaleio-volume",
- VolumeSource: core.VolumeSource{
- ScaleIO: &core.ScaleIOVolumeSource{
- Gateway: "http://agc/efg/gateway",
- System: "",
- VolumeName: "test-vol-1",
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeRequired,
- field: "scaleIO.system",
- }},
- },
- // ProjectedVolumeSource
- {
- name: "ProjectedVolumeSource more than one projection in a source",
- vol: core.Volume{
- Name: "projected-volume",
- VolumeSource: core.VolumeSource{
- Projected: &core.ProjectedVolumeSource{
- Sources: []core.VolumeProjection{
- {
- Secret: &core.SecretProjection{
- LocalObjectReference: core.LocalObjectReference{
- Name: "foo",
- },
- },
- },
- {
- Secret: &core.SecretProjection{
- LocalObjectReference: core.LocalObjectReference{
- Name: "foo",
- },
- },
- DownwardAPI: &core.DownwardAPIProjection{},
- },
- },
- },
- },
- },
- errs: []verr{{
- etype: field.ErrorTypeForbidden,
- field: "projected.sources[1]",
- }},
- },
- {
- name: "ProjectedVolumeSource more than one projection in a source",
- vol: core.Volume{
- Name: "projected-volume",
- VolumeSource: core.VolumeSource{
- Projected: &core.ProjectedVolumeSource{
- Sources: []core.VolumeProjection{
- {
- Secret: &core.SecretProjection{},
- },
- {
- Secret: &core.SecretProjection{},
- DownwardAPI: &core.DownwardAPIProjection{},
- },
- },
- },
- },
- },
- errs: []verr{
- {
- etype: field.ErrorTypeRequired,
- field: "projected.sources[0].secret.name",
- },
- {
- etype: field.ErrorTypeRequired,
- field: "projected.sources[1].secret.name",
- },
- {
- etype: field.ErrorTypeForbidden,
- field: "projected.sources[1]",
- },
- },
- },
- }
- for _, tc := range testCases {
- t.Run(tc.name, func(t *testing.T) {
- names, errs := ValidateVolumes([]core.Volume{tc.vol}, field.NewPath("field"))
- if len(errs) != len(tc.errs) {
- t.Fatalf("unexpected error(s): got %d, want %d: %v", len(tc.errs), len(errs), errs)
- }
- if len(errs) == 0 && (len(names) > 1 || !IsMatchedVolume(tc.vol.Name, names)) {
- t.Errorf("wrong names result: %v", names)
- }
- for i, err := range errs {
- expErr := tc.errs[i]
- if err.Type != expErr.etype {
- t.Errorf("unexpected error type: got %v, want %v", expErr.etype, err.Type)
- }
- if !strings.HasSuffix(err.Field, "."+expErr.field) {
- t.Errorf("unexpected error field: got %v, want %v", expErr.field, err.Field)
- }
- if !strings.Contains(err.Detail, expErr.detail) {
- t.Errorf("unexpected error detail: got %v, want %v", expErr.detail, err.Detail)
- }
- }
- })
- }
- dupsCase := []core.Volume{
- {Name: "abc", VolumeSource: core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{}}},
- {Name: "abc", VolumeSource: core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{}}},
- }
- _, errs := ValidateVolumes(dupsCase, field.NewPath("field"))
- if len(errs) == 0 {
- t.Errorf("expected error")
- } else if len(errs) != 1 {
- t.Errorf("expected 1 error, got %d: %v", len(errs), errs)
- } else if errs[0].Type != field.ErrorTypeDuplicate {
- t.Errorf("expected error type %v, got %v", field.ErrorTypeDuplicate, errs[0].Type)
- }
- // Validate HugePages medium type for EmptyDir
- hugePagesCase := core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{Medium: core.StorageMediumHugePages}}
- // Enable HugePages
- if errs := validateVolumeSource(&hugePagesCase, field.NewPath("field").Index(0), "working"); len(errs) != 0 {
- t.Errorf("Unexpected error when HugePages feature is enabled.")
- }
- }
- func TestHugePagesIsolation(t *testing.T) {
- successCases := []core.Pod{
- { // Basic fields.
- ObjectMeta: metav1.ObjectMeta{Name: "123", Namespace: "ns"},
- Spec: core.PodSpec{
- Containers: []core.Container{
- {
- Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File",
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName(core.ResourceCPU): resource.MustParse("10"),
- core.ResourceName(core.ResourceMemory): resource.MustParse("10G"),
- core.ResourceName("hugepages-2Mi"): resource.MustParse("1Gi"),
- },
- Limits: core.ResourceList{
- core.ResourceName(core.ResourceCPU): resource.MustParse("10"),
- core.ResourceName(core.ResourceMemory): resource.MustParse("10G"),
- core.ResourceName("hugepages-2Mi"): resource.MustParse("1Gi"),
- },
- },
- },
- },
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- },
- },
- }
- failureCases := []core.Pod{
- { // Basic fields.
- ObjectMeta: metav1.ObjectMeta{Name: "hugepages-requireCpuOrMemory", Namespace: "ns"},
- Spec: core.PodSpec{
- Containers: []core.Container{
- {
- Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File",
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName("hugepages-2Mi"): resource.MustParse("1Gi"),
- },
- Limits: core.ResourceList{
- core.ResourceName("hugepages-2Mi"): resource.MustParse("1Gi"),
- },
- },
- },
- },
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- },
- },
- { // Basic fields.
- ObjectMeta: metav1.ObjectMeta{Name: "hugepages-shared", Namespace: "ns"},
- Spec: core.PodSpec{
- Containers: []core.Container{
- {
- Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File",
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName(core.ResourceCPU): resource.MustParse("10"),
- core.ResourceName(core.ResourceMemory): resource.MustParse("10G"),
- core.ResourceName("hugepages-2Mi"): resource.MustParse("1Gi"),
- },
- Limits: core.ResourceList{
- core.ResourceName(core.ResourceCPU): resource.MustParse("10"),
- core.ResourceName(core.ResourceMemory): resource.MustParse("10G"),
- core.ResourceName("hugepages-2Mi"): resource.MustParse("2Gi"),
- },
- },
- },
- },
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- },
- },
- { // Basic fields.
- ObjectMeta: metav1.ObjectMeta{Name: "hugepages-multiple", Namespace: "ns"},
- Spec: core.PodSpec{
- Containers: []core.Container{
- {
- Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File",
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName(core.ResourceCPU): resource.MustParse("10"),
- core.ResourceName(core.ResourceMemory): resource.MustParse("10G"),
- core.ResourceName("hugepages-1Gi"): resource.MustParse("2Gi"),
- },
- Limits: core.ResourceList{
- core.ResourceName(core.ResourceCPU): resource.MustParse("10"),
- core.ResourceName(core.ResourceMemory): resource.MustParse("10G"),
- core.ResourceName("hugepages-2Mi"): resource.MustParse("1Gi"),
- core.ResourceName("hugepages-1Gi"): resource.MustParse("2Gi"),
- },
- },
- },
- },
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- },
- },
- }
- for i := range successCases {
- pod := &successCases[i]
- if errs := ValidatePod(pod); len(errs) != 0 {
- t.Errorf("Unexpected error for case[%d], err: %v", i, errs)
- }
- }
- for i := range failureCases {
- pod := &failureCases[i]
- if errs := ValidatePod(pod); len(errs) == 0 {
- t.Errorf("Expected error for case[%d], pod: %v", i, pod.Name)
- }
- }
- }
- func TestPVCVolumeMode(t *testing.T) {
- // Enable feature BlockVolume for PVC
- defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.BlockVolume, true)()
- block := core.PersistentVolumeBlock
- file := core.PersistentVolumeFilesystem
- fake := core.PersistentVolumeMode("fake")
- empty := core.PersistentVolumeMode("")
- // Success Cases
- successCasesPVC := map[string]*core.PersistentVolumeClaim{
- "valid block value": createTestVolModePVC(&block),
- "valid filesystem value": createTestVolModePVC(&file),
- "valid nil value": createTestVolModePVC(nil),
- }
- for k, v := range successCasesPVC {
- if errs := ValidatePersistentVolumeClaim(v); len(errs) != 0 {
- t.Errorf("expected success for %s", k)
- }
- }
- // Error Cases
- errorCasesPVC := map[string]*core.PersistentVolumeClaim{
- "invalid value": createTestVolModePVC(&fake),
- "empty value": createTestVolModePVC(&empty),
- }
- for k, v := range errorCasesPVC {
- if errs := ValidatePersistentVolumeClaim(v); len(errs) == 0 {
- t.Errorf("expected failure for %s", k)
- }
- }
- }
- func TestPVVolumeMode(t *testing.T) {
- // Enable feature BlockVolume for PVC
- defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.BlockVolume, true)()
- block := core.PersistentVolumeBlock
- file := core.PersistentVolumeFilesystem
- fake := core.PersistentVolumeMode("fake")
- empty := core.PersistentVolumeMode("")
- // Success Cases
- successCasesPV := map[string]*core.PersistentVolume{
- "valid block value": createTestVolModePV(&block),
- "valid filesystem value": createTestVolModePV(&file),
- "valid nil value": createTestVolModePV(nil),
- }
- for k, v := range successCasesPV {
- if errs := ValidatePersistentVolume(v); len(errs) != 0 {
- t.Errorf("expected success for %s", k)
- }
- }
- // Error Cases
- errorCasesPV := map[string]*core.PersistentVolume{
- "invalid value": createTestVolModePV(&fake),
- "empty value": createTestVolModePV(&empty),
- }
- for k, v := range errorCasesPV {
- if errs := ValidatePersistentVolume(v); len(errs) == 0 {
- t.Errorf("expected failure for %s", k)
- }
- }
- }
- func createTestVolModePVC(vmode *core.PersistentVolumeMode) *core.PersistentVolumeClaim {
- validName := "valid-storage-class"
- pvc := core.PersistentVolumeClaim{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- Namespace: "default",
- },
- Spec: core.PersistentVolumeClaimSpec{
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- },
- AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce},
- StorageClassName: &validName,
- VolumeMode: vmode,
- },
- }
- return &pvc
- }
- func createTestVolModePV(vmode *core.PersistentVolumeMode) *core.PersistentVolume {
- // PersistentVolume with VolumeMode set (valid and invalid)
- pv := core.PersistentVolume{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- Namespace: "",
- },
- Spec: core.PersistentVolumeSpec{
- Capacity: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce},
- PersistentVolumeSource: core.PersistentVolumeSource{
- HostPath: &core.HostPathVolumeSource{
- Path: "/foo",
- Type: newHostPathType(string(core.HostPathDirectory)),
- },
- },
- StorageClassName: "test-storage-class",
- VolumeMode: vmode,
- },
- }
- return &pv
- }
- func createTestPV() *core.PersistentVolume {
- // PersistentVolume with VolumeMode set (valid and invalid)
- pv := core.PersistentVolume{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- Namespace: "",
- },
- Spec: core.PersistentVolumeSpec{
- Capacity: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- AccessModes: []core.PersistentVolumeAccessMode{core.ReadWriteOnce},
- PersistentVolumeSource: core.PersistentVolumeSource{
- HostPath: &core.HostPathVolumeSource{
- Path: "/foo",
- Type: newHostPathType(string(core.HostPathDirectory)),
- },
- },
- StorageClassName: "test-storage-class",
- },
- }
- return &pv
- }
- func TestAlphaLocalStorageCapacityIsolation(t *testing.T) {
- testCases := []core.VolumeSource{
- {EmptyDir: &core.EmptyDirVolumeSource{SizeLimit: resource.NewQuantity(int64(5), resource.BinarySI)}},
- }
- for _, tc := range testCases {
- if errs := validateVolumeSource(&tc, field.NewPath("spec"), "tmpvol"); len(errs) != 0 {
- t.Errorf("expected success: %v", errs)
- }
- }
- containerLimitCase := core.ResourceRequirements{
- Limits: core.ResourceList{
- core.ResourceEphemeralStorage: *resource.NewMilliQuantity(
- int64(40000),
- resource.BinarySI),
- },
- }
- if errs := ValidateResourceRequirements(&containerLimitCase, field.NewPath("resources")); len(errs) != 0 {
- t.Errorf("expected success: %v", errs)
- }
- }
- func TestValidateResourceQuotaWithAlphaLocalStorageCapacityIsolation(t *testing.T) {
- spec := core.ResourceQuotaSpec{
- Hard: core.ResourceList{
- core.ResourceCPU: resource.MustParse("100"),
- core.ResourceMemory: resource.MustParse("10000"),
- core.ResourceRequestsCPU: resource.MustParse("100"),
- core.ResourceRequestsMemory: resource.MustParse("10000"),
- core.ResourceLimitsCPU: resource.MustParse("100"),
- core.ResourceLimitsMemory: resource.MustParse("10000"),
- core.ResourcePods: resource.MustParse("10"),
- core.ResourceServices: resource.MustParse("0"),
- core.ResourceReplicationControllers: resource.MustParse("10"),
- core.ResourceQuotas: resource.MustParse("10"),
- core.ResourceConfigMaps: resource.MustParse("10"),
- core.ResourceSecrets: resource.MustParse("10"),
- core.ResourceEphemeralStorage: resource.MustParse("10000"),
- core.ResourceRequestsEphemeralStorage: resource.MustParse("10000"),
- core.ResourceLimitsEphemeralStorage: resource.MustParse("10000"),
- },
- }
- resourceQuota := &core.ResourceQuota{
- ObjectMeta: metav1.ObjectMeta{
- Name: "abc",
- Namespace: "foo",
- },
- Spec: spec,
- }
- if errs := ValidateResourceQuota(resourceQuota); len(errs) != 0 {
- t.Errorf("expected success: %v", errs)
- }
- }
- func TestValidatePorts(t *testing.T) {
- defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.SCTPSupport, true)()
- successCase := []core.ContainerPort{
- {Name: "abc", ContainerPort: 80, HostPort: 80, Protocol: "TCP"},
- {Name: "easy", ContainerPort: 82, Protocol: "TCP"},
- {Name: "as", ContainerPort: 83, Protocol: "UDP"},
- {Name: "do-re-me", ContainerPort: 84, Protocol: "UDP"},
- {ContainerPort: 85, Protocol: "TCP"},
- }
- if errs := validateContainerPorts(successCase, field.NewPath("field")); len(errs) != 0 {
- t.Errorf("expected success: %v", errs)
- }
- nonCanonicalCase := []core.ContainerPort{
- {ContainerPort: 80, Protocol: "TCP"},
- }
- if errs := validateContainerPorts(nonCanonicalCase, field.NewPath("field")); len(errs) != 0 {
- t.Errorf("expected success: %v", errs)
- }
- errorCases := map[string]struct {
- P []core.ContainerPort
- T field.ErrorType
- F string
- D string
- }{
- "name > 15 characters": {
- []core.ContainerPort{{Name: strings.Repeat("a", 16), ContainerPort: 80, Protocol: "TCP"}},
- field.ErrorTypeInvalid,
- "name", "15",
- },
- "name contains invalid characters": {
- []core.ContainerPort{{Name: "a.b.c", ContainerPort: 80, Protocol: "TCP"}},
- field.ErrorTypeInvalid,
- "name", "alpha-numeric",
- },
- "name is a number": {
- []core.ContainerPort{{Name: "80", ContainerPort: 80, Protocol: "TCP"}},
- field.ErrorTypeInvalid,
- "name", "at least one letter",
- },
- "name not unique": {
- []core.ContainerPort{
- {Name: "abc", ContainerPort: 80, Protocol: "TCP"},
- {Name: "abc", ContainerPort: 81, Protocol: "TCP"},
- },
- field.ErrorTypeDuplicate,
- "[1].name", "",
- },
- "zero container port": {
- []core.ContainerPort{{ContainerPort: 0, Protocol: "TCP"}},
- field.ErrorTypeRequired,
- "containerPort", "",
- },
- "invalid container port": {
- []core.ContainerPort{{ContainerPort: 65536, Protocol: "TCP"}},
- field.ErrorTypeInvalid,
- "containerPort", "between",
- },
- "invalid host port": {
- []core.ContainerPort{{ContainerPort: 80, HostPort: 65536, Protocol: "TCP"}},
- field.ErrorTypeInvalid,
- "hostPort", "between",
- },
- "invalid protocol case": {
- []core.ContainerPort{{ContainerPort: 80, Protocol: "tcp"}},
- field.ErrorTypeNotSupported,
- "protocol", `supported values: "SCTP", "TCP", "UDP"`,
- },
- "invalid protocol": {
- []core.ContainerPort{{ContainerPort: 80, Protocol: "ICMP"}},
- field.ErrorTypeNotSupported,
- "protocol", `supported values: "SCTP", "TCP", "UDP"`,
- },
- "protocol required": {
- []core.ContainerPort{{Name: "abc", ContainerPort: 80}},
- field.ErrorTypeRequired,
- "protocol", "",
- },
- }
- for k, v := range errorCases {
- errs := validateContainerPorts(v.P, field.NewPath("field"))
- if len(errs) == 0 {
- t.Errorf("expected failure for %s", k)
- }
- for i := range errs {
- if errs[i].Type != v.T {
- t.Errorf("%s: expected error to have type %q: %q", k, v.T, errs[i].Type)
- }
- if !strings.Contains(errs[i].Field, v.F) {
- t.Errorf("%s: expected error field %q: %q", k, v.F, errs[i].Field)
- }
- if !strings.Contains(errs[i].Detail, v.D) {
- t.Errorf("%s: expected error detail %q, got %q", k, v.D, errs[i].Detail)
- }
- }
- }
- }
- func TestLocalStorageEnvWithFeatureGate(t *testing.T) {
- testCases := []core.EnvVar{
- {
- Name: "ephemeral-storage-limits",
- ValueFrom: &core.EnvVarSource{
- ResourceFieldRef: &core.ResourceFieldSelector{
- ContainerName: "test-container",
- Resource: "limits.ephemeral-storage",
- },
- },
- },
- {
- Name: "ephemeral-storage-requests",
- ValueFrom: &core.EnvVarSource{
- ResourceFieldRef: &core.ResourceFieldSelector{
- ContainerName: "test-container",
- Resource: "requests.ephemeral-storage",
- },
- },
- },
- }
- for _, testCase := range testCases {
- if errs := validateEnvVarValueFrom(testCase, field.NewPath("field")); len(errs) != 0 {
- t.Errorf("expected success, got: %v", errs)
- }
- }
- }
- func TestValidateEnv(t *testing.T) {
- successCase := []core.EnvVar{
- {Name: "abc", Value: "value"},
- {Name: "ABC", Value: "value"},
- {Name: "AbC_123", Value: "value"},
- {Name: "abc", Value: ""},
- {Name: "a.b.c", Value: "value"},
- {Name: "a-b-c", Value: "value"},
- {
- Name: "abc",
- ValueFrom: &core.EnvVarSource{
- FieldRef: &core.ObjectFieldSelector{
- APIVersion: "v1",
- FieldPath: "metadata.annotations['key']",
- },
- },
- },
- {
- Name: "abc",
- ValueFrom: &core.EnvVarSource{
- FieldRef: &core.ObjectFieldSelector{
- APIVersion: "v1",
- FieldPath: "metadata.labels['key']",
- },
- },
- },
- {
- Name: "abc",
- ValueFrom: &core.EnvVarSource{
- FieldRef: &core.ObjectFieldSelector{
- APIVersion: "v1",
- FieldPath: "metadata.name",
- },
- },
- },
- {
- Name: "abc",
- ValueFrom: &core.EnvVarSource{
- FieldRef: &core.ObjectFieldSelector{
- APIVersion: "v1",
- FieldPath: "metadata.namespace",
- },
- },
- },
- {
- Name: "abc",
- ValueFrom: &core.EnvVarSource{
- FieldRef: &core.ObjectFieldSelector{
- APIVersion: "v1",
- FieldPath: "metadata.uid",
- },
- },
- },
- {
- Name: "abc",
- ValueFrom: &core.EnvVarSource{
- FieldRef: &core.ObjectFieldSelector{
- APIVersion: "v1",
- FieldPath: "spec.nodeName",
- },
- },
- },
- {
- Name: "abc",
- ValueFrom: &core.EnvVarSource{
- FieldRef: &core.ObjectFieldSelector{
- APIVersion: "v1",
- FieldPath: "spec.serviceAccountName",
- },
- },
- },
- {
- Name: "abc",
- ValueFrom: &core.EnvVarSource{
- FieldRef: &core.ObjectFieldSelector{
- APIVersion: "v1",
- FieldPath: "status.hostIP",
- },
- },
- },
- {
- Name: "abc",
- ValueFrom: &core.EnvVarSource{
- FieldRef: &core.ObjectFieldSelector{
- APIVersion: "v1",
- FieldPath: "status.podIP",
- },
- },
- },
- {
- Name: "secret_value",
- ValueFrom: &core.EnvVarSource{
- SecretKeyRef: &core.SecretKeySelector{
- LocalObjectReference: core.LocalObjectReference{
- Name: "some-secret",
- },
- Key: "secret-key",
- },
- },
- },
- {
- Name: "ENV_VAR_1",
- ValueFrom: &core.EnvVarSource{
- ConfigMapKeyRef: &core.ConfigMapKeySelector{
- LocalObjectReference: core.LocalObjectReference{
- Name: "some-config-map",
- },
- Key: "some-key",
- },
- },
- },
- }
- if errs := ValidateEnv(successCase, field.NewPath("field")); len(errs) != 0 {
- t.Errorf("expected success, got: %v", errs)
- }
- errorCases := []struct {
- name string
- envs []core.EnvVar
- expectedError string
- }{
- {
- name: "zero-length name",
- envs: []core.EnvVar{{Name: ""}},
- expectedError: "[0].name: Required value",
- },
- {
- name: "illegal character",
- envs: []core.EnvVar{{Name: "a!b"}},
- expectedError: `[0].name: Invalid value: "a!b": ` + envVarNameErrMsg,
- },
- {
- name: "dot only",
- envs: []core.EnvVar{{Name: "."}},
- expectedError: `[0].name: Invalid value: ".": must not be`,
- },
- {
- name: "double dots only",
- envs: []core.EnvVar{{Name: ".."}},
- expectedError: `[0].name: Invalid value: "..": must not be`,
- },
- {
- name: "leading double dots",
- envs: []core.EnvVar{{Name: "..abc"}},
- expectedError: `[0].name: Invalid value: "..abc": must not start with`,
- },
- {
- name: "value and valueFrom specified",
- envs: []core.EnvVar{{
- Name: "abc",
- Value: "foo",
- ValueFrom: &core.EnvVarSource{
- FieldRef: &core.ObjectFieldSelector{
- APIVersion: "v1",
- FieldPath: "metadata.name",
- },
- },
- }},
- expectedError: "[0].valueFrom: Invalid value: \"\": may not be specified when `value` is not empty",
- },
- {
- name: "valueFrom without a source",
- envs: []core.EnvVar{{
- Name: "abc",
- ValueFrom: &core.EnvVarSource{},
- }},
- expectedError: "[0].valueFrom: Invalid value: \"\": must specify one of: `fieldRef`, `resourceFieldRef`, `configMapKeyRef` or `secretKeyRef`",
- },
- {
- name: "valueFrom.fieldRef and valueFrom.secretKeyRef specified",
- envs: []core.EnvVar{{
- Name: "abc",
- ValueFrom: &core.EnvVarSource{
- FieldRef: &core.ObjectFieldSelector{
- APIVersion: "v1",
- FieldPath: "metadata.name",
- },
- SecretKeyRef: &core.SecretKeySelector{
- LocalObjectReference: core.LocalObjectReference{
- Name: "a-secret",
- },
- Key: "a-key",
- },
- },
- }},
- expectedError: "[0].valueFrom: Invalid value: \"\": may not have more than one field specified at a time",
- },
- {
- name: "valueFrom.fieldRef and valueFrom.configMapKeyRef set",
- envs: []core.EnvVar{{
- Name: "some_var_name",
- ValueFrom: &core.EnvVarSource{
- FieldRef: &core.ObjectFieldSelector{
- APIVersion: "v1",
- FieldPath: "metadata.name",
- },
- ConfigMapKeyRef: &core.ConfigMapKeySelector{
- LocalObjectReference: core.LocalObjectReference{
- Name: "some-config-map",
- },
- Key: "some-key",
- },
- },
- }},
- expectedError: `[0].valueFrom: Invalid value: "": may not have more than one field specified at a time`,
- },
- {
- name: "valueFrom.fieldRef and valueFrom.secretKeyRef specified",
- envs: []core.EnvVar{{
- Name: "abc",
- ValueFrom: &core.EnvVarSource{
- FieldRef: &core.ObjectFieldSelector{
- APIVersion: "v1",
- FieldPath: "metadata.name",
- },
- SecretKeyRef: &core.SecretKeySelector{
- LocalObjectReference: core.LocalObjectReference{
- Name: "a-secret",
- },
- Key: "a-key",
- },
- ConfigMapKeyRef: &core.ConfigMapKeySelector{
- LocalObjectReference: core.LocalObjectReference{
- Name: "some-config-map",
- },
- Key: "some-key",
- },
- },
- }},
- expectedError: `[0].valueFrom: Invalid value: "": may not have more than one field specified at a time`,
- },
- {
- name: "valueFrom.secretKeyRef.name invalid",
- envs: []core.EnvVar{{
- Name: "abc",
- ValueFrom: &core.EnvVarSource{
- SecretKeyRef: &core.SecretKeySelector{
- LocalObjectReference: core.LocalObjectReference{
- Name: "$%^&*#",
- },
- Key: "a-key",
- },
- },
- }},
- },
- {
- name: "valueFrom.configMapKeyRef.name invalid",
- envs: []core.EnvVar{{
- Name: "abc",
- ValueFrom: &core.EnvVarSource{
- ConfigMapKeyRef: &core.ConfigMapKeySelector{
- LocalObjectReference: core.LocalObjectReference{
- Name: "$%^&*#",
- },
- Key: "some-key",
- },
- },
- }},
- },
- {
- name: "missing FieldPath on ObjectFieldSelector",
- envs: []core.EnvVar{{
- Name: "abc",
- ValueFrom: &core.EnvVarSource{
- FieldRef: &core.ObjectFieldSelector{
- APIVersion: "v1",
- },
- },
- }},
- expectedError: `[0].valueFrom.fieldRef.fieldPath: Required value`,
- },
- {
- name: "missing APIVersion on ObjectFieldSelector",
- envs: []core.EnvVar{{
- Name: "abc",
- ValueFrom: &core.EnvVarSource{
- FieldRef: &core.ObjectFieldSelector{
- FieldPath: "metadata.name",
- },
- },
- }},
- expectedError: `[0].valueFrom.fieldRef.apiVersion: Required value`,
- },
- {
- name: "invalid fieldPath",
- envs: []core.EnvVar{{
- Name: "abc",
- ValueFrom: &core.EnvVarSource{
- FieldRef: &core.ObjectFieldSelector{
- FieldPath: "metadata.whoops",
- APIVersion: "v1",
- },
- },
- }},
- expectedError: `[0].valueFrom.fieldRef.fieldPath: Invalid value: "metadata.whoops": error converting fieldPath`,
- },
- {
- name: "metadata.name with subscript",
- envs: []core.EnvVar{{
- Name: "labels",
- ValueFrom: &core.EnvVarSource{
- FieldRef: &core.ObjectFieldSelector{
- FieldPath: "metadata.name['key']",
- APIVersion: "v1",
- },
- },
- }},
- expectedError: `[0].valueFrom.fieldRef.fieldPath: Invalid value: "metadata.name['key']": error converting fieldPath: field label does not support subscript`,
- },
- {
- name: "metadata.labels without subscript",
- envs: []core.EnvVar{{
- Name: "labels",
- ValueFrom: &core.EnvVarSource{
- FieldRef: &core.ObjectFieldSelector{
- FieldPath: "metadata.labels",
- APIVersion: "v1",
- },
- },
- }},
- expectedError: `[0].valueFrom.fieldRef.fieldPath: Unsupported value: "metadata.labels": supported values: "metadata.name", "metadata.namespace", "metadata.uid", "spec.nodeName", "spec.serviceAccountName", "status.hostIP", "status.podIP"`,
- },
- {
- name: "metadata.annotations without subscript",
- envs: []core.EnvVar{{
- Name: "abc",
- ValueFrom: &core.EnvVarSource{
- FieldRef: &core.ObjectFieldSelector{
- FieldPath: "metadata.annotations",
- APIVersion: "v1",
- },
- },
- }},
- expectedError: `[0].valueFrom.fieldRef.fieldPath: Unsupported value: "metadata.annotations": supported values: "metadata.name", "metadata.namespace", "metadata.uid", "spec.nodeName", "spec.serviceAccountName", "status.hostIP", "status.podIP"`,
- },
- {
- name: "metadata.annotations with invalid key",
- envs: []core.EnvVar{{
- Name: "abc",
- ValueFrom: &core.EnvVarSource{
- FieldRef: &core.ObjectFieldSelector{
- FieldPath: "metadata.annotations['invalid~key']",
- APIVersion: "v1",
- },
- },
- }},
- expectedError: `field[0].valueFrom.fieldRef: Invalid value: "invalid~key"`,
- },
- {
- name: "metadata.labels with invalid key",
- envs: []core.EnvVar{{
- Name: "abc",
- ValueFrom: &core.EnvVarSource{
- FieldRef: &core.ObjectFieldSelector{
- FieldPath: "metadata.labels['Www.k8s.io/test']",
- APIVersion: "v1",
- },
- },
- }},
- expectedError: `field[0].valueFrom.fieldRef: Invalid value: "Www.k8s.io/test"`,
- },
- {
- name: "unsupported fieldPath",
- envs: []core.EnvVar{{
- Name: "abc",
- ValueFrom: &core.EnvVarSource{
- FieldRef: &core.ObjectFieldSelector{
- FieldPath: "status.phase",
- APIVersion: "v1",
- },
- },
- }},
- expectedError: `valueFrom.fieldRef.fieldPath: Unsupported value: "status.phase": supported values: "metadata.name", "metadata.namespace", "metadata.uid", "spec.nodeName", "spec.serviceAccountName", "status.hostIP", "status.podIP"`,
- },
- }
- for _, tc := range errorCases {
- if errs := ValidateEnv(tc.envs, field.NewPath("field")); len(errs) == 0 {
- t.Errorf("expected failure for %s", tc.name)
- } else {
- for i := range errs {
- str := errs[i].Error()
- if str != "" && !strings.Contains(str, tc.expectedError) {
- t.Errorf("%s: expected error detail either empty or %q, got %q", tc.name, tc.expectedError, str)
- }
- }
- }
- }
- }
- func TestValidateEnvFrom(t *testing.T) {
- successCase := []core.EnvFromSource{
- {
- ConfigMapRef: &core.ConfigMapEnvSource{
- LocalObjectReference: core.LocalObjectReference{Name: "abc"},
- },
- },
- {
- Prefix: "pre_",
- ConfigMapRef: &core.ConfigMapEnvSource{
- LocalObjectReference: core.LocalObjectReference{Name: "abc"},
- },
- },
- {
- Prefix: "a.b",
- ConfigMapRef: &core.ConfigMapEnvSource{
- LocalObjectReference: core.LocalObjectReference{Name: "abc"},
- },
- },
- {
- SecretRef: &core.SecretEnvSource{
- LocalObjectReference: core.LocalObjectReference{Name: "abc"},
- },
- },
- {
- Prefix: "pre_",
- SecretRef: &core.SecretEnvSource{
- LocalObjectReference: core.LocalObjectReference{Name: "abc"},
- },
- },
- {
- Prefix: "a.b",
- SecretRef: &core.SecretEnvSource{
- LocalObjectReference: core.LocalObjectReference{Name: "abc"},
- },
- },
- }
- if errs := ValidateEnvFrom(successCase, field.NewPath("field")); len(errs) != 0 {
- t.Errorf("expected success: %v", errs)
- }
- errorCases := []struct {
- name string
- envs []core.EnvFromSource
- expectedError string
- }{
- {
- name: "zero-length name",
- envs: []core.EnvFromSource{
- {
- ConfigMapRef: &core.ConfigMapEnvSource{
- LocalObjectReference: core.LocalObjectReference{Name: ""}},
- },
- },
- expectedError: "field[0].configMapRef.name: Required value",
- },
- {
- name: "invalid name",
- envs: []core.EnvFromSource{
- {
- ConfigMapRef: &core.ConfigMapEnvSource{
- LocalObjectReference: core.LocalObjectReference{Name: "$"}},
- },
- },
- expectedError: "field[0].configMapRef.name: Invalid value",
- },
- {
- name: "invalid prefix",
- envs: []core.EnvFromSource{
- {
- Prefix: "a!b",
- ConfigMapRef: &core.ConfigMapEnvSource{
- LocalObjectReference: core.LocalObjectReference{Name: "abc"}},
- },
- },
- expectedError: `field[0].prefix: Invalid value: "a!b": ` + envVarNameErrMsg,
- },
- {
- name: "zero-length name",
- envs: []core.EnvFromSource{
- {
- SecretRef: &core.SecretEnvSource{
- LocalObjectReference: core.LocalObjectReference{Name: ""}},
- },
- },
- expectedError: "field[0].secretRef.name: Required value",
- },
- {
- name: "invalid name",
- envs: []core.EnvFromSource{
- {
- SecretRef: &core.SecretEnvSource{
- LocalObjectReference: core.LocalObjectReference{Name: "&"}},
- },
- },
- expectedError: "field[0].secretRef.name: Invalid value",
- },
- {
- name: "invalid prefix",
- envs: []core.EnvFromSource{
- {
- Prefix: "a!b",
- SecretRef: &core.SecretEnvSource{
- LocalObjectReference: core.LocalObjectReference{Name: "abc"}},
- },
- },
- expectedError: `field[0].prefix: Invalid value: "a!b": ` + envVarNameErrMsg,
- },
- {
- name: "no refs",
- envs: []core.EnvFromSource{
- {},
- },
- expectedError: "field: Invalid value: \"\": must specify one of: `configMapRef` or `secretRef`",
- },
- {
- name: "multiple refs",
- envs: []core.EnvFromSource{
- {
- SecretRef: &core.SecretEnvSource{
- LocalObjectReference: core.LocalObjectReference{Name: "abc"}},
- ConfigMapRef: &core.ConfigMapEnvSource{
- LocalObjectReference: core.LocalObjectReference{Name: "abc"}},
- },
- },
- expectedError: "field: Invalid value: \"\": may not have more than one field specified at a time",
- },
- {
- name: "invalid secret ref name",
- envs: []core.EnvFromSource{
- {
- SecretRef: &core.SecretEnvSource{
- LocalObjectReference: core.LocalObjectReference{Name: "$%^&*#"}},
- },
- },
- expectedError: "field[0].secretRef.name: Invalid value: \"$%^&*#\": " + dnsSubdomainLabelErrMsg,
- },
- {
- name: "invalid config ref name",
- envs: []core.EnvFromSource{
- {
- ConfigMapRef: &core.ConfigMapEnvSource{
- LocalObjectReference: core.LocalObjectReference{Name: "$%^&*#"}},
- },
- },
- expectedError: "field[0].configMapRef.name: Invalid value: \"$%^&*#\": " + dnsSubdomainLabelErrMsg,
- },
- }
- for _, tc := range errorCases {
- if errs := ValidateEnvFrom(tc.envs, field.NewPath("field")); len(errs) == 0 {
- t.Errorf("expected failure for %s", tc.name)
- } else {
- for i := range errs {
- str := errs[i].Error()
- if str != "" && !strings.Contains(str, tc.expectedError) {
- t.Errorf("%s: expected error detail either empty or %q, got %q", tc.name, tc.expectedError, str)
- }
- }
- }
- }
- }
- func TestValidateVolumeMounts(t *testing.T) {
- volumes := []core.Volume{
- {Name: "abc", VolumeSource: core.VolumeSource{PersistentVolumeClaim: &core.PersistentVolumeClaimVolumeSource{ClaimName: "testclaim1"}}},
- {Name: "abc-123", VolumeSource: core.VolumeSource{PersistentVolumeClaim: &core.PersistentVolumeClaimVolumeSource{ClaimName: "testclaim2"}}},
- {Name: "123", VolumeSource: core.VolumeSource{HostPath: &core.HostPathVolumeSource{Path: "/foo/baz", Type: newHostPathType(string(core.HostPathUnset))}}},
- }
- vols, v1err := ValidateVolumes(volumes, field.NewPath("field"))
- if len(v1err) > 0 {
- t.Errorf("Invalid test volume - expected success %v", v1err)
- return
- }
- container := core.Container{
- SecurityContext: nil,
- }
- propagation := core.MountPropagationBidirectional
- successCase := []core.VolumeMount{
- {Name: "abc", MountPath: "/foo"},
- {Name: "123", MountPath: "/bar"},
- {Name: "abc-123", MountPath: "/baz"},
- {Name: "abc-123", MountPath: "/baa", SubPath: ""},
- {Name: "abc-123", MountPath: "/bab", SubPath: "baz"},
- {Name: "abc-123", MountPath: "d:", SubPath: ""},
- {Name: "abc-123", MountPath: "F:", SubPath: ""},
- {Name: "abc-123", MountPath: "G:\\mount", SubPath: ""},
- {Name: "abc-123", MountPath: "/bac", SubPath: ".baz"},
- {Name: "abc-123", MountPath: "/bad", SubPath: "..baz"},
- }
- goodVolumeDevices := []core.VolumeDevice{
- {Name: "xyz", DevicePath: "/foofoo"},
- {Name: "uvw", DevicePath: "/foofoo/share/test"},
- }
- if errs := ValidateVolumeMounts(successCase, GetVolumeDeviceMap(goodVolumeDevices), vols, &container, field.NewPath("field")); len(errs) != 0 {
- t.Errorf("expected success: %v", errs)
- }
- errorCases := map[string][]core.VolumeMount{
- "empty name": {{Name: "", MountPath: "/foo"}},
- "name not found": {{Name: "", MountPath: "/foo"}},
- "empty mountpath": {{Name: "abc", MountPath: ""}},
- "mountpath collision": {{Name: "foo", MountPath: "/path/a"}, {Name: "bar", MountPath: "/path/a"}},
- "absolute subpath": {{Name: "abc", MountPath: "/bar", SubPath: "/baz"}},
- "subpath in ..": {{Name: "abc", MountPath: "/bar", SubPath: "../baz"}},
- "subpath contains ..": {{Name: "abc", MountPath: "/bar", SubPath: "baz/../bat"}},
- "subpath ends in ..": {{Name: "abc", MountPath: "/bar", SubPath: "./.."}},
- "disabled MountPropagation feature gate": {{Name: "abc", MountPath: "/bar", MountPropagation: &propagation}},
- "name exists in volumeDevice": {{Name: "xyz", MountPath: "/bar"}},
- "mountpath exists in volumeDevice": {{Name: "uvw", MountPath: "/mnt/exists"}},
- "both exist in volumeDevice": {{Name: "xyz", MountPath: "/mnt/exists"}},
- }
- badVolumeDevice := []core.VolumeDevice{
- {Name: "xyz", DevicePath: "/mnt/exists"},
- }
- for k, v := range errorCases {
- if errs := ValidateVolumeMounts(v, GetVolumeDeviceMap(badVolumeDevice), vols, &container, field.NewPath("field")); len(errs) == 0 {
- t.Errorf("expected failure for %s", k)
- }
- }
- }
- func TestValidateDisabledSubpath(t *testing.T) {
- defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.VolumeSubpath, false)()
- volumes := []core.Volume{
- {Name: "abc", VolumeSource: core.VolumeSource{PersistentVolumeClaim: &core.PersistentVolumeClaimVolumeSource{ClaimName: "testclaim1"}}},
- {Name: "abc-123", VolumeSource: core.VolumeSource{PersistentVolumeClaim: &core.PersistentVolumeClaimVolumeSource{ClaimName: "testclaim2"}}},
- {Name: "123", VolumeSource: core.VolumeSource{HostPath: &core.HostPathVolumeSource{Path: "/foo/baz", Type: newHostPathType(string(core.HostPathUnset))}}},
- }
- vols, v1err := ValidateVolumes(volumes, field.NewPath("field"))
- if len(v1err) > 0 {
- t.Errorf("Invalid test volume - expected success %v", v1err)
- return
- }
- container := core.Container{
- SecurityContext: nil,
- }
- goodVolumeDevices := []core.VolumeDevice{
- {Name: "xyz", DevicePath: "/foofoo"},
- {Name: "uvw", DevicePath: "/foofoo/share/test"},
- }
- cases := map[string]struct {
- mounts []core.VolumeMount
- expectError bool
- }{
- "subpath not specified": {
- []core.VolumeMount{
- {
- Name: "abc-123",
- MountPath: "/bab",
- },
- },
- false,
- },
- "subpath specified": {
- []core.VolumeMount{
- {
- Name: "abc-123",
- MountPath: "/bab",
- SubPath: "baz",
- },
- },
- false, // validation should not fail, dropping the field is handled in PrepareForCreate/PrepareForUpdate
- },
- }
- for name, test := range cases {
- errs := ValidateVolumeMounts(test.mounts, GetVolumeDeviceMap(goodVolumeDevices), vols, &container, field.NewPath("field"))
- if len(errs) != 0 && !test.expectError {
- t.Errorf("test %v failed: %+v", name, errs)
- }
- if len(errs) == 0 && test.expectError {
- t.Errorf("test %v failed, expected error", name)
- }
- }
- }
- func TestValidateSubpathMutuallyExclusive(t *testing.T) {
- // Enable feature VolumeSubpathEnvExpansion and VolumeSubpath
- defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.VolumeSubpathEnvExpansion, true)()
- defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.VolumeSubpath, true)()
- volumes := []core.Volume{
- {Name: "abc", VolumeSource: core.VolumeSource{PersistentVolumeClaim: &core.PersistentVolumeClaimVolumeSource{ClaimName: "testclaim1"}}},
- {Name: "abc-123", VolumeSource: core.VolumeSource{PersistentVolumeClaim: &core.PersistentVolumeClaimVolumeSource{ClaimName: "testclaim2"}}},
- {Name: "123", VolumeSource: core.VolumeSource{HostPath: &core.HostPathVolumeSource{Path: "/foo/baz", Type: newHostPathType(string(core.HostPathUnset))}}},
- }
- vols, v1err := ValidateVolumes(volumes, field.NewPath("field"))
- if len(v1err) > 0 {
- t.Errorf("Invalid test volume - expected success %v", v1err)
- return
- }
- container := core.Container{
- SecurityContext: nil,
- }
- goodVolumeDevices := []core.VolumeDevice{
- {Name: "xyz", DevicePath: "/foofoo"},
- {Name: "uvw", DevicePath: "/foofoo/share/test"},
- }
- cases := map[string]struct {
- mounts []core.VolumeMount
- expectError bool
- }{
- "subpath and subpathexpr not specified": {
- []core.VolumeMount{
- {
- Name: "abc-123",
- MountPath: "/bab",
- },
- },
- false,
- },
- "subpath expr specified": {
- []core.VolumeMount{
- {
- Name: "abc-123",
- MountPath: "/bab",
- SubPathExpr: "$(POD_NAME)",
- },
- },
- false,
- },
- "subpath specified": {
- []core.VolumeMount{
- {
- Name: "abc-123",
- MountPath: "/bab",
- SubPath: "baz",
- },
- },
- false,
- },
- "subpath and subpathexpr specified": {
- []core.VolumeMount{
- {
- Name: "abc-123",
- MountPath: "/bab",
- SubPath: "baz",
- SubPathExpr: "$(POD_NAME)",
- },
- },
- true,
- },
- }
- for name, test := range cases {
- errs := ValidateVolumeMounts(test.mounts, GetVolumeDeviceMap(goodVolumeDevices), vols, &container, field.NewPath("field"))
- if len(errs) != 0 && !test.expectError {
- t.Errorf("test %v failed: %+v", name, errs)
- }
- if len(errs) == 0 && test.expectError {
- t.Errorf("test %v failed, expected error", name)
- }
- }
- }
- func TestValidateDisabledSubpathExpr(t *testing.T) {
- // Enable feature VolumeSubpathEnvExpansion
- defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.VolumeSubpathEnvExpansion, true)()
- volumes := []core.Volume{
- {Name: "abc", VolumeSource: core.VolumeSource{PersistentVolumeClaim: &core.PersistentVolumeClaimVolumeSource{ClaimName: "testclaim1"}}},
- {Name: "abc-123", VolumeSource: core.VolumeSource{PersistentVolumeClaim: &core.PersistentVolumeClaimVolumeSource{ClaimName: "testclaim2"}}},
- {Name: "123", VolumeSource: core.VolumeSource{HostPath: &core.HostPathVolumeSource{Path: "/foo/baz", Type: newHostPathType(string(core.HostPathUnset))}}},
- }
- vols, v1err := ValidateVolumes(volumes, field.NewPath("field"))
- if len(v1err) > 0 {
- t.Errorf("Invalid test volume - expected success %v", v1err)
- return
- }
- container := core.Container{
- SecurityContext: nil,
- }
- goodVolumeDevices := []core.VolumeDevice{
- {Name: "xyz", DevicePath: "/foofoo"},
- {Name: "uvw", DevicePath: "/foofoo/share/test"},
- }
- cases := map[string]struct {
- mounts []core.VolumeMount
- expectError bool
- }{
- "subpath expr not specified": {
- []core.VolumeMount{
- {
- Name: "abc-123",
- MountPath: "/bab",
- },
- },
- false,
- },
- "subpath expr specified": {
- []core.VolumeMount{
- {
- Name: "abc-123",
- MountPath: "/bab",
- SubPathExpr: "$(POD_NAME)",
- },
- },
- false,
- },
- }
- for name, test := range cases {
- errs := ValidateVolumeMounts(test.mounts, GetVolumeDeviceMap(goodVolumeDevices), vols, &container, field.NewPath("field"))
- if len(errs) != 0 && !test.expectError {
- t.Errorf("test %v failed: %+v", name, errs)
- }
- if len(errs) == 0 && test.expectError {
- t.Errorf("test %v failed, expected error", name)
- }
- }
- // Repeat with feature gate off
- defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.VolumeSubpathEnvExpansion, false)()
- cases = map[string]struct {
- mounts []core.VolumeMount
- expectError bool
- }{
- "subpath expr not specified": {
- []core.VolumeMount{
- {
- Name: "abc-123",
- MountPath: "/bab",
- },
- },
- false,
- },
- "subpath expr specified": {
- []core.VolumeMount{
- {
- Name: "abc-123",
- MountPath: "/bab",
- SubPathExpr: "$(POD_NAME)",
- },
- },
- false, // validation should not fail, dropping the field is handled in PrepareForCreate/PrepareForUpdate
- },
- }
- for name, test := range cases {
- errs := ValidateVolumeMounts(test.mounts, GetVolumeDeviceMap(goodVolumeDevices), vols, &container, field.NewPath("field"))
- if len(errs) != 0 && !test.expectError {
- t.Errorf("test %v failed: %+v", name, errs)
- }
- if len(errs) == 0 && test.expectError {
- t.Errorf("test %v failed, expected error", name)
- }
- }
- // Repeat with subpath feature gate off
- defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.VolumeSubpath, false)()
- cases = map[string]struct {
- mounts []core.VolumeMount
- expectError bool
- }{
- "subpath expr not specified": {
- []core.VolumeMount{
- {
- Name: "abc-123",
- MountPath: "/bab",
- },
- },
- false,
- },
- "subpath expr specified": {
- []core.VolumeMount{
- {
- Name: "abc-123",
- MountPath: "/bab",
- SubPathExpr: "$(POD_NAME)",
- },
- },
- false, // validation should not fail, dropping the field is handled in PrepareForCreate/PrepareForUpdate
- },
- }
- for name, test := range cases {
- errs := ValidateVolumeMounts(test.mounts, GetVolumeDeviceMap(goodVolumeDevices), vols, &container, field.NewPath("field"))
- if len(errs) != 0 && !test.expectError {
- t.Errorf("test %v failed: %+v", name, errs)
- }
- if len(errs) == 0 && test.expectError {
- t.Errorf("test %v failed, expected error", name)
- }
- }
- }
- func TestValidateMountPropagation(t *testing.T) {
- bTrue := true
- bFalse := false
- privilegedContainer := &core.Container{
- SecurityContext: &core.SecurityContext{
- Privileged: &bTrue,
- },
- }
- nonPrivilegedContainer := &core.Container{
- SecurityContext: &core.SecurityContext{
- Privileged: &bFalse,
- },
- }
- defaultContainer := &core.Container{}
- propagationBidirectional := core.MountPropagationBidirectional
- propagationHostToContainer := core.MountPropagationHostToContainer
- propagationNone := core.MountPropagationNone
- propagationInvalid := core.MountPropagationMode("invalid")
- tests := []struct {
- mount core.VolumeMount
- container *core.Container
- expectError bool
- }{
- {
- // implicitly non-privileged container + no propagation
- core.VolumeMount{Name: "foo", MountPath: "/foo"},
- defaultContainer,
- false,
- },
- {
- // implicitly non-privileged container + HostToContainer
- core.VolumeMount{Name: "foo", MountPath: "/foo", MountPropagation: &propagationHostToContainer},
- defaultContainer,
- false,
- },
- {
- // non-privileged container + None
- core.VolumeMount{Name: "foo", MountPath: "/foo", MountPropagation: &propagationNone},
- defaultContainer,
- false,
- },
- {
- // error: implicitly non-privileged container + Bidirectional
- core.VolumeMount{Name: "foo", MountPath: "/foo", MountPropagation: &propagationBidirectional},
- defaultContainer,
- true,
- },
- {
- // explicitly non-privileged container + no propagation
- core.VolumeMount{Name: "foo", MountPath: "/foo"},
- nonPrivilegedContainer,
- false,
- },
- {
- // explicitly non-privileged container + HostToContainer
- core.VolumeMount{Name: "foo", MountPath: "/foo", MountPropagation: &propagationHostToContainer},
- nonPrivilegedContainer,
- false,
- },
- {
- // explicitly non-privileged container + HostToContainer
- core.VolumeMount{Name: "foo", MountPath: "/foo", MountPropagation: &propagationBidirectional},
- nonPrivilegedContainer,
- true,
- },
- {
- // privileged container + no propagation
- core.VolumeMount{Name: "foo", MountPath: "/foo"},
- privilegedContainer,
- false,
- },
- {
- // privileged container + HostToContainer
- core.VolumeMount{Name: "foo", MountPath: "/foo", MountPropagation: &propagationHostToContainer},
- privilegedContainer,
- false,
- },
- {
- // privileged container + Bidirectional
- core.VolumeMount{Name: "foo", MountPath: "/foo", MountPropagation: &propagationBidirectional},
- privilegedContainer,
- false,
- },
- {
- // error: privileged container + invalid mount propagation
- core.VolumeMount{Name: "foo", MountPath: "/foo", MountPropagation: &propagationInvalid},
- privilegedContainer,
- true,
- },
- {
- // no container + Bidirectional
- core.VolumeMount{Name: "foo", MountPath: "/foo", MountPropagation: &propagationBidirectional},
- nil,
- false,
- },
- }
- volumes := []core.Volume{
- {Name: "foo", VolumeSource: core.VolumeSource{HostPath: &core.HostPathVolumeSource{Path: "/foo/baz", Type: newHostPathType(string(core.HostPathUnset))}}},
- }
- vols2, v2err := ValidateVolumes(volumes, field.NewPath("field"))
- if len(v2err) > 0 {
- t.Errorf("Invalid test volume - expected success %v", v2err)
- return
- }
- for i, test := range tests {
- errs := ValidateVolumeMounts([]core.VolumeMount{test.mount}, nil, vols2, test.container, field.NewPath("field"))
- if test.expectError && len(errs) == 0 {
- t.Errorf("test %d expected error, got none", i)
- }
- if !test.expectError && len(errs) != 0 {
- t.Errorf("test %d expected success, got error: %v", i, errs)
- }
- }
- }
- func TestAlphaValidateVolumeDevices(t *testing.T) {
- volumes := []core.Volume{
- {Name: "abc", VolumeSource: core.VolumeSource{PersistentVolumeClaim: &core.PersistentVolumeClaimVolumeSource{ClaimName: "testclaim1"}}},
- {Name: "abc-123", VolumeSource: core.VolumeSource{PersistentVolumeClaim: &core.PersistentVolumeClaimVolumeSource{ClaimName: "testclaim2"}}},
- {Name: "def", VolumeSource: core.VolumeSource{HostPath: &core.HostPathVolumeSource{Path: "/foo/baz", Type: newHostPathType(string(core.HostPathUnset))}}},
- }
- vols, v1err := ValidateVolumes(volumes, field.NewPath("field"))
- if len(v1err) > 0 {
- t.Errorf("Invalid test volumes - expected success %v", v1err)
- return
- }
- successCase := []core.VolumeDevice{
- {Name: "abc", DevicePath: "/foo"},
- {Name: "abc-123", DevicePath: "/usr/share/test"},
- }
- goodVolumeMounts := []core.VolumeMount{
- {Name: "xyz", MountPath: "/foofoo"},
- {Name: "ghi", MountPath: "/foo/usr/share/test"},
- }
- errorCases := map[string][]core.VolumeDevice{
- "empty name": {{Name: "", DevicePath: "/foo"}},
- "duplicate name": {{Name: "abc", DevicePath: "/foo"}, {Name: "abc", DevicePath: "/foo/bar"}},
- "name not found": {{Name: "not-found", DevicePath: "/usr/share/test"}},
- "name found but invalid source": {{Name: "def", DevicePath: "/usr/share/test"}},
- "empty devicepath": {{Name: "abc", DevicePath: ""}},
- "relative devicepath": {{Name: "abc-123", DevicePath: "baz"}},
- "duplicate devicepath": {{Name: "abc", DevicePath: "/foo"}, {Name: "abc-123", DevicePath: "/foo"}},
- "no backsteps": {{Name: "def", DevicePath: "/baz/../"}},
- "name exists in volumemounts": {{Name: "abc", DevicePath: "/baz/../"}},
- "path exists in volumemounts": {{Name: "xyz", DevicePath: "/this/path/exists"}},
- "both exist in volumemounts": {{Name: "abc", DevicePath: "/this/path/exists"}},
- }
- badVolumeMounts := []core.VolumeMount{
- {Name: "abc", MountPath: "/foo"},
- {Name: "abc-123", MountPath: "/this/path/exists"},
- }
- // Success Cases:
- // Validate normal success cases - only PVC volumeSource
- if errs := ValidateVolumeDevices(successCase, GetVolumeMountMap(goodVolumeMounts), vols, field.NewPath("field")); len(errs) != 0 {
- t.Errorf("expected success: %v", errs)
- }
- // Error Cases:
- // Validate normal error cases - only PVC volumeSource
- for k, v := range errorCases {
- if errs := ValidateVolumeDevices(v, GetVolumeMountMap(badVolumeMounts), vols, field.NewPath("field")); len(errs) == 0 {
- t.Errorf("expected failure for %s", k)
- }
- }
- }
- func TestValidateProbe(t *testing.T) {
- handler := core.Handler{Exec: &core.ExecAction{Command: []string{"echo"}}}
- // These fields must be positive.
- positiveFields := [...]string{"InitialDelaySeconds", "TimeoutSeconds", "PeriodSeconds", "SuccessThreshold", "FailureThreshold"}
- successCases := []*core.Probe{nil}
- for _, field := range positiveFields {
- probe := &core.Probe{Handler: handler}
- reflect.ValueOf(probe).Elem().FieldByName(field).SetInt(10)
- successCases = append(successCases, probe)
- }
- for _, p := range successCases {
- if errs := validateProbe(p, field.NewPath("field")); len(errs) != 0 {
- t.Errorf("expected success: %v", errs)
- }
- }
- errorCases := []*core.Probe{{TimeoutSeconds: 10, InitialDelaySeconds: 10}}
- for _, field := range positiveFields {
- probe := &core.Probe{Handler: handler}
- reflect.ValueOf(probe).Elem().FieldByName(field).SetInt(-10)
- errorCases = append(errorCases, probe)
- }
- for _, p := range errorCases {
- if errs := validateProbe(p, field.NewPath("field")); len(errs) == 0 {
- t.Errorf("expected failure for %v", p)
- }
- }
- }
- func TestValidateHandler(t *testing.T) {
- successCases := []core.Handler{
- {Exec: &core.ExecAction{Command: []string{"echo"}}},
- {HTTPGet: &core.HTTPGetAction{Path: "/", Port: intstr.FromInt(1), Host: "", Scheme: "HTTP"}},
- {HTTPGet: &core.HTTPGetAction{Path: "/foo", Port: intstr.FromInt(65535), Host: "host", Scheme: "HTTP"}},
- {HTTPGet: &core.HTTPGetAction{Path: "/", Port: intstr.FromString("port"), Host: "", Scheme: "HTTP"}},
- {HTTPGet: &core.HTTPGetAction{Path: "/", Port: intstr.FromString("port"), Host: "", Scheme: "HTTP", HTTPHeaders: []core.HTTPHeader{{Name: "Host", Value: "foo.example.com"}}}},
- {HTTPGet: &core.HTTPGetAction{Path: "/", Port: intstr.FromString("port"), Host: "", Scheme: "HTTP", HTTPHeaders: []core.HTTPHeader{{Name: "X-Forwarded-For", Value: "1.2.3.4"}, {Name: "X-Forwarded-For", Value: "5.6.7.8"}}}},
- }
- for _, h := range successCases {
- if errs := validateHandler(&h, field.NewPath("field")); len(errs) != 0 {
- t.Errorf("expected success: %v", errs)
- }
- }
- errorCases := []core.Handler{
- {},
- {Exec: &core.ExecAction{Command: []string{}}},
- {HTTPGet: &core.HTTPGetAction{Path: "", Port: intstr.FromInt(0), Host: ""}},
- {HTTPGet: &core.HTTPGetAction{Path: "/foo", Port: intstr.FromInt(65536), Host: "host"}},
- {HTTPGet: &core.HTTPGetAction{Path: "", Port: intstr.FromString(""), Host: ""}},
- {HTTPGet: &core.HTTPGetAction{Path: "/", Port: intstr.FromString("port"), Host: "", Scheme: "HTTP", HTTPHeaders: []core.HTTPHeader{{Name: "Host:", Value: "foo.example.com"}}}},
- {HTTPGet: &core.HTTPGetAction{Path: "/", Port: intstr.FromString("port"), Host: "", Scheme: "HTTP", HTTPHeaders: []core.HTTPHeader{{Name: "X_Forwarded_For", Value: "foo.example.com"}}}},
- }
- for _, h := range errorCases {
- if errs := validateHandler(&h, field.NewPath("field")); len(errs) == 0 {
- t.Errorf("expected failure for %#v", h)
- }
- }
- }
- func TestValidatePullPolicy(t *testing.T) {
- type T struct {
- Container core.Container
- ExpectedPolicy core.PullPolicy
- }
- testCases := map[string]T{
- "NotPresent1": {
- core.Container{Name: "abc", Image: "image:latest", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"},
- core.PullIfNotPresent,
- },
- "NotPresent2": {
- core.Container{Name: "abc1", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"},
- core.PullIfNotPresent,
- },
- "Always1": {
- core.Container{Name: "123", Image: "image:latest", ImagePullPolicy: "Always"},
- core.PullAlways,
- },
- "Always2": {
- core.Container{Name: "1234", Image: "image", ImagePullPolicy: "Always"},
- core.PullAlways,
- },
- "Never1": {
- core.Container{Name: "abc-123", Image: "image:latest", ImagePullPolicy: "Never"},
- core.PullNever,
- },
- "Never2": {
- core.Container{Name: "abc-1234", Image: "image", ImagePullPolicy: "Never"},
- core.PullNever,
- },
- }
- for k, v := range testCases {
- ctr := &v.Container
- errs := validatePullPolicy(ctr.ImagePullPolicy, field.NewPath("field"))
- if len(errs) != 0 {
- t.Errorf("case[%s] expected success, got %#v", k, errs)
- }
- if ctr.ImagePullPolicy != v.ExpectedPolicy {
- t.Errorf("case[%s] expected policy %v, got %v", k, v.ExpectedPolicy, ctr.ImagePullPolicy)
- }
- }
- }
- func getResourceLimits(cpu, memory string) core.ResourceList {
- res := core.ResourceList{}
- res[core.ResourceCPU] = resource.MustParse(cpu)
- res[core.ResourceMemory] = resource.MustParse(memory)
- return res
- }
- func TestValidateContainers(t *testing.T) {
- volumeDevices := make(map[string]core.VolumeSource)
- capabilities.SetForTests(capabilities.Capabilities{
- AllowPrivileged: true,
- })
- successCase := []core.Container{
- {Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"},
- // backwards compatibility to ensure containers in pod template spec do not check for this
- {Name: "def", Image: " ", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"},
- {Name: "ghi", Image: " some ", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"},
- {Name: "123", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"},
- {Name: "abc-123", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"},
- {
- Name: "life-123",
- Image: "image",
- Lifecycle: &core.Lifecycle{
- PreStop: &core.Handler{
- Exec: &core.ExecAction{Command: []string{"ls", "-l"}},
- },
- },
- ImagePullPolicy: "IfNotPresent",
- TerminationMessagePolicy: "File",
- },
- {
- Name: "resources-test",
- Image: "image",
- Resources: core.ResourceRequirements{
- Limits: core.ResourceList{
- core.ResourceName(core.ResourceCPU): resource.MustParse("10"),
- core.ResourceName(core.ResourceMemory): resource.MustParse("10G"),
- core.ResourceName("my.org/resource"): resource.MustParse("10"),
- },
- },
- ImagePullPolicy: "IfNotPresent",
- TerminationMessagePolicy: "File",
- },
- {
- Name: "resources-test-with-request-and-limit",
- Image: "image",
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName(core.ResourceCPU): resource.MustParse("10"),
- core.ResourceName(core.ResourceMemory): resource.MustParse("10G"),
- },
- Limits: core.ResourceList{
- core.ResourceName(core.ResourceCPU): resource.MustParse("10"),
- core.ResourceName(core.ResourceMemory): resource.MustParse("10G"),
- },
- },
- ImagePullPolicy: "IfNotPresent",
- TerminationMessagePolicy: "File",
- },
- {
- Name: "resources-request-limit-simple",
- Image: "image",
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName(core.ResourceCPU): resource.MustParse("8"),
- },
- Limits: core.ResourceList{
- core.ResourceName(core.ResourceCPU): resource.MustParse("10"),
- },
- },
- ImagePullPolicy: "IfNotPresent",
- TerminationMessagePolicy: "File",
- },
- {
- Name: "resources-request-limit-edge",
- Image: "image",
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName(core.ResourceCPU): resource.MustParse("10"),
- core.ResourceName(core.ResourceMemory): resource.MustParse("10G"),
- core.ResourceName("my.org/resource"): resource.MustParse("10"),
- },
- Limits: core.ResourceList{
- core.ResourceName(core.ResourceCPU): resource.MustParse("10"),
- core.ResourceName(core.ResourceMemory): resource.MustParse("10G"),
- core.ResourceName("my.org/resource"): resource.MustParse("10"),
- },
- },
- ImagePullPolicy: "IfNotPresent",
- TerminationMessagePolicy: "File",
- },
- {
- Name: "resources-request-limit-partials",
- Image: "image",
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName(core.ResourceCPU): resource.MustParse("9.5"),
- core.ResourceName(core.ResourceMemory): resource.MustParse("10G"),
- },
- Limits: core.ResourceList{
- core.ResourceName(core.ResourceCPU): resource.MustParse("10"),
- core.ResourceName("my.org/resource"): resource.MustParse("10"),
- },
- },
- ImagePullPolicy: "IfNotPresent",
- TerminationMessagePolicy: "File",
- },
- {
- Name: "resources-request",
- Image: "image",
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName(core.ResourceCPU): resource.MustParse("9.5"),
- core.ResourceName(core.ResourceMemory): resource.MustParse("10G"),
- },
- },
- ImagePullPolicy: "IfNotPresent",
- TerminationMessagePolicy: "File",
- },
- {
- Name: "same-host-port-different-protocol",
- Image: "image",
- Ports: []core.ContainerPort{
- {ContainerPort: 80, HostPort: 80, Protocol: "TCP"},
- {ContainerPort: 80, HostPort: 80, Protocol: "UDP"},
- },
- ImagePullPolicy: "IfNotPresent",
- TerminationMessagePolicy: "File",
- },
- {
- Name: "fallback-to-logs-termination-message",
- Image: "image",
- ImagePullPolicy: "IfNotPresent",
- TerminationMessagePolicy: "FallbackToLogsOnError",
- },
- {
- Name: "file-termination-message",
- Image: "image",
- ImagePullPolicy: "IfNotPresent",
- TerminationMessagePolicy: "File",
- },
- {
- Name: "env-from-source",
- Image: "image",
- ImagePullPolicy: "IfNotPresent",
- TerminationMessagePolicy: "File",
- EnvFrom: []core.EnvFromSource{
- {
- ConfigMapRef: &core.ConfigMapEnvSource{
- LocalObjectReference: core.LocalObjectReference{
- Name: "test",
- },
- },
- },
- },
- },
- {Name: "abc-1234", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File", SecurityContext: fakeValidSecurityContext(true)},
- }
- if errs := validateContainers(successCase, false, volumeDevices, field.NewPath("field")); len(errs) != 0 {
- t.Errorf("expected success: %v", errs)
- }
- capabilities.SetForTests(capabilities.Capabilities{
- AllowPrivileged: false,
- })
- errorCases := map[string][]core.Container{
- "zero-length name": {{Name: "", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- "zero-length-image": {{Name: "abc", Image: "", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- "name > 63 characters": {{Name: strings.Repeat("a", 64), Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- "name not a DNS label": {{Name: "a.b.c", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- "name not unique": {
- {Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"},
- {Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"},
- },
- "zero-length image": {{Name: "abc", Image: "", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- "host port not unique": {
- {Name: "abc", Image: "image", Ports: []core.ContainerPort{{ContainerPort: 80, HostPort: 80, Protocol: "TCP"}},
- ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"},
- {Name: "def", Image: "image", Ports: []core.ContainerPort{{ContainerPort: 81, HostPort: 80, Protocol: "TCP"}},
- ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"},
- },
- "invalid env var name": {
- {Name: "abc", Image: "image", Env: []core.EnvVar{{Name: "ev!1"}}, ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"},
- },
- "unknown volume name": {
- {Name: "abc", Image: "image", VolumeMounts: []core.VolumeMount{{Name: "anything", MountPath: "/foo"}},
- ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"},
- },
- "invalid lifecycle, no exec command.": {
- {
- Name: "life-123",
- Image: "image",
- Lifecycle: &core.Lifecycle{
- PreStop: &core.Handler{
- Exec: &core.ExecAction{},
- },
- },
- ImagePullPolicy: "IfNotPresent",
- TerminationMessagePolicy: "File",
- },
- },
- "invalid lifecycle, no http path.": {
- {
- Name: "life-123",
- Image: "image",
- Lifecycle: &core.Lifecycle{
- PreStop: &core.Handler{
- HTTPGet: &core.HTTPGetAction{},
- },
- },
- ImagePullPolicy: "IfNotPresent",
- TerminationMessagePolicy: "File",
- },
- },
- "invalid lifecycle, no tcp socket port.": {
- {
- Name: "life-123",
- Image: "image",
- Lifecycle: &core.Lifecycle{
- PreStop: &core.Handler{
- TCPSocket: &core.TCPSocketAction{},
- },
- },
- ImagePullPolicy: "IfNotPresent",
- TerminationMessagePolicy: "File",
- },
- },
- "invalid lifecycle, zero tcp socket port.": {
- {
- Name: "life-123",
- Image: "image",
- Lifecycle: &core.Lifecycle{
- PreStop: &core.Handler{
- TCPSocket: &core.TCPSocketAction{
- Port: intstr.FromInt(0),
- },
- },
- },
- ImagePullPolicy: "IfNotPresent",
- TerminationMessagePolicy: "File",
- },
- },
- "invalid lifecycle, no action.": {
- {
- Name: "life-123",
- Image: "image",
- Lifecycle: &core.Lifecycle{
- PreStop: &core.Handler{},
- },
- ImagePullPolicy: "IfNotPresent",
- TerminationMessagePolicy: "File",
- },
- },
- "invalid liveness probe, no tcp socket port.": {
- {
- Name: "life-123",
- Image: "image",
- LivenessProbe: &core.Probe{
- Handler: core.Handler{
- TCPSocket: &core.TCPSocketAction{},
- },
- },
- ImagePullPolicy: "IfNotPresent",
- TerminationMessagePolicy: "File",
- },
- },
- "invalid liveness probe, no action.": {
- {
- Name: "life-123",
- Image: "image",
- LivenessProbe: &core.Probe{
- Handler: core.Handler{},
- },
- ImagePullPolicy: "IfNotPresent",
- TerminationMessagePolicy: "File",
- },
- },
- "invalid message termination policy": {
- {
- Name: "life-123",
- Image: "image",
- ImagePullPolicy: "IfNotPresent",
- TerminationMessagePolicy: "Unknown",
- },
- },
- "empty message termination policy": {
- {
- Name: "life-123",
- Image: "image",
- ImagePullPolicy: "IfNotPresent",
- TerminationMessagePolicy: "",
- },
- },
- "privilege disabled": {
- {Name: "abc", Image: "image", SecurityContext: fakeValidSecurityContext(true)},
- },
- "invalid compute resource": {
- {
- Name: "abc-123",
- Image: "image",
- Resources: core.ResourceRequirements{
- Limits: core.ResourceList{
- "disk": resource.MustParse("10G"),
- },
- },
- ImagePullPolicy: "IfNotPresent",
- TerminationMessagePolicy: "File",
- },
- },
- "Resource CPU invalid": {
- {
- Name: "abc-123",
- Image: "image",
- Resources: core.ResourceRequirements{
- Limits: getResourceLimits("-10", "0"),
- },
- ImagePullPolicy: "IfNotPresent",
- TerminationMessagePolicy: "File",
- },
- },
- "Resource Requests CPU invalid": {
- {
- Name: "abc-123",
- Image: "image",
- Resources: core.ResourceRequirements{
- Requests: getResourceLimits("-10", "0"),
- },
- ImagePullPolicy: "IfNotPresent",
- TerminationMessagePolicy: "File",
- },
- },
- "Resource Memory invalid": {
- {
- Name: "abc-123",
- Image: "image",
- Resources: core.ResourceRequirements{
- Limits: getResourceLimits("0", "-10"),
- },
- ImagePullPolicy: "IfNotPresent",
- TerminationMessagePolicy: "File",
- },
- },
- "Request limit simple invalid": {
- {
- Name: "abc-123",
- Image: "image",
- Resources: core.ResourceRequirements{
- Limits: getResourceLimits("5", "3"),
- Requests: getResourceLimits("6", "3"),
- },
- ImagePullPolicy: "IfNotPresent",
- TerminationMessagePolicy: "File",
- },
- },
- "Invalid storage limit request": {
- {
- Name: "abc-123",
- Image: "image",
- Resources: core.ResourceRequirements{
- Limits: core.ResourceList{
- core.ResourceName("attachable-volumes-aws-ebs"): *resource.NewQuantity(10, resource.DecimalSI),
- },
- },
- ImagePullPolicy: "IfNotPresent",
- TerminationMessagePolicy: "File",
- },
- },
- "Request limit multiple invalid": {
- {
- Name: "abc-123",
- Image: "image",
- Resources: core.ResourceRequirements{
- Limits: getResourceLimits("5", "3"),
- Requests: getResourceLimits("6", "4"),
- },
- ImagePullPolicy: "IfNotPresent",
- TerminationMessagePolicy: "File",
- },
- },
- "Invalid env from": {
- {
- Name: "env-from-source",
- Image: "image",
- ImagePullPolicy: "IfNotPresent",
- TerminationMessagePolicy: "File",
- EnvFrom: []core.EnvFromSource{
- {
- ConfigMapRef: &core.ConfigMapEnvSource{
- LocalObjectReference: core.LocalObjectReference{
- Name: "$%^&*#",
- },
- },
- },
- },
- },
- },
- }
- for k, v := range errorCases {
- if errs := validateContainers(v, false, volumeDevices, field.NewPath("field")); len(errs) == 0 {
- t.Errorf("expected failure for %s", k)
- }
- }
- }
- func TestValidateInitContainers(t *testing.T) {
- volumeDevices := make(map[string]core.VolumeSource)
- capabilities.SetForTests(capabilities.Capabilities{
- AllowPrivileged: true,
- })
- successCase := []core.Container{
- {
- Name: "container-1-same-host-port-different-protocol",
- Image: "image",
- Ports: []core.ContainerPort{
- {ContainerPort: 80, HostPort: 80, Protocol: "TCP"},
- {ContainerPort: 80, HostPort: 80, Protocol: "UDP"},
- },
- ImagePullPolicy: "IfNotPresent",
- TerminationMessagePolicy: "File",
- },
- {
- Name: "container-2-same-host-port-different-protocol",
- Image: "image",
- Ports: []core.ContainerPort{
- {ContainerPort: 80, HostPort: 80, Protocol: "TCP"},
- {ContainerPort: 80, HostPort: 80, Protocol: "UDP"},
- },
- ImagePullPolicy: "IfNotPresent",
- TerminationMessagePolicy: "File",
- },
- }
- if errs := validateContainers(successCase, true, volumeDevices, field.NewPath("field")); len(errs) != 0 {
- t.Errorf("expected success: %v", errs)
- }
- capabilities.SetForTests(capabilities.Capabilities{
- AllowPrivileged: false,
- })
- errorCases := map[string][]core.Container{
- "duplicate ports": {
- {
- Name: "abc",
- Image: "image",
- Ports: []core.ContainerPort{
- {
- ContainerPort: 8080, HostPort: 8080, Protocol: "TCP",
- },
- {
- ContainerPort: 8080, HostPort: 8080, Protocol: "TCP",
- },
- },
- ImagePullPolicy: "IfNotPresent",
- TerminationMessagePolicy: "File",
- },
- },
- }
- for k, v := range errorCases {
- if errs := validateContainers(v, true, volumeDevices, field.NewPath("field")); len(errs) == 0 {
- t.Errorf("expected failure for %s", k)
- }
- }
- }
- func TestValidateRestartPolicy(t *testing.T) {
- successCases := []core.RestartPolicy{
- core.RestartPolicyAlways,
- core.RestartPolicyOnFailure,
- core.RestartPolicyNever,
- }
- for _, policy := range successCases {
- if errs := validateRestartPolicy(&policy, field.NewPath("field")); len(errs) != 0 {
- t.Errorf("expected success: %v", errs)
- }
- }
- errorCases := []core.RestartPolicy{"", "newpolicy"}
- for k, policy := range errorCases {
- if errs := validateRestartPolicy(&policy, field.NewPath("field")); len(errs) == 0 {
- t.Errorf("expected failure for %d", k)
- }
- }
- }
- func TestValidateDNSPolicy(t *testing.T) {
- successCases := []core.DNSPolicy{core.DNSClusterFirst, core.DNSDefault, core.DNSPolicy(core.DNSClusterFirst), core.DNSNone}
- for _, policy := range successCases {
- if errs := validateDNSPolicy(&policy, field.NewPath("field")); len(errs) != 0 {
- t.Errorf("expected success: %v", errs)
- }
- }
- errorCases := []core.DNSPolicy{core.DNSPolicy("invalid")}
- for _, policy := range errorCases {
- if errs := validateDNSPolicy(&policy, field.NewPath("field")); len(errs) == 0 {
- t.Errorf("expected failure for %v", policy)
- }
- }
- }
- func TestValidatePodDNSConfig(t *testing.T) {
- generateTestSearchPathFunc := func(numChars int) string {
- res := ""
- for i := 0; i < numChars; i++ {
- res = res + "a"
- }
- return res
- }
- testOptionValue := "2"
- testDNSNone := core.DNSNone
- testDNSClusterFirst := core.DNSClusterFirst
- testCases := []struct {
- desc string
- dnsConfig *core.PodDNSConfig
- dnsPolicy *core.DNSPolicy
- expectedError bool
- }{
- {
- desc: "valid: empty DNSConfig",
- dnsConfig: &core.PodDNSConfig{},
- expectedError: false,
- },
- {
- desc: "valid: 1 option",
- dnsConfig: &core.PodDNSConfig{
- Options: []core.PodDNSConfigOption{
- {Name: "ndots", Value: &testOptionValue},
- },
- },
- expectedError: false,
- },
- {
- desc: "valid: 1 nameserver",
- dnsConfig: &core.PodDNSConfig{
- Nameservers: []string{"127.0.0.1"},
- },
- expectedError: false,
- },
- {
- desc: "valid: DNSNone with 1 nameserver",
- dnsConfig: &core.PodDNSConfig{
- Nameservers: []string{"127.0.0.1"},
- },
- dnsPolicy: &testDNSNone,
- expectedError: false,
- },
- {
- desc: "valid: 1 search path",
- dnsConfig: &core.PodDNSConfig{
- Searches: []string{"custom"},
- },
- expectedError: false,
- },
- {
- desc: "valid: 1 search path with trailing period",
- dnsConfig: &core.PodDNSConfig{
- Searches: []string{"custom."},
- },
- expectedError: false,
- },
- {
- desc: "valid: 3 nameservers and 6 search paths",
- dnsConfig: &core.PodDNSConfig{
- Nameservers: []string{"127.0.0.1", "10.0.0.10", "8.8.8.8"},
- Searches: []string{"custom", "mydomain.com", "local", "cluster.local", "svc.cluster.local", "default.svc.cluster.local."},
- },
- expectedError: false,
- },
- {
- desc: "valid: 256 characters in search path list",
- dnsConfig: &core.PodDNSConfig{
- // We can have 256 - (6 - 1) = 251 characters in total for 6 search paths.
- Searches: []string{
- generateTestSearchPathFunc(1),
- generateTestSearchPathFunc(50),
- generateTestSearchPathFunc(50),
- generateTestSearchPathFunc(50),
- generateTestSearchPathFunc(50),
- generateTestSearchPathFunc(50),
- },
- },
- expectedError: false,
- },
- {
- desc: "valid: ipv6 nameserver",
- dnsConfig: &core.PodDNSConfig{
- Nameservers: []string{"FE80::0202:B3FF:FE1E:8329"},
- },
- expectedError: false,
- },
- {
- desc: "invalid: 4 nameservers",
- dnsConfig: &core.PodDNSConfig{
- Nameservers: []string{"127.0.0.1", "10.0.0.10", "8.8.8.8", "1.2.3.4"},
- },
- expectedError: true,
- },
- {
- desc: "invalid: 7 search paths",
- dnsConfig: &core.PodDNSConfig{
- Searches: []string{"custom", "mydomain.com", "local", "cluster.local", "svc.cluster.local", "default.svc.cluster.local", "exceeded"},
- },
- expectedError: true,
- },
- {
- desc: "invalid: 257 characters in search path list",
- dnsConfig: &core.PodDNSConfig{
- // We can have 256 - (6 - 1) = 251 characters in total for 6 search paths.
- Searches: []string{
- generateTestSearchPathFunc(2),
- generateTestSearchPathFunc(50),
- generateTestSearchPathFunc(50),
- generateTestSearchPathFunc(50),
- generateTestSearchPathFunc(50),
- generateTestSearchPathFunc(50),
- },
- },
- expectedError: true,
- },
- {
- desc: "invalid search path",
- dnsConfig: &core.PodDNSConfig{
- Searches: []string{"custom?"},
- },
- expectedError: true,
- },
- {
- desc: "invalid nameserver",
- dnsConfig: &core.PodDNSConfig{
- Nameservers: []string{"invalid"},
- },
- expectedError: true,
- },
- {
- desc: "invalid empty option name",
- dnsConfig: &core.PodDNSConfig{
- Options: []core.PodDNSConfigOption{
- {Value: &testOptionValue},
- },
- },
- expectedError: true,
- },
- {
- desc: "invalid: DNSNone with 0 nameserver",
- dnsConfig: &core.PodDNSConfig{
- Searches: []string{"custom"},
- },
- dnsPolicy: &testDNSNone,
- expectedError: true,
- },
- }
- for _, tc := range testCases {
- if tc.dnsPolicy == nil {
- tc.dnsPolicy = &testDNSClusterFirst
- }
- errs := validatePodDNSConfig(tc.dnsConfig, tc.dnsPolicy, field.NewPath("dnsConfig"))
- if len(errs) != 0 && !tc.expectedError {
- t.Errorf("%v: validatePodDNSConfig(%v) = %v, want nil", tc.desc, tc.dnsConfig, errs)
- } else if len(errs) == 0 && tc.expectedError {
- t.Errorf("%v: validatePodDNSConfig(%v) = nil, want error", tc.desc, tc.dnsConfig)
- }
- }
- }
- func TestValidatePodReadinessGates(t *testing.T) {
- successCases := []struct {
- desc string
- readinessGates []core.PodReadinessGate
- }{
- {
- "no gate",
- []core.PodReadinessGate{},
- },
- {
- "one readiness gate",
- []core.PodReadinessGate{
- {
- ConditionType: core.PodConditionType("example.com/condition"),
- },
- },
- },
- {
- "two readiness gates",
- []core.PodReadinessGate{
- {
- ConditionType: core.PodConditionType("example.com/condition1"),
- },
- {
- ConditionType: core.PodConditionType("example.com/condition2"),
- },
- },
- },
- }
- for _, tc := range successCases {
- if errs := validateReadinessGates(tc.readinessGates, field.NewPath("field")); len(errs) != 0 {
- t.Errorf("expect tc %q to success: %v", tc.desc, errs)
- }
- }
- errorCases := []struct {
- desc string
- readinessGates []core.PodReadinessGate
- }{
- {
- "invalid condition type",
- []core.PodReadinessGate{
- {
- ConditionType: core.PodConditionType("invalid/condition/type"),
- },
- },
- },
- }
- for _, tc := range errorCases {
- if errs := validateReadinessGates(tc.readinessGates, field.NewPath("field")); len(errs) == 0 {
- t.Errorf("expected tc %q to fail", tc.desc)
- }
- }
- }
- func TestValidatePodConditions(t *testing.T) {
- successCases := []struct {
- desc string
- podConditions []core.PodCondition
- }{
- {
- "no condition",
- []core.PodCondition{},
- },
- {
- "one system condition",
- []core.PodCondition{
- {
- Type: core.PodReady,
- Status: core.ConditionTrue,
- },
- },
- },
- {
- "one system condition and one custom condition",
- []core.PodCondition{
- {
- Type: core.PodReady,
- Status: core.ConditionTrue,
- },
- {
- Type: core.PodConditionType("example.com/condition"),
- Status: core.ConditionFalse,
- },
- },
- },
- {
- "two custom condition",
- []core.PodCondition{
- {
- Type: core.PodConditionType("foobar"),
- Status: core.ConditionTrue,
- },
- {
- Type: core.PodConditionType("example.com/condition"),
- Status: core.ConditionFalse,
- },
- },
- },
- }
- for _, tc := range successCases {
- if errs := validatePodConditions(tc.podConditions, field.NewPath("field")); len(errs) != 0 {
- t.Errorf("expected tc %q to success, but got: %v", tc.desc, errs)
- }
- }
- errorCases := []struct {
- desc string
- podConditions []core.PodCondition
- }{
- {
- "one system condition and a invalid custom condition",
- []core.PodCondition{
- {
- Type: core.PodReady,
- Status: core.ConditionStatus("True"),
- },
- {
- Type: core.PodConditionType("invalid/custom/condition"),
- Status: core.ConditionStatus("True"),
- },
- },
- },
- }
- for _, tc := range errorCases {
- if errs := validatePodConditions(tc.podConditions, field.NewPath("field")); len(errs) == 0 {
- t.Errorf("expected tc %q to fail", tc.desc)
- }
- }
- }
- func TestValidatePodSpec(t *testing.T) {
- activeDeadlineSeconds := int64(30)
- activeDeadlineSecondsMax := int64(math.MaxInt32)
- minUserID := int64(0)
- maxUserID := int64(2147483647)
- minGroupID := int64(0)
- maxGroupID := int64(2147483647)
- defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.PodPriority, true)()
- defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.RuntimeClass, true)()
- successCases := []core.PodSpec{
- { // Populate basic fields, leave defaults for most.
- Volumes: []core.Volume{{Name: "vol", VolumeSource: core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{}}}},
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- },
- { // Populate all fields.
- Volumes: []core.Volume{
- {Name: "vol", VolumeSource: core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{}}},
- },
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- InitContainers: []core.Container{{Name: "ictr", Image: "iimage", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- RestartPolicy: core.RestartPolicyAlways,
- NodeSelector: map[string]string{
- "key": "value",
- },
- NodeName: "foobar",
- DNSPolicy: core.DNSClusterFirst,
- ActiveDeadlineSeconds: &activeDeadlineSeconds,
- ServiceAccountName: "acct",
- },
- { // Populate all fields with larger active deadline.
- Volumes: []core.Volume{
- {Name: "vol", VolumeSource: core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{}}},
- },
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- InitContainers: []core.Container{{Name: "ictr", Image: "iimage", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- RestartPolicy: core.RestartPolicyAlways,
- NodeSelector: map[string]string{
- "key": "value",
- },
- NodeName: "foobar",
- DNSPolicy: core.DNSClusterFirst,
- ActiveDeadlineSeconds: &activeDeadlineSecondsMax,
- ServiceAccountName: "acct",
- },
- { // Populate HostNetwork.
- Containers: []core.Container{
- {Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File",
- Ports: []core.ContainerPort{
- {HostPort: 8080, ContainerPort: 8080, Protocol: "TCP"}},
- },
- },
- SecurityContext: &core.PodSecurityContext{
- HostNetwork: true,
- },
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- },
- { // Populate RunAsUser SupplementalGroups FSGroup with minID 0
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- SecurityContext: &core.PodSecurityContext{
- SupplementalGroups: []int64{minGroupID},
- RunAsUser: &minUserID,
- FSGroup: &minGroupID,
- },
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- },
- { // Populate RunAsUser SupplementalGroups FSGroup with maxID 2147483647
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- SecurityContext: &core.PodSecurityContext{
- SupplementalGroups: []int64{maxGroupID},
- RunAsUser: &maxUserID,
- FSGroup: &maxGroupID,
- },
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- },
- { // Populate HostIPC.
- SecurityContext: &core.PodSecurityContext{
- HostIPC: true,
- },
- Volumes: []core.Volume{{Name: "vol", VolumeSource: core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{}}}},
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- },
- { // Populate HostPID.
- SecurityContext: &core.PodSecurityContext{
- HostPID: true,
- },
- Volumes: []core.Volume{{Name: "vol", VolumeSource: core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{}}}},
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- },
- { // Populate Affinity.
- Volumes: []core.Volume{{Name: "vol", VolumeSource: core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{}}}},
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- },
- { // Populate HostAliases.
- HostAliases: []core.HostAlias{{IP: "12.34.56.78", Hostnames: []string{"host1", "host2"}}},
- Volumes: []core.Volume{{Name: "vol", VolumeSource: core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{}}}},
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- },
- { // Populate HostAliases with `foo.bar` hostnames.
- HostAliases: []core.HostAlias{{IP: "12.34.56.78", Hostnames: []string{"host1.foo", "host2.bar"}}},
- Volumes: []core.Volume{{Name: "vol", VolumeSource: core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{}}}},
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- },
- { // Populate HostAliases with HostNetwork.
- HostAliases: []core.HostAlias{{IP: "12.34.56.78", Hostnames: []string{"host1.foo", "host2.bar"}}},
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- SecurityContext: &core.PodSecurityContext{
- HostNetwork: true,
- },
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- },
- { // Populate PriorityClassName.
- Volumes: []core.Volume{{Name: "vol", VolumeSource: core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{}}}},
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- PriorityClassName: "valid-name",
- },
- { // Populate ShareProcessNamespace
- Volumes: []core.Volume{{Name: "vol", VolumeSource: core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{}}}},
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- SecurityContext: &core.PodSecurityContext{
- ShareProcessNamespace: &[]bool{true}[0],
- },
- },
- { // Populate RuntimeClassName
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- RuntimeClassName: utilpointer.StringPtr("valid-sandbox"),
- },
- }
- for i := range successCases {
- if errs := ValidatePodSpec(&successCases[i], field.NewPath("field")); len(errs) != 0 {
- t.Errorf("expected success: %v", errs)
- }
- }
- activeDeadlineSeconds = int64(0)
- activeDeadlineSecondsTooLarge := int64(math.MaxInt32 + 1)
- minUserID = int64(-1)
- maxUserID = int64(2147483648)
- minGroupID = int64(-1)
- maxGroupID = int64(2147483648)
- failureCases := map[string]core.PodSpec{
- "bad volume": {
- Volumes: []core.Volume{{}},
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- },
- "no containers": {
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- },
- "bad container": {
- Containers: []core.Container{{}},
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- },
- "bad init container": {
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- InitContainers: []core.Container{{}},
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- },
- "bad DNS policy": {
- DNSPolicy: core.DNSPolicy("invalid"),
- RestartPolicy: core.RestartPolicyAlways,
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- },
- "bad service account name": {
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- ServiceAccountName: "invalidName",
- },
- "bad restart policy": {
- RestartPolicy: "UnknowPolicy",
- DNSPolicy: core.DNSClusterFirst,
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- },
- "with hostNetwork hostPort not equal to containerPort": {
- Containers: []core.Container{
- {Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", Ports: []core.ContainerPort{
- {HostPort: 8080, ContainerPort: 2600, Protocol: "TCP"}},
- },
- },
- SecurityContext: &core.PodSecurityContext{
- HostNetwork: true,
- },
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- },
- "with hostAliases with invalid IP": {
- SecurityContext: &core.PodSecurityContext{
- HostNetwork: false,
- },
- HostAliases: []core.HostAlias{{IP: "999.999.999.999", Hostnames: []string{"host1", "host2"}}},
- },
- "with hostAliases with invalid hostname": {
- SecurityContext: &core.PodSecurityContext{
- HostNetwork: false,
- },
- HostAliases: []core.HostAlias{{IP: "12.34.56.78", Hostnames: []string{"@#$^#@#$"}}},
- },
- "bad supplementalGroups large than math.MaxInt32": {
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- SecurityContext: &core.PodSecurityContext{
- HostNetwork: false,
- SupplementalGroups: []int64{maxGroupID, 1234},
- },
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- },
- "bad supplementalGroups less than 0": {
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- SecurityContext: &core.PodSecurityContext{
- HostNetwork: false,
- SupplementalGroups: []int64{minGroupID, 1234},
- },
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- },
- "bad runAsUser large than math.MaxInt32": {
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- SecurityContext: &core.PodSecurityContext{
- HostNetwork: false,
- RunAsUser: &maxUserID,
- },
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- },
- "bad runAsUser less than 0": {
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- SecurityContext: &core.PodSecurityContext{
- HostNetwork: false,
- RunAsUser: &minUserID,
- },
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- },
- "bad fsGroup large than math.MaxInt32": {
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- SecurityContext: &core.PodSecurityContext{
- HostNetwork: false,
- FSGroup: &maxGroupID,
- },
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- },
- "bad fsGroup less than 0": {
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- SecurityContext: &core.PodSecurityContext{
- HostNetwork: false,
- FSGroup: &minGroupID,
- },
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- },
- "bad-active-deadline-seconds": {
- Volumes: []core.Volume{
- {Name: "vol", VolumeSource: core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{}}},
- },
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- RestartPolicy: core.RestartPolicyAlways,
- NodeSelector: map[string]string{
- "key": "value",
- },
- NodeName: "foobar",
- DNSPolicy: core.DNSClusterFirst,
- ActiveDeadlineSeconds: &activeDeadlineSeconds,
- },
- "active-deadline-seconds-too-large": {
- Volumes: []core.Volume{
- {Name: "vol", VolumeSource: core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{}}},
- },
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- RestartPolicy: core.RestartPolicyAlways,
- NodeSelector: map[string]string{
- "key": "value",
- },
- NodeName: "foobar",
- DNSPolicy: core.DNSClusterFirst,
- ActiveDeadlineSeconds: &activeDeadlineSecondsTooLarge,
- },
- "bad nodeName": {
- NodeName: "node name",
- Volumes: []core.Volume{{Name: "vol", VolumeSource: core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{}}}},
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- },
- "bad PriorityClassName": {
- Volumes: []core.Volume{{Name: "vol", VolumeSource: core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{}}}},
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- PriorityClassName: "InvalidName",
- },
- "ShareProcessNamespace and HostPID both set": {
- Volumes: []core.Volume{{Name: "vol", VolumeSource: core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{}}}},
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- SecurityContext: &core.PodSecurityContext{
- HostPID: true,
- ShareProcessNamespace: &[]bool{true}[0],
- },
- },
- "bad RuntimeClassName": {
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- RuntimeClassName: utilpointer.StringPtr("invalid/sandbox"),
- },
- }
- for k, v := range failureCases {
- if errs := ValidatePodSpec(&v, field.NewPath("field")); len(errs) == 0 {
- t.Errorf("expected failure for %q", k)
- }
- }
- }
- func extendPodSpecwithTolerations(in core.PodSpec, tolerations []core.Toleration) core.PodSpec {
- var out core.PodSpec
- out.Containers = in.Containers
- out.RestartPolicy = in.RestartPolicy
- out.DNSPolicy = in.DNSPolicy
- out.Tolerations = tolerations
- return out
- }
- func TestValidatePod(t *testing.T) {
- validPodSpec := func(affinity *core.Affinity) core.PodSpec {
- spec := core.PodSpec{
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- }
- if affinity != nil {
- spec.Affinity = affinity
- }
- return spec
- }
- successCases := []core.Pod{
- { // Basic fields.
- ObjectMeta: metav1.ObjectMeta{Name: "123", Namespace: "ns"},
- Spec: core.PodSpec{
- Volumes: []core.Volume{{Name: "vol", VolumeSource: core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{}}}},
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- },
- },
- { // Just about everything.
- ObjectMeta: metav1.ObjectMeta{Name: "abc.123.do-re-mi", Namespace: "ns"},
- Spec: core.PodSpec{
- Volumes: []core.Volume{
- {Name: "vol", VolumeSource: core.VolumeSource{EmptyDir: &core.EmptyDirVolumeSource{}}},
- },
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- NodeSelector: map[string]string{
- "key": "value",
- },
- NodeName: "foobar",
- },
- },
- { // Serialized node affinity requirements.
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- },
- Spec: validPodSpec(
- // TODO: Uncomment and move this block and move inside NodeAffinity once
- // RequiredDuringSchedulingRequiredDuringExecution is implemented
- // RequiredDuringSchedulingRequiredDuringExecution: &core.NodeSelector{
- // NodeSelectorTerms: []core.NodeSelectorTerm{
- // {
- // MatchExpressions: []core.NodeSelectorRequirement{
- // {
- // Key: "key1",
- // Operator: core.NodeSelectorOpExists
- // },
- // },
- // },
- // },
- // },
- &core.Affinity{
- NodeAffinity: &core.NodeAffinity{
- RequiredDuringSchedulingIgnoredDuringExecution: &core.NodeSelector{
- NodeSelectorTerms: []core.NodeSelectorTerm{
- {
- MatchExpressions: []core.NodeSelectorRequirement{
- {
- Key: "key2",
- Operator: core.NodeSelectorOpIn,
- Values: []string{"value1", "value2"},
- },
- },
- MatchFields: []core.NodeSelectorRequirement{
- {
- Key: "metadata.name",
- Operator: core.NodeSelectorOpIn,
- Values: []string{"host1"},
- },
- },
- },
- },
- },
- PreferredDuringSchedulingIgnoredDuringExecution: []core.PreferredSchedulingTerm{
- {
- Weight: 10,
- Preference: core.NodeSelectorTerm{
- MatchExpressions: []core.NodeSelectorRequirement{
- {
- Key: "foo",
- Operator: core.NodeSelectorOpIn,
- Values: []string{"bar"},
- },
- },
- },
- },
- },
- },
- },
- ),
- },
- { // Serialized node affinity requirements.
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- },
- Spec: validPodSpec(
- // TODO: Uncomment and move this block and move inside NodeAffinity once
- // RequiredDuringSchedulingRequiredDuringExecution is implemented
- // RequiredDuringSchedulingRequiredDuringExecution: &core.NodeSelector{
- // NodeSelectorTerms: []core.NodeSelectorTerm{
- // {
- // MatchExpressions: []core.NodeSelectorRequirement{
- // {
- // Key: "key1",
- // Operator: core.NodeSelectorOpExists
- // },
- // },
- // },
- // },
- // },
- &core.Affinity{
- NodeAffinity: &core.NodeAffinity{
- RequiredDuringSchedulingIgnoredDuringExecution: &core.NodeSelector{
- NodeSelectorTerms: []core.NodeSelectorTerm{
- {
- MatchExpressions: []core.NodeSelectorRequirement{},
- },
- },
- },
- PreferredDuringSchedulingIgnoredDuringExecution: []core.PreferredSchedulingTerm{
- {
- Weight: 10,
- Preference: core.NodeSelectorTerm{
- MatchExpressions: []core.NodeSelectorRequirement{},
- },
- },
- },
- },
- },
- ),
- },
- { // Serialized pod affinity in affinity requirements in annotations.
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- // TODO: Uncomment and move this block into Annotations map once
- // RequiredDuringSchedulingRequiredDuringExecution is implemented
- // "requiredDuringSchedulingRequiredDuringExecution": [{
- // "labelSelector": {
- // "matchExpressions": [{
- // "key": "key2",
- // "operator": "In",
- // "values": ["value1", "value2"]
- // }]
- // },
- // "namespaces":["ns"],
- // "topologyKey": "zone"
- // }]
- },
- Spec: validPodSpec(&core.Affinity{
- PodAffinity: &core.PodAffinity{
- RequiredDuringSchedulingIgnoredDuringExecution: []core.PodAffinityTerm{
- {
- LabelSelector: &metav1.LabelSelector{
- MatchExpressions: []metav1.LabelSelectorRequirement{
- {
- Key: "key2",
- Operator: metav1.LabelSelectorOpIn,
- Values: []string{"value1", "value2"},
- },
- },
- },
- TopologyKey: "zone",
- Namespaces: []string{"ns"},
- },
- },
- PreferredDuringSchedulingIgnoredDuringExecution: []core.WeightedPodAffinityTerm{
- {
- Weight: 10,
- PodAffinityTerm: core.PodAffinityTerm{
- LabelSelector: &metav1.LabelSelector{
- MatchExpressions: []metav1.LabelSelectorRequirement{
- {
- Key: "key2",
- Operator: metav1.LabelSelectorOpNotIn,
- Values: []string{"value1", "value2"},
- },
- },
- },
- Namespaces: []string{"ns"},
- TopologyKey: "region",
- },
- },
- },
- },
- }),
- },
- { // Serialized pod anti affinity with different Label Operators in affinity requirements in annotations.
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- // TODO: Uncomment and move this block into Annotations map once
- // RequiredDuringSchedulingRequiredDuringExecution is implemented
- // "requiredDuringSchedulingRequiredDuringExecution": [{
- // "labelSelector": {
- // "matchExpressions": [{
- // "key": "key2",
- // "operator": "In",
- // "values": ["value1", "value2"]
- // }]
- // },
- // "namespaces":["ns"],
- // "topologyKey": "zone"
- // }]
- },
- Spec: validPodSpec(&core.Affinity{
- PodAntiAffinity: &core.PodAntiAffinity{
- RequiredDuringSchedulingIgnoredDuringExecution: []core.PodAffinityTerm{
- {
- LabelSelector: &metav1.LabelSelector{
- MatchExpressions: []metav1.LabelSelectorRequirement{
- {
- Key: "key2",
- Operator: metav1.LabelSelectorOpExists,
- },
- },
- },
- TopologyKey: "zone",
- Namespaces: []string{"ns"},
- },
- },
- PreferredDuringSchedulingIgnoredDuringExecution: []core.WeightedPodAffinityTerm{
- {
- Weight: 10,
- PodAffinityTerm: core.PodAffinityTerm{
- LabelSelector: &metav1.LabelSelector{
- MatchExpressions: []metav1.LabelSelectorRequirement{
- {
- Key: "key2",
- Operator: metav1.LabelSelectorOpDoesNotExist,
- },
- },
- },
- Namespaces: []string{"ns"},
- TopologyKey: "region",
- },
- },
- },
- },
- }),
- },
- { // populate forgiveness tolerations with exists operator in annotations.
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- },
- Spec: extendPodSpecwithTolerations(validPodSpec(nil), []core.Toleration{{Key: "foo", Operator: "Exists", Value: "", Effect: "NoExecute", TolerationSeconds: &[]int64{60}[0]}}),
- },
- { // populate forgiveness tolerations with equal operator in annotations.
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- },
- Spec: extendPodSpecwithTolerations(validPodSpec(nil), []core.Toleration{{Key: "foo", Operator: "Equal", Value: "bar", Effect: "NoExecute", TolerationSeconds: &[]int64{60}[0]}}),
- },
- { // populate tolerations equal operator in annotations.
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- },
- Spec: extendPodSpecwithTolerations(validPodSpec(nil), []core.Toleration{{Key: "foo", Operator: "Equal", Value: "bar", Effect: "NoSchedule"}}),
- },
- { // populate tolerations exists operator in annotations.
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- },
- Spec: validPodSpec(nil),
- },
- { // empty key with Exists operator is OK for toleration, empty toleration key means match all taint keys.
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- },
- Spec: extendPodSpecwithTolerations(validPodSpec(nil), []core.Toleration{{Operator: "Exists", Effect: "NoSchedule"}}),
- },
- { // empty operator is OK for toleration, defaults to Equal.
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- },
- Spec: extendPodSpecwithTolerations(validPodSpec(nil), []core.Toleration{{Key: "foo", Value: "bar", Effect: "NoSchedule"}}),
- },
- { // empty effect is OK for toleration, empty toleration effect means match all taint effects.
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- },
- Spec: extendPodSpecwithTolerations(validPodSpec(nil), []core.Toleration{{Key: "foo", Operator: "Equal", Value: "bar"}}),
- },
- { // negative tolerationSeconds is OK for toleration.
- ObjectMeta: metav1.ObjectMeta{
- Name: "pod-forgiveness-invalid",
- Namespace: "ns",
- },
- Spec: extendPodSpecwithTolerations(validPodSpec(nil), []core.Toleration{{Key: "node.kubernetes.io/not-ready", Operator: "Exists", Effect: "NoExecute", TolerationSeconds: &[]int64{-2}[0]}}),
- },
- { // runtime default seccomp profile
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- Annotations: map[string]string{
- core.SeccompPodAnnotationKey: core.SeccompProfileRuntimeDefault,
- },
- },
- Spec: validPodSpec(nil),
- },
- { // docker default seccomp profile
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- Annotations: map[string]string{
- core.SeccompPodAnnotationKey: core.DeprecatedSeccompProfileDockerDefault,
- },
- },
- Spec: validPodSpec(nil),
- },
- { // unconfined seccomp profile
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- Annotations: map[string]string{
- core.SeccompPodAnnotationKey: "unconfined",
- },
- },
- Spec: validPodSpec(nil),
- },
- { // localhost seccomp profile
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- Annotations: map[string]string{
- core.SeccompPodAnnotationKey: "localhost/foo",
- },
- },
- Spec: validPodSpec(nil),
- },
- { // localhost seccomp profile for a container
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- Annotations: map[string]string{
- core.SeccompContainerAnnotationKeyPrefix + "foo": "localhost/foo",
- },
- },
- Spec: validPodSpec(nil),
- },
- { // default AppArmor profile for a container
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- Annotations: map[string]string{
- apparmor.ContainerAnnotationKeyPrefix + "ctr": apparmor.ProfileRuntimeDefault,
- },
- },
- Spec: validPodSpec(nil),
- },
- { // default AppArmor profile for an init container
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- Annotations: map[string]string{
- apparmor.ContainerAnnotationKeyPrefix + "init-ctr": apparmor.ProfileRuntimeDefault,
- },
- },
- Spec: core.PodSpec{
- InitContainers: []core.Container{{Name: "init-ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- },
- },
- { // localhost AppArmor profile for a container
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- Annotations: map[string]string{
- apparmor.ContainerAnnotationKeyPrefix + "ctr": apparmor.ProfileNamePrefix + "foo",
- },
- },
- Spec: validPodSpec(nil),
- },
- { // syntactically valid sysctls
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- },
- Spec: core.PodSpec{
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- SecurityContext: &core.PodSecurityContext{
- Sysctls: []core.Sysctl{
- {
- Name: "kernel.shmmni",
- Value: "32768",
- },
- {
- Name: "kernel.shmmax",
- Value: "1000000000",
- },
- {
- Name: "knet.ipv4.route.min_pmtu",
- Value: "1000",
- },
- },
- },
- },
- },
- { // valid extended resources for init container
- ObjectMeta: metav1.ObjectMeta{Name: "valid-extended", Namespace: "ns"},
- Spec: core.PodSpec{
- InitContainers: []core.Container{
- {
- Name: "valid-extended",
- Image: "image",
- ImagePullPolicy: "IfNotPresent",
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName("example.com/a"): resource.MustParse("10"),
- },
- Limits: core.ResourceList{
- core.ResourceName("example.com/a"): resource.MustParse("10"),
- },
- },
- TerminationMessagePolicy: "File",
- },
- },
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- },
- },
- { // valid extended resources for regular container
- ObjectMeta: metav1.ObjectMeta{Name: "valid-extended", Namespace: "ns"},
- Spec: core.PodSpec{
- InitContainers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- Containers: []core.Container{
- {
- Name: "valid-extended",
- Image: "image",
- ImagePullPolicy: "IfNotPresent",
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName("example.com/a"): resource.MustParse("10"),
- },
- Limits: core.ResourceList{
- core.ResourceName("example.com/a"): resource.MustParse("10"),
- },
- },
- TerminationMessagePolicy: "File",
- },
- },
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- },
- },
- { // valid serviceaccount token projected volume with serviceaccount name specified
- ObjectMeta: metav1.ObjectMeta{Name: "valid-extended", Namespace: "ns"},
- Spec: core.PodSpec{
- ServiceAccountName: "some-service-account",
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- Volumes: []core.Volume{
- {
- Name: "projected-volume",
- VolumeSource: core.VolumeSource{
- Projected: &core.ProjectedVolumeSource{
- Sources: []core.VolumeProjection{
- {
- ServiceAccountToken: &core.ServiceAccountTokenProjection{
- Audience: "foo-audience",
- ExpirationSeconds: 6000,
- Path: "foo-path",
- },
- },
- },
- },
- },
- },
- },
- },
- },
- }
- for _, pod := range successCases {
- if errs := ValidatePod(&pod); len(errs) != 0 {
- t.Errorf("expected success: %v", errs)
- }
- }
- errorCases := map[string]struct {
- spec core.Pod
- expectedError string
- }{
- "bad name": {
- expectedError: "metadata.name",
- spec: core.Pod{
- ObjectMeta: metav1.ObjectMeta{Name: "", Namespace: "ns"},
- Spec: core.PodSpec{
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- },
- },
- },
- "image whitespace": {
- expectedError: "spec.containers[0].image",
- spec: core.Pod{
- ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: "ns"},
- Spec: core.PodSpec{
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- Containers: []core.Container{{Name: "ctr", Image: " ", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- },
- },
- },
- "image leading and trailing whitespace": {
- expectedError: "spec.containers[0].image",
- spec: core.Pod{
- ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: "ns"},
- Spec: core.PodSpec{
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- Containers: []core.Container{{Name: "ctr", Image: " something ", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- },
- },
- },
- "bad namespace": {
- expectedError: "metadata.namespace",
- spec: core.Pod{
- ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: ""},
- Spec: core.PodSpec{
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- },
- },
- },
- "bad spec": {
- expectedError: "spec.containers[0].name",
- spec: core.Pod{
- ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: "ns"},
- Spec: core.PodSpec{
- Containers: []core.Container{{}},
- },
- },
- },
- "bad label": {
- expectedError: "NoUppercaseOrSpecialCharsLike=Equals",
- spec: core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "abc",
- Namespace: "ns",
- Labels: map[string]string{
- "NoUppercaseOrSpecialCharsLike=Equals": "bar",
- },
- },
- Spec: core.PodSpec{
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- },
- },
- },
- "invalid node selector requirement in node affinity, operator can't be null": {
- expectedError: "spec.affinity.nodeAffinity.requiredDuringSchedulingIgnoredDuringExecution.nodeSelectorTerms[0].matchExpressions[0].operator",
- spec: core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- },
- Spec: validPodSpec(&core.Affinity{
- NodeAffinity: &core.NodeAffinity{
- RequiredDuringSchedulingIgnoredDuringExecution: &core.NodeSelector{
- NodeSelectorTerms: []core.NodeSelectorTerm{
- {
- MatchExpressions: []core.NodeSelectorRequirement{
- {
- Key: "key1",
- },
- },
- },
- },
- },
- },
- }),
- },
- },
- "invalid node selector requirement in node affinity, key is invalid": {
- expectedError: "spec.affinity.nodeAffinity.requiredDuringSchedulingIgnoredDuringExecution.nodeSelectorTerms[0].matchExpressions[0].key",
- spec: core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- },
- Spec: validPodSpec(&core.Affinity{
- NodeAffinity: &core.NodeAffinity{
- RequiredDuringSchedulingIgnoredDuringExecution: &core.NodeSelector{
- NodeSelectorTerms: []core.NodeSelectorTerm{
- {
- MatchExpressions: []core.NodeSelectorRequirement{
- {
- Key: "invalid key ___@#",
- Operator: core.NodeSelectorOpExists,
- },
- },
- },
- },
- },
- },
- }),
- },
- },
- "invalid node field selector requirement in node affinity, more values for field selector": {
- expectedError: "spec.affinity.nodeAffinity.requiredDuringSchedulingIgnoredDuringExecution.nodeSelectorTerms[0].matchFields[0].values",
- spec: core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- },
- Spec: validPodSpec(&core.Affinity{
- NodeAffinity: &core.NodeAffinity{
- RequiredDuringSchedulingIgnoredDuringExecution: &core.NodeSelector{
- NodeSelectorTerms: []core.NodeSelectorTerm{
- {
- MatchFields: []core.NodeSelectorRequirement{
- {
- Key: "metadata.name",
- Operator: core.NodeSelectorOpIn,
- Values: []string{"host1", "host2"},
- },
- },
- },
- },
- },
- },
- }),
- },
- },
- "invalid node field selector requirement in node affinity, invalid operator": {
- expectedError: "spec.affinity.nodeAffinity.requiredDuringSchedulingIgnoredDuringExecution.nodeSelectorTerms[0].matchFields[0].operator",
- spec: core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- },
- Spec: validPodSpec(&core.Affinity{
- NodeAffinity: &core.NodeAffinity{
- RequiredDuringSchedulingIgnoredDuringExecution: &core.NodeSelector{
- NodeSelectorTerms: []core.NodeSelectorTerm{
- {
- MatchFields: []core.NodeSelectorRequirement{
- {
- Key: "metadata.name",
- Operator: core.NodeSelectorOpExists,
- },
- },
- },
- },
- },
- },
- }),
- },
- },
- "invalid node field selector requirement in node affinity, invalid key": {
- expectedError: "spec.affinity.nodeAffinity.requiredDuringSchedulingIgnoredDuringExecution.nodeSelectorTerms[0].matchFields[0].key",
- spec: core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- },
- Spec: validPodSpec(&core.Affinity{
- NodeAffinity: &core.NodeAffinity{
- RequiredDuringSchedulingIgnoredDuringExecution: &core.NodeSelector{
- NodeSelectorTerms: []core.NodeSelectorTerm{
- {
- MatchFields: []core.NodeSelectorRequirement{
- {
- Key: "metadata.namespace",
- Operator: core.NodeSelectorOpIn,
- Values: []string{"ns1"},
- },
- },
- },
- },
- },
- },
- }),
- },
- },
- "invalid preferredSchedulingTerm in node affinity, weight should be in range 1-100": {
- expectedError: "must be in the range 1-100",
- spec: core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- },
- Spec: validPodSpec(&core.Affinity{
- NodeAffinity: &core.NodeAffinity{
- PreferredDuringSchedulingIgnoredDuringExecution: []core.PreferredSchedulingTerm{
- {
- Weight: 199,
- Preference: core.NodeSelectorTerm{
- MatchExpressions: []core.NodeSelectorRequirement{
- {
- Key: "foo",
- Operator: core.NodeSelectorOpIn,
- Values: []string{"bar"},
- },
- },
- },
- },
- },
- },
- }),
- },
- },
- "invalid requiredDuringSchedulingIgnoredDuringExecution node selector, nodeSelectorTerms must have at least one term": {
- expectedError: "spec.affinity.nodeAffinity.requiredDuringSchedulingIgnoredDuringExecution.nodeSelectorTerms",
- spec: core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- },
- Spec: validPodSpec(&core.Affinity{
- NodeAffinity: &core.NodeAffinity{
- RequiredDuringSchedulingIgnoredDuringExecution: &core.NodeSelector{
- NodeSelectorTerms: []core.NodeSelectorTerm{},
- },
- },
- }),
- },
- },
- "invalid weight in preferredDuringSchedulingIgnoredDuringExecution in pod affinity annotations, weight should be in range 1-100": {
- expectedError: "must be in the range 1-100",
- spec: core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- },
- Spec: validPodSpec(&core.Affinity{
- PodAffinity: &core.PodAffinity{
- PreferredDuringSchedulingIgnoredDuringExecution: []core.WeightedPodAffinityTerm{
- {
- Weight: 109,
- PodAffinityTerm: core.PodAffinityTerm{
- LabelSelector: &metav1.LabelSelector{
- MatchExpressions: []metav1.LabelSelectorRequirement{
- {
- Key: "key2",
- Operator: metav1.LabelSelectorOpNotIn,
- Values: []string{"value1", "value2"},
- },
- },
- },
- Namespaces: []string{"ns"},
- TopologyKey: "region",
- },
- },
- },
- },
- }),
- },
- },
- "invalid labelSelector in preferredDuringSchedulingIgnoredDuringExecution in podaffinity annotations, values should be empty if the operator is Exists": {
- expectedError: "spec.affinity.podAntiAffinity.preferredDuringSchedulingIgnoredDuringExecution[0].podAffinityTerm.matchExpressions.matchExpressions[0].values",
- spec: core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- },
- Spec: validPodSpec(&core.Affinity{
- PodAntiAffinity: &core.PodAntiAffinity{
- PreferredDuringSchedulingIgnoredDuringExecution: []core.WeightedPodAffinityTerm{
- {
- Weight: 10,
- PodAffinityTerm: core.PodAffinityTerm{
- LabelSelector: &metav1.LabelSelector{
- MatchExpressions: []metav1.LabelSelectorRequirement{
- {
- Key: "key2",
- Operator: metav1.LabelSelectorOpExists,
- Values: []string{"value1", "value2"},
- },
- },
- },
- Namespaces: []string{"ns"},
- TopologyKey: "region",
- },
- },
- },
- },
- }),
- },
- },
- "invalid name space in preferredDuringSchedulingIgnoredDuringExecution in podaffinity annotations, name space shouldbe valid": {
- expectedError: "spec.affinity.podAffinity.preferredDuringSchedulingIgnoredDuringExecution[0].podAffinityTerm.namespace",
- spec: core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- },
- Spec: validPodSpec(&core.Affinity{
- PodAffinity: &core.PodAffinity{
- PreferredDuringSchedulingIgnoredDuringExecution: []core.WeightedPodAffinityTerm{
- {
- Weight: 10,
- PodAffinityTerm: core.PodAffinityTerm{
- LabelSelector: &metav1.LabelSelector{
- MatchExpressions: []metav1.LabelSelectorRequirement{
- {
- Key: "key2",
- Operator: metav1.LabelSelectorOpExists,
- },
- },
- },
- Namespaces: []string{"INVALID_NAMESPACE"},
- TopologyKey: "region",
- },
- },
- },
- },
- }),
- },
- },
- "invalid hard pod affinity, empty topologyKey is not allowed for hard pod affinity": {
- expectedError: "can not be empty",
- spec: core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- },
- Spec: validPodSpec(&core.Affinity{
- PodAffinity: &core.PodAffinity{
- RequiredDuringSchedulingIgnoredDuringExecution: []core.PodAffinityTerm{
- {
- LabelSelector: &metav1.LabelSelector{
- MatchExpressions: []metav1.LabelSelectorRequirement{
- {
- Key: "key2",
- Operator: metav1.LabelSelectorOpIn,
- Values: []string{"value1", "value2"},
- },
- },
- },
- Namespaces: []string{"ns"},
- },
- },
- },
- }),
- },
- },
- "invalid hard pod anti-affinity, empty topologyKey is not allowed for hard pod anti-affinity": {
- expectedError: "can not be empty",
- spec: core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- },
- Spec: validPodSpec(&core.Affinity{
- PodAntiAffinity: &core.PodAntiAffinity{
- RequiredDuringSchedulingIgnoredDuringExecution: []core.PodAffinityTerm{
- {
- LabelSelector: &metav1.LabelSelector{
- MatchExpressions: []metav1.LabelSelectorRequirement{
- {
- Key: "key2",
- Operator: metav1.LabelSelectorOpIn,
- Values: []string{"value1", "value2"},
- },
- },
- },
- Namespaces: []string{"ns"},
- },
- },
- },
- }),
- },
- },
- "invalid soft pod affinity, empty topologyKey is not allowed for soft pod affinity": {
- expectedError: "can not be empty",
- spec: core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- },
- Spec: validPodSpec(&core.Affinity{
- PodAffinity: &core.PodAffinity{
- PreferredDuringSchedulingIgnoredDuringExecution: []core.WeightedPodAffinityTerm{
- {
- Weight: 10,
- PodAffinityTerm: core.PodAffinityTerm{
- LabelSelector: &metav1.LabelSelector{
- MatchExpressions: []metav1.LabelSelectorRequirement{
- {
- Key: "key2",
- Operator: metav1.LabelSelectorOpNotIn,
- Values: []string{"value1", "value2"},
- },
- },
- },
- Namespaces: []string{"ns"},
- },
- },
- },
- },
- }),
- },
- },
- "invalid soft pod anti-affinity, empty topologyKey is not allowed for soft pod anti-affinity": {
- expectedError: "can not be empty",
- spec: core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- },
- Spec: validPodSpec(&core.Affinity{
- PodAntiAffinity: &core.PodAntiAffinity{
- PreferredDuringSchedulingIgnoredDuringExecution: []core.WeightedPodAffinityTerm{
- {
- Weight: 10,
- PodAffinityTerm: core.PodAffinityTerm{
- LabelSelector: &metav1.LabelSelector{
- MatchExpressions: []metav1.LabelSelectorRequirement{
- {
- Key: "key2",
- Operator: metav1.LabelSelectorOpNotIn,
- Values: []string{"value1", "value2"},
- },
- },
- },
- Namespaces: []string{"ns"},
- },
- },
- },
- },
- }),
- },
- },
- "invalid toleration key": {
- expectedError: "spec.tolerations[0].key",
- spec: core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- },
- Spec: extendPodSpecwithTolerations(validPodSpec(nil), []core.Toleration{{Key: "nospecialchars^=@", Operator: "Equal", Value: "bar", Effect: "NoSchedule"}}),
- },
- },
- "invalid toleration operator": {
- expectedError: "spec.tolerations[0].operator",
- spec: core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- },
- Spec: extendPodSpecwithTolerations(validPodSpec(nil), []core.Toleration{{Key: "foo", Operator: "In", Value: "bar", Effect: "NoSchedule"}}),
- },
- },
- "value must be empty when `operator` is 'Exists'": {
- expectedError: "spec.tolerations[0].operator",
- spec: core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- },
- Spec: extendPodSpecwithTolerations(validPodSpec(nil), []core.Toleration{{Key: "foo", Operator: "Exists", Value: "bar", Effect: "NoSchedule"}}),
- },
- },
- "operator must be 'Exists' when `key` is empty": {
- expectedError: "spec.tolerations[0].operator",
- spec: core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- },
- Spec: extendPodSpecwithTolerations(validPodSpec(nil), []core.Toleration{{Operator: "Equal", Value: "bar", Effect: "NoSchedule"}}),
- },
- },
- "effect must be 'NoExecute' when `TolerationSeconds` is set": {
- expectedError: "spec.tolerations[0].effect",
- spec: core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "pod-forgiveness-invalid",
- Namespace: "ns",
- },
- Spec: extendPodSpecwithTolerations(validPodSpec(nil), []core.Toleration{{Key: "node.kubernetes.io/not-ready", Operator: "Exists", Effect: "NoSchedule", TolerationSeconds: &[]int64{20}[0]}}),
- },
- },
- "must be a valid pod seccomp profile": {
- expectedError: "must be a valid seccomp profile",
- spec: core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- Annotations: map[string]string{
- core.SeccompPodAnnotationKey: "foo",
- },
- },
- Spec: validPodSpec(nil),
- },
- },
- "must be a valid container seccomp profile": {
- expectedError: "must be a valid seccomp profile",
- spec: core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- Annotations: map[string]string{
- core.SeccompContainerAnnotationKeyPrefix + "foo": "foo",
- },
- },
- Spec: validPodSpec(nil),
- },
- },
- "must be a non-empty container name in seccomp annotation": {
- expectedError: "name part must be non-empty",
- spec: core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- Annotations: map[string]string{
- core.SeccompContainerAnnotationKeyPrefix: "foo",
- },
- },
- Spec: validPodSpec(nil),
- },
- },
- "must be a non-empty container profile in seccomp annotation": {
- expectedError: "must be a valid seccomp profile",
- spec: core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- Annotations: map[string]string{
- core.SeccompContainerAnnotationKeyPrefix + "foo": "",
- },
- },
- Spec: validPodSpec(nil),
- },
- },
- "must be a relative path in a node-local seccomp profile annotation": {
- expectedError: "must be a relative path",
- spec: core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- Annotations: map[string]string{
- core.SeccompPodAnnotationKey: "localhost//foo",
- },
- },
- Spec: validPodSpec(nil),
- },
- },
- "must not start with '../'": {
- expectedError: "must not contain '..'",
- spec: core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- Annotations: map[string]string{
- core.SeccompPodAnnotationKey: "localhost/../foo",
- },
- },
- Spec: validPodSpec(nil),
- },
- },
- "AppArmor profile must apply to a container": {
- expectedError: "metadata.annotations[container.apparmor.security.beta.kubernetes.io/fake-ctr]",
- spec: core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- Annotations: map[string]string{
- apparmor.ContainerAnnotationKeyPrefix + "ctr": apparmor.ProfileRuntimeDefault,
- apparmor.ContainerAnnotationKeyPrefix + "init-ctr": apparmor.ProfileRuntimeDefault,
- apparmor.ContainerAnnotationKeyPrefix + "fake-ctr": apparmor.ProfileRuntimeDefault,
- },
- },
- Spec: core.PodSpec{
- InitContainers: []core.Container{{Name: "init-ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- },
- },
- },
- "AppArmor profile format must be valid": {
- expectedError: "invalid AppArmor profile name",
- spec: core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- Annotations: map[string]string{
- apparmor.ContainerAnnotationKeyPrefix + "ctr": "bad-name",
- },
- },
- Spec: validPodSpec(nil),
- },
- },
- "only default AppArmor profile may start with runtime/": {
- expectedError: "invalid AppArmor profile name",
- spec: core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- Annotations: map[string]string{
- apparmor.ContainerAnnotationKeyPrefix + "ctr": "runtime/foo",
- },
- },
- Spec: validPodSpec(nil),
- },
- },
- "invalid extended resource name in container request": {
- expectedError: "must be a standard resource for containers",
- spec: core.Pod{
- ObjectMeta: metav1.ObjectMeta{Name: "123", Namespace: "ns"},
- Spec: core.PodSpec{
- Containers: []core.Container{
- {
- Name: "invalid",
- Image: "image",
- ImagePullPolicy: "IfNotPresent",
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName("invalid-name"): resource.MustParse("2"),
- },
- Limits: core.ResourceList{
- core.ResourceName("invalid-name"): resource.MustParse("2"),
- },
- },
- },
- },
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- },
- },
- },
- "invalid extended resource requirement: request must be == limit": {
- expectedError: "must be equal to example.com/a",
- spec: core.Pod{
- ObjectMeta: metav1.ObjectMeta{Name: "123", Namespace: "ns"},
- Spec: core.PodSpec{
- Containers: []core.Container{
- {
- Name: "invalid",
- Image: "image",
- ImagePullPolicy: "IfNotPresent",
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName("example.com/a"): resource.MustParse("2"),
- },
- Limits: core.ResourceList{
- core.ResourceName("example.com/a"): resource.MustParse("1"),
- },
- },
- },
- },
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- },
- },
- },
- "invalid extended resource requirement without limit": {
- expectedError: "Limit must be set",
- spec: core.Pod{
- ObjectMeta: metav1.ObjectMeta{Name: "123", Namespace: "ns"},
- Spec: core.PodSpec{
- Containers: []core.Container{
- {
- Name: "invalid",
- Image: "image",
- ImagePullPolicy: "IfNotPresent",
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName("example.com/a"): resource.MustParse("2"),
- },
- },
- },
- },
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- },
- },
- },
- "invalid fractional extended resource in container request": {
- expectedError: "must be an integer",
- spec: core.Pod{
- ObjectMeta: metav1.ObjectMeta{Name: "123", Namespace: "ns"},
- Spec: core.PodSpec{
- Containers: []core.Container{
- {
- Name: "invalid",
- Image: "image",
- ImagePullPolicy: "IfNotPresent",
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName("example.com/a"): resource.MustParse("500m"),
- },
- },
- },
- },
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- },
- },
- },
- "invalid fractional extended resource in init container request": {
- expectedError: "must be an integer",
- spec: core.Pod{
- ObjectMeta: metav1.ObjectMeta{Name: "123", Namespace: "ns"},
- Spec: core.PodSpec{
- InitContainers: []core.Container{
- {
- Name: "invalid",
- Image: "image",
- ImagePullPolicy: "IfNotPresent",
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName("example.com/a"): resource.MustParse("500m"),
- },
- },
- },
- },
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- },
- },
- },
- "invalid fractional extended resource in container limit": {
- expectedError: "must be an integer",
- spec: core.Pod{
- ObjectMeta: metav1.ObjectMeta{Name: "123", Namespace: "ns"},
- Spec: core.PodSpec{
- Containers: []core.Container{
- {
- Name: "invalid",
- Image: "image",
- ImagePullPolicy: "IfNotPresent",
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName("example.com/a"): resource.MustParse("5"),
- },
- Limits: core.ResourceList{
- core.ResourceName("example.com/a"): resource.MustParse("2.5"),
- },
- },
- },
- },
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- },
- },
- },
- "invalid fractional extended resource in init container limit": {
- expectedError: "must be an integer",
- spec: core.Pod{
- ObjectMeta: metav1.ObjectMeta{Name: "123", Namespace: "ns"},
- Spec: core.PodSpec{
- InitContainers: []core.Container{
- {
- Name: "invalid",
- Image: "image",
- ImagePullPolicy: "IfNotPresent",
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName("example.com/a"): resource.MustParse("2.5"),
- },
- Limits: core.ResourceList{
- core.ResourceName("example.com/a"): resource.MustParse("2.5"),
- },
- },
- },
- },
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- },
- },
- },
- "mirror-pod present without nodeName": {
- expectedError: "mirror",
- spec: core.Pod{
- ObjectMeta: metav1.ObjectMeta{Name: "123", Namespace: "ns", Annotations: map[string]string{core.MirrorPodAnnotationKey: ""}},
- Spec: core.PodSpec{
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- },
- },
- },
- "mirror-pod populated without nodeName": {
- expectedError: "mirror",
- spec: core.Pod{
- ObjectMeta: metav1.ObjectMeta{Name: "123", Namespace: "ns", Annotations: map[string]string{core.MirrorPodAnnotationKey: "foo"}},
- Spec: core.PodSpec{
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- },
- },
- },
- "serviceaccount token projected volume with no serviceaccount name specified": {
- expectedError: "must not be specified when serviceAccountName is not set",
- spec: core.Pod{
- ObjectMeta: metav1.ObjectMeta{Name: "123", Namespace: "ns"},
- Spec: core.PodSpec{
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- Volumes: []core.Volume{
- {
- Name: "projected-volume",
- VolumeSource: core.VolumeSource{
- Projected: &core.ProjectedVolumeSource{
- Sources: []core.VolumeProjection{
- {
- ServiceAccountToken: &core.ServiceAccountTokenProjection{
- Audience: "foo-audience",
- ExpirationSeconds: 6000,
- Path: "foo-path",
- },
- },
- },
- },
- },
- },
- },
- },
- },
- },
- }
- for k, v := range errorCases {
- if errs := ValidatePod(&v.spec); len(errs) == 0 {
- t.Errorf("expected failure for %q", k)
- } else if v.expectedError == "" {
- t.Errorf("missing expectedError for %q, got %q", k, errs.ToAggregate().Error())
- } else if actualError := errs.ToAggregate().Error(); !strings.Contains(actualError, v.expectedError) {
- t.Errorf("expected error for %q to contain %q, got %q", k, v.expectedError, actualError)
- }
- }
- }
- func TestValidatePodUpdate(t *testing.T) {
- var (
- activeDeadlineSecondsZero = int64(0)
- activeDeadlineSecondsNegative = int64(-30)
- activeDeadlineSecondsPositive = int64(30)
- activeDeadlineSecondsLarger = int64(31)
- now = metav1.Now()
- grace = int64(30)
- grace2 = int64(31)
- )
- tests := []struct {
- new core.Pod
- old core.Pod
- err string
- test string
- }{
- {core.Pod{}, core.Pod{}, "", "nothing"},
- {
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{Name: "foo"},
- },
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{Name: "bar"},
- },
- "metadata.name",
- "ids",
- },
- {
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- Labels: map[string]string{
- "foo": "bar",
- },
- },
- },
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- Labels: map[string]string{
- "bar": "foo",
- },
- },
- },
- "",
- "labels",
- },
- {
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- Annotations: map[string]string{
- "foo": "bar",
- },
- },
- },
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- Annotations: map[string]string{
- "bar": "foo",
- },
- },
- },
- "",
- "annotations",
- },
- {
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- },
- Spec: core.PodSpec{
- Containers: []core.Container{
- {
- Image: "foo:V1",
- },
- },
- },
- },
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{Name: "foo"},
- Spec: core.PodSpec{
- Containers: []core.Container{
- {
- Image: "foo:V2",
- },
- {
- Image: "bar:V2",
- },
- },
- },
- },
- "may not add or remove containers",
- "less containers",
- },
- {
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- },
- Spec: core.PodSpec{
- Containers: []core.Container{
- {
- Image: "foo:V1",
- },
- {
- Image: "bar:V2",
- },
- },
- },
- },
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{Name: "foo"},
- Spec: core.PodSpec{
- Containers: []core.Container{
- {
- Image: "foo:V2",
- },
- },
- },
- },
- "may not add or remove containers",
- "more containers",
- },
- {
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- },
- Spec: core.PodSpec{
- InitContainers: []core.Container{
- {
- Image: "foo:V1",
- },
- },
- },
- },
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{Name: "foo"},
- Spec: core.PodSpec{
- InitContainers: []core.Container{
- {
- Image: "foo:V2",
- },
- {
- Image: "bar:V2",
- },
- },
- },
- },
- "may not add or remove containers",
- "more init containers",
- },
- {
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{Name: "foo"},
- Spec: core.PodSpec{Containers: []core.Container{{Image: "foo:V1"}}},
- },
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{Name: "foo", DeletionTimestamp: &now},
- Spec: core.PodSpec{Containers: []core.Container{{Image: "foo:V1"}}},
- },
- "metadata.deletionTimestamp",
- "deletion timestamp removed",
- },
- {
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{Name: "foo", DeletionTimestamp: &now},
- Spec: core.PodSpec{Containers: []core.Container{{Image: "foo:V1"}}},
- },
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{Name: "foo"},
- Spec: core.PodSpec{Containers: []core.Container{{Image: "foo:V1"}}},
- },
- "metadata.deletionTimestamp",
- "deletion timestamp added",
- },
- {
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{Name: "foo", DeletionTimestamp: &now, DeletionGracePeriodSeconds: &grace},
- Spec: core.PodSpec{Containers: []core.Container{{Image: "foo:V1"}}},
- },
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{Name: "foo", DeletionTimestamp: &now, DeletionGracePeriodSeconds: &grace2},
- Spec: core.PodSpec{Containers: []core.Container{{Image: "foo:V1"}}},
- },
- "metadata.deletionGracePeriodSeconds",
- "deletion grace period seconds changed",
- },
- {
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{Name: "foo"},
- Spec: core.PodSpec{
- Containers: []core.Container{
- {
- Image: "foo:V1",
- },
- },
- },
- },
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{Name: "foo"},
- Spec: core.PodSpec{
- Containers: []core.Container{
- {
- Image: "foo:V2",
- },
- },
- },
- },
- "",
- "image change",
- },
- {
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{Name: "foo"},
- Spec: core.PodSpec{
- InitContainers: []core.Container{
- {
- Image: "foo:V1",
- },
- },
- },
- },
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{Name: "foo"},
- Spec: core.PodSpec{
- InitContainers: []core.Container{
- {
- Image: "foo:V2",
- },
- },
- },
- },
- "",
- "init container image change",
- },
- {
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{Name: "foo"},
- Spec: core.PodSpec{
- Containers: []core.Container{
- {},
- },
- },
- },
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{Name: "foo"},
- Spec: core.PodSpec{
- Containers: []core.Container{
- {
- Image: "foo:V2",
- },
- },
- },
- },
- "spec.containers[0].image",
- "image change to empty",
- },
- {
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{Name: "foo"},
- Spec: core.PodSpec{
- InitContainers: []core.Container{
- {},
- },
- },
- },
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{Name: "foo"},
- Spec: core.PodSpec{
- InitContainers: []core.Container{
- {
- Image: "foo:V2",
- },
- },
- },
- },
- "spec.initContainers[0].image",
- "init container image change to empty",
- },
- {
- core.Pod{
- Spec: core.PodSpec{},
- },
- core.Pod{
- Spec: core.PodSpec{},
- },
- "",
- "activeDeadlineSeconds no change, nil",
- },
- {
- core.Pod{
- Spec: core.PodSpec{
- ActiveDeadlineSeconds: &activeDeadlineSecondsPositive,
- },
- },
- core.Pod{
- Spec: core.PodSpec{
- ActiveDeadlineSeconds: &activeDeadlineSecondsPositive,
- },
- },
- "",
- "activeDeadlineSeconds no change, set",
- },
- {
- core.Pod{
- Spec: core.PodSpec{
- ActiveDeadlineSeconds: &activeDeadlineSecondsPositive,
- },
- },
- core.Pod{},
- "",
- "activeDeadlineSeconds change to positive from nil",
- },
- {
- core.Pod{
- Spec: core.PodSpec{
- ActiveDeadlineSeconds: &activeDeadlineSecondsPositive,
- },
- },
- core.Pod{
- Spec: core.PodSpec{
- ActiveDeadlineSeconds: &activeDeadlineSecondsLarger,
- },
- },
- "",
- "activeDeadlineSeconds change to smaller positive",
- },
- {
- core.Pod{
- Spec: core.PodSpec{
- ActiveDeadlineSeconds: &activeDeadlineSecondsLarger,
- },
- },
- core.Pod{
- Spec: core.PodSpec{
- ActiveDeadlineSeconds: &activeDeadlineSecondsPositive,
- },
- },
- "spec.activeDeadlineSeconds",
- "activeDeadlineSeconds change to larger positive",
- },
- {
- core.Pod{
- Spec: core.PodSpec{
- ActiveDeadlineSeconds: &activeDeadlineSecondsNegative,
- },
- },
- core.Pod{},
- "spec.activeDeadlineSeconds",
- "activeDeadlineSeconds change to negative from nil",
- },
- {
- core.Pod{
- Spec: core.PodSpec{
- ActiveDeadlineSeconds: &activeDeadlineSecondsNegative,
- },
- },
- core.Pod{
- Spec: core.PodSpec{
- ActiveDeadlineSeconds: &activeDeadlineSecondsPositive,
- },
- },
- "spec.activeDeadlineSeconds",
- "activeDeadlineSeconds change to negative from positive",
- },
- {
- core.Pod{
- Spec: core.PodSpec{
- ActiveDeadlineSeconds: &activeDeadlineSecondsZero,
- },
- },
- core.Pod{
- Spec: core.PodSpec{
- ActiveDeadlineSeconds: &activeDeadlineSecondsPositive,
- },
- },
- "",
- "activeDeadlineSeconds change to zero from positive",
- },
- {
- core.Pod{
- Spec: core.PodSpec{
- ActiveDeadlineSeconds: &activeDeadlineSecondsZero,
- },
- },
- core.Pod{},
- "",
- "activeDeadlineSeconds change to zero from nil",
- },
- {
- core.Pod{},
- core.Pod{
- Spec: core.PodSpec{
- ActiveDeadlineSeconds: &activeDeadlineSecondsPositive,
- },
- },
- "spec.activeDeadlineSeconds",
- "activeDeadlineSeconds change to nil from positive",
- },
- {
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{Name: "foo"},
- Spec: core.PodSpec{
- Containers: []core.Container{
- {
- Image: "foo:V1",
- Resources: core.ResourceRequirements{
- Limits: getResourceLimits("100m", "0"),
- },
- },
- },
- },
- },
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{Name: "foo"},
- Spec: core.PodSpec{
- Containers: []core.Container{
- {
- Image: "foo:V2",
- Resources: core.ResourceRequirements{
- Limits: getResourceLimits("1000m", "0"),
- },
- },
- },
- },
- },
- "spec: Forbidden: pod updates may not change fields",
- "cpu change",
- },
- {
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{Name: "foo"},
- Spec: core.PodSpec{
- Containers: []core.Container{
- {
- Image: "foo:V1",
- Ports: []core.ContainerPort{
- {HostPort: 8080, ContainerPort: 80},
- },
- },
- },
- },
- },
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{Name: "foo"},
- Spec: core.PodSpec{
- Containers: []core.Container{
- {
- Image: "foo:V2",
- Ports: []core.ContainerPort{
- {HostPort: 8000, ContainerPort: 80},
- },
- },
- },
- },
- },
- "spec: Forbidden: pod updates may not change fields",
- "port change",
- },
- {
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- Labels: map[string]string{
- "foo": "bar",
- },
- },
- },
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- Labels: map[string]string{
- "Bar": "foo",
- },
- },
- },
- "",
- "bad label change",
- },
- {
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- },
- Spec: core.PodSpec{
- NodeName: "node1",
- Tolerations: []core.Toleration{{Key: "key1", Value: "value2"}},
- },
- },
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- },
- Spec: core.PodSpec{
- NodeName: "node1",
- Tolerations: []core.Toleration{{Key: "key1", Value: "value1"}},
- },
- },
- "spec.tolerations: Forbidden",
- "existing toleration value modified in pod spec updates",
- },
- {
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- },
- Spec: core.PodSpec{
- NodeName: "node1",
- Tolerations: []core.Toleration{{Key: "key1", Value: "value2", Operator: "Equal", Effect: "NoExecute", TolerationSeconds: nil}},
- },
- },
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- },
- Spec: core.PodSpec{
- NodeName: "node1",
- Tolerations: []core.Toleration{{Key: "key1", Value: "value1", Operator: "Equal", Effect: "NoExecute", TolerationSeconds: &[]int64{10}[0]}},
- },
- },
- "spec.tolerations: Forbidden",
- "existing toleration value modified in pod spec updates with modified tolerationSeconds",
- },
- {
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- },
- Spec: core.PodSpec{
- NodeName: "node1",
- Tolerations: []core.Toleration{{Key: "key1", Value: "value1", Operator: "Equal", Effect: "NoExecute", TolerationSeconds: &[]int64{10}[0]}},
- },
- },
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- },
- Spec: core.PodSpec{
- NodeName: "node1",
- Tolerations: []core.Toleration{{Key: "key1", Value: "value1", Operator: "Equal", Effect: "NoExecute", TolerationSeconds: &[]int64{20}[0]}},
- }},
- "",
- "modified tolerationSeconds in existing toleration value in pod spec updates",
- },
- {
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- },
- Spec: core.PodSpec{
- Tolerations: []core.Toleration{{Key: "key1", Value: "value2"}},
- },
- },
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- },
- Spec: core.PodSpec{
- NodeName: "",
- Tolerations: []core.Toleration{{Key: "key1", Value: "value1"}},
- },
- },
- "spec.tolerations: Forbidden",
- "toleration modified in updates to an unscheduled pod",
- },
- {
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- },
- Spec: core.PodSpec{
- NodeName: "node1",
- Tolerations: []core.Toleration{{Key: "key1", Value: "value1"}},
- },
- },
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- },
- Spec: core.PodSpec{
- NodeName: "node1",
- Tolerations: []core.Toleration{{Key: "key1", Value: "value1"}},
- },
- },
- "",
- "tolerations unmodified in updates to a scheduled pod",
- },
- {
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- },
- Spec: core.PodSpec{
- NodeName: "node1",
- Tolerations: []core.Toleration{
- {Key: "key1", Value: "value1", Operator: "Equal", Effect: "NoExecute", TolerationSeconds: &[]int64{20}[0]},
- {Key: "key2", Value: "value2", Operator: "Equal", Effect: "NoExecute", TolerationSeconds: &[]int64{30}[0]},
- },
- }},
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- },
- Spec: core.PodSpec{
- NodeName: "node1",
- Tolerations: []core.Toleration{{Key: "key1", Value: "value1", Operator: "Equal", Effect: "NoExecute", TolerationSeconds: &[]int64{10}[0]}},
- },
- },
- "",
- "added valid new toleration to existing tolerations in pod spec updates",
- },
- {
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{Name: "foo"}, Spec: core.PodSpec{
- NodeName: "node1",
- Tolerations: []core.Toleration{
- {Key: "key1", Value: "value1", Operator: "Equal", Effect: "NoExecute", TolerationSeconds: &[]int64{20}[0]},
- {Key: "key2", Value: "value2", Operator: "Equal", Effect: "NoSchedule", TolerationSeconds: &[]int64{30}[0]},
- },
- }},
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- },
- Spec: core.PodSpec{
- NodeName: "node1", Tolerations: []core.Toleration{{Key: "key1", Value: "value1", Operator: "Equal", Effect: "NoExecute", TolerationSeconds: &[]int64{10}[0]}},
- }},
- "spec.tolerations[1].effect",
- "added invalid new toleration to existing tolerations in pod spec updates",
- },
- {
- core.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo"}, Spec: core.PodSpec{NodeName: "foo"}},
- core.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo"}},
- "spec: Forbidden: pod updates may not change fields",
- "removed nodeName from pod spec",
- },
- {
- core.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo", Annotations: map[string]string{core.MirrorPodAnnotationKey: ""}}, Spec: core.PodSpec{NodeName: "foo"}},
- core.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo"}, Spec: core.PodSpec{NodeName: "foo"}},
- "metadata.annotations[kubernetes.io/config.mirror]",
- "added mirror pod annotation",
- },
- {
- core.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo"}, Spec: core.PodSpec{NodeName: "foo"}},
- core.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo", Annotations: map[string]string{core.MirrorPodAnnotationKey: ""}}, Spec: core.PodSpec{NodeName: "foo"}},
- "metadata.annotations[kubernetes.io/config.mirror]",
- "removed mirror pod annotation",
- },
- {
- core.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo", Annotations: map[string]string{core.MirrorPodAnnotationKey: "foo"}}, Spec: core.PodSpec{NodeName: "foo"}},
- core.Pod{ObjectMeta: metav1.ObjectMeta{Name: "foo", Annotations: map[string]string{core.MirrorPodAnnotationKey: "bar"}}, Spec: core.PodSpec{NodeName: "foo"}},
- "metadata.annotations[kubernetes.io/config.mirror]",
- "changed mirror pod annotation",
- },
- {
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- },
- Spec: core.PodSpec{
- NodeName: "node1",
- PriorityClassName: "bar-priority",
- },
- },
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- },
- Spec: core.PodSpec{
- NodeName: "node1",
- PriorityClassName: "foo-priority",
- },
- },
- "spec: Forbidden: pod updates",
- "changed priority class name",
- },
- {
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- },
- Spec: core.PodSpec{
- NodeName: "node1",
- PriorityClassName: "",
- },
- },
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- },
- Spec: core.PodSpec{
- NodeName: "node1",
- PriorityClassName: "foo-priority",
- },
- },
- "spec: Forbidden: pod updates",
- "removed priority class name",
- },
- }
- for _, test := range tests {
- test.new.ObjectMeta.ResourceVersion = "1"
- test.old.ObjectMeta.ResourceVersion = "1"
- errs := ValidatePodUpdate(&test.new, &test.old)
- if test.err == "" {
- if len(errs) != 0 {
- t.Errorf("unexpected invalid: %s (%+v)\nA: %+v\nB: %+v", test.test, errs, test.new, test.old)
- }
- } else {
- if len(errs) == 0 {
- t.Errorf("unexpected valid: %s\nA: %+v\nB: %+v", test.test, test.new, test.old)
- } else if actualErr := errs.ToAggregate().Error(); !strings.Contains(actualErr, test.err) {
- t.Errorf("unexpected error message: %s\nExpected error: %s\nActual error: %s", test.test, test.err, actualErr)
- }
- }
- }
- }
- func TestValidatePodStatusUpdate(t *testing.T) {
- tests := []struct {
- new core.Pod
- old core.Pod
- err string
- test string
- }{
- {
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- },
- Spec: core.PodSpec{
- NodeName: "node1",
- },
- Status: core.PodStatus{
- NominatedNodeName: "node1",
- },
- },
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- },
- Spec: core.PodSpec{
- NodeName: "node1",
- },
- Status: core.PodStatus{},
- },
- "",
- "removed nominatedNodeName",
- },
- {
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- },
- Spec: core.PodSpec{
- NodeName: "node1",
- },
- },
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- },
- Spec: core.PodSpec{
- NodeName: "node1",
- },
- Status: core.PodStatus{
- NominatedNodeName: "node1",
- },
- },
- "",
- "add valid nominatedNodeName",
- },
- {
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- },
- Spec: core.PodSpec{
- NodeName: "node1",
- },
- Status: core.PodStatus{
- NominatedNodeName: "Node1",
- },
- },
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- },
- Spec: core.PodSpec{
- NodeName: "node1",
- },
- },
- "nominatedNodeName",
- "Add invalid nominatedNodeName",
- },
- {
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- },
- Spec: core.PodSpec{
- NodeName: "node1",
- },
- Status: core.PodStatus{
- NominatedNodeName: "node1",
- },
- },
- core.Pod{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- },
- Spec: core.PodSpec{
- NodeName: "node1",
- },
- Status: core.PodStatus{
- NominatedNodeName: "node2",
- },
- },
- "",
- "Update nominatedNodeName",
- },
- }
- for _, test := range tests {
- test.new.ObjectMeta.ResourceVersion = "1"
- test.old.ObjectMeta.ResourceVersion = "1"
- errs := ValidatePodStatusUpdate(&test.new, &test.old)
- if test.err == "" {
- if len(errs) != 0 {
- t.Errorf("unexpected invalid: %s (%+v)\nA: %+v\nB: %+v", test.test, errs, test.new, test.old)
- }
- } else {
- if len(errs) == 0 {
- t.Errorf("unexpected valid: %s\nA: %+v\nB: %+v", test.test, test.new, test.old)
- } else if actualErr := errs.ToAggregate().Error(); !strings.Contains(actualErr, test.err) {
- t.Errorf("unexpected error message: %s\nExpected error: %s\nActual error: %s", test.test, test.err, actualErr)
- }
- }
- }
- }
- func makeValidService() core.Service {
- return core.Service{
- ObjectMeta: metav1.ObjectMeta{
- Name: "valid",
- Namespace: "valid",
- Labels: map[string]string{},
- Annotations: map[string]string{},
- ResourceVersion: "1",
- },
- Spec: core.ServiceSpec{
- Selector: map[string]string{"key": "val"},
- SessionAffinity: "None",
- Type: core.ServiceTypeClusterIP,
- Ports: []core.ServicePort{{Name: "p", Protocol: "TCP", Port: 8675, TargetPort: intstr.FromInt(8675)}},
- },
- }
- }
- func TestValidateService(t *testing.T) {
- defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.SCTPSupport, true)()
- testCases := []struct {
- name string
- tweakSvc func(svc *core.Service) // given a basic valid service, each test case can customize it
- numErrs int
- }{
- {
- name: "missing namespace",
- tweakSvc: func(s *core.Service) {
- s.Namespace = ""
- },
- numErrs: 1,
- },
- {
- name: "invalid namespace",
- tweakSvc: func(s *core.Service) {
- s.Namespace = "-123"
- },
- numErrs: 1,
- },
- {
- name: "missing name",
- tweakSvc: func(s *core.Service) {
- s.Name = ""
- },
- numErrs: 1,
- },
- {
- name: "invalid name",
- tweakSvc: func(s *core.Service) {
- s.Name = "-123"
- },
- numErrs: 1,
- },
- {
- name: "too long name",
- tweakSvc: func(s *core.Service) {
- s.Name = strings.Repeat("a", 64)
- },
- numErrs: 1,
- },
- {
- name: "invalid generateName",
- tweakSvc: func(s *core.Service) {
- s.GenerateName = "-123"
- },
- numErrs: 1,
- },
- {
- name: "too long generateName",
- tweakSvc: func(s *core.Service) {
- s.GenerateName = strings.Repeat("a", 64)
- },
- numErrs: 1,
- },
- {
- name: "invalid label",
- tweakSvc: func(s *core.Service) {
- s.Labels["NoUppercaseOrSpecialCharsLike=Equals"] = "bar"
- },
- numErrs: 1,
- },
- {
- name: "invalid annotation",
- tweakSvc: func(s *core.Service) {
- s.Annotations["NoSpecialCharsLike=Equals"] = "bar"
- },
- numErrs: 1,
- },
- {
- name: "nil selector",
- tweakSvc: func(s *core.Service) {
- s.Spec.Selector = nil
- },
- numErrs: 0,
- },
- {
- name: "invalid selector",
- tweakSvc: func(s *core.Service) {
- s.Spec.Selector["NoSpecialCharsLike=Equals"] = "bar"
- },
- numErrs: 1,
- },
- {
- name: "missing session affinity",
- tweakSvc: func(s *core.Service) {
- s.Spec.SessionAffinity = ""
- },
- numErrs: 1,
- },
- {
- name: "missing type",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = ""
- },
- numErrs: 1,
- },
- {
- name: "missing ports",
- tweakSvc: func(s *core.Service) {
- s.Spec.Ports = nil
- },
- numErrs: 1,
- },
- {
- name: "missing ports but headless",
- tweakSvc: func(s *core.Service) {
- s.Spec.Ports = nil
- s.Spec.ClusterIP = core.ClusterIPNone
- },
- numErrs: 0,
- },
- {
- name: "empty port[0] name",
- tweakSvc: func(s *core.Service) {
- s.Spec.Ports[0].Name = ""
- },
- numErrs: 0,
- },
- {
- name: "empty port[1] name",
- tweakSvc: func(s *core.Service) {
- s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "", Protocol: "TCP", Port: 12345, TargetPort: intstr.FromInt(12345)})
- },
- numErrs: 1,
- },
- {
- name: "empty multi-port port[0] name",
- tweakSvc: func(s *core.Service) {
- s.Spec.Ports[0].Name = ""
- s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "p", Protocol: "TCP", Port: 12345, TargetPort: intstr.FromInt(12345)})
- },
- numErrs: 1,
- },
- {
- name: "invalid port name",
- tweakSvc: func(s *core.Service) {
- s.Spec.Ports[0].Name = "INVALID"
- },
- numErrs: 1,
- },
- {
- name: "missing protocol",
- tweakSvc: func(s *core.Service) {
- s.Spec.Ports[0].Protocol = ""
- },
- numErrs: 1,
- },
- {
- name: "invalid protocol",
- tweakSvc: func(s *core.Service) {
- s.Spec.Ports[0].Protocol = "INVALID"
- },
- numErrs: 1,
- },
- {
- name: "invalid cluster ip",
- tweakSvc: func(s *core.Service) {
- s.Spec.ClusterIP = "invalid"
- },
- numErrs: 1,
- },
- {
- name: "missing port",
- tweakSvc: func(s *core.Service) {
- s.Spec.Ports[0].Port = 0
- },
- numErrs: 1,
- },
- {
- name: "invalid port",
- tweakSvc: func(s *core.Service) {
- s.Spec.Ports[0].Port = 65536
- },
- numErrs: 1,
- },
- {
- name: "invalid TargetPort int",
- tweakSvc: func(s *core.Service) {
- s.Spec.Ports[0].TargetPort = intstr.FromInt(65536)
- },
- numErrs: 1,
- },
- {
- name: "valid port headless",
- tweakSvc: func(s *core.Service) {
- s.Spec.Ports[0].Port = 11722
- s.Spec.Ports[0].TargetPort = intstr.FromInt(11722)
- s.Spec.ClusterIP = core.ClusterIPNone
- },
- numErrs: 0,
- },
- {
- name: "invalid port headless 1",
- tweakSvc: func(s *core.Service) {
- s.Spec.Ports[0].Port = 11722
- s.Spec.Ports[0].TargetPort = intstr.FromInt(11721)
- s.Spec.ClusterIP = core.ClusterIPNone
- },
- // in the v1 API, targetPorts on headless services were tolerated.
- // once we have version-specific validation, we can reject this on newer API versions, but until then, we have to tolerate it for compatibility.
- // numErrs: 1,
- numErrs: 0,
- },
- {
- name: "invalid port headless 2",
- tweakSvc: func(s *core.Service) {
- s.Spec.Ports[0].Port = 11722
- s.Spec.Ports[0].TargetPort = intstr.FromString("target")
- s.Spec.ClusterIP = core.ClusterIPNone
- },
- // in the v1 API, targetPorts on headless services were tolerated.
- // once we have version-specific validation, we can reject this on newer API versions, but until then, we have to tolerate it for compatibility.
- // numErrs: 1,
- numErrs: 0,
- },
- {
- name: "invalid publicIPs localhost",
- tweakSvc: func(s *core.Service) {
- s.Spec.ExternalIPs = []string{"127.0.0.1"}
- },
- numErrs: 1,
- },
- {
- name: "invalid publicIPs unspecified",
- tweakSvc: func(s *core.Service) {
- s.Spec.ExternalIPs = []string{"0.0.0.0"}
- },
- numErrs: 1,
- },
- {
- name: "invalid publicIPs loopback",
- tweakSvc: func(s *core.Service) {
- s.Spec.ExternalIPs = []string{"127.0.0.1"}
- },
- numErrs: 1,
- },
- {
- name: "invalid publicIPs host",
- tweakSvc: func(s *core.Service) {
- s.Spec.ExternalIPs = []string{"myhost.mydomain"}
- },
- numErrs: 1,
- },
- {
- name: "dup port name",
- tweakSvc: func(s *core.Service) {
- s.Spec.Ports[0].Name = "p"
- s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "p", Port: 12345, Protocol: "TCP", TargetPort: intstr.FromInt(12345)})
- },
- numErrs: 1,
- },
- {
- name: "valid load balancer protocol UDP 1",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = core.ServiceTypeLoadBalancer
- s.Spec.Ports[0].Protocol = "UDP"
- },
- numErrs: 0,
- },
- {
- name: "valid load balancer protocol UDP 2",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = core.ServiceTypeLoadBalancer
- s.Spec.Ports[0] = core.ServicePort{Name: "q", Port: 12345, Protocol: "UDP", TargetPort: intstr.FromInt(12345)}
- },
- numErrs: 0,
- },
- {
- name: "invalid load balancer with mix protocol",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = core.ServiceTypeLoadBalancer
- s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "q", Port: 12345, Protocol: "UDP", TargetPort: intstr.FromInt(12345)})
- },
- numErrs: 1,
- },
- {
- name: "valid 1",
- tweakSvc: func(s *core.Service) {
- // do nothing
- },
- numErrs: 0,
- },
- {
- name: "valid 2",
- tweakSvc: func(s *core.Service) {
- s.Spec.Ports[0].Protocol = "UDP"
- s.Spec.Ports[0].TargetPort = intstr.FromInt(12345)
- },
- numErrs: 0,
- },
- {
- name: "valid 3",
- tweakSvc: func(s *core.Service) {
- s.Spec.Ports[0].TargetPort = intstr.FromString("http")
- },
- numErrs: 0,
- },
- {
- name: "valid cluster ip - none ",
- tweakSvc: func(s *core.Service) {
- s.Spec.ClusterIP = "None"
- },
- numErrs: 0,
- },
- {
- name: "valid cluster ip - empty",
- tweakSvc: func(s *core.Service) {
- s.Spec.ClusterIP = ""
- s.Spec.Ports[0].TargetPort = intstr.FromString("http")
- },
- numErrs: 0,
- },
- {
- name: "valid type - cluster",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = core.ServiceTypeClusterIP
- },
- numErrs: 0,
- },
- {
- name: "valid type - loadbalancer",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = core.ServiceTypeLoadBalancer
- },
- numErrs: 0,
- },
- {
- name: "valid type loadbalancer 2 ports",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = core.ServiceTypeLoadBalancer
- s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "q", Port: 12345, Protocol: "TCP", TargetPort: intstr.FromInt(12345)})
- },
- numErrs: 0,
- },
- {
- name: "valid external load balancer 2 ports",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = core.ServiceTypeLoadBalancer
- s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "q", Port: 12345, Protocol: "TCP", TargetPort: intstr.FromInt(12345)})
- },
- numErrs: 0,
- },
- {
- name: "duplicate nodeports",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = core.ServiceTypeNodePort
- s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "q", Port: 1, Protocol: "TCP", NodePort: 1, TargetPort: intstr.FromInt(1)})
- s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "r", Port: 2, Protocol: "TCP", NodePort: 1, TargetPort: intstr.FromInt(2)})
- },
- numErrs: 1,
- },
- {
- name: "duplicate nodeports (different protocols)",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = core.ServiceTypeNodePort
- s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "q", Port: 1, Protocol: "TCP", NodePort: 1, TargetPort: intstr.FromInt(1)})
- s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "r", Port: 2, Protocol: "UDP", NodePort: 1, TargetPort: intstr.FromInt(2)})
- s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "s", Port: 3, Protocol: "SCTP", NodePort: 1, TargetPort: intstr.FromInt(3)})
- },
- numErrs: 0,
- },
- {
- name: "invalid duplicate ports (with same protocol)",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = core.ServiceTypeClusterIP
- s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "q", Port: 12345, Protocol: "TCP", TargetPort: intstr.FromInt(8080)})
- s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "r", Port: 12345, Protocol: "TCP", TargetPort: intstr.FromInt(80)})
- },
- numErrs: 1,
- },
- {
- name: "valid duplicate ports (with different protocols)",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = core.ServiceTypeClusterIP
- s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "q", Port: 12345, Protocol: "TCP", TargetPort: intstr.FromInt(8080)})
- s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "r", Port: 12345, Protocol: "UDP", TargetPort: intstr.FromInt(80)})
- s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "s", Port: 12345, Protocol: "SCTP", TargetPort: intstr.FromInt(8088)})
- },
- numErrs: 0,
- },
- {
- name: "valid type - cluster",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = core.ServiceTypeClusterIP
- },
- numErrs: 0,
- },
- {
- name: "valid type - nodeport",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = core.ServiceTypeNodePort
- },
- numErrs: 0,
- },
- {
- name: "valid type - loadbalancer",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = core.ServiceTypeLoadBalancer
- },
- numErrs: 0,
- },
- {
- name: "valid type loadbalancer 2 ports",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = core.ServiceTypeLoadBalancer
- s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "q", Port: 12345, Protocol: "TCP", TargetPort: intstr.FromInt(12345)})
- },
- numErrs: 0,
- },
- {
- name: "valid type loadbalancer with NodePort",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = core.ServiceTypeLoadBalancer
- s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "q", Port: 12345, Protocol: "TCP", NodePort: 12345, TargetPort: intstr.FromInt(12345)})
- },
- numErrs: 0,
- },
- {
- name: "valid type=NodePort service with NodePort",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = core.ServiceTypeNodePort
- s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "q", Port: 12345, Protocol: "TCP", NodePort: 12345, TargetPort: intstr.FromInt(12345)})
- },
- numErrs: 0,
- },
- {
- name: "valid type=NodePort service without NodePort",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = core.ServiceTypeNodePort
- s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "q", Port: 12345, Protocol: "TCP", TargetPort: intstr.FromInt(12345)})
- },
- numErrs: 0,
- },
- {
- name: "valid cluster service without NodePort",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = core.ServiceTypeClusterIP
- s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "q", Port: 12345, Protocol: "TCP", TargetPort: intstr.FromInt(12345)})
- },
- numErrs: 0,
- },
- {
- name: "invalid cluster service with NodePort",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = core.ServiceTypeClusterIP
- s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "q", Port: 12345, Protocol: "TCP", NodePort: 12345, TargetPort: intstr.FromInt(12345)})
- },
- numErrs: 1,
- },
- {
- name: "invalid public service with duplicate NodePort",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = core.ServiceTypeNodePort
- s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "p1", Port: 1, Protocol: "TCP", NodePort: 1, TargetPort: intstr.FromInt(1)})
- s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "p2", Port: 2, Protocol: "TCP", NodePort: 1, TargetPort: intstr.FromInt(2)})
- },
- numErrs: 1,
- },
- {
- name: "valid type=LoadBalancer",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = core.ServiceTypeLoadBalancer
- s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "q", Port: 12345, Protocol: "TCP", TargetPort: intstr.FromInt(12345)})
- },
- numErrs: 0,
- },
- {
- // For now we open firewalls, and its insecure if we open 10250, remove this
- // when we have better protections in place.
- name: "invalid port type=LoadBalancer",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = core.ServiceTypeLoadBalancer
- s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "kubelet", Port: 10250, Protocol: "TCP", TargetPort: intstr.FromInt(12345)})
- },
- numErrs: 1,
- },
- {
- name: "valid LoadBalancer source range annotation",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = core.ServiceTypeLoadBalancer
- s.Annotations[core.AnnotationLoadBalancerSourceRangesKey] = "1.2.3.4/8, 5.6.7.8/16"
- },
- numErrs: 0,
- },
- {
- name: "empty LoadBalancer source range annotation",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = core.ServiceTypeLoadBalancer
- s.Annotations[core.AnnotationLoadBalancerSourceRangesKey] = ""
- },
- numErrs: 0,
- },
- {
- name: "invalid LoadBalancer source range annotation (hostname)",
- tweakSvc: func(s *core.Service) {
- s.Annotations[core.AnnotationLoadBalancerSourceRangesKey] = "foo.bar"
- },
- numErrs: 2,
- },
- {
- name: "invalid LoadBalancer source range annotation (invalid CIDR)",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = core.ServiceTypeLoadBalancer
- s.Annotations[core.AnnotationLoadBalancerSourceRangesKey] = "1.2.3.4/33"
- },
- numErrs: 1,
- },
- {
- name: "invalid source range for non LoadBalancer type service",
- tweakSvc: func(s *core.Service) {
- s.Spec.LoadBalancerSourceRanges = []string{"1.2.3.4/8", "5.6.7.8/16"}
- },
- numErrs: 1,
- },
- {
- name: "valid LoadBalancer source range",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = core.ServiceTypeLoadBalancer
- s.Spec.LoadBalancerSourceRanges = []string{"1.2.3.4/8", "5.6.7.8/16"}
- },
- numErrs: 0,
- },
- {
- name: "empty LoadBalancer source range",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = core.ServiceTypeLoadBalancer
- s.Spec.LoadBalancerSourceRanges = []string{" "}
- },
- numErrs: 1,
- },
- {
- name: "invalid LoadBalancer source range",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = core.ServiceTypeLoadBalancer
- s.Spec.LoadBalancerSourceRanges = []string{"foo.bar"}
- },
- numErrs: 1,
- },
- {
- name: "valid ExternalName",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = core.ServiceTypeExternalName
- s.Spec.ClusterIP = ""
- s.Spec.ExternalName = "foo.bar.example.com"
- },
- numErrs: 0,
- },
- {
- name: "valid ExternalName (trailing dot)",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = core.ServiceTypeExternalName
- s.Spec.ClusterIP = ""
- s.Spec.ExternalName = "foo.bar.example.com."
- },
- numErrs: 0,
- },
- {
- name: "invalid ExternalName clusterIP (valid IP)",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = core.ServiceTypeExternalName
- s.Spec.ClusterIP = "1.2.3.4"
- s.Spec.ExternalName = "foo.bar.example.com"
- },
- numErrs: 1,
- },
- {
- name: "invalid ExternalName clusterIP (None)",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = core.ServiceTypeExternalName
- s.Spec.ClusterIP = "None"
- s.Spec.ExternalName = "foo.bar.example.com"
- },
- numErrs: 1,
- },
- {
- name: "invalid ExternalName (not a DNS name)",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = core.ServiceTypeExternalName
- s.Spec.ClusterIP = ""
- s.Spec.ExternalName = "-123"
- },
- numErrs: 1,
- },
- {
- name: "LoadBalancer type cannot have None ClusterIP",
- tweakSvc: func(s *core.Service) {
- s.Spec.ClusterIP = "None"
- s.Spec.Type = core.ServiceTypeLoadBalancer
- },
- numErrs: 1,
- },
- {
- name: "invalid node port with clusterIP None",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = core.ServiceTypeNodePort
- s.Spec.Ports = append(s.Spec.Ports, core.ServicePort{Name: "q", Port: 1, Protocol: "TCP", NodePort: 1, TargetPort: intstr.FromInt(1)})
- s.Spec.ClusterIP = "None"
- },
- numErrs: 1,
- },
- // ESIPP section begins.
- {
- name: "invalid externalTraffic field",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = core.ServiceTypeLoadBalancer
- s.Spec.ExternalTrafficPolicy = "invalid"
- },
- numErrs: 1,
- },
- {
- name: "nagative healthCheckNodePort field",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = core.ServiceTypeLoadBalancer
- s.Spec.ExternalTrafficPolicy = core.ServiceExternalTrafficPolicyTypeLocal
- s.Spec.HealthCheckNodePort = -1
- },
- numErrs: 1,
- },
- {
- name: "nagative healthCheckNodePort field",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = core.ServiceTypeLoadBalancer
- s.Spec.ExternalTrafficPolicy = core.ServiceExternalTrafficPolicyTypeLocal
- s.Spec.HealthCheckNodePort = 31100
- },
- numErrs: 0,
- },
- // ESIPP section ends.
- {
- name: "invalid timeoutSeconds field",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = core.ServiceTypeClusterIP
- s.Spec.SessionAffinity = core.ServiceAffinityClientIP
- s.Spec.SessionAffinityConfig = &core.SessionAffinityConfig{
- ClientIP: &core.ClientIPConfig{
- TimeoutSeconds: utilpointer.Int32Ptr(-1),
- },
- }
- },
- numErrs: 1,
- },
- {
- name: "sessionAffinityConfig can't be set when session affinity is None",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = core.ServiceTypeLoadBalancer
- s.Spec.SessionAffinity = core.ServiceAffinityNone
- s.Spec.SessionAffinityConfig = &core.SessionAffinityConfig{
- ClientIP: &core.ClientIPConfig{
- TimeoutSeconds: utilpointer.Int32Ptr(90),
- },
- }
- },
- numErrs: 1,
- },
- }
- for _, tc := range testCases {
- svc := makeValidService()
- tc.tweakSvc(&svc)
- errs := ValidateService(&svc)
- if len(errs) != tc.numErrs {
- t.Errorf("Unexpected error list for case %q: %v", tc.name, errs.ToAggregate())
- }
- }
- }
- func TestValidateServiceExternalTrafficFieldsCombination(t *testing.T) {
- testCases := []struct {
- name string
- tweakSvc func(svc *core.Service) // Given a basic valid service, each test case can customize it.
- numErrs int
- }{
- {
- name: "valid loadBalancer service with externalTrafficPolicy and healthCheckNodePort set",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = core.ServiceTypeLoadBalancer
- s.Spec.ExternalTrafficPolicy = core.ServiceExternalTrafficPolicyTypeLocal
- s.Spec.HealthCheckNodePort = 34567
- },
- numErrs: 0,
- },
- {
- name: "valid nodePort service with externalTrafficPolicy set",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = core.ServiceTypeNodePort
- s.Spec.ExternalTrafficPolicy = core.ServiceExternalTrafficPolicyTypeLocal
- },
- numErrs: 0,
- },
- {
- name: "valid clusterIP service with none of externalTrafficPolicy and healthCheckNodePort set",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = core.ServiceTypeClusterIP
- },
- numErrs: 0,
- },
- {
- name: "cannot set healthCheckNodePort field on loadBalancer service with externalTrafficPolicy!=Local",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = core.ServiceTypeLoadBalancer
- s.Spec.ExternalTrafficPolicy = core.ServiceExternalTrafficPolicyTypeCluster
- s.Spec.HealthCheckNodePort = 34567
- },
- numErrs: 1,
- },
- {
- name: "cannot set healthCheckNodePort field on nodePort service",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = core.ServiceTypeNodePort
- s.Spec.ExternalTrafficPolicy = core.ServiceExternalTrafficPolicyTypeLocal
- s.Spec.HealthCheckNodePort = 34567
- },
- numErrs: 1,
- },
- {
- name: "cannot set externalTrafficPolicy or healthCheckNodePort fields on clusterIP service",
- tweakSvc: func(s *core.Service) {
- s.Spec.Type = core.ServiceTypeClusterIP
- s.Spec.ExternalTrafficPolicy = core.ServiceExternalTrafficPolicyTypeLocal
- s.Spec.HealthCheckNodePort = 34567
- },
- numErrs: 2,
- },
- }
- for _, tc := range testCases {
- svc := makeValidService()
- tc.tweakSvc(&svc)
- errs := ValidateServiceExternalTrafficFieldsCombination(&svc)
- if len(errs) != tc.numErrs {
- t.Errorf("Unexpected error list for case %q: %v", tc.name, errs.ToAggregate())
- }
- }
- }
- func TestValidateReplicationControllerStatus(t *testing.T) {
- tests := []struct {
- name string
- replicas int32
- fullyLabeledReplicas int32
- readyReplicas int32
- availableReplicas int32
- observedGeneration int64
- expectedErr bool
- }{
- {
- name: "valid status",
- replicas: 3,
- fullyLabeledReplicas: 3,
- readyReplicas: 2,
- availableReplicas: 1,
- observedGeneration: 2,
- expectedErr: false,
- },
- {
- name: "invalid replicas",
- replicas: -1,
- fullyLabeledReplicas: 3,
- readyReplicas: 2,
- availableReplicas: 1,
- observedGeneration: 2,
- expectedErr: true,
- },
- {
- name: "invalid fullyLabeledReplicas",
- replicas: 3,
- fullyLabeledReplicas: -1,
- readyReplicas: 2,
- availableReplicas: 1,
- observedGeneration: 2,
- expectedErr: true,
- },
- {
- name: "invalid readyReplicas",
- replicas: 3,
- fullyLabeledReplicas: 3,
- readyReplicas: -1,
- availableReplicas: 1,
- observedGeneration: 2,
- expectedErr: true,
- },
- {
- name: "invalid availableReplicas",
- replicas: 3,
- fullyLabeledReplicas: 3,
- readyReplicas: 3,
- availableReplicas: -1,
- observedGeneration: 2,
- expectedErr: true,
- },
- {
- name: "invalid observedGeneration",
- replicas: 3,
- fullyLabeledReplicas: 3,
- readyReplicas: 3,
- availableReplicas: 3,
- observedGeneration: -1,
- expectedErr: true,
- },
- {
- name: "fullyLabeledReplicas greater than replicas",
- replicas: 3,
- fullyLabeledReplicas: 4,
- readyReplicas: 3,
- availableReplicas: 3,
- observedGeneration: 1,
- expectedErr: true,
- },
- {
- name: "readyReplicas greater than replicas",
- replicas: 3,
- fullyLabeledReplicas: 3,
- readyReplicas: 4,
- availableReplicas: 3,
- observedGeneration: 1,
- expectedErr: true,
- },
- {
- name: "availableReplicas greater than replicas",
- replicas: 3,
- fullyLabeledReplicas: 3,
- readyReplicas: 3,
- availableReplicas: 4,
- observedGeneration: 1,
- expectedErr: true,
- },
- {
- name: "availableReplicas greater than readyReplicas",
- replicas: 3,
- fullyLabeledReplicas: 3,
- readyReplicas: 2,
- availableReplicas: 3,
- observedGeneration: 1,
- expectedErr: true,
- },
- }
- for _, test := range tests {
- status := core.ReplicationControllerStatus{
- Replicas: test.replicas,
- FullyLabeledReplicas: test.fullyLabeledReplicas,
- ReadyReplicas: test.readyReplicas,
- AvailableReplicas: test.availableReplicas,
- ObservedGeneration: test.observedGeneration,
- }
- if hasErr := len(ValidateReplicationControllerStatus(status, field.NewPath("status"))) > 0; hasErr != test.expectedErr {
- t.Errorf("%s: expected error: %t, got error: %t", test.name, test.expectedErr, hasErr)
- }
- }
- }
- func TestValidateReplicationControllerStatusUpdate(t *testing.T) {
- validSelector := map[string]string{"a": "b"}
- validPodTemplate := core.PodTemplate{
- Template: core.PodTemplateSpec{
- ObjectMeta: metav1.ObjectMeta{
- Labels: validSelector,
- },
- Spec: core.PodSpec{
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- Containers: []core.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- },
- },
- }
- type rcUpdateTest struct {
- old core.ReplicationController
- update core.ReplicationController
- }
- successCases := []rcUpdateTest{
- {
- old: core.ReplicationController{
- ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: metav1.NamespaceDefault},
- Spec: core.ReplicationControllerSpec{
- Selector: validSelector,
- Template: &validPodTemplate.Template,
- },
- Status: core.ReplicationControllerStatus{
- Replicas: 2,
- },
- },
- update: core.ReplicationController{
- ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: metav1.NamespaceDefault},
- Spec: core.ReplicationControllerSpec{
- Replicas: 3,
- Selector: validSelector,
- Template: &validPodTemplate.Template,
- },
- Status: core.ReplicationControllerStatus{
- Replicas: 4,
- },
- },
- },
- }
- for _, successCase := range successCases {
- successCase.old.ObjectMeta.ResourceVersion = "1"
- successCase.update.ObjectMeta.ResourceVersion = "1"
- if errs := ValidateReplicationControllerStatusUpdate(&successCase.update, &successCase.old); len(errs) != 0 {
- t.Errorf("expected success: %v", errs)
- }
- }
- errorCases := map[string]rcUpdateTest{
- "negative replicas": {
- old: core.ReplicationController{
- ObjectMeta: metav1.ObjectMeta{Name: "", Namespace: metav1.NamespaceDefault},
- Spec: core.ReplicationControllerSpec{
- Selector: validSelector,
- Template: &validPodTemplate.Template,
- },
- Status: core.ReplicationControllerStatus{
- Replicas: 3,
- },
- },
- update: core.ReplicationController{
- ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: metav1.NamespaceDefault},
- Spec: core.ReplicationControllerSpec{
- Replicas: 2,
- Selector: validSelector,
- Template: &validPodTemplate.Template,
- },
- Status: core.ReplicationControllerStatus{
- Replicas: -3,
- },
- },
- },
- }
- for testName, errorCase := range errorCases {
- if errs := ValidateReplicationControllerStatusUpdate(&errorCase.update, &errorCase.old); len(errs) == 0 {
- t.Errorf("expected failure: %s", testName)
- }
- }
- }
- func TestValidateReplicationControllerUpdate(t *testing.T) {
- validSelector := map[string]string{"a": "b"}
- validPodTemplate := core.PodTemplate{
- Template: core.PodTemplateSpec{
- ObjectMeta: metav1.ObjectMeta{
- Labels: validSelector,
- },
- Spec: core.PodSpec{
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- Containers: []core.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- },
- },
- }
- readWriteVolumePodTemplate := core.PodTemplate{
- Template: core.PodTemplateSpec{
- ObjectMeta: metav1.ObjectMeta{
- Labels: validSelector,
- },
- Spec: core.PodSpec{
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- Containers: []core.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- Volumes: []core.Volume{{Name: "gcepd", VolumeSource: core.VolumeSource{GCEPersistentDisk: &core.GCEPersistentDiskVolumeSource{PDName: "my-PD", FSType: "ext4", Partition: 1, ReadOnly: false}}}},
- },
- },
- }
- invalidSelector := map[string]string{"NoUppercaseOrSpecialCharsLike=Equals": "b"}
- invalidPodTemplate := core.PodTemplate{
- Template: core.PodTemplateSpec{
- Spec: core.PodSpec{
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- },
- ObjectMeta: metav1.ObjectMeta{
- Labels: invalidSelector,
- },
- },
- }
- type rcUpdateTest struct {
- old core.ReplicationController
- update core.ReplicationController
- }
- successCases := []rcUpdateTest{
- {
- old: core.ReplicationController{
- ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: metav1.NamespaceDefault},
- Spec: core.ReplicationControllerSpec{
- Selector: validSelector,
- Template: &validPodTemplate.Template,
- },
- },
- update: core.ReplicationController{
- ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: metav1.NamespaceDefault},
- Spec: core.ReplicationControllerSpec{
- Replicas: 3,
- Selector: validSelector,
- Template: &validPodTemplate.Template,
- },
- },
- },
- {
- old: core.ReplicationController{
- ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: metav1.NamespaceDefault},
- Spec: core.ReplicationControllerSpec{
- Selector: validSelector,
- Template: &validPodTemplate.Template,
- },
- },
- update: core.ReplicationController{
- ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: metav1.NamespaceDefault},
- Spec: core.ReplicationControllerSpec{
- Replicas: 1,
- Selector: validSelector,
- Template: &readWriteVolumePodTemplate.Template,
- },
- },
- },
- }
- for _, successCase := range successCases {
- successCase.old.ObjectMeta.ResourceVersion = "1"
- successCase.update.ObjectMeta.ResourceVersion = "1"
- if errs := ValidateReplicationControllerUpdate(&successCase.update, &successCase.old); len(errs) != 0 {
- t.Errorf("expected success: %v", errs)
- }
- }
- errorCases := map[string]rcUpdateTest{
- "more than one read/write": {
- old: core.ReplicationController{
- ObjectMeta: metav1.ObjectMeta{Name: "", Namespace: metav1.NamespaceDefault},
- Spec: core.ReplicationControllerSpec{
- Selector: validSelector,
- Template: &validPodTemplate.Template,
- },
- },
- update: core.ReplicationController{
- ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: metav1.NamespaceDefault},
- Spec: core.ReplicationControllerSpec{
- Replicas: 2,
- Selector: validSelector,
- Template: &readWriteVolumePodTemplate.Template,
- },
- },
- },
- "invalid selector": {
- old: core.ReplicationController{
- ObjectMeta: metav1.ObjectMeta{Name: "", Namespace: metav1.NamespaceDefault},
- Spec: core.ReplicationControllerSpec{
- Selector: validSelector,
- Template: &validPodTemplate.Template,
- },
- },
- update: core.ReplicationController{
- ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: metav1.NamespaceDefault},
- Spec: core.ReplicationControllerSpec{
- Replicas: 2,
- Selector: invalidSelector,
- Template: &validPodTemplate.Template,
- },
- },
- },
- "invalid pod": {
- old: core.ReplicationController{
- ObjectMeta: metav1.ObjectMeta{Name: "", Namespace: metav1.NamespaceDefault},
- Spec: core.ReplicationControllerSpec{
- Selector: validSelector,
- Template: &validPodTemplate.Template,
- },
- },
- update: core.ReplicationController{
- ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: metav1.NamespaceDefault},
- Spec: core.ReplicationControllerSpec{
- Replicas: 2,
- Selector: validSelector,
- Template: &invalidPodTemplate.Template,
- },
- },
- },
- "negative replicas": {
- old: core.ReplicationController{
- ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: metav1.NamespaceDefault},
- Spec: core.ReplicationControllerSpec{
- Selector: validSelector,
- Template: &validPodTemplate.Template,
- },
- },
- update: core.ReplicationController{
- ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: metav1.NamespaceDefault},
- Spec: core.ReplicationControllerSpec{
- Replicas: -1,
- Selector: validSelector,
- Template: &validPodTemplate.Template,
- },
- },
- },
- }
- for testName, errorCase := range errorCases {
- if errs := ValidateReplicationControllerUpdate(&errorCase.update, &errorCase.old); len(errs) == 0 {
- t.Errorf("expected failure: %s", testName)
- }
- }
- }
- func TestValidateReplicationController(t *testing.T) {
- validSelector := map[string]string{"a": "b"}
- validPodTemplate := core.PodTemplate{
- Template: core.PodTemplateSpec{
- ObjectMeta: metav1.ObjectMeta{
- Labels: validSelector,
- },
- Spec: core.PodSpec{
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- Containers: []core.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- },
- },
- }
- readWriteVolumePodTemplate := core.PodTemplate{
- Template: core.PodTemplateSpec{
- ObjectMeta: metav1.ObjectMeta{
- Labels: validSelector,
- },
- Spec: core.PodSpec{
- Volumes: []core.Volume{{Name: "gcepd", VolumeSource: core.VolumeSource{GCEPersistentDisk: &core.GCEPersistentDiskVolumeSource{PDName: "my-PD", FSType: "ext4", Partition: 1, ReadOnly: false}}}},
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- Containers: []core.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- },
- },
- }
- invalidSelector := map[string]string{"NoUppercaseOrSpecialCharsLike=Equals": "b"}
- invalidPodTemplate := core.PodTemplate{
- Template: core.PodTemplateSpec{
- Spec: core.PodSpec{
- RestartPolicy: core.RestartPolicyAlways,
- DNSPolicy: core.DNSClusterFirst,
- },
- ObjectMeta: metav1.ObjectMeta{
- Labels: invalidSelector,
- },
- },
- }
- successCases := []core.ReplicationController{
- {
- ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: metav1.NamespaceDefault},
- Spec: core.ReplicationControllerSpec{
- Selector: validSelector,
- Template: &validPodTemplate.Template,
- },
- },
- {
- ObjectMeta: metav1.ObjectMeta{Name: "abc-123", Namespace: metav1.NamespaceDefault},
- Spec: core.ReplicationControllerSpec{
- Selector: validSelector,
- Template: &validPodTemplate.Template,
- },
- },
- {
- ObjectMeta: metav1.ObjectMeta{Name: "abc-123", Namespace: metav1.NamespaceDefault},
- Spec: core.ReplicationControllerSpec{
- Replicas: 1,
- Selector: validSelector,
- Template: &readWriteVolumePodTemplate.Template,
- },
- },
- }
- for _, successCase := range successCases {
- if errs := ValidateReplicationController(&successCase); len(errs) != 0 {
- t.Errorf("expected success: %v", errs)
- }
- }
- errorCases := map[string]core.ReplicationController{
- "zero-length ID": {
- ObjectMeta: metav1.ObjectMeta{Name: "", Namespace: metav1.NamespaceDefault},
- Spec: core.ReplicationControllerSpec{
- Selector: validSelector,
- Template: &validPodTemplate.Template,
- },
- },
- "missing-namespace": {
- ObjectMeta: metav1.ObjectMeta{Name: "abc-123"},
- Spec: core.ReplicationControllerSpec{
- Selector: validSelector,
- Template: &validPodTemplate.Template,
- },
- },
- "empty selector": {
- ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: metav1.NamespaceDefault},
- Spec: core.ReplicationControllerSpec{
- Template: &validPodTemplate.Template,
- },
- },
- "selector_doesnt_match": {
- ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: metav1.NamespaceDefault},
- Spec: core.ReplicationControllerSpec{
- Selector: map[string]string{"foo": "bar"},
- Template: &validPodTemplate.Template,
- },
- },
- "invalid manifest": {
- ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: metav1.NamespaceDefault},
- Spec: core.ReplicationControllerSpec{
- Selector: validSelector,
- },
- },
- "read-write persistent disk with > 1 pod": {
- ObjectMeta: metav1.ObjectMeta{Name: "abc"},
- Spec: core.ReplicationControllerSpec{
- Replicas: 2,
- Selector: validSelector,
- Template: &readWriteVolumePodTemplate.Template,
- },
- },
- "negative_replicas": {
- ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: metav1.NamespaceDefault},
- Spec: core.ReplicationControllerSpec{
- Replicas: -1,
- Selector: validSelector,
- },
- },
- "invalid_label": {
- ObjectMeta: metav1.ObjectMeta{
- Name: "abc-123",
- Namespace: metav1.NamespaceDefault,
- Labels: map[string]string{
- "NoUppercaseOrSpecialCharsLike=Equals": "bar",
- },
- },
- Spec: core.ReplicationControllerSpec{
- Selector: validSelector,
- Template: &validPodTemplate.Template,
- },
- },
- "invalid_label 2": {
- ObjectMeta: metav1.ObjectMeta{
- Name: "abc-123",
- Namespace: metav1.NamespaceDefault,
- Labels: map[string]string{
- "NoUppercaseOrSpecialCharsLike=Equals": "bar",
- },
- },
- Spec: core.ReplicationControllerSpec{
- Template: &invalidPodTemplate.Template,
- },
- },
- "invalid_annotation": {
- ObjectMeta: metav1.ObjectMeta{
- Name: "abc-123",
- Namespace: metav1.NamespaceDefault,
- Annotations: map[string]string{
- "NoUppercaseOrSpecialCharsLike=Equals": "bar",
- },
- },
- Spec: core.ReplicationControllerSpec{
- Selector: validSelector,
- Template: &validPodTemplate.Template,
- },
- },
- "invalid restart policy 1": {
- ObjectMeta: metav1.ObjectMeta{
- Name: "abc-123",
- Namespace: metav1.NamespaceDefault,
- },
- Spec: core.ReplicationControllerSpec{
- Selector: validSelector,
- Template: &core.PodTemplateSpec{
- Spec: core.PodSpec{
- RestartPolicy: core.RestartPolicyOnFailure,
- DNSPolicy: core.DNSClusterFirst,
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- },
- ObjectMeta: metav1.ObjectMeta{
- Labels: validSelector,
- },
- },
- },
- },
- "invalid restart policy 2": {
- ObjectMeta: metav1.ObjectMeta{
- Name: "abc-123",
- Namespace: metav1.NamespaceDefault,
- },
- Spec: core.ReplicationControllerSpec{
- Selector: validSelector,
- Template: &core.PodTemplateSpec{
- Spec: core.PodSpec{
- RestartPolicy: core.RestartPolicyNever,
- DNSPolicy: core.DNSClusterFirst,
- Containers: []core.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: "File"}},
- },
- ObjectMeta: metav1.ObjectMeta{
- Labels: validSelector,
- },
- },
- },
- },
- }
- for k, v := range errorCases {
- errs := ValidateReplicationController(&v)
- if len(errs) == 0 {
- t.Errorf("expected failure for %s", k)
- }
- for i := range errs {
- field := errs[i].Field
- if !strings.HasPrefix(field, "spec.template.") &&
- field != "metadata.name" &&
- field != "metadata.namespace" &&
- field != "spec.selector" &&
- field != "spec.template" &&
- field != "GCEPersistentDisk.ReadOnly" &&
- field != "spec.replicas" &&
- field != "spec.template.labels" &&
- field != "metadata.annotations" &&
- field != "metadata.labels" &&
- field != "status.replicas" {
- t.Errorf("%s: missing prefix for: %v", k, errs[i])
- }
- }
- }
- }
- func TestValidateNode(t *testing.T) {
- validSelector := map[string]string{"a": "b"}
- invalidSelector := map[string]string{"NoUppercaseOrSpecialCharsLike=Equals": "b"}
- successCases := []core.Node{
- {
- ObjectMeta: metav1.ObjectMeta{
- Name: "abc",
- Labels: validSelector,
- },
- Status: core.NodeStatus{
- Addresses: []core.NodeAddress{
- {Type: core.NodeExternalIP, Address: "something"},
- },
- Capacity: core.ResourceList{
- core.ResourceName(core.ResourceCPU): resource.MustParse("10"),
- core.ResourceName(core.ResourceMemory): resource.MustParse("10G"),
- core.ResourceName("my.org/gpu"): resource.MustParse("10"),
- core.ResourceName("hugepages-2Mi"): resource.MustParse("10Gi"),
- core.ResourceName("hugepages-1Gi"): resource.MustParse("0"),
- },
- },
- },
- {
- ObjectMeta: metav1.ObjectMeta{
- Name: "abc",
- },
- Status: core.NodeStatus{
- Addresses: []core.NodeAddress{
- {Type: core.NodeExternalIP, Address: "something"},
- },
- Capacity: core.ResourceList{
- core.ResourceName(core.ResourceCPU): resource.MustParse("10"),
- core.ResourceName(core.ResourceMemory): resource.MustParse("0"),
- },
- },
- },
- {
- ObjectMeta: metav1.ObjectMeta{
- Name: "dedicated-node1",
- },
- Status: core.NodeStatus{
- Addresses: []core.NodeAddress{
- {Type: core.NodeExternalIP, Address: "something"},
- },
- Capacity: core.ResourceList{
- core.ResourceName(core.ResourceCPU): resource.MustParse("10"),
- core.ResourceName(core.ResourceMemory): resource.MustParse("0"),
- },
- },
- Spec: core.NodeSpec{
- // Add a valid taint to a node
- Taints: []core.Taint{{Key: "GPU", Value: "true", Effect: "NoSchedule"}},
- },
- },
- {
- ObjectMeta: metav1.ObjectMeta{
- Name: "abc",
- Annotations: map[string]string{
- core.PreferAvoidPodsAnnotationKey: `
- {
- "preferAvoidPods": [
- {
- "podSignature": {
- "podController": {
- "apiVersion": "v1",
- "kind": "ReplicationController",
- "name": "foo",
- "uid": "abcdef123456",
- "controller": true
- }
- },
- "reason": "some reason",
- "message": "some message"
- }
- ]
- }`,
- },
- },
- Status: core.NodeStatus{
- Addresses: []core.NodeAddress{
- {Type: core.NodeExternalIP, Address: "something"},
- },
- Capacity: core.ResourceList{
- core.ResourceName(core.ResourceCPU): resource.MustParse("10"),
- core.ResourceName(core.ResourceMemory): resource.MustParse("0"),
- },
- },
- },
- {
- ObjectMeta: metav1.ObjectMeta{
- Name: "abc",
- },
- Status: core.NodeStatus{
- Addresses: []core.NodeAddress{
- {Type: core.NodeExternalIP, Address: "something"},
- },
- Capacity: core.ResourceList{
- core.ResourceName(core.ResourceCPU): resource.MustParse("10"),
- core.ResourceName(core.ResourceMemory): resource.MustParse("0"),
- },
- },
- Spec: core.NodeSpec{
- PodCIDR: "192.168.0.0/16",
- },
- },
- }
- for _, successCase := range successCases {
- if errs := ValidateNode(&successCase); len(errs) != 0 {
- t.Errorf("expected success: %v", errs)
- }
- }
- errorCases := map[string]core.Node{
- "zero-length Name": {
- ObjectMeta: metav1.ObjectMeta{
- Name: "",
- Labels: validSelector,
- },
- Status: core.NodeStatus{
- Addresses: []core.NodeAddress{},
- Capacity: core.ResourceList{
- core.ResourceName(core.ResourceCPU): resource.MustParse("10"),
- core.ResourceName(core.ResourceMemory): resource.MustParse("10G"),
- },
- },
- },
- "invalid-labels": {
- ObjectMeta: metav1.ObjectMeta{
- Name: "abc-123",
- Labels: invalidSelector,
- },
- Status: core.NodeStatus{
- Capacity: core.ResourceList{
- core.ResourceName(core.ResourceCPU): resource.MustParse("10"),
- core.ResourceName(core.ResourceMemory): resource.MustParse("10G"),
- },
- },
- },
- "missing-taint-key": {
- ObjectMeta: metav1.ObjectMeta{
- Name: "dedicated-node1",
- },
- Spec: core.NodeSpec{
- // Add a taint with an empty key to a node
- Taints: []core.Taint{{Key: "", Value: "special-user-1", Effect: "NoSchedule"}},
- },
- },
- "bad-taint-key": {
- ObjectMeta: metav1.ObjectMeta{
- Name: "dedicated-node1",
- },
- Spec: core.NodeSpec{
- // Add a taint with an invalid key to a node
- Taints: []core.Taint{{Key: "NoUppercaseOrSpecialCharsLike=Equals", Value: "special-user-1", Effect: "NoSchedule"}},
- },
- },
- "bad-taint-value": {
- ObjectMeta: metav1.ObjectMeta{
- Name: "dedicated-node2",
- },
- Status: core.NodeStatus{
- Addresses: []core.NodeAddress{
- {Type: core.NodeExternalIP, Address: "something"},
- },
- Capacity: core.ResourceList{
- core.ResourceName(core.ResourceCPU): resource.MustParse("10"),
- core.ResourceName(core.ResourceMemory): resource.MustParse("0"),
- },
- },
- Spec: core.NodeSpec{
- // Add a taint with a bad value to a node
- Taints: []core.Taint{{Key: "dedicated", Value: "some\\bad\\value", Effect: "NoSchedule"}},
- },
- },
- "missing-taint-effect": {
- ObjectMeta: metav1.ObjectMeta{
- Name: "dedicated-node3",
- },
- Status: core.NodeStatus{
- Addresses: []core.NodeAddress{
- {Type: core.NodeExternalIP, Address: "something"},
- },
- Capacity: core.ResourceList{
- core.ResourceName(core.ResourceCPU): resource.MustParse("10"),
- core.ResourceName(core.ResourceMemory): resource.MustParse("0"),
- },
- },
- Spec: core.NodeSpec{
- // Add a taint with an empty effect to a node
- Taints: []core.Taint{{Key: "dedicated", Value: "special-user-3", Effect: ""}},
- },
- },
- "invalid-taint-effect": {
- ObjectMeta: metav1.ObjectMeta{
- Name: "dedicated-node3",
- },
- Status: core.NodeStatus{
- Addresses: []core.NodeAddress{
- {Type: core.NodeExternalIP, Address: "something"},
- },
- Capacity: core.ResourceList{
- core.ResourceName(core.ResourceCPU): resource.MustParse("10"),
- core.ResourceName(core.ResourceMemory): resource.MustParse("0"),
- },
- },
- Spec: core.NodeSpec{
- // Add a taint with NoExecute effect to a node
- Taints: []core.Taint{{Key: "dedicated", Value: "special-user-3", Effect: "NoScheduleNoAdmit"}},
- },
- },
- "duplicated-taints-with-same-key-effect": {
- ObjectMeta: metav1.ObjectMeta{
- Name: "dedicated-node1",
- },
- Spec: core.NodeSpec{
- // Add two taints to the node with the same key and effect; should be rejected.
- Taints: []core.Taint{
- {Key: "dedicated", Value: "special-user-1", Effect: "NoSchedule"},
- {Key: "dedicated", Value: "special-user-2", Effect: "NoSchedule"},
- },
- },
- },
- "missing-podSignature": {
- ObjectMeta: metav1.ObjectMeta{
- Name: "abc-123",
- Annotations: map[string]string{
- core.PreferAvoidPodsAnnotationKey: `
- {
- "preferAvoidPods": [
- {
- "reason": "some reason",
- "message": "some message"
- }
- ]
- }`,
- },
- },
- Status: core.NodeStatus{
- Addresses: []core.NodeAddress{},
- Capacity: core.ResourceList{
- core.ResourceName(core.ResourceCPU): resource.MustParse("10"),
- core.ResourceName(core.ResourceMemory): resource.MustParse("0"),
- },
- },
- },
- "invalid-podController": {
- ObjectMeta: metav1.ObjectMeta{
- Name: "abc-123",
- Annotations: map[string]string{
- core.PreferAvoidPodsAnnotationKey: `
- {
- "preferAvoidPods": [
- {
- "podSignature": {
- "podController": {
- "apiVersion": "v1",
- "kind": "ReplicationController",
- "name": "foo",
- "uid": "abcdef123456",
- "controller": false
- }
- },
- "reason": "some reason",
- "message": "some message"
- }
- ]
- }`,
- },
- },
- Status: core.NodeStatus{
- Addresses: []core.NodeAddress{},
- Capacity: core.ResourceList{
- core.ResourceName(core.ResourceCPU): resource.MustParse("10"),
- core.ResourceName(core.ResourceMemory): resource.MustParse("0"),
- },
- },
- },
- "multiple-pre-allocated-hugepages": {
- ObjectMeta: metav1.ObjectMeta{
- Name: "abc",
- Labels: validSelector,
- },
- Status: core.NodeStatus{
- Addresses: []core.NodeAddress{
- {Type: core.NodeExternalIP, Address: "something"},
- },
- Capacity: core.ResourceList{
- core.ResourceName(core.ResourceCPU): resource.MustParse("10"),
- core.ResourceName(core.ResourceMemory): resource.MustParse("10G"),
- core.ResourceName("my.org/gpu"): resource.MustParse("10"),
- core.ResourceName("hugepages-2Mi"): resource.MustParse("10Gi"),
- core.ResourceName("hugepages-1Gi"): resource.MustParse("10Gi"),
- },
- },
- },
- "invalid-pod-cidr": {
- ObjectMeta: metav1.ObjectMeta{
- Name: "abc",
- },
- Status: core.NodeStatus{
- Addresses: []core.NodeAddress{
- {Type: core.NodeExternalIP, Address: "something"},
- },
- Capacity: core.ResourceList{
- core.ResourceName(core.ResourceCPU): resource.MustParse("10"),
- core.ResourceName(core.ResourceMemory): resource.MustParse("0"),
- },
- },
- Spec: core.NodeSpec{
- PodCIDR: "192.168.0.0",
- },
- },
- }
- for k, v := range errorCases {
- errs := ValidateNode(&v)
- if len(errs) == 0 {
- t.Errorf("expected failure for %s", k)
- }
- for i := range errs {
- field := errs[i].Field
- expectedFields := map[string]bool{
- "metadata.name": true,
- "metadata.labels": true,
- "metadata.annotations": true,
- "metadata.namespace": true,
- "spec.externalID": true,
- "spec.taints[0].key": true,
- "spec.taints[0].value": true,
- "spec.taints[0].effect": true,
- "metadata.annotations.scheduler.alpha.kubernetes.io/preferAvoidPods[0].PodSignature": true,
- "metadata.annotations.scheduler.alpha.kubernetes.io/preferAvoidPods[0].PodSignature.PodController.Controller": true,
- }
- if val, ok := expectedFields[field]; ok {
- if !val {
- t.Errorf("%s: missing prefix for: %v", k, errs[i])
- }
- }
- }
- }
- }
- func TestValidateNodeUpdate(t *testing.T) {
- tests := []struct {
- oldNode core.Node
- node core.Node
- valid bool
- }{
- {core.Node{}, core.Node{}, true},
- {core.Node{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo"}},
- core.Node{
- ObjectMeta: metav1.ObjectMeta{
- Name: "bar"},
- }, false},
- {core.Node{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- Labels: map[string]string{"foo": "bar"},
- },
- }, core.Node{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- Labels: map[string]string{"foo": "baz"},
- },
- }, true},
- {core.Node{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- },
- }, core.Node{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- Labels: map[string]string{"foo": "baz"},
- },
- }, true},
- {core.Node{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- Labels: map[string]string{"bar": "foo"},
- },
- }, core.Node{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- Labels: map[string]string{"foo": "baz"},
- },
- }, true},
- {core.Node{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- },
- Spec: core.NodeSpec{
- PodCIDR: "",
- },
- }, core.Node{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- },
- Spec: core.NodeSpec{
- PodCIDR: "192.168.0.0/16",
- },
- }, true},
- {core.Node{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- },
- Spec: core.NodeSpec{
- PodCIDR: "192.123.0.0/16",
- },
- }, core.Node{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- },
- Spec: core.NodeSpec{
- PodCIDR: "192.168.0.0/16",
- },
- }, false},
- {core.Node{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- },
- Status: core.NodeStatus{
- Capacity: core.ResourceList{
- core.ResourceCPU: resource.MustParse("10000"),
- core.ResourceMemory: resource.MustParse("100"),
- },
- },
- }, core.Node{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- },
- Status: core.NodeStatus{
- Capacity: core.ResourceList{
- core.ResourceCPU: resource.MustParse("100"),
- core.ResourceMemory: resource.MustParse("10000"),
- },
- },
- }, true},
- {core.Node{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- Labels: map[string]string{"bar": "foo"},
- },
- Status: core.NodeStatus{
- Capacity: core.ResourceList{
- core.ResourceCPU: resource.MustParse("10000"),
- core.ResourceMemory: resource.MustParse("100"),
- },
- },
- }, core.Node{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- Labels: map[string]string{"bar": "fooobaz"},
- },
- Status: core.NodeStatus{
- Capacity: core.ResourceList{
- core.ResourceCPU: resource.MustParse("100"),
- core.ResourceMemory: resource.MustParse("10000"),
- },
- },
- }, true},
- {core.Node{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- Labels: map[string]string{"bar": "foo"},
- },
- Status: core.NodeStatus{
- Addresses: []core.NodeAddress{
- {Type: core.NodeExternalIP, Address: "1.2.3.4"},
- },
- },
- }, core.Node{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- Labels: map[string]string{"bar": "fooobaz"},
- },
- }, true},
- {core.Node{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- Labels: map[string]string{"foo": "baz"},
- },
- }, core.Node{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- Labels: map[string]string{"Foo": "baz"},
- },
- }, true},
- {core.Node{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- },
- Spec: core.NodeSpec{
- Unschedulable: false,
- },
- }, core.Node{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- },
- Spec: core.NodeSpec{
- Unschedulable: true,
- },
- }, true},
- {core.Node{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- },
- Spec: core.NodeSpec{
- Unschedulable: false,
- },
- }, core.Node{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- },
- Status: core.NodeStatus{
- Addresses: []core.NodeAddress{
- {Type: core.NodeExternalIP, Address: "1.1.1.1"},
- {Type: core.NodeExternalIP, Address: "1.1.1.1"},
- },
- },
- }, false},
- {core.Node{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- },
- Spec: core.NodeSpec{
- Unschedulable: false,
- },
- }, core.Node{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- },
- Status: core.NodeStatus{
- Addresses: []core.NodeAddress{
- {Type: core.NodeExternalIP, Address: "1.1.1.1"},
- {Type: core.NodeInternalIP, Address: "10.1.1.1"},
- },
- },
- }, true},
- {core.Node{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- },
- }, core.Node{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- Annotations: map[string]string{
- core.PreferAvoidPodsAnnotationKey: `
- {
- "preferAvoidPods": [
- {
- "podSignature": {
- "podController": {
- "apiVersion": "v1",
- "kind": "ReplicationController",
- "name": "foo",
- "uid": "abcdef123456",
- "controller": true
- }
- },
- "reason": "some reason",
- "message": "some message"
- }
- ]
- }`,
- },
- },
- Spec: core.NodeSpec{
- Unschedulable: false,
- },
- }, true},
- {core.Node{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- },
- }, core.Node{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- Annotations: map[string]string{
- core.PreferAvoidPodsAnnotationKey: `
- {
- "preferAvoidPods": [
- {
- "reason": "some reason",
- "message": "some message"
- }
- ]
- }`,
- },
- },
- }, false},
- {core.Node{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- },
- }, core.Node{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- Annotations: map[string]string{
- core.PreferAvoidPodsAnnotationKey: `
- {
- "preferAvoidPods": [
- {
- "podSignature": {
- "podController": {
- "apiVersion": "v1",
- "kind": "ReplicationController",
- "name": "foo",
- "uid": "abcdef123456",
- "controller": false
- }
- },
- "reason": "some reason",
- "message": "some message"
- }
- ]
- }`,
- },
- },
- }, false},
- {core.Node{
- ObjectMeta: metav1.ObjectMeta{
- Name: "valid-extended-resources",
- },
- }, core.Node{
- ObjectMeta: metav1.ObjectMeta{
- Name: "valid-extended-resources",
- },
- Status: core.NodeStatus{
- Capacity: core.ResourceList{
- core.ResourceName(core.ResourceCPU): resource.MustParse("10"),
- core.ResourceName(core.ResourceMemory): resource.MustParse("10G"),
- core.ResourceName("example.com/a"): resource.MustParse("5"),
- core.ResourceName("example.com/b"): resource.MustParse("10"),
- },
- },
- }, true},
- {core.Node{
- ObjectMeta: metav1.ObjectMeta{
- Name: "invalid-fractional-extended-capacity",
- },
- }, core.Node{
- ObjectMeta: metav1.ObjectMeta{
- Name: "invalid-fractional-extended-capacity",
- },
- Status: core.NodeStatus{
- Capacity: core.ResourceList{
- core.ResourceName(core.ResourceCPU): resource.MustParse("10"),
- core.ResourceName(core.ResourceMemory): resource.MustParse("10G"),
- core.ResourceName("example.com/a"): resource.MustParse("500m"),
- },
- },
- }, false},
- {core.Node{
- ObjectMeta: metav1.ObjectMeta{
- Name: "invalid-fractional-extended-allocatable",
- },
- }, core.Node{
- ObjectMeta: metav1.ObjectMeta{
- Name: "invalid-fractional-extended-allocatable",
- },
- Status: core.NodeStatus{
- Capacity: core.ResourceList{
- core.ResourceName(core.ResourceCPU): resource.MustParse("10"),
- core.ResourceName(core.ResourceMemory): resource.MustParse("10G"),
- core.ResourceName("example.com/a"): resource.MustParse("5"),
- },
- Allocatable: core.ResourceList{
- core.ResourceName(core.ResourceCPU): resource.MustParse("10"),
- core.ResourceName(core.ResourceMemory): resource.MustParse("10G"),
- core.ResourceName("example.com/a"): resource.MustParse("4.5"),
- },
- },
- }, false},
- {core.Node{
- ObjectMeta: metav1.ObjectMeta{
- Name: "update-provider-id-when-not-set",
- },
- }, core.Node{
- ObjectMeta: metav1.ObjectMeta{
- Name: "update-provider-id-when-not-set",
- },
- Spec: core.NodeSpec{
- ProviderID: "provider:///new",
- },
- }, true},
- {core.Node{
- ObjectMeta: metav1.ObjectMeta{
- Name: "update-provider-id-when-set",
- },
- Spec: core.NodeSpec{
- ProviderID: "provider:///old",
- },
- }, core.Node{
- ObjectMeta: metav1.ObjectMeta{
- Name: "update-provider-id-when-set",
- },
- Spec: core.NodeSpec{
- ProviderID: "provider:///new",
- },
- }, false},
- }
- for i, test := range tests {
- test.oldNode.ObjectMeta.ResourceVersion = "1"
- test.node.ObjectMeta.ResourceVersion = "1"
- errs := ValidateNodeUpdate(&test.node, &test.oldNode)
- if test.valid && len(errs) > 0 {
- t.Errorf("%d: Unexpected error: %v", i, errs)
- t.Logf("%#v vs %#v", test.oldNode.ObjectMeta, test.node.ObjectMeta)
- }
- if !test.valid && len(errs) == 0 {
- t.Errorf("%d: Unexpected non-error", i)
- }
- }
- }
- func TestValidateServiceUpdate(t *testing.T) {
- testCases := []struct {
- name string
- tweakSvc func(oldSvc, newSvc *core.Service) // given basic valid services, each test case can customize them
- numErrs int
- }{
- {
- name: "no change",
- tweakSvc: func(oldSvc, newSvc *core.Service) {
- // do nothing
- },
- numErrs: 0,
- },
- {
- name: "change name",
- tweakSvc: func(oldSvc, newSvc *core.Service) {
- newSvc.Name += "2"
- },
- numErrs: 1,
- },
- {
- name: "change namespace",
- tweakSvc: func(oldSvc, newSvc *core.Service) {
- newSvc.Namespace += "2"
- },
- numErrs: 1,
- },
- {
- name: "change label valid",
- tweakSvc: func(oldSvc, newSvc *core.Service) {
- newSvc.Labels["key"] = "other-value"
- },
- numErrs: 0,
- },
- {
- name: "add label",
- tweakSvc: func(oldSvc, newSvc *core.Service) {
- newSvc.Labels["key2"] = "value2"
- },
- numErrs: 0,
- },
- {
- name: "change cluster IP",
- tweakSvc: func(oldSvc, newSvc *core.Service) {
- oldSvc.Spec.ClusterIP = "1.2.3.4"
- newSvc.Spec.ClusterIP = "8.6.7.5"
- },
- numErrs: 1,
- },
- {
- name: "remove cluster IP",
- tweakSvc: func(oldSvc, newSvc *core.Service) {
- oldSvc.Spec.ClusterIP = "1.2.3.4"
- newSvc.Spec.ClusterIP = ""
- },
- numErrs: 1,
- },
- {
- name: "change affinity",
- tweakSvc: func(oldSvc, newSvc *core.Service) {
- newSvc.Spec.SessionAffinity = "ClientIP"
- newSvc.Spec.SessionAffinityConfig = &core.SessionAffinityConfig{
- ClientIP: &core.ClientIPConfig{
- TimeoutSeconds: utilpointer.Int32Ptr(90),
- },
- }
- },
- numErrs: 0,
- },
- {
- name: "remove affinity",
- tweakSvc: func(oldSvc, newSvc *core.Service) {
- newSvc.Spec.SessionAffinity = ""
- },
- numErrs: 1,
- },
- {
- name: "change type",
- tweakSvc: func(oldSvc, newSvc *core.Service) {
- newSvc.Spec.Type = core.ServiceTypeLoadBalancer
- },
- numErrs: 0,
- },
- {
- name: "remove type",
- tweakSvc: func(oldSvc, newSvc *core.Service) {
- newSvc.Spec.Type = ""
- },
- numErrs: 1,
- },
- {
- name: "change type -> nodeport",
- tweakSvc: func(oldSvc, newSvc *core.Service) {
- newSvc.Spec.Type = core.ServiceTypeNodePort
- },
- numErrs: 0,
- },
- {
- name: "add loadBalancerSourceRanges",
- tweakSvc: func(oldSvc, newSvc *core.Service) {
- oldSvc.Spec.Type = core.ServiceTypeLoadBalancer
- newSvc.Spec.Type = core.ServiceTypeLoadBalancer
- newSvc.Spec.LoadBalancerSourceRanges = []string{"10.0.0.0/8"}
- },
- numErrs: 0,
- },
- {
- name: "update loadBalancerSourceRanges",
- tweakSvc: func(oldSvc, newSvc *core.Service) {
- oldSvc.Spec.Type = core.ServiceTypeLoadBalancer
- oldSvc.Spec.LoadBalancerSourceRanges = []string{"10.0.0.0/8"}
- newSvc.Spec.Type = core.ServiceTypeLoadBalancer
- newSvc.Spec.LoadBalancerSourceRanges = []string{"10.100.0.0/16"}
- },
- numErrs: 0,
- },
- {
- name: "LoadBalancer type cannot have None ClusterIP",
- tweakSvc: func(oldSvc, newSvc *core.Service) {
- newSvc.Spec.ClusterIP = "None"
- newSvc.Spec.Type = core.ServiceTypeLoadBalancer
- },
- numErrs: 1,
- },
- {
- name: "`None` ClusterIP cannot be changed",
- tweakSvc: func(oldSvc, newSvc *core.Service) {
- oldSvc.Spec.ClusterIP = "None"
- newSvc.Spec.ClusterIP = "1.2.3.4"
- },
- numErrs: 1,
- },
- {
- name: "`None` ClusterIP cannot be removed",
- tweakSvc: func(oldSvc, newSvc *core.Service) {
- oldSvc.Spec.ClusterIP = "None"
- newSvc.Spec.ClusterIP = ""
- },
- numErrs: 1,
- },
- {
- name: "Service with ClusterIP type cannot change its set ClusterIP",
- tweakSvc: func(oldSvc, newSvc *core.Service) {
- oldSvc.Spec.Type = core.ServiceTypeClusterIP
- newSvc.Spec.Type = core.ServiceTypeClusterIP
- oldSvc.Spec.ClusterIP = "1.2.3.4"
- newSvc.Spec.ClusterIP = "1.2.3.5"
- },
- numErrs: 1,
- },
- {
- name: "Service with ClusterIP type can change its empty ClusterIP",
- tweakSvc: func(oldSvc, newSvc *core.Service) {
- oldSvc.Spec.Type = core.ServiceTypeClusterIP
- newSvc.Spec.Type = core.ServiceTypeClusterIP
- oldSvc.Spec.ClusterIP = ""
- newSvc.Spec.ClusterIP = "1.2.3.5"
- },
- numErrs: 0,
- },
- {
- name: "Service with ClusterIP type cannot change its set ClusterIP when changing type to NodePort",
- tweakSvc: func(oldSvc, newSvc *core.Service) {
- oldSvc.Spec.Type = core.ServiceTypeClusterIP
- newSvc.Spec.Type = core.ServiceTypeNodePort
- oldSvc.Spec.ClusterIP = "1.2.3.4"
- newSvc.Spec.ClusterIP = "1.2.3.5"
- },
- numErrs: 1,
- },
- {
- name: "Service with ClusterIP type can change its empty ClusterIP when changing type to NodePort",
- tweakSvc: func(oldSvc, newSvc *core.Service) {
- oldSvc.Spec.Type = core.ServiceTypeClusterIP
- newSvc.Spec.Type = core.ServiceTypeNodePort
- oldSvc.Spec.ClusterIP = ""
- newSvc.Spec.ClusterIP = "1.2.3.5"
- },
- numErrs: 0,
- },
- {
- name: "Service with ClusterIP type cannot change its ClusterIP when changing type to LoadBalancer",
- tweakSvc: func(oldSvc, newSvc *core.Service) {
- oldSvc.Spec.Type = core.ServiceTypeClusterIP
- newSvc.Spec.Type = core.ServiceTypeLoadBalancer
- oldSvc.Spec.ClusterIP = "1.2.3.4"
- newSvc.Spec.ClusterIP = "1.2.3.5"
- },
- numErrs: 1,
- },
- {
- name: "Service with ClusterIP type can change its empty ClusterIP when changing type to LoadBalancer",
- tweakSvc: func(oldSvc, newSvc *core.Service) {
- oldSvc.Spec.Type = core.ServiceTypeClusterIP
- newSvc.Spec.Type = core.ServiceTypeLoadBalancer
- oldSvc.Spec.ClusterIP = ""
- newSvc.Spec.ClusterIP = "1.2.3.5"
- },
- numErrs: 0,
- },
- {
- name: "Service with NodePort type cannot change its set ClusterIP",
- tweakSvc: func(oldSvc, newSvc *core.Service) {
- oldSvc.Spec.Type = core.ServiceTypeNodePort
- newSvc.Spec.Type = core.ServiceTypeNodePort
- oldSvc.Spec.ClusterIP = "1.2.3.4"
- newSvc.Spec.ClusterIP = "1.2.3.5"
- },
- numErrs: 1,
- },
- {
- name: "Service with NodePort type can change its empty ClusterIP",
- tweakSvc: func(oldSvc, newSvc *core.Service) {
- oldSvc.Spec.Type = core.ServiceTypeNodePort
- newSvc.Spec.Type = core.ServiceTypeNodePort
- oldSvc.Spec.ClusterIP = ""
- newSvc.Spec.ClusterIP = "1.2.3.5"
- },
- numErrs: 0,
- },
- {
- name: "Service with NodePort type cannot change its set ClusterIP when changing type to ClusterIP",
- tweakSvc: func(oldSvc, newSvc *core.Service) {
- oldSvc.Spec.Type = core.ServiceTypeNodePort
- newSvc.Spec.Type = core.ServiceTypeClusterIP
- oldSvc.Spec.ClusterIP = "1.2.3.4"
- newSvc.Spec.ClusterIP = "1.2.3.5"
- },
- numErrs: 1,
- },
- {
- name: "Service with NodePort type can change its empty ClusterIP when changing type to ClusterIP",
- tweakSvc: func(oldSvc, newSvc *core.Service) {
- oldSvc.Spec.Type = core.ServiceTypeNodePort
- newSvc.Spec.Type = core.ServiceTypeClusterIP
- oldSvc.Spec.ClusterIP = ""
- newSvc.Spec.ClusterIP = "1.2.3.5"
- },
- numErrs: 0,
- },
- {
- name: "Service with NodePort type cannot change its set ClusterIP when changing type to LoadBalancer",
- tweakSvc: func(oldSvc, newSvc *core.Service) {
- oldSvc.Spec.Type = core.ServiceTypeNodePort
- newSvc.Spec.Type = core.ServiceTypeLoadBalancer
- oldSvc.Spec.ClusterIP = "1.2.3.4"
- newSvc.Spec.ClusterIP = "1.2.3.5"
- },
- numErrs: 1,
- },
- {
- name: "Service with NodePort type can change its empty ClusterIP when changing type to LoadBalancer",
- tweakSvc: func(oldSvc, newSvc *core.Service) {
- oldSvc.Spec.Type = core.ServiceTypeNodePort
- newSvc.Spec.Type = core.ServiceTypeLoadBalancer
- oldSvc.Spec.ClusterIP = ""
- newSvc.Spec.ClusterIP = "1.2.3.5"
- },
- numErrs: 0,
- },
- {
- name: "Service with LoadBalancer type cannot change its set ClusterIP",
- tweakSvc: func(oldSvc, newSvc *core.Service) {
- oldSvc.Spec.Type = core.ServiceTypeLoadBalancer
- newSvc.Spec.Type = core.ServiceTypeLoadBalancer
- oldSvc.Spec.ClusterIP = "1.2.3.4"
- newSvc.Spec.ClusterIP = "1.2.3.5"
- },
- numErrs: 1,
- },
- {
- name: "Service with LoadBalancer type can change its empty ClusterIP",
- tweakSvc: func(oldSvc, newSvc *core.Service) {
- oldSvc.Spec.Type = core.ServiceTypeLoadBalancer
- newSvc.Spec.Type = core.ServiceTypeLoadBalancer
- oldSvc.Spec.ClusterIP = ""
- newSvc.Spec.ClusterIP = "1.2.3.5"
- },
- numErrs: 0,
- },
- {
- name: "Service with LoadBalancer type cannot change its set ClusterIP when changing type to ClusterIP",
- tweakSvc: func(oldSvc, newSvc *core.Service) {
- oldSvc.Spec.Type = core.ServiceTypeLoadBalancer
- newSvc.Spec.Type = core.ServiceTypeClusterIP
- oldSvc.Spec.ClusterIP = "1.2.3.4"
- newSvc.Spec.ClusterIP = "1.2.3.5"
- },
- numErrs: 1,
- },
- {
- name: "Service with LoadBalancer type can change its empty ClusterIP when changing type to ClusterIP",
- tweakSvc: func(oldSvc, newSvc *core.Service) {
- oldSvc.Spec.Type = core.ServiceTypeLoadBalancer
- newSvc.Spec.Type = core.ServiceTypeClusterIP
- oldSvc.Spec.ClusterIP = ""
- newSvc.Spec.ClusterIP = "1.2.3.5"
- },
- numErrs: 0,
- },
- {
- name: "Service with LoadBalancer type cannot change its set ClusterIP when changing type to NodePort",
- tweakSvc: func(oldSvc, newSvc *core.Service) {
- oldSvc.Spec.Type = core.ServiceTypeLoadBalancer
- newSvc.Spec.Type = core.ServiceTypeNodePort
- oldSvc.Spec.ClusterIP = "1.2.3.4"
- newSvc.Spec.ClusterIP = "1.2.3.5"
- },
- numErrs: 1,
- },
- {
- name: "Service with LoadBalancer type can change its empty ClusterIP when changing type to NodePort",
- tweakSvc: func(oldSvc, newSvc *core.Service) {
- oldSvc.Spec.Type = core.ServiceTypeLoadBalancer
- newSvc.Spec.Type = core.ServiceTypeNodePort
- oldSvc.Spec.ClusterIP = ""
- newSvc.Spec.ClusterIP = "1.2.3.5"
- },
- numErrs: 0,
- },
- {
- name: "Service with ExternalName type can change its empty ClusterIP when changing type to ClusterIP",
- tweakSvc: func(oldSvc, newSvc *core.Service) {
- oldSvc.Spec.Type = core.ServiceTypeExternalName
- newSvc.Spec.Type = core.ServiceTypeClusterIP
- oldSvc.Spec.ClusterIP = ""
- newSvc.Spec.ClusterIP = "1.2.3.5"
- },
- numErrs: 0,
- },
- {
- name: "Service with ExternalName type can change its set ClusterIP when changing type to ClusterIP",
- tweakSvc: func(oldSvc, newSvc *core.Service) {
- oldSvc.Spec.Type = core.ServiceTypeExternalName
- newSvc.Spec.Type = core.ServiceTypeClusterIP
- oldSvc.Spec.ClusterIP = "1.2.3.4"
- newSvc.Spec.ClusterIP = "1.2.3.5"
- },
- numErrs: 0,
- },
- {
- name: "invalid node port with clusterIP None",
- tweakSvc: func(oldSvc, newSvc *core.Service) {
- oldSvc.Spec.Type = core.ServiceTypeNodePort
- newSvc.Spec.Type = core.ServiceTypeNodePort
- oldSvc.Spec.Ports = append(oldSvc.Spec.Ports, core.ServicePort{Name: "q", Port: 1, Protocol: "TCP", NodePort: 1, TargetPort: intstr.FromInt(1)})
- newSvc.Spec.Ports = append(newSvc.Spec.Ports, core.ServicePort{Name: "q", Port: 1, Protocol: "TCP", NodePort: 1, TargetPort: intstr.FromInt(1)})
- oldSvc.Spec.ClusterIP = ""
- newSvc.Spec.ClusterIP = "None"
- },
- numErrs: 1,
- },
- }
- for _, tc := range testCases {
- oldSvc := makeValidService()
- newSvc := makeValidService()
- tc.tweakSvc(&oldSvc, &newSvc)
- errs := ValidateServiceUpdate(&newSvc, &oldSvc)
- if len(errs) != tc.numErrs {
- t.Errorf("Unexpected error list for case %q: %v", tc.name, errs.ToAggregate())
- }
- }
- }
- func TestValidateResourceNames(t *testing.T) {
- table := []struct {
- input string
- success bool
- expect string
- }{
- {"memory", true, ""},
- {"cpu", true, ""},
- {"storage", true, ""},
- {"requests.cpu", true, ""},
- {"requests.memory", true, ""},
- {"requests.storage", true, ""},
- {"limits.cpu", true, ""},
- {"limits.memory", true, ""},
- {"network", false, ""},
- {"disk", false, ""},
- {"", false, ""},
- {".", false, ""},
- {"..", false, ""},
- {"my.favorite.app.co/12345", true, ""},
- {"my.favorite.app.co/_12345", false, ""},
- {"my.favorite.app.co/12345_", false, ""},
- {"kubernetes.io/..", false, ""},
- {"kubernetes.io/" + strings.Repeat("a", 63), true, ""},
- {"kubernetes.io/" + strings.Repeat("a", 64), false, ""},
- {"kubernetes.io//", false, ""},
- {"kubernetes.io", false, ""},
- {"kubernetes.io/will/not/work/", false, ""},
- }
- for k, item := range table {
- err := validateResourceName(item.input, field.NewPath("field"))
- if len(err) != 0 && item.success {
- t.Errorf("expected no failure for input %q", item.input)
- } else if len(err) == 0 && !item.success {
- t.Errorf("expected failure for input %q", item.input)
- for i := range err {
- detail := err[i].Detail
- if detail != "" && !strings.Contains(detail, item.expect) {
- t.Errorf("%d: expected error detail either empty or %s, got %s", k, item.expect, detail)
- }
- }
- }
- }
- }
- func getResourceList(cpu, memory string) core.ResourceList {
- res := core.ResourceList{}
- if cpu != "" {
- res[core.ResourceCPU] = resource.MustParse(cpu)
- }
- if memory != "" {
- res[core.ResourceMemory] = resource.MustParse(memory)
- }
- return res
- }
- func getStorageResourceList(storage string) core.ResourceList {
- res := core.ResourceList{}
- if storage != "" {
- res[core.ResourceStorage] = resource.MustParse(storage)
- }
- return res
- }
- func getLocalStorageResourceList(ephemeralStorage string) core.ResourceList {
- res := core.ResourceList{}
- if ephemeralStorage != "" {
- res[core.ResourceEphemeralStorage] = resource.MustParse(ephemeralStorage)
- }
- return res
- }
- func TestValidateLimitRangeForLocalStorage(t *testing.T) {
- testCases := []struct {
- name string
- spec core.LimitRangeSpec
- }{
- {
- name: "all-fields-valid",
- spec: core.LimitRangeSpec{
- Limits: []core.LimitRangeItem{
- {
- Type: core.LimitTypePod,
- Max: getLocalStorageResourceList("10000Mi"),
- Min: getLocalStorageResourceList("100Mi"),
- MaxLimitRequestRatio: getLocalStorageResourceList(""),
- },
- {
- Type: core.LimitTypeContainer,
- Max: getLocalStorageResourceList("10000Mi"),
- Min: getLocalStorageResourceList("100Mi"),
- Default: getLocalStorageResourceList("500Mi"),
- DefaultRequest: getLocalStorageResourceList("200Mi"),
- MaxLimitRequestRatio: getLocalStorageResourceList(""),
- },
- },
- },
- },
- }
- for _, testCase := range testCases {
- limitRange := &core.LimitRange{ObjectMeta: metav1.ObjectMeta{Name: testCase.name, Namespace: "foo"}, Spec: testCase.spec}
- if errs := ValidateLimitRange(limitRange); len(errs) != 0 {
- t.Errorf("Case %v, unexpected error: %v", testCase.name, errs)
- }
- }
- }
- func TestValidateLimitRange(t *testing.T) {
- successCases := []struct {
- name string
- spec core.LimitRangeSpec
- }{
- {
- name: "all-fields-valid",
- spec: core.LimitRangeSpec{
- Limits: []core.LimitRangeItem{
- {
- Type: core.LimitTypePod,
- Max: getResourceList("100m", "10000Mi"),
- Min: getResourceList("5m", "100Mi"),
- MaxLimitRequestRatio: getResourceList("10", ""),
- },
- {
- Type: core.LimitTypeContainer,
- Max: getResourceList("100m", "10000Mi"),
- Min: getResourceList("5m", "100Mi"),
- Default: getResourceList("50m", "500Mi"),
- DefaultRequest: getResourceList("10m", "200Mi"),
- MaxLimitRequestRatio: getResourceList("10", ""),
- },
- {
- Type: core.LimitTypePersistentVolumeClaim,
- Max: getStorageResourceList("10Gi"),
- Min: getStorageResourceList("5Gi"),
- },
- },
- },
- },
- {
- name: "pvc-min-only",
- spec: core.LimitRangeSpec{
- Limits: []core.LimitRangeItem{
- {
- Type: core.LimitTypePersistentVolumeClaim,
- Min: getStorageResourceList("5Gi"),
- },
- },
- },
- },
- {
- name: "pvc-max-only",
- spec: core.LimitRangeSpec{
- Limits: []core.LimitRangeItem{
- {
- Type: core.LimitTypePersistentVolumeClaim,
- Max: getStorageResourceList("10Gi"),
- },
- },
- },
- },
- {
- name: "all-fields-valid-big-numbers",
- spec: core.LimitRangeSpec{
- Limits: []core.LimitRangeItem{
- {
- Type: core.LimitTypeContainer,
- Max: getResourceList("100m", "10000T"),
- Min: getResourceList("5m", "100Mi"),
- Default: getResourceList("50m", "500Mi"),
- DefaultRequest: getResourceList("10m", "200Mi"),
- MaxLimitRequestRatio: getResourceList("10", ""),
- },
- },
- },
- },
- {
- name: "thirdparty-fields-all-valid-standard-container-resources",
- spec: core.LimitRangeSpec{
- Limits: []core.LimitRangeItem{
- {
- Type: "thirdparty.com/foo",
- Max: getResourceList("100m", "10000T"),
- Min: getResourceList("5m", "100Mi"),
- Default: getResourceList("50m", "500Mi"),
- DefaultRequest: getResourceList("10m", "200Mi"),
- MaxLimitRequestRatio: getResourceList("10", ""),
- },
- },
- },
- },
- {
- name: "thirdparty-fields-all-valid-storage-resources",
- spec: core.LimitRangeSpec{
- Limits: []core.LimitRangeItem{
- {
- Type: "thirdparty.com/foo",
- Max: getStorageResourceList("10000T"),
- Min: getStorageResourceList("100Mi"),
- Default: getStorageResourceList("500Mi"),
- DefaultRequest: getStorageResourceList("200Mi"),
- MaxLimitRequestRatio: getStorageResourceList(""),
- },
- },
- },
- },
- }
- for _, successCase := range successCases {
- limitRange := &core.LimitRange{ObjectMeta: metav1.ObjectMeta{Name: successCase.name, Namespace: "foo"}, Spec: successCase.spec}
- if errs := ValidateLimitRange(limitRange); len(errs) != 0 {
- t.Errorf("Case %v, unexpected error: %v", successCase.name, errs)
- }
- }
- errorCases := map[string]struct {
- R core.LimitRange
- D string
- }{
- "zero-length-name": {
- core.LimitRange{ObjectMeta: metav1.ObjectMeta{Name: "", Namespace: "foo"}, Spec: core.LimitRangeSpec{}},
- "name or generateName is required",
- },
- "zero-length-namespace": {
- core.LimitRange{ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: ""}, Spec: core.LimitRangeSpec{}},
- "",
- },
- "invalid-name": {
- core.LimitRange{ObjectMeta: metav1.ObjectMeta{Name: "^Invalid", Namespace: "foo"}, Spec: core.LimitRangeSpec{}},
- dnsSubdomainLabelErrMsg,
- },
- "invalid-namespace": {
- core.LimitRange{ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: "^Invalid"}, Spec: core.LimitRangeSpec{}},
- dnsLabelErrMsg,
- },
- "duplicate-limit-type": {
- core.LimitRange{ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: core.LimitRangeSpec{
- Limits: []core.LimitRangeItem{
- {
- Type: core.LimitTypePod,
- Max: getResourceList("100m", "10000m"),
- Min: getResourceList("0m", "100m"),
- },
- {
- Type: core.LimitTypePod,
- Min: getResourceList("0m", "100m"),
- },
- },
- }},
- "",
- },
- "default-limit-type-pod": {
- core.LimitRange{ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: core.LimitRangeSpec{
- Limits: []core.LimitRangeItem{
- {
- Type: core.LimitTypePod,
- Max: getResourceList("100m", "10000m"),
- Min: getResourceList("0m", "100m"),
- Default: getResourceList("10m", "100m"),
- },
- },
- }},
- "may not be specified when `type` is 'Pod'",
- },
- "default-request-limit-type-pod": {
- core.LimitRange{ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: core.LimitRangeSpec{
- Limits: []core.LimitRangeItem{
- {
- Type: core.LimitTypePod,
- Max: getResourceList("100m", "10000m"),
- Min: getResourceList("0m", "100m"),
- DefaultRequest: getResourceList("10m", "100m"),
- },
- },
- }},
- "may not be specified when `type` is 'Pod'",
- },
- "min value 100m is greater than max value 10m": {
- core.LimitRange{ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: core.LimitRangeSpec{
- Limits: []core.LimitRangeItem{
- {
- Type: core.LimitTypePod,
- Max: getResourceList("10m", ""),
- Min: getResourceList("100m", ""),
- },
- },
- }},
- "min value 100m is greater than max value 10m",
- },
- "invalid spec default outside range": {
- core.LimitRange{ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: core.LimitRangeSpec{
- Limits: []core.LimitRangeItem{
- {
- Type: core.LimitTypeContainer,
- Max: getResourceList("1", ""),
- Min: getResourceList("100m", ""),
- Default: getResourceList("2000m", ""),
- },
- },
- }},
- "default value 2 is greater than max value 1",
- },
- "invalid spec default request outside range": {
- core.LimitRange{ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: core.LimitRangeSpec{
- Limits: []core.LimitRangeItem{
- {
- Type: core.LimitTypeContainer,
- Max: getResourceList("1", ""),
- Min: getResourceList("100m", ""),
- DefaultRequest: getResourceList("2000m", ""),
- },
- },
- }},
- "default request value 2 is greater than max value 1",
- },
- "invalid spec default request more than default": {
- core.LimitRange{ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: core.LimitRangeSpec{
- Limits: []core.LimitRangeItem{
- {
- Type: core.LimitTypeContainer,
- Max: getResourceList("2", ""),
- Min: getResourceList("100m", ""),
- Default: getResourceList("500m", ""),
- DefaultRequest: getResourceList("800m", ""),
- },
- },
- }},
- "default request value 800m is greater than default limit value 500m",
- },
- "invalid spec maxLimitRequestRatio less than 1": {
- core.LimitRange{ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: core.LimitRangeSpec{
- Limits: []core.LimitRangeItem{
- {
- Type: core.LimitTypePod,
- MaxLimitRequestRatio: getResourceList("800m", ""),
- },
- },
- }},
- "ratio 800m is less than 1",
- },
- "invalid spec maxLimitRequestRatio greater than max/min": {
- core.LimitRange{ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: core.LimitRangeSpec{
- Limits: []core.LimitRangeItem{
- {
- Type: core.LimitTypeContainer,
- Max: getResourceList("", "2Gi"),
- Min: getResourceList("", "512Mi"),
- MaxLimitRequestRatio: getResourceList("", "10"),
- },
- },
- }},
- "ratio 10 is greater than max/min = 4.000000",
- },
- "invalid non standard limit type": {
- core.LimitRange{ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: core.LimitRangeSpec{
- Limits: []core.LimitRangeItem{
- {
- Type: "foo",
- Max: getStorageResourceList("10000T"),
- Min: getStorageResourceList("100Mi"),
- Default: getStorageResourceList("500Mi"),
- DefaultRequest: getStorageResourceList("200Mi"),
- MaxLimitRequestRatio: getStorageResourceList(""),
- },
- },
- }},
- "must be a standard limit type or fully qualified",
- },
- "min and max values missing, one required": {
- core.LimitRange{ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: core.LimitRangeSpec{
- Limits: []core.LimitRangeItem{
- {
- Type: core.LimitTypePersistentVolumeClaim,
- },
- },
- }},
- "either minimum or maximum storage value is required, but neither was provided",
- },
- "invalid min greater than max": {
- core.LimitRange{ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: core.LimitRangeSpec{
- Limits: []core.LimitRangeItem{
- {
- Type: core.LimitTypePersistentVolumeClaim,
- Min: getStorageResourceList("10Gi"),
- Max: getStorageResourceList("1Gi"),
- },
- },
- }},
- "min value 10Gi is greater than max value 1Gi",
- },
- }
- for k, v := range errorCases {
- errs := ValidateLimitRange(&v.R)
- if len(errs) == 0 {
- t.Errorf("expected failure for %s", k)
- }
- for i := range errs {
- detail := errs[i].Detail
- if !strings.Contains(detail, v.D) {
- t.Errorf("[%s]: expected error detail either empty or %q, got %q", k, v.D, detail)
- }
- }
- }
- }
- func TestValidatePersistentVolumeClaimStatusUpdate(t *testing.T) {
- validClaim := testVolumeClaim("foo", "ns", core.PersistentVolumeClaimSpec{
- AccessModes: []core.PersistentVolumeAccessMode{
- core.ReadWriteOnce,
- core.ReadOnlyMany,
- },
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- },
- })
- validConditionUpdate := testVolumeClaimWithStatus("foo", "ns", core.PersistentVolumeClaimSpec{
- AccessModes: []core.PersistentVolumeAccessMode{
- core.ReadWriteOnce,
- core.ReadOnlyMany,
- },
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- },
- }, core.PersistentVolumeClaimStatus{
- Phase: core.ClaimPending,
- Conditions: []core.PersistentVolumeClaimCondition{
- {Type: core.PersistentVolumeClaimResizing, Status: core.ConditionTrue},
- },
- })
- scenarios := map[string]struct {
- isExpectedFailure bool
- oldClaim *core.PersistentVolumeClaim
- newClaim *core.PersistentVolumeClaim
- enableResize bool
- }{
- "condition-update-with-enabled-feature-gate": {
- isExpectedFailure: false,
- oldClaim: validClaim,
- newClaim: validConditionUpdate,
- enableResize: true,
- },
- }
- for name, scenario := range scenarios {
- t.Run(name, func(t *testing.T) {
- // ensure we have a resource version specified for updates
- scenario.oldClaim.ResourceVersion = "1"
- scenario.newClaim.ResourceVersion = "1"
- errs := ValidatePersistentVolumeClaimStatusUpdate(scenario.newClaim, scenario.oldClaim)
- if len(errs) == 0 && scenario.isExpectedFailure {
- t.Errorf("Unexpected success for scenario: %s", name)
- }
- if len(errs) > 0 && !scenario.isExpectedFailure {
- t.Errorf("Unexpected failure for scenario: %s - %+v", name, errs)
- }
- })
- }
- }
- func TestValidateResourceQuota(t *testing.T) {
- spec := core.ResourceQuotaSpec{
- Hard: core.ResourceList{
- core.ResourceCPU: resource.MustParse("100"),
- core.ResourceMemory: resource.MustParse("10000"),
- core.ResourceRequestsCPU: resource.MustParse("100"),
- core.ResourceRequestsMemory: resource.MustParse("10000"),
- core.ResourceLimitsCPU: resource.MustParse("100"),
- core.ResourceLimitsMemory: resource.MustParse("10000"),
- core.ResourcePods: resource.MustParse("10"),
- core.ResourceServices: resource.MustParse("0"),
- core.ResourceReplicationControllers: resource.MustParse("10"),
- core.ResourceQuotas: resource.MustParse("10"),
- core.ResourceConfigMaps: resource.MustParse("10"),
- core.ResourceSecrets: resource.MustParse("10"),
- },
- }
- terminatingSpec := core.ResourceQuotaSpec{
- Hard: core.ResourceList{
- core.ResourceCPU: resource.MustParse("100"),
- core.ResourceLimitsCPU: resource.MustParse("200"),
- },
- Scopes: []core.ResourceQuotaScope{core.ResourceQuotaScopeTerminating},
- }
- nonTerminatingSpec := core.ResourceQuotaSpec{
- Hard: core.ResourceList{
- core.ResourceCPU: resource.MustParse("100"),
- },
- Scopes: []core.ResourceQuotaScope{core.ResourceQuotaScopeNotTerminating},
- }
- bestEffortSpec := core.ResourceQuotaSpec{
- Hard: core.ResourceList{
- core.ResourcePods: resource.MustParse("100"),
- },
- Scopes: []core.ResourceQuotaScope{core.ResourceQuotaScopeBestEffort},
- }
- nonBestEffortSpec := core.ResourceQuotaSpec{
- Hard: core.ResourceList{
- core.ResourceCPU: resource.MustParse("100"),
- },
- Scopes: []core.ResourceQuotaScope{core.ResourceQuotaScopeNotBestEffort},
- }
- scopeSelectorSpec := core.ResourceQuotaSpec{
- ScopeSelector: &core.ScopeSelector{
- MatchExpressions: []core.ScopedResourceSelectorRequirement{
- {
- ScopeName: core.ResourceQuotaScopePriorityClass,
- Operator: core.ScopeSelectorOpIn,
- Values: []string{"cluster-services"},
- },
- },
- },
- }
- // storage is not yet supported as a quota tracked resource
- invalidQuotaResourceSpec := core.ResourceQuotaSpec{
- Hard: core.ResourceList{
- core.ResourceStorage: resource.MustParse("10"),
- },
- }
- negativeSpec := core.ResourceQuotaSpec{
- Hard: core.ResourceList{
- core.ResourceCPU: resource.MustParse("-100"),
- core.ResourceMemory: resource.MustParse("-10000"),
- core.ResourcePods: resource.MustParse("-10"),
- core.ResourceServices: resource.MustParse("-10"),
- core.ResourceReplicationControllers: resource.MustParse("-10"),
- core.ResourceQuotas: resource.MustParse("-10"),
- core.ResourceConfigMaps: resource.MustParse("-10"),
- core.ResourceSecrets: resource.MustParse("-10"),
- },
- }
- fractionalComputeSpec := core.ResourceQuotaSpec{
- Hard: core.ResourceList{
- core.ResourceCPU: resource.MustParse("100m"),
- },
- }
- fractionalPodSpec := core.ResourceQuotaSpec{
- Hard: core.ResourceList{
- core.ResourcePods: resource.MustParse(".1"),
- core.ResourceServices: resource.MustParse(".5"),
- core.ResourceReplicationControllers: resource.MustParse("1.25"),
- core.ResourceQuotas: resource.MustParse("2.5"),
- },
- }
- invalidTerminatingScopePairsSpec := core.ResourceQuotaSpec{
- Hard: core.ResourceList{
- core.ResourceCPU: resource.MustParse("100"),
- },
- Scopes: []core.ResourceQuotaScope{core.ResourceQuotaScopeTerminating, core.ResourceQuotaScopeNotTerminating},
- }
- invalidBestEffortScopePairsSpec := core.ResourceQuotaSpec{
- Hard: core.ResourceList{
- core.ResourcePods: resource.MustParse("100"),
- },
- Scopes: []core.ResourceQuotaScope{core.ResourceQuotaScopeBestEffort, core.ResourceQuotaScopeNotBestEffort},
- }
- invalidScopeNameSpec := core.ResourceQuotaSpec{
- Hard: core.ResourceList{
- core.ResourceCPU: resource.MustParse("100"),
- },
- Scopes: []core.ResourceQuotaScope{core.ResourceQuotaScope("foo")},
- }
- successCases := []core.ResourceQuota{
- {
- ObjectMeta: metav1.ObjectMeta{
- Name: "abc",
- Namespace: "foo",
- },
- Spec: spec,
- },
- {
- ObjectMeta: metav1.ObjectMeta{
- Name: "abc",
- Namespace: "foo",
- },
- Spec: fractionalComputeSpec,
- },
- {
- ObjectMeta: metav1.ObjectMeta{
- Name: "abc",
- Namespace: "foo",
- },
- Spec: terminatingSpec,
- },
- {
- ObjectMeta: metav1.ObjectMeta{
- Name: "abc",
- Namespace: "foo",
- },
- Spec: nonTerminatingSpec,
- },
- {
- ObjectMeta: metav1.ObjectMeta{
- Name: "abc",
- Namespace: "foo",
- },
- Spec: bestEffortSpec,
- },
- {
- ObjectMeta: metav1.ObjectMeta{
- Name: "abc",
- Namespace: "foo",
- },
- Spec: scopeSelectorSpec,
- },
- {
- ObjectMeta: metav1.ObjectMeta{
- Name: "abc",
- Namespace: "foo",
- },
- Spec: nonBestEffortSpec,
- },
- }
- for _, successCase := range successCases {
- if errs := ValidateResourceQuota(&successCase); len(errs) != 0 {
- t.Errorf("expected success: %v", errs)
- }
- }
- errorCases := map[string]struct {
- R core.ResourceQuota
- D string
- }{
- "zero-length Name": {
- core.ResourceQuota{ObjectMeta: metav1.ObjectMeta{Name: "", Namespace: "foo"}, Spec: spec},
- "name or generateName is required",
- },
- "zero-length Namespace": {
- core.ResourceQuota{ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: ""}, Spec: spec},
- "",
- },
- "invalid Name": {
- core.ResourceQuota{ObjectMeta: metav1.ObjectMeta{Name: "^Invalid", Namespace: "foo"}, Spec: spec},
- dnsSubdomainLabelErrMsg,
- },
- "invalid Namespace": {
- core.ResourceQuota{ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: "^Invalid"}, Spec: spec},
- dnsLabelErrMsg,
- },
- "negative-limits": {
- core.ResourceQuota{ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: negativeSpec},
- isNegativeErrorMsg,
- },
- "fractional-api-resource": {
- core.ResourceQuota{ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: fractionalPodSpec},
- isNotIntegerErrorMsg,
- },
- "invalid-quota-resource": {
- core.ResourceQuota{ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: invalidQuotaResourceSpec},
- isInvalidQuotaResource,
- },
- "invalid-quota-terminating-pair": {
- core.ResourceQuota{ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: invalidTerminatingScopePairsSpec},
- "conflicting scopes",
- },
- "invalid-quota-besteffort-pair": {
- core.ResourceQuota{ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: invalidBestEffortScopePairsSpec},
- "conflicting scopes",
- },
- "invalid-quota-scope-name": {
- core.ResourceQuota{ObjectMeta: metav1.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: invalidScopeNameSpec},
- "unsupported scope",
- },
- }
- for k, v := range errorCases {
- errs := ValidateResourceQuota(&v.R)
- if len(errs) == 0 {
- t.Errorf("expected failure for %s", k)
- }
- for i := range errs {
- if !strings.Contains(errs[i].Detail, v.D) {
- t.Errorf("[%s]: expected error detail either empty or %s, got %s", k, v.D, errs[i].Detail)
- }
- }
- }
- }
- func TestValidateNamespace(t *testing.T) {
- validLabels := map[string]string{"a": "b"}
- invalidLabels := map[string]string{"NoUppercaseOrSpecialCharsLike=Equals": "b"}
- successCases := []core.Namespace{
- {
- ObjectMeta: metav1.ObjectMeta{Name: "abc", Labels: validLabels},
- },
- {
- ObjectMeta: metav1.ObjectMeta{Name: "abc-123"},
- Spec: core.NamespaceSpec{
- Finalizers: []core.FinalizerName{"example.com/something", "example.com/other"},
- },
- },
- }
- for _, successCase := range successCases {
- if errs := ValidateNamespace(&successCase); len(errs) != 0 {
- t.Errorf("expected success: %v", errs)
- }
- }
- errorCases := map[string]struct {
- R core.Namespace
- D string
- }{
- "zero-length name": {
- core.Namespace{ObjectMeta: metav1.ObjectMeta{Name: ""}},
- "",
- },
- "defined-namespace": {
- core.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "abc-123", Namespace: "makesnosense"}},
- "",
- },
- "invalid-labels": {
- core.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "abc", Labels: invalidLabels}},
- "",
- },
- }
- for k, v := range errorCases {
- errs := ValidateNamespace(&v.R)
- if len(errs) == 0 {
- t.Errorf("expected failure for %s", k)
- }
- }
- }
- func TestValidateNamespaceFinalizeUpdate(t *testing.T) {
- tests := []struct {
- oldNamespace core.Namespace
- namespace core.Namespace
- valid bool
- }{
- {core.Namespace{}, core.Namespace{}, true},
- {core.Namespace{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo"}},
- core.Namespace{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo"},
- Spec: core.NamespaceSpec{
- Finalizers: []core.FinalizerName{"Foo"},
- },
- }, false},
- {core.Namespace{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo"},
- Spec: core.NamespaceSpec{
- Finalizers: []core.FinalizerName{"foo.com/bar"},
- },
- },
- core.Namespace{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo"},
- Spec: core.NamespaceSpec{
- Finalizers: []core.FinalizerName{"foo.com/bar", "what.com/bar"},
- },
- }, true},
- {core.Namespace{
- ObjectMeta: metav1.ObjectMeta{
- Name: "fooemptyfinalizer"},
- Spec: core.NamespaceSpec{
- Finalizers: []core.FinalizerName{"foo.com/bar"},
- },
- },
- core.Namespace{
- ObjectMeta: metav1.ObjectMeta{
- Name: "fooemptyfinalizer"},
- Spec: core.NamespaceSpec{
- Finalizers: []core.FinalizerName{"", "foo.com/bar", "what.com/bar"},
- },
- }, false},
- }
- for i, test := range tests {
- test.namespace.ObjectMeta.ResourceVersion = "1"
- test.oldNamespace.ObjectMeta.ResourceVersion = "1"
- errs := ValidateNamespaceFinalizeUpdate(&test.namespace, &test.oldNamespace)
- if test.valid && len(errs) > 0 {
- t.Errorf("%d: Unexpected error: %v", i, errs)
- t.Logf("%#v vs %#v", test.oldNamespace, test.namespace)
- }
- if !test.valid && len(errs) == 0 {
- t.Errorf("%d: Unexpected non-error", i)
- }
- }
- }
- func TestValidateNamespaceStatusUpdate(t *testing.T) {
- now := metav1.Now()
- tests := []struct {
- oldNamespace core.Namespace
- namespace core.Namespace
- valid bool
- }{
- {core.Namespace{}, core.Namespace{
- Status: core.NamespaceStatus{
- Phase: core.NamespaceActive,
- },
- }, true},
- // Cannot set deletionTimestamp via status update
- {core.Namespace{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo"}},
- core.Namespace{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- DeletionTimestamp: &now},
- Status: core.NamespaceStatus{
- Phase: core.NamespaceTerminating,
- },
- }, false},
- // Can update phase via status update
- {core.Namespace{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- DeletionTimestamp: &now}},
- core.Namespace{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- DeletionTimestamp: &now},
- Status: core.NamespaceStatus{
- Phase: core.NamespaceTerminating,
- },
- }, true},
- {core.Namespace{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo"}},
- core.Namespace{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo"},
- Status: core.NamespaceStatus{
- Phase: core.NamespaceTerminating,
- },
- }, false},
- {core.Namespace{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo"}},
- core.Namespace{
- ObjectMeta: metav1.ObjectMeta{
- Name: "bar"},
- Status: core.NamespaceStatus{
- Phase: core.NamespaceTerminating,
- },
- }, false},
- }
- for i, test := range tests {
- test.namespace.ObjectMeta.ResourceVersion = "1"
- test.oldNamespace.ObjectMeta.ResourceVersion = "1"
- errs := ValidateNamespaceStatusUpdate(&test.namespace, &test.oldNamespace)
- if test.valid && len(errs) > 0 {
- t.Errorf("%d: Unexpected error: %v", i, errs)
- t.Logf("%#v vs %#v", test.oldNamespace.ObjectMeta, test.namespace.ObjectMeta)
- }
- if !test.valid && len(errs) == 0 {
- t.Errorf("%d: Unexpected non-error", i)
- }
- }
- }
- func TestValidateNamespaceUpdate(t *testing.T) {
- tests := []struct {
- oldNamespace core.Namespace
- namespace core.Namespace
- valid bool
- }{
- {core.Namespace{}, core.Namespace{}, true},
- {core.Namespace{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo1"}},
- core.Namespace{
- ObjectMeta: metav1.ObjectMeta{
- Name: "bar1"},
- }, false},
- {core.Namespace{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo2",
- Labels: map[string]string{"foo": "bar"},
- },
- }, core.Namespace{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo2",
- Labels: map[string]string{"foo": "baz"},
- },
- }, true},
- {core.Namespace{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo3",
- },
- }, core.Namespace{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo3",
- Labels: map[string]string{"foo": "baz"},
- },
- }, true},
- {core.Namespace{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo4",
- Labels: map[string]string{"bar": "foo"},
- },
- }, core.Namespace{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo4",
- Labels: map[string]string{"foo": "baz"},
- },
- }, true},
- {core.Namespace{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo5",
- Labels: map[string]string{"foo": "baz"},
- },
- }, core.Namespace{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo5",
- Labels: map[string]string{"Foo": "baz"},
- },
- }, true},
- {core.Namespace{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo6",
- Labels: map[string]string{"foo": "baz"},
- },
- }, core.Namespace{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo6",
- Labels: map[string]string{"Foo": "baz"},
- },
- Spec: core.NamespaceSpec{
- Finalizers: []core.FinalizerName{"kubernetes"},
- },
- Status: core.NamespaceStatus{
- Phase: core.NamespaceTerminating,
- },
- }, true},
- }
- for i, test := range tests {
- test.namespace.ObjectMeta.ResourceVersion = "1"
- test.oldNamespace.ObjectMeta.ResourceVersion = "1"
- errs := ValidateNamespaceUpdate(&test.namespace, &test.oldNamespace)
- if test.valid && len(errs) > 0 {
- t.Errorf("%d: Unexpected error: %v", i, errs)
- t.Logf("%#v vs %#v", test.oldNamespace.ObjectMeta, test.namespace.ObjectMeta)
- }
- if !test.valid && len(errs) == 0 {
- t.Errorf("%d: Unexpected non-error", i)
- }
- }
- }
- func TestValidateSecret(t *testing.T) {
- // Opaque secret validation
- validSecret := func() core.Secret {
- return core.Secret{
- ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "bar"},
- Data: map[string][]byte{
- "data-1": []byte("bar"),
- },
- }
- }
- var (
- emptyName = validSecret()
- invalidName = validSecret()
- emptyNs = validSecret()
- invalidNs = validSecret()
- overMaxSize = validSecret()
- invalidKey = validSecret()
- leadingDotKey = validSecret()
- dotKey = validSecret()
- doubleDotKey = validSecret()
- )
- emptyName.Name = ""
- invalidName.Name = "NoUppercaseOrSpecialCharsLike=Equals"
- emptyNs.Namespace = ""
- invalidNs.Namespace = "NoUppercaseOrSpecialCharsLike=Equals"
- overMaxSize.Data = map[string][]byte{
- "over": make([]byte, core.MaxSecretSize+1),
- }
- invalidKey.Data["a*b"] = []byte("whoops")
- leadingDotKey.Data[".key"] = []byte("bar")
- dotKey.Data["."] = []byte("bar")
- doubleDotKey.Data[".."] = []byte("bar")
- // kubernetes.io/service-account-token secret validation
- validServiceAccountTokenSecret := func() core.Secret {
- return core.Secret{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- Namespace: "bar",
- Annotations: map[string]string{
- core.ServiceAccountNameKey: "foo",
- },
- },
- Type: core.SecretTypeServiceAccountToken,
- Data: map[string][]byte{
- "data-1": []byte("bar"),
- },
- }
- }
- var (
- emptyTokenAnnotation = validServiceAccountTokenSecret()
- missingTokenAnnotation = validServiceAccountTokenSecret()
- missingTokenAnnotations = validServiceAccountTokenSecret()
- )
- emptyTokenAnnotation.Annotations[core.ServiceAccountNameKey] = ""
- delete(missingTokenAnnotation.Annotations, core.ServiceAccountNameKey)
- missingTokenAnnotations.Annotations = nil
- tests := map[string]struct {
- secret core.Secret
- valid bool
- }{
- "valid": {validSecret(), true},
- "empty name": {emptyName, false},
- "invalid name": {invalidName, false},
- "empty namespace": {emptyNs, false},
- "invalid namespace": {invalidNs, false},
- "over max size": {overMaxSize, false},
- "invalid key": {invalidKey, false},
- "valid service-account-token secret": {validServiceAccountTokenSecret(), true},
- "empty service-account-token annotation": {emptyTokenAnnotation, false},
- "missing service-account-token annotation": {missingTokenAnnotation, false},
- "missing service-account-token annotations": {missingTokenAnnotations, false},
- "leading dot key": {leadingDotKey, true},
- "dot key": {dotKey, false},
- "double dot key": {doubleDotKey, false},
- }
- for name, tc := range tests {
- errs := ValidateSecret(&tc.secret)
- if tc.valid && len(errs) > 0 {
- t.Errorf("%v: Unexpected error: %v", name, errs)
- }
- if !tc.valid && len(errs) == 0 {
- t.Errorf("%v: Unexpected non-error", name)
- }
- }
- }
- func TestValidateDockerConfigSecret(t *testing.T) {
- validDockerSecret := func() core.Secret {
- return core.Secret{
- ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "bar"},
- Type: core.SecretTypeDockercfg,
- Data: map[string][]byte{
- core.DockerConfigKey: []byte(`{"https://index.docker.io/v1/": {"auth": "Y2x1ZWRyb29sZXIwMDAxOnBhc3N3b3Jk","email": "fake@example.com"}}`),
- },
- }
- }
- validDockerSecret2 := func() core.Secret {
- return core.Secret{
- ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "bar"},
- Type: core.SecretTypeDockerConfigJson,
- Data: map[string][]byte{
- core.DockerConfigJsonKey: []byte(`{"auths":{"https://index.docker.io/v1/": {"auth": "Y2x1ZWRyb29sZXIwMDAxOnBhc3N3b3Jk","email": "fake@example.com"}}}`),
- },
- }
- }
- var (
- missingDockerConfigKey = validDockerSecret()
- emptyDockerConfigKey = validDockerSecret()
- invalidDockerConfigKey = validDockerSecret()
- missingDockerConfigKey2 = validDockerSecret2()
- emptyDockerConfigKey2 = validDockerSecret2()
- invalidDockerConfigKey2 = validDockerSecret2()
- )
- delete(missingDockerConfigKey.Data, core.DockerConfigKey)
- emptyDockerConfigKey.Data[core.DockerConfigKey] = []byte("")
- invalidDockerConfigKey.Data[core.DockerConfigKey] = []byte("bad")
- delete(missingDockerConfigKey2.Data, core.DockerConfigJsonKey)
- emptyDockerConfigKey2.Data[core.DockerConfigJsonKey] = []byte("")
- invalidDockerConfigKey2.Data[core.DockerConfigJsonKey] = []byte("bad")
- tests := map[string]struct {
- secret core.Secret
- valid bool
- }{
- "valid dockercfg": {validDockerSecret(), true},
- "missing dockercfg": {missingDockerConfigKey, false},
- "empty dockercfg": {emptyDockerConfigKey, false},
- "invalid dockercfg": {invalidDockerConfigKey, false},
- "valid config.json": {validDockerSecret2(), true},
- "missing config.json": {missingDockerConfigKey2, false},
- "empty config.json": {emptyDockerConfigKey2, false},
- "invalid config.json": {invalidDockerConfigKey2, false},
- }
- for name, tc := range tests {
- errs := ValidateSecret(&tc.secret)
- if tc.valid && len(errs) > 0 {
- t.Errorf("%v: Unexpected error: %v", name, errs)
- }
- if !tc.valid && len(errs) == 0 {
- t.Errorf("%v: Unexpected non-error", name)
- }
- }
- }
- func TestValidateBasicAuthSecret(t *testing.T) {
- validBasicAuthSecret := func() core.Secret {
- return core.Secret{
- ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "bar"},
- Type: core.SecretTypeBasicAuth,
- Data: map[string][]byte{
- core.BasicAuthUsernameKey: []byte("username"),
- core.BasicAuthPasswordKey: []byte("password"),
- },
- }
- }
- var (
- missingBasicAuthUsernamePasswordKeys = validBasicAuthSecret()
- )
- delete(missingBasicAuthUsernamePasswordKeys.Data, core.BasicAuthUsernameKey)
- delete(missingBasicAuthUsernamePasswordKeys.Data, core.BasicAuthPasswordKey)
- tests := map[string]struct {
- secret core.Secret
- valid bool
- }{
- "valid": {validBasicAuthSecret(), true},
- "missing username and password": {missingBasicAuthUsernamePasswordKeys, false},
- }
- for name, tc := range tests {
- errs := ValidateSecret(&tc.secret)
- if tc.valid && len(errs) > 0 {
- t.Errorf("%v: Unexpected error: %v", name, errs)
- }
- if !tc.valid && len(errs) == 0 {
- t.Errorf("%v: Unexpected non-error", name)
- }
- }
- }
- func TestValidateSSHAuthSecret(t *testing.T) {
- validSSHAuthSecret := func() core.Secret {
- return core.Secret{
- ObjectMeta: metav1.ObjectMeta{Name: "foo", Namespace: "bar"},
- Type: core.SecretTypeSSHAuth,
- Data: map[string][]byte{
- core.SSHAuthPrivateKey: []byte("foo-bar-baz"),
- },
- }
- }
- missingSSHAuthPrivateKey := validSSHAuthSecret()
- delete(missingSSHAuthPrivateKey.Data, core.SSHAuthPrivateKey)
- tests := map[string]struct {
- secret core.Secret
- valid bool
- }{
- "valid": {validSSHAuthSecret(), true},
- "missing private key": {missingSSHAuthPrivateKey, false},
- }
- for name, tc := range tests {
- errs := ValidateSecret(&tc.secret)
- if tc.valid && len(errs) > 0 {
- t.Errorf("%v: Unexpected error: %v", name, errs)
- }
- if !tc.valid && len(errs) == 0 {
- t.Errorf("%v: Unexpected non-error", name)
- }
- }
- }
- func TestValidateEndpoints(t *testing.T) {
- successCases := map[string]core.Endpoints{
- "simple endpoint": {
- ObjectMeta: metav1.ObjectMeta{Name: "mysvc", Namespace: "namespace"},
- Subsets: []core.EndpointSubset{
- {
- Addresses: []core.EndpointAddress{{IP: "10.10.1.1"}, {IP: "10.10.2.2"}},
- Ports: []core.EndpointPort{{Name: "a", Port: 8675, Protocol: "TCP"}, {Name: "b", Port: 309, Protocol: "TCP"}},
- },
- {
- Addresses: []core.EndpointAddress{{IP: "10.10.3.3"}},
- Ports: []core.EndpointPort{{Name: "a", Port: 93, Protocol: "TCP"}, {Name: "b", Port: 76, Protocol: "TCP"}},
- },
- },
- },
- "empty subsets": {
- ObjectMeta: metav1.ObjectMeta{Name: "mysvc", Namespace: "namespace"},
- },
- "no name required for singleton port": {
- ObjectMeta: metav1.ObjectMeta{Name: "mysvc", Namespace: "namespace"},
- Subsets: []core.EndpointSubset{
- {
- Addresses: []core.EndpointAddress{{IP: "10.10.1.1"}},
- Ports: []core.EndpointPort{{Port: 8675, Protocol: "TCP"}},
- },
- },
- },
- "empty ports": {
- ObjectMeta: metav1.ObjectMeta{Name: "mysvc", Namespace: "namespace"},
- Subsets: []core.EndpointSubset{
- {
- Addresses: []core.EndpointAddress{{IP: "10.10.3.3"}},
- },
- },
- },
- }
- for k, v := range successCases {
- if errs := ValidateEndpoints(&v); len(errs) != 0 {
- t.Errorf("Expected success for %s, got %v", k, errs)
- }
- }
- errorCases := map[string]struct {
- endpoints core.Endpoints
- errorType field.ErrorType
- errorDetail string
- }{
- "missing namespace": {
- endpoints: core.Endpoints{ObjectMeta: metav1.ObjectMeta{Name: "mysvc"}},
- errorType: "FieldValueRequired",
- },
- "missing name": {
- endpoints: core.Endpoints{ObjectMeta: metav1.ObjectMeta{Namespace: "namespace"}},
- errorType: "FieldValueRequired",
- },
- "invalid namespace": {
- endpoints: core.Endpoints{ObjectMeta: metav1.ObjectMeta{Name: "mysvc", Namespace: "no@#invalid.;chars\"allowed"}},
- errorType: "FieldValueInvalid",
- errorDetail: dnsLabelErrMsg,
- },
- "invalid name": {
- endpoints: core.Endpoints{ObjectMeta: metav1.ObjectMeta{Name: "-_Invliad^&Characters", Namespace: "namespace"}},
- errorType: "FieldValueInvalid",
- errorDetail: dnsSubdomainLabelErrMsg,
- },
- "empty addresses": {
- endpoints: core.Endpoints{
- ObjectMeta: metav1.ObjectMeta{Name: "mysvc", Namespace: "namespace"},
- Subsets: []core.EndpointSubset{
- {
- Ports: []core.EndpointPort{{Name: "a", Port: 93, Protocol: "TCP"}},
- },
- },
- },
- errorType: "FieldValueRequired",
- },
- "invalid IP": {
- endpoints: core.Endpoints{
- ObjectMeta: metav1.ObjectMeta{Name: "mysvc", Namespace: "namespace"},
- Subsets: []core.EndpointSubset{
- {
- Addresses: []core.EndpointAddress{{IP: "[2001:0db8:85a3:0042:1000:8a2e:0370:7334]"}},
- Ports: []core.EndpointPort{{Name: "a", Port: 93, Protocol: "TCP"}},
- },
- },
- },
- errorType: "FieldValueInvalid",
- errorDetail: "must be a valid IP address",
- },
- "Multiple ports, one without name": {
- endpoints: core.Endpoints{
- ObjectMeta: metav1.ObjectMeta{Name: "mysvc", Namespace: "namespace"},
- Subsets: []core.EndpointSubset{
- {
- Addresses: []core.EndpointAddress{{IP: "10.10.1.1"}},
- Ports: []core.EndpointPort{{Port: 8675, Protocol: "TCP"}, {Name: "b", Port: 309, Protocol: "TCP"}},
- },
- },
- },
- errorType: "FieldValueRequired",
- },
- "Invalid port number": {
- endpoints: core.Endpoints{
- ObjectMeta: metav1.ObjectMeta{Name: "mysvc", Namespace: "namespace"},
- Subsets: []core.EndpointSubset{
- {
- Addresses: []core.EndpointAddress{{IP: "10.10.1.1"}},
- Ports: []core.EndpointPort{{Name: "a", Port: 66000, Protocol: "TCP"}},
- },
- },
- },
- errorType: "FieldValueInvalid",
- errorDetail: "between",
- },
- "Invalid protocol": {
- endpoints: core.Endpoints{
- ObjectMeta: metav1.ObjectMeta{Name: "mysvc", Namespace: "namespace"},
- Subsets: []core.EndpointSubset{
- {
- Addresses: []core.EndpointAddress{{IP: "10.10.1.1"}},
- Ports: []core.EndpointPort{{Name: "a", Port: 93, Protocol: "Protocol"}},
- },
- },
- },
- errorType: "FieldValueNotSupported",
- },
- "Address missing IP": {
- endpoints: core.Endpoints{
- ObjectMeta: metav1.ObjectMeta{Name: "mysvc", Namespace: "namespace"},
- Subsets: []core.EndpointSubset{
- {
- Addresses: []core.EndpointAddress{{}},
- Ports: []core.EndpointPort{{Name: "a", Port: 93, Protocol: "TCP"}},
- },
- },
- },
- errorType: "FieldValueInvalid",
- errorDetail: "must be a valid IP address",
- },
- "Port missing number": {
- endpoints: core.Endpoints{
- ObjectMeta: metav1.ObjectMeta{Name: "mysvc", Namespace: "namespace"},
- Subsets: []core.EndpointSubset{
- {
- Addresses: []core.EndpointAddress{{IP: "10.10.1.1"}},
- Ports: []core.EndpointPort{{Name: "a", Protocol: "TCP"}},
- },
- },
- },
- errorType: "FieldValueInvalid",
- errorDetail: "between",
- },
- "Port missing protocol": {
- endpoints: core.Endpoints{
- ObjectMeta: metav1.ObjectMeta{Name: "mysvc", Namespace: "namespace"},
- Subsets: []core.EndpointSubset{
- {
- Addresses: []core.EndpointAddress{{IP: "10.10.1.1"}},
- Ports: []core.EndpointPort{{Name: "a", Port: 93}},
- },
- },
- },
- errorType: "FieldValueRequired",
- },
- "Address is loopback": {
- endpoints: core.Endpoints{
- ObjectMeta: metav1.ObjectMeta{Name: "mysvc", Namespace: "namespace"},
- Subsets: []core.EndpointSubset{
- {
- Addresses: []core.EndpointAddress{{IP: "127.0.0.1"}},
- Ports: []core.EndpointPort{{Name: "p", Port: 93, Protocol: "TCP"}},
- },
- },
- },
- errorType: "FieldValueInvalid",
- errorDetail: "loopback",
- },
- "Address is link-local": {
- endpoints: core.Endpoints{
- ObjectMeta: metav1.ObjectMeta{Name: "mysvc", Namespace: "namespace"},
- Subsets: []core.EndpointSubset{
- {
- Addresses: []core.EndpointAddress{{IP: "169.254.169.254"}},
- Ports: []core.EndpointPort{{Name: "p", Port: 93, Protocol: "TCP"}},
- },
- },
- },
- errorType: "FieldValueInvalid",
- errorDetail: "link-local",
- },
- "Address is link-local multicast": {
- endpoints: core.Endpoints{
- ObjectMeta: metav1.ObjectMeta{Name: "mysvc", Namespace: "namespace"},
- Subsets: []core.EndpointSubset{
- {
- Addresses: []core.EndpointAddress{{IP: "224.0.0.1"}},
- Ports: []core.EndpointPort{{Name: "p", Port: 93, Protocol: "TCP"}},
- },
- },
- },
- errorType: "FieldValueInvalid",
- errorDetail: "link-local multicast",
- },
- }
- for k, v := range errorCases {
- if errs := ValidateEndpoints(&v.endpoints); len(errs) == 0 || errs[0].Type != v.errorType || !strings.Contains(errs[0].Detail, v.errorDetail) {
- t.Errorf("[%s] Expected error type %s with detail %q, got %v", k, v.errorType, v.errorDetail, errs)
- }
- }
- }
- func TestValidateTLSSecret(t *testing.T) {
- successCases := map[string]core.Secret{
- "empty certificate chain": {
- ObjectMeta: metav1.ObjectMeta{Name: "tls-cert", Namespace: "namespace"},
- Data: map[string][]byte{
- core.TLSCertKey: []byte("public key"),
- core.TLSPrivateKeyKey: []byte("private key"),
- },
- },
- }
- for k, v := range successCases {
- if errs := ValidateSecret(&v); len(errs) != 0 {
- t.Errorf("Expected success for %s, got %v", k, errs)
- }
- }
- errorCases := map[string]struct {
- secrets core.Secret
- errorType field.ErrorType
- errorDetail string
- }{
- "missing public key": {
- secrets: core.Secret{
- ObjectMeta: metav1.ObjectMeta{Name: "tls-cert"},
- Data: map[string][]byte{
- core.TLSCertKey: []byte("public key"),
- },
- },
- errorType: "FieldValueRequired",
- },
- "missing private key": {
- secrets: core.Secret{
- ObjectMeta: metav1.ObjectMeta{Name: "tls-cert"},
- Data: map[string][]byte{
- core.TLSCertKey: []byte("public key"),
- },
- },
- errorType: "FieldValueRequired",
- },
- }
- for k, v := range errorCases {
- if errs := ValidateSecret(&v.secrets); len(errs) == 0 || errs[0].Type != v.errorType || !strings.Contains(errs[0].Detail, v.errorDetail) {
- t.Errorf("[%s] Expected error type %s with detail %q, got %v", k, v.errorType, v.errorDetail, errs)
- }
- }
- }
- func TestValidateSecurityContext(t *testing.T) {
- runAsUser := int64(1)
- fullValidSC := func() *core.SecurityContext {
- return &core.SecurityContext{
- Privileged: utilpointer.BoolPtr(false),
- Capabilities: &core.Capabilities{
- Add: []core.Capability{"foo"},
- Drop: []core.Capability{"bar"},
- },
- SELinuxOptions: &core.SELinuxOptions{
- User: "user",
- Role: "role",
- Type: "type",
- Level: "level",
- },
- RunAsUser: &runAsUser,
- }
- }
- //setup data
- allSettings := fullValidSC()
- noCaps := fullValidSC()
- noCaps.Capabilities = nil
- noSELinux := fullValidSC()
- noSELinux.SELinuxOptions = nil
- noPrivRequest := fullValidSC()
- noPrivRequest.Privileged = nil
- noRunAsUser := fullValidSC()
- noRunAsUser.RunAsUser = nil
- successCases := map[string]struct {
- sc *core.SecurityContext
- }{
- "all settings": {allSettings},
- "no capabilities": {noCaps},
- "no selinux": {noSELinux},
- "no priv request": {noPrivRequest},
- "no run as user": {noRunAsUser},
- }
- for k, v := range successCases {
- if errs := ValidateSecurityContext(v.sc, field.NewPath("field")); len(errs) != 0 {
- t.Errorf("[%s] Expected success, got %v", k, errs)
- }
- }
- privRequestWithGlobalDeny := fullValidSC()
- privRequestWithGlobalDeny.Privileged = utilpointer.BoolPtr(true)
- negativeRunAsUser := fullValidSC()
- negativeUser := int64(-1)
- negativeRunAsUser.RunAsUser = &negativeUser
- privWithoutEscalation := fullValidSC()
- privWithoutEscalation.Privileged = utilpointer.BoolPtr(true)
- privWithoutEscalation.AllowPrivilegeEscalation = utilpointer.BoolPtr(false)
- capSysAdminWithoutEscalation := fullValidSC()
- capSysAdminWithoutEscalation.Capabilities.Add = []core.Capability{"CAP_SYS_ADMIN"}
- capSysAdminWithoutEscalation.AllowPrivilegeEscalation = utilpointer.BoolPtr(false)
- errorCases := map[string]struct {
- sc *core.SecurityContext
- errorType field.ErrorType
- errorDetail string
- capAllowPriv bool
- }{
- "request privileged when capabilities forbids": {
- sc: privRequestWithGlobalDeny,
- errorType: "FieldValueForbidden",
- errorDetail: "disallowed by cluster policy",
- },
- "negative RunAsUser": {
- sc: negativeRunAsUser,
- errorType: "FieldValueInvalid",
- errorDetail: "must be between",
- },
- "with CAP_SYS_ADMIN and allowPrivilegeEscalation false": {
- sc: capSysAdminWithoutEscalation,
- errorType: "FieldValueInvalid",
- errorDetail: "cannot set `allowPrivilegeEscalation` to false and `capabilities.Add` CAP_SYS_ADMIN",
- },
- "with privileged and allowPrivilegeEscalation false": {
- sc: privWithoutEscalation,
- errorType: "FieldValueInvalid",
- errorDetail: "cannot set `allowPrivilegeEscalation` to false and `privileged` to true",
- capAllowPriv: true,
- },
- }
- for k, v := range errorCases {
- capabilities.SetForTests(capabilities.Capabilities{
- AllowPrivileged: v.capAllowPriv,
- })
- if errs := ValidateSecurityContext(v.sc, field.NewPath("field")); len(errs) == 0 || errs[0].Type != v.errorType || !strings.Contains(errs[0].Detail, v.errorDetail) {
- t.Errorf("[%s] Expected error type %q with detail %q, got %v", k, v.errorType, v.errorDetail, errs)
- }
- }
- }
- func fakeValidSecurityContext(priv bool) *core.SecurityContext {
- return &core.SecurityContext{
- Privileged: &priv,
- }
- }
- func TestValidPodLogOptions(t *testing.T) {
- now := metav1.Now()
- negative := int64(-1)
- zero := int64(0)
- positive := int64(1)
- tests := []struct {
- opt core.PodLogOptions
- errs int
- }{
- {core.PodLogOptions{}, 0},
- {core.PodLogOptions{Previous: true}, 0},
- {core.PodLogOptions{Follow: true}, 0},
- {core.PodLogOptions{TailLines: &zero}, 0},
- {core.PodLogOptions{TailLines: &negative}, 1},
- {core.PodLogOptions{TailLines: &positive}, 0},
- {core.PodLogOptions{LimitBytes: &zero}, 1},
- {core.PodLogOptions{LimitBytes: &negative}, 1},
- {core.PodLogOptions{LimitBytes: &positive}, 0},
- {core.PodLogOptions{SinceSeconds: &negative}, 1},
- {core.PodLogOptions{SinceSeconds: &positive}, 0},
- {core.PodLogOptions{SinceSeconds: &zero}, 1},
- {core.PodLogOptions{SinceTime: &now}, 0},
- }
- for i, test := range tests {
- errs := ValidatePodLogOptions(&test.opt)
- if test.errs != len(errs) {
- t.Errorf("%d: Unexpected errors: %v", i, errs)
- }
- }
- }
- func TestValidateConfigMap(t *testing.T) {
- newConfigMap := func(name, namespace string, data map[string]string, binaryData map[string][]byte) core.ConfigMap {
- return core.ConfigMap{
- ObjectMeta: metav1.ObjectMeta{
- Name: name,
- Namespace: namespace,
- },
- Data: data,
- BinaryData: binaryData,
- }
- }
- var (
- validConfigMap = newConfigMap("validname", "validns", map[string]string{"key": "value"}, map[string][]byte{"bin": []byte("value")})
- maxKeyLength = newConfigMap("validname", "validns", map[string]string{strings.Repeat("a", 253): "value"}, nil)
- emptyName = newConfigMap("", "validns", nil, nil)
- invalidName = newConfigMap("NoUppercaseOrSpecialCharsLike=Equals", "validns", nil, nil)
- emptyNs = newConfigMap("validname", "", nil, nil)
- invalidNs = newConfigMap("validname", "NoUppercaseOrSpecialCharsLike=Equals", nil, nil)
- invalidKey = newConfigMap("validname", "validns", map[string]string{"a*b": "value"}, nil)
- leadingDotKey = newConfigMap("validname", "validns", map[string]string{".ab": "value"}, nil)
- dotKey = newConfigMap("validname", "validns", map[string]string{".": "value"}, nil)
- doubleDotKey = newConfigMap("validname", "validns", map[string]string{"..": "value"}, nil)
- overMaxKeyLength = newConfigMap("validname", "validns", map[string]string{strings.Repeat("a", 254): "value"}, nil)
- overMaxSize = newConfigMap("validname", "validns", map[string]string{"key": strings.Repeat("a", v1.MaxSecretSize+1)}, nil)
- duplicatedKey = newConfigMap("validname", "validns", map[string]string{"key": "value1"}, map[string][]byte{"key": []byte("value2")})
- binDataInvalidKey = newConfigMap("validname", "validns", nil, map[string][]byte{"a*b": []byte("value")})
- binDataLeadingDotKey = newConfigMap("validname", "validns", nil, map[string][]byte{".ab": []byte("value")})
- binDataDotKey = newConfigMap("validname", "validns", nil, map[string][]byte{".": []byte("value")})
- binDataDoubleDotKey = newConfigMap("validname", "validns", nil, map[string][]byte{"..": []byte("value")})
- binDataOverMaxKeyLength = newConfigMap("validname", "validns", nil, map[string][]byte{strings.Repeat("a", 254): []byte("value")})
- binDataOverMaxSize = newConfigMap("validname", "validns", nil, map[string][]byte{"bin": bytes.Repeat([]byte("a"), v1.MaxSecretSize+1)})
- binNonUtf8Value = newConfigMap("validname", "validns", nil, map[string][]byte{"key": {0, 0xFE, 0, 0xFF}})
- )
- tests := map[string]struct {
- cfg core.ConfigMap
- isValid bool
- }{
- "valid": {validConfigMap, true},
- "max key length": {maxKeyLength, true},
- "leading dot key": {leadingDotKey, true},
- "empty name": {emptyName, false},
- "invalid name": {invalidName, false},
- "invalid key": {invalidKey, false},
- "empty namespace": {emptyNs, false},
- "invalid namespace": {invalidNs, false},
- "dot key": {dotKey, false},
- "double dot key": {doubleDotKey, false},
- "over max key length": {overMaxKeyLength, false},
- "over max size": {overMaxSize, false},
- "duplicated key": {duplicatedKey, false},
- "binary data invalid key": {binDataInvalidKey, false},
- "binary data leading dot key": {binDataLeadingDotKey, true},
- "binary data dot key": {binDataDotKey, false},
- "binary data double dot key": {binDataDoubleDotKey, false},
- "binary data over max key length": {binDataOverMaxKeyLength, false},
- "binary data max size": {binDataOverMaxSize, false},
- "binary data non utf-8 bytes": {binNonUtf8Value, true},
- }
- for name, tc := range tests {
- errs := ValidateConfigMap(&tc.cfg)
- if tc.isValid && len(errs) > 0 {
- t.Errorf("%v: unexpected error: %v", name, errs)
- }
- if !tc.isValid && len(errs) == 0 {
- t.Errorf("%v: unexpected non-error", name)
- }
- }
- }
- func TestValidateConfigMapUpdate(t *testing.T) {
- newConfigMap := func(version, name, namespace string, data map[string]string) core.ConfigMap {
- return core.ConfigMap{
- ObjectMeta: metav1.ObjectMeta{
- Name: name,
- Namespace: namespace,
- ResourceVersion: version,
- },
- Data: data,
- }
- }
- var (
- validConfigMap = newConfigMap("1", "validname", "validns", map[string]string{"key": "value"})
- noVersion = newConfigMap("", "validname", "validns", map[string]string{"key": "value"})
- )
- cases := []struct {
- name string
- newCfg core.ConfigMap
- oldCfg core.ConfigMap
- isValid bool
- }{
- {
- name: "valid",
- newCfg: validConfigMap,
- oldCfg: validConfigMap,
- isValid: true,
- },
- {
- name: "invalid",
- newCfg: noVersion,
- oldCfg: validConfigMap,
- isValid: false,
- },
- }
- for _, tc := range cases {
- errs := ValidateConfigMapUpdate(&tc.newCfg, &tc.oldCfg)
- if tc.isValid && len(errs) > 0 {
- t.Errorf("%v: unexpected error: %v", tc.name, errs)
- }
- if !tc.isValid && len(errs) == 0 {
- t.Errorf("%v: unexpected non-error", tc.name)
- }
- }
- }
- func TestValidateHasLabel(t *testing.T) {
- successCase := metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- Labels: map[string]string{
- "other": "blah",
- "foo": "bar",
- },
- }
- if errs := ValidateHasLabel(successCase, field.NewPath("field"), "foo", "bar"); len(errs) != 0 {
- t.Errorf("expected success: %v", errs)
- }
- missingCase := metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- Labels: map[string]string{
- "other": "blah",
- },
- }
- if errs := ValidateHasLabel(missingCase, field.NewPath("field"), "foo", "bar"); len(errs) == 0 {
- t.Errorf("expected failure")
- }
- wrongValueCase := metav1.ObjectMeta{
- Name: "123",
- Namespace: "ns",
- Labels: map[string]string{
- "other": "blah",
- "foo": "notbar",
- },
- }
- if errs := ValidateHasLabel(wrongValueCase, field.NewPath("field"), "foo", "bar"); len(errs) == 0 {
- t.Errorf("expected failure")
- }
- }
- func TestIsValidSysctlName(t *testing.T) {
- valid := []string{
- "a.b.c.d",
- "a",
- "a_b",
- "a-b",
- "abc",
- "abc.def",
- }
- invalid := []string{
- "",
- "*",
- "ä",
- "a_",
- "_",
- "__",
- "_a",
- "_a._b",
- "-",
- ".",
- "a.",
- ".a",
- "a.b.",
- "a*.b",
- "a*b",
- "*a",
- "a.*",
- "*",
- "abc*",
- "a.abc*",
- "a.b.*",
- "Abc",
- func(n int) string {
- x := make([]byte, n)
- for i := range x {
- x[i] = byte('a')
- }
- return string(x)
- }(256),
- }
- for _, s := range valid {
- if !IsValidSysctlName(s) {
- t.Errorf("%q expected to be a valid sysctl name", s)
- }
- }
- for _, s := range invalid {
- if IsValidSysctlName(s) {
- t.Errorf("%q expected to be an invalid sysctl name", s)
- }
- }
- }
- func TestValidateSysctls(t *testing.T) {
- valid := []string{
- "net.foo.bar",
- "kernel.shmmax",
- }
- invalid := []string{
- "i..nvalid",
- "_invalid",
- }
- duplicates := []string{
- "kernel.shmmax",
- "kernel.shmmax",
- }
- sysctls := make([]core.Sysctl, len(valid))
- for i, sysctl := range valid {
- sysctls[i].Name = sysctl
- }
- errs := validateSysctls(sysctls, field.NewPath("foo"))
- if len(errs) != 0 {
- t.Errorf("unexpected validation errors: %v", errs)
- }
- sysctls = make([]core.Sysctl, len(invalid))
- for i, sysctl := range invalid {
- sysctls[i].Name = sysctl
- }
- errs = validateSysctls(sysctls, field.NewPath("foo"))
- if len(errs) != 2 {
- t.Errorf("expected 2 validation errors. Got: %v", errs)
- } else {
- if got, expected := errs[0].Error(), "foo"; !strings.Contains(got, expected) {
- t.Errorf("unexpected errors: expected=%q, got=%q", expected, got)
- }
- if got, expected := errs[1].Error(), "foo"; !strings.Contains(got, expected) {
- t.Errorf("unexpected errors: expected=%q, got=%q", expected, got)
- }
- }
- sysctls = make([]core.Sysctl, len(duplicates))
- for i, sysctl := range duplicates {
- sysctls[i].Name = sysctl
- }
- errs = validateSysctls(sysctls, field.NewPath("foo"))
- if len(errs) != 1 {
- t.Errorf("unexpected validation errors: %v", errs)
- } else if errs[0].Type != field.ErrorTypeDuplicate {
- t.Errorf("expected error type %v, got %v", field.ErrorTypeDuplicate, errs[0].Type)
- }
- }
- func newNodeNameEndpoint(nodeName string) *core.Endpoints {
- ep := &core.Endpoints{
- ObjectMeta: metav1.ObjectMeta{
- Name: "foo",
- Namespace: metav1.NamespaceDefault,
- ResourceVersion: "1",
- },
- Subsets: []core.EndpointSubset{
- {
- NotReadyAddresses: []core.EndpointAddress{},
- Ports: []core.EndpointPort{{Name: "https", Port: 443, Protocol: "TCP"}},
- Addresses: []core.EndpointAddress{
- {
- IP: "8.8.8.8",
- Hostname: "zookeeper1",
- NodeName: &nodeName}}}}}
- return ep
- }
- func TestEndpointAddressNodeNameUpdateRestrictions(t *testing.T) {
- oldEndpoint := newNodeNameEndpoint("kubernetes-node-setup-by-backend")
- updatedEndpoint := newNodeNameEndpoint("kubernetes-changed-nodename")
- // Check that NodeName can be changed during update, this is to accommodate the case where nodeIP or PodCIDR is reused.
- // The same ip will now have a different nodeName.
- errList := ValidateEndpoints(updatedEndpoint)
- errList = append(errList, ValidateEndpointsUpdate(updatedEndpoint, oldEndpoint)...)
- if len(errList) != 0 {
- t.Error("Endpoint should allow changing of Subset.Addresses.NodeName on update")
- }
- }
- func TestEndpointAddressNodeNameInvalidDNSSubdomain(t *testing.T) {
- // Check NodeName DNS validation
- endpoint := newNodeNameEndpoint("illegal*.nodename")
- errList := ValidateEndpoints(endpoint)
- if len(errList) == 0 {
- t.Error("Endpoint should reject invalid NodeName")
- }
- }
- func TestEndpointAddressNodeNameCanBeAnIPAddress(t *testing.T) {
- endpoint := newNodeNameEndpoint("10.10.1.1")
- errList := ValidateEndpoints(endpoint)
- if len(errList) != 0 {
- t.Error("Endpoint should accept a NodeName that is an IP address")
- }
- }
- func TestValidateFlexVolumeSource(t *testing.T) {
- testcases := map[string]struct {
- source *core.FlexVolumeSource
- expectedErrs map[string]string
- }{
- "valid": {
- source: &core.FlexVolumeSource{Driver: "foo"},
- expectedErrs: map[string]string{},
- },
- "valid with options": {
- source: &core.FlexVolumeSource{Driver: "foo", Options: map[string]string{"foo": "bar"}},
- expectedErrs: map[string]string{},
- },
- "no driver": {
- source: &core.FlexVolumeSource{Driver: ""},
- expectedErrs: map[string]string{"driver": "Required value"},
- },
- "reserved option keys": {
- source: &core.FlexVolumeSource{
- Driver: "foo",
- Options: map[string]string{
- // valid options
- "myns.io": "A",
- "myns.io/bar": "A",
- "myns.io/kubernetes.io": "A",
- // invalid options
- "KUBERNETES.IO": "A",
- "kubernetes.io": "A",
- "kubernetes.io/": "A",
- "kubernetes.io/foo": "A",
- "alpha.kubernetes.io": "A",
- "alpha.kubernetes.io/": "A",
- "alpha.kubernetes.io/foo": "A",
- "k8s.io": "A",
- "k8s.io/": "A",
- "k8s.io/foo": "A",
- "alpha.k8s.io": "A",
- "alpha.k8s.io/": "A",
- "alpha.k8s.io/foo": "A",
- },
- },
- expectedErrs: map[string]string{
- "options[KUBERNETES.IO]": "reserved",
- "options[kubernetes.io]": "reserved",
- "options[kubernetes.io/]": "reserved",
- "options[kubernetes.io/foo]": "reserved",
- "options[alpha.kubernetes.io]": "reserved",
- "options[alpha.kubernetes.io/]": "reserved",
- "options[alpha.kubernetes.io/foo]": "reserved",
- "options[k8s.io]": "reserved",
- "options[k8s.io/]": "reserved",
- "options[k8s.io/foo]": "reserved",
- "options[alpha.k8s.io]": "reserved",
- "options[alpha.k8s.io/]": "reserved",
- "options[alpha.k8s.io/foo]": "reserved",
- },
- },
- }
- for k, tc := range testcases {
- errs := validateFlexVolumeSource(tc.source, nil)
- for _, err := range errs {
- expectedErr, ok := tc.expectedErrs[err.Field]
- if !ok {
- t.Errorf("%s: unexpected err on field %s: %v", k, err.Field, err)
- continue
- }
- if !strings.Contains(err.Error(), expectedErr) {
- t.Errorf("%s: expected err on field %s to contain '%s', was %v", k, err.Field, expectedErr, err.Error())
- continue
- }
- }
- if len(errs) != len(tc.expectedErrs) {
- t.Errorf("%s: expected errs %#v, got %#v", k, tc.expectedErrs, errs)
- continue
- }
- }
- }
- func TestValidateOrSetClientIPAffinityConfig(t *testing.T) {
- successCases := map[string]*core.SessionAffinityConfig{
- "non-empty config, valid timeout: 1": {
- ClientIP: &core.ClientIPConfig{
- TimeoutSeconds: utilpointer.Int32Ptr(1),
- },
- },
- "non-empty config, valid timeout: core.MaxClientIPServiceAffinitySeconds-1": {
- ClientIP: &core.ClientIPConfig{
- TimeoutSeconds: utilpointer.Int32Ptr(core.MaxClientIPServiceAffinitySeconds - 1),
- },
- },
- "non-empty config, valid timeout: core.MaxClientIPServiceAffinitySeconds": {
- ClientIP: &core.ClientIPConfig{
- TimeoutSeconds: utilpointer.Int32Ptr(core.MaxClientIPServiceAffinitySeconds),
- },
- },
- }
- for name, test := range successCases {
- if errs := validateClientIPAffinityConfig(test, field.NewPath("field")); len(errs) != 0 {
- t.Errorf("case: %s, expected success: %v", name, errs)
- }
- }
- errorCases := map[string]*core.SessionAffinityConfig{
- "empty session affinity config": nil,
- "empty client IP config": {
- ClientIP: nil,
- },
- "empty timeoutSeconds": {
- ClientIP: &core.ClientIPConfig{
- TimeoutSeconds: nil,
- },
- },
- "non-empty config, invalid timeout: core.MaxClientIPServiceAffinitySeconds+1": {
- ClientIP: &core.ClientIPConfig{
- TimeoutSeconds: utilpointer.Int32Ptr(core.MaxClientIPServiceAffinitySeconds + 1),
- },
- },
- "non-empty config, invalid timeout: -1": {
- ClientIP: &core.ClientIPConfig{
- TimeoutSeconds: utilpointer.Int32Ptr(-1),
- },
- },
- "non-empty config, invalid timeout: 0": {
- ClientIP: &core.ClientIPConfig{
- TimeoutSeconds: utilpointer.Int32Ptr(0),
- },
- },
- }
- for name, test := range errorCases {
- if errs := validateClientIPAffinityConfig(test, field.NewPath("field")); len(errs) == 0 {
- t.Errorf("case: %v, expected failures: %v", name, errs)
- }
- }
- }
- func TestValidateWindowsSecurityContextOptions(t *testing.T) {
- toPtr := func(s string) *string {
- return &s
- }
- testCases := []struct {
- testName string
- windowsOptions *core.WindowsSecurityContextOptions
- expectedErrorSubstring string
- }{
- {
- testName: "a nil pointer",
- },
- {
- testName: "an empty struct",
- windowsOptions: &core.WindowsSecurityContextOptions{},
- },
- {
- testName: "a valid input",
- windowsOptions: &core.WindowsSecurityContextOptions{
- GMSACredentialSpecName: toPtr("dummy-gmsa-crep-spec-name"),
- GMSACredentialSpec: toPtr("dummy-gmsa-crep-spec-contents"),
- },
- },
- {
- testName: "a GMSA cred spec name that is not a valid resource name",
- windowsOptions: &core.WindowsSecurityContextOptions{
- // invalid because of the underscore
- GMSACredentialSpecName: toPtr("not_a-valid-gmsa-crep-spec-name"),
- },
- expectedErrorSubstring: dnsSubdomainLabelErrMsg,
- },
- {
- testName: "empty GMSA cred spec contents",
- windowsOptions: &core.WindowsSecurityContextOptions{
- GMSACredentialSpec: toPtr(""),
- },
- expectedErrorSubstring: "gmsaCredentialSpec cannot be an empty string",
- },
- {
- testName: "GMSA cred spec contents that are too long",
- windowsOptions: &core.WindowsSecurityContextOptions{
- GMSACredentialSpec: toPtr(strings.Repeat("a", maxGMSACredentialSpecLength+1)),
- },
- expectedErrorSubstring: "gmsaCredentialSpec size must be under",
- },
- }
- for _, testCase := range testCases {
- t.Run("validateWindowsSecurityContextOptions with"+testCase.testName, func(t *testing.T) {
- errs := validateWindowsSecurityContextOptions(testCase.windowsOptions, field.NewPath("field"))
- switch len(errs) {
- case 0:
- if testCase.expectedErrorSubstring != "" {
- t.Errorf("expected a failure containing the substring: %q", testCase.expectedErrorSubstring)
- }
- case 1:
- if testCase.expectedErrorSubstring == "" {
- t.Errorf("didn't expect a failure, got: %q", errs[0].Error())
- } else if !strings.Contains(errs[0].Error(), testCase.expectedErrorSubstring) {
- t.Errorf("expected a failure with the substring %q, got %q instead", testCase.expectedErrorSubstring, errs[0].Error())
- }
- default:
- t.Errorf("got %d failures", len(errs))
- for i, err := range errs {
- t.Errorf("error %d: %q", i, err.Error())
- }
- }
- })
- }
- }
- func testDataSourceInSpec(name string, kind string, apiGroup string) *core.PersistentVolumeClaimSpec {
- scName := "csi-plugin"
- dataSourceInSpec := core.PersistentVolumeClaimSpec{
- AccessModes: []core.PersistentVolumeAccessMode{
- core.ReadOnlyMany,
- },
- Resources: core.ResourceRequirements{
- Requests: core.ResourceList{
- core.ResourceName(core.ResourceStorage): resource.MustParse("10G"),
- },
- },
- StorageClassName: &scName,
- DataSource: &core.TypedLocalObjectReference{
- APIGroup: &apiGroup,
- Kind: kind,
- Name: name,
- },
- }
- return &dataSourceInSpec
- }
- func TestAlphaVolumePVCDataSource(t *testing.T) {
- testCases := []struct {
- testName string
- claimSpec core.PersistentVolumeClaimSpec
- expectedFail bool
- }{
- {
- testName: "test create from valid snapshot source",
- claimSpec: *testDataSourceInSpec("test_snapshot", "VolumeSnapshot", "snapshot.storage.k8s.io"),
- },
- {
- testName: "test create from valid pvc source",
- claimSpec: *testDataSourceInSpec("test_pvc", "PersistentVolumeClaim", ""),
- },
- {
- testName: "test missing name in snapshot datasource should fail",
- claimSpec: *testDataSourceInSpec("", "VolumeSnapshot", "snapshot.storage.k8s.io"),
- expectedFail: true,
- },
- {
- testName: "test specifying pvc with snapshot api group should fail",
- claimSpec: *testDataSourceInSpec("test_snapshot", "PersistentVolumeClaim", "snapshot.storage.k8s.io"),
- expectedFail: true,
- },
- {
- testName: "test invalid group name in snapshot datasource should fail",
- claimSpec: *testDataSourceInSpec("test_snapshot", "VolumeSnapshot", "storage.k8s.io"),
- expectedFail: true,
- },
- }
- for _, tc := range testCases {
- if tc.expectedFail {
- if errs := ValidatePersistentVolumeClaimSpec(&tc.claimSpec, field.NewPath("spec")); len(errs) == 0 {
- t.Errorf("expected failure: %v", errs)
- }
- } else {
- if errs := ValidatePersistentVolumeClaimSpec(&tc.claimSpec, field.NewPath("spec")); len(errs) != 0 {
- t.Errorf("expected success: %v", errs)
- }
- }
- }
- }
|