server.go 45 KB

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