server.go 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648
  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. name := vars["name"]
  911. cont, err := s.daemon.Get(name)
  912. if err != nil {
  913. return err
  914. }
  915. status, _ := cont.WaitStop(-1 * time.Second)
  916. return writeJSON(w, http.StatusOK, &types.ContainerWaitResponse{
  917. StatusCode: status,
  918. })
  919. }
  920. func (s *Server) postContainersResize(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  921. if err := parseForm(r); err != nil {
  922. return err
  923. }
  924. if vars == nil {
  925. return fmt.Errorf("Missing parameter")
  926. }
  927. height, err := strconv.Atoi(r.Form.Get("h"))
  928. if err != nil {
  929. return err
  930. }
  931. width, err := strconv.Atoi(r.Form.Get("w"))
  932. if err != nil {
  933. return err
  934. }
  935. return s.daemon.ContainerResize(vars["name"], height, width)
  936. }
  937. func (s *Server) postContainersAttach(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  938. if err := parseForm(r); err != nil {
  939. return err
  940. }
  941. if vars == nil {
  942. return fmt.Errorf("Missing parameter")
  943. }
  944. cont, err := s.daemon.Get(vars["name"])
  945. if err != nil {
  946. return err
  947. }
  948. inStream, outStream, err := hijackServer(w)
  949. if err != nil {
  950. return err
  951. }
  952. defer closeStreams(inStream, outStream)
  953. var errStream io.Writer
  954. if _, ok := r.Header["Upgrade"]; ok {
  955. 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")
  956. } else {
  957. fmt.Fprintf(outStream, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n")
  958. }
  959. if !cont.Config.Tty && version.GreaterThanOrEqualTo("1.6") {
  960. errStream = stdcopy.NewStdWriter(outStream, stdcopy.Stderr)
  961. outStream = stdcopy.NewStdWriter(outStream, stdcopy.Stdout)
  962. } else {
  963. errStream = outStream
  964. }
  965. logs := boolValue(r, "logs")
  966. stream := boolValue(r, "stream")
  967. var stdin io.ReadCloser
  968. var stdout, stderr io.Writer
  969. if boolValue(r, "stdin") {
  970. stdin = inStream
  971. }
  972. if boolValue(r, "stdout") {
  973. stdout = outStream
  974. }
  975. if boolValue(r, "stderr") {
  976. stderr = errStream
  977. }
  978. if err := cont.AttachWithLogs(stdin, stdout, stderr, logs, stream); err != nil {
  979. fmt.Fprintf(outStream, "Error attaching: %s\n", err)
  980. }
  981. return nil
  982. }
  983. func (s *Server) wsContainersAttach(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  984. if err := parseForm(r); err != nil {
  985. return err
  986. }
  987. if vars == nil {
  988. return fmt.Errorf("Missing parameter")
  989. }
  990. cont, err := s.daemon.Get(vars["name"])
  991. if err != nil {
  992. return err
  993. }
  994. h := websocket.Handler(func(ws *websocket.Conn) {
  995. defer ws.Close()
  996. logs := r.Form.Get("logs") != ""
  997. stream := r.Form.Get("stream") != ""
  998. if err := cont.AttachWithLogs(ws, ws, ws, logs, stream); err != nil {
  999. logrus.Errorf("Error attaching websocket: %s", err)
  1000. }
  1001. })
  1002. h.ServeHTTP(w, r)
  1003. return nil
  1004. }
  1005. func (s *Server) getContainersByName(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1006. if vars == nil {
  1007. return fmt.Errorf("Missing parameter")
  1008. }
  1009. name := vars["name"]
  1010. if version.LessThan("1.12") {
  1011. containerJSONRaw, err := s.daemon.ContainerInspectRaw(name)
  1012. if err != nil {
  1013. return err
  1014. }
  1015. return writeJSON(w, http.StatusOK, containerJSONRaw)
  1016. }
  1017. containerJSON, err := s.daemon.ContainerInspect(name)
  1018. if err != nil {
  1019. return err
  1020. }
  1021. return writeJSON(w, http.StatusOK, containerJSON)
  1022. }
  1023. func (s *Server) getExecByID(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1024. if vars == nil {
  1025. return fmt.Errorf("Missing parameter 'id'")
  1026. }
  1027. eConfig, err := s.daemon.ContainerExecInspect(vars["id"])
  1028. if err != nil {
  1029. return err
  1030. }
  1031. return writeJSON(w, http.StatusOK, eConfig)
  1032. }
  1033. func (s *Server) getImagesByName(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1034. if vars == nil {
  1035. return fmt.Errorf("Missing parameter")
  1036. }
  1037. name := vars["name"]
  1038. if version.LessThan("1.12") {
  1039. imageInspectRaw, err := s.daemon.Repositories().LookupRaw(name)
  1040. if err != nil {
  1041. return err
  1042. }
  1043. return writeJSON(w, http.StatusOK, imageInspectRaw)
  1044. }
  1045. imageInspect, err := s.daemon.Repositories().Lookup(name)
  1046. if err != nil {
  1047. return err
  1048. }
  1049. return writeJSON(w, http.StatusOK, imageInspect)
  1050. }
  1051. func (s *Server) postBuild(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1052. if version.LessThan("1.3") {
  1053. return fmt.Errorf("Multipart upload for build is no longer supported. Please upgrade your docker client.")
  1054. }
  1055. var (
  1056. authEncoded = r.Header.Get("X-Registry-Auth")
  1057. authConfig = &cliconfig.AuthConfig{}
  1058. configFileEncoded = r.Header.Get("X-Registry-Config")
  1059. configFile = &cliconfig.ConfigFile{}
  1060. buildConfig = builder.NewBuildConfig()
  1061. )
  1062. // This block can be removed when API versions prior to 1.9 are deprecated.
  1063. // Both headers will be parsed and sent along to the daemon, but if a non-empty
  1064. // ConfigFile is present, any value provided as an AuthConfig directly will
  1065. // be overridden. See BuildFile::CmdFrom for details.
  1066. if version.LessThan("1.9") && authEncoded != "" {
  1067. authJson := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authEncoded))
  1068. if err := json.NewDecoder(authJson).Decode(authConfig); err != nil {
  1069. // for a pull it is not an error if no auth was given
  1070. // to increase compatibility with the existing api it is defaulting to be empty
  1071. authConfig = &cliconfig.AuthConfig{}
  1072. }
  1073. }
  1074. if configFileEncoded != "" {
  1075. configFileJson := base64.NewDecoder(base64.URLEncoding, strings.NewReader(configFileEncoded))
  1076. if err := json.NewDecoder(configFileJson).Decode(configFile); err != nil {
  1077. // for a pull it is not an error if no auth was given
  1078. // to increase compatibility with the existing api it is defaulting to be empty
  1079. configFile = &cliconfig.ConfigFile{}
  1080. }
  1081. }
  1082. if version.GreaterThanOrEqualTo("1.8") {
  1083. w.Header().Set("Content-Type", "application/json")
  1084. buildConfig.JSONFormat = true
  1085. }
  1086. if boolValue(r, "forcerm") && version.GreaterThanOrEqualTo("1.12") {
  1087. buildConfig.Remove = true
  1088. } else if r.FormValue("rm") == "" && version.GreaterThanOrEqualTo("1.12") {
  1089. buildConfig.Remove = true
  1090. } else {
  1091. buildConfig.Remove = boolValue(r, "rm")
  1092. }
  1093. if boolValue(r, "pull") && version.GreaterThanOrEqualTo("1.16") {
  1094. buildConfig.Pull = true
  1095. }
  1096. output := ioutils.NewWriteFlusher(w)
  1097. buildConfig.Stdout = output
  1098. buildConfig.Context = r.Body
  1099. buildConfig.RemoteURL = r.FormValue("remote")
  1100. buildConfig.DockerfileName = r.FormValue("dockerfile")
  1101. buildConfig.RepoName = r.FormValue("t")
  1102. buildConfig.SuppressOutput = boolValue(r, "q")
  1103. buildConfig.NoCache = boolValue(r, "nocache")
  1104. buildConfig.ForceRemove = boolValue(r, "forcerm")
  1105. buildConfig.AuthConfig = authConfig
  1106. buildConfig.ConfigFile = configFile
  1107. buildConfig.MemorySwap = int64ValueOrZero(r, "memswap")
  1108. buildConfig.Memory = int64ValueOrZero(r, "memory")
  1109. buildConfig.CpuShares = int64ValueOrZero(r, "cpushares")
  1110. buildConfig.CpuPeriod = int64ValueOrZero(r, "cpuperiod")
  1111. buildConfig.CpuQuota = int64ValueOrZero(r, "cpuquota")
  1112. buildConfig.CpuSetCpus = r.FormValue("cpusetcpus")
  1113. buildConfig.CpuSetMems = r.FormValue("cpusetmems")
  1114. buildConfig.CgroupParent = r.FormValue("cgroupparent")
  1115. // Job cancellation. Note: not all job types support this.
  1116. if closeNotifier, ok := w.(http.CloseNotifier); ok {
  1117. finished := make(chan struct{})
  1118. defer close(finished)
  1119. go func() {
  1120. select {
  1121. case <-finished:
  1122. case <-closeNotifier.CloseNotify():
  1123. logrus.Infof("Client disconnected, cancelling job: build")
  1124. buildConfig.Cancel()
  1125. }
  1126. }()
  1127. }
  1128. if err := builder.Build(s.daemon, buildConfig); err != nil {
  1129. // Do not write the error in the http output if it's still empty.
  1130. // This prevents from writing a 200(OK) when there is an interal error.
  1131. if !output.Flushed() {
  1132. return err
  1133. }
  1134. sf := streamformatter.NewStreamFormatter(version.GreaterThanOrEqualTo("1.8"))
  1135. w.Write(sf.FormatError(err))
  1136. }
  1137. return nil
  1138. }
  1139. func (s *Server) postContainersCopy(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1140. if vars == nil {
  1141. return fmt.Errorf("Missing parameter")
  1142. }
  1143. if err := checkForJson(r); err != nil {
  1144. return err
  1145. }
  1146. cfg := types.CopyConfig{}
  1147. if err := json.NewDecoder(r.Body).Decode(&cfg); err != nil {
  1148. return err
  1149. }
  1150. if cfg.Resource == "" {
  1151. return fmt.Errorf("Path cannot be empty")
  1152. }
  1153. data, err := s.daemon.ContainerCopy(vars["name"], cfg.Resource)
  1154. if err != nil {
  1155. if strings.Contains(strings.ToLower(err.Error()), "no such id") {
  1156. w.WriteHeader(http.StatusNotFound)
  1157. return nil
  1158. }
  1159. if os.IsNotExist(err) {
  1160. return fmt.Errorf("Could not find the file %s in container %s", cfg.Resource, vars["name"])
  1161. }
  1162. return err
  1163. }
  1164. defer data.Close()
  1165. w.Header().Set("Content-Type", "application/x-tar")
  1166. if _, err := io.Copy(w, data); err != nil {
  1167. return err
  1168. }
  1169. return nil
  1170. }
  1171. func (s *Server) postContainerExecCreate(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1172. if err := parseForm(r); err != nil {
  1173. return nil
  1174. }
  1175. name := vars["name"]
  1176. execConfig := &runconfig.ExecConfig{}
  1177. if err := json.NewDecoder(r.Body).Decode(execConfig); err != nil {
  1178. return err
  1179. }
  1180. execConfig.Container = name
  1181. if len(execConfig.Cmd) == 0 {
  1182. return fmt.Errorf("No exec command specified")
  1183. }
  1184. // Register an instance of Exec in container.
  1185. id, err := s.daemon.ContainerExecCreate(execConfig)
  1186. if err != nil {
  1187. logrus.Errorf("Error setting up exec command in container %s: %s", name, err)
  1188. return err
  1189. }
  1190. return writeJSON(w, http.StatusCreated, &types.ContainerExecCreateResponse{
  1191. ID: id,
  1192. })
  1193. }
  1194. // TODO(vishh): Refactor the code to avoid having to specify stream config as part of both create and start.
  1195. func (s *Server) postContainerExecStart(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1196. if err := parseForm(r); err != nil {
  1197. return nil
  1198. }
  1199. var (
  1200. execName = vars["name"]
  1201. stdin io.ReadCloser
  1202. stdout io.Writer
  1203. stderr io.Writer
  1204. )
  1205. execStartCheck := &types.ExecStartCheck{}
  1206. if err := json.NewDecoder(r.Body).Decode(execStartCheck); err != nil {
  1207. return err
  1208. }
  1209. if !execStartCheck.Detach {
  1210. // Setting up the streaming http interface.
  1211. inStream, outStream, err := hijackServer(w)
  1212. if err != nil {
  1213. return err
  1214. }
  1215. defer closeStreams(inStream, outStream)
  1216. var errStream io.Writer
  1217. if _, ok := r.Header["Upgrade"]; ok {
  1218. 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")
  1219. } else {
  1220. fmt.Fprintf(outStream, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n")
  1221. }
  1222. if !execStartCheck.Tty && version.GreaterThanOrEqualTo("1.6") {
  1223. errStream = stdcopy.NewStdWriter(outStream, stdcopy.Stderr)
  1224. outStream = stdcopy.NewStdWriter(outStream, stdcopy.Stdout)
  1225. } else {
  1226. errStream = outStream
  1227. }
  1228. stdin = inStream
  1229. stdout = outStream
  1230. stderr = errStream
  1231. }
  1232. // Now run the user process in container.
  1233. if err := s.daemon.ContainerExecStart(execName, stdin, stdout, stderr); err != nil {
  1234. logrus.Errorf("Error starting exec command in container %s: %s", execName, err)
  1235. return err
  1236. }
  1237. w.WriteHeader(http.StatusNoContent)
  1238. return nil
  1239. }
  1240. func (s *Server) postContainerExecResize(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1241. if err := parseForm(r); err != nil {
  1242. return err
  1243. }
  1244. if vars == nil {
  1245. return fmt.Errorf("Missing parameter")
  1246. }
  1247. height, err := strconv.Atoi(r.Form.Get("h"))
  1248. if err != nil {
  1249. return err
  1250. }
  1251. width, err := strconv.Atoi(r.Form.Get("w"))
  1252. if err != nil {
  1253. return err
  1254. }
  1255. return s.daemon.ContainerExecResize(vars["name"], height, width)
  1256. }
  1257. func (s *Server) optionsHandler(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1258. w.WriteHeader(http.StatusOK)
  1259. return nil
  1260. }
  1261. func writeCorsHeaders(w http.ResponseWriter, r *http.Request, corsHeaders string) {
  1262. logrus.Debugf("CORS header is enabled and set to: %s", corsHeaders)
  1263. w.Header().Add("Access-Control-Allow-Origin", corsHeaders)
  1264. w.Header().Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, X-Registry-Auth")
  1265. w.Header().Add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS")
  1266. }
  1267. func (s *Server) ping(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1268. _, err := w.Write([]byte{'O', 'K'})
  1269. return err
  1270. }
  1271. func makeHttpHandler(logging bool, localMethod string, localRoute string, handlerFunc HttpApiFunc, corsHeaders string, dockerVersion version.Version) http.HandlerFunc {
  1272. return func(w http.ResponseWriter, r *http.Request) {
  1273. // log the request
  1274. logrus.Debugf("Calling %s %s", localMethod, localRoute)
  1275. if logging {
  1276. logrus.Infof("%s %s", r.Method, r.RequestURI)
  1277. }
  1278. if strings.Contains(r.Header.Get("User-Agent"), "Docker-Client/") {
  1279. userAgent := strings.Split(r.Header.Get("User-Agent"), "/")
  1280. if len(userAgent) == 2 && !dockerVersion.Equal(version.Version(userAgent[1])) {
  1281. logrus.Debugf("Warning: client and server don't have the same version (client: %s, server: %s)", userAgent[1], dockerVersion)
  1282. }
  1283. }
  1284. version := version.Version(mux.Vars(r)["version"])
  1285. if version == "" {
  1286. version = api.APIVERSION
  1287. }
  1288. if corsHeaders != "" {
  1289. writeCorsHeaders(w, r, corsHeaders)
  1290. }
  1291. if version.GreaterThan(api.APIVERSION) {
  1292. 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)
  1293. return
  1294. }
  1295. if err := handlerFunc(version, w, r, mux.Vars(r)); err != nil {
  1296. logrus.Errorf("Handler for %s %s returned error: %s", localMethod, localRoute, err)
  1297. httpError(w, err)
  1298. }
  1299. }
  1300. }
  1301. // we keep enableCors just for legacy usage, need to be removed in the future
  1302. func createRouter(s *Server) *mux.Router {
  1303. r := mux.NewRouter()
  1304. if os.Getenv("DEBUG") != "" {
  1305. ProfilerSetup(r, "/debug/")
  1306. }
  1307. m := map[string]map[string]HttpApiFunc{
  1308. "GET": {
  1309. "/_ping": s.ping,
  1310. "/events": s.getEvents,
  1311. "/info": s.getInfo,
  1312. "/version": s.getVersion,
  1313. "/images/json": s.getImagesJSON,
  1314. "/images/search": s.getImagesSearch,
  1315. "/images/get": s.getImagesGet,
  1316. "/images/{name:.*}/get": s.getImagesGet,
  1317. "/images/{name:.*}/history": s.getImagesHistory,
  1318. "/images/{name:.*}/json": s.getImagesByName,
  1319. "/containers/ps": s.getContainersJSON,
  1320. "/containers/json": s.getContainersJSON,
  1321. "/containers/{name:.*}/export": s.getContainersExport,
  1322. "/containers/{name:.*}/changes": s.getContainersChanges,
  1323. "/containers/{name:.*}/json": s.getContainersByName,
  1324. "/containers/{name:.*}/top": s.getContainersTop,
  1325. "/containers/{name:.*}/logs": s.getContainersLogs,
  1326. "/containers/{name:.*}/stats": s.getContainersStats,
  1327. "/containers/{name:.*}/attach/ws": s.wsContainersAttach,
  1328. "/exec/{id:.*}/json": s.getExecByID,
  1329. },
  1330. "POST": {
  1331. "/auth": s.postAuth,
  1332. "/commit": s.postCommit,
  1333. "/build": s.postBuild,
  1334. "/images/create": s.postImagesCreate,
  1335. "/images/load": s.postImagesLoad,
  1336. "/images/{name:.*}/push": s.postImagesPush,
  1337. "/images/{name:.*}/tag": s.postImagesTag,
  1338. "/containers/create": s.postContainersCreate,
  1339. "/containers/{name:.*}/kill": s.postContainersKill,
  1340. "/containers/{name:.*}/pause": s.postContainersPause,
  1341. "/containers/{name:.*}/unpause": s.postContainersUnpause,
  1342. "/containers/{name:.*}/restart": s.postContainersRestart,
  1343. "/containers/{name:.*}/start": s.postContainersStart,
  1344. "/containers/{name:.*}/stop": s.postContainersStop,
  1345. "/containers/{name:.*}/wait": s.postContainersWait,
  1346. "/containers/{name:.*}/resize": s.postContainersResize,
  1347. "/containers/{name:.*}/attach": s.postContainersAttach,
  1348. "/containers/{name:.*}/copy": s.postContainersCopy,
  1349. "/containers/{name:.*}/exec": s.postContainerExecCreate,
  1350. "/exec/{name:.*}/start": s.postContainerExecStart,
  1351. "/exec/{name:.*}/resize": s.postContainerExecResize,
  1352. "/containers/{name:.*}/rename": s.postContainerRename,
  1353. },
  1354. "DELETE": {
  1355. "/containers/{name:.*}": s.deleteContainers,
  1356. "/images/{name:.*}": s.deleteImages,
  1357. },
  1358. "OPTIONS": {
  1359. "": s.optionsHandler,
  1360. },
  1361. }
  1362. // If "api-cors-header" is not given, but "api-enable-cors" is true, we set cors to "*"
  1363. // otherwise, all head values will be passed to HTTP handler
  1364. corsHeaders := s.cfg.CorsHeaders
  1365. if corsHeaders == "" && s.cfg.EnableCors {
  1366. corsHeaders = "*"
  1367. }
  1368. for method, routes := range m {
  1369. for route, fct := range routes {
  1370. logrus.Debugf("Registering %s, %s", method, route)
  1371. // NOTE: scope issue, make sure the variables are local and won't be changed
  1372. localRoute := route
  1373. localFct := fct
  1374. localMethod := method
  1375. // build the handler function
  1376. f := makeHttpHandler(s.cfg.Logging, localMethod, localRoute, localFct, corsHeaders, version.Version(s.cfg.Version))
  1377. // add the new route
  1378. if localRoute == "" {
  1379. r.Methods(localMethod).HandlerFunc(f)
  1380. } else {
  1381. r.Path("/v{version:[0-9.]+}" + localRoute).Methods(localMethod).HandlerFunc(f)
  1382. r.Path(localRoute).Methods(localMethod).HandlerFunc(f)
  1383. }
  1384. }
  1385. }
  1386. return r
  1387. }
  1388. func allocateDaemonPort(addr string) error {
  1389. host, port, err := net.SplitHostPort(addr)
  1390. if err != nil {
  1391. return err
  1392. }
  1393. intPort, err := strconv.Atoi(port)
  1394. if err != nil {
  1395. return err
  1396. }
  1397. var hostIPs []net.IP
  1398. if parsedIP := net.ParseIP(host); parsedIP != nil {
  1399. hostIPs = append(hostIPs, parsedIP)
  1400. } else if hostIPs, err = net.LookupIP(host); err != nil {
  1401. return fmt.Errorf("failed to lookup %s address in host specification", host)
  1402. }
  1403. for _, hostIP := range hostIPs {
  1404. if _, err := bridge.RequestPort(hostIP, "tcp", intPort); err != nil {
  1405. return fmt.Errorf("failed to allocate daemon listening port %d (err: %v)", intPort, err)
  1406. }
  1407. }
  1408. return nil
  1409. }