server.go 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709
  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. // Config provides the configuration for the API server
  40. type Config struct {
  41. Logging bool
  42. EnableCors bool
  43. CorsHeaders string
  44. Version string
  45. SocketGroup string
  46. TLSConfig *tls.Config
  47. }
  48. // Server contains instance details for the server
  49. type Server struct {
  50. daemon *daemon.Daemon
  51. cfg *Config
  52. router *mux.Router
  53. start chan struct{}
  54. servers []serverCloser
  55. }
  56. // New returns a new instance of the server based on the specified configuration.
  57. func New(cfg *Config) *Server {
  58. srv := &Server{
  59. cfg: cfg,
  60. start: make(chan struct{}),
  61. }
  62. r := createRouter(srv)
  63. srv.router = r
  64. return srv
  65. }
  66. // Close closes servers and thus stop receiving requests
  67. func (s *Server) Close() {
  68. for _, srv := range s.servers {
  69. if err := srv.Close(); err != nil {
  70. logrus.Error(err)
  71. }
  72. }
  73. }
  74. type serverCloser interface {
  75. Serve() error
  76. Close() error
  77. }
  78. // ServeAPI loops through all of the protocols sent in to docker and spawns
  79. // off a go routine to setup a serving http.Server for each.
  80. func (s *Server) ServeAPI(protoAddrs []string) error {
  81. var chErrors = make(chan error, len(protoAddrs))
  82. for _, protoAddr := range protoAddrs {
  83. protoAddrParts := strings.SplitN(protoAddr, "://", 2)
  84. if len(protoAddrParts) != 2 {
  85. return fmt.Errorf("bad format, expected PROTO://ADDR")
  86. }
  87. srv, err := s.newServer(protoAddrParts[0], protoAddrParts[1])
  88. if err != nil {
  89. return err
  90. }
  91. s.servers = append(s.servers, srv...)
  92. for _, s := range srv {
  93. logrus.Infof("Listening for HTTP on %s (%s)", protoAddrParts[0], protoAddrParts[1])
  94. go func(s serverCloser) {
  95. if err := s.Serve(); err != nil && strings.Contains(err.Error(), "use of closed network connection") {
  96. err = nil
  97. }
  98. chErrors <- err
  99. }(s)
  100. }
  101. }
  102. for i := 0; i < len(protoAddrs); i++ {
  103. err := <-chErrors
  104. if err != nil {
  105. return err
  106. }
  107. }
  108. return nil
  109. }
  110. // HTTPServer contains an instance of http server and the listener.
  111. // srv *http.Server, contains configuration to create a http server and a mux router with all api end points.
  112. // l net.Listener, is a TCP or Socket listener that dispatches incoming request to the router.
  113. type HTTPServer struct {
  114. srv *http.Server
  115. l net.Listener
  116. }
  117. // Serve starts listening for inbound requests.
  118. func (s *HTTPServer) Serve() error {
  119. return s.srv.Serve(s.l)
  120. }
  121. // Close closes the HTTPServer from listening for the inbound requests.
  122. func (s *HTTPServer) Close() error {
  123. return s.l.Close()
  124. }
  125. // HTTPAPIFunc is an adapter to allow the use of ordinary functions as Docker API endpoints.
  126. // Any function that has the appropriate signature can be register as a API endpoint (e.g. getVersion).
  127. type HTTPAPIFunc func(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error
  128. func hijackServer(w http.ResponseWriter) (io.ReadCloser, io.Writer, error) {
  129. conn, _, err := w.(http.Hijacker).Hijack()
  130. if err != nil {
  131. return nil, nil, err
  132. }
  133. // Flush the options to make sure the client sets the raw mode
  134. conn.Write([]byte{})
  135. return conn, conn, nil
  136. }
  137. func closeStreams(streams ...interface{}) {
  138. for _, stream := range streams {
  139. if tcpc, ok := stream.(interface {
  140. CloseWrite() error
  141. }); ok {
  142. tcpc.CloseWrite()
  143. } else if closer, ok := stream.(io.Closer); ok {
  144. closer.Close()
  145. }
  146. }
  147. }
  148. // checkForJSON makes sure that the request's Content-Type is application/json.
  149. func checkForJSON(r *http.Request) error {
  150. ct := r.Header.Get("Content-Type")
  151. // No Content-Type header is ok as long as there's no Body
  152. if ct == "" {
  153. if r.Body == nil || r.ContentLength == 0 {
  154. return nil
  155. }
  156. }
  157. // Otherwise it better be json
  158. if api.MatchesContentType(ct, "application/json") {
  159. return nil
  160. }
  161. return fmt.Errorf("Content-Type specified (%s) must be 'application/json'", ct)
  162. }
  163. //If we don't do this, POST method without Content-type (even with empty body) will fail
  164. func parseForm(r *http.Request) error {
  165. if r == nil {
  166. return nil
  167. }
  168. if err := r.ParseForm(); err != nil && !strings.HasPrefix(err.Error(), "mime:") {
  169. return err
  170. }
  171. return nil
  172. }
  173. func parseMultipartForm(r *http.Request) error {
  174. if err := r.ParseMultipartForm(4096); err != nil && !strings.HasPrefix(err.Error(), "mime:") {
  175. return err
  176. }
  177. return nil
  178. }
  179. func httpError(w http.ResponseWriter, err error) {
  180. if err == nil || w == nil {
  181. logrus.WithFields(logrus.Fields{"error": err, "writer": w}).Error("unexpected HTTP error handling")
  182. return
  183. }
  184. statusCode := http.StatusInternalServerError
  185. // FIXME: this is brittle and should not be necessary.
  186. // If we need to differentiate between different possible error types, we should
  187. // create appropriate error types with clearly defined meaning.
  188. errStr := strings.ToLower(err.Error())
  189. for keyword, status := range map[string]int{
  190. "not found": http.StatusNotFound,
  191. "no such": http.StatusNotFound,
  192. "bad parameter": http.StatusBadRequest,
  193. "conflict": http.StatusConflict,
  194. "impossible": http.StatusNotAcceptable,
  195. "wrong login/password": http.StatusUnauthorized,
  196. "hasn't been activated": http.StatusForbidden,
  197. } {
  198. if strings.Contains(errStr, keyword) {
  199. statusCode = status
  200. break
  201. }
  202. }
  203. logrus.WithFields(logrus.Fields{"statusCode": statusCode, "err": err}).Error("HTTP Error")
  204. http.Error(w, err.Error(), statusCode)
  205. }
  206. // writeJSON writes the value v to the http response stream as json with standard
  207. // json encoding.
  208. func writeJSON(w http.ResponseWriter, code int, v interface{}) error {
  209. w.Header().Set("Content-Type", "application/json")
  210. w.WriteHeader(code)
  211. return json.NewEncoder(w).Encode(v)
  212. }
  213. func (s *Server) postAuth(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  214. var config *cliconfig.AuthConfig
  215. err := json.NewDecoder(r.Body).Decode(&config)
  216. r.Body.Close()
  217. if err != nil {
  218. return err
  219. }
  220. status, err := s.daemon.RegistryService.Auth(config)
  221. if err != nil {
  222. return err
  223. }
  224. return writeJSON(w, http.StatusOK, &types.AuthResponse{
  225. Status: status,
  226. })
  227. }
  228. func (s *Server) getVersion(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  229. v := &types.Version{
  230. Version: dockerversion.VERSION,
  231. ApiVersion: api.Version,
  232. GitCommit: dockerversion.GITCOMMIT,
  233. GoVersion: runtime.Version(),
  234. Os: runtime.GOOS,
  235. Arch: runtime.GOARCH,
  236. BuildTime: dockerversion.BUILDTIME,
  237. }
  238. if version.GreaterThanOrEqualTo("1.19") {
  239. v.Experimental = utils.ExperimentalBuild()
  240. }
  241. if kernelVersion, err := kernel.GetKernelVersion(); err == nil {
  242. v.KernelVersion = kernelVersion.String()
  243. }
  244. return writeJSON(w, http.StatusOK, v)
  245. }
  246. func (s *Server) postContainersKill(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  247. if vars == nil {
  248. return fmt.Errorf("Missing parameter")
  249. }
  250. if err := parseForm(r); err != nil {
  251. return err
  252. }
  253. var sig uint64
  254. name := vars["name"]
  255. // If we have a signal, look at it. Otherwise, do nothing
  256. if sigStr := r.Form.Get("signal"); sigStr != "" {
  257. // Check if we passed the signal as a number:
  258. // The largest legal signal is 31, so let's parse on 5 bits
  259. sigN, err := strconv.ParseUint(sigStr, 10, 5)
  260. if err != nil {
  261. // The signal is not a number, treat it as a string (either like
  262. // "KILL" or like "SIGKILL")
  263. syscallSig, ok := signal.SignalMap[strings.TrimPrefix(sigStr, "SIG")]
  264. if !ok {
  265. return fmt.Errorf("Invalid signal: %s", sigStr)
  266. }
  267. sig = uint64(syscallSig)
  268. } else {
  269. sig = sigN
  270. }
  271. if sig == 0 {
  272. return fmt.Errorf("Invalid signal: %s", sigStr)
  273. }
  274. }
  275. if err := s.daemon.ContainerKill(name, sig); err != nil {
  276. return err
  277. }
  278. w.WriteHeader(http.StatusNoContent)
  279. return nil
  280. }
  281. func (s *Server) postContainersPause(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  282. if vars == nil {
  283. return fmt.Errorf("Missing parameter")
  284. }
  285. if err := parseForm(r); err != nil {
  286. return err
  287. }
  288. if err := s.daemon.ContainerPause(vars["name"]); err != nil {
  289. return err
  290. }
  291. w.WriteHeader(http.StatusNoContent)
  292. return nil
  293. }
  294. func (s *Server) postContainersUnpause(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  295. if vars == nil {
  296. return fmt.Errorf("Missing parameter")
  297. }
  298. if err := parseForm(r); err != nil {
  299. return err
  300. }
  301. if err := s.daemon.ContainerUnpause(vars["name"]); err != nil {
  302. return err
  303. }
  304. w.WriteHeader(http.StatusNoContent)
  305. return nil
  306. }
  307. func (s *Server) getContainersExport(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  308. if vars == nil {
  309. return fmt.Errorf("Missing parameter")
  310. }
  311. return s.daemon.ContainerExport(vars["name"], w)
  312. }
  313. func (s *Server) getImagesJSON(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  314. if err := parseForm(r); err != nil {
  315. return err
  316. }
  317. // FIXME: The filter parameter could just be a match filter
  318. images, err := s.daemon.Repositories().Images(r.Form.Get("filters"), r.Form.Get("filter"), boolValue(r, "all"))
  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. // 'err' MUST NOT be defined within this block, we need any error
  670. // generated from the download to be available to the output
  671. // stream processing below
  672. var newConfig *runconfig.Config
  673. newConfig, err = builder.BuildFromConfig(s.daemon, &runconfig.Config{}, r.Form["changes"])
  674. if err != nil {
  675. return err
  676. }
  677. err = s.daemon.Repositories().Import(src, repo, tag, r.Body, output, newConfig)
  678. }
  679. if err != nil {
  680. if !output.Flushed() {
  681. return err
  682. }
  683. sf := streamformatter.NewJSONStreamFormatter()
  684. output.Write(sf.FormatError(err))
  685. }
  686. return nil
  687. }
  688. func (s *Server) getImagesSearch(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  689. if err := parseForm(r); err != nil {
  690. return err
  691. }
  692. var (
  693. config *cliconfig.AuthConfig
  694. authEncoded = r.Header.Get("X-Registry-Auth")
  695. headers = map[string][]string{}
  696. )
  697. if authEncoded != "" {
  698. authJSON := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authEncoded))
  699. if err := json.NewDecoder(authJSON).Decode(&config); err != nil {
  700. // for a search it is not an error if no auth was given
  701. // to increase compatibility with the existing api it is defaulting to be empty
  702. config = &cliconfig.AuthConfig{}
  703. }
  704. }
  705. for k, v := range r.Header {
  706. if strings.HasPrefix(k, "X-Meta-") {
  707. headers[k] = v
  708. }
  709. }
  710. query, err := s.daemon.RegistryService.Search(r.Form.Get("term"), config, headers)
  711. if err != nil {
  712. return err
  713. }
  714. return writeJSON(w, http.StatusOK, query.Results)
  715. }
  716. func (s *Server) postImagesPush(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  717. if vars == nil {
  718. return fmt.Errorf("Missing parameter")
  719. }
  720. metaHeaders := map[string][]string{}
  721. for k, v := range r.Header {
  722. if strings.HasPrefix(k, "X-Meta-") {
  723. metaHeaders[k] = v
  724. }
  725. }
  726. if err := parseForm(r); err != nil {
  727. return err
  728. }
  729. authConfig := &cliconfig.AuthConfig{}
  730. authEncoded := r.Header.Get("X-Registry-Auth")
  731. if authEncoded != "" {
  732. // the new format is to handle the authConfig as a header
  733. authJSON := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authEncoded))
  734. if err := json.NewDecoder(authJSON).Decode(authConfig); err != nil {
  735. // to increase compatibility to existing api it is defaulting to be empty
  736. authConfig = &cliconfig.AuthConfig{}
  737. }
  738. } else {
  739. // the old format is supported for compatibility if there was no authConfig header
  740. if err := json.NewDecoder(r.Body).Decode(authConfig); err != nil {
  741. return fmt.Errorf("Bad parameters and missing X-Registry-Auth: %v", err)
  742. }
  743. }
  744. name := vars["name"]
  745. output := ioutils.NewWriteFlusher(w)
  746. imagePushConfig := &graph.ImagePushConfig{
  747. MetaHeaders: metaHeaders,
  748. AuthConfig: authConfig,
  749. Tag: r.Form.Get("tag"),
  750. OutStream: output,
  751. }
  752. w.Header().Set("Content-Type", "application/json")
  753. if err := s.daemon.Repositories().Push(name, imagePushConfig); err != nil {
  754. if !output.Flushed() {
  755. return err
  756. }
  757. sf := streamformatter.NewJSONStreamFormatter()
  758. output.Write(sf.FormatError(err))
  759. }
  760. return nil
  761. }
  762. func (s *Server) getImagesGet(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  763. if vars == nil {
  764. return fmt.Errorf("Missing parameter")
  765. }
  766. if err := parseForm(r); err != nil {
  767. return err
  768. }
  769. w.Header().Set("Content-Type", "application/x-tar")
  770. output := ioutils.NewWriteFlusher(w)
  771. var names []string
  772. if name, ok := vars["name"]; ok {
  773. names = []string{name}
  774. } else {
  775. names = r.Form["names"]
  776. }
  777. if err := s.daemon.Repositories().ImageExport(names, output); err != nil {
  778. if !output.Flushed() {
  779. return err
  780. }
  781. sf := streamformatter.NewJSONStreamFormatter()
  782. output.Write(sf.FormatError(err))
  783. }
  784. return nil
  785. }
  786. func (s *Server) postImagesLoad(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  787. return s.daemon.Repositories().Load(r.Body, w)
  788. }
  789. func (s *Server) postContainersCreate(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 err := checkForJSON(r); err != nil {
  794. return err
  795. }
  796. var (
  797. warnings []string
  798. name = r.Form.Get("name")
  799. )
  800. config, hostConfig, err := runconfig.DecodeContainerConfig(r.Body)
  801. if err != nil {
  802. return err
  803. }
  804. adjustCPUShares(version, hostConfig)
  805. containerID, warnings, err := s.daemon.ContainerCreate(name, config, hostConfig)
  806. if err != nil {
  807. return err
  808. }
  809. return writeJSON(w, http.StatusCreated, &types.ContainerCreateResponse{
  810. ID: containerID,
  811. Warnings: warnings,
  812. })
  813. }
  814. func (s *Server) postContainersRestart(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  815. if err := parseForm(r); err != nil {
  816. return err
  817. }
  818. if vars == nil {
  819. return fmt.Errorf("Missing parameter")
  820. }
  821. timeout, _ := strconv.Atoi(r.Form.Get("t"))
  822. if err := s.daemon.ContainerRestart(vars["name"], timeout); err != nil {
  823. return err
  824. }
  825. w.WriteHeader(http.StatusNoContent)
  826. return nil
  827. }
  828. func (s *Server) postContainerRename(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  829. if err := parseForm(r); err != nil {
  830. return err
  831. }
  832. if vars == nil {
  833. return fmt.Errorf("Missing parameter")
  834. }
  835. name := vars["name"]
  836. newName := r.Form.Get("name")
  837. if err := s.daemon.ContainerRename(name, newName); err != nil {
  838. return err
  839. }
  840. w.WriteHeader(http.StatusNoContent)
  841. return nil
  842. }
  843. func (s *Server) deleteContainers(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  844. if err := parseForm(r); err != nil {
  845. return err
  846. }
  847. if vars == nil {
  848. return fmt.Errorf("Missing parameter")
  849. }
  850. name := vars["name"]
  851. config := &daemon.ContainerRmConfig{
  852. ForceRemove: boolValue(r, "force"),
  853. RemoveVolume: boolValue(r, "v"),
  854. RemoveLink: boolValue(r, "link"),
  855. }
  856. if err := s.daemon.ContainerRm(name, config); err != nil {
  857. // Force a 404 for the empty string
  858. if strings.Contains(strings.ToLower(err.Error()), "prefix can't be empty") {
  859. return fmt.Errorf("no such id: \"\"")
  860. }
  861. return err
  862. }
  863. w.WriteHeader(http.StatusNoContent)
  864. return nil
  865. }
  866. func (s *Server) deleteImages(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  867. if err := parseForm(r); err != nil {
  868. return err
  869. }
  870. if vars == nil {
  871. return fmt.Errorf("Missing parameter")
  872. }
  873. name := vars["name"]
  874. force := boolValue(r, "force")
  875. noprune := boolValue(r, "noprune")
  876. list, err := s.daemon.ImageDelete(name, force, noprune)
  877. if err != nil {
  878. return err
  879. }
  880. return writeJSON(w, http.StatusOK, list)
  881. }
  882. func (s *Server) postContainersStart(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  883. if vars == nil {
  884. return fmt.Errorf("Missing parameter")
  885. }
  886. // If contentLength is -1, we can assumed chunked encoding
  887. // or more technically that the length is unknown
  888. // https://golang.org/src/pkg/net/http/request.go#L139
  889. // net/http otherwise seems to swallow any headers related to chunked encoding
  890. // including r.TransferEncoding
  891. // allow a nil body for backwards compatibility
  892. var hostConfig *runconfig.HostConfig
  893. if r.Body != nil && (r.ContentLength > 0 || r.ContentLength == -1) {
  894. if err := checkForJSON(r); err != nil {
  895. return err
  896. }
  897. c, err := runconfig.DecodeHostConfig(r.Body)
  898. if err != nil {
  899. return err
  900. }
  901. hostConfig = c
  902. }
  903. if err := s.daemon.ContainerStart(vars["name"], hostConfig); err != nil {
  904. if err.Error() == "Container already started" {
  905. w.WriteHeader(http.StatusNotModified)
  906. return nil
  907. }
  908. return err
  909. }
  910. w.WriteHeader(http.StatusNoContent)
  911. return nil
  912. }
  913. func (s *Server) postContainersStop(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  914. if err := parseForm(r); err != nil {
  915. return err
  916. }
  917. if vars == nil {
  918. return fmt.Errorf("Missing parameter")
  919. }
  920. seconds, _ := strconv.Atoi(r.Form.Get("t"))
  921. if err := s.daemon.ContainerStop(vars["name"], seconds); err != nil {
  922. if err.Error() == "Container already stopped" {
  923. w.WriteHeader(http.StatusNotModified)
  924. return nil
  925. }
  926. return err
  927. }
  928. w.WriteHeader(http.StatusNoContent)
  929. return nil
  930. }
  931. func (s *Server) postContainersWait(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  932. if vars == nil {
  933. return fmt.Errorf("Missing parameter")
  934. }
  935. status, err := s.daemon.ContainerWait(vars["name"], -1*time.Second)
  936. if err != nil {
  937. return err
  938. }
  939. return writeJSON(w, http.StatusOK, &types.ContainerWaitResponse{
  940. StatusCode: status,
  941. })
  942. }
  943. func (s *Server) postContainersResize(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  944. if err := parseForm(r); err != nil {
  945. return err
  946. }
  947. if vars == nil {
  948. return fmt.Errorf("Missing parameter")
  949. }
  950. height, err := strconv.Atoi(r.Form.Get("h"))
  951. if err != nil {
  952. return err
  953. }
  954. width, err := strconv.Atoi(r.Form.Get("w"))
  955. if err != nil {
  956. return err
  957. }
  958. return s.daemon.ContainerResize(vars["name"], height, width)
  959. }
  960. func (s *Server) postContainersAttach(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  961. if err := parseForm(r); err != nil {
  962. return err
  963. }
  964. if vars == nil {
  965. return fmt.Errorf("Missing parameter")
  966. }
  967. cont, err := s.daemon.Get(vars["name"])
  968. if err != nil {
  969. return err
  970. }
  971. inStream, outStream, err := hijackServer(w)
  972. if err != nil {
  973. return err
  974. }
  975. defer closeStreams(inStream, outStream)
  976. if _, ok := r.Header["Upgrade"]; ok {
  977. 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")
  978. } else {
  979. fmt.Fprintf(outStream, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n")
  980. }
  981. attachWithLogsConfig := &daemon.ContainerAttachWithLogsConfig{
  982. InStream: inStream,
  983. OutStream: outStream,
  984. UseStdin: boolValue(r, "stdin"),
  985. UseStdout: boolValue(r, "stdout"),
  986. UseStderr: boolValue(r, "stderr"),
  987. Logs: boolValue(r, "logs"),
  988. Stream: boolValue(r, "stream"),
  989. }
  990. if err := s.daemon.ContainerAttachWithLogs(cont, attachWithLogsConfig); err != nil {
  991. fmt.Fprintf(outStream, "Error attaching: %s\n", err)
  992. }
  993. return nil
  994. }
  995. func (s *Server) wsContainersAttach(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  996. if err := parseForm(r); err != nil {
  997. return err
  998. }
  999. if vars == nil {
  1000. return fmt.Errorf("Missing parameter")
  1001. }
  1002. cont, err := s.daemon.Get(vars["name"])
  1003. if err != nil {
  1004. return err
  1005. }
  1006. h := websocket.Handler(func(ws *websocket.Conn) {
  1007. defer ws.Close()
  1008. wsAttachWithLogsConfig := &daemon.ContainerWsAttachWithLogsConfig{
  1009. InStream: ws,
  1010. OutStream: ws,
  1011. ErrStream: ws,
  1012. Logs: boolValue(r, "logs"),
  1013. Stream: boolValue(r, "stream"),
  1014. }
  1015. if err := s.daemon.ContainerWsAttachWithLogs(cont, wsAttachWithLogsConfig); err != nil {
  1016. logrus.Errorf("Error attaching websocket: %s", err)
  1017. }
  1018. })
  1019. h.ServeHTTP(w, r)
  1020. return nil
  1021. }
  1022. func (s *Server) getContainersByName(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1023. if vars == nil {
  1024. return fmt.Errorf("Missing parameter")
  1025. }
  1026. if version.LessThan("1.20") && runtime.GOOS != "windows" {
  1027. return getContainersByNameDownlevel(w, s, vars["name"])
  1028. }
  1029. containerJSON, err := s.daemon.ContainerInspect(vars["name"])
  1030. if err != nil {
  1031. return err
  1032. }
  1033. return writeJSON(w, http.StatusOK, containerJSON)
  1034. }
  1035. func (s *Server) getExecByID(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1036. if vars == nil {
  1037. return fmt.Errorf("Missing parameter 'id'")
  1038. }
  1039. eConfig, err := s.daemon.ContainerExecInspect(vars["id"])
  1040. if err != nil {
  1041. return err
  1042. }
  1043. return writeJSON(w, http.StatusOK, eConfig)
  1044. }
  1045. func (s *Server) getImagesByName(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1046. if vars == nil {
  1047. return fmt.Errorf("Missing parameter")
  1048. }
  1049. imageInspect, err := s.daemon.Repositories().Lookup(vars["name"])
  1050. if err != nil {
  1051. return err
  1052. }
  1053. return writeJSON(w, http.StatusOK, imageInspect)
  1054. }
  1055. func (s *Server) postBuild(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1056. var (
  1057. authConfigs = map[string]cliconfig.AuthConfig{}
  1058. authConfigsEncoded = r.Header.Get("X-Registry-Config")
  1059. buildConfig = builder.NewBuildConfig()
  1060. )
  1061. if authConfigsEncoded != "" {
  1062. authConfigsJSON := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authConfigsEncoded))
  1063. if err := json.NewDecoder(authConfigsJSON).Decode(&authConfigs); err != nil {
  1064. // for a pull it is not an error if no auth was given
  1065. // to increase compatibility with the existing api it is defaulting
  1066. // to be empty.
  1067. }
  1068. }
  1069. w.Header().Set("Content-Type", "application/json")
  1070. if boolValue(r, "forcerm") && version.GreaterThanOrEqualTo("1.12") {
  1071. buildConfig.Remove = true
  1072. } else if r.FormValue("rm") == "" && version.GreaterThanOrEqualTo("1.12") {
  1073. buildConfig.Remove = true
  1074. } else {
  1075. buildConfig.Remove = boolValue(r, "rm")
  1076. }
  1077. if boolValue(r, "pull") && version.GreaterThanOrEqualTo("1.16") {
  1078. buildConfig.Pull = true
  1079. }
  1080. output := ioutils.NewWriteFlusher(w)
  1081. buildConfig.Stdout = output
  1082. buildConfig.Context = r.Body
  1083. buildConfig.RemoteURL = r.FormValue("remote")
  1084. buildConfig.DockerfileName = r.FormValue("dockerfile")
  1085. buildConfig.RepoName = r.FormValue("t")
  1086. buildConfig.SuppressOutput = boolValue(r, "q")
  1087. buildConfig.NoCache = boolValue(r, "nocache")
  1088. buildConfig.ForceRemove = boolValue(r, "forcerm")
  1089. buildConfig.AuthConfigs = authConfigs
  1090. buildConfig.MemorySwap = int64ValueOrZero(r, "memswap")
  1091. buildConfig.Memory = int64ValueOrZero(r, "memory")
  1092. buildConfig.CPUShares = int64ValueOrZero(r, "cpushares")
  1093. buildConfig.CPUPeriod = int64ValueOrZero(r, "cpuperiod")
  1094. buildConfig.CPUQuota = int64ValueOrZero(r, "cpuquota")
  1095. buildConfig.CPUSetCpus = r.FormValue("cpusetcpus")
  1096. buildConfig.CPUSetMems = r.FormValue("cpusetmems")
  1097. buildConfig.CgroupParent = r.FormValue("cgroupparent")
  1098. var buildUlimits = []*ulimit.Ulimit{}
  1099. ulimitsJSON := r.FormValue("ulimits")
  1100. if ulimitsJSON != "" {
  1101. if err := json.NewDecoder(strings.NewReader(ulimitsJSON)).Decode(&buildUlimits); err != nil {
  1102. return err
  1103. }
  1104. buildConfig.Ulimits = buildUlimits
  1105. }
  1106. // Job cancellation. Note: not all job types support this.
  1107. if closeNotifier, ok := w.(http.CloseNotifier); ok {
  1108. finished := make(chan struct{})
  1109. defer close(finished)
  1110. go func() {
  1111. select {
  1112. case <-finished:
  1113. case <-closeNotifier.CloseNotify():
  1114. logrus.Infof("Client disconnected, cancelling job: build")
  1115. buildConfig.Cancel()
  1116. }
  1117. }()
  1118. }
  1119. if err := builder.Build(s.daemon, buildConfig); err != nil {
  1120. // Do not write the error in the http output if it's still empty.
  1121. // This prevents from writing a 200(OK) when there is an interal error.
  1122. if !output.Flushed() {
  1123. return err
  1124. }
  1125. sf := streamformatter.NewJSONStreamFormatter()
  1126. w.Write(sf.FormatError(err))
  1127. }
  1128. return nil
  1129. }
  1130. // postContainersCopy is deprecated in favor of getContainersArchivePath.
  1131. func (s *Server) postContainersCopy(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1132. if vars == nil {
  1133. return fmt.Errorf("Missing parameter")
  1134. }
  1135. if err := checkForJSON(r); err != nil {
  1136. return err
  1137. }
  1138. cfg := types.CopyConfig{}
  1139. if err := json.NewDecoder(r.Body).Decode(&cfg); err != nil {
  1140. return err
  1141. }
  1142. if cfg.Resource == "" {
  1143. return fmt.Errorf("Path cannot be empty")
  1144. }
  1145. data, err := s.daemon.ContainerCopy(vars["name"], cfg.Resource)
  1146. if err != nil {
  1147. if strings.Contains(strings.ToLower(err.Error()), "no such id") {
  1148. w.WriteHeader(http.StatusNotFound)
  1149. return nil
  1150. }
  1151. if os.IsNotExist(err) {
  1152. return fmt.Errorf("Could not find the file %s in container %s", cfg.Resource, vars["name"])
  1153. }
  1154. return err
  1155. }
  1156. defer data.Close()
  1157. w.Header().Set("Content-Type", "application/x-tar")
  1158. if _, err := io.Copy(w, data); err != nil {
  1159. return err
  1160. }
  1161. return nil
  1162. }
  1163. // // Encode the stat to JSON, base64 encode, and place in a header.
  1164. func setContainerPathStatHeader(stat *types.ContainerPathStat, header http.Header) error {
  1165. statJSON, err := json.Marshal(stat)
  1166. if err != nil {
  1167. return err
  1168. }
  1169. header.Set(
  1170. "X-Docker-Container-Path-Stat",
  1171. base64.StdEncoding.EncodeToString(statJSON),
  1172. )
  1173. return nil
  1174. }
  1175. func (s *Server) headContainersArchive(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1176. v, err := archiveFormValues(r, vars)
  1177. if err != nil {
  1178. return err
  1179. }
  1180. stat, err := s.daemon.ContainerStatPath(v.name, v.path)
  1181. if err != nil {
  1182. return err
  1183. }
  1184. return setContainerPathStatHeader(stat, w.Header())
  1185. }
  1186. func (s *Server) getContainersArchive(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1187. v, err := archiveFormValues(r, vars)
  1188. if err != nil {
  1189. return err
  1190. }
  1191. tarArchive, stat, err := s.daemon.ContainerArchivePath(v.name, v.path)
  1192. if err != nil {
  1193. return err
  1194. }
  1195. defer tarArchive.Close()
  1196. if err := setContainerPathStatHeader(stat, w.Header()); err != nil {
  1197. return err
  1198. }
  1199. w.Header().Set("Content-Type", "application/x-tar")
  1200. _, err = io.Copy(w, tarArchive)
  1201. return err
  1202. }
  1203. func (s *Server) putContainersArchive(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1204. v, err := archiveFormValues(r, vars)
  1205. if err != nil {
  1206. return err
  1207. }
  1208. noOverwriteDirNonDir := boolValue(r, "noOverwriteDirNonDir")
  1209. return s.daemon.ContainerExtractToDir(v.name, v.path, noOverwriteDirNonDir, r.Body)
  1210. }
  1211. func (s *Server) postContainerExecCreate(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1212. if err := parseForm(r); err != nil {
  1213. return err
  1214. }
  1215. if err := checkForJSON(r); err != nil {
  1216. return err
  1217. }
  1218. name := vars["name"]
  1219. execConfig := &runconfig.ExecConfig{}
  1220. if err := json.NewDecoder(r.Body).Decode(execConfig); err != nil {
  1221. return err
  1222. }
  1223. execConfig.Container = name
  1224. if len(execConfig.Cmd) == 0 {
  1225. return fmt.Errorf("No exec command specified")
  1226. }
  1227. // Register an instance of Exec in container.
  1228. id, err := s.daemon.ContainerExecCreate(execConfig)
  1229. if err != nil {
  1230. logrus.Errorf("Error setting up exec command in container %s: %s", name, err)
  1231. return err
  1232. }
  1233. return writeJSON(w, http.StatusCreated, &types.ContainerExecCreateResponse{
  1234. ID: id,
  1235. })
  1236. }
  1237. // TODO(vishh): Refactor the code to avoid having to specify stream config as part of both create and start.
  1238. func (s *Server) postContainerExecStart(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1239. if err := parseForm(r); err != nil {
  1240. return err
  1241. }
  1242. var (
  1243. execName = vars["name"]
  1244. stdin io.ReadCloser
  1245. stdout io.Writer
  1246. stderr io.Writer
  1247. )
  1248. execStartCheck := &types.ExecStartCheck{}
  1249. if err := json.NewDecoder(r.Body).Decode(execStartCheck); err != nil {
  1250. return err
  1251. }
  1252. if !execStartCheck.Detach {
  1253. // Setting up the streaming http interface.
  1254. inStream, outStream, err := hijackServer(w)
  1255. if err != nil {
  1256. return err
  1257. }
  1258. defer closeStreams(inStream, outStream)
  1259. var errStream io.Writer
  1260. if _, ok := r.Header["Upgrade"]; ok {
  1261. 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")
  1262. } else {
  1263. fmt.Fprintf(outStream, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n")
  1264. }
  1265. if !execStartCheck.Tty {
  1266. errStream = stdcopy.NewStdWriter(outStream, stdcopy.Stderr)
  1267. outStream = stdcopy.NewStdWriter(outStream, stdcopy.Stdout)
  1268. }
  1269. stdin = inStream
  1270. stdout = outStream
  1271. stderr = errStream
  1272. }
  1273. // Now run the user process in container.
  1274. if err := s.daemon.ContainerExecStart(execName, stdin, stdout, stderr); err != nil {
  1275. logrus.Errorf("Error starting exec command in container %s: %s", execName, err)
  1276. return err
  1277. }
  1278. w.WriteHeader(http.StatusNoContent)
  1279. return nil
  1280. }
  1281. func (s *Server) postContainerExecResize(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1282. if err := parseForm(r); err != nil {
  1283. return err
  1284. }
  1285. if vars == nil {
  1286. return fmt.Errorf("Missing parameter")
  1287. }
  1288. height, err := strconv.Atoi(r.Form.Get("h"))
  1289. if err != nil {
  1290. return err
  1291. }
  1292. width, err := strconv.Atoi(r.Form.Get("w"))
  1293. if err != nil {
  1294. return err
  1295. }
  1296. return s.daemon.ContainerExecResize(vars["name"], height, width)
  1297. }
  1298. func (s *Server) optionsHandler(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1299. w.WriteHeader(http.StatusOK)
  1300. return nil
  1301. }
  1302. func writeCorsHeaders(w http.ResponseWriter, r *http.Request, corsHeaders string) {
  1303. logrus.Debugf("CORS header is enabled and set to: %s", corsHeaders)
  1304. w.Header().Add("Access-Control-Allow-Origin", corsHeaders)
  1305. w.Header().Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, X-Registry-Auth")
  1306. w.Header().Add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS")
  1307. }
  1308. func (s *Server) ping(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  1309. _, err := w.Write([]byte{'O', 'K'})
  1310. return err
  1311. }
  1312. func (s *Server) initTCPSocket(addr string) (l net.Listener, err error) {
  1313. if s.cfg.TLSConfig == nil || s.cfg.TLSConfig.ClientAuth != tls.RequireAndVerifyClientCert {
  1314. logrus.Warn("/!\\ DON'T BIND ON ANY IP ADDRESS WITHOUT setting -tlsverify IF YOU DON'T KNOW WHAT YOU'RE DOING /!\\")
  1315. }
  1316. if l, err = sockets.NewTCPSocket(addr, s.cfg.TLSConfig, s.start); err != nil {
  1317. return nil, err
  1318. }
  1319. if err := allocateDaemonPort(addr); err != nil {
  1320. return nil, err
  1321. }
  1322. return
  1323. }
  1324. func makeHTTPHandler(logging bool, localMethod string, localRoute string, handlerFunc HTTPAPIFunc, corsHeaders string, dockerVersion version.Version) http.HandlerFunc {
  1325. return func(w http.ResponseWriter, r *http.Request) {
  1326. // log the request
  1327. logrus.Debugf("Calling %s %s", localMethod, localRoute)
  1328. if logging {
  1329. logrus.Infof("%s %s", r.Method, r.RequestURI)
  1330. }
  1331. if strings.Contains(r.Header.Get("User-Agent"), "Docker-Client/") {
  1332. userAgent := strings.Split(r.Header.Get("User-Agent"), "/")
  1333. // v1.20 onwards includes the GOOS of the client after the version
  1334. // such as Docker/1.7.0 (linux)
  1335. if len(userAgent) == 2 && strings.Contains(userAgent[1], " ") {
  1336. userAgent[1] = strings.Split(userAgent[1], " ")[0]
  1337. }
  1338. if len(userAgent) == 2 && !dockerVersion.Equal(version.Version(userAgent[1])) {
  1339. logrus.Debugf("Warning: client and server don't have the same version (client: %s, server: %s)", userAgent[1], dockerVersion)
  1340. }
  1341. }
  1342. version := version.Version(mux.Vars(r)["version"])
  1343. if version == "" {
  1344. version = api.Version
  1345. }
  1346. if corsHeaders != "" {
  1347. writeCorsHeaders(w, r, corsHeaders)
  1348. }
  1349. if version.GreaterThan(api.Version) {
  1350. http.Error(w, fmt.Errorf("client is newer than server (client API version: %s, server API version: %s)", version, api.Version).Error(), http.StatusBadRequest)
  1351. return
  1352. }
  1353. if version.LessThan(api.MinVersion) {
  1354. 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)
  1355. return
  1356. }
  1357. w.Header().Set("Server", "Docker/"+dockerversion.VERSION+" ("+runtime.GOOS+")")
  1358. if err := handlerFunc(version, w, r, mux.Vars(r)); err != nil {
  1359. logrus.Errorf("Handler for %s %s returned error: %s", localMethod, localRoute, err)
  1360. httpError(w, err)
  1361. }
  1362. }
  1363. }
  1364. // we keep enableCors just for legacy usage, need to be removed in the future
  1365. func createRouter(s *Server) *mux.Router {
  1366. r := mux.NewRouter()
  1367. if os.Getenv("DEBUG") != "" {
  1368. profilerSetup(r, "/debug/")
  1369. }
  1370. m := map[string]map[string]HTTPAPIFunc{
  1371. "HEAD": {
  1372. "/containers/{name:.*}/archive": s.headContainersArchive,
  1373. },
  1374. "GET": {
  1375. "/_ping": s.ping,
  1376. "/events": s.getEvents,
  1377. "/info": s.getInfo,
  1378. "/version": s.getVersion,
  1379. "/images/json": s.getImagesJSON,
  1380. "/images/search": s.getImagesSearch,
  1381. "/images/get": s.getImagesGet,
  1382. "/images/{name:.*}/get": s.getImagesGet,
  1383. "/images/{name:.*}/history": s.getImagesHistory,
  1384. "/images/{name:.*}/json": s.getImagesByName,
  1385. "/containers/ps": s.getContainersJSON,
  1386. "/containers/json": s.getContainersJSON,
  1387. "/containers/{name:.*}/export": s.getContainersExport,
  1388. "/containers/{name:.*}/changes": s.getContainersChanges,
  1389. "/containers/{name:.*}/json": s.getContainersByName,
  1390. "/containers/{name:.*}/top": s.getContainersTop,
  1391. "/containers/{name:.*}/logs": s.getContainersLogs,
  1392. "/containers/{name:.*}/stats": s.getContainersStats,
  1393. "/containers/{name:.*}/attach/ws": s.wsContainersAttach,
  1394. "/exec/{id:.*}/json": s.getExecByID,
  1395. "/containers/{name:.*}/archive": s.getContainersArchive,
  1396. },
  1397. "POST": {
  1398. "/auth": s.postAuth,
  1399. "/commit": s.postCommit,
  1400. "/build": s.postBuild,
  1401. "/images/create": s.postImagesCreate,
  1402. "/images/load": s.postImagesLoad,
  1403. "/images/{name:.*}/push": s.postImagesPush,
  1404. "/images/{name:.*}/tag": s.postImagesTag,
  1405. "/containers/create": s.postContainersCreate,
  1406. "/containers/{name:.*}/kill": s.postContainersKill,
  1407. "/containers/{name:.*}/pause": s.postContainersPause,
  1408. "/containers/{name:.*}/unpause": s.postContainersUnpause,
  1409. "/containers/{name:.*}/restart": s.postContainersRestart,
  1410. "/containers/{name:.*}/start": s.postContainersStart,
  1411. "/containers/{name:.*}/stop": s.postContainersStop,
  1412. "/containers/{name:.*}/wait": s.postContainersWait,
  1413. "/containers/{name:.*}/resize": s.postContainersResize,
  1414. "/containers/{name:.*}/attach": s.postContainersAttach,
  1415. "/containers/{name:.*}/copy": s.postContainersCopy,
  1416. "/containers/{name:.*}/exec": s.postContainerExecCreate,
  1417. "/exec/{name:.*}/start": s.postContainerExecStart,
  1418. "/exec/{name:.*}/resize": s.postContainerExecResize,
  1419. "/containers/{name:.*}/rename": s.postContainerRename,
  1420. },
  1421. "PUT": {
  1422. "/containers/{name:.*}/archive": s.putContainersArchive,
  1423. },
  1424. "DELETE": {
  1425. "/containers/{name:.*}": s.deleteContainers,
  1426. "/images/{name:.*}": s.deleteImages,
  1427. },
  1428. "OPTIONS": {
  1429. "": s.optionsHandler,
  1430. },
  1431. }
  1432. // If "api-cors-header" is not given, but "api-enable-cors" is true, we set cors to "*"
  1433. // otherwise, all head values will be passed to HTTP handler
  1434. corsHeaders := s.cfg.CorsHeaders
  1435. if corsHeaders == "" && s.cfg.EnableCors {
  1436. corsHeaders = "*"
  1437. }
  1438. for method, routes := range m {
  1439. for route, fct := range routes {
  1440. logrus.Debugf("Registering %s, %s", method, route)
  1441. // NOTE: scope issue, make sure the variables are local and won't be changed
  1442. localRoute := route
  1443. localFct := fct
  1444. localMethod := method
  1445. // build the handler function
  1446. f := makeHTTPHandler(s.cfg.Logging, localMethod, localRoute, localFct, corsHeaders, version.Version(s.cfg.Version))
  1447. // add the new route
  1448. if localRoute == "" {
  1449. r.Methods(localMethod).HandlerFunc(f)
  1450. } else {
  1451. r.Path("/v{version:[0-9.]+}" + localRoute).Methods(localMethod).HandlerFunc(f)
  1452. r.Path(localRoute).Methods(localMethod).HandlerFunc(f)
  1453. }
  1454. }
  1455. }
  1456. return r
  1457. }