server.go 44 KB

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