server.go 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648
  1. package server
  2. import (
  3. "bufio"
  4. "bytes"
  5. "time"
  6. "encoding/base64"
  7. "encoding/json"
  8. "fmt"
  9. "io"
  10. "net"
  11. "net/http"
  12. "os"
  13. "strconv"
  14. "strings"
  15. "code.google.com/p/go.net/websocket"
  16. "github.com/gorilla/mux"
  17. "github.com/Sirupsen/logrus"
  18. "github.com/docker/docker/api"
  19. "github.com/docker/docker/api/types"
  20. "github.com/docker/docker/daemon"
  21. "github.com/docker/docker/daemon/networkdriver/bridge"
  22. "github.com/docker/docker/engine"
  23. "github.com/docker/docker/graph"
  24. "github.com/docker/docker/pkg/jsonmessage"
  25. "github.com/docker/docker/pkg/parsers"
  26. "github.com/docker/docker/pkg/parsers/filters"
  27. "github.com/docker/docker/pkg/signal"
  28. "github.com/docker/docker/pkg/stdcopy"
  29. "github.com/docker/docker/pkg/streamformatter"
  30. "github.com/docker/docker/pkg/version"
  31. "github.com/docker/docker/registry"
  32. "github.com/docker/docker/utils"
  33. )
  34. var (
  35. activationLock = make(chan struct{})
  36. )
  37. type HttpServer struct {
  38. srv *http.Server
  39. l net.Listener
  40. }
  41. func (s *HttpServer) Serve() error {
  42. return s.srv.Serve(s.l)
  43. }
  44. func (s *HttpServer) Close() error {
  45. return s.l.Close()
  46. }
  47. type HttpApiFunc func(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error
  48. func hijackServer(w http.ResponseWriter) (io.ReadCloser, io.Writer, error) {
  49. conn, _, err := w.(http.Hijacker).Hijack()
  50. if err != nil {
  51. return nil, nil, err
  52. }
  53. // Flush the options to make sure the client sets the raw mode
  54. conn.Write([]byte{})
  55. return conn, conn, nil
  56. }
  57. func closeStreams(streams ...interface{}) {
  58. for _, stream := range streams {
  59. if tcpc, ok := stream.(interface {
  60. CloseWrite() error
  61. }); ok {
  62. tcpc.CloseWrite()
  63. } else if closer, ok := stream.(io.Closer); ok {
  64. closer.Close()
  65. }
  66. }
  67. }
  68. // Check to make sure request's Content-Type is application/json
  69. func checkForJson(r *http.Request) error {
  70. ct := r.Header.Get("Content-Type")
  71. // No Content-Type header is ok as long as there's no Body
  72. if ct == "" {
  73. if r.Body == nil || r.ContentLength == 0 {
  74. return nil
  75. }
  76. }
  77. // Otherwise it better be json
  78. if api.MatchesContentType(ct, "application/json") {
  79. return nil
  80. }
  81. return fmt.Errorf("Content-Type specified (%s) must be 'application/json'", ct)
  82. }
  83. //If we don't do this, POST method without Content-type (even with empty body) will fail
  84. func parseForm(r *http.Request) error {
  85. if r == nil {
  86. return nil
  87. }
  88. if err := r.ParseForm(); err != nil && !strings.HasPrefix(err.Error(), "mime:") {
  89. return err
  90. }
  91. return nil
  92. }
  93. func parseMultipartForm(r *http.Request) error {
  94. if err := r.ParseMultipartForm(4096); err != nil && !strings.HasPrefix(err.Error(), "mime:") {
  95. return err
  96. }
  97. return nil
  98. }
  99. func httpError(w http.ResponseWriter, err error) {
  100. statusCode := http.StatusInternalServerError
  101. // FIXME: this is brittle and should not be necessary.
  102. // If we need to differentiate between different possible error types, we should
  103. // create appropriate error types with clearly defined meaning.
  104. errStr := strings.ToLower(err.Error())
  105. if strings.Contains(errStr, "no such") {
  106. statusCode = http.StatusNotFound
  107. } else if strings.Contains(errStr, "bad parameter") {
  108. statusCode = http.StatusBadRequest
  109. } else if strings.Contains(errStr, "conflict") {
  110. statusCode = http.StatusConflict
  111. } else if strings.Contains(errStr, "impossible") {
  112. statusCode = http.StatusNotAcceptable
  113. } else if strings.Contains(errStr, "wrong login/password") {
  114. statusCode = http.StatusUnauthorized
  115. } else if strings.Contains(errStr, "hasn't been activated") {
  116. statusCode = http.StatusForbidden
  117. }
  118. if err != nil {
  119. logrus.Errorf("HTTP Error: statusCode=%d %v", statusCode, err)
  120. http.Error(w, err.Error(), statusCode)
  121. }
  122. }
  123. // writeJSONEnv writes the engine.Env values to the http response stream as a
  124. // json encoded body.
  125. func writeJSONEnv(w http.ResponseWriter, code int, v engine.Env) error {
  126. w.Header().Set("Content-Type", "application/json")
  127. w.WriteHeader(code)
  128. return v.Encode(w)
  129. }
  130. // writeJSON writes the value v to the http response stream as json with standard
  131. // json encoding.
  132. func writeJSON(w http.ResponseWriter, code int, v interface{}) error {
  133. w.Header().Set("Content-Type", "application/json")
  134. w.WriteHeader(code)
  135. return json.NewEncoder(w).Encode(v)
  136. }
  137. func streamJSON(job *engine.Job, w http.ResponseWriter, flush bool) {
  138. w.Header().Set("Content-Type", "application/json")
  139. if flush {
  140. job.Stdout.Add(utils.NewWriteFlusher(w))
  141. } else {
  142. job.Stdout.Add(w)
  143. }
  144. }
  145. func getDaemon(eng *engine.Engine) *daemon.Daemon {
  146. return eng.HackGetGlobalVar("httpapi.daemon").(*daemon.Daemon)
  147. }
  148. func postAuth(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  149. var config *registry.AuthConfig
  150. err := json.NewDecoder(r.Body).Decode(&config)
  151. r.Body.Close()
  152. if err != nil {
  153. return err
  154. }
  155. d := getDaemon(eng)
  156. status, err := d.RegistryService.Auth(config)
  157. if err != nil {
  158. return err
  159. }
  160. return writeJSON(w, http.StatusOK, &types.AuthResponse{
  161. Status: status,
  162. })
  163. }
  164. func getVersion(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  165. w.Header().Set("Content-Type", "application/json")
  166. eng.ServeHTTP(w, r)
  167. return nil
  168. }
  169. func postContainersKill(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  170. if vars == nil {
  171. return fmt.Errorf("Missing parameter")
  172. }
  173. err := parseForm(r)
  174. if err != nil {
  175. return err
  176. }
  177. var sig uint64
  178. name := vars["name"]
  179. // If we have a signal, look at it. Otherwise, do nothing
  180. if sigStr := vars["signal"]; sigStr != "" {
  181. // Check if we passed the signal as a number:
  182. // The largest legal signal is 31, so let's parse on 5 bits
  183. sig, err = strconv.ParseUint(sigStr, 10, 5)
  184. if err != nil {
  185. // The signal is not a number, treat it as a string (either like
  186. // "KILL" or like "SIGKILL")
  187. sig = uint64(signal.SignalMap[strings.TrimPrefix(sigStr, "SIG")])
  188. }
  189. if sig == 0 {
  190. return fmt.Errorf("Invalid signal: %s", sigStr)
  191. }
  192. }
  193. if err = getDaemon(eng).ContainerKill(name, sig); err != nil {
  194. return err
  195. }
  196. w.WriteHeader(http.StatusNoContent)
  197. return nil
  198. }
  199. func postContainersPause(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  200. if vars == nil {
  201. return fmt.Errorf("Missing parameter")
  202. }
  203. if err := parseForm(r); err != nil {
  204. return err
  205. }
  206. name := vars["name"]
  207. d := getDaemon(eng)
  208. cont, err := d.Get(name)
  209. if err != nil {
  210. return err
  211. }
  212. if err := cont.Pause(); err != nil {
  213. return fmt.Errorf("Cannot pause container %s: %s", name, err)
  214. }
  215. cont.LogEvent("pause")
  216. w.WriteHeader(http.StatusNoContent)
  217. return nil
  218. }
  219. func postContainersUnpause(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  220. if vars == nil {
  221. return fmt.Errorf("Missing parameter")
  222. }
  223. if err := parseForm(r); err != nil {
  224. return err
  225. }
  226. name := vars["name"]
  227. d := getDaemon(eng)
  228. cont, err := d.Get(name)
  229. if err != nil {
  230. return err
  231. }
  232. if err := cont.Unpause(); err != nil {
  233. return fmt.Errorf("Cannot unpause container %s: %s", name, err)
  234. }
  235. cont.LogEvent("unpause")
  236. w.WriteHeader(http.StatusNoContent)
  237. return nil
  238. }
  239. func getContainersExport(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  240. if vars == nil {
  241. return fmt.Errorf("Missing parameter")
  242. }
  243. d := getDaemon(eng)
  244. return d.ContainerExport(vars["name"], w)
  245. }
  246. func getImagesJSON(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  247. if err := parseForm(r); err != nil {
  248. return err
  249. }
  250. imagesConfig := graph.ImagesConfig{
  251. Filters: r.Form.Get("filters"),
  252. // FIXME this parameter could just be a match filter
  253. Filter: r.Form.Get("filter"),
  254. All: toBool(r.Form.Get("all")),
  255. }
  256. images, err := getDaemon(eng).Repositories().Images(&imagesConfig)
  257. if err != nil {
  258. return err
  259. }
  260. if version.GreaterThanOrEqualTo("1.7") {
  261. return writeJSON(w, http.StatusOK, images)
  262. }
  263. legacyImages := []types.LegacyImage{}
  264. for _, image := range images {
  265. for _, repoTag := range image.RepoTags {
  266. repo, tag := parsers.ParseRepositoryTag(repoTag)
  267. legacyImage := types.LegacyImage{
  268. Repository: repo,
  269. Tag: tag,
  270. ID: image.ID,
  271. Created: image.Created,
  272. Size: image.Size,
  273. VirtualSize: image.VirtualSize,
  274. }
  275. legacyImages = append(legacyImages, legacyImage)
  276. }
  277. }
  278. return writeJSON(w, http.StatusOK, legacyImages)
  279. }
  280. func getImagesViz(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  281. if version.GreaterThan("1.6") {
  282. w.WriteHeader(http.StatusNotFound)
  283. return fmt.Errorf("This is now implemented in the client.")
  284. }
  285. eng.ServeHTTP(w, r)
  286. return nil
  287. }
  288. func getInfo(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  289. w.Header().Set("Content-Type", "application/json")
  290. eng.ServeHTTP(w, r)
  291. return nil
  292. }
  293. func getEvents(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  294. if err := parseForm(r); err != nil {
  295. return err
  296. }
  297. var since int64 = -1
  298. if r.Form.Get("since") != "" {
  299. s, err := strconv.ParseInt(r.Form.Get("since"), 10, 64)
  300. if err != nil {
  301. return err
  302. }
  303. since = s
  304. }
  305. var until int64 = -1
  306. if r.Form.Get("until") != "" {
  307. u, err := strconv.ParseInt(r.Form.Get("until"), 10, 64)
  308. if err != nil {
  309. return err
  310. }
  311. until = u
  312. }
  313. timer := time.NewTimer(0)
  314. timer.Stop()
  315. if until > 0 {
  316. dur := time.Unix(until, 0).Sub(time.Now())
  317. timer = time.NewTimer(dur)
  318. }
  319. ef, err := filters.FromParam(r.Form.Get("filters"))
  320. if err != nil {
  321. return err
  322. }
  323. isFiltered := func(field string, filter []string) bool {
  324. if len(filter) == 0 {
  325. return false
  326. }
  327. for _, v := range filter {
  328. if v == field {
  329. return false
  330. }
  331. if strings.Contains(field, ":") {
  332. image := strings.Split(field, ":")
  333. if image[0] == v {
  334. return false
  335. }
  336. }
  337. }
  338. return true
  339. }
  340. d := getDaemon(eng)
  341. es := d.EventsService
  342. w.Header().Set("Content-Type", "application/json")
  343. enc := json.NewEncoder(utils.NewWriteFlusher(w))
  344. getContainerId := func(cn string) string {
  345. c, err := d.Get(cn)
  346. if err != nil {
  347. return ""
  348. }
  349. return c.ID
  350. }
  351. sendEvent := func(ev *jsonmessage.JSONMessage) error {
  352. //incoming container filter can be name,id or partial id, convert and replace as a full container id
  353. for i, cn := range ef["container"] {
  354. ef["container"][i] = getContainerId(cn)
  355. }
  356. if isFiltered(ev.Status, ef["event"]) || isFiltered(ev.From, ef["image"]) ||
  357. isFiltered(ev.ID, ef["container"]) {
  358. return nil
  359. }
  360. return enc.Encode(ev)
  361. }
  362. current, l := es.Subscribe()
  363. defer es.Evict(l)
  364. for _, ev := range current {
  365. if ev.Time < since {
  366. continue
  367. }
  368. if err := sendEvent(ev); err != nil {
  369. return err
  370. }
  371. }
  372. for {
  373. select {
  374. case ev := <-l:
  375. jev, ok := ev.(*jsonmessage.JSONMessage)
  376. if !ok {
  377. continue
  378. }
  379. if err := sendEvent(jev); err != nil {
  380. return err
  381. }
  382. case <-timer.C:
  383. return nil
  384. }
  385. }
  386. }
  387. func getImagesHistory(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  388. if vars == nil {
  389. return fmt.Errorf("Missing parameter")
  390. }
  391. name := vars["name"]
  392. history, err := getDaemon(eng).Repositories().History(name)
  393. if err != nil {
  394. return err
  395. }
  396. return writeJSON(w, http.StatusOK, history)
  397. }
  398. func getContainersChanges(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  399. if vars == nil {
  400. return fmt.Errorf("Missing parameter")
  401. }
  402. name := vars["name"]
  403. if name == "" {
  404. return fmt.Errorf("Container name cannot be empty")
  405. }
  406. d := getDaemon(eng)
  407. cont, err := d.Get(name)
  408. if err != nil {
  409. return err
  410. }
  411. changes, err := cont.Changes()
  412. if err != nil {
  413. return err
  414. }
  415. return writeJSON(w, http.StatusOK, changes)
  416. }
  417. func getContainersTop(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  418. if version.LessThan("1.4") {
  419. return fmt.Errorf("top was improved a lot since 1.3, Please upgrade your docker client.")
  420. }
  421. if vars == nil {
  422. return fmt.Errorf("Missing parameter")
  423. }
  424. if err := parseForm(r); err != nil {
  425. return err
  426. }
  427. procList, err := getDaemon(eng).ContainerTop(vars["name"], r.Form.Get("ps_args"))
  428. if err != nil {
  429. return err
  430. }
  431. return writeJSON(w, http.StatusOK, procList)
  432. }
  433. func getContainersJSON(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  434. var err error
  435. if err = parseForm(r); err != nil {
  436. return err
  437. }
  438. config := &daemon.ContainersConfig{
  439. All: toBool(r.Form.Get("all")),
  440. Size: toBool(r.Form.Get("size")),
  441. Since: r.Form.Get("since"),
  442. Before: r.Form.Get("before"),
  443. Filters: r.Form.Get("filters"),
  444. }
  445. if tmpLimit := r.Form.Get("limit"); tmpLimit != "" {
  446. config.Limit, err = strconv.Atoi(tmpLimit)
  447. if err != nil {
  448. return err
  449. }
  450. }
  451. containers, err := getDaemon(eng).Containers(config)
  452. if err != nil {
  453. return err
  454. }
  455. return writeJSON(w, http.StatusOK, containers)
  456. }
  457. func getContainersStats(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  458. if err := parseForm(r); err != nil {
  459. return err
  460. }
  461. if vars == nil {
  462. return fmt.Errorf("Missing parameter")
  463. }
  464. name := vars["name"]
  465. job := eng.Job("container_stats", name)
  466. streamJSON(job, w, true)
  467. return job.Run()
  468. }
  469. func getContainersLogs(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  470. if err := parseForm(r); err != nil {
  471. return err
  472. }
  473. if vars == nil {
  474. return fmt.Errorf("Missing parameter")
  475. }
  476. // Validate args here, because we can't return not StatusOK after job.Run() call
  477. stdout, stderr := toBool(r.Form.Get("stdout")), toBool(r.Form.Get("stderr"))
  478. if !(stdout || stderr) {
  479. return fmt.Errorf("Bad parameters: you must choose at least one stream")
  480. }
  481. logsConfig := &daemon.ContainerLogsConfig{
  482. Follow: toBool(r.Form.Get("follow")),
  483. Timestamps: toBool(r.Form.Get("timestamps")),
  484. Tail: r.Form.Get("tail"),
  485. UseStdout: stdout,
  486. UseStderr: stderr,
  487. OutStream: utils.NewWriteFlusher(w),
  488. }
  489. d := getDaemon(eng)
  490. if err := d.ContainerLogs(vars["name"], logsConfig); err != nil {
  491. fmt.Fprintf(w, "Error running logs job: %s\n", err)
  492. }
  493. return nil
  494. }
  495. func postImagesTag(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  496. if err := parseForm(r); err != nil {
  497. return err
  498. }
  499. if vars == nil {
  500. return fmt.Errorf("Missing parameter")
  501. }
  502. job := eng.Job("tag", vars["name"], r.Form.Get("repo"), r.Form.Get("tag"))
  503. job.Setenv("force", r.Form.Get("force"))
  504. if err := job.Run(); err != nil {
  505. return err
  506. }
  507. w.WriteHeader(http.StatusCreated)
  508. return nil
  509. }
  510. func postCommit(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  511. if err := parseForm(r); err != nil {
  512. return err
  513. }
  514. var (
  515. config engine.Env
  516. job = eng.Job("commit", r.Form.Get("container"))
  517. stdoutBuffer = bytes.NewBuffer(nil)
  518. )
  519. if err := checkForJson(r); err != nil {
  520. return err
  521. }
  522. if err := config.Decode(r.Body); err != nil {
  523. logrus.Errorf("%s", err)
  524. }
  525. if r.FormValue("pause") == "" && version.GreaterThanOrEqualTo("1.13") {
  526. job.Setenv("pause", "1")
  527. } else {
  528. job.Setenv("pause", r.FormValue("pause"))
  529. }
  530. job.Setenv("repo", r.Form.Get("repo"))
  531. job.Setenv("tag", r.Form.Get("tag"))
  532. job.Setenv("author", r.Form.Get("author"))
  533. job.Setenv("comment", r.Form.Get("comment"))
  534. job.SetenvList("changes", r.Form["changes"])
  535. job.SetenvSubEnv("config", &config)
  536. job.Stdout.Add(stdoutBuffer)
  537. if err := job.Run(); err != nil {
  538. return err
  539. }
  540. return writeJSON(w, http.StatusCreated, &types.ContainerCommitResponse{
  541. ID: engine.Tail(stdoutBuffer, 1),
  542. })
  543. }
  544. // Creates an image from Pull or from Import
  545. func postImagesCreate(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  546. if err := parseForm(r); err != nil {
  547. return err
  548. }
  549. var (
  550. image = r.Form.Get("fromImage")
  551. repo = r.Form.Get("repo")
  552. tag = r.Form.Get("tag")
  553. job *engine.Job
  554. )
  555. authEncoded := r.Header.Get("X-Registry-Auth")
  556. authConfig := &registry.AuthConfig{}
  557. if authEncoded != "" {
  558. authJson := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authEncoded))
  559. if err := json.NewDecoder(authJson).Decode(authConfig); err != nil {
  560. // for a pull it is not an error if no auth was given
  561. // to increase compatibility with the existing api it is defaulting to be empty
  562. authConfig = &registry.AuthConfig{}
  563. }
  564. }
  565. if image != "" { //pull
  566. if tag == "" {
  567. image, tag = parsers.ParseRepositoryTag(image)
  568. }
  569. metaHeaders := map[string][]string{}
  570. for k, v := range r.Header {
  571. if strings.HasPrefix(k, "X-Meta-") {
  572. metaHeaders[k] = v
  573. }
  574. }
  575. job = eng.Job("pull", image, tag)
  576. job.SetenvBool("parallel", version.GreaterThan("1.3"))
  577. job.SetenvJson("metaHeaders", metaHeaders)
  578. job.SetenvJson("authConfig", authConfig)
  579. } else { //import
  580. if tag == "" {
  581. repo, tag = parsers.ParseRepositoryTag(repo)
  582. }
  583. job = eng.Job("import", r.Form.Get("fromSrc"), repo, tag)
  584. job.Stdin.Add(r.Body)
  585. job.SetenvList("changes", r.Form["changes"])
  586. }
  587. if version.GreaterThan("1.0") {
  588. job.SetenvBool("json", true)
  589. streamJSON(job, w, true)
  590. } else {
  591. job.Stdout.Add(utils.NewWriteFlusher(w))
  592. }
  593. if err := job.Run(); err != nil {
  594. if !job.Stdout.Used() {
  595. return err
  596. }
  597. sf := streamformatter.NewStreamFormatter(version.GreaterThan("1.0"))
  598. w.Write(sf.FormatError(err))
  599. }
  600. return nil
  601. }
  602. func getImagesSearch(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  603. if err := parseForm(r); err != nil {
  604. return err
  605. }
  606. var (
  607. config *registry.AuthConfig
  608. authEncoded = r.Header.Get("X-Registry-Auth")
  609. headers = map[string][]string{}
  610. )
  611. if authEncoded != "" {
  612. authJson := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authEncoded))
  613. if err := json.NewDecoder(authJson).Decode(&config); err != nil {
  614. // for a search it is not an error if no auth was given
  615. // to increase compatibility with the existing api it is defaulting to be empty
  616. config = &registry.AuthConfig{}
  617. }
  618. }
  619. for k, v := range r.Header {
  620. if strings.HasPrefix(k, "X-Meta-") {
  621. headers[k] = v
  622. }
  623. }
  624. d := getDaemon(eng)
  625. query, err := d.RegistryService.Search(r.Form.Get("term"), config, headers)
  626. if err != nil {
  627. return err
  628. }
  629. return json.NewEncoder(w).Encode(query.Results)
  630. }
  631. func postImagesPush(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  632. if vars == nil {
  633. return fmt.Errorf("Missing parameter")
  634. }
  635. metaHeaders := map[string][]string{}
  636. for k, v := range r.Header {
  637. if strings.HasPrefix(k, "X-Meta-") {
  638. metaHeaders[k] = v
  639. }
  640. }
  641. if err := parseForm(r); err != nil {
  642. return err
  643. }
  644. authConfig := &registry.AuthConfig{}
  645. authEncoded := r.Header.Get("X-Registry-Auth")
  646. if authEncoded != "" {
  647. // the new format is to handle the authConfig as a header
  648. authJson := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authEncoded))
  649. if err := json.NewDecoder(authJson).Decode(authConfig); err != nil {
  650. // to increase compatibility to existing api it is defaulting to be empty
  651. authConfig = &registry.AuthConfig{}
  652. }
  653. } else {
  654. // the old format is supported for compatibility if there was no authConfig header
  655. if err := json.NewDecoder(r.Body).Decode(authConfig); err != nil {
  656. return fmt.Errorf("Bad parameters and missing X-Registry-Auth: %v", err)
  657. }
  658. }
  659. job := eng.Job("push", vars["name"])
  660. job.SetenvJson("metaHeaders", metaHeaders)
  661. job.SetenvJson("authConfig", authConfig)
  662. job.Setenv("tag", r.Form.Get("tag"))
  663. if version.GreaterThan("1.0") {
  664. job.SetenvBool("json", true)
  665. streamJSON(job, w, true)
  666. } else {
  667. job.Stdout.Add(utils.NewWriteFlusher(w))
  668. }
  669. if err := job.Run(); err != nil {
  670. if !job.Stdout.Used() {
  671. return err
  672. }
  673. sf := streamformatter.NewStreamFormatter(version.GreaterThan("1.0"))
  674. w.Write(sf.FormatError(err))
  675. }
  676. return nil
  677. }
  678. func getImagesGet(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  679. if vars == nil {
  680. return fmt.Errorf("Missing parameter")
  681. }
  682. if err := parseForm(r); err != nil {
  683. return err
  684. }
  685. if version.GreaterThan("1.0") {
  686. w.Header().Set("Content-Type", "application/x-tar")
  687. }
  688. var job *engine.Job
  689. if name, ok := vars["name"]; ok {
  690. job = eng.Job("image_export", name)
  691. } else {
  692. job = eng.Job("image_export", r.Form["names"]...)
  693. }
  694. job.Stdout.Add(w)
  695. return job.Run()
  696. }
  697. func postImagesLoad(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  698. job := eng.Job("load")
  699. job.Stdin.Add(r.Body)
  700. job.Stdout.Add(w)
  701. return job.Run()
  702. }
  703. func postContainersCreate(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  704. if err := parseForm(r); err != nil {
  705. return nil
  706. }
  707. if err := checkForJson(r); err != nil {
  708. return err
  709. }
  710. var (
  711. job = eng.Job("create", r.Form.Get("name"))
  712. outWarnings []string
  713. stdoutBuffer = bytes.NewBuffer(nil)
  714. warnings = bytes.NewBuffer(nil)
  715. )
  716. if err := job.DecodeEnv(r.Body); err != nil {
  717. return err
  718. }
  719. // Read container ID from the first line of stdout
  720. job.Stdout.Add(stdoutBuffer)
  721. // Read warnings from stderr
  722. job.Stderr.Add(warnings)
  723. if err := job.Run(); err != nil {
  724. return err
  725. }
  726. // Parse warnings from stderr
  727. scanner := bufio.NewScanner(warnings)
  728. for scanner.Scan() {
  729. outWarnings = append(outWarnings, scanner.Text())
  730. }
  731. return writeJSON(w, http.StatusCreated, &types.ContainerCreateResponse{
  732. ID: engine.Tail(stdoutBuffer, 1),
  733. Warnings: outWarnings,
  734. })
  735. }
  736. func postContainersRestart(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  737. if err := parseForm(r); err != nil {
  738. return err
  739. }
  740. if vars == nil {
  741. return fmt.Errorf("Missing parameter")
  742. }
  743. job := eng.Job("restart", vars["name"])
  744. job.Setenv("t", r.Form.Get("t"))
  745. if err := job.Run(); err != nil {
  746. return err
  747. }
  748. w.WriteHeader(http.StatusNoContent)
  749. return nil
  750. }
  751. func postContainerRename(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  752. if err := parseForm(r); err != nil {
  753. return err
  754. }
  755. if vars == nil {
  756. return fmt.Errorf("Missing parameter")
  757. }
  758. d := getDaemon(eng)
  759. name := vars["name"]
  760. newName := r.Form.Get("name")
  761. if err := d.ContainerRename(name, newName); err != nil {
  762. return err
  763. }
  764. w.WriteHeader(http.StatusNoContent)
  765. return nil
  766. }
  767. func deleteContainers(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  768. if err := parseForm(r); err != nil {
  769. return err
  770. }
  771. if vars == nil {
  772. return fmt.Errorf("Missing parameter")
  773. }
  774. name := vars["name"]
  775. if name == "" {
  776. return fmt.Errorf("Container name cannot be empty")
  777. }
  778. d := getDaemon(eng)
  779. config := &daemon.ContainerRmConfig{
  780. ForceRemove: toBool(r.Form.Get("force")),
  781. RemoveVolume: toBool(r.Form.Get("v")),
  782. RemoveLink: toBool(r.Form.Get("link")),
  783. }
  784. if err := d.ContainerRm(name, config); err != nil {
  785. return err
  786. }
  787. w.WriteHeader(http.StatusNoContent)
  788. return nil
  789. }
  790. func deleteImages(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  791. if err := parseForm(r); err != nil {
  792. return err
  793. }
  794. if vars == nil {
  795. return fmt.Errorf("Missing parameter")
  796. }
  797. d := getDaemon(eng)
  798. name := vars["name"]
  799. force := toBool(r.Form.Get("force"))
  800. noprune := toBool(r.Form.Get("noprune"))
  801. list, err := d.ImageDelete(name, force, noprune)
  802. if err != nil {
  803. return err
  804. }
  805. return writeJSON(w, http.StatusOK, list)
  806. }
  807. func postContainersStart(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  808. if vars == nil {
  809. return fmt.Errorf("Missing parameter")
  810. }
  811. var (
  812. name = vars["name"]
  813. job = eng.Job("start", name)
  814. )
  815. // If contentLength is -1, we can assumed chunked encoding
  816. // or more technically that the length is unknown
  817. // http://golang.org/src/pkg/net/http/request.go#L139
  818. // net/http otherwise seems to swallow any headers related to chunked encoding
  819. // including r.TransferEncoding
  820. // allow a nil body for backwards compatibility
  821. if r.Body != nil && (r.ContentLength > 0 || r.ContentLength == -1) {
  822. if err := checkForJson(r); err != nil {
  823. return err
  824. }
  825. if err := job.DecodeEnv(r.Body); err != nil {
  826. return err
  827. }
  828. }
  829. if err := job.Run(); err != nil {
  830. if err.Error() == "Container already started" {
  831. w.WriteHeader(http.StatusNotModified)
  832. return nil
  833. }
  834. return err
  835. }
  836. w.WriteHeader(http.StatusNoContent)
  837. return nil
  838. }
  839. func postContainersStop(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  840. if err := parseForm(r); err != nil {
  841. return err
  842. }
  843. if vars == nil {
  844. return fmt.Errorf("Missing parameter")
  845. }
  846. d := getDaemon(eng)
  847. seconds, err := strconv.Atoi(r.Form.Get("t"))
  848. if err != nil {
  849. return err
  850. }
  851. if err := d.ContainerStop(vars["name"], seconds); err != nil {
  852. if err.Error() == "Container already stopped" {
  853. w.WriteHeader(http.StatusNotModified)
  854. return nil
  855. }
  856. return err
  857. }
  858. w.WriteHeader(http.StatusNoContent)
  859. return nil
  860. }
  861. func postContainersWait(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  862. if vars == nil {
  863. return fmt.Errorf("Missing parameter")
  864. }
  865. name := vars["name"]
  866. d := getDaemon(eng)
  867. cont, err := d.Get(name)
  868. if err != nil {
  869. return err
  870. }
  871. status, _ := cont.WaitStop(-1 * time.Second)
  872. return writeJSON(w, http.StatusOK, &types.ContainerWaitResponse{
  873. StatusCode: status,
  874. })
  875. }
  876. func postContainersResize(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  877. if err := parseForm(r); err != nil {
  878. return err
  879. }
  880. if vars == nil {
  881. return fmt.Errorf("Missing parameter")
  882. }
  883. height, err := strconv.Atoi(r.Form.Get("h"))
  884. if err != nil {
  885. return nil
  886. }
  887. width, err := strconv.Atoi(r.Form.Get("w"))
  888. if err != nil {
  889. return nil
  890. }
  891. d := getDaemon(eng)
  892. cont, err := d.Get(vars["name"])
  893. if err != nil {
  894. return err
  895. }
  896. if err := cont.Resize(height, width); err != nil {
  897. return err
  898. }
  899. return nil
  900. }
  901. func postContainersAttach(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  902. if err := parseForm(r); err != nil {
  903. return err
  904. }
  905. if vars == nil {
  906. return fmt.Errorf("Missing parameter")
  907. }
  908. d := getDaemon(eng)
  909. cont, err := d.Get(vars["name"])
  910. if err != nil {
  911. return err
  912. }
  913. inStream, outStream, err := hijackServer(w)
  914. if err != nil {
  915. return err
  916. }
  917. defer closeStreams(inStream, outStream)
  918. var errStream io.Writer
  919. if _, ok := r.Header["Upgrade"]; ok {
  920. fmt.Fprintf(outStream, "HTTP/1.1 101 UPGRADED\r\nContent-Type: application/vnd.docker.raw-stream\r\nConnection: Upgrade\r\nUpgrade: tcp\r\n\r\n")
  921. } else {
  922. fmt.Fprintf(outStream, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n")
  923. }
  924. if !cont.Config.Tty && version.GreaterThanOrEqualTo("1.6") {
  925. errStream = stdcopy.NewStdWriter(outStream, stdcopy.Stderr)
  926. outStream = stdcopy.NewStdWriter(outStream, stdcopy.Stdout)
  927. } else {
  928. errStream = outStream
  929. }
  930. logs := toBool(r.Form.Get("logs"))
  931. stream := toBool(r.Form.Get("stream"))
  932. var stdin io.ReadCloser
  933. var stdout, stderr io.Writer
  934. if toBool(r.Form.Get("stdin")) {
  935. stdin = inStream
  936. }
  937. if toBool(r.Form.Get("stdout")) {
  938. stdout = outStream
  939. }
  940. if toBool(r.Form.Get("stderr")) {
  941. stderr = errStream
  942. }
  943. if err := cont.AttachWithLogs(stdin, stdout, stderr, logs, stream); err != nil {
  944. fmt.Fprintf(outStream, "Error attaching: %s\n", err)
  945. }
  946. return nil
  947. }
  948. func wsContainersAttach(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  949. if err := parseForm(r); err != nil {
  950. return err
  951. }
  952. if vars == nil {
  953. return fmt.Errorf("Missing parameter")
  954. }
  955. d := getDaemon(eng)
  956. cont, err := d.Get(vars["name"])
  957. if err != nil {
  958. return err
  959. }
  960. h := websocket.Handler(func(ws *websocket.Conn) {
  961. defer ws.Close()
  962. logs := r.Form.Get("logs") != ""
  963. stream := r.Form.Get("stream") != ""
  964. if err := cont.AttachWithLogs(ws, ws, ws, logs, stream); err != nil {
  965. logrus.Errorf("Error attaching websocket: %s", err)
  966. }
  967. })
  968. h.ServeHTTP(w, r)
  969. return nil
  970. }
  971. func getContainersByName(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  972. if vars == nil {
  973. return fmt.Errorf("Missing parameter")
  974. }
  975. var job = eng.Job("container_inspect", vars["name"])
  976. if version.LessThan("1.12") {
  977. job.SetenvBool("raw", true)
  978. }
  979. streamJSON(job, w, false)
  980. return job.Run()
  981. }
  982. func getExecByID(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  983. if vars == nil {
  984. return fmt.Errorf("Missing parameter 'id'")
  985. }
  986. d := getDaemon(eng)
  987. eConfig, err := d.ContainerExecInspect(vars["id"])
  988. if err != nil {
  989. return err
  990. }
  991. return writeJSON(w, http.StatusOK, eConfig)
  992. }
  993. func getImagesByName(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  994. if vars == nil {
  995. return fmt.Errorf("Missing parameter")
  996. }
  997. var job = eng.Job("image_inspect", vars["name"])
  998. if version.LessThan("1.12") {
  999. job.SetenvBool("raw", true)
  1000. }
  1001. streamJSON(job, w, false)
  1002. return job.Run()
  1003. }
  1004. func postBuild(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1005. if version.LessThan("1.3") {
  1006. return fmt.Errorf("Multipart upload for build is no longer supported. Please upgrade your docker client.")
  1007. }
  1008. var (
  1009. authEncoded = r.Header.Get("X-Registry-Auth")
  1010. authConfig = &registry.AuthConfig{}
  1011. configFileEncoded = r.Header.Get("X-Registry-Config")
  1012. configFile = &registry.ConfigFile{}
  1013. job = eng.Job("build")
  1014. )
  1015. // This block can be removed when API versions prior to 1.9 are deprecated.
  1016. // Both headers will be parsed and sent along to the daemon, but if a non-empty
  1017. // ConfigFile is present, any value provided as an AuthConfig directly will
  1018. // be overridden. See BuildFile::CmdFrom for details.
  1019. if version.LessThan("1.9") && authEncoded != "" {
  1020. authJson := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authEncoded))
  1021. if err := json.NewDecoder(authJson).Decode(authConfig); err != nil {
  1022. // for a pull it is not an error if no auth was given
  1023. // to increase compatibility with the existing api it is defaulting to be empty
  1024. authConfig = &registry.AuthConfig{}
  1025. }
  1026. }
  1027. if configFileEncoded != "" {
  1028. configFileJson := base64.NewDecoder(base64.URLEncoding, strings.NewReader(configFileEncoded))
  1029. if err := json.NewDecoder(configFileJson).Decode(configFile); err != nil {
  1030. // for a pull it is not an error if no auth was given
  1031. // to increase compatibility with the existing api it is defaulting to be empty
  1032. configFile = &registry.ConfigFile{}
  1033. }
  1034. }
  1035. if version.GreaterThanOrEqualTo("1.8") {
  1036. job.SetenvBool("json", true)
  1037. streamJSON(job, w, true)
  1038. } else {
  1039. job.Stdout.Add(utils.NewWriteFlusher(w))
  1040. }
  1041. if toBool(r.FormValue("forcerm")) && version.GreaterThanOrEqualTo("1.12") {
  1042. job.Setenv("rm", "1")
  1043. } else if r.FormValue("rm") == "" && version.GreaterThanOrEqualTo("1.12") {
  1044. job.Setenv("rm", "1")
  1045. } else {
  1046. job.Setenv("rm", r.FormValue("rm"))
  1047. }
  1048. if toBool(r.FormValue("pull")) && version.GreaterThanOrEqualTo("1.16") {
  1049. job.Setenv("pull", "1")
  1050. }
  1051. job.Stdin.Add(r.Body)
  1052. job.Setenv("remote", r.FormValue("remote"))
  1053. job.Setenv("dockerfile", r.FormValue("dockerfile"))
  1054. job.Setenv("t", r.FormValue("t"))
  1055. job.Setenv("q", r.FormValue("q"))
  1056. job.Setenv("nocache", r.FormValue("nocache"))
  1057. job.Setenv("forcerm", r.FormValue("forcerm"))
  1058. job.SetenvJson("authConfig", authConfig)
  1059. job.SetenvJson("configFile", configFile)
  1060. job.Setenv("memswap", r.FormValue("memswap"))
  1061. job.Setenv("memory", r.FormValue("memory"))
  1062. job.Setenv("cpusetcpus", r.FormValue("cpusetcpus"))
  1063. job.Setenv("cpushares", r.FormValue("cpushares"))
  1064. // Job cancellation. Note: not all job types support this.
  1065. if closeNotifier, ok := w.(http.CloseNotifier); ok {
  1066. finished := make(chan struct{})
  1067. defer close(finished)
  1068. go func() {
  1069. select {
  1070. case <-finished:
  1071. case <-closeNotifier.CloseNotify():
  1072. logrus.Infof("Client disconnected, cancelling job: %s", job.Name)
  1073. job.Cancel()
  1074. }
  1075. }()
  1076. }
  1077. if err := job.Run(); err != nil {
  1078. if !job.Stdout.Used() {
  1079. return err
  1080. }
  1081. sf := streamformatter.NewStreamFormatter(version.GreaterThanOrEqualTo("1.8"))
  1082. w.Write(sf.FormatError(err))
  1083. }
  1084. return nil
  1085. }
  1086. func postContainersCopy(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1087. if vars == nil {
  1088. return fmt.Errorf("Missing parameter")
  1089. }
  1090. if err := checkForJson(r); err != nil {
  1091. return err
  1092. }
  1093. cfg := types.CopyConfig{}
  1094. if err := json.NewDecoder(r.Body).Decode(&cfg); err != nil {
  1095. return err
  1096. }
  1097. if cfg.Resource == "" {
  1098. return fmt.Errorf("Path cannot be empty")
  1099. }
  1100. res := cfg.Resource
  1101. if res[0] == '/' {
  1102. res = res[1:]
  1103. }
  1104. cont, err := getDaemon(eng).Get(vars["name"])
  1105. if err != nil {
  1106. logrus.Errorf("%v", err)
  1107. if strings.Contains(strings.ToLower(err.Error()), "no such id") {
  1108. w.WriteHeader(http.StatusNotFound)
  1109. return nil
  1110. }
  1111. }
  1112. data, err := cont.Copy(res)
  1113. if err != nil {
  1114. logrus.Errorf("%v", err)
  1115. if os.IsNotExist(err) {
  1116. return fmt.Errorf("Could not find the file %s in container %s", cfg.Resource, vars["name"])
  1117. }
  1118. return err
  1119. }
  1120. defer data.Close()
  1121. w.Header().Set("Content-Type", "application/x-tar")
  1122. if _, err := io.Copy(w, data); err != nil {
  1123. return err
  1124. }
  1125. return nil
  1126. }
  1127. func postContainerExecCreate(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1128. if err := parseForm(r); err != nil {
  1129. return nil
  1130. }
  1131. var (
  1132. name = vars["name"]
  1133. job = eng.Job("execCreate", name)
  1134. stdoutBuffer = bytes.NewBuffer(nil)
  1135. outWarnings []string
  1136. warnings = bytes.NewBuffer(nil)
  1137. )
  1138. if err := job.DecodeEnv(r.Body); err != nil {
  1139. return err
  1140. }
  1141. job.Stdout.Add(stdoutBuffer)
  1142. // Read warnings from stderr
  1143. job.Stderr.Add(warnings)
  1144. // Register an instance of Exec in container.
  1145. if err := job.Run(); err != nil {
  1146. fmt.Fprintf(os.Stderr, "Error setting up exec command in container %s: %s\n", name, err)
  1147. return err
  1148. }
  1149. // Parse warnings from stderr
  1150. scanner := bufio.NewScanner(warnings)
  1151. for scanner.Scan() {
  1152. outWarnings = append(outWarnings, scanner.Text())
  1153. }
  1154. return writeJSON(w, http.StatusCreated, &types.ContainerExecCreateResponse{
  1155. ID: engine.Tail(stdoutBuffer, 1),
  1156. Warnings: outWarnings,
  1157. })
  1158. }
  1159. // TODO(vishh): Refactor the code to avoid having to specify stream config as part of both create and start.
  1160. func postContainerExecStart(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1161. if err := parseForm(r); err != nil {
  1162. return nil
  1163. }
  1164. var (
  1165. name = vars["name"]
  1166. job = eng.Job("execStart", name)
  1167. errOut io.Writer = os.Stderr
  1168. )
  1169. if err := job.DecodeEnv(r.Body); err != nil {
  1170. return err
  1171. }
  1172. if !job.GetenvBool("Detach") {
  1173. // Setting up the streaming http interface.
  1174. inStream, outStream, err := hijackServer(w)
  1175. if err != nil {
  1176. return err
  1177. }
  1178. defer closeStreams(inStream, outStream)
  1179. var errStream io.Writer
  1180. if _, ok := r.Header["Upgrade"]; ok {
  1181. fmt.Fprintf(outStream, "HTTP/1.1 101 UPGRADED\r\nContent-Type: application/vnd.docker.raw-stream\r\nConnection: Upgrade\r\nUpgrade: tcp\r\n\r\n")
  1182. } else {
  1183. fmt.Fprintf(outStream, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n")
  1184. }
  1185. if !job.GetenvBool("Tty") && version.GreaterThanOrEqualTo("1.6") {
  1186. errStream = stdcopy.NewStdWriter(outStream, stdcopy.Stderr)
  1187. outStream = stdcopy.NewStdWriter(outStream, stdcopy.Stdout)
  1188. } else {
  1189. errStream = outStream
  1190. }
  1191. job.Stdin.Add(inStream)
  1192. job.Stdout.Add(outStream)
  1193. job.Stderr.Set(errStream)
  1194. errOut = outStream
  1195. }
  1196. // Now run the user process in container.
  1197. job.SetCloseIO(false)
  1198. if err := job.Run(); err != nil {
  1199. fmt.Fprintf(errOut, "Error starting exec command in container %s: %s\n", name, err)
  1200. return err
  1201. }
  1202. w.WriteHeader(http.StatusNoContent)
  1203. return nil
  1204. }
  1205. func postContainerExecResize(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1206. if err := parseForm(r); err != nil {
  1207. return err
  1208. }
  1209. if vars == nil {
  1210. return fmt.Errorf("Missing parameter")
  1211. }
  1212. height, err := strconv.Atoi(r.Form.Get("h"))
  1213. if err != nil {
  1214. return nil
  1215. }
  1216. width, err := strconv.Atoi(r.Form.Get("w"))
  1217. if err != nil {
  1218. return nil
  1219. }
  1220. d := getDaemon(eng)
  1221. if err := d.ContainerExecResize(vars["name"], height, width); err != nil {
  1222. return err
  1223. }
  1224. return nil
  1225. }
  1226. func optionsHandler(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1227. w.WriteHeader(http.StatusOK)
  1228. return nil
  1229. }
  1230. func writeCorsHeaders(w http.ResponseWriter, r *http.Request, corsHeaders string) {
  1231. logrus.Debugf("CORS header is enabled and set to: %s", corsHeaders)
  1232. w.Header().Add("Access-Control-Allow-Origin", corsHeaders)
  1233. w.Header().Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, X-Registry-Auth")
  1234. w.Header().Add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS")
  1235. }
  1236. func ping(eng *engine.Engine, version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1237. _, err := w.Write([]byte{'O', 'K'})
  1238. return err
  1239. }
  1240. func makeHttpHandler(eng *engine.Engine, logging bool, localMethod string, localRoute string, handlerFunc HttpApiFunc, corsHeaders string, dockerVersion version.Version) http.HandlerFunc {
  1241. return func(w http.ResponseWriter, r *http.Request) {
  1242. // log the request
  1243. logrus.Debugf("Calling %s %s", localMethod, localRoute)
  1244. if logging {
  1245. logrus.Infof("%s %s", r.Method, r.RequestURI)
  1246. }
  1247. if strings.Contains(r.Header.Get("User-Agent"), "Docker-Client/") {
  1248. userAgent := strings.Split(r.Header.Get("User-Agent"), "/")
  1249. if len(userAgent) == 2 && !dockerVersion.Equal(version.Version(userAgent[1])) {
  1250. logrus.Debugf("Warning: client and server don't have the same version (client: %s, server: %s)", userAgent[1], dockerVersion)
  1251. }
  1252. }
  1253. version := version.Version(mux.Vars(r)["version"])
  1254. if version == "" {
  1255. version = api.APIVERSION
  1256. }
  1257. if corsHeaders != "" {
  1258. writeCorsHeaders(w, r, corsHeaders)
  1259. }
  1260. if version.GreaterThan(api.APIVERSION) {
  1261. http.Error(w, fmt.Errorf("client and server don't have same version (client API version: %s, server API version: %s)", version, api.APIVERSION).Error(), http.StatusNotFound)
  1262. return
  1263. }
  1264. if err := handlerFunc(eng, version, w, r, mux.Vars(r)); err != nil {
  1265. logrus.Errorf("Handler for %s %s returned error: %s", localMethod, localRoute, err)
  1266. httpError(w, err)
  1267. }
  1268. }
  1269. }
  1270. // we keep enableCors just for legacy usage, need to be removed in the future
  1271. func createRouter(eng *engine.Engine, logging, enableCors bool, corsHeaders string, dockerVersion string) *mux.Router {
  1272. r := mux.NewRouter()
  1273. if os.Getenv("DEBUG") != "" {
  1274. ProfilerSetup(r, "/debug/")
  1275. }
  1276. m := map[string]map[string]HttpApiFunc{
  1277. "GET": {
  1278. "/_ping": ping,
  1279. "/events": getEvents,
  1280. "/info": getInfo,
  1281. "/version": getVersion,
  1282. "/images/json": getImagesJSON,
  1283. "/images/viz": getImagesViz,
  1284. "/images/search": getImagesSearch,
  1285. "/images/get": getImagesGet,
  1286. "/images/{name:.*}/get": getImagesGet,
  1287. "/images/{name:.*}/history": getImagesHistory,
  1288. "/images/{name:.*}/json": getImagesByName,
  1289. "/containers/ps": getContainersJSON,
  1290. "/containers/json": getContainersJSON,
  1291. "/containers/{name:.*}/export": getContainersExport,
  1292. "/containers/{name:.*}/changes": getContainersChanges,
  1293. "/containers/{name:.*}/json": getContainersByName,
  1294. "/containers/{name:.*}/top": getContainersTop,
  1295. "/containers/{name:.*}/logs": getContainersLogs,
  1296. "/containers/{name:.*}/stats": getContainersStats,
  1297. "/containers/{name:.*}/attach/ws": wsContainersAttach,
  1298. "/exec/{id:.*}/json": getExecByID,
  1299. },
  1300. "POST": {
  1301. "/auth": postAuth,
  1302. "/commit": postCommit,
  1303. "/build": postBuild,
  1304. "/images/create": postImagesCreate,
  1305. "/images/load": postImagesLoad,
  1306. "/images/{name:.*}/push": postImagesPush,
  1307. "/images/{name:.*}/tag": postImagesTag,
  1308. "/containers/create": postContainersCreate,
  1309. "/containers/{name:.*}/kill": postContainersKill,
  1310. "/containers/{name:.*}/pause": postContainersPause,
  1311. "/containers/{name:.*}/unpause": postContainersUnpause,
  1312. "/containers/{name:.*}/restart": postContainersRestart,
  1313. "/containers/{name:.*}/start": postContainersStart,
  1314. "/containers/{name:.*}/stop": postContainersStop,
  1315. "/containers/{name:.*}/wait": postContainersWait,
  1316. "/containers/{name:.*}/resize": postContainersResize,
  1317. "/containers/{name:.*}/attach": postContainersAttach,
  1318. "/containers/{name:.*}/copy": postContainersCopy,
  1319. "/containers/{name:.*}/exec": postContainerExecCreate,
  1320. "/exec/{name:.*}/start": postContainerExecStart,
  1321. "/exec/{name:.*}/resize": postContainerExecResize,
  1322. "/containers/{name:.*}/rename": postContainerRename,
  1323. },
  1324. "DELETE": {
  1325. "/containers/{name:.*}": deleteContainers,
  1326. "/images/{name:.*}": deleteImages,
  1327. },
  1328. "OPTIONS": {
  1329. "": optionsHandler,
  1330. },
  1331. }
  1332. // If "api-cors-header" is not given, but "api-enable-cors" is true, we set cors to "*"
  1333. // otherwise, all head values will be passed to HTTP handler
  1334. if corsHeaders == "" && enableCors {
  1335. corsHeaders = "*"
  1336. }
  1337. for method, routes := range m {
  1338. for route, fct := range routes {
  1339. logrus.Debugf("Registering %s, %s", method, route)
  1340. // NOTE: scope issue, make sure the variables are local and won't be changed
  1341. localRoute := route
  1342. localFct := fct
  1343. localMethod := method
  1344. // build the handler function
  1345. f := makeHttpHandler(eng, logging, localMethod, localRoute, localFct, corsHeaders, version.Version(dockerVersion))
  1346. // add the new route
  1347. if localRoute == "" {
  1348. r.Methods(localMethod).HandlerFunc(f)
  1349. } else {
  1350. r.Path("/v{version:[0-9.]+}" + localRoute).Methods(localMethod).HandlerFunc(f)
  1351. r.Path(localRoute).Methods(localMethod).HandlerFunc(f)
  1352. }
  1353. }
  1354. }
  1355. return r
  1356. }
  1357. // ServeRequest processes a single http request to the docker remote api.
  1358. // FIXME: refactor this to be part of Server and not require re-creating a new
  1359. // router each time. This requires first moving ListenAndServe into Server.
  1360. func ServeRequest(eng *engine.Engine, apiversion version.Version, w http.ResponseWriter, req *http.Request) {
  1361. router := createRouter(eng, false, true, "", "")
  1362. // Insert APIVERSION into the request as a convenience
  1363. req.URL.Path = fmt.Sprintf("/v%s%s", apiversion, req.URL.Path)
  1364. router.ServeHTTP(w, req)
  1365. }
  1366. func allocateDaemonPort(addr string) error {
  1367. host, port, err := net.SplitHostPort(addr)
  1368. if err != nil {
  1369. return err
  1370. }
  1371. intPort, err := strconv.Atoi(port)
  1372. if err != nil {
  1373. return err
  1374. }
  1375. var hostIPs []net.IP
  1376. if parsedIP := net.ParseIP(host); parsedIP != nil {
  1377. hostIPs = append(hostIPs, parsedIP)
  1378. } else if hostIPs, err = net.LookupIP(host); err != nil {
  1379. return fmt.Errorf("failed to lookup %s address in host specification", host)
  1380. }
  1381. for _, hostIP := range hostIPs {
  1382. if _, err := bridge.RequestPort(hostIP, "tcp", intPort); err != nil {
  1383. return fmt.Errorf("failed to allocate daemon listening port %d (err: %v)", intPort, err)
  1384. }
  1385. }
  1386. return nil
  1387. }
  1388. type Server interface {
  1389. Serve() error
  1390. Close() error
  1391. }
  1392. // ServeApi loops through all of the protocols sent in to docker and spawns
  1393. // off a go routine to setup a serving http.Server for each.
  1394. func ServeApi(job *engine.Job) error {
  1395. if len(job.Args) == 0 {
  1396. return fmt.Errorf("usage: %s PROTO://ADDR [PROTO://ADDR ...]", job.Name)
  1397. }
  1398. var (
  1399. protoAddrs = job.Args
  1400. chErrors = make(chan error, len(protoAddrs))
  1401. )
  1402. for _, protoAddr := range protoAddrs {
  1403. protoAddrParts := strings.SplitN(protoAddr, "://", 2)
  1404. if len(protoAddrParts) != 2 {
  1405. return fmt.Errorf("usage: %s PROTO://ADDR [PROTO://ADDR ...]", job.Name)
  1406. }
  1407. go func() {
  1408. logrus.Infof("Listening for HTTP on %s (%s)", protoAddrParts[0], protoAddrParts[1])
  1409. srv, err := NewServer(protoAddrParts[0], protoAddrParts[1], job)
  1410. if err != nil {
  1411. chErrors <- err
  1412. return
  1413. }
  1414. job.Eng.OnShutdown(func() {
  1415. if err := srv.Close(); err != nil {
  1416. logrus.Error(err)
  1417. }
  1418. })
  1419. if err = srv.Serve(); err != nil && strings.Contains(err.Error(), "use of closed network connection") {
  1420. err = nil
  1421. }
  1422. chErrors <- err
  1423. }()
  1424. }
  1425. for i := 0; i < len(protoAddrs); i++ {
  1426. err := <-chErrors
  1427. if err != nil {
  1428. return err
  1429. }
  1430. }
  1431. return nil
  1432. }
  1433. func toBool(s string) bool {
  1434. s = strings.ToLower(strings.TrimSpace(s))
  1435. return !(s == "" || s == "0" || s == "no" || s == "false" || s == "none")
  1436. }