-
Notifications
You must be signed in to change notification settings - Fork 0
/
check.go
280 lines (258 loc) · 9.07 KB
/
check.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
package composectl
import (
"context"
"encoding/json"
"fmt"
"github.com/containerd/containerd/platforms"
"github.com/containerd/containerd/reference"
dockertypes "github.com/docker/docker/api/types"
"github.com/docker/go-units"
"github.com/foundriesio/composeapp/pkg/compose"
v1 "github.com/foundriesio/composeapp/pkg/compose/v1"
"github.com/opencontainers/go-digest"
"github.com/spf13/cobra"
"os"
"path"
)
var (
checkCmd = &cobra.Command{
Use: "check",
Short: "check <ref> [<ref>]",
Long: ``,
Args: cobra.MinimumNArgs(1),
}
)
type (
checkOptions struct {
UsageWatermark *uint
SrcStorePath *string
Locally *bool
Format string
CheckInstall bool
}
checkAppResult struct {
MissingBlobs map[digest.Digest]compose.BlobInfo `json:"missing_blobs"`
TotalPullSize int64 `json:"total_pull_size"`
TotalStoreSize int64 `json:"total_store_size"`
TotalRuntimeSize int64 `json:"total_runtime_size"`
}
appInstallCheckResult struct {
AppName string `json:"app_name"`
MissingImages []string `json:"missing_images"`
}
installCheckResult map[string]*appInstallCheckResult
)
const (
MinUsageWatermark = 20
MaxUsageWatermark = 95
)
func init() {
opts := checkOptions{}
opts.UsageWatermark = checkCmd.Flags().UintP("storage-usage-watermark", "u", 80,
"The maximum allowed storage usage in percentage")
opts.SrcStorePath = checkCmd.Flags().StringP("source-store-path", "l", "",
"A path to the source store root directory")
opts.Locally = checkCmd.Flags().BoolP("local", "", false,
"Check whether app is fetched without getting app manifest from registry")
checkCmd.Flags().StringVar(&opts.Format, "format", "plain",
"Output format; supported: plain, json")
checkCmd.Flags().BoolVar(&opts.CheckInstall, "install", false,
"Check both whether app is fetched and installed")
checkCmd.Run = func(cmd *cobra.Command, args []string) {
if opts.Format != "plain" && opts.Format != "json" {
DieNotNil(cmd.Usage())
fmt.Fprintf(os.Stderr, "unsupported `--format` value: %s\n", opts.Format)
os.Exit(1)
}
checkAppsCmd(cmd, args, &opts)
}
rootCmd.AddCommand(checkCmd)
}
func checkAppsCmd(cmd *cobra.Command, args []string, opts *checkOptions) {
if *opts.Locally && len(*opts.SrcStorePath) == 0 {
// Use the local store as the source store to check whether app is fetched without a need in connection to Registry.
// Requires app manifest and app archive presence in the local store, otherwise fails.
opts.SrcStorePath = &config.StoreRoot
}
quietCheck := false
if opts.Format == "json" {
quietCheck = true
}
cr, ui, _ := checkApps(cmd.Context(), args, *opts.UsageWatermark, *opts.SrcStorePath, quietCheck)
var ir installCheckResult
var err error
if opts.CheckInstall {
ir, err = checkIfInstalled(cmd.Context(), args, *opts.SrcStorePath, config.DockerHost)
DieNotNil(err)
}
if opts.Format == "json" {
aggregatedCheckRes :=
struct {
FetchCheck *checkAppResult `json:"fetch_check"`
InstallCheck *installCheckResult `json:"install_check"`
}{
FetchCheck: cr,
InstallCheck: &ir,
}
if b, err := json.MarshalIndent(aggregatedCheckRes, "", " "); err == nil {
fmt.Println(string(b))
} else {
DieNotNil(err)
}
} else {
ui.Print()
cr.print()
if opts.CheckInstall {
for appRef, r := range ir {
if len(r.MissingImages) > 0 {
fmt.Printf("%s is not installed (%s); missing images:\n", r.AppName, appRef)
} else {
fmt.Printf("%s is installed (%s)\n", r.AppName, appRef)
}
for _, i := range r.MissingImages {
fmt.Printf("\t- %s\n", i)
}
}
}
}
}
func checkApps(ctx context.Context, appRefs []string, usageWatermark uint, srcStorePath string, quiet bool) (*checkAppResult, *compose.UsageInfo, []compose.App) {
if usageWatermark < MinUsageWatermark {
DieNotNil(fmt.Errorf("the specified usage watermark is lower than the minimum allowed; %d < %d", usageWatermark, MinUsageWatermark))
}
if usageWatermark > MaxUsageWatermark {
DieNotNil(fmt.Errorf("the specified usage watermark is higher than the maximum allowed; %d < %d", usageWatermark, MaxUsageWatermark))
}
cs, err := v1.NewAppStore(config.StoreRoot, config.Platform)
DieNotNil(err)
var localSrcStore string
var blobProvider compose.BlobProvider
if len(srcStorePath) > 0 {
blobProvider = compose.NewStoreBlobProvider(path.Join(srcStorePath, "blobs", "sha256"))
} else {
authorizer := compose.NewRegistryAuthorizer(config.DockerCfg)
resolver := compose.NewResolver(authorizer)
blobProvider = compose.NewRemoteBlobProvider(resolver)
}
var apps []compose.App
blobsToPull := map[digest.Digest]compose.BlobInfo{}
checkRes := checkAppResult{MissingBlobs: blobsToPull}
for _, appRef := range appRefs {
if !quiet {
if len(localSrcStore) > 0 {
fmt.Printf("Loading %s metadata from %s...\n", appRef, localSrcStore)
} else {
fmt.Printf("Loading %s metadata from registry...\n", appRef)
}
}
app, tree, err := v1.NewAppLoader().LoadAppTree(ctx, blobProvider, platforms.OnlyStrict(config.Platform), appRef)
DieNotNil(err)
apps = append(apps, app)
if !quiet {
fmt.Printf("%s metadata loaded\n", app.Name())
fmt.Printf("Checking %s state in the local store...\n", app.Name())
}
var blockSize int64 = 4096
s, err := compose.GetFsStat(config.StoreRoot)
if err != nil && !quiet {
fmt.Printf("Failed to get FS block size: %s\n", err.Error())
fmt.Printf("Assuming the FS block size if 4096")
} else {
blockSize = s.BlockSize
}
err = tree.Walk(func(node *compose.TreeNode, depth int) error {
if !quiet {
blobDescStr := fmt.Sprintf("%*s %10s %s", depth*8, " ", node.Type, node.Descriptor.Digest.Encoded())
fmt.Printf("%s %*d", blobDescStr, 120-len(blobDescStr), node.Descriptor.Size)
}
bs, stateCheckErr := compose.CheckBlob(ctx, cs, compose.WithExpectedDigest(node.Descriptor.Digest),
compose.WithExpectedSize(node.Descriptor.Size))
if stateCheckErr != nil {
return stateCheckErr
}
if !quiet {
fmt.Printf("...%s\n", bs.String())
}
if bs != compose.BlobOk {
blobsToPull[node.Descriptor.Digest] = compose.BlobInfo{
Descriptor: node.Descriptor,
State: bs,
Type: node.Type,
StoreSize: compose.AlignToBlockSize(node.Descriptor.Size, blockSize),
RuntimeSize: app.GetBlobRuntimeSize(node.Descriptor, config.Platform.Architecture, blockSize),
}
}
return nil
})
DieNotNil(err)
if !quiet {
fmt.Println()
if len(blobsToPull) == 0 {
fmt.Printf("%s is in sync (%s)\n", app.Name(), appRef)
continue
}
if !app.HasLayersMeta(config.Platform.Architecture) {
fmt.Println("No app layers meta are found, the app layer sizes are approximated!")
}
}
for _, b := range blobsToPull {
checkRes.TotalPullSize += b.Descriptor.Size
checkRes.TotalStoreSize += b.StoreSize
checkRes.TotalRuntimeSize += b.RuntimeSize
}
}
// TODO: take into account that docker data root and OCI/blob store can be located on different volumes
ui, err := compose.GetUsageInfo(config.StoreRoot, checkRes.TotalStoreSize+checkRes.TotalRuntimeSize, usageWatermark)
if err != nil && !quiet {
fmt.Printf("Failed to get storage usage information")
}
return &checkRes, ui, apps
}
func (cr *checkAppResult) print() {
fmt.Printf("%d blobs to pull; total download size: %s, total store size: %s, total runtime size of missing blobs: %s, total required: %s\n",
len(cr.MissingBlobs), units.BytesSize(float64(cr.TotalPullSize)), units.BytesSize(float64(cr.TotalStoreSize)), units.BytesSize(float64(cr.TotalRuntimeSize)), units.BytesSize(float64(cr.TotalStoreSize+cr.TotalRuntimeSize)))
}
func checkIfInstalled(ctx context.Context, appRefs []string, srcStorePath string, dockerHost string) (installCheckResult, error) {
cli, err := compose.GetDockerClient(dockerHost)
if err != nil {
return nil, err
}
images, err := cli.ImageList(ctx, dockertypes.ImageListOptions{All: true})
if err != nil {
return nil, err
}
installedImages := map[string]bool{}
for _, i := range images {
if len(i.RepoDigests) > 0 {
installedImages[i.RepoDigests[0]] = true
}
if len(i.RepoTags) > 0 {
// unpatch docker won't store the digest URI of loaded image
installedImages[i.RepoTags[0]] = true
}
}
checkResult := installCheckResult{}
blobProvider := compose.NewStoreBlobProvider(path.Join(srcStorePath, "blobs", "sha256"))
for _, appRef := range appRefs {
app, _, err := v1.NewAppLoader().LoadAppTree(ctx, blobProvider, platforms.OnlyStrict(config.Platform), appRef)
DieNotNil(err)
var missingImages []string
appComposeRoot := app.GetComposeRoot()
for _, imageNode := range appComposeRoot.Children {
imageUri := imageNode.Descriptor.URLs[0]
if !installedImages[imageUri] {
if s, err := reference.Parse(imageUri); err == nil {
taggedUri := s.Locator + ":" + (s.Digest().Encoded())[:7]
if !installedImages[taggedUri] {
missingImages = append(missingImages, imageUri)
}
}
}
}
checkResult[appRef] = &appInstallCheckResult{
AppName: app.Name(),
MissingImages: missingImages,
}
}
return checkResult, nil
}