-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy patharm_check.go
More file actions
177 lines (153 loc) · 4.85 KB
/
arm_check.go
File metadata and controls
177 lines (153 loc) · 4.85 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
package main
import (
"context"
"fmt"
"io"
"math/rand"
"strings"
"sync"
"time"
"github.com/awslabs/amazon-ecr-credential-helper/ecr-login"
"github.com/chrismellard/docker-credential-acr-env/pkg/credhelper"
"github.com/google/go-containerregistry/pkg/authn"
"github.com/google/go-containerregistry/pkg/authn/github"
"github.com/google/go-containerregistry/pkg/name"
"github.com/google/go-containerregistry/pkg/v1/google"
"github.com/google/go-containerregistry/pkg/v1/remote"
"github.com/google/go-containerregistry/pkg/v1/types"
corev1 "k8s.io/api/core/v1"
)
type ArmResult struct {
Supported bool
Err error
}
const MaxConcurrent = 7
var armResultCache = make(map[string]ArmResult)
var armResultCacheMutex sync.RWMutex
func CheckAllWorkloadsArm(workloads []Workload) []ArmResult {
results := make([]ArmResult, len(workloads))
var wg sync.WaitGroup
sem := make(chan struct{}, MaxConcurrent)
for idx := range workloads {
wg.Add(1)
go func(i int) {
defer wg.Done()
sem <- struct{}{}
defer func() { <-sem }()
cacheKey := fmt.Sprintf("%s:%s:%s", workloads[i].Kind, workloads[i].Name, workloads[i].Namespace)
armResultCacheMutex.RLock()
cachedResult, found := armResultCache[cacheKey]
armResultCacheMutex.RUnlock()
if found {
results[i] = cachedResult
return
}
var supported bool
var err error
for {
supported, err = CheckWorkloadSupportsArm(&workloads[i])
if err != nil && strings.Contains(err.Error(), "TOOMANYREQUESTS") {
time.Sleep(time.Millisecond * time.Duration(rand.Int63n(800)))
} else {
break
}
}
result := ArmResult{Supported: supported, Err: err}
results[i] = result
armResultCacheMutex.Lock()
armResultCache[cacheKey] = result
armResultCacheMutex.Unlock()
}(idx)
}
wg.Wait()
return results
}
func CheckWorkloadSupportsArm(w *Workload) (bool, error) {
var podSpec *corev1.PodSpec
switch w.Kind {
case WorkloadDeployment:
podSpec = &w.deployment.Spec.Template.Spec
case WorkloadStatefulSet:
podSpec = &w.statefulSet.Spec.Template.Spec
default:
return false, fmt.Errorf("unsupported workload kind: %s", w.Kind)
}
images := getPodTemplateImages(*podSpec)
supportArm := true
for _, image := range images {
ret, err := imageSupportsArm64(image)
if err != nil {
return false, fmt.Errorf("failed to check image %s for arm64 support: %w", image, err)
}
if ret == false {
supportArm = false
break
}
}
return supportArm, nil
}
func getPodTemplateImages(podSpec corev1.PodSpec) []string {
var images []string
for _, c := range podSpec.Containers {
images = append(images, c.Image)
}
for _, c := range podSpec.InitContainers {
images = append(images, c.Image)
}
return images
}
var keychain = authn.NewMultiKeychain(
authn.NewKeychainFromHelper(ecr.NewECRHelper(ecr.WithLogger(io.Discard))), // ECR
authn.NewKeychainFromHelper(credhelper.NewACRCredentialsHelper()), // ACR
google.Keychain, // GCR & Artifact Registry
github.Keychain, // GHCR
authn.DefaultKeychain, // local ~/.docker/config.json
)
// imageSupportsArm64 checks whether the given container image supports the linux/arm64
// platform. It returns true if the image manifest list (index) contains an arm64
// variant, or if the single-arch image itself is built for arm64.
func imageSupportsArm64(imageRef string) (bool, error) {
// Parse an arbitrary image reference (registry/name:tag or digest).
ref, err := name.ParseReference(imageRef, name.WeakValidation)
if err != nil {
return false, fmt.Errorf("failed to parse image reference: %w", err)
}
// Pull the descriptor (manifest or index) from the remote registry.
remoteOpts := []remote.Option{
remote.WithAuthFromKeychain(keychain),
remote.WithContext(context.Background()),
}
desc, err := remote.Get(ref, remoteOpts...)
if err != nil {
return false, fmt.Errorf("failed to fetch image descriptor: %w", err)
}
mt := desc.Descriptor.MediaType
// Handle multi-arch images (OCI index / Docker manifest list).
if mt == types.OCIImageIndex || mt == types.DockerManifestList {
idx, err := desc.ImageIndex()
if err != nil {
return false, fmt.Errorf("failed to load image index: %w", err)
}
indexManifest, err := idx.IndexManifest()
if err != nil {
return false, fmt.Errorf("failed to read index manifest: %w", err)
}
for _, manifest := range indexManifest.Manifests {
plat := manifest.Platform
if plat != nil && plat.Architecture == "arm64" && strings.EqualFold(plat.OS, "linux") {
return true, nil // linux/arm64 variant found
}
}
return false, nil // no arm64 variant in the index
}
// Handle single-arch images.
img, err := desc.Image()
if err != nil {
return false, fmt.Errorf("failed to load image: %w", err)
}
cfg, err := img.ConfigFile()
if err != nil {
return false, fmt.Errorf("failed to read image config: %w", err)
}
return cfg.Architecture == "arm64", nil
}