server.go 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740
  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. c, err := s.daemon.Get(vars["name"])
  542. if err != nil {
  543. return err
  544. }
  545. outStream := ioutils.NewWriteFlusher(w)
  546. // write an empty chunk of data (this is to ensure that the
  547. // HTTP Response is sent immediatly, even if the container has
  548. // not yet produced any data)
  549. outStream.Write(nil)
  550. logsConfig := &daemon.ContainerLogsConfig{
  551. Follow: boolValue(r, "follow"),
  552. Timestamps: boolValue(r, "timestamps"),
  553. Since: since,
  554. Tail: r.Form.Get("tail"),
  555. UseStdout: stdout,
  556. UseStderr: stderr,
  557. OutStream: outStream,
  558. Stop: closeNotifier,
  559. }
  560. if err := s.daemon.ContainerLogs(c, logsConfig); err != nil {
  561. fmt.Fprintf(w, "Error running logs job: %s\n", err)
  562. }
  563. return nil
  564. }
  565. func (s *Server) postImagesTag(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  566. if err := parseForm(r); err != nil {
  567. return err
  568. }
  569. if vars == nil {
  570. return fmt.Errorf("Missing parameter")
  571. }
  572. repo := r.Form.Get("repo")
  573. tag := r.Form.Get("tag")
  574. force := boolValue(r, "force")
  575. name := vars["name"]
  576. if err := s.daemon.Repositories().Tag(repo, tag, name, force); err != nil {
  577. return err
  578. }
  579. s.daemon.EventsService.Log("tag", utils.ImageReference(repo, tag), "")
  580. w.WriteHeader(http.StatusCreated)
  581. return nil
  582. }
  583. func (s *Server) postCommit(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  584. if err := parseForm(r); err != nil {
  585. return err
  586. }
  587. if err := checkForJson(r); err != nil {
  588. return err
  589. }
  590. cname := r.Form.Get("container")
  591. pause := boolValue(r, "pause")
  592. if r.FormValue("pause") == "" && version.GreaterThanOrEqualTo("1.13") {
  593. pause = true
  594. }
  595. c, _, err := runconfig.DecodeContainerConfig(r.Body)
  596. if err != nil && err != io.EOF { //Do not fail if body is empty.
  597. return err
  598. }
  599. commitCfg := &builder.CommitConfig{
  600. Pause: pause,
  601. Repo: r.Form.Get("repo"),
  602. Tag: r.Form.Get("tag"),
  603. Author: r.Form.Get("author"),
  604. Comment: r.Form.Get("comment"),
  605. Changes: r.Form["changes"],
  606. Config: c,
  607. }
  608. imgID, err := builder.Commit(cname, s.daemon, commitCfg)
  609. if err != nil {
  610. return err
  611. }
  612. return writeJSON(w, http.StatusCreated, &types.ContainerCommitResponse{
  613. ID: imgID,
  614. })
  615. }
  616. // Creates an image from Pull or from Import
  617. func (s *Server) postImagesCreate(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  618. if err := parseForm(r); err != nil {
  619. return err
  620. }
  621. var (
  622. image = r.Form.Get("fromImage")
  623. repo = r.Form.Get("repo")
  624. tag = r.Form.Get("tag")
  625. )
  626. authEncoded := r.Header.Get("X-Registry-Auth")
  627. authConfig := &cliconfig.AuthConfig{}
  628. if authEncoded != "" {
  629. authJson := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authEncoded))
  630. if err := json.NewDecoder(authJson).Decode(authConfig); err != nil {
  631. // for a pull it is not an error if no auth was given
  632. // to increase compatibility with the existing api it is defaulting to be empty
  633. authConfig = &cliconfig.AuthConfig{}
  634. }
  635. }
  636. var (
  637. err error
  638. output = ioutils.NewWriteFlusher(w)
  639. )
  640. w.Header().Set("Content-Type", "application/json")
  641. if image != "" { //pull
  642. if tag == "" {
  643. image, tag = parsers.ParseRepositoryTag(image)
  644. }
  645. metaHeaders := map[string][]string{}
  646. for k, v := range r.Header {
  647. if strings.HasPrefix(k, "X-Meta-") {
  648. metaHeaders[k] = v
  649. }
  650. }
  651. imagePullConfig := &graph.ImagePullConfig{
  652. MetaHeaders: metaHeaders,
  653. AuthConfig: authConfig,
  654. OutStream: output,
  655. }
  656. err = s.daemon.Repositories().Pull(image, tag, imagePullConfig)
  657. } else { //import
  658. if tag == "" {
  659. repo, tag = parsers.ParseRepositoryTag(repo)
  660. }
  661. src := r.Form.Get("fromSrc")
  662. imageImportConfig := &graph.ImageImportConfig{
  663. Changes: r.Form["changes"],
  664. InConfig: r.Body,
  665. OutStream: output,
  666. }
  667. // 'err' MUST NOT be defined within this block, we need any error
  668. // generated from the download to be available to the output
  669. // stream processing below
  670. var newConfig *runconfig.Config
  671. newConfig, err = builder.BuildFromConfig(s.daemon, &runconfig.Config{}, imageImportConfig.Changes)
  672. if err != nil {
  673. return err
  674. }
  675. imageImportConfig.ContainerConfig = newConfig
  676. err = s.daemon.Repositories().Import(src, repo, tag, imageImportConfig)
  677. }
  678. if err != nil {
  679. if !output.Flushed() {
  680. return err
  681. }
  682. sf := streamformatter.NewJSONStreamFormatter()
  683. output.Write(sf.FormatError(err))
  684. }
  685. return nil
  686. }
  687. func (s *Server) getImagesSearch(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  688. if err := parseForm(r); err != nil {
  689. return err
  690. }
  691. var (
  692. config *cliconfig.AuthConfig
  693. authEncoded = r.Header.Get("X-Registry-Auth")
  694. headers = map[string][]string{}
  695. )
  696. if authEncoded != "" {
  697. authJson := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authEncoded))
  698. if err := json.NewDecoder(authJson).Decode(&config); err != nil {
  699. // for a search it is not an error if no auth was given
  700. // to increase compatibility with the existing api it is defaulting to be empty
  701. config = &cliconfig.AuthConfig{}
  702. }
  703. }
  704. for k, v := range r.Header {
  705. if strings.HasPrefix(k, "X-Meta-") {
  706. headers[k] = v
  707. }
  708. }
  709. query, err := s.daemon.RegistryService.Search(r.Form.Get("term"), config, headers)
  710. if err != nil {
  711. return err
  712. }
  713. return writeJSON(w, http.StatusOK, query.Results)
  714. }
  715. func (s *Server) postImagesPush(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  716. if vars == nil {
  717. return fmt.Errorf("Missing parameter")
  718. }
  719. metaHeaders := map[string][]string{}
  720. for k, v := range r.Header {
  721. if strings.HasPrefix(k, "X-Meta-") {
  722. metaHeaders[k] = v
  723. }
  724. }
  725. if err := parseForm(r); err != nil {
  726. return err
  727. }
  728. authConfig := &cliconfig.AuthConfig{}
  729. authEncoded := r.Header.Get("X-Registry-Auth")
  730. if authEncoded != "" {
  731. // the new format is to handle the authConfig as a header
  732. authJson := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authEncoded))
  733. if err := json.NewDecoder(authJson).Decode(authConfig); err != nil {
  734. // to increase compatibility to existing api it is defaulting to be empty
  735. authConfig = &cliconfig.AuthConfig{}
  736. }
  737. } else {
  738. // the old format is supported for compatibility if there was no authConfig header
  739. if err := json.NewDecoder(r.Body).Decode(authConfig); err != nil {
  740. return fmt.Errorf("Bad parameters and missing X-Registry-Auth: %v", err)
  741. }
  742. }
  743. name := vars["name"]
  744. output := ioutils.NewWriteFlusher(w)
  745. imagePushConfig := &graph.ImagePushConfig{
  746. MetaHeaders: metaHeaders,
  747. AuthConfig: authConfig,
  748. Tag: r.Form.Get("tag"),
  749. OutStream: output,
  750. }
  751. w.Header().Set("Content-Type", "application/json")
  752. if err := s.daemon.Repositories().Push(name, imagePushConfig); err != nil {
  753. if !output.Flushed() {
  754. return err
  755. }
  756. sf := streamformatter.NewJSONStreamFormatter()
  757. output.Write(sf.FormatError(err))
  758. }
  759. return nil
  760. }
  761. func (s *Server) getImagesGet(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  762. if vars == nil {
  763. return fmt.Errorf("Missing parameter")
  764. }
  765. if err := parseForm(r); err != nil {
  766. return err
  767. }
  768. w.Header().Set("Content-Type", "application/x-tar")
  769. output := ioutils.NewWriteFlusher(w)
  770. imageExportConfig := &graph.ImageExportConfig{Outstream: output}
  771. if name, ok := vars["name"]; ok {
  772. imageExportConfig.Names = []string{name}
  773. } else {
  774. imageExportConfig.Names = r.Form["names"]
  775. }
  776. if err := s.daemon.Repositories().ImageExport(imageExportConfig); err != nil {
  777. if !output.Flushed() {
  778. return err
  779. }
  780. sf := streamformatter.NewJSONStreamFormatter()
  781. output.Write(sf.FormatError(err))
  782. }
  783. return nil
  784. }
  785. func (s *Server) postImagesLoad(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  786. return s.daemon.Repositories().Load(r.Body, w)
  787. }
  788. func (s *Server) postContainersCreate(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  789. if err := parseForm(r); err != nil {
  790. return err
  791. }
  792. if err := checkForJson(r); err != nil {
  793. return err
  794. }
  795. var (
  796. warnings []string
  797. name = r.Form.Get("name")
  798. )
  799. config, hostConfig, err := runconfig.DecodeContainerConfig(r.Body)
  800. if err != nil {
  801. return err
  802. }
  803. adjustCpuShares(version, hostConfig)
  804. containerId, warnings, err := s.daemon.ContainerCreate(name, config, hostConfig)
  805. if err != nil {
  806. return err
  807. }
  808. return writeJSON(w, http.StatusCreated, &types.ContainerCreateResponse{
  809. ID: containerId,
  810. Warnings: warnings,
  811. })
  812. }
  813. func (s *Server) postContainersRestart(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  814. if err := parseForm(r); err != nil {
  815. return err
  816. }
  817. if vars == nil {
  818. return fmt.Errorf("Missing parameter")
  819. }
  820. timeout, _ := strconv.Atoi(r.Form.Get("t"))
  821. if err := s.daemon.ContainerRestart(vars["name"], timeout); err != nil {
  822. return err
  823. }
  824. w.WriteHeader(http.StatusNoContent)
  825. return nil
  826. }
  827. func (s *Server) postContainerRename(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  828. if err := parseForm(r); err != nil {
  829. return err
  830. }
  831. if vars == nil {
  832. return fmt.Errorf("Missing parameter")
  833. }
  834. name := vars["name"]
  835. newName := r.Form.Get("name")
  836. if err := s.daemon.ContainerRename(name, newName); err != nil {
  837. return err
  838. }
  839. w.WriteHeader(http.StatusNoContent)
  840. return nil
  841. }
  842. func (s *Server) deleteContainers(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  843. if err := parseForm(r); err != nil {
  844. return err
  845. }
  846. if vars == nil {
  847. return fmt.Errorf("Missing parameter")
  848. }
  849. name := vars["name"]
  850. config := &daemon.ContainerRmConfig{
  851. ForceRemove: boolValue(r, "force"),
  852. RemoveVolume: boolValue(r, "v"),
  853. RemoveLink: boolValue(r, "link"),
  854. }
  855. if err := s.daemon.ContainerRm(name, config); err != nil {
  856. // Force a 404 for the empty string
  857. if strings.Contains(strings.ToLower(err.Error()), "prefix can't be empty") {
  858. return fmt.Errorf("no such id: \"\"")
  859. }
  860. return err
  861. }
  862. w.WriteHeader(http.StatusNoContent)
  863. return nil
  864. }
  865. func (s *Server) deleteImages(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  866. if err := parseForm(r); err != nil {
  867. return err
  868. }
  869. if vars == nil {
  870. return fmt.Errorf("Missing parameter")
  871. }
  872. name := vars["name"]
  873. force := boolValue(r, "force")
  874. noprune := boolValue(r, "noprune")
  875. list, err := s.daemon.ImageDelete(name, force, noprune)
  876. if err != nil {
  877. return err
  878. }
  879. return writeJSON(w, http.StatusOK, list)
  880. }
  881. func (s *Server) postContainersStart(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  882. if vars == nil {
  883. return fmt.Errorf("Missing parameter")
  884. }
  885. // If contentLength is -1, we can assumed chunked encoding
  886. // or more technically that the length is unknown
  887. // https://golang.org/src/pkg/net/http/request.go#L139
  888. // net/http otherwise seems to swallow any headers related to chunked encoding
  889. // including r.TransferEncoding
  890. // allow a nil body for backwards compatibility
  891. var hostConfig *runconfig.HostConfig
  892. if r.Body != nil && (r.ContentLength > 0 || r.ContentLength == -1) {
  893. if err := checkForJson(r); err != nil {
  894. return err
  895. }
  896. c, err := runconfig.DecodeHostConfig(r.Body)
  897. if err != nil {
  898. return err
  899. }
  900. hostConfig = c
  901. }
  902. if err := s.daemon.ContainerStart(vars["name"], hostConfig); err != nil {
  903. if err.Error() == "Container already started" {
  904. w.WriteHeader(http.StatusNotModified)
  905. return nil
  906. }
  907. return err
  908. }
  909. w.WriteHeader(http.StatusNoContent)
  910. return nil
  911. }
  912. func (s *Server) postContainersStop(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  913. if err := parseForm(r); err != nil {
  914. return err
  915. }
  916. if vars == nil {
  917. return fmt.Errorf("Missing parameter")
  918. }
  919. seconds, _ := strconv.Atoi(r.Form.Get("t"))
  920. if err := s.daemon.ContainerStop(vars["name"], seconds); err != nil {
  921. if err.Error() == "Container already stopped" {
  922. w.WriteHeader(http.StatusNotModified)
  923. return nil
  924. }
  925. return err
  926. }
  927. w.WriteHeader(http.StatusNoContent)
  928. return nil
  929. }
  930. func (s *Server) postContainersWait(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  931. if vars == nil {
  932. return fmt.Errorf("Missing parameter")
  933. }
  934. status, err := s.daemon.ContainerWait(vars["name"], -1*time.Second)
  935. if err != nil {
  936. return err
  937. }
  938. return writeJSON(w, http.StatusOK, &types.ContainerWaitResponse{
  939. StatusCode: status,
  940. })
  941. }
  942. func (s *Server) postContainersResize(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  943. if err := parseForm(r); err != nil {
  944. return err
  945. }
  946. if vars == nil {
  947. return fmt.Errorf("Missing parameter")
  948. }
  949. height, err := strconv.Atoi(r.Form.Get("h"))
  950. if err != nil {
  951. return err
  952. }
  953. width, err := strconv.Atoi(r.Form.Get("w"))
  954. if err != nil {
  955. return err
  956. }
  957. return s.daemon.ContainerResize(vars["name"], height, width)
  958. }
  959. func (s *Server) postContainersAttach(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  960. if err := parseForm(r); err != nil {
  961. return err
  962. }
  963. if vars == nil {
  964. return fmt.Errorf("Missing parameter")
  965. }
  966. cont, err := s.daemon.Get(vars["name"])
  967. if err != nil {
  968. return err
  969. }
  970. inStream, outStream, err := hijackServer(w)
  971. if err != nil {
  972. return err
  973. }
  974. defer closeStreams(inStream, outStream)
  975. if _, ok := r.Header["Upgrade"]; ok {
  976. 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")
  977. } else {
  978. fmt.Fprintf(outStream, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n")
  979. }
  980. attachWithLogsConfig := &daemon.ContainerAttachWithLogsConfig{
  981. InStream: inStream,
  982. OutStream: outStream,
  983. UseStdin: boolValue(r, "stdin"),
  984. UseStdout: boolValue(r, "stdout"),
  985. UseStderr: boolValue(r, "stderr"),
  986. Logs: boolValue(r, "logs"),
  987. Stream: boolValue(r, "stream"),
  988. }
  989. if err := s.daemon.ContainerAttachWithLogs(cont, attachWithLogsConfig); err != nil {
  990. fmt.Fprintf(outStream, "Error attaching: %s\n", err)
  991. }
  992. return nil
  993. }
  994. func (s *Server) wsContainersAttach(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  995. if err := parseForm(r); err != nil {
  996. return err
  997. }
  998. if vars == nil {
  999. return fmt.Errorf("Missing parameter")
  1000. }
  1001. cont, err := s.daemon.Get(vars["name"])
  1002. if err != nil {
  1003. return err
  1004. }
  1005. h := websocket.Handler(func(ws *websocket.Conn) {
  1006. defer ws.Close()
  1007. wsAttachWithLogsConfig := &daemon.ContainerWsAttachWithLogsConfig{
  1008. InStream: ws,
  1009. OutStream: ws,
  1010. ErrStream: ws,
  1011. Logs: boolValue(r, "logs"),
  1012. Stream: boolValue(r, "stream"),
  1013. }
  1014. if err := s.daemon.ContainerWsAttachWithLogs(cont, wsAttachWithLogsConfig); err != nil {
  1015. logrus.Errorf("Error attaching websocket: %s", err)
  1016. }
  1017. })
  1018. h.ServeHTTP(w, r)
  1019. return nil
  1020. }
  1021. func (s *Server) getContainersByName(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1022. if vars == nil {
  1023. return fmt.Errorf("Missing parameter")
  1024. }
  1025. if version.LessThan("1.20") {
  1026. containerJSONRaw, err := s.daemon.ContainerInspectPre120(vars["name"])
  1027. if err != nil {
  1028. return err
  1029. }
  1030. return writeJSON(w, http.StatusOK, containerJSONRaw)
  1031. }
  1032. containerJSON, err := s.daemon.ContainerInspect(vars["name"])
  1033. if err != nil {
  1034. return err
  1035. }
  1036. return writeJSON(w, http.StatusOK, containerJSON)
  1037. }
  1038. func (s *Server) getExecByID(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1039. if vars == nil {
  1040. return fmt.Errorf("Missing parameter 'id'")
  1041. }
  1042. eConfig, err := s.daemon.ContainerExecInspect(vars["id"])
  1043. if err != nil {
  1044. return err
  1045. }
  1046. return writeJSON(w, http.StatusOK, eConfig)
  1047. }
  1048. func (s *Server) getImagesByName(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1049. if vars == nil {
  1050. return fmt.Errorf("Missing parameter")
  1051. }
  1052. imageInspect, err := s.daemon.Repositories().Lookup(vars["name"])
  1053. if err != nil {
  1054. return err
  1055. }
  1056. return writeJSON(w, http.StatusOK, imageInspect)
  1057. }
  1058. func (s *Server) postBuild(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1059. var (
  1060. authConfigs = map[string]cliconfig.AuthConfig{}
  1061. authConfigsEncoded = r.Header.Get("X-Registry-Config")
  1062. buildConfig = builder.NewBuildConfig()
  1063. )
  1064. if authConfigsEncoded != "" {
  1065. authConfigsJSON := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authConfigsEncoded))
  1066. if err := json.NewDecoder(authConfigsJSON).Decode(&authConfigs); err != nil {
  1067. // for a pull it is not an error if no auth was given
  1068. // to increase compatibility with the existing api it is defaulting
  1069. // to be empty.
  1070. }
  1071. }
  1072. w.Header().Set("Content-Type", "application/json")
  1073. if boolValue(r, "forcerm") && version.GreaterThanOrEqualTo("1.12") {
  1074. buildConfig.Remove = true
  1075. } else if r.FormValue("rm") == "" && version.GreaterThanOrEqualTo("1.12") {
  1076. buildConfig.Remove = true
  1077. } else {
  1078. buildConfig.Remove = boolValue(r, "rm")
  1079. }
  1080. if boolValue(r, "pull") && version.GreaterThanOrEqualTo("1.16") {
  1081. buildConfig.Pull = true
  1082. }
  1083. output := ioutils.NewWriteFlusher(w)
  1084. buildConfig.Stdout = output
  1085. buildConfig.Context = r.Body
  1086. buildConfig.RemoteURL = r.FormValue("remote")
  1087. buildConfig.DockerfileName = r.FormValue("dockerfile")
  1088. buildConfig.RepoName = r.FormValue("t")
  1089. buildConfig.SuppressOutput = boolValue(r, "q")
  1090. buildConfig.NoCache = boolValue(r, "nocache")
  1091. buildConfig.ForceRemove = boolValue(r, "forcerm")
  1092. buildConfig.AuthConfigs = authConfigs
  1093. buildConfig.MemorySwap = int64ValueOrZero(r, "memswap")
  1094. buildConfig.Memory = int64ValueOrZero(r, "memory")
  1095. buildConfig.CPUShares = int64ValueOrZero(r, "cpushares")
  1096. buildConfig.CPUPeriod = int64ValueOrZero(r, "cpuperiod")
  1097. buildConfig.CPUQuota = int64ValueOrZero(r, "cpuquota")
  1098. buildConfig.CPUSetCpus = r.FormValue("cpusetcpus")
  1099. buildConfig.CPUSetMems = r.FormValue("cpusetmems")
  1100. buildConfig.CgroupParent = r.FormValue("cgroupparent")
  1101. // Job cancellation. Note: not all job types support this.
  1102. if closeNotifier, ok := w.(http.CloseNotifier); ok {
  1103. finished := make(chan struct{})
  1104. defer close(finished)
  1105. go func() {
  1106. select {
  1107. case <-finished:
  1108. case <-closeNotifier.CloseNotify():
  1109. logrus.Infof("Client disconnected, cancelling job: build")
  1110. buildConfig.Cancel()
  1111. }
  1112. }()
  1113. }
  1114. if err := builder.Build(s.daemon, buildConfig); err != nil {
  1115. // Do not write the error in the http output if it's still empty.
  1116. // This prevents from writing a 200(OK) when there is an interal error.
  1117. if !output.Flushed() {
  1118. return err
  1119. }
  1120. sf := streamformatter.NewJSONStreamFormatter()
  1121. w.Write(sf.FormatError(err))
  1122. }
  1123. return nil
  1124. }
  1125. // postContainersCopy is deprecated in favor of getContainersArchivePath.
  1126. func (s *Server) postContainersCopy(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1127. if vars == nil {
  1128. return fmt.Errorf("Missing parameter")
  1129. }
  1130. if err := checkForJson(r); err != nil {
  1131. return err
  1132. }
  1133. cfg := types.CopyConfig{}
  1134. if err := json.NewDecoder(r.Body).Decode(&cfg); err != nil {
  1135. return err
  1136. }
  1137. if cfg.Resource == "" {
  1138. return fmt.Errorf("Path cannot be empty")
  1139. }
  1140. data, err := s.daemon.ContainerCopy(vars["name"], cfg.Resource)
  1141. if err != nil {
  1142. if strings.Contains(strings.ToLower(err.Error()), "no such id") {
  1143. w.WriteHeader(http.StatusNotFound)
  1144. return nil
  1145. }
  1146. if os.IsNotExist(err) {
  1147. return fmt.Errorf("Could not find the file %s in container %s", cfg.Resource, vars["name"])
  1148. }
  1149. return err
  1150. }
  1151. defer data.Close()
  1152. w.Header().Set("Content-Type", "application/x-tar")
  1153. if _, err := io.Copy(w, data); err != nil {
  1154. return err
  1155. }
  1156. return nil
  1157. }
  1158. // // Encode the stat to JSON, base64 encode, and place in a header.
  1159. func setContainerPathStatHeader(stat *types.ContainerPathStat, header http.Header) error {
  1160. statJSON, err := json.Marshal(stat)
  1161. if err != nil {
  1162. return err
  1163. }
  1164. header.Set(
  1165. "X-Docker-Container-Path-Stat",
  1166. base64.StdEncoding.EncodeToString(statJSON),
  1167. )
  1168. return nil
  1169. }
  1170. func (s *Server) headContainersArchive(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1171. if vars == nil {
  1172. return fmt.Errorf("Missing parameter")
  1173. }
  1174. if err := parseForm(r); err != nil {
  1175. return err
  1176. }
  1177. name := vars["name"]
  1178. path := r.Form.Get("path")
  1179. switch {
  1180. case name == "":
  1181. return fmt.Errorf("bad parameter: 'name' cannot be empty")
  1182. case path == "":
  1183. return fmt.Errorf("bad parameter: 'path' cannot be empty")
  1184. }
  1185. stat, err := s.daemon.ContainerStatPath(name, path)
  1186. if err != nil {
  1187. return err
  1188. }
  1189. return setContainerPathStatHeader(stat, w.Header())
  1190. }
  1191. func (s *Server) getContainersArchive(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1192. if vars == nil {
  1193. return fmt.Errorf("Missing parameter")
  1194. }
  1195. if err := parseForm(r); err != nil {
  1196. return err
  1197. }
  1198. name := vars["name"]
  1199. path := r.Form.Get("path")
  1200. switch {
  1201. case name == "":
  1202. return fmt.Errorf("bad parameter: 'name' cannot be empty")
  1203. case path == "":
  1204. return fmt.Errorf("bad parameter: 'path' cannot be empty")
  1205. }
  1206. tarArchive, stat, err := s.daemon.ContainerArchivePath(name, path)
  1207. if err != nil {
  1208. return err
  1209. }
  1210. defer tarArchive.Close()
  1211. if err := setContainerPathStatHeader(stat, w.Header()); err != nil {
  1212. return err
  1213. }
  1214. w.Header().Set("Content-Type", "application/x-tar")
  1215. _, err = io.Copy(w, tarArchive)
  1216. return err
  1217. }
  1218. func (s *Server) putContainersArchive(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1219. if vars == nil {
  1220. return fmt.Errorf("Missing parameter")
  1221. }
  1222. if err := parseForm(r); err != nil {
  1223. return err
  1224. }
  1225. name := vars["name"]
  1226. path := r.Form.Get("path")
  1227. noOverwriteDirNonDir := boolValue(r, "noOverwriteDirNonDir")
  1228. switch {
  1229. case name == "":
  1230. return fmt.Errorf("bad parameter: 'name' cannot be empty")
  1231. case path == "":
  1232. return fmt.Errorf("bad parameter: 'path' cannot be empty")
  1233. }
  1234. return s.daemon.ContainerExtractToDir(name, path, noOverwriteDirNonDir, r.Body)
  1235. }
  1236. func (s *Server) postContainerExecCreate(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1237. if err := parseForm(r); err != nil {
  1238. return err
  1239. }
  1240. if err := checkForJson(r); err != nil {
  1241. return err
  1242. }
  1243. name := vars["name"]
  1244. execConfig := &runconfig.ExecConfig{}
  1245. if err := json.NewDecoder(r.Body).Decode(execConfig); err != nil {
  1246. return err
  1247. }
  1248. execConfig.Container = name
  1249. if len(execConfig.Cmd) == 0 {
  1250. return fmt.Errorf("No exec command specified")
  1251. }
  1252. // Register an instance of Exec in container.
  1253. id, err := s.daemon.ContainerExecCreate(execConfig)
  1254. if err != nil {
  1255. logrus.Errorf("Error setting up exec command in container %s: %s", name, err)
  1256. return err
  1257. }
  1258. return writeJSON(w, http.StatusCreated, &types.ContainerExecCreateResponse{
  1259. ID: id,
  1260. })
  1261. }
  1262. // TODO(vishh): Refactor the code to avoid having to specify stream config as part of both create and start.
  1263. func (s *Server) postContainerExecStart(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1264. if err := parseForm(r); err != nil {
  1265. return err
  1266. }
  1267. var (
  1268. execName = vars["name"]
  1269. stdin io.ReadCloser
  1270. stdout io.Writer
  1271. stderr io.Writer
  1272. )
  1273. execStartCheck := &types.ExecStartCheck{}
  1274. if err := json.NewDecoder(r.Body).Decode(execStartCheck); err != nil {
  1275. return err
  1276. }
  1277. if !execStartCheck.Detach {
  1278. // Setting up the streaming http interface.
  1279. inStream, outStream, err := hijackServer(w)
  1280. if err != nil {
  1281. return err
  1282. }
  1283. defer closeStreams(inStream, outStream)
  1284. var errStream io.Writer
  1285. if _, ok := r.Header["Upgrade"]; ok {
  1286. 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")
  1287. } else {
  1288. fmt.Fprintf(outStream, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n")
  1289. }
  1290. if !execStartCheck.Tty {
  1291. errStream = stdcopy.NewStdWriter(outStream, stdcopy.Stderr)
  1292. outStream = stdcopy.NewStdWriter(outStream, stdcopy.Stdout)
  1293. }
  1294. stdin = inStream
  1295. stdout = outStream
  1296. stderr = errStream
  1297. }
  1298. // Now run the user process in container.
  1299. if err := s.daemon.ContainerExecStart(execName, stdin, stdout, stderr); err != nil {
  1300. logrus.Errorf("Error starting exec command in container %s: %s", execName, err)
  1301. return err
  1302. }
  1303. w.WriteHeader(http.StatusNoContent)
  1304. return nil
  1305. }
  1306. func (s *Server) postContainerExecResize(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1307. if err := parseForm(r); err != nil {
  1308. return err
  1309. }
  1310. if vars == nil {
  1311. return fmt.Errorf("Missing parameter")
  1312. }
  1313. height, err := strconv.Atoi(r.Form.Get("h"))
  1314. if err != nil {
  1315. return err
  1316. }
  1317. width, err := strconv.Atoi(r.Form.Get("w"))
  1318. if err != nil {
  1319. return err
  1320. }
  1321. return s.daemon.ContainerExecResize(vars["name"], height, width)
  1322. }
  1323. func (s *Server) optionsHandler(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1324. w.WriteHeader(http.StatusOK)
  1325. return nil
  1326. }
  1327. func writeCorsHeaders(w http.ResponseWriter, r *http.Request, corsHeaders string) {
  1328. logrus.Debugf("CORS header is enabled and set to: %s", corsHeaders)
  1329. w.Header().Add("Access-Control-Allow-Origin", corsHeaders)
  1330. w.Header().Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, X-Registry-Auth")
  1331. w.Header().Add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS")
  1332. }
  1333. func (s *Server) ping(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1334. _, err := w.Write([]byte{'O', 'K'})
  1335. return err
  1336. }
  1337. func (s *Server) initTcpSocket(addr string) (l net.Listener, err error) {
  1338. if s.cfg.TLSConfig == nil || s.cfg.TLSConfig.ClientAuth != tls.RequireAndVerifyClientCert {
  1339. logrus.Warn("/!\\ DON'T BIND ON ANY IP ADDRESS WITHOUT setting -tlsverify IF YOU DON'T KNOW WHAT YOU'RE DOING /!\\")
  1340. }
  1341. if l, err = sockets.NewTcpSocket(addr, s.cfg.TLSConfig, s.start); err != nil {
  1342. return nil, err
  1343. }
  1344. if err := allocateDaemonPort(addr); err != nil {
  1345. return nil, err
  1346. }
  1347. return
  1348. }
  1349. func makeHttpHandler(logging bool, localMethod string, localRoute string, handlerFunc HttpApiFunc, corsHeaders string, dockerVersion version.Version) http.HandlerFunc {
  1350. return func(w http.ResponseWriter, r *http.Request) {
  1351. // log the request
  1352. logrus.Debugf("Calling %s %s", localMethod, localRoute)
  1353. if logging {
  1354. logrus.Infof("%s %s", r.Method, r.RequestURI)
  1355. }
  1356. if strings.Contains(r.Header.Get("User-Agent"), "Docker-Client/") {
  1357. userAgent := strings.Split(r.Header.Get("User-Agent"), "/")
  1358. // v1.20 onwards includes the GOOS of the client after the version
  1359. // such as Docker/1.7.0 (linux)
  1360. if len(userAgent) == 2 && strings.Contains(userAgent[1], " ") {
  1361. userAgent[1] = strings.Split(userAgent[1], " ")[0]
  1362. }
  1363. if len(userAgent) == 2 && !dockerVersion.Equal(version.Version(userAgent[1])) {
  1364. logrus.Debugf("Warning: client and server don't have the same version (client: %s, server: %s)", userAgent[1], dockerVersion)
  1365. }
  1366. }
  1367. version := version.Version(mux.Vars(r)["version"])
  1368. if version == "" {
  1369. version = api.Version
  1370. }
  1371. if corsHeaders != "" {
  1372. writeCorsHeaders(w, r, corsHeaders)
  1373. }
  1374. if version.GreaterThan(api.Version) {
  1375. http.Error(w, fmt.Errorf("client is newer than server (client API version: %s, server API version: %s)", version, api.Version).Error(), http.StatusBadRequest)
  1376. return
  1377. }
  1378. if version.LessThan(api.MinVersion) {
  1379. 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)
  1380. return
  1381. }
  1382. w.Header().Set("Server", "Docker/"+dockerversion.VERSION+" ("+runtime.GOOS+")")
  1383. if err := handlerFunc(version, w, r, mux.Vars(r)); err != nil {
  1384. logrus.Errorf("Handler for %s %s returned error: %s", localMethod, localRoute, err)
  1385. httpError(w, err)
  1386. }
  1387. }
  1388. }
  1389. // we keep enableCors just for legacy usage, need to be removed in the future
  1390. func createRouter(s *Server) *mux.Router {
  1391. r := mux.NewRouter()
  1392. if os.Getenv("DEBUG") != "" {
  1393. ProfilerSetup(r, "/debug/")
  1394. }
  1395. m := map[string]map[string]HttpApiFunc{
  1396. "HEAD": {
  1397. "/containers/{name:.*}/archive": s.headContainersArchive,
  1398. },
  1399. "GET": {
  1400. "/_ping": s.ping,
  1401. "/events": s.getEvents,
  1402. "/info": s.getInfo,
  1403. "/version": s.getVersion,
  1404. "/images/json": s.getImagesJSON,
  1405. "/images/search": s.getImagesSearch,
  1406. "/images/get": s.getImagesGet,
  1407. "/images/{name:.*}/get": s.getImagesGet,
  1408. "/images/{name:.*}/history": s.getImagesHistory,
  1409. "/images/{name:.*}/json": s.getImagesByName,
  1410. "/containers/ps": s.getContainersJSON,
  1411. "/containers/json": s.getContainersJSON,
  1412. "/containers/{name:.*}/export": s.getContainersExport,
  1413. "/containers/{name:.*}/changes": s.getContainersChanges,
  1414. "/containers/{name:.*}/json": s.getContainersByName,
  1415. "/containers/{name:.*}/top": s.getContainersTop,
  1416. "/containers/{name:.*}/logs": s.getContainersLogs,
  1417. "/containers/{name:.*}/stats": s.getContainersStats,
  1418. "/containers/{name:.*}/attach/ws": s.wsContainersAttach,
  1419. "/exec/{id:.*}/json": s.getExecByID,
  1420. "/containers/{name:.*}/archive": s.getContainersArchive,
  1421. },
  1422. "POST": {
  1423. "/auth": s.postAuth,
  1424. "/commit": s.postCommit,
  1425. "/build": s.postBuild,
  1426. "/images/create": s.postImagesCreate,
  1427. "/images/load": s.postImagesLoad,
  1428. "/images/{name:.*}/push": s.postImagesPush,
  1429. "/images/{name:.*}/tag": s.postImagesTag,
  1430. "/containers/create": s.postContainersCreate,
  1431. "/containers/{name:.*}/kill": s.postContainersKill,
  1432. "/containers/{name:.*}/pause": s.postContainersPause,
  1433. "/containers/{name:.*}/unpause": s.postContainersUnpause,
  1434. "/containers/{name:.*}/restart": s.postContainersRestart,
  1435. "/containers/{name:.*}/start": s.postContainersStart,
  1436. "/containers/{name:.*}/stop": s.postContainersStop,
  1437. "/containers/{name:.*}/wait": s.postContainersWait,
  1438. "/containers/{name:.*}/resize": s.postContainersResize,
  1439. "/containers/{name:.*}/attach": s.postContainersAttach,
  1440. "/containers/{name:.*}/copy": s.postContainersCopy,
  1441. "/containers/{name:.*}/exec": s.postContainerExecCreate,
  1442. "/exec/{name:.*}/start": s.postContainerExecStart,
  1443. "/exec/{name:.*}/resize": s.postContainerExecResize,
  1444. "/containers/{name:.*}/rename": s.postContainerRename,
  1445. },
  1446. "PUT": {
  1447. "/containers/{name:.*}/archive": s.putContainersArchive,
  1448. },
  1449. "DELETE": {
  1450. "/containers/{name:.*}": s.deleteContainers,
  1451. "/images/{name:.*}": s.deleteImages,
  1452. },
  1453. "OPTIONS": {
  1454. "": s.optionsHandler,
  1455. },
  1456. }
  1457. // If "api-cors-header" is not given, but "api-enable-cors" is true, we set cors to "*"
  1458. // otherwise, all head values will be passed to HTTP handler
  1459. corsHeaders := s.cfg.CorsHeaders
  1460. if corsHeaders == "" && s.cfg.EnableCors {
  1461. corsHeaders = "*"
  1462. }
  1463. for method, routes := range m {
  1464. for route, fct := range routes {
  1465. logrus.Debugf("Registering %s, %s", method, route)
  1466. // NOTE: scope issue, make sure the variables are local and won't be changed
  1467. localRoute := route
  1468. localFct := fct
  1469. localMethod := method
  1470. // build the handler function
  1471. f := makeHttpHandler(s.cfg.Logging, localMethod, localRoute, localFct, corsHeaders, version.Version(s.cfg.Version))
  1472. // add the new route
  1473. if localRoute == "" {
  1474. r.Methods(localMethod).HandlerFunc(f)
  1475. } else {
  1476. r.Path("/v{version:[0-9.]+}" + localRoute).Methods(localMethod).HandlerFunc(f)
  1477. r.Path(localRoute).Methods(localMethod).HandlerFunc(f)
  1478. }
  1479. }
  1480. }
  1481. return r
  1482. }