docker_cli_build_test.go 180 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792
  1. package main
  2. import (
  3. "archive/tar"
  4. "bytes"
  5. "encoding/json"
  6. "fmt"
  7. "io/ioutil"
  8. "os"
  9. "os/exec"
  10. "path/filepath"
  11. "reflect"
  12. "regexp"
  13. "runtime"
  14. "strconv"
  15. "strings"
  16. "text/template"
  17. "time"
  18. "github.com/docker/docker/builder/dockerfile/command"
  19. "github.com/docker/docker/integration-cli/checker"
  20. "github.com/docker/docker/pkg/archive"
  21. "github.com/docker/docker/pkg/stringutils"
  22. "github.com/docker/docker/pkg/testutil"
  23. icmd "github.com/docker/docker/pkg/testutil/cmd"
  24. "github.com/go-check/check"
  25. )
  26. func (s *DockerSuite) TestBuildJSONEmptyRun(c *check.C) {
  27. buildImageSuccessfully(c, "testbuildjsonemptyrun", withDockerfile(`
  28. FROM busybox
  29. RUN []
  30. `))
  31. }
  32. func (s *DockerSuite) TestBuildShCmdJSONEntrypoint(c *check.C) {
  33. name := "testbuildshcmdjsonentrypoint"
  34. expected := "/bin/sh -c echo test"
  35. if testEnv.DaemonPlatform() == "windows" {
  36. expected = "cmd /S /C echo test"
  37. }
  38. buildImageSuccessfully(c, name, withDockerfile(`
  39. FROM busybox
  40. ENTRYPOINT ["echo"]
  41. CMD echo test
  42. `))
  43. out, _ := dockerCmd(c, "run", "--rm", name)
  44. if strings.TrimSpace(out) != expected {
  45. c.Fatalf("CMD did not contain %q : %q", expected, out)
  46. }
  47. }
  48. func (s *DockerSuite) TestBuildEnvironmentReplacementUser(c *check.C) {
  49. // Windows does not support FROM scratch or the USER command
  50. testRequires(c, DaemonIsLinux)
  51. name := "testbuildenvironmentreplacement"
  52. buildImageSuccessfully(c, name, withDockerfile(`
  53. FROM scratch
  54. ENV user foo
  55. USER ${user}
  56. `))
  57. res := inspectFieldJSON(c, name, "Config.User")
  58. if res != `"foo"` {
  59. c.Fatal("User foo from environment not in Config.User on image")
  60. }
  61. }
  62. func (s *DockerSuite) TestBuildEnvironmentReplacementVolume(c *check.C) {
  63. name := "testbuildenvironmentreplacement"
  64. var volumePath string
  65. if testEnv.DaemonPlatform() == "windows" {
  66. volumePath = "c:/quux"
  67. } else {
  68. volumePath = "/quux"
  69. }
  70. buildImageSuccessfully(c, name, withDockerfile(`
  71. FROM `+minimalBaseImage()+`
  72. ENV volume `+volumePath+`
  73. VOLUME ${volume}
  74. `))
  75. var volumes map[string]interface{}
  76. inspectFieldAndUnmarshall(c, name, "Config.Volumes", &volumes)
  77. if _, ok := volumes[volumePath]; !ok {
  78. c.Fatal("Volume " + volumePath + " from environment not in Config.Volumes on image")
  79. }
  80. }
  81. func (s *DockerSuite) TestBuildEnvironmentReplacementExpose(c *check.C) {
  82. // Windows does not support FROM scratch or the EXPOSE command
  83. testRequires(c, DaemonIsLinux)
  84. name := "testbuildenvironmentreplacement"
  85. buildImageSuccessfully(c, name, withDockerfile(`
  86. FROM scratch
  87. ENV port 80
  88. EXPOSE ${port}
  89. ENV ports " 99 100 "
  90. EXPOSE ${ports}
  91. `))
  92. var exposedPorts map[string]interface{}
  93. inspectFieldAndUnmarshall(c, name, "Config.ExposedPorts", &exposedPorts)
  94. exp := []int{80, 99, 100}
  95. for _, p := range exp {
  96. tmp := fmt.Sprintf("%d/tcp", p)
  97. if _, ok := exposedPorts[tmp]; !ok {
  98. c.Fatalf("Exposed port %d from environment not in Config.ExposedPorts on image", p)
  99. }
  100. }
  101. }
  102. func (s *DockerSuite) TestBuildEnvironmentReplacementWorkdir(c *check.C) {
  103. name := "testbuildenvironmentreplacement"
  104. buildImageSuccessfully(c, name, withDockerfile(`
  105. FROM busybox
  106. ENV MYWORKDIR /work
  107. RUN mkdir ${MYWORKDIR}
  108. WORKDIR ${MYWORKDIR}
  109. `))
  110. res := inspectFieldJSON(c, name, "Config.WorkingDir")
  111. expected := `"/work"`
  112. if testEnv.DaemonPlatform() == "windows" {
  113. expected = `"C:\\work"`
  114. }
  115. if res != expected {
  116. c.Fatalf("Workdir /workdir from environment not in Config.WorkingDir on image: %s", res)
  117. }
  118. }
  119. func (s *DockerSuite) TestBuildEnvironmentReplacementAddCopy(c *check.C) {
  120. name := "testbuildenvironmentreplacement"
  121. buildImageSuccessfully(c, name, withBuildContext(c,
  122. withFile("Dockerfile", `
  123. FROM `+minimalBaseImage()+`
  124. ENV baz foo
  125. ENV quux bar
  126. ENV dot .
  127. ENV fee fff
  128. ENV gee ggg
  129. ADD ${baz} ${dot}
  130. COPY ${quux} ${dot}
  131. ADD ${zzz:-${fee}} ${dot}
  132. COPY ${zzz:-${gee}} ${dot}
  133. `),
  134. withFile("foo", "test1"),
  135. withFile("bar", "test2"),
  136. withFile("fff", "test3"),
  137. withFile("ggg", "test4"),
  138. ))
  139. }
  140. func (s *DockerSuite) TestBuildEnvironmentReplacementEnv(c *check.C) {
  141. // ENV expansions work differently in Windows
  142. testRequires(c, DaemonIsLinux)
  143. name := "testbuildenvironmentreplacement"
  144. buildImageSuccessfully(c, name, withDockerfile(`
  145. FROM busybox
  146. ENV foo zzz
  147. ENV bar ${foo}
  148. ENV abc1='$foo'
  149. ENV env1=$foo env2=${foo} env3="$foo" env4="${foo}"
  150. RUN [ "$abc1" = '$foo' ] && (echo "$abc1" | grep -q foo)
  151. ENV abc2="\$foo"
  152. RUN [ "$abc2" = '$foo' ] && (echo "$abc2" | grep -q foo)
  153. ENV abc3 '$foo'
  154. RUN [ "$abc3" = '$foo' ] && (echo "$abc3" | grep -q foo)
  155. ENV abc4 "\$foo"
  156. RUN [ "$abc4" = '$foo' ] && (echo "$abc4" | grep -q foo)
  157. `))
  158. envResult := []string{}
  159. inspectFieldAndUnmarshall(c, name, "Config.Env", &envResult)
  160. found := false
  161. envCount := 0
  162. for _, env := range envResult {
  163. parts := strings.SplitN(env, "=", 2)
  164. if parts[0] == "bar" {
  165. found = true
  166. if parts[1] != "zzz" {
  167. c.Fatalf("Could not find replaced var for env `bar`: got %q instead of `zzz`", parts[1])
  168. }
  169. } else if strings.HasPrefix(parts[0], "env") {
  170. envCount++
  171. if parts[1] != "zzz" {
  172. c.Fatalf("%s should be 'foo' but instead its %q", parts[0], parts[1])
  173. }
  174. } else if strings.HasPrefix(parts[0], "env") {
  175. envCount++
  176. if parts[1] != "foo" {
  177. c.Fatalf("%s should be 'foo' but instead its %q", parts[0], parts[1])
  178. }
  179. }
  180. }
  181. if !found {
  182. c.Fatal("Never found the `bar` env variable")
  183. }
  184. if envCount != 4 {
  185. c.Fatalf("Didn't find all env vars - only saw %d\n%s", envCount, envResult)
  186. }
  187. }
  188. func (s *DockerSuite) TestBuildHandleEscapesInVolume(c *check.C) {
  189. // The volume paths used in this test are invalid on Windows
  190. testRequires(c, DaemonIsLinux)
  191. name := "testbuildhandleescapes"
  192. testCases := []struct {
  193. volumeValue string
  194. expected string
  195. }{
  196. {
  197. volumeValue: "${FOO}",
  198. expected: "bar",
  199. },
  200. {
  201. volumeValue: `\${FOO}`,
  202. expected: "${FOO}",
  203. },
  204. // this test in particular provides *7* backslashes and expects 6 to come back.
  205. // Like above, the first escape is swallowed and the rest are treated as
  206. // literals, this one is just less obvious because of all the character noise.
  207. {
  208. volumeValue: `\\\\\\\${FOO}`,
  209. expected: `\\\${FOO}`,
  210. },
  211. }
  212. for _, tc := range testCases {
  213. buildImageSuccessfully(c, name, withDockerfile(fmt.Sprintf(`
  214. FROM scratch
  215. ENV FOO bar
  216. VOLUME %s
  217. `, tc.volumeValue)))
  218. var result map[string]map[string]struct{}
  219. inspectFieldAndUnmarshall(c, name, "Config.Volumes", &result)
  220. if _, ok := result[tc.expected]; !ok {
  221. c.Fatalf("Could not find volume %s set from env foo in volumes table, got %q", tc.expected, result)
  222. }
  223. // Remove the image for the next iteration
  224. dockerCmd(c, "rmi", name)
  225. }
  226. }
  227. func (s *DockerSuite) TestBuildOnBuildLowercase(c *check.C) {
  228. name := "testbuildonbuildlowercase"
  229. name2 := "testbuildonbuildlowercase2"
  230. buildImageSuccessfully(c, name, withDockerfile(`
  231. FROM busybox
  232. onbuild run echo quux
  233. `))
  234. result := buildImage(name2, withDockerfile(fmt.Sprintf(`
  235. FROM %s
  236. `, name)))
  237. result.Assert(c, icmd.Success)
  238. if !strings.Contains(result.Combined(), "quux") {
  239. c.Fatalf("Did not receive the expected echo text, got %s", result.Combined())
  240. }
  241. if strings.Contains(result.Combined(), "ONBUILD ONBUILD") {
  242. c.Fatalf("Got an ONBUILD ONBUILD error with no error: got %s", result.Combined())
  243. }
  244. }
  245. func (s *DockerSuite) TestBuildEnvEscapes(c *check.C) {
  246. // ENV expansions work differently in Windows
  247. testRequires(c, DaemonIsLinux)
  248. name := "testbuildenvescapes"
  249. buildImageSuccessfully(c, name, withDockerfile(`
  250. FROM busybox
  251. ENV TEST foo
  252. CMD echo \$
  253. `))
  254. out, _ := dockerCmd(c, "run", "-t", name)
  255. if strings.TrimSpace(out) != "$" {
  256. c.Fatalf("Env TEST was not overwritten with bar when foo was supplied to dockerfile: was %q", strings.TrimSpace(out))
  257. }
  258. }
  259. func (s *DockerSuite) TestBuildEnvOverwrite(c *check.C) {
  260. // ENV expansions work differently in Windows
  261. testRequires(c, DaemonIsLinux)
  262. name := "testbuildenvoverwrite"
  263. buildImageSuccessfully(c, name, withDockerfile(`
  264. FROM busybox
  265. ENV TEST foo
  266. CMD echo ${TEST}
  267. `))
  268. out, _ := dockerCmd(c, "run", "-e", "TEST=bar", "-t", name)
  269. if strings.TrimSpace(out) != "bar" {
  270. c.Fatalf("Env TEST was not overwritten with bar when foo was supplied to dockerfile: was %q", strings.TrimSpace(out))
  271. }
  272. }
  273. // FIXME(vdemeester) why we disabled cache here ?
  274. func (s *DockerSuite) TestBuildOnBuildCmdEntrypointJSON(c *check.C) {
  275. name1 := "onbuildcmd"
  276. name2 := "onbuildgenerated"
  277. buildImageSuccessfully(c, name1, withDockerfile(`
  278. FROM busybox
  279. ONBUILD CMD ["hello world"]
  280. ONBUILD ENTRYPOINT ["echo"]
  281. ONBUILD RUN ["true"]`))
  282. buildImageSuccessfully(c, name2, withDockerfile(fmt.Sprintf(`FROM %s`, name1)))
  283. out, _ := dockerCmd(c, "run", name2)
  284. if !regexp.MustCompile(`(?m)^hello world`).MatchString(out) {
  285. c.Fatalf("did not get echo output from onbuild. Got: %q", out)
  286. }
  287. }
  288. // FIXME(vdemeester) why we disabled cache here ?
  289. func (s *DockerSuite) TestBuildOnBuildEntrypointJSON(c *check.C) {
  290. name1 := "onbuildcmd"
  291. name2 := "onbuildgenerated"
  292. buildImageSuccessfully(c, name1, withDockerfile(`
  293. FROM busybox
  294. ONBUILD ENTRYPOINT ["echo"]`))
  295. buildImageSuccessfully(c, name2, withDockerfile(fmt.Sprintf("FROM %s\nCMD [\"hello world\"]\n", name1)))
  296. out, _ := dockerCmd(c, "run", name2)
  297. if !regexp.MustCompile(`(?m)^hello world`).MatchString(out) {
  298. c.Fatal("got malformed output from onbuild", out)
  299. }
  300. }
  301. func (s *DockerSuite) TestBuildCacheAdd(c *check.C) {
  302. testRequires(c, DaemonIsLinux) // Windows doesn't have httpserver image yet
  303. name := "testbuildtwoimageswithadd"
  304. server := fakeStorage(c, map[string]string{
  305. "robots.txt": "hello",
  306. "index.html": "world",
  307. })
  308. defer server.Close()
  309. buildImageSuccessfully(c, name, withDockerfile(fmt.Sprintf(`FROM scratch
  310. ADD %s/robots.txt /`, server.URL())))
  311. result := buildImage(name, withDockerfile(fmt.Sprintf(`FROM scratch
  312. ADD %s/index.html /`, server.URL())))
  313. result.Assert(c, icmd.Success)
  314. if strings.Contains(result.Combined(), "Using cache") {
  315. c.Fatal("2nd build used cache on ADD, it shouldn't")
  316. }
  317. }
  318. func (s *DockerSuite) TestBuildLastModified(c *check.C) {
  319. name := "testbuildlastmodified"
  320. server := fakeStorage(c, map[string]string{
  321. "file": "hello",
  322. })
  323. defer server.Close()
  324. var out, out2 string
  325. dFmt := `FROM busybox
  326. ADD %s/file /`
  327. dockerfile := fmt.Sprintf(dFmt, server.URL())
  328. buildImageSuccessfully(c, name, withoutCache, withDockerfile(dockerfile))
  329. out, _ = dockerCmd(c, "run", name, "ls", "-le", "/file")
  330. // Build it again and make sure the mtime of the file didn't change.
  331. // Wait a few seconds to make sure the time changed enough to notice
  332. time.Sleep(2 * time.Second)
  333. buildImageSuccessfully(c, name, withoutCache, withDockerfile(dockerfile))
  334. out2, _ = dockerCmd(c, "run", name, "ls", "-le", "/file")
  335. if out != out2 {
  336. c.Fatalf("MTime changed:\nOrigin:%s\nNew:%s", out, out2)
  337. }
  338. // Now 'touch' the file and make sure the timestamp DID change this time
  339. // Create a new fakeStorage instead of just using Add() to help windows
  340. server = fakeStorage(c, map[string]string{
  341. "file": "hello",
  342. })
  343. defer server.Close()
  344. dockerfile = fmt.Sprintf(dFmt, server.URL())
  345. buildImageSuccessfully(c, name, withoutCache, withDockerfile(dockerfile))
  346. out2, _ = dockerCmd(c, "run", name, "ls", "-le", "/file")
  347. if out == out2 {
  348. c.Fatalf("MTime didn't change:\nOrigin:%s\nNew:%s", out, out2)
  349. }
  350. }
  351. // Regression for https://github.com/docker/docker/pull/27805
  352. // Makes sure that we don't use the cache if the contents of
  353. // a file in a subfolder of the context is modified and we re-build.
  354. func (s *DockerSuite) TestBuildModifyFileInFolder(c *check.C) {
  355. name := "testbuildmodifyfileinfolder"
  356. ctx := fakeContext(c, `FROM busybox
  357. RUN ["mkdir", "/test"]
  358. ADD folder/file /test/changetarget`,
  359. map[string]string{})
  360. defer ctx.Close()
  361. if err := ctx.Add("folder/file", "first"); err != nil {
  362. c.Fatal(err)
  363. }
  364. buildImageSuccessfully(c, name, withExternalBuildContext(ctx))
  365. id1 := getIDByName(c, name)
  366. if err := ctx.Add("folder/file", "second"); err != nil {
  367. c.Fatal(err)
  368. }
  369. buildImageSuccessfully(c, name, withExternalBuildContext(ctx))
  370. id2 := getIDByName(c, name)
  371. if id1 == id2 {
  372. c.Fatal("cache was used even though file contents in folder was changed")
  373. }
  374. }
  375. func (s *DockerSuite) TestBuildAddSingleFileToRoot(c *check.C) {
  376. testRequires(c, DaemonIsLinux) // Linux specific test
  377. buildImageSuccessfully(c, "testaddimg", withBuildContext(c,
  378. withFile("Dockerfile", fmt.Sprintf(`FROM busybox
  379. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  380. RUN echo 'dockerio:x:1001:' >> /etc/group
  381. RUN touch /exists
  382. RUN chown dockerio.dockerio /exists
  383. ADD test_file /
  384. RUN [ $(ls -l /test_file | awk '{print $3":"$4}') = 'root:root' ]
  385. RUN [ $(ls -l /test_file | awk '{print $1}') = '%s' ]
  386. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`, expectedFileChmod)),
  387. withFile("test_file", "test1")))
  388. }
  389. // Issue #3960: "ADD src ." hangs
  390. func (s *DockerSuite) TestBuildAddSingleFileToWorkdir(c *check.C) {
  391. name := "testaddsinglefiletoworkdir"
  392. ctx := fakeContext(c, `FROM busybox
  393. ADD test_file .`,
  394. map[string]string{
  395. "test_file": "test1",
  396. })
  397. defer ctx.Close()
  398. errChan := make(chan error)
  399. go func() {
  400. errChan <- buildImage(name, withExternalBuildContext(ctx)).Error
  401. close(errChan)
  402. }()
  403. select {
  404. case <-time.After(15 * time.Second):
  405. c.Fatal("Build with adding to workdir timed out")
  406. case err := <-errChan:
  407. c.Assert(err, check.IsNil)
  408. }
  409. }
  410. func (s *DockerSuite) TestBuildAddSingleFileToExistDir(c *check.C) {
  411. testRequires(c, DaemonIsLinux) // Linux specific test
  412. buildImageSuccessfully(c, "testaddsinglefiletoexistdir", withBuildContext(c,
  413. withFile("Dockerfile", `FROM busybox
  414. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  415. RUN echo 'dockerio:x:1001:' >> /etc/group
  416. RUN mkdir /exists
  417. RUN touch /exists/exists_file
  418. RUN chown -R dockerio.dockerio /exists
  419. ADD test_file /exists/
  420. RUN [ $(ls -l / | grep exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  421. RUN [ $(ls -l /exists/test_file | awk '{print $3":"$4}') = 'root:root' ]
  422. RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`),
  423. withFile("test_file", "test1")))
  424. }
  425. func (s *DockerSuite) TestBuildCopyAddMultipleFiles(c *check.C) {
  426. testRequires(c, DaemonIsLinux) // Linux specific test
  427. server := fakeStorage(c, map[string]string{
  428. "robots.txt": "hello",
  429. })
  430. defer server.Close()
  431. buildImageSuccessfully(c, "testcopymultiplefilestofile", withBuildContext(c,
  432. withFile("Dockerfile", fmt.Sprintf(`FROM busybox
  433. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  434. RUN echo 'dockerio:x:1001:' >> /etc/group
  435. RUN mkdir /exists
  436. RUN touch /exists/exists_file
  437. RUN chown -R dockerio.dockerio /exists
  438. COPY test_file1 test_file2 /exists/
  439. ADD test_file3 test_file4 %s/robots.txt /exists/
  440. RUN [ $(ls -l / | grep exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  441. RUN [ $(ls -l /exists/test_file1 | awk '{print $3":"$4}') = 'root:root' ]
  442. RUN [ $(ls -l /exists/test_file2 | awk '{print $3":"$4}') = 'root:root' ]
  443. RUN [ $(ls -l /exists/test_file3 | awk '{print $3":"$4}') = 'root:root' ]
  444. RUN [ $(ls -l /exists/test_file4 | awk '{print $3":"$4}') = 'root:root' ]
  445. RUN [ $(ls -l /exists/robots.txt | awk '{print $3":"$4}') = 'root:root' ]
  446. RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  447. `, server.URL())),
  448. withFile("test_file1", "test1"),
  449. withFile("test_file2", "test2"),
  450. withFile("test_file3", "test3"),
  451. withFile("test_file3", "test3"),
  452. withFile("test_file4", "test4")))
  453. }
  454. // These tests are mainly for user namespaces to verify that new directories
  455. // are created as the remapped root uid/gid pair
  456. func (s *DockerSuite) TestBuildUsernamespaceValidateRemappedRoot(c *check.C) {
  457. testRequires(c, DaemonIsLinux)
  458. testCases := []string{
  459. "ADD . /new_dir",
  460. "COPY test_dir /new_dir",
  461. "WORKDIR /new_dir",
  462. }
  463. name := "testbuildusernamespacevalidateremappedroot"
  464. for _, tc := range testCases {
  465. buildImageSuccessfully(c, name, withBuildContext(c,
  466. withFile("Dockerfile", fmt.Sprintf(`FROM busybox
  467. %s
  468. RUN [ $(ls -l / | grep new_dir | awk '{print $3":"$4}') = 'root:root' ]`, tc)),
  469. withFile("test_dir/test_file", "test file")))
  470. dockerCmd(c, "rmi", name)
  471. }
  472. }
  473. func (s *DockerSuite) TestBuildAddAndCopyFileWithWhitespace(c *check.C) {
  474. testRequires(c, DaemonIsLinux) // Not currently passing on Windows
  475. name := "testaddfilewithwhitespace"
  476. for _, command := range []string{"ADD", "COPY"} {
  477. buildImageSuccessfully(c, name, withBuildContext(c,
  478. withFile("Dockerfile", fmt.Sprintf(`FROM busybox
  479. RUN mkdir "/test dir"
  480. RUN mkdir "/test_dir"
  481. %s [ "test file1", "/test_file1" ]
  482. %s [ "test_file2", "/test file2" ]
  483. %s [ "test file3", "/test file3" ]
  484. %s [ "test dir/test_file4", "/test_dir/test_file4" ]
  485. %s [ "test_dir/test_file5", "/test dir/test_file5" ]
  486. %s [ "test dir/test_file6", "/test dir/test_file6" ]
  487. RUN [ $(cat "/test_file1") = 'test1' ]
  488. RUN [ $(cat "/test file2") = 'test2' ]
  489. RUN [ $(cat "/test file3") = 'test3' ]
  490. RUN [ $(cat "/test_dir/test_file4") = 'test4' ]
  491. RUN [ $(cat "/test dir/test_file5") = 'test5' ]
  492. RUN [ $(cat "/test dir/test_file6") = 'test6' ]`, command, command, command, command, command, command)),
  493. withFile("test file1", "test1"),
  494. withFile("test_file2", "test2"),
  495. withFile("test file3", "test3"),
  496. withFile("test dir/test_file4", "test4"),
  497. withFile("test_dir/test_file5", "test5"),
  498. withFile("test dir/test_file6", "test6"),
  499. ))
  500. dockerCmd(c, "rmi", name)
  501. }
  502. }
  503. func (s *DockerSuite) TestBuildCopyFileWithWhitespaceOnWindows(c *check.C) {
  504. testRequires(c, DaemonIsWindows)
  505. dockerfile := `FROM ` + testEnv.MinimalBaseImage() + `
  506. RUN mkdir "C:/test dir"
  507. RUN mkdir "C:/test_dir"
  508. COPY [ "test file1", "/test_file1" ]
  509. COPY [ "test_file2", "/test file2" ]
  510. COPY [ "test file3", "/test file3" ]
  511. COPY [ "test dir/test_file4", "/test_dir/test_file4" ]
  512. COPY [ "test_dir/test_file5", "/test dir/test_file5" ]
  513. COPY [ "test dir/test_file6", "/test dir/test_file6" ]
  514. RUN find "test1" "C:/test_file1"
  515. RUN find "test2" "C:/test file2"
  516. RUN find "test3" "C:/test file3"
  517. RUN find "test4" "C:/test_dir/test_file4"
  518. RUN find "test5" "C:/test dir/test_file5"
  519. RUN find "test6" "C:/test dir/test_file6"`
  520. name := "testcopyfilewithwhitespace"
  521. buildImageSuccessfully(c, name, withBuildContext(c,
  522. withFile("Dockerfile", dockerfile),
  523. withFile("test file1", "test1"),
  524. withFile("test_file2", "test2"),
  525. withFile("test file3", "test3"),
  526. withFile("test dir/test_file4", "test4"),
  527. withFile("test_dir/test_file5", "test5"),
  528. withFile("test dir/test_file6", "test6"),
  529. ))
  530. }
  531. func (s *DockerSuite) TestBuildCopyWildcard(c *check.C) {
  532. name := "testcopywildcard"
  533. server := fakeStorage(c, map[string]string{
  534. "robots.txt": "hello",
  535. "index.html": "world",
  536. })
  537. defer server.Close()
  538. ctx := fakeContext(c, fmt.Sprintf(`FROM busybox
  539. COPY file*.txt /tmp/
  540. RUN ls /tmp/file1.txt /tmp/file2.txt
  541. RUN [ "mkdir", "/tmp1" ]
  542. COPY dir* /tmp1/
  543. RUN ls /tmp1/dirt /tmp1/nested_file /tmp1/nested_dir/nest_nest_file
  544. RUN [ "mkdir", "/tmp2" ]
  545. ADD dir/*dir %s/robots.txt /tmp2/
  546. RUN ls /tmp2/nest_nest_file /tmp2/robots.txt
  547. `, server.URL()),
  548. map[string]string{
  549. "file1.txt": "test1",
  550. "file2.txt": "test2",
  551. "dir/nested_file": "nested file",
  552. "dir/nested_dir/nest_nest_file": "2 times nested",
  553. "dirt": "dirty",
  554. })
  555. defer ctx.Close()
  556. buildImageSuccessfully(c, name, withExternalBuildContext(ctx))
  557. id1 := getIDByName(c, name)
  558. // Now make sure we use a cache the 2nd time
  559. buildImageSuccessfully(c, name, withExternalBuildContext(ctx))
  560. id2 := getIDByName(c, name)
  561. if id1 != id2 {
  562. c.Fatal("didn't use the cache")
  563. }
  564. }
  565. func (s *DockerSuite) TestBuildCopyWildcardInName(c *check.C) {
  566. // Run this only on Linux
  567. // Below is the original comment (that I don't agree with — vdemeester)
  568. // Normally we would do c.Fatal(err) here but given that
  569. // the odds of this failing are so rare, it must be because
  570. // the OS we're running the client on doesn't support * in
  571. // filenames (like windows). So, instead of failing the test
  572. // just let it pass. Then we don't need to explicitly
  573. // say which OSs this works on or not.
  574. testRequires(c, DaemonIsLinux)
  575. buildImageSuccessfully(c, "testcopywildcardinname", withBuildContext(c,
  576. withFile("Dockerfile", `FROM busybox
  577. COPY *.txt /tmp/
  578. RUN [ "$(cat /tmp/\*.txt)" = 'hi there' ]
  579. `),
  580. withFile("*.txt", "hi there"),
  581. ))
  582. }
  583. func (s *DockerSuite) TestBuildCopyWildcardCache(c *check.C) {
  584. name := "testcopywildcardcache"
  585. ctx := fakeContext(c, `FROM busybox
  586. COPY file1.txt /tmp/`,
  587. map[string]string{
  588. "file1.txt": "test1",
  589. })
  590. defer ctx.Close()
  591. buildImageSuccessfully(c, name, withExternalBuildContext(ctx))
  592. id1 := getIDByName(c, name)
  593. // Now make sure we use a cache the 2nd time even with wild cards.
  594. // Use the same context so the file is the same and the checksum will match
  595. ctx.Add("Dockerfile", `FROM busybox
  596. COPY file*.txt /tmp/`)
  597. buildImageSuccessfully(c, name, withExternalBuildContext(ctx))
  598. id2 := getIDByName(c, name)
  599. if id1 != id2 {
  600. c.Fatal("didn't use the cache")
  601. }
  602. }
  603. func (s *DockerSuite) TestBuildAddSingleFileToNonExistingDir(c *check.C) {
  604. testRequires(c, DaemonIsLinux) // Linux specific test
  605. buildImageSuccessfully(c, "testaddsinglefiletononexistingdir", withBuildContext(c,
  606. withFile("Dockerfile", `FROM busybox
  607. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  608. RUN echo 'dockerio:x:1001:' >> /etc/group
  609. RUN touch /exists
  610. RUN chown dockerio.dockerio /exists
  611. ADD test_file /test_dir/
  612. RUN [ $(ls -l / | grep test_dir | awk '{print $3":"$4}') = 'root:root' ]
  613. RUN [ $(ls -l /test_dir/test_file | awk '{print $3":"$4}') = 'root:root' ]
  614. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`),
  615. withFile("test_file", "test1")))
  616. }
  617. func (s *DockerSuite) TestBuildAddDirContentToRoot(c *check.C) {
  618. testRequires(c, DaemonIsLinux) // Linux specific test
  619. buildImageSuccessfully(c, "testadddircontenttoroot", withBuildContext(c,
  620. withFile("Dockerfile", `FROM busybox
  621. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  622. RUN echo 'dockerio:x:1001:' >> /etc/group
  623. RUN touch /exists
  624. RUN chown dockerio.dockerio exists
  625. ADD test_dir /
  626. RUN [ $(ls -l /test_file | awk '{print $3":"$4}') = 'root:root' ]
  627. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`),
  628. withFile("test_dir/test_file", "test1")))
  629. }
  630. func (s *DockerSuite) TestBuildAddDirContentToExistingDir(c *check.C) {
  631. testRequires(c, DaemonIsLinux) // Linux specific test
  632. buildImageSuccessfully(c, "testadddircontenttoexistingdir", withBuildContext(c,
  633. withFile("Dockerfile", `FROM busybox
  634. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  635. RUN echo 'dockerio:x:1001:' >> /etc/group
  636. RUN mkdir /exists
  637. RUN touch /exists/exists_file
  638. RUN chown -R dockerio.dockerio /exists
  639. ADD test_dir/ /exists/
  640. RUN [ $(ls -l / | grep exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  641. RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  642. RUN [ $(ls -l /exists/test_file | awk '{print $3":"$4}') = 'root:root' ]`),
  643. withFile("test_dir/test_file", "test1")))
  644. }
  645. func (s *DockerSuite) TestBuildAddWholeDirToRoot(c *check.C) {
  646. testRequires(c, DaemonIsLinux) // Linux specific test
  647. buildImageSuccessfully(c, "testaddwholedirtoroot", withBuildContext(c,
  648. withFile("Dockerfile", fmt.Sprintf(`FROM busybox
  649. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  650. RUN echo 'dockerio:x:1001:' >> /etc/group
  651. RUN touch /exists
  652. RUN chown dockerio.dockerio exists
  653. ADD test_dir /test_dir
  654. RUN [ $(ls -l / | grep test_dir | awk '{print $3":"$4}') = 'root:root' ]
  655. RUN [ $(ls -l / | grep test_dir | awk '{print $1}') = 'drwxr-xr-x' ]
  656. RUN [ $(ls -l /test_dir/test_file | awk '{print $3":"$4}') = 'root:root' ]
  657. RUN [ $(ls -l /test_dir/test_file | awk '{print $1}') = '%s' ]
  658. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`, expectedFileChmod)),
  659. withFile("test_dir/test_file", "test1")))
  660. }
  661. // Testing #5941 : Having an etc directory in context conflicts with the /etc/mtab
  662. func (s *DockerSuite) TestBuildAddOrCopyEtcToRootShouldNotConflict(c *check.C) {
  663. buildImageSuccessfully(c, "testaddetctoroot", withBuildContext(c,
  664. withFile("Dockerfile", `FROM `+minimalBaseImage()+`
  665. ADD . /`),
  666. withFile("etc/test_file", "test1")))
  667. buildImageSuccessfully(c, "testcopyetctoroot", withBuildContext(c,
  668. withFile("Dockerfile", `FROM `+minimalBaseImage()+`
  669. COPY . /`),
  670. withFile("etc/test_file", "test1")))
  671. }
  672. // Testing #9401 : Losing setuid flag after a ADD
  673. func (s *DockerSuite) TestBuildAddPreservesFilesSpecialBits(c *check.C) {
  674. testRequires(c, DaemonIsLinux) // Linux specific test
  675. buildImageSuccessfully(c, "testaddetctoroot", withBuildContext(c,
  676. withFile("Dockerfile", `FROM busybox
  677. ADD suidbin /usr/bin/suidbin
  678. RUN chmod 4755 /usr/bin/suidbin
  679. RUN [ $(ls -l /usr/bin/suidbin | awk '{print $1}') = '-rwsr-xr-x' ]
  680. ADD ./data/ /
  681. RUN [ $(ls -l /usr/bin/suidbin | awk '{print $1}') = '-rwsr-xr-x' ]`),
  682. withFile("suidbin", "suidbin"),
  683. withFile("/data/usr/test_file", "test1")))
  684. }
  685. func (s *DockerSuite) TestBuildCopySingleFileToRoot(c *check.C) {
  686. testRequires(c, DaemonIsLinux) // Linux specific test
  687. buildImageSuccessfully(c, "testcopysinglefiletoroot", withBuildContext(c,
  688. withFile("Dockerfile", fmt.Sprintf(`FROM busybox
  689. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  690. RUN echo 'dockerio:x:1001:' >> /etc/group
  691. RUN touch /exists
  692. RUN chown dockerio.dockerio /exists
  693. COPY test_file /
  694. RUN [ $(ls -l /test_file | awk '{print $3":"$4}') = 'root:root' ]
  695. RUN [ $(ls -l /test_file | awk '{print $1}') = '%s' ]
  696. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`, expectedFileChmod)),
  697. withFile("test_file", "test1")))
  698. }
  699. // Issue #3960: "ADD src ." hangs - adapted for COPY
  700. func (s *DockerSuite) TestBuildCopySingleFileToWorkdir(c *check.C) {
  701. name := "testcopysinglefiletoworkdir"
  702. ctx := fakeContext(c, `FROM busybox
  703. COPY test_file .`,
  704. map[string]string{
  705. "test_file": "test1",
  706. })
  707. defer ctx.Close()
  708. errChan := make(chan error)
  709. go func() {
  710. errChan <- buildImage(name, withExternalBuildContext(ctx)).Error
  711. close(errChan)
  712. }()
  713. select {
  714. case <-time.After(15 * time.Second):
  715. c.Fatal("Build with adding to workdir timed out")
  716. case err := <-errChan:
  717. c.Assert(err, check.IsNil)
  718. }
  719. }
  720. func (s *DockerSuite) TestBuildCopySingleFileToExistDir(c *check.C) {
  721. testRequires(c, DaemonIsLinux) // Linux specific test
  722. buildImageSuccessfully(c, "testcopysinglefiletoexistdir", withBuildContext(c,
  723. withFile("Dockerfile", `FROM busybox
  724. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  725. RUN echo 'dockerio:x:1001:' >> /etc/group
  726. RUN mkdir /exists
  727. RUN touch /exists/exists_file
  728. RUN chown -R dockerio.dockerio /exists
  729. COPY test_file /exists/
  730. RUN [ $(ls -l / | grep exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  731. RUN [ $(ls -l /exists/test_file | awk '{print $3":"$4}') = 'root:root' ]
  732. RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`),
  733. withFile("test_file", "test1")))
  734. }
  735. func (s *DockerSuite) TestBuildCopySingleFileToNonExistDir(c *check.C) {
  736. testRequires(c, DaemonIsLinux) // Linux specific
  737. buildImageSuccessfully(c, "testcopysinglefiletononexistdir", withBuildContext(c,
  738. withFile("Dockerfile", `FROM busybox
  739. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  740. RUN echo 'dockerio:x:1001:' >> /etc/group
  741. RUN touch /exists
  742. RUN chown dockerio.dockerio /exists
  743. COPY test_file /test_dir/
  744. RUN [ $(ls -l / | grep test_dir | awk '{print $3":"$4}') = 'root:root' ]
  745. RUN [ $(ls -l /test_dir/test_file | awk '{print $3":"$4}') = 'root:root' ]
  746. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`),
  747. withFile("test_file", "test1")))
  748. }
  749. func (s *DockerSuite) TestBuildCopyDirContentToRoot(c *check.C) {
  750. testRequires(c, DaemonIsLinux) // Linux specific test
  751. buildImageSuccessfully(c, "testcopydircontenttoroot", withBuildContext(c,
  752. withFile("Dockerfile", `FROM busybox
  753. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  754. RUN echo 'dockerio:x:1001:' >> /etc/group
  755. RUN touch /exists
  756. RUN chown dockerio.dockerio exists
  757. COPY test_dir /
  758. RUN [ $(ls -l /test_file | awk '{print $3":"$4}') = 'root:root' ]
  759. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`),
  760. withFile("test_dir/test_file", "test1")))
  761. }
  762. func (s *DockerSuite) TestBuildCopyDirContentToExistDir(c *check.C) {
  763. testRequires(c, DaemonIsLinux) // Linux specific test
  764. buildImageSuccessfully(c, "testcopydircontenttoexistdir", withBuildContext(c,
  765. withFile("Dockerfile", `FROM busybox
  766. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  767. RUN echo 'dockerio:x:1001:' >> /etc/group
  768. RUN mkdir /exists
  769. RUN touch /exists/exists_file
  770. RUN chown -R dockerio.dockerio /exists
  771. COPY test_dir/ /exists/
  772. RUN [ $(ls -l / | grep exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  773. RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  774. RUN [ $(ls -l /exists/test_file | awk '{print $3":"$4}') = 'root:root' ]`),
  775. withFile("test_dir/test_file", "test1")))
  776. }
  777. func (s *DockerSuite) TestBuildCopyWholeDirToRoot(c *check.C) {
  778. testRequires(c, DaemonIsLinux) // Linux specific test
  779. buildImageSuccessfully(c, "testcopywholedirtoroot", withBuildContext(c,
  780. withFile("Dockerfile", fmt.Sprintf(`FROM busybox
  781. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  782. RUN echo 'dockerio:x:1001:' >> /etc/group
  783. RUN touch /exists
  784. RUN chown dockerio.dockerio exists
  785. COPY test_dir /test_dir
  786. RUN [ $(ls -l / | grep test_dir | awk '{print $3":"$4}') = 'root:root' ]
  787. RUN [ $(ls -l / | grep test_dir | awk '{print $1}') = 'drwxr-xr-x' ]
  788. RUN [ $(ls -l /test_dir/test_file | awk '{print $3":"$4}') = 'root:root' ]
  789. RUN [ $(ls -l /test_dir/test_file | awk '{print $1}') = '%s' ]
  790. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`, expectedFileChmod)),
  791. withFile("test_dir/test_file", "test1")))
  792. }
  793. func (s *DockerSuite) TestBuildAddBadLinks(c *check.C) {
  794. testRequires(c, DaemonIsLinux) // Not currently working on Windows
  795. dockerfile := `
  796. FROM scratch
  797. ADD links.tar /
  798. ADD foo.txt /symlink/
  799. `
  800. targetFile := "foo.txt"
  801. var (
  802. name = "test-link-absolute"
  803. )
  804. ctx := fakeContext(c, dockerfile, nil)
  805. defer ctx.Close()
  806. tempDir, err := ioutil.TempDir("", "test-link-absolute-temp-")
  807. if err != nil {
  808. c.Fatalf("failed to create temporary directory: %s", tempDir)
  809. }
  810. defer os.RemoveAll(tempDir)
  811. var symlinkTarget string
  812. if runtime.GOOS == "windows" {
  813. var driveLetter string
  814. if abs, err := filepath.Abs(tempDir); err != nil {
  815. c.Fatal(err)
  816. } else {
  817. driveLetter = abs[:1]
  818. }
  819. tempDirWithoutDrive := tempDir[2:]
  820. symlinkTarget = fmt.Sprintf(`%s:\..\..\..\..\..\..\..\..\..\..\..\..%s`, driveLetter, tempDirWithoutDrive)
  821. } else {
  822. symlinkTarget = fmt.Sprintf("/../../../../../../../../../../../..%s", tempDir)
  823. }
  824. tarPath := filepath.Join(ctx.Dir, "links.tar")
  825. nonExistingFile := filepath.Join(tempDir, targetFile)
  826. fooPath := filepath.Join(ctx.Dir, targetFile)
  827. tarOut, err := os.Create(tarPath)
  828. if err != nil {
  829. c.Fatal(err)
  830. }
  831. tarWriter := tar.NewWriter(tarOut)
  832. header := &tar.Header{
  833. Name: "symlink",
  834. Typeflag: tar.TypeSymlink,
  835. Linkname: symlinkTarget,
  836. Mode: 0755,
  837. Uid: 0,
  838. Gid: 0,
  839. }
  840. err = tarWriter.WriteHeader(header)
  841. if err != nil {
  842. c.Fatal(err)
  843. }
  844. tarWriter.Close()
  845. tarOut.Close()
  846. foo, err := os.Create(fooPath)
  847. if err != nil {
  848. c.Fatal(err)
  849. }
  850. defer foo.Close()
  851. if _, err := foo.WriteString("test"); err != nil {
  852. c.Fatal(err)
  853. }
  854. buildImageSuccessfully(c, name, withExternalBuildContext(ctx))
  855. if _, err := os.Stat(nonExistingFile); err == nil || err != nil && !os.IsNotExist(err) {
  856. c.Fatalf("%s shouldn't have been written and it shouldn't exist", nonExistingFile)
  857. }
  858. }
  859. func (s *DockerSuite) TestBuildAddBadLinksVolume(c *check.C) {
  860. testRequires(c, DaemonIsLinux) // ln not implemented on Windows busybox
  861. const (
  862. dockerfileTemplate = `
  863. FROM busybox
  864. RUN ln -s /../../../../../../../../%s /x
  865. VOLUME /x
  866. ADD foo.txt /x/`
  867. targetFile = "foo.txt"
  868. )
  869. var (
  870. name = "test-link-absolute-volume"
  871. dockerfile = ""
  872. )
  873. tempDir, err := ioutil.TempDir("", "test-link-absolute-volume-temp-")
  874. if err != nil {
  875. c.Fatalf("failed to create temporary directory: %s", tempDir)
  876. }
  877. defer os.RemoveAll(tempDir)
  878. dockerfile = fmt.Sprintf(dockerfileTemplate, tempDir)
  879. nonExistingFile := filepath.Join(tempDir, targetFile)
  880. ctx := fakeContext(c, dockerfile, nil)
  881. defer ctx.Close()
  882. fooPath := filepath.Join(ctx.Dir, targetFile)
  883. foo, err := os.Create(fooPath)
  884. if err != nil {
  885. c.Fatal(err)
  886. }
  887. defer foo.Close()
  888. if _, err := foo.WriteString("test"); err != nil {
  889. c.Fatal(err)
  890. }
  891. buildImageSuccessfully(c, name, withExternalBuildContext(ctx))
  892. if _, err := os.Stat(nonExistingFile); err == nil || err != nil && !os.IsNotExist(err) {
  893. c.Fatalf("%s shouldn't have been written and it shouldn't exist", nonExistingFile)
  894. }
  895. }
  896. // Issue #5270 - ensure we throw a better error than "unexpected EOF"
  897. // when we can't access files in the context.
  898. func (s *DockerSuite) TestBuildWithInaccessibleFilesInContext(c *check.C) {
  899. testRequires(c, DaemonIsLinux, UnixCli) // test uses chown/chmod: not available on windows
  900. {
  901. name := "testbuildinaccessiblefiles"
  902. ctx := fakeContext(c, "FROM scratch\nADD . /foo/", map[string]string{"fileWithoutReadAccess": "foo"})
  903. defer ctx.Close()
  904. // This is used to ensure we detect inaccessible files early during build in the cli client
  905. pathToFileWithoutReadAccess := filepath.Join(ctx.Dir, "fileWithoutReadAccess")
  906. if err := os.Chown(pathToFileWithoutReadAccess, 0, 0); err != nil {
  907. c.Fatalf("failed to chown file to root: %s", err)
  908. }
  909. if err := os.Chmod(pathToFileWithoutReadAccess, 0700); err != nil {
  910. c.Fatalf("failed to chmod file to 700: %s", err)
  911. }
  912. result := icmd.RunCmd(icmd.Cmd{
  913. Command: []string{"su", "unprivilegeduser", "-c", fmt.Sprintf("%s build -t %s .", dockerBinary, name)},
  914. Dir: ctx.Dir,
  915. })
  916. if result.Error == nil {
  917. c.Fatalf("build should have failed: %s %s", result.Error, result.Combined())
  918. }
  919. // check if we've detected the failure before we started building
  920. if !strings.Contains(result.Combined(), "no permission to read from ") {
  921. c.Fatalf("output should've contained the string: no permission to read from but contained: %s", result.Combined())
  922. }
  923. if !strings.Contains(result.Combined(), "Error checking context") {
  924. c.Fatalf("output should've contained the string: Error checking context")
  925. }
  926. }
  927. {
  928. name := "testbuildinaccessibledirectory"
  929. ctx := fakeContext(c, "FROM scratch\nADD . /foo/", map[string]string{"directoryWeCantStat/bar": "foo"})
  930. defer ctx.Close()
  931. // This is used to ensure we detect inaccessible directories early during build in the cli client
  932. pathToDirectoryWithoutReadAccess := filepath.Join(ctx.Dir, "directoryWeCantStat")
  933. pathToFileInDirectoryWithoutReadAccess := filepath.Join(pathToDirectoryWithoutReadAccess, "bar")
  934. if err := os.Chown(pathToDirectoryWithoutReadAccess, 0, 0); err != nil {
  935. c.Fatalf("failed to chown directory to root: %s", err)
  936. }
  937. if err := os.Chmod(pathToDirectoryWithoutReadAccess, 0444); err != nil {
  938. c.Fatalf("failed to chmod directory to 444: %s", err)
  939. }
  940. if err := os.Chmod(pathToFileInDirectoryWithoutReadAccess, 0700); err != nil {
  941. c.Fatalf("failed to chmod file to 700: %s", err)
  942. }
  943. result := icmd.RunCmd(icmd.Cmd{
  944. Command: []string{"su", "unprivilegeduser", "-c", fmt.Sprintf("%s build -t %s .", dockerBinary, name)},
  945. Dir: ctx.Dir,
  946. })
  947. if result.Error == nil {
  948. c.Fatalf("build should have failed: %s %s", result.Error, result.Combined())
  949. }
  950. // check if we've detected the failure before we started building
  951. if !strings.Contains(result.Combined(), "can't stat") {
  952. c.Fatalf("output should've contained the string: can't access %s", result.Combined())
  953. }
  954. if !strings.Contains(result.Combined(), "Error checking context") {
  955. c.Fatalf("output should've contained the string: Error checking context\ngot:%s", result.Combined())
  956. }
  957. }
  958. {
  959. name := "testlinksok"
  960. ctx := fakeContext(c, "FROM scratch\nADD . /foo/", nil)
  961. defer ctx.Close()
  962. target := "../../../../../../../../../../../../../../../../../../../azA"
  963. if err := os.Symlink(filepath.Join(ctx.Dir, "g"), target); err != nil {
  964. c.Fatal(err)
  965. }
  966. defer os.Remove(target)
  967. // This is used to ensure we don't follow links when checking if everything in the context is accessible
  968. // This test doesn't require that we run commands as an unprivileged user
  969. buildImageSuccessfully(c, name, withExternalBuildContext(ctx))
  970. }
  971. {
  972. name := "testbuildignoredinaccessible"
  973. ctx := fakeContext(c, "FROM scratch\nADD . /foo/",
  974. map[string]string{
  975. "directoryWeCantStat/bar": "foo",
  976. ".dockerignore": "directoryWeCantStat",
  977. })
  978. defer ctx.Close()
  979. // This is used to ensure we don't try to add inaccessible files when they are ignored by a .dockerignore pattern
  980. pathToDirectoryWithoutReadAccess := filepath.Join(ctx.Dir, "directoryWeCantStat")
  981. pathToFileInDirectoryWithoutReadAccess := filepath.Join(pathToDirectoryWithoutReadAccess, "bar")
  982. if err := os.Chown(pathToDirectoryWithoutReadAccess, 0, 0); err != nil {
  983. c.Fatalf("failed to chown directory to root: %s", err)
  984. }
  985. if err := os.Chmod(pathToDirectoryWithoutReadAccess, 0444); err != nil {
  986. c.Fatalf("failed to chmod directory to 444: %s", err)
  987. }
  988. if err := os.Chmod(pathToFileInDirectoryWithoutReadAccess, 0700); err != nil {
  989. c.Fatalf("failed to chmod file to 700: %s", err)
  990. }
  991. result := icmd.RunCmd(icmd.Cmd{
  992. Dir: ctx.Dir,
  993. Command: []string{"su", "unprivilegeduser", "-c",
  994. fmt.Sprintf("%s build -t %s .", dockerBinary, name)},
  995. })
  996. result.Assert(c, icmd.Expected{})
  997. }
  998. }
  999. func (s *DockerSuite) TestBuildForceRm(c *check.C) {
  1000. containerCountBefore, err := getContainerCount()
  1001. if err != nil {
  1002. c.Fatalf("failed to get the container count: %s", err)
  1003. }
  1004. name := "testbuildforcerm"
  1005. buildImage(name, withBuildFlags("--force-rm"), withBuildContext(c,
  1006. withFile("Dockerfile", `FROM `+minimalBaseImage()+`
  1007. RUN true
  1008. RUN thiswillfail`))).Assert(c, icmd.Expected{
  1009. ExitCode: 1,
  1010. })
  1011. containerCountAfter, err := getContainerCount()
  1012. if err != nil {
  1013. c.Fatalf("failed to get the container count: %s", err)
  1014. }
  1015. if containerCountBefore != containerCountAfter {
  1016. c.Fatalf("--force-rm shouldn't have left containers behind")
  1017. }
  1018. }
  1019. func (s *DockerSuite) TestBuildRm(c *check.C) {
  1020. name := "testbuildrm"
  1021. testCases := []struct {
  1022. buildflags []string
  1023. shouldLeftContainerBehind bool
  1024. }{
  1025. // Default case (i.e. --rm=true)
  1026. {
  1027. buildflags: []string{},
  1028. shouldLeftContainerBehind: false,
  1029. },
  1030. {
  1031. buildflags: []string{"--rm"},
  1032. shouldLeftContainerBehind: false,
  1033. },
  1034. {
  1035. buildflags: []string{"--rm=false"},
  1036. shouldLeftContainerBehind: true,
  1037. },
  1038. }
  1039. for _, tc := range testCases {
  1040. containerCountBefore, err := getContainerCount()
  1041. if err != nil {
  1042. c.Fatalf("failed to get the container count: %s", err)
  1043. }
  1044. buildImageSuccessfully(c, name, withBuildFlags(tc.buildflags...), withDockerfile(`FROM busybox
  1045. RUN echo hello world`))
  1046. containerCountAfter, err := getContainerCount()
  1047. if err != nil {
  1048. c.Fatalf("failed to get the container count: %s", err)
  1049. }
  1050. if tc.shouldLeftContainerBehind {
  1051. if containerCountBefore == containerCountAfter {
  1052. c.Fatalf("flags %v should have left containers behind", tc.buildflags)
  1053. }
  1054. } else {
  1055. if containerCountBefore != containerCountAfter {
  1056. c.Fatalf("flags %v shouldn't have left containers behind", tc.buildflags)
  1057. }
  1058. }
  1059. dockerCmd(c, "rmi", name)
  1060. }
  1061. }
  1062. func (s *DockerSuite) TestBuildWithVolumes(c *check.C) {
  1063. testRequires(c, DaemonIsLinux) // Invalid volume paths on Windows
  1064. var (
  1065. result map[string]map[string]struct{}
  1066. name = "testbuildvolumes"
  1067. emptyMap = make(map[string]struct{})
  1068. expected = map[string]map[string]struct{}{
  1069. "/test1": emptyMap,
  1070. "/test2": emptyMap,
  1071. "/test3": emptyMap,
  1072. "/test4": emptyMap,
  1073. "/test5": emptyMap,
  1074. "/test6": emptyMap,
  1075. "[/test7": emptyMap,
  1076. "/test8]": emptyMap,
  1077. }
  1078. )
  1079. buildImageSuccessfully(c, name, withDockerfile(`FROM scratch
  1080. VOLUME /test1
  1081. VOLUME /test2
  1082. VOLUME /test3 /test4
  1083. VOLUME ["/test5", "/test6"]
  1084. VOLUME [/test7 /test8]
  1085. `))
  1086. inspectFieldAndUnmarshall(c, name, "Config.Volumes", &result)
  1087. equal := reflect.DeepEqual(&result, &expected)
  1088. if !equal {
  1089. c.Fatalf("Volumes %s, expected %s", result, expected)
  1090. }
  1091. }
  1092. func (s *DockerSuite) TestBuildMaintainer(c *check.C) {
  1093. name := "testbuildmaintainer"
  1094. buildImageSuccessfully(c, name, withDockerfile(`FROM `+minimalBaseImage()+`
  1095. MAINTAINER dockerio`))
  1096. expected := "dockerio"
  1097. res := inspectField(c, name, "Author")
  1098. if res != expected {
  1099. c.Fatalf("Maintainer %s, expected %s", res, expected)
  1100. }
  1101. }
  1102. func (s *DockerSuite) TestBuildUser(c *check.C) {
  1103. testRequires(c, DaemonIsLinux)
  1104. name := "testbuilduser"
  1105. expected := "dockerio"
  1106. buildImageSuccessfully(c, name, withDockerfile(`FROM busybox
  1107. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1108. USER dockerio
  1109. RUN [ $(whoami) = 'dockerio' ]`))
  1110. res := inspectField(c, name, "Config.User")
  1111. if res != expected {
  1112. c.Fatalf("User %s, expected %s", res, expected)
  1113. }
  1114. }
  1115. func (s *DockerSuite) TestBuildRelativeWorkdir(c *check.C) {
  1116. name := "testbuildrelativeworkdir"
  1117. var (
  1118. expected1 string
  1119. expected2 string
  1120. expected3 string
  1121. expected4 string
  1122. expectedFinal string
  1123. )
  1124. if testEnv.DaemonPlatform() == "windows" {
  1125. expected1 = `C:/`
  1126. expected2 = `C:/test1`
  1127. expected3 = `C:/test2`
  1128. expected4 = `C:/test2/test3`
  1129. expectedFinal = `C:\test2\test3` // Note inspect is going to return Windows paths, as it's not in busybox
  1130. } else {
  1131. expected1 = `/`
  1132. expected2 = `/test1`
  1133. expected3 = `/test2`
  1134. expected4 = `/test2/test3`
  1135. expectedFinal = `/test2/test3`
  1136. }
  1137. buildImageSuccessfully(c, name, withDockerfile(`FROM busybox
  1138. RUN sh -c "[ "$PWD" = "`+expected1+`" ]"
  1139. WORKDIR test1
  1140. RUN sh -c "[ "$PWD" = "`+expected2+`" ]"
  1141. WORKDIR /test2
  1142. RUN sh -c "[ "$PWD" = "`+expected3+`" ]"
  1143. WORKDIR test3
  1144. RUN sh -c "[ "$PWD" = "`+expected4+`" ]"`))
  1145. res := inspectField(c, name, "Config.WorkingDir")
  1146. if res != expectedFinal {
  1147. c.Fatalf("Workdir %s, expected %s", res, expectedFinal)
  1148. }
  1149. }
  1150. // #22181 Regression test. Single end-to-end test of using
  1151. // Windows semantics. Most path handling verifications are in unit tests
  1152. func (s *DockerSuite) TestBuildWindowsWorkdirProcessing(c *check.C) {
  1153. testRequires(c, DaemonIsWindows)
  1154. buildImageSuccessfully(c, "testbuildwindowsworkdirprocessing", withDockerfile(`FROM busybox
  1155. WORKDIR C:\\foo
  1156. WORKDIR bar
  1157. RUN sh -c "[ "$PWD" = "C:/foo/bar" ]"
  1158. `))
  1159. }
  1160. // #22181 Regression test. Most paths handling verifications are in unit test.
  1161. // One functional test for end-to-end
  1162. func (s *DockerSuite) TestBuildWindowsAddCopyPathProcessing(c *check.C) {
  1163. testRequires(c, DaemonIsWindows)
  1164. // TODO Windows (@jhowardmsft). Needs a follow-up PR to 22181 to
  1165. // support backslash such as .\\ being equivalent to ./ and c:\\ being
  1166. // equivalent to c:/. This is not currently (nor ever has been) supported
  1167. // by docker on the Windows platform.
  1168. buildImageSuccessfully(c, "testbuildwindowsaddcopypathprocessing", withBuildContext(c,
  1169. withFile("Dockerfile", `FROM busybox
  1170. # No trailing slash on COPY/ADD
  1171. # Results in dir being changed to a file
  1172. WORKDIR /wc1
  1173. COPY wc1 c:/wc1
  1174. WORKDIR /wc2
  1175. ADD wc2 c:/wc2
  1176. WORKDIR c:/
  1177. RUN sh -c "[ $(cat c:/wc1/wc1) = 'hellowc1' ]"
  1178. RUN sh -c "[ $(cat c:/wc2/wc2) = 'worldwc2' ]"
  1179. # Trailing slash on COPY/ADD, Windows-style path.
  1180. WORKDIR /wd1
  1181. COPY wd1 c:/wd1/
  1182. WORKDIR /wd2
  1183. ADD wd2 c:/wd2/
  1184. RUN sh -c "[ $(cat c:/wd1/wd1) = 'hellowd1' ]"
  1185. RUN sh -c "[ $(cat c:/wd2/wd2) = 'worldwd2' ]"
  1186. `),
  1187. withFile("wc1", "hellowc1"),
  1188. withFile("wc2", "worldwc2"),
  1189. withFile("wd1", "hellowd1"),
  1190. withFile("wd2", "worldwd2"),
  1191. ))
  1192. }
  1193. func (s *DockerSuite) TestBuildWorkdirWithEnvVariables(c *check.C) {
  1194. name := "testbuildworkdirwithenvvariables"
  1195. var expected string
  1196. if testEnv.DaemonPlatform() == "windows" {
  1197. expected = `C:\test1\test2`
  1198. } else {
  1199. expected = `/test1/test2`
  1200. }
  1201. buildImageSuccessfully(c, name, withDockerfile(`FROM busybox
  1202. ENV DIRPATH /test1
  1203. ENV SUBDIRNAME test2
  1204. WORKDIR $DIRPATH
  1205. WORKDIR $SUBDIRNAME/$MISSING_VAR`))
  1206. res := inspectField(c, name, "Config.WorkingDir")
  1207. if res != expected {
  1208. c.Fatalf("Workdir %s, expected %s", res, expected)
  1209. }
  1210. }
  1211. func (s *DockerSuite) TestBuildRelativeCopy(c *check.C) {
  1212. // cat /test1/test2/foo gets permission denied for the user
  1213. testRequires(c, NotUserNamespace)
  1214. var expected string
  1215. if testEnv.DaemonPlatform() == "windows" {
  1216. expected = `C:/test1/test2`
  1217. } else {
  1218. expected = `/test1/test2`
  1219. }
  1220. buildImageSuccessfully(c, "testbuildrelativecopy", withBuildContext(c,
  1221. withFile("Dockerfile", `FROM busybox
  1222. WORKDIR /test1
  1223. WORKDIR test2
  1224. RUN sh -c "[ "$PWD" = '`+expected+`' ]"
  1225. COPY foo ./
  1226. RUN sh -c "[ $(cat /test1/test2/foo) = 'hello' ]"
  1227. ADD foo ./bar/baz
  1228. RUN sh -c "[ $(cat /test1/test2/bar/baz) = 'hello' ]"
  1229. COPY foo ./bar/baz2
  1230. RUN sh -c "[ $(cat /test1/test2/bar/baz2) = 'hello' ]"
  1231. WORKDIR ..
  1232. COPY foo ./
  1233. RUN sh -c "[ $(cat /test1/foo) = 'hello' ]"
  1234. COPY foo /test3/
  1235. RUN sh -c "[ $(cat /test3/foo) = 'hello' ]"
  1236. WORKDIR /test4
  1237. COPY . .
  1238. RUN sh -c "[ $(cat /test4/foo) = 'hello' ]"
  1239. WORKDIR /test5/test6
  1240. COPY foo ../
  1241. RUN sh -c "[ $(cat /test5/foo) = 'hello' ]"
  1242. `),
  1243. withFile("foo", "hello"),
  1244. ))
  1245. }
  1246. func (s *DockerSuite) TestBuildBlankName(c *check.C) {
  1247. name := "testbuildblankname"
  1248. testCases := []struct {
  1249. expression string
  1250. expectedStderr string
  1251. }{
  1252. {
  1253. expression: "ENV =",
  1254. expectedStderr: "ENV names can not be blank",
  1255. },
  1256. {
  1257. expression: "LABEL =",
  1258. expectedStderr: "LABEL names can not be blank",
  1259. },
  1260. {
  1261. expression: "ARG =foo",
  1262. expectedStderr: "ARG names can not be blank",
  1263. },
  1264. }
  1265. for _, tc := range testCases {
  1266. buildImage(name, withDockerfile(fmt.Sprintf(`FROM busybox
  1267. %s`, tc.expression))).Assert(c, icmd.Expected{
  1268. ExitCode: 1,
  1269. Err: tc.expectedStderr,
  1270. })
  1271. }
  1272. }
  1273. func (s *DockerSuite) TestBuildEnv(c *check.C) {
  1274. testRequires(c, DaemonIsLinux) // ENV expansion is different in Windows
  1275. name := "testbuildenv"
  1276. expected := "[PATH=/test:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin PORT=2375]"
  1277. buildImageSuccessfully(c, name, withDockerfile(`FROM busybox
  1278. ENV PATH /test:$PATH
  1279. ENV PORT 2375
  1280. RUN [ $(env | grep PORT) = 'PORT=2375' ]`))
  1281. res := inspectField(c, name, "Config.Env")
  1282. if res != expected {
  1283. c.Fatalf("Env %s, expected %s", res, expected)
  1284. }
  1285. }
  1286. func (s *DockerSuite) TestBuildPATH(c *check.C) {
  1287. testRequires(c, DaemonIsLinux) // ENV expansion is different in Windows
  1288. defPath := "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
  1289. fn := func(dockerfile string, expected string) {
  1290. buildImageSuccessfully(c, "testbldpath", withDockerfile(dockerfile))
  1291. res := inspectField(c, "testbldpath", "Config.Env")
  1292. if res != expected {
  1293. c.Fatalf("Env %q, expected %q for dockerfile:%q", res, expected, dockerfile)
  1294. }
  1295. }
  1296. tests := []struct{ dockerfile, exp string }{
  1297. {"FROM scratch\nMAINTAINER me", "[PATH=" + defPath + "]"},
  1298. {"FROM busybox\nMAINTAINER me", "[PATH=" + defPath + "]"},
  1299. {"FROM scratch\nENV FOO=bar", "[PATH=" + defPath + " FOO=bar]"},
  1300. {"FROM busybox\nENV FOO=bar", "[PATH=" + defPath + " FOO=bar]"},
  1301. {"FROM scratch\nENV PATH=/test", "[PATH=/test]"},
  1302. {"FROM busybox\nENV PATH=/test", "[PATH=/test]"},
  1303. {"FROM scratch\nENV PATH=''", "[PATH=]"},
  1304. {"FROM busybox\nENV PATH=''", "[PATH=]"},
  1305. }
  1306. for _, test := range tests {
  1307. fn(test.dockerfile, test.exp)
  1308. }
  1309. }
  1310. func (s *DockerSuite) TestBuildContextCleanup(c *check.C) {
  1311. testRequires(c, SameHostDaemon)
  1312. name := "testbuildcontextcleanup"
  1313. entries, err := ioutil.ReadDir(filepath.Join(testEnv.DockerBasePath(), "tmp"))
  1314. if err != nil {
  1315. c.Fatalf("failed to list contents of tmp dir: %s", err)
  1316. }
  1317. buildImageSuccessfully(c, name, withDockerfile(`FROM `+minimalBaseImage()+`
  1318. ENTRYPOINT ["/bin/echo"]`))
  1319. entriesFinal, err := ioutil.ReadDir(filepath.Join(testEnv.DockerBasePath(), "tmp"))
  1320. if err != nil {
  1321. c.Fatalf("failed to list contents of tmp dir: %s", err)
  1322. }
  1323. if err = testutil.CompareDirectoryEntries(entries, entriesFinal); err != nil {
  1324. c.Fatalf("context should have been deleted, but wasn't")
  1325. }
  1326. }
  1327. func (s *DockerSuite) TestBuildContextCleanupFailedBuild(c *check.C) {
  1328. testRequires(c, SameHostDaemon)
  1329. name := "testbuildcontextcleanup"
  1330. entries, err := ioutil.ReadDir(filepath.Join(testEnv.DockerBasePath(), "tmp"))
  1331. if err != nil {
  1332. c.Fatalf("failed to list contents of tmp dir: %s", err)
  1333. }
  1334. buildImage(name, withDockerfile(`FROM `+minimalBaseImage()+`
  1335. RUN /non/existing/command`)).Assert(c, icmd.Expected{
  1336. ExitCode: 1,
  1337. })
  1338. entriesFinal, err := ioutil.ReadDir(filepath.Join(testEnv.DockerBasePath(), "tmp"))
  1339. if err != nil {
  1340. c.Fatalf("failed to list contents of tmp dir: %s", err)
  1341. }
  1342. if err = testutil.CompareDirectoryEntries(entries, entriesFinal); err != nil {
  1343. c.Fatalf("context should have been deleted, but wasn't")
  1344. }
  1345. }
  1346. func (s *DockerSuite) TestBuildCmd(c *check.C) {
  1347. name := "testbuildcmd"
  1348. expected := "[/bin/echo Hello World]"
  1349. buildImageSuccessfully(c, name, withDockerfile(`FROM `+minimalBaseImage()+`
  1350. CMD ["/bin/echo", "Hello World"]`))
  1351. res := inspectField(c, name, "Config.Cmd")
  1352. if res != expected {
  1353. c.Fatalf("Cmd %s, expected %s", res, expected)
  1354. }
  1355. }
  1356. func (s *DockerSuite) TestBuildExpose(c *check.C) {
  1357. testRequires(c, DaemonIsLinux) // Expose not implemented on Windows
  1358. name := "testbuildexpose"
  1359. expected := "map[2375/tcp:{}]"
  1360. buildImageSuccessfully(c, name, withDockerfile(`FROM scratch
  1361. EXPOSE 2375`))
  1362. res := inspectField(c, name, "Config.ExposedPorts")
  1363. if res != expected {
  1364. c.Fatalf("Exposed ports %s, expected %s", res, expected)
  1365. }
  1366. }
  1367. func (s *DockerSuite) TestBuildExposeMorePorts(c *check.C) {
  1368. testRequires(c, DaemonIsLinux) // Expose not implemented on Windows
  1369. // start building docker file with a large number of ports
  1370. portList := make([]string, 50)
  1371. line := make([]string, 100)
  1372. expectedPorts := make([]int, len(portList)*len(line))
  1373. for i := 0; i < len(portList); i++ {
  1374. for j := 0; j < len(line); j++ {
  1375. p := i*len(line) + j + 1
  1376. line[j] = strconv.Itoa(p)
  1377. expectedPorts[p-1] = p
  1378. }
  1379. if i == len(portList)-1 {
  1380. portList[i] = strings.Join(line, " ")
  1381. } else {
  1382. portList[i] = strings.Join(line, " ") + ` \`
  1383. }
  1384. }
  1385. dockerfile := `FROM scratch
  1386. EXPOSE {{range .}} {{.}}
  1387. {{end}}`
  1388. tmpl := template.Must(template.New("dockerfile").Parse(dockerfile))
  1389. buf := bytes.NewBuffer(nil)
  1390. tmpl.Execute(buf, portList)
  1391. name := "testbuildexpose"
  1392. buildImageSuccessfully(c, name, withDockerfile(buf.String()))
  1393. // check if all the ports are saved inside Config.ExposedPorts
  1394. res := inspectFieldJSON(c, name, "Config.ExposedPorts")
  1395. var exposedPorts map[string]interface{}
  1396. if err := json.Unmarshal([]byte(res), &exposedPorts); err != nil {
  1397. c.Fatal(err)
  1398. }
  1399. for _, p := range expectedPorts {
  1400. ep := fmt.Sprintf("%d/tcp", p)
  1401. if _, ok := exposedPorts[ep]; !ok {
  1402. c.Errorf("Port(%s) is not exposed", ep)
  1403. } else {
  1404. delete(exposedPorts, ep)
  1405. }
  1406. }
  1407. if len(exposedPorts) != 0 {
  1408. c.Errorf("Unexpected extra exposed ports %v", exposedPorts)
  1409. }
  1410. }
  1411. func (s *DockerSuite) TestBuildExposeOrder(c *check.C) {
  1412. testRequires(c, DaemonIsLinux) // Expose not implemented on Windows
  1413. buildID := func(name, exposed string) string {
  1414. buildImageSuccessfully(c, name, withDockerfile(fmt.Sprintf(`FROM scratch
  1415. EXPOSE %s`, exposed)))
  1416. id := inspectField(c, name, "Id")
  1417. return id
  1418. }
  1419. id1 := buildID("testbuildexpose1", "80 2375")
  1420. id2 := buildID("testbuildexpose2", "2375 80")
  1421. if id1 != id2 {
  1422. c.Errorf("EXPOSE should invalidate the cache only when ports actually changed")
  1423. }
  1424. }
  1425. func (s *DockerSuite) TestBuildExposeUpperCaseProto(c *check.C) {
  1426. testRequires(c, DaemonIsLinux) // Expose not implemented on Windows
  1427. name := "testbuildexposeuppercaseproto"
  1428. expected := "map[5678/udp:{}]"
  1429. buildImageSuccessfully(c, name, withDockerfile(`FROM scratch
  1430. EXPOSE 5678/UDP`))
  1431. res := inspectField(c, name, "Config.ExposedPorts")
  1432. if res != expected {
  1433. c.Fatalf("Exposed ports %s, expected %s", res, expected)
  1434. }
  1435. }
  1436. func (s *DockerSuite) TestBuildEmptyEntrypointInheritance(c *check.C) {
  1437. name := "testbuildentrypointinheritance"
  1438. name2 := "testbuildentrypointinheritance2"
  1439. buildImageSuccessfully(c, name, withDockerfile(`FROM busybox
  1440. ENTRYPOINT ["/bin/echo"]`))
  1441. res := inspectField(c, name, "Config.Entrypoint")
  1442. expected := "[/bin/echo]"
  1443. if res != expected {
  1444. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  1445. }
  1446. buildImageSuccessfully(c, name2, withDockerfile(fmt.Sprintf(`FROM %s
  1447. ENTRYPOINT []`, name)))
  1448. res = inspectField(c, name2, "Config.Entrypoint")
  1449. expected = "[]"
  1450. if res != expected {
  1451. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  1452. }
  1453. }
  1454. func (s *DockerSuite) TestBuildEmptyEntrypoint(c *check.C) {
  1455. name := "testbuildentrypoint"
  1456. expected := "[]"
  1457. buildImageSuccessfully(c, name, withDockerfile(`FROM busybox
  1458. ENTRYPOINT []`))
  1459. res := inspectField(c, name, "Config.Entrypoint")
  1460. if res != expected {
  1461. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  1462. }
  1463. }
  1464. func (s *DockerSuite) TestBuildEntrypoint(c *check.C) {
  1465. name := "testbuildentrypoint"
  1466. expected := "[/bin/echo]"
  1467. buildImageSuccessfully(c, name, withDockerfile(`FROM `+minimalBaseImage()+`
  1468. ENTRYPOINT ["/bin/echo"]`))
  1469. res := inspectField(c, name, "Config.Entrypoint")
  1470. if res != expected {
  1471. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  1472. }
  1473. }
  1474. // #6445 ensure ONBUILD triggers aren't committed to grandchildren
  1475. func (s *DockerSuite) TestBuildOnBuildLimitedInheritence(c *check.C) {
  1476. buildImageSuccessfully(c, "testonbuildtrigger1", withDockerfile(`
  1477. FROM busybox
  1478. RUN echo "GRANDPARENT"
  1479. ONBUILD RUN echo "ONBUILD PARENT"
  1480. `))
  1481. // ONBUILD should be run in second build.
  1482. buildImage("testonbuildtrigger2", withDockerfile("FROM testonbuildtrigger1")).Assert(c, icmd.Expected{
  1483. Out: "ONBUILD PARENT",
  1484. })
  1485. // ONBUILD should *not* be run in third build.
  1486. result := buildImage("testonbuildtrigger3", withDockerfile("FROM testonbuildtrigger2"))
  1487. result.Assert(c, icmd.Success)
  1488. if strings.Contains(result.Combined(), "ONBUILD PARENT") {
  1489. c.Fatalf("ONBUILD instruction ran in grandchild of ONBUILD parent")
  1490. }
  1491. }
  1492. func (s *DockerSuite) TestBuildSameDockerfileWithAndWithoutCache(c *check.C) {
  1493. testRequires(c, DaemonIsLinux) // Expose not implemented on Windows
  1494. name := "testbuildwithcache"
  1495. dockerfile := `FROM scratch
  1496. MAINTAINER dockerio
  1497. EXPOSE 5432
  1498. ENTRYPOINT ["/bin/echo"]`
  1499. buildImageSuccessfully(c, name, withDockerfile(dockerfile))
  1500. id1 := getIDByName(c, name)
  1501. buildImageSuccessfully(c, name, withDockerfile(dockerfile))
  1502. id2 := getIDByName(c, name)
  1503. buildImageSuccessfully(c, name, withoutCache, withDockerfile(dockerfile))
  1504. id3 := getIDByName(c, name)
  1505. if id1 != id2 {
  1506. c.Fatal("The cache should have been used but hasn't.")
  1507. }
  1508. if id1 == id3 {
  1509. c.Fatal("The cache should have been invalided but hasn't.")
  1510. }
  1511. }
  1512. // Make sure that ADD/COPY still populate the cache even if they don't use it
  1513. func (s *DockerSuite) TestBuildConditionalCache(c *check.C) {
  1514. name := "testbuildconditionalcache"
  1515. dockerfile := `
  1516. FROM busybox
  1517. ADD foo /tmp/`
  1518. ctx := fakeContext(c, dockerfile, map[string]string{
  1519. "foo": "hello",
  1520. })
  1521. defer ctx.Close()
  1522. buildImageSuccessfully(c, name, withExternalBuildContext(ctx))
  1523. id1 := getIDByName(c, name)
  1524. if err := ctx.Add("foo", "bye"); err != nil {
  1525. c.Fatalf("Error modifying foo: %s", err)
  1526. }
  1527. // Updating a file should invalidate the cache
  1528. buildImageSuccessfully(c, name, withExternalBuildContext(ctx))
  1529. id2 := getIDByName(c, name)
  1530. if id2 == id1 {
  1531. c.Fatal("Should not have used the cache")
  1532. }
  1533. buildImageSuccessfully(c, name, withExternalBuildContext(ctx))
  1534. id3 := getIDByName(c, name)
  1535. if id3 != id2 {
  1536. c.Fatal("Should have used the cache")
  1537. }
  1538. }
  1539. // FIXME(vdemeester) this really seems to test the same thing as before
  1540. func (s *DockerSuite) TestBuildAddMultipleLocalFileWithAndWithoutCache(c *check.C) {
  1541. name := "testbuildaddmultiplelocalfilewithcache"
  1542. dockerfile := `
  1543. FROM busybox
  1544. MAINTAINER dockerio
  1545. ADD foo Dockerfile /usr/lib/bla/
  1546. RUN sh -c "[ $(cat /usr/lib/bla/foo) = "hello" ]"`
  1547. ctx := fakeContext(c, dockerfile, map[string]string{
  1548. "foo": "hello",
  1549. })
  1550. defer ctx.Close()
  1551. buildImageSuccessfully(c, name, withExternalBuildContext(ctx))
  1552. id1 := getIDByName(c, name)
  1553. buildImageSuccessfully(c, name, withExternalBuildContext(ctx))
  1554. id2 := getIDByName(c, name)
  1555. buildImageSuccessfully(c, name, withoutCache, withExternalBuildContext(ctx))
  1556. id3 := getIDByName(c, name)
  1557. if id1 != id2 {
  1558. c.Fatal("The cache should have been used but hasn't.")
  1559. }
  1560. if id1 == id3 {
  1561. c.Fatal("The cache should have been invalided but hasn't.")
  1562. }
  1563. }
  1564. func (s *DockerSuite) TestBuildCopyDirButNotFile(c *check.C) {
  1565. name := "testbuildcopydirbutnotfile"
  1566. name2 := "testbuildcopydirbutnotfile2"
  1567. dockerfile := `
  1568. FROM ` + minimalBaseImage() + `
  1569. COPY dir /tmp/`
  1570. ctx := fakeContext(c, dockerfile, map[string]string{
  1571. "dir/foo": "hello",
  1572. })
  1573. defer ctx.Close()
  1574. buildImageSuccessfully(c, name, withExternalBuildContext(ctx))
  1575. id1 := getIDByName(c, name)
  1576. // Check that adding file with similar name doesn't mess with cache
  1577. if err := ctx.Add("dir_file", "hello2"); err != nil {
  1578. c.Fatal(err)
  1579. }
  1580. buildImageSuccessfully(c, name2, withExternalBuildContext(ctx))
  1581. id2 := getIDByName(c, name2)
  1582. if id1 != id2 {
  1583. c.Fatal("The cache should have been used but wasn't")
  1584. }
  1585. }
  1586. func (s *DockerSuite) TestBuildAddCurrentDirWithCache(c *check.C) {
  1587. name := "testbuildaddcurrentdirwithcache"
  1588. name2 := name + "2"
  1589. name3 := name + "3"
  1590. name4 := name + "4"
  1591. dockerfile := `
  1592. FROM ` + minimalBaseImage() + `
  1593. MAINTAINER dockerio
  1594. ADD . /usr/lib/bla`
  1595. ctx := fakeContext(c, dockerfile, map[string]string{
  1596. "foo": "hello",
  1597. })
  1598. defer ctx.Close()
  1599. buildImageSuccessfully(c, name, withExternalBuildContext(ctx))
  1600. id1 := getIDByName(c, name)
  1601. // Check that adding file invalidate cache of "ADD ."
  1602. if err := ctx.Add("bar", "hello2"); err != nil {
  1603. c.Fatal(err)
  1604. }
  1605. buildImageSuccessfully(c, name2, withExternalBuildContext(ctx))
  1606. id2 := getIDByName(c, name2)
  1607. if id1 == id2 {
  1608. c.Fatal("The cache should have been invalided but hasn't.")
  1609. }
  1610. // Check that changing file invalidate cache of "ADD ."
  1611. if err := ctx.Add("foo", "hello1"); err != nil {
  1612. c.Fatal(err)
  1613. }
  1614. buildImageSuccessfully(c, name3, withExternalBuildContext(ctx))
  1615. id3 := getIDByName(c, name3)
  1616. if id2 == id3 {
  1617. c.Fatal("The cache should have been invalided but hasn't.")
  1618. }
  1619. // Check that changing file to same content with different mtime does not
  1620. // invalidate cache of "ADD ."
  1621. time.Sleep(1 * time.Second) // wait second because of mtime precision
  1622. if err := ctx.Add("foo", "hello1"); err != nil {
  1623. c.Fatal(err)
  1624. }
  1625. buildImageSuccessfully(c, name4, withExternalBuildContext(ctx))
  1626. id4 := getIDByName(c, name4)
  1627. if id3 != id4 {
  1628. c.Fatal("The cache should have been used but hasn't.")
  1629. }
  1630. }
  1631. // FIXME(vdemeester) this really seems to test the same thing as before (TestBuildAddMultipleLocalFileWithAndWithoutCache)
  1632. func (s *DockerSuite) TestBuildAddCurrentDirWithoutCache(c *check.C) {
  1633. name := "testbuildaddcurrentdirwithoutcache"
  1634. dockerfile := `
  1635. FROM ` + minimalBaseImage() + `
  1636. MAINTAINER dockerio
  1637. ADD . /usr/lib/bla`
  1638. ctx := fakeContext(c, dockerfile, map[string]string{
  1639. "foo": "hello",
  1640. })
  1641. defer ctx.Close()
  1642. buildImageSuccessfully(c, name, withExternalBuildContext(ctx))
  1643. id1 := getIDByName(c, name)
  1644. buildImageSuccessfully(c, name, withoutCache, withExternalBuildContext(ctx))
  1645. id2 := getIDByName(c, name)
  1646. if id1 == id2 {
  1647. c.Fatal("The cache should have been invalided but hasn't.")
  1648. }
  1649. }
  1650. func (s *DockerSuite) TestBuildAddRemoteFileWithAndWithoutCache(c *check.C) {
  1651. name := "testbuildaddremotefilewithcache"
  1652. server := fakeStorage(c, map[string]string{
  1653. "baz": "hello",
  1654. })
  1655. defer server.Close()
  1656. dockerfile := fmt.Sprintf(`FROM `+minimalBaseImage()+`
  1657. MAINTAINER dockerio
  1658. ADD %s/baz /usr/lib/baz/quux`, server.URL())
  1659. buildImageSuccessfully(c, name, withDockerfile(dockerfile))
  1660. id1 := getIDByName(c, name)
  1661. buildImageSuccessfully(c, name, withDockerfile(dockerfile))
  1662. id2 := getIDByName(c, name)
  1663. buildImageSuccessfully(c, name, withoutCache, withDockerfile(dockerfile))
  1664. id3 := getIDByName(c, name)
  1665. if id1 != id2 {
  1666. c.Fatal("The cache should have been used but hasn't.")
  1667. }
  1668. if id1 == id3 {
  1669. c.Fatal("The cache should have been invalided but hasn't.")
  1670. }
  1671. }
  1672. func (s *DockerSuite) TestBuildAddRemoteFileMTime(c *check.C) {
  1673. name := "testbuildaddremotefilemtime"
  1674. name2 := name + "2"
  1675. name3 := name + "3"
  1676. files := map[string]string{"baz": "hello"}
  1677. server := fakeStorage(c, files)
  1678. defer server.Close()
  1679. ctx := fakeContext(c, fmt.Sprintf(`FROM `+minimalBaseImage()+`
  1680. MAINTAINER dockerio
  1681. ADD %s/baz /usr/lib/baz/quux`, server.URL()), nil)
  1682. defer ctx.Close()
  1683. buildImageSuccessfully(c, name, withExternalBuildContext(ctx))
  1684. id1 := getIDByName(c, name)
  1685. buildImageSuccessfully(c, name2, withExternalBuildContext(ctx))
  1686. id2 := getIDByName(c, name2)
  1687. if id1 != id2 {
  1688. c.Fatal("The cache should have been used but wasn't - #1")
  1689. }
  1690. // Now create a different server with same contents (causes different mtime)
  1691. // The cache should still be used
  1692. // allow some time for clock to pass as mtime precision is only 1s
  1693. time.Sleep(2 * time.Second)
  1694. server2 := fakeStorage(c, files)
  1695. defer server2.Close()
  1696. ctx2 := fakeContext(c, fmt.Sprintf(`FROM `+minimalBaseImage()+`
  1697. MAINTAINER dockerio
  1698. ADD %s/baz /usr/lib/baz/quux`, server2.URL()), nil)
  1699. defer ctx2.Close()
  1700. buildImageSuccessfully(c, name3, withExternalBuildContext(ctx2))
  1701. id3 := getIDByName(c, name3)
  1702. if id1 != id3 {
  1703. c.Fatal("The cache should have been used but wasn't")
  1704. }
  1705. }
  1706. // FIXME(vdemeester) this really seems to test the same thing as before (combined)
  1707. func (s *DockerSuite) TestBuildAddLocalAndRemoteFilesWithAndWithoutCache(c *check.C) {
  1708. name := "testbuildaddlocalandremotefilewithcache"
  1709. server := fakeStorage(c, map[string]string{
  1710. "baz": "hello",
  1711. })
  1712. defer server.Close()
  1713. ctx := fakeContext(c, fmt.Sprintf(`FROM `+minimalBaseImage()+`
  1714. MAINTAINER dockerio
  1715. ADD foo /usr/lib/bla/bar
  1716. ADD %s/baz /usr/lib/baz/quux`, server.URL()),
  1717. map[string]string{
  1718. "foo": "hello world",
  1719. })
  1720. defer ctx.Close()
  1721. buildImageSuccessfully(c, name, withExternalBuildContext(ctx))
  1722. id1 := getIDByName(c, name)
  1723. buildImageSuccessfully(c, name, withExternalBuildContext(ctx))
  1724. id2 := getIDByName(c, name)
  1725. buildImageSuccessfully(c, name, withoutCache, withExternalBuildContext(ctx))
  1726. id3 := getIDByName(c, name)
  1727. if id1 != id2 {
  1728. c.Fatal("The cache should have been used but hasn't.")
  1729. }
  1730. if id1 == id3 {
  1731. c.Fatal("The cache should have been invalidated but hasn't.")
  1732. }
  1733. }
  1734. func testContextTar(c *check.C, compression archive.Compression) {
  1735. ctx := fakeContext(c,
  1736. `FROM busybox
  1737. ADD foo /foo
  1738. CMD ["cat", "/foo"]`,
  1739. map[string]string{
  1740. "foo": "bar",
  1741. },
  1742. )
  1743. defer ctx.Close()
  1744. context, err := archive.Tar(ctx.Dir, compression)
  1745. if err != nil {
  1746. c.Fatalf("failed to build context tar: %v", err)
  1747. }
  1748. name := "contexttar"
  1749. icmd.RunCmd(icmd.Cmd{
  1750. Command: []string{dockerBinary, "build", "-t", name, "-"},
  1751. Stdin: context,
  1752. }).Assert(c, icmd.Success)
  1753. }
  1754. func (s *DockerSuite) TestBuildContextTarGzip(c *check.C) {
  1755. testContextTar(c, archive.Gzip)
  1756. }
  1757. func (s *DockerSuite) TestBuildContextTarNoCompression(c *check.C) {
  1758. testContextTar(c, archive.Uncompressed)
  1759. }
  1760. func (s *DockerSuite) TestBuildNoContext(c *check.C) {
  1761. name := "nocontext"
  1762. icmd.RunCmd(icmd.Cmd{
  1763. Command: []string{dockerBinary, "build", "-t", name, "-"},
  1764. Stdin: strings.NewReader(
  1765. `FROM busybox
  1766. CMD ["echo", "ok"]`),
  1767. }).Assert(c, icmd.Success)
  1768. if out, _ := dockerCmd(c, "run", "--rm", "nocontext"); out != "ok\n" {
  1769. c.Fatalf("run produced invalid output: %q, expected %q", out, "ok")
  1770. }
  1771. }
  1772. func (s *DockerSuite) TestBuildWithVolumeOwnership(c *check.C) {
  1773. testRequires(c, DaemonIsLinux)
  1774. name := "testbuildimg"
  1775. buildImageSuccessfully(c, name, withDockerfile(`FROM busybox:latest
  1776. RUN mkdir /test && chown daemon:daemon /test && chmod 0600 /test
  1777. VOLUME /test`))
  1778. out, _ := dockerCmd(c, "run", "--rm", "testbuildimg", "ls", "-la", "/test")
  1779. if expected := "drw-------"; !strings.Contains(out, expected) {
  1780. c.Fatalf("expected %s received %s", expected, out)
  1781. }
  1782. if expected := "daemon daemon"; !strings.Contains(out, expected) {
  1783. c.Fatalf("expected %s received %s", expected, out)
  1784. }
  1785. }
  1786. // testing #1405 - config.Cmd does not get cleaned up if
  1787. // utilizing cache
  1788. func (s *DockerSuite) TestBuildEntrypointRunCleanup(c *check.C) {
  1789. name := "testbuildcmdcleanup"
  1790. buildImageSuccessfully(c, name, withDockerfile(`FROM busybox
  1791. RUN echo "hello"`))
  1792. buildImageSuccessfully(c, name, withBuildContext(c,
  1793. withFile("Dockerfile", `FROM busybox
  1794. RUN echo "hello"
  1795. ADD foo /foo
  1796. ENTRYPOINT ["/bin/echo"]`),
  1797. withFile("foo", "hello")))
  1798. res := inspectField(c, name, "Config.Cmd")
  1799. // Cmd must be cleaned up
  1800. if res != "[]" {
  1801. c.Fatalf("Cmd %s, expected nil", res)
  1802. }
  1803. }
  1804. func (s *DockerSuite) TestBuildAddFileNotFound(c *check.C) {
  1805. name := "testbuildaddnotfound"
  1806. expected := "foo: no such file or directory"
  1807. if testEnv.DaemonPlatform() == "windows" {
  1808. expected = "foo: The system cannot find the file specified"
  1809. }
  1810. buildImage(name, withBuildContext(c,
  1811. withFile("Dockerfile", `FROM `+minimalBaseImage()+`
  1812. ADD foo /usr/local/bar`),
  1813. withFile("bar", "hello"))).Assert(c, icmd.Expected{
  1814. ExitCode: 1,
  1815. Err: expected,
  1816. })
  1817. }
  1818. func (s *DockerSuite) TestBuildInheritance(c *check.C) {
  1819. testRequires(c, DaemonIsLinux)
  1820. name := "testbuildinheritance"
  1821. buildImageSuccessfully(c, name, withDockerfile(`FROM scratch
  1822. EXPOSE 2375`))
  1823. ports1 := inspectField(c, name, "Config.ExposedPorts")
  1824. buildImageSuccessfully(c, name, withDockerfile(fmt.Sprintf(`FROM %s
  1825. ENTRYPOINT ["/bin/echo"]`, name)))
  1826. res := inspectField(c, name, "Config.Entrypoint")
  1827. if expected := "[/bin/echo]"; res != expected {
  1828. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  1829. }
  1830. ports2 := inspectField(c, name, "Config.ExposedPorts")
  1831. if ports1 != ports2 {
  1832. c.Fatalf("Ports must be same: %s != %s", ports1, ports2)
  1833. }
  1834. }
  1835. func (s *DockerSuite) TestBuildFails(c *check.C) {
  1836. name := "testbuildfails"
  1837. buildImage(name, withDockerfile(`FROM busybox
  1838. RUN sh -c "exit 23"`)).Assert(c, icmd.Expected{
  1839. ExitCode: 23,
  1840. Err: "returned a non-zero code: 23",
  1841. })
  1842. }
  1843. func (s *DockerSuite) TestBuildOnBuild(c *check.C) {
  1844. name := "testbuildonbuild"
  1845. buildImageSuccessfully(c, name, withDockerfile(`FROM busybox
  1846. ONBUILD RUN touch foobar`))
  1847. buildImageSuccessfully(c, name, withDockerfile(fmt.Sprintf(`FROM %s
  1848. RUN [ -f foobar ]`, name)))
  1849. }
  1850. // gh #2446
  1851. func (s *DockerSuite) TestBuildAddToSymlinkDest(c *check.C) {
  1852. makeLink := `ln -s /foo /bar`
  1853. if testEnv.DaemonPlatform() == "windows" {
  1854. makeLink = `mklink /D C:\bar C:\foo`
  1855. }
  1856. name := "testbuildaddtosymlinkdest"
  1857. buildImageSuccessfully(c, name, withBuildContext(c,
  1858. withFile("Dockerfile", `
  1859. FROM busybox
  1860. RUN sh -c "mkdir /foo"
  1861. RUN `+makeLink+`
  1862. ADD foo /bar/
  1863. RUN sh -c "[ -f /bar/foo ]"
  1864. RUN sh -c "[ -f /foo/foo ]"`),
  1865. withFile("foo", "hello"),
  1866. ))
  1867. }
  1868. func (s *DockerSuite) TestBuildEscapeWhitespace(c *check.C) {
  1869. name := "testbuildescapewhitespace"
  1870. buildImageSuccessfully(c, name, withDockerfile(`
  1871. # ESCAPE=\
  1872. FROM busybox
  1873. MAINTAINER "Docker \
  1874. IO <io@\
  1875. docker.com>"
  1876. `))
  1877. res := inspectField(c, name, "Author")
  1878. if res != "\"Docker IO <io@docker.com>\"" {
  1879. c.Fatalf("Parsed string did not match the escaped string. Got: %q", res)
  1880. }
  1881. }
  1882. func (s *DockerSuite) TestBuildVerifyIntString(c *check.C) {
  1883. // Verify that strings that look like ints are still passed as strings
  1884. name := "testbuildstringing"
  1885. buildImageSuccessfully(c, name, withDockerfile(`
  1886. FROM busybox
  1887. MAINTAINER 123`))
  1888. out, _ := dockerCmd(c, "inspect", name)
  1889. if !strings.Contains(out, "\"123\"") {
  1890. c.Fatalf("Output does not contain the int as a string:\n%s", out)
  1891. }
  1892. }
  1893. func (s *DockerSuite) TestBuildDockerignore(c *check.C) {
  1894. name := "testbuilddockerignore"
  1895. buildImageSuccessfully(c, name, withBuildContext(c,
  1896. withFile("Dockerfile", `
  1897. FROM busybox
  1898. ADD . /bla
  1899. RUN sh -c "[[ -f /bla/src/x.go ]]"
  1900. RUN sh -c "[[ -f /bla/Makefile ]]"
  1901. RUN sh -c "[[ ! -e /bla/src/_vendor ]]"
  1902. RUN sh -c "[[ ! -e /bla/.gitignore ]]"
  1903. RUN sh -c "[[ ! -e /bla/README.md ]]"
  1904. RUN sh -c "[[ ! -e /bla/dir/foo ]]"
  1905. RUN sh -c "[[ ! -e /bla/foo ]]"
  1906. RUN sh -c "[[ ! -e /bla/.git ]]"
  1907. RUN sh -c "[[ ! -e v.cc ]]"
  1908. RUN sh -c "[[ ! -e src/v.cc ]]"
  1909. RUN sh -c "[[ ! -e src/_vendor/v.cc ]]"`),
  1910. withFile("Makefile", "all:"),
  1911. withFile(".git/HEAD", "ref: foo"),
  1912. withFile("src/x.go", "package main"),
  1913. withFile("src/_vendor/v.go", "package main"),
  1914. withFile("src/_vendor/v.cc", "package main"),
  1915. withFile("src/v.cc", "package main"),
  1916. withFile("v.cc", "package main"),
  1917. withFile("dir/foo", ""),
  1918. withFile(".gitignore", ""),
  1919. withFile("README.md", "readme"),
  1920. withFile(".dockerignore", `
  1921. .git
  1922. pkg
  1923. .gitignore
  1924. src/_vendor
  1925. *.md
  1926. **/*.cc
  1927. dir`),
  1928. ))
  1929. }
  1930. func (s *DockerSuite) TestBuildDockerignoreCleanPaths(c *check.C) {
  1931. name := "testbuilddockerignorecleanpaths"
  1932. buildImageSuccessfully(c, name, withBuildContext(c,
  1933. withFile("Dockerfile", `
  1934. FROM busybox
  1935. ADD . /tmp/
  1936. RUN sh -c "(! ls /tmp/foo) && (! ls /tmp/foo2) && (! ls /tmp/dir1/foo)"`),
  1937. withFile("foo", "foo"),
  1938. withFile("foo2", "foo2"),
  1939. withFile("dir1/foo", "foo in dir1"),
  1940. withFile(".dockerignore", "./foo\ndir1//foo\n./dir1/../foo2"),
  1941. ))
  1942. }
  1943. func (s *DockerSuite) TestBuildDockerignoreExceptions(c *check.C) {
  1944. name := "testbuilddockerignoreexceptions"
  1945. buildImageSuccessfully(c, name, withBuildContext(c,
  1946. withFile("Dockerfile", `
  1947. FROM busybox
  1948. ADD . /bla
  1949. RUN sh -c "[[ -f /bla/src/x.go ]]"
  1950. RUN sh -c "[[ -f /bla/Makefile ]]"
  1951. RUN sh -c "[[ ! -e /bla/src/_vendor ]]"
  1952. RUN sh -c "[[ ! -e /bla/.gitignore ]]"
  1953. RUN sh -c "[[ ! -e /bla/README.md ]]"
  1954. RUN sh -c "[[ -e /bla/dir/dir/foo ]]"
  1955. RUN sh -c "[[ ! -e /bla/dir/foo1 ]]"
  1956. RUN sh -c "[[ -f /bla/dir/e ]]"
  1957. RUN sh -c "[[ -f /bla/dir/e-dir/foo ]]"
  1958. RUN sh -c "[[ ! -e /bla/foo ]]"
  1959. RUN sh -c "[[ ! -e /bla/.git ]]"
  1960. RUN sh -c "[[ -e /bla/dir/a.cc ]]"`),
  1961. withFile("Makefile", "all:"),
  1962. withFile(".git/HEAD", "ref: foo"),
  1963. withFile("src/x.go", "package main"),
  1964. withFile("src/_vendor/v.go", "package main"),
  1965. withFile("dir/foo", ""),
  1966. withFile("dir/foo1", ""),
  1967. withFile("dir/dir/f1", ""),
  1968. withFile("dir/dir/foo", ""),
  1969. withFile("dir/e", ""),
  1970. withFile("dir/e-dir/foo", ""),
  1971. withFile(".gitignore", ""),
  1972. withFile("README.md", "readme"),
  1973. withFile("dir/a.cc", "hello"),
  1974. withFile(".dockerignore", `
  1975. .git
  1976. pkg
  1977. .gitignore
  1978. src/_vendor
  1979. *.md
  1980. dir
  1981. !dir/e*
  1982. !dir/dir/foo
  1983. **/*.cc
  1984. !**/*.cc`),
  1985. ))
  1986. }
  1987. func (s *DockerSuite) TestBuildDockerignoringDockerfile(c *check.C) {
  1988. name := "testbuilddockerignoredockerfile"
  1989. dockerfile := `
  1990. FROM busybox
  1991. ADD . /tmp/
  1992. RUN sh -c "! ls /tmp/Dockerfile"
  1993. RUN ls /tmp/.dockerignore`
  1994. buildImageSuccessfully(c, name, withBuildContext(c,
  1995. withFile("Dockerfile", dockerfile),
  1996. withFile(".dockerignore", "Dockerfile\n"),
  1997. ))
  1998. buildImageSuccessfully(c, name, withBuildContext(c,
  1999. withFile("Dockerfile", dockerfile),
  2000. withFile(".dockerignore", "./Dockerfile\n"),
  2001. ))
  2002. }
  2003. func (s *DockerSuite) TestBuildDockerignoringRenamedDockerfile(c *check.C) {
  2004. name := "testbuilddockerignoredockerfile"
  2005. dockerfile := `
  2006. FROM busybox
  2007. ADD . /tmp/
  2008. RUN ls /tmp/Dockerfile
  2009. RUN sh -c "! ls /tmp/MyDockerfile"
  2010. RUN ls /tmp/.dockerignore`
  2011. buildImageSuccessfully(c, name, withBuildFlags("-f", "MyDockerfile"), withBuildContext(c,
  2012. withFile("Dockerfile", "Should not use me"),
  2013. withFile("MyDockerfile", dockerfile),
  2014. withFile(".dockerignore", "MyDockerfile\n"),
  2015. ))
  2016. buildImageSuccessfully(c, name, withBuildFlags("-f", "MyDockerfile"), withBuildContext(c,
  2017. withFile("Dockerfile", "Should not use me"),
  2018. withFile("MyDockerfile", dockerfile),
  2019. withFile(".dockerignore", "./MyDockerfile\n"),
  2020. ))
  2021. }
  2022. func (s *DockerSuite) TestBuildDockerignoringDockerignore(c *check.C) {
  2023. name := "testbuilddockerignoredockerignore"
  2024. dockerfile := `
  2025. FROM busybox
  2026. ADD . /tmp/
  2027. RUN sh -c "! ls /tmp/.dockerignore"
  2028. RUN ls /tmp/Dockerfile`
  2029. buildImageSuccessfully(c, name, withBuildContext(c,
  2030. withFile("Dockerfile", dockerfile),
  2031. withFile(".dockerignore", ".dockerignore\n"),
  2032. ))
  2033. }
  2034. func (s *DockerSuite) TestBuildDockerignoreTouchDockerfile(c *check.C) {
  2035. name := "testbuilddockerignoretouchdockerfile"
  2036. dockerfile := `
  2037. FROM busybox
  2038. ADD . /tmp/`
  2039. ctx := fakeContext(c, dockerfile, map[string]string{
  2040. "Dockerfile": dockerfile,
  2041. ".dockerignore": "Dockerfile\n",
  2042. })
  2043. defer ctx.Close()
  2044. buildImageSuccessfully(c, name, withExternalBuildContext(ctx))
  2045. id1 := getIDByName(c, name)
  2046. buildImageSuccessfully(c, name, withExternalBuildContext(ctx))
  2047. id2 := getIDByName(c, name)
  2048. if id1 != id2 {
  2049. c.Fatalf("Didn't use the cache - 1")
  2050. }
  2051. // Now make sure touching Dockerfile doesn't invalidate the cache
  2052. if err := ctx.Add("Dockerfile", dockerfile+"\n# hi"); err != nil {
  2053. c.Fatalf("Didn't add Dockerfile: %s", err)
  2054. }
  2055. buildImageSuccessfully(c, name, withExternalBuildContext(ctx))
  2056. id2 = getIDByName(c, name)
  2057. if id1 != id2 {
  2058. c.Fatalf("Didn't use the cache - 2")
  2059. }
  2060. // One more time but just 'touch' it instead of changing the content
  2061. if err := ctx.Add("Dockerfile", dockerfile+"\n# hi"); err != nil {
  2062. c.Fatalf("Didn't add Dockerfile: %s", err)
  2063. }
  2064. buildImageSuccessfully(c, name, withExternalBuildContext(ctx))
  2065. id2 = getIDByName(c, name)
  2066. if id1 != id2 {
  2067. c.Fatalf("Didn't use the cache - 3")
  2068. }
  2069. }
  2070. func (s *DockerSuite) TestBuildDockerignoringWholeDir(c *check.C) {
  2071. name := "testbuilddockerignorewholedir"
  2072. dockerfile := `
  2073. FROM busybox
  2074. COPY . /
  2075. RUN sh -c "[[ ! -e /.gitignore ]]"
  2076. RUN sh -c "[[ ! -e /Makefile ]]"`
  2077. buildImageSuccessfully(c, name, withBuildContext(c,
  2078. withFile("Dockerfile", dockerfile),
  2079. withFile(".dockerignore", "*\n"),
  2080. withFile("Makefile", "all:"),
  2081. withFile(".gitignore", ""),
  2082. ))
  2083. }
  2084. func (s *DockerSuite) TestBuildDockerignoringOnlyDotfiles(c *check.C) {
  2085. name := "testbuilddockerignorewholedir"
  2086. dockerfile := `
  2087. FROM busybox
  2088. COPY . /
  2089. RUN sh -c "[[ ! -e /.gitignore ]]"
  2090. RUN sh -c "[[ -f /Makefile ]]"`
  2091. buildImageSuccessfully(c, name, withBuildContext(c,
  2092. withFile("Dockerfile", dockerfile),
  2093. withFile(".dockerignore", ".*"),
  2094. withFile("Makefile", "all:"),
  2095. withFile(".gitignore", ""),
  2096. ))
  2097. }
  2098. func (s *DockerSuite) TestBuildDockerignoringBadExclusion(c *check.C) {
  2099. name := "testbuilddockerignorebadexclusion"
  2100. buildImage(name, withBuildContext(c,
  2101. withFile("Dockerfile", `
  2102. FROM busybox
  2103. COPY . /
  2104. RUN sh -c "[[ ! -e /.gitignore ]]"
  2105. RUN sh -c "[[ -f /Makefile ]]"`),
  2106. withFile("Makefile", "all:"),
  2107. withFile(".gitignore", ""),
  2108. withFile(".dockerignore", "!\n"),
  2109. )).Assert(c, icmd.Expected{
  2110. ExitCode: 1,
  2111. Err: "Error checking context: 'Illegal exclusion pattern: !",
  2112. })
  2113. }
  2114. func (s *DockerSuite) TestBuildDockerignoringWildTopDir(c *check.C) {
  2115. dockerfile := `
  2116. FROM busybox
  2117. COPY . /
  2118. RUN sh -c "[[ ! -e /.dockerignore ]]"
  2119. RUN sh -c "[[ ! -e /Dockerfile ]]"
  2120. RUN sh -c "[[ ! -e /file1 ]]"
  2121. RUN sh -c "[[ ! -e /dir ]]"`
  2122. // All of these should result in ignoring all files
  2123. for _, variant := range []string{"**", "**/", "**/**", "*"} {
  2124. buildImageSuccessfully(c, "noname", withBuildContext(c,
  2125. withFile("Dockerfile", dockerfile),
  2126. withFile("file1", ""),
  2127. withFile("dir/file1", ""),
  2128. withFile(".dockerignore", variant),
  2129. ))
  2130. dockerCmd(c, "rmi", "noname")
  2131. }
  2132. }
  2133. func (s *DockerSuite) TestBuildDockerignoringWildDirs(c *check.C) {
  2134. dockerfile := `
  2135. FROM busybox
  2136. COPY . /
  2137. #RUN sh -c "[[ -e /.dockerignore ]]"
  2138. RUN sh -c "[[ -e /Dockerfile ]] && \
  2139. [[ ! -e /file0 ]] && \
  2140. [[ ! -e /dir1/file0 ]] && \
  2141. [[ ! -e /dir2/file0 ]] && \
  2142. [[ ! -e /file1 ]] && \
  2143. [[ ! -e /dir1/file1 ]] && \
  2144. [[ ! -e /dir1/dir2/file1 ]] && \
  2145. [[ ! -e /dir1/file2 ]] && \
  2146. [[ -e /dir1/dir2/file2 ]] && \
  2147. [[ ! -e /dir1/dir2/file4 ]] && \
  2148. [[ ! -e /dir1/dir2/file5 ]] && \
  2149. [[ ! -e /dir1/dir2/file6 ]] && \
  2150. [[ ! -e /dir1/dir3/file7 ]] && \
  2151. [[ ! -e /dir1/dir3/file8 ]] && \
  2152. [[ -e /dir1/dir3 ]] && \
  2153. [[ -e /dir1/dir4 ]] && \
  2154. [[ ! -e 'dir1/dir5/fileAA' ]] && \
  2155. [[ -e 'dir1/dir5/fileAB' ]] && \
  2156. [[ -e 'dir1/dir5/fileB' ]]" # "." in pattern means nothing
  2157. RUN echo all done!`
  2158. dockerignore := `
  2159. **/file0
  2160. **/*file1
  2161. **/dir1/file2
  2162. dir1/**/file4
  2163. **/dir2/file5
  2164. **/dir1/dir2/file6
  2165. dir1/dir3/**
  2166. **/dir4/**
  2167. **/file?A
  2168. **/file\?B
  2169. **/dir5/file.
  2170. `
  2171. buildImageSuccessfully(c, "noname", withBuildContext(c,
  2172. withFile("Dockerfile", dockerfile),
  2173. withFile(".dockerignore", dockerignore),
  2174. withFile("dir1/file0", ""),
  2175. withFile("dir1/dir2/file0", ""),
  2176. withFile("file1", ""),
  2177. withFile("dir1/file1", ""),
  2178. withFile("dir1/dir2/file1", ""),
  2179. withFile("dir1/file2", ""),
  2180. withFile("dir1/dir2/file2", ""), // remains
  2181. withFile("dir1/dir2/file4", ""),
  2182. withFile("dir1/dir2/file5", ""),
  2183. withFile("dir1/dir2/file6", ""),
  2184. withFile("dir1/dir3/file7", ""),
  2185. withFile("dir1/dir3/file8", ""),
  2186. withFile("dir1/dir4/file9", ""),
  2187. withFile("dir1/dir5/fileAA", ""),
  2188. withFile("dir1/dir5/fileAB", ""),
  2189. withFile("dir1/dir5/fileB", ""),
  2190. ))
  2191. }
  2192. func (s *DockerSuite) TestBuildLineBreak(c *check.C) {
  2193. testRequires(c, DaemonIsLinux)
  2194. name := "testbuildlinebreak"
  2195. buildImageSuccessfully(c, name, withDockerfile(`FROM busybox
  2196. RUN sh -c 'echo root:testpass \
  2197. > /tmp/passwd'
  2198. RUN mkdir -p /var/run/sshd
  2199. RUN sh -c "[ "$(cat /tmp/passwd)" = "root:testpass" ]"
  2200. RUN sh -c "[ "$(ls -d /var/run/sshd)" = "/var/run/sshd" ]"`))
  2201. }
  2202. func (s *DockerSuite) TestBuildEOLInLine(c *check.C) {
  2203. testRequires(c, DaemonIsLinux)
  2204. name := "testbuildeolinline"
  2205. buildImageSuccessfully(c, name, withDockerfile(`FROM busybox
  2206. RUN sh -c 'echo root:testpass > /tmp/passwd'
  2207. RUN echo "foo \n bar"; echo "baz"
  2208. RUN mkdir -p /var/run/sshd
  2209. RUN sh -c "[ "$(cat /tmp/passwd)" = "root:testpass" ]"
  2210. RUN sh -c "[ "$(ls -d /var/run/sshd)" = "/var/run/sshd" ]"`))
  2211. }
  2212. func (s *DockerSuite) TestBuildCommentsShebangs(c *check.C) {
  2213. testRequires(c, DaemonIsLinux)
  2214. name := "testbuildcomments"
  2215. buildImageSuccessfully(c, name, withDockerfile(`FROM busybox
  2216. # This is an ordinary comment.
  2217. RUN { echo '#!/bin/sh'; echo 'echo hello world'; } > /hello.sh
  2218. RUN [ ! -x /hello.sh ]
  2219. # comment with line break \
  2220. RUN chmod +x /hello.sh
  2221. RUN [ -x /hello.sh ]
  2222. RUN [ "$(cat /hello.sh)" = $'#!/bin/sh\necho hello world' ]
  2223. RUN [ "$(/hello.sh)" = "hello world" ]`))
  2224. }
  2225. func (s *DockerSuite) TestBuildUsersAndGroups(c *check.C) {
  2226. testRequires(c, DaemonIsLinux)
  2227. name := "testbuildusers"
  2228. buildImageSuccessfully(c, name, withDockerfile(`FROM busybox
  2229. # Make sure our defaults work
  2230. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)" = '0:0/root:root' ]
  2231. # TODO decide if "args.user = strconv.Itoa(syscall.Getuid())" is acceptable behavior for changeUser in sysvinit instead of "return nil" when "USER" isn't specified (so that we get the proper group list even if that is the empty list, even in the default case of not supplying an explicit USER to run as, which implies USER 0)
  2232. USER root
  2233. RUN [ "$(id -G):$(id -Gn)" = '0 10:root wheel' ]
  2234. # Setup dockerio user and group
  2235. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd && \
  2236. echo 'dockerio:x:1001:' >> /etc/group
  2237. # Make sure we can switch to our user and all the information is exactly as we expect it to be
  2238. USER dockerio
  2239. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  2240. # Switch back to root and double check that worked exactly as we might expect it to
  2241. USER root
  2242. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '0:0/root:root/0 10:root wheel' ] && \
  2243. # Add a "supplementary" group for our dockerio user
  2244. echo 'supplementary:x:1002:dockerio' >> /etc/group
  2245. # ... and then go verify that we get it like we expect
  2246. USER dockerio
  2247. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001 1002:dockerio supplementary' ]
  2248. USER 1001
  2249. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001 1002:dockerio supplementary' ]
  2250. # super test the new "user:group" syntax
  2251. USER dockerio:dockerio
  2252. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  2253. USER 1001:dockerio
  2254. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  2255. USER dockerio:1001
  2256. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  2257. USER 1001:1001
  2258. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  2259. USER dockerio:supplementary
  2260. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  2261. USER dockerio:1002
  2262. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  2263. USER 1001:supplementary
  2264. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  2265. USER 1001:1002
  2266. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  2267. # make sure unknown uid/gid still works properly
  2268. USER 1042:1043
  2269. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1042:1043/1042:1043/1043:1043' ]`))
  2270. }
  2271. // FIXME(vdemeester) rename this test (and probably "merge" it with the one below TestBuildEnvUsage2)
  2272. func (s *DockerSuite) TestBuildEnvUsage(c *check.C) {
  2273. // /docker/world/hello is not owned by the correct user
  2274. testRequires(c, NotUserNamespace)
  2275. testRequires(c, DaemonIsLinux)
  2276. name := "testbuildenvusage"
  2277. dockerfile := `FROM busybox
  2278. ENV HOME /root
  2279. ENV PATH $HOME/bin:$PATH
  2280. ENV PATH /tmp:$PATH
  2281. RUN [ "$PATH" = "/tmp:$HOME/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" ]
  2282. ENV FOO /foo/baz
  2283. ENV BAR /bar
  2284. ENV BAZ $BAR
  2285. ENV FOOPATH $PATH:$FOO
  2286. RUN [ "$BAR" = "$BAZ" ]
  2287. RUN [ "$FOOPATH" = "$PATH:/foo/baz" ]
  2288. ENV FROM hello/docker/world
  2289. ENV TO /docker/world/hello
  2290. ADD $FROM $TO
  2291. RUN [ "$(cat $TO)" = "hello" ]
  2292. ENV abc=def
  2293. ENV ghi=$abc
  2294. RUN [ "$ghi" = "def" ]
  2295. `
  2296. buildImageSuccessfully(c, name, withBuildContext(c,
  2297. withFile("Dockerfile", dockerfile),
  2298. withFile("hello/docker/world", "hello"),
  2299. ))
  2300. }
  2301. // FIXME(vdemeester) rename this test (and probably "merge" it with the one above TestBuildEnvUsage)
  2302. func (s *DockerSuite) TestBuildEnvUsage2(c *check.C) {
  2303. // /docker/world/hello is not owned by the correct user
  2304. testRequires(c, NotUserNamespace)
  2305. testRequires(c, DaemonIsLinux)
  2306. name := "testbuildenvusage2"
  2307. dockerfile := `FROM busybox
  2308. ENV abc=def def="hello world"
  2309. RUN [ "$abc,$def" = "def,hello world" ]
  2310. ENV def=hello\ world v1=abc v2="hi there" v3='boogie nights' v4="with'quotes too"
  2311. RUN [ "$def,$v1,$v2,$v3,$v4" = "hello world,abc,hi there,boogie nights,with'quotes too" ]
  2312. ENV abc=zzz FROM=hello/docker/world
  2313. ENV abc=zzz TO=/docker/world/hello
  2314. ADD $FROM $TO
  2315. RUN [ "$abc,$(cat $TO)" = "zzz,hello" ]
  2316. ENV abc 'yyy'
  2317. RUN [ $abc = 'yyy' ]
  2318. ENV abc=
  2319. RUN [ "$abc" = "" ]
  2320. # use grep to make sure if the builder substitutes \$foo by mistake
  2321. # we don't get a false positive
  2322. ENV abc=\$foo
  2323. RUN [ "$abc" = "\$foo" ] && (echo "$abc" | grep foo)
  2324. ENV abc \$foo
  2325. RUN [ "$abc" = "\$foo" ] && (echo "$abc" | grep foo)
  2326. ENV abc=\'foo\' abc2=\"foo\"
  2327. RUN [ "$abc,$abc2" = "'foo',\"foo\"" ]
  2328. ENV abc "foo"
  2329. RUN [ "$abc" = "foo" ]
  2330. ENV abc 'foo'
  2331. RUN [ "$abc" = 'foo' ]
  2332. ENV abc \'foo\'
  2333. RUN [ "$abc" = "'foo'" ]
  2334. ENV abc \"foo\"
  2335. RUN [ "$abc" = '"foo"' ]
  2336. ENV abc=ABC
  2337. RUN [ "$abc" = "ABC" ]
  2338. ENV def1=${abc:-DEF} def2=${ccc:-DEF}
  2339. ENV def3=${ccc:-${def2}xx} def4=${abc:+ALT} def5=${def2:+${abc}:} def6=${ccc:-\$abc:} def7=${ccc:-\${abc}:}
  2340. RUN [ "$def1,$def2,$def3,$def4,$def5,$def6,$def7" = 'ABC,DEF,DEFxx,ALT,ABC:,$abc:,${abc:}' ]
  2341. ENV mypath=${mypath:+$mypath:}/home
  2342. ENV mypath=${mypath:+$mypath:}/away
  2343. RUN [ "$mypath" = '/home:/away' ]
  2344. ENV e1=bar
  2345. ENV e2=$e1 e3=$e11 e4=\$e1 e5=\$e11
  2346. RUN [ "$e0,$e1,$e2,$e3,$e4,$e5" = ',bar,bar,,$e1,$e11' ]
  2347. ENV ee1 bar
  2348. ENV ee2 $ee1
  2349. ENV ee3 $ee11
  2350. ENV ee4 \$ee1
  2351. ENV ee5 \$ee11
  2352. RUN [ "$ee1,$ee2,$ee3,$ee4,$ee5" = 'bar,bar,,$ee1,$ee11' ]
  2353. ENV eee1="foo" eee2='foo'
  2354. ENV eee3 "foo"
  2355. ENV eee4 'foo'
  2356. RUN [ "$eee1,$eee2,$eee3,$eee4" = 'foo,foo,foo,foo' ]
  2357. `
  2358. buildImageSuccessfully(c, name, withBuildContext(c,
  2359. withFile("Dockerfile", dockerfile),
  2360. withFile("hello/docker/world", "hello"),
  2361. ))
  2362. }
  2363. func (s *DockerSuite) TestBuildAddScript(c *check.C) {
  2364. testRequires(c, DaemonIsLinux)
  2365. name := "testbuildaddscript"
  2366. dockerfile := `
  2367. FROM busybox
  2368. ADD test /test
  2369. RUN ["chmod","+x","/test"]
  2370. RUN ["/test"]
  2371. RUN [ "$(cat /testfile)" = 'test!' ]`
  2372. buildImageSuccessfully(c, name, withBuildContext(c,
  2373. withFile("Dockerfile", dockerfile),
  2374. withFile("test", "#!/bin/sh\necho 'test!' > /testfile"),
  2375. ))
  2376. }
  2377. func (s *DockerSuite) TestBuildAddTar(c *check.C) {
  2378. // /test/foo is not owned by the correct user
  2379. testRequires(c, NotUserNamespace)
  2380. name := "testbuildaddtar"
  2381. ctx := func() *FakeContext {
  2382. dockerfile := `
  2383. FROM busybox
  2384. ADD test.tar /
  2385. RUN cat /test/foo | grep Hi
  2386. ADD test.tar /test.tar
  2387. RUN cat /test.tar/test/foo | grep Hi
  2388. ADD test.tar /unlikely-to-exist
  2389. RUN cat /unlikely-to-exist/test/foo | grep Hi
  2390. ADD test.tar /unlikely-to-exist-trailing-slash/
  2391. RUN cat /unlikely-to-exist-trailing-slash/test/foo | grep Hi
  2392. RUN sh -c "mkdir /existing-directory" #sh -c is needed on Windows to use the correct mkdir
  2393. ADD test.tar /existing-directory
  2394. RUN cat /existing-directory/test/foo | grep Hi
  2395. ADD test.tar /existing-directory-trailing-slash/
  2396. RUN cat /existing-directory-trailing-slash/test/foo | grep Hi`
  2397. tmpDir, err := ioutil.TempDir("", "fake-context")
  2398. c.Assert(err, check.IsNil)
  2399. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  2400. if err != nil {
  2401. c.Fatalf("failed to create test.tar archive: %v", err)
  2402. }
  2403. defer testTar.Close()
  2404. tw := tar.NewWriter(testTar)
  2405. if err := tw.WriteHeader(&tar.Header{
  2406. Name: "test/foo",
  2407. Size: 2,
  2408. }); err != nil {
  2409. c.Fatalf("failed to write tar file header: %v", err)
  2410. }
  2411. if _, err := tw.Write([]byte("Hi")); err != nil {
  2412. c.Fatalf("failed to write tar file content: %v", err)
  2413. }
  2414. if err := tw.Close(); err != nil {
  2415. c.Fatalf("failed to close tar archive: %v", err)
  2416. }
  2417. if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil {
  2418. c.Fatalf("failed to open destination dockerfile: %v", err)
  2419. }
  2420. return fakeContextFromDir(tmpDir)
  2421. }()
  2422. defer ctx.Close()
  2423. buildImageSuccessfully(c, name, withExternalBuildContext(ctx))
  2424. }
  2425. func (s *DockerSuite) TestBuildAddBrokenTar(c *check.C) {
  2426. name := "testbuildaddbrokentar"
  2427. ctx := func() *FakeContext {
  2428. dockerfile := `
  2429. FROM busybox
  2430. ADD test.tar /`
  2431. tmpDir, err := ioutil.TempDir("", "fake-context")
  2432. c.Assert(err, check.IsNil)
  2433. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  2434. if err != nil {
  2435. c.Fatalf("failed to create test.tar archive: %v", err)
  2436. }
  2437. defer testTar.Close()
  2438. tw := tar.NewWriter(testTar)
  2439. if err := tw.WriteHeader(&tar.Header{
  2440. Name: "test/foo",
  2441. Size: 2,
  2442. }); err != nil {
  2443. c.Fatalf("failed to write tar file header: %v", err)
  2444. }
  2445. if _, err := tw.Write([]byte("Hi")); err != nil {
  2446. c.Fatalf("failed to write tar file content: %v", err)
  2447. }
  2448. if err := tw.Close(); err != nil {
  2449. c.Fatalf("failed to close tar archive: %v", err)
  2450. }
  2451. // Corrupt the tar by removing one byte off the end
  2452. stat, err := testTar.Stat()
  2453. if err != nil {
  2454. c.Fatalf("failed to stat tar archive: %v", err)
  2455. }
  2456. if err := testTar.Truncate(stat.Size() - 1); err != nil {
  2457. c.Fatalf("failed to truncate tar archive: %v", err)
  2458. }
  2459. if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil {
  2460. c.Fatalf("failed to open destination dockerfile: %v", err)
  2461. }
  2462. return fakeContextFromDir(tmpDir)
  2463. }()
  2464. defer ctx.Close()
  2465. buildImage(name, withExternalBuildContext(ctx)).Assert(c, icmd.Expected{
  2466. ExitCode: 1,
  2467. })
  2468. }
  2469. func (s *DockerSuite) TestBuildAddNonTar(c *check.C) {
  2470. name := "testbuildaddnontar"
  2471. // Should not try to extract test.tar
  2472. buildImageSuccessfully(c, name, withBuildContext(c,
  2473. withFile("Dockerfile", `
  2474. FROM busybox
  2475. ADD test.tar /
  2476. RUN test -f /test.tar`),
  2477. withFile("test.tar", "not_a_tar_file"),
  2478. ))
  2479. }
  2480. func (s *DockerSuite) TestBuildAddTarXz(c *check.C) {
  2481. // /test/foo is not owned by the correct user
  2482. testRequires(c, NotUserNamespace)
  2483. testRequires(c, DaemonIsLinux)
  2484. name := "testbuildaddtarxz"
  2485. ctx := func() *FakeContext {
  2486. dockerfile := `
  2487. FROM busybox
  2488. ADD test.tar.xz /
  2489. RUN cat /test/foo | grep Hi`
  2490. tmpDir, err := ioutil.TempDir("", "fake-context")
  2491. c.Assert(err, check.IsNil)
  2492. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  2493. if err != nil {
  2494. c.Fatalf("failed to create test.tar archive: %v", err)
  2495. }
  2496. defer testTar.Close()
  2497. tw := tar.NewWriter(testTar)
  2498. if err := tw.WriteHeader(&tar.Header{
  2499. Name: "test/foo",
  2500. Size: 2,
  2501. }); err != nil {
  2502. c.Fatalf("failed to write tar file header: %v", err)
  2503. }
  2504. if _, err := tw.Write([]byte("Hi")); err != nil {
  2505. c.Fatalf("failed to write tar file content: %v", err)
  2506. }
  2507. if err := tw.Close(); err != nil {
  2508. c.Fatalf("failed to close tar archive: %v", err)
  2509. }
  2510. xzCompressCmd := exec.Command("xz", "-k", "test.tar")
  2511. xzCompressCmd.Dir = tmpDir
  2512. out, _, err := runCommandWithOutput(xzCompressCmd)
  2513. if err != nil {
  2514. c.Fatal(err, out)
  2515. }
  2516. if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil {
  2517. c.Fatalf("failed to open destination dockerfile: %v", err)
  2518. }
  2519. return fakeContextFromDir(tmpDir)
  2520. }()
  2521. defer ctx.Close()
  2522. buildImageSuccessfully(c, name, withExternalBuildContext(ctx))
  2523. }
  2524. func (s *DockerSuite) TestBuildAddTarXzGz(c *check.C) {
  2525. testRequires(c, DaemonIsLinux)
  2526. name := "testbuildaddtarxzgz"
  2527. ctx := func() *FakeContext {
  2528. dockerfile := `
  2529. FROM busybox
  2530. ADD test.tar.xz.gz /
  2531. RUN ls /test.tar.xz.gz`
  2532. tmpDir, err := ioutil.TempDir("", "fake-context")
  2533. c.Assert(err, check.IsNil)
  2534. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  2535. if err != nil {
  2536. c.Fatalf("failed to create test.tar archive: %v", err)
  2537. }
  2538. defer testTar.Close()
  2539. tw := tar.NewWriter(testTar)
  2540. if err := tw.WriteHeader(&tar.Header{
  2541. Name: "test/foo",
  2542. Size: 2,
  2543. }); err != nil {
  2544. c.Fatalf("failed to write tar file header: %v", err)
  2545. }
  2546. if _, err := tw.Write([]byte("Hi")); err != nil {
  2547. c.Fatalf("failed to write tar file content: %v", err)
  2548. }
  2549. if err := tw.Close(); err != nil {
  2550. c.Fatalf("failed to close tar archive: %v", err)
  2551. }
  2552. xzCompressCmd := exec.Command("xz", "-k", "test.tar")
  2553. xzCompressCmd.Dir = tmpDir
  2554. out, _, err := runCommandWithOutput(xzCompressCmd)
  2555. if err != nil {
  2556. c.Fatal(err, out)
  2557. }
  2558. gzipCompressCmd := exec.Command("gzip", "test.tar.xz")
  2559. gzipCompressCmd.Dir = tmpDir
  2560. out, _, err = runCommandWithOutput(gzipCompressCmd)
  2561. if err != nil {
  2562. c.Fatal(err, out)
  2563. }
  2564. if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil {
  2565. c.Fatalf("failed to open destination dockerfile: %v", err)
  2566. }
  2567. return fakeContextFromDir(tmpDir)
  2568. }()
  2569. defer ctx.Close()
  2570. buildImageSuccessfully(c, name, withExternalBuildContext(ctx))
  2571. }
  2572. func (s *DockerSuite) TestBuildFromGit(c *check.C) {
  2573. name := "testbuildfromgit"
  2574. git := newFakeGit(c, "repo", map[string]string{
  2575. "Dockerfile": `FROM busybox
  2576. ADD first /first
  2577. RUN [ -f /first ]
  2578. MAINTAINER docker`,
  2579. "first": "test git data",
  2580. }, true)
  2581. defer git.Close()
  2582. buildImageSuccessfully(c, name, withBuildContextPath(git.RepoURL))
  2583. res := inspectField(c, name, "Author")
  2584. if res != "docker" {
  2585. c.Fatalf("Maintainer should be docker, got %s", res)
  2586. }
  2587. }
  2588. func (s *DockerSuite) TestBuildFromGitWithContext(c *check.C) {
  2589. name := "testbuildfromgit"
  2590. git := newFakeGit(c, "repo", map[string]string{
  2591. "docker/Dockerfile": `FROM busybox
  2592. ADD first /first
  2593. RUN [ -f /first ]
  2594. MAINTAINER docker`,
  2595. "docker/first": "test git data",
  2596. }, true)
  2597. defer git.Close()
  2598. buildImageSuccessfully(c, name, withBuildContextPath(fmt.Sprintf("%s#master:docker", git.RepoURL)))
  2599. res := inspectField(c, name, "Author")
  2600. if res != "docker" {
  2601. c.Fatalf("Maintainer should be docker, got %s", res)
  2602. }
  2603. }
  2604. func (s *DockerSuite) TestBuildFromGitwithF(c *check.C) {
  2605. name := "testbuildfromgitwithf"
  2606. git := newFakeGit(c, "repo", map[string]string{
  2607. "myApp/myDockerfile": `FROM busybox
  2608. RUN echo hi from Dockerfile`,
  2609. }, true)
  2610. defer git.Close()
  2611. buildImage(name, withBuildFlags("-f", "myApp/myDockerfile"), withBuildContextPath(git.RepoURL)).Assert(c, icmd.Expected{
  2612. Out: "hi from Dockerfile",
  2613. })
  2614. }
  2615. func (s *DockerSuite) TestBuildFromRemoteTarball(c *check.C) {
  2616. name := "testbuildfromremotetarball"
  2617. buffer := new(bytes.Buffer)
  2618. tw := tar.NewWriter(buffer)
  2619. defer tw.Close()
  2620. dockerfile := []byte(`FROM busybox
  2621. MAINTAINER docker`)
  2622. if err := tw.WriteHeader(&tar.Header{
  2623. Name: "Dockerfile",
  2624. Size: int64(len(dockerfile)),
  2625. }); err != nil {
  2626. c.Fatalf("failed to write tar file header: %v", err)
  2627. }
  2628. if _, err := tw.Write(dockerfile); err != nil {
  2629. c.Fatalf("failed to write tar file content: %v", err)
  2630. }
  2631. if err := tw.Close(); err != nil {
  2632. c.Fatalf("failed to close tar archive: %v", err)
  2633. }
  2634. server := fakeBinaryStorage(c, map[string]*bytes.Buffer{
  2635. "testT.tar": buffer,
  2636. })
  2637. defer server.Close()
  2638. buildImageSuccessfully(c, name, withBuildContextPath(server.URL()+"/testT.tar"))
  2639. res := inspectField(c, name, "Author")
  2640. if res != "docker" {
  2641. c.Fatalf("Maintainer should be docker, got %s", res)
  2642. }
  2643. }
  2644. func (s *DockerSuite) TestBuildCleanupCmdOnEntrypoint(c *check.C) {
  2645. name := "testbuildcmdcleanuponentrypoint"
  2646. buildImageSuccessfully(c, name, withDockerfile(`FROM `+minimalBaseImage()+`
  2647. CMD ["test"]
  2648. ENTRYPOINT ["echo"]`))
  2649. buildImageSuccessfully(c, name, withDockerfile(fmt.Sprintf(`FROM %s
  2650. ENTRYPOINT ["cat"]`, name)))
  2651. res := inspectField(c, name, "Config.Cmd")
  2652. if res != "[]" {
  2653. c.Fatalf("Cmd %s, expected nil", res)
  2654. }
  2655. res = inspectField(c, name, "Config.Entrypoint")
  2656. if expected := "[cat]"; res != expected {
  2657. c.Fatalf("Entrypoint %s, expected %s", res, expected)
  2658. }
  2659. }
  2660. func (s *DockerSuite) TestBuildClearCmd(c *check.C) {
  2661. name := "testbuildclearcmd"
  2662. buildImageSuccessfully(c, name, withDockerfile(`FROM `+minimalBaseImage()+`
  2663. ENTRYPOINT ["/bin/bash"]
  2664. CMD []`))
  2665. res := inspectFieldJSON(c, name, "Config.Cmd")
  2666. if res != "[]" {
  2667. c.Fatalf("Cmd %s, expected %s", res, "[]")
  2668. }
  2669. }
  2670. func (s *DockerSuite) TestBuildEmptyCmd(c *check.C) {
  2671. // Skip on Windows. Base image on Windows has a CMD set in the image.
  2672. testRequires(c, DaemonIsLinux)
  2673. name := "testbuildemptycmd"
  2674. buildImageSuccessfully(c, name, withDockerfile("FROM "+minimalBaseImage()+"\nMAINTAINER quux\n"))
  2675. res := inspectFieldJSON(c, name, "Config.Cmd")
  2676. if res != "null" {
  2677. c.Fatalf("Cmd %s, expected %s", res, "null")
  2678. }
  2679. }
  2680. func (s *DockerSuite) TestBuildOnBuildOutput(c *check.C) {
  2681. name := "testbuildonbuildparent"
  2682. buildImageSuccessfully(c, name, withDockerfile("FROM busybox\nONBUILD RUN echo foo\n"))
  2683. buildImage(name, withDockerfile("FROM "+name+"\nMAINTAINER quux\n")).Assert(c, icmd.Expected{
  2684. Out: "# Executing 1 build trigger",
  2685. })
  2686. }
  2687. // FIXME(vdemeester) should be a unit test
  2688. func (s *DockerSuite) TestBuildInvalidTag(c *check.C) {
  2689. name := "abcd:" + stringutils.GenerateRandomAlphaOnlyString(200)
  2690. buildImage(name, withDockerfile("FROM "+minimalBaseImage()+"\nMAINTAINER quux\n")).Assert(c, icmd.Expected{
  2691. ExitCode: 125,
  2692. Err: "invalid reference format",
  2693. })
  2694. }
  2695. func (s *DockerSuite) TestBuildCmdShDashC(c *check.C) {
  2696. name := "testbuildcmdshc"
  2697. buildImageSuccessfully(c, name, withDockerfile("FROM busybox\nCMD echo cmd\n"))
  2698. res := inspectFieldJSON(c, name, "Config.Cmd")
  2699. expected := `["/bin/sh","-c","echo cmd"]`
  2700. if testEnv.DaemonPlatform() == "windows" {
  2701. expected = `["cmd","/S","/C","echo cmd"]`
  2702. }
  2703. if res != expected {
  2704. c.Fatalf("Expected value %s not in Config.Cmd: %s", expected, res)
  2705. }
  2706. }
  2707. func (s *DockerSuite) TestBuildCmdSpaces(c *check.C) {
  2708. // Test to make sure that when we strcat arrays we take into account
  2709. // the arg separator to make sure ["echo","hi"] and ["echo hi"] don't
  2710. // look the same
  2711. name := "testbuildcmdspaces"
  2712. buildImageSuccessfully(c, name, withDockerfile("FROM busybox\nCMD [\"echo hi\"]\n"))
  2713. id1 := getIDByName(c, name)
  2714. buildImageSuccessfully(c, name, withDockerfile("FROM busybox\nCMD [\"echo\", \"hi\"]\n"))
  2715. id2 := getIDByName(c, name)
  2716. if id1 == id2 {
  2717. c.Fatal("Should not have resulted in the same CMD")
  2718. }
  2719. // Now do the same with ENTRYPOINT
  2720. buildImageSuccessfully(c, name, withDockerfile("FROM busybox\nENTRYPOINT [\"echo hi\"]\n"))
  2721. id1 = getIDByName(c, name)
  2722. buildImageSuccessfully(c, name, withDockerfile("FROM busybox\nENTRYPOINT [\"echo\", \"hi\"]\n"))
  2723. id2 = getIDByName(c, name)
  2724. if id1 == id2 {
  2725. c.Fatal("Should not have resulted in the same ENTRYPOINT")
  2726. }
  2727. }
  2728. func (s *DockerSuite) TestBuildCmdJSONNoShDashC(c *check.C) {
  2729. name := "testbuildcmdjson"
  2730. buildImageSuccessfully(c, name, withDockerfile("FROM busybox\nCMD [\"echo\", \"cmd\"]"))
  2731. res := inspectFieldJSON(c, name, "Config.Cmd")
  2732. expected := `["echo","cmd"]`
  2733. if res != expected {
  2734. c.Fatalf("Expected value %s not in Config.Cmd: %s", expected, res)
  2735. }
  2736. }
  2737. func (s *DockerSuite) TestBuildEntrypointCanBeOverridenByChild(c *check.C) {
  2738. buildImageSuccessfully(c, "parent", withDockerfile(`
  2739. FROM busybox
  2740. ENTRYPOINT exit 130
  2741. `))
  2742. icmd.RunCommand(dockerBinary, "run", "parent").Assert(c, icmd.Expected{
  2743. ExitCode: 130,
  2744. })
  2745. buildImageSuccessfully(c, "child", withDockerfile(`
  2746. FROM parent
  2747. ENTRYPOINT exit 5
  2748. `))
  2749. icmd.RunCommand(dockerBinary, "run", "child").Assert(c, icmd.Expected{
  2750. ExitCode: 5,
  2751. })
  2752. }
  2753. func (s *DockerSuite) TestBuildEntrypointCanBeOverridenByChildInspect(c *check.C) {
  2754. var (
  2755. name = "testbuildepinherit"
  2756. name2 = "testbuildepinherit2"
  2757. expected = `["/bin/sh","-c","echo quux"]`
  2758. )
  2759. if testEnv.DaemonPlatform() == "windows" {
  2760. expected = `["cmd","/S","/C","echo quux"]`
  2761. }
  2762. buildImageSuccessfully(c, name, withDockerfile("FROM busybox\nENTRYPOINT /foo/bar"))
  2763. buildImageSuccessfully(c, name2, withDockerfile(fmt.Sprintf("FROM %s\nENTRYPOINT echo quux", name)))
  2764. res := inspectFieldJSON(c, name2, "Config.Entrypoint")
  2765. if res != expected {
  2766. c.Fatalf("Expected value %s not in Config.Entrypoint: %s", expected, res)
  2767. }
  2768. icmd.RunCommand(dockerBinary, "run", name2).Assert(c, icmd.Expected{
  2769. Out: "quux",
  2770. })
  2771. }
  2772. func (s *DockerSuite) TestBuildRunShEntrypoint(c *check.C) {
  2773. name := "testbuildentrypoint"
  2774. buildImageSuccessfully(c, name, withDockerfile(`FROM busybox
  2775. ENTRYPOINT echo`))
  2776. dockerCmd(c, "run", "--rm", name)
  2777. }
  2778. func (s *DockerSuite) TestBuildExoticShellInterpolation(c *check.C) {
  2779. testRequires(c, DaemonIsLinux)
  2780. name := "testbuildexoticshellinterpolation"
  2781. buildImageSuccessfully(c, name, withDockerfile(`
  2782. FROM busybox
  2783. ENV SOME_VAR a.b.c
  2784. RUN [ "$SOME_VAR" = 'a.b.c' ]
  2785. RUN [ "${SOME_VAR}" = 'a.b.c' ]
  2786. RUN [ "${SOME_VAR%.*}" = 'a.b' ]
  2787. RUN [ "${SOME_VAR%%.*}" = 'a' ]
  2788. RUN [ "${SOME_VAR#*.}" = 'b.c' ]
  2789. RUN [ "${SOME_VAR##*.}" = 'c' ]
  2790. RUN [ "${SOME_VAR/c/d}" = 'a.b.d' ]
  2791. RUN [ "${#SOME_VAR}" = '5' ]
  2792. RUN [ "${SOME_UNSET_VAR:-$SOME_VAR}" = 'a.b.c' ]
  2793. RUN [ "${SOME_VAR:+Version: ${SOME_VAR}}" = 'Version: a.b.c' ]
  2794. RUN [ "${SOME_UNSET_VAR:+${SOME_VAR}}" = '' ]
  2795. RUN [ "${SOME_UNSET_VAR:-${SOME_VAR:-d.e.f}}" = 'a.b.c' ]
  2796. `))
  2797. }
  2798. func (s *DockerSuite) TestBuildVerifySingleQuoteFails(c *check.C) {
  2799. // This testcase is supposed to generate an error because the
  2800. // JSON array we're passing in on the CMD uses single quotes instead
  2801. // of double quotes (per the JSON spec). This means we interpret it
  2802. // as a "string" instead of "JSON array" and pass it on to "sh -c" and
  2803. // it should barf on it.
  2804. name := "testbuildsinglequotefails"
  2805. expectedExitCode := 2
  2806. if testEnv.DaemonPlatform() == "windows" {
  2807. expectedExitCode = 127
  2808. }
  2809. buildImageSuccessfully(c, name, withDockerfile(`FROM busybox
  2810. CMD [ '/bin/sh', '-c', 'echo hi' ]`))
  2811. icmd.RunCommand(dockerBinary, "run", "--rm", name).Assert(c, icmd.Expected{
  2812. ExitCode: expectedExitCode,
  2813. })
  2814. }
  2815. func (s *DockerSuite) TestBuildVerboseOut(c *check.C) {
  2816. name := "testbuildverboseout"
  2817. expected := "\n123\n"
  2818. if testEnv.DaemonPlatform() == "windows" {
  2819. expected = "\n123\r\n"
  2820. }
  2821. buildImage(name, withDockerfile(`FROM busybox
  2822. RUN echo 123`)).Assert(c, icmd.Expected{
  2823. Out: expected,
  2824. })
  2825. }
  2826. func (s *DockerSuite) TestBuildWithTabs(c *check.C) {
  2827. name := "testbuildwithtabs"
  2828. buildImageSuccessfully(c, name, withDockerfile("FROM busybox\nRUN echo\tone\t\ttwo"))
  2829. res := inspectFieldJSON(c, name, "ContainerConfig.Cmd")
  2830. expected1 := `["/bin/sh","-c","echo\tone\t\ttwo"]`
  2831. expected2 := `["/bin/sh","-c","echo\u0009one\u0009\u0009two"]` // syntactically equivalent, and what Go 1.3 generates
  2832. if testEnv.DaemonPlatform() == "windows" {
  2833. expected1 = `["cmd","/S","/C","echo\tone\t\ttwo"]`
  2834. expected2 = `["cmd","/S","/C","echo\u0009one\u0009\u0009two"]` // syntactically equivalent, and what Go 1.3 generates
  2835. }
  2836. if res != expected1 && res != expected2 {
  2837. c.Fatalf("Missing tabs.\nGot: %s\nExp: %s or %s", res, expected1, expected2)
  2838. }
  2839. }
  2840. func (s *DockerSuite) TestBuildLabels(c *check.C) {
  2841. name := "testbuildlabel"
  2842. expected := `{"License":"GPL","Vendor":"Acme"}`
  2843. buildImageSuccessfully(c, name, withDockerfile(`FROM busybox
  2844. LABEL Vendor=Acme
  2845. LABEL License GPL`))
  2846. res := inspectFieldJSON(c, name, "Config.Labels")
  2847. if res != expected {
  2848. c.Fatalf("Labels %s, expected %s", res, expected)
  2849. }
  2850. }
  2851. func (s *DockerSuite) TestBuildLabelsCache(c *check.C) {
  2852. name := "testbuildlabelcache"
  2853. buildImageSuccessfully(c, name, withDockerfile(`FROM busybox
  2854. LABEL Vendor=Acme`))
  2855. id1 := getIDByName(c, name)
  2856. buildImageSuccessfully(c, name, withDockerfile(`FROM busybox
  2857. LABEL Vendor=Acme`))
  2858. id2 := getIDByName(c, name)
  2859. if id1 != id2 {
  2860. c.Fatalf("Build 2 should have worked & used cache(%s,%s)", id1, id2)
  2861. }
  2862. buildImageSuccessfully(c, name, withDockerfile(`FROM busybox
  2863. LABEL Vendor=Acme1`))
  2864. id2 = getIDByName(c, name)
  2865. if id1 == id2 {
  2866. c.Fatalf("Build 3 should have worked & NOT used cache(%s,%s)", id1, id2)
  2867. }
  2868. buildImageSuccessfully(c, name, withDockerfile(`FROM busybox
  2869. LABEL Vendor Acme`))
  2870. id2 = getIDByName(c, name)
  2871. if id1 != id2 {
  2872. c.Fatalf("Build 4 should have worked & used cache(%s,%s)", id1, id2)
  2873. }
  2874. // Now make sure the cache isn't used by mistake
  2875. buildImageSuccessfully(c, name, withoutCache, withDockerfile(`FROM busybox
  2876. LABEL f1=b1 f2=b2`))
  2877. buildImageSuccessfully(c, name, withDockerfile(`FROM busybox
  2878. LABEL f1=b1 f2=b2`))
  2879. id2 = getIDByName(c, name)
  2880. if id1 == id2 {
  2881. c.Fatalf("Build 6 should have worked & NOT used the cache(%s,%s)", id1, id2)
  2882. }
  2883. }
  2884. func (s *DockerSuite) TestBuildNotVerboseSuccess(c *check.C) {
  2885. // This test makes sure that -q works correctly when build is successful:
  2886. // stdout has only the image ID (long image ID) and stderr is empty.
  2887. outRegexp := regexp.MustCompile("^(sha256:|)[a-z0-9]{64}\\n$")
  2888. buildFlags := withBuildFlags("-q")
  2889. tt := []struct {
  2890. Name string
  2891. BuildFunc func(string) *icmd.Result
  2892. }{
  2893. {
  2894. Name: "quiet_build_stdin_success",
  2895. BuildFunc: func(name string) *icmd.Result {
  2896. return buildImage(name, buildFlags, withDockerfile("FROM busybox"))
  2897. },
  2898. },
  2899. {
  2900. Name: "quiet_build_ctx_success",
  2901. BuildFunc: func(name string) *icmd.Result {
  2902. return buildImage(name, buildFlags, withBuildContext(c,
  2903. withFile("Dockerfile", "FROM busybox"),
  2904. withFile("quiet_build_success_fctx", "test"),
  2905. ))
  2906. },
  2907. },
  2908. {
  2909. Name: "quiet_build_git_success",
  2910. BuildFunc: func(name string) *icmd.Result {
  2911. git := newFakeGit(c, "repo", map[string]string{
  2912. "Dockerfile": "FROM busybox",
  2913. }, true)
  2914. return buildImage(name, buildFlags, withBuildContextPath(git.RepoURL))
  2915. },
  2916. },
  2917. }
  2918. for _, te := range tt {
  2919. result := te.BuildFunc(te.Name)
  2920. result.Assert(c, icmd.Success)
  2921. if outRegexp.Find([]byte(result.Stdout())) == nil {
  2922. c.Fatalf("Test %s expected stdout to match the [%v] regexp, but it is [%v]", te.Name, outRegexp, result.Stdout())
  2923. }
  2924. if result.Stderr() != "" {
  2925. c.Fatalf("Test %s expected stderr to be empty, but it is [%#v]", te.Name, result.Stderr())
  2926. }
  2927. }
  2928. }
  2929. func (s *DockerSuite) TestBuildNotVerboseFailureWithNonExistImage(c *check.C) {
  2930. // This test makes sure that -q works correctly when build fails by
  2931. // comparing between the stderr output in quiet mode and in stdout
  2932. // and stderr output in verbose mode
  2933. testRequires(c, Network)
  2934. testName := "quiet_build_not_exists_image"
  2935. dockerfile := "FROM busybox11"
  2936. quietResult := buildImage(testName, withBuildFlags("-q"), withDockerfile(dockerfile))
  2937. quietResult.Assert(c, icmd.Expected{
  2938. ExitCode: 1,
  2939. })
  2940. result := buildImage(testName, withDockerfile(dockerfile))
  2941. result.Assert(c, icmd.Expected{
  2942. ExitCode: 1,
  2943. })
  2944. if quietResult.Stderr() != result.Combined() {
  2945. c.Fatal(fmt.Errorf("Test[%s] expected that quiet stderr and verbose stdout are equal; quiet [%v], verbose [%v]", testName, quietResult.Stderr(), result.Combined()))
  2946. }
  2947. }
  2948. func (s *DockerSuite) TestBuildNotVerboseFailure(c *check.C) {
  2949. // This test makes sure that -q works correctly when build fails by
  2950. // comparing between the stderr output in quiet mode and in stdout
  2951. // and stderr output in verbose mode
  2952. testCases := []struct {
  2953. testName string
  2954. dockerfile string
  2955. }{
  2956. {"quiet_build_no_from_at_the_beginning", "RUN whoami"},
  2957. {"quiet_build_unknown_instr", "FROMD busybox"},
  2958. }
  2959. for _, tc := range testCases {
  2960. quietResult := buildImage(tc.testName, withBuildFlags("-q"), withDockerfile(tc.dockerfile))
  2961. quietResult.Assert(c, icmd.Expected{
  2962. ExitCode: 1,
  2963. })
  2964. result := buildImage(tc.testName, withDockerfile(tc.dockerfile))
  2965. result.Assert(c, icmd.Expected{
  2966. ExitCode: 1,
  2967. })
  2968. if quietResult.Stderr() != result.Combined() {
  2969. c.Fatal(fmt.Errorf("Test[%s] expected that quiet stderr and verbose stdout are equal; quiet [%v], verbose [%v]", tc.testName, quietResult.Stderr(), result.Combined()))
  2970. }
  2971. }
  2972. }
  2973. func (s *DockerSuite) TestBuildNotVerboseFailureRemote(c *check.C) {
  2974. // This test ensures that when given a wrong URL, stderr in quiet mode and
  2975. // stderr in verbose mode are identical.
  2976. // TODO(vdemeester) with cobra, stdout has a carriage return too much so this test should not check stdout
  2977. URL := "http://something.invalid"
  2978. name := "quiet_build_wrong_remote"
  2979. quietResult := buildImage(name, withBuildFlags("-q"), withBuildContextPath(URL))
  2980. quietResult.Assert(c, icmd.Expected{
  2981. ExitCode: 1,
  2982. })
  2983. result := buildImage(name, withBuildContextPath(URL))
  2984. result.Assert(c, icmd.Expected{
  2985. ExitCode: 1,
  2986. })
  2987. if strings.TrimSpace(quietResult.Stderr()) != strings.TrimSpace(result.Combined()) {
  2988. c.Fatal(fmt.Errorf("Test[%s] expected that quiet stderr and verbose stdout are equal; quiet [%v], verbose [%v]", name, quietResult.Stderr(), result.Combined()))
  2989. }
  2990. }
  2991. func (s *DockerSuite) TestBuildStderr(c *check.C) {
  2992. // This test just makes sure that no non-error output goes
  2993. // to stderr
  2994. name := "testbuildstderr"
  2995. result := buildImage(name, withDockerfile("FROM busybox\nRUN echo one"))
  2996. result.Assert(c, icmd.Success)
  2997. // Windows to non-Windows should have a security warning
  2998. if runtime.GOOS == "windows" && testEnv.DaemonPlatform() != "windows" && !strings.Contains(result.Stdout(), "SECURITY WARNING:") {
  2999. c.Fatalf("Stdout contains unexpected output: %q", result.Stdout())
  3000. }
  3001. // Stderr should always be empty
  3002. if result.Stderr() != "" {
  3003. c.Fatalf("Stderr should have been empty, instead it's: %q", result.Stderr())
  3004. }
  3005. }
  3006. func (s *DockerSuite) TestBuildChownSingleFile(c *check.C) {
  3007. testRequires(c, UnixCli, DaemonIsLinux) // test uses chown: not available on windows
  3008. name := "testbuildchownsinglefile"
  3009. ctx := fakeContext(c, `
  3010. FROM busybox
  3011. COPY test /
  3012. RUN ls -l /test
  3013. RUN [ $(ls -l /test | awk '{print $3":"$4}') = 'root:root' ]
  3014. `, map[string]string{
  3015. "test": "test",
  3016. })
  3017. defer ctx.Close()
  3018. if err := os.Chown(filepath.Join(ctx.Dir, "test"), 4242, 4242); err != nil {
  3019. c.Fatal(err)
  3020. }
  3021. buildImageSuccessfully(c, name, withExternalBuildContext(ctx))
  3022. }
  3023. func (s *DockerSuite) TestBuildSymlinkBreakout(c *check.C) {
  3024. name := "testbuildsymlinkbreakout"
  3025. tmpdir, err := ioutil.TempDir("", name)
  3026. c.Assert(err, check.IsNil)
  3027. defer os.RemoveAll(tmpdir)
  3028. ctx := filepath.Join(tmpdir, "context")
  3029. if err := os.MkdirAll(ctx, 0755); err != nil {
  3030. c.Fatal(err)
  3031. }
  3032. if err := ioutil.WriteFile(filepath.Join(ctx, "Dockerfile"), []byte(`
  3033. from busybox
  3034. add symlink.tar /
  3035. add inject /symlink/
  3036. `), 0644); err != nil {
  3037. c.Fatal(err)
  3038. }
  3039. inject := filepath.Join(ctx, "inject")
  3040. if err := ioutil.WriteFile(inject, nil, 0644); err != nil {
  3041. c.Fatal(err)
  3042. }
  3043. f, err := os.Create(filepath.Join(ctx, "symlink.tar"))
  3044. if err != nil {
  3045. c.Fatal(err)
  3046. }
  3047. w := tar.NewWriter(f)
  3048. w.WriteHeader(&tar.Header{
  3049. Name: "symlink2",
  3050. Typeflag: tar.TypeSymlink,
  3051. Linkname: "/../../../../../../../../../../../../../../",
  3052. Uid: os.Getuid(),
  3053. Gid: os.Getgid(),
  3054. })
  3055. w.WriteHeader(&tar.Header{
  3056. Name: "symlink",
  3057. Typeflag: tar.TypeSymlink,
  3058. Linkname: filepath.Join("symlink2", tmpdir),
  3059. Uid: os.Getuid(),
  3060. Gid: os.Getgid(),
  3061. })
  3062. w.Close()
  3063. f.Close()
  3064. buildImageSuccessfully(c, name, withoutCache, withExternalBuildContext(fakeContextFromDir(ctx)))
  3065. if _, err := os.Lstat(filepath.Join(tmpdir, "inject")); err == nil {
  3066. c.Fatal("symlink breakout - inject")
  3067. } else if !os.IsNotExist(err) {
  3068. c.Fatalf("unexpected error: %v", err)
  3069. }
  3070. }
  3071. func (s *DockerSuite) TestBuildXZHost(c *check.C) {
  3072. // /usr/local/sbin/xz gets permission denied for the user
  3073. testRequires(c, NotUserNamespace)
  3074. testRequires(c, DaemonIsLinux)
  3075. name := "testbuildxzhost"
  3076. buildImageSuccessfully(c, name, withBuildContext(c,
  3077. withFile("Dockerfile", `
  3078. FROM busybox
  3079. ADD xz /usr/local/sbin/
  3080. RUN chmod 755 /usr/local/sbin/xz
  3081. ADD test.xz /
  3082. RUN [ ! -e /injected ]`),
  3083. withFile("test.xz", "\xfd\x37\x7a\x58\x5a\x00\x00\x04\xe6\xd6\xb4\x46\x02\x00"+
  3084. "\x21\x01\x16\x00\x00\x00\x74\x2f\xe5\xa3\x01\x00\x3f\xfd"+
  3085. "\x37\x7a\x58\x5a\x00\x00\x04\xe6\xd6\xb4\x46\x02\x00\x21"),
  3086. withFile("xz", "#!/bin/sh\ntouch /injected"),
  3087. ))
  3088. }
  3089. func (s *DockerSuite) TestBuildVolumesRetainContents(c *check.C) {
  3090. // /foo/file gets permission denied for the user
  3091. testRequires(c, NotUserNamespace)
  3092. testRequires(c, DaemonIsLinux) // TODO Windows: Issue #20127
  3093. var (
  3094. name = "testbuildvolumescontent"
  3095. expected = "some text"
  3096. volName = "/foo"
  3097. )
  3098. if testEnv.DaemonPlatform() == "windows" {
  3099. volName = "C:/foo"
  3100. }
  3101. buildImageSuccessfully(c, name, withBuildContext(c,
  3102. withFile("Dockerfile", `
  3103. FROM busybox
  3104. COPY content /foo/file
  3105. VOLUME `+volName+`
  3106. CMD cat /foo/file`),
  3107. withFile("content", expected),
  3108. ))
  3109. out, _ := dockerCmd(c, "run", "--rm", name)
  3110. if out != expected {
  3111. c.Fatalf("expected file contents for /foo/file to be %q but received %q", expected, out)
  3112. }
  3113. }
  3114. // FIXME(vdemeester) part of this should be unit test, other part should be clearer
  3115. func (s *DockerSuite) TestBuildRenamedDockerfile(c *check.C) {
  3116. ctx := fakeContext(c, `FROM busybox
  3117. RUN echo from Dockerfile`,
  3118. map[string]string{
  3119. "Dockerfile": "FROM busybox\nRUN echo from Dockerfile",
  3120. "files/Dockerfile": "FROM busybox\nRUN echo from files/Dockerfile",
  3121. "files/dFile": "FROM busybox\nRUN echo from files/dFile",
  3122. "dFile": "FROM busybox\nRUN echo from dFile",
  3123. "files/dFile2": "FROM busybox\nRUN echo from files/dFile2",
  3124. })
  3125. defer ctx.Close()
  3126. out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "-t", "test1", ".")
  3127. if err != nil {
  3128. c.Fatalf("Failed to build: %s\n%s", out, err)
  3129. }
  3130. if !strings.Contains(out, "from Dockerfile") {
  3131. c.Fatalf("test1 should have used Dockerfile, output:%s", out)
  3132. }
  3133. out, _, err = dockerCmdInDir(c, ctx.Dir, "build", "-f", filepath.Join("files", "Dockerfile"), "-t", "test2", ".")
  3134. if err != nil {
  3135. c.Fatal(err)
  3136. }
  3137. if !strings.Contains(out, "from files/Dockerfile") {
  3138. c.Fatalf("test2 should have used files/Dockerfile, output:%s", out)
  3139. }
  3140. out, _, err = dockerCmdInDir(c, ctx.Dir, "build", fmt.Sprintf("--file=%s", filepath.Join("files", "dFile")), "-t", "test3", ".")
  3141. if err != nil {
  3142. c.Fatal(err)
  3143. }
  3144. if !strings.Contains(out, "from files/dFile") {
  3145. c.Fatalf("test3 should have used files/dFile, output:%s", out)
  3146. }
  3147. out, _, err = dockerCmdInDir(c, ctx.Dir, "build", "--file=dFile", "-t", "test4", ".")
  3148. if err != nil {
  3149. c.Fatal(err)
  3150. }
  3151. if !strings.Contains(out, "from dFile") {
  3152. c.Fatalf("test4 should have used dFile, output:%s", out)
  3153. }
  3154. dirWithNoDockerfile, err := ioutil.TempDir(os.TempDir(), "test5")
  3155. c.Assert(err, check.IsNil)
  3156. nonDockerfileFile := filepath.Join(dirWithNoDockerfile, "notDockerfile")
  3157. if _, err = os.Create(nonDockerfileFile); err != nil {
  3158. c.Fatal(err)
  3159. }
  3160. out, _, err = dockerCmdInDir(c, ctx.Dir, "build", fmt.Sprintf("--file=%s", nonDockerfileFile), "-t", "test5", ".")
  3161. if err == nil {
  3162. c.Fatalf("test5 was supposed to fail to find passwd")
  3163. }
  3164. if expected := fmt.Sprintf("The Dockerfile (%s) must be within the build context (.)", nonDockerfileFile); !strings.Contains(out, expected) {
  3165. c.Fatalf("wrong error message:%v\nexpected to contain=%v", out, expected)
  3166. }
  3167. out, _, err = dockerCmdInDir(c, filepath.Join(ctx.Dir, "files"), "build", "-f", filepath.Join("..", "Dockerfile"), "-t", "test6", "..")
  3168. if err != nil {
  3169. c.Fatalf("test6 failed: %s", err)
  3170. }
  3171. if !strings.Contains(out, "from Dockerfile") {
  3172. c.Fatalf("test6 should have used root Dockerfile, output:%s", out)
  3173. }
  3174. out, _, err = dockerCmdInDir(c, filepath.Join(ctx.Dir, "files"), "build", "-f", filepath.Join(ctx.Dir, "files", "Dockerfile"), "-t", "test7", "..")
  3175. if err != nil {
  3176. c.Fatalf("test7 failed: %s", err)
  3177. }
  3178. if !strings.Contains(out, "from files/Dockerfile") {
  3179. c.Fatalf("test7 should have used files Dockerfile, output:%s", out)
  3180. }
  3181. out, _, err = dockerCmdInDir(c, filepath.Join(ctx.Dir, "files"), "build", "-f", filepath.Join("..", "Dockerfile"), "-t", "test8", ".")
  3182. if err == nil || !strings.Contains(out, "must be within the build context") {
  3183. c.Fatalf("test8 should have failed with Dockerfile out of context: %s", err)
  3184. }
  3185. tmpDir := os.TempDir()
  3186. out, _, err = dockerCmdInDir(c, tmpDir, "build", "-t", "test9", ctx.Dir)
  3187. if err != nil {
  3188. c.Fatalf("test9 - failed: %s", err)
  3189. }
  3190. if !strings.Contains(out, "from Dockerfile") {
  3191. c.Fatalf("test9 should have used root Dockerfile, output:%s", out)
  3192. }
  3193. out, _, err = dockerCmdInDir(c, filepath.Join(ctx.Dir, "files"), "build", "-f", "dFile2", "-t", "test10", ".")
  3194. if err != nil {
  3195. c.Fatalf("test10 should have worked: %s", err)
  3196. }
  3197. if !strings.Contains(out, "from files/dFile2") {
  3198. c.Fatalf("test10 should have used files/dFile2, output:%s", out)
  3199. }
  3200. }
  3201. func (s *DockerSuite) TestBuildFromMixedcaseDockerfile(c *check.C) {
  3202. testRequires(c, UnixCli) // Dockerfile overwrites dockerfile on windows
  3203. testRequires(c, DaemonIsLinux)
  3204. // If Dockerfile is not present, use dockerfile
  3205. buildImage("test1", withBuildContext(c,
  3206. withFile("dockerfile", `FROM busybox
  3207. RUN echo from dockerfile`),
  3208. )).Assert(c, icmd.Expected{
  3209. Out: "from dockerfile",
  3210. })
  3211. // Prefer Dockerfile in place of dockerfile
  3212. buildImage("test1", withBuildContext(c,
  3213. withFile("dockerfile", `FROM busybox
  3214. RUN echo from dockerfile`),
  3215. withFile("Dockerfile", `FROM busybox
  3216. RUN echo from Dockerfile`),
  3217. )).Assert(c, icmd.Expected{
  3218. Out: "from Dockerfile",
  3219. })
  3220. }
  3221. func (s *DockerSuite) TestBuildFromURLWithF(c *check.C) {
  3222. server := fakeStorage(c, map[string]string{"baz": `FROM busybox
  3223. RUN echo from baz
  3224. COPY * /tmp/
  3225. RUN find /tmp/`})
  3226. defer server.Close()
  3227. ctx := fakeContext(c, `FROM busybox
  3228. RUN echo from Dockerfile`,
  3229. map[string]string{})
  3230. defer ctx.Close()
  3231. // Make sure that -f is ignored and that we don't use the Dockerfile
  3232. // that's in the current dir
  3233. result := buildImage("test1", withBuildFlags("-f", "baz", server.URL()+"/baz"), func(cmd *icmd.Cmd) func() {
  3234. cmd.Dir = ctx.Dir
  3235. return nil
  3236. })
  3237. result.Assert(c, icmd.Success)
  3238. if !strings.Contains(result.Combined(), "from baz") ||
  3239. strings.Contains(result.Combined(), "/tmp/baz") ||
  3240. !strings.Contains(result.Combined(), "/tmp/Dockerfile") {
  3241. c.Fatalf("Missing proper output: %s", result.Combined())
  3242. }
  3243. }
  3244. func (s *DockerSuite) TestBuildFromStdinWithF(c *check.C) {
  3245. testRequires(c, DaemonIsLinux) // TODO Windows: This test is flaky; no idea why
  3246. ctx := fakeContext(c, `FROM busybox
  3247. RUN echo "from Dockerfile"`,
  3248. map[string]string{})
  3249. defer ctx.Close()
  3250. // Make sure that -f is ignored and that we don't use the Dockerfile
  3251. // that's in the current dir
  3252. result := buildImage("test1", withBuildFlags("-f", "baz", "-"), func(cmd *icmd.Cmd) func() {
  3253. cmd.Dir = ctx.Dir
  3254. cmd.Stdin = strings.NewReader(`FROM busybox
  3255. RUN echo "from baz"
  3256. COPY * /tmp/
  3257. RUN sh -c "find /tmp/" # sh -c is needed on Windows to use the correct find`)
  3258. return nil
  3259. })
  3260. result.Assert(c, icmd.Success)
  3261. if !strings.Contains(result.Combined(), "from baz") ||
  3262. strings.Contains(result.Combined(), "/tmp/baz") ||
  3263. !strings.Contains(result.Combined(), "/tmp/Dockerfile") {
  3264. c.Fatalf("Missing proper output: %s", result.Combined())
  3265. }
  3266. }
  3267. func (s *DockerSuite) TestBuildFromOfficialNames(c *check.C) {
  3268. name := "testbuildfromofficial"
  3269. fromNames := []string{
  3270. "busybox",
  3271. "docker.io/busybox",
  3272. "index.docker.io/busybox",
  3273. "library/busybox",
  3274. "docker.io/library/busybox",
  3275. "index.docker.io/library/busybox",
  3276. }
  3277. for idx, fromName := range fromNames {
  3278. imgName := fmt.Sprintf("%s%d", name, idx)
  3279. buildImageSuccessfully(c, imgName, withDockerfile("FROM "+fromName))
  3280. dockerCmd(c, "rmi", imgName)
  3281. }
  3282. }
  3283. func (s *DockerSuite) TestBuildDockerfileOutsideContext(c *check.C) {
  3284. testRequires(c, UnixCli, DaemonIsLinux) // uses os.Symlink: not implemented in windows at the time of writing (go-1.4.2)
  3285. name := "testbuilddockerfileoutsidecontext"
  3286. tmpdir, err := ioutil.TempDir("", name)
  3287. c.Assert(err, check.IsNil)
  3288. defer os.RemoveAll(tmpdir)
  3289. ctx := filepath.Join(tmpdir, "context")
  3290. if err := os.MkdirAll(ctx, 0755); err != nil {
  3291. c.Fatal(err)
  3292. }
  3293. if err := ioutil.WriteFile(filepath.Join(ctx, "Dockerfile"), []byte("FROM scratch\nENV X Y"), 0644); err != nil {
  3294. c.Fatal(err)
  3295. }
  3296. wd, err := os.Getwd()
  3297. if err != nil {
  3298. c.Fatal(err)
  3299. }
  3300. defer os.Chdir(wd)
  3301. if err := os.Chdir(ctx); err != nil {
  3302. c.Fatal(err)
  3303. }
  3304. if err := ioutil.WriteFile(filepath.Join(tmpdir, "outsideDockerfile"), []byte("FROM scratch\nENV x y"), 0644); err != nil {
  3305. c.Fatal(err)
  3306. }
  3307. if err := os.Symlink(filepath.Join("..", "outsideDockerfile"), filepath.Join(ctx, "dockerfile1")); err != nil {
  3308. c.Fatal(err)
  3309. }
  3310. if err := os.Symlink(filepath.Join(tmpdir, "outsideDockerfile"), filepath.Join(ctx, "dockerfile2")); err != nil {
  3311. c.Fatal(err)
  3312. }
  3313. for _, dockerfilePath := range []string{
  3314. filepath.Join("..", "outsideDockerfile"),
  3315. filepath.Join(ctx, "dockerfile1"),
  3316. filepath.Join(ctx, "dockerfile2"),
  3317. } {
  3318. result := dockerCmdWithResult("build", "-t", name, "--no-cache", "-f", dockerfilePath, ".")
  3319. c.Assert(result, icmd.Matches, icmd.Expected{
  3320. Err: "must be within the build context",
  3321. ExitCode: 1,
  3322. })
  3323. deleteImages(name)
  3324. }
  3325. os.Chdir(tmpdir)
  3326. // Path to Dockerfile should be resolved relative to working directory, not relative to context.
  3327. // There is a Dockerfile in the context, but since there is no Dockerfile in the current directory, the following should fail
  3328. out, _, err := dockerCmdWithError("build", "-t", name, "--no-cache", "-f", "Dockerfile", ctx)
  3329. if err == nil {
  3330. c.Fatalf("Expected error. Out: %s", out)
  3331. }
  3332. }
  3333. // FIXME(vdemeester) should be a unit test
  3334. func (s *DockerSuite) TestBuildSpaces(c *check.C) {
  3335. // Test to make sure that leading/trailing spaces on a command
  3336. // doesn't change the error msg we get
  3337. name := "testspaces"
  3338. ctx := fakeContext(c, "FROM busybox\nCOPY\n",
  3339. map[string]string{
  3340. "Dockerfile": "FROM busybox\nCOPY\n",
  3341. })
  3342. defer ctx.Close()
  3343. result1 := buildImage(name, withExternalBuildContext(ctx))
  3344. result1.Assert(c, icmd.Expected{
  3345. ExitCode: 1,
  3346. })
  3347. ctx.Add("Dockerfile", "FROM busybox\nCOPY ")
  3348. result2 := buildImage(name, withExternalBuildContext(ctx))
  3349. result2.Assert(c, icmd.Expected{
  3350. ExitCode: 1,
  3351. })
  3352. removeLogTimestamps := func(s string) string {
  3353. return regexp.MustCompile(`time="(.*?)"`).ReplaceAllString(s, `time=[TIMESTAMP]`)
  3354. }
  3355. // Skip over the times
  3356. e1 := removeLogTimestamps(result1.Error.Error())
  3357. e2 := removeLogTimestamps(result2.Error.Error())
  3358. // Ignore whitespace since that's what were verifying doesn't change stuff
  3359. if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
  3360. c.Fatalf("Build 2's error wasn't the same as build 1's\n1:%s\n2:%s", result1.Error, result2.Error)
  3361. }
  3362. ctx.Add("Dockerfile", "FROM busybox\n COPY")
  3363. result2 = buildImage(name, withoutCache, withExternalBuildContext(ctx))
  3364. result2.Assert(c, icmd.Expected{
  3365. ExitCode: 1,
  3366. })
  3367. // Skip over the times
  3368. e1 = removeLogTimestamps(result1.Error.Error())
  3369. e2 = removeLogTimestamps(result2.Error.Error())
  3370. // Ignore whitespace since that's what were verifying doesn't change stuff
  3371. if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
  3372. c.Fatalf("Build 3's error wasn't the same as build 1's\n1:%s\n3:%s", result1.Error, result2.Error)
  3373. }
  3374. ctx.Add("Dockerfile", "FROM busybox\n COPY ")
  3375. result2 = buildImage(name, withoutCache, withExternalBuildContext(ctx))
  3376. result2.Assert(c, icmd.Expected{
  3377. ExitCode: 1,
  3378. })
  3379. // Skip over the times
  3380. e1 = removeLogTimestamps(result1.Error.Error())
  3381. e2 = removeLogTimestamps(result2.Error.Error())
  3382. // Ignore whitespace since that's what were verifying doesn't change stuff
  3383. if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
  3384. c.Fatalf("Build 4's error wasn't the same as build 1's\n1:%s\n4:%s", result1.Error, result2.Error)
  3385. }
  3386. }
  3387. func (s *DockerSuite) TestBuildSpacesWithQuotes(c *check.C) {
  3388. // Test to make sure that spaces in quotes aren't lost
  3389. name := "testspacesquotes"
  3390. dockerfile := `FROM busybox
  3391. RUN echo " \
  3392. foo "`
  3393. expected := "\n foo \n"
  3394. // Windows uses the builtin echo, which preserves quotes
  3395. if testEnv.DaemonPlatform() == "windows" {
  3396. expected = "\" foo \""
  3397. }
  3398. buildImage(name, withDockerfile(dockerfile)).Assert(c, icmd.Expected{
  3399. Out: expected,
  3400. })
  3401. }
  3402. // #4393
  3403. func (s *DockerSuite) TestBuildVolumeFileExistsinContainer(c *check.C) {
  3404. testRequires(c, DaemonIsLinux) // TODO Windows: This should error out
  3405. buildImage("docker-test-errcreatevolumewithfile", withDockerfile(`
  3406. FROM busybox
  3407. RUN touch /foo
  3408. VOLUME /foo
  3409. `)).Assert(c, icmd.Expected{
  3410. ExitCode: 1,
  3411. Err: "file exists",
  3412. })
  3413. }
  3414. // FIXME(vdemeester) should be a unit test
  3415. func (s *DockerSuite) TestBuildMissingArgs(c *check.C) {
  3416. // Test to make sure that all Dockerfile commands (except the ones listed
  3417. // in skipCmds) will generate an error if no args are provided.
  3418. // Note: INSERT is deprecated so we exclude it because of that.
  3419. skipCmds := map[string]struct{}{
  3420. "CMD": {},
  3421. "RUN": {},
  3422. "ENTRYPOINT": {},
  3423. "INSERT": {},
  3424. }
  3425. if testEnv.DaemonPlatform() == "windows" {
  3426. skipCmds = map[string]struct{}{
  3427. "CMD": {},
  3428. "RUN": {},
  3429. "ENTRYPOINT": {},
  3430. "INSERT": {},
  3431. "STOPSIGNAL": {},
  3432. "ARG": {},
  3433. "USER": {},
  3434. "EXPOSE": {},
  3435. }
  3436. }
  3437. for cmd := range command.Commands {
  3438. cmd = strings.ToUpper(cmd)
  3439. if _, ok := skipCmds[cmd]; ok {
  3440. continue
  3441. }
  3442. var dockerfile string
  3443. if cmd == "FROM" {
  3444. dockerfile = cmd
  3445. } else {
  3446. // Add FROM to make sure we don't complain about it missing
  3447. dockerfile = "FROM busybox\n" + cmd
  3448. }
  3449. buildImage("args", withDockerfile(dockerfile)).Assert(c, icmd.Expected{
  3450. ExitCode: 1,
  3451. Err: cmd + " requires",
  3452. })
  3453. }
  3454. }
  3455. func (s *DockerSuite) TestBuildEmptyScratch(c *check.C) {
  3456. testRequires(c, DaemonIsLinux)
  3457. buildImage("sc", withDockerfile("FROM scratch")).Assert(c, icmd.Expected{
  3458. ExitCode: 1,
  3459. Err: "No image was generated",
  3460. })
  3461. }
  3462. func (s *DockerSuite) TestBuildDotDotFile(c *check.C) {
  3463. buildImageSuccessfully(c, "sc", withBuildContext(c,
  3464. withFile("Dockerfile", "FROM busybox\n"),
  3465. withFile("..gitme", ""),
  3466. ))
  3467. }
  3468. func (s *DockerSuite) TestBuildRUNoneJSON(c *check.C) {
  3469. testRequires(c, DaemonIsLinux) // No hello-world Windows image
  3470. name := "testbuildrunonejson"
  3471. buildImage(name, withDockerfile(`FROM hello-world:frozen
  3472. RUN [ "/hello" ]`)).Assert(c, icmd.Expected{
  3473. Out: "Hello from Docker",
  3474. })
  3475. }
  3476. func (s *DockerSuite) TestBuildEmptyStringVolume(c *check.C) {
  3477. name := "testbuildemptystringvolume"
  3478. buildImage(name, withDockerfile(`
  3479. FROM busybox
  3480. ENV foo=""
  3481. VOLUME $foo
  3482. `)).Assert(c, icmd.Expected{
  3483. ExitCode: 1,
  3484. })
  3485. }
  3486. func (s *DockerSuite) TestBuildContainerWithCgroupParent(c *check.C) {
  3487. testRequires(c, SameHostDaemon, DaemonIsLinux)
  3488. cgroupParent := "test"
  3489. data, err := ioutil.ReadFile("/proc/self/cgroup")
  3490. if err != nil {
  3491. c.Fatalf("failed to read '/proc/self/cgroup - %v", err)
  3492. }
  3493. selfCgroupPaths := testutil.ParseCgroupPaths(string(data))
  3494. _, found := selfCgroupPaths["memory"]
  3495. if !found {
  3496. c.Fatalf("unable to find self memory cgroup path. CgroupsPath: %v", selfCgroupPaths)
  3497. }
  3498. result := buildImage("buildcgroupparent",
  3499. withBuildFlags("--cgroup-parent", cgroupParent),
  3500. withDockerfile(`
  3501. FROM busybox
  3502. RUN cat /proc/self/cgroup
  3503. `))
  3504. result.Assert(c, icmd.Success)
  3505. m, err := regexp.MatchString(fmt.Sprintf("memory:.*/%s/.*", cgroupParent), result.Combined())
  3506. c.Assert(err, check.IsNil)
  3507. if !m {
  3508. c.Fatalf("There is no expected memory cgroup with parent /%s/: %s", cgroupParent, result.Combined())
  3509. }
  3510. }
  3511. // FIXME(vdemeester) could be a unit test
  3512. func (s *DockerSuite) TestBuildNoDupOutput(c *check.C) {
  3513. // Check to make sure our build output prints the Dockerfile cmd
  3514. // property - there was a bug that caused it to be duplicated on the
  3515. // Step X line
  3516. name := "testbuildnodupoutput"
  3517. result := buildImage(name, withDockerfile(`
  3518. FROM busybox
  3519. RUN env`))
  3520. result.Assert(c, icmd.Success)
  3521. exp := "\nStep 2/2 : RUN env\n"
  3522. if !strings.Contains(result.Combined(), exp) {
  3523. c.Fatalf("Bad output\nGot:%s\n\nExpected to contain:%s\n", result.Combined(), exp)
  3524. }
  3525. }
  3526. // GH15826
  3527. // FIXME(vdemeester) could be a unit test
  3528. func (s *DockerSuite) TestBuildStartsFromOne(c *check.C) {
  3529. // Explicit check to ensure that build starts from step 1 rather than 0
  3530. name := "testbuildstartsfromone"
  3531. result := buildImage(name, withDockerfile(`FROM busybox`))
  3532. result.Assert(c, icmd.Success)
  3533. exp := "\nStep 1/1 : FROM busybox\n"
  3534. if !strings.Contains(result.Combined(), exp) {
  3535. c.Fatalf("Bad output\nGot:%s\n\nExpected to contain:%s\n", result.Combined(), exp)
  3536. }
  3537. }
  3538. func (s *DockerSuite) TestBuildRUNErrMsg(c *check.C) {
  3539. // Test to make sure the bad command is quoted with just "s and
  3540. // not as a Go []string
  3541. name := "testbuildbadrunerrmsg"
  3542. shell := "/bin/sh -c"
  3543. exitCode := 127
  3544. if testEnv.DaemonPlatform() == "windows" {
  3545. shell = "cmd /S /C"
  3546. // architectural - Windows has to start the container to determine the exe is bad, Linux does not
  3547. exitCode = 1
  3548. }
  3549. exp := fmt.Sprintf(`The command '%s badEXE a1 \& a2 a3' returned a non-zero code: %d`, shell, exitCode)
  3550. buildImage(name, withDockerfile(`
  3551. FROM busybox
  3552. RUN badEXE a1 \& a2 a3`)).Assert(c, icmd.Expected{
  3553. ExitCode: exitCode,
  3554. Err: exp,
  3555. })
  3556. }
  3557. func (s *DockerTrustSuite) TestTrustedBuild(c *check.C) {
  3558. repoName := s.setupTrustedImage(c, "trusted-build")
  3559. dockerFile := fmt.Sprintf(`
  3560. FROM %s
  3561. RUN []
  3562. `, repoName)
  3563. name := "testtrustedbuild"
  3564. buildImage(name, trustedBuild, withDockerfile(dockerFile)).Assert(c, icmd.Expected{
  3565. Out: fmt.Sprintf("FROM %s@sha", repoName[:len(repoName)-7]),
  3566. })
  3567. // We should also have a tag reference for the image.
  3568. dockerCmd(c, "inspect", repoName)
  3569. // We should now be able to remove the tag reference.
  3570. dockerCmd(c, "rmi", repoName)
  3571. }
  3572. func (s *DockerTrustSuite) TestTrustedBuildUntrustedTag(c *check.C) {
  3573. repoName := fmt.Sprintf("%v/dockercli/build-untrusted-tag:latest", privateRegistryURL)
  3574. dockerFile := fmt.Sprintf(`
  3575. FROM %s
  3576. RUN []
  3577. `, repoName)
  3578. name := "testtrustedbuilduntrustedtag"
  3579. buildImage(name, trustedBuild, withDockerfile(dockerFile)).Assert(c, icmd.Expected{
  3580. ExitCode: 1,
  3581. Err: "does not have trust data for",
  3582. })
  3583. }
  3584. func (s *DockerTrustSuite) TestBuildContextDirIsSymlink(c *check.C) {
  3585. testRequires(c, DaemonIsLinux)
  3586. tempDir, err := ioutil.TempDir("", "test-build-dir-is-symlink-")
  3587. c.Assert(err, check.IsNil)
  3588. defer os.RemoveAll(tempDir)
  3589. // Make a real context directory in this temp directory with a simple
  3590. // Dockerfile.
  3591. realContextDirname := filepath.Join(tempDir, "context")
  3592. if err := os.Mkdir(realContextDirname, os.FileMode(0755)); err != nil {
  3593. c.Fatal(err)
  3594. }
  3595. if err = ioutil.WriteFile(
  3596. filepath.Join(realContextDirname, "Dockerfile"),
  3597. []byte(`
  3598. FROM busybox
  3599. RUN echo hello world
  3600. `),
  3601. os.FileMode(0644),
  3602. ); err != nil {
  3603. c.Fatal(err)
  3604. }
  3605. // Make a symlink to the real context directory.
  3606. contextSymlinkName := filepath.Join(tempDir, "context_link")
  3607. if err := os.Symlink(realContextDirname, contextSymlinkName); err != nil {
  3608. c.Fatal(err)
  3609. }
  3610. // Executing the build with the symlink as the specified context should
  3611. // *not* fail.
  3612. dockerCmd(c, "build", contextSymlinkName)
  3613. }
  3614. func (s *DockerTrustSuite) TestTrustedBuildTagFromReleasesRole(c *check.C) {
  3615. testRequires(c, NotaryHosting)
  3616. latestTag := s.setupTrustedImage(c, "trusted-build-releases-role")
  3617. repoName := strings.TrimSuffix(latestTag, ":latest")
  3618. // Now create the releases role
  3619. s.notaryCreateDelegation(c, repoName, "targets/releases", s.not.keys[0].Public)
  3620. s.notaryImportKey(c, repoName, "targets/releases", s.not.keys[0].Private)
  3621. s.notaryPublish(c, repoName)
  3622. // push a different tag to the releases role
  3623. otherTag := fmt.Sprintf("%s:other", repoName)
  3624. dockerCmd(c, "tag", "busybox", otherTag)
  3625. icmd.RunCmd(icmd.Command(dockerBinary, "push", otherTag), trustedCmd).Assert(c, icmd.Success)
  3626. s.assertTargetInRoles(c, repoName, "other", "targets/releases")
  3627. s.assertTargetNotInRoles(c, repoName, "other", "targets")
  3628. out, status := dockerCmd(c, "rmi", otherTag)
  3629. c.Assert(status, check.Equals, 0, check.Commentf("docker rmi failed: %s", out))
  3630. dockerFile := fmt.Sprintf(`
  3631. FROM %s
  3632. RUN []
  3633. `, otherTag)
  3634. name := "testtrustedbuildreleasesrole"
  3635. buildImage(name, trustedBuild, withDockerfile(dockerFile)).Assert(c, icmd.Expected{
  3636. Out: fmt.Sprintf("FROM %s@sha", repoName),
  3637. })
  3638. }
  3639. func (s *DockerTrustSuite) TestTrustedBuildTagIgnoresOtherDelegationRoles(c *check.C) {
  3640. testRequires(c, NotaryHosting)
  3641. latestTag := s.setupTrustedImage(c, "trusted-build-releases-role")
  3642. repoName := strings.TrimSuffix(latestTag, ":latest")
  3643. // Now create a non-releases delegation role
  3644. s.notaryCreateDelegation(c, repoName, "targets/other", s.not.keys[0].Public)
  3645. s.notaryImportKey(c, repoName, "targets/other", s.not.keys[0].Private)
  3646. s.notaryPublish(c, repoName)
  3647. // push a different tag to the other role
  3648. otherTag := fmt.Sprintf("%s:other", repoName)
  3649. dockerCmd(c, "tag", "busybox", otherTag)
  3650. icmd.RunCmd(icmd.Command(dockerBinary, "push", otherTag), trustedCmd).Assert(c, icmd.Success)
  3651. s.assertTargetInRoles(c, repoName, "other", "targets/other")
  3652. s.assertTargetNotInRoles(c, repoName, "other", "targets")
  3653. out, status := dockerCmd(c, "rmi", otherTag)
  3654. c.Assert(status, check.Equals, 0, check.Commentf("docker rmi failed: %s", out))
  3655. dockerFile := fmt.Sprintf(`
  3656. FROM %s
  3657. RUN []
  3658. `, otherTag)
  3659. name := "testtrustedbuildotherrole"
  3660. buildImage(name, trustedBuild, withDockerfile(dockerFile)).Assert(c, icmd.Expected{
  3661. ExitCode: 1,
  3662. })
  3663. }
  3664. // Issue #15634: COPY fails when path starts with "null"
  3665. func (s *DockerSuite) TestBuildNullStringInAddCopyVolume(c *check.C) {
  3666. name := "testbuildnullstringinaddcopyvolume"
  3667. volName := "nullvolume"
  3668. if testEnv.DaemonPlatform() == "windows" {
  3669. volName = `C:\\nullvolume`
  3670. }
  3671. buildImageSuccessfully(c, name, withBuildContext(c,
  3672. withFile("Dockerfile", `
  3673. FROM busybox
  3674. ADD null /
  3675. COPY nullfile /
  3676. VOLUME `+volName+`
  3677. `),
  3678. withFile("null", "test1"),
  3679. withFile("nullfile", "test2"),
  3680. ))
  3681. }
  3682. func (s *DockerSuite) TestBuildStopSignal(c *check.C) {
  3683. testRequires(c, DaemonIsLinux) // Windows does not support STOPSIGNAL yet
  3684. imgName := "test_build_stop_signal"
  3685. buildImageSuccessfully(c, imgName, withDockerfile(`FROM busybox
  3686. STOPSIGNAL SIGKILL`))
  3687. res := inspectFieldJSON(c, imgName, "Config.StopSignal")
  3688. if res != `"SIGKILL"` {
  3689. c.Fatalf("Signal %s, expected SIGKILL", res)
  3690. }
  3691. containerName := "test-container-stop-signal"
  3692. dockerCmd(c, "run", "-d", "--name", containerName, imgName, "top")
  3693. res = inspectFieldJSON(c, containerName, "Config.StopSignal")
  3694. if res != `"SIGKILL"` {
  3695. c.Fatalf("Signal %s, expected SIGKILL", res)
  3696. }
  3697. }
  3698. func (s *DockerSuite) TestBuildBuildTimeArg(c *check.C) {
  3699. imgName := "bldargtest"
  3700. envKey := "foo"
  3701. envVal := "bar"
  3702. var dockerfile string
  3703. if testEnv.DaemonPlatform() == "windows" {
  3704. // Bugs in Windows busybox port - use the default base image and native cmd stuff
  3705. dockerfile = fmt.Sprintf(`FROM `+minimalBaseImage()+`
  3706. ARG %s
  3707. RUN echo %%%s%%
  3708. CMD setlocal enableextensions && if defined %s (echo %%%s%%)`, envKey, envKey, envKey, envKey)
  3709. } else {
  3710. dockerfile = fmt.Sprintf(`FROM busybox
  3711. ARG %s
  3712. RUN echo $%s
  3713. CMD echo $%s`, envKey, envKey, envKey)
  3714. }
  3715. buildImage(imgName,
  3716. withBuildFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3717. withDockerfile(dockerfile),
  3718. ).Assert(c, icmd.Expected{
  3719. Out: envVal,
  3720. })
  3721. containerName := "bldargCont"
  3722. out, _ := dockerCmd(c, "run", "--name", containerName, imgName)
  3723. out = strings.Trim(out, " \r\n'")
  3724. if out != "" {
  3725. c.Fatalf("run produced invalid output: %q, expected empty string", out)
  3726. }
  3727. }
  3728. func (s *DockerSuite) TestBuildBuildTimeArgHistory(c *check.C) {
  3729. imgName := "bldargtest"
  3730. envKey := "foo"
  3731. envVal := "bar"
  3732. envDef := "bar1"
  3733. dockerfile := fmt.Sprintf(`FROM busybox
  3734. ARG %s=%s`, envKey, envDef)
  3735. buildImage(imgName,
  3736. withBuildFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3737. withDockerfile(dockerfile),
  3738. ).Assert(c, icmd.Expected{
  3739. Out: envVal,
  3740. })
  3741. out, _ := dockerCmd(c, "history", "--no-trunc", imgName)
  3742. outputTabs := strings.Split(out, "\n")[1]
  3743. if !strings.Contains(outputTabs, envDef) {
  3744. c.Fatalf("failed to find arg default in image history output: %q expected: %q", outputTabs, envDef)
  3745. }
  3746. }
  3747. func (s *DockerSuite) TestBuildBuildTimeArgCacheHit(c *check.C) {
  3748. imgName := "bldargtest"
  3749. envKey := "foo"
  3750. envVal := "bar"
  3751. dockerfile := fmt.Sprintf(`FROM busybox
  3752. ARG %s
  3753. RUN echo $%s`, envKey, envKey)
  3754. buildImageSuccessfully(c, imgName,
  3755. withBuildFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3756. withDockerfile(dockerfile),
  3757. )
  3758. origImgID := getIDByName(c, imgName)
  3759. imgNameCache := "bldargtestcachehit"
  3760. buildImageSuccessfully(c, imgNameCache,
  3761. withBuildFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3762. withDockerfile(dockerfile),
  3763. )
  3764. newImgID := getIDByName(c, imgName)
  3765. if newImgID != origImgID {
  3766. c.Fatalf("build didn't use cache! expected image id: %q built image id: %q", origImgID, newImgID)
  3767. }
  3768. }
  3769. func (s *DockerSuite) TestBuildBuildTimeArgCacheMissExtraArg(c *check.C) {
  3770. imgName := "bldargtest"
  3771. envKey := "foo"
  3772. envVal := "bar"
  3773. extraEnvKey := "foo1"
  3774. extraEnvVal := "bar1"
  3775. dockerfile := fmt.Sprintf(`FROM busybox
  3776. ARG %s
  3777. ARG %s
  3778. RUN echo $%s`, envKey, extraEnvKey, envKey)
  3779. buildImageSuccessfully(c, imgName,
  3780. withBuildFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3781. withDockerfile(dockerfile),
  3782. )
  3783. origImgID := getIDByName(c, imgName)
  3784. imgNameCache := "bldargtestcachemiss"
  3785. buildImageSuccessfully(c, imgNameCache,
  3786. withBuildFlags(
  3787. "--build-arg", fmt.Sprintf("%s=%s", envKey, envVal),
  3788. "--build-arg", fmt.Sprintf("%s=%s", extraEnvKey, extraEnvVal),
  3789. ),
  3790. withDockerfile(dockerfile),
  3791. )
  3792. newImgID := getIDByName(c, imgNameCache)
  3793. if newImgID == origImgID {
  3794. c.Fatalf("build used cache, expected a miss!")
  3795. }
  3796. }
  3797. func (s *DockerSuite) TestBuildBuildTimeArgCacheMissSameArgDiffVal(c *check.C) {
  3798. imgName := "bldargtest"
  3799. envKey := "foo"
  3800. envVal := "bar"
  3801. newEnvVal := "bar1"
  3802. dockerfile := fmt.Sprintf(`FROM busybox
  3803. ARG %s
  3804. RUN echo $%s`, envKey, envKey)
  3805. buildImageSuccessfully(c, imgName,
  3806. withBuildFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3807. withDockerfile(dockerfile),
  3808. )
  3809. origImgID := getIDByName(c, imgName)
  3810. imgNameCache := "bldargtestcachemiss"
  3811. buildImageSuccessfully(c, imgNameCache,
  3812. withBuildFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, newEnvVal)),
  3813. withDockerfile(dockerfile),
  3814. )
  3815. newImgID := getIDByName(c, imgNameCache)
  3816. if newImgID == origImgID {
  3817. c.Fatalf("build used cache, expected a miss!")
  3818. }
  3819. }
  3820. func (s *DockerSuite) TestBuildBuildTimeArgOverrideArgDefinedBeforeEnv(c *check.C) {
  3821. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  3822. imgName := "bldargtest"
  3823. envKey := "foo"
  3824. envVal := "bar"
  3825. envValOveride := "barOverride"
  3826. dockerfile := fmt.Sprintf(`FROM busybox
  3827. ARG %s
  3828. ENV %s %s
  3829. RUN echo $%s
  3830. CMD echo $%s
  3831. `, envKey, envKey, envValOveride, envKey, envKey)
  3832. result := buildImage(imgName,
  3833. withBuildFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3834. withDockerfile(dockerfile),
  3835. )
  3836. result.Assert(c, icmd.Success)
  3837. if strings.Count(result.Combined(), envValOveride) != 2 {
  3838. c.Fatalf("failed to access environment variable in output: %q expected: %q", result.Combined(), envValOveride)
  3839. }
  3840. containerName := "bldargCont"
  3841. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); !strings.Contains(out, envValOveride) {
  3842. c.Fatalf("run produced invalid output: %q, expected %q", out, envValOveride)
  3843. }
  3844. }
  3845. // FIXME(vdemeester) might be useful to merge with the one above ?
  3846. func (s *DockerSuite) TestBuildBuildTimeArgOverrideEnvDefinedBeforeArg(c *check.C) {
  3847. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  3848. imgName := "bldargtest"
  3849. envKey := "foo"
  3850. envVal := "bar"
  3851. envValOveride := "barOverride"
  3852. dockerfile := fmt.Sprintf(`FROM busybox
  3853. ENV %s %s
  3854. ARG %s
  3855. RUN echo $%s
  3856. CMD echo $%s
  3857. `, envKey, envValOveride, envKey, envKey, envKey)
  3858. result := buildImage(imgName,
  3859. withBuildFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3860. withDockerfile(dockerfile),
  3861. )
  3862. result.Assert(c, icmd.Success)
  3863. if strings.Count(result.Combined(), envValOveride) != 2 {
  3864. c.Fatalf("failed to access environment variable in output: %q expected: %q", result.Combined(), envValOveride)
  3865. }
  3866. containerName := "bldargCont"
  3867. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); !strings.Contains(out, envValOveride) {
  3868. c.Fatalf("run produced invalid output: %q, expected %q", out, envValOveride)
  3869. }
  3870. }
  3871. func (s *DockerSuite) TestBuildBuildTimeArgExpansion(c *check.C) {
  3872. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  3873. imgName := "bldvarstest"
  3874. wdVar := "WDIR"
  3875. wdVal := "/tmp/"
  3876. addVar := "AFILE"
  3877. addVal := "addFile"
  3878. copyVar := "CFILE"
  3879. copyVal := "copyFile"
  3880. envVar := "foo"
  3881. envVal := "bar"
  3882. exposeVar := "EPORT"
  3883. exposeVal := "9999"
  3884. userVar := "USER"
  3885. userVal := "testUser"
  3886. volVar := "VOL"
  3887. volVal := "/testVol/"
  3888. buildImageSuccessfully(c, imgName,
  3889. withBuildFlags(
  3890. "--build-arg", fmt.Sprintf("%s=%s", wdVar, wdVal),
  3891. "--build-arg", fmt.Sprintf("%s=%s", addVar, addVal),
  3892. "--build-arg", fmt.Sprintf("%s=%s", copyVar, copyVal),
  3893. "--build-arg", fmt.Sprintf("%s=%s", envVar, envVal),
  3894. "--build-arg", fmt.Sprintf("%s=%s", exposeVar, exposeVal),
  3895. "--build-arg", fmt.Sprintf("%s=%s", userVar, userVal),
  3896. "--build-arg", fmt.Sprintf("%s=%s", volVar, volVal),
  3897. ),
  3898. withBuildContext(c,
  3899. withFile("Dockerfile", fmt.Sprintf(`FROM busybox
  3900. ARG %s
  3901. WORKDIR ${%s}
  3902. ARG %s
  3903. ADD ${%s} testDir/
  3904. ARG %s
  3905. COPY $%s testDir/
  3906. ARG %s
  3907. ENV %s=${%s}
  3908. ARG %s
  3909. EXPOSE $%s
  3910. ARG %s
  3911. USER $%s
  3912. ARG %s
  3913. VOLUME ${%s}`,
  3914. wdVar, wdVar, addVar, addVar, copyVar, copyVar, envVar, envVar,
  3915. envVar, exposeVar, exposeVar, userVar, userVar, volVar, volVar)),
  3916. withFile(addVal, "some stuff"),
  3917. withFile(copyVal, "some stuff"),
  3918. ),
  3919. )
  3920. res := inspectField(c, imgName, "Config.WorkingDir")
  3921. if res != filepath.ToSlash(filepath.Clean(wdVal)) {
  3922. c.Fatalf("Config.WorkingDir value mismatch. Expected: %s, got: %s", filepath.ToSlash(filepath.Clean(wdVal)), res)
  3923. }
  3924. var resArr []string
  3925. inspectFieldAndUnmarshall(c, imgName, "Config.Env", &resArr)
  3926. found := false
  3927. for _, v := range resArr {
  3928. if fmt.Sprintf("%s=%s", envVar, envVal) == v {
  3929. found = true
  3930. break
  3931. }
  3932. }
  3933. if !found {
  3934. c.Fatalf("Config.Env value mismatch. Expected <key=value> to exist: %s=%s, got: %v",
  3935. envVar, envVal, resArr)
  3936. }
  3937. var resMap map[string]interface{}
  3938. inspectFieldAndUnmarshall(c, imgName, "Config.ExposedPorts", &resMap)
  3939. if _, ok := resMap[fmt.Sprintf("%s/tcp", exposeVal)]; !ok {
  3940. c.Fatalf("Config.ExposedPorts value mismatch. Expected exposed port: %s/tcp, got: %v", exposeVal, resMap)
  3941. }
  3942. res = inspectField(c, imgName, "Config.User")
  3943. if res != userVal {
  3944. c.Fatalf("Config.User value mismatch. Expected: %s, got: %s", userVal, res)
  3945. }
  3946. inspectFieldAndUnmarshall(c, imgName, "Config.Volumes", &resMap)
  3947. if _, ok := resMap[volVal]; !ok {
  3948. c.Fatalf("Config.Volumes value mismatch. Expected volume: %s, got: %v", volVal, resMap)
  3949. }
  3950. }
  3951. func (s *DockerSuite) TestBuildBuildTimeArgExpansionOverride(c *check.C) {
  3952. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  3953. imgName := "bldvarstest"
  3954. envKey := "foo"
  3955. envVal := "bar"
  3956. envKey1 := "foo1"
  3957. envValOveride := "barOverride"
  3958. dockerfile := fmt.Sprintf(`FROM busybox
  3959. ARG %s
  3960. ENV %s %s
  3961. ENV %s ${%s}
  3962. RUN echo $%s
  3963. CMD echo $%s`, envKey, envKey, envValOveride, envKey1, envKey, envKey1, envKey1)
  3964. result := buildImage(imgName,
  3965. withBuildFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3966. withDockerfile(dockerfile),
  3967. )
  3968. result.Assert(c, icmd.Success)
  3969. if strings.Count(result.Combined(), envValOveride) != 2 {
  3970. c.Fatalf("failed to access environment variable in output: %q expected: %q", result.Combined(), envValOveride)
  3971. }
  3972. containerName := "bldargCont"
  3973. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); !strings.Contains(out, envValOveride) {
  3974. c.Fatalf("run produced invalid output: %q, expected %q", out, envValOveride)
  3975. }
  3976. }
  3977. func (s *DockerSuite) TestBuildBuildTimeArgUntrustedDefinedAfterUse(c *check.C) {
  3978. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  3979. imgName := "bldargtest"
  3980. envKey := "foo"
  3981. envVal := "bar"
  3982. dockerfile := fmt.Sprintf(`FROM busybox
  3983. RUN echo $%s
  3984. ARG %s
  3985. CMD echo $%s`, envKey, envKey, envKey)
  3986. result := buildImage(imgName,
  3987. withBuildFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  3988. withDockerfile(dockerfile),
  3989. )
  3990. result.Assert(c, icmd.Success)
  3991. if strings.Contains(result.Combined(), envVal) {
  3992. c.Fatalf("able to access environment variable in output: %q expected to be missing", result.Combined())
  3993. }
  3994. containerName := "bldargCont"
  3995. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); out != "\n" {
  3996. c.Fatalf("run produced invalid output: %q, expected empty string", out)
  3997. }
  3998. }
  3999. func (s *DockerSuite) TestBuildBuildTimeArgBuiltinArg(c *check.C) {
  4000. testRequires(c, DaemonIsLinux) // Windows does not support --build-arg
  4001. imgName := "bldargtest"
  4002. envKey := "HTTP_PROXY"
  4003. envVal := "bar"
  4004. dockerfile := fmt.Sprintf(`FROM busybox
  4005. RUN echo $%s
  4006. CMD echo $%s`, envKey, envKey)
  4007. result := buildImage(imgName,
  4008. withBuildFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  4009. withDockerfile(dockerfile),
  4010. )
  4011. result.Assert(c, icmd.Success)
  4012. if !strings.Contains(result.Combined(), envVal) {
  4013. c.Fatalf("failed to access environment variable in output: %q expected: %q", result.Combined(), envVal)
  4014. }
  4015. containerName := "bldargCont"
  4016. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); out != "\n" {
  4017. c.Fatalf("run produced invalid output: %q, expected empty string", out)
  4018. }
  4019. }
  4020. func (s *DockerSuite) TestBuildBuildTimeArgDefaultOverride(c *check.C) {
  4021. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  4022. imgName := "bldargtest"
  4023. envKey := "foo"
  4024. envVal := "bar"
  4025. envValOveride := "barOverride"
  4026. dockerfile := fmt.Sprintf(`FROM busybox
  4027. ARG %s=%s
  4028. ENV %s $%s
  4029. RUN echo $%s
  4030. CMD echo $%s`, envKey, envVal, envKey, envKey, envKey, envKey)
  4031. result := buildImage(imgName,
  4032. withBuildFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envValOveride)),
  4033. withDockerfile(dockerfile),
  4034. )
  4035. result.Assert(c, icmd.Success)
  4036. if strings.Count(result.Combined(), envValOveride) != 1 {
  4037. c.Fatalf("failed to access environment variable in output: %q expected: %q", result.Combined(), envValOveride)
  4038. }
  4039. containerName := "bldargCont"
  4040. if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); !strings.Contains(out, envValOveride) {
  4041. c.Fatalf("run produced invalid output: %q, expected %q", out, envValOveride)
  4042. }
  4043. }
  4044. func (s *DockerSuite) TestBuildBuildTimeArgUnconsumedArg(c *check.C) {
  4045. imgName := "bldargtest"
  4046. envKey := "foo"
  4047. envVal := "bar"
  4048. dockerfile := fmt.Sprintf(`FROM busybox
  4049. RUN echo $%s
  4050. CMD echo $%s`, envKey, envKey)
  4051. warnStr := "[Warning] One or more build-args"
  4052. buildImage(imgName,
  4053. withBuildFlags("--build-arg", fmt.Sprintf("%s=%s", envKey, envVal)),
  4054. withDockerfile(dockerfile),
  4055. ).Assert(c, icmd.Expected{
  4056. Out: warnStr,
  4057. })
  4058. }
  4059. func (s *DockerSuite) TestBuildBuildTimeArgEnv(c *check.C) {
  4060. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  4061. dockerfile := `FROM busybox
  4062. ARG FOO1=fromfile
  4063. ARG FOO2=fromfile
  4064. ARG FOO3=fromfile
  4065. ARG FOO4=fromfile
  4066. ARG FOO5
  4067. ARG FOO6
  4068. RUN env
  4069. RUN [ "$FOO1" == "fromcmd" ]
  4070. RUN [ "$FOO2" == "" ]
  4071. RUN [ "$FOO3" == "fromenv" ]
  4072. RUN [ "$FOO4" == "fromfile" ]
  4073. RUN [ "$FOO5" == "fromcmd" ]
  4074. # The following should not exist at all in the env
  4075. RUN [ "$(env | grep FOO6)" == "" ]
  4076. RUN [ "$(env | grep FOO7)" == "" ]
  4077. RUN [ "$(env | grep FOO8)" == "" ]
  4078. RUN [ "$(env | grep FOO9)" == "" ]
  4079. `
  4080. result := buildImage("testbuildtimeargenv",
  4081. withBuildFlags(
  4082. "--build-arg", fmt.Sprintf("FOO1=fromcmd"),
  4083. "--build-arg", fmt.Sprintf("FOO2="),
  4084. "--build-arg", fmt.Sprintf("FOO3"), // set in env
  4085. "--build-arg", fmt.Sprintf("FOO4"), // not set in env
  4086. "--build-arg", fmt.Sprintf("FOO5=fromcmd"),
  4087. // FOO6 is not set at all
  4088. "--build-arg", fmt.Sprintf("FOO7=fromcmd"), // should produce a warning
  4089. "--build-arg", fmt.Sprintf("FOO8="), // should produce a warning
  4090. "--build-arg", fmt.Sprintf("FOO9"), // should produce a warning
  4091. ),
  4092. withEnvironmentVariales(append(os.Environ(),
  4093. "FOO1=fromenv",
  4094. "FOO2=fromenv",
  4095. "FOO3=fromenv")...),
  4096. withBuildContext(c,
  4097. withFile("Dockerfile", dockerfile),
  4098. ),
  4099. )
  4100. result.Assert(c, icmd.Success)
  4101. // Now check to make sure we got a warning msg about unused build-args
  4102. i := strings.Index(result.Combined(), "[Warning]")
  4103. if i < 0 {
  4104. c.Fatalf("Missing the build-arg warning in %q", result.Combined())
  4105. }
  4106. out := result.Combined()[i:] // "out" should contain just the warning message now
  4107. // These were specified on a --build-arg but no ARG was in the Dockerfile
  4108. c.Assert(out, checker.Contains, "FOO7")
  4109. c.Assert(out, checker.Contains, "FOO8")
  4110. c.Assert(out, checker.Contains, "FOO9")
  4111. }
  4112. func (s *DockerSuite) TestBuildBuildTimeArgQuotedValVariants(c *check.C) {
  4113. imgName := "bldargtest"
  4114. envKey := "foo"
  4115. envKey1 := "foo1"
  4116. envKey2 := "foo2"
  4117. envKey3 := "foo3"
  4118. dockerfile := fmt.Sprintf(`FROM busybox
  4119. ARG %s=""
  4120. ARG %s=''
  4121. ARG %s="''"
  4122. ARG %s='""'
  4123. RUN [ "$%s" != "$%s" ]
  4124. RUN [ "$%s" != "$%s" ]
  4125. RUN [ "$%s" != "$%s" ]
  4126. RUN [ "$%s" != "$%s" ]
  4127. RUN [ "$%s" != "$%s" ]`, envKey, envKey1, envKey2, envKey3,
  4128. envKey, envKey2, envKey, envKey3, envKey1, envKey2, envKey1, envKey3,
  4129. envKey2, envKey3)
  4130. buildImageSuccessfully(c, imgName, withDockerfile(dockerfile))
  4131. }
  4132. func (s *DockerSuite) TestBuildBuildTimeArgEmptyValVariants(c *check.C) {
  4133. testRequires(c, DaemonIsLinux) // Windows does not support ARG
  4134. imgName := "bldargtest"
  4135. envKey := "foo"
  4136. envKey1 := "foo1"
  4137. envKey2 := "foo2"
  4138. dockerfile := fmt.Sprintf(`FROM busybox
  4139. ARG %s=
  4140. ARG %s=""
  4141. ARG %s=''
  4142. RUN [ "$%s" == "$%s" ]
  4143. RUN [ "$%s" == "$%s" ]
  4144. RUN [ "$%s" == "$%s" ]`, envKey, envKey1, envKey2, envKey, envKey1, envKey1, envKey2, envKey, envKey2)
  4145. buildImageSuccessfully(c, imgName, withDockerfile(dockerfile))
  4146. }
  4147. func (s *DockerSuite) TestBuildBuildTimeArgDefintionWithNoEnvInjection(c *check.C) {
  4148. imgName := "bldargtest"
  4149. envKey := "foo"
  4150. dockerfile := fmt.Sprintf(`FROM busybox
  4151. ARG %s
  4152. RUN env`, envKey)
  4153. result := buildImage(imgName, withDockerfile(dockerfile))
  4154. result.Assert(c, icmd.Success)
  4155. if strings.Count(result.Combined(), envKey) != 1 {
  4156. c.Fatalf("unexpected number of occurrences of the arg in output: %q expected: 1", result.Combined())
  4157. }
  4158. }
  4159. func (s *DockerSuite) TestBuildNoNamedVolume(c *check.C) {
  4160. volName := "testname:/foo"
  4161. if testEnv.DaemonPlatform() == "windows" {
  4162. volName = "testname:C:\\foo"
  4163. }
  4164. dockerCmd(c, "run", "-v", volName, "busybox", "sh", "-c", "touch /foo/oops")
  4165. dockerFile := `FROM busybox
  4166. VOLUME ` + volName + `
  4167. RUN ls /foo/oops
  4168. `
  4169. buildImage("test", withDockerfile(dockerFile)).Assert(c, icmd.Expected{
  4170. ExitCode: 1,
  4171. })
  4172. }
  4173. func (s *DockerSuite) TestBuildTagEvent(c *check.C) {
  4174. since := daemonUnixTime(c)
  4175. dockerFile := `FROM busybox
  4176. RUN echo events
  4177. `
  4178. buildImageSuccessfully(c, "test", withDockerfile(dockerFile))
  4179. until := daemonUnixTime(c)
  4180. out, _ := dockerCmd(c, "events", "--since", since, "--until", until, "--filter", "type=image")
  4181. events := strings.Split(strings.TrimSpace(out), "\n")
  4182. actions := eventActionsByIDAndType(c, events, "test:latest", "image")
  4183. var foundTag bool
  4184. for _, a := range actions {
  4185. if a == "tag" {
  4186. foundTag = true
  4187. break
  4188. }
  4189. }
  4190. c.Assert(foundTag, checker.True, check.Commentf("No tag event found:\n%s", out))
  4191. }
  4192. // #15780
  4193. func (s *DockerSuite) TestBuildMultipleTags(c *check.C) {
  4194. dockerfile := `
  4195. FROM busybox
  4196. MAINTAINER test-15780
  4197. `
  4198. buildImageSuccessfully(c, "tag1", withBuildFlags("-t", "tag2:v2", "-t", "tag1:latest", "-t", "tag1"), withDockerfile(dockerfile))
  4199. id1 := getIDByName(c, "tag1")
  4200. id2 := getIDByName(c, "tag2:v2")
  4201. c.Assert(id1, check.Equals, id2)
  4202. }
  4203. // #17290
  4204. func (s *DockerSuite) TestBuildCacheBrokenSymlink(c *check.C) {
  4205. name := "testbuildbrokensymlink"
  4206. ctx := fakeContext(c, `
  4207. FROM busybox
  4208. COPY . ./`,
  4209. map[string]string{
  4210. "foo": "bar",
  4211. })
  4212. defer ctx.Close()
  4213. err := os.Symlink(filepath.Join(ctx.Dir, "nosuchfile"), filepath.Join(ctx.Dir, "asymlink"))
  4214. c.Assert(err, checker.IsNil)
  4215. // warm up cache
  4216. buildImageSuccessfully(c, name, withExternalBuildContext(ctx))
  4217. // add new file to context, should invalidate cache
  4218. err = ioutil.WriteFile(filepath.Join(ctx.Dir, "newfile"), []byte("foo"), 0644)
  4219. c.Assert(err, checker.IsNil)
  4220. result := buildImage(name, withExternalBuildContext(ctx))
  4221. result.Assert(c, icmd.Success)
  4222. if strings.Contains(result.Combined(), "Using cache") {
  4223. c.Fatal("2nd build used cache on ADD, it shouldn't")
  4224. }
  4225. }
  4226. func (s *DockerSuite) TestBuildFollowSymlinkToFile(c *check.C) {
  4227. name := "testbuildbrokensymlink"
  4228. ctx := fakeContext(c, `
  4229. FROM busybox
  4230. COPY asymlink target`,
  4231. map[string]string{
  4232. "foo": "bar",
  4233. })
  4234. defer ctx.Close()
  4235. err := os.Symlink("foo", filepath.Join(ctx.Dir, "asymlink"))
  4236. c.Assert(err, checker.IsNil)
  4237. buildImageSuccessfully(c, name, withExternalBuildContext(ctx))
  4238. out, _ := dockerCmd(c, "run", "--rm", name, "cat", "target")
  4239. c.Assert(out, checker.Matches, "bar")
  4240. // change target file should invalidate cache
  4241. err = ioutil.WriteFile(filepath.Join(ctx.Dir, "foo"), []byte("baz"), 0644)
  4242. c.Assert(err, checker.IsNil)
  4243. result := buildImage(name, withExternalBuildContext(ctx))
  4244. result.Assert(c, icmd.Success)
  4245. c.Assert(result.Combined(), checker.Not(checker.Contains), "Using cache")
  4246. out, _ = dockerCmd(c, "run", "--rm", name, "cat", "target")
  4247. c.Assert(out, checker.Matches, "baz")
  4248. }
  4249. func (s *DockerSuite) TestBuildFollowSymlinkToDir(c *check.C) {
  4250. name := "testbuildbrokensymlink"
  4251. ctx := fakeContext(c, `
  4252. FROM busybox
  4253. COPY asymlink /`,
  4254. map[string]string{
  4255. "foo/abc": "bar",
  4256. "foo/def": "baz",
  4257. })
  4258. defer ctx.Close()
  4259. err := os.Symlink("foo", filepath.Join(ctx.Dir, "asymlink"))
  4260. c.Assert(err, checker.IsNil)
  4261. buildImageSuccessfully(c, name, withExternalBuildContext(ctx))
  4262. out, _ := dockerCmd(c, "run", "--rm", name, "cat", "abc", "def")
  4263. c.Assert(out, checker.Matches, "barbaz")
  4264. // change target file should invalidate cache
  4265. err = ioutil.WriteFile(filepath.Join(ctx.Dir, "foo/def"), []byte("bax"), 0644)
  4266. c.Assert(err, checker.IsNil)
  4267. result := buildImage(name, withExternalBuildContext(ctx))
  4268. result.Assert(c, icmd.Success)
  4269. c.Assert(result.Combined(), checker.Not(checker.Contains), "Using cache")
  4270. out, _ = dockerCmd(c, "run", "--rm", name, "cat", "abc", "def")
  4271. c.Assert(out, checker.Matches, "barbax")
  4272. }
  4273. // TestBuildSymlinkBasename tests that target file gets basename from symlink,
  4274. // not from the target file.
  4275. func (s *DockerSuite) TestBuildSymlinkBasename(c *check.C) {
  4276. name := "testbuildbrokensymlink"
  4277. ctx := fakeContext(c, `
  4278. FROM busybox
  4279. COPY asymlink /`,
  4280. map[string]string{
  4281. "foo": "bar",
  4282. })
  4283. defer ctx.Close()
  4284. err := os.Symlink("foo", filepath.Join(ctx.Dir, "asymlink"))
  4285. c.Assert(err, checker.IsNil)
  4286. buildImageSuccessfully(c, name, withExternalBuildContext(ctx))
  4287. out, _ := dockerCmd(c, "run", "--rm", name, "cat", "asymlink")
  4288. c.Assert(out, checker.Matches, "bar")
  4289. }
  4290. // #17827
  4291. func (s *DockerSuite) TestBuildCacheRootSource(c *check.C) {
  4292. name := "testbuildrootsource"
  4293. ctx := fakeContext(c, `
  4294. FROM busybox
  4295. COPY / /data`,
  4296. map[string]string{
  4297. "foo": "bar",
  4298. })
  4299. defer ctx.Close()
  4300. // warm up cache
  4301. buildImageSuccessfully(c, name, withExternalBuildContext(ctx))
  4302. // change file, should invalidate cache
  4303. err := ioutil.WriteFile(filepath.Join(ctx.Dir, "foo"), []byte("baz"), 0644)
  4304. c.Assert(err, checker.IsNil)
  4305. result := buildImage(name, withExternalBuildContext(ctx))
  4306. result.Assert(c, icmd.Success)
  4307. c.Assert(result.Combined(), checker.Not(checker.Contains), "Using cache")
  4308. }
  4309. // #19375
  4310. func (s *DockerSuite) TestBuildFailsGitNotCallable(c *check.C) {
  4311. buildImage("gitnotcallable", withEnvironmentVariales("PATH="),
  4312. withBuildContextPath("github.com/docker/v1.10-migrator.git")).Assert(c, icmd.Expected{
  4313. ExitCode: 1,
  4314. Err: "unable to prepare context: unable to find 'git': ",
  4315. })
  4316. buildImage("gitnotcallable", withEnvironmentVariales("PATH="),
  4317. withBuildContextPath("https://github.com/docker/v1.10-migrator.git")).Assert(c, icmd.Expected{
  4318. ExitCode: 1,
  4319. Err: "unable to prepare context: unable to find 'git': ",
  4320. })
  4321. }
  4322. // TestBuildWorkdirWindowsPath tests that a Windows style path works as a workdir
  4323. func (s *DockerSuite) TestBuildWorkdirWindowsPath(c *check.C) {
  4324. testRequires(c, DaemonIsWindows)
  4325. name := "testbuildworkdirwindowspath"
  4326. buildImageSuccessfully(c, name, withDockerfile(`
  4327. FROM `+testEnv.MinimalBaseImage()+`
  4328. RUN mkdir C:\\work
  4329. WORKDIR C:\\work
  4330. RUN if "%CD%" NEQ "C:\work" exit -1
  4331. `))
  4332. }
  4333. func (s *DockerSuite) TestBuildLabel(c *check.C) {
  4334. name := "testbuildlabel"
  4335. testLabel := "foo"
  4336. buildImageSuccessfully(c, name, withBuildFlags("--label", testLabel),
  4337. withDockerfile(`
  4338. FROM `+minimalBaseImage()+`
  4339. LABEL default foo
  4340. `))
  4341. var labels map[string]string
  4342. inspectFieldAndUnmarshall(c, name, "Config.Labels", &labels)
  4343. if _, ok := labels[testLabel]; !ok {
  4344. c.Fatal("label not found in image")
  4345. }
  4346. }
  4347. func (s *DockerSuite) TestBuildLabelOneNode(c *check.C) {
  4348. name := "testbuildlabel"
  4349. buildImageSuccessfully(c, name, withBuildFlags("--label", "foo=bar"),
  4350. withDockerfile("FROM busybox"))
  4351. var labels map[string]string
  4352. inspectFieldAndUnmarshall(c, name, "Config.Labels", &labels)
  4353. v, ok := labels["foo"]
  4354. if !ok {
  4355. c.Fatal("label `foo` not found in image")
  4356. }
  4357. c.Assert(v, checker.Equals, "bar")
  4358. }
  4359. func (s *DockerSuite) TestBuildLabelCacheCommit(c *check.C) {
  4360. name := "testbuildlabelcachecommit"
  4361. testLabel := "foo"
  4362. buildImageSuccessfully(c, name, withDockerfile(`
  4363. FROM `+minimalBaseImage()+`
  4364. LABEL default foo
  4365. `))
  4366. buildImageSuccessfully(c, name, withBuildFlags("--label", testLabel),
  4367. withDockerfile(`
  4368. FROM `+minimalBaseImage()+`
  4369. LABEL default foo
  4370. `))
  4371. var labels map[string]string
  4372. inspectFieldAndUnmarshall(c, name, "Config.Labels", &labels)
  4373. if _, ok := labels[testLabel]; !ok {
  4374. c.Fatal("label not found in image")
  4375. }
  4376. }
  4377. func (s *DockerSuite) TestBuildLabelMultiple(c *check.C) {
  4378. name := "testbuildlabelmultiple"
  4379. testLabels := map[string]string{
  4380. "foo": "bar",
  4381. "123": "456",
  4382. }
  4383. labelArgs := []string{}
  4384. for k, v := range testLabels {
  4385. labelArgs = append(labelArgs, "--label", k+"="+v)
  4386. }
  4387. buildImageSuccessfully(c, name, withBuildFlags(labelArgs...),
  4388. withDockerfile(`
  4389. FROM `+minimalBaseImage()+`
  4390. LABEL default foo
  4391. `))
  4392. var labels map[string]string
  4393. inspectFieldAndUnmarshall(c, name, "Config.Labels", &labels)
  4394. for k, v := range testLabels {
  4395. if x, ok := labels[k]; !ok || x != v {
  4396. c.Fatalf("label %s=%s not found in image", k, v)
  4397. }
  4398. }
  4399. }
  4400. func (s *DockerRegistryAuthHtpasswdSuite) TestBuildFromAuthenticatedRegistry(c *check.C) {
  4401. dockerCmd(c, "login", "-u", s.reg.Username(), "-p", s.reg.Password(), privateRegistryURL)
  4402. baseImage := privateRegistryURL + "/baseimage"
  4403. buildImageSuccessfully(c, baseImage, withDockerfile(`
  4404. FROM busybox
  4405. ENV env1 val1
  4406. `))
  4407. dockerCmd(c, "push", baseImage)
  4408. dockerCmd(c, "rmi", baseImage)
  4409. buildImageSuccessfully(c, baseImage, withDockerfile(fmt.Sprintf(`
  4410. FROM %s
  4411. ENV env2 val2
  4412. `, baseImage)))
  4413. }
  4414. func (s *DockerRegistryAuthHtpasswdSuite) TestBuildWithExternalAuth(c *check.C) {
  4415. osPath := os.Getenv("PATH")
  4416. defer os.Setenv("PATH", osPath)
  4417. workingDir, err := os.Getwd()
  4418. c.Assert(err, checker.IsNil)
  4419. absolute, err := filepath.Abs(filepath.Join(workingDir, "fixtures", "auth"))
  4420. c.Assert(err, checker.IsNil)
  4421. testPath := fmt.Sprintf("%s%c%s", osPath, filepath.ListSeparator, absolute)
  4422. os.Setenv("PATH", testPath)
  4423. repoName := fmt.Sprintf("%v/dockercli/busybox:authtest", privateRegistryURL)
  4424. tmp, err := ioutil.TempDir("", "integration-cli-")
  4425. c.Assert(err, checker.IsNil)
  4426. externalAuthConfig := `{ "credsStore": "shell-test" }`
  4427. configPath := filepath.Join(tmp, "config.json")
  4428. err = ioutil.WriteFile(configPath, []byte(externalAuthConfig), 0644)
  4429. c.Assert(err, checker.IsNil)
  4430. dockerCmd(c, "--config", tmp, "login", "-u", s.reg.Username(), "-p", s.reg.Password(), privateRegistryURL)
  4431. b, err := ioutil.ReadFile(configPath)
  4432. c.Assert(err, checker.IsNil)
  4433. c.Assert(string(b), checker.Not(checker.Contains), "\"auth\":")
  4434. dockerCmd(c, "--config", tmp, "tag", "busybox", repoName)
  4435. dockerCmd(c, "--config", tmp, "push", repoName)
  4436. // make sure the image is pulled when building
  4437. dockerCmd(c, "rmi", repoName)
  4438. icmd.RunCmd(icmd.Cmd{
  4439. Command: []string{dockerBinary, "--config", tmp, "build", "-"},
  4440. Stdin: strings.NewReader(fmt.Sprintf("FROM %s", repoName)),
  4441. }).Assert(c, icmd.Success)
  4442. }
  4443. // Test cases in #22036
  4444. func (s *DockerSuite) TestBuildLabelsOverride(c *check.C) {
  4445. // Command line option labels will always override
  4446. name := "scratchy"
  4447. expected := `{"bar":"from-flag","foo":"from-flag"}`
  4448. buildImageSuccessfully(c, name, withBuildFlags("--label", "foo=from-flag", "--label", "bar=from-flag"),
  4449. withDockerfile(`FROM `+minimalBaseImage()+`
  4450. LABEL foo=from-dockerfile`))
  4451. res := inspectFieldJSON(c, name, "Config.Labels")
  4452. if res != expected {
  4453. c.Fatalf("Labels %s, expected %s", res, expected)
  4454. }
  4455. name = "from"
  4456. expected = `{"foo":"from-dockerfile"}`
  4457. buildImageSuccessfully(c, name, withDockerfile(`FROM `+minimalBaseImage()+`
  4458. LABEL foo from-dockerfile`))
  4459. res = inspectFieldJSON(c, name, "Config.Labels")
  4460. if res != expected {
  4461. c.Fatalf("Labels %s, expected %s", res, expected)
  4462. }
  4463. // Command line option label will override even via `FROM`
  4464. name = "new"
  4465. expected = `{"bar":"from-dockerfile2","foo":"new"}`
  4466. buildImageSuccessfully(c, name, withBuildFlags("--label", "foo=new"),
  4467. withDockerfile(`FROM from
  4468. LABEL bar from-dockerfile2`))
  4469. res = inspectFieldJSON(c, name, "Config.Labels")
  4470. if res != expected {
  4471. c.Fatalf("Labels %s, expected %s", res, expected)
  4472. }
  4473. // Command line option without a value set (--label foo, --label bar=)
  4474. // will be treated as --label foo="", --label bar=""
  4475. name = "scratchy2"
  4476. expected = `{"bar":"","foo":""}`
  4477. buildImageSuccessfully(c, name, withBuildFlags("--label", "foo", "--label", "bar="),
  4478. withDockerfile(`FROM `+minimalBaseImage()+`
  4479. LABEL foo=from-dockerfile`))
  4480. res = inspectFieldJSON(c, name, "Config.Labels")
  4481. if res != expected {
  4482. c.Fatalf("Labels %s, expected %s", res, expected)
  4483. }
  4484. // Command line option without a value set (--label foo, --label bar=)
  4485. // will be treated as --label foo="", --label bar=""
  4486. // This time is for inherited images
  4487. name = "new2"
  4488. expected = `{"bar":"","foo":""}`
  4489. buildImageSuccessfully(c, name, withBuildFlags("--label", "foo=", "--label", "bar"),
  4490. withDockerfile(`FROM from
  4491. LABEL bar from-dockerfile2`))
  4492. res = inspectFieldJSON(c, name, "Config.Labels")
  4493. if res != expected {
  4494. c.Fatalf("Labels %s, expected %s", res, expected)
  4495. }
  4496. // Command line option labels with only `FROM`
  4497. name = "scratchy"
  4498. expected = `{"bar":"from-flag","foo":"from-flag"}`
  4499. buildImageSuccessfully(c, name, withBuildFlags("--label", "foo=from-flag", "--label", "bar=from-flag"),
  4500. withDockerfile(`FROM `+minimalBaseImage()))
  4501. res = inspectFieldJSON(c, name, "Config.Labels")
  4502. if res != expected {
  4503. c.Fatalf("Labels %s, expected %s", res, expected)
  4504. }
  4505. // Command line option labels with env var
  4506. name = "scratchz"
  4507. expected = `{"bar":"$PATH"}`
  4508. buildImageSuccessfully(c, name, withBuildFlags("--label", "bar=$PATH"),
  4509. withDockerfile(`FROM `+minimalBaseImage()))
  4510. res = inspectFieldJSON(c, name, "Config.Labels")
  4511. if res != expected {
  4512. c.Fatalf("Labels %s, expected %s", res, expected)
  4513. }
  4514. }
  4515. // Test case for #22855
  4516. func (s *DockerSuite) TestBuildDeleteCommittedFile(c *check.C) {
  4517. name := "test-delete-committed-file"
  4518. buildImageSuccessfully(c, name, withDockerfile(`FROM busybox
  4519. RUN echo test > file
  4520. RUN test -e file
  4521. RUN rm file
  4522. RUN sh -c "! test -e file"`))
  4523. }
  4524. // #20083
  4525. func (s *DockerSuite) TestBuildDockerignoreComment(c *check.C) {
  4526. // TODO Windows: Figure out why this test is flakey on TP5. If you add
  4527. // something like RUN sleep 5, or even RUN ls /tmp after the ADD line,
  4528. // it is more reliable, but that's not a good fix.
  4529. testRequires(c, DaemonIsLinux)
  4530. name := "testbuilddockerignorecleanpaths"
  4531. dockerfile := `
  4532. FROM busybox
  4533. ADD . /tmp/
  4534. RUN sh -c "(ls -la /tmp/#1)"
  4535. RUN sh -c "(! ls -la /tmp/#2)"
  4536. RUN sh -c "(! ls /tmp/foo) && (! ls /tmp/foo2) && (ls /tmp/dir1/foo)"`
  4537. buildImageSuccessfully(c, name, withBuildContext(c,
  4538. withFile("Dockerfile", dockerfile),
  4539. withFile("foo", "foo"),
  4540. withFile("foo2", "foo2"),
  4541. withFile("dir1/foo", "foo in dir1"),
  4542. withFile("#1", "# file 1"),
  4543. withFile("#2", "# file 2"),
  4544. withFile(".dockerignore", `# Visual C++ cache files
  4545. # because we have git ;-)
  4546. # The above comment is from #20083
  4547. foo
  4548. #dir1/foo
  4549. foo2
  4550. # The following is considered as comment as # is at the beginning
  4551. #1
  4552. # The following is not considered as comment as # is not at the beginning
  4553. #2
  4554. `)))
  4555. }
  4556. // Test case for #23221
  4557. func (s *DockerSuite) TestBuildWithUTF8BOM(c *check.C) {
  4558. name := "test-with-utf8-bom"
  4559. dockerfile := []byte(`FROM busybox`)
  4560. bomDockerfile := append([]byte{0xEF, 0xBB, 0xBF}, dockerfile...)
  4561. buildImageSuccessfully(c, name, withBuildContext(c,
  4562. withFile("Dockerfile", string(bomDockerfile)),
  4563. ))
  4564. }
  4565. // Test case for UTF-8 BOM in .dockerignore, related to #23221
  4566. func (s *DockerSuite) TestBuildWithUTF8BOMDockerignore(c *check.C) {
  4567. name := "test-with-utf8-bom-dockerignore"
  4568. dockerfile := `
  4569. FROM busybox
  4570. ADD . /tmp/
  4571. RUN ls -la /tmp
  4572. RUN sh -c "! ls /tmp/Dockerfile"
  4573. RUN ls /tmp/.dockerignore`
  4574. dockerignore := []byte("./Dockerfile\n")
  4575. bomDockerignore := append([]byte{0xEF, 0xBB, 0xBF}, dockerignore...)
  4576. buildImageSuccessfully(c, name, withBuildContext(c,
  4577. withFile("Dockerfile", dockerfile),
  4578. withFile(".dockerignore", string(bomDockerignore)),
  4579. ))
  4580. }
  4581. // #22489 Shell test to confirm config gets updated correctly
  4582. func (s *DockerSuite) TestBuildShellUpdatesConfig(c *check.C) {
  4583. name := "testbuildshellupdatesconfig"
  4584. buildImageSuccessfully(c, name, withDockerfile(`FROM `+minimalBaseImage()+`
  4585. SHELL ["foo", "-bar"]`))
  4586. expected := `["foo","-bar","#(nop) ","SHELL [foo -bar]"]`
  4587. res := inspectFieldJSON(c, name, "ContainerConfig.Cmd")
  4588. if res != expected {
  4589. c.Fatalf("%s, expected %s", res, expected)
  4590. }
  4591. res = inspectFieldJSON(c, name, "ContainerConfig.Shell")
  4592. if res != `["foo","-bar"]` {
  4593. c.Fatalf(`%s, expected ["foo","-bar"]`, res)
  4594. }
  4595. }
  4596. // #22489 Changing the shell multiple times and CMD after.
  4597. func (s *DockerSuite) TestBuildShellMultiple(c *check.C) {
  4598. name := "testbuildshellmultiple"
  4599. result := buildImage(name, withDockerfile(`FROM busybox
  4600. RUN echo defaultshell
  4601. SHELL ["echo"]
  4602. RUN echoshell
  4603. SHELL ["ls"]
  4604. RUN -l
  4605. CMD -l`))
  4606. result.Assert(c, icmd.Success)
  4607. // Must contain 'defaultshell' twice
  4608. if len(strings.Split(result.Combined(), "defaultshell")) != 3 {
  4609. c.Fatalf("defaultshell should have appeared twice in %s", result.Combined())
  4610. }
  4611. // Must contain 'echoshell' twice
  4612. if len(strings.Split(result.Combined(), "echoshell")) != 3 {
  4613. c.Fatalf("echoshell should have appeared twice in %s", result.Combined())
  4614. }
  4615. // Must contain "total " (part of ls -l)
  4616. if !strings.Contains(result.Combined(), "total ") {
  4617. c.Fatalf("%s should have contained 'total '", result.Combined())
  4618. }
  4619. // A container started from the image uses the shell-form CMD.
  4620. // Last shell is ls. CMD is -l. So should contain 'total '.
  4621. outrun, _ := dockerCmd(c, "run", "--rm", name)
  4622. if !strings.Contains(outrun, "total ") {
  4623. c.Fatalf("Expected started container to run ls -l. %s", outrun)
  4624. }
  4625. }
  4626. // #22489. Changed SHELL with ENTRYPOINT
  4627. func (s *DockerSuite) TestBuildShellEntrypoint(c *check.C) {
  4628. name := "testbuildshellentrypoint"
  4629. buildImageSuccessfully(c, name, withDockerfile(`FROM busybox
  4630. SHELL ["ls"]
  4631. ENTRYPOINT -l`))
  4632. // A container started from the image uses the shell-form ENTRYPOINT.
  4633. // Shell is ls. ENTRYPOINT is -l. So should contain 'total '.
  4634. outrun, _ := dockerCmd(c, "run", "--rm", name)
  4635. if !strings.Contains(outrun, "total ") {
  4636. c.Fatalf("Expected started container to run ls -l. %s", outrun)
  4637. }
  4638. }
  4639. // #22489 Shell test to confirm shell is inherited in a subsequent build
  4640. func (s *DockerSuite) TestBuildShellInherited(c *check.C) {
  4641. name1 := "testbuildshellinherited1"
  4642. buildImageSuccessfully(c, name1, withDockerfile(`FROM busybox
  4643. SHELL ["ls"]`))
  4644. name2 := "testbuildshellinherited2"
  4645. buildImage(name2, withDockerfile(`FROM `+name1+`
  4646. RUN -l`)).Assert(c, icmd.Expected{
  4647. // ls -l has "total " followed by some number in it, ls without -l does not.
  4648. Out: "total ",
  4649. })
  4650. }
  4651. // #22489 Shell test to confirm non-JSON doesn't work
  4652. func (s *DockerSuite) TestBuildShellNotJSON(c *check.C) {
  4653. name := "testbuildshellnotjson"
  4654. buildImage(name, withDockerfile(`FROM `+minimalBaseImage()+`
  4655. sHeLl exec -form`, // Casing explicit to ensure error is upper-cased.
  4656. )).Assert(c, icmd.Expected{
  4657. ExitCode: 1,
  4658. Err: "SHELL requires the arguments to be in JSON form",
  4659. })
  4660. }
  4661. // #22489 Windows shell test to confirm native is powershell if executing a PS command
  4662. // This would error if the default shell were still cmd.
  4663. func (s *DockerSuite) TestBuildShellWindowsPowershell(c *check.C) {
  4664. testRequires(c, DaemonIsWindows)
  4665. name := "testbuildshellpowershell"
  4666. buildImage(name, withDockerfile(`FROM `+minimalBaseImage()+`
  4667. SHELL ["powershell", "-command"]
  4668. RUN Write-Host John`)).Assert(c, icmd.Expected{
  4669. Out: "\nJohn\n",
  4670. })
  4671. }
  4672. // Verify that escape is being correctly applied to words when escape directive is not \.
  4673. // Tests WORKDIR, ADD
  4674. func (s *DockerSuite) TestBuildEscapeNotBackslashWordTest(c *check.C) {
  4675. testRequires(c, DaemonIsWindows)
  4676. name := "testbuildescapenotbackslashwordtesta"
  4677. buildImage(name, withDockerfile(`# escape= `+"`"+`
  4678. FROM `+minimalBaseImage()+`
  4679. WORKDIR c:\windows
  4680. RUN dir /w`)).Assert(c, icmd.Expected{
  4681. Out: "[System32]",
  4682. })
  4683. name = "testbuildescapenotbackslashwordtestb"
  4684. buildImage(name, withDockerfile(`# escape= `+"`"+`
  4685. FROM `+minimalBaseImage()+`
  4686. SHELL ["powershell.exe"]
  4687. WORKDIR c:\foo
  4688. ADD Dockerfile c:\foo\
  4689. RUN dir Dockerfile`)).Assert(c, icmd.Expected{
  4690. Out: "-a----",
  4691. })
  4692. }
  4693. // #22868. Make sure shell-form CMD is marked as escaped in the config of the image
  4694. func (s *DockerSuite) TestBuildCmdShellArgsEscaped(c *check.C) {
  4695. testRequires(c, DaemonIsWindows)
  4696. name := "testbuildcmdshellescaped"
  4697. buildImageSuccessfully(c, name, withDockerfile(`
  4698. FROM `+minimalBaseImage()+`
  4699. CMD "ipconfig"
  4700. `))
  4701. res := inspectFieldJSON(c, name, "Config.ArgsEscaped")
  4702. if res != "true" {
  4703. c.Fatalf("CMD did not update Config.ArgsEscaped on image: %v", res)
  4704. }
  4705. dockerCmd(c, "run", "--name", "inspectme", name)
  4706. dockerCmd(c, "wait", "inspectme")
  4707. res = inspectFieldJSON(c, name, "Config.Cmd")
  4708. if res != `["cmd","/S","/C","\"ipconfig\""]` {
  4709. c.Fatalf("CMD was not escaped Config.Cmd: got %v", res)
  4710. }
  4711. }
  4712. // Test case for #24912.
  4713. func (s *DockerSuite) TestBuildStepsWithProgress(c *check.C) {
  4714. name := "testbuildstepswithprogress"
  4715. totalRun := 5
  4716. result := buildImage(name, withDockerfile("FROM busybox\n"+strings.Repeat("RUN echo foo\n", totalRun)))
  4717. result.Assert(c, icmd.Success)
  4718. c.Assert(result.Combined(), checker.Contains, fmt.Sprintf("Step 1/%d : FROM busybox", 1+totalRun))
  4719. for i := 2; i <= 1+totalRun; i++ {
  4720. c.Assert(result.Combined(), checker.Contains, fmt.Sprintf("Step %d/%d : RUN echo foo", i, 1+totalRun))
  4721. }
  4722. }
  4723. func (s *DockerSuite) TestBuildWithFailure(c *check.C) {
  4724. name := "testbuildwithfailure"
  4725. // First test case can only detect `nobody` in runtime so all steps will show up
  4726. dockerfile := "FROM busybox\nRUN nobody"
  4727. result := buildImage(name, withDockerfile(dockerfile))
  4728. c.Assert(result.Error, checker.NotNil)
  4729. c.Assert(result.Stdout(), checker.Contains, "Step 1/2 : FROM busybox")
  4730. c.Assert(result.Stdout(), checker.Contains, "Step 2/2 : RUN nobody")
  4731. // Second test case `FFOM` should have been detected before build runs so no steps
  4732. dockerfile = "FFOM nobody\nRUN nobody"
  4733. result = buildImage(name, withDockerfile(dockerfile))
  4734. c.Assert(result.Error, checker.NotNil)
  4735. c.Assert(result.Stdout(), checker.Not(checker.Contains), "Step 1/2 : FROM busybox")
  4736. c.Assert(result.Stdout(), checker.Not(checker.Contains), "Step 2/2 : RUN nobody")
  4737. }
  4738. func (s *DockerSuite) TestBuildCacheFrom(c *check.C) {
  4739. testRequires(c, DaemonIsLinux) // All tests that do save are skipped in windows
  4740. dockerfile := `
  4741. FROM busybox
  4742. ENV FOO=bar
  4743. ADD baz /
  4744. RUN touch bax`
  4745. ctx := fakeContext(c, dockerfile, map[string]string{
  4746. "Dockerfile": dockerfile,
  4747. "baz": "baz",
  4748. })
  4749. defer ctx.Close()
  4750. buildImageSuccessfully(c, "build1", withExternalBuildContext(ctx))
  4751. id1 := getIDByName(c, "build1")
  4752. // rebuild with cache-from
  4753. result := buildImage("build2", withBuildFlags("--cache-from=build1"), withExternalBuildContext(ctx))
  4754. result.Assert(c, icmd.Success)
  4755. id2 := getIDByName(c, "build2")
  4756. c.Assert(id1, checker.Equals, id2)
  4757. c.Assert(strings.Count(result.Combined(), "Using cache"), checker.Equals, 3)
  4758. dockerCmd(c, "rmi", "build2")
  4759. // no cache match with unknown source
  4760. result = buildImage("build2", withBuildFlags("--cache-from=nosuchtag"), withExternalBuildContext(ctx))
  4761. result.Assert(c, icmd.Success)
  4762. id2 = getIDByName(c, "build2")
  4763. c.Assert(id1, checker.Not(checker.Equals), id2)
  4764. c.Assert(strings.Count(result.Combined(), "Using cache"), checker.Equals, 0)
  4765. dockerCmd(c, "rmi", "build2")
  4766. // clear parent images
  4767. tempDir, err := ioutil.TempDir("", "test-build-cache-from-")
  4768. if err != nil {
  4769. c.Fatalf("failed to create temporary directory: %s", tempDir)
  4770. }
  4771. defer os.RemoveAll(tempDir)
  4772. tempFile := filepath.Join(tempDir, "img.tar")
  4773. dockerCmd(c, "save", "-o", tempFile, "build1")
  4774. dockerCmd(c, "rmi", "build1")
  4775. dockerCmd(c, "load", "-i", tempFile)
  4776. parentID, _ := dockerCmd(c, "inspect", "-f", "{{.Parent}}", "build1")
  4777. c.Assert(strings.TrimSpace(parentID), checker.Equals, "")
  4778. // cache still applies without parents
  4779. result = buildImage("build2", withBuildFlags("--cache-from=build1"), withExternalBuildContext(ctx))
  4780. result.Assert(c, icmd.Success)
  4781. id2 = getIDByName(c, "build2")
  4782. c.Assert(id1, checker.Equals, id2)
  4783. c.Assert(strings.Count(result.Combined(), "Using cache"), checker.Equals, 3)
  4784. history1, _ := dockerCmd(c, "history", "-q", "build2")
  4785. // Retry, no new intermediate images
  4786. result = buildImage("build3", withBuildFlags("--cache-from=build1"), withExternalBuildContext(ctx))
  4787. result.Assert(c, icmd.Success)
  4788. id3 := getIDByName(c, "build3")
  4789. c.Assert(id1, checker.Equals, id3)
  4790. c.Assert(strings.Count(result.Combined(), "Using cache"), checker.Equals, 3)
  4791. history2, _ := dockerCmd(c, "history", "-q", "build3")
  4792. c.Assert(history1, checker.Equals, history2)
  4793. dockerCmd(c, "rmi", "build2")
  4794. dockerCmd(c, "rmi", "build3")
  4795. dockerCmd(c, "rmi", "build1")
  4796. dockerCmd(c, "load", "-i", tempFile)
  4797. // Modify file, everything up to last command and layers are reused
  4798. dockerfile = `
  4799. FROM busybox
  4800. ENV FOO=bar
  4801. ADD baz /
  4802. RUN touch newfile`
  4803. err = ioutil.WriteFile(filepath.Join(ctx.Dir, "Dockerfile"), []byte(dockerfile), 0644)
  4804. c.Assert(err, checker.IsNil)
  4805. result = buildImage("build2", withBuildFlags("--cache-from=build1"), withExternalBuildContext(ctx))
  4806. result.Assert(c, icmd.Success)
  4807. id2 = getIDByName(c, "build2")
  4808. c.Assert(id1, checker.Not(checker.Equals), id2)
  4809. c.Assert(strings.Count(result.Combined(), "Using cache"), checker.Equals, 2)
  4810. layers1Str, _ := dockerCmd(c, "inspect", "-f", "{{json .RootFS.Layers}}", "build1")
  4811. layers2Str, _ := dockerCmd(c, "inspect", "-f", "{{json .RootFS.Layers}}", "build2")
  4812. var layers1 []string
  4813. var layers2 []string
  4814. c.Assert(json.Unmarshal([]byte(layers1Str), &layers1), checker.IsNil)
  4815. c.Assert(json.Unmarshal([]byte(layers2Str), &layers2), checker.IsNil)
  4816. c.Assert(len(layers1), checker.Equals, len(layers2))
  4817. for i := 0; i < len(layers1)-1; i++ {
  4818. c.Assert(layers1[i], checker.Equals, layers2[i])
  4819. }
  4820. c.Assert(layers1[len(layers1)-1], checker.Not(checker.Equals), layers2[len(layers1)-1])
  4821. }
  4822. func (s *DockerSuite) TestBuildNetNone(c *check.C) {
  4823. testRequires(c, DaemonIsLinux)
  4824. name := "testbuildnetnone"
  4825. buildImage(name, withBuildFlags("--network=none"), withDockerfile(`
  4826. FROM busybox
  4827. RUN ping -c 1 8.8.8.8
  4828. `)).Assert(c, icmd.Expected{
  4829. ExitCode: 1,
  4830. Out: "unreachable",
  4831. })
  4832. }
  4833. func (s *DockerSuite) TestBuildNetContainer(c *check.C) {
  4834. testRequires(c, DaemonIsLinux)
  4835. id, _ := dockerCmd(c, "run", "--hostname", "foobar", "-d", "busybox", "nc", "-ll", "-p", "1234", "-e", "hostname")
  4836. name := "testbuildnetcontainer"
  4837. buildImageSuccessfully(c, name, withBuildFlags("--network=container:"+strings.TrimSpace(id)),
  4838. withDockerfile(`
  4839. FROM busybox
  4840. RUN nc localhost 1234 > /otherhost
  4841. `))
  4842. host, _ := dockerCmd(c, "run", "testbuildnetcontainer", "cat", "/otherhost")
  4843. c.Assert(strings.TrimSpace(host), check.Equals, "foobar")
  4844. }
  4845. func (s *DockerSuite) TestBuildSquashParent(c *check.C) {
  4846. testRequires(c, ExperimentalDaemon)
  4847. dockerFile := `
  4848. FROM busybox
  4849. RUN echo hello > /hello
  4850. RUN echo world >> /hello
  4851. RUN echo hello > /remove_me
  4852. ENV HELLO world
  4853. RUN rm /remove_me
  4854. `
  4855. // build and get the ID that we can use later for history comparison
  4856. name := "test"
  4857. buildImageSuccessfully(c, name, withDockerfile(dockerFile))
  4858. origID := getIDByName(c, name)
  4859. // build with squash
  4860. buildImageSuccessfully(c, name, withBuildFlags("--squash"), withDockerfile(dockerFile))
  4861. id := getIDByName(c, name)
  4862. out, _ := dockerCmd(c, "run", "--rm", id, "/bin/sh", "-c", "cat /hello")
  4863. c.Assert(strings.TrimSpace(out), checker.Equals, "hello\nworld")
  4864. dockerCmd(c, "run", "--rm", id, "/bin/sh", "-c", "[ ! -f /remove_me ]")
  4865. dockerCmd(c, "run", "--rm", id, "/bin/sh", "-c", `[ "$(echo $HELLO)" == "world" ]`)
  4866. // make sure the ID produced is the ID of the tag we specified
  4867. inspectID, err := inspectImage("test", ".ID")
  4868. c.Assert(err, checker.IsNil)
  4869. c.Assert(inspectID, checker.Equals, id)
  4870. origHistory, _ := dockerCmd(c, "history", origID)
  4871. testHistory, _ := dockerCmd(c, "history", "test")
  4872. splitOrigHistory := strings.Split(strings.TrimSpace(origHistory), "\n")
  4873. splitTestHistory := strings.Split(strings.TrimSpace(testHistory), "\n")
  4874. c.Assert(len(splitTestHistory), checker.Equals, len(splitOrigHistory)+1)
  4875. out, err = inspectImage(id, "len .RootFS.Layers")
  4876. c.Assert(err, checker.IsNil)
  4877. c.Assert(strings.TrimSpace(out), checker.Equals, "3")
  4878. }
  4879. func (s *DockerSuite) TestBuildContChar(c *check.C) {
  4880. name := "testbuildcontchar"
  4881. buildImage(name, withDockerfile(`FROM busybox\`)).Assert(c, icmd.Expected{
  4882. Out: "Step 1/1 : FROM busybox",
  4883. })
  4884. result := buildImage(name, withDockerfile(`FROM busybox
  4885. RUN echo hi \`))
  4886. result.Assert(c, icmd.Success)
  4887. c.Assert(result.Combined(), checker.Contains, "Step 1/2 : FROM busybox")
  4888. c.Assert(result.Combined(), checker.Contains, "Step 2/2 : RUN echo hi\n")
  4889. result = buildImage(name, withDockerfile(`FROM busybox
  4890. RUN echo hi \\`))
  4891. result.Assert(c, icmd.Success)
  4892. c.Assert(result.Combined(), checker.Contains, "Step 1/2 : FROM busybox")
  4893. c.Assert(result.Combined(), checker.Contains, "Step 2/2 : RUN echo hi \\\n")
  4894. result = buildImage(name, withDockerfile(`FROM busybox
  4895. RUN echo hi \\\`))
  4896. result.Assert(c, icmd.Success)
  4897. c.Assert(result.Combined(), checker.Contains, "Step 1/2 : FROM busybox")
  4898. c.Assert(result.Combined(), checker.Contains, "Step 2/2 : RUN echo hi \\\\\n")
  4899. }
  4900. // TestBuildOpaqueDirectory tests that a build succeeds which
  4901. // creates opaque directories.
  4902. // See https://github.com/docker/docker/issues/25244
  4903. func (s *DockerSuite) TestBuildOpaqueDirectory(c *check.C) {
  4904. testRequires(c, DaemonIsLinux)
  4905. dockerFile := `
  4906. FROM busybox
  4907. RUN mkdir /dir1 && touch /dir1/f1
  4908. RUN rm -rf /dir1 && mkdir /dir1 && touch /dir1/f2
  4909. RUN touch /dir1/f3
  4910. RUN [ -f /dir1/f2 ]
  4911. `
  4912. // Test that build succeeds, last command fails if opaque directory
  4913. // was not handled correctly
  4914. buildImageSuccessfully(c, "testopaquedirectory", withDockerfile(dockerFile))
  4915. }
  4916. // Windows test for USER in dockerfile
  4917. func (s *DockerSuite) TestBuildWindowsUser(c *check.C) {
  4918. testRequires(c, DaemonIsWindows)
  4919. name := "testbuildwindowsuser"
  4920. buildImage(name, withDockerfile(`FROM `+testEnv.MinimalBaseImage()+`
  4921. RUN net user user /add
  4922. USER user
  4923. RUN set username
  4924. `)).Assert(c, icmd.Expected{
  4925. Out: "USERNAME=user",
  4926. })
  4927. }
  4928. // Verifies if COPY file . when WORKDIR is set to a non-existing directory,
  4929. // the directory is created and the file is copied into the directory,
  4930. // as opposed to the file being copied as a file with the name of the
  4931. // directory. Fix for 27545 (found on Windows, but regression good for Linux too).
  4932. // Note 27545 was reverted in 28505, but a new fix was added subsequently in 28514.
  4933. func (s *DockerSuite) TestBuildCopyFileDotWithWorkdir(c *check.C) {
  4934. name := "testbuildcopyfiledotwithworkdir"
  4935. buildImageSuccessfully(c, name, withBuildContext(c,
  4936. withFile("Dockerfile", `FROM busybox
  4937. WORKDIR /foo
  4938. COPY file .
  4939. RUN ["cat", "/foo/file"]
  4940. `),
  4941. withFile("file", "content"),
  4942. ))
  4943. }
  4944. // Case-insensitive environment variables on Windows
  4945. func (s *DockerSuite) TestBuildWindowsEnvCaseInsensitive(c *check.C) {
  4946. testRequires(c, DaemonIsWindows)
  4947. name := "testbuildwindowsenvcaseinsensitive"
  4948. buildImageSuccessfully(c, name, withDockerfile(`
  4949. FROM `+testEnv.MinimalBaseImage()+`
  4950. ENV FOO=bar foo=baz
  4951. `))
  4952. res := inspectFieldJSON(c, name, "Config.Env")
  4953. if res != `["foo=baz"]` { // Should not have FOO=bar in it - takes the last one processed. And only one entry as deduped.
  4954. c.Fatalf("Case insensitive environment variables on Windows failed. Got %s", res)
  4955. }
  4956. }
  4957. // Test case for 29667
  4958. func (s *DockerSuite) TestBuildWorkdirImageCmd(c *check.C) {
  4959. image := "testworkdirimagecmd"
  4960. buildImageSuccessfully(c, image, withDockerfile(`
  4961. FROM busybox
  4962. WORKDIR /foo/bar
  4963. `))
  4964. out, _ := dockerCmd(c, "inspect", "--format", "{{ json .Config.Cmd }}", image)
  4965. // The Windows busybox image has a blank `cmd`
  4966. lookingFor := `["sh"]`
  4967. if testEnv.DaemonPlatform() == "windows" {
  4968. lookingFor = "null"
  4969. }
  4970. c.Assert(strings.TrimSpace(out), checker.Equals, lookingFor)
  4971. image = "testworkdirlabelimagecmd"
  4972. buildImageSuccessfully(c, image, withDockerfile(`
  4973. FROM busybox
  4974. WORKDIR /foo/bar
  4975. LABEL a=b
  4976. `))
  4977. out, _ = dockerCmd(c, "inspect", "--format", "{{ json .Config.Cmd }}", image)
  4978. c.Assert(strings.TrimSpace(out), checker.Equals, lookingFor)
  4979. }
  4980. // Test case for 28902/28909
  4981. func (s *DockerSuite) TestBuildWorkdirCmd(c *check.C) {
  4982. testRequires(c, DaemonIsLinux)
  4983. name := "testbuildworkdircmd"
  4984. dockerFile := `
  4985. FROM busybox
  4986. WORKDIR /
  4987. `
  4988. buildImageSuccessfully(c, name, withDockerfile(dockerFile))
  4989. result := buildImage(name, withDockerfile(dockerFile))
  4990. result.Assert(c, icmd.Success)
  4991. c.Assert(strings.Count(result.Combined(), "Using cache"), checker.Equals, 1)
  4992. }
  4993. // FIXME(vdemeester) should be a unit test
  4994. func (s *DockerSuite) TestBuildLineErrorOnBuild(c *check.C) {
  4995. name := "test_build_line_error_onbuild"
  4996. buildImage(name, withDockerfile(`FROM busybox
  4997. ONBUILD
  4998. `)).Assert(c, icmd.Expected{
  4999. ExitCode: 1,
  5000. Err: "Dockerfile parse error line 2: ONBUILD requires at least one argument",
  5001. })
  5002. }
  5003. // FIXME(vdemeester) should be a unit test
  5004. func (s *DockerSuite) TestBuildLineErrorUknownInstruction(c *check.C) {
  5005. name := "test_build_line_error_unknown_instruction"
  5006. buildImage(name, withDockerfile(`FROM busybox
  5007. RUN echo hello world
  5008. NOINSTRUCTION echo ba
  5009. RUN echo hello
  5010. ERROR
  5011. `)).Assert(c, icmd.Expected{
  5012. ExitCode: 1,
  5013. Err: "Dockerfile parse error line 3: Unknown instruction: NOINSTRUCTION",
  5014. })
  5015. }
  5016. // FIXME(vdemeester) should be a unit test
  5017. func (s *DockerSuite) TestBuildLineErrorWithEmptyLines(c *check.C) {
  5018. name := "test_build_line_error_with_empty_lines"
  5019. buildImage(name, withDockerfile(`
  5020. FROM busybox
  5021. RUN echo hello world
  5022. NOINSTRUCTION echo ba
  5023. CMD ["/bin/init"]
  5024. `)).Assert(c, icmd.Expected{
  5025. ExitCode: 1,
  5026. Err: "Dockerfile parse error line 6: Unknown instruction: NOINSTRUCTION",
  5027. })
  5028. }
  5029. // FIXME(vdemeester) should be a unit test
  5030. func (s *DockerSuite) TestBuildLineErrorWithComments(c *check.C) {
  5031. name := "test_build_line_error_with_comments"
  5032. buildImage(name, withDockerfile(`FROM busybox
  5033. # This will print hello world
  5034. # and then ba
  5035. RUN echo hello world
  5036. NOINSTRUCTION echo ba
  5037. `)).Assert(c, icmd.Expected{
  5038. ExitCode: 1,
  5039. Err: "Dockerfile parse error line 5: Unknown instruction: NOINSTRUCTION",
  5040. })
  5041. }