server.go 47 KB

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