-
Notifications
You must be signed in to change notification settings - Fork 25
/
metadata.go
916 lines (835 loc) · 26.1 KB
/
metadata.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
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
// metadata.go has functions to gather and save metadata about a Docker image, including its ID, Author, Parent,
// Creation time, etc.
package collector
import (
"bytes"
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"sort"
"strconv"
"strings"
"time"
config "github.com/banyanops/collector/config"
blog "github.com/ccpaging/log4go"
)
const (
// maxGoCount imposes a limit on number of concurrent goroutines performing registry calls.
maxGoCount = 10
minGoCount = 5
)
var (
ReposToProcess = make(map[RepoType]bool)
ExcludeRepo = func() map[RepoType]bool {
excludeList := []RepoType{} // You can add repos to this list
m := make(map[RepoType]bool)
for _, r := range excludeList {
m[r] = true
}
return m
}()
)
// ImageSet is a set of image IDs.
type ImageSet map[ImageIDType]bool
// NewImageSet creates a new ImageSet.
func NewImageSet() ImageSet {
return ImageSet(make(map[ImageIDType]bool))
}
// HubInfo records the index and auth information provided by Docker Hub to access a repository.
type HubInfo struct {
Repo RepoType
DockerToken string
RegistryURL string
}
// ImageMetadataInfo records basic information about an image.
type ImageMetadataInfo struct {
Image string //this has to be the first field (used in order by)
Datetime time.Time //created at
Repo string
Tag string
Size uint64
Author string
Checksum string
Comment string
Parent string
}
// MetadataSet is a set of Image Metadata Info structures.
type MetadataSet map[ImageMetadataInfo]bool
// ImageToMetadataMap maps image IDs to ImageMetadataInfo structs.
type ImageToMetadataMap map[ImageIDType]ImageMetadataInfo
// NewMetadataSet creates a new MetadataSet.
func NewMetadataSet() MetadataSet {
return MetadataSet(make(map[ImageMetadataInfo]bool))
}
// NewImageToMetadataMap is a constructor for ImageToMetadataMap.
func NewImageToMetadataMap() ImageToMetadataMap {
return make(map[ImageIDType]ImageMetadataInfo)
}
// Insert adds an image ID to an Image ID Map.
func (m ImageToMetadataMap) Insert(imageID ImageIDType, metadata ImageMetadataInfo) {
m[imageID] = metadata
}
// Exists checks whether an image ID is present in an ImageToMetadataMap.
func (m ImageToMetadataMap) Exists(imageID ImageIDType) bool {
_, ok := m[imageID]
return ok
}
// Metadata returns the ImageMetadataInfo corresponding to an image ID if that image
// is present in the input ImageToMetadataMap.
func (m ImageToMetadataMap) Metadata(imageID ImageIDType) (metadata ImageMetadataInfo, e error) {
metadata, ok := m[imageID]
if ok {
return
}
e = errors.New("Image " + string(imageID) + " is not in the Image Metadata Map")
return
}
// TagType represents docker repository tags.
type TagType string
// RepoType represents docker repositories.
type RepoType string
// ImageIDType represents docker image IDs.
type ImageIDType string
// TagInfo records the tag-to-image mappings for a single Docker repository.
type TagInfo struct {
Repo RepoType
TagMap map[TagType]ImageIDType
}
// RepoTagType represents a docker repository and tag.
type RepoTagType struct {
Repo RepoType
Tag TagType
}
// Docker repository description.
type repo struct {
Description string
Name string
}
// Docker registry search reply
type registrySearchResult struct {
NumResults int `json:"num_results"`
Query string `json:"query"`
Results []repo
}
// ImageStruct records information returned by the registry to describe an image.
// This information gets copied to an object of type ImageMetadataInfo.
type ImageStruct struct {
ID string
Parent string
Checksum string
Created string
// Container string
Author string
Size uint64
Comment string
}
// HubInfoMap maps repository name to the corresponding Docker Hub auth/index info.
type HubInfoMap map[RepoType]HubInfo
// NewHubInfoMap is a constructor for HubInfoMap.
func NewHubInfoMap() HubInfoMap {
return make(map[RepoType]HubInfo)
}
// ByDateTime is used to sort ImageMetadataInfo slices by image age from newest to oldest.
type ByDateTime []ImageMetadataInfo
func (a ByDateTime) Len() int {
return len(a)
}
func (a ByDateTime) Swap(i int, j int) {
a[i], a[j] = a[j], a[i]
}
func (a ByDateTime) Less(i int, j int) bool {
return a[i].Datetime.After(a[j].Datetime)
}
// GetImageToMDMap takes image metadata structs and produces a map of imageID to metadata struct.
func GetImageToMDMap(imageMDs []ImageMetadataInfo) (imageToMDMap map[string][]ImageMetadataInfo) {
imageToMDMap = make(map[string][]ImageMetadataInfo)
for _, imageMD := range imageMDs {
imageToMDMap[imageMD.Image] = append(imageToMDMap[imageMD.Image], imageMD)
}
return
}
// GetImageMetadata returns repository/tag/image metadata queried from a Docker registry.
// If the user has specified the repositories to examine, then no other repositories are examined.
// If the user has not specified repositories, then the registry search API is used to
// get the list of all repositories in the registry.
func GetImageMetadata(oldMetadataSet MetadataSet) (tagSlice []TagInfo, metadataSlice []ImageMetadataInfo) {
for {
blog.Info("Get Repos")
repoSlice, e := getRepos()
if e != nil {
blog.Warn(e, " getRepos")
blog.Warn("Retrying")
time.Sleep(config.RETRYDURATION)
continue
}
if len(repoSlice) == 0 {
// For some reason (like, registry search doesn't work), we are not
// seeing any repos in the registry.
// So, just reconstruct the list of repos that we saw earlier.
blog.Warn("Empty repoSlice, reusing previous metadata")
repomap := make(map[string]bool)
for metadata := range oldMetadataSet {
if repomap[metadata.Repo] == false {
repoSlice = append(repoSlice, RepoType(metadata.Repo))
repomap[metadata.Repo] = true
}
}
}
// Now get a list of all the tags, and the image metadata/manifest
if *RegistryProto == "v1" {
blog.Info("Get Tags")
tagSlice, e = getTags(repoSlice)
if e != nil {
blog.Warn(e, " getTags")
blog.Warn("Retrying")
time.Sleep(config.RETRYDURATION)
continue
}
blog.Info("Get Image Metadata")
// Get image metadata
metadataSlice, e = getImageMetadata(tagSlice, oldMetadataSet)
if e != nil {
blog.Warn(e, " getImageMetadata")
blog.Warn("Retrying")
time.Sleep(config.RETRYDURATION)
continue
}
break
}
if *RegistryProto == "v2" {
blog.Info("Get Tags and Metadata")
tagSlice, metadataSlice, e = v2GetTagsMetadata(repoSlice)
if e != nil {
blog.Warn(e)
blog.Warn("Retrying")
time.Sleep(config.RETRYDURATION)
continue
}
break
}
}
return
}
// GetImageMetadataHub returns repositories/tags/image metadata from the Docker Hub.
// The user must have specified a set of repositories of interest.
// The function queries Docker Hub as an index to the registries, and then retrieves
// information directly from the registries, using Docker Hub authentication tokens.
func GetImageMetadataHub(oldMetadataSet MetadataSet) (tagSlice []TagInfo, metadataSlice []ImageMetadataInfo) {
for {
blog.Info("Get Repos from Docker Hub")
hubInfoSlice, e := getReposHub()
if e != nil {
blog.Warn(e, " getReposHub")
blog.Warn("Retrying")
time.Sleep(config.RETRYDURATION)
continue
}
blog.Info("Get Tags and Metadata from Docker Hub")
// Now get a list of all the tags
tagSlice, metadataSlice, e = getTagsMetadataHub(hubInfoSlice, oldMetadataSet)
if e != nil {
blog.Warn(e, " getTagsMetadataHub")
blog.Warn("Retrying")
time.Sleep(config.RETRYDURATION)
continue
}
break
}
return
}
// getRepos queries the Docker registry for the list of the repositories it is currently hosting.
// However, if the user specified a list of repositories, then getRepos() just returns that list
// of specified repositories and does not query the Docker registry.
func getRepos() (repoSlice []RepoType, err error) {
if len(ReposToProcess) > 0 {
for repo := range ReposToProcess {
repoSlice = append(repoSlice, repo)
}
return
}
if *RegistryProto == "v2" {
blog.Error("v2 registry search/catalog interface not yet supported in collector")
return
}
// a query with an empty query string returns all the repos
client := &http.Client{}
response, err := RegistryQuery(client, RegistryAPIURL+"/v1/search?q=", BasicAuth)
if err != nil {
blog.Error(err)
if s, ok := err.(*HTTPStatusCodeError); ok {
blog.Error("HTTP bad status code %d from registry %s using --registryhttps=%v --registryauth=%v --registryproto=%s", s.StatusCode, RegistryAPIURL, *HTTPSRegistry, *AuthRegistry, *RegistryProto)
}
return
}
// parse the JSON response body and populate repo slice
var result registrySearchResult
if err = json.Unmarshal(response, &result); err != nil {
blog.Error(err, "unmarshal", string(response))
return
}
for _, elem := range result.Results {
if ExcludeRepo[RepoType(elem.Name)] {
continue
}
repoSlice = append(repoSlice, RepoType(elem.Name))
}
return
}
// getReposHub validates the user-specified list of repositories against the Docker Hub index.
// It returns a list of HubInfo structs with index info for each validated repository.
func getReposHub() (hubInfo []HubInfo, err error) {
// lookup defines a function that takes a repository name as input and returns
// the Docker auth token and registry URL to access that repository.
client := &http.Client{}
lookup := func(repo RepoType) (dockerToken, registryURL string) {
URL := RegistryAPIURL + "/v1/repositories/" + string(repo) + "/images"
req, e := http.NewRequest("GET", URL, nil)
req.Header.Set("X-Docker-Token", "true")
if BasicAuth != "" {
req.Header.Set("Authorization", "Basic "+BasicAuth)
}
r, e := client.Do(req)
if e != nil {
blog.Error(e, ":getReposHub HTTP request failed")
return
}
defer r.Body.Close()
if r.StatusCode != 200 {
blog.Error("getReposHub HTTP bad status code %d from Docker Hub", r.StatusCode)
return
}
dockerToken = r.Header.Get("X-Docker-Token")
registryURL = r.Header.Get("X-Docker-Endpoints")
arr := strings.Split(registryURL, ",")
if len(arr) == 0 {
registryURL = ""
return
}
registryURL = strings.TrimSpace(arr[0])
return
}
if len(ReposToProcess) > 0 {
for repo := range ReposToProcess {
dockerToken, registryURL := lookup(repo)
if dockerToken == "" {
blog.Error(repo, ":Could not find info for repo.")
continue
}
hubInfo = append(hubInfo,
HubInfo{Repo: repo, DockerToken: dockerToken, RegistryURL: registryURL})
}
}
return
}
func v1GetTags(repoSlice []RepoType) (tagSlice []TagInfo, e error) {
client := &http.Client{}
for _, repo := range repoSlice {
// get tags for one repo
response, err := RegistryQuery(client, RegistryAPIURL+"/v1/repositories/"+string(repo)+"/tags", BasicAuth)
if err != nil {
blog.Error(err)
if s, ok := err.(*HTTPStatusCodeError); ok {
blog.Error("Skipping Repo: %s, tag lookup status code %d", string(repo), s.StatusCode)
continue
}
return
}
//parse JSON output
var m map[TagType]ImageIDType
if e = json.Unmarshal(response, &m); e != nil {
return nil, e
}
var t TagInfo
t.Repo = repo
t.TagMap = m
tagSlice = append(tagSlice, t)
}
return
}
type V2Tag struct {
Name string
Tags []string
}
type V1Compat struct {
V1Compatibility string
}
type V2Manifest struct {
History []V1Compat
}
func v2GetMetadata(client *http.Client, repo, tag string) (metadata ImageMetadataInfo, e error) {
response, err := RegistryQuery(client, RegistryAPIURL+"/v2/"+repo+"/manifests/"+tag, BasicAuth)
if err != nil {
blog.Error(err)
if s, ok := err.(*HTTPStatusCodeError); ok {
blog.Error("Skipping Repo: %s, tag lookup status code %d", string(repo), s.StatusCode)
e = err
}
return
}
//parse JSON output
var m V2Manifest
b := bytes.NewBuffer(response)
if e = json.NewDecoder(b).Decode(&m); e != nil {
return
}
if len(m.History) == 0 {
e = errors.New("repo " + repo + ":" + tag + " no images found in history")
return
}
var image ImageStruct
if e = json.Unmarshal([]byte(m.History[0].V1Compatibility), &image); e != nil {
return
}
var creationTime time.Time
metadata.Image = image.ID
if creationTime, e = time.Parse(time.RFC3339Nano, image.Created); e != nil {
return
}
metadata.Datetime = creationTime
metadata.Repo = repo
metadata.Tag = tag
metadata.Size = image.Size
metadata.Author = image.Author
metadata.Checksum = image.Checksum
metadata.Comment = image.Comment
metadata.Parent = image.Parent
return
}
// getTags queries the Docker registry for the list of the tags for each repository.
func getTags(repoSlice []RepoType) (tagSlice []TagInfo, e error) {
switch *RegistryProto {
case "v1", "quay":
return v1GetTags(repoSlice)
case "v2":
panic("Unreachable")
default:
blog.Error("Unknown registry protocol %s", *RegistryProto)
return
}
panic("Unreachable")
}
// getTagsMetadataHub takes Docker Hub auth and index info and uses it to query
// registries for the tags and metadata for each repository.
func getTagsMetadataHub(hubInfoSlice []HubInfo, oldMetadataSet MetadataSet) (tagSlice []TagInfo,
metadataSlice []ImageMetadataInfo, e error) {
// populate map from ImageID to HubInfo (docker hub token)
hubInfoMap := NewHubInfoMap()
for _, h := range hubInfoSlice {
hubInfoMap[h.Repo] = h
}
// populate map from ImageID to Image Metadata Info
metadataMap := NewImageToMetadataMap()
previousImages := NewImageSet()
for metadata := range oldMetadataSet {
metadataMap.Insert(ImageIDType(metadata.Image), metadata)
previousImages[ImageIDType(metadata.Image)] = true
}
// get tag and image metadata info
for _, hubInfo := range hubInfoSlice {
// singleTagSlice: get all the tags for a single repo
var singleTagSlice []TagInfo
singleTagSlice, e = lookupTagsHub(hubInfo)
if e != nil {
blog.Error(e, ": Error in looking up tags in dockerhub")
//ignore this repo and continue (changed from return to continue)
//TODO: Make sure that this fix has no other side effects
continue
}
tagSlice = append(tagSlice, singleTagSlice...)
ch := make(chan ImageMetadataInfo)
errch := make(chan error)
goCount := 0
// for each tag, generate the current Image Metadata Info
for _, repotag := range singleTagSlice {
repo := repotag.Repo
tagmap := repotag.TagMap
for tag, imageID := range tagmap {
var curr ImageMetadataInfo
if metadataMap.Exists(imageID) {
// copy previous entry and fill in this repo/tag
curr, _ = metadataMap.Metadata(imageID)
curr.Repo = string(repo)
curr.Tag = string(tag)
metadataSlice = append(metadataSlice, curr)
} else {
// create a new entry, and determine field values
// by querying the registry
goCount++
go func(repo RepoType, tag TagType, imageID ImageIDType, hubInfo HubInfo,
ch chan ImageMetadataInfo, errch chan error) {
var metadata ImageMetadataInfo
metadata, e = lookupMetadataHub(repo, tag, imageID, hubInfo)
if e != nil {
blog.Error(e, "Unable to lookup metadata for",
repo, ":", tag, string(imageID))
//ignore this metadata and move on (changed from return to continue)
//TODO: Make sure that this fix has no other side effects
errch <- e
return
}
ch <- metadata
}(repo, tag, imageID, hubInfo, ch, errch)
if goCount > maxGoCount {
for ; goCount > minGoCount; goCount-- {
select {
case metadata := <-ch:
metadataSlice = append(metadataSlice, metadata)
case <-errch:
continue
// blog.Error(err, ":getImageMetadata")
}
}
}
}
}
}
for ; goCount > 0; goCount-- {
select {
case metadata := <-ch:
metadataSlice = append(metadataSlice, metadata)
case <-errch:
continue
// blog.Error(err, ":getImageMetadata")
}
}
}
return
}
// RegistryRequestWithToken queries a Docker Registry that accepts Authorization: Token
// headers with token values obtained from a Docker Index, e.g., Docker Hub.
func RegistryRequestWithToken(client *http.Client, URL string, basicAuth string, dockerToken string) (response []byte, e error) {
var req *http.Request
req, e = http.NewRequest("GET", URL, nil)
if e != nil {
blog.Error(e)
return
}
req.Header.Set("Authorization", "Token "+dockerToken)
var r *http.Response
r, e = client.Do(req)
if e != nil {
blog.Error(e)
return
}
defer r.Body.Close()
if r.StatusCode != 200 {
e = &HTTPStatusCodeError{StatusCode: r.StatusCode}
return
}
response, e = ioutil.ReadAll(r.Body)
if e != nil {
blog.Error(e)
return
}
return
}
// lookupTagsHub accesses the registries pointed to by Docker Hub and returns tag and image info
// for each specified repository.
func lookupTagsHub(info HubInfo) (tagSlice []TagInfo, e error) {
client := &http.Client{}
URL := "https://" + info.RegistryURL + "/v1/repositories/" + string(info.Repo) + "/tags"
response, e := RegistryRequestWithToken(client, URL, BasicAuth, info.DockerToken)
if e != nil {
blog.Error(e)
if s, ok := e.(*HTTPStatusCodeError); ok {
e = errors.New("Skipping Repo: " + string(info.Repo) + "tag lookup status code:" +
strconv.Itoa(s.StatusCode))
}
return
}
//parse JSON output
var m map[TagType]ImageIDType
if e = json.Unmarshal(response, &m); e != nil {
return nil, e
}
var t TagInfo
t.Repo = info.Repo
t.TagMap = m
tagSlice = append(tagSlice, t)
return
}
// lookupMetadataHub takes as input matching repo, tag, imageID, and Docker Hub auth/index info,
// and it returns ImageMetadataInfo for that image by querying the indexed registry.
func lookupMetadataHub(repo RepoType, tag TagType, imageID ImageIDType, hubInfo HubInfo) (
metadata ImageMetadataInfo, e error) {
blog.Info("Get Metadata for Image: %s", string(imageID))
client := &http.Client{}
URL := "https://" + hubInfo.RegistryURL + "/v1/images/" + string(imageID) + "/json"
response, e := RegistryRequestWithToken(client, URL, BasicAuth, hubInfo.DockerToken)
if e != nil {
blog.Error(e, "Unable to query metadata for Repo: "+string(repo)+
"Tag: "+string(tag)+" Image: "+string(imageID))
return
}
// log.Print("metadata query response: " + string(response))
var m ImageStruct
if e = json.Unmarshal(response, &m); e != nil {
return
}
var creationTime time.Time
metadata.Image = string(imageID)
if creationTime, e = time.Parse(time.RFC3339Nano, m.Created); e != nil {
return
}
metadata.Datetime = creationTime
metadata.Repo = string(repo)
metadata.Tag = string(tag)
metadata.Size = m.Size
metadata.Author = m.Author
metadata.Checksum = m.Checksum
metadata.Comment = m.Comment
metadata.Parent = m.Parent
return
}
// GetNewImageMetadata takes the set of existing images, queries the registry to find any changes,
// and then brings the Output Writer up to date by telling it the obsolete metadata to delete
// and the new metadata to add.
func GetNewImageMetadata(oldMetadataSet MetadataSet) (tagSlice []TagInfo,
metadataSlice []ImageMetadataInfo, currentMetadataSet MetadataSet) {
var currentMetadataSlice []ImageMetadataInfo
//config.BanyanUpdate("Loading Registry Metadata")
switch {
case HubAPI == false:
tagSlice, currentMetadataSlice = GetImageMetadata(oldMetadataSet)
case HubAPI == true:
tagSlice, currentMetadataSlice = GetImageMetadataHub(oldMetadataSet)
}
// get only the new metadata from currentMetadataSlice
currentMetadataSet = NewMetadataSet()
for _, metadata := range currentMetadataSlice {
currentMetadataSet[metadata] = true
if _, ok := oldMetadataSet[metadata]; !ok {
// metadata is not in old map
metadataSlice = append(metadataSlice, metadata)
}
}
// find entries in the old map that are not in the current map,
// and remove those entries from the database
obsolete := []ImageMetadataInfo{}
for metadata := range oldMetadataSet {
if _, ok := currentMetadataSet[metadata]; !ok {
if len(ReposToProcess) > 0 {
if _, present := ReposToProcess[RepoType(metadata.Repo)]; present {
obsolete = append(obsolete, metadata)
blog.Info("Need to remove ImageMetadata: %v", metadata)
}
} else {
obsolete = append(obsolete, metadata)
blog.Info("Need to remove ImageMetadata: %v", metadata)
}
}
}
if len(obsolete) > 0 {
RemoveObsoleteMetadata(obsolete)
}
if len(metadataSlice) > 0 || len(obsolete) > 0 {
config.BanyanUpdate("Detected changes in registry metadata")
}
// Sort image metadata from newest image to oldest image
sort.Sort(ByDateTime(metadataSlice))
return
}
const maxStatusLen = 100
func statusMessageMD(metadataSlice []ImageMetadataInfo) string {
statString := ""
for _, metadata := range metadataSlice {
statString += metadata.Repo + ":" + metadata.Tag + ", "
if len(statString) > maxStatusLen {
return statString[0:maxStatusLen]
}
}
return statString
}
// RemoveObsoleteMetadata removes obsolete metadata from the Banyan service.
func RemoveObsoleteMetadata(obsolete []ImageMetadataInfo) {
if len(obsolete) == 0 {
blog.Warn("No image metadata to save!")
return
}
config.BanyanUpdate("Remove Metadata", statusMessageMD(obsolete))
for _, writer := range WriterList {
writer.RemoveImageMetadata(obsolete)
}
return
}
func v2GetTagsMetadata(repoSlice []RepoType) (tagSlice []TagInfo, metadataSlice []ImageMetadataInfo, e error) {
client := &http.Client{}
for _, repo := range repoSlice {
// get tags for one repo
response, err := RegistryQuery(client, RegistryAPIURL+"/v2/"+string(repo)+"/tags/list", BasicAuth)
if err != nil {
blog.Error(err)
if s, ok := err.(*HTTPStatusCodeError); ok {
blog.Error("Skipping Repo: %s, tag lookup status code %d", string(repo), s.StatusCode)
continue
}
return
}
//parse JSON output
var m V2Tag
if e = json.Unmarshal(response, &m); e != nil {
return
}
t := TagInfo{Repo: repo, TagMap: make(map[TagType]ImageIDType)}
for _, tag := range m.Tags {
metadata, e := v2GetMetadata(client, string(repo), tag)
if e != nil {
blog.Error(e, ":Unable to get metadata for repo", string(repo), "tag", tag)
continue
}
t.TagMap[TagType(tag)] = ImageIDType(metadata.Image)
metadataSlice = append(metadataSlice, metadata)
}
tagSlice = append(tagSlice, t)
}
return
}
// getImageMetadata queries the Docker registry for info about each image.
func getImageMetadata(tagSlice []TagInfo, oldMetadataSet MetadataSet) (metadataSlice []ImageMetadataInfo, e error) {
metadataMap := NewImageToMetadataMap()
previousImages := NewImageSet()
for metadata := range oldMetadataSet {
metadataMap.Insert(ImageIDType(metadata.Image), metadata)
previousImages[ImageIDType(metadata.Image)] = true
}
// get map from each imageID to all of its aliases (repo+tag)
imageMap := make(map[ImageIDType][]RepoTagType)
for _, ti := range tagSlice {
for tag, imageID := range ti.TagMap {
repotag := RepoTagType{Repo: ti.Repo, Tag: tag}
if _, ok := imageMap[imageID]; ok {
imageMap[imageID] = append(imageMap[imageID], repotag)
} else {
imageMap[imageID] = []RepoTagType{repotag}
}
}
}
// for each alias, create an entry in metadataSlice
ch := make(chan ImageMetadataInfo)
errch := make(chan error)
goCount := 0
client := &http.Client{}
for imageID := range imageMap {
var curr ImageMetadataInfo
if previousImages[imageID] {
// We already know this image's metadata, but we need to record
// its current repo:tag aliases.
var e error
curr, e = metadataMap.Metadata(imageID)
if e != nil {
blog.Error(e, "imageID", string(imageID), "not in metadataMap")
continue
}
metadataSlice = append(metadataSlice, curr)
continue
}
goCount++
go func(imageID ImageIDType, ch chan ImageMetadataInfo, errch chan error) {
var metadata ImageMetadataInfo
blog.Info("Get Metadata for Image: %s", string(imageID))
if *RegistryProto == "quay" {
// TODO: Properly support quay.io image metadata instead of faking it.
t := time.Date(2011, time.January, 1, 1, 0, 0, 0, time.UTC)
metadata.Image = string(imageID)
metadata.Datetime = t
ch <- metadata
return
}
response, e := RegistryQuery(client, RegistryAPIURL+"/v1/images/"+string(imageID)+"/json", BasicAuth)
if e != nil {
errch <- e
return
}
var m ImageStruct
if e = json.Unmarshal(response, &m); e != nil {
errch <- e
return
}
metadata.Image = string(imageID)
if c, e := time.Parse(time.RFC3339Nano, m.Created); e != nil {
errch <- e
return
} else {
metadata.Datetime = c
metadata.Size = m.Size
metadata.Author = m.Author
metadata.Checksum = m.Checksum
metadata.Comment = m.Comment
metadata.Parent = m.Parent
}
ch <- metadata
}(imageID, ch, errch)
if goCount > maxGoCount {
for ; goCount > minGoCount; goCount-- {
select {
case metadata := <-ch:
metadataSlice = append(metadataSlice, metadata)
case err := <-errch:
blog.Error(err, ":getImageMetadata")
}
}
}
}
for ; goCount > 0; goCount-- {
select {
case metadata := <-ch:
metadataSlice = append(metadataSlice, metadata)
case err := <-errch:
blog.Error(err, ":getImageMetadata")
}
}
// fill in the repo and tag fields of metadataSlice, replicating entries for multiple aliases to an image
finalMetadataSlice := []ImageMetadataInfo{}
for _, metadata := range metadataSlice {
for _, repotag := range imageMap[ImageIDType(metadata.Image)] {
newmd := metadata
// fill in the repo and tag
// _ = repotag
newmd.Repo = string(repotag.Repo)
newmd.Tag = string(repotag.Tag)
finalMetadataSlice = append(finalMetadataSlice, newmd)
}
}
metadataSlice = finalMetadataSlice
return
}
// SaveImageMetadata saves image metadata to selected storage location
// (standard output, Banyan service, etc.).
func SaveImageMetadata(metadataSlice []ImageMetadataInfo) {
if len(metadataSlice) == 0 {
blog.Warn("No image metadata to save!")
return
}
config.BanyanUpdate("Save Image Metadata", statusMessageMD(metadataSlice))
for _, writer := range WriterList {
writer.AppendImageMetadata(metadataSlice)
}
return
}
// ValidRepoName verifies that the name of a repo is in a legal format.
func ValidRepoName(name string) bool {
if len(name) == 0 {
return false
}
if len(name) > 256 {
blog.Error("Invalid repo name, too long: %s", name)
return false
}
for _, c := range name {
switch {
case c >= 'a' && c <= 'z':
continue
case c >= 'A' && c <= 'Z':
continue
case c >= '0' && c <= '9':
continue
case c == '/' || c == '_' || c == '-' || c == '.':
continue
default:
blog.Error("Invalid repo name %s", name)
return false
}
}
return true
}