server.go 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605
  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(filter) == 0 {
  356. return false
  357. }
  358. for _, v := range filter {
  359. if v == field {
  360. return false
  361. }
  362. if strings.Contains(field, ":") {
  363. image := strings.Split(field, ":")
  364. if image[0] == v {
  365. return false
  366. }
  367. }
  368. }
  369. return true
  370. }
  371. d := s.daemon
  372. es := d.EventsService
  373. w.Header().Set("Content-Type", "application/json")
  374. enc := json.NewEncoder(ioutils.NewWriteFlusher(w))
  375. getContainerId := func(cn string) string {
  376. c, err := d.Get(cn)
  377. if err != nil {
  378. return ""
  379. }
  380. return c.ID
  381. }
  382. sendEvent := func(ev *jsonmessage.JSONMessage) error {
  383. //incoming container filter can be name,id or partial id, convert and replace as a full container id
  384. for i, cn := range ef["container"] {
  385. ef["container"][i] = getContainerId(cn)
  386. }
  387. if isFiltered(ev.Status, ef["event"]) || isFiltered(ev.From, ef["image"]) ||
  388. isFiltered(ev.ID, ef["container"]) {
  389. return nil
  390. }
  391. return enc.Encode(ev)
  392. }
  393. current, l := es.Subscribe()
  394. if since == -1 {
  395. current = nil
  396. }
  397. defer es.Evict(l)
  398. for _, ev := range current {
  399. if ev.Time < since {
  400. continue
  401. }
  402. if err := sendEvent(ev); err != nil {
  403. return err
  404. }
  405. }
  406. var closeNotify <-chan bool
  407. if closeNotifier, ok := w.(http.CloseNotifier); ok {
  408. closeNotify = closeNotifier.CloseNotify()
  409. }
  410. for {
  411. select {
  412. case ev := <-l:
  413. jev, ok := ev.(*jsonmessage.JSONMessage)
  414. if !ok {
  415. continue
  416. }
  417. if err := sendEvent(jev); err != nil {
  418. return err
  419. }
  420. case <-timer.C:
  421. return nil
  422. case <-closeNotify:
  423. logrus.Debug("Client disconnected, stop sending events")
  424. return nil
  425. }
  426. }
  427. }
  428. func (s *Server) getImagesHistory(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  429. if vars == nil {
  430. return fmt.Errorf("Missing parameter")
  431. }
  432. name := vars["name"]
  433. history, err := s.daemon.Repositories().History(name)
  434. if err != nil {
  435. return err
  436. }
  437. return writeJSON(w, http.StatusOK, history)
  438. }
  439. func (s *Server) getContainersChanges(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  440. if vars == nil {
  441. return fmt.Errorf("Missing parameter")
  442. }
  443. changes, err := s.daemon.ContainerChanges(vars["name"])
  444. if err != nil {
  445. return err
  446. }
  447. return writeJSON(w, http.StatusOK, changes)
  448. }
  449. func (s *Server) getContainersTop(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  450. if vars == nil {
  451. return fmt.Errorf("Missing parameter")
  452. }
  453. if err := parseForm(r); err != nil {
  454. return err
  455. }
  456. procList, err := s.daemon.ContainerTop(vars["name"], r.Form.Get("ps_args"))
  457. if err != nil {
  458. return err
  459. }
  460. return writeJSON(w, http.StatusOK, procList)
  461. }
  462. func (s *Server) getContainersJSON(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  463. if err := parseForm(r); err != nil {
  464. return err
  465. }
  466. config := &daemon.ContainersConfig{
  467. All: boolValue(r, "all"),
  468. Size: boolValue(r, "size"),
  469. Since: r.Form.Get("since"),
  470. Before: r.Form.Get("before"),
  471. Filters: r.Form.Get("filters"),
  472. }
  473. if tmpLimit := r.Form.Get("limit"); tmpLimit != "" {
  474. limit, err := strconv.Atoi(tmpLimit)
  475. if err != nil {
  476. return err
  477. }
  478. config.Limit = limit
  479. }
  480. containers, err := s.daemon.Containers(config)
  481. if err != nil {
  482. return err
  483. }
  484. return writeJSON(w, http.StatusOK, containers)
  485. }
  486. func (s *Server) getContainersStats(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  487. if err := parseForm(r); err != nil {
  488. return err
  489. }
  490. if vars == nil {
  491. return fmt.Errorf("Missing parameter")
  492. }
  493. stream := boolValueOrDefault(r, "stream", true)
  494. var out io.Writer
  495. if !stream {
  496. w.Header().Set("Content-Type", "application/json")
  497. out = w
  498. } else {
  499. out = ioutils.NewWriteFlusher(w)
  500. }
  501. var closeNotifier <-chan bool
  502. if notifier, ok := w.(http.CloseNotifier); ok {
  503. closeNotifier = notifier.CloseNotify()
  504. }
  505. config := &daemon.ContainerStatsConfig{
  506. Stream: stream,
  507. OutStream: out,
  508. Stop: closeNotifier,
  509. }
  510. return s.daemon.ContainerStats(vars["name"], config)
  511. }
  512. func (s *Server) getContainersLogs(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  513. if err := parseForm(r); err != nil {
  514. return err
  515. }
  516. if vars == nil {
  517. return fmt.Errorf("Missing parameter")
  518. }
  519. // Validate args here, because we can't return not StatusOK after job.Run() call
  520. stdout, stderr := boolValue(r, "stdout"), boolValue(r, "stderr")
  521. if !(stdout || stderr) {
  522. return fmt.Errorf("Bad parameters: you must choose at least one stream")
  523. }
  524. var since time.Time
  525. if r.Form.Get("since") != "" {
  526. s, err := strconv.ParseInt(r.Form.Get("since"), 10, 64)
  527. if err != nil {
  528. return err
  529. }
  530. since = time.Unix(s, 0)
  531. }
  532. var closeNotifier <-chan bool
  533. if notifier, ok := w.(http.CloseNotifier); ok {
  534. closeNotifier = notifier.CloseNotify()
  535. }
  536. logsConfig := &daemon.ContainerLogsConfig{
  537. Follow: boolValue(r, "follow"),
  538. Timestamps: boolValue(r, "timestamps"),
  539. Since: since,
  540. Tail: r.Form.Get("tail"),
  541. UseStdout: stdout,
  542. UseStderr: stderr,
  543. OutStream: ioutils.NewWriteFlusher(w),
  544. Stop: closeNotifier,
  545. }
  546. if err := s.daemon.ContainerLogs(vars["name"], logsConfig); err != nil {
  547. fmt.Fprintf(w, "Error running logs job: %s\n", err)
  548. }
  549. return nil
  550. }
  551. func (s *Server) postImagesTag(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  552. if err := parseForm(r); err != nil {
  553. return err
  554. }
  555. if vars == nil {
  556. return fmt.Errorf("Missing parameter")
  557. }
  558. repo := r.Form.Get("repo")
  559. tag := r.Form.Get("tag")
  560. force := boolValue(r, "force")
  561. name := vars["name"]
  562. if err := s.daemon.Repositories().Tag(repo, tag, name, force); err != nil {
  563. return err
  564. }
  565. s.daemon.EventsService.Log("tag", utils.ImageReference(repo, tag), "")
  566. w.WriteHeader(http.StatusCreated)
  567. return nil
  568. }
  569. func (s *Server) postCommit(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  570. if err := parseForm(r); err != nil {
  571. return err
  572. }
  573. if err := checkForJson(r); err != nil {
  574. return err
  575. }
  576. cont := r.Form.Get("container")
  577. pause := boolValue(r, "pause")
  578. if r.FormValue("pause") == "" && version.GreaterThanOrEqualTo("1.13") {
  579. pause = true
  580. }
  581. c, _, err := runconfig.DecodeContainerConfig(r.Body)
  582. if err != nil && err != io.EOF { //Do not fail if body is empty.
  583. return err
  584. }
  585. containerCommitConfig := &daemon.ContainerCommitConfig{
  586. Pause: pause,
  587. Repo: r.Form.Get("repo"),
  588. Tag: r.Form.Get("tag"),
  589. Author: r.Form.Get("author"),
  590. Comment: r.Form.Get("comment"),
  591. Changes: r.Form["changes"],
  592. Config: c,
  593. }
  594. imgID, err := builder.Commit(s.daemon, cont, containerCommitConfig)
  595. if err != nil {
  596. return err
  597. }
  598. return writeJSON(w, http.StatusCreated, &types.ContainerCommitResponse{
  599. ID: imgID,
  600. })
  601. }
  602. // Creates an image from Pull or from Import
  603. func (s *Server) postImagesCreate(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  604. if err := parseForm(r); err != nil {
  605. return err
  606. }
  607. var (
  608. image = r.Form.Get("fromImage")
  609. repo = r.Form.Get("repo")
  610. tag = r.Form.Get("tag")
  611. )
  612. authEncoded := r.Header.Get("X-Registry-Auth")
  613. authConfig := &cliconfig.AuthConfig{}
  614. if authEncoded != "" {
  615. authJson := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authEncoded))
  616. if err := json.NewDecoder(authJson).Decode(authConfig); err != nil {
  617. // for a pull it is not an error if no auth was given
  618. // to increase compatibility with the existing api it is defaulting to be empty
  619. authConfig = &cliconfig.AuthConfig{}
  620. }
  621. }
  622. var (
  623. err error
  624. output = ioutils.NewWriteFlusher(w)
  625. )
  626. w.Header().Set("Content-Type", "application/json")
  627. if image != "" { //pull
  628. if tag == "" {
  629. image, tag = parsers.ParseRepositoryTag(image)
  630. }
  631. metaHeaders := map[string][]string{}
  632. for k, v := range r.Header {
  633. if strings.HasPrefix(k, "X-Meta-") {
  634. metaHeaders[k] = v
  635. }
  636. }
  637. imagePullConfig := &graph.ImagePullConfig{
  638. MetaHeaders: metaHeaders,
  639. AuthConfig: authConfig,
  640. OutStream: output,
  641. }
  642. err = s.daemon.Repositories().Pull(image, tag, imagePullConfig)
  643. } else { //import
  644. if tag == "" {
  645. repo, tag = parsers.ParseRepositoryTag(repo)
  646. }
  647. src := r.Form.Get("fromSrc")
  648. imageImportConfig := &graph.ImageImportConfig{
  649. Changes: r.Form["changes"],
  650. InConfig: r.Body,
  651. OutStream: output,
  652. }
  653. // 'err' MUST NOT be defined within this block, we need any error
  654. // generated from the download to be available to the output
  655. // stream processing below
  656. var newConfig *runconfig.Config
  657. newConfig, err = builder.BuildFromConfig(s.daemon, &runconfig.Config{}, imageImportConfig.Changes)
  658. if err != nil {
  659. return err
  660. }
  661. imageImportConfig.ContainerConfig = newConfig
  662. err = s.daemon.Repositories().Import(src, repo, tag, imageImportConfig)
  663. }
  664. if err != nil {
  665. if !output.Flushed() {
  666. return err
  667. }
  668. sf := streamformatter.NewJSONStreamFormatter()
  669. output.Write(sf.FormatError(err))
  670. }
  671. return nil
  672. }
  673. func (s *Server) getImagesSearch(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  674. if err := parseForm(r); err != nil {
  675. return err
  676. }
  677. var (
  678. config *cliconfig.AuthConfig
  679. authEncoded = r.Header.Get("X-Registry-Auth")
  680. headers = map[string][]string{}
  681. )
  682. if authEncoded != "" {
  683. authJson := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authEncoded))
  684. if err := json.NewDecoder(authJson).Decode(&config); err != nil {
  685. // for a search it is not an error if no auth was given
  686. // to increase compatibility with the existing api it is defaulting to be empty
  687. config = &cliconfig.AuthConfig{}
  688. }
  689. }
  690. for k, v := range r.Header {
  691. if strings.HasPrefix(k, "X-Meta-") {
  692. headers[k] = v
  693. }
  694. }
  695. query, err := s.daemon.RegistryService.Search(r.Form.Get("term"), config, headers)
  696. if err != nil {
  697. return err
  698. }
  699. return json.NewEncoder(w).Encode(query.Results)
  700. }
  701. func (s *Server) postImagesPush(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  702. if vars == nil {
  703. return fmt.Errorf("Missing parameter")
  704. }
  705. metaHeaders := map[string][]string{}
  706. for k, v := range r.Header {
  707. if strings.HasPrefix(k, "X-Meta-") {
  708. metaHeaders[k] = v
  709. }
  710. }
  711. if err := parseForm(r); err != nil {
  712. return err
  713. }
  714. authConfig := &cliconfig.AuthConfig{}
  715. authEncoded := r.Header.Get("X-Registry-Auth")
  716. if authEncoded != "" {
  717. // the new format is to handle the authConfig as a header
  718. authJson := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authEncoded))
  719. if err := json.NewDecoder(authJson).Decode(authConfig); err != nil {
  720. // to increase compatibility to existing api it is defaulting to be empty
  721. authConfig = &cliconfig.AuthConfig{}
  722. }
  723. } else {
  724. // the old format is supported for compatibility if there was no authConfig header
  725. if err := json.NewDecoder(r.Body).Decode(authConfig); err != nil {
  726. return fmt.Errorf("Bad parameters and missing X-Registry-Auth: %v", err)
  727. }
  728. }
  729. name := vars["name"]
  730. output := ioutils.NewWriteFlusher(w)
  731. imagePushConfig := &graph.ImagePushConfig{
  732. MetaHeaders: metaHeaders,
  733. AuthConfig: authConfig,
  734. Tag: r.Form.Get("tag"),
  735. OutStream: output,
  736. }
  737. w.Header().Set("Content-Type", "application/json")
  738. if err := s.daemon.Repositories().Push(name, imagePushConfig); err != nil {
  739. if !output.Flushed() {
  740. return err
  741. }
  742. sf := streamformatter.NewJSONStreamFormatter()
  743. output.Write(sf.FormatError(err))
  744. }
  745. return nil
  746. }
  747. func (s *Server) getImagesGet(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  748. if vars == nil {
  749. return fmt.Errorf("Missing parameter")
  750. }
  751. if err := parseForm(r); err != nil {
  752. return err
  753. }
  754. w.Header().Set("Content-Type", "application/x-tar")
  755. output := ioutils.NewWriteFlusher(w)
  756. imageExportConfig := &graph.ImageExportConfig{Outstream: output}
  757. if name, ok := vars["name"]; ok {
  758. imageExportConfig.Names = []string{name}
  759. } else {
  760. imageExportConfig.Names = r.Form["names"]
  761. }
  762. if err := s.daemon.Repositories().ImageExport(imageExportConfig); err != nil {
  763. if !output.Flushed() {
  764. return err
  765. }
  766. sf := streamformatter.NewJSONStreamFormatter()
  767. output.Write(sf.FormatError(err))
  768. }
  769. return nil
  770. }
  771. func (s *Server) postImagesLoad(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  772. return s.daemon.Repositories().Load(r.Body, w)
  773. }
  774. func (s *Server) postContainersCreate(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  775. if err := parseForm(r); err != nil {
  776. return err
  777. }
  778. if err := checkForJson(r); err != nil {
  779. return err
  780. }
  781. var (
  782. warnings []string
  783. name = r.Form.Get("name")
  784. )
  785. config, hostConfig, err := runconfig.DecodeContainerConfig(r.Body)
  786. if err != nil {
  787. return err
  788. }
  789. adjustCpuShares(version, hostConfig)
  790. containerId, warnings, err := s.daemon.ContainerCreate(name, config, hostConfig)
  791. if err != nil {
  792. return err
  793. }
  794. return writeJSON(w, http.StatusCreated, &types.ContainerCreateResponse{
  795. ID: containerId,
  796. Warnings: warnings,
  797. })
  798. }
  799. func (s *Server) postContainersRestart(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  800. if err := parseForm(r); err != nil {
  801. return err
  802. }
  803. if vars == nil {
  804. return fmt.Errorf("Missing parameter")
  805. }
  806. timeout, _ := strconv.Atoi(r.Form.Get("t"))
  807. if err := s.daemon.ContainerRestart(vars["name"], timeout); err != nil {
  808. return err
  809. }
  810. w.WriteHeader(http.StatusNoContent)
  811. return nil
  812. }
  813. func (s *Server) postContainerRename(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. name := vars["name"]
  821. newName := r.Form.Get("name")
  822. if err := s.daemon.ContainerRename(name, newName); err != nil {
  823. return err
  824. }
  825. w.WriteHeader(http.StatusNoContent)
  826. return nil
  827. }
  828. func (s *Server) deleteContainers(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  829. if err := parseForm(r); err != nil {
  830. return err
  831. }
  832. if vars == nil {
  833. return fmt.Errorf("Missing parameter")
  834. }
  835. name := vars["name"]
  836. config := &daemon.ContainerRmConfig{
  837. ForceRemove: boolValue(r, "force"),
  838. RemoveVolume: boolValue(r, "v"),
  839. RemoveLink: boolValue(r, "link"),
  840. }
  841. if err := s.daemon.ContainerRm(name, config); err != nil {
  842. // Force a 404 for the empty string
  843. if strings.Contains(strings.ToLower(err.Error()), "prefix can't be empty") {
  844. return fmt.Errorf("no such id: \"\"")
  845. }
  846. return err
  847. }
  848. w.WriteHeader(http.StatusNoContent)
  849. return nil
  850. }
  851. func (s *Server) deleteImages(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  852. if err := parseForm(r); err != nil {
  853. return err
  854. }
  855. if vars == nil {
  856. return fmt.Errorf("Missing parameter")
  857. }
  858. name := vars["name"]
  859. force := boolValue(r, "force")
  860. noprune := boolValue(r, "noprune")
  861. list, err := s.daemon.ImageDelete(name, force, noprune)
  862. if err != nil {
  863. return err
  864. }
  865. return writeJSON(w, http.StatusOK, list)
  866. }
  867. func (s *Server) postContainersStart(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  868. if vars == nil {
  869. return fmt.Errorf("Missing parameter")
  870. }
  871. // If contentLength is -1, we can assumed chunked encoding
  872. // or more technically that the length is unknown
  873. // https://golang.org/src/pkg/net/http/request.go#L139
  874. // net/http otherwise seems to swallow any headers related to chunked encoding
  875. // including r.TransferEncoding
  876. // allow a nil body for backwards compatibility
  877. var hostConfig *runconfig.HostConfig
  878. if r.Body != nil && (r.ContentLength > 0 || r.ContentLength == -1) {
  879. if err := checkForJson(r); err != nil {
  880. return err
  881. }
  882. c, err := runconfig.DecodeHostConfig(r.Body)
  883. if err != nil {
  884. return err
  885. }
  886. hostConfig = c
  887. }
  888. if err := s.daemon.ContainerStart(vars["name"], hostConfig); err != nil {
  889. if err.Error() == "Container already started" {
  890. w.WriteHeader(http.StatusNotModified)
  891. return nil
  892. }
  893. return err
  894. }
  895. w.WriteHeader(http.StatusNoContent)
  896. return nil
  897. }
  898. func (s *Server) postContainersStop(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  899. if err := parseForm(r); err != nil {
  900. return err
  901. }
  902. if vars == nil {
  903. return fmt.Errorf("Missing parameter")
  904. }
  905. seconds, _ := strconv.Atoi(r.Form.Get("t"))
  906. if err := s.daemon.ContainerStop(vars["name"], seconds); err != nil {
  907. if err.Error() == "Container already stopped" {
  908. w.WriteHeader(http.StatusNotModified)
  909. return nil
  910. }
  911. return err
  912. }
  913. w.WriteHeader(http.StatusNoContent)
  914. return nil
  915. }
  916. func (s *Server) postContainersWait(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  917. if vars == nil {
  918. return fmt.Errorf("Missing parameter")
  919. }
  920. status, err := s.daemon.ContainerWait(vars["name"], -1*time.Second)
  921. if err != nil {
  922. return err
  923. }
  924. return writeJSON(w, http.StatusOK, &types.ContainerWaitResponse{
  925. StatusCode: status,
  926. })
  927. }
  928. func (s *Server) postContainersResize(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  929. if err := parseForm(r); err != nil {
  930. return err
  931. }
  932. if vars == nil {
  933. return fmt.Errorf("Missing parameter")
  934. }
  935. height, err := strconv.Atoi(r.Form.Get("h"))
  936. if err != nil {
  937. return err
  938. }
  939. width, err := strconv.Atoi(r.Form.Get("w"))
  940. if err != nil {
  941. return err
  942. }
  943. return s.daemon.ContainerResize(vars["name"], height, width)
  944. }
  945. func (s *Server) postContainersAttach(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  946. if err := parseForm(r); err != nil {
  947. return err
  948. }
  949. if vars == nil {
  950. return fmt.Errorf("Missing parameter")
  951. }
  952. inStream, outStream, err := hijackServer(w)
  953. if err != nil {
  954. return err
  955. }
  956. defer closeStreams(inStream, outStream)
  957. if _, ok := r.Header["Upgrade"]; ok {
  958. 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")
  959. } else {
  960. fmt.Fprintf(outStream, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n")
  961. }
  962. attachWithLogsConfig := &daemon.ContainerAttachWithLogsConfig{
  963. InStream: inStream,
  964. OutStream: outStream,
  965. UseStdin: boolValue(r, "stdin"),
  966. UseStdout: boolValue(r, "stdout"),
  967. UseStderr: boolValue(r, "stderr"),
  968. Logs: boolValue(r, "logs"),
  969. Stream: boolValue(r, "stream"),
  970. }
  971. if err := s.daemon.ContainerAttachWithLogs(vars["name"], attachWithLogsConfig); err != nil {
  972. fmt.Fprintf(outStream, "Error attaching: %s\n", err)
  973. }
  974. return nil
  975. }
  976. func (s *Server) wsContainersAttach(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  977. if err := parseForm(r); err != nil {
  978. return err
  979. }
  980. if vars == nil {
  981. return fmt.Errorf("Missing parameter")
  982. }
  983. h := websocket.Handler(func(ws *websocket.Conn) {
  984. defer ws.Close()
  985. wsAttachWithLogsConfig := &daemon.ContainerWsAttachWithLogsConfig{
  986. InStream: ws,
  987. OutStream: ws,
  988. ErrStream: ws,
  989. Logs: boolValue(r, "logs"),
  990. Stream: boolValue(r, "stream"),
  991. }
  992. if err := s.daemon.ContainerWsAttachWithLogs(vars["name"], wsAttachWithLogsConfig); err != nil {
  993. logrus.Errorf("Error attaching websocket: %s", err)
  994. }
  995. })
  996. h.ServeHTTP(w, r)
  997. return nil
  998. }
  999. func (s *Server) getContainersByName(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1000. if vars == nil {
  1001. return fmt.Errorf("Missing parameter")
  1002. }
  1003. if version.LessThan("1.19") {
  1004. containerJSONRaw, err := s.daemon.ContainerInspectRaw(vars["name"])
  1005. if err != nil {
  1006. return err
  1007. }
  1008. return writeJSON(w, http.StatusOK, containerJSONRaw)
  1009. }
  1010. containerJSON, err := s.daemon.ContainerInspect(vars["name"])
  1011. if err != nil {
  1012. return err
  1013. }
  1014. return writeJSON(w, http.StatusOK, containerJSON)
  1015. }
  1016. func (s *Server) getExecByID(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1017. if vars == nil {
  1018. return fmt.Errorf("Missing parameter 'id'")
  1019. }
  1020. eConfig, err := s.daemon.ContainerExecInspect(vars["id"])
  1021. if err != nil {
  1022. return err
  1023. }
  1024. return writeJSON(w, http.StatusOK, eConfig)
  1025. }
  1026. func (s *Server) getImagesByName(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1027. if vars == nil {
  1028. return fmt.Errorf("Missing parameter")
  1029. }
  1030. imageInspect, err := s.daemon.Repositories().Lookup(vars["name"])
  1031. if err != nil {
  1032. return err
  1033. }
  1034. return writeJSON(w, http.StatusOK, imageInspect)
  1035. }
  1036. func (s *Server) postBuild(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1037. var (
  1038. authConfig = &cliconfig.AuthConfig{}
  1039. configFileEncoded = r.Header.Get("X-Registry-Config")
  1040. configFile = &cliconfig.ConfigFile{}
  1041. buildConfig = builder.NewBuildConfig()
  1042. )
  1043. if configFileEncoded != "" {
  1044. configFileJson := base64.NewDecoder(base64.URLEncoding, strings.NewReader(configFileEncoded))
  1045. if err := json.NewDecoder(configFileJson).Decode(configFile); err != nil {
  1046. // for a pull it is not an error if no auth was given
  1047. // to increase compatibility with the existing api it is defaulting to be empty
  1048. configFile = &cliconfig.ConfigFile{}
  1049. }
  1050. }
  1051. w.Header().Set("Content-Type", "application/json")
  1052. if boolValue(r, "forcerm") && version.GreaterThanOrEqualTo("1.12") {
  1053. buildConfig.Remove = true
  1054. } else if r.FormValue("rm") == "" && version.GreaterThanOrEqualTo("1.12") {
  1055. buildConfig.Remove = true
  1056. } else {
  1057. buildConfig.Remove = boolValue(r, "rm")
  1058. }
  1059. if boolValue(r, "pull") && version.GreaterThanOrEqualTo("1.16") {
  1060. buildConfig.Pull = true
  1061. }
  1062. output := ioutils.NewWriteFlusher(w)
  1063. buildConfig.Stdout = output
  1064. buildConfig.Context = r.Body
  1065. buildConfig.RemoteURL = r.FormValue("remote")
  1066. buildConfig.DockerfileName = r.FormValue("dockerfile")
  1067. buildConfig.RepoName = r.FormValue("t")
  1068. buildConfig.SuppressOutput = boolValue(r, "q")
  1069. buildConfig.NoCache = boolValue(r, "nocache")
  1070. buildConfig.ForceRemove = boolValue(r, "forcerm")
  1071. buildConfig.AuthConfig = authConfig
  1072. buildConfig.ConfigFile = configFile
  1073. buildConfig.MemorySwap = int64ValueOrZero(r, "memswap")
  1074. buildConfig.Memory = int64ValueOrZero(r, "memory")
  1075. buildConfig.CpuShares = int64ValueOrZero(r, "cpushares")
  1076. buildConfig.CpuPeriod = int64ValueOrZero(r, "cpuperiod")
  1077. buildConfig.CpuQuota = int64ValueOrZero(r, "cpuquota")
  1078. buildConfig.CpuSetCpus = r.FormValue("cpusetcpus")
  1079. buildConfig.CpuSetMems = r.FormValue("cpusetmems")
  1080. buildConfig.CgroupParent = r.FormValue("cgroupparent")
  1081. // Job cancellation. Note: not all job types support this.
  1082. if closeNotifier, ok := w.(http.CloseNotifier); ok {
  1083. finished := make(chan struct{})
  1084. defer close(finished)
  1085. go func() {
  1086. select {
  1087. case <-finished:
  1088. case <-closeNotifier.CloseNotify():
  1089. logrus.Infof("Client disconnected, cancelling job: build")
  1090. buildConfig.Cancel()
  1091. }
  1092. }()
  1093. }
  1094. if err := builder.Build(s.daemon, buildConfig); err != nil {
  1095. // Do not write the error in the http output if it's still empty.
  1096. // This prevents from writing a 200(OK) when there is an interal error.
  1097. if !output.Flushed() {
  1098. return err
  1099. }
  1100. sf := streamformatter.NewJSONStreamFormatter()
  1101. w.Write(sf.FormatError(err))
  1102. }
  1103. return nil
  1104. }
  1105. func (s *Server) postContainersCopy(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1106. if vars == nil {
  1107. return fmt.Errorf("Missing parameter")
  1108. }
  1109. if err := checkForJson(r); err != nil {
  1110. return err
  1111. }
  1112. cfg := types.CopyConfig{}
  1113. if err := json.NewDecoder(r.Body).Decode(&cfg); err != nil {
  1114. return err
  1115. }
  1116. if cfg.Resource == "" {
  1117. return fmt.Errorf("Path cannot be empty")
  1118. }
  1119. data, err := s.daemon.ContainerCopy(vars["name"], cfg.Resource)
  1120. if err != nil {
  1121. if strings.Contains(strings.ToLower(err.Error()), "no such id") {
  1122. w.WriteHeader(http.StatusNotFound)
  1123. return nil
  1124. }
  1125. if os.IsNotExist(err) {
  1126. return fmt.Errorf("Could not find the file %s in container %s", cfg.Resource, vars["name"])
  1127. }
  1128. return err
  1129. }
  1130. defer data.Close()
  1131. w.Header().Set("Content-Type", "application/x-tar")
  1132. if _, err := io.Copy(w, data); err != nil {
  1133. return err
  1134. }
  1135. return nil
  1136. }
  1137. func (s *Server) postContainerExecCreate(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1138. if err := parseForm(r); err != nil {
  1139. return err
  1140. }
  1141. name := vars["name"]
  1142. execConfig := &runconfig.ExecConfig{}
  1143. if err := json.NewDecoder(r.Body).Decode(execConfig); err != nil {
  1144. return err
  1145. }
  1146. execConfig.Container = name
  1147. if len(execConfig.Cmd) == 0 {
  1148. return fmt.Errorf("No exec command specified")
  1149. }
  1150. // Register an instance of Exec in container.
  1151. id, err := s.daemon.ContainerExecCreate(execConfig)
  1152. if err != nil {
  1153. logrus.Errorf("Error setting up exec command in container %s: %s", name, err)
  1154. return err
  1155. }
  1156. return writeJSON(w, http.StatusCreated, &types.ContainerExecCreateResponse{
  1157. ID: id,
  1158. })
  1159. }
  1160. // TODO(vishh): Refactor the code to avoid having to specify stream config as part of both create and start.
  1161. func (s *Server) postContainerExecStart(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1162. if err := parseForm(r); err != nil {
  1163. return err
  1164. }
  1165. var (
  1166. execName = vars["name"]
  1167. stdin io.ReadCloser
  1168. stdout io.Writer
  1169. stderr io.Writer
  1170. )
  1171. execStartCheck := &types.ExecStartCheck{}
  1172. if err := json.NewDecoder(r.Body).Decode(execStartCheck); err != nil {
  1173. return err
  1174. }
  1175. if !execStartCheck.Detach {
  1176. // Setting up the streaming http interface.
  1177. inStream, outStream, err := hijackServer(w)
  1178. if err != nil {
  1179. return err
  1180. }
  1181. defer closeStreams(inStream, outStream)
  1182. var errStream io.Writer
  1183. if _, ok := r.Header["Upgrade"]; ok {
  1184. 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")
  1185. } else {
  1186. fmt.Fprintf(outStream, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n")
  1187. }
  1188. if !execStartCheck.Tty {
  1189. errStream = stdcopy.NewStdWriter(outStream, stdcopy.Stderr)
  1190. outStream = stdcopy.NewStdWriter(outStream, stdcopy.Stdout)
  1191. }
  1192. stdin = inStream
  1193. stdout = outStream
  1194. stderr = errStream
  1195. }
  1196. // Now run the user process in container.
  1197. if err := s.daemon.ContainerExecStart(execName, stdin, stdout, stderr); err != nil {
  1198. logrus.Errorf("Error starting exec command in container %s: %s", execName, err)
  1199. return err
  1200. }
  1201. w.WriteHeader(http.StatusNoContent)
  1202. return nil
  1203. }
  1204. func (s *Server) postContainerExecResize(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1205. if err := parseForm(r); err != nil {
  1206. return err
  1207. }
  1208. if vars == nil {
  1209. return fmt.Errorf("Missing parameter")
  1210. }
  1211. height, err := strconv.Atoi(r.Form.Get("h"))
  1212. if err != nil {
  1213. return err
  1214. }
  1215. width, err := strconv.Atoi(r.Form.Get("w"))
  1216. if err != nil {
  1217. return err
  1218. }
  1219. return s.daemon.ContainerExecResize(vars["name"], height, width)
  1220. }
  1221. func (s *Server) optionsHandler(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1222. w.WriteHeader(http.StatusOK)
  1223. return nil
  1224. }
  1225. func writeCorsHeaders(w http.ResponseWriter, r *http.Request, corsHeaders string) {
  1226. logrus.Debugf("CORS header is enabled and set to: %s", corsHeaders)
  1227. w.Header().Add("Access-Control-Allow-Origin", corsHeaders)
  1228. w.Header().Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, X-Registry-Auth")
  1229. w.Header().Add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS")
  1230. }
  1231. func (s *Server) ping(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1232. _, err := w.Write([]byte{'O', 'K'})
  1233. return err
  1234. }
  1235. func (s *Server) initTcpSocket(addr string) (l net.Listener, err error) {
  1236. if s.cfg.TLSConfig == nil || s.cfg.TLSConfig.ClientAuth != tls.RequireAndVerifyClientCert {
  1237. logrus.Warn("/!\\ DON'T BIND ON ANY IP ADDRESS WITHOUT setting -tlsverify IF YOU DON'T KNOW WHAT YOU'RE DOING /!\\")
  1238. }
  1239. if l, err = sockets.NewTcpSocket(addr, s.cfg.TLSConfig, s.start); err != nil {
  1240. return nil, err
  1241. }
  1242. if err := allocateDaemonPort(addr); err != nil {
  1243. return nil, err
  1244. }
  1245. return
  1246. }
  1247. func makeHttpHandler(logging bool, localMethod string, localRoute string, handlerFunc HttpApiFunc, corsHeaders string, dockerVersion version.Version) http.HandlerFunc {
  1248. return func(w http.ResponseWriter, r *http.Request) {
  1249. // log the request
  1250. logrus.Debugf("Calling %s %s", localMethod, localRoute)
  1251. if logging {
  1252. logrus.Infof("%s %s", r.Method, r.RequestURI)
  1253. }
  1254. if strings.Contains(r.Header.Get("User-Agent"), "Docker-Client/") {
  1255. userAgent := strings.Split(r.Header.Get("User-Agent"), "/")
  1256. // v1.20 onwards includes the GOOS of the client after the version
  1257. // such as Docker/1.7.0 (linux)
  1258. if len(userAgent) == 2 && strings.Contains(userAgent[1], " ") {
  1259. userAgent[1] = strings.Split(userAgent[1], " ")[0]
  1260. }
  1261. if len(userAgent) == 2 && !dockerVersion.Equal(version.Version(userAgent[1])) {
  1262. logrus.Debugf("Warning: client and server don't have the same version (client: %s, server: %s)", userAgent[1], dockerVersion)
  1263. }
  1264. }
  1265. version := version.Version(mux.Vars(r)["version"])
  1266. if version == "" {
  1267. version = api.Version
  1268. }
  1269. if corsHeaders != "" {
  1270. writeCorsHeaders(w, r, corsHeaders)
  1271. }
  1272. if version.GreaterThan(api.Version) {
  1273. http.Error(w, fmt.Errorf("client is newer than server (client API version: %s, server API version: %s)", version, api.Version).Error(), http.StatusBadRequest)
  1274. return
  1275. }
  1276. if version.LessThan(api.MinVersion) {
  1277. 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)
  1278. return
  1279. }
  1280. if err := handlerFunc(version, w, r, mux.Vars(r)); err != nil {
  1281. logrus.Errorf("Handler for %s %s returned error: %s", localMethod, localRoute, err)
  1282. httpError(w, err)
  1283. }
  1284. }
  1285. }
  1286. // we keep enableCors just for legacy usage, need to be removed in the future
  1287. func createRouter(s *Server) *mux.Router {
  1288. r := mux.NewRouter()
  1289. if os.Getenv("DEBUG") != "" {
  1290. ProfilerSetup(r, "/debug/")
  1291. }
  1292. m := map[string]map[string]HttpApiFunc{
  1293. "GET": {
  1294. "/_ping": s.ping,
  1295. "/events": s.getEvents,
  1296. "/info": s.getInfo,
  1297. "/version": s.getVersion,
  1298. "/images/json": s.getImagesJSON,
  1299. "/images/search": s.getImagesSearch,
  1300. "/images/get": s.getImagesGet,
  1301. "/images/{name:.*}/get": s.getImagesGet,
  1302. "/images/{name:.*}/history": s.getImagesHistory,
  1303. "/images/{name:.*}/json": s.getImagesByName,
  1304. "/containers/ps": s.getContainersJSON,
  1305. "/containers/json": s.getContainersJSON,
  1306. "/containers/{name:.*}/export": s.getContainersExport,
  1307. "/containers/{name:.*}/changes": s.getContainersChanges,
  1308. "/containers/{name:.*}/json": s.getContainersByName,
  1309. "/containers/{name:.*}/top": s.getContainersTop,
  1310. "/containers/{name:.*}/logs": s.getContainersLogs,
  1311. "/containers/{name:.*}/stats": s.getContainersStats,
  1312. "/containers/{name:.*}/attach/ws": s.wsContainersAttach,
  1313. "/exec/{id:.*}/json": s.getExecByID,
  1314. },
  1315. "POST": {
  1316. "/auth": s.postAuth,
  1317. "/commit": s.postCommit,
  1318. "/build": s.postBuild,
  1319. "/images/create": s.postImagesCreate,
  1320. "/images/load": s.postImagesLoad,
  1321. "/images/{name:.*}/push": s.postImagesPush,
  1322. "/images/{name:.*}/tag": s.postImagesTag,
  1323. "/containers/create": s.postContainersCreate,
  1324. "/containers/{name:.*}/kill": s.postContainersKill,
  1325. "/containers/{name:.*}/pause": s.postContainersPause,
  1326. "/containers/{name:.*}/unpause": s.postContainersUnpause,
  1327. "/containers/{name:.*}/restart": s.postContainersRestart,
  1328. "/containers/{name:.*}/start": s.postContainersStart,
  1329. "/containers/{name:.*}/stop": s.postContainersStop,
  1330. "/containers/{name:.*}/wait": s.postContainersWait,
  1331. "/containers/{name:.*}/resize": s.postContainersResize,
  1332. "/containers/{name:.*}/attach": s.postContainersAttach,
  1333. "/containers/{name:.*}/copy": s.postContainersCopy,
  1334. "/containers/{name:.*}/exec": s.postContainerExecCreate,
  1335. "/exec/{name:.*}/start": s.postContainerExecStart,
  1336. "/exec/{name:.*}/resize": s.postContainerExecResize,
  1337. "/containers/{name:.*}/rename": s.postContainerRename,
  1338. },
  1339. "DELETE": {
  1340. "/containers/{name:.*}": s.deleteContainers,
  1341. "/images/{name:.*}": s.deleteImages,
  1342. },
  1343. "OPTIONS": {
  1344. "": s.optionsHandler,
  1345. },
  1346. }
  1347. // If "api-cors-header" is not given, but "api-enable-cors" is true, we set cors to "*"
  1348. // otherwise, all head values will be passed to HTTP handler
  1349. corsHeaders := s.cfg.CorsHeaders
  1350. if corsHeaders == "" && s.cfg.EnableCors {
  1351. corsHeaders = "*"
  1352. }
  1353. for method, routes := range m {
  1354. for route, fct := range routes {
  1355. logrus.Debugf("Registering %s, %s", method, route)
  1356. // NOTE: scope issue, make sure the variables are local and won't be changed
  1357. localRoute := route
  1358. localFct := fct
  1359. localMethod := method
  1360. // build the handler function
  1361. f := makeHttpHandler(s.cfg.Logging, localMethod, localRoute, localFct, corsHeaders, version.Version(s.cfg.Version))
  1362. // add the new route
  1363. if localRoute == "" {
  1364. r.Methods(localMethod).HandlerFunc(f)
  1365. } else {
  1366. r.Path("/v{version:[0-9.]+}" + localRoute).Methods(localMethod).HandlerFunc(f)
  1367. r.Path(localRoute).Methods(localMethod).HandlerFunc(f)
  1368. }
  1369. }
  1370. }
  1371. return r
  1372. }