server.go 47 KB

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