github.com/blixtra/nomad@v0.7.2-0.20171221000451-da9a1d7bb050/client/vaultclient/vaultclient.go (about)

     1  package vaultclient
     2  
     3  import (
     4  	"container/heap"
     5  	"fmt"
     6  	"log"
     7  	"math/rand"
     8  	"strings"
     9  	"sync"
    10  	"time"
    11  
    12  	"github.com/hashicorp/nomad/nomad/structs"
    13  	"github.com/hashicorp/nomad/nomad/structs/config"
    14  	vaultapi "github.com/hashicorp/vault/api"
    15  )
    16  
    17  // TokenDeriverFunc takes in an allocation and a set of tasks and derives a
    18  // wrapped token for all the tasks, from the nomad server. All the derived
    19  // wrapped tokens will be unwrapped using the vault API client.
    20  type TokenDeriverFunc func(*structs.Allocation, []string, *vaultapi.Client) (map[string]string, error)
    21  
    22  // The interface which nomad client uses to interact with vault and
    23  // periodically renews the tokens and secrets.
    24  type VaultClient interface {
    25  	// Start initiates the renewal loop of tokens and secrets
    26  	Start()
    27  
    28  	// Stop terminates the renewal loop for tokens and secrets
    29  	Stop()
    30  
    31  	// DeriveToken contacts the nomad server and fetches wrapped tokens for
    32  	// a set of tasks. The wrapped tokens will be unwrapped using vault and
    33  	// returned.
    34  	DeriveToken(*structs.Allocation, []string) (map[string]string, error)
    35  
    36  	// GetConsulACL fetches the Consul ACL token required for the task
    37  	GetConsulACL(string, string) (*vaultapi.Secret, error)
    38  
    39  	// RenewToken renews a token with the given increment and adds it to
    40  	// the min-heap for periodic renewal.
    41  	RenewToken(string, int) (<-chan error, error)
    42  
    43  	// StopRenewToken removes the token from the min-heap, stopping its
    44  	// renewal.
    45  	StopRenewToken(string) error
    46  
    47  	// RenewLease renews a vault secret's lease and adds the lease
    48  	// identifier to the min-heap for periodic renewal.
    49  	RenewLease(string, int) (<-chan error, error)
    50  
    51  	// StopRenewLease removes a secret's lease ID from the min-heap,
    52  	// stopping its renewal.
    53  	StopRenewLease(string) error
    54  }
    55  
    56  // Implementation of VaultClient interface to interact with vault and perform
    57  // token and lease renewals periodically.
    58  type vaultClient struct {
    59  	// tokenDeriver is a function pointer passed in by the client to derive
    60  	// tokens by making RPC calls to the nomad server. The wrapped tokens
    61  	// returned by the nomad server will be unwrapped by this function
    62  	// using the vault API client.
    63  	tokenDeriver TokenDeriverFunc
    64  
    65  	// running indicates if the renewal loop is active or not
    66  	running bool
    67  
    68  	// client is the API client to interact with vault
    69  	client *vaultapi.Client
    70  
    71  	// updateCh is the channel to notify heap modifications to the renewal
    72  	// loop
    73  	updateCh chan struct{}
    74  
    75  	// stopCh is the channel to trigger termination of renewal loop
    76  	stopCh chan struct{}
    77  
    78  	// heap is the min-heap to keep track of both tokens and leases
    79  	heap *vaultClientHeap
    80  
    81  	// config is the configuration to connect to vault
    82  	config *config.VaultConfig
    83  
    84  	lock   sync.RWMutex
    85  	logger *log.Logger
    86  }
    87  
    88  // vaultClientRenewalRequest is a request object for renewal of both tokens and
    89  // secret's leases.
    90  type vaultClientRenewalRequest struct {
    91  	// errCh is the channel into which any renewal error will be sent to
    92  	errCh chan error
    93  
    94  	// id is an identifier which represents either a token or a lease
    95  	id string
    96  
    97  	// increment is the duration for which the token or lease should be
    98  	// renewed for
    99  	increment int
   100  
   101  	// isToken indicates whether the 'id' field is a token or not
   102  	isToken bool
   103  }
   104  
   105  // Element representing an entry in the renewal heap
   106  type vaultClientHeapEntry struct {
   107  	req   *vaultClientRenewalRequest
   108  	next  time.Time
   109  	index int
   110  }
   111  
   112  // Wrapper around the actual heap to provide additional symantics on top of
   113  // functions provided by the heap interface. In order to achieve that, an
   114  // additional map is placed beside the actual heap. This map can be used to
   115  // check if an entry is already present in the heap.
   116  type vaultClientHeap struct {
   117  	heapMap map[string]*vaultClientHeapEntry
   118  	heap    vaultDataHeapImp
   119  }
   120  
   121  // Data type of the heap
   122  type vaultDataHeapImp []*vaultClientHeapEntry
   123  
   124  // NewVaultClient returns a new vault client from the given config.
   125  func NewVaultClient(config *config.VaultConfig, logger *log.Logger, tokenDeriver TokenDeriverFunc) (*vaultClient, error) {
   126  	if config == nil {
   127  		return nil, fmt.Errorf("nil vault config")
   128  	}
   129  
   130  	if logger == nil {
   131  		return nil, fmt.Errorf("nil logger")
   132  	}
   133  
   134  	c := &vaultClient{
   135  		config: config,
   136  		stopCh: make(chan struct{}),
   137  		// Update channel should be a buffered channel
   138  		updateCh:     make(chan struct{}, 1),
   139  		heap:         newVaultClientHeap(),
   140  		logger:       logger,
   141  		tokenDeriver: tokenDeriver,
   142  	}
   143  
   144  	if !config.IsEnabled() {
   145  		return c, nil
   146  	}
   147  
   148  	// Get the Vault API configuration
   149  	apiConf, err := config.ApiConfig()
   150  	if err != nil {
   151  		logger.Printf("[ERR] client.vault: failed to create vault API config: %v", err)
   152  		return nil, err
   153  	}
   154  
   155  	// Create the Vault API client
   156  	client, err := vaultapi.NewClient(apiConf)
   157  	if err != nil {
   158  		logger.Printf("[ERR] client.vault: failed to create Vault client. Not retrying: %v", err)
   159  		return nil, err
   160  	}
   161  
   162  	c.client = client
   163  
   164  	return c, nil
   165  }
   166  
   167  // newVaultClientHeap returns a new vault client heap with both the heap and a
   168  // map which is a secondary index for heap elements, both initialized.
   169  func newVaultClientHeap() *vaultClientHeap {
   170  	return &vaultClientHeap{
   171  		heapMap: make(map[string]*vaultClientHeapEntry),
   172  		heap:    make(vaultDataHeapImp, 0),
   173  	}
   174  }
   175  
   176  // isTracked returns if a given identifier is already present in the heap and
   177  // hence is being renewed. Lock should be held before calling this method.
   178  func (c *vaultClient) isTracked(id string) bool {
   179  	if id == "" {
   180  		return false
   181  	}
   182  
   183  	_, ok := c.heap.heapMap[id]
   184  	return ok
   185  }
   186  
   187  // Starts the renewal loop of vault client
   188  func (c *vaultClient) Start() {
   189  	if !c.config.IsEnabled() || c.running {
   190  		return
   191  	}
   192  
   193  	c.lock.Lock()
   194  	c.running = true
   195  	c.lock.Unlock()
   196  
   197  	go c.run()
   198  }
   199  
   200  // Stops the renewal loop of vault client
   201  func (c *vaultClient) Stop() {
   202  	if !c.config.IsEnabled() || !c.running {
   203  		return
   204  	}
   205  
   206  	c.lock.Lock()
   207  	defer c.lock.Unlock()
   208  
   209  	c.running = false
   210  	close(c.stopCh)
   211  }
   212  
   213  // unlockAndUnset is used to unset the vault token on the client and release the
   214  // lock. Helper method for deferring a call that does both.
   215  func (c *vaultClient) unlockAndUnset() {
   216  	c.client.SetToken("")
   217  	c.lock.Unlock()
   218  }
   219  
   220  // DeriveToken takes in an allocation and a set of tasks and for each of the
   221  // task, it derives a vault token from nomad server and unwraps it using vault.
   222  // The return value is a map containing all the unwrapped tokens indexed by the
   223  // task name.
   224  func (c *vaultClient) DeriveToken(alloc *structs.Allocation, taskNames []string) (map[string]string, error) {
   225  	if !c.config.IsEnabled() {
   226  		return nil, fmt.Errorf("vault client not enabled")
   227  	}
   228  	if !c.running {
   229  		return nil, fmt.Errorf("vault client is not running")
   230  	}
   231  
   232  	c.lock.Lock()
   233  	defer c.unlockAndUnset()
   234  
   235  	// Use the token supplied to interact with vault
   236  	c.client.SetToken("")
   237  
   238  	tokens, err := c.tokenDeriver(alloc, taskNames, c.client)
   239  	if err != nil {
   240  		c.logger.Printf("[ERR] client.vault: failed to derive token for allocation %q and tasks %v: %v", alloc.ID, taskNames, err)
   241  		return nil, err
   242  	}
   243  
   244  	return tokens, nil
   245  }
   246  
   247  // GetConsulACL creates a vault API client and reads from vault a consul ACL
   248  // token used by the task.
   249  func (c *vaultClient) GetConsulACL(token, path string) (*vaultapi.Secret, error) {
   250  	if !c.config.IsEnabled() {
   251  		return nil, fmt.Errorf("vault client not enabled")
   252  	}
   253  	if token == "" {
   254  		return nil, fmt.Errorf("missing token")
   255  	}
   256  	if path == "" {
   257  		return nil, fmt.Errorf("missing consul ACL token vault path")
   258  	}
   259  
   260  	c.lock.Lock()
   261  	defer c.unlockAndUnset()
   262  
   263  	// Use the token supplied to interact with vault
   264  	c.client.SetToken(token)
   265  
   266  	// Read the consul ACL token and return the secret directly
   267  	return c.client.Logical().Read(path)
   268  }
   269  
   270  // RenewToken renews the supplied token for a given duration (in seconds) and
   271  // adds it to the min-heap so that it is renewed periodically by the renewal
   272  // loop. Any error returned during renewal will be written to a buffered
   273  // channel and the channel is returned instead of an actual error. This helps
   274  // the caller be notified of a renewal failure asynchronously for appropriate
   275  // actions to be taken. The caller of this function need not have to close the
   276  // error channel.
   277  func (c *vaultClient) RenewToken(token string, increment int) (<-chan error, error) {
   278  	if token == "" {
   279  		err := fmt.Errorf("missing token")
   280  		return nil, err
   281  	}
   282  	if increment < 1 {
   283  		err := fmt.Errorf("increment cannot be less than 1")
   284  		return nil, err
   285  	}
   286  
   287  	// Create a buffered error channel
   288  	errCh := make(chan error, 1)
   289  
   290  	// Create a renewal request and indicate that the identifier in the
   291  	// request is a token and not a lease
   292  	renewalReq := &vaultClientRenewalRequest{
   293  		errCh:     errCh,
   294  		id:        token,
   295  		isToken:   true,
   296  		increment: increment,
   297  	}
   298  
   299  	// Perform the renewal of the token and send any error to the dedicated
   300  	// error channel.
   301  	if err := c.renew(renewalReq); err != nil {
   302  		c.logger.Printf("[ERR] client.vault: renewal of token failed: %v", err)
   303  		return nil, err
   304  	}
   305  
   306  	return errCh, nil
   307  }
   308  
   309  // RenewLease renews the supplied lease identifier for a supplied duration (in
   310  // seconds) and adds it to the min-heap so that it gets renewed periodically by
   311  // the renewal loop. Any error returned during renewal will be written to a
   312  // buffered channel and the channel is returned instead of an actual error.
   313  // This helps the caller be notified of a renewal failure asynchronously for
   314  // appropriate actions to be taken. The caller of this function need not have
   315  // to close the error channel.
   316  func (c *vaultClient) RenewLease(leaseId string, increment int) (<-chan error, error) {
   317  	if leaseId == "" {
   318  		err := fmt.Errorf("missing lease ID")
   319  		return nil, err
   320  	}
   321  
   322  	if increment < 1 {
   323  		err := fmt.Errorf("increment cannot be less than 1")
   324  		return nil, err
   325  	}
   326  
   327  	// Create a buffered error channel
   328  	errCh := make(chan error, 1)
   329  
   330  	// Create a renewal request using the supplied lease and duration
   331  	renewalReq := &vaultClientRenewalRequest{
   332  		errCh:     errCh,
   333  		id:        leaseId,
   334  		increment: increment,
   335  	}
   336  
   337  	// Renew the secret and send any error to the dedicated error channel
   338  	if err := c.renew(renewalReq); err != nil {
   339  		c.logger.Printf("[ERR] client.vault: renewal of lease failed: %v", err)
   340  		return nil, err
   341  	}
   342  
   343  	return errCh, nil
   344  }
   345  
   346  // renew is a common method to handle renewal of both tokens and secret leases.
   347  // It invokes a token renewal or a secret's lease renewal. If renewal is
   348  // successful, min-heap is updated based on the duration after which it needs
   349  // renewal again. The next renewal time is randomly selected to avoid spikes in
   350  // the number of APIs periodically.
   351  func (c *vaultClient) renew(req *vaultClientRenewalRequest) error {
   352  	c.lock.Lock()
   353  	defer c.lock.Unlock()
   354  
   355  	if req == nil {
   356  		return fmt.Errorf("nil renewal request")
   357  	}
   358  	if req.errCh == nil {
   359  		return fmt.Errorf("renewal request error channel nil")
   360  	}
   361  
   362  	if !c.config.IsEnabled() {
   363  		close(req.errCh)
   364  		return fmt.Errorf("vault client not enabled")
   365  	}
   366  	if !c.running {
   367  		close(req.errCh)
   368  		return fmt.Errorf("vault client is not running")
   369  	}
   370  	if req.id == "" {
   371  		close(req.errCh)
   372  		return fmt.Errorf("missing id in renewal request")
   373  	}
   374  	if req.increment < 1 {
   375  		close(req.errCh)
   376  		return fmt.Errorf("increment cannot be less than 1")
   377  	}
   378  
   379  	var renewalErr error
   380  	leaseDuration := req.increment
   381  	if req.isToken {
   382  		// Set the token in the API client to the one that needs
   383  		// renewal
   384  		c.client.SetToken(req.id)
   385  
   386  		// Renew the token
   387  		renewResp, err := c.client.Auth().Token().RenewSelf(req.increment)
   388  		if err != nil {
   389  			renewalErr = fmt.Errorf("failed to renew the vault token: %v", err)
   390  		} else if renewResp == nil || renewResp.Auth == nil {
   391  			renewalErr = fmt.Errorf("failed to renew the vault token")
   392  		} else {
   393  			// Don't set this if renewal fails
   394  			leaseDuration = renewResp.Auth.LeaseDuration
   395  		}
   396  
   397  		// Reset the token in the API client before returning
   398  		c.client.SetToken("")
   399  	} else {
   400  		// Renew the secret
   401  		renewResp, err := c.client.Sys().Renew(req.id, req.increment)
   402  		if err != nil {
   403  			renewalErr = fmt.Errorf("failed to renew vault secret: %v", err)
   404  		} else if renewResp == nil {
   405  			renewalErr = fmt.Errorf("failed to renew vault secret")
   406  		} else {
   407  			// Don't set this if renewal fails
   408  			leaseDuration = renewResp.LeaseDuration
   409  		}
   410  	}
   411  
   412  	duration := leaseDuration / 2
   413  	switch {
   414  	case leaseDuration < 30:
   415  		// Don't bother about introducing randomness if the
   416  		// leaseDuration is too small.
   417  	default:
   418  		// Give a breathing space of 20 seconds
   419  		min := 10
   420  		max := leaseDuration - min
   421  		rand.Seed(time.Now().Unix())
   422  		duration = min + rand.Intn(max-min)
   423  	}
   424  
   425  	// Determine the next renewal time
   426  	next := time.Now().Add(time.Duration(duration) * time.Second)
   427  
   428  	fatal := false
   429  	if renewalErr != nil &&
   430  		(strings.Contains(renewalErr.Error(), "lease not found or lease is not renewable") ||
   431  			strings.Contains(renewalErr.Error(), "token not found") ||
   432  			strings.Contains(renewalErr.Error(), "permission denied")) {
   433  		fatal = true
   434  	} else if renewalErr != nil {
   435  		c.logger.Printf("[DEBUG] client.vault: req.increment: %d, leaseDuration: %d, duration: %d", req.increment, leaseDuration, duration)
   436  		c.logger.Printf("[ERR] client.vault: renewal of lease or token failed due to a non-fatal error. Retrying at %v: %v", next.String(), renewalErr)
   437  	}
   438  
   439  	if c.isTracked(req.id) {
   440  		if fatal {
   441  			// If encountered with an error where in a lease or a
   442  			// token is not valid at all with vault, and if that
   443  			// item is tracked by the renewal loop, stop renewing
   444  			// it by removing the corresponding heap entry.
   445  			if err := c.heap.Remove(req.id); err != nil {
   446  				return fmt.Errorf("failed to remove heap entry: %v", err)
   447  			}
   448  
   449  			// Report the fatal error to the client
   450  			req.errCh <- renewalErr
   451  			close(req.errCh)
   452  
   453  			return renewalErr
   454  		}
   455  
   456  		// If the identifier is already tracked, this indicates a
   457  		// subsequest renewal. In this case, update the existing
   458  		// element in the heap with the new renewal time.
   459  		if err := c.heap.Update(req, next); err != nil {
   460  			return fmt.Errorf("failed to update heap entry. err: %v", err)
   461  		}
   462  
   463  		// There is no need to signal an update to the renewal loop
   464  		// here because this case is hit from the renewal loop itself.
   465  	} else {
   466  		if fatal {
   467  			// If encountered with an error where in a lease or a
   468  			// token is not valid at all with vault, and if that
   469  			// item is not tracked by renewal loop, don't add it.
   470  
   471  			// Report the fatal error to the client
   472  			req.errCh <- renewalErr
   473  			close(req.errCh)
   474  
   475  			return renewalErr
   476  		}
   477  
   478  		// If the identifier is not already tracked, this is a first
   479  		// renewal request. In this case, add an entry into the heap
   480  		// with the next renewal time.
   481  		if err := c.heap.Push(req, next); err != nil {
   482  			return fmt.Errorf("failed to push an entry to heap.  err: %v", err)
   483  		}
   484  
   485  		// Signal an update for the renewal loop to trigger a fresh
   486  		// computation for the next best candidate for renewal.
   487  		if c.running {
   488  			select {
   489  			case c.updateCh <- struct{}{}:
   490  			default:
   491  			}
   492  		}
   493  	}
   494  
   495  	return nil
   496  }
   497  
   498  // run is the renewal loop which performs the periodic renewals of both the
   499  // tokens and the secret leases.
   500  func (c *vaultClient) run() {
   501  	if !c.config.IsEnabled() {
   502  		return
   503  	}
   504  
   505  	var renewalCh <-chan time.Time
   506  	for c.config.IsEnabled() && c.running {
   507  		// Fetches the candidate for next renewal
   508  		renewalReq, renewalTime := c.nextRenewal()
   509  		if renewalTime.IsZero() {
   510  			// If the heap is empty, don't do anything
   511  			renewalCh = nil
   512  		} else {
   513  			now := time.Now()
   514  			if renewalTime.After(now) {
   515  				// Compute the duration after which the item
   516  				// needs renewal and set the renewalCh to fire
   517  				// at that time.
   518  				renewalDuration := renewalTime.Sub(time.Now())
   519  				renewalCh = time.After(renewalDuration)
   520  			} else {
   521  				// If the renewals of multiple items are too
   522  				// close to each other and by the time the
   523  				// entry is fetched from heap it might be past
   524  				// the current time (by a small margin). In
   525  				// which case, fire immediately.
   526  				renewalCh = time.After(0)
   527  			}
   528  		}
   529  
   530  		select {
   531  		case <-renewalCh:
   532  			if err := c.renew(renewalReq); err != nil {
   533  				c.logger.Printf("[ERR] client.vault: renewal of token failed: %v", err)
   534  			}
   535  		case <-c.updateCh:
   536  			continue
   537  		case <-c.stopCh:
   538  			c.logger.Printf("[DEBUG] client.vault: stopped")
   539  			return
   540  		}
   541  	}
   542  }
   543  
   544  // StopRenewToken removes the item from the heap which represents the given
   545  // token.
   546  func (c *vaultClient) StopRenewToken(token string) error {
   547  	return c.stopRenew(token)
   548  }
   549  
   550  // StopRenewLease removes the item from the heap which represents the given
   551  // lease identifier.
   552  func (c *vaultClient) StopRenewLease(leaseId string) error {
   553  	return c.stopRenew(leaseId)
   554  }
   555  
   556  // stopRenew removes the given identifier from the heap and signals the renewal
   557  // loop to compute the next best candidate for renewal.
   558  func (c *vaultClient) stopRenew(id string) error {
   559  	c.lock.Lock()
   560  	defer c.lock.Unlock()
   561  
   562  	if !c.isTracked(id) {
   563  		return nil
   564  	}
   565  
   566  	if err := c.heap.Remove(id); err != nil {
   567  		return fmt.Errorf("failed to remove heap entry: %v", err)
   568  	}
   569  
   570  	// Signal an update to the renewal loop.
   571  	if c.running {
   572  		select {
   573  		case c.updateCh <- struct{}{}:
   574  		default:
   575  		}
   576  	}
   577  
   578  	return nil
   579  }
   580  
   581  // nextRenewal returns the root element of the min-heap, which represents the
   582  // next element to be renewed and the time at which the renewal needs to be
   583  // triggered.
   584  func (c *vaultClient) nextRenewal() (*vaultClientRenewalRequest, time.Time) {
   585  	c.lock.RLock()
   586  	defer c.lock.RUnlock()
   587  
   588  	if c.heap.Length() == 0 {
   589  		return nil, time.Time{}
   590  	}
   591  
   592  	// Fetches the root element in the min-heap
   593  	nextEntry := c.heap.Peek()
   594  	if nextEntry == nil {
   595  		return nil, time.Time{}
   596  	}
   597  
   598  	return nextEntry.req, nextEntry.next
   599  }
   600  
   601  // Additional helper functions on top of interface methods
   602  
   603  // Length returns the number of elements in the heap
   604  func (h *vaultClientHeap) Length() int {
   605  	return len(h.heap)
   606  }
   607  
   608  // Returns the root node of the min-heap
   609  func (h *vaultClientHeap) Peek() *vaultClientHeapEntry {
   610  	if len(h.heap) == 0 {
   611  		return nil
   612  	}
   613  
   614  	return h.heap[0]
   615  }
   616  
   617  // Push adds the secondary index and inserts an item into the heap
   618  func (h *vaultClientHeap) Push(req *vaultClientRenewalRequest, next time.Time) error {
   619  	if req == nil {
   620  		return fmt.Errorf("nil request")
   621  	}
   622  
   623  	if _, ok := h.heapMap[req.id]; ok {
   624  		return fmt.Errorf("entry %v already exists", req.id)
   625  	}
   626  
   627  	heapEntry := &vaultClientHeapEntry{
   628  		req:  req,
   629  		next: next,
   630  	}
   631  	h.heapMap[req.id] = heapEntry
   632  	heap.Push(&h.heap, heapEntry)
   633  	return nil
   634  }
   635  
   636  // Update will modify the existing item in the heap with the new data and the
   637  // time, and fixes the heap.
   638  func (h *vaultClientHeap) Update(req *vaultClientRenewalRequest, next time.Time) error {
   639  	if entry, ok := h.heapMap[req.id]; ok {
   640  		entry.req = req
   641  		entry.next = next
   642  		heap.Fix(&h.heap, entry.index)
   643  		return nil
   644  	}
   645  
   646  	return fmt.Errorf("heap doesn't contain %v", req.id)
   647  }
   648  
   649  // Remove will remove an identifier from the secondary index and deletes the
   650  // corresponding node from the heap.
   651  func (h *vaultClientHeap) Remove(id string) error {
   652  	if entry, ok := h.heapMap[id]; ok {
   653  		heap.Remove(&h.heap, entry.index)
   654  		delete(h.heapMap, id)
   655  		return nil
   656  	}
   657  
   658  	return fmt.Errorf("heap doesn't contain entry for %v", id)
   659  }
   660  
   661  // The heap interface requires the following methods to be implemented.
   662  // * Push(x interface{}) // add x as element Len()
   663  // * Pop() interface{}   // remove and return element Len() - 1.
   664  // * sort.Interface
   665  //
   666  // sort.Interface comprises of the following methods:
   667  // * Len() int
   668  // * Less(i, j int) bool
   669  // * Swap(i, j int)
   670  
   671  // Part of sort.Interface
   672  func (h vaultDataHeapImp) Len() int { return len(h) }
   673  
   674  // Part of sort.Interface
   675  func (h vaultDataHeapImp) Less(i, j int) bool {
   676  	// Two zero times should return false.
   677  	// Otherwise, zero is "greater" than any other time.
   678  	// (To sort it at the end of the list.)
   679  	// Sort such that zero times are at the end of the list.
   680  	iZero, jZero := h[i].next.IsZero(), h[j].next.IsZero()
   681  	if iZero && jZero {
   682  		return false
   683  	} else if iZero {
   684  		return false
   685  	} else if jZero {
   686  		return true
   687  	}
   688  
   689  	return h[i].next.Before(h[j].next)
   690  }
   691  
   692  // Part of sort.Interface
   693  func (h vaultDataHeapImp) Swap(i, j int) {
   694  	h[i], h[j] = h[j], h[i]
   695  	h[i].index = i
   696  	h[j].index = j
   697  }
   698  
   699  // Part of heap.Interface
   700  func (h *vaultDataHeapImp) Push(x interface{}) {
   701  	n := len(*h)
   702  	entry := x.(*vaultClientHeapEntry)
   703  	entry.index = n
   704  	*h = append(*h, entry)
   705  }
   706  
   707  // Part of heap.Interface
   708  func (h *vaultDataHeapImp) Pop() interface{} {
   709  	old := *h
   710  	n := len(old)
   711  	entry := old[n-1]
   712  	entry.index = -1 // for safety
   713  	*h = old[0 : n-1]
   714  	return entry
   715  }