server.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. package server
  2. import (
  3. "crypto/tls"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "net"
  8. "net/http"
  9. "os"
  10. "strings"
  11. "github.com/gorilla/mux"
  12. "github.com/Sirupsen/logrus"
  13. "github.com/docker/distribution/registry/api/errcode"
  14. "github.com/docker/docker/api"
  15. "github.com/docker/docker/context"
  16. "github.com/docker/docker/daemon"
  17. "github.com/docker/docker/pkg/sockets"
  18. "github.com/docker/docker/pkg/stringid"
  19. "github.com/docker/docker/utils"
  20. )
  21. // Config provides the configuration for the API server
  22. type Config struct {
  23. Logging bool
  24. EnableCors bool
  25. CorsHeaders string
  26. Version string
  27. SocketGroup string
  28. TLSConfig *tls.Config
  29. }
  30. // Server contains instance details for the server
  31. type Server struct {
  32. daemon *daemon.Daemon
  33. cfg *Config
  34. router *mux.Router
  35. start chan struct{}
  36. servers []serverCloser
  37. }
  38. // New returns a new instance of the server based on the specified configuration.
  39. func New(ctx context.Context, cfg *Config) *Server {
  40. srv := &Server{
  41. cfg: cfg,
  42. start: make(chan struct{}),
  43. }
  44. srv.router = createRouter(ctx, srv)
  45. return srv
  46. }
  47. // Close closes servers and thus stop receiving requests
  48. func (s *Server) Close() {
  49. for _, srv := range s.servers {
  50. if err := srv.Close(); err != nil {
  51. logrus.Error(err)
  52. }
  53. }
  54. }
  55. type serverCloser interface {
  56. Serve() error
  57. Close() error
  58. }
  59. // ServeAPI loops through all of the protocols sent in to docker and spawns
  60. // off a go routine to setup a serving http.Server for each.
  61. func (s *Server) ServeAPI(protoAddrs []string) error {
  62. var chErrors = make(chan error, len(protoAddrs))
  63. for _, protoAddr := range protoAddrs {
  64. protoAddrParts := strings.SplitN(protoAddr, "://", 2)
  65. if len(protoAddrParts) != 2 {
  66. return fmt.Errorf("bad format, expected PROTO://ADDR")
  67. }
  68. srv, err := s.newServer(protoAddrParts[0], protoAddrParts[1])
  69. if err != nil {
  70. return err
  71. }
  72. s.servers = append(s.servers, srv...)
  73. for _, s := range srv {
  74. logrus.Infof("Listening for HTTP on %s (%s)", protoAddrParts[0], protoAddrParts[1])
  75. go func(s serverCloser) {
  76. if err := s.Serve(); err != nil && strings.Contains(err.Error(), "use of closed network connection") {
  77. err = nil
  78. }
  79. chErrors <- err
  80. }(s)
  81. }
  82. }
  83. for i := 0; i < len(protoAddrs); i++ {
  84. err := <-chErrors
  85. if err != nil {
  86. return err
  87. }
  88. }
  89. return nil
  90. }
  91. // HTTPServer contains an instance of http server and the listener.
  92. // srv *http.Server, contains configuration to create a http server and a mux router with all api end points.
  93. // l net.Listener, is a TCP or Socket listener that dispatches incoming request to the router.
  94. type HTTPServer struct {
  95. srv *http.Server
  96. l net.Listener
  97. }
  98. // Serve starts listening for inbound requests.
  99. func (s *HTTPServer) Serve() error {
  100. return s.srv.Serve(s.l)
  101. }
  102. // Close closes the HTTPServer from listening for the inbound requests.
  103. func (s *HTTPServer) Close() error {
  104. return s.l.Close()
  105. }
  106. // HTTPAPIFunc is an adapter to allow the use of ordinary functions as Docker API endpoints.
  107. // Any function that has the appropriate signature can be register as a API endpoint (e.g. getVersion).
  108. type HTTPAPIFunc func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error
  109. func hijackServer(w http.ResponseWriter) (io.ReadCloser, io.Writer, error) {
  110. conn, _, err := w.(http.Hijacker).Hijack()
  111. if err != nil {
  112. return nil, nil, err
  113. }
  114. // Flush the options to make sure the client sets the raw mode
  115. conn.Write([]byte{})
  116. return conn, conn, nil
  117. }
  118. func closeStreams(streams ...interface{}) {
  119. for _, stream := range streams {
  120. if tcpc, ok := stream.(interface {
  121. CloseWrite() error
  122. }); ok {
  123. tcpc.CloseWrite()
  124. } else if closer, ok := stream.(io.Closer); ok {
  125. closer.Close()
  126. }
  127. }
  128. }
  129. // checkForJSON makes sure that the request's Content-Type is application/json.
  130. func checkForJSON(r *http.Request) error {
  131. ct := r.Header.Get("Content-Type")
  132. // No Content-Type header is ok as long as there's no Body
  133. if ct == "" {
  134. if r.Body == nil || r.ContentLength == 0 {
  135. return nil
  136. }
  137. }
  138. // Otherwise it better be json
  139. if api.MatchesContentType(ct, "application/json") {
  140. return nil
  141. }
  142. return fmt.Errorf("Content-Type specified (%s) must be 'application/json'", ct)
  143. }
  144. //If we don't do this, POST method without Content-type (even with empty body) will fail
  145. func parseForm(r *http.Request) error {
  146. if r == nil {
  147. return nil
  148. }
  149. if err := r.ParseForm(); err != nil && !strings.HasPrefix(err.Error(), "mime:") {
  150. return err
  151. }
  152. return nil
  153. }
  154. func parseMultipartForm(r *http.Request) error {
  155. if err := r.ParseMultipartForm(4096); err != nil && !strings.HasPrefix(err.Error(), "mime:") {
  156. return err
  157. }
  158. return nil
  159. }
  160. func httpError(w http.ResponseWriter, err error) {
  161. if err == nil || w == nil {
  162. logrus.WithFields(logrus.Fields{"error": err, "writer": w}).Error("unexpected HTTP error handling")
  163. return
  164. }
  165. statusCode := http.StatusInternalServerError
  166. errMsg := err.Error()
  167. // Based on the type of error we get we need to process things
  168. // slightly differently to extract the error message.
  169. // In the 'errcode.*' cases there are two different type of
  170. // error that could be returned. errocode.ErrorCode is the base
  171. // type of error object - it is just an 'int' that can then be
  172. // used as the look-up key to find the message. errorcode.Error
  173. // extends errorcode.Error by adding error-instance specific
  174. // data, like 'details' or variable strings to be inserted into
  175. // the message.
  176. //
  177. // Ideally, we should just be able to call err.Error() for all
  178. // cases but the errcode package doesn't support that yet.
  179. //
  180. // Additionally, in both errcode cases, there might be an http
  181. // status code associated with it, and if so use it.
  182. switch err.(type) {
  183. case errcode.ErrorCode:
  184. daError, _ := err.(errcode.ErrorCode)
  185. statusCode = daError.Descriptor().HTTPStatusCode
  186. errMsg = daError.Message()
  187. case errcode.Error:
  188. // For reference, if you're looking for a particular error
  189. // then you can do something like :
  190. // import ( derr "github.com/docker/docker/errors" )
  191. // if daError.ErrorCode() == derr.ErrorCodeNoSuchContainer { ... }
  192. daError, _ := err.(errcode.Error)
  193. statusCode = daError.ErrorCode().Descriptor().HTTPStatusCode
  194. errMsg = daError.Message
  195. default:
  196. // This part of will be removed once we've
  197. // converted everything over to use the errcode package
  198. // FIXME: this is brittle and should not be necessary.
  199. // If we need to differentiate between different possible error types,
  200. // we should create appropriate error types with clearly defined meaning
  201. errStr := strings.ToLower(err.Error())
  202. for keyword, status := range map[string]int{
  203. "not found": http.StatusNotFound,
  204. "no such": http.StatusNotFound,
  205. "bad parameter": http.StatusBadRequest,
  206. "conflict": http.StatusConflict,
  207. "impossible": http.StatusNotAcceptable,
  208. "wrong login/password": http.StatusUnauthorized,
  209. "hasn't been activated": http.StatusForbidden,
  210. } {
  211. if strings.Contains(errStr, keyword) {
  212. statusCode = status
  213. break
  214. }
  215. }
  216. }
  217. if statusCode == 0 {
  218. statusCode = http.StatusInternalServerError
  219. }
  220. logrus.WithFields(logrus.Fields{"statusCode": statusCode, "err": utils.GetErrorMessage(err)}).Error("HTTP Error")
  221. http.Error(w, errMsg, statusCode)
  222. }
  223. // writeJSON writes the value v to the http response stream as json with standard
  224. // json encoding.
  225. func writeJSON(w http.ResponseWriter, code int, v interface{}) error {
  226. w.Header().Set("Content-Type", "application/json")
  227. w.WriteHeader(code)
  228. return json.NewEncoder(w).Encode(v)
  229. }
  230. func (s *Server) optionsHandler(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  231. w.WriteHeader(http.StatusOK)
  232. return nil
  233. }
  234. func writeCorsHeaders(w http.ResponseWriter, r *http.Request, corsHeaders string) {
  235. logrus.Debugf("CORS header is enabled and set to: %s", corsHeaders)
  236. w.Header().Add("Access-Control-Allow-Origin", corsHeaders)
  237. w.Header().Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, X-Registry-Auth")
  238. w.Header().Add("Access-Control-Allow-Methods", "HEAD, GET, POST, DELETE, PUT, OPTIONS")
  239. }
  240. func (s *Server) ping(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  241. _, err := w.Write([]byte{'O', 'K'})
  242. return err
  243. }
  244. func (s *Server) initTCPSocket(addr string) (l net.Listener, err error) {
  245. if s.cfg.TLSConfig == nil || s.cfg.TLSConfig.ClientAuth != tls.RequireAndVerifyClientCert {
  246. logrus.Warn("/!\\ DON'T BIND ON ANY IP ADDRESS WITHOUT setting -tlsverify IF YOU DON'T KNOW WHAT YOU'RE DOING /!\\")
  247. }
  248. if l, err = sockets.NewTCPSocket(addr, s.cfg.TLSConfig, s.start); err != nil {
  249. return nil, err
  250. }
  251. if err := allocateDaemonPort(addr); err != nil {
  252. return nil, err
  253. }
  254. return
  255. }
  256. func (s *Server) makeHTTPHandler(ctx context.Context, localMethod string, localRoute string, localHandler HTTPAPIFunc) http.HandlerFunc {
  257. return func(w http.ResponseWriter, r *http.Request) {
  258. // log the handler generation
  259. logrus.Debugf("Calling %s %s", localMethod, localRoute)
  260. // Define the context that we'll pass around to share info
  261. // like the docker-request-id.
  262. //
  263. // The 'context' will be used for global data that should
  264. // apply to all requests. Data that is specific to the
  265. // immediate function being called should still be passed
  266. // as 'args' on the function call.
  267. reqID := stringid.TruncateID(stringid.GenerateNonCryptoID())
  268. ctx = context.WithValue(ctx, context.RequestID, reqID)
  269. handlerFunc := s.handleWithGlobalMiddlewares(localHandler)
  270. if err := handlerFunc(ctx, w, r, mux.Vars(r)); err != nil {
  271. logrus.Errorf("Handler for %s %s returned error: %s", localMethod, localRoute, utils.GetErrorMessage(err))
  272. httpError(w, err)
  273. }
  274. }
  275. }
  276. // createRouter initializes the main router the server uses.
  277. // we keep enableCors just for legacy usage, need to be removed in the future
  278. func createRouter(ctx context.Context, s *Server) *mux.Router {
  279. r := mux.NewRouter()
  280. if os.Getenv("DEBUG") != "" {
  281. profilerSetup(r, "/debug/")
  282. }
  283. m := map[string]map[string]HTTPAPIFunc{
  284. "HEAD": {
  285. "/containers/{name:.*}/archive": s.headContainersArchive,
  286. },
  287. "GET": {
  288. "/_ping": s.ping,
  289. "/events": s.getEvents,
  290. "/info": s.getInfo,
  291. "/version": s.getVersion,
  292. "/images/json": s.getImagesJSON,
  293. "/images/search": s.getImagesSearch,
  294. "/images/get": s.getImagesGet,
  295. "/images/{name:.*}/get": s.getImagesGet,
  296. "/images/{name:.*}/history": s.getImagesHistory,
  297. "/images/{name:.*}/json": s.getImagesByName,
  298. "/containers/json": s.getContainersJSON,
  299. "/containers/{name:.*}/export": s.getContainersExport,
  300. "/containers/{name:.*}/changes": s.getContainersChanges,
  301. "/containers/{name:.*}/json": s.getContainersByName,
  302. "/containers/{name:.*}/top": s.getContainersTop,
  303. "/containers/{name:.*}/logs": s.getContainersLogs,
  304. "/containers/{name:.*}/stats": s.getContainersStats,
  305. "/containers/{name:.*}/attach/ws": s.wsContainersAttach,
  306. "/exec/{id:.*}/json": s.getExecByID,
  307. "/containers/{name:.*}/archive": s.getContainersArchive,
  308. "/volumes": s.getVolumesList,
  309. "/volumes/{name:.*}": s.getVolumeByName,
  310. },
  311. "POST": {
  312. "/auth": s.postAuth,
  313. "/commit": s.postCommit,
  314. "/build": s.postBuild,
  315. "/images/create": s.postImagesCreate,
  316. "/images/load": s.postImagesLoad,
  317. "/images/{name:.*}/push": s.postImagesPush,
  318. "/images/{name:.*}/tag": s.postImagesTag,
  319. "/containers/create": s.postContainersCreate,
  320. "/containers/{name:.*}/kill": s.postContainersKill,
  321. "/containers/{name:.*}/pause": s.postContainersPause,
  322. "/containers/{name:.*}/unpause": s.postContainersUnpause,
  323. "/containers/{name:.*}/restart": s.postContainersRestart,
  324. "/containers/{name:.*}/start": s.postContainersStart,
  325. "/containers/{name:.*}/stop": s.postContainersStop,
  326. "/containers/{name:.*}/wait": s.postContainersWait,
  327. "/containers/{name:.*}/resize": s.postContainersResize,
  328. "/containers/{name:.*}/attach": s.postContainersAttach,
  329. "/containers/{name:.*}/copy": s.postContainersCopy,
  330. "/containers/{name:.*}/exec": s.postContainerExecCreate,
  331. "/exec/{name:.*}/start": s.postContainerExecStart,
  332. "/exec/{name:.*}/resize": s.postContainerExecResize,
  333. "/containers/{name:.*}/rename": s.postContainerRename,
  334. "/volumes": s.postVolumesCreate,
  335. },
  336. "PUT": {
  337. "/containers/{name:.*}/archive": s.putContainersArchive,
  338. },
  339. "DELETE": {
  340. "/containers/{name:.*}": s.deleteContainers,
  341. "/images/{name:.*}": s.deleteImages,
  342. "/volumes/{name:.*}": s.deleteVolumes,
  343. },
  344. "OPTIONS": {
  345. "": s.optionsHandler,
  346. },
  347. }
  348. for method, routes := range m {
  349. for route, fct := range routes {
  350. logrus.Debugf("Registering %s, %s", method, route)
  351. // NOTE: scope issue, make sure the variables are local and won't be changed
  352. localRoute := route
  353. localFct := fct
  354. localMethod := method
  355. // build the handler function
  356. f := s.makeHTTPHandler(ctx, localMethod, localRoute, localFct)
  357. // add the new route
  358. if localRoute == "" {
  359. r.Methods(localMethod).HandlerFunc(f)
  360. } else {
  361. r.Path("/v{version:[0-9.]+}" + localRoute).Methods(localMethod).HandlerFunc(f)
  362. r.Path(localRoute).Methods(localMethod).HandlerFunc(f)
  363. }
  364. }
  365. }
  366. return r
  367. }