/
updater.go
87 lines (73 loc) · 2.04 KB
/
updater.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package runtime
import (
"encoding/json"
"fmt"
"github.com/golang/glog"
"github.com/inconshreveable/go-update"
omni_http "github.com/qorio/omni/http"
"io"
"io/ioutil"
"net/http"
"strings"
)
type UpdateExecutableRequest struct {
DownloadUrl string `json:"downloadUrl"`
}
type UpdateResult struct {
Error error
RecoverError error
}
func StartUpdateHandler(resp http.ResponseWriter, request *http.Request) {
omni_http.SetCORSHeaders(resp)
body, err := ioutil.ReadAll(request.Body)
if err != nil {
renderJsonError(resp, request, err.Error(), http.StatusInternalServerError)
return
}
var message UpdateExecutableRequest
dec := json.NewDecoder(strings.NewReader(string(body)))
for {
if err := dec.Decode(&message); err == io.EOF {
break
} else if err != nil {
renderJsonError(resp, request, err.Error(), http.StatusBadRequest)
return
}
}
if message.DownloadUrl == "" {
renderJsonError(resp, request, "update-no-download-url", http.StatusBadRequest)
return
}
// Blocks while update is happening
result := <-RunUpdate(&message)
if result.Error != nil {
renderJsonError(resp, request, "update-error-download", http.StatusInternalServerError)
return
} else if result.RecoverError != nil {
renderJsonError(resp, request, "update-recover-error", http.StatusInternalServerError)
return
}
resp.Write([]byte(fmt.Sprintf("{\"status\":\"installed\"}")))
return
}
func RunUpdate(request *UpdateExecutableRequest) <-chan UpdateResult {
resultChan := make(chan UpdateResult)
go func() {
updater := update.New()
glog.Infoln("Starting update executable from", request.DownloadUrl)
err, recoverErr := updater.FromUrl(request.DownloadUrl)
if err != nil {
glog.Warningln("update-executable-error", err)
}
resultChan <- UpdateResult{
Error: err,
RecoverError: recoverErr,
}
}()
return resultChan
}
func renderJsonError(resp http.ResponseWriter, req *http.Request, message string, code int) (err error) {
resp.WriteHeader(code)
resp.Write([]byte(fmt.Sprintf("{\"error\":\"%s\"}", message)))
return
}