forked from canonical/snapd
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstore.go
More file actions
1430 lines (1218 loc) · 37.5 KB
/
Copy pathstore.go
File metadata and controls
1430 lines (1218 loc) · 37.5 KB
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2016-2020 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package store
import (
"bufio"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/gorilla/mux"
"github.com/snapcore/snapd/asserts"
"github.com/snapcore/snapd/asserts/sysdb"
"github.com/snapcore/snapd/asserts/systestkeys"
"github.com/snapcore/snapd/logger"
"github.com/snapcore/snapd/snap"
"github.com/snapcore/snapd/snap/snapfile"
"github.com/snapcore/snapd/snapdenv"
"github.com/snapcore/snapd/store"
)
func rootEndpoint(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(418)
fmt.Fprintf(w, "I'm a teapot")
}
func hexify(in string) string {
bs, err := base64.RawURLEncoding.DecodeString(in)
if err != nil {
panic(err)
}
return fmt.Sprintf("%x", bs)
}
type snapCachedInfo struct {
info *snap.Info
err error
}
// Store is our snappy software store implementation
type Store struct {
lock sync.Mutex
url string
blobDir string
assertDir string
assertFallback bool
fallback *store.Store
srv *http.Server
channelRepository *ChannelRepository
snapsCache map[string]snapCachedInfo
// endpoint -> quota value, note this is stateful, i.e. the quota is counted
// for all requests to a given endpoint and after exceeding it, all
// subsequent requests will fail until it is reset through a request
killAfter map[string]int64
}
type wrappedWriter struct {
http.ResponseWriter
s int
}
func (w *wrappedWriter) WriteHeader(s int) {
w.s = s
w.ResponseWriter.WriteHeader(s)
}
func logit(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ww := &wrappedWriter{ResponseWriter: w}
t0 := time.Now()
next.ServeHTTP(ww, r)
t := time.Since(t0)
logger.Noticef("%s %s %s %s %d", r.RemoteAddr, r.Method, r.URL, t, ww.s)
})
}
func logRangeHeader(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if len(r.Header["Range"]) > 0 {
logger.Noticef(`%s %s %s range request %v`, r.RemoteAddr, r.Method, r.URL, r.Header["Range"])
}
next.ServeHTTP(w, r)
})
}
// NewStore creates a new store server serving snaps from the given top directory and assertions from topDir/asserts. If assertFallback is true missing assertions are looked up in the main online store.
func NewStore(topDir, addr string, assertFallback bool) *Store {
r := mux.NewRouter()
var sto *store.Store
if assertFallback {
snapdenv.SetUserAgentFromVersion("unknown", nil, "fakestore")
sto = store.New(nil, nil)
}
store := &Store{
blobDir: topDir,
assertDir: filepath.Join(topDir, "asserts"),
assertFallback: assertFallback,
fallback: sto,
url: fmt.Sprintf("http://%s", addr),
srv: &http.Server{
Addr: addr,
Handler: r,
},
channelRepository: &ChannelRepository{
rootDir: filepath.Join(topDir, "channels"),
},
snapsCache: make(map[string]snapCachedInfo),
killAfter: make(map[string]int64),
}
r.Use(logit)
r.Use(store.applyKillAfter)
r.HandleFunc("/", rootEndpoint)
r.HandleFunc("/api/v1/snaps/search", store.searchEndpoint)
r.HandleFunc("/api/v1/snaps/details/{name}", store.detailsEndpoint).Methods("GET")
r.HandleFunc("/api/v1/snaps/metadata", store.bulkEndpoint).Methods("POST")
fileServer := http.StripPrefix("/download/", http.FileServer(http.Dir(topDir)))
dr := r.PathPrefix("/download/").Subrouter()
dr.Use(logRangeHeader)
dr.PathPrefix("/").HandlerFunc(fileServer.ServeHTTP).Methods("GET")
r.HandleFunc("/api/v1/snaps/auth/nonces", store.nonceEndpoint)
r.HandleFunc("/api/v1/snaps/auth/sessions", store.sessionEndpoint)
// v2
// TODO: use path vars for assertion type
r.PathPrefix("/v2/assertions/").HandlerFunc(store.assertionsEndpoint).Methods("GET")
r.HandleFunc("/v2/snaps/refresh", store.snapActionEndpoint)
// TODO use path vars for brand and repair IDs
r.PathPrefix("/v2/repairs/").HandlerFunc(store.repairsEndpoint).Methods("GET")
r.HandleFunc("/debug", store.debugEndpoint).Methods("GET", "POST")
return store
}
// URL returns the base-url that the store is listening on
func (s *Store) URL() string {
return s.url
}
func (s *Store) RealURL(req *http.Request) string {
if req.Host == "" {
return s.url
} else {
return fmt.Sprintf("http://%s", req.Host)
}
}
func (s *Store) SnapsDir() string {
return s.blobDir
}
// Start listening
func (s *Store) Start() error {
l, err := net.Listen("tcp", s.srv.Addr)
if err != nil {
return err
}
s.url = fmt.Sprintf("http://%s", l.Addr())
go s.srv.Serve(l)
return nil
}
// Stop stops the server
func (s *Store) Stop() error {
timeoutTime := 2000 * time.Millisecond
ctx, cancel := context.WithTimeout(context.Background(), timeoutTime)
defer cancel()
if err := s.srv.Shutdown(ctx); err != nil {
// forceful close
s.srv.Close()
return fmt.Errorf("store failed to stop after: %s", timeoutTime)
}
return nil
}
var (
defaultDeveloper = "canonical"
defaultDeveloperID = "canonical"
defaultRevision = 424242
)
func makeRevision(info *snap.Info) int {
// TODO: This is a hack to ensure we have higher
// revisions here than locally. The fake
// snaps get versions like
// "1.0+fake1+fake1+fake1"
// so we can use this for now to generate
// fake revisions. However in the longer
// term we should read the real revision
// of the snap, increment and add a ".aux"
// file to the download directory of the
// store that contains the revision and the
// developer. The fake-store can then read
// that file when sending the reply.
n := strings.Count(info.Version, "+fake") + 1
return n * defaultRevision
}
type essentialInfo struct {
Name string
SnapID string
DeveloperID string
DevelName string
Revision int
Version string
Size uint64
Digest string
Confinement string
Type string
Base string
}
func (s *Store) snapEssentialInfo(fn, snapID string, bs asserts.Backstore) (*essentialInfo, error) {
restoreSanitize := snap.MockSanitizePlugsSlots(func(snapInfo *snap.Info) {})
defer restoreSanitize()
cached, isCached := s.snapsCache[fn]
if !isCached {
f, err := snapfile.Open(fn)
if err != nil {
return nil, fmt.Errorf("cannot read: %v: %v", fn, err)
}
info, err := snap.ReadInfoFromSnapFile(f, nil)
cached.info = info
cached.err = err
s.snapsCache[fn] = cached
}
if cached.err != nil {
return nil, fmt.Errorf("cannot get info for: %v: %v", fn, cached.err)
}
snapDigest, size, err := asserts.SnapFileSHA3_384(fn)
if err != nil {
return nil, fmt.Errorf("cannot get digest for: %v: %v", fn, err)
}
snapRev, devAcct, err := findSnapRevision(snapDigest, bs)
if err != nil && !errors.Is(err, &asserts.NotFoundError{}) {
return nil, fmt.Errorf("cannot get info for: %v: %v", fn, err)
}
var devel, develID string
var revision int
if snapRev != nil {
snapID = snapRev.SnapID()
develID = snapRev.DeveloperID()
devel = devAcct.Username()
revision = snapRev.SnapRevision()
} else {
// XXX: fallback until we are always assertion based
develID = defaultDeveloperID
devel = defaultDeveloper
revision = makeRevision(cached.info)
}
return &essentialInfo{
Name: cached.info.SnapName(),
SnapID: snapID,
DeveloperID: develID,
DevelName: devel,
Revision: revision,
Version: cached.info.Version,
Digest: snapDigest,
Size: size,
Confinement: string(cached.info.Confinement),
Type: string(cached.info.Type()),
Base: cached.info.Base,
}, nil
}
func addComponentBlobToRevisionSet(snaps map[string]*revisionSet, snapIDs map[string]string, fn string, bs asserts.Backstore) error {
f, err := snapfile.Open(fn)
if err != nil {
return fmt.Errorf("cannot read: %v: %v", fn, err)
}
info, err := snap.ReadComponentInfoFromContainer(f, nil, nil)
if err != nil {
return fmt.Errorf("cannot get info for: %v: %v", fn, err)
}
compName := info.Component.ComponentName
snapName := info.Component.SnapName
digest, _, err := asserts.SnapFileSHA3_384(fn)
if err != nil {
return fmt.Errorf("cannot get digest for: %v: %v", fn, err)
}
set, ok := snaps[snapName]
if !ok {
return fmt.Errorf("cannot find snap %q for component: %q", snapName, info.Component)
}
snapID, ok := snapIDs[snapName]
if !ok {
return fmt.Errorf("cannot find snap id for snap %q", snapName)
}
pk, err := asserts.PrimaryKeyFromHeaders(asserts.SnapResourceRevisionType, map[string]string{
"snap-id": snapID,
"resource-name": compName,
"resource-sha3-384": digest,
})
if err != nil {
return err
}
a, err := bs.Get(asserts.SnapResourceRevisionType, pk, asserts.SnapResourceRevisionType.MaxSupportedFormat())
if err != nil {
return err
}
compRev := snap.R(a.(*asserts.SnapResourceRevision).ResourceRevision())
for snapRev := range set.revisions {
pk, err := asserts.PrimaryKeyFromHeaders(asserts.SnapResourcePairType, map[string]string{
"resource-name": compName,
"snap-id": snapID,
"resource-revision": compRev.String(),
"snap-revision": snapRev.String(),
})
if err != nil {
return err
}
_, err = bs.Get(asserts.SnapResourcePairType, pk, asserts.SnapResourcePairType.MaxSupportedFormat())
if err != nil {
// no pair assertion for this snap revision, so this one isn't
// associated with this snap revision
if errors.Is(err, &asserts.NotFoundError{}) {
continue
}
return err
}
if err := set.addComponent(compName, compRev, fn, snapRev); err != nil {
return err
}
}
return nil
}
type detailsReplyJSON struct {
Architectures []string `json:"architecture"`
SnapID string `json:"snap_id"`
PackageName string `json:"package_name"`
Developer string `json:"origin"`
DeveloperID string `json:"developer_id"`
AnonDownloadURL string `json:"anon_download_url"`
DownloadURL string `json:"download_url"`
Version string `json:"version"`
Revision int `json:"revision"`
DownloadDigest string `json:"download_sha3_384"`
Confinement string `json:"confinement"`
Type string `json:"type"`
Base string `json:"base,omitempty"`
}
type killAfterWriter struct {
http.ResponseWriter
path string
consumeQuota func(want int) int
}
func (kaw *killAfterWriter) Write(p []byte) (int, error) {
toWrite := p
shouldKill := false
got := kaw.consumeQuota(len(toWrite))
if len(p) > got {
// write only up to the remaining quota
toWrite = p[:got]
shouldKill = true
}
n, err := kaw.ResponseWriter.Write(toWrite)
if shouldKill {
logger.Noticef("request to %s was force killed, quota exceeded", kaw.path)
kaw.hijackAndClose()
return n, fmt.Errorf("connection killed")
}
return n, err
}
func (kaw *killAfterWriter) hijackAndClose() {
// flush any buffered data before closing
if f, ok := kaw.ResponseWriter.(http.Flusher); ok {
f.Flush()
}
// and proceed to close
hj, ok := kaw.ResponseWriter.(http.Hijacker)
if ok {
conn, _, _ := hj.Hijack()
conn.Close()
}
}
type debugRequestJSON struct {
Action string `json:"action"`
KillPath string `json:"kill-path"`
KillAfter int64 `json:"kill-after"`
}
type debugResultJSON struct {
KillAfter map[string]int64 `json:"kill-after"`
}
func (s *Store) debugEndpoint(w http.ResponseWriter, req *http.Request) {
if req.Method == http.MethodGet {
out, err := func() ([]byte, error) {
s.lock.Lock()
defer s.lock.Unlock()
res := debugResultJSON{
KillAfter: s.killAfter,
}
return json.Marshal(res)
}()
if err != nil {
http.Error(w, fmt.Sprintf("cannot marshal: %v", err), 500)
return
}
w.WriteHeader(200)
w.Write(out)
return
}
if req.Method != http.MethodPost {
w.WriteHeader(405) // Method Not Allowed
return
}
var debugReq *debugRequestJSON
decoder := json.NewDecoder(req.Body)
if err := decoder.Decode(&debugReq); err != nil {
http.Error(w, fmt.Sprintf("cannot decode request body: %v", err), 400)
return
}
var err error
switch debugReq.Action {
case "kill-request":
err = s.debugActionKillDownload(debugReq)
case "reset":
s.debugActionReset(debugReq)
default:
err = fmt.Errorf("unexpected debug action %q", debugReq.Action)
}
if err != nil {
w.WriteHeader(400)
fmt.Fprint(w, err.Error())
} else {
w.WriteHeader(200)
}
}
func (s *Store) debugActionKillDownload(debugReq *debugRequestJSON) error {
if debugReq.KillPath == "" {
return fmt.Errorf("kill-path cannot be empty")
}
if strings.HasPrefix(debugReq.KillPath, "/debug/") {
return fmt.Errorf("kill-path cannot be applied to /debug/ endpoints")
}
s.lock.Lock()
defer s.lock.Unlock()
if debugReq.KillAfter == 0 {
delete(s.killAfter, debugReq.KillPath)
} else {
s.killAfter[debugReq.KillPath] = debugReq.KillAfter
}
return nil
}
func (s *Store) debugActionReset(_ *debugRequestJSON) {
s.lock.Lock()
defer s.lock.Unlock()
s.killAfter = map[string]int64{}
}
func (s *Store) applyKillAfter(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
path := req.URL.Path
exists := func() bool {
s.lock.Lock()
defer s.lock.Unlock()
_, ok := s.killAfter[path]
return ok
}()
if exists {
kaw := &killAfterWriter{
ResponseWriter: w,
path: path,
consumeQuota: func(want int) int {
s.lock.Lock()
defer s.lock.Unlock()
v, ok := s.killAfter[path]
if !ok {
// no quota set
return want
}
left := int(v)
var got int
if want > left {
got = left
left = 0
} else {
got = want
left -= want
}
s.killAfter[path] = int64(left)
return got
},
}
w = kaw
}
next.ServeHTTP(w, req)
})
}
func (s *Store) searchEndpoint(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(501)
fmt.Fprintf(w, "search not implemented")
}
func (s *Store) repairsEndpoint(w http.ResponseWriter, req *http.Request) {
brandAndRepairID := strings.Split(strings.TrimPrefix(req.URL.Path, "/v2/repairs/"), "/")
if len(brandAndRepairID) != 2 {
http.Error(w, "missing brand and repair ID", 400)
return
}
bs, err := s.collectAssertions()
if err != nil {
http.Error(w, fmt.Sprintf("internal error collecting assertions: %v", err), 500)
return
}
a, err := s.retrieveAssertion(bs, asserts.RepairType, brandAndRepairID)
if errors.Is(err, &asserts.NotFoundError{}) {
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(404)
w.Write([]byte(`{"status": 404}`))
return
}
if err != nil {
http.Error(w, fmt.Sprintf("cannot retrieve repair assertion %v: %v", brandAndRepairID, err), 400)
return
}
// handle If-None-Match caching
revNumString := req.Header.Get("If-None-Match")
if revNumString != "" {
revRegexp := regexp.MustCompile(`^"([0-9]+)"$`)
match := revRegexp.FindStringSubmatch(revNumString)
if match == nil || len(match) != 2 {
http.Error(w, fmt.Sprintf("malformed If-None-Match header (%q): must be repair revision number in quotes", revNumString), 400)
return
}
revNum, err := strconv.Atoi(match[1])
if err != nil {
http.Error(w, fmt.Sprintf("malformed If-None-Match header (%q): %v", revNumString, err), 400)
return
}
if revNum == a.Revision() {
// if the If-None-Match header is the assertion revision verbatim
// then return 304 (Not Modified) and stop
w.WriteHeader(304)
return
}
}
// there are two cases, one where we are asked for the full assertion, and
// one where we are asked for JSON headers of the assertion, so check which
// one we were asked for by inspecting the Accept header
switch accept := req.Header.Get("Accept"); accept {
case "application/json":
// headers only
headers := a.Headers()
// we have to wrap the headers in a JSON object under the key
// "headers"
resp := map[string]any{
"headers": headers,
}
b, err := json.Marshal(resp)
if err != nil {
http.Error(w, fmt.Sprintf("internal error collecting assertion headers as json: %v", err), 500)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
w.Write(b)
case "application/x.ubuntu.assertion":
// full assertion
w.Header().Set("Content-Type", asserts.MediaType)
w.WriteHeader(200)
w.Write(asserts.Encode(a))
default:
http.Error(w, fmt.Sprintf("unsupported Accept format (%q): only application/json and application/x.ubuntu.assertion is support", accept), 400)
}
}
func (s *Store) detailsEndpoint(w http.ResponseWriter, req *http.Request) {
pkg := mux.Vars(req)["name"]
bs, err := s.collectAssertions()
if err != nil {
http.Error(w, fmt.Sprintf("internal error collecting assertions: %v", err), 500)
return
}
snaps, err := s.collectSnaps(bs)
if err != nil {
http.Error(w, fmt.Sprintf("internal error collecting snaps: %v", err), 500)
return
}
set, ok := snaps[pkg]
if !ok {
http.NotFound(w, req)
return
}
sn := set.getLatest()
essInfo, err := s.snapEssentialInfo(sn.path, "", bs)
if err != nil {
http.Error(w, err.Error(), 400)
return
}
details := detailsReplyJSON{
Architectures: []string{"all"},
SnapID: essInfo.SnapID,
PackageName: essInfo.Name,
Developer: essInfo.DevelName,
DeveloperID: essInfo.DeveloperID,
AnonDownloadURL: fmt.Sprintf("%s/download/%s", s.RealURL(req), filepath.Base(sn.path)),
DownloadURL: fmt.Sprintf("%s/download/%s", s.RealURL(req), filepath.Base(sn.path)),
Version: essInfo.Version,
Revision: essInfo.Revision,
DownloadDigest: hexify(essInfo.Digest),
Confinement: essInfo.Confinement,
Type: essInfo.Type,
Base: essInfo.Base,
}
// use indent because this is a development tool, output
// should look nice
out, err := json.MarshalIndent(details, "", " ")
if err != nil {
http.Error(w, fmt.Sprintf("cannot marshal: %v: %v", details, err), 400)
return
}
w.Write(out)
}
type revisionSet struct {
latest snap.Revision
revisions map[snap.Revision]availableSnap
}
type availableSnap struct {
path string
components map[string]availableComponent
}
type availableComponent struct {
path string
revision snap.Revision
}
func (rs *revisionSet) get(rev snap.Revision) (availableSnap, bool) {
if rev.Unset() {
rev = rs.latest
}
sn, ok := rs.revisions[rev]
return sn, ok
}
func (rs *revisionSet) getLatest() availableSnap {
sn, ok := rs.revisions[rs.latest]
if !ok {
panic("internal error: revision set should always contain latest revision")
}
return sn
}
func (rs *revisionSet) add(rev snap.Revision, path string) {
if rs.revisions == nil {
rs.revisions = make(map[snap.Revision]availableSnap)
}
if rs.latest.N < rev.N {
rs.latest = rev
}
rs.revisions[rev] = availableSnap{path: path, components: make(map[string]availableComponent)}
}
func (rs *revisionSet) addComponent(name string, compRev snap.Revision, path string, snapRev snap.Revision) error {
sn, ok := rs.revisions[snapRev]
if !ok {
return fmt.Errorf("cannot find snap revision %q", snapRev)
}
sn.components[name] = availableComponent{path: path, revision: compRev}
return nil
}
func (s *Store) collectSnaps(bs asserts.Backstore) (map[string]*revisionSet, error) {
snapFns, err := filepath.Glob(filepath.Join(s.blobDir, "*.snap"))
if err != nil {
return nil, err
}
restoreSanitize := snap.MockSanitizePlugsSlots(func(snapInfo *snap.Info) {})
defer restoreSanitize()
snaps := make(map[string]*revisionSet)
snapNamesToID := make(map[string]string, len(snapFns))
for _, fn := range snapFns {
// if the snap is asserted, then the returned info will contain the ID
// taken from the database
const snapID = ""
info, err := s.snapEssentialInfo(fn, snapID, bs)
if err != nil {
return nil, err
}
if _, ok := snaps[info.Name]; !ok {
snaps[info.Name] = &revisionSet{}
}
snaps[info.Name].add(snap.R(info.Revision), fn)
channels, err := s.channelRepository.findSnapChannels(info.Digest)
if err != nil {
return nil, err
}
for _, channel := range channels {
compositeName := fmt.Sprintf("%s|%s", info.Name, channel)
if _, ok := snaps[compositeName]; !ok {
snaps[compositeName] = &revisionSet{}
}
snaps[compositeName].add(snap.R(info.Revision), fn)
}
if info.SnapID != "" {
snapNamesToID[info.Name] = info.SnapID
}
logger.Debugf("found snap %q (revision %d) at %v", info.Name, info.Revision, fn)
}
compFns, err := filepath.Glob(filepath.Join(s.blobDir, "*.comp"))
if err != nil {
return nil, err
}
for _, fn := range compFns {
if err := addComponentBlobToRevisionSet(snaps, snapNamesToID, fn, bs); err != nil {
return nil, err
}
}
return snaps, err
}
type candidateSnap struct {
SnapID string `json:"snap_id"`
}
type bulkReqJSON struct {
CandidateSnaps []candidateSnap `json:"snaps"`
Fields []string `json:"fields"`
}
type payload struct {
Packages []detailsReplyJSON `json:"clickindex:package"`
}
type bulkReplyJSON struct {
Payload payload `json:"_embedded"`
}
var someSnapIDtoName = map[string]map[string]string{
"production": {
"b8X2psL1ryVrPt5WEmpYiqfr5emixTd7": "ubuntu-core",
"99T7MUlRhtI3U0QFgl5mXXESAiSwt776": "core",
"bul8uZn9U3Ll4ke6BMqvNVEZjuJCSQvO": "canonical-pc",
"SkKeDk2PRgBrX89DdgULk3pyY5DJo6Jk": "canonical-pc-linux",
"eFe8BTR5L5V9F7yHeMAPxkEr2NdUXMtw": "test-snapd-tools",
"Wcs8QL2iRQMjsPYQ4qz4V1uOlElZ1ZOb": "test-snapd-python-webserver",
"DVvhXhpa9oJjcm0rnxfxftH1oo5vTW1M": "test-snapd-go-webserver",
},
"staging": {
"xMNMpEm0COPZy7jq9YRwWVLCD9q5peow": "core",
"02AHdOomTzby7gTaiLX3M3SGMmXDfLJp": "test-snapd-tools",
"uHjTANBWSXSiYzNOUXZNDnOSH3POSqWS": "test-snapd-python-webserver",
"edmdK5G9fP1q1bGyrjnaDXS4RkdjiTGV": "test-snapd-go-webserver",
},
}
func (s *Store) bulkEndpoint(w http.ResponseWriter, req *http.Request) {
var pkgs bulkReqJSON
var replyData bulkReplyJSON
decoder := json.NewDecoder(req.Body)
if err := decoder.Decode(&pkgs); err != nil {
http.Error(w, fmt.Sprintf("cannot decode request body: %v", err), 400)
return
}
bs, err := s.collectAssertions()
if err != nil {
http.Error(w, fmt.Sprintf("internal error collecting assertions: %v", err), 500)
return
}
var remoteStore string
if snapdenv.UseStagingStore() {
remoteStore = "staging"
} else {
remoteStore = "production"
}
snapIDtoName, err := addSnapIDs(bs, someSnapIDtoName[remoteStore])
if err != nil {
http.Error(w, fmt.Sprintf("internal error collecting snapIDs: %v", err), 500)
return
}
snaps, err := s.collectSnaps(bs)
if err != nil {
http.Error(w, fmt.Sprintf("internal error collecting snaps: %v", err), 500)
return
}
// check if we have downloadable snap of the given SnapID
for _, pkg := range pkgs.CandidateSnaps {
name := snapIDtoName[pkg.SnapID]
if name == "" {
http.Error(w, fmt.Sprintf("unknown snap-id: %q", pkg.SnapID), 400)
return
}
set, ok := snaps[name]
if !ok {
continue
}
sn := set.getLatest()
essInfo, err := s.snapEssentialInfo(sn.path, pkg.SnapID, bs)
if err != nil {
http.Error(w, err.Error(), 400)
return
}
replyData.Payload.Packages = append(replyData.Payload.Packages, detailsReplyJSON{
Architectures: []string{"all"},
SnapID: essInfo.SnapID,
PackageName: essInfo.Name,
Developer: essInfo.DevelName,
DeveloperID: essInfo.DeveloperID,
DownloadURL: fmt.Sprintf("%s/download/%s", s.RealURL(req), filepath.Base(sn.path)),
AnonDownloadURL: fmt.Sprintf("%s/download/%s", s.RealURL(req), filepath.Base(sn.path)),
Version: essInfo.Version,
Revision: essInfo.Revision,
DownloadDigest: hexify(essInfo.Digest),
Confinement: essInfo.Confinement,
Type: essInfo.Type,
Base: essInfo.Base,
})
}
// use indent because this is a development tool, output
// should look nice
out, err := json.MarshalIndent(replyData, "", " ")
if err != nil {
http.Error(w, fmt.Sprintf("cannot marshal: %v: %v", replyData, err), 400)
return
}
w.Write(out)
}
func (s *Store) collectAssertions() (asserts.Backstore, error) {
bs := asserts.NewMemoryBackstore()
add := func(a asserts.Assertion) {
if err := bs.Put(a.Type(), a); err != nil {
logger.Noticef("cannot add assertion %q: %v", a.Headers(), err)
}
}
for _, t := range sysdb.Trusted() {
add(t)
}
add(systestkeys.TestRootAccount)
add(systestkeys.TestRootAccountKey)
add(systestkeys.TestStoreAccountKey)
aFiles, err := filepath.Glob(filepath.Join(s.assertDir, "*"))
if err != nil {
return nil, err
}
for _, fn := range aFiles {
b, err := os.ReadFile(fn)
if err != nil {
return nil, err
}
a, err := asserts.Decode(b)
if err != nil {
return nil, err
}
add(a)
}
return bs, nil
}
type currentSnap struct {
SnapID string `json:"snap-id"`
InstanceKey string `json:"instance-key"`
TrackingChannel string `json:"tracking-channel"`
}
type snapAction struct {
Action string `json:"action"`
InstanceKey string `json:"instance-key"`
SnapID string `json:"snap-id"`