server.go 44 KB

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