github.com/iqoqo/nomad@v0.11.3-0.20200911112621-d7021c74d101/client/allocrunner/migrate_hook.go (about)

     1  package allocrunner
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  
     7  	log "github.com/hashicorp/go-hclog"
     8  	"github.com/hashicorp/nomad/client/allocdir"
     9  	"github.com/hashicorp/nomad/client/allocwatcher"
    10  )
    11  
    12  // diskMigrationHook migrates ephemeral disk volumes. Depends on alloc dir
    13  // being built but must be run before anything else manipulates the alloc dir.
    14  type diskMigrationHook struct {
    15  	allocDir     *allocdir.AllocDir
    16  	allocWatcher allocwatcher.PrevAllocMigrator
    17  	logger       log.Logger
    18  }
    19  
    20  func newDiskMigrationHook(logger log.Logger, allocWatcher allocwatcher.PrevAllocMigrator, allocDir *allocdir.AllocDir) *diskMigrationHook {
    21  	h := &diskMigrationHook{
    22  		allocDir:     allocDir,
    23  		allocWatcher: allocWatcher,
    24  	}
    25  	h.logger = logger.Named(h.Name())
    26  	return h
    27  }
    28  
    29  func (h *diskMigrationHook) Name() string {
    30  	return "migrate_disk"
    31  }
    32  
    33  func (h *diskMigrationHook) Prerun() error {
    34  	ctx := context.TODO()
    35  
    36  	// Wait for a previous alloc - if any - to terminate
    37  	if err := h.allocWatcher.Wait(ctx); err != nil {
    38  		return err
    39  	}
    40  
    41  	// Wait for data to be migrated from a previous alloc if applicable
    42  	if err := h.allocWatcher.Migrate(ctx, h.allocDir); err != nil {
    43  		if err == context.Canceled {
    44  			return err
    45  		}
    46  
    47  		// Soft-fail on migration errors
    48  		h.logger.Warn("error migrating data from previous alloc", "error", err)
    49  
    50  		// Recreate alloc dir to ensure a clean slate
    51  		h.allocDir.Destroy()
    52  		if err := h.allocDir.Build(); err != nil {
    53  			return fmt.Errorf("failed to clean task directories after failed migration: %v", err)
    54  		}
    55  	}
    56  
    57  	return nil
    58  }