server.go 44 KB

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