-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathimage.go
More file actions
243 lines (210 loc) · 6.57 KB
/
Copy pathimage.go
File metadata and controls
243 lines (210 loc) · 6.57 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
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
)
// ListImages lists all available images
func ListImages() {
imageDir := "/tmp/basic-docker/images"
fmt.Println("IMAGE NAME\tSIZE")
if _, err := os.Stat(imageDir); os.IsNotExist(err) {
return
}
entries, err := os.ReadDir(imageDir)
if err != nil {
fmt.Printf("Error reading images: %v\n", err)
return
}
for _, entry := range entries {
if entry.IsDir() {
size, err := calculateDirSize(filepath.Join(imageDir, entry.Name()))
if err != nil {
fmt.Printf("%s\tError calculating size\n", entry.Name())
} else {
fmt.Printf("%s\t%d bytes\n", entry.Name(), size)
}
}
}
}
// calculateDirSize calculates the total size of a directory
func calculateDirSize(dirPath string) (int64, error) {
var totalSize int64
err := filepath.Walk(dirPath, func(_ string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
totalSize += info.Size()
}
return nil
})
if err != nil {
return 0, err
}
return totalSize, nil
}
// Image represents a container image
type Image struct {
Name string
RootFS string
Layers []string
}
// Registry represents a generic interface for interacting with container registries
type Registry interface {
FetchManifest(repo, tag string) (*Manifest, error)
FetchLayer(repo, digest string) (io.ReadCloser, error)
}
// DockerHubRegistry is a default implementation of the Registry interface for GHCR or custom registries.
type DockerHubRegistry struct {
BaseURL string
Username string
Password string
}
// NewDockerHubRegistry creates a new instance of DockerHubRegistry with an optional custom registry URL.
func NewDockerHubRegistry(customURL string) *DockerHubRegistry {
if customURL == "" {
customURL = "https://ghcr.io/v2/"
}
return &DockerHubRegistry{
BaseURL: customURL,
}
}
// NewDockerHubRegistryWithCreds creates a DockerHubRegistry that sends HTTP Basic Auth on every request.
func NewDockerHubRegistryWithCreds(customURL, username, password string) *DockerHubRegistry {
r := NewDockerHubRegistry(customURL)
r.Username = username
r.Password = password
return r
}
// FetchManifest fetches the manifest for a given repository and tag.
func (r *DockerHubRegistry) FetchManifest(repo, tag string) (*Manifest, error) {
url := fmt.Sprintf("%s%s/manifests/%s", r.BaseURL, repo, tag)
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, fmt.Errorf("failed to create manifest request: %w", err)
}
if r.Username != "" {
req.SetBasicAuth(r.Username, r.Password)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to fetch manifest: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("unexpected status code: %d", resp.StatusCode)
}
var manifest Manifest
if err := json.NewDecoder(resp.Body).Decode(&manifest); err != nil {
return nil, fmt.Errorf("failed to decode manifest: %w", err)
}
return &manifest, nil
}
// FetchLayer fetches a specific layer by its digest.
func (r *DockerHubRegistry) FetchLayer(repo, digest string) (io.ReadCloser, error) {
url := fmt.Sprintf("%s%s/blobs/%s", r.BaseURL, repo, digest)
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, fmt.Errorf("failed to create layer request: %w", err)
}
if r.Username != "" {
req.SetBasicAuth(r.Username, r.Password)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to fetch layer: %w", err)
}
if resp.StatusCode != http.StatusOK {
resp.Body.Close()
return nil, fmt.Errorf("unexpected status code: %d", resp.StatusCode)
}
return resp.Body, nil
}
// Manifest represents the structure of an image manifest
type Manifest struct {
Config struct {
Digest string `json:"digest"`
} `json:"config"`
Layers []struct {
Digest string `json:"digest"`
} `json:"layers"`
}
// Pull downloads an image using the provided registry
func Pull(registry Registry, name string) (*Image, error) {
fmt.Printf("[DEBUG] Starting to pull image '%s'\n", name)
// Split the image name into repository and tag
parts := strings.Split(name, ":")
repo := parts[0]
tag := "latest"
if len(parts) > 1 {
tag = parts[1]
}
fmt.Printf("[DEBUG] Fetching manifest for repo '%s' and tag '%s'\n", repo, tag)
// Fetch the image manifest
manifest, err := registry.FetchManifest(repo, tag)
if err != nil {
return nil, fmt.Errorf("failed to fetch manifest: %w", err)
}
fmt.Printf("[DEBUG] Manifest fetched successfully. Number of layers: %d\n", len(manifest.Layers))
// Download and extract layers
rootfs := filepath.Join("/tmp/basic-docker/images", name, "rootfs")
if err := os.MkdirAll(rootfs, 0755); err != nil {
return nil, fmt.Errorf("failed to create rootfs: %w", err)
}
for _, layer := range manifest.Layers {
fmt.Printf("[DEBUG] Downloading layer with digest '%s'\n", layer.Digest)
layerReader, err := registry.FetchLayer(repo, layer.Digest)
if err != nil {
return nil, fmt.Errorf("failed to download layer %s: %w", layer.Digest, err)
}
defer layerReader.Close()
fmt.Printf("[DEBUG] Extracting layer '%s'\n", layer.Digest)
if err := extractLayer(layerReader, rootfs); err != nil {
return nil, fmt.Errorf("failed to extract layer %s: %w", layer.Digest, err)
}
}
fmt.Printf("[DEBUG] Image '%s' pulled successfully. RootFS path: %s\n", name, rootfs)
return &Image{
Name: name,
RootFS: rootfs,
Layers: []string{"base"},
}, nil
}
// extractLayer extracts a tar archive to the specified rootfs directory
func extractLayer(reader io.Reader, rootfs string) error {
// Use tar to extract the layer
cmd := exec.Command("tar", "-x", "-C", rootfs)
cmd.Stdin = reader
if err := cmd.Run(); err != nil {
return fmt.Errorf("failed to extract layer: %w", err)
}
return nil
}
// LoadImageFromTar loads a container image from a .tar file
func LoadImageFromTar(tarFilePath string, imageName string) (*Image, error) {
rootfs := filepath.Join("/tmp/basic-docker/images", imageName, "rootfs")
if err := os.MkdirAll(rootfs, 0755); err != nil {
return nil, fmt.Errorf("failed to create rootfs: %w", err)
}
// Extract the tar file to the rootfs directory
tarFile, err := os.Open(tarFilePath)
if err != nil {
return nil, fmt.Errorf("failed to open tar file: %w", err)
}
defer tarFile.Close()
cmd := exec.Command("tar", "-x", "-C", rootfs, "-f", tarFilePath)
if err := cmd.Run(); err != nil {
return nil, fmt.Errorf("failed to extract tar file: %w", err)
}
return &Image{
Name: imageName,
RootFS: rootfs,
Layers: []string{"base"},
}, nil
}