github.com/ferranbt/nomad@v0.9.3-0.20190607002617-85c449b7667c/nomad/deploymentwatcher/deployments_watcher.go (about)

     1  package deploymentwatcher
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"sync"
     7  	"time"
     8  
     9  	"golang.org/x/time/rate"
    10  
    11  	log "github.com/hashicorp/go-hclog"
    12  	memdb "github.com/hashicorp/go-memdb"
    13  
    14  	"github.com/hashicorp/nomad/nomad/state"
    15  	"github.com/hashicorp/nomad/nomad/structs"
    16  )
    17  
    18  const (
    19  	// LimitStateQueriesPerSecond is the number of state queries allowed per
    20  	// second
    21  	LimitStateQueriesPerSecond = 100.0
    22  
    23  	// CrossDeploymentUpdateBatchDuration is the duration in which allocation
    24  	// desired transition and evaluation creation updates are batched across
    25  	// all deployment watchers before committing to Raft.
    26  	CrossDeploymentUpdateBatchDuration = 250 * time.Millisecond
    27  )
    28  
    29  var (
    30  	// notEnabled is the error returned when the deployment watcher is not
    31  	// enabled
    32  	notEnabled = fmt.Errorf("deployment watcher not enabled")
    33  )
    34  
    35  // DeploymentRaftEndpoints exposes the deployment watcher to a set of functions
    36  // to apply data transforms via Raft.
    37  type DeploymentRaftEndpoints interface {
    38  	// UpsertJob is used to upsert a job
    39  	UpsertJob(job *structs.Job) (uint64, error)
    40  
    41  	// UpdateDeploymentStatus is used to make a deployment status update
    42  	// and potentially create an evaluation.
    43  	UpdateDeploymentStatus(u *structs.DeploymentStatusUpdateRequest) (uint64, error)
    44  
    45  	// UpdateDeploymentPromotion is used to promote canaries in a deployment
    46  	UpdateDeploymentPromotion(req *structs.ApplyDeploymentPromoteRequest) (uint64, error)
    47  
    48  	// UpdateDeploymentAllocHealth is used to set the health of allocations in a
    49  	// deployment
    50  	UpdateDeploymentAllocHealth(req *structs.ApplyDeploymentAllocHealthRequest) (uint64, error)
    51  
    52  	// UpdateAllocDesiredTransition is used to update the desired transition
    53  	// for allocations.
    54  	UpdateAllocDesiredTransition(req *structs.AllocUpdateDesiredTransitionRequest) (uint64, error)
    55  }
    56  
    57  // Watcher is used to watch deployments and their allocations created
    58  // by the scheduler and trigger the scheduler when allocation health
    59  // transitions.
    60  type Watcher struct {
    61  	enabled bool
    62  	logger  log.Logger
    63  
    64  	// queryLimiter is used to limit the rate of blocking queries
    65  	queryLimiter *rate.Limiter
    66  
    67  	// updateBatchDuration is the duration to batch allocation desired
    68  	// transition and eval creation across all deployment watchers
    69  	updateBatchDuration time.Duration
    70  
    71  	// raft contains the set of Raft endpoints that can be used by the
    72  	// deployments watcher
    73  	raft DeploymentRaftEndpoints
    74  
    75  	// state is the state that is watched for state changes.
    76  	state *state.StateStore
    77  
    78  	// watchers is the set of active watchers, one per deployment
    79  	watchers map[string]*deploymentWatcher
    80  
    81  	// allocUpdateBatcher is used to batch the creation of evaluations and
    82  	// allocation desired transition updates
    83  	allocUpdateBatcher *AllocUpdateBatcher
    84  
    85  	// ctx and exitFn are used to cancel the watcher
    86  	ctx    context.Context
    87  	exitFn context.CancelFunc
    88  
    89  	l sync.RWMutex
    90  }
    91  
    92  // NewDeploymentsWatcher returns a deployments watcher that is used to watch
    93  // deployments and trigger the scheduler as needed.
    94  func NewDeploymentsWatcher(logger log.Logger,
    95  	raft DeploymentRaftEndpoints, stateQueriesPerSecond float64,
    96  	updateBatchDuration time.Duration) *Watcher {
    97  
    98  	return &Watcher{
    99  		raft:                raft,
   100  		queryLimiter:        rate.NewLimiter(rate.Limit(stateQueriesPerSecond), 100),
   101  		updateBatchDuration: updateBatchDuration,
   102  		logger:              logger.Named("deployments_watcher"),
   103  	}
   104  }
   105  
   106  // SetEnabled is used to control if the watcher is enabled. The watcher
   107  // should only be enabled on the active leader. When being enabled the state is
   108  // passed in as it is no longer valid once a leader election has taken place.
   109  func (w *Watcher) SetEnabled(enabled bool, state *state.StateStore) {
   110  	w.l.Lock()
   111  	defer w.l.Unlock()
   112  
   113  	wasEnabled := w.enabled
   114  	w.enabled = enabled
   115  
   116  	if state != nil {
   117  		w.state = state
   118  	}
   119  
   120  	// Flush the state to create the necessary objects
   121  	w.flush()
   122  
   123  	// If we are starting now, launch the watch daemon
   124  	if enabled && !wasEnabled {
   125  		go w.watchDeployments(w.ctx)
   126  	}
   127  }
   128  
   129  // flush is used to clear the state of the watcher
   130  func (w *Watcher) flush() {
   131  	// Stop all the watchers and clear it
   132  	for _, watcher := range w.watchers {
   133  		watcher.StopWatch()
   134  	}
   135  
   136  	// Kill everything associated with the watcher
   137  	if w.exitFn != nil {
   138  		w.exitFn()
   139  	}
   140  
   141  	w.watchers = make(map[string]*deploymentWatcher, 32)
   142  	w.ctx, w.exitFn = context.WithCancel(context.Background())
   143  	w.allocUpdateBatcher = NewAllocUpdateBatcher(w.updateBatchDuration, w.raft, w.ctx)
   144  }
   145  
   146  // watchDeployments is the long lived go-routine that watches for deployments to
   147  // add and remove watchers on.
   148  func (w *Watcher) watchDeployments(ctx context.Context) {
   149  	dindex := uint64(1)
   150  	for {
   151  		// Block getting all deployments using the last deployment index.
   152  		deployments, idx, err := w.getDeploys(ctx, dindex)
   153  		if err != nil {
   154  			if err == context.Canceled {
   155  				return
   156  			}
   157  
   158  			w.logger.Error("failed to retrieve deployments", "error", err)
   159  		}
   160  
   161  		// Update the latest index
   162  		dindex = idx
   163  
   164  		// Ensure we are tracking the things we should and not tracking what we
   165  		// shouldn't be
   166  		for _, d := range deployments {
   167  			if d.Active() {
   168  				if err := w.add(d); err != nil {
   169  					w.logger.Error("failed to track deployment", "deployment_id", d.ID, "error", err)
   170  				}
   171  			} else {
   172  				w.remove(d)
   173  			}
   174  		}
   175  	}
   176  }
   177  
   178  // getDeploys retrieves all deployments blocking at the given index.
   179  func (w *Watcher) getDeploys(ctx context.Context, minIndex uint64) ([]*structs.Deployment, uint64, error) {
   180  	resp, index, err := w.state.BlockingQuery(w.getDeploysImpl, minIndex, ctx)
   181  	if err != nil {
   182  		return nil, 0, err
   183  	}
   184  
   185  	return resp.([]*structs.Deployment), index, nil
   186  }
   187  
   188  // getDeploysImpl retrieves all deployments from the passed state store.
   189  func (w *Watcher) getDeploysImpl(ws memdb.WatchSet, state *state.StateStore) (interface{}, uint64, error) {
   190  
   191  	iter, err := state.Deployments(ws)
   192  	if err != nil {
   193  		return nil, 0, err
   194  	}
   195  
   196  	var deploys []*structs.Deployment
   197  	for {
   198  		raw := iter.Next()
   199  		if raw == nil {
   200  			break
   201  		}
   202  		deploy := raw.(*structs.Deployment)
   203  		deploys = append(deploys, deploy)
   204  	}
   205  
   206  	// Use the last index that affected the deployment table
   207  	index, err := state.Index("deployment")
   208  	if err != nil {
   209  		return nil, 0, err
   210  	}
   211  
   212  	return deploys, index, nil
   213  }
   214  
   215  // add adds a deployment to the watch list
   216  func (w *Watcher) add(d *structs.Deployment) error {
   217  	w.l.Lock()
   218  	defer w.l.Unlock()
   219  	_, err := w.addLocked(d)
   220  	return err
   221  }
   222  
   223  // addLocked adds a deployment to the watch list and should only be called when
   224  // locked. Creating the deploymentWatcher starts a go routine to .watch() it
   225  func (w *Watcher) addLocked(d *structs.Deployment) (*deploymentWatcher, error) {
   226  	// Not enabled so no-op
   227  	if !w.enabled {
   228  		return nil, nil
   229  	}
   230  
   231  	if !d.Active() {
   232  		return nil, fmt.Errorf("deployment %q is terminal", d.ID)
   233  	}
   234  
   235  	// Already watched so just update the deployment
   236  	if w, ok := w.watchers[d.ID]; ok {
   237  		w.updateDeployment(d)
   238  		return nil, nil
   239  	}
   240  
   241  	// Get the job the deployment is referencing
   242  	snap, err := w.state.Snapshot()
   243  	if err != nil {
   244  		return nil, err
   245  	}
   246  
   247  	job, err := snap.JobByID(nil, d.Namespace, d.JobID)
   248  	if err != nil {
   249  		return nil, err
   250  	}
   251  	if job == nil {
   252  		return nil, fmt.Errorf("deployment %q references unknown job %q", d.ID, d.JobID)
   253  	}
   254  
   255  	watcher := newDeploymentWatcher(w.ctx, w.queryLimiter, w.logger, w.state, d, job, w)
   256  	w.watchers[d.ID] = watcher
   257  	return watcher, nil
   258  }
   259  
   260  // remove stops watching a deployment. This can be because the deployment is
   261  // complete or being deleted.
   262  func (w *Watcher) remove(d *structs.Deployment) {
   263  	w.l.Lock()
   264  	defer w.l.Unlock()
   265  
   266  	// Not enabled so no-op
   267  	if !w.enabled {
   268  		return
   269  	}
   270  
   271  	if watcher, ok := w.watchers[d.ID]; ok {
   272  		watcher.StopWatch()
   273  		delete(w.watchers, d.ID)
   274  	}
   275  }
   276  
   277  // forceAdd is used to force a lookup of the given deployment object and create
   278  // a watcher. If the deployment does not exist or is terminal an error is
   279  // returned.
   280  func (w *Watcher) forceAdd(dID string) (*deploymentWatcher, error) {
   281  	snap, err := w.state.Snapshot()
   282  	if err != nil {
   283  		return nil, err
   284  	}
   285  
   286  	deployment, err := snap.DeploymentByID(nil, dID)
   287  	if err != nil {
   288  		return nil, err
   289  	}
   290  
   291  	if deployment == nil {
   292  		return nil, fmt.Errorf("unknown deployment %q", dID)
   293  	}
   294  
   295  	return w.addLocked(deployment)
   296  }
   297  
   298  // getOrCreateWatcher returns the deployment watcher for the given deployment ID.
   299  func (w *Watcher) getOrCreateWatcher(dID string) (*deploymentWatcher, error) {
   300  	w.l.Lock()
   301  	defer w.l.Unlock()
   302  
   303  	// Not enabled so no-op
   304  	if !w.enabled {
   305  		return nil, notEnabled
   306  	}
   307  
   308  	watcher, ok := w.watchers[dID]
   309  	if ok {
   310  		return watcher, nil
   311  	}
   312  
   313  	return w.forceAdd(dID)
   314  }
   315  
   316  // SetAllocHealth is used to set the health of allocations for a deployment. If
   317  // there are any unhealthy allocations, the deployment is updated to be failed.
   318  // Otherwise the allocations are updated and an evaluation is created.
   319  func (w *Watcher) SetAllocHealth(req *structs.DeploymentAllocHealthRequest, resp *structs.DeploymentUpdateResponse) error {
   320  	watcher, err := w.getOrCreateWatcher(req.DeploymentID)
   321  	if err != nil {
   322  		return err
   323  	}
   324  
   325  	return watcher.SetAllocHealth(req, resp)
   326  }
   327  
   328  // PromoteDeployment is used to promote a deployment. If promote is false,
   329  // deployment is marked as failed. Otherwise the deployment is updated and an
   330  // evaluation is created.
   331  func (w *Watcher) PromoteDeployment(req *structs.DeploymentPromoteRequest, resp *structs.DeploymentUpdateResponse) error {
   332  	watcher, err := w.getOrCreateWatcher(req.DeploymentID)
   333  	if err != nil {
   334  		return err
   335  	}
   336  
   337  	return watcher.PromoteDeployment(req, resp)
   338  }
   339  
   340  // PauseDeployment is used to toggle the pause state on a deployment. If the
   341  // deployment is being unpaused, an evaluation is created.
   342  func (w *Watcher) PauseDeployment(req *structs.DeploymentPauseRequest, resp *structs.DeploymentUpdateResponse) error {
   343  	watcher, err := w.getOrCreateWatcher(req.DeploymentID)
   344  	if err != nil {
   345  		return err
   346  	}
   347  
   348  	return watcher.PauseDeployment(req, resp)
   349  }
   350  
   351  // FailDeployment is used to fail the deployment.
   352  func (w *Watcher) FailDeployment(req *structs.DeploymentFailRequest, resp *structs.DeploymentUpdateResponse) error {
   353  	watcher, err := w.getOrCreateWatcher(req.DeploymentID)
   354  	if err != nil {
   355  		return err
   356  	}
   357  
   358  	return watcher.FailDeployment(req, resp)
   359  }
   360  
   361  // createUpdate commits the given allocation desired transition and evaluation
   362  // to Raft but batches the commit with other calls.
   363  func (w *Watcher) createUpdate(allocs map[string]*structs.DesiredTransition, eval *structs.Evaluation) (uint64, error) {
   364  	return w.allocUpdateBatcher.CreateUpdate(allocs, eval).Results()
   365  }
   366  
   367  // upsertJob commits the given job to Raft
   368  func (w *Watcher) upsertJob(job *structs.Job) (uint64, error) {
   369  	return w.raft.UpsertJob(job)
   370  }
   371  
   372  // upsertDeploymentStatusUpdate commits the given deployment update and optional
   373  // evaluation to Raft
   374  func (w *Watcher) upsertDeploymentStatusUpdate(
   375  	u *structs.DeploymentStatusUpdate,
   376  	e *structs.Evaluation,
   377  	j *structs.Job) (uint64, error) {
   378  	return w.raft.UpdateDeploymentStatus(&structs.DeploymentStatusUpdateRequest{
   379  		DeploymentUpdate: u,
   380  		Eval:             e,
   381  		Job:              j,
   382  	})
   383  }
   384  
   385  // upsertDeploymentPromotion commits the given deployment promotion to Raft
   386  func (w *Watcher) upsertDeploymentPromotion(req *structs.ApplyDeploymentPromoteRequest) (uint64, error) {
   387  	return w.raft.UpdateDeploymentPromotion(req)
   388  }
   389  
   390  // upsertDeploymentAllocHealth commits the given allocation health changes to
   391  // Raft
   392  func (w *Watcher) upsertDeploymentAllocHealth(req *structs.ApplyDeploymentAllocHealthRequest) (uint64, error) {
   393  	return w.raft.UpdateDeploymentAllocHealth(req)
   394  }