github.com/iaas-resource-provision/iaas-rpc@v1.0.7-0.20211021023331-ed21f798c408/internal/states/statemgr/filesystem.go (about)

     1  package statemgr
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"fmt"
     7  	"io"
     8  	"io/ioutil"
     9  	"log"
    10  	"os"
    11  	"path/filepath"
    12  	"sync"
    13  	"time"
    14  
    15  	multierror "github.com/hashicorp/go-multierror"
    16  
    17  	"github.com/iaas-resource-provision/iaas-rpc/internal/states"
    18  	"github.com/iaas-resource-provision/iaas-rpc/internal/states/statefile"
    19  )
    20  
    21  // Filesystem is a full state manager that uses a file in the local filesystem
    22  // for persistent storage.
    23  //
    24  // The transient storage for Filesystem is always in-memory.
    25  type Filesystem struct {
    26  	mu sync.Mutex
    27  
    28  	// path is the location where a file will be created or replaced for
    29  	// each persistent snapshot.
    30  	path string
    31  
    32  	// readPath is read by RefreshState instead of "path" until the first
    33  	// call to PersistState, after which it is ignored.
    34  	//
    35  	// The file at readPath must never be written to by this manager.
    36  	readPath string
    37  
    38  	// backupPath is an optional extra path which, if non-empty, will be
    39  	// created or overwritten with the first state snapshot we read if there
    40  	// is a subsequent call to write a different state.
    41  	backupPath string
    42  
    43  	// the file handle corresponding to PathOut
    44  	stateFileOut *os.File
    45  
    46  	// While the stateFileOut will correspond to the lock directly,
    47  	// store and check the lock ID to maintain a strict statemgr.Locker
    48  	// implementation.
    49  	lockID string
    50  
    51  	// created is set to true if stateFileOut didn't exist before we created it.
    52  	// This is mostly so we can clean up empty files during tests, but doesn't
    53  	// hurt to remove file we never wrote to.
    54  	created bool
    55  
    56  	file          *statefile.File
    57  	readFile      *statefile.File
    58  	backupFile    *statefile.File
    59  	writtenBackup bool
    60  }
    61  
    62  var (
    63  	_ Full           = (*Filesystem)(nil)
    64  	_ PersistentMeta = (*Filesystem)(nil)
    65  	_ Migrator       = (*Filesystem)(nil)
    66  )
    67  
    68  // NewFilesystem creates a filesystem-based state manager that reads and writes
    69  // state snapshots at the given filesystem path.
    70  //
    71  // This is equivalent to calling NewFileSystemBetweenPaths with statePath as
    72  // both of the path arguments.
    73  func NewFilesystem(statePath string) *Filesystem {
    74  	return &Filesystem{
    75  		path:     statePath,
    76  		readPath: statePath,
    77  	}
    78  }
    79  
    80  // NewFilesystemBetweenPaths creates a filesystem-based state manager that
    81  // reads an initial snapshot from readPath and then writes all new snapshots to
    82  // writePath.
    83  func NewFilesystemBetweenPaths(readPath, writePath string) *Filesystem {
    84  	return &Filesystem{
    85  		path:     writePath,
    86  		readPath: readPath,
    87  	}
    88  }
    89  
    90  // SetBackupPath configures the receiever so that it will create a local
    91  // backup file of the next state snapshot it reads (in State) if a different
    92  // snapshot is subsequently written (in WriteState). Only one backup is
    93  // written for the lifetime of the object, unless reset as described below.
    94  //
    95  // For correct operation, this must be called before any other state methods
    96  // are called. If called multiple times, each call resets the backup
    97  // function so that the next read will become the backup snapshot and a
    98  // following write will save a backup of it.
    99  func (s *Filesystem) SetBackupPath(path string) {
   100  	s.backupPath = path
   101  	s.backupFile = nil
   102  	s.writtenBackup = false
   103  }
   104  
   105  // BackupPath returns the manager's backup path if backup files are enabled,
   106  // or an empty string otherwise.
   107  func (s *Filesystem) BackupPath() string {
   108  	return s.backupPath
   109  }
   110  
   111  // State is an implementation of Reader.
   112  func (s *Filesystem) State() *states.State {
   113  	defer s.mutex()()
   114  	if s.file == nil {
   115  		return nil
   116  	}
   117  	return s.file.DeepCopy().State
   118  }
   119  
   120  // WriteState is an incorrect implementation of Writer that actually also
   121  // persists.
   122  func (s *Filesystem) WriteState(state *states.State) error {
   123  	// TODO: this should use a more robust method of writing state, by first
   124  	// writing to a temp file on the same filesystem, and renaming the file over
   125  	// the original.
   126  
   127  	defer s.mutex()()
   128  
   129  	if s.readFile == nil {
   130  		err := s.refreshState()
   131  		if err != nil {
   132  			return err
   133  		}
   134  	}
   135  
   136  	return s.writeState(state, nil)
   137  }
   138  
   139  func (s *Filesystem) writeState(state *states.State, meta *SnapshotMeta) error {
   140  	if s.stateFileOut == nil {
   141  		if err := s.createStateFiles(); err != nil {
   142  			return nil
   143  		}
   144  	}
   145  	defer s.stateFileOut.Sync()
   146  
   147  	// We'll try to write our backup first, so we can be sure we've created
   148  	// it successfully before clobbering the original file it came from.
   149  	if !s.writtenBackup && s.backupFile != nil && s.backupPath != "" {
   150  		if !statefile.StatesMarshalEqual(state, s.backupFile.State) {
   151  			log.Printf("[TRACE] statemgr.Filesystem: creating backup snapshot at %s", s.backupPath)
   152  			bfh, err := os.Create(s.backupPath)
   153  			if err != nil {
   154  				return fmt.Errorf("failed to create local state backup file: %s", err)
   155  			}
   156  			defer bfh.Close()
   157  
   158  			err = statefile.Write(s.backupFile, bfh)
   159  			if err != nil {
   160  				return fmt.Errorf("failed to write to local state backup file: %s", err)
   161  			}
   162  
   163  			s.writtenBackup = true
   164  		} else {
   165  			log.Print("[TRACE] statemgr.Filesystem: not making a backup, because the new snapshot is identical to the old")
   166  		}
   167  	} else {
   168  		// This branch is all just logging, to help understand why we didn't make a backup.
   169  		switch {
   170  		case s.backupPath == "":
   171  			log.Print("[TRACE] statemgr.Filesystem: state file backups are disabled")
   172  		case s.writtenBackup:
   173  			log.Printf("[TRACE] statemgr.Filesystem: have already backed up original %s to %s on a previous write", s.path, s.backupPath)
   174  		case s.backupFile == nil:
   175  			log.Printf("[TRACE] statemgr.Filesystem: no original state snapshot to back up")
   176  		default:
   177  			log.Printf("[TRACE] statemgr.Filesystem: not creating a backup for an unknown reason")
   178  		}
   179  	}
   180  
   181  	s.file = s.file.DeepCopy()
   182  	if s.file == nil {
   183  		s.file = NewStateFile()
   184  	}
   185  	s.file.State = state.DeepCopy()
   186  
   187  	if _, err := s.stateFileOut.Seek(0, io.SeekStart); err != nil {
   188  		return err
   189  	}
   190  	if err := s.stateFileOut.Truncate(0); err != nil {
   191  		return err
   192  	}
   193  
   194  	if state == nil {
   195  		// if we have no state, don't write anything else.
   196  		log.Print("[TRACE] statemgr.Filesystem: state is nil, so leaving the file empty")
   197  		return nil
   198  	}
   199  
   200  	if meta == nil {
   201  		if s.readFile == nil || !statefile.StatesMarshalEqual(s.file.State, s.readFile.State) {
   202  			s.file.Serial++
   203  			log.Printf("[TRACE] statemgr.Filesystem: state has changed since last snapshot, so incrementing serial to %d", s.file.Serial)
   204  		} else {
   205  			log.Print("[TRACE] statemgr.Filesystem: no state changes since last snapshot")
   206  		}
   207  	} else {
   208  		// Force new metadata
   209  		s.file.Lineage = meta.Lineage
   210  		s.file.Serial = meta.Serial
   211  		log.Printf("[TRACE] statemgr.Filesystem: forcing lineage %q serial %d for migration/import", s.file.Lineage, s.file.Serial)
   212  	}
   213  
   214  	log.Printf("[TRACE] statemgr.Filesystem: writing snapshot at %s", s.path)
   215  	if err := statefile.Write(s.file, s.stateFileOut); err != nil {
   216  		return err
   217  	}
   218  
   219  	// Any future reads must come from the file we've now updated
   220  	s.readPath = s.path
   221  	return nil
   222  }
   223  
   224  // PersistState is an implementation of Persister that does nothing because
   225  // this type's Writer implementation does its own persistence.
   226  func (s *Filesystem) PersistState() error {
   227  	return nil
   228  }
   229  
   230  // RefreshState is an implementation of Refresher.
   231  func (s *Filesystem) RefreshState() error {
   232  	defer s.mutex()()
   233  	return s.refreshState()
   234  }
   235  
   236  func (s *Filesystem) refreshState() error {
   237  	var reader io.Reader
   238  
   239  	// The s.readPath file is only OK to read if we have not written any state out
   240  	// (in which case the same state needs to be read in), and no state output file
   241  	// has been opened (possibly via a lock) or the input path is different
   242  	// than the output path.
   243  	// This is important for Windows, as if the input file is the same as the
   244  	// output file, and the output file has been locked already, we can't open
   245  	// the file again.
   246  	if s.stateFileOut == nil || s.readPath != s.path {
   247  		// we haven't written a state file yet, so load from readPath
   248  		log.Printf("[TRACE] statemgr.Filesystem: reading initial snapshot from %s", s.readPath)
   249  		f, err := os.Open(s.readPath)
   250  		if err != nil {
   251  			// It is okay if the file doesn't exist; we'll treat that as a nil state.
   252  			if !os.IsNotExist(err) {
   253  				return err
   254  			}
   255  
   256  			// we need a non-nil reader for ReadState and an empty buffer works
   257  			// to return EOF immediately
   258  			reader = bytes.NewBuffer(nil)
   259  
   260  		} else {
   261  			defer f.Close()
   262  			reader = f
   263  		}
   264  	} else {
   265  		log.Printf("[TRACE] statemgr.Filesystem: reading latest snapshot from %s", s.path)
   266  		// no state to refresh
   267  		if s.stateFileOut == nil {
   268  			return nil
   269  		}
   270  
   271  		// we have a state file, make sure we're at the start
   272  		s.stateFileOut.Seek(0, io.SeekStart)
   273  		reader = s.stateFileOut
   274  	}
   275  
   276  	f, err := statefile.Read(reader)
   277  	// if there's no state then a nil file is fine
   278  	if err != nil {
   279  		if err != statefile.ErrNoState {
   280  			return err
   281  		}
   282  		log.Printf("[TRACE] statemgr.Filesystem: snapshot file has nil snapshot, but that's okay")
   283  	}
   284  
   285  	s.file = f
   286  	s.readFile = s.file.DeepCopy()
   287  	if s.file != nil {
   288  		log.Printf("[TRACE] statemgr.Filesystem: read snapshot with lineage %q serial %d", s.file.Lineage, s.file.Serial)
   289  	} else {
   290  		log.Print("[TRACE] statemgr.Filesystem: read nil snapshot")
   291  	}
   292  	return nil
   293  }
   294  
   295  // Lock implements Locker using filesystem discretionary locks.
   296  func (s *Filesystem) Lock(info *LockInfo) (string, error) {
   297  	defer s.mutex()()
   298  
   299  	if s.stateFileOut == nil {
   300  		if err := s.createStateFiles(); err != nil {
   301  			return "", err
   302  		}
   303  	}
   304  
   305  	if s.lockID != "" {
   306  		return "", fmt.Errorf("state %q already locked", s.stateFileOut.Name())
   307  	}
   308  
   309  	if err := s.lock(); err != nil {
   310  		info, infoErr := s.lockInfo()
   311  		if infoErr != nil {
   312  			err = multierror.Append(err, infoErr)
   313  		}
   314  
   315  		lockErr := &LockError{
   316  			Info: info,
   317  			Err:  err,
   318  		}
   319  
   320  		return "", lockErr
   321  	}
   322  
   323  	s.lockID = info.ID
   324  	return s.lockID, s.writeLockInfo(info)
   325  }
   326  
   327  // Unlock is the companion to Lock, completing the implemention of Locker.
   328  func (s *Filesystem) Unlock(id string) error {
   329  	defer s.mutex()()
   330  
   331  	if s.lockID == "" {
   332  		return fmt.Errorf("LocalState not locked")
   333  	}
   334  
   335  	if id != s.lockID {
   336  		idErr := fmt.Errorf("invalid lock id: %q. current id: %q", id, s.lockID)
   337  		info, err := s.lockInfo()
   338  		if err != nil {
   339  			idErr = multierror.Append(idErr, err)
   340  		}
   341  
   342  		return &LockError{
   343  			Err:  idErr,
   344  			Info: info,
   345  		}
   346  	}
   347  
   348  	lockInfoPath := s.lockInfoPath()
   349  	log.Printf("[TRACE] statemgr.Filesystem: removing lock metadata file %s", lockInfoPath)
   350  	os.Remove(lockInfoPath)
   351  
   352  	fileName := s.stateFileOut.Name()
   353  
   354  	unlockErr := s.unlock()
   355  
   356  	s.stateFileOut.Close()
   357  	s.stateFileOut = nil
   358  	s.lockID = ""
   359  
   360  	// clean up the state file if we created it an never wrote to it
   361  	stat, err := os.Stat(fileName)
   362  	if err == nil && stat.Size() == 0 && s.created {
   363  		os.Remove(fileName)
   364  	}
   365  
   366  	return unlockErr
   367  }
   368  
   369  // StateSnapshotMeta returns the metadata from the most recently persisted
   370  // or refreshed persistent state snapshot.
   371  //
   372  // This is an implementation of PersistentMeta.
   373  func (s *Filesystem) StateSnapshotMeta() SnapshotMeta {
   374  	if s.file == nil {
   375  		return SnapshotMeta{} // placeholder
   376  	}
   377  
   378  	return SnapshotMeta{
   379  		Lineage: s.file.Lineage,
   380  		Serial:  s.file.Serial,
   381  
   382  		TerraformVersion: s.file.TerraformVersion,
   383  	}
   384  }
   385  
   386  // StateForMigration is part of our implementation of Migrator.
   387  func (s *Filesystem) StateForMigration() *statefile.File {
   388  	return s.file.DeepCopy()
   389  }
   390  
   391  // WriteStateForMigration is part of our implementation of Migrator.
   392  func (s *Filesystem) WriteStateForMigration(f *statefile.File, force bool) error {
   393  	defer s.mutex()()
   394  
   395  	if s.readFile == nil {
   396  		err := s.refreshState()
   397  		if err != nil {
   398  			return err
   399  		}
   400  	}
   401  
   402  	if !force {
   403  		err := CheckValidImport(f, s.readFile)
   404  		if err != nil {
   405  			return err
   406  		}
   407  	}
   408  
   409  	if s.readFile != nil {
   410  		log.Printf(
   411  			"[TRACE] statemgr.Filesystem: Importing snapshot with lineage %q serial %d over snapshot with lineage %q serial %d at %s",
   412  			f.Lineage, f.Serial,
   413  			s.readFile.Lineage, s.readFile.Serial,
   414  			s.path,
   415  		)
   416  	} else {
   417  		log.Printf(
   418  			"[TRACE] statemgr.Filesystem: Importing snapshot with lineage %q serial %d as the initial state snapshot at %s",
   419  			f.Lineage, f.Serial,
   420  			s.path,
   421  		)
   422  	}
   423  
   424  	err := s.writeState(f.State, &SnapshotMeta{Lineage: f.Lineage, Serial: f.Serial})
   425  	if err != nil {
   426  		return err
   427  	}
   428  
   429  	return nil
   430  }
   431  
   432  // Open the state file, creating the directories and file as needed.
   433  func (s *Filesystem) createStateFiles() error {
   434  	log.Printf("[TRACE] statemgr.Filesystem: preparing to manage state snapshots at %s", s.path)
   435  
   436  	// This could race, but we only use it to clean up empty files
   437  	if _, err := os.Stat(s.path); os.IsNotExist(err) {
   438  		s.created = true
   439  	}
   440  
   441  	// Create all the directories
   442  	if err := os.MkdirAll(filepath.Dir(s.path), 0755); err != nil {
   443  		return err
   444  	}
   445  
   446  	f, err := os.OpenFile(s.path, os.O_RDWR|os.O_CREATE, 0666)
   447  	if err != nil {
   448  		return err
   449  	}
   450  
   451  	s.stateFileOut = f
   452  
   453  	// If the file already existed with content then that'll be the content
   454  	// of our backup file if we write a change later.
   455  	s.backupFile, err = statefile.Read(s.stateFileOut)
   456  	if err != nil {
   457  		if err != statefile.ErrNoState {
   458  			return err
   459  		}
   460  		log.Printf("[TRACE] statemgr.Filesystem: no previously-stored snapshot exists")
   461  	} else {
   462  		log.Printf("[TRACE] statemgr.Filesystem: existing snapshot has lineage %q serial %d", s.backupFile.Lineage, s.backupFile.Serial)
   463  	}
   464  
   465  	// Refresh now, to load in the snapshot if the file already existed
   466  	return nil
   467  }
   468  
   469  // return the path for the lockInfo metadata.
   470  func (s *Filesystem) lockInfoPath() string {
   471  	stateDir, stateName := filepath.Split(s.path)
   472  	if stateName == "" {
   473  		panic("empty state file path")
   474  	}
   475  
   476  	if stateName[0] == '.' {
   477  		stateName = stateName[1:]
   478  	}
   479  
   480  	return filepath.Join(stateDir, fmt.Sprintf(".%s.lock.info", stateName))
   481  }
   482  
   483  // lockInfo returns the data in a lock info file
   484  func (s *Filesystem) lockInfo() (*LockInfo, error) {
   485  	path := s.lockInfoPath()
   486  	infoData, err := ioutil.ReadFile(path)
   487  	if err != nil {
   488  		return nil, err
   489  	}
   490  
   491  	info := LockInfo{}
   492  	err = json.Unmarshal(infoData, &info)
   493  	if err != nil {
   494  		return nil, fmt.Errorf("state file %q locked, but could not unmarshal lock info: %s", s.readPath, err)
   495  	}
   496  	return &info, nil
   497  }
   498  
   499  // write a new lock info file
   500  func (s *Filesystem) writeLockInfo(info *LockInfo) error {
   501  	path := s.lockInfoPath()
   502  	info.Path = s.readPath
   503  	info.Created = time.Now().UTC()
   504  
   505  	log.Printf("[TRACE] statemgr.Filesystem: writing lock metadata to %s", path)
   506  	err := ioutil.WriteFile(path, info.Marshal(), 0600)
   507  	if err != nil {
   508  		return fmt.Errorf("could not write lock info for %q: %s", s.readPath, err)
   509  	}
   510  	return nil
   511  }
   512  
   513  func (s *Filesystem) mutex() func() {
   514  	s.mu.Lock()
   515  	return s.mu.Unlock
   516  }