docker_cli_build_test.go 110 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404
  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"
  11. "path/filepath"
  12. "reflect"
  13. "regexp"
  14. "strconv"
  15. "strings"
  16. "syscall"
  17. "testing"
  18. "text/template"
  19. "time"
  20. "github.com/docker/docker/pkg/archive"
  21. )
  22. func TestBuildJSONEmptyRun(t *testing.T) {
  23. name := "testbuildjsonemptyrun"
  24. defer deleteImages(name)
  25. _, err := buildImage(
  26. name,
  27. `
  28. FROM busybox
  29. RUN []
  30. `,
  31. true)
  32. if err != nil {
  33. t.Fatal("error when dealing with a RUN statement with empty JSON array")
  34. }
  35. logDone("build - RUN with an empty array should not panic")
  36. }
  37. func TestBuildEmptyWhitespace(t *testing.T) {
  38. name := "testbuildemptywhitespace"
  39. defer deleteImages(name)
  40. _, err := buildImage(
  41. name,
  42. `
  43. FROM busybox
  44. RUN
  45. quux \
  46. bar
  47. `,
  48. true)
  49. if err == nil {
  50. t.Fatal("no error when dealing with a RUN statement with no content on the same line")
  51. }
  52. logDone("build - statements with whitespace and no content should generate a parse error")
  53. }
  54. func TestBuildShCmdJSONEntrypoint(t *testing.T) {
  55. name := "testbuildshcmdjsonentrypoint"
  56. defer deleteImages(name)
  57. _, err := buildImage(
  58. name,
  59. `
  60. FROM busybox
  61. ENTRYPOINT ["/bin/echo"]
  62. CMD echo test
  63. `,
  64. true)
  65. if err != nil {
  66. t.Fatal(err)
  67. }
  68. out, _, err := runCommandWithOutput(
  69. exec.Command(
  70. dockerBinary,
  71. "run",
  72. "--rm",
  73. name))
  74. if err != nil {
  75. t.Fatal(err)
  76. }
  77. if strings.TrimSpace(out) != "/bin/sh -c echo test" {
  78. t.Fatal("CMD did not contain /bin/sh -c")
  79. }
  80. logDone("build - CMD should always contain /bin/sh -c when specified without JSON")
  81. }
  82. func TestBuildEnvironmentReplacementUser(t *testing.T) {
  83. name := "testbuildenvironmentreplacement"
  84. defer deleteImages(name)
  85. _, err := buildImage(name, `
  86. FROM scratch
  87. ENV user foo
  88. USER ${user}
  89. `, true)
  90. if err != nil {
  91. t.Fatal(err)
  92. }
  93. res, err := inspectFieldJSON(name, "Config.User")
  94. if err != nil {
  95. t.Fatal(err)
  96. }
  97. if res != `"foo"` {
  98. t.Fatal("User foo from environment not in Config.User on image")
  99. }
  100. logDone("build - user environment replacement")
  101. }
  102. func TestBuildEnvironmentReplacementVolume(t *testing.T) {
  103. name := "testbuildenvironmentreplacement"
  104. defer deleteImages(name)
  105. _, err := buildImage(name, `
  106. FROM scratch
  107. ENV volume /quux
  108. VOLUME ${volume}
  109. `, true)
  110. if err != nil {
  111. t.Fatal(err)
  112. }
  113. res, err := inspectFieldJSON(name, "Config.Volumes")
  114. if err != nil {
  115. t.Fatal(err)
  116. }
  117. var volumes map[string]interface{}
  118. if err := json.Unmarshal([]byte(res), &volumes); err != nil {
  119. t.Fatal(err)
  120. }
  121. if _, ok := volumes["/quux"]; !ok {
  122. t.Fatal("Volume /quux from environment not in Config.Volumes on image")
  123. }
  124. logDone("build - volume environment replacement")
  125. }
  126. func TestBuildEnvironmentReplacementExpose(t *testing.T) {
  127. name := "testbuildenvironmentreplacement"
  128. defer deleteImages(name)
  129. _, err := buildImage(name, `
  130. FROM scratch
  131. ENV port 80
  132. EXPOSE ${port}
  133. `, true)
  134. if err != nil {
  135. t.Fatal(err)
  136. }
  137. res, err := inspectFieldJSON(name, "Config.ExposedPorts")
  138. if err != nil {
  139. t.Fatal(err)
  140. }
  141. var exposedPorts map[string]interface{}
  142. if err := json.Unmarshal([]byte(res), &exposedPorts); err != nil {
  143. t.Fatal(err)
  144. }
  145. if _, ok := exposedPorts["80/tcp"]; !ok {
  146. t.Fatal("Exposed port 80 from environment not in Config.ExposedPorts on image")
  147. }
  148. logDone("build - expose environment replacement")
  149. }
  150. func TestBuildEnvironmentReplacementWorkdir(t *testing.T) {
  151. name := "testbuildenvironmentreplacement"
  152. defer deleteImages(name)
  153. _, err := buildImage(name, `
  154. FROM busybox
  155. ENV MYWORKDIR /work
  156. RUN mkdir ${MYWORKDIR}
  157. WORKDIR ${MYWORKDIR}
  158. `, true)
  159. if err != nil {
  160. t.Fatal(err)
  161. }
  162. logDone("build - workdir environment replacement")
  163. }
  164. func TestBuildEnvironmentReplacementAddCopy(t *testing.T) {
  165. name := "testbuildenvironmentreplacement"
  166. defer deleteImages(name)
  167. ctx, err := fakeContext(`
  168. FROM scratch
  169. ENV baz foo
  170. ENV quux bar
  171. ENV dot .
  172. ADD ${baz} ${dot}
  173. COPY ${quux} ${dot}
  174. `,
  175. map[string]string{
  176. "foo": "test1",
  177. "bar": "test2",
  178. })
  179. if err != nil {
  180. t.Fatal(err)
  181. }
  182. defer ctx.Close()
  183. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  184. t.Fatal(err)
  185. }
  186. logDone("build - add/copy environment replacement")
  187. }
  188. func TestBuildEnvironmentReplacementEnv(t *testing.T) {
  189. name := "testbuildenvironmentreplacement"
  190. defer deleteImages(name)
  191. _, err := buildImage(name,
  192. `
  193. FROM scratch
  194. ENV foo foo
  195. ENV bar ${foo}
  196. `, true)
  197. if err != nil {
  198. t.Fatal(err)
  199. }
  200. res, err := inspectFieldJSON(name, "Config.Env")
  201. if err != nil {
  202. t.Fatal(err)
  203. }
  204. envResult := []string{}
  205. if err = unmarshalJSON([]byte(res), &envResult); err != nil {
  206. t.Fatal(err)
  207. }
  208. found := false
  209. for _, env := range envResult {
  210. parts := strings.SplitN(env, "=", 2)
  211. if parts[0] == "bar" {
  212. found = true
  213. if parts[1] != "foo" {
  214. t.Fatalf("Could not find replaced var for env `bar`: got %q instead of `foo`", parts[1])
  215. }
  216. }
  217. }
  218. if !found {
  219. t.Fatal("Never found the `bar` env variable")
  220. }
  221. logDone("build - env environment replacement")
  222. }
  223. func TestBuildHandleEscapes(t *testing.T) {
  224. name := "testbuildhandleescapes"
  225. defer deleteImages(name)
  226. _, err := buildImage(name,
  227. `
  228. FROM scratch
  229. ENV FOO bar
  230. VOLUME ${FOO}
  231. `, true)
  232. if err != nil {
  233. t.Fatal(err)
  234. }
  235. var result map[string]map[string]struct{}
  236. res, err := inspectFieldJSON(name, "Config.Volumes")
  237. if err != nil {
  238. t.Fatal(err)
  239. }
  240. if err = unmarshalJSON([]byte(res), &result); err != nil {
  241. t.Fatal(err)
  242. }
  243. if _, ok := result["bar"]; !ok {
  244. t.Fatal("Could not find volume bar set from env foo in volumes table")
  245. }
  246. deleteImages(name)
  247. _, err = buildImage(name,
  248. `
  249. FROM scratch
  250. ENV FOO bar
  251. VOLUME \${FOO}
  252. `, true)
  253. if err != nil {
  254. t.Fatal(err)
  255. }
  256. res, err = inspectFieldJSON(name, "Config.Volumes")
  257. if err != nil {
  258. t.Fatal(err)
  259. }
  260. if err = unmarshalJSON([]byte(res), &result); err != nil {
  261. t.Fatal(err)
  262. }
  263. if _, ok := result["${FOO}"]; !ok {
  264. t.Fatal("Could not find volume ${FOO} set from env foo in volumes table")
  265. }
  266. deleteImages(name)
  267. // this test in particular provides *7* backslashes and expects 6 to come back.
  268. // Like above, the first escape is swallowed and the rest are treated as
  269. // literals, this one is just less obvious because of all the character noise.
  270. _, err = buildImage(name,
  271. `
  272. FROM scratch
  273. ENV FOO bar
  274. VOLUME \\\\\\\${FOO}
  275. `, true)
  276. if err != nil {
  277. t.Fatal(err)
  278. }
  279. res, err = inspectFieldJSON(name, "Config.Volumes")
  280. if err != nil {
  281. t.Fatal(err)
  282. }
  283. if err = unmarshalJSON([]byte(res), &result); err != nil {
  284. t.Fatal(err)
  285. }
  286. if _, ok := result[`\\\\\\${FOO}`]; !ok {
  287. t.Fatal(`Could not find volume \\\\\\${FOO} set from env foo in volumes table`)
  288. }
  289. logDone("build - handle escapes")
  290. }
  291. func TestBuildOnBuildLowercase(t *testing.T) {
  292. name := "testbuildonbuildlowercase"
  293. name2 := "testbuildonbuildlowercase2"
  294. defer deleteImages(name, name2)
  295. _, err := buildImage(name,
  296. `
  297. FROM busybox
  298. onbuild run echo quux
  299. `, true)
  300. if err != nil {
  301. t.Fatal(err)
  302. }
  303. _, out, err := buildImageWithOut(name2, fmt.Sprintf(`
  304. FROM %s
  305. `, name), true)
  306. if err != nil {
  307. t.Fatal(err)
  308. }
  309. if !strings.Contains(out, "quux") {
  310. t.Fatalf("Did not receive the expected echo text, got %s", out)
  311. }
  312. if strings.Contains(out, "ONBUILD ONBUILD") {
  313. t.Fatalf("Got an ONBUILD ONBUILD error with no error: got %s", out)
  314. }
  315. logDone("build - handle case-insensitive onbuild statement")
  316. }
  317. func TestBuildEnvEscapes(t *testing.T) {
  318. name := "testbuildenvescapes"
  319. defer deleteImages(name)
  320. defer deleteAllContainers()
  321. _, err := buildImage(name,
  322. `
  323. FROM busybox
  324. ENV TEST foo
  325. CMD echo \$
  326. `,
  327. true)
  328. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-t", name))
  329. if err != nil {
  330. t.Fatal(err)
  331. }
  332. if strings.TrimSpace(out) != "$" {
  333. t.Fatalf("Env TEST was not overwritten with bar when foo was supplied to dockerfile: was %q", strings.TrimSpace(out))
  334. }
  335. logDone("build - env should handle \\$ properly")
  336. }
  337. func TestBuildEnvOverwrite(t *testing.T) {
  338. name := "testbuildenvoverwrite"
  339. defer deleteImages(name)
  340. defer deleteAllContainers()
  341. _, err := buildImage(name,
  342. `
  343. FROM busybox
  344. ENV TEST foo
  345. CMD echo ${TEST}
  346. `,
  347. true)
  348. if err != nil {
  349. t.Fatal(err)
  350. }
  351. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-e", "TEST=bar", "-t", name))
  352. if err != nil {
  353. t.Fatal(err)
  354. }
  355. if strings.TrimSpace(out) != "bar" {
  356. t.Fatalf("Env TEST was not overwritten with bar when foo was supplied to dockerfile: was %q", strings.TrimSpace(out))
  357. }
  358. logDone("build - env should overwrite builder ENV during run")
  359. }
  360. func TestBuildOnBuildForbiddenMaintainerInSourceImage(t *testing.T) {
  361. name := "testbuildonbuildforbiddenmaintainerinsourceimage"
  362. defer deleteImages("onbuild")
  363. defer deleteImages(name)
  364. defer deleteAllContainers()
  365. createCmd := exec.Command(dockerBinary, "create", "busybox", "true")
  366. out, _, _, err := runCommandWithStdoutStderr(createCmd)
  367. if err != nil {
  368. t.Fatal(out, err)
  369. }
  370. cleanedContainerID := stripTrailingCharacters(out)
  371. commitCmd := exec.Command(dockerBinary, "commit", "--run", "{\"OnBuild\":[\"MAINTAINER docker.io\"]}", cleanedContainerID, "onbuild")
  372. if _, err := runCommand(commitCmd); err != nil {
  373. t.Fatal(err)
  374. }
  375. _, err = buildImage(name,
  376. `FROM onbuild`,
  377. true)
  378. if err != nil {
  379. if !strings.Contains(err.Error(), "maintainer isn't allowed as an ONBUILD trigger") {
  380. t.Fatalf("Wrong error %v, must be about MAINTAINER and ONBUILD in source image", err)
  381. }
  382. } else {
  383. t.Fatal("Error must not be nil")
  384. }
  385. logDone("build - onbuild forbidden maintainer in source image")
  386. }
  387. func TestBuildOnBuildForbiddenFromInSourceImage(t *testing.T) {
  388. name := "testbuildonbuildforbiddenfrominsourceimage"
  389. defer deleteImages("onbuild")
  390. defer deleteImages(name)
  391. defer deleteAllContainers()
  392. createCmd := exec.Command(dockerBinary, "create", "busybox", "true")
  393. out, _, _, err := runCommandWithStdoutStderr(createCmd)
  394. if err != nil {
  395. t.Fatal(out, err)
  396. }
  397. cleanedContainerID := stripTrailingCharacters(out)
  398. commitCmd := exec.Command(dockerBinary, "commit", "--run", "{\"OnBuild\":[\"FROM busybox\"]}", cleanedContainerID, "onbuild")
  399. if _, err := runCommand(commitCmd); err != nil {
  400. t.Fatal(err)
  401. }
  402. _, err = buildImage(name,
  403. `FROM onbuild`,
  404. true)
  405. if err != nil {
  406. if !strings.Contains(err.Error(), "from isn't allowed as an ONBUILD trigger") {
  407. t.Fatalf("Wrong error %v, must be about FROM and ONBUILD in source image", err)
  408. }
  409. } else {
  410. t.Fatal("Error must not be nil")
  411. }
  412. logDone("build - onbuild forbidden from in source image")
  413. }
  414. func TestBuildOnBuildForbiddenChainedInSourceImage(t *testing.T) {
  415. name := "testbuildonbuildforbiddenchainedinsourceimage"
  416. defer deleteImages("onbuild")
  417. defer deleteImages(name)
  418. defer deleteAllContainers()
  419. createCmd := exec.Command(dockerBinary, "create", "busybox", "true")
  420. out, _, _, err := runCommandWithStdoutStderr(createCmd)
  421. if err != nil {
  422. t.Fatal(out, err)
  423. }
  424. cleanedContainerID := stripTrailingCharacters(out)
  425. commitCmd := exec.Command(dockerBinary, "commit", "--run", "{\"OnBuild\":[\"ONBUILD RUN ls\"]}", cleanedContainerID, "onbuild")
  426. if _, err := runCommand(commitCmd); err != nil {
  427. t.Fatal(err)
  428. }
  429. _, err = buildImage(name,
  430. `FROM onbuild`,
  431. true)
  432. if err != nil {
  433. if !strings.Contains(err.Error(), "Chaining ONBUILD via `ONBUILD ONBUILD` isn't allowed") {
  434. t.Fatalf("Wrong error %v, must be about chaining ONBUILD in source image", err)
  435. }
  436. } else {
  437. t.Fatal("Error must not be nil")
  438. }
  439. logDone("build - onbuild forbidden chained in source image")
  440. }
  441. func TestBuildOnBuildCmdEntrypointJSON(t *testing.T) {
  442. name1 := "onbuildcmd"
  443. name2 := "onbuildgenerated"
  444. defer deleteImages(name2)
  445. defer deleteImages(name1)
  446. defer deleteAllContainers()
  447. _, err := buildImage(name1, `
  448. FROM busybox
  449. ONBUILD CMD ["hello world"]
  450. ONBUILD ENTRYPOINT ["echo"]
  451. ONBUILD RUN ["true"]`,
  452. false)
  453. if err != nil {
  454. t.Fatal(err)
  455. }
  456. _, err = buildImage(name2, fmt.Sprintf(`FROM %s`, name1), false)
  457. if err != nil {
  458. t.Fatal(err)
  459. }
  460. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-t", name2))
  461. if err != nil {
  462. t.Fatal(err)
  463. }
  464. if !regexp.MustCompile(`(?m)^hello world`).MatchString(out) {
  465. t.Fatal("did not get echo output from onbuild", out)
  466. }
  467. logDone("build - onbuild with json entrypoint/cmd")
  468. }
  469. func TestBuildOnBuildEntrypointJSON(t *testing.T) {
  470. name1 := "onbuildcmd"
  471. name2 := "onbuildgenerated"
  472. defer deleteImages(name2)
  473. defer deleteImages(name1)
  474. defer deleteAllContainers()
  475. _, err := buildImage(name1, `
  476. FROM busybox
  477. ONBUILD ENTRYPOINT ["echo"]`,
  478. false)
  479. if err != nil {
  480. t.Fatal(err)
  481. }
  482. _, err = buildImage(name2, fmt.Sprintf("FROM %s\nCMD [\"hello world\"]\n", name1), false)
  483. if err != nil {
  484. t.Fatal(err)
  485. }
  486. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-t", name2))
  487. if err != nil {
  488. t.Fatal(err)
  489. }
  490. if !regexp.MustCompile(`(?m)^hello world`).MatchString(out) {
  491. t.Fatal("got malformed output from onbuild", out)
  492. }
  493. logDone("build - onbuild with json entrypoint")
  494. }
  495. func TestBuildCacheADD(t *testing.T) {
  496. name := "testbuildtwoimageswithadd"
  497. defer deleteImages(name)
  498. server, err := fakeStorage(map[string]string{
  499. "robots.txt": "hello",
  500. "index.html": "world",
  501. })
  502. if err != nil {
  503. t.Fatal(err)
  504. }
  505. defer server.Close()
  506. if _, err := buildImage(name,
  507. fmt.Sprintf(`FROM scratch
  508. ADD %s/robots.txt /`, server.URL),
  509. true); err != nil {
  510. t.Fatal(err)
  511. }
  512. if err != nil {
  513. t.Fatal(err)
  514. }
  515. deleteImages(name)
  516. _, out, err := buildImageWithOut(name,
  517. fmt.Sprintf(`FROM scratch
  518. ADD %s/index.html /`, server.URL),
  519. true)
  520. if err != nil {
  521. t.Fatal(err)
  522. }
  523. if strings.Contains(out, "Using cache") {
  524. t.Fatal("2nd build used cache on ADD, it shouldn't")
  525. }
  526. logDone("build - build two images with remote ADD")
  527. }
  528. func TestBuildSixtySteps(t *testing.T) {
  529. name := "foobuildsixtysteps"
  530. defer deleteImages(name)
  531. ctx, err := fakeContext("FROM scratch\n"+strings.Repeat("ADD foo /\n", 60),
  532. map[string]string{
  533. "foo": "test1",
  534. })
  535. if err != nil {
  536. t.Fatal(err)
  537. }
  538. defer ctx.Close()
  539. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  540. t.Fatal(err)
  541. }
  542. logDone("build - build an image with sixty build steps")
  543. }
  544. func TestBuildAddSingleFileToRoot(t *testing.T) {
  545. name := "testaddimg"
  546. defer deleteImages(name)
  547. ctx, err := fakeContext(`FROM busybox
  548. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  549. RUN echo 'dockerio:x:1001:' >> /etc/group
  550. RUN touch /exists
  551. RUN chown dockerio.dockerio /exists
  552. ADD test_file /
  553. RUN [ $(ls -l /test_file | awk '{print $3":"$4}') = 'root:root' ]
  554. RUN [ $(ls -l /test_file | awk '{print $1}') = '-rw-r--r--' ]
  555. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`,
  556. map[string]string{
  557. "test_file": "test1",
  558. })
  559. if err != nil {
  560. t.Fatal(err)
  561. }
  562. defer ctx.Close()
  563. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  564. t.Fatal(err)
  565. }
  566. logDone("build - add single file to root")
  567. }
  568. // Issue #3960: "ADD src ." hangs
  569. func TestBuildAddSingleFileToWorkdir(t *testing.T) {
  570. name := "testaddsinglefiletoworkdir"
  571. defer deleteImages(name)
  572. ctx, err := fakeContext(`FROM busybox
  573. ADD test_file .`,
  574. map[string]string{
  575. "test_file": "test1",
  576. })
  577. if err != nil {
  578. t.Fatal(err)
  579. }
  580. defer ctx.Close()
  581. done := make(chan struct{})
  582. go func() {
  583. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  584. t.Fatal(err)
  585. }
  586. close(done)
  587. }()
  588. select {
  589. case <-time.After(5 * time.Second):
  590. t.Fatal("Build with adding to workdir timed out")
  591. case <-done:
  592. }
  593. logDone("build - add single file to workdir")
  594. }
  595. func TestBuildAddSingleFileToExistDir(t *testing.T) {
  596. name := "testaddsinglefiletoexistdir"
  597. defer deleteImages(name)
  598. ctx, err := fakeContext(`FROM busybox
  599. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  600. RUN echo 'dockerio:x:1001:' >> /etc/group
  601. RUN mkdir /exists
  602. RUN touch /exists/exists_file
  603. RUN chown -R dockerio.dockerio /exists
  604. ADD test_file /exists/
  605. RUN [ $(ls -l / | grep exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  606. RUN [ $(ls -l /exists/test_file | awk '{print $3":"$4}') = 'root:root' ]
  607. RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`,
  608. map[string]string{
  609. "test_file": "test1",
  610. })
  611. if err != nil {
  612. t.Fatal(err)
  613. }
  614. defer ctx.Close()
  615. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  616. t.Fatal(err)
  617. }
  618. logDone("build - add single file to existing dir")
  619. }
  620. func TestBuildCopyAddMultipleFiles(t *testing.T) {
  621. name := "testcopymultiplefilestofile"
  622. defer deleteImages(name)
  623. ctx, err := fakeContext(`FROM busybox
  624. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  625. RUN echo 'dockerio:x:1001:' >> /etc/group
  626. RUN mkdir /exists
  627. RUN touch /exists/exists_file
  628. RUN chown -R dockerio.dockerio /exists
  629. COPY test_file1 test_file2 /exists/
  630. ADD test_file3 test_file4 https://dockerproject.com/robots.txt /exists/
  631. RUN [ $(ls -l / | grep exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  632. RUN [ $(ls -l /exists/test_file1 | awk '{print $3":"$4}') = 'root:root' ]
  633. RUN [ $(ls -l /exists/test_file2 | awk '{print $3":"$4}') = 'root:root' ]
  634. RUN [ $(ls -l /exists/test_file3 | awk '{print $3":"$4}') = 'root:root' ]
  635. RUN [ $(ls -l /exists/test_file4 | awk '{print $3":"$4}') = 'root:root' ]
  636. RUN [ $(ls -l /exists/robots.txt | awk '{print $3":"$4}') = 'root:root' ]
  637. RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  638. `,
  639. map[string]string{
  640. "test_file1": "test1",
  641. "test_file2": "test2",
  642. "test_file3": "test3",
  643. "test_file4": "test4",
  644. })
  645. defer ctx.Close()
  646. if err != nil {
  647. t.Fatal(err)
  648. }
  649. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  650. t.Fatal(err)
  651. }
  652. logDone("build - mulitple file copy/add tests")
  653. }
  654. func TestBuildAddMultipleFilesToFile(t *testing.T) {
  655. name := "testaddmultiplefilestofile"
  656. defer deleteImages(name)
  657. ctx, err := fakeContext(`FROM scratch
  658. ADD file1.txt file2.txt test
  659. `,
  660. map[string]string{
  661. "file1.txt": "test1",
  662. "file2.txt": "test1",
  663. })
  664. defer ctx.Close()
  665. if err != nil {
  666. t.Fatal(err)
  667. }
  668. expected := "When using ADD with more than one source file, the destination must be a directory and end with a /"
  669. if _, err := buildImageFromContext(name, ctx, true); err == nil || !strings.Contains(err.Error(), expected) {
  670. t.Fatalf("Wrong error: (should contain \"%s\") got:\n%v", expected, err)
  671. }
  672. logDone("build - multiple add files to file")
  673. }
  674. func TestBuildAddMultipleFilesToFileWild(t *testing.T) {
  675. name := "testaddmultiplefilestofilewild"
  676. defer deleteImages(name)
  677. ctx, err := fakeContext(`FROM scratch
  678. ADD file*.txt test
  679. `,
  680. map[string]string{
  681. "file1.txt": "test1",
  682. "file2.txt": "test1",
  683. })
  684. defer ctx.Close()
  685. if err != nil {
  686. t.Fatal(err)
  687. }
  688. expected := "When using ADD with more than one source file, the destination must be a directory and end with a /"
  689. if _, err := buildImageFromContext(name, ctx, true); err == nil || !strings.Contains(err.Error(), expected) {
  690. t.Fatalf("Wrong error: (should contain \"%s\") got:\n%v", expected, err)
  691. }
  692. logDone("build - multiple add files to file wild")
  693. }
  694. func TestBuildCopyMultipleFilesToFile(t *testing.T) {
  695. name := "testcopymultiplefilestofile"
  696. defer deleteImages(name)
  697. ctx, err := fakeContext(`FROM scratch
  698. COPY file1.txt file2.txt test
  699. `,
  700. map[string]string{
  701. "file1.txt": "test1",
  702. "file2.txt": "test1",
  703. })
  704. defer ctx.Close()
  705. if err != nil {
  706. t.Fatal(err)
  707. }
  708. expected := "When using COPY with more than one source file, the destination must be a directory and end with a /"
  709. if _, err := buildImageFromContext(name, ctx, true); err == nil || !strings.Contains(err.Error(), expected) {
  710. t.Fatalf("Wrong error: (should contain \"%s\") got:\n%v", expected, err)
  711. }
  712. logDone("build - multiple copy files to file")
  713. }
  714. func TestBuildCopyWildcard(t *testing.T) {
  715. name := "testcopywildcard"
  716. defer deleteImages(name)
  717. server, err := fakeStorage(map[string]string{
  718. "robots.txt": "hello",
  719. "index.html": "world",
  720. })
  721. if err != nil {
  722. t.Fatal(err)
  723. }
  724. defer server.Close()
  725. ctx, err := fakeContext(fmt.Sprintf(`FROM busybox
  726. COPY file*.txt /tmp/
  727. RUN ls /tmp/file1.txt /tmp/file2.txt
  728. RUN mkdir /tmp1
  729. COPY dir* /tmp1/
  730. RUN ls /tmp1/dirt /tmp1/nested_file /tmp1/nested_dir/nest_nest_file
  731. RUN mkdir /tmp2
  732. ADD dir/*dir %s/robots.txt /tmp2/
  733. RUN ls /tmp2/nest_nest_file /tmp2/robots.txt
  734. `, server.URL),
  735. map[string]string{
  736. "file1.txt": "test1",
  737. "file2.txt": "test2",
  738. "dir/nested_file": "nested file",
  739. "dir/nested_dir/nest_nest_file": "2 times nested",
  740. "dirt": "dirty",
  741. })
  742. defer ctx.Close()
  743. if err != nil {
  744. t.Fatal(err)
  745. }
  746. id1, err := buildImageFromContext(name, ctx, true)
  747. if err != nil {
  748. t.Fatal(err)
  749. }
  750. // Now make sure we use a cache the 2nd time
  751. id2, err := buildImageFromContext(name, ctx, true)
  752. if err != nil {
  753. t.Fatal(err)
  754. }
  755. if id1 != id2 {
  756. t.Fatal("didn't use the cache")
  757. }
  758. logDone("build - copy wild card")
  759. }
  760. func TestBuildCopyWildcardNoFind(t *testing.T) {
  761. name := "testcopywildcardnofind"
  762. defer deleteImages(name)
  763. ctx, err := fakeContext(`FROM busybox
  764. COPY file*.txt /tmp/
  765. `, nil)
  766. defer ctx.Close()
  767. if err != nil {
  768. t.Fatal(err)
  769. }
  770. _, err = buildImageFromContext(name, ctx, true)
  771. if err == nil {
  772. t.Fatal("should have failed to find a file")
  773. }
  774. if !strings.Contains(err.Error(), "No source files were specified") {
  775. t.Fatalf("Wrong error %v, must be about no source files", err)
  776. }
  777. logDone("build - copy wild card no find")
  778. }
  779. func TestBuildCopyWildcardCache(t *testing.T) {
  780. name := "testcopywildcardcache"
  781. defer deleteImages(name)
  782. ctx, err := fakeContext(`FROM busybox
  783. COPY file1.txt /tmp/`,
  784. map[string]string{
  785. "file1.txt": "test1",
  786. })
  787. defer ctx.Close()
  788. if err != nil {
  789. t.Fatal(err)
  790. }
  791. id1, err := buildImageFromContext(name, ctx, true)
  792. if err != nil {
  793. t.Fatal(err)
  794. }
  795. // Now make sure we use a cache the 2nd time even with wild cards.
  796. // Use the same context so the file is the same and the checksum will match
  797. ctx.Add("Dockerfile", `FROM busybox
  798. COPY file*.txt /tmp/`)
  799. id2, err := buildImageFromContext(name, ctx, true)
  800. if err != nil {
  801. t.Fatal(err)
  802. }
  803. if id1 != id2 {
  804. t.Fatal("didn't use the cache")
  805. }
  806. logDone("build - copy wild card cache")
  807. }
  808. func TestBuildAddSingleFileToNonExistingDir(t *testing.T) {
  809. name := "testaddsinglefiletononexistingdir"
  810. defer deleteImages(name)
  811. ctx, err := fakeContext(`FROM busybox
  812. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  813. RUN echo 'dockerio:x:1001:' >> /etc/group
  814. RUN touch /exists
  815. RUN chown dockerio.dockerio /exists
  816. ADD test_file /test_dir/
  817. RUN [ $(ls -l / | grep test_dir | awk '{print $3":"$4}') = 'root:root' ]
  818. RUN [ $(ls -l /test_dir/test_file | awk '{print $3":"$4}') = 'root:root' ]
  819. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`,
  820. map[string]string{
  821. "test_file": "test1",
  822. })
  823. if err != nil {
  824. t.Fatal(err)
  825. }
  826. defer ctx.Close()
  827. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  828. t.Fatal(err)
  829. }
  830. logDone("build - add single file to non-existing dir")
  831. }
  832. func TestBuildAddDirContentToRoot(t *testing.T) {
  833. name := "testadddircontenttoroot"
  834. defer deleteImages(name)
  835. ctx, err := fakeContext(`FROM busybox
  836. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  837. RUN echo 'dockerio:x:1001:' >> /etc/group
  838. RUN touch /exists
  839. RUN chown dockerio.dockerio exists
  840. ADD test_dir /
  841. RUN [ $(ls -l /test_file | awk '{print $3":"$4}') = 'root:root' ]
  842. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`,
  843. map[string]string{
  844. "test_dir/test_file": "test1",
  845. })
  846. if err != nil {
  847. t.Fatal(err)
  848. }
  849. defer ctx.Close()
  850. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  851. t.Fatal(err)
  852. }
  853. logDone("build - add directory contents to root")
  854. }
  855. func TestBuildAddDirContentToExistingDir(t *testing.T) {
  856. name := "testadddircontenttoexistingdir"
  857. defer deleteImages(name)
  858. ctx, err := fakeContext(`FROM busybox
  859. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  860. RUN echo 'dockerio:x:1001:' >> /etc/group
  861. RUN mkdir /exists
  862. RUN touch /exists/exists_file
  863. RUN chown -R dockerio.dockerio /exists
  864. ADD test_dir/ /exists/
  865. RUN [ $(ls -l / | grep exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  866. RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  867. RUN [ $(ls -l /exists/test_file | awk '{print $3":"$4}') = 'root:root' ]`,
  868. map[string]string{
  869. "test_dir/test_file": "test1",
  870. })
  871. if err != nil {
  872. t.Fatal(err)
  873. }
  874. defer ctx.Close()
  875. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  876. t.Fatal(err)
  877. }
  878. logDone("build - add directory contents to existing dir")
  879. }
  880. func TestBuildAddWholeDirToRoot(t *testing.T) {
  881. name := "testaddwholedirtoroot"
  882. defer deleteImages(name)
  883. ctx, err := fakeContext(`FROM busybox
  884. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  885. RUN echo 'dockerio:x:1001:' >> /etc/group
  886. RUN touch /exists
  887. RUN chown dockerio.dockerio exists
  888. ADD test_dir /test_dir
  889. RUN [ $(ls -l / | grep test_dir | awk '{print $3":"$4}') = 'root:root' ]
  890. RUN [ $(ls -l / | grep test_dir | awk '{print $1}') = 'drwxr-xr-x' ]
  891. RUN [ $(ls -l /test_dir/test_file | awk '{print $3":"$4}') = 'root:root' ]
  892. RUN [ $(ls -l /test_dir/test_file | awk '{print $1}') = '-rw-r--r--' ]
  893. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`,
  894. map[string]string{
  895. "test_dir/test_file": "test1",
  896. })
  897. if err != nil {
  898. t.Fatal(err)
  899. }
  900. defer ctx.Close()
  901. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  902. t.Fatal(err)
  903. }
  904. logDone("build - add whole directory to root")
  905. }
  906. // Testing #5941
  907. func TestBuildAddEtcToRoot(t *testing.T) {
  908. name := "testaddetctoroot"
  909. defer deleteImages(name)
  910. ctx, err := fakeContext(`FROM scratch
  911. ADD . /`,
  912. map[string]string{
  913. "etc/test_file": "test1",
  914. })
  915. if err != nil {
  916. t.Fatal(err)
  917. }
  918. defer ctx.Close()
  919. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  920. t.Fatal(err)
  921. }
  922. logDone("build - add etc directory to root")
  923. }
  924. // Testing #9401
  925. func TestBuildAddPreservesFilesSpecialBits(t *testing.T) {
  926. name := "testaddpreservesfilesspecialbits"
  927. defer deleteImages(name)
  928. ctx, err := fakeContext(`FROM busybox
  929. ADD suidbin /usr/bin/suidbin
  930. RUN chmod 4755 /usr/bin/suidbin
  931. RUN [ $(ls -l /usr/bin/suidbin | awk '{print $1}') = '-rwsr-xr-x' ]
  932. ADD ./data/ /
  933. RUN [ $(ls -l /usr/bin/suidbin | awk '{print $1}') = '-rwsr-xr-x' ]`,
  934. map[string]string{
  935. "suidbin": "suidbin",
  936. "/data/usr/test_file": "test1",
  937. })
  938. if err != nil {
  939. t.Fatal(err)
  940. }
  941. defer ctx.Close()
  942. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  943. t.Fatal(err)
  944. }
  945. logDone("build - add preserves files special bits")
  946. }
  947. func TestBuildCopySingleFileToRoot(t *testing.T) {
  948. name := "testcopysinglefiletoroot"
  949. defer deleteImages(name)
  950. ctx, err := fakeContext(`FROM busybox
  951. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  952. RUN echo 'dockerio:x:1001:' >> /etc/group
  953. RUN touch /exists
  954. RUN chown dockerio.dockerio /exists
  955. COPY test_file /
  956. RUN [ $(ls -l /test_file | awk '{print $3":"$4}') = 'root:root' ]
  957. RUN [ $(ls -l /test_file | awk '{print $1}') = '-rw-r--r--' ]
  958. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`,
  959. map[string]string{
  960. "test_file": "test1",
  961. })
  962. if err != nil {
  963. t.Fatal(err)
  964. }
  965. defer ctx.Close()
  966. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  967. t.Fatal(err)
  968. }
  969. logDone("build - copy single file to root")
  970. }
  971. // Issue #3960: "ADD src ." hangs - adapted for COPY
  972. func TestBuildCopySingleFileToWorkdir(t *testing.T) {
  973. name := "testcopysinglefiletoworkdir"
  974. defer deleteImages(name)
  975. ctx, err := fakeContext(`FROM busybox
  976. COPY test_file .`,
  977. map[string]string{
  978. "test_file": "test1",
  979. })
  980. if err != nil {
  981. t.Fatal(err)
  982. }
  983. defer ctx.Close()
  984. done := make(chan struct{})
  985. go func() {
  986. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  987. t.Fatal(err)
  988. }
  989. close(done)
  990. }()
  991. select {
  992. case <-time.After(5 * time.Second):
  993. t.Fatal("Build with adding to workdir timed out")
  994. case <-done:
  995. }
  996. logDone("build - copy single file to workdir")
  997. }
  998. func TestBuildCopySingleFileToExistDir(t *testing.T) {
  999. name := "testcopysinglefiletoexistdir"
  1000. defer deleteImages(name)
  1001. ctx, err := fakeContext(`FROM busybox
  1002. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1003. RUN echo 'dockerio:x:1001:' >> /etc/group
  1004. RUN mkdir /exists
  1005. RUN touch /exists/exists_file
  1006. RUN chown -R dockerio.dockerio /exists
  1007. COPY test_file /exists/
  1008. RUN [ $(ls -l / | grep exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  1009. RUN [ $(ls -l /exists/test_file | awk '{print $3":"$4}') = 'root:root' ]
  1010. RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`,
  1011. map[string]string{
  1012. "test_file": "test1",
  1013. })
  1014. if err != nil {
  1015. t.Fatal(err)
  1016. }
  1017. defer ctx.Close()
  1018. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1019. t.Fatal(err)
  1020. }
  1021. logDone("build - copy single file to existing dir")
  1022. }
  1023. func TestBuildCopySingleFileToNonExistDir(t *testing.T) {
  1024. name := "testcopysinglefiletononexistdir"
  1025. defer deleteImages(name)
  1026. ctx, err := fakeContext(`FROM busybox
  1027. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1028. RUN echo 'dockerio:x:1001:' >> /etc/group
  1029. RUN touch /exists
  1030. RUN chown dockerio.dockerio /exists
  1031. COPY test_file /test_dir/
  1032. RUN [ $(ls -l / | grep test_dir | awk '{print $3":"$4}') = 'root:root' ]
  1033. RUN [ $(ls -l /test_dir/test_file | awk '{print $3":"$4}') = 'root:root' ]
  1034. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`,
  1035. map[string]string{
  1036. "test_file": "test1",
  1037. })
  1038. if err != nil {
  1039. t.Fatal(err)
  1040. }
  1041. defer ctx.Close()
  1042. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1043. t.Fatal(err)
  1044. }
  1045. logDone("build - copy single file to non-existing dir")
  1046. }
  1047. func TestBuildCopyDirContentToRoot(t *testing.T) {
  1048. name := "testcopydircontenttoroot"
  1049. defer deleteImages(name)
  1050. ctx, err := fakeContext(`FROM busybox
  1051. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1052. RUN echo 'dockerio:x:1001:' >> /etc/group
  1053. RUN touch /exists
  1054. RUN chown dockerio.dockerio exists
  1055. COPY test_dir /
  1056. RUN [ $(ls -l /test_file | awk '{print $3":"$4}') = 'root:root' ]
  1057. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`,
  1058. map[string]string{
  1059. "test_dir/test_file": "test1",
  1060. })
  1061. if err != nil {
  1062. t.Fatal(err)
  1063. }
  1064. defer ctx.Close()
  1065. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1066. t.Fatal(err)
  1067. }
  1068. logDone("build - copy directory contents to root")
  1069. }
  1070. func TestBuildCopyDirContentToExistDir(t *testing.T) {
  1071. name := "testcopydircontenttoexistdir"
  1072. defer deleteImages(name)
  1073. ctx, err := fakeContext(`FROM busybox
  1074. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1075. RUN echo 'dockerio:x:1001:' >> /etc/group
  1076. RUN mkdir /exists
  1077. RUN touch /exists/exists_file
  1078. RUN chown -R dockerio.dockerio /exists
  1079. COPY test_dir/ /exists/
  1080. RUN [ $(ls -l / | grep exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  1081. RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio' ]
  1082. RUN [ $(ls -l /exists/test_file | awk '{print $3":"$4}') = 'root:root' ]`,
  1083. map[string]string{
  1084. "test_dir/test_file": "test1",
  1085. })
  1086. if err != nil {
  1087. t.Fatal(err)
  1088. }
  1089. defer ctx.Close()
  1090. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1091. t.Fatal(err)
  1092. }
  1093. logDone("build - copy directory contents to existing dir")
  1094. }
  1095. func TestBuildCopyWholeDirToRoot(t *testing.T) {
  1096. name := "testcopywholedirtoroot"
  1097. defer deleteImages(name)
  1098. ctx, err := fakeContext(`FROM busybox
  1099. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1100. RUN echo 'dockerio:x:1001:' >> /etc/group
  1101. RUN touch /exists
  1102. RUN chown dockerio.dockerio exists
  1103. COPY test_dir /test_dir
  1104. RUN [ $(ls -l / | grep test_dir | awk '{print $3":"$4}') = 'root:root' ]
  1105. RUN [ $(ls -l / | grep test_dir | awk '{print $1}') = 'drwxr-xr-x' ]
  1106. RUN [ $(ls -l /test_dir/test_file | awk '{print $3":"$4}') = 'root:root' ]
  1107. RUN [ $(ls -l /test_dir/test_file | awk '{print $1}') = '-rw-r--r--' ]
  1108. RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`,
  1109. map[string]string{
  1110. "test_dir/test_file": "test1",
  1111. })
  1112. if err != nil {
  1113. t.Fatal(err)
  1114. }
  1115. defer ctx.Close()
  1116. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1117. t.Fatal(err)
  1118. }
  1119. logDone("build - copy whole directory to root")
  1120. }
  1121. func TestBuildCopyEtcToRoot(t *testing.T) {
  1122. name := "testcopyetctoroot"
  1123. defer deleteImages(name)
  1124. ctx, err := fakeContext(`FROM scratch
  1125. COPY . /`,
  1126. map[string]string{
  1127. "etc/test_file": "test1",
  1128. })
  1129. if err != nil {
  1130. t.Fatal(err)
  1131. }
  1132. defer ctx.Close()
  1133. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1134. t.Fatal(err)
  1135. }
  1136. logDone("build - copy etc directory to root")
  1137. }
  1138. func TestBuildCopyDisallowRemote(t *testing.T) {
  1139. name := "testcopydisallowremote"
  1140. defer deleteImages(name)
  1141. _, out, err := buildImageWithOut(name, `FROM scratch
  1142. COPY https://index.docker.io/robots.txt /`,
  1143. true)
  1144. if err == nil || !strings.Contains(out, "Source can't be a URL for COPY") {
  1145. t.Fatalf("Error should be about disallowed remote source, got err: %s, out: %q", err, out)
  1146. }
  1147. logDone("build - copy - disallow copy from remote")
  1148. }
  1149. func TestBuildAddBadLinks(t *testing.T) {
  1150. const (
  1151. dockerfile = `
  1152. FROM scratch
  1153. ADD links.tar /
  1154. ADD foo.txt /symlink/
  1155. `
  1156. targetFile = "foo.txt"
  1157. )
  1158. var (
  1159. name = "test-link-absolute"
  1160. )
  1161. defer deleteImages(name)
  1162. ctx, err := fakeContext(dockerfile, nil)
  1163. if err != nil {
  1164. t.Fatal(err)
  1165. }
  1166. defer ctx.Close()
  1167. tempDir, err := ioutil.TempDir("", "test-link-absolute-temp-")
  1168. if err != nil {
  1169. t.Fatalf("failed to create temporary directory: %s", tempDir)
  1170. }
  1171. defer os.RemoveAll(tempDir)
  1172. symlinkTarget := fmt.Sprintf("/../../../../../../../../../../../..%s", tempDir)
  1173. tarPath := filepath.Join(ctx.Dir, "links.tar")
  1174. nonExistingFile := filepath.Join(tempDir, targetFile)
  1175. fooPath := filepath.Join(ctx.Dir, targetFile)
  1176. tarOut, err := os.Create(tarPath)
  1177. if err != nil {
  1178. t.Fatal(err)
  1179. }
  1180. tarWriter := tar.NewWriter(tarOut)
  1181. header := &tar.Header{
  1182. Name: "symlink",
  1183. Typeflag: tar.TypeSymlink,
  1184. Linkname: symlinkTarget,
  1185. Mode: 0755,
  1186. Uid: 0,
  1187. Gid: 0,
  1188. }
  1189. err = tarWriter.WriteHeader(header)
  1190. if err != nil {
  1191. t.Fatal(err)
  1192. }
  1193. tarWriter.Close()
  1194. tarOut.Close()
  1195. foo, err := os.Create(fooPath)
  1196. if err != nil {
  1197. t.Fatal(err)
  1198. }
  1199. defer foo.Close()
  1200. if _, err := foo.WriteString("test"); err != nil {
  1201. t.Fatal(err)
  1202. }
  1203. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1204. t.Fatal(err)
  1205. }
  1206. if _, err := os.Stat(nonExistingFile); err == nil || err != nil && !os.IsNotExist(err) {
  1207. t.Fatalf("%s shouldn't have been written and it shouldn't exist", nonExistingFile)
  1208. }
  1209. logDone("build - ADD must add files in container")
  1210. }
  1211. func TestBuildAddBadLinksVolume(t *testing.T) {
  1212. const (
  1213. dockerfileTemplate = `
  1214. FROM busybox
  1215. RUN ln -s /../../../../../../../../%s /x
  1216. VOLUME /x
  1217. ADD foo.txt /x/`
  1218. targetFile = "foo.txt"
  1219. )
  1220. var (
  1221. name = "test-link-absolute-volume"
  1222. dockerfile = ""
  1223. )
  1224. defer deleteImages(name)
  1225. tempDir, err := ioutil.TempDir("", "test-link-absolute-volume-temp-")
  1226. if err != nil {
  1227. t.Fatalf("failed to create temporary directory: %s", tempDir)
  1228. }
  1229. defer os.RemoveAll(tempDir)
  1230. dockerfile = fmt.Sprintf(dockerfileTemplate, tempDir)
  1231. nonExistingFile := filepath.Join(tempDir, targetFile)
  1232. ctx, err := fakeContext(dockerfile, nil)
  1233. if err != nil {
  1234. t.Fatal(err)
  1235. }
  1236. defer ctx.Close()
  1237. fooPath := filepath.Join(ctx.Dir, targetFile)
  1238. foo, err := os.Create(fooPath)
  1239. if err != nil {
  1240. t.Fatal(err)
  1241. }
  1242. defer foo.Close()
  1243. if _, err := foo.WriteString("test"); err != nil {
  1244. t.Fatal(err)
  1245. }
  1246. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1247. t.Fatal(err)
  1248. }
  1249. if _, err := os.Stat(nonExistingFile); err == nil || err != nil && !os.IsNotExist(err) {
  1250. t.Fatalf("%s shouldn't have been written and it shouldn't exist", nonExistingFile)
  1251. }
  1252. logDone("build - ADD should add files in volume")
  1253. }
  1254. // Issue #5270 - ensure we throw a better error than "unexpected EOF"
  1255. // when we can't access files in the context.
  1256. func TestBuildWithInaccessibleFilesInContext(t *testing.T) {
  1257. {
  1258. name := "testbuildinaccessiblefiles"
  1259. defer deleteImages(name)
  1260. ctx, err := fakeContext("FROM scratch\nADD . /foo/", map[string]string{"fileWithoutReadAccess": "foo"})
  1261. if err != nil {
  1262. t.Fatal(err)
  1263. }
  1264. defer ctx.Close()
  1265. // This is used to ensure we detect inaccessible files early during build in the cli client
  1266. pathToFileWithoutReadAccess := filepath.Join(ctx.Dir, "fileWithoutReadAccess")
  1267. if err = os.Chown(pathToFileWithoutReadAccess, 0, 0); err != nil {
  1268. t.Fatalf("failed to chown file to root: %s", err)
  1269. }
  1270. if err = os.Chmod(pathToFileWithoutReadAccess, 0700); err != nil {
  1271. t.Fatalf("failed to chmod file to 700: %s", err)
  1272. }
  1273. buildCmd := exec.Command("su", "unprivilegeduser", "-c", fmt.Sprintf("%s build -t %s .", dockerBinary, name))
  1274. buildCmd.Dir = ctx.Dir
  1275. out, _, err := runCommandWithOutput(buildCmd)
  1276. if err == nil {
  1277. t.Fatalf("build should have failed: %s %s", err, out)
  1278. }
  1279. // check if we've detected the failure before we started building
  1280. if !strings.Contains(out, "no permission to read from ") {
  1281. t.Fatalf("output should've contained the string: no permission to read from but contained: %s", out)
  1282. }
  1283. if !strings.Contains(out, "Error checking context is accessible") {
  1284. t.Fatalf("output should've contained the string: Error checking context is accessible")
  1285. }
  1286. }
  1287. {
  1288. name := "testbuildinaccessibledirectory"
  1289. defer deleteImages(name)
  1290. ctx, err := fakeContext("FROM scratch\nADD . /foo/", map[string]string{"directoryWeCantStat/bar": "foo"})
  1291. if err != nil {
  1292. t.Fatal(err)
  1293. }
  1294. defer ctx.Close()
  1295. // This is used to ensure we detect inaccessible directories early during build in the cli client
  1296. pathToDirectoryWithoutReadAccess := filepath.Join(ctx.Dir, "directoryWeCantStat")
  1297. pathToFileInDirectoryWithoutReadAccess := filepath.Join(pathToDirectoryWithoutReadAccess, "bar")
  1298. if err = os.Chown(pathToDirectoryWithoutReadAccess, 0, 0); err != nil {
  1299. t.Fatalf("failed to chown directory to root: %s", err)
  1300. }
  1301. if err = os.Chmod(pathToDirectoryWithoutReadAccess, 0444); err != nil {
  1302. t.Fatalf("failed to chmod directory to 755: %s", err)
  1303. }
  1304. if err = os.Chmod(pathToFileInDirectoryWithoutReadAccess, 0700); err != nil {
  1305. t.Fatalf("failed to chmod file to 444: %s", err)
  1306. }
  1307. buildCmd := exec.Command("su", "unprivilegeduser", "-c", fmt.Sprintf("%s build -t %s .", dockerBinary, name))
  1308. buildCmd.Dir = ctx.Dir
  1309. out, _, err := runCommandWithOutput(buildCmd)
  1310. if err == nil {
  1311. t.Fatalf("build should have failed: %s %s", err, out)
  1312. }
  1313. // check if we've detected the failure before we started building
  1314. if !strings.Contains(out, "can't stat") {
  1315. t.Fatalf("output should've contained the string: can't access %s", out)
  1316. }
  1317. if !strings.Contains(out, "Error checking context is accessible") {
  1318. t.Fatalf("output should've contained the string: Error checking context is accessible")
  1319. }
  1320. }
  1321. {
  1322. name := "testlinksok"
  1323. defer deleteImages(name)
  1324. ctx, err := fakeContext("FROM scratch\nADD . /foo/", nil)
  1325. if err != nil {
  1326. t.Fatal(err)
  1327. }
  1328. defer ctx.Close()
  1329. target := "../../../../../../../../../../../../../../../../../../../azA"
  1330. if err := os.Symlink(filepath.Join(ctx.Dir, "g"), target); err != nil {
  1331. t.Fatal(err)
  1332. }
  1333. defer os.Remove(target)
  1334. // This is used to ensure we don't follow links when checking if everything in the context is accessible
  1335. // This test doesn't require that we run commands as an unprivileged user
  1336. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  1337. t.Fatal(err)
  1338. }
  1339. }
  1340. {
  1341. name := "testbuildignoredinaccessible"
  1342. defer deleteImages(name)
  1343. ctx, err := fakeContext("FROM scratch\nADD . /foo/",
  1344. map[string]string{
  1345. "directoryWeCantStat/bar": "foo",
  1346. ".dockerignore": "directoryWeCantStat",
  1347. })
  1348. if err != nil {
  1349. t.Fatal(err)
  1350. }
  1351. defer ctx.Close()
  1352. // This is used to ensure we don't try to add inaccessible files when they are ignored by a .dockerignore pattern
  1353. pathToDirectoryWithoutReadAccess := filepath.Join(ctx.Dir, "directoryWeCantStat")
  1354. pathToFileInDirectoryWithoutReadAccess := filepath.Join(pathToDirectoryWithoutReadAccess, "bar")
  1355. if err = os.Chown(pathToDirectoryWithoutReadAccess, 0, 0); err != nil {
  1356. t.Fatalf("failed to chown directory to root: %s", err)
  1357. }
  1358. if err = os.Chmod(pathToDirectoryWithoutReadAccess, 0444); err != nil {
  1359. t.Fatalf("failed to chmod directory to 755: %s", err)
  1360. }
  1361. if err = os.Chmod(pathToFileInDirectoryWithoutReadAccess, 0700); err != nil {
  1362. t.Fatalf("failed to chmod file to 444: %s", err)
  1363. }
  1364. buildCmd := exec.Command("su", "unprivilegeduser", "-c", fmt.Sprintf("%s build -t %s .", dockerBinary, name))
  1365. buildCmd.Dir = ctx.Dir
  1366. if out, _, err := runCommandWithOutput(buildCmd); err != nil {
  1367. t.Fatalf("build should have worked: %s %s", err, out)
  1368. }
  1369. }
  1370. logDone("build - ADD from context with inaccessible files must fail")
  1371. logDone("build - ADD from context with accessible links must work")
  1372. logDone("build - ADD from context with ignored inaccessible files must work")
  1373. }
  1374. func TestBuildForceRm(t *testing.T) {
  1375. containerCountBefore, err := getContainerCount()
  1376. if err != nil {
  1377. t.Fatalf("failed to get the container count: %s", err)
  1378. }
  1379. name := "testbuildforcerm"
  1380. defer deleteImages(name)
  1381. ctx, err := fakeContext("FROM scratch\nRUN true\nRUN thiswillfail", nil)
  1382. if err != nil {
  1383. t.Fatal(err)
  1384. }
  1385. defer ctx.Close()
  1386. buildCmd := exec.Command(dockerBinary, "build", "-t", name, "--force-rm", ".")
  1387. buildCmd.Dir = ctx.Dir
  1388. if out, _, err := runCommandWithOutput(buildCmd); err == nil {
  1389. t.Fatalf("failed to build the image: %s, %v", out, err)
  1390. }
  1391. containerCountAfter, err := getContainerCount()
  1392. if err != nil {
  1393. t.Fatalf("failed to get the container count: %s", err)
  1394. }
  1395. if containerCountBefore != containerCountAfter {
  1396. t.Fatalf("--force-rm shouldn't have left containers behind")
  1397. }
  1398. logDone("build - ensure --force-rm doesn't leave containers behind")
  1399. }
  1400. func TestBuildRm(t *testing.T) {
  1401. name := "testbuildrm"
  1402. defer deleteImages(name)
  1403. ctx, err := fakeContext("FROM scratch\nADD foo /\nADD foo /", map[string]string{"foo": "bar"})
  1404. if err != nil {
  1405. t.Fatal(err)
  1406. }
  1407. defer ctx.Close()
  1408. {
  1409. containerCountBefore, err := getContainerCount()
  1410. if err != nil {
  1411. t.Fatalf("failed to get the container count: %s", err)
  1412. }
  1413. out, _, err := dockerCmdInDir(t, ctx.Dir, "build", "--rm", "-t", name, ".")
  1414. if err != nil {
  1415. t.Fatal("failed to build the image", out)
  1416. }
  1417. containerCountAfter, err := getContainerCount()
  1418. if err != nil {
  1419. t.Fatalf("failed to get the container count: %s", err)
  1420. }
  1421. if containerCountBefore != containerCountAfter {
  1422. t.Fatalf("-rm shouldn't have left containers behind")
  1423. }
  1424. deleteImages(name)
  1425. }
  1426. {
  1427. containerCountBefore, err := getContainerCount()
  1428. if err != nil {
  1429. t.Fatalf("failed to get the container count: %s", err)
  1430. }
  1431. out, _, err := dockerCmdInDir(t, ctx.Dir, "build", "-t", name, ".")
  1432. if err != nil {
  1433. t.Fatal("failed to build the image", out)
  1434. }
  1435. containerCountAfter, err := getContainerCount()
  1436. if err != nil {
  1437. t.Fatalf("failed to get the container count: %s", err)
  1438. }
  1439. if containerCountBefore != containerCountAfter {
  1440. t.Fatalf("--rm shouldn't have left containers behind")
  1441. }
  1442. deleteImages(name)
  1443. }
  1444. {
  1445. containerCountBefore, err := getContainerCount()
  1446. if err != nil {
  1447. t.Fatalf("failed to get the container count: %s", err)
  1448. }
  1449. out, _, err := dockerCmdInDir(t, ctx.Dir, "build", "--rm=false", "-t", name, ".")
  1450. if err != nil {
  1451. t.Fatal("failed to build the image", out)
  1452. }
  1453. containerCountAfter, err := getContainerCount()
  1454. if err != nil {
  1455. t.Fatalf("failed to get the container count: %s", err)
  1456. }
  1457. if containerCountBefore == containerCountAfter {
  1458. t.Fatalf("--rm=false should have left containers behind")
  1459. }
  1460. deleteAllContainers()
  1461. deleteImages(name)
  1462. }
  1463. logDone("build - ensure --rm doesn't leave containers behind and that --rm=true is the default")
  1464. logDone("build - ensure --rm=false overrides the default")
  1465. }
  1466. func TestBuildWithVolumes(t *testing.T) {
  1467. var (
  1468. result map[string]map[string]struct{}
  1469. name = "testbuildvolumes"
  1470. emptyMap = make(map[string]struct{})
  1471. expected = map[string]map[string]struct{}{
  1472. "/test1": emptyMap,
  1473. "/test2": emptyMap,
  1474. "/test3": emptyMap,
  1475. "/test4": emptyMap,
  1476. "/test5": emptyMap,
  1477. "/test6": emptyMap,
  1478. "[/test7": emptyMap,
  1479. "/test8]": emptyMap,
  1480. }
  1481. )
  1482. defer deleteImages(name)
  1483. _, err := buildImage(name,
  1484. `FROM scratch
  1485. VOLUME /test1
  1486. VOLUME /test2
  1487. VOLUME /test3 /test4
  1488. VOLUME ["/test5", "/test6"]
  1489. VOLUME [/test7 /test8]
  1490. `,
  1491. true)
  1492. if err != nil {
  1493. t.Fatal(err)
  1494. }
  1495. res, err := inspectFieldJSON(name, "Config.Volumes")
  1496. if err != nil {
  1497. t.Fatal(err)
  1498. }
  1499. err = unmarshalJSON([]byte(res), &result)
  1500. if err != nil {
  1501. t.Fatal(err)
  1502. }
  1503. equal := reflect.DeepEqual(&result, &expected)
  1504. if !equal {
  1505. t.Fatalf("Volumes %s, expected %s", result, expected)
  1506. }
  1507. logDone("build - with volumes")
  1508. }
  1509. func TestBuildMaintainer(t *testing.T) {
  1510. name := "testbuildmaintainer"
  1511. expected := "dockerio"
  1512. defer deleteImages(name)
  1513. _, err := buildImage(name,
  1514. `FROM scratch
  1515. MAINTAINER dockerio`,
  1516. true)
  1517. if err != nil {
  1518. t.Fatal(err)
  1519. }
  1520. res, err := inspectField(name, "Author")
  1521. if err != nil {
  1522. t.Fatal(err)
  1523. }
  1524. if res != expected {
  1525. t.Fatalf("Maintainer %s, expected %s", res, expected)
  1526. }
  1527. logDone("build - maintainer")
  1528. }
  1529. func TestBuildUser(t *testing.T) {
  1530. name := "testbuilduser"
  1531. expected := "dockerio"
  1532. defer deleteImages(name)
  1533. _, err := buildImage(name,
  1534. `FROM busybox
  1535. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1536. USER dockerio
  1537. RUN [ $(whoami) = 'dockerio' ]`,
  1538. true)
  1539. if err != nil {
  1540. t.Fatal(err)
  1541. }
  1542. res, err := inspectField(name, "Config.User")
  1543. if err != nil {
  1544. t.Fatal(err)
  1545. }
  1546. if res != expected {
  1547. t.Fatalf("User %s, expected %s", res, expected)
  1548. }
  1549. logDone("build - user")
  1550. }
  1551. func TestBuildRelativeWorkdir(t *testing.T) {
  1552. name := "testbuildrelativeworkdir"
  1553. expected := "/test2/test3"
  1554. defer deleteImages(name)
  1555. _, err := buildImage(name,
  1556. `FROM busybox
  1557. RUN [ "$PWD" = '/' ]
  1558. WORKDIR test1
  1559. RUN [ "$PWD" = '/test1' ]
  1560. WORKDIR /test2
  1561. RUN [ "$PWD" = '/test2' ]
  1562. WORKDIR test3
  1563. RUN [ "$PWD" = '/test2/test3' ]`,
  1564. true)
  1565. if err != nil {
  1566. t.Fatal(err)
  1567. }
  1568. res, err := inspectField(name, "Config.WorkingDir")
  1569. if err != nil {
  1570. t.Fatal(err)
  1571. }
  1572. if res != expected {
  1573. t.Fatalf("Workdir %s, expected %s", res, expected)
  1574. }
  1575. logDone("build - relative workdir")
  1576. }
  1577. func TestBuildWorkdirWithEnvVariables(t *testing.T) {
  1578. name := "testbuildworkdirwithenvvariables"
  1579. expected := "/test1/test2/$MISSING_VAR"
  1580. defer deleteImages(name)
  1581. _, err := buildImage(name,
  1582. `FROM busybox
  1583. ENV DIRPATH /test1
  1584. ENV SUBDIRNAME test2
  1585. WORKDIR $DIRPATH
  1586. WORKDIR $SUBDIRNAME/$MISSING_VAR`,
  1587. true)
  1588. if err != nil {
  1589. t.Fatal(err)
  1590. }
  1591. res, err := inspectField(name, "Config.WorkingDir")
  1592. if err != nil {
  1593. t.Fatal(err)
  1594. }
  1595. if res != expected {
  1596. t.Fatalf("Workdir %s, expected %s", res, expected)
  1597. }
  1598. logDone("build - workdir with env variables")
  1599. }
  1600. func TestBuildRelativeCopy(t *testing.T) {
  1601. name := "testbuildrelativecopy"
  1602. defer deleteImages(name)
  1603. dockerfile := `
  1604. FROM busybox
  1605. WORKDIR /test1
  1606. WORKDIR test2
  1607. RUN [ "$PWD" = '/test1/test2' ]
  1608. COPY foo ./
  1609. RUN [ "$(cat /test1/test2/foo)" = 'hello' ]
  1610. ADD foo ./bar/baz
  1611. RUN [ "$(cat /test1/test2/bar/baz)" = 'hello' ]
  1612. COPY foo ./bar/baz2
  1613. RUN [ "$(cat /test1/test2/bar/baz2)" = 'hello' ]
  1614. WORKDIR ..
  1615. COPY foo ./
  1616. RUN [ "$(cat /test1/foo)" = 'hello' ]
  1617. COPY foo /test3/
  1618. RUN [ "$(cat /test3/foo)" = 'hello' ]
  1619. WORKDIR /test4
  1620. COPY . .
  1621. RUN [ "$(cat /test4/foo)" = 'hello' ]
  1622. WORKDIR /test5/test6
  1623. COPY foo ../
  1624. RUN [ "$(cat /test5/foo)" = 'hello' ]
  1625. `
  1626. ctx, err := fakeContext(dockerfile, map[string]string{
  1627. "foo": "hello",
  1628. })
  1629. defer ctx.Close()
  1630. if err != nil {
  1631. t.Fatal(err)
  1632. }
  1633. _, err = buildImageFromContext(name, ctx, false)
  1634. if err != nil {
  1635. t.Fatal(err)
  1636. }
  1637. logDone("build - relative copy/add")
  1638. }
  1639. func TestBuildEnv(t *testing.T) {
  1640. name := "testbuildenv"
  1641. expected := "[PATH=/test:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin PORT=2375]"
  1642. defer deleteImages(name)
  1643. _, err := buildImage(name,
  1644. `FROM busybox
  1645. ENV PATH /test:$PATH
  1646. ENV PORT 2375
  1647. RUN [ $(env | grep PORT) = 'PORT=2375' ]`,
  1648. true)
  1649. if err != nil {
  1650. t.Fatal(err)
  1651. }
  1652. res, err := inspectField(name, "Config.Env")
  1653. if err != nil {
  1654. t.Fatal(err)
  1655. }
  1656. if res != expected {
  1657. t.Fatalf("Env %s, expected %s", res, expected)
  1658. }
  1659. logDone("build - env")
  1660. }
  1661. func TestBuildContextCleanup(t *testing.T) {
  1662. name := "testbuildcontextcleanup"
  1663. defer deleteImages(name)
  1664. entries, err := ioutil.ReadDir("/var/lib/docker/tmp")
  1665. if err != nil {
  1666. t.Fatalf("failed to list contents of tmp dir: %s", err)
  1667. }
  1668. _, err = buildImage(name,
  1669. `FROM scratch
  1670. ENTRYPOINT ["/bin/echo"]`,
  1671. true)
  1672. if err != nil {
  1673. t.Fatal(err)
  1674. }
  1675. entriesFinal, err := ioutil.ReadDir("/var/lib/docker/tmp")
  1676. if err != nil {
  1677. t.Fatalf("failed to list contents of tmp dir: %s", err)
  1678. }
  1679. if err = compareDirectoryEntries(entries, entriesFinal); err != nil {
  1680. t.Fatalf("context should have been deleted, but wasn't")
  1681. }
  1682. logDone("build - verify context cleanup works properly")
  1683. }
  1684. func TestBuildContextCleanupFailedBuild(t *testing.T) {
  1685. name := "testbuildcontextcleanup"
  1686. defer deleteImages(name)
  1687. defer deleteAllContainers()
  1688. entries, err := ioutil.ReadDir("/var/lib/docker/tmp")
  1689. if err != nil {
  1690. t.Fatalf("failed to list contents of tmp dir: %s", err)
  1691. }
  1692. _, err = buildImage(name,
  1693. `FROM scratch
  1694. RUN /non/existing/command`,
  1695. true)
  1696. if err == nil {
  1697. t.Fatalf("expected build to fail, but it didn't")
  1698. }
  1699. entriesFinal, err := ioutil.ReadDir("/var/lib/docker/tmp")
  1700. if err != nil {
  1701. t.Fatalf("failed to list contents of tmp dir: %s", err)
  1702. }
  1703. if err = compareDirectoryEntries(entries, entriesFinal); err != nil {
  1704. t.Fatalf("context should have been deleted, but wasn't")
  1705. }
  1706. logDone("build - verify context cleanup works properly after a failed build")
  1707. }
  1708. func TestBuildCmd(t *testing.T) {
  1709. name := "testbuildcmd"
  1710. expected := "[/bin/echo Hello World]"
  1711. defer deleteImages(name)
  1712. _, err := buildImage(name,
  1713. `FROM scratch
  1714. CMD ["/bin/echo", "Hello World"]`,
  1715. true)
  1716. if err != nil {
  1717. t.Fatal(err)
  1718. }
  1719. res, err := inspectField(name, "Config.Cmd")
  1720. if err != nil {
  1721. t.Fatal(err)
  1722. }
  1723. if res != expected {
  1724. t.Fatalf("Cmd %s, expected %s", res, expected)
  1725. }
  1726. logDone("build - cmd")
  1727. }
  1728. func TestBuildExpose(t *testing.T) {
  1729. name := "testbuildexpose"
  1730. expected := "map[2375/tcp:map[]]"
  1731. defer deleteImages(name)
  1732. _, err := buildImage(name,
  1733. `FROM scratch
  1734. EXPOSE 2375`,
  1735. true)
  1736. if err != nil {
  1737. t.Fatal(err)
  1738. }
  1739. res, err := inspectField(name, "Config.ExposedPorts")
  1740. if err != nil {
  1741. t.Fatal(err)
  1742. }
  1743. if res != expected {
  1744. t.Fatalf("Exposed ports %s, expected %s", res, expected)
  1745. }
  1746. logDone("build - expose")
  1747. }
  1748. func TestBuildExposeMorePorts(t *testing.T) {
  1749. // start building docker file with a large number of ports
  1750. portList := make([]string, 50)
  1751. line := make([]string, 100)
  1752. expectedPorts := make([]int, len(portList)*len(line))
  1753. for i := 0; i < len(portList); i++ {
  1754. for j := 0; j < len(line); j++ {
  1755. p := i*len(line) + j + 1
  1756. line[j] = strconv.Itoa(p)
  1757. expectedPorts[p-1] = p
  1758. }
  1759. if i == len(portList)-1 {
  1760. portList[i] = strings.Join(line, " ")
  1761. } else {
  1762. portList[i] = strings.Join(line, " ") + ` \`
  1763. }
  1764. }
  1765. dockerfile := `FROM scratch
  1766. EXPOSE {{range .}} {{.}}
  1767. {{end}}`
  1768. tmpl := template.Must(template.New("dockerfile").Parse(dockerfile))
  1769. buf := bytes.NewBuffer(nil)
  1770. tmpl.Execute(buf, portList)
  1771. name := "testbuildexpose"
  1772. defer deleteImages(name)
  1773. _, err := buildImage(name, buf.String(), true)
  1774. if err != nil {
  1775. t.Fatal(err)
  1776. }
  1777. // check if all the ports are saved inside Config.ExposedPorts
  1778. res, err := inspectFieldJSON(name, "Config.ExposedPorts")
  1779. if err != nil {
  1780. t.Fatal(err)
  1781. }
  1782. var exposedPorts map[string]interface{}
  1783. if err := json.Unmarshal([]byte(res), &exposedPorts); err != nil {
  1784. t.Fatal(err)
  1785. }
  1786. for _, p := range expectedPorts {
  1787. ep := fmt.Sprintf("%d/tcp", p)
  1788. if _, ok := exposedPorts[ep]; !ok {
  1789. t.Errorf("Port(%s) is not exposed", ep)
  1790. } else {
  1791. delete(exposedPorts, ep)
  1792. }
  1793. }
  1794. if len(exposedPorts) != 0 {
  1795. t.Errorf("Unexpected extra exposed ports %v", exposedPorts)
  1796. }
  1797. logDone("build - expose large number of ports")
  1798. }
  1799. func TestBuildExposeOrder(t *testing.T) {
  1800. buildID := func(name, exposed string) string {
  1801. _, err := buildImage(name, fmt.Sprintf(`FROM scratch
  1802. EXPOSE %s`, exposed), true)
  1803. if err != nil {
  1804. t.Fatal(err)
  1805. }
  1806. id, err := inspectField(name, "Id")
  1807. if err != nil {
  1808. t.Fatal(err)
  1809. }
  1810. return id
  1811. }
  1812. id1 := buildID("testbuildexpose1", "80 2375")
  1813. id2 := buildID("testbuildexpose2", "2375 80")
  1814. defer deleteImages("testbuildexpose1", "testbuildexpose2")
  1815. if id1 != id2 {
  1816. t.Errorf("EXPOSE should invalidate the cache only when ports actually changed")
  1817. }
  1818. logDone("build - expose order")
  1819. }
  1820. func TestBuildEmptyEntrypointInheritance(t *testing.T) {
  1821. name := "testbuildentrypointinheritance"
  1822. name2 := "testbuildentrypointinheritance2"
  1823. defer deleteImages(name, name2)
  1824. _, err := buildImage(name,
  1825. `FROM busybox
  1826. ENTRYPOINT ["/bin/echo"]`,
  1827. true)
  1828. if err != nil {
  1829. t.Fatal(err)
  1830. }
  1831. res, err := inspectField(name, "Config.Entrypoint")
  1832. if err != nil {
  1833. t.Fatal(err)
  1834. }
  1835. expected := "[/bin/echo]"
  1836. if res != expected {
  1837. t.Fatalf("Entrypoint %s, expected %s", res, expected)
  1838. }
  1839. _, err = buildImage(name2,
  1840. fmt.Sprintf(`FROM %s
  1841. ENTRYPOINT []`, name),
  1842. true)
  1843. if err != nil {
  1844. t.Fatal(err)
  1845. }
  1846. res, err = inspectField(name2, "Config.Entrypoint")
  1847. if err != nil {
  1848. t.Fatal(err)
  1849. }
  1850. expected = "[]"
  1851. if res != expected {
  1852. t.Fatalf("Entrypoint %s, expected %s", res, expected)
  1853. }
  1854. logDone("build - empty entrypoint inheritance")
  1855. }
  1856. func TestBuildEmptyEntrypoint(t *testing.T) {
  1857. name := "testbuildentrypoint"
  1858. defer deleteImages(name)
  1859. expected := "[]"
  1860. _, err := buildImage(name,
  1861. `FROM busybox
  1862. ENTRYPOINT []`,
  1863. true)
  1864. if err != nil {
  1865. t.Fatal(err)
  1866. }
  1867. res, err := inspectField(name, "Config.Entrypoint")
  1868. if err != nil {
  1869. t.Fatal(err)
  1870. }
  1871. if res != expected {
  1872. t.Fatalf("Entrypoint %s, expected %s", res, expected)
  1873. }
  1874. logDone("build - empty entrypoint")
  1875. }
  1876. func TestBuildEntrypoint(t *testing.T) {
  1877. name := "testbuildentrypoint"
  1878. expected := "[/bin/echo]"
  1879. defer deleteImages(name)
  1880. _, err := buildImage(name,
  1881. `FROM scratch
  1882. ENTRYPOINT ["/bin/echo"]`,
  1883. true)
  1884. if err != nil {
  1885. t.Fatal(err)
  1886. }
  1887. res, err := inspectField(name, "Config.Entrypoint")
  1888. if err != nil {
  1889. t.Fatal(err)
  1890. }
  1891. if res != expected {
  1892. t.Fatalf("Entrypoint %s, expected %s", res, expected)
  1893. }
  1894. logDone("build - entrypoint")
  1895. }
  1896. // #6445 ensure ONBUILD triggers aren't committed to grandchildren
  1897. func TestBuildOnBuildLimitedInheritence(t *testing.T) {
  1898. var (
  1899. out2, out3 string
  1900. )
  1901. {
  1902. name1 := "testonbuildtrigger1"
  1903. dockerfile1 := `
  1904. FROM busybox
  1905. RUN echo "GRANDPARENT"
  1906. ONBUILD RUN echo "ONBUILD PARENT"
  1907. `
  1908. ctx, err := fakeContext(dockerfile1, nil)
  1909. if err != nil {
  1910. t.Fatal(err)
  1911. }
  1912. defer ctx.Close()
  1913. out1, _, err := dockerCmdInDir(t, ctx.Dir, "build", "-t", name1, ".")
  1914. if err != nil {
  1915. t.Fatalf("build failed to complete: %s, %v", out1, err)
  1916. }
  1917. defer deleteImages(name1)
  1918. }
  1919. {
  1920. name2 := "testonbuildtrigger2"
  1921. dockerfile2 := `
  1922. FROM testonbuildtrigger1
  1923. `
  1924. ctx, err := fakeContext(dockerfile2, nil)
  1925. if err != nil {
  1926. t.Fatal(err)
  1927. }
  1928. defer ctx.Close()
  1929. out2, _, err = dockerCmdInDir(t, ctx.Dir, "build", "-t", name2, ".")
  1930. if err != nil {
  1931. t.Fatalf("build failed to complete: %s, %v", out2, err)
  1932. }
  1933. defer deleteImages(name2)
  1934. }
  1935. {
  1936. name3 := "testonbuildtrigger3"
  1937. dockerfile3 := `
  1938. FROM testonbuildtrigger2
  1939. `
  1940. ctx, err := fakeContext(dockerfile3, nil)
  1941. if err != nil {
  1942. t.Fatal(err)
  1943. }
  1944. defer ctx.Close()
  1945. out3, _, err = dockerCmdInDir(t, ctx.Dir, "build", "-t", name3, ".")
  1946. if err != nil {
  1947. t.Fatalf("build failed to complete: %s, %v", out3, err)
  1948. }
  1949. defer deleteImages(name3)
  1950. }
  1951. // ONBUILD should be run in second build.
  1952. if !strings.Contains(out2, "ONBUILD PARENT") {
  1953. t.Fatalf("ONBUILD instruction did not run in child of ONBUILD parent")
  1954. }
  1955. // ONBUILD should *not* be run in third build.
  1956. if strings.Contains(out3, "ONBUILD PARENT") {
  1957. t.Fatalf("ONBUILD instruction ran in grandchild of ONBUILD parent")
  1958. }
  1959. logDone("build - onbuild")
  1960. }
  1961. func TestBuildWithCache(t *testing.T) {
  1962. name := "testbuildwithcache"
  1963. defer deleteImages(name)
  1964. id1, err := buildImage(name,
  1965. `FROM scratch
  1966. MAINTAINER dockerio
  1967. EXPOSE 5432
  1968. ENTRYPOINT ["/bin/echo"]`,
  1969. true)
  1970. if err != nil {
  1971. t.Fatal(err)
  1972. }
  1973. id2, err := buildImage(name,
  1974. `FROM scratch
  1975. MAINTAINER dockerio
  1976. EXPOSE 5432
  1977. ENTRYPOINT ["/bin/echo"]`,
  1978. true)
  1979. if err != nil {
  1980. t.Fatal(err)
  1981. }
  1982. if id1 != id2 {
  1983. t.Fatal("The cache should have been used but hasn't.")
  1984. }
  1985. logDone("build - with cache")
  1986. }
  1987. func TestBuildWithoutCache(t *testing.T) {
  1988. name := "testbuildwithoutcache"
  1989. name2 := "testbuildwithoutcache2"
  1990. defer deleteImages(name, name2)
  1991. id1, err := buildImage(name,
  1992. `FROM scratch
  1993. MAINTAINER dockerio
  1994. EXPOSE 5432
  1995. ENTRYPOINT ["/bin/echo"]`,
  1996. true)
  1997. if err != nil {
  1998. t.Fatal(err)
  1999. }
  2000. id2, err := buildImage(name2,
  2001. `FROM scratch
  2002. MAINTAINER dockerio
  2003. EXPOSE 5432
  2004. ENTRYPOINT ["/bin/echo"]`,
  2005. false)
  2006. if err != nil {
  2007. t.Fatal(err)
  2008. }
  2009. if id1 == id2 {
  2010. t.Fatal("The cache should have been invalided but hasn't.")
  2011. }
  2012. logDone("build - without cache")
  2013. }
  2014. func TestBuildConditionalCache(t *testing.T) {
  2015. name := "testbuildconditionalcache"
  2016. name2 := "testbuildconditionalcache2"
  2017. defer deleteImages(name, name2)
  2018. dockerfile := `
  2019. FROM busybox
  2020. ADD foo /tmp/`
  2021. ctx, err := fakeContext(dockerfile, map[string]string{
  2022. "foo": "hello",
  2023. })
  2024. id1, err := buildImageFromContext(name, ctx, true)
  2025. if err != nil {
  2026. t.Fatalf("Error building #1: %s", err)
  2027. }
  2028. if err := ctx.Add("foo", "bye"); err != nil {
  2029. t.Fatalf("Error modifying foo: %s", err)
  2030. }
  2031. id2, err := buildImageFromContext(name, ctx, false)
  2032. if err != nil {
  2033. t.Fatalf("Error building #2: %s", err)
  2034. }
  2035. if id2 == id1 {
  2036. t.Fatal("Should not have used the cache")
  2037. }
  2038. id3, err := buildImageFromContext(name, ctx, true)
  2039. if err != nil {
  2040. t.Fatalf("Error building #3: %s", err)
  2041. }
  2042. if id3 != id2 {
  2043. t.Fatal("Should have used the cache")
  2044. }
  2045. logDone("build - conditional cache")
  2046. }
  2047. func TestBuildADDLocalFileWithCache(t *testing.T) {
  2048. name := "testbuildaddlocalfilewithcache"
  2049. name2 := "testbuildaddlocalfilewithcache2"
  2050. defer deleteImages(name, name2)
  2051. dockerfile := `
  2052. FROM busybox
  2053. MAINTAINER dockerio
  2054. ADD foo /usr/lib/bla/bar
  2055. RUN [ "$(cat /usr/lib/bla/bar)" = "hello" ]`
  2056. ctx, err := fakeContext(dockerfile, map[string]string{
  2057. "foo": "hello",
  2058. })
  2059. defer ctx.Close()
  2060. if err != nil {
  2061. t.Fatal(err)
  2062. }
  2063. id1, err := buildImageFromContext(name, ctx, true)
  2064. if err != nil {
  2065. t.Fatal(err)
  2066. }
  2067. id2, err := buildImageFromContext(name2, ctx, true)
  2068. if err != nil {
  2069. t.Fatal(err)
  2070. }
  2071. if id1 != id2 {
  2072. t.Fatal("The cache should have been used but hasn't.")
  2073. }
  2074. logDone("build - add local file with cache")
  2075. }
  2076. func TestBuildADDMultipleLocalFileWithCache(t *testing.T) {
  2077. name := "testbuildaddmultiplelocalfilewithcache"
  2078. name2 := "testbuildaddmultiplelocalfilewithcache2"
  2079. defer deleteImages(name, name2)
  2080. dockerfile := `
  2081. FROM busybox
  2082. MAINTAINER dockerio
  2083. ADD foo Dockerfile /usr/lib/bla/
  2084. RUN [ "$(cat /usr/lib/bla/foo)" = "hello" ]`
  2085. ctx, err := fakeContext(dockerfile, map[string]string{
  2086. "foo": "hello",
  2087. })
  2088. defer ctx.Close()
  2089. if err != nil {
  2090. t.Fatal(err)
  2091. }
  2092. id1, err := buildImageFromContext(name, ctx, true)
  2093. if err != nil {
  2094. t.Fatal(err)
  2095. }
  2096. id2, err := buildImageFromContext(name2, ctx, true)
  2097. if err != nil {
  2098. t.Fatal(err)
  2099. }
  2100. if id1 != id2 {
  2101. t.Fatal("The cache should have been used but hasn't.")
  2102. }
  2103. logDone("build - add multiple local files with cache")
  2104. }
  2105. func TestBuildADDLocalFileWithoutCache(t *testing.T) {
  2106. name := "testbuildaddlocalfilewithoutcache"
  2107. name2 := "testbuildaddlocalfilewithoutcache2"
  2108. defer deleteImages(name, name2)
  2109. dockerfile := `
  2110. FROM busybox
  2111. MAINTAINER dockerio
  2112. ADD foo /usr/lib/bla/bar
  2113. RUN [ "$(cat /usr/lib/bla/bar)" = "hello" ]`
  2114. ctx, err := fakeContext(dockerfile, map[string]string{
  2115. "foo": "hello",
  2116. })
  2117. defer ctx.Close()
  2118. if err != nil {
  2119. t.Fatal(err)
  2120. }
  2121. id1, err := buildImageFromContext(name, ctx, true)
  2122. if err != nil {
  2123. t.Fatal(err)
  2124. }
  2125. id2, err := buildImageFromContext(name2, ctx, false)
  2126. if err != nil {
  2127. t.Fatal(err)
  2128. }
  2129. if id1 == id2 {
  2130. t.Fatal("The cache should have been invalided but hasn't.")
  2131. }
  2132. logDone("build - add local file without cache")
  2133. }
  2134. func TestBuildCopyDirButNotFile(t *testing.T) {
  2135. name := "testbuildcopydirbutnotfile"
  2136. name2 := "testbuildcopydirbutnotfile2"
  2137. defer deleteImages(name, name2)
  2138. dockerfile := `
  2139. FROM scratch
  2140. COPY dir /tmp/`
  2141. ctx, err := fakeContext(dockerfile, map[string]string{
  2142. "dir/foo": "hello",
  2143. })
  2144. defer ctx.Close()
  2145. if err != nil {
  2146. t.Fatal(err)
  2147. }
  2148. id1, err := buildImageFromContext(name, ctx, true)
  2149. if err != nil {
  2150. t.Fatal(err)
  2151. }
  2152. // Check that adding file with similar name doesn't mess with cache
  2153. if err := ctx.Add("dir_file", "hello2"); err != nil {
  2154. t.Fatal(err)
  2155. }
  2156. id2, err := buildImageFromContext(name2, ctx, true)
  2157. if err != nil {
  2158. t.Fatal(err)
  2159. }
  2160. if id1 != id2 {
  2161. t.Fatal("The cache should have been used but wasn't")
  2162. }
  2163. logDone("build - add current directory but not file")
  2164. }
  2165. func TestBuildADDCurrentDirWithCache(t *testing.T) {
  2166. name := "testbuildaddcurrentdirwithcache"
  2167. name2 := name + "2"
  2168. name3 := name + "3"
  2169. name4 := name + "4"
  2170. name5 := name + "5"
  2171. defer deleteImages(name, name2, name3, name4, name5)
  2172. dockerfile := `
  2173. FROM scratch
  2174. MAINTAINER dockerio
  2175. ADD . /usr/lib/bla`
  2176. ctx, err := fakeContext(dockerfile, map[string]string{
  2177. "foo": "hello",
  2178. })
  2179. defer ctx.Close()
  2180. if err != nil {
  2181. t.Fatal(err)
  2182. }
  2183. id1, err := buildImageFromContext(name, ctx, true)
  2184. if err != nil {
  2185. t.Fatal(err)
  2186. }
  2187. // Check that adding file invalidate cache of "ADD ."
  2188. if err := ctx.Add("bar", "hello2"); err != nil {
  2189. t.Fatal(err)
  2190. }
  2191. id2, err := buildImageFromContext(name2, ctx, true)
  2192. if err != nil {
  2193. t.Fatal(err)
  2194. }
  2195. if id1 == id2 {
  2196. t.Fatal("The cache should have been invalided but hasn't.")
  2197. }
  2198. // Check that changing file invalidate cache of "ADD ."
  2199. if err := ctx.Add("foo", "hello1"); err != nil {
  2200. t.Fatal(err)
  2201. }
  2202. id3, err := buildImageFromContext(name3, ctx, true)
  2203. if err != nil {
  2204. t.Fatal(err)
  2205. }
  2206. if id2 == id3 {
  2207. t.Fatal("The cache should have been invalided but hasn't.")
  2208. }
  2209. // Check that changing file to same content invalidate cache of "ADD ."
  2210. time.Sleep(1 * time.Second) // wait second because of mtime precision
  2211. if err := ctx.Add("foo", "hello1"); err != nil {
  2212. t.Fatal(err)
  2213. }
  2214. id4, err := buildImageFromContext(name4, ctx, true)
  2215. if err != nil {
  2216. t.Fatal(err)
  2217. }
  2218. if id3 == id4 {
  2219. t.Fatal("The cache should have been invalided but hasn't.")
  2220. }
  2221. id5, err := buildImageFromContext(name5, ctx, true)
  2222. if err != nil {
  2223. t.Fatal(err)
  2224. }
  2225. if id4 != id5 {
  2226. t.Fatal("The cache should have been used but hasn't.")
  2227. }
  2228. logDone("build - add current directory with cache")
  2229. }
  2230. func TestBuildADDCurrentDirWithoutCache(t *testing.T) {
  2231. name := "testbuildaddcurrentdirwithoutcache"
  2232. name2 := "testbuildaddcurrentdirwithoutcache2"
  2233. defer deleteImages(name, name2)
  2234. dockerfile := `
  2235. FROM scratch
  2236. MAINTAINER dockerio
  2237. ADD . /usr/lib/bla`
  2238. ctx, err := fakeContext(dockerfile, map[string]string{
  2239. "foo": "hello",
  2240. })
  2241. defer ctx.Close()
  2242. if err != nil {
  2243. t.Fatal(err)
  2244. }
  2245. id1, err := buildImageFromContext(name, ctx, true)
  2246. if err != nil {
  2247. t.Fatal(err)
  2248. }
  2249. id2, err := buildImageFromContext(name2, ctx, false)
  2250. if err != nil {
  2251. t.Fatal(err)
  2252. }
  2253. if id1 == id2 {
  2254. t.Fatal("The cache should have been invalided but hasn't.")
  2255. }
  2256. logDone("build - add current directory without cache")
  2257. }
  2258. func TestBuildADDRemoteFileWithCache(t *testing.T) {
  2259. name := "testbuildaddremotefilewithcache"
  2260. defer deleteImages(name)
  2261. server, err := fakeStorage(map[string]string{
  2262. "baz": "hello",
  2263. })
  2264. if err != nil {
  2265. t.Fatal(err)
  2266. }
  2267. defer server.Close()
  2268. id1, err := buildImage(name,
  2269. fmt.Sprintf(`FROM scratch
  2270. MAINTAINER dockerio
  2271. ADD %s/baz /usr/lib/baz/quux`, server.URL),
  2272. true)
  2273. if err != nil {
  2274. t.Fatal(err)
  2275. }
  2276. id2, err := buildImage(name,
  2277. fmt.Sprintf(`FROM scratch
  2278. MAINTAINER dockerio
  2279. ADD %s/baz /usr/lib/baz/quux`, server.URL),
  2280. true)
  2281. if err != nil {
  2282. t.Fatal(err)
  2283. }
  2284. if id1 != id2 {
  2285. t.Fatal("The cache should have been used but hasn't.")
  2286. }
  2287. logDone("build - add remote file with cache")
  2288. }
  2289. func TestBuildADDRemoteFileWithoutCache(t *testing.T) {
  2290. name := "testbuildaddremotefilewithoutcache"
  2291. name2 := "testbuildaddremotefilewithoutcache2"
  2292. defer deleteImages(name, name2)
  2293. server, err := fakeStorage(map[string]string{
  2294. "baz": "hello",
  2295. })
  2296. if err != nil {
  2297. t.Fatal(err)
  2298. }
  2299. defer server.Close()
  2300. id1, err := buildImage(name,
  2301. fmt.Sprintf(`FROM scratch
  2302. MAINTAINER dockerio
  2303. ADD %s/baz /usr/lib/baz/quux`, server.URL),
  2304. true)
  2305. if err != nil {
  2306. t.Fatal(err)
  2307. }
  2308. id2, err := buildImage(name2,
  2309. fmt.Sprintf(`FROM scratch
  2310. MAINTAINER dockerio
  2311. ADD %s/baz /usr/lib/baz/quux`, server.URL),
  2312. false)
  2313. if err != nil {
  2314. t.Fatal(err)
  2315. }
  2316. if id1 == id2 {
  2317. t.Fatal("The cache should have been invalided but hasn't.")
  2318. }
  2319. logDone("build - add remote file without cache")
  2320. }
  2321. func TestBuildADDRemoteFileMTime(t *testing.T) {
  2322. name := "testbuildaddremotefilemtime"
  2323. name2 := name + "2"
  2324. name3 := name + "3"
  2325. name4 := name + "4"
  2326. defer deleteImages(name, name2, name3, name4)
  2327. server, err := fakeStorage(map[string]string{"baz": "hello"})
  2328. if err != nil {
  2329. t.Fatal(err)
  2330. }
  2331. defer server.Close()
  2332. ctx, err := fakeContext(fmt.Sprintf(`FROM scratch
  2333. MAINTAINER dockerio
  2334. ADD %s/baz /usr/lib/baz/quux`, server.URL), nil)
  2335. if err != nil {
  2336. t.Fatal(err)
  2337. }
  2338. defer ctx.Close()
  2339. id1, err := buildImageFromContext(name, ctx, true)
  2340. if err != nil {
  2341. t.Fatal(err)
  2342. }
  2343. id2, err := buildImageFromContext(name2, ctx, true)
  2344. if err != nil {
  2345. t.Fatal(err)
  2346. }
  2347. if id1 != id2 {
  2348. t.Fatal("The cache should have been used but wasn't - #1")
  2349. }
  2350. // Now set baz's times to anything else and redo the build
  2351. // This time the cache should not be used
  2352. bazPath := path.Join(server.FakeContext.Dir, "baz")
  2353. err = syscall.UtimesNano(bazPath, make([]syscall.Timespec, 2))
  2354. if err != nil {
  2355. t.Fatalf("Error setting mtime on %q: %v", bazPath, err)
  2356. }
  2357. id3, err := buildImageFromContext(name3, ctx, true)
  2358. if err != nil {
  2359. t.Fatal(err)
  2360. }
  2361. if id1 == id3 {
  2362. t.Fatal("The cache should not have been used but was")
  2363. }
  2364. // And for good measure do it again and make sure cache is used this time
  2365. id4, err := buildImageFromContext(name4, ctx, true)
  2366. if err != nil {
  2367. t.Fatal(err)
  2368. }
  2369. if id3 != id4 {
  2370. t.Fatal("The cache should have been used but wasn't - #2")
  2371. }
  2372. logDone("build - add remote file testing mtime")
  2373. }
  2374. func TestBuildADDLocalAndRemoteFilesWithCache(t *testing.T) {
  2375. name := "testbuildaddlocalandremotefilewithcache"
  2376. defer deleteImages(name)
  2377. server, err := fakeStorage(map[string]string{
  2378. "baz": "hello",
  2379. })
  2380. if err != nil {
  2381. t.Fatal(err)
  2382. }
  2383. defer server.Close()
  2384. ctx, err := fakeContext(fmt.Sprintf(`FROM scratch
  2385. MAINTAINER dockerio
  2386. ADD foo /usr/lib/bla/bar
  2387. ADD %s/baz /usr/lib/baz/quux`, server.URL),
  2388. map[string]string{
  2389. "foo": "hello world",
  2390. })
  2391. if err != nil {
  2392. t.Fatal(err)
  2393. }
  2394. defer ctx.Close()
  2395. id1, err := buildImageFromContext(name, ctx, true)
  2396. if err != nil {
  2397. t.Fatal(err)
  2398. }
  2399. id2, err := buildImageFromContext(name, ctx, true)
  2400. if err != nil {
  2401. t.Fatal(err)
  2402. }
  2403. if id1 != id2 {
  2404. t.Fatal("The cache should have been used but hasn't.")
  2405. }
  2406. logDone("build - add local and remote file with cache")
  2407. }
  2408. func testContextTar(t *testing.T, compression archive.Compression) {
  2409. ctx, err := fakeContext(
  2410. `FROM busybox
  2411. ADD foo /foo
  2412. CMD ["cat", "/foo"]`,
  2413. map[string]string{
  2414. "foo": "bar",
  2415. },
  2416. )
  2417. defer ctx.Close()
  2418. if err != nil {
  2419. t.Fatal(err)
  2420. }
  2421. context, err := archive.Tar(ctx.Dir, compression)
  2422. if err != nil {
  2423. t.Fatalf("failed to build context tar: %v", err)
  2424. }
  2425. name := "contexttar"
  2426. buildCmd := exec.Command(dockerBinary, "build", "-t", name, "-")
  2427. defer deleteImages(name)
  2428. buildCmd.Stdin = context
  2429. if out, _, err := runCommandWithOutput(buildCmd); err != nil {
  2430. t.Fatalf("build failed to complete: %v %v", out, err)
  2431. }
  2432. logDone(fmt.Sprintf("build - build an image with a context tar, compression: %v", compression))
  2433. }
  2434. func TestBuildContextTarGzip(t *testing.T) {
  2435. testContextTar(t, archive.Gzip)
  2436. }
  2437. func TestBuildContextTarNoCompression(t *testing.T) {
  2438. testContextTar(t, archive.Uncompressed)
  2439. }
  2440. func TestBuildNoContext(t *testing.T) {
  2441. buildCmd := exec.Command(dockerBinary, "build", "-t", "nocontext", "-")
  2442. buildCmd.Stdin = strings.NewReader("FROM busybox\nCMD echo ok\n")
  2443. if out, _, err := runCommandWithOutput(buildCmd); err != nil {
  2444. t.Fatalf("build failed to complete: %v %v", out, err)
  2445. }
  2446. if out, _, err := dockerCmd(t, "run", "--rm", "nocontext"); out != "ok\n" || err != nil {
  2447. t.Fatalf("run produced invalid output: %q, expected %q", out, "ok")
  2448. }
  2449. deleteImages("nocontext")
  2450. logDone("build - build an image with no context")
  2451. }
  2452. // TODO: TestCaching
  2453. func TestBuildADDLocalAndRemoteFilesWithoutCache(t *testing.T) {
  2454. name := "testbuildaddlocalandremotefilewithoutcache"
  2455. name2 := "testbuildaddlocalandremotefilewithoutcache2"
  2456. defer deleteImages(name, name2)
  2457. server, err := fakeStorage(map[string]string{
  2458. "baz": "hello",
  2459. })
  2460. if err != nil {
  2461. t.Fatal(err)
  2462. }
  2463. defer server.Close()
  2464. ctx, err := fakeContext(fmt.Sprintf(`FROM scratch
  2465. MAINTAINER dockerio
  2466. ADD foo /usr/lib/bla/bar
  2467. ADD %s/baz /usr/lib/baz/quux`, server.URL),
  2468. map[string]string{
  2469. "foo": "hello world",
  2470. })
  2471. if err != nil {
  2472. t.Fatal(err)
  2473. }
  2474. defer ctx.Close()
  2475. id1, err := buildImageFromContext(name, ctx, true)
  2476. if err != nil {
  2477. t.Fatal(err)
  2478. }
  2479. id2, err := buildImageFromContext(name2, ctx, false)
  2480. if err != nil {
  2481. t.Fatal(err)
  2482. }
  2483. if id1 == id2 {
  2484. t.Fatal("The cache should have been invalided but hasn't.")
  2485. }
  2486. logDone("build - add local and remote file without cache")
  2487. }
  2488. func TestBuildWithVolumeOwnership(t *testing.T) {
  2489. name := "testbuildimg"
  2490. defer deleteImages(name)
  2491. _, err := buildImage(name,
  2492. `FROM busybox:latest
  2493. RUN mkdir /test && chown daemon:daemon /test && chmod 0600 /test
  2494. VOLUME /test`,
  2495. true)
  2496. if err != nil {
  2497. t.Fatal(err)
  2498. }
  2499. cmd := exec.Command(dockerBinary, "run", "--rm", "testbuildimg", "ls", "-la", "/test")
  2500. out, _, err := runCommandWithOutput(cmd)
  2501. if err != nil {
  2502. t.Fatal(out, err)
  2503. }
  2504. if expected := "drw-------"; !strings.Contains(out, expected) {
  2505. t.Fatalf("expected %s received %s", expected, out)
  2506. }
  2507. if expected := "daemon daemon"; !strings.Contains(out, expected) {
  2508. t.Fatalf("expected %s received %s", expected, out)
  2509. }
  2510. logDone("build - volume ownership")
  2511. }
  2512. // testing #1405 - config.Cmd does not get cleaned up if
  2513. // utilizing cache
  2514. func TestBuildEntrypointRunCleanup(t *testing.T) {
  2515. name := "testbuildcmdcleanup"
  2516. defer deleteImages(name)
  2517. if _, err := buildImage(name,
  2518. `FROM busybox
  2519. RUN echo "hello"`,
  2520. true); err != nil {
  2521. t.Fatal(err)
  2522. }
  2523. ctx, err := fakeContext(`FROM busybox
  2524. RUN echo "hello"
  2525. ADD foo /foo
  2526. ENTRYPOINT ["/bin/echo"]`,
  2527. map[string]string{
  2528. "foo": "hello",
  2529. })
  2530. defer ctx.Close()
  2531. if err != nil {
  2532. t.Fatal(err)
  2533. }
  2534. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  2535. t.Fatal(err)
  2536. }
  2537. res, err := inspectField(name, "Config.Cmd")
  2538. if err != nil {
  2539. t.Fatal(err)
  2540. }
  2541. // Cmd must be cleaned up
  2542. if expected := "<no value>"; res != expected {
  2543. t.Fatalf("Cmd %s, expected %s", res, expected)
  2544. }
  2545. logDone("build - cleanup cmd after RUN")
  2546. }
  2547. func TestBuildForbiddenContextPath(t *testing.T) {
  2548. name := "testbuildforbidpath"
  2549. defer deleteImages(name)
  2550. ctx, err := fakeContext(`FROM scratch
  2551. ADD ../../ test/
  2552. `,
  2553. map[string]string{
  2554. "test.txt": "test1",
  2555. "other.txt": "other",
  2556. })
  2557. defer ctx.Close()
  2558. if err != nil {
  2559. t.Fatal(err)
  2560. }
  2561. expected := "Forbidden path outside the build context: ../../ "
  2562. if _, err := buildImageFromContext(name, ctx, true); err == nil || !strings.Contains(err.Error(), expected) {
  2563. t.Fatalf("Wrong error: (should contain \"%s\") got:\n%v", expected, err)
  2564. }
  2565. logDone("build - forbidden context path")
  2566. }
  2567. func TestBuildADDFileNotFound(t *testing.T) {
  2568. name := "testbuildaddnotfound"
  2569. defer deleteImages(name)
  2570. ctx, err := fakeContext(`FROM scratch
  2571. ADD foo /usr/local/bar`,
  2572. map[string]string{"bar": "hello"})
  2573. defer ctx.Close()
  2574. if err != nil {
  2575. t.Fatal(err)
  2576. }
  2577. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  2578. if !strings.Contains(err.Error(), "foo: no such file or directory") {
  2579. t.Fatalf("Wrong error %v, must be about missing foo file or directory", err)
  2580. }
  2581. } else {
  2582. t.Fatal("Error must not be nil")
  2583. }
  2584. logDone("build - add file not found")
  2585. }
  2586. func TestBuildInheritance(t *testing.T) {
  2587. name := "testbuildinheritance"
  2588. defer deleteImages(name)
  2589. _, err := buildImage(name,
  2590. `FROM scratch
  2591. EXPOSE 2375`,
  2592. true)
  2593. if err != nil {
  2594. t.Fatal(err)
  2595. }
  2596. ports1, err := inspectField(name, "Config.ExposedPorts")
  2597. if err != nil {
  2598. t.Fatal(err)
  2599. }
  2600. _, err = buildImage(name,
  2601. fmt.Sprintf(`FROM %s
  2602. ENTRYPOINT ["/bin/echo"]`, name),
  2603. true)
  2604. if err != nil {
  2605. t.Fatal(err)
  2606. }
  2607. res, err := inspectField(name, "Config.Entrypoint")
  2608. if err != nil {
  2609. t.Fatal(err)
  2610. }
  2611. if expected := "[/bin/echo]"; res != expected {
  2612. t.Fatalf("Entrypoint %s, expected %s", res, expected)
  2613. }
  2614. ports2, err := inspectField(name, "Config.ExposedPorts")
  2615. if err != nil {
  2616. t.Fatal(err)
  2617. }
  2618. if ports1 != ports2 {
  2619. t.Fatalf("Ports must be same: %s != %s", ports1, ports2)
  2620. }
  2621. logDone("build - inheritance")
  2622. }
  2623. func TestBuildFails(t *testing.T) {
  2624. name := "testbuildfails"
  2625. defer deleteImages(name)
  2626. defer deleteAllContainers()
  2627. _, err := buildImage(name,
  2628. `FROM busybox
  2629. RUN sh -c "exit 23"`,
  2630. true)
  2631. if err != nil {
  2632. if !strings.Contains(err.Error(), "returned a non-zero code: 23") {
  2633. t.Fatalf("Wrong error %v, must be about non-zero code 23", err)
  2634. }
  2635. } else {
  2636. t.Fatal("Error must not be nil")
  2637. }
  2638. logDone("build - fails")
  2639. }
  2640. func TestBuildFailsDockerfileEmpty(t *testing.T) {
  2641. name := "testbuildfails"
  2642. defer deleteImages(name)
  2643. _, err := buildImage(name, ``, true)
  2644. if err != nil {
  2645. if !strings.Contains(err.Error(), "Dockerfile cannot be empty") {
  2646. t.Fatalf("Wrong error %v, must be about empty Dockerfile", err)
  2647. }
  2648. } else {
  2649. t.Fatal("Error must not be nil")
  2650. }
  2651. logDone("build - fails with empty dockerfile")
  2652. }
  2653. func TestBuildOnBuild(t *testing.T) {
  2654. name := "testbuildonbuild"
  2655. defer deleteImages(name)
  2656. _, err := buildImage(name,
  2657. `FROM busybox
  2658. ONBUILD RUN touch foobar`,
  2659. true)
  2660. if err != nil {
  2661. t.Fatal(err)
  2662. }
  2663. _, err = buildImage(name,
  2664. fmt.Sprintf(`FROM %s
  2665. RUN [ -f foobar ]`, name),
  2666. true)
  2667. if err != nil {
  2668. t.Fatal(err)
  2669. }
  2670. logDone("build - onbuild")
  2671. }
  2672. func TestBuildOnBuildForbiddenChained(t *testing.T) {
  2673. name := "testbuildonbuildforbiddenchained"
  2674. defer deleteImages(name)
  2675. _, err := buildImage(name,
  2676. `FROM busybox
  2677. ONBUILD ONBUILD RUN touch foobar`,
  2678. true)
  2679. if err != nil {
  2680. if !strings.Contains(err.Error(), "Chaining ONBUILD via `ONBUILD ONBUILD` isn't allowed") {
  2681. t.Fatalf("Wrong error %v, must be about chaining ONBUILD", err)
  2682. }
  2683. } else {
  2684. t.Fatal("Error must not be nil")
  2685. }
  2686. logDone("build - onbuild forbidden chained")
  2687. }
  2688. func TestBuildOnBuildForbiddenFrom(t *testing.T) {
  2689. name := "testbuildonbuildforbiddenfrom"
  2690. defer deleteImages(name)
  2691. _, err := buildImage(name,
  2692. `FROM busybox
  2693. ONBUILD FROM scratch`,
  2694. true)
  2695. if err != nil {
  2696. if !strings.Contains(err.Error(), "FROM isn't allowed as an ONBUILD trigger") {
  2697. t.Fatalf("Wrong error %v, must be about FROM forbidden", err)
  2698. }
  2699. } else {
  2700. t.Fatal("Error must not be nil")
  2701. }
  2702. logDone("build - onbuild forbidden from")
  2703. }
  2704. func TestBuildOnBuildForbiddenMaintainer(t *testing.T) {
  2705. name := "testbuildonbuildforbiddenmaintainer"
  2706. defer deleteImages(name)
  2707. _, err := buildImage(name,
  2708. `FROM busybox
  2709. ONBUILD MAINTAINER docker.io`,
  2710. true)
  2711. if err != nil {
  2712. if !strings.Contains(err.Error(), "MAINTAINER isn't allowed as an ONBUILD trigger") {
  2713. t.Fatalf("Wrong error %v, must be about MAINTAINER forbidden", err)
  2714. }
  2715. } else {
  2716. t.Fatal("Error must not be nil")
  2717. }
  2718. logDone("build - onbuild forbidden maintainer")
  2719. }
  2720. // gh #2446
  2721. func TestBuildAddToSymlinkDest(t *testing.T) {
  2722. name := "testbuildaddtosymlinkdest"
  2723. defer deleteImages(name)
  2724. ctx, err := fakeContext(`FROM busybox
  2725. RUN mkdir /foo
  2726. RUN ln -s /foo /bar
  2727. ADD foo /bar/
  2728. RUN [ -f /bar/foo ]
  2729. RUN [ -f /foo/foo ]`,
  2730. map[string]string{
  2731. "foo": "hello",
  2732. })
  2733. if err != nil {
  2734. t.Fatal(err)
  2735. }
  2736. defer ctx.Close()
  2737. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  2738. t.Fatal(err)
  2739. }
  2740. logDone("build - add to symlink destination")
  2741. }
  2742. func TestBuildEscapeWhitespace(t *testing.T) {
  2743. name := "testbuildescaping"
  2744. defer deleteImages(name)
  2745. _, err := buildImage(name, `
  2746. FROM busybox
  2747. MAINTAINER "Docker \
  2748. IO <io@\
  2749. docker.com>"
  2750. `, true)
  2751. res, err := inspectField(name, "Author")
  2752. if err != nil {
  2753. t.Fatal(err)
  2754. }
  2755. if res != "\"Docker IO <io@docker.com>\"" {
  2756. t.Fatalf("Parsed string did not match the escaped string. Got: %q", res)
  2757. }
  2758. logDone("build - validate escaping whitespace")
  2759. }
  2760. func TestBuildVerifyIntString(t *testing.T) {
  2761. // Verify that strings that look like ints are still passed as strings
  2762. name := "testbuildstringing"
  2763. defer deleteImages(name)
  2764. _, err := buildImage(name, `
  2765. FROM busybox
  2766. MAINTAINER 123
  2767. `, true)
  2768. out, rc, err := runCommandWithOutput(exec.Command(dockerBinary, "inspect", name))
  2769. if rc != 0 || err != nil {
  2770. t.Fatalf("Unexcepted error from inspect: rc: %v err: %v", rc, err)
  2771. }
  2772. if !strings.Contains(out, "\"123\"") {
  2773. t.Fatalf("Output does not contain the int as a string:\n%s", out)
  2774. }
  2775. logDone("build - verify int/strings as strings")
  2776. }
  2777. func TestBuildDockerignore(t *testing.T) {
  2778. name := "testbuilddockerignore"
  2779. defer deleteImages(name)
  2780. dockerfile := `
  2781. FROM busybox
  2782. ADD . /bla
  2783. RUN [[ -f /bla/src/x.go ]]
  2784. RUN [[ -f /bla/Makefile ]]
  2785. RUN [[ ! -e /bla/src/_vendor ]]
  2786. RUN [[ ! -e /bla/.gitignore ]]
  2787. RUN [[ ! -e /bla/README.md ]]
  2788. RUN [[ ! -e /bla/.git ]]`
  2789. ctx, err := fakeContext(dockerfile, map[string]string{
  2790. "Makefile": "all:",
  2791. ".git/HEAD": "ref: foo",
  2792. "src/x.go": "package main",
  2793. "src/_vendor/v.go": "package main",
  2794. ".gitignore": "",
  2795. "README.md": "readme",
  2796. ".dockerignore": ".git\npkg\n.gitignore\nsrc/_vendor\n*.md",
  2797. })
  2798. defer ctx.Close()
  2799. if err != nil {
  2800. t.Fatal(err)
  2801. }
  2802. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  2803. t.Fatal(err)
  2804. }
  2805. logDone("build - test .dockerignore")
  2806. }
  2807. func TestBuildDockerignoreCleanPaths(t *testing.T) {
  2808. name := "testbuilddockerignorecleanpaths"
  2809. defer deleteImages(name)
  2810. dockerfile := `
  2811. FROM busybox
  2812. ADD . /tmp/
  2813. RUN (! ls /tmp/foo) && (! ls /tmp/foo2) && (! ls /tmp/dir1/foo)`
  2814. ctx, err := fakeContext(dockerfile, map[string]string{
  2815. "foo": "foo",
  2816. "foo2": "foo2",
  2817. "dir1/foo": "foo in dir1",
  2818. ".dockerignore": "./foo\ndir1//foo\n./dir1/../foo2",
  2819. })
  2820. if err != nil {
  2821. t.Fatal(err)
  2822. }
  2823. defer ctx.Close()
  2824. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  2825. t.Fatal(err)
  2826. }
  2827. logDone("build - test .dockerignore with clean paths")
  2828. }
  2829. func TestBuildDockerignoringDockerfile(t *testing.T) {
  2830. name := "testbuilddockerignoredockerfile"
  2831. defer deleteImages(name)
  2832. dockerfile := `
  2833. FROM busybox
  2834. ADD . /tmp/
  2835. RUN ! ls /tmp/Dockerfile
  2836. RUN ls /tmp/.dockerignore`
  2837. ctx, err := fakeContext(dockerfile, map[string]string{
  2838. "Dockerfile": dockerfile,
  2839. ".dockerignore": "Dockerfile\n",
  2840. })
  2841. if err != nil {
  2842. t.Fatal(err)
  2843. }
  2844. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  2845. t.Fatalf("Didn't ignore Dockerfile correctly:%s", err)
  2846. }
  2847. // now try it with ./Dockerfile
  2848. ctx.Add(".dockerignore", "./Dockerfile\n")
  2849. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  2850. t.Fatalf("Didn't ignore ./Dockerfile correctly:%s", err)
  2851. }
  2852. logDone("build - test .dockerignore of Dockerfile")
  2853. }
  2854. func TestBuildDockerignoringRenamedDockerfile(t *testing.T) {
  2855. name := "testbuilddockerignoredockerfile"
  2856. defer deleteImages(name)
  2857. dockerfile := `
  2858. FROM busybox
  2859. ADD . /tmp/
  2860. RUN ls /tmp/Dockerfile
  2861. RUN ! ls /tmp/MyDockerfile
  2862. RUN ls /tmp/.dockerignore`
  2863. ctx, err := fakeContext(dockerfile, map[string]string{
  2864. "Dockerfile": "Should not use me",
  2865. "MyDockerfile": dockerfile,
  2866. ".dockerignore": "MyDockerfile\n",
  2867. })
  2868. if err != nil {
  2869. t.Fatal(err)
  2870. }
  2871. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  2872. t.Fatalf("Didn't ignore MyDockerfile correctly:%s", err)
  2873. }
  2874. // now try it with ./MyDockerfile
  2875. ctx.Add(".dockerignore", "./MyDockerfile\n")
  2876. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  2877. t.Fatalf("Didn't ignore ./MyDockerfile correctly:%s", err)
  2878. }
  2879. logDone("build - test .dockerignore of renamed Dockerfile")
  2880. }
  2881. func TestBuildDockerignoringDockerignore(t *testing.T) {
  2882. name := "testbuilddockerignoredockerignore"
  2883. defer deleteImages(name)
  2884. dockerfile := `
  2885. FROM busybox
  2886. ADD . /tmp/
  2887. RUN ! ls /tmp/.dockerignore
  2888. RUN ls /tmp/Dockerfile`
  2889. ctx, err := fakeContext(dockerfile, map[string]string{
  2890. "Dockerfile": dockerfile,
  2891. ".dockerignore": ".dockerignore\n",
  2892. })
  2893. defer ctx.Close()
  2894. if err != nil {
  2895. t.Fatal(err)
  2896. }
  2897. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  2898. t.Fatalf("Didn't ignore .dockerignore correctly:%s", err)
  2899. }
  2900. logDone("build - test .dockerignore of .dockerignore")
  2901. }
  2902. func TestBuildDockerignoreTouchDockerfile(t *testing.T) {
  2903. var id1 string
  2904. var id2 string
  2905. name := "testbuilddockerignoretouchdockerfile"
  2906. defer deleteImages(name)
  2907. dockerfile := `
  2908. FROM busybox
  2909. ADD . /tmp/`
  2910. ctx, err := fakeContext(dockerfile, map[string]string{
  2911. "Dockerfile": dockerfile,
  2912. ".dockerignore": "Dockerfile\n",
  2913. })
  2914. defer ctx.Close()
  2915. if err != nil {
  2916. t.Fatal(err)
  2917. }
  2918. if id1, err = buildImageFromContext(name, ctx, true); err != nil {
  2919. t.Fatalf("Didn't build it correctly:%s", err)
  2920. }
  2921. if id2, err = buildImageFromContext(name, ctx, true); err != nil {
  2922. t.Fatalf("Didn't build it correctly:%s", err)
  2923. }
  2924. if id1 != id2 {
  2925. t.Fatalf("Didn't use the cache - 1")
  2926. }
  2927. // Now make sure touching Dockerfile doesn't invalidate the cache
  2928. if err = ctx.Add("Dockerfile", dockerfile+"\n# hi"); err != nil {
  2929. t.Fatalf("Didn't add Dockerfile: %s", err)
  2930. }
  2931. if id2, err = buildImageFromContext(name, ctx, true); err != nil {
  2932. t.Fatalf("Didn't build it correctly:%s", err)
  2933. }
  2934. if id1 != id2 {
  2935. t.Fatalf("Didn't use the cache - 2")
  2936. }
  2937. // One more time but just 'touch' it instead of changing the content
  2938. if err = ctx.Add("Dockerfile", dockerfile+"\n# hi"); err != nil {
  2939. t.Fatalf("Didn't add Dockerfile: %s", err)
  2940. }
  2941. if id2, err = buildImageFromContext(name, ctx, true); err != nil {
  2942. t.Fatalf("Didn't build it correctly:%s", err)
  2943. }
  2944. if id1 != id2 {
  2945. t.Fatalf("Didn't use the cache - 3")
  2946. }
  2947. logDone("build - test .dockerignore touch dockerfile")
  2948. }
  2949. func TestBuildDockerignoringWholeDir(t *testing.T) {
  2950. name := "testbuilddockerignorewholedir"
  2951. defer deleteImages(name)
  2952. dockerfile := `
  2953. FROM busybox
  2954. COPY . /
  2955. RUN [[ ! -e /.gitignore ]]
  2956. RUN [[ -f /Makefile ]]`
  2957. ctx, err := fakeContext(dockerfile, map[string]string{
  2958. "Dockerfile": "FROM scratch",
  2959. "Makefile": "all:",
  2960. ".dockerignore": ".*\n",
  2961. })
  2962. defer ctx.Close()
  2963. if err != nil {
  2964. t.Fatal(err)
  2965. }
  2966. if _, err = buildImageFromContext(name, ctx, true); err != nil {
  2967. t.Fatal(err)
  2968. }
  2969. logDone("build - test .dockerignore whole dir with .*")
  2970. }
  2971. func TestBuildLineBreak(t *testing.T) {
  2972. name := "testbuildlinebreak"
  2973. defer deleteImages(name)
  2974. _, err := buildImage(name,
  2975. `FROM busybox
  2976. RUN sh -c 'echo root:testpass \
  2977. > /tmp/passwd'
  2978. RUN mkdir -p /var/run/sshd
  2979. RUN [ "$(cat /tmp/passwd)" = "root:testpass" ]
  2980. RUN [ "$(ls -d /var/run/sshd)" = "/var/run/sshd" ]`,
  2981. true)
  2982. if err != nil {
  2983. t.Fatal(err)
  2984. }
  2985. logDone("build - line break with \\")
  2986. }
  2987. func TestBuildEOLInLine(t *testing.T) {
  2988. name := "testbuildeolinline"
  2989. defer deleteImages(name)
  2990. _, err := buildImage(name,
  2991. `FROM busybox
  2992. RUN sh -c 'echo root:testpass > /tmp/passwd'
  2993. RUN echo "foo \n bar"; echo "baz"
  2994. RUN mkdir -p /var/run/sshd
  2995. RUN [ "$(cat /tmp/passwd)" = "root:testpass" ]
  2996. RUN [ "$(ls -d /var/run/sshd)" = "/var/run/sshd" ]`,
  2997. true)
  2998. if err != nil {
  2999. t.Fatal(err)
  3000. }
  3001. logDone("build - end of line in dockerfile instruction")
  3002. }
  3003. func TestBuildCommentsShebangs(t *testing.T) {
  3004. name := "testbuildcomments"
  3005. defer deleteImages(name)
  3006. _, err := buildImage(name,
  3007. `FROM busybox
  3008. # This is an ordinary comment.
  3009. RUN { echo '#!/bin/sh'; echo 'echo hello world'; } > /hello.sh
  3010. RUN [ ! -x /hello.sh ]
  3011. # comment with line break \
  3012. RUN chmod +x /hello.sh
  3013. RUN [ -x /hello.sh ]
  3014. RUN [ "$(cat /hello.sh)" = $'#!/bin/sh\necho hello world' ]
  3015. RUN [ "$(/hello.sh)" = "hello world" ]`,
  3016. true)
  3017. if err != nil {
  3018. t.Fatal(err)
  3019. }
  3020. logDone("build - comments and shebangs")
  3021. }
  3022. func TestBuildUsersAndGroups(t *testing.T) {
  3023. name := "testbuildusers"
  3024. defer deleteImages(name)
  3025. _, err := buildImage(name,
  3026. `FROM busybox
  3027. # Make sure our defaults work
  3028. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)" = '0:0/root:root' ]
  3029. # 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)
  3030. USER root
  3031. RUN [ "$(id -G):$(id -Gn)" = '0 10:root wheel' ]
  3032. # Setup dockerio user and group
  3033. RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  3034. RUN echo 'dockerio:x:1001:' >> /etc/group
  3035. # Make sure we can switch to our user and all the information is exactly as we expect it to be
  3036. USER dockerio
  3037. RUN id -G
  3038. RUN id -Gn
  3039. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3040. # Switch back to root and double check that worked exactly as we might expect it to
  3041. USER root
  3042. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '0:0/root:root/0 10:root wheel' ]
  3043. # Add a "supplementary" group for our dockerio user
  3044. RUN echo 'supplementary:x:1002:dockerio' >> /etc/group
  3045. # ... and then go verify that we get it like we expect
  3046. USER dockerio
  3047. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001 1002:dockerio supplementary' ]
  3048. USER 1001
  3049. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001 1002:dockerio supplementary' ]
  3050. # super test the new "user:group" syntax
  3051. USER dockerio:dockerio
  3052. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3053. USER 1001:dockerio
  3054. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3055. USER dockerio:1001
  3056. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3057. USER 1001:1001
  3058. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ]
  3059. USER dockerio:supplementary
  3060. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  3061. USER dockerio:1002
  3062. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  3063. USER 1001:supplementary
  3064. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  3065. USER 1001:1002
  3066. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ]
  3067. # make sure unknown uid/gid still works properly
  3068. USER 1042:1043
  3069. RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1042:1043/1042:1043/1043:1043' ]`,
  3070. true)
  3071. if err != nil {
  3072. t.Fatal(err)
  3073. }
  3074. logDone("build - users and groups")
  3075. }
  3076. func TestBuildEnvUsage(t *testing.T) {
  3077. name := "testbuildenvusage"
  3078. defer deleteImages(name)
  3079. dockerfile := `FROM busybox
  3080. ENV HOME /root
  3081. ENV PATH $HOME/bin:$PATH
  3082. ENV PATH /tmp:$PATH
  3083. RUN [ "$PATH" = "/tmp:$HOME/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" ]
  3084. ENV FOO /foo/baz
  3085. ENV BAR /bar
  3086. ENV BAZ $BAR
  3087. ENV FOOPATH $PATH:$FOO
  3088. RUN [ "$BAR" = "$BAZ" ]
  3089. RUN [ "$FOOPATH" = "$PATH:/foo/baz" ]
  3090. ENV FROM hello/docker/world
  3091. ENV TO /docker/world/hello
  3092. ADD $FROM $TO
  3093. RUN [ "$(cat $TO)" = "hello" ]
  3094. `
  3095. ctx, err := fakeContext(dockerfile, map[string]string{
  3096. "hello/docker/world": "hello",
  3097. })
  3098. if err != nil {
  3099. t.Fatal(err)
  3100. }
  3101. defer ctx.Close()
  3102. _, err = buildImageFromContext(name, ctx, true)
  3103. if err != nil {
  3104. t.Fatal(err)
  3105. }
  3106. logDone("build - environment variables usage")
  3107. }
  3108. func TestBuildEnvUsage2(t *testing.T) {
  3109. name := "testbuildenvusage2"
  3110. defer deleteImages(name)
  3111. dockerfile := `FROM busybox
  3112. ENV abc=def
  3113. RUN [ "$abc" = "def" ]
  3114. ENV def="hello world"
  3115. RUN [ "$def" = "hello world" ]
  3116. ENV def=hello\ world
  3117. RUN [ "$def" = "hello world" ]
  3118. ENV v1=abc v2="hi there"
  3119. RUN [ "$v1" = "abc" ]
  3120. RUN [ "$v2" = "hi there" ]
  3121. ENV v3='boogie nights' v4="with'quotes too"
  3122. RUN [ "$v3" = "boogie nights" ]
  3123. RUN [ "$v4" = "with'quotes too" ]
  3124. ENV abc=zzz FROM=hello/docker/world
  3125. ENV abc=zzz TO=/docker/world/hello
  3126. ADD $FROM $TO
  3127. RUN [ "$(cat $TO)" = "hello" ]
  3128. ENV abc "zzz"
  3129. RUN [ $abc = \"zzz\" ]
  3130. ENV abc 'yyy'
  3131. RUN [ $abc = \'yyy\' ]
  3132. ENV abc=
  3133. RUN [ "$abc" = "" ]
  3134. `
  3135. ctx, err := fakeContext(dockerfile, map[string]string{
  3136. "hello/docker/world": "hello",
  3137. })
  3138. if err != nil {
  3139. t.Fatal(err)
  3140. }
  3141. _, err = buildImageFromContext(name, ctx, true)
  3142. if err != nil {
  3143. t.Fatal(err)
  3144. }
  3145. logDone("build - environment variables usage2")
  3146. }
  3147. func TestBuildAddScript(t *testing.T) {
  3148. name := "testbuildaddscript"
  3149. defer deleteImages(name)
  3150. dockerfile := `
  3151. FROM busybox
  3152. ADD test /test
  3153. RUN ["chmod","+x","/test"]
  3154. RUN ["/test"]
  3155. RUN [ "$(cat /testfile)" = 'test!' ]`
  3156. ctx, err := fakeContext(dockerfile, map[string]string{
  3157. "test": "#!/bin/sh\necho 'test!' > /testfile",
  3158. })
  3159. if err != nil {
  3160. t.Fatal(err)
  3161. }
  3162. defer ctx.Close()
  3163. _, err = buildImageFromContext(name, ctx, true)
  3164. if err != nil {
  3165. t.Fatal(err)
  3166. }
  3167. logDone("build - add and run script")
  3168. }
  3169. func TestBuildAddTar(t *testing.T) {
  3170. name := "testbuildaddtar"
  3171. defer deleteImages(name)
  3172. ctx := func() *FakeContext {
  3173. dockerfile := `
  3174. FROM busybox
  3175. ADD test.tar /
  3176. RUN cat /test/foo | grep Hi
  3177. ADD test.tar /test.tar
  3178. RUN cat /test.tar/test/foo | grep Hi
  3179. ADD test.tar /unlikely-to-exist
  3180. RUN cat /unlikely-to-exist/test/foo | grep Hi
  3181. ADD test.tar /unlikely-to-exist-trailing-slash/
  3182. RUN cat /unlikely-to-exist-trailing-slash/test/foo | grep Hi
  3183. RUN mkdir /existing-directory
  3184. ADD test.tar /existing-directory
  3185. RUN cat /existing-directory/test/foo | grep Hi
  3186. ADD test.tar /existing-directory-trailing-slash/
  3187. RUN cat /existing-directory-trailing-slash/test/foo | grep Hi`
  3188. tmpDir, err := ioutil.TempDir("", "fake-context")
  3189. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  3190. if err != nil {
  3191. t.Fatalf("failed to create test.tar archive: %v", err)
  3192. }
  3193. defer testTar.Close()
  3194. tw := tar.NewWriter(testTar)
  3195. if err := tw.WriteHeader(&tar.Header{
  3196. Name: "test/foo",
  3197. Size: 2,
  3198. }); err != nil {
  3199. t.Fatalf("failed to write tar file header: %v", err)
  3200. }
  3201. if _, err := tw.Write([]byte("Hi")); err != nil {
  3202. t.Fatalf("failed to write tar file content: %v", err)
  3203. }
  3204. if err := tw.Close(); err != nil {
  3205. t.Fatalf("failed to close tar archive: %v", err)
  3206. }
  3207. if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil {
  3208. t.Fatalf("failed to open destination dockerfile: %v", err)
  3209. }
  3210. return &FakeContext{Dir: tmpDir}
  3211. }()
  3212. defer ctx.Close()
  3213. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3214. t.Fatalf("build failed to complete for TestBuildAddTar: %v", err)
  3215. }
  3216. logDone("build - ADD tar")
  3217. }
  3218. func TestBuildAddTarXz(t *testing.T) {
  3219. name := "testbuildaddtarxz"
  3220. defer deleteImages(name)
  3221. ctx := func() *FakeContext {
  3222. dockerfile := `
  3223. FROM busybox
  3224. ADD test.tar.xz /
  3225. RUN cat /test/foo | grep Hi`
  3226. tmpDir, err := ioutil.TempDir("", "fake-context")
  3227. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  3228. if err != nil {
  3229. t.Fatalf("failed to create test.tar archive: %v", err)
  3230. }
  3231. defer testTar.Close()
  3232. tw := tar.NewWriter(testTar)
  3233. if err := tw.WriteHeader(&tar.Header{
  3234. Name: "test/foo",
  3235. Size: 2,
  3236. }); err != nil {
  3237. t.Fatalf("failed to write tar file header: %v", err)
  3238. }
  3239. if _, err := tw.Write([]byte("Hi")); err != nil {
  3240. t.Fatalf("failed to write tar file content: %v", err)
  3241. }
  3242. if err := tw.Close(); err != nil {
  3243. t.Fatalf("failed to close tar archive: %v", err)
  3244. }
  3245. xzCompressCmd := exec.Command("xz", "test.tar")
  3246. xzCompressCmd.Dir = tmpDir
  3247. out, _, err := runCommandWithOutput(xzCompressCmd)
  3248. if err != nil {
  3249. t.Fatal(err, out)
  3250. }
  3251. if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil {
  3252. t.Fatalf("failed to open destination dockerfile: %v", err)
  3253. }
  3254. return &FakeContext{Dir: tmpDir}
  3255. }()
  3256. defer ctx.Close()
  3257. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3258. t.Fatalf("build failed to complete for TestBuildAddTarXz: %v", err)
  3259. }
  3260. logDone("build - ADD tar.xz")
  3261. }
  3262. func TestBuildAddTarXzGz(t *testing.T) {
  3263. name := "testbuildaddtarxzgz"
  3264. defer deleteImages(name)
  3265. ctx := func() *FakeContext {
  3266. dockerfile := `
  3267. FROM busybox
  3268. ADD test.tar.xz.gz /
  3269. RUN ls /test.tar.xz.gz`
  3270. tmpDir, err := ioutil.TempDir("", "fake-context")
  3271. testTar, err := os.Create(filepath.Join(tmpDir, "test.tar"))
  3272. if err != nil {
  3273. t.Fatalf("failed to create test.tar archive: %v", err)
  3274. }
  3275. defer testTar.Close()
  3276. tw := tar.NewWriter(testTar)
  3277. if err := tw.WriteHeader(&tar.Header{
  3278. Name: "test/foo",
  3279. Size: 2,
  3280. }); err != nil {
  3281. t.Fatalf("failed to write tar file header: %v", err)
  3282. }
  3283. if _, err := tw.Write([]byte("Hi")); err != nil {
  3284. t.Fatalf("failed to write tar file content: %v", err)
  3285. }
  3286. if err := tw.Close(); err != nil {
  3287. t.Fatalf("failed to close tar archive: %v", err)
  3288. }
  3289. xzCompressCmd := exec.Command("xz", "test.tar")
  3290. xzCompressCmd.Dir = tmpDir
  3291. out, _, err := runCommandWithOutput(xzCompressCmd)
  3292. if err != nil {
  3293. t.Fatal(err, out)
  3294. }
  3295. gzipCompressCmd := exec.Command("gzip", "test.tar.xz")
  3296. gzipCompressCmd.Dir = tmpDir
  3297. out, _, err = runCommandWithOutput(gzipCompressCmd)
  3298. if err != nil {
  3299. t.Fatal(err, out)
  3300. }
  3301. if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil {
  3302. t.Fatalf("failed to open destination dockerfile: %v", err)
  3303. }
  3304. return &FakeContext{Dir: tmpDir}
  3305. }()
  3306. defer ctx.Close()
  3307. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3308. t.Fatalf("build failed to complete for TestBuildAddTarXz: %v", err)
  3309. }
  3310. logDone("build - ADD tar.xz.gz")
  3311. }
  3312. func TestBuildFromGIT(t *testing.T) {
  3313. name := "testbuildfromgit"
  3314. defer deleteImages(name)
  3315. git, err := fakeGIT("repo", map[string]string{
  3316. "Dockerfile": `FROM busybox
  3317. ADD first /first
  3318. RUN [ -f /first ]
  3319. MAINTAINER docker`,
  3320. "first": "test git data",
  3321. })
  3322. if err != nil {
  3323. t.Fatal(err)
  3324. }
  3325. defer git.Close()
  3326. _, err = buildImageFromPath(name, git.RepoURL, true)
  3327. if err != nil {
  3328. t.Fatal(err)
  3329. }
  3330. res, err := inspectField(name, "Author")
  3331. if err != nil {
  3332. t.Fatal(err)
  3333. }
  3334. if res != "docker" {
  3335. t.Fatalf("Maintainer should be docker, got %s", res)
  3336. }
  3337. logDone("build - build from GIT")
  3338. }
  3339. func TestBuildCleanupCmdOnEntrypoint(t *testing.T) {
  3340. name := "testbuildcmdcleanuponentrypoint"
  3341. defer deleteImages(name)
  3342. if _, err := buildImage(name,
  3343. `FROM scratch
  3344. CMD ["test"]
  3345. ENTRYPOINT ["echo"]`,
  3346. true); err != nil {
  3347. t.Fatal(err)
  3348. }
  3349. if _, err := buildImage(name,
  3350. fmt.Sprintf(`FROM %s
  3351. ENTRYPOINT ["cat"]`, name),
  3352. true); err != nil {
  3353. t.Fatal(err)
  3354. }
  3355. res, err := inspectField(name, "Config.Cmd")
  3356. if err != nil {
  3357. t.Fatal(err)
  3358. }
  3359. if expected := "<no value>"; res != expected {
  3360. t.Fatalf("Cmd %s, expected %s", res, expected)
  3361. }
  3362. res, err = inspectField(name, "Config.Entrypoint")
  3363. if err != nil {
  3364. t.Fatal(err)
  3365. }
  3366. if expected := "[cat]"; res != expected {
  3367. t.Fatalf("Entrypoint %s, expected %s", res, expected)
  3368. }
  3369. logDone("build - cleanup cmd on ENTRYPOINT")
  3370. }
  3371. func TestBuildClearCmd(t *testing.T) {
  3372. name := "testbuildclearcmd"
  3373. defer deleteImages(name)
  3374. _, err := buildImage(name,
  3375. `From scratch
  3376. ENTRYPOINT ["/bin/bash"]
  3377. CMD []`,
  3378. true)
  3379. if err != nil {
  3380. t.Fatal(err)
  3381. }
  3382. res, err := inspectFieldJSON(name, "Config.Cmd")
  3383. if err != nil {
  3384. t.Fatal(err)
  3385. }
  3386. if res != "[]" {
  3387. t.Fatalf("Cmd %s, expected %s", res, "[]")
  3388. }
  3389. logDone("build - clearcmd")
  3390. }
  3391. func TestBuildEmptyCmd(t *testing.T) {
  3392. name := "testbuildemptycmd"
  3393. defer deleteImages(name)
  3394. if _, err := buildImage(name, "FROM scratch\nMAINTAINER quux\n", true); err != nil {
  3395. t.Fatal(err)
  3396. }
  3397. res, err := inspectFieldJSON(name, "Config.Cmd")
  3398. if err != nil {
  3399. t.Fatal(err)
  3400. }
  3401. if res != "null" {
  3402. t.Fatalf("Cmd %s, expected %s", res, "null")
  3403. }
  3404. logDone("build - empty cmd")
  3405. }
  3406. func TestBuildOnBuildOutput(t *testing.T) {
  3407. name := "testbuildonbuildparent"
  3408. defer deleteImages(name)
  3409. if _, err := buildImage(name, "FROM busybox\nONBUILD RUN echo foo\n", true); err != nil {
  3410. t.Fatal(err)
  3411. }
  3412. childname := "testbuildonbuildchild"
  3413. defer deleteImages(childname)
  3414. _, out, err := buildImageWithOut(name, "FROM "+name+"\nMAINTAINER quux\n", true)
  3415. if err != nil {
  3416. t.Fatal(err)
  3417. }
  3418. if !strings.Contains(out, "Trigger 0, RUN echo foo") {
  3419. t.Fatal("failed to find the ONBUILD output", out)
  3420. }
  3421. logDone("build - onbuild output")
  3422. }
  3423. func TestBuildInvalidTag(t *testing.T) {
  3424. name := "abcd:" + makeRandomString(200)
  3425. defer deleteImages(name)
  3426. _, out, err := buildImageWithOut(name, "FROM scratch\nMAINTAINER quux\n", true)
  3427. // if the error doesnt check for illegal tag name, or the image is built
  3428. // then this should fail
  3429. if !strings.Contains(out, "Illegal tag name") || strings.Contains(out, "Sending build context to Docker daemon") {
  3430. t.Fatalf("failed to stop before building. Error: %s, Output: %s", err, out)
  3431. }
  3432. logDone("build - invalid tag")
  3433. }
  3434. func TestBuildCmdShDashC(t *testing.T) {
  3435. name := "testbuildcmdshc"
  3436. defer deleteImages(name)
  3437. if _, err := buildImage(name, "FROM busybox\nCMD echo cmd\n", true); err != nil {
  3438. t.Fatal(err)
  3439. }
  3440. res, err := inspectFieldJSON(name, "Config.Cmd")
  3441. if err != nil {
  3442. t.Fatal(err, res)
  3443. }
  3444. expected := `["/bin/sh","-c","echo cmd"]`
  3445. if res != expected {
  3446. t.Fatalf("Expected value %s not in Config.Cmd: %s", expected, res)
  3447. }
  3448. logDone("build - cmd should have sh -c for non-json")
  3449. }
  3450. func TestBuildCmdJSONNoShDashC(t *testing.T) {
  3451. name := "testbuildcmdjson"
  3452. defer deleteImages(name)
  3453. if _, err := buildImage(name, "FROM busybox\nCMD [\"echo\", \"cmd\"]", true); err != nil {
  3454. t.Fatal(err)
  3455. }
  3456. res, err := inspectFieldJSON(name, "Config.Cmd")
  3457. if err != nil {
  3458. t.Fatal(err, res)
  3459. }
  3460. expected := `["echo","cmd"]`
  3461. if res != expected {
  3462. t.Fatalf("Expected value %s not in Config.Cmd: %s", expected, res)
  3463. }
  3464. logDone("build - cmd should not have /bin/sh -c for json")
  3465. }
  3466. func TestBuildIgnoreInvalidInstruction(t *testing.T) {
  3467. name := "testbuildignoreinvalidinstruction"
  3468. defer deleteImages(name)
  3469. out, _, err := buildImageWithOut(name, "FROM busybox\nfoo bar", true)
  3470. if err != nil {
  3471. t.Fatal(err, out)
  3472. }
  3473. logDone("build - ignore invalid Dockerfile instruction")
  3474. }
  3475. func TestBuildEntrypointInheritance(t *testing.T) {
  3476. defer deleteImages("parent", "child")
  3477. defer deleteAllContainers()
  3478. if _, err := buildImage("parent", `
  3479. FROM busybox
  3480. ENTRYPOINT exit 130
  3481. `, true); err != nil {
  3482. t.Fatal(err)
  3483. }
  3484. status, _ := runCommand(exec.Command(dockerBinary, "run", "parent"))
  3485. if status != 130 {
  3486. t.Fatalf("expected exit code 130 but received %d", status)
  3487. }
  3488. if _, err := buildImage("child", `
  3489. FROM parent
  3490. ENTRYPOINT exit 5
  3491. `, true); err != nil {
  3492. t.Fatal(err)
  3493. }
  3494. status, _ = runCommand(exec.Command(dockerBinary, "run", "child"))
  3495. if status != 5 {
  3496. t.Fatalf("expected exit code 5 but received %d", status)
  3497. }
  3498. logDone("build - clear entrypoint")
  3499. }
  3500. func TestBuildEntrypointInheritanceInspect(t *testing.T) {
  3501. var (
  3502. name = "testbuildepinherit"
  3503. name2 = "testbuildepinherit2"
  3504. expected = `["/bin/sh","-c","echo quux"]`
  3505. )
  3506. defer deleteImages(name, name2)
  3507. defer deleteAllContainers()
  3508. if _, err := buildImage(name, "FROM busybox\nENTRYPOINT /foo/bar", true); err != nil {
  3509. t.Fatal(err)
  3510. }
  3511. if _, err := buildImage(name2, fmt.Sprintf("FROM %s\nENTRYPOINT echo quux", name), true); err != nil {
  3512. t.Fatal(err)
  3513. }
  3514. res, err := inspectFieldJSON(name2, "Config.Entrypoint")
  3515. if err != nil {
  3516. t.Fatal(err, res)
  3517. }
  3518. if res != expected {
  3519. t.Fatalf("Expected value %s not in Config.Entrypoint: %s", expected, res)
  3520. }
  3521. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "-t", name2))
  3522. if err != nil {
  3523. t.Fatal(err, out)
  3524. }
  3525. expected = "quux"
  3526. if strings.TrimSpace(out) != expected {
  3527. t.Fatalf("Expected output is %s, got %s", expected, out)
  3528. }
  3529. logDone("build - entrypoint override inheritance properly")
  3530. }
  3531. func TestBuildRunShEntrypoint(t *testing.T) {
  3532. name := "testbuildentrypoint"
  3533. defer deleteImages(name)
  3534. _, err := buildImage(name,
  3535. `FROM busybox
  3536. ENTRYPOINT /bin/echo`,
  3537. true)
  3538. if err != nil {
  3539. t.Fatal(err)
  3540. }
  3541. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "--rm", name))
  3542. if err != nil {
  3543. t.Fatal(err, out)
  3544. }
  3545. logDone("build - entrypoint with /bin/echo running successfully")
  3546. }
  3547. func TestBuildExoticShellInterpolation(t *testing.T) {
  3548. name := "testbuildexoticshellinterpolation"
  3549. defer deleteImages(name)
  3550. _, err := buildImage(name, `
  3551. FROM busybox
  3552. ENV SOME_VAR a.b.c
  3553. RUN [ "$SOME_VAR" = 'a.b.c' ]
  3554. RUN [ "${SOME_VAR}" = 'a.b.c' ]
  3555. RUN [ "${SOME_VAR%.*}" = 'a.b' ]
  3556. RUN [ "${SOME_VAR%%.*}" = 'a' ]
  3557. RUN [ "${SOME_VAR#*.}" = 'b.c' ]
  3558. RUN [ "${SOME_VAR##*.}" = 'c' ]
  3559. RUN [ "${SOME_VAR/c/d}" = 'a.b.d' ]
  3560. RUN [ "${#SOME_VAR}" = '5' ]
  3561. RUN [ "${SOME_UNSET_VAR:-$SOME_VAR}" = 'a.b.c' ]
  3562. RUN [ "${SOME_VAR:+Version: ${SOME_VAR}}" = 'Version: a.b.c' ]
  3563. RUN [ "${SOME_UNSET_VAR:+${SOME_VAR}}" = '' ]
  3564. RUN [ "${SOME_UNSET_VAR:-${SOME_VAR:-d.e.f}}" = 'a.b.c' ]
  3565. `, false)
  3566. if err != nil {
  3567. t.Fatal(err)
  3568. }
  3569. logDone("build - exotic shell interpolation")
  3570. }
  3571. func TestBuildVerifySingleQuoteFails(t *testing.T) {
  3572. // This testcase is supposed to generate an error because the
  3573. // JSON array we're passing in on the CMD uses single quotes instead
  3574. // of double quotes (per the JSON spec). This means we interpret it
  3575. // as a "string" insead of "JSON array" and pass it on to "sh -c" and
  3576. // it should barf on it.
  3577. name := "testbuildsinglequotefails"
  3578. defer deleteImages(name)
  3579. defer deleteAllContainers()
  3580. _, err := buildImage(name,
  3581. `FROM busybox
  3582. CMD [ '/bin/sh', '-c', 'echo hi' ]`,
  3583. true)
  3584. _, _, err = runCommandWithOutput(exec.Command(dockerBinary, "run", "--rm", name))
  3585. if err == nil {
  3586. t.Fatal("The image was not supposed to be able to run")
  3587. }
  3588. logDone("build - verify single quotes fail")
  3589. }
  3590. func TestBuildVerboseOut(t *testing.T) {
  3591. name := "testbuildverboseout"
  3592. defer deleteImages(name)
  3593. _, out, err := buildImageWithOut(name,
  3594. `FROM busybox
  3595. RUN echo 123`,
  3596. false)
  3597. if err != nil {
  3598. t.Fatal(err)
  3599. }
  3600. if !strings.Contains(out, "\n123\n") {
  3601. t.Fatalf("Output should contain %q: %q", "123", out)
  3602. }
  3603. logDone("build - verbose output from commands")
  3604. }
  3605. func TestBuildWithTabs(t *testing.T) {
  3606. name := "testbuildwithtabs"
  3607. defer deleteImages(name)
  3608. _, err := buildImage(name,
  3609. "FROM busybox\nRUN echo\tone\t\ttwo", true)
  3610. if err != nil {
  3611. t.Fatal(err)
  3612. }
  3613. res, err := inspectFieldJSON(name, "ContainerConfig.Cmd")
  3614. if err != nil {
  3615. t.Fatal(err)
  3616. }
  3617. expected := `["/bin/sh","-c","echo\tone\t\ttwo"]`
  3618. if res != expected {
  3619. t.Fatalf("Missing tabs.\nGot:%s\nExp:%s", res, expected)
  3620. }
  3621. logDone("build - with tabs")
  3622. }
  3623. func TestBuildStderr(t *testing.T) {
  3624. // This test just makes sure that no non-error output goes
  3625. // to stderr
  3626. name := "testbuildstderr"
  3627. defer deleteImages(name)
  3628. _, _, stderr, err := buildImageWithStdoutStderr(name,
  3629. "FROM busybox\nRUN echo one", true)
  3630. if err != nil {
  3631. t.Fatal(err)
  3632. }
  3633. if stderr != "" {
  3634. t.Fatalf("Stderr should have been empty, instead its: %q", stderr)
  3635. }
  3636. logDone("build - testing stderr")
  3637. }
  3638. func TestBuildChownSingleFile(t *testing.T) {
  3639. name := "testbuildchownsinglefile"
  3640. defer deleteImages(name)
  3641. ctx, err := fakeContext(`
  3642. FROM busybox
  3643. COPY test /
  3644. RUN ls -l /test
  3645. RUN [ $(ls -l /test | awk '{print $3":"$4}') = 'root:root' ]
  3646. `, map[string]string{
  3647. "test": "test",
  3648. })
  3649. if err != nil {
  3650. t.Fatal(err)
  3651. }
  3652. defer ctx.Close()
  3653. if err := os.Chown(filepath.Join(ctx.Dir, "test"), 4242, 4242); err != nil {
  3654. t.Fatal(err)
  3655. }
  3656. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3657. t.Fatal(err)
  3658. }
  3659. logDone("build - change permission on single file")
  3660. }
  3661. func TestBuildSymlinkBreakout(t *testing.T) {
  3662. name := "testbuildsymlinkbreakout"
  3663. tmpdir, err := ioutil.TempDir("", name)
  3664. if err != nil {
  3665. t.Fatal(err)
  3666. }
  3667. defer os.RemoveAll(tmpdir)
  3668. ctx := filepath.Join(tmpdir, "context")
  3669. if err := os.MkdirAll(ctx, 0755); err != nil {
  3670. t.Fatal(err)
  3671. }
  3672. if err := ioutil.WriteFile(filepath.Join(ctx, "Dockerfile"), []byte(`
  3673. from busybox
  3674. add symlink.tar /
  3675. add inject /symlink/
  3676. `), 0644); err != nil {
  3677. t.Fatal(err)
  3678. }
  3679. inject := filepath.Join(ctx, "inject")
  3680. if err := ioutil.WriteFile(inject, nil, 0644); err != nil {
  3681. t.Fatal(err)
  3682. }
  3683. f, err := os.Create(filepath.Join(ctx, "symlink.tar"))
  3684. if err != nil {
  3685. t.Fatal(err)
  3686. }
  3687. w := tar.NewWriter(f)
  3688. w.WriteHeader(&tar.Header{
  3689. Name: "symlink2",
  3690. Typeflag: tar.TypeSymlink,
  3691. Linkname: "/../../../../../../../../../../../../../../",
  3692. Uid: os.Getuid(),
  3693. Gid: os.Getgid(),
  3694. })
  3695. w.WriteHeader(&tar.Header{
  3696. Name: "symlink",
  3697. Typeflag: tar.TypeSymlink,
  3698. Linkname: filepath.Join("symlink2", tmpdir),
  3699. Uid: os.Getuid(),
  3700. Gid: os.Getgid(),
  3701. })
  3702. w.Close()
  3703. f.Close()
  3704. if _, err := buildImageFromContext(name, &FakeContext{Dir: ctx}, false); err != nil {
  3705. t.Fatal(err)
  3706. }
  3707. if _, err := os.Lstat(filepath.Join(tmpdir, "inject")); err == nil {
  3708. t.Fatal("symlink breakout - inject")
  3709. } else if !os.IsNotExist(err) {
  3710. t.Fatalf("unexpected error: %v", err)
  3711. }
  3712. logDone("build - symlink breakout")
  3713. }
  3714. func TestBuildXZHost(t *testing.T) {
  3715. name := "testbuildxzhost"
  3716. defer deleteImages(name)
  3717. ctx, err := fakeContext(`
  3718. FROM busybox
  3719. ADD xz /usr/local/sbin/
  3720. RUN chmod 755 /usr/local/sbin/xz
  3721. ADD test.xz /
  3722. RUN [ ! -e /injected ]`,
  3723. map[string]string{
  3724. "test.xz": "\xfd\x37\x7a\x58\x5a\x00\x00\x04\xe6\xd6\xb4\x46\x02\x00" +
  3725. "\x21\x01\x16\x00\x00\x00\x74\x2f\xe5\xa3\x01\x00\x3f\xfd" +
  3726. "\x37\x7a\x58\x5a\x00\x00\x04\xe6\xd6\xb4\x46\x02\x00\x21",
  3727. "xz": "#!/bin/sh\ntouch /injected",
  3728. })
  3729. if err != nil {
  3730. t.Fatal(err)
  3731. }
  3732. defer ctx.Close()
  3733. if _, err := buildImageFromContext(name, ctx, true); err != nil {
  3734. t.Fatal(err)
  3735. }
  3736. logDone("build - xz host is being used")
  3737. }
  3738. func TestBuildVolumesRetainContents(t *testing.T) {
  3739. var (
  3740. name = "testbuildvolumescontent"
  3741. expected = "some text"
  3742. )
  3743. defer deleteImages(name)
  3744. ctx, err := fakeContext(`
  3745. FROM busybox
  3746. COPY content /foo/file
  3747. VOLUME /foo
  3748. CMD cat /foo/file`,
  3749. map[string]string{
  3750. "content": expected,
  3751. })
  3752. if err != nil {
  3753. t.Fatal(err)
  3754. }
  3755. defer ctx.Close()
  3756. if _, err := buildImageFromContext(name, ctx, false); err != nil {
  3757. t.Fatal(err)
  3758. }
  3759. out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "run", "--rm", name))
  3760. if err != nil {
  3761. t.Fatal(err)
  3762. }
  3763. if out != expected {
  3764. t.Fatalf("expected file contents for /foo/file to be %q but received %q", expected, out)
  3765. }
  3766. logDone("build - volumes retain contents in build")
  3767. }
  3768. func TestBuildRenamedDockerfile(t *testing.T) {
  3769. defer deleteAllContainers()
  3770. ctx, err := fakeContext(`FROM busybox
  3771. RUN echo from Dockerfile`,
  3772. map[string]string{
  3773. "Dockerfile": "FROM busybox\nRUN echo from Dockerfile",
  3774. "files/Dockerfile": "FROM busybox\nRUN echo from files/Dockerfile",
  3775. "files/dFile": "FROM busybox\nRUN echo from files/dFile",
  3776. "dFile": "FROM busybox\nRUN echo from dFile",
  3777. })
  3778. defer ctx.Close()
  3779. if err != nil {
  3780. t.Fatal(err)
  3781. }
  3782. out, _, err := dockerCmdInDir(t, ctx.Dir, "build", "-t", "test1", ".")
  3783. if err != nil {
  3784. t.Fatalf("Failed to build: %s\n%s", out, err)
  3785. }
  3786. if !strings.Contains(out, "from Dockerfile") {
  3787. t.Fatalf("Should have used Dockerfile, output:%s", out)
  3788. }
  3789. out, _, err = dockerCmdInDir(t, ctx.Dir, "build", "-f", "files/Dockerfile", "-t", "test2", ".")
  3790. if err != nil {
  3791. t.Fatal(err)
  3792. }
  3793. if !strings.Contains(out, "from files/Dockerfile") {
  3794. t.Fatalf("Should have used files/Dockerfile, output:%s", out)
  3795. }
  3796. out, _, err = dockerCmdInDir(t, ctx.Dir, "build", "--file=files/dFile", "-t", "test3", ".")
  3797. if err != nil {
  3798. t.Fatal(err)
  3799. }
  3800. if !strings.Contains(out, "from files/dFile") {
  3801. t.Fatalf("Should have used files/dFile, output:%s", out)
  3802. }
  3803. out, _, err = dockerCmdInDir(t, ctx.Dir, "build", "--file=dFile", "-t", "test4", ".")
  3804. if err != nil {
  3805. t.Fatal(err)
  3806. }
  3807. if !strings.Contains(out, "from dFile") {
  3808. t.Fatalf("Should have used dFile, output:%s", out)
  3809. }
  3810. out, _, err = dockerCmdInDir(t, ctx.Dir, "build", "--file=/etc/passwd", "-t", "test5", ".")
  3811. if err == nil {
  3812. t.Fatalf("Was supposed to fail to find passwd")
  3813. }
  3814. if !strings.Contains(out, "The Dockerfile (/etc/passwd) must be within the build context (.)") {
  3815. t.Fatalf("Wrong error message for passwd:%v", out)
  3816. }
  3817. out, _, err = dockerCmdInDir(t, ctx.Dir+"/files", "build", "-f", "../Dockerfile", "-t", "test5", "..")
  3818. if err != nil {
  3819. t.Fatal(err)
  3820. }
  3821. if !strings.Contains(out, "from Dockerfile") {
  3822. t.Fatalf("Should have used root Dockerfile, output:%s", out)
  3823. }
  3824. out, _, err = dockerCmdInDir(t, ctx.Dir+"/files", "build", "-f", ctx.Dir+"/files/Dockerfile", "-t", "test6", "..")
  3825. if err != nil {
  3826. t.Fatal(err)
  3827. }
  3828. if !strings.Contains(out, "from files/Dockerfile") {
  3829. t.Fatalf("Should have used files Dockerfile - 2, output:%s", out)
  3830. }
  3831. out, _, err = dockerCmdInDir(t, ctx.Dir+"/files", "build", "-f", "../Dockerfile", "-t", "test7", ".")
  3832. if err == nil || !strings.Contains(out, "must be within the build context") {
  3833. t.Fatalf("Should have failed with Dockerfile out of context")
  3834. }
  3835. out, _, err = dockerCmdInDir(t, "/tmp", "build", "-t", "test6", ctx.Dir)
  3836. if err != nil {
  3837. t.Fatal(err)
  3838. }
  3839. if !strings.Contains(out, "from Dockerfile") {
  3840. t.Fatalf("Should have used root Dockerfile, output:%s", out)
  3841. }
  3842. logDone("build - rename dockerfile")
  3843. }
  3844. func TestBuildFromOfficialNames(t *testing.T) {
  3845. name := "testbuildfromofficial"
  3846. fromNames := []string{
  3847. "busybox",
  3848. "docker.io/busybox",
  3849. "index.docker.io/busybox",
  3850. "library/busybox",
  3851. "docker.io/library/busybox",
  3852. "index.docker.io/library/busybox",
  3853. }
  3854. for idx, fromName := range fromNames {
  3855. imgName := fmt.Sprintf("%s%d", name, idx)
  3856. _, err := buildImage(imgName, "FROM "+fromName, true)
  3857. if err != nil {
  3858. t.Errorf("Build failed using FROM %s: %s", fromName, err)
  3859. }
  3860. deleteImages(imgName)
  3861. }
  3862. logDone("build - from official names")
  3863. }