|
| 1 | +// Package main implements a registry exporter for Prometheus metrics. |
| 2 | +package main |
| 3 | + |
| 4 | +import ( |
| 5 | + "encoding/base64" |
| 6 | + "encoding/json" |
| 7 | + "log" |
| 8 | + "net/http" |
| 9 | + "os" |
| 10 | + "os/exec" |
| 11 | + "strings" |
| 12 | + |
| 13 | + "github.com/prometheus/client_golang/prometheus" |
| 14 | + "github.com/prometheus/client_golang/prometheus/promhttp" |
| 15 | + "github.com/stretchr/testify/assert/yaml" |
| 16 | +) |
| 17 | + |
| 18 | +type Metrics struct { |
| 19 | + RegistryTestUp *prometheus.GaugeVec |
| 20 | + RegistryPullCount *prometheus.CounterVec |
| 21 | + RegistryTotalPullCount *prometheus.CounterVec |
| 22 | + RegistryPushCount *prometheus.CounterVec |
| 23 | + RegistryTotalPushCount *prometheus.CounterVec |
| 24 | +} |
| 25 | + |
| 26 | +// authBase64 is used to parse the "auth" field from docker config JSON. |
| 27 | +type authBase64 struct { |
| 28 | + Auth string `json:"auth"` |
| 29 | +} |
| 30 | + |
| 31 | +// ConfigJSON represents the structure of docker config JSON. |
| 32 | +type ConfigJSON struct { |
| 33 | + Auths map[string]authBase64 `json:"auths"` |
| 34 | +} |
| 35 | + |
| 36 | +// Secret represents a Kubernetes secret containing docker config. |
| 37 | +type Secret struct { |
| 38 | + Data map[string]string `yaml:"data"` |
| 39 | +} |
| 40 | + |
| 41 | +func InitPodmanLogin(registryType string) { |
| 42 | + log.Print("Try logging into registry...") |
| 43 | + |
| 44 | + filePath := os.Getenv("DOCKERCFG_PATH") |
| 45 | + if filePath == "" { |
| 46 | + log.Panicf("DOCKERCFG_PATH environment variable is not set") |
| 47 | + return |
| 48 | + } |
| 49 | + |
| 50 | + var secret Secret |
| 51 | + fileBytes, err := os.ReadFile(filePath) |
| 52 | + if err != nil { |
| 53 | + log.Printf("failed to read docker config file at %s: %v", filePath, err) |
| 54 | + return |
| 55 | + } |
| 56 | + |
| 57 | + if err := yaml.Unmarshal(fileBytes, &secret); err != nil { |
| 58 | + log.Printf("failed to unmarshal docker config yaml: %v", err) |
| 59 | + return |
| 60 | + } |
| 61 | + |
| 62 | + dockerConfigB64, ok := secret.Data[".dockerconfigjson"] |
| 63 | + if !ok { |
| 64 | + log.Printf(".dockerconfigjson not found in secret data") |
| 65 | + return |
| 66 | + } |
| 67 | + |
| 68 | + dockerConfigJSONBytes, err := base64.StdEncoding.DecodeString(dockerConfigB64) |
| 69 | + if err != nil { |
| 70 | + log.Printf("failed to decode .dockerconfigjson: %v", err) |
| 71 | + return |
| 72 | + } |
| 73 | + // Note: At this point, this is how would the usual podman authfile look like, maybe it can be used directly? |
| 74 | + // ... |
| 75 | + |
| 76 | + var configJSON ConfigJSON |
| 77 | + if err := json.Unmarshal(dockerConfigJSONBytes, &configJSON); err != nil { |
| 78 | + log.Printf("failed to unmarshal docker config JSON: %v", err) |
| 79 | + return |
| 80 | + } |
| 81 | + |
| 82 | + // Extract the first auth token found in the file |
| 83 | + // Is there a better way for that? :thinking: |
| 84 | + var registryAuthToken string |
| 85 | + for _, auth := range configJSON.Auths { |
| 86 | + registryAuthToken = auth.Auth |
| 87 | + break |
| 88 | + } |
| 89 | + if registryAuthToken == "" { |
| 90 | + log.Printf("auth token not found in the docker config file") |
| 91 | + return |
| 92 | + } |
| 93 | + |
| 94 | + decodedAuth, err := base64.StdEncoding.DecodeString(registryAuthToken) |
| 95 | + if err != nil { |
| 96 | + log.Printf("failed to decode registry auth token: %v", err) |
| 97 | + return |
| 98 | + } |
| 99 | + |
| 100 | + decodedAuthParts := strings.SplitN(string(decodedAuth), ":", 2) |
| 101 | + if len(decodedAuthParts) != 2 { |
| 102 | + log.Printf("invalid registry auth token format") |
| 103 | + return |
| 104 | + } |
| 105 | + |
| 106 | + loginCmd := exec.Command("podman", "login", "--username", decodedAuthParts[0], "--password", decodedAuthParts[1], registryType) |
| 107 | + loginOutput, loginErr := loginCmd.CombinedOutput() |
| 108 | + if loginErr != nil { |
| 109 | + log.Panicf("Registry login failed: %v, output: %s", loginErr, string(loginOutput)) |
| 110 | + } |
| 111 | + log.Print("Registry login successful.") |
| 112 | +} |
| 113 | + |
| 114 | +// InitMetrics initializes and registers Prometheus metrics. |
| 115 | +func InitMetrics(reg prometheus.Registerer) *Metrics { |
| 116 | + m := &Metrics{ |
| 117 | + RegistryTestUp: prometheus.NewGaugeVec( |
| 118 | + prometheus.GaugeOpts{ |
| 119 | + Name: "registry_test_up", |
| 120 | + Help: "A simple gauge to indicate if the registryType is accessible (1 for up).", |
| 121 | + }, |
| 122 | + []string{"registryType"}, |
| 123 | + ), |
| 124 | + RegistryPullCount: prometheus.NewCounterVec( |
| 125 | + prometheus.CounterOpts{ |
| 126 | + Name: "registry_successful_pull_count", |
| 127 | + Help: "Total number of successful image pulls.", |
| 128 | + }, |
| 129 | + []string{"registryType"}, |
| 130 | + ), |
| 131 | + RegistryTotalPullCount: prometheus.NewCounterVec( |
| 132 | + prometheus.CounterOpts{ |
| 133 | + Name: "registry_total_pull_count", |
| 134 | + Help: "Total number of image pulls.", |
| 135 | + }, |
| 136 | + []string{"registryType"}, |
| 137 | + ), |
| 138 | + RegistryPushCount: prometheus.NewCounterVec( |
| 139 | + prometheus.CounterOpts{ |
| 140 | + Name: "registry_successful_push_count", |
| 141 | + Help: "Total number of successful image pushes.", |
| 142 | + }, |
| 143 | + []string{"registryType"}, |
| 144 | + ), |
| 145 | + RegistryTotalPushCount: prometheus.NewCounterVec( |
| 146 | + prometheus.CounterOpts{ |
| 147 | + Name: "registry_total_push_count", |
| 148 | + Help: "Total number of image pushes.", |
| 149 | + }, |
| 150 | + []string{"registryType"}, |
| 151 | + ), |
| 152 | + } |
| 153 | + reg.MustRegister(m.RegistryTestUp) |
| 154 | + reg.MustRegister(m.RegistryPullCount) |
| 155 | + reg.MustRegister(m.RegistryTotalPullCount) |
| 156 | + reg.MustRegister(m.RegistryPushCount) |
| 157 | + reg.MustRegister(m.RegistryTotalPushCount) |
| 158 | + return m |
| 159 | +} |
| 160 | + |
| 161 | +var registryTypes = map[string]string{ |
| 162 | + "quay.io": "quay.io/redhat-user-workloads/rh-ee-tbehal-tenant/test-component", |
| 163 | + "images.paas.redhat.com": "images.paas.redhat.com/o11y/todo", |
| 164 | +} |
| 165 | + |
| 166 | +func ImagePullTest(metrics *Metrics, registryType string) { |
| 167 | + defer metrics.RegistryTotalPullCount.WithLabelValues(registryType).Inc() |
| 168 | + |
| 169 | + imageName, ok := registryTypes[registryType] |
| 170 | + if !ok { |
| 171 | + log.Printf("Unknown registry type: %s", registryType) |
| 172 | + return |
| 173 | + } |
| 174 | + imageName += ":pull" // TODO: Add tag management |
| 175 | + log.Print("Starting Image Pull Test...") |
| 176 | + cmd := exec.Command("podman", "pull", imageName) |
| 177 | + output, err := cmd.CombinedOutput() |
| 178 | + if err != nil { |
| 179 | + log.Printf("Image pull failed: %v, output: %s", err, string(output)) |
| 180 | + return |
| 181 | + } |
| 182 | + log.Print("Image pull successful.") |
| 183 | + metrics.RegistryPullCount.WithLabelValues(registryType).Inc() |
| 184 | +} |
| 185 | + |
| 186 | +// TODO: This works only locally, probably needs to be adapted for cluster use |
| 187 | +func CreateDockerfile() { |
| 188 | + dockerfileContent := `FROM busybox:glibc |
| 189 | +
|
| 190 | +# Add a build-time timestamp to force uniqueness and avoid layer caching |
| 191 | +ARG BUILD_TIMESTAMP |
| 192 | +ENV BUILD_TIMESTAMP=${BUILD_TIMESTAMP} |
| 193 | +
|
| 194 | +LABEL quay.expires-after="1m" |
| 195 | +
|
| 196 | +# Example: touch a file with the timestamp |
| 197 | +RUN echo "${BUILD_TIMESTAMP}" > /timestamp.txt |
| 198 | +` |
| 199 | + |
| 200 | + // PVC mountpoint expected e.g.: /mnt/data/ |
| 201 | + filePath := os.Getenv("DOCKERFILE_PATH") |
| 202 | + if filePath == "" { |
| 203 | + log.Panicf("DOCKERFILE_PATH environment variable is not set") |
| 204 | + return |
| 205 | + } |
| 206 | + |
| 207 | + if err := os.WriteFile(filePath+"Dockerfile", []byte(dockerfileContent), 0644); err != nil { |
| 208 | + log.Panicf("Failed to create Dockerfile: %v", err) |
| 209 | + } |
| 210 | +} |
| 211 | + |
| 212 | +func ImagePushTest(metrics *Metrics, registryType string) { |
| 213 | + defer metrics.RegistryTotalPushCount.WithLabelValues(registryType).Inc() |
| 214 | + |
| 215 | + imageName, ok := registryTypes[registryType] |
| 216 | + if !ok { |
| 217 | + log.Printf("Unknown registry type: %s", registryType) |
| 218 | + return |
| 219 | + } |
| 220 | + imageName += ":push" // TODO: Add tag management |
| 221 | + log.Print("Starting Image Push Test...") |
| 222 | + |
| 223 | + // Build image with podman |
| 224 | + buildTimestamp := os.Getenv("BUILD_TIMESTAMP") |
| 225 | + if buildTimestamp == "" { |
| 226 | + buildTimestamp = "now" |
| 227 | + } |
| 228 | + buildCmd := exec.Command("podman", "build", "-t", imageName, "--build-arg", "BUILD_TIMESTAMP="+buildTimestamp, "-f", os.Getenv("DOCKERFILE_PATH")+"Dockerfile", ".") |
| 229 | + buildOutput, buildErr := buildCmd.CombinedOutput() |
| 230 | + if buildErr != nil { |
| 231 | + log.Printf("Image build failed: %v, output: %s", buildErr, string(buildOutput)) |
| 232 | + return |
| 233 | + } |
| 234 | + log.Print("Image build successful.") |
| 235 | + |
| 236 | + // For push, assume podman login is handled externally or via entrypoint script |
| 237 | + pushCmd := exec.Command("podman", "push", imageName) |
| 238 | + pushOutput, pushErr := pushCmd.CombinedOutput() |
| 239 | + if pushErr != nil { |
| 240 | + log.Printf("Image push failed: %v, output: %s", pushErr, string(pushOutput)) |
| 241 | + return |
| 242 | + } |
| 243 | + log.Print("Image push successful.") |
| 244 | + metrics.RegistryPushCount.WithLabelValues(registryType).Inc() |
| 245 | +} |
| 246 | + |
| 247 | +func ImageManifestTest(metrics *Metrics) { |
| 248 | + // TODO: Implement manifest test |
| 249 | +} |
| 250 | + |
| 251 | +func main() { |
| 252 | + log.SetOutput(os.Stderr) |
| 253 | + |
| 254 | + registryType := "quay.io" |
| 255 | + |
| 256 | + reg := prometheus.NewRegistry() |
| 257 | + metrics := InitMetrics(reg) |
| 258 | + |
| 259 | + InitPodmanLogin(registryType) |
| 260 | + CreateDockerfile() |
| 261 | + |
| 262 | + metrics.RegistryTestUp.WithLabelValues(registryType).Set(1) |
| 263 | + |
| 264 | + handler := promhttp.HandlerFor(reg, promhttp.HandlerOpts{}) |
| 265 | + |
| 266 | + http.HandleFunc("/metrics", func(w http.ResponseWriter, r *http.Request) { |
| 267 | + log.Println("Metrics endpoint hit, running tests...") |
| 268 | + go ImagePullTest(metrics, registryType) |
| 269 | + go ImagePushTest(metrics, registryType) |
| 270 | + handler.ServeHTTP(w, r) |
| 271 | + |
| 272 | + // TODO: Figure out where to increment these |
| 273 | + // metrics.RegistryTotalPullCount.WithLabelValues(registryType).Inc() |
| 274 | + // metrics.RegistryTotalPushCount.WithLabelValues(registryType).Inc() |
| 275 | + }) |
| 276 | + |
| 277 | + log.Println("http://localhost:9101/metrics") |
| 278 | + log.Fatal(http.ListenAndServe(":9101", nil)) |
| 279 | +} |
0 commit comments