github.com/niedbalski/juju@v0.0.0-20190215020005-8ff100488e47/worker/meterstatus/state.go (about)

     1  // Copyright 2015 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package meterstatus
     5  
     6  import (
     7  	"os"
     8  	"time"
     9  
    10  	"github.com/juju/errors"
    11  	"github.com/juju/utils"
    12  )
    13  
    14  // StateFile holds the meter status on disk.
    15  type StateFile struct {
    16  	path string
    17  }
    18  
    19  // NewStateFile creates a new file for persistent storage of
    20  // the meter status.
    21  func NewStateFile(path string) *StateFile {
    22  	return &StateFile{path: path}
    23  }
    24  
    25  type state struct {
    26  	Code         string        `yaml:"status-code"`
    27  	Info         string        `yaml:"status-info"`
    28  	Disconnected *Disconnected `yaml:"disconnected,omitempty"`
    29  }
    30  
    31  // Disconnected stores the information relevant to the inactive meter status worker.
    32  type Disconnected struct {
    33  	Disconnected int64       `yaml:"disconnected-at,omitempty"`
    34  	State        WorkerState `yaml:"disconnected-state,omitempty"`
    35  }
    36  
    37  // When returns the time when the unit was disconnected.
    38  func (d Disconnected) When() time.Time {
    39  	return time.Unix(d.Disconnected, 0)
    40  }
    41  
    42  // Read reads the current meter status information from disk.
    43  func (f *StateFile) Read() (string, string, *Disconnected, error) {
    44  	var st state
    45  	if err := utils.ReadYaml(f.path, &st); err != nil {
    46  		if os.IsNotExist(err) {
    47  			return "", "", nil, nil
    48  		}
    49  		return "", "", nil, errors.Trace(err)
    50  	}
    51  
    52  	return st.Code, st.Info, st.Disconnected, nil
    53  }
    54  
    55  // Write stores the supplied status information to disk.
    56  func (f *StateFile) Write(code, info string, disconnected *Disconnected) error {
    57  	st := state{
    58  		Code:         code,
    59  		Info:         info,
    60  		Disconnected: disconnected,
    61  	}
    62  
    63  	return errors.Trace(utils.WriteYaml(f.path, st))
    64  }