-
Notifications
You must be signed in to change notification settings - Fork 308
/
local_manifests.go
385 lines (331 loc) · 10.9 KB
/
local_manifests.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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
// Copyright 2020 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.
package v1manifest
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
cjson "github.com/gibson042/canonicaljson-go"
"github.com/pingcap/errors"
"github.com/pingcap/tiup/pkg/localdata"
"github.com/pingcap/tiup/pkg/utils"
)
// LocalManifests methods for accessing a store of manifests.
type LocalManifests interface {
// SaveManifest saves a manifest to disk, it will overwrite filename if it exists.
SaveManifest(manifest *Manifest, filename string) error
// SaveComponentManifest saves a component manifest to disk, it will overwrite filename if it exists.
SaveComponentManifest(manifest *Manifest, filename string) error
// LoadManifest loads and validates the most recent manifest of role's type. The returned bool is true if the file
// exists.
LoadManifest(role ValidManifest) (*Manifest, bool, error)
// LoadComponentManifest loads and validates the most recent manifest at filename.
LoadComponentManifest(item *ComponentItem, filename string) (*Component, error)
// ComponentInstalled is true if the version of component is present locally.
ComponentInstalled(component, version string) (bool, error)
// InstallComponent installs the component from the reader.
InstallComponent(reader io.Reader, targetDir, component, version, filename string, noExpand bool) error
// Return the local key store.
KeyStore() *KeyStore
// ManifestVersion opens filename, if it exists and is a manifest, returns its manifest version number. Otherwise
// returns 0.
ManifestVersion(filename string) uint
}
// FsManifests represents a collection of v1 manifests on disk.
// Invariant: any manifest written to disk should be valid, but may have expired. (It is also possible the manifest was
// ok when written and has expired since).
type FsManifests struct {
profile *localdata.Profile
keys *KeyStore
cache map[string]string
}
// FIXME implement garbage collection of old manifests
// NewManifests creates a new FsManifests with local store at root.
// There must exist a trusted root.json.
func NewManifests(profile *localdata.Profile) (*FsManifests, error) {
result := &FsManifests{profile: profile, keys: NewKeyStore(), cache: make(map[string]string)}
// Load the root manifest.
manifest, err := result.load(ManifestFilenameRoot)
if err != nil {
return nil, errors.AddStack(err)
}
// We must load without validation because we have no keys yet.
var root Root
err = ReadNoVerify(strings.NewReader(manifest), &root)
if err != nil {
return nil, errors.AddStack(err)
}
// Populate our key store from the root manifest.
err = loadKeys(&root, result.keys)
if err != nil {
return nil, errors.AddStack(err)
}
// Now that we've bootstrapped the key store, we can verify the root manifest we loaded earlier.
_, err = ReadManifest(strings.NewReader(manifest), &root, result.keys)
if err != nil {
return nil, errors.AddStack(err)
}
result.cache[ManifestFilenameRoot] = manifest
return result, nil
}
// SaveManifest implements LocalManifests.
func (ms *FsManifests) SaveManifest(manifest *Manifest, filename string) error {
err := ms.save(manifest, filename)
if err != nil {
return err
}
return loadKeys(manifest.Signed, ms.keys)
}
// SaveComponentManifest implements LocalManifests.
func (ms *FsManifests) SaveComponentManifest(manifest *Manifest, filename string) error {
return ms.save(manifest, filename)
}
func (ms *FsManifests) save(manifest *Manifest, filename string) error {
bytes, err := cjson.Marshal(manifest)
if err != nil {
return err
}
// Save all manifests in `$TIUP_HOME/manifests`
path := filepath.Join(ms.profile.Root(), localdata.ManifestParentDir, filename)
// create sub directory if needed
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
return errors.Trace(err)
}
err = ioutil.WriteFile(path, bytes, 0644)
if err != nil {
return err
}
ms.cache[filename] = string(bytes)
return nil
}
// LoadManifest implements LocalManifests.
func (ms *FsManifests) LoadManifest(role ValidManifest) (*Manifest, bool, error) {
filename := role.Filename()
manifest, err := ms.load(filename)
if err != nil || manifest == "" {
return nil, false, err
}
m, err := ReadManifest(strings.NewReader(manifest), role, ms.keys)
if err != nil {
return m, true, err
}
ms.cache[filename] = manifest
return m, true, loadKeys(role, ms.keys)
}
// LoadComponentManifest implements LocalManifests.
func (ms *FsManifests) LoadComponentManifest(item *ComponentItem, filename string) (*Component, error) {
manifest, err := ms.load(filename)
if err != nil || manifest == "" {
return nil, err
}
component := new(Component)
_, err = ReadComponentManifest(strings.NewReader(manifest), component, item, ms.keys)
if err != nil {
return nil, err
}
ms.cache[filename] = manifest
return component, nil
}
// load return the file for the manifest from disk.
// The returned string is empty if the file does not exist.
func (ms *FsManifests) load(filename string) (string, error) {
str, cached := ms.cache[filename]
if cached {
return str, nil
}
fullPath := filepath.Join(ms.profile.Root(), localdata.ManifestParentDir, filename)
file, err := os.Open(fullPath)
if err != nil {
if os.IsNotExist(err) {
// Use the hardcode root.json if there is no root.json currently
if filename == ManifestFilenameRoot {
initRoot, err := filepath.Abs(filepath.Join(ms.profile.Root(), "bin/root.json"))
if err != nil {
return "", errors.Trace(err)
}
bytes, err := ioutil.ReadFile(initRoot)
if err != nil {
return "", errors.Errorf("cannot open the initial root.json at %s", initRoot)
}
return string(bytes), nil
}
return "", nil
}
return "", err
}
defer file.Close()
builder := strings.Builder{}
_, err = io.Copy(&builder, file)
if err != nil {
return "", errors.AddStack(err)
}
return builder.String(), nil
}
// ComponentInstalled implements LocalManifests.
func (ms *FsManifests) ComponentInstalled(component, version string) (bool, error) {
return ms.profile.VersionIsInstalled(component, version)
}
// InstallComponent implements LocalManifests.
func (ms *FsManifests) InstallComponent(reader io.Reader, targetDir, component, version, filename string, noExpand bool) error {
// TODO factor path construction to profile (also used by v0 repo).
if targetDir == "" {
targetDir = ms.profile.Path(localdata.ComponentParentDir, component, version)
}
if !noExpand {
return utils.Untar(reader, targetDir)
}
if err := os.MkdirAll(targetDir, 0755); err != nil {
return errors.Trace(err)
}
writer, err := os.OpenFile(filepath.Join(targetDir, filename), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
if err != nil {
return errors.Trace(err)
}
defer writer.Close()
if _, err = io.Copy(writer, reader); err != nil {
return errors.Trace(err)
}
return nil
}
// KeyStore implements LocalManifests.
func (ms *FsManifests) KeyStore() *KeyStore {
return ms.keys
}
// ManifestVersion implements LocalManifests.
func (ms *FsManifests) ManifestVersion(filename string) uint {
data, err := ms.load(filename)
if err != nil {
return 0
}
var manifest RawManifest
err = json.Unmarshal([]byte(data), &manifest)
if err != nil {
return 0
}
var base SignedBase
err = json.Unmarshal(manifest.Signed, &base)
if err != nil {
return 0
}
return base.Version
}
// MockManifests is a LocalManifests implementation for testing.
type MockManifests struct {
Manifests map[string]*Manifest
Saved []string
Installed map[string]MockInstalled
Ks *KeyStore
}
// MockInstalled is used by MockManifests to remember what was installed for a component.
type MockInstalled struct {
Version string
Contents string
}
// NewMockManifests creates an empty MockManifests.
func NewMockManifests() *MockManifests {
return &MockManifests{
Manifests: map[string]*Manifest{},
Saved: []string{},
Installed: map[string]MockInstalled{},
Ks: NewKeyStore(),
}
}
// SaveManifest implements LocalManifests.
func (ms *MockManifests) SaveManifest(manifest *Manifest, filename string) error {
ms.Saved = append(ms.Saved, filename)
ms.Manifests[filename] = manifest
return loadKeys(manifest.Signed, ms.Ks)
}
// SaveComponentManifest implements LocalManifests.
func (ms *MockManifests) SaveComponentManifest(manifest *Manifest, filename string) error {
ms.Saved = append(ms.Saved, filename)
ms.Manifests[filename] = manifest
return nil
}
// LoadManifest implements LocalManifests.
func (ms *MockManifests) LoadManifest(role ValidManifest) (*Manifest, bool, error) {
manifest, ok := ms.Manifests[role.Filename()]
if !ok {
return nil, false, nil
}
switch role.Filename() {
case ManifestFilenameRoot:
ptr := role.(*Root)
*ptr = *manifest.Signed.(*Root)
case ManifestFilenameIndex:
ptr := role.(*Index)
*ptr = *manifest.Signed.(*Index)
case ManifestFilenameSnapshot:
ptr := role.(*Snapshot)
*ptr = *manifest.Signed.(*Snapshot)
case ManifestFilenameTimestamp:
ptr := role.(*Timestamp)
*ptr = *manifest.Signed.(*Timestamp)
default:
return nil, true, fmt.Errorf("unknown manifest type: %s", role.Filename())
}
err := loadKeys(role, ms.Ks)
if err != nil {
return nil, false, errors.AddStack(err)
}
return manifest, true, nil
}
// LoadComponentManifest implements LocalManifests.
func (ms *MockManifests) LoadComponentManifest(item *ComponentItem, filename string) (*Component, error) {
manifest, ok := ms.Manifests[filename]
if !ok {
return nil, nil
}
comp, ok := manifest.Signed.(*Component)
if !ok {
return nil, fmt.Errorf("manifest %s is not a component manifest", filename)
}
return comp, nil
}
// ComponentInstalled implements LocalManifests.
func (ms *MockManifests) ComponentInstalled(component, version string) (bool, error) {
inst, ok := ms.Installed[component]
if !ok {
return false, nil
}
return inst.Version == version, nil
}
// InstallComponent implements LocalManifests.
func (ms *MockManifests) InstallComponent(reader io.Reader, targetDir string, component, version, filename string, noExpand bool) error {
buf := strings.Builder{}
_, err := io.Copy(&buf, reader)
if err != nil {
return err
}
ms.Installed[component] = MockInstalled{
Version: version,
Contents: buf.String(),
}
return nil
}
// KeyStore implements LocalManifests.
func (ms *MockManifests) KeyStore() *KeyStore {
return ms.Ks
}
// ManifestVersion implements LocalManifests.
func (ms *MockManifests) ManifestVersion(filename string) uint {
manifest, ok := ms.Manifests[filename]
if ok {
return manifest.Signed.Base().Version
}
return 0
}