forked from chuck-lee/jiri
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupdate.go
232 lines (202 loc) · 5.44 KB
/
update.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
// Copyright 2016 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package jiri
import (
"bufio"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"runtime"
"strings"
"syscall"
"fuchsia.googlesource.com/jiri/osutil"
"fuchsia.googlesource.com/jiri/version"
)
const (
JiriRepository = "https://fuchsia.googlesource.com/jiri"
JiriStorageBucket = "https://storage.googleapis.com/fuchsia-build/jiri"
)
var (
updateTestVersionErr = fmt.Errorf("jiri has test version")
updateVersionErr = fmt.Errorf("jiri is already at latest version")
updateNotAvailableErr = fmt.Errorf("latest version of jiri not available")
)
// Update checks whether a new version of Jiri is available and if so,
// it will download it and replace the current version with the new one.
func Update(force bool) error {
if !force && version.GitCommit == "" {
return updateTestVersionErr
}
commit, err := getCurrentCommit(JiriRepository)
if err != nil {
return err
}
if force || commit != version.GitCommit {
// Check if the prebuilt for new version exsits.
has, err := hasPrebuilt(JiriStorageBucket, commit)
if err != nil {
return fmt.Errorf("cannot check if prebuilt is available, %s", err)
}
if !has {
return updateNotAvailableErr
}
// New version is available, download and update to it.
b, err := downloadBinary(JiriStorageBucket, commit)
if err != nil {
return fmt.Errorf("cannot download latest jiri binary, %s", err)
}
path, err := osutil.Executable()
if err != nil {
return fmt.Errorf("cannot get executable path, %s", err)
}
return updateExecutable(path, b)
}
return updateVersionErr
}
func UpdateAndExecute(force bool) error {
// Capture executable path before it is replaced in Update func
path, err := osutil.Executable()
if err != nil {
return fmt.Errorf("cannot get executable path, %s", err)
}
if err := Update(force); err != nil {
if err != updateNotAvailableErr && err != updateVersionErr &&
err != updateTestVersionErr {
return err
} else {
return nil
}
}
args := []string{}
for _, a := range os.Args {
if !strings.HasPrefix(a, "-force-autoupdate") {
args = append(args, a)
}
}
// Run the update version.
if err = syscall.Exec(path, args, os.Environ()); err != nil {
return fmt.Errorf("cannot execute %s: %s", path, err)
}
return nil
}
func getCurrentCommit(repository string) (string, error) {
u, err := url.Parse(repository)
if err != nil {
return "", err
}
if u.Scheme != "http" && u.Scheme != "https" {
return "", fmt.Errorf("remote host scheme is not http(s): %s", repository)
}
u.Path = path.Join(u.Path, "+refs/heads/master")
q := u.Query()
q.Set("format", "json")
u.RawQuery = q.Encode()
// Use Gitiles to find out the latest revision.
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
return "", err
}
req.Header.Add("Accept", "application/json")
res, err := http.DefaultClient.Do(req)
if err != nil {
return "", err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return "", fmt.Errorf("HTTP request failed: %v", http.StatusText(res.StatusCode))
}
r := bufio.NewReader(res.Body)
// The first line of the input is the XSSI guard ")]}'".
if _, err := r.ReadSlice('\n'); err != nil {
return "", err
}
var result map[string]struct {
Value string `json:"value"`
}
if err := json.NewDecoder(r).Decode(&result); err != nil {
return "", err
}
if v, ok := result["refs/heads/master"]; ok {
return v.Value, nil
} else {
return "", fmt.Errorf("cannot find current commit")
}
}
func hasPrebuilt(bucket, version string) (bool, error) {
url := fmt.Sprintf("%s/%s-%s/%s", bucket, runtime.GOOS, runtime.GOARCH, version)
res, err := http.Head(url)
if err != nil {
return false, err
}
if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusNotFound {
return false, fmt.Errorf("HTTP request failed: %v", http.StatusText(res.StatusCode))
}
return res.StatusCode == http.StatusOK, nil
}
func downloadBinary(bucket, version string) ([]byte, error) {
url := fmt.Sprintf("%s/%s-%s/%s", bucket, runtime.GOOS, runtime.GOARCH, version)
res, err := http.Get(url)
if err != nil {
return nil, err
}
if res.StatusCode != http.StatusOK {
return nil, fmt.Errorf("HTTP request failed: %v", http.StatusText(res.StatusCode))
}
defer res.Body.Close()
bytes, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
return bytes, nil
}
func updateExecutable(path string, b []byte) error {
fi, err := os.Stat(path)
if err != nil {
return err
}
dir := filepath.Dir(path)
// Write the new version to a file.
newfile, err := ioutil.TempFile(dir, "jiri")
if err != nil {
return err
}
if _, err := newfile.Write(b); err != nil {
return err
}
if err := newfile.Chmod(fi.Mode()); err != nil {
return err
}
if err := newfile.Close(); err != nil {
return err
}
// Backup the existing version.
oldfile, err := ioutil.TempFile(dir, "jiri")
if err != nil {
return err
}
defer os.Remove(oldfile.Name())
if err := oldfile.Close(); err != nil {
return err
}
err = osutil.Rename(path, oldfile.Name())
if err != nil {
return err
}
// Replace the existing version.
err = osutil.Rename(newfile.Name(), path)
if err != nil {
// Try to rollback the change in case of error.
rerr := osutil.Rename(oldfile.Name(), path)
if rerr != nil {
return rerr
}
return err
}
return nil
}