Skip to content

Commit

Permalink
Merge pull request moby#16567 from calavera/context_per_request
Browse files Browse the repository at this point in the history
Define a context per request.
  • Loading branch information
Jess Frazelle committed Sep 25, 2015
2 parents 80e31df + 27c7652 commit ff92f45
Show file tree
Hide file tree
Showing 17 changed files with 82 additions and 94 deletions.
18 changes: 9 additions & 9 deletions api/server/image.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ func (s *Server) postImagesCreate(ctx context.Context, w http.ResponseWriter, r
OutStream: output,
}

err = s.daemon.Repositories(ctx).Pull(ctx, image, tag, imagePullConfig)
err = s.daemon.Repositories().Pull(ctx, image, tag, imagePullConfig)
} else { //import
if tag == "" {
repo, tag = parsers.ParseRepositoryTag(repo)
Expand All @@ -129,7 +129,7 @@ func (s *Server) postImagesCreate(ctx context.Context, w http.ResponseWriter, r
return err
}

err = s.daemon.Repositories(ctx).Import(ctx, src, repo, tag, message, r.Body, output, newConfig)
err = s.daemon.Repositories().Import(ctx, src, repo, tag, message, r.Body, output, newConfig)
}
if err != nil {
if !output.Flushed() {
Expand Down Expand Up @@ -184,7 +184,7 @@ func (s *Server) postImagesPush(ctx context.Context, w http.ResponseWriter, r *h

w.Header().Set("Content-Type", "application/json")

if err := s.daemon.Repositories(ctx).Push(ctx, name, imagePushConfig); err != nil {
if err := s.daemon.Repositories().Push(ctx, name, imagePushConfig); err != nil {
if !output.Flushed() {
return err
}
Expand Down Expand Up @@ -212,7 +212,7 @@ func (s *Server) getImagesGet(ctx context.Context, w http.ResponseWriter, r *htt
names = r.Form["names"]
}

if err := s.daemon.Repositories(ctx).ImageExport(names, output); err != nil {
if err := s.daemon.Repositories().ImageExport(names, output); err != nil {
if !output.Flushed() {
return err
}
Expand All @@ -223,7 +223,7 @@ func (s *Server) getImagesGet(ctx context.Context, w http.ResponseWriter, r *htt
}

func (s *Server) postImagesLoad(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
return s.daemon.Repositories(ctx).Load(r.Body, w)
return s.daemon.Repositories().Load(r.Body, w)
}

func (s *Server) deleteImages(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
Expand Down Expand Up @@ -256,7 +256,7 @@ func (s *Server) getImagesByName(ctx context.Context, w http.ResponseWriter, r *
return fmt.Errorf("Missing parameter")
}

imageInspect, err := s.daemon.Repositories(ctx).Lookup(vars["name"])
imageInspect, err := s.daemon.Repositories().Lookup(vars["name"])
if err != nil {
return err
}
Expand Down Expand Up @@ -364,7 +364,7 @@ func (s *Server) getImagesJSON(ctx context.Context, w http.ResponseWriter, r *ht
}

// FIXME: The filter parameter could just be a match filter
images, err := s.daemon.Repositories(ctx).Images(r.Form.Get("filters"), r.Form.Get("filter"), boolValue(r, "all"))
images, err := s.daemon.Repositories().Images(r.Form.Get("filters"), r.Form.Get("filter"), boolValue(r, "all"))
if err != nil {
return err
}
Expand All @@ -378,7 +378,7 @@ func (s *Server) getImagesHistory(ctx context.Context, w http.ResponseWriter, r
}

name := vars["name"]
history, err := s.daemon.Repositories(ctx).History(name)
history, err := s.daemon.Repositories().History(name)
if err != nil {
return err
}
Expand All @@ -398,7 +398,7 @@ func (s *Server) postImagesTag(ctx context.Context, w http.ResponseWriter, r *ht
tag := r.Form.Get("tag")
force := boolValue(r, "force")
name := vars["name"]
if err := s.daemon.Repositories(ctx).Tag(repo, tag, name, force); err != nil {
if err := s.daemon.Repositories().Tag(repo, tag, name, force); err != nil {
return err
}
s.daemon.EventsService.Log(ctx, "tag", utils.ImageReference(repo, tag), "")
Expand Down
12 changes: 7 additions & 5 deletions api/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,12 @@ type Server struct {
}

// New returns a new instance of the server based on the specified configuration.
func New(ctx context.Context, cfg *Config) *Server {
func New(cfg *Config) *Server {
srv := &Server{
cfg: cfg,
start: make(chan struct{}),
}
srv.router = createRouter(ctx, srv)
srv.router = createRouter(srv)
return srv
}

Expand Down Expand Up @@ -291,7 +291,7 @@ func (s *Server) initTCPSocket(addr string) (l net.Listener, err error) {
return
}

func (s *Server) makeHTTPHandler(ctx context.Context, localMethod string, localRoute string, localHandler HTTPAPIFunc) http.HandlerFunc {
func (s *Server) makeHTTPHandler(localMethod string, localRoute string, localHandler HTTPAPIFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// log the handler generation
logrus.Debugf("Calling %s %s", localMethod, localRoute)
Expand All @@ -303,6 +303,8 @@ func (s *Server) makeHTTPHandler(ctx context.Context, localMethod string, localR
// apply to all requests. Data that is specific to the
// immediate function being called should still be passed
// as 'args' on the function call.
ctx := context.Background()

reqID := stringid.TruncateID(stringid.GenerateNonCryptoID())
ctx = context.WithValue(ctx, context.RequestID, reqID)
handlerFunc := s.handleWithGlobalMiddlewares(localHandler)
Expand All @@ -316,7 +318,7 @@ func (s *Server) makeHTTPHandler(ctx context.Context, localMethod string, localR

// createRouter initializes the main router the server uses.
// we keep enableCors just for legacy usage, need to be removed in the future
func createRouter(ctx context.Context, s *Server) *mux.Router {
func createRouter(s *Server) *mux.Router {
r := mux.NewRouter()
if os.Getenv("DEBUG") != "" {
profilerSetup(r, "/debug/")
Expand Down Expand Up @@ -396,7 +398,7 @@ func createRouter(ctx context.Context, s *Server) *mux.Router {
localMethod := method

// build the handler function
f := s.makeHTTPHandler(ctx, localMethod, localRoute, localFct)
f := s.makeHTTPHandler(localMethod, localRoute, localFct)

// add the new route
if localRoute == "" {
Expand Down
8 changes: 2 additions & 6 deletions api/server/server_experimental_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,8 @@

package server

import (
"github.com/docker/docker/context"
)

func (s *Server) registerSubRouter(ctx context.Context) {
httpHandler := s.daemon.NetworkAPIRouter(ctx)
func (s *Server) registerSubRouter() {
httpHandler := s.daemon.NetworkAPIRouter()

subrouter := s.router.PathPrefix("/v{version:[0-9.]+}/networks").Subrouter()
subrouter.Methods("GET", "POST", "PUT", "DELETE").HandlerFunc(httpHandler)
Expand Down
6 changes: 1 addition & 5 deletions api/server/server_stub.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,5 @@

package server

import (
"github.com/docker/docker/context"
)

func (s *Server) registerSubRouter(ctx context.Context) {
func (s *Server) registerSubRouter() {
}
5 changes: 2 additions & 3 deletions api/server/server_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"net/http"
"strconv"

"github.com/docker/docker/context"
"github.com/docker/docker/daemon"
"github.com/docker/docker/pkg/sockets"
"github.com/docker/libnetwork/portallocator"
Expand Down Expand Up @@ -64,10 +63,10 @@ func (s *Server) newServer(proto, addr string) ([]serverCloser, error) {
// AcceptConnections allows clients to connect to the API server.
// Referenced Daemon is notified about this server, and waits for the
// daemon acknowledgement before the incoming connections are accepted.
func (s *Server) AcceptConnections(ctx context.Context, d *daemon.Daemon) {
func (s *Server) AcceptConnections(d *daemon.Daemon) {
// Tell the init daemon we are accepting requests
s.daemon = d
s.registerSubRouter(ctx)
s.registerSubRouter()
go systemdDaemon.SdNotify("READY=1")
// close the lock so the listeners start accepting connections
select {
Expand Down
5 changes: 2 additions & 3 deletions api/server/server_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"net"
"net/http"

"github.com/docker/docker/context"
"github.com/docker/docker/daemon"
)

Expand Down Expand Up @@ -43,9 +42,9 @@ func (s *Server) newServer(proto, addr string) ([]serverCloser, error) {
}

// AcceptConnections allows router to start listening for the incoming requests.
func (s *Server) AcceptConnections(ctx context.Context, d *daemon.Daemon) {
func (s *Server) AcceptConnections(d *daemon.Daemon) {
s.daemon = d
s.registerSubRouter(ctx)
s.registerSubRouter()
// close the lock so the listeners start accepting connections
select {
case <-s.start:
Expand Down
4 changes: 2 additions & 2 deletions builder/dispatchers.go
Original file line number Diff line number Diff line change
Expand Up @@ -209,15 +209,15 @@ func from(ctx context.Context, b *builder, args []string, attributes map[string]
return nil
}

image, err := b.Daemon.Repositories(ctx).LookupImage(name)
image, err := b.Daemon.Repositories().LookupImage(name)
if b.Pull {
image, err = b.pullImage(ctx, name)
if err != nil {
return err
}
}
if err != nil {
if b.Daemon.Graph(ctx).IsNotExist(err, name) {
if b.Daemon.Graph().IsNotExist(err, name) {
image, err = b.pullImage(ctx, name)
}

Expand Down
8 changes: 4 additions & 4 deletions builder/internals.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ func (b *builder) commit(ctx context.Context, id string, autoCmd *stringutils.St
if err != nil {
return err
}
b.Daemon.Graph(ctx).Retain(b.id, image.ID)
b.Daemon.Graph().Retain(b.id, image.ID)
b.activeImages = append(b.activeImages, image.ID)
b.image = image.ID
return nil
Expand Down Expand Up @@ -516,11 +516,11 @@ func (b *builder) pullImage(ctx context.Context, name string) (*image.Image, err
OutStream: ioutils.NopWriteCloser(b.OutOld),
}

if err := b.Daemon.Repositories(ctx).Pull(ctx, remote, tag, imagePullConfig); err != nil {
if err := b.Daemon.Repositories().Pull(ctx, remote, tag, imagePullConfig); err != nil {
return nil, err
}

image, err := b.Daemon.Repositories(ctx).LookupImage(name)
image, err := b.Daemon.Repositories().LookupImage(name)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -600,7 +600,7 @@ func (b *builder) probeCache(ctx context.Context) (bool, error) {
fmt.Fprintf(b.OutStream, " ---> Using cache\n")
logrus.Debugf("[BUILDER] Use cached version")
b.image = cache.ID
b.Daemon.Graph(ctx).Retain(b.id, cache.ID)
b.Daemon.Graph().Retain(b.id, cache.ID)
b.activeImages = append(b.activeImages, cache.ID)
return true, nil
}
Expand Down
4 changes: 2 additions & 2 deletions builder/job.go
Original file line number Diff line number Diff line change
Expand Up @@ -230,15 +230,15 @@ func Build(ctx context.Context, d *daemon.Daemon, buildConfig *Config) error {
}

defer func() {
builder.Daemon.Graph(ctx).Release(builder.id, builder.activeImages...)
builder.Daemon.Graph().Release(builder.id, builder.activeImages...)
}()

id, err := builder.Run(ctx, context)
if err != nil {
return err
}
if repoName != "" {
return d.Repositories(ctx).Tag(repoName, tag, id, true)
return d.Repositories().Tag(repoName, tag, id, true)
}
return nil
}
Expand Down
2 changes: 1 addition & 1 deletion daemon/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ func (daemon *Daemon) ContainerCreate(ctx context.Context, name string, config *

container, buildWarnings, err := daemon.Create(ctx, config, hostConfig, name)
if err != nil {
if daemon.Graph(ctx).IsNotExist(err, config.Image) {
if daemon.Graph().IsNotExist(err, config.Image) {
if strings.Contains(config.Image, "@") {
return types.ContainerCreateResponse{"", warnings}, derr.ErrorCodeNoSuchImageHash.WithArgs(config.Image)
}
Expand Down
21 changes: 11 additions & 10 deletions daemon/daemon.go
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,7 @@ func (daemon *Daemon) ensureName(container *Container) error {
return nil
}

func (daemon *Daemon) restore(ctx context.Context) error {
func (daemon *Daemon) restore() error {
type cr struct {
container *Container
registered bool
Expand Down Expand Up @@ -307,6 +307,7 @@ func (daemon *Daemon) restore(ctx context.Context) error {
}

group := sync.WaitGroup{}
ctx := context.Background()
for _, c := range containers {
group.Add(1)

Expand Down Expand Up @@ -571,7 +572,7 @@ func (daemon *Daemon) registerLink(parent, child *Container, alias string) error

// NewDaemon sets up everything for the daemon to be able to service
// requests from the webserver.
func NewDaemon(ctx context.Context, config *Config, registryService *registry.Service) (daemon *Daemon, err error) {
func NewDaemon(config *Config, registryService *registry.Service) (daemon *Daemon, err error) {
setDefaultMtu(config)

// Ensure we have compatible configuration options
Expand Down Expand Up @@ -639,7 +640,7 @@ func NewDaemon(ctx context.Context, config *Config, registryService *registry.Se
// Ensure the graph driver is shutdown at a later point
defer func() {
if err != nil {
if err := d.Shutdown(ctx); err != nil {
if err := d.Shutdown(context.Background()); err != nil {
logrus.Error(err)
}
}
Expand Down Expand Up @@ -773,7 +774,7 @@ func NewDaemon(ctx context.Context, config *Config, registryService *registry.Se

go d.execCommandGC()

if err := d.restore(ctx); err != nil {
if err := d.restore(); err != nil {
return nil, err
}

Expand All @@ -786,7 +787,7 @@ func (daemon *Daemon) Shutdown(ctx context.Context) error {
if daemon.containers != nil {
group := sync.WaitGroup{}
logrus.Debug("starting clean shutdown of all containers...")
for _, container := range daemon.List(ctx) {
for _, container := range daemon.List() {
c := container
if c.IsRunning() {
logrus.Debugf("stopping %s", c.ID)
Expand Down Expand Up @@ -961,12 +962,12 @@ func (daemon *Daemon) createRootfs(container *Container) error {
// which need direct access to daemon.graph.
// Once the tests switch to using engine and jobs, this method
// can go away.
func (daemon *Daemon) Graph(ctx context.Context) *graph.Graph {
func (daemon *Daemon) Graph() *graph.Graph {
return daemon.graph
}

// Repositories returns all repositories.
func (daemon *Daemon) Repositories(ctx context.Context) *graph.TagStore {
func (daemon *Daemon) Repositories() *graph.TagStore {
return daemon.repositories
}

Expand All @@ -980,13 +981,13 @@ func (daemon *Daemon) systemInitPath() string {

// GraphDriver returns the currently used driver for processing
// container layers.
func (daemon *Daemon) GraphDriver(ctx context.Context) graphdriver.Driver {
func (daemon *Daemon) GraphDriver() graphdriver.Driver {
return daemon.driver
}

// ExecutionDriver returns the currently used driver for creating and
// starting execs in a container.
func (daemon *Daemon) ExecutionDriver(ctx context.Context) execdriver.Driver {
func (daemon *Daemon) ExecutionDriver() execdriver.Driver {
return daemon.execDriver
}

Expand All @@ -1000,7 +1001,7 @@ func (daemon *Daemon) containerGraph() *graphdb.Database {
// returned if the parent image cannot be found.
func (daemon *Daemon) ImageGetCached(ctx context.Context, imgID string, config *runconfig.Config) (*image.Image, error) {
// Retrieve all images
images := daemon.Graph(ctx).Map()
images := daemon.Graph().Map()

// Store the tree in a map of map (map[parentId][childId])
imageMap := make(map[string]map[string]struct{})
Expand Down
6 changes: 3 additions & 3 deletions daemon/daemon_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,8 +123,8 @@ func verifyPlatformContainerSettings(ctx context.Context, daemon *Daemon, hostCo
warnings := []string{}
sysInfo := sysinfo.New(true)

if hostConfig.LxcConf.Len() > 0 && !strings.Contains(daemon.ExecutionDriver(ctx).Name(), "lxc") {
return warnings, fmt.Errorf("Cannot use --lxc-conf with execdriver: %s", daemon.ExecutionDriver(ctx).Name())
if hostConfig.LxcConf.Len() > 0 && !strings.Contains(daemon.ExecutionDriver().Name(), "lxc") {
return warnings, fmt.Errorf("Cannot use --lxc-conf with execdriver: %s", daemon.ExecutionDriver().Name())
}

// memory subsystem checks and adjustments
Expand Down Expand Up @@ -497,7 +497,7 @@ func setupInitLayer(initLayer string) error {

// NetworkAPIRouter implements a feature for server-experimental,
// directly calling into libnetwork.
func (daemon *Daemon) NetworkAPIRouter(ctx context.Context) func(w http.ResponseWriter, req *http.Request) {
func (daemon *Daemon) NetworkAPIRouter() func(w http.ResponseWriter, req *http.Request) {
return nwapi.NewHTTPHandler(daemon.netController)
}

Expand Down
Loading

0 comments on commit ff92f45

Please sign in to comment.