server.go 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630
  1. package server
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "net"
  8. "net/http"
  9. "os"
  10. "runtime"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "code.google.com/p/go.net/websocket"
  15. "github.com/gorilla/mux"
  16. "github.com/Sirupsen/logrus"
  17. "github.com/docker/docker/api"
  18. "github.com/docker/docker/api/types"
  19. "github.com/docker/docker/autogen/dockerversion"
  20. "github.com/docker/docker/builder"
  21. "github.com/docker/docker/cliconfig"
  22. "github.com/docker/docker/daemon"
  23. "github.com/docker/docker/daemon/networkdriver/bridge"
  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/stdcopy"
  32. "github.com/docker/docker/pkg/streamformatter"
  33. "github.com/docker/docker/pkg/version"
  34. "github.com/docker/docker/runconfig"
  35. )
  36. type ServerConfig struct {
  37. Logging bool
  38. EnableCors bool
  39. CorsHeaders string
  40. Version string
  41. SocketGroup string
  42. Tls bool
  43. TlsVerify bool
  44. TlsCa string
  45. TlsCert string
  46. TlsKey string
  47. }
  48. type Server struct {
  49. daemon *daemon.Daemon
  50. cfg *ServerConfig
  51. router *mux.Router
  52. start chan struct{}
  53. servers []serverCloser
  54. }
  55. func New(cfg *ServerConfig) *Server {
  56. srv := &Server{
  57. cfg: cfg,
  58. start: make(chan struct{}),
  59. }
  60. r := createRouter(srv)
  61. srv.router = r
  62. return srv
  63. }
  64. func (s *Server) Close() {
  65. for _, srv := range s.servers {
  66. if err := srv.Close(); err != nil {
  67. logrus.Error(err)
  68. }
  69. }
  70. }
  71. type serverCloser interface {
  72. Serve() error
  73. Close() error
  74. }
  75. // ServeApi loops through all of the protocols sent in to docker and spawns
  76. // off a go routine to setup a serving http.Server for each.
  77. func (s *Server) ServeApi(protoAddrs []string) error {
  78. var chErrors = make(chan error, len(protoAddrs))
  79. for _, protoAddr := range protoAddrs {
  80. protoAddrParts := strings.SplitN(protoAddr, "://", 2)
  81. if len(protoAddrParts) != 2 {
  82. return fmt.Errorf("bad format, expected PROTO://ADDR")
  83. }
  84. srv, err := s.newServer(protoAddrParts[0], protoAddrParts[1])
  85. if err != nil {
  86. return err
  87. }
  88. s.servers = append(s.servers, srv)
  89. go func(proto, addr string) {
  90. logrus.Infof("Listening for HTTP on %s (%s)", proto, addr)
  91. if err := srv.Serve(); err != nil && strings.Contains(err.Error(), "use of closed network connection") {
  92. err = nil
  93. }
  94. chErrors <- err
  95. }(protoAddrParts[0], protoAddrParts[1])
  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. w.Header().Set("Content-Type", "application/json")
  218. v := &types.Version{
  219. Version: dockerversion.VERSION,
  220. ApiVersion: api.APIVERSION,
  221. GitCommit: dockerversion.GITCOMMIT,
  222. GoVersion: runtime.Version(),
  223. Os: runtime.GOOS,
  224. Arch: runtime.GOARCH,
  225. }
  226. if kernelVersion, err := kernel.GetKernelVersion(); err == nil {
  227. v.KernelVersion = kernelVersion.String()
  228. }
  229. return writeJSON(w, http.StatusOK, v)
  230. }
  231. func (s *Server) postContainersKill(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  232. if vars == nil {
  233. return fmt.Errorf("Missing parameter")
  234. }
  235. if err := parseForm(r); err != nil {
  236. return err
  237. }
  238. var sig uint64
  239. name := vars["name"]
  240. // If we have a signal, look at it. Otherwise, do nothing
  241. if sigStr := vars["signal"]; sigStr != "" {
  242. // Check if we passed the signal as a number:
  243. // The largest legal signal is 31, so let's parse on 5 bits
  244. sig, err := strconv.ParseUint(sigStr, 10, 5)
  245. if err != nil {
  246. // The signal is not a number, treat it as a string (either like
  247. // "KILL" or like "SIGKILL")
  248. sig = uint64(signal.SignalMap[strings.TrimPrefix(sigStr, "SIG")])
  249. }
  250. if sig == 0 {
  251. return fmt.Errorf("Invalid signal: %s", sigStr)
  252. }
  253. }
  254. if err := s.daemon.ContainerKill(name, sig); err != nil {
  255. return err
  256. }
  257. w.WriteHeader(http.StatusNoContent)
  258. return nil
  259. }
  260. func (s *Server) postContainersPause(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  261. if vars == nil {
  262. return fmt.Errorf("Missing parameter")
  263. }
  264. if err := parseForm(r); err != nil {
  265. return err
  266. }
  267. if err := s.daemon.ContainerPause(vars["name"]); err != nil {
  268. return err
  269. }
  270. w.WriteHeader(http.StatusNoContent)
  271. return nil
  272. }
  273. func (s *Server) postContainersUnpause(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  274. if vars == nil {
  275. return fmt.Errorf("Missing parameter")
  276. }
  277. if err := parseForm(r); err != nil {
  278. return err
  279. }
  280. if err := s.daemon.ContainerUnpause(vars["name"]); err != nil {
  281. return err
  282. }
  283. w.WriteHeader(http.StatusNoContent)
  284. return nil
  285. }
  286. func (s *Server) getContainersExport(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  287. if vars == nil {
  288. return fmt.Errorf("Missing parameter")
  289. }
  290. return s.daemon.ContainerExport(vars["name"], w)
  291. }
  292. func (s *Server) getImagesJSON(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  293. if err := parseForm(r); err != nil {
  294. return err
  295. }
  296. imagesConfig := graph.ImagesConfig{
  297. Filters: r.Form.Get("filters"),
  298. // FIXME this parameter could just be a match filter
  299. Filter: r.Form.Get("filter"),
  300. All: boolValue(r, "all"),
  301. }
  302. images, err := s.daemon.Repositories().Images(&imagesConfig)
  303. if err != nil {
  304. return err
  305. }
  306. if version.GreaterThanOrEqualTo("1.7") {
  307. return writeJSON(w, http.StatusOK, images)
  308. }
  309. legacyImages := []types.LegacyImage{}
  310. for _, image := range images {
  311. for _, repoTag := range image.RepoTags {
  312. repo, tag := parsers.ParseRepositoryTag(repoTag)
  313. legacyImage := types.LegacyImage{
  314. Repository: repo,
  315. Tag: tag,
  316. ID: image.ID,
  317. Created: image.Created,
  318. Size: image.Size,
  319. VirtualSize: image.VirtualSize,
  320. }
  321. legacyImages = append(legacyImages, legacyImage)
  322. }
  323. }
  324. return writeJSON(w, http.StatusOK, legacyImages)
  325. }
  326. func (s *Server) getInfo(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  327. w.Header().Set("Content-Type", "application/json")
  328. info, err := s.daemon.SystemInfo()
  329. if err != nil {
  330. return err
  331. }
  332. return writeJSON(w, http.StatusOK, info)
  333. }
  334. func (s *Server) getEvents(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  335. if err := parseForm(r); err != nil {
  336. return err
  337. }
  338. var since int64 = -1
  339. if r.Form.Get("since") != "" {
  340. s, err := strconv.ParseInt(r.Form.Get("since"), 10, 64)
  341. if err != nil {
  342. return err
  343. }
  344. since = s
  345. }
  346. var until int64 = -1
  347. if r.Form.Get("until") != "" {
  348. u, err := strconv.ParseInt(r.Form.Get("until"), 10, 64)
  349. if err != nil {
  350. return err
  351. }
  352. until = u
  353. }
  354. timer := time.NewTimer(0)
  355. timer.Stop()
  356. if until > 0 {
  357. dur := time.Unix(until, 0).Sub(time.Now())
  358. timer = time.NewTimer(dur)
  359. }
  360. ef, err := filters.FromParam(r.Form.Get("filters"))
  361. if err != nil {
  362. return err
  363. }
  364. isFiltered := func(field string, filter []string) bool {
  365. if len(filter) == 0 {
  366. return false
  367. }
  368. for _, v := range filter {
  369. if v == field {
  370. return false
  371. }
  372. if strings.Contains(field, ":") {
  373. image := strings.Split(field, ":")
  374. if image[0] == v {
  375. return false
  376. }
  377. }
  378. }
  379. return true
  380. }
  381. d := s.daemon
  382. es := d.EventsService
  383. w.Header().Set("Content-Type", "application/json")
  384. enc := json.NewEncoder(ioutils.NewWriteFlusher(w))
  385. getContainerId := func(cn string) string {
  386. c, err := d.Get(cn)
  387. if err != nil {
  388. return ""
  389. }
  390. return c.ID
  391. }
  392. sendEvent := func(ev *jsonmessage.JSONMessage) error {
  393. //incoming container filter can be name,id or partial id, convert and replace as a full container id
  394. for i, cn := range ef["container"] {
  395. ef["container"][i] = getContainerId(cn)
  396. }
  397. if isFiltered(ev.Status, ef["event"]) || isFiltered(ev.From, ef["image"]) ||
  398. isFiltered(ev.ID, ef["container"]) {
  399. return nil
  400. }
  401. return enc.Encode(ev)
  402. }
  403. current, l := es.Subscribe()
  404. defer es.Evict(l)
  405. for _, ev := range current {
  406. if ev.Time < since {
  407. continue
  408. }
  409. if err := sendEvent(ev); err != nil {
  410. return err
  411. }
  412. }
  413. for {
  414. select {
  415. case ev := <-l:
  416. jev, ok := ev.(*jsonmessage.JSONMessage)
  417. if !ok {
  418. continue
  419. }
  420. if err := sendEvent(jev); err != nil {
  421. return err
  422. }
  423. case <-timer.C:
  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 version.LessThan("1.4") {
  451. return fmt.Errorf("top was improved a lot since 1.3, Please upgrade your docker client.")
  452. }
  453. if vars == nil {
  454. return fmt.Errorf("Missing parameter")
  455. }
  456. if err := parseForm(r); err != nil {
  457. return err
  458. }
  459. procList, err := s.daemon.ContainerTop(vars["name"], r.Form.Get("ps_args"))
  460. if err != nil {
  461. return err
  462. }
  463. return writeJSON(w, http.StatusOK, procList)
  464. }
  465. func (s *Server) getContainersJSON(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  466. if err := parseForm(r); err != nil {
  467. return err
  468. }
  469. config := &daemon.ContainersConfig{
  470. All: boolValue(r, "all"),
  471. Size: boolValue(r, "size"),
  472. Since: r.Form.Get("since"),
  473. Before: r.Form.Get("before"),
  474. Filters: r.Form.Get("filters"),
  475. }
  476. if tmpLimit := r.Form.Get("limit"); tmpLimit != "" {
  477. limit, err := strconv.Atoi(tmpLimit)
  478. if err != nil {
  479. return err
  480. }
  481. config.Limit = limit
  482. }
  483. containers, err := s.daemon.Containers(config)
  484. if err != nil {
  485. return err
  486. }
  487. return writeJSON(w, http.StatusOK, containers)
  488. }
  489. func (s *Server) getContainersStats(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  490. if err := parseForm(r); err != nil {
  491. return err
  492. }
  493. if vars == nil {
  494. return fmt.Errorf("Missing parameter")
  495. }
  496. return s.daemon.ContainerStats(vars["name"], boolValue(r, "stream"), ioutils.NewWriteFlusher(w))
  497. }
  498. func (s *Server) getContainersLogs(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  499. if err := parseForm(r); err != nil {
  500. return err
  501. }
  502. if vars == nil {
  503. return fmt.Errorf("Missing parameter")
  504. }
  505. // Validate args here, because we can't return not StatusOK after job.Run() call
  506. stdout, stderr := boolValue(r, "stdout"), boolValue(r, "stderr")
  507. if !(stdout || stderr) {
  508. return fmt.Errorf("Bad parameters: you must choose at least one stream")
  509. }
  510. var since time.Time
  511. if r.Form.Get("since") != "" {
  512. s, err := strconv.ParseInt(r.Form.Get("since"), 10, 64)
  513. if err != nil {
  514. return err
  515. }
  516. since = time.Unix(s, 0)
  517. }
  518. logsConfig := &daemon.ContainerLogsConfig{
  519. Follow: boolValue(r, "follow"),
  520. Timestamps: boolValue(r, "timestamps"),
  521. Since: since,
  522. Tail: r.Form.Get("tail"),
  523. UseStdout: stdout,
  524. UseStderr: stderr,
  525. OutStream: ioutils.NewWriteFlusher(w),
  526. }
  527. if err := s.daemon.ContainerLogs(vars["name"], logsConfig); err != nil {
  528. fmt.Fprintf(w, "Error running logs job: %s\n", err)
  529. }
  530. return nil
  531. }
  532. func (s *Server) postImagesTag(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  533. if err := parseForm(r); err != nil {
  534. return err
  535. }
  536. if vars == nil {
  537. return fmt.Errorf("Missing parameter")
  538. }
  539. repo := r.Form.Get("repo")
  540. tag := r.Form.Get("tag")
  541. force := boolValue(r, "force")
  542. if err := s.daemon.Repositories().Tag(repo, tag, vars["name"], force); err != nil {
  543. return err
  544. }
  545. w.WriteHeader(http.StatusCreated)
  546. return nil
  547. }
  548. func (s *Server) postCommit(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  549. if err := parseForm(r); err != nil {
  550. return err
  551. }
  552. if err := checkForJson(r); err != nil {
  553. return err
  554. }
  555. cont := r.Form.Get("container")
  556. pause := boolValue(r, "pause")
  557. if r.FormValue("pause") == "" && version.GreaterThanOrEqualTo("1.13") {
  558. pause = true
  559. }
  560. c, _, err := runconfig.DecodeContainerConfig(r.Body)
  561. if err != nil && err != io.EOF { //Do not fail if body is empty.
  562. return err
  563. }
  564. if c == nil {
  565. c = &runconfig.Config{}
  566. }
  567. containerCommitConfig := &daemon.ContainerCommitConfig{
  568. Pause: pause,
  569. Repo: r.Form.Get("repo"),
  570. Tag: r.Form.Get("tag"),
  571. Author: r.Form.Get("author"),
  572. Comment: r.Form.Get("comment"),
  573. Changes: r.Form["changes"],
  574. Config: c,
  575. }
  576. imgID, err := builder.Commit(s.daemon, cont, containerCommitConfig)
  577. if err != nil {
  578. return err
  579. }
  580. return writeJSON(w, http.StatusCreated, &types.ContainerCommitResponse{
  581. ID: imgID,
  582. })
  583. }
  584. // Creates an image from Pull or from Import
  585. func (s *Server) postImagesCreate(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  586. if err := parseForm(r); err != nil {
  587. return err
  588. }
  589. var (
  590. image = r.Form.Get("fromImage")
  591. repo = r.Form.Get("repo")
  592. tag = r.Form.Get("tag")
  593. )
  594. authEncoded := r.Header.Get("X-Registry-Auth")
  595. authConfig := &cliconfig.AuthConfig{}
  596. if authEncoded != "" {
  597. authJson := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authEncoded))
  598. if err := json.NewDecoder(authJson).Decode(authConfig); err != nil {
  599. // for a pull it is not an error if no auth was given
  600. // to increase compatibility with the existing api it is defaulting to be empty
  601. authConfig = &cliconfig.AuthConfig{}
  602. }
  603. }
  604. var (
  605. err error
  606. useJSON = version.GreaterThan("1.0")
  607. output = ioutils.NewWriteFlusher(w)
  608. )
  609. if useJSON {
  610. w.Header().Set("Content-Type", "application/json")
  611. }
  612. if image != "" { //pull
  613. if tag == "" {
  614. image, tag = parsers.ParseRepositoryTag(image)
  615. }
  616. metaHeaders := map[string][]string{}
  617. for k, v := range r.Header {
  618. if strings.HasPrefix(k, "X-Meta-") {
  619. metaHeaders[k] = v
  620. }
  621. }
  622. imagePullConfig := &graph.ImagePullConfig{
  623. Parallel: version.GreaterThan("1.3"),
  624. MetaHeaders: metaHeaders,
  625. AuthConfig: authConfig,
  626. OutStream: output,
  627. Json: useJSON,
  628. }
  629. err = s.daemon.Repositories().Pull(image, tag, imagePullConfig)
  630. } else { //import
  631. if tag == "" {
  632. repo, tag = parsers.ParseRepositoryTag(repo)
  633. }
  634. src := r.Form.Get("fromSrc")
  635. imageImportConfig := &graph.ImageImportConfig{
  636. Changes: r.Form["changes"],
  637. InConfig: r.Body,
  638. OutStream: output,
  639. Json: useJSON,
  640. }
  641. newConfig, err := builder.BuildFromConfig(s.daemon, &runconfig.Config{}, imageImportConfig.Changes)
  642. if err != nil {
  643. return err
  644. }
  645. imageImportConfig.ContainerConfig = newConfig
  646. err = s.daemon.Repositories().Import(src, repo, tag, imageImportConfig)
  647. }
  648. if err != nil {
  649. if !output.Flushed() {
  650. return err
  651. }
  652. sf := streamformatter.NewStreamFormatter(useJSON)
  653. output.Write(sf.FormatError(err))
  654. }
  655. return nil
  656. }
  657. func (s *Server) getImagesSearch(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  658. if err := parseForm(r); err != nil {
  659. return err
  660. }
  661. var (
  662. config *cliconfig.AuthConfig
  663. authEncoded = r.Header.Get("X-Registry-Auth")
  664. headers = map[string][]string{}
  665. )
  666. if authEncoded != "" {
  667. authJson := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authEncoded))
  668. if err := json.NewDecoder(authJson).Decode(&config); err != nil {
  669. // for a search it is not an error if no auth was given
  670. // to increase compatibility with the existing api it is defaulting to be empty
  671. config = &cliconfig.AuthConfig{}
  672. }
  673. }
  674. for k, v := range r.Header {
  675. if strings.HasPrefix(k, "X-Meta-") {
  676. headers[k] = v
  677. }
  678. }
  679. query, err := s.daemon.RegistryService.Search(r.Form.Get("term"), config, headers)
  680. if err != nil {
  681. return err
  682. }
  683. return json.NewEncoder(w).Encode(query.Results)
  684. }
  685. func (s *Server) postImagesPush(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  686. if vars == nil {
  687. return fmt.Errorf("Missing parameter")
  688. }
  689. metaHeaders := map[string][]string{}
  690. for k, v := range r.Header {
  691. if strings.HasPrefix(k, "X-Meta-") {
  692. metaHeaders[k] = v
  693. }
  694. }
  695. if err := parseForm(r); err != nil {
  696. return err
  697. }
  698. authConfig := &cliconfig.AuthConfig{}
  699. authEncoded := r.Header.Get("X-Registry-Auth")
  700. if authEncoded != "" {
  701. // the new format is to handle the authConfig as a header
  702. authJson := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authEncoded))
  703. if err := json.NewDecoder(authJson).Decode(authConfig); err != nil {
  704. // to increase compatibility to existing api it is defaulting to be empty
  705. authConfig = &cliconfig.AuthConfig{}
  706. }
  707. } else {
  708. // the old format is supported for compatibility if there was no authConfig header
  709. if err := json.NewDecoder(r.Body).Decode(authConfig); err != nil {
  710. return fmt.Errorf("Bad parameters and missing X-Registry-Auth: %v", err)
  711. }
  712. }
  713. useJSON := version.GreaterThan("1.0")
  714. name := vars["name"]
  715. output := ioutils.NewWriteFlusher(w)
  716. imagePushConfig := &graph.ImagePushConfig{
  717. MetaHeaders: metaHeaders,
  718. AuthConfig: authConfig,
  719. Tag: r.Form.Get("tag"),
  720. OutStream: output,
  721. Json: useJSON,
  722. }
  723. if useJSON {
  724. w.Header().Set("Content-Type", "application/json")
  725. }
  726. if err := s.daemon.Repositories().Push(name, imagePushConfig); err != nil {
  727. if !output.Flushed() {
  728. return err
  729. }
  730. sf := streamformatter.NewStreamFormatter(useJSON)
  731. output.Write(sf.FormatError(err))
  732. }
  733. return nil
  734. }
  735. func (s *Server) getImagesGet(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  736. if vars == nil {
  737. return fmt.Errorf("Missing parameter")
  738. }
  739. if err := parseForm(r); err != nil {
  740. return err
  741. }
  742. useJSON := version.GreaterThan("1.0")
  743. if useJSON {
  744. w.Header().Set("Content-Type", "application/x-tar")
  745. }
  746. output := ioutils.NewWriteFlusher(w)
  747. imageExportConfig := &graph.ImageExportConfig{Outstream: output}
  748. if name, ok := vars["name"]; ok {
  749. imageExportConfig.Names = []string{name}
  750. } else {
  751. imageExportConfig.Names = r.Form["names"]
  752. }
  753. if err := s.daemon.Repositories().ImageExport(imageExportConfig); err != nil {
  754. if !output.Flushed() {
  755. return err
  756. }
  757. sf := streamformatter.NewStreamFormatter(useJSON)
  758. output.Write(sf.FormatError(err))
  759. }
  760. return nil
  761. }
  762. func (s *Server) postImagesLoad(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  763. return s.daemon.Repositories().Load(r.Body, w)
  764. }
  765. func (s *Server) postContainersCreate(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  766. if err := parseForm(r); err != nil {
  767. return nil
  768. }
  769. if err := checkForJson(r); err != nil {
  770. return err
  771. }
  772. var (
  773. warnings []string
  774. name = r.Form.Get("name")
  775. )
  776. config, hostConfig, err := runconfig.DecodeContainerConfig(r.Body)
  777. if err != nil {
  778. return err
  779. }
  780. containerId, warnings, err := s.daemon.ContainerCreate(name, config, hostConfig)
  781. if err != nil {
  782. return err
  783. }
  784. return writeJSON(w, http.StatusCreated, &types.ContainerCreateResponse{
  785. ID: containerId,
  786. Warnings: warnings,
  787. })
  788. }
  789. func (s *Server) postContainersRestart(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  790. if err := parseForm(r); err != nil {
  791. return err
  792. }
  793. if vars == nil {
  794. return fmt.Errorf("Missing parameter")
  795. }
  796. timeout, _ := strconv.Atoi(r.Form.Get("t"))
  797. if err := s.daemon.ContainerRestart(vars["name"], timeout); err != nil {
  798. return err
  799. }
  800. w.WriteHeader(http.StatusNoContent)
  801. return nil
  802. }
  803. func (s *Server) postContainerRename(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  804. if err := parseForm(r); err != nil {
  805. return err
  806. }
  807. if vars == nil {
  808. return fmt.Errorf("Missing parameter")
  809. }
  810. name := vars["name"]
  811. newName := r.Form.Get("name")
  812. if err := s.daemon.ContainerRename(name, newName); err != nil {
  813. return err
  814. }
  815. w.WriteHeader(http.StatusNoContent)
  816. return nil
  817. }
  818. func (s *Server) deleteContainers(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  819. if err := parseForm(r); err != nil {
  820. return err
  821. }
  822. if vars == nil {
  823. return fmt.Errorf("Missing parameter")
  824. }
  825. name := vars["name"]
  826. config := &daemon.ContainerRmConfig{
  827. ForceRemove: boolValue(r, "force"),
  828. RemoveVolume: boolValue(r, "v"),
  829. RemoveLink: boolValue(r, "link"),
  830. }
  831. if err := s.daemon.ContainerRm(name, config); err != nil {
  832. // Force a 404 for the empty string
  833. if strings.Contains(strings.ToLower(err.Error()), "prefix can't be empty") {
  834. return fmt.Errorf("no such id: \"\"")
  835. }
  836. return err
  837. }
  838. w.WriteHeader(http.StatusNoContent)
  839. return nil
  840. }
  841. func (s *Server) deleteImages(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  842. if err := parseForm(r); err != nil {
  843. return err
  844. }
  845. if vars == nil {
  846. return fmt.Errorf("Missing parameter")
  847. }
  848. name := vars["name"]
  849. force := boolValue(r, "force")
  850. noprune := boolValue(r, "noprune")
  851. list, err := s.daemon.ImageDelete(name, force, noprune)
  852. if err != nil {
  853. return err
  854. }
  855. return writeJSON(w, http.StatusOK, list)
  856. }
  857. func (s *Server) postContainersStart(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  858. if vars == nil {
  859. return fmt.Errorf("Missing parameter")
  860. }
  861. // If contentLength is -1, we can assumed chunked encoding
  862. // or more technically that the length is unknown
  863. // https://golang.org/src/pkg/net/http/request.go#L139
  864. // net/http otherwise seems to swallow any headers related to chunked encoding
  865. // including r.TransferEncoding
  866. // allow a nil body for backwards compatibility
  867. var hostConfig *runconfig.HostConfig
  868. if r.Body != nil && (r.ContentLength > 0 || r.ContentLength == -1) {
  869. if err := checkForJson(r); err != nil {
  870. return err
  871. }
  872. c, err := runconfig.DecodeHostConfig(r.Body)
  873. if err != nil {
  874. return err
  875. }
  876. hostConfig = c
  877. }
  878. if err := s.daemon.ContainerStart(vars["name"], hostConfig); err != nil {
  879. if err.Error() == "Container already started" {
  880. w.WriteHeader(http.StatusNotModified)
  881. return nil
  882. }
  883. return err
  884. }
  885. w.WriteHeader(http.StatusNoContent)
  886. return nil
  887. }
  888. func (s *Server) postContainersStop(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  889. if err := parseForm(r); err != nil {
  890. return err
  891. }
  892. if vars == nil {
  893. return fmt.Errorf("Missing parameter")
  894. }
  895. seconds, _ := strconv.Atoi(r.Form.Get("t"))
  896. if err := s.daemon.ContainerStop(vars["name"], seconds); err != nil {
  897. if err.Error() == "Container already stopped" {
  898. w.WriteHeader(http.StatusNotModified)
  899. return nil
  900. }
  901. return err
  902. }
  903. w.WriteHeader(http.StatusNoContent)
  904. return nil
  905. }
  906. func (s *Server) postContainersWait(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  907. if vars == nil {
  908. return fmt.Errorf("Missing parameter")
  909. }
  910. status, err := s.daemon.ContainerWait(vars["name"], -1*time.Second)
  911. if err != nil {
  912. return err
  913. }
  914. return writeJSON(w, http.StatusOK, &types.ContainerWaitResponse{
  915. StatusCode: status,
  916. })
  917. }
  918. func (s *Server) postContainersResize(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  919. if err := parseForm(r); err != nil {
  920. return err
  921. }
  922. if vars == nil {
  923. return fmt.Errorf("Missing parameter")
  924. }
  925. height, err := strconv.Atoi(r.Form.Get("h"))
  926. if err != nil {
  927. return err
  928. }
  929. width, err := strconv.Atoi(r.Form.Get("w"))
  930. if err != nil {
  931. return err
  932. }
  933. return s.daemon.ContainerResize(vars["name"], height, width)
  934. }
  935. func (s *Server) postContainersAttach(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  936. if err := parseForm(r); err != nil {
  937. return err
  938. }
  939. if vars == nil {
  940. return fmt.Errorf("Missing parameter")
  941. }
  942. inStream, outStream, err := hijackServer(w)
  943. if err != nil {
  944. return err
  945. }
  946. defer closeStreams(inStream, outStream)
  947. if _, ok := r.Header["Upgrade"]; ok {
  948. 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")
  949. } else {
  950. fmt.Fprintf(outStream, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n")
  951. }
  952. attachWithLogsConfig := &daemon.ContainerAttachWithLogsConfig{
  953. InStream: inStream,
  954. OutStream: outStream,
  955. UseStdin: boolValue(r, "stdin"),
  956. UseStdout: boolValue(r, "stdout"),
  957. UseStderr: boolValue(r, "stderr"),
  958. Logs: boolValue(r, "logs"),
  959. Stream: boolValue(r, "stream"),
  960. Multiplex: version.GreaterThanOrEqualTo("1.6"),
  961. }
  962. if err := s.daemon.ContainerAttachWithLogs(vars["name"], attachWithLogsConfig); err != nil {
  963. fmt.Fprintf(outStream, "Error attaching: %s\n", err)
  964. }
  965. return nil
  966. }
  967. func (s *Server) wsContainersAttach(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  968. if err := parseForm(r); err != nil {
  969. return err
  970. }
  971. if vars == nil {
  972. return fmt.Errorf("Missing parameter")
  973. }
  974. h := websocket.Handler(func(ws *websocket.Conn) {
  975. defer ws.Close()
  976. wsAttachWithLogsConfig := &daemon.ContainerWsAttachWithLogsConfig{
  977. InStream: ws,
  978. OutStream: ws,
  979. ErrStream: ws,
  980. Logs: boolValue(r, "logs"),
  981. Stream: boolValue(r, "stream"),
  982. }
  983. if err := s.daemon.ContainerWsAttachWithLogs(vars["name"], wsAttachWithLogsConfig); err != nil {
  984. logrus.Errorf("Error attaching websocket: %s", err)
  985. }
  986. })
  987. h.ServeHTTP(w, r)
  988. return nil
  989. }
  990. func (s *Server) getContainersByName(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  991. if vars == nil {
  992. return fmt.Errorf("Missing parameter")
  993. }
  994. name := vars["name"]
  995. if version.LessThan("1.12") {
  996. containerJSONRaw, err := s.daemon.ContainerInspectRaw(name)
  997. if err != nil {
  998. return err
  999. }
  1000. return writeJSON(w, http.StatusOK, containerJSONRaw)
  1001. }
  1002. containerJSON, err := s.daemon.ContainerInspect(name)
  1003. if err != nil {
  1004. return err
  1005. }
  1006. return writeJSON(w, http.StatusOK, containerJSON)
  1007. }
  1008. func (s *Server) getExecByID(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1009. if vars == nil {
  1010. return fmt.Errorf("Missing parameter 'id'")
  1011. }
  1012. eConfig, err := s.daemon.ContainerExecInspect(vars["id"])
  1013. if err != nil {
  1014. return err
  1015. }
  1016. return writeJSON(w, http.StatusOK, eConfig)
  1017. }
  1018. func (s *Server) getImagesByName(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1019. if vars == nil {
  1020. return fmt.Errorf("Missing parameter")
  1021. }
  1022. name := vars["name"]
  1023. if version.LessThan("1.12") {
  1024. imageInspectRaw, err := s.daemon.Repositories().LookupRaw(name)
  1025. if err != nil {
  1026. return err
  1027. }
  1028. return writeJSON(w, http.StatusOK, imageInspectRaw)
  1029. }
  1030. imageInspect, err := s.daemon.Repositories().Lookup(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. if version.LessThan("1.3") {
  1038. return fmt.Errorf("Multipart upload for build is no longer supported. Please upgrade your docker client.")
  1039. }
  1040. var (
  1041. authEncoded = r.Header.Get("X-Registry-Auth")
  1042. authConfig = &cliconfig.AuthConfig{}
  1043. configFileEncoded = r.Header.Get("X-Registry-Config")
  1044. configFile = &cliconfig.ConfigFile{}
  1045. buildConfig = builder.NewBuildConfig()
  1046. )
  1047. // This block can be removed when API versions prior to 1.9 are deprecated.
  1048. // Both headers will be parsed and sent along to the daemon, but if a non-empty
  1049. // ConfigFile is present, any value provided as an AuthConfig directly will
  1050. // be overridden. See BuildFile::CmdFrom for details.
  1051. if version.LessThan("1.9") && authEncoded != "" {
  1052. authJson := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authEncoded))
  1053. if err := json.NewDecoder(authJson).Decode(authConfig); err != nil {
  1054. // for a pull it is not an error if no auth was given
  1055. // to increase compatibility with the existing api it is defaulting to be empty
  1056. authConfig = &cliconfig.AuthConfig{}
  1057. }
  1058. }
  1059. if configFileEncoded != "" {
  1060. configFileJson := base64.NewDecoder(base64.URLEncoding, strings.NewReader(configFileEncoded))
  1061. if err := json.NewDecoder(configFileJson).Decode(configFile); err != nil {
  1062. // for a pull it is not an error if no auth was given
  1063. // to increase compatibility with the existing api it is defaulting to be empty
  1064. configFile = &cliconfig.ConfigFile{}
  1065. }
  1066. }
  1067. if version.GreaterThanOrEqualTo("1.8") {
  1068. w.Header().Set("Content-Type", "application/json")
  1069. buildConfig.JSONFormat = true
  1070. }
  1071. if boolValue(r, "forcerm") && version.GreaterThanOrEqualTo("1.12") {
  1072. buildConfig.Remove = true
  1073. } else if r.FormValue("rm") == "" && version.GreaterThanOrEqualTo("1.12") {
  1074. buildConfig.Remove = true
  1075. } else {
  1076. buildConfig.Remove = boolValue(r, "rm")
  1077. }
  1078. if boolValue(r, "pull") && version.GreaterThanOrEqualTo("1.16") {
  1079. buildConfig.Pull = true
  1080. }
  1081. output := ioutils.NewWriteFlusher(w)
  1082. buildConfig.Stdout = output
  1083. buildConfig.Context = r.Body
  1084. buildConfig.RemoteURL = r.FormValue("remote")
  1085. buildConfig.DockerfileName = r.FormValue("dockerfile")
  1086. buildConfig.RepoName = r.FormValue("t")
  1087. buildConfig.SuppressOutput = boolValue(r, "q")
  1088. buildConfig.NoCache = boolValue(r, "nocache")
  1089. buildConfig.ForceRemove = boolValue(r, "forcerm")
  1090. buildConfig.AuthConfig = authConfig
  1091. buildConfig.ConfigFile = configFile
  1092. buildConfig.MemorySwap = int64ValueOrZero(r, "memswap")
  1093. buildConfig.Memory = int64ValueOrZero(r, "memory")
  1094. buildConfig.CpuShares = int64ValueOrZero(r, "cpushares")
  1095. buildConfig.CpuPeriod = int64ValueOrZero(r, "cpuperiod")
  1096. buildConfig.CpuQuota = int64ValueOrZero(r, "cpuquota")
  1097. buildConfig.CpuSetCpus = r.FormValue("cpusetcpus")
  1098. buildConfig.CpuSetMems = r.FormValue("cpusetmems")
  1099. buildConfig.CgroupParent = r.FormValue("cgroupparent")
  1100. // Job cancellation. Note: not all job types support this.
  1101. if closeNotifier, ok := w.(http.CloseNotifier); ok {
  1102. finished := make(chan struct{})
  1103. defer close(finished)
  1104. go func() {
  1105. select {
  1106. case <-finished:
  1107. case <-closeNotifier.CloseNotify():
  1108. logrus.Infof("Client disconnected, cancelling job: build")
  1109. buildConfig.Cancel()
  1110. }
  1111. }()
  1112. }
  1113. if err := builder.Build(s.daemon, buildConfig); err != nil {
  1114. // Do not write the error in the http output if it's still empty.
  1115. // This prevents from writing a 200(OK) when there is an interal error.
  1116. if !output.Flushed() {
  1117. return err
  1118. }
  1119. sf := streamformatter.NewStreamFormatter(version.GreaterThanOrEqualTo("1.8"))
  1120. w.Write(sf.FormatError(err))
  1121. }
  1122. return nil
  1123. }
  1124. func (s *Server) postContainersCopy(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1125. if vars == nil {
  1126. return fmt.Errorf("Missing parameter")
  1127. }
  1128. if err := checkForJson(r); err != nil {
  1129. return err
  1130. }
  1131. cfg := types.CopyConfig{}
  1132. if err := json.NewDecoder(r.Body).Decode(&cfg); err != nil {
  1133. return err
  1134. }
  1135. if cfg.Resource == "" {
  1136. return fmt.Errorf("Path cannot be empty")
  1137. }
  1138. data, err := s.daemon.ContainerCopy(vars["name"], cfg.Resource)
  1139. if err != nil {
  1140. if strings.Contains(strings.ToLower(err.Error()), "no such id") {
  1141. w.WriteHeader(http.StatusNotFound)
  1142. return nil
  1143. }
  1144. if os.IsNotExist(err) {
  1145. return fmt.Errorf("Could not find the file %s in container %s", cfg.Resource, vars["name"])
  1146. }
  1147. return err
  1148. }
  1149. defer data.Close()
  1150. w.Header().Set("Content-Type", "application/x-tar")
  1151. if _, err := io.Copy(w, data); err != nil {
  1152. return err
  1153. }
  1154. return nil
  1155. }
  1156. func (s *Server) postContainerExecCreate(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1157. if err := parseForm(r); err != nil {
  1158. return nil
  1159. }
  1160. name := vars["name"]
  1161. execConfig := &runconfig.ExecConfig{}
  1162. if err := json.NewDecoder(r.Body).Decode(execConfig); err != nil {
  1163. return err
  1164. }
  1165. execConfig.Container = name
  1166. if len(execConfig.Cmd) == 0 {
  1167. return fmt.Errorf("No exec command specified")
  1168. }
  1169. // Register an instance of Exec in container.
  1170. id, err := s.daemon.ContainerExecCreate(execConfig)
  1171. if err != nil {
  1172. logrus.Errorf("Error setting up exec command in container %s: %s", name, err)
  1173. return err
  1174. }
  1175. return writeJSON(w, http.StatusCreated, &types.ContainerExecCreateResponse{
  1176. ID: id,
  1177. })
  1178. }
  1179. // TODO(vishh): Refactor the code to avoid having to specify stream config as part of both create and start.
  1180. func (s *Server) postContainerExecStart(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1181. if err := parseForm(r); err != nil {
  1182. return nil
  1183. }
  1184. var (
  1185. execName = vars["name"]
  1186. stdin io.ReadCloser
  1187. stdout io.Writer
  1188. stderr io.Writer
  1189. )
  1190. execStartCheck := &types.ExecStartCheck{}
  1191. if err := json.NewDecoder(r.Body).Decode(execStartCheck); err != nil {
  1192. return err
  1193. }
  1194. if !execStartCheck.Detach {
  1195. // Setting up the streaming http interface.
  1196. inStream, outStream, err := hijackServer(w)
  1197. if err != nil {
  1198. return err
  1199. }
  1200. defer closeStreams(inStream, outStream)
  1201. var errStream io.Writer
  1202. if _, ok := r.Header["Upgrade"]; ok {
  1203. 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")
  1204. } else {
  1205. fmt.Fprintf(outStream, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n")
  1206. }
  1207. if !execStartCheck.Tty && version.GreaterThanOrEqualTo("1.6") {
  1208. errStream = stdcopy.NewStdWriter(outStream, stdcopy.Stderr)
  1209. outStream = stdcopy.NewStdWriter(outStream, stdcopy.Stdout)
  1210. } else {
  1211. errStream = outStream
  1212. }
  1213. stdin = inStream
  1214. stdout = outStream
  1215. stderr = errStream
  1216. }
  1217. // Now run the user process in container.
  1218. if err := s.daemon.ContainerExecStart(execName, stdin, stdout, stderr); err != nil {
  1219. logrus.Errorf("Error starting exec command in container %s: %s", execName, err)
  1220. return err
  1221. }
  1222. w.WriteHeader(http.StatusNoContent)
  1223. return nil
  1224. }
  1225. func (s *Server) postContainerExecResize(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1226. if err := parseForm(r); err != nil {
  1227. return err
  1228. }
  1229. if vars == nil {
  1230. return fmt.Errorf("Missing parameter")
  1231. }
  1232. height, err := strconv.Atoi(r.Form.Get("h"))
  1233. if err != nil {
  1234. return err
  1235. }
  1236. width, err := strconv.Atoi(r.Form.Get("w"))
  1237. if err != nil {
  1238. return err
  1239. }
  1240. return s.daemon.ContainerExecResize(vars["name"], height, width)
  1241. }
  1242. func (s *Server) optionsHandler(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1243. w.WriteHeader(http.StatusOK)
  1244. return nil
  1245. }
  1246. func writeCorsHeaders(w http.ResponseWriter, r *http.Request, corsHeaders string) {
  1247. logrus.Debugf("CORS header is enabled and set to: %s", corsHeaders)
  1248. w.Header().Add("Access-Control-Allow-Origin", corsHeaders)
  1249. w.Header().Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, X-Registry-Auth")
  1250. w.Header().Add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS")
  1251. }
  1252. func (s *Server) ping(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1253. _, err := w.Write([]byte{'O', 'K'})
  1254. return err
  1255. }
  1256. func makeHttpHandler(logging bool, localMethod string, localRoute string, handlerFunc HttpApiFunc, corsHeaders string, dockerVersion version.Version) http.HandlerFunc {
  1257. return func(w http.ResponseWriter, r *http.Request) {
  1258. // log the request
  1259. logrus.Debugf("Calling %s %s", localMethod, localRoute)
  1260. if logging {
  1261. logrus.Infof("%s %s", r.Method, r.RequestURI)
  1262. }
  1263. if strings.Contains(r.Header.Get("User-Agent"), "Docker-Client/") {
  1264. userAgent := strings.Split(r.Header.Get("User-Agent"), "/")
  1265. if len(userAgent) == 2 && !dockerVersion.Equal(version.Version(userAgent[1])) {
  1266. logrus.Debugf("Warning: client and server don't have the same version (client: %s, server: %s)", userAgent[1], dockerVersion)
  1267. }
  1268. }
  1269. version := version.Version(mux.Vars(r)["version"])
  1270. if version == "" {
  1271. version = api.APIVERSION
  1272. }
  1273. if corsHeaders != "" {
  1274. writeCorsHeaders(w, r, corsHeaders)
  1275. }
  1276. if version.GreaterThan(api.APIVERSION) {
  1277. http.Error(w, fmt.Errorf("client and server don't have same version (client API version: %s, server API version: %s)", version, api.APIVERSION).Error(), http.StatusNotFound)
  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. }
  1373. func allocateDaemonPort(addr string) error {
  1374. host, port, err := net.SplitHostPort(addr)
  1375. if err != nil {
  1376. return err
  1377. }
  1378. intPort, err := strconv.Atoi(port)
  1379. if err != nil {
  1380. return err
  1381. }
  1382. var hostIPs []net.IP
  1383. if parsedIP := net.ParseIP(host); parsedIP != nil {
  1384. hostIPs = append(hostIPs, parsedIP)
  1385. } else if hostIPs, err = net.LookupIP(host); err != nil {
  1386. return fmt.Errorf("failed to lookup %s address in host specification", host)
  1387. }
  1388. for _, hostIP := range hostIPs {
  1389. if _, err := bridge.RequestPort(hostIP, "tcp", intPort); err != nil {
  1390. return fmt.Errorf("failed to allocate daemon listening port %d (err: %v)", intPort, err)
  1391. }
  1392. }
  1393. return nil
  1394. }