diff --git a/cmd/OliveTin/main.go b/cmd/OliveTin/main.go index 1119022..6c522bf 100644 --- a/cmd/OliveTin/main.go +++ b/cmd/OliveTin/main.go @@ -4,6 +4,7 @@ import ( log "github.com/sirupsen/logrus" grpcapi "github.com/jamesread/OliveTin/internal/grpcapi" + updatecheck "github.com/jamesread/OliveTin/internal/updatecheck" "github.com/jamesread/OliveTin/internal/httpservers" @@ -57,7 +58,9 @@ func init() { func main() { log.Info("OliveTin started") - log.Debugf("%+v", cfg) + log.Debugf("Config: %+v", cfg) + + go updatecheck.CheckForUpdate(version, commit, cfg) go grpcapi.Start(cfg) diff --git a/go.mod b/go.mod index 6f3b7a3..a8e08a9 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,8 @@ module github.com/jamesread/OliveTin go 1.15 require ( + github.com/denisbrodbeck/machineid v1.0.1 // indirect + github.com/go-co-op/gocron v1.6.2 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.4.0 github.com/sirupsen/logrus v1.8.1 github.com/spf13/viper v1.7.1 diff --git a/internal/updatecheck/updateCheck.go b/internal/updatecheck/updateCheck.go new file mode 100644 index 0000000..46423e5 --- /dev/null +++ b/internal/updatecheck/updateCheck.go @@ -0,0 +1,79 @@ +package updatecheck + +import ( + config "github.com/jamesread/OliveTin/internal/config" + log "github.com/sirupsen/logrus" + "github.com/denisbrodbeck/machineid" + "github.com/go-co-op/gocron" + "runtime" + "net/http" + "encoding/json" + "bytes" + "time" + "io/ioutil" +) + +type UpdateRequest struct { + CurrentVersion string + CurrentCommit string + OS string + Arch string + MachineId string +} + +func machineId() string { + v, err := machineid.ProtectedID("OliveTin") + + if err != nil { + log.Warnf("Error getting machine ID: %v", err) + return "?" + } + + return v; +} + +func CheckForUpdate(currentVersion string, currentCommit string, cfg *config.Config) { + payload := UpdateRequest { + CurrentVersion: currentVersion, + CurrentCommit: currentCommit, + OS: runtime.GOOS, + Arch: runtime.GOARCH, + MachineId: machineId(), + } + + s := gocron.NewScheduler(time.UTC) + + s.Every(7).Days().Do(func() { + actualCheckForUpdate(payload) + }) + + s.StartAsync() +} + +func actualCheckForUpdate(payload UpdateRequest) { + jsonUpdateRequest, err := json.Marshal(payload) + + req, err := http.NewRequest("POST", "http://update-check.olivetin.app", bytes.NewReader(jsonUpdateRequest)) + + if err != nil { + log.Errorf("Update check failed %v", err) + return + } + + req.Header.Set("Content-Type", "application/json") + + resp, err := http.DefaultClient.Do(req) + + if err != nil { + log.Errorf("Update check failed %v", err) + } else { + newVersion, _ := ioutil.ReadAll(resp.Body) + + log.WithFields(log.Fields { + "NewVersion": string(newVersion), + }).Infof("Update check complete"); + + defer resp.Body.Close(); + } + +}