version.go 2.44 KB
Newer Older
1 2
package config

3 4 5 6
import (
	"strconv"
	"time"
)
7 8 9

// Version regulates checking if the most recent version is run
type Version struct {
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
	// Current is the ipfs version for which config was generated
	Current string

	// Check signals how to react on updates:
	// - "ignore" for not checking
	// - "warn" for issuing a warning and proceeding
	// - "error" for exiting with an error
	Check string

	// CheckDate is a timestamp for the last time API endpoint was checked for updates
	CheckDate time.Time

	// CheckPeriod is the time duration over which the update check will not be performed
	// (Note: cannot use time.Duration because marshalling with json breaks it)
	CheckPeriod string
Henry's avatar
Henry committed
25 26 27 28 29 30 31

	// AutoUpdate is optional and has these these options:
	// - "never" do not auto-update
	// - "patch" auto-update on new patch versions
	// - "minor" auto-update on new minor (or patch) versions (Default)
	// - "major" auto-update on any new version
	AutoUpdate string
32 33 34 35
}

// supported Version.Check values
const (
36 37 38 39 40 41 42 43
	// CheckError value for Version.Check to raise error and exit if version is obsolete
	CheckError = "error"

	// CheckWarn value for Version.Check to show warning message if version is obsolete
	CheckWarn = "warn"

	// CheckIgnore value for Version.Check to not perform update check
	CheckIgnore = "ignore"
44 45
)

Henry's avatar
Henry committed
46 47 48 49 50 51 52 53
// supported Version.AutoUpdate values
const (
	UpdateNever = "never"
	UpdatePatch = "patch"
	UpdateMinor = "minor"
	UpdateMajor = "major"
)

54 55
// defaultCheckPeriod governs h
var defaultCheckPeriod = time.Hour * 48
56

57 58 59 60 61 62 63 64 65 66 67 68 69 70
func (v *Version) checkPeriodDuration() time.Duration {
	d, err := strconv.Atoi(v.CheckPeriod)
	if err != nil {
		log.Error("config.Version.CheckPeriod parse error. Using default.")
		return defaultCheckPeriod
	}
	return time.Duration(d)
}

// ShouldCheckForUpdate returns if update check API endpoint is needed for this specific runtime
func (v *Version) ShouldCheckForUpdate() bool {

	period := v.checkPeriodDuration()
	if v.Check == CheckIgnore || v.CheckDate.Add(period).After(time.Now()) {
71 72 73 74 75
		return false
	}
	return true
}

76 77 78 79 80 81 82 83
// RecordUpdateCheck is called to record that an update check was performed,
// showing that the running version is the most recent one.
func RecordUpdateCheck(cfg *Config, filename string) {
	cfg.Version.CheckDate = time.Now()

	if cfg.Version.CheckPeriod == "" {
		// CheckPeriod was not initialized for some reason (e.g. config file broken)
		cfg.Version.CheckPeriod = strconv.Itoa(int(defaultCheckPeriod))
84 85 86 87
	}

	WriteConfigFile(filename, cfg)
}