validation_test.go 221 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033
  1. /*
  2. Copyright 2014 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package validation
  14. import (
  15. "math/rand"
  16. "reflect"
  17. "strings"
  18. "testing"
  19. "time"
  20. "k8s.io/kubernetes/pkg/api"
  21. "k8s.io/kubernetes/pkg/api/resource"
  22. "k8s.io/kubernetes/pkg/api/service"
  23. "k8s.io/kubernetes/pkg/api/testapi"
  24. "k8s.io/kubernetes/pkg/api/unversioned"
  25. "k8s.io/kubernetes/pkg/capabilities"
  26. "k8s.io/kubernetes/pkg/security/apparmor"
  27. "k8s.io/kubernetes/pkg/util/intstr"
  28. "k8s.io/kubernetes/pkg/util/sets"
  29. "k8s.io/kubernetes/pkg/util/validation/field"
  30. )
  31. func expectPrefix(t *testing.T, prefix string, errs field.ErrorList) {
  32. for i := range errs {
  33. if f, p := errs[i].Field, prefix; !strings.HasPrefix(f, p) {
  34. t.Errorf("expected prefix '%s' for field '%s' (%v)", p, f, errs[i])
  35. }
  36. }
  37. }
  38. // Ensure custom name functions are allowed
  39. func TestValidateObjectMetaCustomName(t *testing.T) {
  40. errs := ValidateObjectMeta(
  41. &api.ObjectMeta{Name: "test", GenerateName: "foo"},
  42. false,
  43. func(s string, prefix bool) []string {
  44. if s == "test" {
  45. return nil
  46. }
  47. return []string{"name-gen"}
  48. },
  49. field.NewPath("field"))
  50. if len(errs) != 1 {
  51. t.Fatalf("unexpected errors: %v", errs)
  52. }
  53. if !strings.Contains(errs[0].Error(), "name-gen") {
  54. t.Errorf("unexpected error message: %v", errs)
  55. }
  56. }
  57. // Ensure namespace names follow dns label format
  58. func TestValidateObjectMetaNamespaces(t *testing.T) {
  59. errs := ValidateObjectMeta(
  60. &api.ObjectMeta{Name: "test", Namespace: "foo.bar"},
  61. true,
  62. func(s string, prefix bool) []string {
  63. return nil
  64. },
  65. field.NewPath("field"))
  66. if len(errs) != 1 {
  67. t.Fatalf("unexpected errors: %v", errs)
  68. }
  69. if !strings.Contains(errs[0].Error(), `Invalid value: "foo.bar"`) {
  70. t.Errorf("unexpected error message: %v", errs)
  71. }
  72. maxLength := 63
  73. letters := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
  74. b := make([]rune, maxLength+1)
  75. for i := range b {
  76. b[i] = letters[rand.Intn(len(letters))]
  77. }
  78. errs = ValidateObjectMeta(
  79. &api.ObjectMeta{Name: "test", Namespace: string(b)},
  80. true,
  81. func(s string, prefix bool) []string {
  82. return nil
  83. },
  84. field.NewPath("field"))
  85. if len(errs) != 2 {
  86. t.Fatalf("unexpected errors: %v", errs)
  87. }
  88. if !strings.Contains(errs[0].Error(), "Invalid value") || !strings.Contains(errs[1].Error(), "Invalid value") {
  89. t.Errorf("unexpected error message: %v", errs)
  90. }
  91. }
  92. func TestValidateObjectMetaOwnerReferences(t *testing.T) {
  93. trueVar := true
  94. falseVar := false
  95. testCases := []struct {
  96. description string
  97. ownerReferences []api.OwnerReference
  98. expectError bool
  99. expectedErrorMessage string
  100. }{
  101. {
  102. description: "simple success - third party extension.",
  103. ownerReferences: []api.OwnerReference{
  104. {
  105. APIVersion: "thirdpartyVersion",
  106. Kind: "thirdpartyKind",
  107. Name: "name",
  108. UID: "1",
  109. },
  110. },
  111. expectError: false,
  112. expectedErrorMessage: "",
  113. },
  114. {
  115. description: "simple failures - event shouldn't be set as an owner",
  116. ownerReferences: []api.OwnerReference{
  117. {
  118. APIVersion: "v1",
  119. Kind: "Event",
  120. Name: "name",
  121. UID: "1",
  122. },
  123. },
  124. expectError: true,
  125. expectedErrorMessage: "is disallowed from being an owner",
  126. },
  127. {
  128. description: "simple controller ref success - one reference with Controller set",
  129. ownerReferences: []api.OwnerReference{
  130. {
  131. APIVersion: "thirdpartyVersion",
  132. Kind: "thirdpartyKind",
  133. Name: "name",
  134. UID: "1",
  135. Controller: &falseVar,
  136. },
  137. {
  138. APIVersion: "thirdpartyVersion",
  139. Kind: "thirdpartyKind",
  140. Name: "name",
  141. UID: "2",
  142. Controller: &trueVar,
  143. },
  144. {
  145. APIVersion: "thirdpartyVersion",
  146. Kind: "thirdpartyKind",
  147. Name: "name",
  148. UID: "3",
  149. Controller: &falseVar,
  150. },
  151. {
  152. APIVersion: "thirdpartyVersion",
  153. Kind: "thirdpartyKind",
  154. Name: "name",
  155. UID: "4",
  156. },
  157. },
  158. expectError: false,
  159. expectedErrorMessage: "",
  160. },
  161. {
  162. description: "simple controller ref failure - two references with Controller set",
  163. ownerReferences: []api.OwnerReference{
  164. {
  165. APIVersion: "thirdpartyVersion",
  166. Kind: "thirdpartyKind",
  167. Name: "name",
  168. UID: "1",
  169. Controller: &falseVar,
  170. },
  171. {
  172. APIVersion: "thirdpartyVersion",
  173. Kind: "thirdpartyKind",
  174. Name: "name",
  175. UID: "2",
  176. Controller: &trueVar,
  177. },
  178. {
  179. APIVersion: "thirdpartyVersion",
  180. Kind: "thirdpartyKind",
  181. Name: "name",
  182. UID: "3",
  183. Controller: &trueVar,
  184. },
  185. {
  186. APIVersion: "thirdpartyVersion",
  187. Kind: "thirdpartyKind",
  188. Name: "name",
  189. UID: "4",
  190. },
  191. },
  192. expectError: true,
  193. expectedErrorMessage: "Only one reference can have Controller set to true",
  194. },
  195. }
  196. for _, tc := range testCases {
  197. errs := ValidateObjectMeta(
  198. &api.ObjectMeta{Name: "test", Namespace: "test", OwnerReferences: tc.ownerReferences},
  199. true,
  200. func(s string, prefix bool) []string {
  201. return nil
  202. },
  203. field.NewPath("field"))
  204. if len(errs) != 0 && !tc.expectError {
  205. t.Errorf("unexpected error: %v in test case %v", errs, tc.description)
  206. }
  207. if len(errs) == 0 && tc.expectError {
  208. t.Errorf("expect error in test case %v", tc.description)
  209. }
  210. if len(errs) != 0 && !strings.Contains(errs[0].Error(), tc.expectedErrorMessage) {
  211. t.Errorf("unexpected error message: %v in test case %v", errs, tc.description)
  212. }
  213. }
  214. }
  215. func TestValidateObjectMetaUpdateIgnoresCreationTimestamp(t *testing.T) {
  216. if errs := ValidateObjectMetaUpdate(
  217. &api.ObjectMeta{Name: "test", ResourceVersion: "1"},
  218. &api.ObjectMeta{Name: "test", ResourceVersion: "1", CreationTimestamp: unversioned.NewTime(time.Unix(10, 0))},
  219. field.NewPath("field"),
  220. ); len(errs) != 0 {
  221. t.Fatalf("unexpected errors: %v", errs)
  222. }
  223. if errs := ValidateObjectMetaUpdate(
  224. &api.ObjectMeta{Name: "test", ResourceVersion: "1", CreationTimestamp: unversioned.NewTime(time.Unix(10, 0))},
  225. &api.ObjectMeta{Name: "test", ResourceVersion: "1"},
  226. field.NewPath("field"),
  227. ); len(errs) != 0 {
  228. t.Fatalf("unexpected errors: %v", errs)
  229. }
  230. if errs := ValidateObjectMetaUpdate(
  231. &api.ObjectMeta{Name: "test", ResourceVersion: "1", CreationTimestamp: unversioned.NewTime(time.Unix(10, 0))},
  232. &api.ObjectMeta{Name: "test", ResourceVersion: "1", CreationTimestamp: unversioned.NewTime(time.Unix(11, 0))},
  233. field.NewPath("field"),
  234. ); len(errs) != 0 {
  235. t.Fatalf("unexpected errors: %v", errs)
  236. }
  237. }
  238. func TestValidateObjectMetaUpdatePreventsDeletionFieldMutation(t *testing.T) {
  239. now := unversioned.NewTime(time.Unix(1000, 0).UTC())
  240. later := unversioned.NewTime(time.Unix(2000, 0).UTC())
  241. gracePeriodShort := int64(30)
  242. gracePeriodLong := int64(40)
  243. testcases := map[string]struct {
  244. Old api.ObjectMeta
  245. New api.ObjectMeta
  246. ExpectedNew api.ObjectMeta
  247. ExpectedErrs []string
  248. }{
  249. "valid without deletion fields": {
  250. Old: api.ObjectMeta{Name: "test", ResourceVersion: "1"},
  251. New: api.ObjectMeta{Name: "test", ResourceVersion: "1"},
  252. ExpectedNew: api.ObjectMeta{Name: "test", ResourceVersion: "1"},
  253. ExpectedErrs: []string{},
  254. },
  255. "valid with deletion fields": {
  256. Old: api.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &now, DeletionGracePeriodSeconds: &gracePeriodShort},
  257. New: api.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &now, DeletionGracePeriodSeconds: &gracePeriodShort},
  258. ExpectedNew: api.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &now, DeletionGracePeriodSeconds: &gracePeriodShort},
  259. ExpectedErrs: []string{},
  260. },
  261. "invalid set deletionTimestamp": {
  262. Old: api.ObjectMeta{Name: "test", ResourceVersion: "1"},
  263. New: api.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &now},
  264. ExpectedNew: api.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &now},
  265. ExpectedErrs: []string{"field.deletionTimestamp: Invalid value: \"1970-01-01T00:16:40Z\": field is immutable; may only be changed via deletion"},
  266. },
  267. "invalid clear deletionTimestamp": {
  268. Old: api.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &now},
  269. New: api.ObjectMeta{Name: "test", ResourceVersion: "1"},
  270. ExpectedNew: api.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &now},
  271. ExpectedErrs: []string{}, // no errors, validation copies the old value
  272. },
  273. "invalid change deletionTimestamp": {
  274. Old: api.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &now},
  275. New: api.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &later},
  276. ExpectedNew: api.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionTimestamp: &now},
  277. ExpectedErrs: []string{}, // no errors, validation copies the old value
  278. },
  279. "invalid set deletionGracePeriodSeconds": {
  280. Old: api.ObjectMeta{Name: "test", ResourceVersion: "1"},
  281. New: api.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionGracePeriodSeconds: &gracePeriodShort},
  282. ExpectedNew: api.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionGracePeriodSeconds: &gracePeriodShort},
  283. ExpectedErrs: []string{"field.deletionGracePeriodSeconds: Invalid value: 30: field is immutable; may only be changed via deletion"},
  284. },
  285. "invalid clear deletionGracePeriodSeconds": {
  286. Old: api.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionGracePeriodSeconds: &gracePeriodShort},
  287. New: api.ObjectMeta{Name: "test", ResourceVersion: "1"},
  288. ExpectedNew: api.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionGracePeriodSeconds: &gracePeriodShort},
  289. ExpectedErrs: []string{}, // no errors, validation copies the old value
  290. },
  291. "invalid change deletionGracePeriodSeconds": {
  292. Old: api.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionGracePeriodSeconds: &gracePeriodShort},
  293. New: api.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionGracePeriodSeconds: &gracePeriodLong},
  294. ExpectedNew: api.ObjectMeta{Name: "test", ResourceVersion: "1", DeletionGracePeriodSeconds: &gracePeriodLong},
  295. ExpectedErrs: []string{"field.deletionGracePeriodSeconds: Invalid value: 40: field is immutable; may only be changed via deletion"},
  296. },
  297. }
  298. for k, tc := range testcases {
  299. errs := ValidateObjectMetaUpdate(&tc.New, &tc.Old, field.NewPath("field"))
  300. if len(errs) != len(tc.ExpectedErrs) {
  301. t.Logf("%s: Expected: %#v", k, tc.ExpectedErrs)
  302. t.Logf("%s: Got: %#v", k, errs)
  303. t.Errorf("%s: expected %d errors, got %d", k, len(tc.ExpectedErrs), len(errs))
  304. continue
  305. }
  306. for i := range errs {
  307. if errs[i].Error() != tc.ExpectedErrs[i] {
  308. t.Errorf("%s: error #%d: expected %q, got %q", k, i, tc.ExpectedErrs[i], errs[i].Error())
  309. }
  310. }
  311. if !reflect.DeepEqual(tc.New, tc.ExpectedNew) {
  312. t.Errorf("%s: Expected after validation:\n%#v\ngot\n%#v", k, tc.ExpectedNew, tc.New)
  313. }
  314. }
  315. }
  316. func TestObjectMetaGenerationUpdate(t *testing.T) {
  317. testcases := map[string]struct {
  318. Old api.ObjectMeta
  319. New api.ObjectMeta
  320. ExpectedErrs []string
  321. }{
  322. "invalid generation change - decremented": {
  323. Old: api.ObjectMeta{Name: "test", ResourceVersion: "1", Generation: 5},
  324. New: api.ObjectMeta{Name: "test", ResourceVersion: "1", Generation: 4},
  325. ExpectedErrs: []string{"field.generation: Invalid value: 4: must not be decremented"},
  326. },
  327. "valid generation change - incremented by one": {
  328. Old: api.ObjectMeta{Name: "test", ResourceVersion: "1", Generation: 1},
  329. New: api.ObjectMeta{Name: "test", ResourceVersion: "1", Generation: 2},
  330. ExpectedErrs: []string{},
  331. },
  332. "valid generation field - not updated": {
  333. Old: api.ObjectMeta{Name: "test", ResourceVersion: "1", Generation: 5},
  334. New: api.ObjectMeta{Name: "test", ResourceVersion: "1", Generation: 5},
  335. ExpectedErrs: []string{},
  336. },
  337. }
  338. for k, tc := range testcases {
  339. errList := []string{}
  340. errs := ValidateObjectMetaUpdate(&tc.New, &tc.Old, field.NewPath("field"))
  341. if len(errs) != len(tc.ExpectedErrs) {
  342. t.Logf("%s: Expected: %#v", k, tc.ExpectedErrs)
  343. for _, err := range errs {
  344. errList = append(errList, err.Error())
  345. }
  346. t.Logf("%s: Got: %#v", k, errList)
  347. t.Errorf("%s: expected %d errors, got %d", k, len(tc.ExpectedErrs), len(errs))
  348. continue
  349. }
  350. for i := range errList {
  351. if errList[i] != tc.ExpectedErrs[i] {
  352. t.Errorf("%s: error #%d: expected %q, got %q", k, i, tc.ExpectedErrs[i], errList[i])
  353. }
  354. }
  355. }
  356. }
  357. // Ensure trailing slash is allowed in generate name
  358. func TestValidateObjectMetaTrimsTrailingSlash(t *testing.T) {
  359. errs := ValidateObjectMeta(
  360. &api.ObjectMeta{Name: "test", GenerateName: "foo-"},
  361. false,
  362. NameIsDNSSubdomain,
  363. field.NewPath("field"))
  364. if len(errs) != 0 {
  365. t.Fatalf("unexpected errors: %v", errs)
  366. }
  367. }
  368. func TestValidateAnnotations(t *testing.T) {
  369. successCases := []map[string]string{
  370. {"simple": "bar"},
  371. {"now-with-dashes": "bar"},
  372. {"1-starts-with-num": "bar"},
  373. {"1234": "bar"},
  374. {"simple/simple": "bar"},
  375. {"now-with-dashes/simple": "bar"},
  376. {"now-with-dashes/now-with-dashes": "bar"},
  377. {"now.with.dots/simple": "bar"},
  378. {"now-with.dashes-and.dots/simple": "bar"},
  379. {"1-num.2-num/3-num": "bar"},
  380. {"1234/5678": "bar"},
  381. {"1.2.3.4/5678": "bar"},
  382. {"UpperCase123": "bar"},
  383. {"a": strings.Repeat("b", totalAnnotationSizeLimitB-1)},
  384. {
  385. "a": strings.Repeat("b", totalAnnotationSizeLimitB/2-1),
  386. "c": strings.Repeat("d", totalAnnotationSizeLimitB/2-1),
  387. },
  388. }
  389. for i := range successCases {
  390. errs := ValidateAnnotations(successCases[i], field.NewPath("field"))
  391. if len(errs) != 0 {
  392. t.Errorf("case[%d] expected success, got %#v", i, errs)
  393. }
  394. }
  395. nameErrorCases := []struct {
  396. annotations map[string]string
  397. expect string
  398. }{
  399. {map[string]string{"nospecialchars^=@": "bar"}, "must match the regex"},
  400. {map[string]string{"cantendwithadash-": "bar"}, "must match the regex"},
  401. {map[string]string{"only/one/slash": "bar"}, "must match the regex"},
  402. {map[string]string{strings.Repeat("a", 254): "bar"}, "must be no more than"},
  403. }
  404. for i := range nameErrorCases {
  405. errs := ValidateAnnotations(nameErrorCases[i].annotations, field.NewPath("field"))
  406. if len(errs) != 1 {
  407. t.Errorf("case[%d]: expected failure", i)
  408. } else {
  409. if !strings.Contains(errs[0].Detail, nameErrorCases[i].expect) {
  410. t.Errorf("case[%d]: error details do not include %q: %q", i, nameErrorCases[i].expect, errs[0].Detail)
  411. }
  412. }
  413. }
  414. totalSizeErrorCases := []map[string]string{
  415. {"a": strings.Repeat("b", totalAnnotationSizeLimitB)},
  416. {
  417. "a": strings.Repeat("b", totalAnnotationSizeLimitB/2),
  418. "c": strings.Repeat("d", totalAnnotationSizeLimitB/2),
  419. },
  420. }
  421. for i := range totalSizeErrorCases {
  422. errs := ValidateAnnotations(totalSizeErrorCases[i], field.NewPath("field"))
  423. if len(errs) != 1 {
  424. t.Errorf("case[%d] expected failure", i)
  425. }
  426. }
  427. }
  428. func testVolume(name string, namespace string, spec api.PersistentVolumeSpec) *api.PersistentVolume {
  429. objMeta := api.ObjectMeta{Name: name}
  430. if namespace != "" {
  431. objMeta.Namespace = namespace
  432. }
  433. return &api.PersistentVolume{
  434. ObjectMeta: objMeta,
  435. Spec: spec,
  436. }
  437. }
  438. func TestValidatePersistentVolumes(t *testing.T) {
  439. scenarios := map[string]struct {
  440. isExpectedFailure bool
  441. volume *api.PersistentVolume
  442. }{
  443. "good-volume": {
  444. isExpectedFailure: false,
  445. volume: testVolume("foo", "", api.PersistentVolumeSpec{
  446. Capacity: api.ResourceList{
  447. api.ResourceName(api.ResourceStorage): resource.MustParse("10G"),
  448. },
  449. AccessModes: []api.PersistentVolumeAccessMode{api.ReadWriteOnce},
  450. PersistentVolumeSource: api.PersistentVolumeSource{
  451. HostPath: &api.HostPathVolumeSource{Path: "/foo"},
  452. },
  453. }),
  454. },
  455. "invalid-accessmode": {
  456. isExpectedFailure: true,
  457. volume: testVolume("foo", "", api.PersistentVolumeSpec{
  458. Capacity: api.ResourceList{
  459. api.ResourceName(api.ResourceStorage): resource.MustParse("10G"),
  460. },
  461. AccessModes: []api.PersistentVolumeAccessMode{"fakemode"},
  462. PersistentVolumeSource: api.PersistentVolumeSource{
  463. HostPath: &api.HostPathVolumeSource{Path: "/foo"},
  464. },
  465. }),
  466. },
  467. "unexpected-namespace": {
  468. isExpectedFailure: true,
  469. volume: testVolume("foo", "unexpected-namespace", api.PersistentVolumeSpec{
  470. Capacity: api.ResourceList{
  471. api.ResourceName(api.ResourceStorage): resource.MustParse("10G"),
  472. },
  473. AccessModes: []api.PersistentVolumeAccessMode{api.ReadWriteOnce},
  474. PersistentVolumeSource: api.PersistentVolumeSource{
  475. HostPath: &api.HostPathVolumeSource{Path: "/foo"},
  476. },
  477. }),
  478. },
  479. "bad-name": {
  480. isExpectedFailure: true,
  481. volume: testVolume("123*Bad(Name", "unexpected-namespace", api.PersistentVolumeSpec{
  482. Capacity: api.ResourceList{
  483. api.ResourceName(api.ResourceStorage): resource.MustParse("10G"),
  484. },
  485. AccessModes: []api.PersistentVolumeAccessMode{api.ReadWriteOnce},
  486. PersistentVolumeSource: api.PersistentVolumeSource{
  487. HostPath: &api.HostPathVolumeSource{Path: "/foo"},
  488. },
  489. }),
  490. },
  491. "missing-name": {
  492. isExpectedFailure: true,
  493. volume: testVolume("", "", api.PersistentVolumeSpec{
  494. Capacity: api.ResourceList{
  495. api.ResourceName(api.ResourceStorage): resource.MustParse("10G"),
  496. },
  497. AccessModes: []api.PersistentVolumeAccessMode{api.ReadWriteOnce},
  498. }),
  499. },
  500. "missing-capacity": {
  501. isExpectedFailure: true,
  502. volume: testVolume("foo", "", api.PersistentVolumeSpec{}),
  503. },
  504. "missing-accessmodes": {
  505. isExpectedFailure: true,
  506. volume: testVolume("goodname", "missing-accessmodes", api.PersistentVolumeSpec{
  507. Capacity: api.ResourceList{
  508. api.ResourceName(api.ResourceStorage): resource.MustParse("10G"),
  509. },
  510. PersistentVolumeSource: api.PersistentVolumeSource{
  511. HostPath: &api.HostPathVolumeSource{Path: "/foo"},
  512. },
  513. }),
  514. },
  515. "too-many-sources": {
  516. isExpectedFailure: true,
  517. volume: testVolume("", "", api.PersistentVolumeSpec{
  518. Capacity: api.ResourceList{
  519. api.ResourceName(api.ResourceStorage): resource.MustParse("5G"),
  520. },
  521. PersistentVolumeSource: api.PersistentVolumeSource{
  522. HostPath: &api.HostPathVolumeSource{Path: "/foo"},
  523. GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{PDName: "foo", FSType: "ext4"},
  524. },
  525. }),
  526. },
  527. "host mount of / with recycle reclaim policy": {
  528. isExpectedFailure: true,
  529. volume: testVolume("bad-recycle-do-not-want", "", api.PersistentVolumeSpec{
  530. Capacity: api.ResourceList{
  531. api.ResourceName(api.ResourceStorage): resource.MustParse("10G"),
  532. },
  533. AccessModes: []api.PersistentVolumeAccessMode{api.ReadWriteOnce},
  534. PersistentVolumeSource: api.PersistentVolumeSource{
  535. HostPath: &api.HostPathVolumeSource{Path: "/"},
  536. },
  537. PersistentVolumeReclaimPolicy: api.PersistentVolumeReclaimRecycle,
  538. }),
  539. },
  540. "host mount of / with recycle reclaim policy 2": {
  541. isExpectedFailure: true,
  542. volume: testVolume("bad-recycle-do-not-want", "", api.PersistentVolumeSpec{
  543. Capacity: api.ResourceList{
  544. api.ResourceName(api.ResourceStorage): resource.MustParse("10G"),
  545. },
  546. AccessModes: []api.PersistentVolumeAccessMode{api.ReadWriteOnce},
  547. PersistentVolumeSource: api.PersistentVolumeSource{
  548. HostPath: &api.HostPathVolumeSource{Path: "/a/.."},
  549. },
  550. PersistentVolumeReclaimPolicy: api.PersistentVolumeReclaimRecycle,
  551. }),
  552. },
  553. }
  554. for name, scenario := range scenarios {
  555. errs := ValidatePersistentVolume(scenario.volume)
  556. if len(errs) == 0 && scenario.isExpectedFailure {
  557. t.Errorf("Unexpected success for scenario: %s", name)
  558. }
  559. if len(errs) > 0 && !scenario.isExpectedFailure {
  560. t.Errorf("Unexpected failure for scenario: %s - %+v", name, errs)
  561. }
  562. }
  563. }
  564. func testVolumeClaim(name string, namespace string, spec api.PersistentVolumeClaimSpec) *api.PersistentVolumeClaim {
  565. return &api.PersistentVolumeClaim{
  566. ObjectMeta: api.ObjectMeta{Name: name, Namespace: namespace},
  567. Spec: spec,
  568. }
  569. }
  570. func TestValidatePersistentVolumeClaim(t *testing.T) {
  571. scenarios := map[string]struct {
  572. isExpectedFailure bool
  573. claim *api.PersistentVolumeClaim
  574. }{
  575. "good-claim": {
  576. isExpectedFailure: false,
  577. claim: testVolumeClaim("foo", "ns", api.PersistentVolumeClaimSpec{
  578. Selector: &unversioned.LabelSelector{
  579. MatchExpressions: []unversioned.LabelSelectorRequirement{
  580. {
  581. Key: "key2",
  582. Operator: "Exists",
  583. },
  584. },
  585. },
  586. AccessModes: []api.PersistentVolumeAccessMode{
  587. api.ReadWriteOnce,
  588. api.ReadOnlyMany,
  589. },
  590. Resources: api.ResourceRequirements{
  591. Requests: api.ResourceList{
  592. api.ResourceName(api.ResourceStorage): resource.MustParse("10G"),
  593. },
  594. },
  595. }),
  596. },
  597. "invalid-label-selector": {
  598. isExpectedFailure: true,
  599. claim: testVolumeClaim("foo", "ns", api.PersistentVolumeClaimSpec{
  600. Selector: &unversioned.LabelSelector{
  601. MatchExpressions: []unversioned.LabelSelectorRequirement{
  602. {
  603. Key: "key2",
  604. Operator: "InvalidOp",
  605. Values: []string{"value1", "value2"},
  606. },
  607. },
  608. },
  609. AccessModes: []api.PersistentVolumeAccessMode{
  610. api.ReadWriteOnce,
  611. api.ReadOnlyMany,
  612. },
  613. Resources: api.ResourceRequirements{
  614. Requests: api.ResourceList{
  615. api.ResourceName(api.ResourceStorage): resource.MustParse("10G"),
  616. },
  617. },
  618. }),
  619. },
  620. "invalid-accessmode": {
  621. isExpectedFailure: true,
  622. claim: testVolumeClaim("foo", "ns", api.PersistentVolumeClaimSpec{
  623. AccessModes: []api.PersistentVolumeAccessMode{"fakemode"},
  624. Resources: api.ResourceRequirements{
  625. Requests: api.ResourceList{
  626. api.ResourceName(api.ResourceStorage): resource.MustParse("10G"),
  627. },
  628. },
  629. }),
  630. },
  631. "missing-namespace": {
  632. isExpectedFailure: true,
  633. claim: testVolumeClaim("foo", "", api.PersistentVolumeClaimSpec{
  634. AccessModes: []api.PersistentVolumeAccessMode{
  635. api.ReadWriteOnce,
  636. api.ReadOnlyMany,
  637. },
  638. Resources: api.ResourceRequirements{
  639. Requests: api.ResourceList{
  640. api.ResourceName(api.ResourceStorage): resource.MustParse("10G"),
  641. },
  642. },
  643. }),
  644. },
  645. "no-access-modes": {
  646. isExpectedFailure: true,
  647. claim: testVolumeClaim("foo", "ns", api.PersistentVolumeClaimSpec{
  648. Resources: api.ResourceRequirements{
  649. Requests: api.ResourceList{
  650. api.ResourceName(api.ResourceStorage): resource.MustParse("10G"),
  651. },
  652. },
  653. }),
  654. },
  655. "no-resource-requests": {
  656. isExpectedFailure: true,
  657. claim: testVolumeClaim("foo", "ns", api.PersistentVolumeClaimSpec{
  658. AccessModes: []api.PersistentVolumeAccessMode{
  659. api.ReadWriteOnce,
  660. },
  661. }),
  662. },
  663. "invalid-resource-requests": {
  664. isExpectedFailure: true,
  665. claim: testVolumeClaim("foo", "ns", api.PersistentVolumeClaimSpec{
  666. AccessModes: []api.PersistentVolumeAccessMode{
  667. api.ReadWriteOnce,
  668. },
  669. Resources: api.ResourceRequirements{
  670. Requests: api.ResourceList{
  671. api.ResourceName(api.ResourceMemory): resource.MustParse("10G"),
  672. },
  673. },
  674. }),
  675. },
  676. "negative-storage-request": {
  677. isExpectedFailure: true,
  678. claim: testVolumeClaim("foo", "ns", api.PersistentVolumeClaimSpec{
  679. Selector: &unversioned.LabelSelector{
  680. MatchExpressions: []unversioned.LabelSelectorRequirement{
  681. {
  682. Key: "key2",
  683. Operator: "Exists",
  684. },
  685. },
  686. },
  687. AccessModes: []api.PersistentVolumeAccessMode{
  688. api.ReadWriteOnce,
  689. api.ReadOnlyMany,
  690. },
  691. Resources: api.ResourceRequirements{
  692. Requests: api.ResourceList{
  693. api.ResourceName(api.ResourceStorage): resource.MustParse("-10G"),
  694. },
  695. },
  696. }),
  697. },
  698. }
  699. for name, scenario := range scenarios {
  700. errs := ValidatePersistentVolumeClaim(scenario.claim)
  701. if len(errs) == 0 && scenario.isExpectedFailure {
  702. t.Errorf("Unexpected success for scenario: %s", name)
  703. }
  704. if len(errs) > 0 && !scenario.isExpectedFailure {
  705. t.Errorf("Unexpected failure for scenario: %s - %+v", name, errs)
  706. }
  707. }
  708. }
  709. func TestValidatePersistentVolumeClaimUpdate(t *testing.T) {
  710. validClaim := testVolumeClaim("foo", "ns", api.PersistentVolumeClaimSpec{
  711. AccessModes: []api.PersistentVolumeAccessMode{
  712. api.ReadWriteOnce,
  713. api.ReadOnlyMany,
  714. },
  715. Resources: api.ResourceRequirements{
  716. Requests: api.ResourceList{
  717. api.ResourceName(api.ResourceStorage): resource.MustParse("10G"),
  718. },
  719. },
  720. })
  721. validUpdateClaim := testVolumeClaim("foo", "ns", api.PersistentVolumeClaimSpec{
  722. AccessModes: []api.PersistentVolumeAccessMode{
  723. api.ReadWriteOnce,
  724. api.ReadOnlyMany,
  725. },
  726. Resources: api.ResourceRequirements{
  727. Requests: api.ResourceList{
  728. api.ResourceName(api.ResourceStorage): resource.MustParse("10G"),
  729. },
  730. },
  731. VolumeName: "volume",
  732. })
  733. invalidUpdateClaimResources := testVolumeClaim("foo", "ns", api.PersistentVolumeClaimSpec{
  734. AccessModes: []api.PersistentVolumeAccessMode{
  735. api.ReadWriteOnce,
  736. api.ReadOnlyMany,
  737. },
  738. Resources: api.ResourceRequirements{
  739. Requests: api.ResourceList{
  740. api.ResourceName(api.ResourceStorage): resource.MustParse("20G"),
  741. },
  742. },
  743. VolumeName: "volume",
  744. })
  745. invalidUpdateClaimAccessModes := testVolumeClaim("foo", "ns", api.PersistentVolumeClaimSpec{
  746. AccessModes: []api.PersistentVolumeAccessMode{
  747. api.ReadWriteOnce,
  748. },
  749. Resources: api.ResourceRequirements{
  750. Requests: api.ResourceList{
  751. api.ResourceName(api.ResourceStorage): resource.MustParse("10G"),
  752. },
  753. },
  754. VolumeName: "volume",
  755. })
  756. scenarios := map[string]struct {
  757. isExpectedFailure bool
  758. oldClaim *api.PersistentVolumeClaim
  759. newClaim *api.PersistentVolumeClaim
  760. }{
  761. "valid-update-volumeName-only": {
  762. isExpectedFailure: false,
  763. oldClaim: validClaim,
  764. newClaim: validUpdateClaim,
  765. },
  766. "valid-no-op-update": {
  767. isExpectedFailure: false,
  768. oldClaim: validUpdateClaim,
  769. newClaim: validUpdateClaim,
  770. },
  771. "invalid-update-change-resources-on-bound-claim": {
  772. isExpectedFailure: true,
  773. oldClaim: validUpdateClaim,
  774. newClaim: invalidUpdateClaimResources,
  775. },
  776. "invalid-update-change-access-modes-on-bound-claim": {
  777. isExpectedFailure: true,
  778. oldClaim: validUpdateClaim,
  779. newClaim: invalidUpdateClaimAccessModes,
  780. },
  781. }
  782. for name, scenario := range scenarios {
  783. // ensure we have a resource version specified for updates
  784. scenario.oldClaim.ResourceVersion = "1"
  785. scenario.newClaim.ResourceVersion = "1"
  786. errs := ValidatePersistentVolumeClaimUpdate(scenario.newClaim, scenario.oldClaim)
  787. if len(errs) == 0 && scenario.isExpectedFailure {
  788. t.Errorf("Unexpected success for scenario: %s", name)
  789. }
  790. if len(errs) > 0 && !scenario.isExpectedFailure {
  791. t.Errorf("Unexpected failure for scenario: %s - %+v", name, errs)
  792. }
  793. }
  794. }
  795. func TestValidateKeyToPath(t *testing.T) {
  796. testCases := []struct {
  797. kp api.KeyToPath
  798. ok bool
  799. errtype field.ErrorType
  800. }{
  801. {
  802. kp: api.KeyToPath{Key: "k", Path: "p"},
  803. ok: true,
  804. },
  805. {
  806. kp: api.KeyToPath{Key: "k", Path: "p/p/p/p"},
  807. ok: true,
  808. },
  809. {
  810. kp: api.KeyToPath{Key: "k", Path: "p/..p/p../p..p"},
  811. ok: true,
  812. },
  813. {
  814. kp: api.KeyToPath{Key: "k", Path: "p", Mode: newInt32(0644)},
  815. ok: true,
  816. },
  817. {
  818. kp: api.KeyToPath{Key: "", Path: "p"},
  819. ok: false,
  820. errtype: field.ErrorTypeRequired,
  821. },
  822. {
  823. kp: api.KeyToPath{Key: "k", Path: ""},
  824. ok: false,
  825. errtype: field.ErrorTypeRequired,
  826. },
  827. {
  828. kp: api.KeyToPath{Key: "k", Path: "..p"},
  829. ok: false,
  830. errtype: field.ErrorTypeInvalid,
  831. },
  832. {
  833. kp: api.KeyToPath{Key: "k", Path: "../p"},
  834. ok: false,
  835. errtype: field.ErrorTypeInvalid,
  836. },
  837. {
  838. kp: api.KeyToPath{Key: "k", Path: "p/../p"},
  839. ok: false,
  840. errtype: field.ErrorTypeInvalid,
  841. },
  842. {
  843. kp: api.KeyToPath{Key: "k", Path: "p/.."},
  844. ok: false,
  845. errtype: field.ErrorTypeInvalid,
  846. },
  847. {
  848. kp: api.KeyToPath{Key: "k", Path: "p", Mode: newInt32(01000)},
  849. ok: false,
  850. errtype: field.ErrorTypeInvalid,
  851. },
  852. {
  853. kp: api.KeyToPath{Key: "k", Path: "p", Mode: newInt32(-1)},
  854. ok: false,
  855. errtype: field.ErrorTypeInvalid,
  856. },
  857. }
  858. for i, tc := range testCases {
  859. errs := validateKeyToPath(&tc.kp, field.NewPath("field"))
  860. if tc.ok && len(errs) > 0 {
  861. t.Errorf("[%d] unexpected errors: %v", i, errs)
  862. } else if !tc.ok && len(errs) == 0 {
  863. t.Errorf("[%d] expected error type %v", i, tc.errtype)
  864. } else if len(errs) > 1 {
  865. t.Errorf("[%d] expected only one error, got %d", i, len(errs))
  866. } else if !tc.ok {
  867. if errs[0].Type != tc.errtype {
  868. t.Errorf("[%d] expected error type %v, got %v", i, tc.errtype, errs[0].Type)
  869. }
  870. }
  871. }
  872. }
  873. // helper
  874. func newInt32(val int) *int32 {
  875. p := new(int32)
  876. *p = int32(val)
  877. return p
  878. }
  879. // This test is a little too top-to-bottom. Ideally we would test each volume
  880. // type on its own, but we want to also make sure that the logic works through
  881. // the one-of wrapper, so we just do it all in one place.
  882. func TestValidateVolumes(t *testing.T) {
  883. testCases := []struct {
  884. name string
  885. vol api.Volume
  886. errtype field.ErrorType
  887. errfield string
  888. errdetail string
  889. }{
  890. // EmptyDir and basic volume names
  891. {
  892. name: "valid alpha name",
  893. vol: api.Volume{
  894. Name: "empty",
  895. VolumeSource: api.VolumeSource{
  896. EmptyDir: &api.EmptyDirVolumeSource{},
  897. },
  898. },
  899. },
  900. {
  901. name: "valid num name",
  902. vol: api.Volume{
  903. Name: "123",
  904. VolumeSource: api.VolumeSource{
  905. EmptyDir: &api.EmptyDirVolumeSource{},
  906. },
  907. },
  908. },
  909. {
  910. name: "valid alphanum name",
  911. vol: api.Volume{
  912. Name: "empty-123",
  913. VolumeSource: api.VolumeSource{
  914. EmptyDir: &api.EmptyDirVolumeSource{},
  915. },
  916. },
  917. },
  918. {
  919. name: "valid numalpha name",
  920. vol: api.Volume{
  921. Name: "123-empty",
  922. VolumeSource: api.VolumeSource{
  923. EmptyDir: &api.EmptyDirVolumeSource{},
  924. },
  925. },
  926. },
  927. {
  928. name: "zero-length name",
  929. vol: api.Volume{
  930. Name: "",
  931. VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{}},
  932. },
  933. errtype: field.ErrorTypeRequired,
  934. errfield: "name",
  935. },
  936. {
  937. name: "name > 63 characters",
  938. vol: api.Volume{
  939. Name: strings.Repeat("a", 64),
  940. VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{}},
  941. },
  942. errtype: field.ErrorTypeInvalid,
  943. errfield: "name",
  944. errdetail: "must be no more than",
  945. },
  946. {
  947. name: "name not a DNS label",
  948. vol: api.Volume{
  949. Name: "a.b.c",
  950. VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{}},
  951. },
  952. errtype: field.ErrorTypeInvalid,
  953. errfield: "name",
  954. errdetail: "must match the regex",
  955. },
  956. // More than one source field specified.
  957. {
  958. name: "more than one source",
  959. vol: api.Volume{
  960. Name: "dups",
  961. VolumeSource: api.VolumeSource{
  962. EmptyDir: &api.EmptyDirVolumeSource{},
  963. HostPath: &api.HostPathVolumeSource{
  964. Path: "/mnt/path",
  965. },
  966. },
  967. },
  968. errtype: field.ErrorTypeForbidden,
  969. errfield: "hostPath",
  970. errdetail: "may not specify more than 1 volume",
  971. },
  972. // HostPath
  973. {
  974. name: "valid HostPath",
  975. vol: api.Volume{
  976. Name: "hostpath",
  977. VolumeSource: api.VolumeSource{
  978. HostPath: &api.HostPathVolumeSource{
  979. Path: "/mnt/path",
  980. },
  981. },
  982. },
  983. },
  984. // GcePersistentDisk
  985. {
  986. name: "valid GcePersistentDisk",
  987. vol: api.Volume{
  988. Name: "gce-pd",
  989. VolumeSource: api.VolumeSource{
  990. GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{
  991. PDName: "my-PD",
  992. FSType: "ext4",
  993. Partition: 1,
  994. ReadOnly: false,
  995. },
  996. },
  997. },
  998. },
  999. // AWSElasticBlockStore
  1000. {
  1001. name: "valid AWSElasticBlockStore",
  1002. vol: api.Volume{
  1003. Name: "aws-ebs",
  1004. VolumeSource: api.VolumeSource{
  1005. AWSElasticBlockStore: &api.AWSElasticBlockStoreVolumeSource{
  1006. VolumeID: "my-PD",
  1007. FSType: "ext4",
  1008. Partition: 1,
  1009. ReadOnly: false,
  1010. },
  1011. },
  1012. },
  1013. },
  1014. // GitRepo
  1015. {
  1016. name: "valid GitRepo",
  1017. vol: api.Volume{
  1018. Name: "git-repo",
  1019. VolumeSource: api.VolumeSource{
  1020. GitRepo: &api.GitRepoVolumeSource{
  1021. Repository: "my-repo",
  1022. Revision: "hashstring",
  1023. Directory: "target",
  1024. },
  1025. },
  1026. },
  1027. },
  1028. {
  1029. name: "valid GitRepo in .",
  1030. vol: api.Volume{
  1031. Name: "git-repo-dot",
  1032. VolumeSource: api.VolumeSource{
  1033. GitRepo: &api.GitRepoVolumeSource{
  1034. Repository: "my-repo",
  1035. Directory: ".",
  1036. },
  1037. },
  1038. },
  1039. },
  1040. {
  1041. name: "valid GitRepo with .. in name",
  1042. vol: api.Volume{
  1043. Name: "git-repo-dot-dot-foo",
  1044. VolumeSource: api.VolumeSource{
  1045. GitRepo: &api.GitRepoVolumeSource{
  1046. Repository: "my-repo",
  1047. Directory: "..foo",
  1048. },
  1049. },
  1050. },
  1051. },
  1052. {
  1053. name: "GitRepo starts with ../",
  1054. vol: api.Volume{
  1055. Name: "gitrepo",
  1056. VolumeSource: api.VolumeSource{
  1057. GitRepo: &api.GitRepoVolumeSource{
  1058. Repository: "foo",
  1059. Directory: "../dots/bar",
  1060. },
  1061. },
  1062. },
  1063. errtype: field.ErrorTypeInvalid,
  1064. errfield: "gitRepo.directory",
  1065. errdetail: `must not contain '..'`,
  1066. },
  1067. {
  1068. name: "GitRepo contains ..",
  1069. vol: api.Volume{
  1070. Name: "gitrepo",
  1071. VolumeSource: api.VolumeSource{
  1072. GitRepo: &api.GitRepoVolumeSource{
  1073. Repository: "foo",
  1074. Directory: "dots/../bar",
  1075. },
  1076. },
  1077. },
  1078. errtype: field.ErrorTypeInvalid,
  1079. errfield: "gitRepo.directory",
  1080. errdetail: `must not contain '..'`,
  1081. },
  1082. {
  1083. name: "GitRepo absolute target",
  1084. vol: api.Volume{
  1085. Name: "gitrepo",
  1086. VolumeSource: api.VolumeSource{
  1087. GitRepo: &api.GitRepoVolumeSource{
  1088. Repository: "foo",
  1089. Directory: "/abstarget",
  1090. },
  1091. },
  1092. },
  1093. errtype: field.ErrorTypeInvalid,
  1094. errfield: "gitRepo.directory",
  1095. },
  1096. // ISCSI
  1097. {
  1098. name: "valid ISCSI",
  1099. vol: api.Volume{
  1100. Name: "iscsi",
  1101. VolumeSource: api.VolumeSource{
  1102. ISCSI: &api.ISCSIVolumeSource{
  1103. TargetPortal: "127.0.0.1",
  1104. IQN: "iqn.2015-02.example.com:test",
  1105. Lun: 1,
  1106. FSType: "ext4",
  1107. ReadOnly: false,
  1108. },
  1109. },
  1110. },
  1111. },
  1112. {
  1113. name: "empty portal",
  1114. vol: api.Volume{
  1115. Name: "iscsi",
  1116. VolumeSource: api.VolumeSource{
  1117. ISCSI: &api.ISCSIVolumeSource{
  1118. TargetPortal: "",
  1119. IQN: "iqn.2015-02.example.com:test",
  1120. Lun: 1,
  1121. FSType: "ext4",
  1122. ReadOnly: false,
  1123. },
  1124. },
  1125. },
  1126. errtype: field.ErrorTypeRequired,
  1127. errfield: "iscsi.targetPortal",
  1128. },
  1129. {
  1130. name: "empty iqn",
  1131. vol: api.Volume{
  1132. Name: "iscsi",
  1133. VolumeSource: api.VolumeSource{
  1134. ISCSI: &api.ISCSIVolumeSource{
  1135. TargetPortal: "127.0.0.1",
  1136. IQN: "",
  1137. Lun: 1,
  1138. FSType: "ext4",
  1139. ReadOnly: false,
  1140. },
  1141. },
  1142. },
  1143. errtype: field.ErrorTypeRequired,
  1144. errfield: "iscsi.iqn",
  1145. },
  1146. // Secret
  1147. {
  1148. name: "valid Secret",
  1149. vol: api.Volume{
  1150. Name: "secret",
  1151. VolumeSource: api.VolumeSource{
  1152. Secret: &api.SecretVolumeSource{
  1153. SecretName: "my-secret",
  1154. },
  1155. },
  1156. },
  1157. },
  1158. {
  1159. name: "valid Secret with defaultMode",
  1160. vol: api.Volume{
  1161. Name: "secret",
  1162. VolumeSource: api.VolumeSource{
  1163. Secret: &api.SecretVolumeSource{
  1164. SecretName: "my-secret",
  1165. DefaultMode: newInt32(0644),
  1166. },
  1167. },
  1168. },
  1169. },
  1170. {
  1171. name: "valid Secret with projection and mode",
  1172. vol: api.Volume{
  1173. Name: "secret",
  1174. VolumeSource: api.VolumeSource{
  1175. Secret: &api.SecretVolumeSource{
  1176. SecretName: "my-secret",
  1177. Items: []api.KeyToPath{{
  1178. Key: "key",
  1179. Path: "filename",
  1180. Mode: newInt32(0644),
  1181. }},
  1182. },
  1183. },
  1184. },
  1185. },
  1186. {
  1187. name: "valid Secret with subdir projection",
  1188. vol: api.Volume{
  1189. Name: "secret",
  1190. VolumeSource: api.VolumeSource{
  1191. Secret: &api.SecretVolumeSource{
  1192. SecretName: "my-secret",
  1193. Items: []api.KeyToPath{{
  1194. Key: "key",
  1195. Path: "dir/filename",
  1196. }},
  1197. },
  1198. },
  1199. },
  1200. },
  1201. {
  1202. name: "secret with missing path",
  1203. vol: api.Volume{
  1204. Name: "secret",
  1205. VolumeSource: api.VolumeSource{
  1206. Secret: &api.SecretVolumeSource{
  1207. SecretName: "s",
  1208. Items: []api.KeyToPath{{Key: "key", Path: ""}},
  1209. },
  1210. },
  1211. },
  1212. errtype: field.ErrorTypeRequired,
  1213. errfield: "secret.items[0].path",
  1214. },
  1215. {
  1216. name: "secret with leading ..",
  1217. vol: api.Volume{
  1218. Name: "secret",
  1219. VolumeSource: api.VolumeSource{
  1220. Secret: &api.SecretVolumeSource{
  1221. SecretName: "s",
  1222. Items: []api.KeyToPath{{Key: "key", Path: "../foo"}},
  1223. },
  1224. },
  1225. },
  1226. errtype: field.ErrorTypeInvalid,
  1227. errfield: "secret.items[0].path",
  1228. },
  1229. {
  1230. name: "secret with .. inside",
  1231. vol: api.Volume{
  1232. Name: "secret",
  1233. VolumeSource: api.VolumeSource{
  1234. Secret: &api.SecretVolumeSource{
  1235. SecretName: "s",
  1236. Items: []api.KeyToPath{{Key: "key", Path: "foo/../bar"}},
  1237. },
  1238. },
  1239. },
  1240. errtype: field.ErrorTypeInvalid,
  1241. errfield: "secret.items[0].path",
  1242. },
  1243. {
  1244. name: "secret with invalid positive defaultMode",
  1245. vol: api.Volume{
  1246. Name: "secret",
  1247. VolumeSource: api.VolumeSource{
  1248. Secret: &api.SecretVolumeSource{
  1249. SecretName: "s",
  1250. DefaultMode: newInt32(01000),
  1251. },
  1252. },
  1253. },
  1254. errtype: field.ErrorTypeInvalid,
  1255. errfield: "secret.defaultMode",
  1256. },
  1257. {
  1258. name: "secret with invalid negative defaultMode",
  1259. vol: api.Volume{
  1260. Name: "secret",
  1261. VolumeSource: api.VolumeSource{
  1262. Secret: &api.SecretVolumeSource{
  1263. SecretName: "s",
  1264. DefaultMode: newInt32(-1),
  1265. },
  1266. },
  1267. },
  1268. errtype: field.ErrorTypeInvalid,
  1269. errfield: "secret.defaultMode",
  1270. },
  1271. // ConfigMap
  1272. {
  1273. name: "valid ConfigMap",
  1274. vol: api.Volume{
  1275. Name: "cfgmap",
  1276. VolumeSource: api.VolumeSource{
  1277. ConfigMap: &api.ConfigMapVolumeSource{
  1278. LocalObjectReference: api.LocalObjectReference{
  1279. Name: "my-cfgmap",
  1280. },
  1281. },
  1282. },
  1283. },
  1284. },
  1285. {
  1286. name: "valid ConfigMap with defaultMode",
  1287. vol: api.Volume{
  1288. Name: "cfgmap",
  1289. VolumeSource: api.VolumeSource{
  1290. ConfigMap: &api.ConfigMapVolumeSource{
  1291. LocalObjectReference: api.LocalObjectReference{
  1292. Name: "my-cfgmap",
  1293. },
  1294. DefaultMode: newInt32(0644),
  1295. },
  1296. },
  1297. },
  1298. },
  1299. {
  1300. name: "valid ConfigMap with projection and mode",
  1301. vol: api.Volume{
  1302. Name: "cfgmap",
  1303. VolumeSource: api.VolumeSource{
  1304. ConfigMap: &api.ConfigMapVolumeSource{
  1305. LocalObjectReference: api.LocalObjectReference{
  1306. Name: "my-cfgmap"},
  1307. Items: []api.KeyToPath{{
  1308. Key: "key",
  1309. Path: "filename",
  1310. Mode: newInt32(0644),
  1311. }},
  1312. },
  1313. },
  1314. },
  1315. },
  1316. {
  1317. name: "valid ConfigMap with subdir projection",
  1318. vol: api.Volume{
  1319. Name: "cfgmap",
  1320. VolumeSource: api.VolumeSource{
  1321. ConfigMap: &api.ConfigMapVolumeSource{
  1322. LocalObjectReference: api.LocalObjectReference{
  1323. Name: "my-cfgmap"},
  1324. Items: []api.KeyToPath{{
  1325. Key: "key",
  1326. Path: "dir/filename",
  1327. }},
  1328. },
  1329. },
  1330. },
  1331. },
  1332. {
  1333. name: "configmap with missing path",
  1334. vol: api.Volume{
  1335. Name: "cfgmap",
  1336. VolumeSource: api.VolumeSource{
  1337. ConfigMap: &api.ConfigMapVolumeSource{
  1338. LocalObjectReference: api.LocalObjectReference{Name: "c"},
  1339. Items: []api.KeyToPath{{Key: "key", Path: ""}},
  1340. },
  1341. },
  1342. },
  1343. errtype: field.ErrorTypeRequired,
  1344. errfield: "configMap.items[0].path",
  1345. },
  1346. {
  1347. name: "configmap with leading ..",
  1348. vol: api.Volume{
  1349. Name: "cfgmap",
  1350. VolumeSource: api.VolumeSource{
  1351. ConfigMap: &api.ConfigMapVolumeSource{
  1352. LocalObjectReference: api.LocalObjectReference{Name: "c"},
  1353. Items: []api.KeyToPath{{Key: "key", Path: "../foo"}},
  1354. },
  1355. },
  1356. },
  1357. errtype: field.ErrorTypeInvalid,
  1358. errfield: "configMap.items[0].path",
  1359. },
  1360. {
  1361. name: "configmap with .. inside",
  1362. vol: api.Volume{
  1363. Name: "cfgmap",
  1364. VolumeSource: api.VolumeSource{
  1365. ConfigMap: &api.ConfigMapVolumeSource{
  1366. LocalObjectReference: api.LocalObjectReference{Name: "c"},
  1367. Items: []api.KeyToPath{{Key: "key", Path: "foo/../bar"}},
  1368. },
  1369. },
  1370. },
  1371. errtype: field.ErrorTypeInvalid,
  1372. errfield: "configMap.items[0].path",
  1373. },
  1374. {
  1375. name: "configmap with invalid positive defaultMode",
  1376. vol: api.Volume{
  1377. Name: "cfgmap",
  1378. VolumeSource: api.VolumeSource{
  1379. ConfigMap: &api.ConfigMapVolumeSource{
  1380. LocalObjectReference: api.LocalObjectReference{Name: "c"},
  1381. DefaultMode: newInt32(01000),
  1382. },
  1383. },
  1384. },
  1385. errtype: field.ErrorTypeInvalid,
  1386. errfield: "configMap.defaultMode",
  1387. },
  1388. {
  1389. name: "configmap with invalid negative defaultMode",
  1390. vol: api.Volume{
  1391. Name: "cfgmap",
  1392. VolumeSource: api.VolumeSource{
  1393. ConfigMap: &api.ConfigMapVolumeSource{
  1394. LocalObjectReference: api.LocalObjectReference{Name: "c"},
  1395. DefaultMode: newInt32(-1),
  1396. },
  1397. },
  1398. },
  1399. errtype: field.ErrorTypeInvalid,
  1400. errfield: "configMap.defaultMode",
  1401. },
  1402. // Glusterfs
  1403. {
  1404. name: "valid Glusterfs",
  1405. vol: api.Volume{
  1406. Name: "glusterfs",
  1407. VolumeSource: api.VolumeSource{
  1408. Glusterfs: &api.GlusterfsVolumeSource{
  1409. EndpointsName: "host1",
  1410. Path: "path",
  1411. ReadOnly: false,
  1412. },
  1413. },
  1414. },
  1415. },
  1416. {
  1417. name: "empty hosts",
  1418. vol: api.Volume{
  1419. Name: "glusterfs",
  1420. VolumeSource: api.VolumeSource{
  1421. Glusterfs: &api.GlusterfsVolumeSource{
  1422. EndpointsName: "",
  1423. Path: "path",
  1424. ReadOnly: false,
  1425. },
  1426. },
  1427. },
  1428. errtype: field.ErrorTypeRequired,
  1429. errfield: "glusterfs.endpoints",
  1430. },
  1431. {
  1432. name: "empty path",
  1433. vol: api.Volume{
  1434. Name: "glusterfs",
  1435. VolumeSource: api.VolumeSource{
  1436. Glusterfs: &api.GlusterfsVolumeSource{
  1437. EndpointsName: "host",
  1438. Path: "",
  1439. ReadOnly: false,
  1440. },
  1441. },
  1442. },
  1443. errtype: field.ErrorTypeRequired,
  1444. errfield: "glusterfs.path",
  1445. },
  1446. // Flocker
  1447. {
  1448. name: "valid Flocker",
  1449. vol: api.Volume{
  1450. Name: "flocker",
  1451. VolumeSource: api.VolumeSource{
  1452. Flocker: &api.FlockerVolumeSource{
  1453. DatasetName: "datasetName",
  1454. },
  1455. },
  1456. },
  1457. },
  1458. {
  1459. name: "empty flocker datasetName",
  1460. vol: api.Volume{
  1461. Name: "flocker",
  1462. VolumeSource: api.VolumeSource{
  1463. Flocker: &api.FlockerVolumeSource{
  1464. DatasetName: "",
  1465. },
  1466. },
  1467. },
  1468. errtype: field.ErrorTypeRequired,
  1469. errfield: "flocker.datasetName",
  1470. },
  1471. {
  1472. name: "slash in flocker datasetName",
  1473. vol: api.Volume{
  1474. Name: "flocker",
  1475. VolumeSource: api.VolumeSource{
  1476. Flocker: &api.FlockerVolumeSource{
  1477. DatasetName: "foo/bar",
  1478. },
  1479. },
  1480. },
  1481. errtype: field.ErrorTypeInvalid,
  1482. errfield: "flocker.datasetName",
  1483. errdetail: "must not contain '/'",
  1484. },
  1485. // RBD
  1486. {
  1487. name: "valid RBD",
  1488. vol: api.Volume{
  1489. Name: "rbd",
  1490. VolumeSource: api.VolumeSource{
  1491. RBD: &api.RBDVolumeSource{
  1492. CephMonitors: []string{"foo"},
  1493. RBDImage: "bar",
  1494. FSType: "ext4",
  1495. },
  1496. },
  1497. },
  1498. },
  1499. {
  1500. name: "empty rbd monitors",
  1501. vol: api.Volume{
  1502. Name: "rbd",
  1503. VolumeSource: api.VolumeSource{
  1504. RBD: &api.RBDVolumeSource{
  1505. CephMonitors: []string{},
  1506. RBDImage: "bar",
  1507. FSType: "ext4",
  1508. },
  1509. },
  1510. },
  1511. errtype: field.ErrorTypeRequired,
  1512. errfield: "rbd.monitors",
  1513. },
  1514. {
  1515. name: "empty image",
  1516. vol: api.Volume{
  1517. Name: "rbd",
  1518. VolumeSource: api.VolumeSource{
  1519. RBD: &api.RBDVolumeSource{
  1520. CephMonitors: []string{"foo"},
  1521. RBDImage: "",
  1522. FSType: "ext4",
  1523. },
  1524. },
  1525. },
  1526. errtype: field.ErrorTypeRequired,
  1527. errfield: "rbd.image",
  1528. },
  1529. // Cinder
  1530. {
  1531. name: "valid Cinder",
  1532. vol: api.Volume{
  1533. Name: "cinder",
  1534. VolumeSource: api.VolumeSource{
  1535. Cinder: &api.CinderVolumeSource{
  1536. VolumeID: "29ea5088-4f60-4757-962e-dba678767887",
  1537. FSType: "ext4",
  1538. ReadOnly: false,
  1539. },
  1540. },
  1541. },
  1542. },
  1543. // CephFS
  1544. {
  1545. name: "valid CephFS",
  1546. vol: api.Volume{
  1547. Name: "cephfs",
  1548. VolumeSource: api.VolumeSource{
  1549. CephFS: &api.CephFSVolumeSource{
  1550. Monitors: []string{"foo"},
  1551. },
  1552. },
  1553. },
  1554. },
  1555. {
  1556. name: "empty cephfs monitors",
  1557. vol: api.Volume{
  1558. Name: "cephfs",
  1559. VolumeSource: api.VolumeSource{
  1560. CephFS: &api.CephFSVolumeSource{
  1561. Monitors: []string{},
  1562. },
  1563. },
  1564. },
  1565. errtype: field.ErrorTypeRequired,
  1566. errfield: "cephfs.monitors",
  1567. },
  1568. // DownwardAPI
  1569. {
  1570. name: "valid DownwardAPI",
  1571. vol: api.Volume{
  1572. Name: "downwardapi",
  1573. VolumeSource: api.VolumeSource{
  1574. DownwardAPI: &api.DownwardAPIVolumeSource{
  1575. Items: []api.DownwardAPIVolumeFile{
  1576. {
  1577. Path: "labels",
  1578. FieldRef: &api.ObjectFieldSelector{
  1579. APIVersion: "v1",
  1580. FieldPath: "metadata.labels",
  1581. },
  1582. },
  1583. {
  1584. Path: "annotations",
  1585. FieldRef: &api.ObjectFieldSelector{
  1586. APIVersion: "v1",
  1587. FieldPath: "metadata.annotations",
  1588. },
  1589. },
  1590. {
  1591. Path: "namespace",
  1592. FieldRef: &api.ObjectFieldSelector{
  1593. APIVersion: "v1",
  1594. FieldPath: "metadata.namespace",
  1595. },
  1596. },
  1597. {
  1598. Path: "name",
  1599. FieldRef: &api.ObjectFieldSelector{
  1600. APIVersion: "v1",
  1601. FieldPath: "metadata.name",
  1602. },
  1603. },
  1604. {
  1605. Path: "path/with/subdirs",
  1606. FieldRef: &api.ObjectFieldSelector{
  1607. APIVersion: "v1",
  1608. FieldPath: "metadata.labels",
  1609. },
  1610. },
  1611. {
  1612. Path: "path/./withdot",
  1613. FieldRef: &api.ObjectFieldSelector{
  1614. APIVersion: "v1",
  1615. FieldPath: "metadata.labels",
  1616. },
  1617. },
  1618. {
  1619. Path: "path/with/embedded..dotdot",
  1620. FieldRef: &api.ObjectFieldSelector{
  1621. APIVersion: "v1",
  1622. FieldPath: "metadata.labels",
  1623. },
  1624. },
  1625. {
  1626. Path: "path/with/leading/..dotdot",
  1627. FieldRef: &api.ObjectFieldSelector{
  1628. APIVersion: "v1",
  1629. FieldPath: "metadata.labels",
  1630. },
  1631. },
  1632. {
  1633. Path: "cpu_limit",
  1634. ResourceFieldRef: &api.ResourceFieldSelector{
  1635. ContainerName: "test-container",
  1636. Resource: "limits.cpu",
  1637. },
  1638. },
  1639. {
  1640. Path: "cpu_request",
  1641. ResourceFieldRef: &api.ResourceFieldSelector{
  1642. ContainerName: "test-container",
  1643. Resource: "requests.cpu",
  1644. },
  1645. },
  1646. {
  1647. Path: "memory_limit",
  1648. ResourceFieldRef: &api.ResourceFieldSelector{
  1649. ContainerName: "test-container",
  1650. Resource: "limits.memory",
  1651. },
  1652. },
  1653. {
  1654. Path: "memory_request",
  1655. ResourceFieldRef: &api.ResourceFieldSelector{
  1656. ContainerName: "test-container",
  1657. Resource: "requests.memory",
  1658. },
  1659. },
  1660. },
  1661. },
  1662. },
  1663. },
  1664. },
  1665. {
  1666. name: "downapi valid defaultMode",
  1667. vol: api.Volume{
  1668. Name: "downapi",
  1669. VolumeSource: api.VolumeSource{
  1670. DownwardAPI: &api.DownwardAPIVolumeSource{
  1671. DefaultMode: newInt32(0644),
  1672. },
  1673. },
  1674. },
  1675. },
  1676. {
  1677. name: "downapi valid item mode",
  1678. vol: api.Volume{
  1679. Name: "downapi",
  1680. VolumeSource: api.VolumeSource{
  1681. DownwardAPI: &api.DownwardAPIVolumeSource{
  1682. Items: []api.DownwardAPIVolumeFile{{
  1683. Mode: newInt32(0644),
  1684. Path: "path",
  1685. FieldRef: &api.ObjectFieldSelector{
  1686. APIVersion: "v1",
  1687. FieldPath: "metadata.labels",
  1688. },
  1689. }},
  1690. },
  1691. },
  1692. },
  1693. },
  1694. {
  1695. name: "downapi invalid positive item mode",
  1696. vol: api.Volume{
  1697. Name: "downapi",
  1698. VolumeSource: api.VolumeSource{
  1699. DownwardAPI: &api.DownwardAPIVolumeSource{
  1700. Items: []api.DownwardAPIVolumeFile{{
  1701. Mode: newInt32(01000),
  1702. Path: "path",
  1703. FieldRef: &api.ObjectFieldSelector{
  1704. APIVersion: "v1",
  1705. FieldPath: "metadata.labels",
  1706. },
  1707. }},
  1708. },
  1709. },
  1710. },
  1711. errtype: field.ErrorTypeInvalid,
  1712. errfield: "downwardAPI.mode",
  1713. },
  1714. {
  1715. name: "downapi invalid negative item mode",
  1716. vol: api.Volume{
  1717. Name: "downapi",
  1718. VolumeSource: api.VolumeSource{
  1719. DownwardAPI: &api.DownwardAPIVolumeSource{
  1720. Items: []api.DownwardAPIVolumeFile{{
  1721. Mode: newInt32(-1),
  1722. Path: "path",
  1723. FieldRef: &api.ObjectFieldSelector{
  1724. APIVersion: "v1",
  1725. FieldPath: "metadata.labels",
  1726. },
  1727. }},
  1728. },
  1729. },
  1730. },
  1731. errtype: field.ErrorTypeInvalid,
  1732. errfield: "downwardAPI.mode",
  1733. },
  1734. {
  1735. name: "downapi empty metatada path",
  1736. vol: api.Volume{
  1737. Name: "downapi",
  1738. VolumeSource: api.VolumeSource{
  1739. DownwardAPI: &api.DownwardAPIVolumeSource{
  1740. Items: []api.DownwardAPIVolumeFile{{
  1741. Path: "",
  1742. FieldRef: &api.ObjectFieldSelector{
  1743. APIVersion: "v1",
  1744. FieldPath: "metadata.labels",
  1745. },
  1746. }},
  1747. },
  1748. },
  1749. },
  1750. errtype: field.ErrorTypeRequired,
  1751. errfield: "downwardAPI.path",
  1752. },
  1753. {
  1754. name: "downapi absolute path",
  1755. vol: api.Volume{
  1756. Name: "downapi",
  1757. VolumeSource: api.VolumeSource{
  1758. DownwardAPI: &api.DownwardAPIVolumeSource{
  1759. Items: []api.DownwardAPIVolumeFile{{
  1760. Path: "/absolutepath",
  1761. FieldRef: &api.ObjectFieldSelector{
  1762. APIVersion: "v1",
  1763. FieldPath: "metadata.labels",
  1764. },
  1765. }},
  1766. },
  1767. },
  1768. },
  1769. errtype: field.ErrorTypeInvalid,
  1770. errfield: "downwardAPI.path",
  1771. },
  1772. {
  1773. name: "downapi dot dot path",
  1774. vol: api.Volume{
  1775. Name: "downapi",
  1776. VolumeSource: api.VolumeSource{
  1777. DownwardAPI: &api.DownwardAPIVolumeSource{
  1778. Items: []api.DownwardAPIVolumeFile{{
  1779. Path: "../../passwd",
  1780. FieldRef: &api.ObjectFieldSelector{
  1781. APIVersion: "v1",
  1782. FieldPath: "metadata.labels",
  1783. },
  1784. }},
  1785. },
  1786. },
  1787. },
  1788. errtype: field.ErrorTypeInvalid,
  1789. errfield: "downwardAPI.path",
  1790. errdetail: `must not contain '..'`,
  1791. },
  1792. {
  1793. name: "downapi dot dot file name",
  1794. vol: api.Volume{
  1795. Name: "downapi",
  1796. VolumeSource: api.VolumeSource{
  1797. DownwardAPI: &api.DownwardAPIVolumeSource{
  1798. Items: []api.DownwardAPIVolumeFile{{
  1799. Path: "..badFileName",
  1800. FieldRef: &api.ObjectFieldSelector{
  1801. APIVersion: "v1",
  1802. FieldPath: "metadata.labels",
  1803. },
  1804. }},
  1805. },
  1806. },
  1807. },
  1808. errtype: field.ErrorTypeInvalid,
  1809. errfield: "downwardAPI.path",
  1810. errdetail: `must not start with '..'`,
  1811. },
  1812. {
  1813. name: "downapi dot dot first level dirent",
  1814. vol: api.Volume{
  1815. Name: "downapi",
  1816. VolumeSource: api.VolumeSource{
  1817. DownwardAPI: &api.DownwardAPIVolumeSource{
  1818. Items: []api.DownwardAPIVolumeFile{{
  1819. Path: "..badDirName/goodFileName",
  1820. FieldRef: &api.ObjectFieldSelector{
  1821. APIVersion: "v1",
  1822. FieldPath: "metadata.labels",
  1823. },
  1824. }},
  1825. },
  1826. },
  1827. },
  1828. errtype: field.ErrorTypeInvalid,
  1829. errfield: "downwardAPI.path",
  1830. errdetail: `must not start with '..'`,
  1831. },
  1832. {
  1833. name: "downapi fieldRef and ResourceFieldRef together",
  1834. vol: api.Volume{
  1835. Name: "downapi",
  1836. VolumeSource: api.VolumeSource{
  1837. DownwardAPI: &api.DownwardAPIVolumeSource{
  1838. Items: []api.DownwardAPIVolumeFile{{
  1839. Path: "test",
  1840. FieldRef: &api.ObjectFieldSelector{
  1841. APIVersion: "v1",
  1842. FieldPath: "metadata.labels",
  1843. },
  1844. ResourceFieldRef: &api.ResourceFieldSelector{
  1845. ContainerName: "test-container",
  1846. Resource: "requests.memory",
  1847. },
  1848. }},
  1849. },
  1850. },
  1851. },
  1852. errtype: field.ErrorTypeInvalid,
  1853. errfield: "downwardAPI",
  1854. errdetail: "fieldRef and resourceFieldRef can not be specified simultaneously",
  1855. },
  1856. {
  1857. name: "downapi invalid positive defaultMode",
  1858. vol: api.Volume{
  1859. Name: "downapi",
  1860. VolumeSource: api.VolumeSource{
  1861. DownwardAPI: &api.DownwardAPIVolumeSource{
  1862. DefaultMode: newInt32(01000),
  1863. },
  1864. },
  1865. },
  1866. errtype: field.ErrorTypeInvalid,
  1867. errfield: "downwardAPI.defaultMode",
  1868. },
  1869. {
  1870. name: "downapi invalid negative defaultMode",
  1871. vol: api.Volume{
  1872. Name: "downapi",
  1873. VolumeSource: api.VolumeSource{
  1874. DownwardAPI: &api.DownwardAPIVolumeSource{
  1875. DefaultMode: newInt32(-1),
  1876. },
  1877. },
  1878. },
  1879. errtype: field.ErrorTypeInvalid,
  1880. errfield: "downwardAPI.defaultMode",
  1881. },
  1882. // FC
  1883. {
  1884. name: "valid FC",
  1885. vol: api.Volume{
  1886. Name: "fc",
  1887. VolumeSource: api.VolumeSource{
  1888. FC: &api.FCVolumeSource{
  1889. TargetWWNs: []string{"some_wwn"},
  1890. Lun: newInt32(1),
  1891. FSType: "ext4",
  1892. ReadOnly: false,
  1893. },
  1894. },
  1895. },
  1896. },
  1897. {
  1898. name: "fc empty wwn",
  1899. vol: api.Volume{
  1900. Name: "fc",
  1901. VolumeSource: api.VolumeSource{
  1902. FC: &api.FCVolumeSource{
  1903. TargetWWNs: []string{},
  1904. Lun: newInt32(1),
  1905. FSType: "ext4",
  1906. ReadOnly: false,
  1907. },
  1908. },
  1909. },
  1910. errtype: field.ErrorTypeRequired,
  1911. errfield: "fc.targetWWNs",
  1912. },
  1913. {
  1914. name: "fc empty lun",
  1915. vol: api.Volume{
  1916. Name: "fc",
  1917. VolumeSource: api.VolumeSource{
  1918. FC: &api.FCVolumeSource{
  1919. TargetWWNs: []string{"wwn"},
  1920. Lun: nil,
  1921. FSType: "ext4",
  1922. ReadOnly: false,
  1923. },
  1924. },
  1925. },
  1926. errtype: field.ErrorTypeRequired,
  1927. errfield: "fc.lun",
  1928. },
  1929. // FlexVolume
  1930. {
  1931. name: "valid FlexVolume",
  1932. vol: api.Volume{
  1933. Name: "flex-volume",
  1934. VolumeSource: api.VolumeSource{
  1935. FlexVolume: &api.FlexVolumeSource{
  1936. Driver: "kubernetes.io/blue",
  1937. FSType: "ext4",
  1938. },
  1939. },
  1940. },
  1941. },
  1942. // AzureFile
  1943. {
  1944. name: "valid AzureFile",
  1945. vol: api.Volume{
  1946. Name: "azure-file",
  1947. VolumeSource: api.VolumeSource{
  1948. AzureFile: &api.AzureFileVolumeSource{
  1949. SecretName: "key",
  1950. ShareName: "share",
  1951. ReadOnly: false,
  1952. },
  1953. },
  1954. },
  1955. },
  1956. {
  1957. name: "AzureFile empty secret",
  1958. vol: api.Volume{
  1959. Name: "azure-file",
  1960. VolumeSource: api.VolumeSource{
  1961. AzureFile: &api.AzureFileVolumeSource{
  1962. SecretName: "",
  1963. ShareName: "share",
  1964. ReadOnly: false,
  1965. },
  1966. },
  1967. },
  1968. errtype: field.ErrorTypeRequired,
  1969. errfield: "azureFile.secretName",
  1970. },
  1971. {
  1972. name: "AzureFile empty share",
  1973. vol: api.Volume{
  1974. Name: "azure-file",
  1975. VolumeSource: api.VolumeSource{
  1976. AzureFile: &api.AzureFileVolumeSource{
  1977. SecretName: "name",
  1978. ShareName: "",
  1979. ReadOnly: false,
  1980. },
  1981. },
  1982. },
  1983. errtype: field.ErrorTypeRequired,
  1984. errfield: "azureFile.shareName",
  1985. },
  1986. // Quobyte
  1987. {
  1988. name: "valid Quobyte",
  1989. vol: api.Volume{
  1990. Name: "quobyte",
  1991. VolumeSource: api.VolumeSource{
  1992. Quobyte: &api.QuobyteVolumeSource{
  1993. Registry: "registry:7861",
  1994. Volume: "volume",
  1995. ReadOnly: false,
  1996. User: "root",
  1997. Group: "root",
  1998. },
  1999. },
  2000. },
  2001. },
  2002. {
  2003. name: "empty registry quobyte",
  2004. vol: api.Volume{
  2005. Name: "quobyte",
  2006. VolumeSource: api.VolumeSource{
  2007. Quobyte: &api.QuobyteVolumeSource{
  2008. Volume: "/test",
  2009. },
  2010. },
  2011. },
  2012. errtype: field.ErrorTypeRequired,
  2013. errfield: "quobyte.registry",
  2014. },
  2015. {
  2016. name: "wrong format registry quobyte",
  2017. vol: api.Volume{
  2018. Name: "quobyte",
  2019. VolumeSource: api.VolumeSource{
  2020. Quobyte: &api.QuobyteVolumeSource{
  2021. Registry: "registry7861",
  2022. Volume: "/test",
  2023. },
  2024. },
  2025. },
  2026. errtype: field.ErrorTypeInvalid,
  2027. errfield: "quobyte.registry",
  2028. },
  2029. {
  2030. name: "wrong format multiple registries quobyte",
  2031. vol: api.Volume{
  2032. Name: "quobyte",
  2033. VolumeSource: api.VolumeSource{
  2034. Quobyte: &api.QuobyteVolumeSource{
  2035. Registry: "registry:7861,reg2",
  2036. Volume: "/test",
  2037. },
  2038. },
  2039. },
  2040. errtype: field.ErrorTypeInvalid,
  2041. errfield: "quobyte.registry",
  2042. },
  2043. {
  2044. name: "empty volume quobyte",
  2045. vol: api.Volume{
  2046. Name: "quobyte",
  2047. VolumeSource: api.VolumeSource{
  2048. Quobyte: &api.QuobyteVolumeSource{
  2049. Registry: "registry:7861",
  2050. },
  2051. },
  2052. },
  2053. errtype: field.ErrorTypeRequired,
  2054. errfield: "quobyte.volume",
  2055. },
  2056. // AzureDisk
  2057. {
  2058. name: "valid AzureDisk",
  2059. vol: api.Volume{
  2060. Name: "azure-disk",
  2061. VolumeSource: api.VolumeSource{
  2062. AzureDisk: &api.AzureDiskVolumeSource{
  2063. DiskName: "foo",
  2064. DataDiskURI: "https://blob/vhds/bar.vhd",
  2065. },
  2066. },
  2067. },
  2068. },
  2069. {
  2070. name: "AzureDisk empty disk name",
  2071. vol: api.Volume{
  2072. Name: "azure-disk",
  2073. VolumeSource: api.VolumeSource{
  2074. AzureDisk: &api.AzureDiskVolumeSource{
  2075. DiskName: "",
  2076. DataDiskURI: "https://blob/vhds/bar.vhd",
  2077. },
  2078. },
  2079. },
  2080. errtype: field.ErrorTypeRequired,
  2081. errfield: "azureDisk.diskName",
  2082. },
  2083. {
  2084. name: "AzureDisk empty disk uri",
  2085. vol: api.Volume{
  2086. Name: "azure-disk",
  2087. VolumeSource: api.VolumeSource{
  2088. AzureDisk: &api.AzureDiskVolumeSource{
  2089. DiskName: "foo",
  2090. DataDiskURI: "",
  2091. },
  2092. },
  2093. },
  2094. errtype: field.ErrorTypeRequired,
  2095. errfield: "azureDisk.diskURI",
  2096. },
  2097. }
  2098. for i, tc := range testCases {
  2099. names, errs := validateVolumes([]api.Volume{tc.vol}, field.NewPath("field"))
  2100. if len(errs) > 0 && tc.errtype == "" {
  2101. t.Errorf("[%d: %q] unexpected error(s): %v", i, tc.name, errs)
  2102. } else if len(errs) > 1 {
  2103. t.Errorf("[%d: %q] expected 1 error, got %d: %v", i, tc.name, len(errs), errs)
  2104. } else if len(errs) == 0 && tc.errtype != "" {
  2105. t.Errorf("[%d: %q] expected error type %v", i, tc.name, tc.errtype)
  2106. } else if len(errs) == 1 {
  2107. if errs[0].Type != tc.errtype {
  2108. t.Errorf("[%d: %q] expected error type %v, got %v", i, tc.name, tc.errtype, errs[0].Type)
  2109. } else if !strings.HasSuffix(errs[0].Field, "."+tc.errfield) {
  2110. t.Errorf("[%d: %q] expected error on field %q, got %q", i, tc.name, tc.errfield, errs[0].Field)
  2111. } else if !strings.Contains(errs[0].Detail, tc.errdetail) {
  2112. t.Errorf("[%d: %q] expected error detail %q, got %q", i, tc.name, tc.errdetail, errs[0].Detail)
  2113. }
  2114. } else {
  2115. if len(names) != 1 || !names.Has(tc.vol.Name) {
  2116. t.Errorf("[%d: %q] wrong names result: %v", i, tc.name, names)
  2117. }
  2118. }
  2119. }
  2120. dupsCase := []api.Volume{
  2121. {Name: "abc", VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{}}},
  2122. {Name: "abc", VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{}}},
  2123. }
  2124. _, errs := validateVolumes(dupsCase, field.NewPath("field"))
  2125. if len(errs) == 0 {
  2126. t.Errorf("expected error")
  2127. } else if len(errs) != 1 {
  2128. t.Errorf("expected 1 error, got %d: %v", len(errs), errs)
  2129. } else if errs[0].Type != field.ErrorTypeDuplicate {
  2130. t.Errorf("expected error type %v, got %v", field.ErrorTypeDuplicate, errs[0].Type)
  2131. }
  2132. }
  2133. func TestValidatePorts(t *testing.T) {
  2134. successCase := []api.ContainerPort{
  2135. {Name: "abc", ContainerPort: 80, HostPort: 80, Protocol: "TCP"},
  2136. {Name: "easy", ContainerPort: 82, Protocol: "TCP"},
  2137. {Name: "as", ContainerPort: 83, Protocol: "UDP"},
  2138. {Name: "do-re-me", ContainerPort: 84, Protocol: "UDP"},
  2139. {ContainerPort: 85, Protocol: "TCP"},
  2140. }
  2141. if errs := validateContainerPorts(successCase, field.NewPath("field")); len(errs) != 0 {
  2142. t.Errorf("expected success: %v", errs)
  2143. }
  2144. nonCanonicalCase := []api.ContainerPort{
  2145. {ContainerPort: 80, Protocol: "TCP"},
  2146. }
  2147. if errs := validateContainerPorts(nonCanonicalCase, field.NewPath("field")); len(errs) != 0 {
  2148. t.Errorf("expected success: %v", errs)
  2149. }
  2150. errorCases := map[string]struct {
  2151. P []api.ContainerPort
  2152. T field.ErrorType
  2153. F string
  2154. D string
  2155. }{
  2156. "name > 15 characters": {
  2157. []api.ContainerPort{{Name: strings.Repeat("a", 16), ContainerPort: 80, Protocol: "TCP"}},
  2158. field.ErrorTypeInvalid,
  2159. "name", "15",
  2160. },
  2161. "name contains invalid characters": {
  2162. []api.ContainerPort{{Name: "a.b.c", ContainerPort: 80, Protocol: "TCP"}},
  2163. field.ErrorTypeInvalid,
  2164. "name", "alpha-numeric",
  2165. },
  2166. "name is a number": {
  2167. []api.ContainerPort{{Name: "80", ContainerPort: 80, Protocol: "TCP"}},
  2168. field.ErrorTypeInvalid,
  2169. "name", "at least one letter",
  2170. },
  2171. "name not unique": {
  2172. []api.ContainerPort{
  2173. {Name: "abc", ContainerPort: 80, Protocol: "TCP"},
  2174. {Name: "abc", ContainerPort: 81, Protocol: "TCP"},
  2175. },
  2176. field.ErrorTypeDuplicate,
  2177. "[1].name", "",
  2178. },
  2179. "zero container port": {
  2180. []api.ContainerPort{{ContainerPort: 0, Protocol: "TCP"}},
  2181. field.ErrorTypeRequired,
  2182. "containerPort", "",
  2183. },
  2184. "invalid container port": {
  2185. []api.ContainerPort{{ContainerPort: 65536, Protocol: "TCP"}},
  2186. field.ErrorTypeInvalid,
  2187. "containerPort", "between",
  2188. },
  2189. "invalid host port": {
  2190. []api.ContainerPort{{ContainerPort: 80, HostPort: 65536, Protocol: "TCP"}},
  2191. field.ErrorTypeInvalid,
  2192. "hostPort", "between",
  2193. },
  2194. "invalid protocol case": {
  2195. []api.ContainerPort{{ContainerPort: 80, Protocol: "tcp"}},
  2196. field.ErrorTypeNotSupported,
  2197. "protocol", "supported values: TCP, UDP",
  2198. },
  2199. "invalid protocol": {
  2200. []api.ContainerPort{{ContainerPort: 80, Protocol: "ICMP"}},
  2201. field.ErrorTypeNotSupported,
  2202. "protocol", "supported values: TCP, UDP",
  2203. },
  2204. "protocol required": {
  2205. []api.ContainerPort{{Name: "abc", ContainerPort: 80}},
  2206. field.ErrorTypeRequired,
  2207. "protocol", "",
  2208. },
  2209. }
  2210. for k, v := range errorCases {
  2211. errs := validateContainerPorts(v.P, field.NewPath("field"))
  2212. if len(errs) == 0 {
  2213. t.Errorf("expected failure for %s", k)
  2214. }
  2215. for i := range errs {
  2216. if errs[i].Type != v.T {
  2217. t.Errorf("%s: expected error to have type %q: %q", k, v.T, errs[i].Type)
  2218. }
  2219. if !strings.Contains(errs[i].Field, v.F) {
  2220. t.Errorf("%s: expected error field %q: %q", k, v.F, errs[i].Field)
  2221. }
  2222. if !strings.Contains(errs[i].Detail, v.D) {
  2223. t.Errorf("%s: expected error detail %q, got %q", k, v.D, errs[i].Detail)
  2224. }
  2225. }
  2226. }
  2227. }
  2228. func TestValidateEnv(t *testing.T) {
  2229. successCase := []api.EnvVar{
  2230. {Name: "abc", Value: "value"},
  2231. {Name: "ABC", Value: "value"},
  2232. {Name: "AbC_123", Value: "value"},
  2233. {Name: "abc", Value: ""},
  2234. {
  2235. Name: "abc",
  2236. ValueFrom: &api.EnvVarSource{
  2237. FieldRef: &api.ObjectFieldSelector{
  2238. APIVersion: testapi.Default.GroupVersion().String(),
  2239. FieldPath: "metadata.name",
  2240. },
  2241. },
  2242. },
  2243. {
  2244. Name: "abc",
  2245. ValueFrom: &api.EnvVarSource{
  2246. FieldRef: &api.ObjectFieldSelector{
  2247. APIVersion: testapi.Default.GroupVersion().String(),
  2248. FieldPath: "spec.nodeName",
  2249. },
  2250. },
  2251. },
  2252. {
  2253. Name: "abc",
  2254. ValueFrom: &api.EnvVarSource{
  2255. FieldRef: &api.ObjectFieldSelector{
  2256. APIVersion: testapi.Default.GroupVersion().String(),
  2257. FieldPath: "spec.serviceAccountName",
  2258. },
  2259. },
  2260. },
  2261. {
  2262. Name: "secret_value",
  2263. ValueFrom: &api.EnvVarSource{
  2264. SecretKeyRef: &api.SecretKeySelector{
  2265. LocalObjectReference: api.LocalObjectReference{
  2266. Name: "some-secret",
  2267. },
  2268. Key: "secret-key",
  2269. },
  2270. },
  2271. },
  2272. {
  2273. Name: "ENV_VAR_1",
  2274. ValueFrom: &api.EnvVarSource{
  2275. ConfigMapKeyRef: &api.ConfigMapKeySelector{
  2276. LocalObjectReference: api.LocalObjectReference{
  2277. Name: "some-config-map",
  2278. },
  2279. Key: "some-key",
  2280. },
  2281. },
  2282. },
  2283. }
  2284. if errs := validateEnv(successCase, field.NewPath("field")); len(errs) != 0 {
  2285. t.Errorf("expected success: %v", errs)
  2286. }
  2287. errorCases := []struct {
  2288. name string
  2289. envs []api.EnvVar
  2290. expectedError string
  2291. }{
  2292. {
  2293. name: "zero-length name",
  2294. envs: []api.EnvVar{{Name: ""}},
  2295. expectedError: "[0].name: Required value",
  2296. },
  2297. {
  2298. name: "name not a C identifier",
  2299. envs: []api.EnvVar{{Name: "a.b.c"}},
  2300. expectedError: `[0].name: Invalid value: "a.b.c": must match the regex`,
  2301. },
  2302. {
  2303. name: "value and valueFrom specified",
  2304. envs: []api.EnvVar{{
  2305. Name: "abc",
  2306. Value: "foo",
  2307. ValueFrom: &api.EnvVarSource{
  2308. FieldRef: &api.ObjectFieldSelector{
  2309. APIVersion: testapi.Default.GroupVersion().String(),
  2310. FieldPath: "metadata.name",
  2311. },
  2312. },
  2313. }},
  2314. expectedError: "[0].valueFrom: Invalid value: \"\": may not be specified when `value` is not empty",
  2315. },
  2316. {
  2317. name: "valueFrom.fieldRef and valueFrom.secretKeyRef specified",
  2318. envs: []api.EnvVar{{
  2319. Name: "abc",
  2320. ValueFrom: &api.EnvVarSource{
  2321. FieldRef: &api.ObjectFieldSelector{
  2322. APIVersion: testapi.Default.GroupVersion().String(),
  2323. FieldPath: "metadata.name",
  2324. },
  2325. SecretKeyRef: &api.SecretKeySelector{
  2326. LocalObjectReference: api.LocalObjectReference{
  2327. Name: "a-secret",
  2328. },
  2329. Key: "a-key",
  2330. },
  2331. },
  2332. }},
  2333. expectedError: "[0].valueFrom: Invalid value: \"\": may not have more than one field specified at a time",
  2334. },
  2335. {
  2336. name: "valueFrom.fieldRef and valueFrom.configMapKeyRef set",
  2337. envs: []api.EnvVar{{
  2338. Name: "some_var_name",
  2339. ValueFrom: &api.EnvVarSource{
  2340. FieldRef: &api.ObjectFieldSelector{
  2341. APIVersion: testapi.Default.GroupVersion().String(),
  2342. FieldPath: "metadata.name",
  2343. },
  2344. ConfigMapKeyRef: &api.ConfigMapKeySelector{
  2345. LocalObjectReference: api.LocalObjectReference{
  2346. Name: "some-config-map",
  2347. },
  2348. Key: "some-key",
  2349. },
  2350. },
  2351. }},
  2352. expectedError: `[0].valueFrom: Invalid value: "": may not have more than one field specified at a time`,
  2353. },
  2354. {
  2355. name: "valueFrom.fieldRef and valueFrom.secretKeyRef specified",
  2356. envs: []api.EnvVar{{
  2357. Name: "abc",
  2358. ValueFrom: &api.EnvVarSource{
  2359. FieldRef: &api.ObjectFieldSelector{
  2360. APIVersion: testapi.Default.GroupVersion().String(),
  2361. FieldPath: "metadata.name",
  2362. },
  2363. SecretKeyRef: &api.SecretKeySelector{
  2364. LocalObjectReference: api.LocalObjectReference{
  2365. Name: "a-secret",
  2366. },
  2367. Key: "a-key",
  2368. },
  2369. ConfigMapKeyRef: &api.ConfigMapKeySelector{
  2370. LocalObjectReference: api.LocalObjectReference{
  2371. Name: "some-config-map",
  2372. },
  2373. Key: "some-key",
  2374. },
  2375. },
  2376. }},
  2377. expectedError: `[0].valueFrom: Invalid value: "": may not have more than one field specified at a time`,
  2378. },
  2379. {
  2380. name: "missing FieldPath on ObjectFieldSelector",
  2381. envs: []api.EnvVar{{
  2382. Name: "abc",
  2383. ValueFrom: &api.EnvVarSource{
  2384. FieldRef: &api.ObjectFieldSelector{
  2385. APIVersion: testapi.Default.GroupVersion().String(),
  2386. },
  2387. },
  2388. }},
  2389. expectedError: `[0].valueFrom.fieldRef.fieldPath: Required value`,
  2390. },
  2391. {
  2392. name: "missing APIVersion on ObjectFieldSelector",
  2393. envs: []api.EnvVar{{
  2394. Name: "abc",
  2395. ValueFrom: &api.EnvVarSource{
  2396. FieldRef: &api.ObjectFieldSelector{
  2397. FieldPath: "metadata.name",
  2398. },
  2399. },
  2400. }},
  2401. expectedError: `[0].valueFrom.fieldRef.apiVersion: Required value`,
  2402. },
  2403. {
  2404. name: "invalid fieldPath",
  2405. envs: []api.EnvVar{{
  2406. Name: "abc",
  2407. ValueFrom: &api.EnvVarSource{
  2408. FieldRef: &api.ObjectFieldSelector{
  2409. FieldPath: "metadata.whoops",
  2410. APIVersion: testapi.Default.GroupVersion().String(),
  2411. },
  2412. },
  2413. }},
  2414. expectedError: `[0].valueFrom.fieldRef.fieldPath: Invalid value: "metadata.whoops": error converting fieldPath`,
  2415. },
  2416. {
  2417. name: "invalid fieldPath labels",
  2418. envs: []api.EnvVar{{
  2419. Name: "labels",
  2420. ValueFrom: &api.EnvVarSource{
  2421. FieldRef: &api.ObjectFieldSelector{
  2422. FieldPath: "metadata.labels",
  2423. APIVersion: "v1",
  2424. },
  2425. },
  2426. }},
  2427. expectedError: `[0].valueFrom.fieldRef.fieldPath: Unsupported value: "metadata.labels": supported values: metadata.name, metadata.namespace, spec.nodeName, spec.serviceAccountName, status.podIP`,
  2428. },
  2429. {
  2430. name: "invalid fieldPath annotations",
  2431. envs: []api.EnvVar{{
  2432. Name: "abc",
  2433. ValueFrom: &api.EnvVarSource{
  2434. FieldRef: &api.ObjectFieldSelector{
  2435. FieldPath: "metadata.annotations",
  2436. APIVersion: "v1",
  2437. },
  2438. },
  2439. }},
  2440. expectedError: `[0].valueFrom.fieldRef.fieldPath: Unsupported value: "metadata.annotations": supported values: metadata.name, metadata.namespace, spec.nodeName, spec.serviceAccountName, status.podIP`,
  2441. },
  2442. {
  2443. name: "unsupported fieldPath",
  2444. envs: []api.EnvVar{{
  2445. Name: "abc",
  2446. ValueFrom: &api.EnvVarSource{
  2447. FieldRef: &api.ObjectFieldSelector{
  2448. FieldPath: "status.phase",
  2449. APIVersion: testapi.Default.GroupVersion().String(),
  2450. },
  2451. },
  2452. }},
  2453. expectedError: `valueFrom.fieldRef.fieldPath: Unsupported value: "status.phase": supported values: metadata.name, metadata.namespace, spec.nodeName, spec.serviceAccountName, status.podIP`,
  2454. },
  2455. }
  2456. for _, tc := range errorCases {
  2457. if errs := validateEnv(tc.envs, field.NewPath("field")); len(errs) == 0 {
  2458. t.Errorf("expected failure for %s", tc.name)
  2459. } else {
  2460. for i := range errs {
  2461. str := errs[i].Error()
  2462. if str != "" && !strings.Contains(str, tc.expectedError) {
  2463. t.Errorf("%s: expected error detail either empty or %q, got %q", tc.name, tc.expectedError, str)
  2464. }
  2465. }
  2466. }
  2467. }
  2468. }
  2469. func TestValidateVolumeMounts(t *testing.T) {
  2470. volumes := sets.NewString("abc", "123", "abc-123")
  2471. successCase := []api.VolumeMount{
  2472. {Name: "abc", MountPath: "/foo"},
  2473. {Name: "123", MountPath: "/bar"},
  2474. {Name: "abc-123", MountPath: "/baz"},
  2475. {Name: "abc-123", MountPath: "/baa", SubPath: ""},
  2476. {Name: "abc-123", MountPath: "/bab", SubPath: "baz"},
  2477. {Name: "abc-123", MountPath: "/bac", SubPath: ".baz"},
  2478. {Name: "abc-123", MountPath: "/bad", SubPath: "..baz"},
  2479. }
  2480. if errs := validateVolumeMounts(successCase, volumes, field.NewPath("field")); len(errs) != 0 {
  2481. t.Errorf("expected success: %v", errs)
  2482. }
  2483. errorCases := map[string][]api.VolumeMount{
  2484. "empty name": {{Name: "", MountPath: "/foo"}},
  2485. "name not found": {{Name: "", MountPath: "/foo"}},
  2486. "empty mountpath": {{Name: "abc", MountPath: ""}},
  2487. "colon mountpath": {{Name: "abc", MountPath: "foo:bar"}},
  2488. "mountpath collision": {{Name: "foo", MountPath: "/path/a"}, {Name: "bar", MountPath: "/path/a"}},
  2489. "absolute subpath": {{Name: "abc", MountPath: "/bar", SubPath: "/baz"}},
  2490. "subpath in ..": {{Name: "abc", MountPath: "/bar", SubPath: "../baz"}},
  2491. "subpath contains ..": {{Name: "abc", MountPath: "/bar", SubPath: "baz/../bat"}},
  2492. "subpath ends in ..": {{Name: "abc", MountPath: "/bar", SubPath: "./.."}},
  2493. }
  2494. for k, v := range errorCases {
  2495. if errs := validateVolumeMounts(v, volumes, field.NewPath("field")); len(errs) == 0 {
  2496. t.Errorf("expected failure for %s", k)
  2497. }
  2498. }
  2499. }
  2500. func TestValidateProbe(t *testing.T) {
  2501. handler := api.Handler{Exec: &api.ExecAction{Command: []string{"echo"}}}
  2502. // These fields must be positive.
  2503. positiveFields := [...]string{"InitialDelaySeconds", "TimeoutSeconds", "PeriodSeconds", "SuccessThreshold", "FailureThreshold"}
  2504. successCases := []*api.Probe{nil}
  2505. for _, field := range positiveFields {
  2506. probe := &api.Probe{Handler: handler}
  2507. reflect.ValueOf(probe).Elem().FieldByName(field).SetInt(10)
  2508. successCases = append(successCases, probe)
  2509. }
  2510. for _, p := range successCases {
  2511. if errs := validateProbe(p, field.NewPath("field")); len(errs) != 0 {
  2512. t.Errorf("expected success: %v", errs)
  2513. }
  2514. }
  2515. errorCases := []*api.Probe{{TimeoutSeconds: 10, InitialDelaySeconds: 10}}
  2516. for _, field := range positiveFields {
  2517. probe := &api.Probe{Handler: handler}
  2518. reflect.ValueOf(probe).Elem().FieldByName(field).SetInt(-10)
  2519. errorCases = append(errorCases, probe)
  2520. }
  2521. for _, p := range errorCases {
  2522. if errs := validateProbe(p, field.NewPath("field")); len(errs) == 0 {
  2523. t.Errorf("expected failure for %v", p)
  2524. }
  2525. }
  2526. }
  2527. func TestValidateHandler(t *testing.T) {
  2528. successCases := []api.Handler{
  2529. {Exec: &api.ExecAction{Command: []string{"echo"}}},
  2530. {HTTPGet: &api.HTTPGetAction{Path: "/", Port: intstr.FromInt(1), Host: "", Scheme: "HTTP"}},
  2531. {HTTPGet: &api.HTTPGetAction{Path: "/foo", Port: intstr.FromInt(65535), Host: "host", Scheme: "HTTP"}},
  2532. {HTTPGet: &api.HTTPGetAction{Path: "/", Port: intstr.FromString("port"), Host: "", Scheme: "HTTP"}},
  2533. {HTTPGet: &api.HTTPGetAction{Path: "/", Port: intstr.FromString("port"), Host: "", Scheme: "HTTP", HTTPHeaders: []api.HTTPHeader{{Name: "Host", Value: "foo.example.com"}}}},
  2534. {HTTPGet: &api.HTTPGetAction{Path: "/", Port: intstr.FromString("port"), Host: "", Scheme: "HTTP", HTTPHeaders: []api.HTTPHeader{{Name: "X-Forwarded-For", Value: "1.2.3.4"}, {Name: "X-Forwarded-For", Value: "5.6.7.8"}}}},
  2535. }
  2536. for _, h := range successCases {
  2537. if errs := validateHandler(&h, field.NewPath("field")); len(errs) != 0 {
  2538. t.Errorf("expected success: %v", errs)
  2539. }
  2540. }
  2541. errorCases := []api.Handler{
  2542. {},
  2543. {Exec: &api.ExecAction{Command: []string{}}},
  2544. {HTTPGet: &api.HTTPGetAction{Path: "", Port: intstr.FromInt(0), Host: ""}},
  2545. {HTTPGet: &api.HTTPGetAction{Path: "/foo", Port: intstr.FromInt(65536), Host: "host"}},
  2546. {HTTPGet: &api.HTTPGetAction{Path: "", Port: intstr.FromString(""), Host: ""}},
  2547. {HTTPGet: &api.HTTPGetAction{Path: "/", Port: intstr.FromString("port"), Host: "", Scheme: "HTTP", HTTPHeaders: []api.HTTPHeader{{Name: "Host:", Value: "foo.example.com"}}}},
  2548. {HTTPGet: &api.HTTPGetAction{Path: "/", Port: intstr.FromString("port"), Host: "", Scheme: "HTTP", HTTPHeaders: []api.HTTPHeader{{Name: "X_Forwarded_For", Value: "foo.example.com"}}}},
  2549. }
  2550. for _, h := range errorCases {
  2551. if errs := validateHandler(&h, field.NewPath("field")); len(errs) == 0 {
  2552. t.Errorf("expected failure for %#v", h)
  2553. }
  2554. }
  2555. }
  2556. func TestValidatePullPolicy(t *testing.T) {
  2557. type T struct {
  2558. Container api.Container
  2559. ExpectedPolicy api.PullPolicy
  2560. }
  2561. testCases := map[string]T{
  2562. "NotPresent1": {
  2563. api.Container{Name: "abc", Image: "image:latest", ImagePullPolicy: "IfNotPresent"},
  2564. api.PullIfNotPresent,
  2565. },
  2566. "NotPresent2": {
  2567. api.Container{Name: "abc1", Image: "image", ImagePullPolicy: "IfNotPresent"},
  2568. api.PullIfNotPresent,
  2569. },
  2570. "Always1": {
  2571. api.Container{Name: "123", Image: "image:latest", ImagePullPolicy: "Always"},
  2572. api.PullAlways,
  2573. },
  2574. "Always2": {
  2575. api.Container{Name: "1234", Image: "image", ImagePullPolicy: "Always"},
  2576. api.PullAlways,
  2577. },
  2578. "Never1": {
  2579. api.Container{Name: "abc-123", Image: "image:latest", ImagePullPolicy: "Never"},
  2580. api.PullNever,
  2581. },
  2582. "Never2": {
  2583. api.Container{Name: "abc-1234", Image: "image", ImagePullPolicy: "Never"},
  2584. api.PullNever,
  2585. },
  2586. }
  2587. for k, v := range testCases {
  2588. ctr := &v.Container
  2589. errs := validatePullPolicy(ctr.ImagePullPolicy, field.NewPath("field"))
  2590. if len(errs) != 0 {
  2591. t.Errorf("case[%s] expected success, got %#v", k, errs)
  2592. }
  2593. if ctr.ImagePullPolicy != v.ExpectedPolicy {
  2594. t.Errorf("case[%s] expected policy %v, got %v", k, v.ExpectedPolicy, ctr.ImagePullPolicy)
  2595. }
  2596. }
  2597. }
  2598. func getResourceLimits(cpu, memory string) api.ResourceList {
  2599. res := api.ResourceList{}
  2600. res[api.ResourceCPU] = resource.MustParse(cpu)
  2601. res[api.ResourceMemory] = resource.MustParse(memory)
  2602. return res
  2603. }
  2604. func TestValidateContainers(t *testing.T) {
  2605. volumes := sets.String{}
  2606. capabilities.SetForTests(capabilities.Capabilities{
  2607. AllowPrivileged: true,
  2608. })
  2609. successCase := []api.Container{
  2610. {Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent"},
  2611. {Name: "123", Image: "image", ImagePullPolicy: "IfNotPresent"},
  2612. {Name: "abc-123", Image: "image", ImagePullPolicy: "IfNotPresent"},
  2613. {
  2614. Name: "life-123",
  2615. Image: "image",
  2616. Lifecycle: &api.Lifecycle{
  2617. PreStop: &api.Handler{
  2618. Exec: &api.ExecAction{Command: []string{"ls", "-l"}},
  2619. },
  2620. },
  2621. ImagePullPolicy: "IfNotPresent",
  2622. },
  2623. {
  2624. Name: "resources-test",
  2625. Image: "image",
  2626. Resources: api.ResourceRequirements{
  2627. Limits: api.ResourceList{
  2628. api.ResourceName(api.ResourceCPU): resource.MustParse("10"),
  2629. api.ResourceName(api.ResourceMemory): resource.MustParse("10G"),
  2630. api.ResourceName("my.org/resource"): resource.MustParse("10m"),
  2631. },
  2632. },
  2633. ImagePullPolicy: "IfNotPresent",
  2634. },
  2635. {
  2636. Name: "resources-test-with-gpu-with-request",
  2637. Image: "image",
  2638. Resources: api.ResourceRequirements{
  2639. Requests: api.ResourceList{
  2640. api.ResourceName(api.ResourceCPU): resource.MustParse("10"),
  2641. api.ResourceName(api.ResourceMemory): resource.MustParse("10G"),
  2642. api.ResourceName(api.ResourceNvidiaGPU): resource.MustParse("1"),
  2643. },
  2644. Limits: api.ResourceList{
  2645. api.ResourceName(api.ResourceCPU): resource.MustParse("10"),
  2646. api.ResourceName(api.ResourceMemory): resource.MustParse("10G"),
  2647. api.ResourceName(api.ResourceNvidiaGPU): resource.MustParse("1"),
  2648. },
  2649. },
  2650. ImagePullPolicy: "IfNotPresent",
  2651. },
  2652. {
  2653. Name: "resources-test-with-gpu-without-request",
  2654. Image: "image",
  2655. Resources: api.ResourceRequirements{
  2656. Requests: api.ResourceList{
  2657. api.ResourceName(api.ResourceCPU): resource.MustParse("10"),
  2658. api.ResourceName(api.ResourceMemory): resource.MustParse("10G"),
  2659. },
  2660. Limits: api.ResourceList{
  2661. api.ResourceName(api.ResourceCPU): resource.MustParse("10"),
  2662. api.ResourceName(api.ResourceMemory): resource.MustParse("10G"),
  2663. api.ResourceName(api.ResourceNvidiaGPU): resource.MustParse("1"),
  2664. },
  2665. },
  2666. ImagePullPolicy: "IfNotPresent",
  2667. },
  2668. {
  2669. Name: "resources-request-limit-simple",
  2670. Image: "image",
  2671. Resources: api.ResourceRequirements{
  2672. Requests: api.ResourceList{
  2673. api.ResourceName(api.ResourceCPU): resource.MustParse("8"),
  2674. },
  2675. Limits: api.ResourceList{
  2676. api.ResourceName(api.ResourceCPU): resource.MustParse("10"),
  2677. },
  2678. },
  2679. ImagePullPolicy: "IfNotPresent",
  2680. },
  2681. {
  2682. Name: "resources-request-limit-edge",
  2683. Image: "image",
  2684. Resources: api.ResourceRequirements{
  2685. Requests: api.ResourceList{
  2686. api.ResourceName(api.ResourceCPU): resource.MustParse("10"),
  2687. api.ResourceName(api.ResourceMemory): resource.MustParse("10G"),
  2688. api.ResourceName("my.org/resource"): resource.MustParse("10m"),
  2689. },
  2690. Limits: api.ResourceList{
  2691. api.ResourceName(api.ResourceCPU): resource.MustParse("10"),
  2692. api.ResourceName(api.ResourceMemory): resource.MustParse("10G"),
  2693. api.ResourceName("my.org/resource"): resource.MustParse("10m"),
  2694. },
  2695. },
  2696. ImagePullPolicy: "IfNotPresent",
  2697. },
  2698. {
  2699. Name: "resources-request-limit-partials",
  2700. Image: "image",
  2701. Resources: api.ResourceRequirements{
  2702. Requests: api.ResourceList{
  2703. api.ResourceName(api.ResourceCPU): resource.MustParse("9.5"),
  2704. api.ResourceName(api.ResourceMemory): resource.MustParse("10G"),
  2705. },
  2706. Limits: api.ResourceList{
  2707. api.ResourceName(api.ResourceCPU): resource.MustParse("10"),
  2708. api.ResourceName("my.org/resource"): resource.MustParse("10m"),
  2709. },
  2710. },
  2711. ImagePullPolicy: "IfNotPresent",
  2712. },
  2713. {
  2714. Name: "resources-request",
  2715. Image: "image",
  2716. Resources: api.ResourceRequirements{
  2717. Requests: api.ResourceList{
  2718. api.ResourceName(api.ResourceCPU): resource.MustParse("9.5"),
  2719. api.ResourceName(api.ResourceMemory): resource.MustParse("10G"),
  2720. },
  2721. },
  2722. ImagePullPolicy: "IfNotPresent",
  2723. },
  2724. {
  2725. Name: "same-host-port-different-protocol",
  2726. Image: "image",
  2727. Ports: []api.ContainerPort{
  2728. {ContainerPort: 80, HostPort: 80, Protocol: "TCP"},
  2729. {ContainerPort: 80, HostPort: 80, Protocol: "UDP"},
  2730. },
  2731. ImagePullPolicy: "IfNotPresent",
  2732. },
  2733. {Name: "abc-1234", Image: "image", ImagePullPolicy: "IfNotPresent", SecurityContext: fakeValidSecurityContext(true)},
  2734. }
  2735. if errs := validateContainers(successCase, volumes, field.NewPath("field")); len(errs) != 0 {
  2736. t.Errorf("expected success: %v", errs)
  2737. }
  2738. capabilities.SetForTests(capabilities.Capabilities{
  2739. AllowPrivileged: false,
  2740. })
  2741. errorCases := map[string][]api.Container{
  2742. "zero-length name": {{Name: "", Image: "image", ImagePullPolicy: "IfNotPresent"}},
  2743. "name > 63 characters": {{Name: strings.Repeat("a", 64), Image: "image", ImagePullPolicy: "IfNotPresent"}},
  2744. "name not a DNS label": {{Name: "a.b.c", Image: "image", ImagePullPolicy: "IfNotPresent"}},
  2745. "name not unique": {
  2746. {Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent"},
  2747. {Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent"},
  2748. },
  2749. "zero-length image": {{Name: "abc", Image: "", ImagePullPolicy: "IfNotPresent"}},
  2750. "host port not unique": {
  2751. {Name: "abc", Image: "image", Ports: []api.ContainerPort{{ContainerPort: 80, HostPort: 80, Protocol: "TCP"}},
  2752. ImagePullPolicy: "IfNotPresent"},
  2753. {Name: "def", Image: "image", Ports: []api.ContainerPort{{ContainerPort: 81, HostPort: 80, Protocol: "TCP"}},
  2754. ImagePullPolicy: "IfNotPresent"},
  2755. },
  2756. "invalid env var name": {
  2757. {Name: "abc", Image: "image", Env: []api.EnvVar{{Name: "ev.1"}}, ImagePullPolicy: "IfNotPresent"},
  2758. },
  2759. "unknown volume name": {
  2760. {Name: "abc", Image: "image", VolumeMounts: []api.VolumeMount{{Name: "anything", MountPath: "/foo"}},
  2761. ImagePullPolicy: "IfNotPresent"},
  2762. },
  2763. "invalid lifecycle, no exec command.": {
  2764. {
  2765. Name: "life-123",
  2766. Image: "image",
  2767. Lifecycle: &api.Lifecycle{
  2768. PreStop: &api.Handler{
  2769. Exec: &api.ExecAction{},
  2770. },
  2771. },
  2772. ImagePullPolicy: "IfNotPresent",
  2773. },
  2774. },
  2775. "invalid lifecycle, no http path.": {
  2776. {
  2777. Name: "life-123",
  2778. Image: "image",
  2779. Lifecycle: &api.Lifecycle{
  2780. PreStop: &api.Handler{
  2781. HTTPGet: &api.HTTPGetAction{},
  2782. },
  2783. },
  2784. ImagePullPolicy: "IfNotPresent",
  2785. },
  2786. },
  2787. "invalid lifecycle, no tcp socket port.": {
  2788. {
  2789. Name: "life-123",
  2790. Image: "image",
  2791. Lifecycle: &api.Lifecycle{
  2792. PreStop: &api.Handler{
  2793. TCPSocket: &api.TCPSocketAction{},
  2794. },
  2795. },
  2796. ImagePullPolicy: "IfNotPresent",
  2797. },
  2798. },
  2799. "invalid lifecycle, zero tcp socket port.": {
  2800. {
  2801. Name: "life-123",
  2802. Image: "image",
  2803. Lifecycle: &api.Lifecycle{
  2804. PreStop: &api.Handler{
  2805. TCPSocket: &api.TCPSocketAction{
  2806. Port: intstr.FromInt(0),
  2807. },
  2808. },
  2809. },
  2810. ImagePullPolicy: "IfNotPresent",
  2811. },
  2812. },
  2813. "invalid lifecycle, no action.": {
  2814. {
  2815. Name: "life-123",
  2816. Image: "image",
  2817. Lifecycle: &api.Lifecycle{
  2818. PreStop: &api.Handler{},
  2819. },
  2820. ImagePullPolicy: "IfNotPresent",
  2821. },
  2822. },
  2823. "invalid liveness probe, no tcp socket port.": {
  2824. {
  2825. Name: "life-123",
  2826. Image: "image",
  2827. LivenessProbe: &api.Probe{
  2828. Handler: api.Handler{
  2829. TCPSocket: &api.TCPSocketAction{},
  2830. },
  2831. },
  2832. ImagePullPolicy: "IfNotPresent",
  2833. },
  2834. },
  2835. "invalid liveness probe, no action.": {
  2836. {
  2837. Name: "life-123",
  2838. Image: "image",
  2839. LivenessProbe: &api.Probe{
  2840. Handler: api.Handler{},
  2841. },
  2842. ImagePullPolicy: "IfNotPresent",
  2843. },
  2844. },
  2845. "privilege disabled": {
  2846. {Name: "abc", Image: "image", SecurityContext: fakeValidSecurityContext(true)},
  2847. },
  2848. "invalid compute resource": {
  2849. {
  2850. Name: "abc-123",
  2851. Image: "image",
  2852. Resources: api.ResourceRequirements{
  2853. Limits: api.ResourceList{
  2854. "disk": resource.MustParse("10G"),
  2855. },
  2856. },
  2857. ImagePullPolicy: "IfNotPresent",
  2858. },
  2859. },
  2860. "Resource CPU invalid": {
  2861. {
  2862. Name: "abc-123",
  2863. Image: "image",
  2864. Resources: api.ResourceRequirements{
  2865. Limits: getResourceLimits("-10", "0"),
  2866. },
  2867. ImagePullPolicy: "IfNotPresent",
  2868. },
  2869. },
  2870. "Resource Requests CPU invalid": {
  2871. {
  2872. Name: "abc-123",
  2873. Image: "image",
  2874. Resources: api.ResourceRequirements{
  2875. Requests: getResourceLimits("-10", "0"),
  2876. },
  2877. ImagePullPolicy: "IfNotPresent",
  2878. },
  2879. },
  2880. "Resource Memory invalid": {
  2881. {
  2882. Name: "abc-123",
  2883. Image: "image",
  2884. Resources: api.ResourceRequirements{
  2885. Limits: getResourceLimits("0", "-10"),
  2886. },
  2887. ImagePullPolicy: "IfNotPresent",
  2888. },
  2889. },
  2890. "Resource GPU limit must match request": {
  2891. {
  2892. Name: "gpu-resource-request-limit",
  2893. Image: "image",
  2894. Resources: api.ResourceRequirements{
  2895. Requests: api.ResourceList{
  2896. api.ResourceName(api.ResourceCPU): resource.MustParse("10"),
  2897. api.ResourceName(api.ResourceMemory): resource.MustParse("10G"),
  2898. api.ResourceName(api.ResourceNvidiaGPU): resource.MustParse("0"),
  2899. },
  2900. Limits: api.ResourceList{
  2901. api.ResourceName(api.ResourceCPU): resource.MustParse("10"),
  2902. api.ResourceName(api.ResourceMemory): resource.MustParse("10G"),
  2903. api.ResourceName(api.ResourceNvidiaGPU): resource.MustParse("1"),
  2904. },
  2905. },
  2906. ImagePullPolicy: "IfNotPresent",
  2907. },
  2908. },
  2909. "Request limit simple invalid": {
  2910. {
  2911. Name: "abc-123",
  2912. Image: "image",
  2913. Resources: api.ResourceRequirements{
  2914. Limits: getResourceLimits("5", "3"),
  2915. Requests: getResourceLimits("6", "3"),
  2916. },
  2917. ImagePullPolicy: "IfNotPresent",
  2918. },
  2919. },
  2920. "Request limit multiple invalid": {
  2921. {
  2922. Name: "abc-123",
  2923. Image: "image",
  2924. Resources: api.ResourceRequirements{
  2925. Limits: getResourceLimits("5", "3"),
  2926. Requests: getResourceLimits("6", "4"),
  2927. },
  2928. ImagePullPolicy: "IfNotPresent",
  2929. },
  2930. },
  2931. }
  2932. for k, v := range errorCases {
  2933. if errs := validateContainers(v, volumes, field.NewPath("field")); len(errs) == 0 {
  2934. t.Errorf("expected failure for %s", k)
  2935. }
  2936. }
  2937. }
  2938. func TestValidateRestartPolicy(t *testing.T) {
  2939. successCases := []api.RestartPolicy{
  2940. api.RestartPolicyAlways,
  2941. api.RestartPolicyOnFailure,
  2942. api.RestartPolicyNever,
  2943. }
  2944. for _, policy := range successCases {
  2945. if errs := validateRestartPolicy(&policy, field.NewPath("field")); len(errs) != 0 {
  2946. t.Errorf("expected success: %v", errs)
  2947. }
  2948. }
  2949. errorCases := []api.RestartPolicy{"", "newpolicy"}
  2950. for k, policy := range errorCases {
  2951. if errs := validateRestartPolicy(&policy, field.NewPath("field")); len(errs) == 0 {
  2952. t.Errorf("expected failure for %d", k)
  2953. }
  2954. }
  2955. }
  2956. func TestValidateDNSPolicy(t *testing.T) {
  2957. successCases := []api.DNSPolicy{api.DNSClusterFirst, api.DNSDefault, api.DNSPolicy(api.DNSClusterFirst)}
  2958. for _, policy := range successCases {
  2959. if errs := validateDNSPolicy(&policy, field.NewPath("field")); len(errs) != 0 {
  2960. t.Errorf("expected success: %v", errs)
  2961. }
  2962. }
  2963. errorCases := []api.DNSPolicy{api.DNSPolicy("invalid")}
  2964. for _, policy := range errorCases {
  2965. if errs := validateDNSPolicy(&policy, field.NewPath("field")); len(errs) == 0 {
  2966. t.Errorf("expected failure for %v", policy)
  2967. }
  2968. }
  2969. }
  2970. func TestValidatePodSpec(t *testing.T) {
  2971. activeDeadlineSeconds := int64(30)
  2972. minID := int64(0)
  2973. maxID := int64(2147483647)
  2974. successCases := []api.PodSpec{
  2975. { // Populate basic fields, leave defaults for most.
  2976. Volumes: []api.Volume{{Name: "vol", VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{}}}},
  2977. Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}},
  2978. RestartPolicy: api.RestartPolicyAlways,
  2979. DNSPolicy: api.DNSClusterFirst,
  2980. },
  2981. { // Populate all fields.
  2982. Volumes: []api.Volume{
  2983. {Name: "vol", VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{}}},
  2984. },
  2985. Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}},
  2986. InitContainers: []api.Container{{Name: "ictr", Image: "iimage", ImagePullPolicy: "IfNotPresent"}},
  2987. RestartPolicy: api.RestartPolicyAlways,
  2988. NodeSelector: map[string]string{
  2989. "key": "value",
  2990. },
  2991. NodeName: "foobar",
  2992. DNSPolicy: api.DNSClusterFirst,
  2993. ActiveDeadlineSeconds: &activeDeadlineSeconds,
  2994. ServiceAccountName: "acct",
  2995. },
  2996. { // Populate HostNetwork.
  2997. Containers: []api.Container{
  2998. {Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", Ports: []api.ContainerPort{
  2999. {HostPort: 8080, ContainerPort: 8080, Protocol: "TCP"}},
  3000. },
  3001. },
  3002. SecurityContext: &api.PodSecurityContext{
  3003. HostNetwork: true,
  3004. },
  3005. RestartPolicy: api.RestartPolicyAlways,
  3006. DNSPolicy: api.DNSClusterFirst,
  3007. },
  3008. { // Populate RunAsUser SupplementalGroups FSGroup with minID 0
  3009. Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}},
  3010. SecurityContext: &api.PodSecurityContext{
  3011. SupplementalGroups: []int64{minID},
  3012. RunAsUser: &minID,
  3013. FSGroup: &minID,
  3014. },
  3015. RestartPolicy: api.RestartPolicyAlways,
  3016. DNSPolicy: api.DNSClusterFirst,
  3017. },
  3018. { // Populate RunAsUser SupplementalGroups FSGroup with maxID 2147483647
  3019. Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}},
  3020. SecurityContext: &api.PodSecurityContext{
  3021. SupplementalGroups: []int64{maxID},
  3022. RunAsUser: &maxID,
  3023. FSGroup: &maxID,
  3024. },
  3025. RestartPolicy: api.RestartPolicyAlways,
  3026. DNSPolicy: api.DNSClusterFirst,
  3027. },
  3028. { // Populate HostIPC.
  3029. SecurityContext: &api.PodSecurityContext{
  3030. HostIPC: true,
  3031. },
  3032. Volumes: []api.Volume{{Name: "vol", VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{}}}},
  3033. Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}},
  3034. RestartPolicy: api.RestartPolicyAlways,
  3035. DNSPolicy: api.DNSClusterFirst,
  3036. },
  3037. { // Populate HostPID.
  3038. SecurityContext: &api.PodSecurityContext{
  3039. HostPID: true,
  3040. },
  3041. Volumes: []api.Volume{{Name: "vol", VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{}}}},
  3042. Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}},
  3043. RestartPolicy: api.RestartPolicyAlways,
  3044. DNSPolicy: api.DNSClusterFirst,
  3045. },
  3046. { // Populate Affinity.
  3047. Volumes: []api.Volume{{Name: "vol", VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{}}}},
  3048. Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}},
  3049. RestartPolicy: api.RestartPolicyAlways,
  3050. DNSPolicy: api.DNSClusterFirst,
  3051. },
  3052. }
  3053. for i := range successCases {
  3054. if errs := ValidatePodSpec(&successCases[i], field.NewPath("field")); len(errs) != 0 {
  3055. t.Errorf("expected success: %v", errs)
  3056. }
  3057. }
  3058. activeDeadlineSeconds = int64(0)
  3059. minID = int64(-1)
  3060. maxID = int64(2147483648)
  3061. failureCases := map[string]api.PodSpec{
  3062. "bad volume": {
  3063. Volumes: []api.Volume{{}},
  3064. RestartPolicy: api.RestartPolicyAlways,
  3065. DNSPolicy: api.DNSClusterFirst,
  3066. Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}},
  3067. },
  3068. "no containers": {
  3069. RestartPolicy: api.RestartPolicyAlways,
  3070. DNSPolicy: api.DNSClusterFirst,
  3071. },
  3072. "bad container": {
  3073. Containers: []api.Container{{}},
  3074. RestartPolicy: api.RestartPolicyAlways,
  3075. DNSPolicy: api.DNSClusterFirst,
  3076. },
  3077. "bad init container": {
  3078. Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}},
  3079. InitContainers: []api.Container{{}},
  3080. RestartPolicy: api.RestartPolicyAlways,
  3081. DNSPolicy: api.DNSClusterFirst,
  3082. },
  3083. "bad DNS policy": {
  3084. DNSPolicy: api.DNSPolicy("invalid"),
  3085. RestartPolicy: api.RestartPolicyAlways,
  3086. Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}},
  3087. },
  3088. "bad service account name": {
  3089. Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}},
  3090. RestartPolicy: api.RestartPolicyAlways,
  3091. DNSPolicy: api.DNSClusterFirst,
  3092. ServiceAccountName: "invalidName",
  3093. },
  3094. "bad restart policy": {
  3095. RestartPolicy: "UnknowPolicy",
  3096. DNSPolicy: api.DNSClusterFirst,
  3097. Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}},
  3098. },
  3099. "with hostNetwork hostPort not equal to containerPort": {
  3100. Containers: []api.Container{
  3101. {Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent", Ports: []api.ContainerPort{
  3102. {HostPort: 8080, ContainerPort: 2600, Protocol: "TCP"}},
  3103. },
  3104. },
  3105. SecurityContext: &api.PodSecurityContext{
  3106. HostNetwork: true,
  3107. },
  3108. RestartPolicy: api.RestartPolicyAlways,
  3109. DNSPolicy: api.DNSClusterFirst,
  3110. },
  3111. "bad supplementalGroups large than math.MaxInt32": {
  3112. Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}},
  3113. SecurityContext: &api.PodSecurityContext{
  3114. HostNetwork: false,
  3115. SupplementalGroups: []int64{maxID, 1234},
  3116. },
  3117. RestartPolicy: api.RestartPolicyAlways,
  3118. DNSPolicy: api.DNSClusterFirst,
  3119. },
  3120. "bad supplementalGroups less than 0": {
  3121. Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}},
  3122. SecurityContext: &api.PodSecurityContext{
  3123. HostNetwork: false,
  3124. SupplementalGroups: []int64{minID, 1234},
  3125. },
  3126. RestartPolicy: api.RestartPolicyAlways,
  3127. DNSPolicy: api.DNSClusterFirst,
  3128. },
  3129. "bad runAsUser large than math.MaxInt32": {
  3130. Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}},
  3131. SecurityContext: &api.PodSecurityContext{
  3132. HostNetwork: false,
  3133. RunAsUser: &maxID,
  3134. },
  3135. RestartPolicy: api.RestartPolicyAlways,
  3136. DNSPolicy: api.DNSClusterFirst,
  3137. },
  3138. "bad runAsUser less than 0": {
  3139. Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}},
  3140. SecurityContext: &api.PodSecurityContext{
  3141. HostNetwork: false,
  3142. RunAsUser: &minID,
  3143. },
  3144. RestartPolicy: api.RestartPolicyAlways,
  3145. DNSPolicy: api.DNSClusterFirst,
  3146. },
  3147. "bad fsGroup large than math.MaxInt32": {
  3148. Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}},
  3149. SecurityContext: &api.PodSecurityContext{
  3150. HostNetwork: false,
  3151. FSGroup: &maxID,
  3152. },
  3153. RestartPolicy: api.RestartPolicyAlways,
  3154. DNSPolicy: api.DNSClusterFirst,
  3155. },
  3156. "bad fsGroup less than 0": {
  3157. Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}},
  3158. SecurityContext: &api.PodSecurityContext{
  3159. HostNetwork: false,
  3160. FSGroup: &minID,
  3161. },
  3162. RestartPolicy: api.RestartPolicyAlways,
  3163. DNSPolicy: api.DNSClusterFirst,
  3164. },
  3165. "bad-active-deadline-seconds": {
  3166. Volumes: []api.Volume{
  3167. {Name: "vol", VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{}}},
  3168. },
  3169. Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}},
  3170. RestartPolicy: api.RestartPolicyAlways,
  3171. NodeSelector: map[string]string{
  3172. "key": "value",
  3173. },
  3174. NodeName: "foobar",
  3175. DNSPolicy: api.DNSClusterFirst,
  3176. ActiveDeadlineSeconds: &activeDeadlineSeconds,
  3177. },
  3178. "bad nodeName": {
  3179. NodeName: "node name",
  3180. Volumes: []api.Volume{{Name: "vol", VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{}}}},
  3181. Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}},
  3182. RestartPolicy: api.RestartPolicyAlways,
  3183. DNSPolicy: api.DNSClusterFirst,
  3184. },
  3185. }
  3186. for k, v := range failureCases {
  3187. if errs := ValidatePodSpec(&v, field.NewPath("field")); len(errs) == 0 {
  3188. t.Errorf("expected failure for %q", k)
  3189. }
  3190. }
  3191. }
  3192. func TestValidatePod(t *testing.T) {
  3193. validPodSpec := api.PodSpec{
  3194. Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}},
  3195. RestartPolicy: api.RestartPolicyAlways,
  3196. DNSPolicy: api.DNSClusterFirst,
  3197. }
  3198. successCases := []api.Pod{
  3199. { // Basic fields.
  3200. ObjectMeta: api.ObjectMeta{Name: "123", Namespace: "ns"},
  3201. Spec: api.PodSpec{
  3202. Volumes: []api.Volume{{Name: "vol", VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{}}}},
  3203. Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}},
  3204. RestartPolicy: api.RestartPolicyAlways,
  3205. DNSPolicy: api.DNSClusterFirst,
  3206. },
  3207. },
  3208. { // Just about everything.
  3209. ObjectMeta: api.ObjectMeta{Name: "abc.123.do-re-mi", Namespace: "ns"},
  3210. Spec: api.PodSpec{
  3211. Volumes: []api.Volume{
  3212. {Name: "vol", VolumeSource: api.VolumeSource{EmptyDir: &api.EmptyDirVolumeSource{}}},
  3213. },
  3214. Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}},
  3215. RestartPolicy: api.RestartPolicyAlways,
  3216. DNSPolicy: api.DNSClusterFirst,
  3217. NodeSelector: map[string]string{
  3218. "key": "value",
  3219. },
  3220. NodeName: "foobar",
  3221. },
  3222. },
  3223. { // Serialized affinity requirements in annotations.
  3224. ObjectMeta: api.ObjectMeta{
  3225. Name: "123",
  3226. Namespace: "ns",
  3227. // TODO: Uncomment and move this block into Annotations map once
  3228. // RequiredDuringSchedulingRequiredDuringExecution is implemented
  3229. // "requiredDuringSchedulingRequiredDuringExecution": {
  3230. // "nodeSelectorTerms": [{
  3231. // "matchExpressions": [{
  3232. // "key": "key1",
  3233. // "operator": "Exists"
  3234. // }]
  3235. // }]
  3236. // },
  3237. Annotations: map[string]string{
  3238. api.AffinityAnnotationKey: `
  3239. {"nodeAffinity": {
  3240. "requiredDuringSchedulingIgnoredDuringExecution": {
  3241. "nodeSelectorTerms": [{
  3242. "matchExpressions": [{
  3243. "key": "key2",
  3244. "operator": "In",
  3245. "values": ["value1", "value2"]
  3246. }]
  3247. }]
  3248. },
  3249. "preferredDuringSchedulingIgnoredDuringExecution": [
  3250. {
  3251. "weight": 10,
  3252. "preference": {"matchExpressions": [
  3253. {
  3254. "key": "foo",
  3255. "operator": "In", "values": ["bar"]
  3256. }
  3257. ]}
  3258. }
  3259. ]
  3260. }}`,
  3261. },
  3262. },
  3263. Spec: api.PodSpec{
  3264. Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}},
  3265. RestartPolicy: api.RestartPolicyAlways,
  3266. DNSPolicy: api.DNSClusterFirst,
  3267. },
  3268. },
  3269. { // Serialized pod affinity in affinity requirements in annotations.
  3270. ObjectMeta: api.ObjectMeta{
  3271. Name: "123",
  3272. Namespace: "ns",
  3273. // TODO: Uncomment and move this block into Annotations map once
  3274. // RequiredDuringSchedulingRequiredDuringExecution is implemented
  3275. // "requiredDuringSchedulingRequiredDuringExecution": [{
  3276. // "labelSelector": {
  3277. // "matchExpressions": [{
  3278. // "key": "key2",
  3279. // "operator": "In",
  3280. // "values": ["value1", "value2"]
  3281. // }]
  3282. // },
  3283. // "namespaces":["ns"],
  3284. // "topologyKey": "zone"
  3285. // }]
  3286. Annotations: map[string]string{
  3287. api.AffinityAnnotationKey: `
  3288. {"podAffinity": {
  3289. "requiredDuringSchedulingIgnoredDuringExecution": [{
  3290. "labelSelector": {
  3291. "matchExpressions": [{
  3292. "key": "key2",
  3293. "operator": "In",
  3294. "values": ["value1", "value2"]
  3295. }]
  3296. },
  3297. "topologyKey": "zone",
  3298. "namespaces": ["ns"]
  3299. }],
  3300. "preferredDuringSchedulingIgnoredDuringExecution": [{
  3301. "weight": 10,
  3302. "podAffinityTerm": {
  3303. "labelSelector": {
  3304. "matchExpressions": [{
  3305. "key": "key2",
  3306. "operator": "NotIn",
  3307. "values": ["value1", "value2"]
  3308. }]
  3309. },
  3310. "namespaces": ["ns"],
  3311. "topologyKey": "region"
  3312. }
  3313. }]
  3314. }}`,
  3315. },
  3316. },
  3317. Spec: validPodSpec,
  3318. },
  3319. { // Serialized pod anti affinity with different Label Operators in affinity requirements in annotations.
  3320. ObjectMeta: api.ObjectMeta{
  3321. Name: "123",
  3322. Namespace: "ns",
  3323. // TODO: Uncomment and move this block into Annotations map once
  3324. // RequiredDuringSchedulingRequiredDuringExecution is implemented
  3325. // "requiredDuringSchedulingRequiredDuringExecution": [{
  3326. // "labelSelector": {
  3327. // "matchExpressions": [{
  3328. // "key": "key2",
  3329. // "operator": "In",
  3330. // "values": ["value1", "value2"]
  3331. // }]
  3332. // },
  3333. // "namespaces":["ns"],
  3334. // "topologyKey": "zone"
  3335. // }]
  3336. Annotations: map[string]string{
  3337. api.AffinityAnnotationKey: `
  3338. {"podAntiAffinity": {
  3339. "requiredDuringSchedulingIgnoredDuringExecution": [{
  3340. "labelSelector": {
  3341. "matchExpressions": [{
  3342. "key": "key2",
  3343. "operator": "Exists"
  3344. }]
  3345. },
  3346. "topologyKey": "zone",
  3347. "namespaces": ["ns"]
  3348. }],
  3349. "preferredDuringSchedulingIgnoredDuringExecution": [{
  3350. "weight": 10,
  3351. "podAffinityTerm": {
  3352. "labelSelector": {
  3353. "matchExpressions": [{
  3354. "key": "key2",
  3355. "operator": "DoesNotExist"
  3356. }]
  3357. },
  3358. "namespaces": ["ns"],
  3359. "topologyKey": "region"
  3360. }
  3361. }]
  3362. }}`,
  3363. },
  3364. },
  3365. Spec: validPodSpec,
  3366. },
  3367. { // populate tolerations equal operator in annotations.
  3368. ObjectMeta: api.ObjectMeta{
  3369. Name: "123",
  3370. Namespace: "ns",
  3371. Annotations: map[string]string{
  3372. api.TolerationsAnnotationKey: `
  3373. [{
  3374. "key": "foo",
  3375. "operator": "Equal",
  3376. "value": "bar",
  3377. "effect": "NoSchedule"
  3378. }]`,
  3379. },
  3380. },
  3381. Spec: validPodSpec,
  3382. },
  3383. { // populate tolerations exists operator in annotations.
  3384. ObjectMeta: api.ObjectMeta{
  3385. Name: "123",
  3386. Namespace: "ns",
  3387. Annotations: map[string]string{
  3388. api.TolerationsAnnotationKey: `
  3389. [{
  3390. "key": "foo",
  3391. "operator": "Exists",
  3392. "effect": "NoSchedule"
  3393. }]`,
  3394. },
  3395. },
  3396. Spec: validPodSpec,
  3397. },
  3398. { // empty operator is ok for toleration
  3399. ObjectMeta: api.ObjectMeta{
  3400. Name: "123",
  3401. Namespace: "ns",
  3402. Annotations: map[string]string{
  3403. api.TolerationsAnnotationKey: `
  3404. [{
  3405. "key": "foo",
  3406. "value": "bar",
  3407. "effect": "NoSchedule"
  3408. }]`,
  3409. },
  3410. },
  3411. Spec: validPodSpec,
  3412. },
  3413. { // empty efffect is ok for toleration
  3414. ObjectMeta: api.ObjectMeta{
  3415. Name: "123",
  3416. Namespace: "ns",
  3417. Annotations: map[string]string{
  3418. api.TolerationsAnnotationKey: `
  3419. [{
  3420. "key": "foo",
  3421. "operator": "Equal",
  3422. "value": "bar"
  3423. }]`,
  3424. },
  3425. },
  3426. Spec: validPodSpec,
  3427. },
  3428. { // docker default seccomp profile
  3429. ObjectMeta: api.ObjectMeta{
  3430. Name: "123",
  3431. Namespace: "ns",
  3432. Annotations: map[string]string{
  3433. api.SeccompPodAnnotationKey: "docker/default",
  3434. },
  3435. },
  3436. Spec: validPodSpec,
  3437. },
  3438. { // unconfined seccomp profile
  3439. ObjectMeta: api.ObjectMeta{
  3440. Name: "123",
  3441. Namespace: "ns",
  3442. Annotations: map[string]string{
  3443. api.SeccompPodAnnotationKey: "unconfined",
  3444. },
  3445. },
  3446. Spec: validPodSpec,
  3447. },
  3448. { // localhost seccomp profile
  3449. ObjectMeta: api.ObjectMeta{
  3450. Name: "123",
  3451. Namespace: "ns",
  3452. Annotations: map[string]string{
  3453. api.SeccompPodAnnotationKey: "localhost/foo",
  3454. },
  3455. },
  3456. Spec: validPodSpec,
  3457. },
  3458. { // localhost seccomp profile for a container
  3459. ObjectMeta: api.ObjectMeta{
  3460. Name: "123",
  3461. Namespace: "ns",
  3462. Annotations: map[string]string{
  3463. api.SeccompContainerAnnotationKeyPrefix + "foo": "localhost/foo",
  3464. },
  3465. },
  3466. Spec: validPodSpec,
  3467. },
  3468. { // default AppArmor profile for a container
  3469. ObjectMeta: api.ObjectMeta{
  3470. Name: "123",
  3471. Namespace: "ns",
  3472. Annotations: map[string]string{
  3473. apparmor.ContainerAnnotationKeyPrefix + "ctr": apparmor.ProfileRuntimeDefault,
  3474. },
  3475. },
  3476. Spec: validPodSpec,
  3477. },
  3478. { // default AppArmor profile for an init container
  3479. ObjectMeta: api.ObjectMeta{
  3480. Name: "123",
  3481. Namespace: "ns",
  3482. Annotations: map[string]string{
  3483. apparmor.ContainerAnnotationKeyPrefix + "init-ctr": apparmor.ProfileRuntimeDefault,
  3484. },
  3485. },
  3486. Spec: api.PodSpec{
  3487. InitContainers: []api.Container{{Name: "init-ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}},
  3488. Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}},
  3489. RestartPolicy: api.RestartPolicyAlways,
  3490. DNSPolicy: api.DNSClusterFirst,
  3491. },
  3492. },
  3493. { // localhost AppArmor profile for a container
  3494. ObjectMeta: api.ObjectMeta{
  3495. Name: "123",
  3496. Namespace: "ns",
  3497. Annotations: map[string]string{
  3498. apparmor.ContainerAnnotationKeyPrefix + "ctr": apparmor.ProfileNamePrefix + "foo",
  3499. },
  3500. },
  3501. Spec: validPodSpec,
  3502. },
  3503. { // syntactically valid sysctls
  3504. ObjectMeta: api.ObjectMeta{
  3505. Name: "123",
  3506. Namespace: "ns",
  3507. Annotations: map[string]string{
  3508. api.SysctlsPodAnnotationKey: "kernel.shmmni=32768,kernel.shmmax=1000000000",
  3509. api.UnsafeSysctlsPodAnnotationKey: "knet.ipv4.route.min_pmtu=1000",
  3510. },
  3511. },
  3512. Spec: validPodSpec,
  3513. },
  3514. }
  3515. for _, pod := range successCases {
  3516. if errs := ValidatePod(&pod); len(errs) != 0 {
  3517. t.Errorf("expected success: %v", errs)
  3518. }
  3519. }
  3520. errorCases := map[string]api.Pod{
  3521. "bad name": {
  3522. ObjectMeta: api.ObjectMeta{Name: "", Namespace: "ns"},
  3523. Spec: api.PodSpec{
  3524. RestartPolicy: api.RestartPolicyAlways,
  3525. DNSPolicy: api.DNSClusterFirst,
  3526. Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}},
  3527. },
  3528. },
  3529. "bad namespace": {
  3530. ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: ""},
  3531. Spec: api.PodSpec{
  3532. RestartPolicy: api.RestartPolicyAlways,
  3533. DNSPolicy: api.DNSClusterFirst,
  3534. Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}},
  3535. },
  3536. },
  3537. "bad spec": {
  3538. ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: "ns"},
  3539. Spec: api.PodSpec{
  3540. Containers: []api.Container{{}},
  3541. },
  3542. },
  3543. "bad label": {
  3544. ObjectMeta: api.ObjectMeta{
  3545. Name: "abc",
  3546. Namespace: "ns",
  3547. Labels: map[string]string{
  3548. "NoUppercaseOrSpecialCharsLike=Equals": "bar",
  3549. },
  3550. },
  3551. Spec: api.PodSpec{
  3552. RestartPolicy: api.RestartPolicyAlways,
  3553. DNSPolicy: api.DNSClusterFirst,
  3554. Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}},
  3555. },
  3556. },
  3557. "invalid json of node affinity in pod annotations": {
  3558. ObjectMeta: api.ObjectMeta{
  3559. Name: "123",
  3560. Namespace: "ns",
  3561. Annotations: map[string]string{
  3562. api.AffinityAnnotationKey: `
  3563. {"nodeAffinity": {
  3564. "requiredDuringSchedulingIgnoredDuringExecution": {
  3565. "nodeSelectorTerms": [{
  3566. `,
  3567. },
  3568. },
  3569. Spec: validPodSpec,
  3570. },
  3571. "invalid node selector requirement in node affinity in pod annotations, operator can't be null": {
  3572. ObjectMeta: api.ObjectMeta{
  3573. Name: "123",
  3574. Namespace: "ns",
  3575. Annotations: map[string]string{
  3576. api.AffinityAnnotationKey: `
  3577. {"nodeAffinity": {"requiredDuringSchedulingIgnoredDuringExecution": {
  3578. "nodeSelectorTerms": [{
  3579. "matchExpressions": [{
  3580. "key": "key1",
  3581. }]
  3582. }]
  3583. }}}`,
  3584. },
  3585. },
  3586. Spec: validPodSpec,
  3587. },
  3588. "invalid preferredSchedulingTerm in node affinity in pod annotations, weight should be in range 1-100": {
  3589. ObjectMeta: api.ObjectMeta{
  3590. Name: "123",
  3591. Namespace: "ns",
  3592. Annotations: map[string]string{
  3593. api.AffinityAnnotationKey: `
  3594. {"nodeAffinity": {"preferredDuringSchedulingIgnoredDuringExecution": [
  3595. {
  3596. "weight": 199,
  3597. "preference": {"matchExpressions": [
  3598. {
  3599. "key": "foo",
  3600. "operator": "In",
  3601. "values": ["bar"]
  3602. }
  3603. ]}
  3604. }
  3605. ]}}`,
  3606. },
  3607. },
  3608. Spec: validPodSpec,
  3609. },
  3610. "invalid requiredDuringSchedulingIgnoredDuringExecution node selector, nodeSelectorTerms must have at least one term": {
  3611. ObjectMeta: api.ObjectMeta{
  3612. Name: "123",
  3613. Namespace: "ns",
  3614. Annotations: map[string]string{
  3615. api.AffinityAnnotationKey: `
  3616. {"nodeAffinity": {
  3617. "requiredDuringSchedulingIgnoredDuringExecution": {
  3618. "nodeSelectorTerms": []
  3619. },
  3620. }}`,
  3621. },
  3622. },
  3623. Spec: validPodSpec,
  3624. },
  3625. "invalid requiredDuringSchedulingIgnoredDuringExecution node selector term, matchExpressions must have at least one node selector requirement": {
  3626. ObjectMeta: api.ObjectMeta{
  3627. Name: "123",
  3628. Namespace: "ns",
  3629. Annotations: map[string]string{
  3630. api.AffinityAnnotationKey: `
  3631. {"nodeAffinity": {
  3632. "requiredDuringSchedulingIgnoredDuringExecution": {
  3633. "nodeSelectorTerms": [{
  3634. "matchExpressions": []
  3635. }]
  3636. },
  3637. }}`,
  3638. },
  3639. },
  3640. Spec: validPodSpec,
  3641. },
  3642. "invalid weight in preferredDuringSchedulingIgnoredDuringExecution in pod affinity annotations, weight should be in range 1-100": {
  3643. ObjectMeta: api.ObjectMeta{
  3644. Name: "123",
  3645. Namespace: "ns",
  3646. Annotations: map[string]string{
  3647. api.AffinityAnnotationKey: `
  3648. {"podAffinity": {"preferredDuringSchedulingIgnoredDuringExecution": [{
  3649. "weight": 109,
  3650. "podAffinityTerm":
  3651. {
  3652. "labelSelector": {
  3653. "matchExpressions": [{
  3654. "key": "key2",
  3655. "operator": "NotIn",
  3656. "values": ["value1", "value2"]
  3657. }]
  3658. },
  3659. "namespaces": ["ns"],
  3660. "topologyKey": "region"
  3661. }
  3662. }]}}`,
  3663. },
  3664. },
  3665. Spec: validPodSpec,
  3666. },
  3667. "invalid labelSelector in preferredDuringSchedulingIgnoredDuringExecution in podaffinity annotations, values should be empty if the operator is Exists": {
  3668. ObjectMeta: api.ObjectMeta{
  3669. Name: "123",
  3670. Namespace: "ns",
  3671. Annotations: map[string]string{
  3672. api.AffinityAnnotationKey: `
  3673. {"podAffinity": {"preferredDuringSchedulingIgnoredDuringExecution": [{
  3674. "weight": 10,
  3675. "podAffinityTerm":
  3676. {
  3677. "labelSelector": {
  3678. "matchExpressions": [{
  3679. "key": "key2",
  3680. "operator": "Exists",
  3681. "values": ["value1", "value2"]
  3682. }]
  3683. },
  3684. "namespaces": ["ns"],
  3685. "topologyKey": "region"
  3686. }
  3687. }]}}`,
  3688. },
  3689. },
  3690. Spec: validPodSpec,
  3691. },
  3692. "invalid name space in preferredDuringSchedulingIgnoredDuringExecution in podaffinity annotations, name space shouldbe valid": {
  3693. ObjectMeta: api.ObjectMeta{
  3694. Name: "123",
  3695. Namespace: "ns",
  3696. Annotations: map[string]string{
  3697. api.AffinityAnnotationKey: `
  3698. {"podAffinity": {"preferredDuringSchedulingIgnoredDuringExecution": [{
  3699. "weight": 10,
  3700. "podAffinityTerm":
  3701. {
  3702. "labelSelector": {
  3703. "matchExpressions": [{
  3704. "key": "key2",
  3705. "operator": "Exists",
  3706. "values": ["value1", "value2"]
  3707. }]
  3708. },
  3709. "namespaces": ["INVALID_NAMESPACE"],
  3710. "topologyKey": "region"
  3711. }
  3712. }]}}`,
  3713. },
  3714. },
  3715. Spec: validPodSpec,
  3716. },
  3717. "invalid labelOperator in preferredDuringSchedulingIgnoredDuringExecution in podantiaffinity annotations, labelOperator should be proper": {
  3718. ObjectMeta: api.ObjectMeta{
  3719. Name: "123",
  3720. Namespace: "ns",
  3721. Annotations: map[string]string{
  3722. api.AffinityAnnotationKey: `
  3723. {"podAntiAffinity": {"preferredDuringSchedulingIgnoredDuringExecution": [{
  3724. "weight": 10,
  3725. "podAffinityTerm":
  3726. {
  3727. "labelSelector": {
  3728. "matchExpressions": [{
  3729. "key": "key2",
  3730. "operator": "WrongOp",
  3731. "values": ["value1", "value2"]
  3732. }]
  3733. },
  3734. "namespaces": ["ns"],
  3735. "topologyKey": "region"
  3736. }
  3737. }]}}`,
  3738. },
  3739. },
  3740. Spec: validPodSpec,
  3741. },
  3742. "invalid pod affinity, empty topologyKey is not allowed for hard pod affinity": {
  3743. ObjectMeta: api.ObjectMeta{
  3744. Name: "123",
  3745. Namespace: "ns",
  3746. Annotations: map[string]string{
  3747. api.AffinityAnnotationKey: `
  3748. {"podAffinity": {"requiredDuringSchedulingIgnoredDuringExecution": [{
  3749. "weight": 10,
  3750. "podAffinityTerm":
  3751. {
  3752. "labelSelector": {
  3753. "matchExpressions": [{
  3754. "key": "key2",
  3755. "operator": "In",
  3756. "values": ["value1", "value2"]
  3757. }]
  3758. },
  3759. "namespaces": ["ns"],
  3760. "topologyKey": ""
  3761. }
  3762. }]}}`,
  3763. },
  3764. },
  3765. Spec: validPodSpec,
  3766. },
  3767. "invalid pod anti-affinity, empty topologyKey is not allowed for hard pod anti-affinity": {
  3768. ObjectMeta: api.ObjectMeta{
  3769. Name: "123",
  3770. Namespace: "ns",
  3771. Annotations: map[string]string{
  3772. api.AffinityAnnotationKey: `
  3773. {"podAntiAffinity": {"requiredDuringSchedulingIgnoredDuringExecution": [{
  3774. "weight": 10,
  3775. "podAffinityTerm":
  3776. {
  3777. "labelSelector": {
  3778. "matchExpressions": [{
  3779. "key": "key2",
  3780. "operator": "In",
  3781. "values": ["value1", "value2"]
  3782. }]
  3783. },
  3784. "namespaces": ["ns"],
  3785. "topologyKey": ""
  3786. }
  3787. }]}}`,
  3788. },
  3789. },
  3790. Spec: validPodSpec,
  3791. },
  3792. "invalid pod anti-affinity, empty topologyKey is not allowed for soft pod affinity": {
  3793. ObjectMeta: api.ObjectMeta{
  3794. Name: "123",
  3795. Namespace: "ns",
  3796. Annotations: map[string]string{
  3797. api.AffinityAnnotationKey: `
  3798. {"podAffinity": {"preferredDuringSchedulingIgnoredDuringExecution": [{
  3799. "weight": 10,
  3800. "podAffinityTerm":
  3801. {
  3802. "labelSelector": {
  3803. "matchExpressions": [{
  3804. "key": "key2",
  3805. "operator": "In",
  3806. "values": ["value1", "value2"]
  3807. }]
  3808. },
  3809. "namespaces": ["ns"],
  3810. "topologyKey": ""
  3811. }
  3812. }]}}`,
  3813. },
  3814. },
  3815. Spec: validPodSpec,
  3816. },
  3817. "invalid toleration key": {
  3818. ObjectMeta: api.ObjectMeta{
  3819. Name: "123",
  3820. Namespace: "ns",
  3821. Annotations: map[string]string{
  3822. api.TolerationsAnnotationKey: `
  3823. [{
  3824. "key": "nospecialchars^=@",
  3825. "operator": "Equal",
  3826. "value": "bar",
  3827. "effect": "NoSchedule"
  3828. }]`,
  3829. },
  3830. },
  3831. Spec: validPodSpec,
  3832. },
  3833. "invalid toleration operator": {
  3834. ObjectMeta: api.ObjectMeta{
  3835. Name: "123",
  3836. Namespace: "ns",
  3837. Annotations: map[string]string{
  3838. api.TolerationsAnnotationKey: `
  3839. [{
  3840. "key": "foo",
  3841. "operator": "In",
  3842. "value": "bar",
  3843. "effect": "NoSchedule"
  3844. }]`,
  3845. },
  3846. },
  3847. Spec: validPodSpec,
  3848. },
  3849. "value must be empty when `operator` is 'Exists'": {
  3850. ObjectMeta: api.ObjectMeta{
  3851. Name: "123",
  3852. Namespace: "ns",
  3853. Annotations: map[string]string{
  3854. api.TolerationsAnnotationKey: `
  3855. [{
  3856. "key": "foo",
  3857. "operator": "Exists",
  3858. "value": "bar",
  3859. "effect": "NoSchedule"
  3860. }]`,
  3861. },
  3862. },
  3863. Spec: validPodSpec,
  3864. },
  3865. "must be a valid pod seccomp profile": {
  3866. ObjectMeta: api.ObjectMeta{
  3867. Name: "123",
  3868. Namespace: "ns",
  3869. Annotations: map[string]string{
  3870. api.SeccompPodAnnotationKey: "foo",
  3871. },
  3872. },
  3873. Spec: validPodSpec,
  3874. },
  3875. "must be a valid container seccomp profile": {
  3876. ObjectMeta: api.ObjectMeta{
  3877. Name: "123",
  3878. Namespace: "ns",
  3879. Annotations: map[string]string{
  3880. api.SeccompContainerAnnotationKeyPrefix + "foo": "foo",
  3881. },
  3882. },
  3883. Spec: validPodSpec,
  3884. },
  3885. "must be a non-empty container name in seccomp annotation": {
  3886. ObjectMeta: api.ObjectMeta{
  3887. Name: "123",
  3888. Namespace: "ns",
  3889. Annotations: map[string]string{
  3890. api.SeccompContainerAnnotationKeyPrefix: "foo",
  3891. },
  3892. },
  3893. Spec: validPodSpec,
  3894. },
  3895. "must be a non-empty container profile in seccomp annotation": {
  3896. ObjectMeta: api.ObjectMeta{
  3897. Name: "123",
  3898. Namespace: "ns",
  3899. Annotations: map[string]string{
  3900. api.SeccompContainerAnnotationKeyPrefix + "foo": "",
  3901. },
  3902. },
  3903. Spec: validPodSpec,
  3904. },
  3905. "must be a relative path in a node-local seccomp profile annotation": {
  3906. ObjectMeta: api.ObjectMeta{
  3907. Name: "123",
  3908. Namespace: "ns",
  3909. Annotations: map[string]string{
  3910. api.SeccompPodAnnotationKey: "localhost//foo",
  3911. },
  3912. },
  3913. Spec: validPodSpec,
  3914. },
  3915. "must not start with '../'": {
  3916. ObjectMeta: api.ObjectMeta{
  3917. Name: "123",
  3918. Namespace: "ns",
  3919. Annotations: map[string]string{
  3920. api.SeccompPodAnnotationKey: "localhost/../foo",
  3921. },
  3922. },
  3923. Spec: validPodSpec,
  3924. },
  3925. "AppArmor profile must apply to a container": {
  3926. ObjectMeta: api.ObjectMeta{
  3927. Name: "123",
  3928. Namespace: "ns",
  3929. Annotations: map[string]string{
  3930. apparmor.ContainerAnnotationKeyPrefix + "ctr": apparmor.ProfileRuntimeDefault,
  3931. apparmor.ContainerAnnotationKeyPrefix + "init-ctr": apparmor.ProfileRuntimeDefault,
  3932. apparmor.ContainerAnnotationKeyPrefix + "fake-ctr": apparmor.ProfileRuntimeDefault,
  3933. },
  3934. },
  3935. Spec: api.PodSpec{
  3936. InitContainers: []api.Container{{Name: "init-ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}},
  3937. Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}},
  3938. RestartPolicy: api.RestartPolicyAlways,
  3939. DNSPolicy: api.DNSClusterFirst,
  3940. },
  3941. },
  3942. "AppArmor profile format must be valid": {
  3943. ObjectMeta: api.ObjectMeta{
  3944. Name: "123",
  3945. Namespace: "ns",
  3946. Annotations: map[string]string{
  3947. apparmor.ContainerAnnotationKeyPrefix + "ctr": "bad-name",
  3948. },
  3949. },
  3950. Spec: validPodSpec,
  3951. },
  3952. "only default AppArmor profile may start with runtime/": {
  3953. ObjectMeta: api.ObjectMeta{
  3954. Name: "123",
  3955. Namespace: "ns",
  3956. Annotations: map[string]string{
  3957. apparmor.ContainerAnnotationKeyPrefix + "ctr": "runtime/foo",
  3958. },
  3959. },
  3960. Spec: validPodSpec,
  3961. },
  3962. "invalid sysctl annotation": {
  3963. ObjectMeta: api.ObjectMeta{
  3964. Name: "123",
  3965. Namespace: "ns",
  3966. Annotations: map[string]string{
  3967. api.SysctlsPodAnnotationKey: "foo:",
  3968. },
  3969. },
  3970. Spec: validPodSpec,
  3971. },
  3972. "invalid comma-separated sysctl annotation": {
  3973. ObjectMeta: api.ObjectMeta{
  3974. Name: "123",
  3975. Namespace: "ns",
  3976. Annotations: map[string]string{
  3977. api.SysctlsPodAnnotationKey: "kernel.msgmax,",
  3978. },
  3979. },
  3980. Spec: validPodSpec,
  3981. },
  3982. "invalid unsafe sysctl annotation": {
  3983. ObjectMeta: api.ObjectMeta{
  3984. Name: "123",
  3985. Namespace: "ns",
  3986. Annotations: map[string]string{
  3987. api.SysctlsPodAnnotationKey: "foo:",
  3988. },
  3989. },
  3990. Spec: validPodSpec,
  3991. },
  3992. "intersecting safe sysctls and unsafe sysctls annotations": {
  3993. ObjectMeta: api.ObjectMeta{
  3994. Name: "123",
  3995. Namespace: "ns",
  3996. Annotations: map[string]string{
  3997. api.SysctlsPodAnnotationKey: "kernel.shmmax=10000000",
  3998. api.UnsafeSysctlsPodAnnotationKey: "kernel.shmmax=10000000",
  3999. },
  4000. },
  4001. Spec: validPodSpec,
  4002. },
  4003. }
  4004. for k, v := range errorCases {
  4005. if errs := ValidatePod(&v); len(errs) == 0 {
  4006. t.Errorf("expected failure for %q", k)
  4007. }
  4008. }
  4009. }
  4010. func TestValidatePodUpdate(t *testing.T) {
  4011. var (
  4012. activeDeadlineSecondsZero = int64(0)
  4013. activeDeadlineSecondsNegative = int64(-30)
  4014. activeDeadlineSecondsPositive = int64(30)
  4015. activeDeadlineSecondsLarger = int64(31)
  4016. now = unversioned.Now()
  4017. grace = int64(30)
  4018. grace2 = int64(31)
  4019. )
  4020. tests := []struct {
  4021. a api.Pod
  4022. b api.Pod
  4023. isValid bool
  4024. test string
  4025. }{
  4026. {api.Pod{}, api.Pod{}, true, "nothing"},
  4027. {
  4028. api.Pod{
  4029. ObjectMeta: api.ObjectMeta{Name: "foo"},
  4030. },
  4031. api.Pod{
  4032. ObjectMeta: api.ObjectMeta{Name: "bar"},
  4033. },
  4034. false,
  4035. "ids",
  4036. },
  4037. {
  4038. api.Pod{
  4039. ObjectMeta: api.ObjectMeta{
  4040. Name: "foo",
  4041. Labels: map[string]string{
  4042. "foo": "bar",
  4043. },
  4044. },
  4045. },
  4046. api.Pod{
  4047. ObjectMeta: api.ObjectMeta{
  4048. Name: "foo",
  4049. Labels: map[string]string{
  4050. "bar": "foo",
  4051. },
  4052. },
  4053. },
  4054. true,
  4055. "labels",
  4056. },
  4057. {
  4058. api.Pod{
  4059. ObjectMeta: api.ObjectMeta{
  4060. Name: "foo",
  4061. Annotations: map[string]string{
  4062. "foo": "bar",
  4063. },
  4064. },
  4065. },
  4066. api.Pod{
  4067. ObjectMeta: api.ObjectMeta{
  4068. Name: "foo",
  4069. Annotations: map[string]string{
  4070. "bar": "foo",
  4071. },
  4072. },
  4073. },
  4074. true,
  4075. "annotations",
  4076. },
  4077. {
  4078. api.Pod{
  4079. ObjectMeta: api.ObjectMeta{
  4080. Name: "foo",
  4081. },
  4082. Spec: api.PodSpec{
  4083. Containers: []api.Container{
  4084. {
  4085. Image: "foo:V1",
  4086. },
  4087. },
  4088. },
  4089. },
  4090. api.Pod{
  4091. ObjectMeta: api.ObjectMeta{Name: "foo"},
  4092. Spec: api.PodSpec{
  4093. Containers: []api.Container{
  4094. {
  4095. Image: "foo:V2",
  4096. },
  4097. {
  4098. Image: "bar:V2",
  4099. },
  4100. },
  4101. },
  4102. },
  4103. false,
  4104. "more containers",
  4105. },
  4106. {
  4107. api.Pod{
  4108. ObjectMeta: api.ObjectMeta{
  4109. Name: "foo",
  4110. },
  4111. Spec: api.PodSpec{
  4112. InitContainers: []api.Container{
  4113. {
  4114. Image: "foo:V1",
  4115. },
  4116. },
  4117. },
  4118. },
  4119. api.Pod{
  4120. ObjectMeta: api.ObjectMeta{Name: "foo"},
  4121. Spec: api.PodSpec{
  4122. InitContainers: []api.Container{
  4123. {
  4124. Image: "foo:V2",
  4125. },
  4126. {
  4127. Image: "bar:V2",
  4128. },
  4129. },
  4130. },
  4131. },
  4132. false,
  4133. "more init containers",
  4134. },
  4135. {
  4136. api.Pod{
  4137. ObjectMeta: api.ObjectMeta{Name: "foo"},
  4138. Spec: api.PodSpec{Containers: []api.Container{{Image: "foo:V1"}}},
  4139. },
  4140. api.Pod{
  4141. ObjectMeta: api.ObjectMeta{Name: "foo", DeletionTimestamp: &now},
  4142. Spec: api.PodSpec{Containers: []api.Container{{Image: "foo:V1"}}},
  4143. },
  4144. true,
  4145. "deletion timestamp filled out",
  4146. },
  4147. {
  4148. api.Pod{
  4149. ObjectMeta: api.ObjectMeta{Name: "foo", DeletionTimestamp: &now, DeletionGracePeriodSeconds: &grace},
  4150. Spec: api.PodSpec{Containers: []api.Container{{Image: "foo:V1"}}},
  4151. },
  4152. api.Pod{
  4153. ObjectMeta: api.ObjectMeta{Name: "foo", DeletionTimestamp: &now, DeletionGracePeriodSeconds: &grace2},
  4154. Spec: api.PodSpec{Containers: []api.Container{{Image: "foo:V1"}}},
  4155. },
  4156. false,
  4157. "deletion grace period seconds cleared",
  4158. },
  4159. {
  4160. api.Pod{
  4161. ObjectMeta: api.ObjectMeta{Name: "foo"},
  4162. Spec: api.PodSpec{
  4163. Containers: []api.Container{
  4164. {
  4165. Image: "foo:V1",
  4166. },
  4167. },
  4168. },
  4169. },
  4170. api.Pod{
  4171. ObjectMeta: api.ObjectMeta{Name: "foo"},
  4172. Spec: api.PodSpec{
  4173. Containers: []api.Container{
  4174. {
  4175. Image: "foo:V2",
  4176. },
  4177. },
  4178. },
  4179. },
  4180. true,
  4181. "image change",
  4182. },
  4183. {
  4184. api.Pod{
  4185. ObjectMeta: api.ObjectMeta{Name: "foo"},
  4186. Spec: api.PodSpec{
  4187. InitContainers: []api.Container{
  4188. {
  4189. Image: "foo:V1",
  4190. },
  4191. },
  4192. },
  4193. },
  4194. api.Pod{
  4195. ObjectMeta: api.ObjectMeta{Name: "foo"},
  4196. Spec: api.PodSpec{
  4197. InitContainers: []api.Container{
  4198. {
  4199. Image: "foo:V2",
  4200. },
  4201. },
  4202. },
  4203. },
  4204. true,
  4205. "init container image change",
  4206. },
  4207. {
  4208. api.Pod{
  4209. ObjectMeta: api.ObjectMeta{Name: "foo"},
  4210. Spec: api.PodSpec{
  4211. Containers: []api.Container{
  4212. {},
  4213. },
  4214. },
  4215. },
  4216. api.Pod{
  4217. ObjectMeta: api.ObjectMeta{Name: "foo"},
  4218. Spec: api.PodSpec{
  4219. Containers: []api.Container{
  4220. {
  4221. Image: "foo:V2",
  4222. },
  4223. },
  4224. },
  4225. },
  4226. false,
  4227. "image change to empty",
  4228. },
  4229. {
  4230. api.Pod{
  4231. ObjectMeta: api.ObjectMeta{Name: "foo"},
  4232. Spec: api.PodSpec{
  4233. InitContainers: []api.Container{
  4234. {},
  4235. },
  4236. },
  4237. },
  4238. api.Pod{
  4239. ObjectMeta: api.ObjectMeta{Name: "foo"},
  4240. Spec: api.PodSpec{
  4241. InitContainers: []api.Container{
  4242. {
  4243. Image: "foo:V2",
  4244. },
  4245. },
  4246. },
  4247. },
  4248. false,
  4249. "init container image change to empty",
  4250. },
  4251. {
  4252. api.Pod{
  4253. Spec: api.PodSpec{},
  4254. },
  4255. api.Pod{
  4256. Spec: api.PodSpec{},
  4257. },
  4258. true,
  4259. "activeDeadlineSeconds no change, nil",
  4260. },
  4261. {
  4262. api.Pod{
  4263. Spec: api.PodSpec{
  4264. ActiveDeadlineSeconds: &activeDeadlineSecondsPositive,
  4265. },
  4266. },
  4267. api.Pod{
  4268. Spec: api.PodSpec{
  4269. ActiveDeadlineSeconds: &activeDeadlineSecondsPositive,
  4270. },
  4271. },
  4272. true,
  4273. "activeDeadlineSeconds no change, set",
  4274. },
  4275. {
  4276. api.Pod{
  4277. Spec: api.PodSpec{
  4278. ActiveDeadlineSeconds: &activeDeadlineSecondsPositive,
  4279. },
  4280. },
  4281. api.Pod{},
  4282. true,
  4283. "activeDeadlineSeconds change to positive from nil",
  4284. },
  4285. {
  4286. api.Pod{
  4287. Spec: api.PodSpec{
  4288. ActiveDeadlineSeconds: &activeDeadlineSecondsPositive,
  4289. },
  4290. },
  4291. api.Pod{
  4292. Spec: api.PodSpec{
  4293. ActiveDeadlineSeconds: &activeDeadlineSecondsLarger,
  4294. },
  4295. },
  4296. true,
  4297. "activeDeadlineSeconds change to smaller positive",
  4298. },
  4299. {
  4300. api.Pod{
  4301. Spec: api.PodSpec{
  4302. ActiveDeadlineSeconds: &activeDeadlineSecondsLarger,
  4303. },
  4304. },
  4305. api.Pod{
  4306. Spec: api.PodSpec{
  4307. ActiveDeadlineSeconds: &activeDeadlineSecondsPositive,
  4308. },
  4309. },
  4310. false,
  4311. "activeDeadlineSeconds change to larger positive",
  4312. },
  4313. {
  4314. api.Pod{
  4315. Spec: api.PodSpec{
  4316. ActiveDeadlineSeconds: &activeDeadlineSecondsNegative,
  4317. },
  4318. },
  4319. api.Pod{},
  4320. false,
  4321. "activeDeadlineSeconds change to negative from nil",
  4322. },
  4323. {
  4324. api.Pod{
  4325. Spec: api.PodSpec{
  4326. ActiveDeadlineSeconds: &activeDeadlineSecondsNegative,
  4327. },
  4328. },
  4329. api.Pod{
  4330. Spec: api.PodSpec{
  4331. ActiveDeadlineSeconds: &activeDeadlineSecondsPositive,
  4332. },
  4333. },
  4334. false,
  4335. "activeDeadlineSeconds change to negative from positive",
  4336. },
  4337. {
  4338. api.Pod{
  4339. Spec: api.PodSpec{
  4340. ActiveDeadlineSeconds: &activeDeadlineSecondsZero,
  4341. },
  4342. },
  4343. api.Pod{
  4344. Spec: api.PodSpec{
  4345. ActiveDeadlineSeconds: &activeDeadlineSecondsPositive,
  4346. },
  4347. },
  4348. true,
  4349. "activeDeadlineSeconds change to zero from positive",
  4350. },
  4351. {
  4352. api.Pod{
  4353. Spec: api.PodSpec{
  4354. ActiveDeadlineSeconds: &activeDeadlineSecondsZero,
  4355. },
  4356. },
  4357. api.Pod{},
  4358. true,
  4359. "activeDeadlineSeconds change to zero from nil",
  4360. },
  4361. {
  4362. api.Pod{},
  4363. api.Pod{
  4364. Spec: api.PodSpec{
  4365. ActiveDeadlineSeconds: &activeDeadlineSecondsPositive,
  4366. },
  4367. },
  4368. false,
  4369. "activeDeadlineSeconds change to nil from positive",
  4370. },
  4371. {
  4372. api.Pod{
  4373. ObjectMeta: api.ObjectMeta{Name: "foo"},
  4374. Spec: api.PodSpec{
  4375. Containers: []api.Container{
  4376. {
  4377. Image: "foo:V1",
  4378. Resources: api.ResourceRequirements{
  4379. Limits: getResourceLimits("100m", "0"),
  4380. },
  4381. },
  4382. },
  4383. },
  4384. },
  4385. api.Pod{
  4386. ObjectMeta: api.ObjectMeta{Name: "foo"},
  4387. Spec: api.PodSpec{
  4388. Containers: []api.Container{
  4389. {
  4390. Image: "foo:V2",
  4391. Resources: api.ResourceRequirements{
  4392. Limits: getResourceLimits("1000m", "0"),
  4393. },
  4394. },
  4395. },
  4396. },
  4397. },
  4398. false,
  4399. "cpu change",
  4400. },
  4401. {
  4402. api.Pod{
  4403. ObjectMeta: api.ObjectMeta{Name: "foo"},
  4404. Spec: api.PodSpec{
  4405. Containers: []api.Container{
  4406. {
  4407. Image: "foo:V1",
  4408. Ports: []api.ContainerPort{
  4409. {HostPort: 8080, ContainerPort: 80},
  4410. },
  4411. },
  4412. },
  4413. },
  4414. },
  4415. api.Pod{
  4416. ObjectMeta: api.ObjectMeta{Name: "foo"},
  4417. Spec: api.PodSpec{
  4418. Containers: []api.Container{
  4419. {
  4420. Image: "foo:V2",
  4421. Ports: []api.ContainerPort{
  4422. {HostPort: 8000, ContainerPort: 80},
  4423. },
  4424. },
  4425. },
  4426. },
  4427. },
  4428. false,
  4429. "port change",
  4430. },
  4431. {
  4432. api.Pod{
  4433. ObjectMeta: api.ObjectMeta{
  4434. Name: "foo",
  4435. Labels: map[string]string{
  4436. "foo": "bar",
  4437. },
  4438. },
  4439. },
  4440. api.Pod{
  4441. ObjectMeta: api.ObjectMeta{
  4442. Name: "foo",
  4443. Labels: map[string]string{
  4444. "Bar": "foo",
  4445. },
  4446. },
  4447. },
  4448. true,
  4449. "bad label change",
  4450. },
  4451. }
  4452. for _, test := range tests {
  4453. test.a.ObjectMeta.ResourceVersion = "1"
  4454. test.b.ObjectMeta.ResourceVersion = "1"
  4455. errs := ValidatePodUpdate(&test.a, &test.b)
  4456. if test.isValid {
  4457. if len(errs) != 0 {
  4458. t.Errorf("unexpected invalid: %s (%+v)\nA: %+v\nB: %+v", test.test, errs, test.a, test.b)
  4459. }
  4460. } else {
  4461. if len(errs) == 0 {
  4462. t.Errorf("unexpected valid: %s\nA: %+v\nB: %+v", test.test, test.a, test.b)
  4463. }
  4464. }
  4465. }
  4466. }
  4467. func makeValidService() api.Service {
  4468. return api.Service{
  4469. ObjectMeta: api.ObjectMeta{
  4470. Name: "valid",
  4471. Namespace: "valid",
  4472. Labels: map[string]string{},
  4473. Annotations: map[string]string{},
  4474. ResourceVersion: "1",
  4475. },
  4476. Spec: api.ServiceSpec{
  4477. Selector: map[string]string{"key": "val"},
  4478. SessionAffinity: "None",
  4479. Type: api.ServiceTypeClusterIP,
  4480. Ports: []api.ServicePort{{Name: "p", Protocol: "TCP", Port: 8675, TargetPort: intstr.FromInt(8675)}},
  4481. },
  4482. }
  4483. }
  4484. func TestValidateService(t *testing.T) {
  4485. testCases := []struct {
  4486. name string
  4487. tweakSvc func(svc *api.Service) // given a basic valid service, each test case can customize it
  4488. numErrs int
  4489. }{
  4490. {
  4491. name: "missing namespace",
  4492. tweakSvc: func(s *api.Service) {
  4493. s.Namespace = ""
  4494. },
  4495. numErrs: 1,
  4496. },
  4497. {
  4498. name: "invalid namespace",
  4499. tweakSvc: func(s *api.Service) {
  4500. s.Namespace = "-123"
  4501. },
  4502. numErrs: 1,
  4503. },
  4504. {
  4505. name: "missing name",
  4506. tweakSvc: func(s *api.Service) {
  4507. s.Name = ""
  4508. },
  4509. numErrs: 1,
  4510. },
  4511. {
  4512. name: "invalid name",
  4513. tweakSvc: func(s *api.Service) {
  4514. s.Name = "-123"
  4515. },
  4516. numErrs: 1,
  4517. },
  4518. {
  4519. name: "too long name",
  4520. tweakSvc: func(s *api.Service) {
  4521. s.Name = strings.Repeat("a", 64)
  4522. },
  4523. numErrs: 1,
  4524. },
  4525. {
  4526. name: "invalid generateName",
  4527. tweakSvc: func(s *api.Service) {
  4528. s.GenerateName = "-123"
  4529. },
  4530. numErrs: 1,
  4531. },
  4532. {
  4533. name: "too long generateName",
  4534. tweakSvc: func(s *api.Service) {
  4535. s.GenerateName = strings.Repeat("a", 64)
  4536. },
  4537. numErrs: 1,
  4538. },
  4539. {
  4540. name: "invalid label",
  4541. tweakSvc: func(s *api.Service) {
  4542. s.Labels["NoUppercaseOrSpecialCharsLike=Equals"] = "bar"
  4543. },
  4544. numErrs: 1,
  4545. },
  4546. {
  4547. name: "invalid annotation",
  4548. tweakSvc: func(s *api.Service) {
  4549. s.Annotations["NoSpecialCharsLike=Equals"] = "bar"
  4550. },
  4551. numErrs: 1,
  4552. },
  4553. {
  4554. name: "nil selector",
  4555. tweakSvc: func(s *api.Service) {
  4556. s.Spec.Selector = nil
  4557. },
  4558. numErrs: 0,
  4559. },
  4560. {
  4561. name: "invalid selector",
  4562. tweakSvc: func(s *api.Service) {
  4563. s.Spec.Selector["NoSpecialCharsLike=Equals"] = "bar"
  4564. },
  4565. numErrs: 1,
  4566. },
  4567. {
  4568. name: "missing session affinity",
  4569. tweakSvc: func(s *api.Service) {
  4570. s.Spec.SessionAffinity = ""
  4571. },
  4572. numErrs: 1,
  4573. },
  4574. {
  4575. name: "missing type",
  4576. tweakSvc: func(s *api.Service) {
  4577. s.Spec.Type = ""
  4578. },
  4579. numErrs: 1,
  4580. },
  4581. {
  4582. name: "missing ports",
  4583. tweakSvc: func(s *api.Service) {
  4584. s.Spec.Ports = nil
  4585. },
  4586. numErrs: 1,
  4587. },
  4588. {
  4589. name: "missing ports but headless",
  4590. tweakSvc: func(s *api.Service) {
  4591. s.Spec.Ports = nil
  4592. s.Spec.ClusterIP = api.ClusterIPNone
  4593. },
  4594. numErrs: 0,
  4595. },
  4596. {
  4597. name: "empty port[0] name",
  4598. tweakSvc: func(s *api.Service) {
  4599. s.Spec.Ports[0].Name = ""
  4600. },
  4601. numErrs: 0,
  4602. },
  4603. {
  4604. name: "empty port[1] name",
  4605. tweakSvc: func(s *api.Service) {
  4606. s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "", Protocol: "TCP", Port: 12345, TargetPort: intstr.FromInt(12345)})
  4607. },
  4608. numErrs: 1,
  4609. },
  4610. {
  4611. name: "empty multi-port port[0] name",
  4612. tweakSvc: func(s *api.Service) {
  4613. s.Spec.Ports[0].Name = ""
  4614. s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "p", Protocol: "TCP", Port: 12345, TargetPort: intstr.FromInt(12345)})
  4615. },
  4616. numErrs: 1,
  4617. },
  4618. {
  4619. name: "invalid port name",
  4620. tweakSvc: func(s *api.Service) {
  4621. s.Spec.Ports[0].Name = "INVALID"
  4622. },
  4623. numErrs: 1,
  4624. },
  4625. {
  4626. name: "missing protocol",
  4627. tweakSvc: func(s *api.Service) {
  4628. s.Spec.Ports[0].Protocol = ""
  4629. },
  4630. numErrs: 1,
  4631. },
  4632. {
  4633. name: "invalid protocol",
  4634. tweakSvc: func(s *api.Service) {
  4635. s.Spec.Ports[0].Protocol = "INVALID"
  4636. },
  4637. numErrs: 1,
  4638. },
  4639. {
  4640. name: "invalid cluster ip",
  4641. tweakSvc: func(s *api.Service) {
  4642. s.Spec.ClusterIP = "invalid"
  4643. },
  4644. numErrs: 1,
  4645. },
  4646. {
  4647. name: "missing port",
  4648. tweakSvc: func(s *api.Service) {
  4649. s.Spec.Ports[0].Port = 0
  4650. },
  4651. numErrs: 1,
  4652. },
  4653. {
  4654. name: "invalid port",
  4655. tweakSvc: func(s *api.Service) {
  4656. s.Spec.Ports[0].Port = 65536
  4657. },
  4658. numErrs: 1,
  4659. },
  4660. {
  4661. name: "invalid TargetPort int",
  4662. tweakSvc: func(s *api.Service) {
  4663. s.Spec.Ports[0].TargetPort = intstr.FromInt(65536)
  4664. },
  4665. numErrs: 1,
  4666. },
  4667. {
  4668. name: "valid port headless",
  4669. tweakSvc: func(s *api.Service) {
  4670. s.Spec.Ports[0].Port = 11722
  4671. s.Spec.Ports[0].TargetPort = intstr.FromInt(11722)
  4672. s.Spec.ClusterIP = api.ClusterIPNone
  4673. },
  4674. numErrs: 0,
  4675. },
  4676. {
  4677. name: "invalid port headless 1",
  4678. tweakSvc: func(s *api.Service) {
  4679. s.Spec.Ports[0].Port = 11722
  4680. s.Spec.Ports[0].TargetPort = intstr.FromInt(11721)
  4681. s.Spec.ClusterIP = api.ClusterIPNone
  4682. },
  4683. // in the v1 API, targetPorts on headless services were tolerated.
  4684. // once we have version-specific validation, we can reject this on newer API versions, but until then, we have to tolerate it for compatibility.
  4685. // numErrs: 1,
  4686. numErrs: 0,
  4687. },
  4688. {
  4689. name: "invalid port headless 2",
  4690. tweakSvc: func(s *api.Service) {
  4691. s.Spec.Ports[0].Port = 11722
  4692. s.Spec.Ports[0].TargetPort = intstr.FromString("target")
  4693. s.Spec.ClusterIP = api.ClusterIPNone
  4694. },
  4695. // in the v1 API, targetPorts on headless services were tolerated.
  4696. // once we have version-specific validation, we can reject this on newer API versions, but until then, we have to tolerate it for compatibility.
  4697. // numErrs: 1,
  4698. numErrs: 0,
  4699. },
  4700. {
  4701. name: "invalid publicIPs localhost",
  4702. tweakSvc: func(s *api.Service) {
  4703. s.Spec.ExternalIPs = []string{"127.0.0.1"}
  4704. },
  4705. numErrs: 1,
  4706. },
  4707. {
  4708. name: "invalid publicIPs unspecified",
  4709. tweakSvc: func(s *api.Service) {
  4710. s.Spec.ExternalIPs = []string{"0.0.0.0"}
  4711. },
  4712. numErrs: 1,
  4713. },
  4714. {
  4715. name: "invalid publicIPs loopback",
  4716. tweakSvc: func(s *api.Service) {
  4717. s.Spec.ExternalIPs = []string{"127.0.0.1"}
  4718. },
  4719. numErrs: 1,
  4720. },
  4721. {
  4722. name: "invalid publicIPs host",
  4723. tweakSvc: func(s *api.Service) {
  4724. s.Spec.ExternalIPs = []string{"myhost.mydomain"}
  4725. },
  4726. numErrs: 1,
  4727. },
  4728. {
  4729. name: "dup port name",
  4730. tweakSvc: func(s *api.Service) {
  4731. s.Spec.Ports[0].Name = "p"
  4732. s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "p", Port: 12345, Protocol: "TCP", TargetPort: intstr.FromInt(12345)})
  4733. },
  4734. numErrs: 1,
  4735. },
  4736. {
  4737. name: "valid load balancer protocol UDP 1",
  4738. tweakSvc: func(s *api.Service) {
  4739. s.Spec.Type = api.ServiceTypeLoadBalancer
  4740. s.Spec.Ports[0].Protocol = "UDP"
  4741. },
  4742. numErrs: 0,
  4743. },
  4744. {
  4745. name: "valid load balancer protocol UDP 2",
  4746. tweakSvc: func(s *api.Service) {
  4747. s.Spec.Type = api.ServiceTypeLoadBalancer
  4748. s.Spec.Ports[0] = api.ServicePort{Name: "q", Port: 12345, Protocol: "UDP", TargetPort: intstr.FromInt(12345)}
  4749. },
  4750. numErrs: 0,
  4751. },
  4752. {
  4753. name: "invalid load balancer with mix protocol",
  4754. tweakSvc: func(s *api.Service) {
  4755. s.Spec.Type = api.ServiceTypeLoadBalancer
  4756. s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "q", Port: 12345, Protocol: "UDP", TargetPort: intstr.FromInt(12345)})
  4757. },
  4758. numErrs: 1,
  4759. },
  4760. {
  4761. name: "valid 1",
  4762. tweakSvc: func(s *api.Service) {
  4763. // do nothing
  4764. },
  4765. numErrs: 0,
  4766. },
  4767. {
  4768. name: "valid 2",
  4769. tweakSvc: func(s *api.Service) {
  4770. s.Spec.Ports[0].Protocol = "UDP"
  4771. s.Spec.Ports[0].TargetPort = intstr.FromInt(12345)
  4772. },
  4773. numErrs: 0,
  4774. },
  4775. {
  4776. name: "valid 3",
  4777. tweakSvc: func(s *api.Service) {
  4778. s.Spec.Ports[0].TargetPort = intstr.FromString("http")
  4779. },
  4780. numErrs: 0,
  4781. },
  4782. {
  4783. name: "valid cluster ip - none ",
  4784. tweakSvc: func(s *api.Service) {
  4785. s.Spec.ClusterIP = "None"
  4786. },
  4787. numErrs: 0,
  4788. },
  4789. {
  4790. name: "valid cluster ip - empty",
  4791. tweakSvc: func(s *api.Service) {
  4792. s.Spec.ClusterIP = ""
  4793. s.Spec.Ports[0].TargetPort = intstr.FromString("http")
  4794. },
  4795. numErrs: 0,
  4796. },
  4797. {
  4798. name: "valid type - cluster",
  4799. tweakSvc: func(s *api.Service) {
  4800. s.Spec.Type = api.ServiceTypeClusterIP
  4801. },
  4802. numErrs: 0,
  4803. },
  4804. {
  4805. name: "valid type - loadbalancer",
  4806. tweakSvc: func(s *api.Service) {
  4807. s.Spec.Type = api.ServiceTypeLoadBalancer
  4808. },
  4809. numErrs: 0,
  4810. },
  4811. {
  4812. name: "valid type loadbalancer 2 ports",
  4813. tweakSvc: func(s *api.Service) {
  4814. s.Spec.Type = api.ServiceTypeLoadBalancer
  4815. s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "q", Port: 12345, Protocol: "TCP", TargetPort: intstr.FromInt(12345)})
  4816. },
  4817. numErrs: 0,
  4818. },
  4819. {
  4820. name: "valid external load balancer 2 ports",
  4821. tweakSvc: func(s *api.Service) {
  4822. s.Spec.Type = api.ServiceTypeLoadBalancer
  4823. s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "q", Port: 12345, Protocol: "TCP", TargetPort: intstr.FromInt(12345)})
  4824. },
  4825. numErrs: 0,
  4826. },
  4827. {
  4828. name: "duplicate nodeports",
  4829. tweakSvc: func(s *api.Service) {
  4830. s.Spec.Type = api.ServiceTypeNodePort
  4831. s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "q", Port: 1, Protocol: "TCP", NodePort: 1, TargetPort: intstr.FromInt(1)})
  4832. s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "r", Port: 2, Protocol: "TCP", NodePort: 1, TargetPort: intstr.FromInt(2)})
  4833. },
  4834. numErrs: 1,
  4835. },
  4836. {
  4837. name: "duplicate nodeports (different protocols)",
  4838. tweakSvc: func(s *api.Service) {
  4839. s.Spec.Type = api.ServiceTypeNodePort
  4840. s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "q", Port: 1, Protocol: "TCP", NodePort: 1, TargetPort: intstr.FromInt(1)})
  4841. s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "r", Port: 2, Protocol: "UDP", NodePort: 1, TargetPort: intstr.FromInt(2)})
  4842. },
  4843. numErrs: 0,
  4844. },
  4845. {
  4846. name: "valid type - cluster",
  4847. tweakSvc: func(s *api.Service) {
  4848. s.Spec.Type = api.ServiceTypeClusterIP
  4849. },
  4850. numErrs: 0,
  4851. },
  4852. {
  4853. name: "valid type - nodeport",
  4854. tweakSvc: func(s *api.Service) {
  4855. s.Spec.Type = api.ServiceTypeNodePort
  4856. },
  4857. numErrs: 0,
  4858. },
  4859. {
  4860. name: "valid type - loadbalancer",
  4861. tweakSvc: func(s *api.Service) {
  4862. s.Spec.Type = api.ServiceTypeLoadBalancer
  4863. },
  4864. numErrs: 0,
  4865. },
  4866. {
  4867. name: "valid type loadbalancer 2 ports",
  4868. tweakSvc: func(s *api.Service) {
  4869. s.Spec.Type = api.ServiceTypeLoadBalancer
  4870. s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "q", Port: 12345, Protocol: "TCP", TargetPort: intstr.FromInt(12345)})
  4871. },
  4872. numErrs: 0,
  4873. },
  4874. {
  4875. name: "valid type loadbalancer with NodePort",
  4876. tweakSvc: func(s *api.Service) {
  4877. s.Spec.Type = api.ServiceTypeLoadBalancer
  4878. s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "q", Port: 12345, Protocol: "TCP", NodePort: 12345, TargetPort: intstr.FromInt(12345)})
  4879. },
  4880. numErrs: 0,
  4881. },
  4882. {
  4883. name: "valid type=NodePort service with NodePort",
  4884. tweakSvc: func(s *api.Service) {
  4885. s.Spec.Type = api.ServiceTypeNodePort
  4886. s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "q", Port: 12345, Protocol: "TCP", NodePort: 12345, TargetPort: intstr.FromInt(12345)})
  4887. },
  4888. numErrs: 0,
  4889. },
  4890. {
  4891. name: "valid type=NodePort service without NodePort",
  4892. tweakSvc: func(s *api.Service) {
  4893. s.Spec.Type = api.ServiceTypeNodePort
  4894. s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "q", Port: 12345, Protocol: "TCP", TargetPort: intstr.FromInt(12345)})
  4895. },
  4896. numErrs: 0,
  4897. },
  4898. {
  4899. name: "valid cluster service without NodePort",
  4900. tweakSvc: func(s *api.Service) {
  4901. s.Spec.Type = api.ServiceTypeClusterIP
  4902. s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "q", Port: 12345, Protocol: "TCP", TargetPort: intstr.FromInt(12345)})
  4903. },
  4904. numErrs: 0,
  4905. },
  4906. {
  4907. name: "invalid cluster service with NodePort",
  4908. tweakSvc: func(s *api.Service) {
  4909. s.Spec.Type = api.ServiceTypeClusterIP
  4910. s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "q", Port: 12345, Protocol: "TCP", NodePort: 12345, TargetPort: intstr.FromInt(12345)})
  4911. },
  4912. numErrs: 1,
  4913. },
  4914. {
  4915. name: "invalid public service with duplicate NodePort",
  4916. tweakSvc: func(s *api.Service) {
  4917. s.Spec.Type = api.ServiceTypeNodePort
  4918. s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "p1", Port: 1, Protocol: "TCP", NodePort: 1, TargetPort: intstr.FromInt(1)})
  4919. s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "p2", Port: 2, Protocol: "TCP", NodePort: 1, TargetPort: intstr.FromInt(2)})
  4920. },
  4921. numErrs: 1,
  4922. },
  4923. {
  4924. name: "valid type=LoadBalancer",
  4925. tweakSvc: func(s *api.Service) {
  4926. s.Spec.Type = api.ServiceTypeLoadBalancer
  4927. s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "q", Port: 12345, Protocol: "TCP", TargetPort: intstr.FromInt(12345)})
  4928. },
  4929. numErrs: 0,
  4930. },
  4931. {
  4932. // For now we open firewalls, and its insecure if we open 10250, remove this
  4933. // when we have better protections in place.
  4934. name: "invalid port type=LoadBalancer",
  4935. tweakSvc: func(s *api.Service) {
  4936. s.Spec.Type = api.ServiceTypeLoadBalancer
  4937. s.Spec.Ports = append(s.Spec.Ports, api.ServicePort{Name: "kubelet", Port: 10250, Protocol: "TCP", TargetPort: intstr.FromInt(12345)})
  4938. },
  4939. numErrs: 1,
  4940. },
  4941. {
  4942. name: "valid LoadBalancer source range annotation",
  4943. tweakSvc: func(s *api.Service) {
  4944. s.Spec.Type = api.ServiceTypeLoadBalancer
  4945. s.Annotations[service.AnnotationLoadBalancerSourceRangesKey] = "1.2.3.4/8, 5.6.7.8/16"
  4946. },
  4947. numErrs: 0,
  4948. },
  4949. {
  4950. name: "empty LoadBalancer source range annotation",
  4951. tweakSvc: func(s *api.Service) {
  4952. s.Spec.Type = api.ServiceTypeLoadBalancer
  4953. s.Annotations[service.AnnotationLoadBalancerSourceRangesKey] = ""
  4954. },
  4955. numErrs: 0,
  4956. },
  4957. {
  4958. name: "invalid LoadBalancer source range annotation (hostname)",
  4959. tweakSvc: func(s *api.Service) {
  4960. s.Annotations[service.AnnotationLoadBalancerSourceRangesKey] = "foo.bar"
  4961. },
  4962. numErrs: 2,
  4963. },
  4964. {
  4965. name: "invalid LoadBalancer source range annotation (invalid CIDR)",
  4966. tweakSvc: func(s *api.Service) {
  4967. s.Spec.Type = api.ServiceTypeLoadBalancer
  4968. s.Annotations[service.AnnotationLoadBalancerSourceRangesKey] = "1.2.3.4/33"
  4969. },
  4970. numErrs: 1,
  4971. },
  4972. {
  4973. name: "invalid source range for non LoadBalancer type service",
  4974. tweakSvc: func(s *api.Service) {
  4975. s.Spec.LoadBalancerSourceRanges = []string{"1.2.3.4/8", "5.6.7.8/16"}
  4976. },
  4977. numErrs: 1,
  4978. },
  4979. {
  4980. name: "valid LoadBalancer source range",
  4981. tweakSvc: func(s *api.Service) {
  4982. s.Spec.Type = api.ServiceTypeLoadBalancer
  4983. s.Spec.LoadBalancerSourceRanges = []string{"1.2.3.4/8", "5.6.7.8/16"}
  4984. },
  4985. numErrs: 0,
  4986. },
  4987. {
  4988. name: "empty LoadBalancer source range",
  4989. tweakSvc: func(s *api.Service) {
  4990. s.Spec.Type = api.ServiceTypeLoadBalancer
  4991. s.Spec.LoadBalancerSourceRanges = []string{" "}
  4992. },
  4993. numErrs: 1,
  4994. },
  4995. {
  4996. name: "invalid LoadBalancer source range",
  4997. tweakSvc: func(s *api.Service) {
  4998. s.Spec.Type = api.ServiceTypeLoadBalancer
  4999. s.Spec.LoadBalancerSourceRanges = []string{"foo.bar"}
  5000. },
  5001. numErrs: 1,
  5002. },
  5003. {
  5004. name: "valid ExternalName",
  5005. tweakSvc: func(s *api.Service) {
  5006. s.Spec.Type = api.ServiceTypeExternalName
  5007. s.Spec.ClusterIP = ""
  5008. s.Spec.ExternalName = "foo.bar.example.com"
  5009. },
  5010. numErrs: 0,
  5011. },
  5012. {
  5013. name: "invalid ExternalName clusterIP (valid IP)",
  5014. tweakSvc: func(s *api.Service) {
  5015. s.Spec.Type = api.ServiceTypeExternalName
  5016. s.Spec.ClusterIP = "1.2.3.4"
  5017. s.Spec.ExternalName = "foo.bar.example.com"
  5018. },
  5019. numErrs: 1,
  5020. },
  5021. {
  5022. name: "invalid ExternalName clusterIP (None)",
  5023. tweakSvc: func(s *api.Service) {
  5024. s.Spec.Type = api.ServiceTypeExternalName
  5025. s.Spec.ClusterIP = "None"
  5026. s.Spec.ExternalName = "foo.bar.example.com"
  5027. },
  5028. numErrs: 1,
  5029. },
  5030. {
  5031. name: "invalid ExternalName (not a DNS name)",
  5032. tweakSvc: func(s *api.Service) {
  5033. s.Spec.Type = api.ServiceTypeExternalName
  5034. s.Spec.ClusterIP = ""
  5035. s.Spec.ExternalName = "-123"
  5036. },
  5037. numErrs: 1,
  5038. },
  5039. }
  5040. for _, tc := range testCases {
  5041. svc := makeValidService()
  5042. tc.tweakSvc(&svc)
  5043. errs := ValidateService(&svc)
  5044. if len(errs) != tc.numErrs {
  5045. t.Errorf("Unexpected error list for case %q: %v", tc.name, errs.ToAggregate())
  5046. }
  5047. }
  5048. }
  5049. func TestValidateReplicationControllerStatusUpdate(t *testing.T) {
  5050. validSelector := map[string]string{"a": "b"}
  5051. validPodTemplate := api.PodTemplate{
  5052. Template: api.PodTemplateSpec{
  5053. ObjectMeta: api.ObjectMeta{
  5054. Labels: validSelector,
  5055. },
  5056. Spec: api.PodSpec{
  5057. RestartPolicy: api.RestartPolicyAlways,
  5058. DNSPolicy: api.DNSClusterFirst,
  5059. Containers: []api.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent"}},
  5060. },
  5061. },
  5062. }
  5063. type rcUpdateTest struct {
  5064. old api.ReplicationController
  5065. update api.ReplicationController
  5066. }
  5067. successCases := []rcUpdateTest{
  5068. {
  5069. old: api.ReplicationController{
  5070. ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault},
  5071. Spec: api.ReplicationControllerSpec{
  5072. Selector: validSelector,
  5073. Template: &validPodTemplate.Template,
  5074. },
  5075. Status: api.ReplicationControllerStatus{
  5076. Replicas: 2,
  5077. },
  5078. },
  5079. update: api.ReplicationController{
  5080. ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault},
  5081. Spec: api.ReplicationControllerSpec{
  5082. Replicas: 3,
  5083. Selector: validSelector,
  5084. Template: &validPodTemplate.Template,
  5085. },
  5086. Status: api.ReplicationControllerStatus{
  5087. Replicas: 4,
  5088. },
  5089. },
  5090. },
  5091. }
  5092. for _, successCase := range successCases {
  5093. successCase.old.ObjectMeta.ResourceVersion = "1"
  5094. successCase.update.ObjectMeta.ResourceVersion = "1"
  5095. if errs := ValidateReplicationControllerStatusUpdate(&successCase.update, &successCase.old); len(errs) != 0 {
  5096. t.Errorf("expected success: %v", errs)
  5097. }
  5098. }
  5099. errorCases := map[string]rcUpdateTest{
  5100. "negative replicas": {
  5101. old: api.ReplicationController{
  5102. ObjectMeta: api.ObjectMeta{Name: "", Namespace: api.NamespaceDefault},
  5103. Spec: api.ReplicationControllerSpec{
  5104. Selector: validSelector,
  5105. Template: &validPodTemplate.Template,
  5106. },
  5107. Status: api.ReplicationControllerStatus{
  5108. Replicas: 3,
  5109. },
  5110. },
  5111. update: api.ReplicationController{
  5112. ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault},
  5113. Spec: api.ReplicationControllerSpec{
  5114. Replicas: 2,
  5115. Selector: validSelector,
  5116. Template: &validPodTemplate.Template,
  5117. },
  5118. Status: api.ReplicationControllerStatus{
  5119. Replicas: -3,
  5120. },
  5121. },
  5122. },
  5123. }
  5124. for testName, errorCase := range errorCases {
  5125. if errs := ValidateReplicationControllerStatusUpdate(&errorCase.update, &errorCase.old); len(errs) == 0 {
  5126. t.Errorf("expected failure: %s", testName)
  5127. }
  5128. }
  5129. }
  5130. func TestValidateReplicationControllerUpdate(t *testing.T) {
  5131. validSelector := map[string]string{"a": "b"}
  5132. validPodTemplate := api.PodTemplate{
  5133. Template: api.PodTemplateSpec{
  5134. ObjectMeta: api.ObjectMeta{
  5135. Labels: validSelector,
  5136. },
  5137. Spec: api.PodSpec{
  5138. RestartPolicy: api.RestartPolicyAlways,
  5139. DNSPolicy: api.DNSClusterFirst,
  5140. Containers: []api.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent"}},
  5141. },
  5142. },
  5143. }
  5144. readWriteVolumePodTemplate := api.PodTemplate{
  5145. Template: api.PodTemplateSpec{
  5146. ObjectMeta: api.ObjectMeta{
  5147. Labels: validSelector,
  5148. },
  5149. Spec: api.PodSpec{
  5150. RestartPolicy: api.RestartPolicyAlways,
  5151. DNSPolicy: api.DNSClusterFirst,
  5152. Containers: []api.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent"}},
  5153. Volumes: []api.Volume{{Name: "gcepd", VolumeSource: api.VolumeSource{GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{PDName: "my-PD", FSType: "ext4", Partition: 1, ReadOnly: false}}}},
  5154. },
  5155. },
  5156. }
  5157. invalidSelector := map[string]string{"NoUppercaseOrSpecialCharsLike=Equals": "b"}
  5158. invalidPodTemplate := api.PodTemplate{
  5159. Template: api.PodTemplateSpec{
  5160. Spec: api.PodSpec{
  5161. RestartPolicy: api.RestartPolicyAlways,
  5162. DNSPolicy: api.DNSClusterFirst,
  5163. },
  5164. ObjectMeta: api.ObjectMeta{
  5165. Labels: invalidSelector,
  5166. },
  5167. },
  5168. }
  5169. type rcUpdateTest struct {
  5170. old api.ReplicationController
  5171. update api.ReplicationController
  5172. }
  5173. successCases := []rcUpdateTest{
  5174. {
  5175. old: api.ReplicationController{
  5176. ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault},
  5177. Spec: api.ReplicationControllerSpec{
  5178. Selector: validSelector,
  5179. Template: &validPodTemplate.Template,
  5180. },
  5181. },
  5182. update: api.ReplicationController{
  5183. ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault},
  5184. Spec: api.ReplicationControllerSpec{
  5185. Replicas: 3,
  5186. Selector: validSelector,
  5187. Template: &validPodTemplate.Template,
  5188. },
  5189. },
  5190. },
  5191. {
  5192. old: api.ReplicationController{
  5193. ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault},
  5194. Spec: api.ReplicationControllerSpec{
  5195. Selector: validSelector,
  5196. Template: &validPodTemplate.Template,
  5197. },
  5198. },
  5199. update: api.ReplicationController{
  5200. ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault},
  5201. Spec: api.ReplicationControllerSpec{
  5202. Replicas: 1,
  5203. Selector: validSelector,
  5204. Template: &readWriteVolumePodTemplate.Template,
  5205. },
  5206. },
  5207. },
  5208. }
  5209. for _, successCase := range successCases {
  5210. successCase.old.ObjectMeta.ResourceVersion = "1"
  5211. successCase.update.ObjectMeta.ResourceVersion = "1"
  5212. if errs := ValidateReplicationControllerUpdate(&successCase.update, &successCase.old); len(errs) != 0 {
  5213. t.Errorf("expected success: %v", errs)
  5214. }
  5215. }
  5216. errorCases := map[string]rcUpdateTest{
  5217. "more than one read/write": {
  5218. old: api.ReplicationController{
  5219. ObjectMeta: api.ObjectMeta{Name: "", Namespace: api.NamespaceDefault},
  5220. Spec: api.ReplicationControllerSpec{
  5221. Selector: validSelector,
  5222. Template: &validPodTemplate.Template,
  5223. },
  5224. },
  5225. update: api.ReplicationController{
  5226. ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault},
  5227. Spec: api.ReplicationControllerSpec{
  5228. Replicas: 2,
  5229. Selector: validSelector,
  5230. Template: &readWriteVolumePodTemplate.Template,
  5231. },
  5232. },
  5233. },
  5234. "invalid selector": {
  5235. old: api.ReplicationController{
  5236. ObjectMeta: api.ObjectMeta{Name: "", Namespace: api.NamespaceDefault},
  5237. Spec: api.ReplicationControllerSpec{
  5238. Selector: validSelector,
  5239. Template: &validPodTemplate.Template,
  5240. },
  5241. },
  5242. update: api.ReplicationController{
  5243. ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault},
  5244. Spec: api.ReplicationControllerSpec{
  5245. Replicas: 2,
  5246. Selector: invalidSelector,
  5247. Template: &validPodTemplate.Template,
  5248. },
  5249. },
  5250. },
  5251. "invalid pod": {
  5252. old: api.ReplicationController{
  5253. ObjectMeta: api.ObjectMeta{Name: "", Namespace: api.NamespaceDefault},
  5254. Spec: api.ReplicationControllerSpec{
  5255. Selector: validSelector,
  5256. Template: &validPodTemplate.Template,
  5257. },
  5258. },
  5259. update: api.ReplicationController{
  5260. ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault},
  5261. Spec: api.ReplicationControllerSpec{
  5262. Replicas: 2,
  5263. Selector: validSelector,
  5264. Template: &invalidPodTemplate.Template,
  5265. },
  5266. },
  5267. },
  5268. "negative replicas": {
  5269. old: api.ReplicationController{
  5270. ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault},
  5271. Spec: api.ReplicationControllerSpec{
  5272. Selector: validSelector,
  5273. Template: &validPodTemplate.Template,
  5274. },
  5275. },
  5276. update: api.ReplicationController{
  5277. ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault},
  5278. Spec: api.ReplicationControllerSpec{
  5279. Replicas: -1,
  5280. Selector: validSelector,
  5281. Template: &validPodTemplate.Template,
  5282. },
  5283. },
  5284. },
  5285. }
  5286. for testName, errorCase := range errorCases {
  5287. if errs := ValidateReplicationControllerUpdate(&errorCase.update, &errorCase.old); len(errs) == 0 {
  5288. t.Errorf("expected failure: %s", testName)
  5289. }
  5290. }
  5291. }
  5292. func TestValidateReplicationController(t *testing.T) {
  5293. validSelector := map[string]string{"a": "b"}
  5294. validPodTemplate := api.PodTemplate{
  5295. Template: api.PodTemplateSpec{
  5296. ObjectMeta: api.ObjectMeta{
  5297. Labels: validSelector,
  5298. },
  5299. Spec: api.PodSpec{
  5300. RestartPolicy: api.RestartPolicyAlways,
  5301. DNSPolicy: api.DNSClusterFirst,
  5302. Containers: []api.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent"}},
  5303. },
  5304. },
  5305. }
  5306. readWriteVolumePodTemplate := api.PodTemplate{
  5307. Template: api.PodTemplateSpec{
  5308. ObjectMeta: api.ObjectMeta{
  5309. Labels: validSelector,
  5310. },
  5311. Spec: api.PodSpec{
  5312. Volumes: []api.Volume{{Name: "gcepd", VolumeSource: api.VolumeSource{GCEPersistentDisk: &api.GCEPersistentDiskVolumeSource{PDName: "my-PD", FSType: "ext4", Partition: 1, ReadOnly: false}}}},
  5313. RestartPolicy: api.RestartPolicyAlways,
  5314. DNSPolicy: api.DNSClusterFirst,
  5315. Containers: []api.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent"}},
  5316. },
  5317. },
  5318. }
  5319. invalidSelector := map[string]string{"NoUppercaseOrSpecialCharsLike=Equals": "b"}
  5320. invalidPodTemplate := api.PodTemplate{
  5321. Template: api.PodTemplateSpec{
  5322. Spec: api.PodSpec{
  5323. RestartPolicy: api.RestartPolicyAlways,
  5324. DNSPolicy: api.DNSClusterFirst,
  5325. },
  5326. ObjectMeta: api.ObjectMeta{
  5327. Labels: invalidSelector,
  5328. },
  5329. },
  5330. }
  5331. successCases := []api.ReplicationController{
  5332. {
  5333. ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault},
  5334. Spec: api.ReplicationControllerSpec{
  5335. Selector: validSelector,
  5336. Template: &validPodTemplate.Template,
  5337. },
  5338. },
  5339. {
  5340. ObjectMeta: api.ObjectMeta{Name: "abc-123", Namespace: api.NamespaceDefault},
  5341. Spec: api.ReplicationControllerSpec{
  5342. Selector: validSelector,
  5343. Template: &validPodTemplate.Template,
  5344. },
  5345. },
  5346. {
  5347. ObjectMeta: api.ObjectMeta{Name: "abc-123", Namespace: api.NamespaceDefault},
  5348. Spec: api.ReplicationControllerSpec{
  5349. Replicas: 1,
  5350. Selector: validSelector,
  5351. Template: &readWriteVolumePodTemplate.Template,
  5352. },
  5353. },
  5354. }
  5355. for _, successCase := range successCases {
  5356. if errs := ValidateReplicationController(&successCase); len(errs) != 0 {
  5357. t.Errorf("expected success: %v", errs)
  5358. }
  5359. }
  5360. errorCases := map[string]api.ReplicationController{
  5361. "zero-length ID": {
  5362. ObjectMeta: api.ObjectMeta{Name: "", Namespace: api.NamespaceDefault},
  5363. Spec: api.ReplicationControllerSpec{
  5364. Selector: validSelector,
  5365. Template: &validPodTemplate.Template,
  5366. },
  5367. },
  5368. "missing-namespace": {
  5369. ObjectMeta: api.ObjectMeta{Name: "abc-123"},
  5370. Spec: api.ReplicationControllerSpec{
  5371. Selector: validSelector,
  5372. Template: &validPodTemplate.Template,
  5373. },
  5374. },
  5375. "empty selector": {
  5376. ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault},
  5377. Spec: api.ReplicationControllerSpec{
  5378. Template: &validPodTemplate.Template,
  5379. },
  5380. },
  5381. "selector_doesnt_match": {
  5382. ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault},
  5383. Spec: api.ReplicationControllerSpec{
  5384. Selector: map[string]string{"foo": "bar"},
  5385. Template: &validPodTemplate.Template,
  5386. },
  5387. },
  5388. "invalid manifest": {
  5389. ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault},
  5390. Spec: api.ReplicationControllerSpec{
  5391. Selector: validSelector,
  5392. },
  5393. },
  5394. "read-write persistent disk with > 1 pod": {
  5395. ObjectMeta: api.ObjectMeta{Name: "abc"},
  5396. Spec: api.ReplicationControllerSpec{
  5397. Replicas: 2,
  5398. Selector: validSelector,
  5399. Template: &readWriteVolumePodTemplate.Template,
  5400. },
  5401. },
  5402. "negative_replicas": {
  5403. ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: api.NamespaceDefault},
  5404. Spec: api.ReplicationControllerSpec{
  5405. Replicas: -1,
  5406. Selector: validSelector,
  5407. },
  5408. },
  5409. "invalid_label": {
  5410. ObjectMeta: api.ObjectMeta{
  5411. Name: "abc-123",
  5412. Namespace: api.NamespaceDefault,
  5413. Labels: map[string]string{
  5414. "NoUppercaseOrSpecialCharsLike=Equals": "bar",
  5415. },
  5416. },
  5417. Spec: api.ReplicationControllerSpec{
  5418. Selector: validSelector,
  5419. Template: &validPodTemplate.Template,
  5420. },
  5421. },
  5422. "invalid_label 2": {
  5423. ObjectMeta: api.ObjectMeta{
  5424. Name: "abc-123",
  5425. Namespace: api.NamespaceDefault,
  5426. Labels: map[string]string{
  5427. "NoUppercaseOrSpecialCharsLike=Equals": "bar",
  5428. },
  5429. },
  5430. Spec: api.ReplicationControllerSpec{
  5431. Template: &invalidPodTemplate.Template,
  5432. },
  5433. },
  5434. "invalid_annotation": {
  5435. ObjectMeta: api.ObjectMeta{
  5436. Name: "abc-123",
  5437. Namespace: api.NamespaceDefault,
  5438. Annotations: map[string]string{
  5439. "NoUppercaseOrSpecialCharsLike=Equals": "bar",
  5440. },
  5441. },
  5442. Spec: api.ReplicationControllerSpec{
  5443. Selector: validSelector,
  5444. Template: &validPodTemplate.Template,
  5445. },
  5446. },
  5447. "invalid restart policy 1": {
  5448. ObjectMeta: api.ObjectMeta{
  5449. Name: "abc-123",
  5450. Namespace: api.NamespaceDefault,
  5451. },
  5452. Spec: api.ReplicationControllerSpec{
  5453. Selector: validSelector,
  5454. Template: &api.PodTemplateSpec{
  5455. Spec: api.PodSpec{
  5456. RestartPolicy: api.RestartPolicyOnFailure,
  5457. DNSPolicy: api.DNSClusterFirst,
  5458. Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}},
  5459. },
  5460. ObjectMeta: api.ObjectMeta{
  5461. Labels: validSelector,
  5462. },
  5463. },
  5464. },
  5465. },
  5466. "invalid restart policy 2": {
  5467. ObjectMeta: api.ObjectMeta{
  5468. Name: "abc-123",
  5469. Namespace: api.NamespaceDefault,
  5470. },
  5471. Spec: api.ReplicationControllerSpec{
  5472. Selector: validSelector,
  5473. Template: &api.PodTemplateSpec{
  5474. Spec: api.PodSpec{
  5475. RestartPolicy: api.RestartPolicyNever,
  5476. DNSPolicy: api.DNSClusterFirst,
  5477. Containers: []api.Container{{Name: "ctr", Image: "image", ImagePullPolicy: "IfNotPresent"}},
  5478. },
  5479. ObjectMeta: api.ObjectMeta{
  5480. Labels: validSelector,
  5481. },
  5482. },
  5483. },
  5484. },
  5485. }
  5486. for k, v := range errorCases {
  5487. errs := ValidateReplicationController(&v)
  5488. if len(errs) == 0 {
  5489. t.Errorf("expected failure for %s", k)
  5490. }
  5491. for i := range errs {
  5492. field := errs[i].Field
  5493. if !strings.HasPrefix(field, "spec.template.") &&
  5494. field != "metadata.name" &&
  5495. field != "metadata.namespace" &&
  5496. field != "spec.selector" &&
  5497. field != "spec.template" &&
  5498. field != "GCEPersistentDisk.ReadOnly" &&
  5499. field != "spec.replicas" &&
  5500. field != "spec.template.labels" &&
  5501. field != "metadata.annotations" &&
  5502. field != "metadata.labels" &&
  5503. field != "status.replicas" {
  5504. t.Errorf("%s: missing prefix for: %v", k, errs[i])
  5505. }
  5506. }
  5507. }
  5508. }
  5509. func TestValidateNode(t *testing.T) {
  5510. validSelector := map[string]string{"a": "b"}
  5511. invalidSelector := map[string]string{"NoUppercaseOrSpecialCharsLike=Equals": "b"}
  5512. successCases := []api.Node{
  5513. {
  5514. ObjectMeta: api.ObjectMeta{
  5515. Name: "abc",
  5516. Labels: validSelector,
  5517. },
  5518. Status: api.NodeStatus{
  5519. Addresses: []api.NodeAddress{
  5520. {Type: api.NodeLegacyHostIP, Address: "something"},
  5521. },
  5522. Capacity: api.ResourceList{
  5523. api.ResourceName(api.ResourceCPU): resource.MustParse("10"),
  5524. api.ResourceName(api.ResourceMemory): resource.MustParse("10G"),
  5525. api.ResourceName("my.org/gpu"): resource.MustParse("10"),
  5526. },
  5527. },
  5528. Spec: api.NodeSpec{
  5529. ExternalID: "external",
  5530. },
  5531. },
  5532. {
  5533. ObjectMeta: api.ObjectMeta{
  5534. Name: "abc",
  5535. },
  5536. Status: api.NodeStatus{
  5537. Addresses: []api.NodeAddress{
  5538. {Type: api.NodeLegacyHostIP, Address: "something"},
  5539. },
  5540. Capacity: api.ResourceList{
  5541. api.ResourceName(api.ResourceCPU): resource.MustParse("10"),
  5542. api.ResourceName(api.ResourceMemory): resource.MustParse("0"),
  5543. },
  5544. },
  5545. Spec: api.NodeSpec{
  5546. ExternalID: "external",
  5547. },
  5548. },
  5549. {
  5550. ObjectMeta: api.ObjectMeta{
  5551. Name: "dedicated-node1",
  5552. // Add a valid taint to a node
  5553. Annotations: map[string]string{
  5554. api.TaintsAnnotationKey: `
  5555. [{
  5556. "key": "GPU",
  5557. "value": "true",
  5558. "effect": "NoSchedule"
  5559. }]`,
  5560. },
  5561. },
  5562. Status: api.NodeStatus{
  5563. Addresses: []api.NodeAddress{
  5564. {Type: api.NodeLegacyHostIP, Address: "something"},
  5565. },
  5566. Capacity: api.ResourceList{
  5567. api.ResourceName(api.ResourceCPU): resource.MustParse("10"),
  5568. api.ResourceName(api.ResourceMemory): resource.MustParse("0"),
  5569. },
  5570. },
  5571. Spec: api.NodeSpec{
  5572. ExternalID: "external",
  5573. },
  5574. },
  5575. {
  5576. ObjectMeta: api.ObjectMeta{
  5577. Name: "abc",
  5578. Annotations: map[string]string{
  5579. api.PreferAvoidPodsAnnotationKey: `
  5580. {
  5581. "preferAvoidPods": [
  5582. {
  5583. "podSignature": {
  5584. "podController": {
  5585. "apiVersion": "v1",
  5586. "kind": "ReplicationController",
  5587. "name": "foo",
  5588. "uid": "abcdef123456",
  5589. "controller": true
  5590. }
  5591. },
  5592. "reason": "some reason",
  5593. "message": "some message"
  5594. }
  5595. ]
  5596. }`,
  5597. },
  5598. },
  5599. Status: api.NodeStatus{
  5600. Addresses: []api.NodeAddress{
  5601. {Type: api.NodeLegacyHostIP, Address: "something"},
  5602. },
  5603. Capacity: api.ResourceList{
  5604. api.ResourceName(api.ResourceCPU): resource.MustParse("10"),
  5605. api.ResourceName(api.ResourceMemory): resource.MustParse("0"),
  5606. },
  5607. },
  5608. Spec: api.NodeSpec{
  5609. ExternalID: "external",
  5610. },
  5611. },
  5612. }
  5613. for _, successCase := range successCases {
  5614. if errs := ValidateNode(&successCase); len(errs) != 0 {
  5615. t.Errorf("expected success: %v", errs)
  5616. }
  5617. }
  5618. errorCases := map[string]api.Node{
  5619. "zero-length Name": {
  5620. ObjectMeta: api.ObjectMeta{
  5621. Name: "",
  5622. Labels: validSelector,
  5623. },
  5624. Status: api.NodeStatus{
  5625. Addresses: []api.NodeAddress{},
  5626. Capacity: api.ResourceList{
  5627. api.ResourceName(api.ResourceCPU): resource.MustParse("10"),
  5628. api.ResourceName(api.ResourceMemory): resource.MustParse("10G"),
  5629. },
  5630. },
  5631. Spec: api.NodeSpec{
  5632. ExternalID: "external",
  5633. },
  5634. },
  5635. "invalid-labels": {
  5636. ObjectMeta: api.ObjectMeta{
  5637. Name: "abc-123",
  5638. Labels: invalidSelector,
  5639. },
  5640. Status: api.NodeStatus{
  5641. Capacity: api.ResourceList{
  5642. api.ResourceName(api.ResourceCPU): resource.MustParse("10"),
  5643. api.ResourceName(api.ResourceMemory): resource.MustParse("10G"),
  5644. },
  5645. },
  5646. Spec: api.NodeSpec{
  5647. ExternalID: "external",
  5648. },
  5649. },
  5650. "missing-external-id": {
  5651. ObjectMeta: api.ObjectMeta{
  5652. Name: "abc-123",
  5653. Labels: validSelector,
  5654. },
  5655. Status: api.NodeStatus{
  5656. Capacity: api.ResourceList{
  5657. api.ResourceName(api.ResourceCPU): resource.MustParse("10"),
  5658. api.ResourceName(api.ResourceMemory): resource.MustParse("10G"),
  5659. },
  5660. },
  5661. },
  5662. "missing-taint-key": {
  5663. ObjectMeta: api.ObjectMeta{
  5664. Name: "dedicated-node1",
  5665. // Add a taint with an empty key to a node
  5666. Annotations: map[string]string{
  5667. api.TaintsAnnotationKey: `
  5668. [{
  5669. "key": "",
  5670. "value": "special-user-1",
  5671. "effect": "NoSchedule"
  5672. }]`,
  5673. },
  5674. },
  5675. Spec: api.NodeSpec{
  5676. ExternalID: "external",
  5677. },
  5678. },
  5679. "bad-taint-key": {
  5680. ObjectMeta: api.ObjectMeta{
  5681. Name: "dedicated-node1",
  5682. // Add a taint with an empty key to a node
  5683. Annotations: map[string]string{
  5684. api.TaintsAnnotationKey: `
  5685. [{
  5686. "key": "NoUppercaseOrSpecialCharsLike=Equals",
  5687. "value": "special-user-1",
  5688. "effect": "NoSchedule"
  5689. }]`,
  5690. },
  5691. },
  5692. Spec: api.NodeSpec{
  5693. ExternalID: "external",
  5694. },
  5695. },
  5696. "bad-taint-value": {
  5697. ObjectMeta: api.ObjectMeta{
  5698. Name: "dedicated-node2",
  5699. Annotations: map[string]string{
  5700. api.TaintsAnnotationKey: `
  5701. [{
  5702. "key": "dedicated",
  5703. "value": "some\\bad\\value",
  5704. "effect": "NoSchedule"
  5705. }]`,
  5706. },
  5707. },
  5708. Status: api.NodeStatus{
  5709. Addresses: []api.NodeAddress{
  5710. {Type: api.NodeLegacyHostIP, Address: "something"},
  5711. },
  5712. Capacity: api.ResourceList{
  5713. api.ResourceName(api.ResourceCPU): resource.MustParse("10"),
  5714. api.ResourceName(api.ResourceMemory): resource.MustParse("0"),
  5715. },
  5716. },
  5717. // Add a taint with an empty value to a node
  5718. Spec: api.NodeSpec{
  5719. ExternalID: "external",
  5720. },
  5721. },
  5722. "missing-taint-effect": {
  5723. ObjectMeta: api.ObjectMeta{
  5724. Name: "dedicated-node3",
  5725. // Add a taint with an empty effect to a node
  5726. Annotations: map[string]string{
  5727. api.TaintsAnnotationKey: `
  5728. [{
  5729. "key": "dedicated",
  5730. "value": "special-user-3",
  5731. "effect": ""
  5732. }]`,
  5733. },
  5734. },
  5735. Status: api.NodeStatus{
  5736. Addresses: []api.NodeAddress{
  5737. {Type: api.NodeLegacyHostIP, Address: "something"},
  5738. },
  5739. Capacity: api.ResourceList{
  5740. api.ResourceName(api.ResourceCPU): resource.MustParse("10"),
  5741. api.ResourceName(api.ResourceMemory): resource.MustParse("0"),
  5742. },
  5743. },
  5744. Spec: api.NodeSpec{
  5745. ExternalID: "external",
  5746. },
  5747. },
  5748. "invalide-taint-effect": {
  5749. ObjectMeta: api.ObjectMeta{
  5750. Name: "dedicated-node3",
  5751. // Add a taint with an empty effect to a node
  5752. Annotations: map[string]string{
  5753. api.TaintsAnnotationKey: `
  5754. [{
  5755. "key": "dedicated",
  5756. "value": "special-user-3",
  5757. "effect": "NoExecute"
  5758. }]`,
  5759. },
  5760. },
  5761. Status: api.NodeStatus{
  5762. Addresses: []api.NodeAddress{
  5763. {Type: api.NodeLegacyHostIP, Address: "something"},
  5764. },
  5765. Capacity: api.ResourceList{
  5766. api.ResourceName(api.ResourceCPU): resource.MustParse("10"),
  5767. api.ResourceName(api.ResourceMemory): resource.MustParse("0"),
  5768. },
  5769. },
  5770. Spec: api.NodeSpec{
  5771. ExternalID: "external",
  5772. },
  5773. },
  5774. "duplicated-taints-with-same-key-effect": {
  5775. ObjectMeta: api.ObjectMeta{
  5776. Name: "dedicated-node1",
  5777. // Add two taints to the node with the same key and effect; should be rejected.
  5778. Annotations: map[string]string{
  5779. api.TaintsAnnotationKey: `
  5780. [{
  5781. "key": "dedicated",
  5782. "value": "special-user-1",
  5783. "effect": "NoSchedule"
  5784. }, {
  5785. "key": "dedicated",
  5786. "value": "special-user-2",
  5787. "effect": "NoSchedule"
  5788. }]`,
  5789. },
  5790. },
  5791. Spec: api.NodeSpec{
  5792. ExternalID: "external",
  5793. },
  5794. },
  5795. "missing-podSignature": {
  5796. ObjectMeta: api.ObjectMeta{
  5797. Name: "abc-123",
  5798. Annotations: map[string]string{
  5799. api.PreferAvoidPodsAnnotationKey: `
  5800. {
  5801. "preferAvoidPods": [
  5802. {
  5803. "reason": "some reason",
  5804. "message": "some message"
  5805. }
  5806. ]
  5807. }`,
  5808. },
  5809. },
  5810. Status: api.NodeStatus{
  5811. Addresses: []api.NodeAddress{},
  5812. Capacity: api.ResourceList{
  5813. api.ResourceName(api.ResourceCPU): resource.MustParse("10"),
  5814. api.ResourceName(api.ResourceMemory): resource.MustParse("0"),
  5815. },
  5816. },
  5817. Spec: api.NodeSpec{
  5818. ExternalID: "external",
  5819. },
  5820. },
  5821. "invalid-podController": {
  5822. ObjectMeta: api.ObjectMeta{
  5823. Name: "abc-123",
  5824. Annotations: map[string]string{
  5825. api.PreferAvoidPodsAnnotationKey: `
  5826. {
  5827. "preferAvoidPods": [
  5828. {
  5829. "podSignature": {
  5830. "podController": {
  5831. "apiVersion": "v1",
  5832. "kind": "ReplicationController",
  5833. "name": "foo",
  5834. "uid": "abcdef123456",
  5835. "controller": false
  5836. }
  5837. },
  5838. "reason": "some reason",
  5839. "message": "some message"
  5840. }
  5841. ]
  5842. }`,
  5843. },
  5844. },
  5845. Status: api.NodeStatus{
  5846. Addresses: []api.NodeAddress{},
  5847. Capacity: api.ResourceList{
  5848. api.ResourceName(api.ResourceCPU): resource.MustParse("10"),
  5849. api.ResourceName(api.ResourceMemory): resource.MustParse("0"),
  5850. },
  5851. },
  5852. Spec: api.NodeSpec{
  5853. ExternalID: "external",
  5854. },
  5855. },
  5856. }
  5857. for k, v := range errorCases {
  5858. errs := ValidateNode(&v)
  5859. if len(errs) == 0 {
  5860. t.Errorf("expected failure for %s", k)
  5861. }
  5862. for i := range errs {
  5863. field := errs[i].Field
  5864. expectedFields := map[string]bool{
  5865. "metadata.name": true,
  5866. "metadata.labels": true,
  5867. "metadata.annotations": true,
  5868. "metadata.namespace": true,
  5869. "spec.externalID": true,
  5870. "metadata.annotations.scheduler.alpha.kubernetes.io/taints[0].key": true,
  5871. "metadata.annotations.scheduler.alpha.kubernetes.io/taints[0].value": true,
  5872. "metadata.annotations.scheduler.alpha.kubernetes.io/taints[0].effect": true,
  5873. "metadata.annotations.scheduler.alpha.kubernetes.io/preferAvoidPods[0].PodSignature": true,
  5874. "metadata.annotations.scheduler.alpha.kubernetes.io/preferAvoidPods[0].PodSignature.PodController.Controller": true,
  5875. }
  5876. if val, ok := expectedFields[field]; ok {
  5877. if !val {
  5878. t.Errorf("%s: missing prefix for: %v", k, errs[i])
  5879. }
  5880. }
  5881. }
  5882. }
  5883. }
  5884. func TestValidateNodeUpdate(t *testing.T) {
  5885. tests := []struct {
  5886. oldNode api.Node
  5887. node api.Node
  5888. valid bool
  5889. }{
  5890. {api.Node{}, api.Node{}, true},
  5891. {api.Node{
  5892. ObjectMeta: api.ObjectMeta{
  5893. Name: "foo"}},
  5894. api.Node{
  5895. ObjectMeta: api.ObjectMeta{
  5896. Name: "bar"},
  5897. }, false},
  5898. {api.Node{
  5899. ObjectMeta: api.ObjectMeta{
  5900. Name: "foo",
  5901. Labels: map[string]string{"foo": "bar"},
  5902. },
  5903. }, api.Node{
  5904. ObjectMeta: api.ObjectMeta{
  5905. Name: "foo",
  5906. Labels: map[string]string{"foo": "baz"},
  5907. },
  5908. }, true},
  5909. {api.Node{
  5910. ObjectMeta: api.ObjectMeta{
  5911. Name: "foo",
  5912. },
  5913. }, api.Node{
  5914. ObjectMeta: api.ObjectMeta{
  5915. Name: "foo",
  5916. Labels: map[string]string{"foo": "baz"},
  5917. },
  5918. }, true},
  5919. {api.Node{
  5920. ObjectMeta: api.ObjectMeta{
  5921. Name: "foo",
  5922. Labels: map[string]string{"bar": "foo"},
  5923. },
  5924. }, api.Node{
  5925. ObjectMeta: api.ObjectMeta{
  5926. Name: "foo",
  5927. Labels: map[string]string{"foo": "baz"},
  5928. },
  5929. }, true},
  5930. {api.Node{
  5931. ObjectMeta: api.ObjectMeta{
  5932. Name: "foo",
  5933. },
  5934. Spec: api.NodeSpec{
  5935. PodCIDR: "",
  5936. },
  5937. }, api.Node{
  5938. ObjectMeta: api.ObjectMeta{
  5939. Name: "foo",
  5940. },
  5941. Spec: api.NodeSpec{
  5942. PodCIDR: "192.168.0.0/16",
  5943. },
  5944. }, true},
  5945. {api.Node{
  5946. ObjectMeta: api.ObjectMeta{
  5947. Name: "foo",
  5948. },
  5949. Spec: api.NodeSpec{
  5950. PodCIDR: "192.123.0.0/16",
  5951. },
  5952. }, api.Node{
  5953. ObjectMeta: api.ObjectMeta{
  5954. Name: "foo",
  5955. },
  5956. Spec: api.NodeSpec{
  5957. PodCIDR: "192.168.0.0/16",
  5958. },
  5959. }, false},
  5960. {api.Node{
  5961. ObjectMeta: api.ObjectMeta{
  5962. Name: "foo",
  5963. },
  5964. Status: api.NodeStatus{
  5965. Capacity: api.ResourceList{
  5966. api.ResourceCPU: resource.MustParse("10000"),
  5967. api.ResourceMemory: resource.MustParse("100"),
  5968. },
  5969. },
  5970. }, api.Node{
  5971. ObjectMeta: api.ObjectMeta{
  5972. Name: "foo",
  5973. },
  5974. Status: api.NodeStatus{
  5975. Capacity: api.ResourceList{
  5976. api.ResourceCPU: resource.MustParse("100"),
  5977. api.ResourceMemory: resource.MustParse("10000"),
  5978. },
  5979. },
  5980. }, true},
  5981. {api.Node{
  5982. ObjectMeta: api.ObjectMeta{
  5983. Name: "foo",
  5984. Labels: map[string]string{"bar": "foo"},
  5985. },
  5986. Status: api.NodeStatus{
  5987. Capacity: api.ResourceList{
  5988. api.ResourceCPU: resource.MustParse("10000"),
  5989. api.ResourceMemory: resource.MustParse("100"),
  5990. },
  5991. },
  5992. }, api.Node{
  5993. ObjectMeta: api.ObjectMeta{
  5994. Name: "foo",
  5995. Labels: map[string]string{"bar": "fooobaz"},
  5996. },
  5997. Status: api.NodeStatus{
  5998. Capacity: api.ResourceList{
  5999. api.ResourceCPU: resource.MustParse("100"),
  6000. api.ResourceMemory: resource.MustParse("10000"),
  6001. },
  6002. },
  6003. }, true},
  6004. {api.Node{
  6005. ObjectMeta: api.ObjectMeta{
  6006. Name: "foo",
  6007. Labels: map[string]string{"bar": "foo"},
  6008. },
  6009. Status: api.NodeStatus{
  6010. Addresses: []api.NodeAddress{
  6011. {Type: api.NodeLegacyHostIP, Address: "1.2.3.4"},
  6012. },
  6013. },
  6014. }, api.Node{
  6015. ObjectMeta: api.ObjectMeta{
  6016. Name: "foo",
  6017. Labels: map[string]string{"bar": "fooobaz"},
  6018. },
  6019. }, true},
  6020. {api.Node{
  6021. ObjectMeta: api.ObjectMeta{
  6022. Name: "foo",
  6023. Labels: map[string]string{"foo": "baz"},
  6024. },
  6025. }, api.Node{
  6026. ObjectMeta: api.ObjectMeta{
  6027. Name: "foo",
  6028. Labels: map[string]string{"Foo": "baz"},
  6029. },
  6030. }, true},
  6031. {api.Node{
  6032. ObjectMeta: api.ObjectMeta{
  6033. Name: "foo",
  6034. },
  6035. Spec: api.NodeSpec{
  6036. Unschedulable: false,
  6037. },
  6038. }, api.Node{
  6039. ObjectMeta: api.ObjectMeta{
  6040. Name: "foo",
  6041. },
  6042. Spec: api.NodeSpec{
  6043. Unschedulable: true,
  6044. },
  6045. }, true},
  6046. {api.Node{
  6047. ObjectMeta: api.ObjectMeta{
  6048. Name: "foo",
  6049. },
  6050. Spec: api.NodeSpec{
  6051. Unschedulable: false,
  6052. },
  6053. }, api.Node{
  6054. ObjectMeta: api.ObjectMeta{
  6055. Name: "foo",
  6056. },
  6057. Status: api.NodeStatus{
  6058. Addresses: []api.NodeAddress{
  6059. {Type: api.NodeExternalIP, Address: "1.1.1.1"},
  6060. {Type: api.NodeExternalIP, Address: "1.1.1.1"},
  6061. },
  6062. },
  6063. }, false},
  6064. {api.Node{
  6065. ObjectMeta: api.ObjectMeta{
  6066. Name: "foo",
  6067. },
  6068. Spec: api.NodeSpec{
  6069. Unschedulable: false,
  6070. },
  6071. }, api.Node{
  6072. ObjectMeta: api.ObjectMeta{
  6073. Name: "foo",
  6074. },
  6075. Status: api.NodeStatus{
  6076. Addresses: []api.NodeAddress{
  6077. {Type: api.NodeExternalIP, Address: "1.1.1.1"},
  6078. {Type: api.NodeInternalIP, Address: "10.1.1.1"},
  6079. },
  6080. },
  6081. }, true},
  6082. {api.Node{
  6083. ObjectMeta: api.ObjectMeta{
  6084. Name: "foo",
  6085. },
  6086. }, api.Node{
  6087. ObjectMeta: api.ObjectMeta{
  6088. Name: "foo",
  6089. Annotations: map[string]string{
  6090. api.PreferAvoidPodsAnnotationKey: `
  6091. {
  6092. "preferAvoidPods": [
  6093. {
  6094. "podSignature": {
  6095. "podController": {
  6096. "apiVersion": "v1",
  6097. "kind": "ReplicationController",
  6098. "name": "foo",
  6099. "uid": "abcdef123456",
  6100. "controller": true
  6101. }
  6102. },
  6103. "reason": "some reason",
  6104. "message": "some message"
  6105. }
  6106. ]
  6107. }`,
  6108. },
  6109. },
  6110. Spec: api.NodeSpec{
  6111. Unschedulable: false,
  6112. },
  6113. }, true},
  6114. {api.Node{
  6115. ObjectMeta: api.ObjectMeta{
  6116. Name: "foo",
  6117. },
  6118. }, api.Node{
  6119. ObjectMeta: api.ObjectMeta{
  6120. Name: "foo",
  6121. Annotations: map[string]string{
  6122. api.PreferAvoidPodsAnnotationKey: `
  6123. {
  6124. "preferAvoidPods": [
  6125. {
  6126. "reason": "some reason",
  6127. "message": "some message"
  6128. }
  6129. ]
  6130. }`,
  6131. },
  6132. },
  6133. }, false},
  6134. {api.Node{
  6135. ObjectMeta: api.ObjectMeta{
  6136. Name: "foo",
  6137. },
  6138. }, api.Node{
  6139. ObjectMeta: api.ObjectMeta{
  6140. Name: "foo",
  6141. Annotations: map[string]string{
  6142. api.PreferAvoidPodsAnnotationKey: `
  6143. {
  6144. "preferAvoidPods": [
  6145. {
  6146. "podSignature": {
  6147. "podController": {
  6148. "apiVersion": "v1",
  6149. "kind": "ReplicationController",
  6150. "name": "foo",
  6151. "uid": "abcdef123456",
  6152. "controller": false
  6153. }
  6154. },
  6155. "reason": "some reason",
  6156. "message": "some message"
  6157. }
  6158. ]
  6159. }`,
  6160. },
  6161. },
  6162. }, false},
  6163. }
  6164. for i, test := range tests {
  6165. test.oldNode.ObjectMeta.ResourceVersion = "1"
  6166. test.node.ObjectMeta.ResourceVersion = "1"
  6167. errs := ValidateNodeUpdate(&test.node, &test.oldNode)
  6168. if test.valid && len(errs) > 0 {
  6169. t.Errorf("%d: Unexpected error: %v", i, errs)
  6170. t.Logf("%#v vs %#v", test.oldNode.ObjectMeta, test.node.ObjectMeta)
  6171. }
  6172. if !test.valid && len(errs) == 0 {
  6173. t.Errorf("%d: Unexpected non-error", i)
  6174. }
  6175. }
  6176. }
  6177. func TestValidateServiceUpdate(t *testing.T) {
  6178. testCases := []struct {
  6179. name string
  6180. tweakSvc func(oldSvc, newSvc *api.Service) // given basic valid services, each test case can customize them
  6181. numErrs int
  6182. }{
  6183. {
  6184. name: "no change",
  6185. tweakSvc: func(oldSvc, newSvc *api.Service) {
  6186. // do nothing
  6187. },
  6188. numErrs: 0,
  6189. },
  6190. {
  6191. name: "change name",
  6192. tweakSvc: func(oldSvc, newSvc *api.Service) {
  6193. newSvc.Name += "2"
  6194. },
  6195. numErrs: 1,
  6196. },
  6197. {
  6198. name: "change namespace",
  6199. tweakSvc: func(oldSvc, newSvc *api.Service) {
  6200. newSvc.Namespace += "2"
  6201. },
  6202. numErrs: 1,
  6203. },
  6204. {
  6205. name: "change label valid",
  6206. tweakSvc: func(oldSvc, newSvc *api.Service) {
  6207. newSvc.Labels["key"] = "other-value"
  6208. },
  6209. numErrs: 0,
  6210. },
  6211. {
  6212. name: "add label",
  6213. tweakSvc: func(oldSvc, newSvc *api.Service) {
  6214. newSvc.Labels["key2"] = "value2"
  6215. },
  6216. numErrs: 0,
  6217. },
  6218. {
  6219. name: "change cluster IP",
  6220. tweakSvc: func(oldSvc, newSvc *api.Service) {
  6221. oldSvc.Spec.ClusterIP = "1.2.3.4"
  6222. newSvc.Spec.ClusterIP = "8.6.7.5"
  6223. },
  6224. numErrs: 1,
  6225. },
  6226. {
  6227. name: "remove cluster IP",
  6228. tweakSvc: func(oldSvc, newSvc *api.Service) {
  6229. oldSvc.Spec.ClusterIP = "1.2.3.4"
  6230. newSvc.Spec.ClusterIP = ""
  6231. },
  6232. numErrs: 1,
  6233. },
  6234. {
  6235. name: "change affinity",
  6236. tweakSvc: func(oldSvc, newSvc *api.Service) {
  6237. newSvc.Spec.SessionAffinity = "ClientIP"
  6238. },
  6239. numErrs: 0,
  6240. },
  6241. {
  6242. name: "remove affinity",
  6243. tweakSvc: func(oldSvc, newSvc *api.Service) {
  6244. newSvc.Spec.SessionAffinity = ""
  6245. },
  6246. numErrs: 1,
  6247. },
  6248. {
  6249. name: "change type",
  6250. tweakSvc: func(oldSvc, newSvc *api.Service) {
  6251. newSvc.Spec.Type = api.ServiceTypeLoadBalancer
  6252. },
  6253. numErrs: 0,
  6254. },
  6255. {
  6256. name: "remove type",
  6257. tweakSvc: func(oldSvc, newSvc *api.Service) {
  6258. newSvc.Spec.Type = ""
  6259. },
  6260. numErrs: 1,
  6261. },
  6262. {
  6263. name: "change type -> nodeport",
  6264. tweakSvc: func(oldSvc, newSvc *api.Service) {
  6265. newSvc.Spec.Type = api.ServiceTypeNodePort
  6266. },
  6267. numErrs: 0,
  6268. },
  6269. }
  6270. for _, tc := range testCases {
  6271. oldSvc := makeValidService()
  6272. newSvc := makeValidService()
  6273. tc.tweakSvc(&oldSvc, &newSvc)
  6274. errs := ValidateServiceUpdate(&newSvc, &oldSvc)
  6275. if len(errs) != tc.numErrs {
  6276. t.Errorf("Unexpected error list for case %q: %v", tc.name, errs.ToAggregate())
  6277. }
  6278. }
  6279. }
  6280. func TestValidateResourceNames(t *testing.T) {
  6281. table := []struct {
  6282. input string
  6283. success bool
  6284. expect string
  6285. }{
  6286. {"memory", true, ""},
  6287. {"cpu", true, ""},
  6288. {"network", false, ""},
  6289. {"disk", false, ""},
  6290. {"", false, ""},
  6291. {".", false, ""},
  6292. {"..", false, ""},
  6293. {"my.favorite.app.co/12345", true, ""},
  6294. {"my.favorite.app.co/_12345", false, ""},
  6295. {"my.favorite.app.co/12345_", false, ""},
  6296. {"kubernetes.io/..", false, ""},
  6297. {"kubernetes.io/" + strings.Repeat("a", 63), true, ""},
  6298. {"kubernetes.io/" + strings.Repeat("a", 64), false, ""},
  6299. {"kubernetes.io//", false, ""},
  6300. {"kubernetes.io", false, ""},
  6301. {"kubernetes.io/will/not/work/", false, ""},
  6302. }
  6303. for k, item := range table {
  6304. err := validateResourceName(item.input, field.NewPath("field"))
  6305. if len(err) != 0 && item.success {
  6306. t.Errorf("expected no failure for input %q", item.input)
  6307. } else if len(err) == 0 && !item.success {
  6308. t.Errorf("expected failure for input %q", item.input)
  6309. for i := range err {
  6310. detail := err[i].Detail
  6311. if detail != "" && !strings.Contains(detail, item.expect) {
  6312. t.Errorf("%d: expected error detail either empty or %s, got %s", k, item.expect, detail)
  6313. }
  6314. }
  6315. }
  6316. }
  6317. }
  6318. func getResourceList(cpu, memory string) api.ResourceList {
  6319. res := api.ResourceList{}
  6320. if cpu != "" {
  6321. res[api.ResourceCPU] = resource.MustParse(cpu)
  6322. }
  6323. if memory != "" {
  6324. res[api.ResourceMemory] = resource.MustParse(memory)
  6325. }
  6326. return res
  6327. }
  6328. func getStorageResourceList(storage string) api.ResourceList {
  6329. res := api.ResourceList{}
  6330. if storage != "" {
  6331. res[api.ResourceStorage] = resource.MustParse(storage)
  6332. }
  6333. return res
  6334. }
  6335. func TestValidateLimitRange(t *testing.T) {
  6336. successCases := []struct {
  6337. name string
  6338. spec api.LimitRangeSpec
  6339. }{
  6340. {
  6341. name: "all-fields-valid",
  6342. spec: api.LimitRangeSpec{
  6343. Limits: []api.LimitRangeItem{
  6344. {
  6345. Type: api.LimitTypePod,
  6346. Max: getResourceList("100m", "10000Mi"),
  6347. Min: getResourceList("5m", "100Mi"),
  6348. MaxLimitRequestRatio: getResourceList("10", ""),
  6349. },
  6350. {
  6351. Type: api.LimitTypeContainer,
  6352. Max: getResourceList("100m", "10000Mi"),
  6353. Min: getResourceList("5m", "100Mi"),
  6354. Default: getResourceList("50m", "500Mi"),
  6355. DefaultRequest: getResourceList("10m", "200Mi"),
  6356. MaxLimitRequestRatio: getResourceList("10", ""),
  6357. },
  6358. },
  6359. },
  6360. },
  6361. {
  6362. name: "all-fields-valid-big-numbers",
  6363. spec: api.LimitRangeSpec{
  6364. Limits: []api.LimitRangeItem{
  6365. {
  6366. Type: api.LimitTypeContainer,
  6367. Max: getResourceList("100m", "10000T"),
  6368. Min: getResourceList("5m", "100Mi"),
  6369. Default: getResourceList("50m", "500Mi"),
  6370. DefaultRequest: getResourceList("10m", "200Mi"),
  6371. MaxLimitRequestRatio: getResourceList("10", ""),
  6372. },
  6373. },
  6374. },
  6375. },
  6376. {
  6377. name: "thirdparty-fields-all-valid-standard-container-resources",
  6378. spec: api.LimitRangeSpec{
  6379. Limits: []api.LimitRangeItem{
  6380. {
  6381. Type: "thirdparty.com/foo",
  6382. Max: getResourceList("100m", "10000T"),
  6383. Min: getResourceList("5m", "100Mi"),
  6384. Default: getResourceList("50m", "500Mi"),
  6385. DefaultRequest: getResourceList("10m", "200Mi"),
  6386. MaxLimitRequestRatio: getResourceList("10", ""),
  6387. },
  6388. },
  6389. },
  6390. },
  6391. {
  6392. name: "thirdparty-fields-all-valid-storage-resources",
  6393. spec: api.LimitRangeSpec{
  6394. Limits: []api.LimitRangeItem{
  6395. {
  6396. Type: "thirdparty.com/foo",
  6397. Max: getStorageResourceList("10000T"),
  6398. Min: getStorageResourceList("100Mi"),
  6399. Default: getStorageResourceList("500Mi"),
  6400. DefaultRequest: getStorageResourceList("200Mi"),
  6401. MaxLimitRequestRatio: getStorageResourceList(""),
  6402. },
  6403. },
  6404. },
  6405. },
  6406. }
  6407. for _, successCase := range successCases {
  6408. limitRange := &api.LimitRange{ObjectMeta: api.ObjectMeta{Name: successCase.name, Namespace: "foo"}, Spec: successCase.spec}
  6409. if errs := ValidateLimitRange(limitRange); len(errs) != 0 {
  6410. t.Errorf("Case %v, unexpected error: %v", successCase.name, errs)
  6411. }
  6412. }
  6413. errorCases := map[string]struct {
  6414. R api.LimitRange
  6415. D string
  6416. }{
  6417. "zero-length-name": {
  6418. api.LimitRange{ObjectMeta: api.ObjectMeta{Name: "", Namespace: "foo"}, Spec: api.LimitRangeSpec{}},
  6419. "name or generateName is required",
  6420. },
  6421. "zero-length-namespace": {
  6422. api.LimitRange{ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: ""}, Spec: api.LimitRangeSpec{}},
  6423. "",
  6424. },
  6425. "invalid-name": {
  6426. api.LimitRange{ObjectMeta: api.ObjectMeta{Name: "^Invalid", Namespace: "foo"}, Spec: api.LimitRangeSpec{}},
  6427. "must match the regex",
  6428. },
  6429. "invalid-namespace": {
  6430. api.LimitRange{ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: "^Invalid"}, Spec: api.LimitRangeSpec{}},
  6431. "must match the regex",
  6432. },
  6433. "duplicate-limit-type": {
  6434. api.LimitRange{ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: api.LimitRangeSpec{
  6435. Limits: []api.LimitRangeItem{
  6436. {
  6437. Type: api.LimitTypePod,
  6438. Max: getResourceList("100m", "10000m"),
  6439. Min: getResourceList("0m", "100m"),
  6440. },
  6441. {
  6442. Type: api.LimitTypePod,
  6443. Min: getResourceList("0m", "100m"),
  6444. },
  6445. },
  6446. }},
  6447. "",
  6448. },
  6449. "default-limit-type-pod": {
  6450. api.LimitRange{ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: api.LimitRangeSpec{
  6451. Limits: []api.LimitRangeItem{
  6452. {
  6453. Type: api.LimitTypePod,
  6454. Max: getResourceList("100m", "10000m"),
  6455. Min: getResourceList("0m", "100m"),
  6456. Default: getResourceList("10m", "100m"),
  6457. },
  6458. },
  6459. }},
  6460. "may not be specified when `type` is 'Pod'",
  6461. },
  6462. "default-request-limit-type-pod": {
  6463. api.LimitRange{ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: api.LimitRangeSpec{
  6464. Limits: []api.LimitRangeItem{
  6465. {
  6466. Type: api.LimitTypePod,
  6467. Max: getResourceList("100m", "10000m"),
  6468. Min: getResourceList("0m", "100m"),
  6469. DefaultRequest: getResourceList("10m", "100m"),
  6470. },
  6471. },
  6472. }},
  6473. "may not be specified when `type` is 'Pod'",
  6474. },
  6475. "min value 100m is greater than max value 10m": {
  6476. api.LimitRange{ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: api.LimitRangeSpec{
  6477. Limits: []api.LimitRangeItem{
  6478. {
  6479. Type: api.LimitTypePod,
  6480. Max: getResourceList("10m", ""),
  6481. Min: getResourceList("100m", ""),
  6482. },
  6483. },
  6484. }},
  6485. "min value 100m is greater than max value 10m",
  6486. },
  6487. "invalid spec default outside range": {
  6488. api.LimitRange{ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: api.LimitRangeSpec{
  6489. Limits: []api.LimitRangeItem{
  6490. {
  6491. Type: api.LimitTypeContainer,
  6492. Max: getResourceList("1", ""),
  6493. Min: getResourceList("100m", ""),
  6494. Default: getResourceList("2000m", ""),
  6495. },
  6496. },
  6497. }},
  6498. "default value 2 is greater than max value 1",
  6499. },
  6500. "invalid spec defaultrequest outside range": {
  6501. api.LimitRange{ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: api.LimitRangeSpec{
  6502. Limits: []api.LimitRangeItem{
  6503. {
  6504. Type: api.LimitTypeContainer,
  6505. Max: getResourceList("1", ""),
  6506. Min: getResourceList("100m", ""),
  6507. DefaultRequest: getResourceList("2000m", ""),
  6508. },
  6509. },
  6510. }},
  6511. "default request value 2 is greater than max value 1",
  6512. },
  6513. "invalid spec defaultrequest more than default": {
  6514. api.LimitRange{ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: api.LimitRangeSpec{
  6515. Limits: []api.LimitRangeItem{
  6516. {
  6517. Type: api.LimitTypeContainer,
  6518. Max: getResourceList("2", ""),
  6519. Min: getResourceList("100m", ""),
  6520. Default: getResourceList("500m", ""),
  6521. DefaultRequest: getResourceList("800m", ""),
  6522. },
  6523. },
  6524. }},
  6525. "default request value 800m is greater than default limit value 500m",
  6526. },
  6527. "invalid spec maxLimitRequestRatio less than 1": {
  6528. api.LimitRange{ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: api.LimitRangeSpec{
  6529. Limits: []api.LimitRangeItem{
  6530. {
  6531. Type: api.LimitTypePod,
  6532. MaxLimitRequestRatio: getResourceList("800m", ""),
  6533. },
  6534. },
  6535. }},
  6536. "ratio 800m is less than 1",
  6537. },
  6538. "invalid spec maxLimitRequestRatio greater than max/min": {
  6539. api.LimitRange{ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: api.LimitRangeSpec{
  6540. Limits: []api.LimitRangeItem{
  6541. {
  6542. Type: api.LimitTypeContainer,
  6543. Max: getResourceList("", "2Gi"),
  6544. Min: getResourceList("", "512Mi"),
  6545. MaxLimitRequestRatio: getResourceList("", "10"),
  6546. },
  6547. },
  6548. }},
  6549. "ratio 10 is greater than max/min = 4.000000",
  6550. },
  6551. "invalid non standard limit type": {
  6552. api.LimitRange{ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: api.LimitRangeSpec{
  6553. Limits: []api.LimitRangeItem{
  6554. {
  6555. Type: "foo",
  6556. Max: getStorageResourceList("10000T"),
  6557. Min: getStorageResourceList("100Mi"),
  6558. Default: getStorageResourceList("500Mi"),
  6559. DefaultRequest: getStorageResourceList("200Mi"),
  6560. MaxLimitRequestRatio: getStorageResourceList(""),
  6561. },
  6562. },
  6563. }},
  6564. "must be a standard limit type or fully qualified",
  6565. },
  6566. }
  6567. for k, v := range errorCases {
  6568. errs := ValidateLimitRange(&v.R)
  6569. if len(errs) == 0 {
  6570. t.Errorf("expected failure for %s", k)
  6571. }
  6572. for i := range errs {
  6573. detail := errs[i].Detail
  6574. if !strings.Contains(detail, v.D) {
  6575. t.Errorf("[%s]: expected error detail either empty or %q, got %q", k, v.D, detail)
  6576. }
  6577. }
  6578. }
  6579. }
  6580. func TestValidateResourceQuota(t *testing.T) {
  6581. spec := api.ResourceQuotaSpec{
  6582. Hard: api.ResourceList{
  6583. api.ResourceCPU: resource.MustParse("100"),
  6584. api.ResourceMemory: resource.MustParse("10000"),
  6585. api.ResourceRequestsCPU: resource.MustParse("100"),
  6586. api.ResourceRequestsMemory: resource.MustParse("10000"),
  6587. api.ResourceLimitsCPU: resource.MustParse("100"),
  6588. api.ResourceLimitsMemory: resource.MustParse("10000"),
  6589. api.ResourcePods: resource.MustParse("10"),
  6590. api.ResourceServices: resource.MustParse("0"),
  6591. api.ResourceReplicationControllers: resource.MustParse("10"),
  6592. api.ResourceQuotas: resource.MustParse("10"),
  6593. api.ResourceConfigMaps: resource.MustParse("10"),
  6594. api.ResourceSecrets: resource.MustParse("10"),
  6595. },
  6596. }
  6597. terminatingSpec := api.ResourceQuotaSpec{
  6598. Hard: api.ResourceList{
  6599. api.ResourceCPU: resource.MustParse("100"),
  6600. api.ResourceLimitsCPU: resource.MustParse("200"),
  6601. },
  6602. Scopes: []api.ResourceQuotaScope{api.ResourceQuotaScopeTerminating},
  6603. }
  6604. nonTerminatingSpec := api.ResourceQuotaSpec{
  6605. Hard: api.ResourceList{
  6606. api.ResourceCPU: resource.MustParse("100"),
  6607. },
  6608. Scopes: []api.ResourceQuotaScope{api.ResourceQuotaScopeNotTerminating},
  6609. }
  6610. bestEffortSpec := api.ResourceQuotaSpec{
  6611. Hard: api.ResourceList{
  6612. api.ResourcePods: resource.MustParse("100"),
  6613. },
  6614. Scopes: []api.ResourceQuotaScope{api.ResourceQuotaScopeBestEffort},
  6615. }
  6616. nonBestEffortSpec := api.ResourceQuotaSpec{
  6617. Hard: api.ResourceList{
  6618. api.ResourceCPU: resource.MustParse("100"),
  6619. },
  6620. Scopes: []api.ResourceQuotaScope{api.ResourceQuotaScopeNotBestEffort},
  6621. }
  6622. // storage is not yet supported as a quota tracked resource
  6623. invalidQuotaResourceSpec := api.ResourceQuotaSpec{
  6624. Hard: api.ResourceList{
  6625. api.ResourceStorage: resource.MustParse("10"),
  6626. },
  6627. }
  6628. negativeSpec := api.ResourceQuotaSpec{
  6629. Hard: api.ResourceList{
  6630. api.ResourceCPU: resource.MustParse("-100"),
  6631. api.ResourceMemory: resource.MustParse("-10000"),
  6632. api.ResourcePods: resource.MustParse("-10"),
  6633. api.ResourceServices: resource.MustParse("-10"),
  6634. api.ResourceReplicationControllers: resource.MustParse("-10"),
  6635. api.ResourceQuotas: resource.MustParse("-10"),
  6636. api.ResourceConfigMaps: resource.MustParse("-10"),
  6637. api.ResourceSecrets: resource.MustParse("-10"),
  6638. },
  6639. }
  6640. fractionalComputeSpec := api.ResourceQuotaSpec{
  6641. Hard: api.ResourceList{
  6642. api.ResourceCPU: resource.MustParse("100m"),
  6643. },
  6644. }
  6645. fractionalPodSpec := api.ResourceQuotaSpec{
  6646. Hard: api.ResourceList{
  6647. api.ResourcePods: resource.MustParse(".1"),
  6648. api.ResourceServices: resource.MustParse(".5"),
  6649. api.ResourceReplicationControllers: resource.MustParse("1.25"),
  6650. api.ResourceQuotas: resource.MustParse("2.5"),
  6651. },
  6652. }
  6653. invalidTerminatingScopePairsSpec := api.ResourceQuotaSpec{
  6654. Hard: api.ResourceList{
  6655. api.ResourceCPU: resource.MustParse("100"),
  6656. },
  6657. Scopes: []api.ResourceQuotaScope{api.ResourceQuotaScopeTerminating, api.ResourceQuotaScopeNotTerminating},
  6658. }
  6659. invalidBestEffortScopePairsSpec := api.ResourceQuotaSpec{
  6660. Hard: api.ResourceList{
  6661. api.ResourcePods: resource.MustParse("100"),
  6662. },
  6663. Scopes: []api.ResourceQuotaScope{api.ResourceQuotaScopeBestEffort, api.ResourceQuotaScopeNotBestEffort},
  6664. }
  6665. invalidScopeNameSpec := api.ResourceQuotaSpec{
  6666. Hard: api.ResourceList{
  6667. api.ResourceCPU: resource.MustParse("100"),
  6668. },
  6669. Scopes: []api.ResourceQuotaScope{api.ResourceQuotaScope("foo")},
  6670. }
  6671. successCases := []api.ResourceQuota{
  6672. {
  6673. ObjectMeta: api.ObjectMeta{
  6674. Name: "abc",
  6675. Namespace: "foo",
  6676. },
  6677. Spec: spec,
  6678. },
  6679. {
  6680. ObjectMeta: api.ObjectMeta{
  6681. Name: "abc",
  6682. Namespace: "foo",
  6683. },
  6684. Spec: fractionalComputeSpec,
  6685. },
  6686. {
  6687. ObjectMeta: api.ObjectMeta{
  6688. Name: "abc",
  6689. Namespace: "foo",
  6690. },
  6691. Spec: terminatingSpec,
  6692. },
  6693. {
  6694. ObjectMeta: api.ObjectMeta{
  6695. Name: "abc",
  6696. Namespace: "foo",
  6697. },
  6698. Spec: nonTerminatingSpec,
  6699. },
  6700. {
  6701. ObjectMeta: api.ObjectMeta{
  6702. Name: "abc",
  6703. Namespace: "foo",
  6704. },
  6705. Spec: bestEffortSpec,
  6706. },
  6707. {
  6708. ObjectMeta: api.ObjectMeta{
  6709. Name: "abc",
  6710. Namespace: "foo",
  6711. },
  6712. Spec: nonBestEffortSpec,
  6713. },
  6714. }
  6715. for _, successCase := range successCases {
  6716. if errs := ValidateResourceQuota(&successCase); len(errs) != 0 {
  6717. t.Errorf("expected success: %v", errs)
  6718. }
  6719. }
  6720. errorCases := map[string]struct {
  6721. R api.ResourceQuota
  6722. D string
  6723. }{
  6724. "zero-length Name": {
  6725. api.ResourceQuota{ObjectMeta: api.ObjectMeta{Name: "", Namespace: "foo"}, Spec: spec},
  6726. "name or generateName is required",
  6727. },
  6728. "zero-length Namespace": {
  6729. api.ResourceQuota{ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: ""}, Spec: spec},
  6730. "",
  6731. },
  6732. "invalid Name": {
  6733. api.ResourceQuota{ObjectMeta: api.ObjectMeta{Name: "^Invalid", Namespace: "foo"}, Spec: spec},
  6734. "must match the regex",
  6735. },
  6736. "invalid Namespace": {
  6737. api.ResourceQuota{ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: "^Invalid"}, Spec: spec},
  6738. "must match the regex",
  6739. },
  6740. "negative-limits": {
  6741. api.ResourceQuota{ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: negativeSpec},
  6742. isNegativeErrorMsg,
  6743. },
  6744. "fractional-api-resource": {
  6745. api.ResourceQuota{ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: fractionalPodSpec},
  6746. isNotIntegerErrorMsg,
  6747. },
  6748. "invalid-quota-resource": {
  6749. api.ResourceQuota{ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: invalidQuotaResourceSpec},
  6750. isInvalidQuotaResource,
  6751. },
  6752. "invalid-quota-terminating-pair": {
  6753. api.ResourceQuota{ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: invalidTerminatingScopePairsSpec},
  6754. "conflicting scopes",
  6755. },
  6756. "invalid-quota-besteffort-pair": {
  6757. api.ResourceQuota{ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: invalidBestEffortScopePairsSpec},
  6758. "conflicting scopes",
  6759. },
  6760. "invalid-quota-scope-name": {
  6761. api.ResourceQuota{ObjectMeta: api.ObjectMeta{Name: "abc", Namespace: "foo"}, Spec: invalidScopeNameSpec},
  6762. "unsupported scope",
  6763. },
  6764. }
  6765. for k, v := range errorCases {
  6766. errs := ValidateResourceQuota(&v.R)
  6767. if len(errs) == 0 {
  6768. t.Errorf("expected failure for %s", k)
  6769. }
  6770. for i := range errs {
  6771. if !strings.Contains(errs[i].Detail, v.D) {
  6772. t.Errorf("[%s]: expected error detail either empty or %s, got %s", k, v.D, errs[i].Detail)
  6773. }
  6774. }
  6775. }
  6776. }
  6777. func TestValidateNamespace(t *testing.T) {
  6778. validLabels := map[string]string{"a": "b"}
  6779. invalidLabels := map[string]string{"NoUppercaseOrSpecialCharsLike=Equals": "b"}
  6780. successCases := []api.Namespace{
  6781. {
  6782. ObjectMeta: api.ObjectMeta{Name: "abc", Labels: validLabels},
  6783. },
  6784. {
  6785. ObjectMeta: api.ObjectMeta{Name: "abc-123"},
  6786. Spec: api.NamespaceSpec{
  6787. Finalizers: []api.FinalizerName{"example.com/something", "example.com/other"},
  6788. },
  6789. },
  6790. }
  6791. for _, successCase := range successCases {
  6792. if errs := ValidateNamespace(&successCase); len(errs) != 0 {
  6793. t.Errorf("expected success: %v", errs)
  6794. }
  6795. }
  6796. errorCases := map[string]struct {
  6797. R api.Namespace
  6798. D string
  6799. }{
  6800. "zero-length name": {
  6801. api.Namespace{ObjectMeta: api.ObjectMeta{Name: ""}},
  6802. "",
  6803. },
  6804. "defined-namespace": {
  6805. api.Namespace{ObjectMeta: api.ObjectMeta{Name: "abc-123", Namespace: "makesnosense"}},
  6806. "",
  6807. },
  6808. "invalid-labels": {
  6809. api.Namespace{ObjectMeta: api.ObjectMeta{Name: "abc", Labels: invalidLabels}},
  6810. "",
  6811. },
  6812. }
  6813. for k, v := range errorCases {
  6814. errs := ValidateNamespace(&v.R)
  6815. if len(errs) == 0 {
  6816. t.Errorf("expected failure for %s", k)
  6817. }
  6818. }
  6819. }
  6820. func TestValidateNamespaceFinalizeUpdate(t *testing.T) {
  6821. tests := []struct {
  6822. oldNamespace api.Namespace
  6823. namespace api.Namespace
  6824. valid bool
  6825. }{
  6826. {api.Namespace{}, api.Namespace{}, true},
  6827. {api.Namespace{
  6828. ObjectMeta: api.ObjectMeta{
  6829. Name: "foo"}},
  6830. api.Namespace{
  6831. ObjectMeta: api.ObjectMeta{
  6832. Name: "foo"},
  6833. Spec: api.NamespaceSpec{
  6834. Finalizers: []api.FinalizerName{"Foo"},
  6835. },
  6836. }, false},
  6837. {api.Namespace{
  6838. ObjectMeta: api.ObjectMeta{
  6839. Name: "foo"},
  6840. Spec: api.NamespaceSpec{
  6841. Finalizers: []api.FinalizerName{"foo.com/bar"},
  6842. },
  6843. },
  6844. api.Namespace{
  6845. ObjectMeta: api.ObjectMeta{
  6846. Name: "foo"},
  6847. Spec: api.NamespaceSpec{
  6848. Finalizers: []api.FinalizerName{"foo.com/bar", "what.com/bar"},
  6849. },
  6850. }, true},
  6851. {api.Namespace{
  6852. ObjectMeta: api.ObjectMeta{
  6853. Name: "fooemptyfinalizer"},
  6854. Spec: api.NamespaceSpec{
  6855. Finalizers: []api.FinalizerName{"foo.com/bar"},
  6856. },
  6857. },
  6858. api.Namespace{
  6859. ObjectMeta: api.ObjectMeta{
  6860. Name: "fooemptyfinalizer"},
  6861. Spec: api.NamespaceSpec{
  6862. Finalizers: []api.FinalizerName{"", "foo.com/bar", "what.com/bar"},
  6863. },
  6864. }, false},
  6865. }
  6866. for i, test := range tests {
  6867. test.namespace.ObjectMeta.ResourceVersion = "1"
  6868. test.oldNamespace.ObjectMeta.ResourceVersion = "1"
  6869. errs := ValidateNamespaceFinalizeUpdate(&test.namespace, &test.oldNamespace)
  6870. if test.valid && len(errs) > 0 {
  6871. t.Errorf("%d: Unexpected error: %v", i, errs)
  6872. t.Logf("%#v vs %#v", test.oldNamespace, test.namespace)
  6873. }
  6874. if !test.valid && len(errs) == 0 {
  6875. t.Errorf("%d: Unexpected non-error", i)
  6876. }
  6877. }
  6878. }
  6879. func TestValidateNamespaceStatusUpdate(t *testing.T) {
  6880. now := unversioned.Now()
  6881. tests := []struct {
  6882. oldNamespace api.Namespace
  6883. namespace api.Namespace
  6884. valid bool
  6885. }{
  6886. {api.Namespace{}, api.Namespace{
  6887. Status: api.NamespaceStatus{
  6888. Phase: api.NamespaceActive,
  6889. },
  6890. }, true},
  6891. // Cannot set deletionTimestamp via status update
  6892. {api.Namespace{
  6893. ObjectMeta: api.ObjectMeta{
  6894. Name: "foo"}},
  6895. api.Namespace{
  6896. ObjectMeta: api.ObjectMeta{
  6897. Name: "foo",
  6898. DeletionTimestamp: &now},
  6899. Status: api.NamespaceStatus{
  6900. Phase: api.NamespaceTerminating,
  6901. },
  6902. }, false},
  6903. // Can update phase via status update
  6904. {api.Namespace{
  6905. ObjectMeta: api.ObjectMeta{
  6906. Name: "foo",
  6907. DeletionTimestamp: &now}},
  6908. api.Namespace{
  6909. ObjectMeta: api.ObjectMeta{
  6910. Name: "foo",
  6911. DeletionTimestamp: &now},
  6912. Status: api.NamespaceStatus{
  6913. Phase: api.NamespaceTerminating,
  6914. },
  6915. }, true},
  6916. {api.Namespace{
  6917. ObjectMeta: api.ObjectMeta{
  6918. Name: "foo"}},
  6919. api.Namespace{
  6920. ObjectMeta: api.ObjectMeta{
  6921. Name: "foo"},
  6922. Status: api.NamespaceStatus{
  6923. Phase: api.NamespaceTerminating,
  6924. },
  6925. }, false},
  6926. {api.Namespace{
  6927. ObjectMeta: api.ObjectMeta{
  6928. Name: "foo"}},
  6929. api.Namespace{
  6930. ObjectMeta: api.ObjectMeta{
  6931. Name: "bar"},
  6932. Status: api.NamespaceStatus{
  6933. Phase: api.NamespaceTerminating,
  6934. },
  6935. }, false},
  6936. }
  6937. for i, test := range tests {
  6938. test.namespace.ObjectMeta.ResourceVersion = "1"
  6939. test.oldNamespace.ObjectMeta.ResourceVersion = "1"
  6940. errs := ValidateNamespaceStatusUpdate(&test.namespace, &test.oldNamespace)
  6941. if test.valid && len(errs) > 0 {
  6942. t.Errorf("%d: Unexpected error: %v", i, errs)
  6943. t.Logf("%#v vs %#v", test.oldNamespace.ObjectMeta, test.namespace.ObjectMeta)
  6944. }
  6945. if !test.valid && len(errs) == 0 {
  6946. t.Errorf("%d: Unexpected non-error", i)
  6947. }
  6948. }
  6949. }
  6950. func TestValidateNamespaceUpdate(t *testing.T) {
  6951. tests := []struct {
  6952. oldNamespace api.Namespace
  6953. namespace api.Namespace
  6954. valid bool
  6955. }{
  6956. {api.Namespace{}, api.Namespace{}, true},
  6957. {api.Namespace{
  6958. ObjectMeta: api.ObjectMeta{
  6959. Name: "foo1"}},
  6960. api.Namespace{
  6961. ObjectMeta: api.ObjectMeta{
  6962. Name: "bar1"},
  6963. }, false},
  6964. {api.Namespace{
  6965. ObjectMeta: api.ObjectMeta{
  6966. Name: "foo2",
  6967. Labels: map[string]string{"foo": "bar"},
  6968. },
  6969. }, api.Namespace{
  6970. ObjectMeta: api.ObjectMeta{
  6971. Name: "foo2",
  6972. Labels: map[string]string{"foo": "baz"},
  6973. },
  6974. }, true},
  6975. {api.Namespace{
  6976. ObjectMeta: api.ObjectMeta{
  6977. Name: "foo3",
  6978. },
  6979. }, api.Namespace{
  6980. ObjectMeta: api.ObjectMeta{
  6981. Name: "foo3",
  6982. Labels: map[string]string{"foo": "baz"},
  6983. },
  6984. }, true},
  6985. {api.Namespace{
  6986. ObjectMeta: api.ObjectMeta{
  6987. Name: "foo4",
  6988. Labels: map[string]string{"bar": "foo"},
  6989. },
  6990. }, api.Namespace{
  6991. ObjectMeta: api.ObjectMeta{
  6992. Name: "foo4",
  6993. Labels: map[string]string{"foo": "baz"},
  6994. },
  6995. }, true},
  6996. {api.Namespace{
  6997. ObjectMeta: api.ObjectMeta{
  6998. Name: "foo5",
  6999. Labels: map[string]string{"foo": "baz"},
  7000. },
  7001. }, api.Namespace{
  7002. ObjectMeta: api.ObjectMeta{
  7003. Name: "foo5",
  7004. Labels: map[string]string{"Foo": "baz"},
  7005. },
  7006. }, true},
  7007. {api.Namespace{
  7008. ObjectMeta: api.ObjectMeta{
  7009. Name: "foo6",
  7010. Labels: map[string]string{"foo": "baz"},
  7011. },
  7012. }, api.Namespace{
  7013. ObjectMeta: api.ObjectMeta{
  7014. Name: "foo6",
  7015. Labels: map[string]string{"Foo": "baz"},
  7016. },
  7017. Spec: api.NamespaceSpec{
  7018. Finalizers: []api.FinalizerName{"kubernetes"},
  7019. },
  7020. Status: api.NamespaceStatus{
  7021. Phase: api.NamespaceTerminating,
  7022. },
  7023. }, true},
  7024. }
  7025. for i, test := range tests {
  7026. test.namespace.ObjectMeta.ResourceVersion = "1"
  7027. test.oldNamespace.ObjectMeta.ResourceVersion = "1"
  7028. errs := ValidateNamespaceUpdate(&test.namespace, &test.oldNamespace)
  7029. if test.valid && len(errs) > 0 {
  7030. t.Errorf("%d: Unexpected error: %v", i, errs)
  7031. t.Logf("%#v vs %#v", test.oldNamespace.ObjectMeta, test.namespace.ObjectMeta)
  7032. }
  7033. if !test.valid && len(errs) == 0 {
  7034. t.Errorf("%d: Unexpected non-error", i)
  7035. }
  7036. }
  7037. }
  7038. func TestValidateSecret(t *testing.T) {
  7039. // Opaque secret validation
  7040. validSecret := func() api.Secret {
  7041. return api.Secret{
  7042. ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "bar"},
  7043. Data: map[string][]byte{
  7044. "data-1": []byte("bar"),
  7045. },
  7046. }
  7047. }
  7048. var (
  7049. emptyName = validSecret()
  7050. invalidName = validSecret()
  7051. emptyNs = validSecret()
  7052. invalidNs = validSecret()
  7053. overMaxSize = validSecret()
  7054. invalidKey = validSecret()
  7055. leadingDotKey = validSecret()
  7056. dotKey = validSecret()
  7057. doubleDotKey = validSecret()
  7058. )
  7059. emptyName.Name = ""
  7060. invalidName.Name = "NoUppercaseOrSpecialCharsLike=Equals"
  7061. emptyNs.Namespace = ""
  7062. invalidNs.Namespace = "NoUppercaseOrSpecialCharsLike=Equals"
  7063. overMaxSize.Data = map[string][]byte{
  7064. "over": make([]byte, api.MaxSecretSize+1),
  7065. }
  7066. invalidKey.Data["a*b"] = []byte("whoops")
  7067. leadingDotKey.Data[".key"] = []byte("bar")
  7068. dotKey.Data["."] = []byte("bar")
  7069. doubleDotKey.Data[".."] = []byte("bar")
  7070. // kubernetes.io/service-account-token secret validation
  7071. validServiceAccountTokenSecret := func() api.Secret {
  7072. return api.Secret{
  7073. ObjectMeta: api.ObjectMeta{
  7074. Name: "foo",
  7075. Namespace: "bar",
  7076. Annotations: map[string]string{
  7077. api.ServiceAccountNameKey: "foo",
  7078. },
  7079. },
  7080. Type: api.SecretTypeServiceAccountToken,
  7081. Data: map[string][]byte{
  7082. "data-1": []byte("bar"),
  7083. },
  7084. }
  7085. }
  7086. var (
  7087. emptyTokenAnnotation = validServiceAccountTokenSecret()
  7088. missingTokenAnnotation = validServiceAccountTokenSecret()
  7089. missingTokenAnnotations = validServiceAccountTokenSecret()
  7090. )
  7091. emptyTokenAnnotation.Annotations[api.ServiceAccountNameKey] = ""
  7092. delete(missingTokenAnnotation.Annotations, api.ServiceAccountNameKey)
  7093. missingTokenAnnotations.Annotations = nil
  7094. tests := map[string]struct {
  7095. secret api.Secret
  7096. valid bool
  7097. }{
  7098. "valid": {validSecret(), true},
  7099. "empty name": {emptyName, false},
  7100. "invalid name": {invalidName, false},
  7101. "empty namespace": {emptyNs, false},
  7102. "invalid namespace": {invalidNs, false},
  7103. "over max size": {overMaxSize, false},
  7104. "invalid key": {invalidKey, false},
  7105. "valid service-account-token secret": {validServiceAccountTokenSecret(), true},
  7106. "empty service-account-token annotation": {emptyTokenAnnotation, false},
  7107. "missing service-account-token annotation": {missingTokenAnnotation, false},
  7108. "missing service-account-token annotations": {missingTokenAnnotations, false},
  7109. "leading dot key": {leadingDotKey, true},
  7110. "dot key": {dotKey, false},
  7111. "double dot key": {doubleDotKey, false},
  7112. }
  7113. for name, tc := range tests {
  7114. errs := ValidateSecret(&tc.secret)
  7115. if tc.valid && len(errs) > 0 {
  7116. t.Errorf("%v: Unexpected error: %v", name, errs)
  7117. }
  7118. if !tc.valid && len(errs) == 0 {
  7119. t.Errorf("%v: Unexpected non-error", name)
  7120. }
  7121. }
  7122. }
  7123. func TestValidateDockerConfigSecret(t *testing.T) {
  7124. validDockerSecret := func() api.Secret {
  7125. return api.Secret{
  7126. ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "bar"},
  7127. Type: api.SecretTypeDockercfg,
  7128. Data: map[string][]byte{
  7129. api.DockerConfigKey: []byte(`{"https://index.docker.io/v1/": {"auth": "Y2x1ZWRyb29sZXIwMDAxOnBhc3N3b3Jk","email": "fake@example.com"}}`),
  7130. },
  7131. }
  7132. }
  7133. validDockerSecret2 := func() api.Secret {
  7134. return api.Secret{
  7135. ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "bar"},
  7136. Type: api.SecretTypeDockerConfigJson,
  7137. Data: map[string][]byte{
  7138. api.DockerConfigJsonKey: []byte(`{"auths":{"https://index.docker.io/v1/": {"auth": "Y2x1ZWRyb29sZXIwMDAxOnBhc3N3b3Jk","email": "fake@example.com"}}}`),
  7139. },
  7140. }
  7141. }
  7142. var (
  7143. missingDockerConfigKey = validDockerSecret()
  7144. emptyDockerConfigKey = validDockerSecret()
  7145. invalidDockerConfigKey = validDockerSecret()
  7146. missingDockerConfigKey2 = validDockerSecret2()
  7147. emptyDockerConfigKey2 = validDockerSecret2()
  7148. invalidDockerConfigKey2 = validDockerSecret2()
  7149. )
  7150. delete(missingDockerConfigKey.Data, api.DockerConfigKey)
  7151. emptyDockerConfigKey.Data[api.DockerConfigKey] = []byte("")
  7152. invalidDockerConfigKey.Data[api.DockerConfigKey] = []byte("bad")
  7153. delete(missingDockerConfigKey2.Data, api.DockerConfigJsonKey)
  7154. emptyDockerConfigKey2.Data[api.DockerConfigJsonKey] = []byte("")
  7155. invalidDockerConfigKey2.Data[api.DockerConfigJsonKey] = []byte("bad")
  7156. tests := map[string]struct {
  7157. secret api.Secret
  7158. valid bool
  7159. }{
  7160. "valid dockercfg": {validDockerSecret(), true},
  7161. "missing dockercfg": {missingDockerConfigKey, false},
  7162. "empty dockercfg": {emptyDockerConfigKey, false},
  7163. "invalid dockercfg": {invalidDockerConfigKey, false},
  7164. "valid config.json": {validDockerSecret2(), true},
  7165. "missing config.json": {missingDockerConfigKey2, false},
  7166. "empty config.json": {emptyDockerConfigKey2, false},
  7167. "invalid config.json": {invalidDockerConfigKey2, false},
  7168. }
  7169. for name, tc := range tests {
  7170. errs := ValidateSecret(&tc.secret)
  7171. if tc.valid && len(errs) > 0 {
  7172. t.Errorf("%v: Unexpected error: %v", name, errs)
  7173. }
  7174. if !tc.valid && len(errs) == 0 {
  7175. t.Errorf("%v: Unexpected non-error", name)
  7176. }
  7177. }
  7178. }
  7179. func TestValidateBasicAuthSecret(t *testing.T) {
  7180. validBasicAuthSecret := func() api.Secret {
  7181. return api.Secret{
  7182. ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "bar"},
  7183. Type: api.SecretTypeBasicAuth,
  7184. Data: map[string][]byte{
  7185. api.BasicAuthUsernameKey: []byte("username"),
  7186. api.BasicAuthPasswordKey: []byte("password"),
  7187. },
  7188. }
  7189. }
  7190. var (
  7191. missingBasicAuthUsernamePasswordKeys = validBasicAuthSecret()
  7192. // invalidBasicAuthUsernamePasswordKey = validBasicAuthSecret()
  7193. // emptyBasicAuthUsernameKey = validBasicAuthSecret()
  7194. // emptyBasicAuthPasswordKey = validBasicAuthSecret()
  7195. )
  7196. delete(missingBasicAuthUsernamePasswordKeys.Data, api.BasicAuthUsernameKey)
  7197. delete(missingBasicAuthUsernamePasswordKeys.Data, api.BasicAuthPasswordKey)
  7198. // invalidBasicAuthUsernamePasswordKey.Data[api.BasicAuthUsernameKey] = []byte("bad")
  7199. // invalidBasicAuthUsernamePasswordKey.Data[api.BasicAuthPasswordKey] = []byte("bad")
  7200. // emptyBasicAuthUsernameKey.Data[api.BasicAuthUsernameKey] = []byte("")
  7201. // emptyBasicAuthPasswordKey.Data[api.BasicAuthPasswordKey] = []byte("")
  7202. tests := map[string]struct {
  7203. secret api.Secret
  7204. valid bool
  7205. }{
  7206. "valid": {validBasicAuthSecret(), true},
  7207. "missing username and password": {missingBasicAuthUsernamePasswordKeys, false},
  7208. // "invalid username and password": {invalidBasicAuthUsernamePasswordKey, false},
  7209. // "empty username": {emptyBasicAuthUsernameKey, false},
  7210. // "empty password": {emptyBasicAuthPasswordKey, false},
  7211. }
  7212. for name, tc := range tests {
  7213. errs := ValidateSecret(&tc.secret)
  7214. if tc.valid && len(errs) > 0 {
  7215. t.Errorf("%v: Unexpected error: %v", name, errs)
  7216. }
  7217. if !tc.valid && len(errs) == 0 {
  7218. t.Errorf("%v: Unexpected non-error", name)
  7219. }
  7220. }
  7221. }
  7222. func TestValidateSSHAuthSecret(t *testing.T) {
  7223. validSSHAuthSecret := func() api.Secret {
  7224. return api.Secret{
  7225. ObjectMeta: api.ObjectMeta{Name: "foo", Namespace: "bar"},
  7226. Type: api.SecretTypeSSHAuth,
  7227. Data: map[string][]byte{
  7228. api.SSHAuthPrivateKey: []byte("foo-bar-baz"),
  7229. },
  7230. }
  7231. }
  7232. missingSSHAuthPrivateKey := validSSHAuthSecret()
  7233. delete(missingSSHAuthPrivateKey.Data, api.SSHAuthPrivateKey)
  7234. tests := map[string]struct {
  7235. secret api.Secret
  7236. valid bool
  7237. }{
  7238. "valid": {validSSHAuthSecret(), true},
  7239. "missing private key": {missingSSHAuthPrivateKey, false},
  7240. }
  7241. for name, tc := range tests {
  7242. errs := ValidateSecret(&tc.secret)
  7243. if tc.valid && len(errs) > 0 {
  7244. t.Errorf("%v: Unexpected error: %v", name, errs)
  7245. }
  7246. if !tc.valid && len(errs) == 0 {
  7247. t.Errorf("%v: Unexpected non-error", name)
  7248. }
  7249. }
  7250. }
  7251. func TestValidateEndpoints(t *testing.T) {
  7252. successCases := map[string]api.Endpoints{
  7253. "simple endpoint": {
  7254. ObjectMeta: api.ObjectMeta{Name: "mysvc", Namespace: "namespace"},
  7255. Subsets: []api.EndpointSubset{
  7256. {
  7257. Addresses: []api.EndpointAddress{{IP: "10.10.1.1"}, {IP: "10.10.2.2"}},
  7258. Ports: []api.EndpointPort{{Name: "a", Port: 8675, Protocol: "TCP"}, {Name: "b", Port: 309, Protocol: "TCP"}},
  7259. },
  7260. {
  7261. Addresses: []api.EndpointAddress{{IP: "10.10.3.3"}},
  7262. Ports: []api.EndpointPort{{Name: "a", Port: 93, Protocol: "TCP"}, {Name: "b", Port: 76, Protocol: "TCP"}},
  7263. },
  7264. },
  7265. },
  7266. "empty subsets": {
  7267. ObjectMeta: api.ObjectMeta{Name: "mysvc", Namespace: "namespace"},
  7268. },
  7269. "no name required for singleton port": {
  7270. ObjectMeta: api.ObjectMeta{Name: "mysvc", Namespace: "namespace"},
  7271. Subsets: []api.EndpointSubset{
  7272. {
  7273. Addresses: []api.EndpointAddress{{IP: "10.10.1.1"}},
  7274. Ports: []api.EndpointPort{{Port: 8675, Protocol: "TCP"}},
  7275. },
  7276. },
  7277. },
  7278. }
  7279. for k, v := range successCases {
  7280. if errs := ValidateEndpoints(&v); len(errs) != 0 {
  7281. t.Errorf("Expected success for %s, got %v", k, errs)
  7282. }
  7283. }
  7284. errorCases := map[string]struct {
  7285. endpoints api.Endpoints
  7286. errorType field.ErrorType
  7287. errorDetail string
  7288. }{
  7289. "missing namespace": {
  7290. endpoints: api.Endpoints{ObjectMeta: api.ObjectMeta{Name: "mysvc"}},
  7291. errorType: "FieldValueRequired",
  7292. },
  7293. "missing name": {
  7294. endpoints: api.Endpoints{ObjectMeta: api.ObjectMeta{Namespace: "namespace"}},
  7295. errorType: "FieldValueRequired",
  7296. },
  7297. "invalid namespace": {
  7298. endpoints: api.Endpoints{ObjectMeta: api.ObjectMeta{Name: "mysvc", Namespace: "no@#invalid.;chars\"allowed"}},
  7299. errorType: "FieldValueInvalid",
  7300. errorDetail: "must match the regex",
  7301. },
  7302. "invalid name": {
  7303. endpoints: api.Endpoints{ObjectMeta: api.ObjectMeta{Name: "-_Invliad^&Characters", Namespace: "namespace"}},
  7304. errorType: "FieldValueInvalid",
  7305. errorDetail: "must match the regex",
  7306. },
  7307. "empty addresses": {
  7308. endpoints: api.Endpoints{
  7309. ObjectMeta: api.ObjectMeta{Name: "mysvc", Namespace: "namespace"},
  7310. Subsets: []api.EndpointSubset{
  7311. {
  7312. Ports: []api.EndpointPort{{Name: "a", Port: 93, Protocol: "TCP"}},
  7313. },
  7314. },
  7315. },
  7316. errorType: "FieldValueRequired",
  7317. },
  7318. "empty ports": {
  7319. endpoints: api.Endpoints{
  7320. ObjectMeta: api.ObjectMeta{Name: "mysvc", Namespace: "namespace"},
  7321. Subsets: []api.EndpointSubset{
  7322. {
  7323. Addresses: []api.EndpointAddress{{IP: "10.10.3.3"}},
  7324. },
  7325. },
  7326. },
  7327. errorType: "FieldValueRequired",
  7328. },
  7329. "invalid IP": {
  7330. endpoints: api.Endpoints{
  7331. ObjectMeta: api.ObjectMeta{Name: "mysvc", Namespace: "namespace"},
  7332. Subsets: []api.EndpointSubset{
  7333. {
  7334. Addresses: []api.EndpointAddress{{IP: "[2001:0db8:85a3:0042:1000:8a2e:0370:7334]"}},
  7335. Ports: []api.EndpointPort{{Name: "a", Port: 93, Protocol: "TCP"}},
  7336. },
  7337. },
  7338. },
  7339. errorType: "FieldValueInvalid",
  7340. errorDetail: "must be a valid IP address",
  7341. },
  7342. "Multiple ports, one without name": {
  7343. endpoints: api.Endpoints{
  7344. ObjectMeta: api.ObjectMeta{Name: "mysvc", Namespace: "namespace"},
  7345. Subsets: []api.EndpointSubset{
  7346. {
  7347. Addresses: []api.EndpointAddress{{IP: "10.10.1.1"}},
  7348. Ports: []api.EndpointPort{{Port: 8675, Protocol: "TCP"}, {Name: "b", Port: 309, Protocol: "TCP"}},
  7349. },
  7350. },
  7351. },
  7352. errorType: "FieldValueRequired",
  7353. },
  7354. "Invalid port number": {
  7355. endpoints: api.Endpoints{
  7356. ObjectMeta: api.ObjectMeta{Name: "mysvc", Namespace: "namespace"},
  7357. Subsets: []api.EndpointSubset{
  7358. {
  7359. Addresses: []api.EndpointAddress{{IP: "10.10.1.1"}},
  7360. Ports: []api.EndpointPort{{Name: "a", Port: 66000, Protocol: "TCP"}},
  7361. },
  7362. },
  7363. },
  7364. errorType: "FieldValueInvalid",
  7365. errorDetail: "between",
  7366. },
  7367. "Invalid protocol": {
  7368. endpoints: api.Endpoints{
  7369. ObjectMeta: api.ObjectMeta{Name: "mysvc", Namespace: "namespace"},
  7370. Subsets: []api.EndpointSubset{
  7371. {
  7372. Addresses: []api.EndpointAddress{{IP: "10.10.1.1"}},
  7373. Ports: []api.EndpointPort{{Name: "a", Port: 93, Protocol: "Protocol"}},
  7374. },
  7375. },
  7376. },
  7377. errorType: "FieldValueNotSupported",
  7378. },
  7379. "Address missing IP": {
  7380. endpoints: api.Endpoints{
  7381. ObjectMeta: api.ObjectMeta{Name: "mysvc", Namespace: "namespace"},
  7382. Subsets: []api.EndpointSubset{
  7383. {
  7384. Addresses: []api.EndpointAddress{{}},
  7385. Ports: []api.EndpointPort{{Name: "a", Port: 93, Protocol: "TCP"}},
  7386. },
  7387. },
  7388. },
  7389. errorType: "FieldValueInvalid",
  7390. errorDetail: "must be a valid IP address",
  7391. },
  7392. "Port missing number": {
  7393. endpoints: api.Endpoints{
  7394. ObjectMeta: api.ObjectMeta{Name: "mysvc", Namespace: "namespace"},
  7395. Subsets: []api.EndpointSubset{
  7396. {
  7397. Addresses: []api.EndpointAddress{{IP: "10.10.1.1"}},
  7398. Ports: []api.EndpointPort{{Name: "a", Protocol: "TCP"}},
  7399. },
  7400. },
  7401. },
  7402. errorType: "FieldValueInvalid",
  7403. errorDetail: "between",
  7404. },
  7405. "Port missing protocol": {
  7406. endpoints: api.Endpoints{
  7407. ObjectMeta: api.ObjectMeta{Name: "mysvc", Namespace: "namespace"},
  7408. Subsets: []api.EndpointSubset{
  7409. {
  7410. Addresses: []api.EndpointAddress{{IP: "10.10.1.1"}},
  7411. Ports: []api.EndpointPort{{Name: "a", Port: 93}},
  7412. },
  7413. },
  7414. },
  7415. errorType: "FieldValueRequired",
  7416. },
  7417. "Address is loopback": {
  7418. endpoints: api.Endpoints{
  7419. ObjectMeta: api.ObjectMeta{Name: "mysvc", Namespace: "namespace"},
  7420. Subsets: []api.EndpointSubset{
  7421. {
  7422. Addresses: []api.EndpointAddress{{IP: "127.0.0.1"}},
  7423. Ports: []api.EndpointPort{{Name: "p", Port: 93, Protocol: "TCP"}},
  7424. },
  7425. },
  7426. },
  7427. errorType: "FieldValueInvalid",
  7428. errorDetail: "loopback",
  7429. },
  7430. "Address is link-local": {
  7431. endpoints: api.Endpoints{
  7432. ObjectMeta: api.ObjectMeta{Name: "mysvc", Namespace: "namespace"},
  7433. Subsets: []api.EndpointSubset{
  7434. {
  7435. Addresses: []api.EndpointAddress{{IP: "169.254.169.254"}},
  7436. Ports: []api.EndpointPort{{Name: "p", Port: 93, Protocol: "TCP"}},
  7437. },
  7438. },
  7439. },
  7440. errorType: "FieldValueInvalid",
  7441. errorDetail: "link-local",
  7442. },
  7443. "Address is link-local multicast": {
  7444. endpoints: api.Endpoints{
  7445. ObjectMeta: api.ObjectMeta{Name: "mysvc", Namespace: "namespace"},
  7446. Subsets: []api.EndpointSubset{
  7447. {
  7448. Addresses: []api.EndpointAddress{{IP: "224.0.0.1"}},
  7449. Ports: []api.EndpointPort{{Name: "p", Port: 93, Protocol: "TCP"}},
  7450. },
  7451. },
  7452. },
  7453. errorType: "FieldValueInvalid",
  7454. errorDetail: "link-local multicast",
  7455. },
  7456. }
  7457. for k, v := range errorCases {
  7458. if errs := ValidateEndpoints(&v.endpoints); len(errs) == 0 || errs[0].Type != v.errorType || !strings.Contains(errs[0].Detail, v.errorDetail) {
  7459. t.Errorf("[%s] Expected error type %s with detail %q, got %v", k, v.errorType, v.errorDetail, errs)
  7460. }
  7461. }
  7462. }
  7463. func TestValidateTLSSecret(t *testing.T) {
  7464. successCases := map[string]api.Secret{
  7465. "emtpy certificate chain": {
  7466. ObjectMeta: api.ObjectMeta{Name: "tls-cert", Namespace: "namespace"},
  7467. Data: map[string][]byte{
  7468. api.TLSCertKey: []byte("public key"),
  7469. api.TLSPrivateKeyKey: []byte("private key"),
  7470. },
  7471. },
  7472. }
  7473. for k, v := range successCases {
  7474. if errs := ValidateSecret(&v); len(errs) != 0 {
  7475. t.Errorf("Expected success for %s, got %v", k, errs)
  7476. }
  7477. }
  7478. errorCases := map[string]struct {
  7479. secrets api.Secret
  7480. errorType field.ErrorType
  7481. errorDetail string
  7482. }{
  7483. "missing public key": {
  7484. secrets: api.Secret{
  7485. ObjectMeta: api.ObjectMeta{Name: "tls-cert"},
  7486. Data: map[string][]byte{
  7487. api.TLSCertKey: []byte("public key"),
  7488. },
  7489. },
  7490. errorType: "FieldValueRequired",
  7491. },
  7492. "missing private key": {
  7493. secrets: api.Secret{
  7494. ObjectMeta: api.ObjectMeta{Name: "tls-cert"},
  7495. Data: map[string][]byte{
  7496. api.TLSCertKey: []byte("public key"),
  7497. },
  7498. },
  7499. errorType: "FieldValueRequired",
  7500. },
  7501. }
  7502. for k, v := range errorCases {
  7503. if errs := ValidateSecret(&v.secrets); len(errs) == 0 || errs[0].Type != v.errorType || !strings.Contains(errs[0].Detail, v.errorDetail) {
  7504. t.Errorf("[%s] Expected error type %s with detail %q, got %v", k, v.errorType, v.errorDetail, errs)
  7505. }
  7506. }
  7507. }
  7508. func TestValidateSecurityContext(t *testing.T) {
  7509. priv := false
  7510. var runAsUser int64 = 1
  7511. fullValidSC := func() *api.SecurityContext {
  7512. return &api.SecurityContext{
  7513. Privileged: &priv,
  7514. Capabilities: &api.Capabilities{
  7515. Add: []api.Capability{"foo"},
  7516. Drop: []api.Capability{"bar"},
  7517. },
  7518. SELinuxOptions: &api.SELinuxOptions{
  7519. User: "user",
  7520. Role: "role",
  7521. Type: "type",
  7522. Level: "level",
  7523. },
  7524. RunAsUser: &runAsUser,
  7525. }
  7526. }
  7527. //setup data
  7528. allSettings := fullValidSC()
  7529. noCaps := fullValidSC()
  7530. noCaps.Capabilities = nil
  7531. noSELinux := fullValidSC()
  7532. noSELinux.SELinuxOptions = nil
  7533. noPrivRequest := fullValidSC()
  7534. noPrivRequest.Privileged = nil
  7535. noRunAsUser := fullValidSC()
  7536. noRunAsUser.RunAsUser = nil
  7537. successCases := map[string]struct {
  7538. sc *api.SecurityContext
  7539. }{
  7540. "all settings": {allSettings},
  7541. "no capabilities": {noCaps},
  7542. "no selinux": {noSELinux},
  7543. "no priv request": {noPrivRequest},
  7544. "no run as user": {noRunAsUser},
  7545. }
  7546. for k, v := range successCases {
  7547. if errs := ValidateSecurityContext(v.sc, field.NewPath("field")); len(errs) != 0 {
  7548. t.Errorf("[%s] Expected success, got %v", k, errs)
  7549. }
  7550. }
  7551. privRequestWithGlobalDeny := fullValidSC()
  7552. requestPrivileged := true
  7553. privRequestWithGlobalDeny.Privileged = &requestPrivileged
  7554. negativeRunAsUser := fullValidSC()
  7555. var negativeUser int64 = -1
  7556. negativeRunAsUser.RunAsUser = &negativeUser
  7557. errorCases := map[string]struct {
  7558. sc *api.SecurityContext
  7559. errorType field.ErrorType
  7560. errorDetail string
  7561. }{
  7562. "request privileged when capabilities forbids": {
  7563. sc: privRequestWithGlobalDeny,
  7564. errorType: "FieldValueForbidden",
  7565. errorDetail: "disallowed by policy",
  7566. },
  7567. "negative RunAsUser": {
  7568. sc: negativeRunAsUser,
  7569. errorType: "FieldValueInvalid",
  7570. errorDetail: isNegativeErrorMsg,
  7571. },
  7572. }
  7573. for k, v := range errorCases {
  7574. if errs := ValidateSecurityContext(v.sc, field.NewPath("field")); len(errs) == 0 || errs[0].Type != v.errorType || !strings.Contains(errs[0].Detail, v.errorDetail) {
  7575. t.Errorf("[%s] Expected error type %q with detail %q, got %v", k, v.errorType, v.errorDetail, errs)
  7576. }
  7577. }
  7578. }
  7579. func fakeValidSecurityContext(priv bool) *api.SecurityContext {
  7580. return &api.SecurityContext{
  7581. Privileged: &priv,
  7582. }
  7583. }
  7584. func TestValidPodLogOptions(t *testing.T) {
  7585. now := unversioned.Now()
  7586. negative := int64(-1)
  7587. zero := int64(0)
  7588. positive := int64(1)
  7589. tests := []struct {
  7590. opt api.PodLogOptions
  7591. errs int
  7592. }{
  7593. {api.PodLogOptions{}, 0},
  7594. {api.PodLogOptions{Previous: true}, 0},
  7595. {api.PodLogOptions{Follow: true}, 0},
  7596. {api.PodLogOptions{TailLines: &zero}, 0},
  7597. {api.PodLogOptions{TailLines: &negative}, 1},
  7598. {api.PodLogOptions{TailLines: &positive}, 0},
  7599. {api.PodLogOptions{LimitBytes: &zero}, 1},
  7600. {api.PodLogOptions{LimitBytes: &negative}, 1},
  7601. {api.PodLogOptions{LimitBytes: &positive}, 0},
  7602. {api.PodLogOptions{SinceSeconds: &negative}, 1},
  7603. {api.PodLogOptions{SinceSeconds: &positive}, 0},
  7604. {api.PodLogOptions{SinceSeconds: &zero}, 1},
  7605. {api.PodLogOptions{SinceTime: &now}, 0},
  7606. }
  7607. for i, test := range tests {
  7608. errs := ValidatePodLogOptions(&test.opt)
  7609. if test.errs != len(errs) {
  7610. t.Errorf("%d: Unexpected errors: %v", i, errs)
  7611. }
  7612. }
  7613. }
  7614. func TestValidateConfigMap(t *testing.T) {
  7615. newConfigMap := func(name, namespace string, data map[string]string) api.ConfigMap {
  7616. return api.ConfigMap{
  7617. ObjectMeta: api.ObjectMeta{
  7618. Name: name,
  7619. Namespace: namespace,
  7620. },
  7621. Data: data,
  7622. }
  7623. }
  7624. var (
  7625. validConfigMap = newConfigMap("validname", "validns", map[string]string{"key": "value"})
  7626. maxKeyLength = newConfigMap("validname", "validns", map[string]string{strings.Repeat("a", 253): "value"})
  7627. emptyName = newConfigMap("", "validns", nil)
  7628. invalidName = newConfigMap("NoUppercaseOrSpecialCharsLike=Equals", "validns", nil)
  7629. emptyNs = newConfigMap("validname", "", nil)
  7630. invalidNs = newConfigMap("validname", "NoUppercaseOrSpecialCharsLike=Equals", nil)
  7631. invalidKey = newConfigMap("validname", "validns", map[string]string{"a*b": "value"})
  7632. leadingDotKey = newConfigMap("validname", "validns", map[string]string{".ab": "value"})
  7633. dotKey = newConfigMap("validname", "validns", map[string]string{".": "value"})
  7634. doubleDotKey = newConfigMap("validname", "validns", map[string]string{"..": "value"})
  7635. overMaxKeyLength = newConfigMap("validname", "validns", map[string]string{strings.Repeat("a", 254): "value"})
  7636. overMaxSize = newConfigMap("validname", "validns", map[string]string{"key": strings.Repeat("a", api.MaxSecretSize+1)})
  7637. )
  7638. tests := map[string]struct {
  7639. cfg api.ConfigMap
  7640. isValid bool
  7641. }{
  7642. "valid": {validConfigMap, true},
  7643. "max key length": {maxKeyLength, true},
  7644. "leading dot key": {leadingDotKey, true},
  7645. "empty name": {emptyName, false},
  7646. "invalid name": {invalidName, false},
  7647. "invalid key": {invalidKey, false},
  7648. "empty namespace": {emptyNs, false},
  7649. "invalid namespace": {invalidNs, false},
  7650. "dot key": {dotKey, false},
  7651. "double dot key": {doubleDotKey, false},
  7652. "over max key length": {overMaxKeyLength, false},
  7653. "over max size": {overMaxSize, false},
  7654. }
  7655. for name, tc := range tests {
  7656. errs := ValidateConfigMap(&tc.cfg)
  7657. if tc.isValid && len(errs) > 0 {
  7658. t.Errorf("%v: unexpected error: %v", name, errs)
  7659. }
  7660. if !tc.isValid && len(errs) == 0 {
  7661. t.Errorf("%v: unexpected non-error", name)
  7662. }
  7663. }
  7664. }
  7665. func TestValidateConfigMapUpdate(t *testing.T) {
  7666. newConfigMap := func(version, name, namespace string, data map[string]string) api.ConfigMap {
  7667. return api.ConfigMap{
  7668. ObjectMeta: api.ObjectMeta{
  7669. Name: name,
  7670. Namespace: namespace,
  7671. ResourceVersion: version,
  7672. },
  7673. Data: data,
  7674. }
  7675. }
  7676. var (
  7677. validConfigMap = newConfigMap("1", "validname", "validns", map[string]string{"key": "value"})
  7678. noVersion = newConfigMap("", "validname", "validns", map[string]string{"key": "value"})
  7679. )
  7680. cases := []struct {
  7681. name string
  7682. newCfg api.ConfigMap
  7683. oldCfg api.ConfigMap
  7684. isValid bool
  7685. }{
  7686. {
  7687. name: "valid",
  7688. newCfg: validConfigMap,
  7689. oldCfg: validConfigMap,
  7690. isValid: true,
  7691. },
  7692. {
  7693. name: "invalid",
  7694. newCfg: noVersion,
  7695. oldCfg: validConfigMap,
  7696. isValid: false,
  7697. },
  7698. }
  7699. for _, tc := range cases {
  7700. errs := ValidateConfigMapUpdate(&tc.newCfg, &tc.oldCfg)
  7701. if tc.isValid && len(errs) > 0 {
  7702. t.Errorf("%v: unexpected error: %v", tc.name, errs)
  7703. }
  7704. if !tc.isValid && len(errs) == 0 {
  7705. t.Errorf("%v: unexpected non-error", tc.name)
  7706. }
  7707. }
  7708. }
  7709. func TestValidateHasLabel(t *testing.T) {
  7710. successCase := api.ObjectMeta{
  7711. Name: "123",
  7712. Namespace: "ns",
  7713. Labels: map[string]string{
  7714. "other": "blah",
  7715. "foo": "bar",
  7716. },
  7717. }
  7718. if errs := ValidateHasLabel(successCase, field.NewPath("field"), "foo", "bar"); len(errs) != 0 {
  7719. t.Errorf("expected success: %v", errs)
  7720. }
  7721. missingCase := api.ObjectMeta{
  7722. Name: "123",
  7723. Namespace: "ns",
  7724. Labels: map[string]string{
  7725. "other": "blah",
  7726. },
  7727. }
  7728. if errs := ValidateHasLabel(missingCase, field.NewPath("field"), "foo", "bar"); len(errs) == 0 {
  7729. t.Errorf("expected failure")
  7730. }
  7731. wrongValueCase := api.ObjectMeta{
  7732. Name: "123",
  7733. Namespace: "ns",
  7734. Labels: map[string]string{
  7735. "other": "blah",
  7736. "foo": "notbar",
  7737. },
  7738. }
  7739. if errs := ValidateHasLabel(wrongValueCase, field.NewPath("field"), "foo", "bar"); len(errs) == 0 {
  7740. t.Errorf("expected failure")
  7741. }
  7742. }
  7743. func TestIsValidSysctlName(t *testing.T) {
  7744. valid := []string{
  7745. "a.b.c.d",
  7746. "a",
  7747. "a_b",
  7748. "a-b",
  7749. "abc",
  7750. "abc.def",
  7751. }
  7752. invalid := []string{
  7753. "",
  7754. "*",
  7755. "ä",
  7756. "a_",
  7757. "_",
  7758. "__",
  7759. "_a",
  7760. "_a._b",
  7761. "-",
  7762. ".",
  7763. "a.",
  7764. ".a",
  7765. "a.b.",
  7766. "a*.b",
  7767. "a*b",
  7768. "*a",
  7769. "a.*",
  7770. "*",
  7771. "abc*",
  7772. "a.abc*",
  7773. "a.b.*",
  7774. "Abc",
  7775. func(n int) string {
  7776. x := make([]byte, n)
  7777. for i := range x {
  7778. x[i] = byte('a')
  7779. }
  7780. return string(x)
  7781. }(256),
  7782. }
  7783. for _, s := range valid {
  7784. if !IsValidSysctlName(s) {
  7785. t.Errorf("%q expected to be a valid sysctl name", s)
  7786. }
  7787. }
  7788. for _, s := range invalid {
  7789. if IsValidSysctlName(s) {
  7790. t.Errorf("%q expected to be an invalid sysctl name", s)
  7791. }
  7792. }
  7793. }
  7794. func TestValidateSysctls(t *testing.T) {
  7795. valid := []string{
  7796. "net.foo.bar",
  7797. "kernel.shmmax",
  7798. }
  7799. invalid := []string{
  7800. "i..nvalid",
  7801. "_invalid",
  7802. }
  7803. sysctls := make([]api.Sysctl, len(valid))
  7804. for i, sysctl := range valid {
  7805. sysctls[i].Name = sysctl
  7806. }
  7807. errs := validateSysctls(sysctls, field.NewPath("foo"))
  7808. if len(errs) != 0 {
  7809. t.Errorf("unexpected validation errors: %v", errs)
  7810. }
  7811. sysctls = make([]api.Sysctl, len(invalid))
  7812. for i, sysctl := range invalid {
  7813. sysctls[i].Name = sysctl
  7814. }
  7815. errs = validateSysctls(sysctls, field.NewPath("foo"))
  7816. if len(errs) != 2 {
  7817. t.Errorf("expected 2 validation errors. Got: %v", errs)
  7818. } else {
  7819. if got, expected := errs[0].Error(), "foo"; !strings.Contains(got, expected) {
  7820. t.Errorf("unexpected errors: expected=%q, got=%q", expected, got)
  7821. }
  7822. if got, expected := errs[1].Error(), "foo"; !strings.Contains(got, expected) {
  7823. t.Errorf("unexpected errors: expected=%q, got=%q", expected, got)
  7824. }
  7825. }
  7826. }
  7827. func newNodeNameEndpoint(nodeName string) *api.Endpoints {
  7828. ep := &api.Endpoints{
  7829. ObjectMeta: api.ObjectMeta{
  7830. Name: "foo",
  7831. Namespace: api.NamespaceDefault,
  7832. ResourceVersion: "1",
  7833. },
  7834. Subsets: []api.EndpointSubset{
  7835. {
  7836. NotReadyAddresses: []api.EndpointAddress{},
  7837. Ports: []api.EndpointPort{{Name: "https", Port: 443, Protocol: "TCP"}},
  7838. Addresses: []api.EndpointAddress{
  7839. {
  7840. IP: "8.8.8.8",
  7841. Hostname: "zookeeper1",
  7842. NodeName: &nodeName}}}}}
  7843. return ep
  7844. }
  7845. func TestEndpointAddressNodeNameUpdateRestrictions(t *testing.T) {
  7846. oldEndpoint := newNodeNameEndpoint("kubernetes-minion-setup-by-backend")
  7847. updatedEndpoint := newNodeNameEndpoint("kubernetes-changed-nodename")
  7848. // Check that NodeName cannot be changed during update (if already set)
  7849. errList := ValidateEndpoints(updatedEndpoint)
  7850. errList = append(errList, ValidateEndpointsUpdate(updatedEndpoint, oldEndpoint)...)
  7851. if len(errList) == 0 {
  7852. t.Error("Endpoint should not allow changing of Subset.Addresses.NodeName on update")
  7853. }
  7854. }
  7855. func TestEndpointAddressNodeNameInvalidDNS1123(t *testing.T) {
  7856. // Check NodeName DNS validation
  7857. endpoint := newNodeNameEndpoint("illegal.nodename")
  7858. errList := ValidateEndpoints(endpoint)
  7859. if len(errList) == 0 {
  7860. t.Error("Endpoint should reject invalid NodeName")
  7861. }
  7862. }