forked from mudler/poco
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
425 lines (388 loc) · 11.2 KB
/
main.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
// Copyright © 2021 Ettore Di Giacinto <mudler@mocaccino.org>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, see <http://www.gnu.org/licenses/>.
package main
import (
"errors"
"fmt"
"os"
"path"
"path/filepath"
"runtime"
"strings"
"github.com/mholt/archiver/v3"
"github.com/mudler/luet/pkg/api/core/image"
"github.com/otiai10/copy"
"github.com/pterm/pterm"
"github.com/skrashevich/poco/internal"
"github.com/skrashevich/poco/pkg/bundler"
"github.com/skrashevich/poco/pkg/extractor"
"github.com/urfave/cli"
)
func common() []cli.Flag {
return []cli.Flag{
&cli.StringFlag{
Name: "entrypoint",
EnvVar: "ENTRYPOINT",
Usage: "Default binary entrypoint. This is the first binary from the container image which will be executed.",
Value: "/bin/sh",
},
&cli.StringFlag{
Name: "output",
Usage: "Default binary output location",
EnvVar: "OUTPUT",
Value: "sample",
},
&cli.StringFlag{
Name: "directory",
Usage: "Directory to pack",
EnvVar: "DIRECTORY",
Value: "",
},
&cli.StringFlag{
Name: "app-description",
Usage: "App description",
EnvVar: "DESCRIPTION",
Value: "sample",
},
&cli.StringFlag{
Name: "app-copyright",
Usage: "App copyright",
EnvVar: "COPYRIGHT",
Value: "sample",
},
&cli.StringFlag{
Name: "app-author",
Usage: "App author",
EnvVar: "AUTHOR",
Value: "sample",
},
&cli.StringFlag{
Name: "app-name",
Usage: "Application name",
EnvVar: "NAME",
Value: "sample",
},
&cli.StringFlag{
Name: "app-version",
Usage: "Application version. This is used during bundle upgrades.",
EnvVar: "VERSION",
Value: "0.1",
},
&cli.BoolFlag{
Name: "local",
EnvVar: "LOCAL",
Usage: "Use local docker daemon to retrieve the image",
},
&cli.StringSliceFlag{
Name: "app-mounts",
Usage: "Define a list of default application mount bindings. For example: /tmp, /dev:/foo/dev",
EnvVar: "MOUNTS",
},
&cli.StringSliceFlag{
Name: "app-attrs",
Usage: "Define a list of default application attrs. Example: ipc, net, user",
EnvVar: "ATTRS",
Value: &cli.StringSlice{"ipc", "uts", "user", "ns", "pid"},
},
&cli.StringSliceFlag{
Name: "app-store",
Usage: "Define a default application store where the bundle content will be uncompressed. It defaults to a temporary directory otherwise. (e.g. $HOME/.app/foo)",
EnvVar: "STORE",
},
&cli.StringFlag{
Usage: "Image to be used as bundle content",
Name: "image",
EnvVar: "IMAGE",
Value: "alpine",
},
&cli.StringFlag{
Name: "command-prefix",
EnvVar: "COMMAND_PREFIX",
Value: "sudo",
Usage: "Prefix go generate commands with sudo. This is required if not running bundler as root and want to preserve container permissions",
},
}
}
func pocoVersion() string {
return fmt.Sprintf("%s-g%s", internal.Version, internal.Commit)
}
func cliParse(c *cli.Context) *bundler.Bundler {
opts := []bundler.Option{
bundler.WithRenderData(
c.String("image"),
c.String("command-prefix"),
c.Bool("local"),
c.String("directory") == "",
bundler.App{
Name: c.String("app-name"),
Author: c.String("app-author"),
Version: c.String("app-version"),
Entrypoint: c.String("entrypoint"),
Mounts: c.StringSlice("app-mounts"),
Attrs: c.StringSlice("app-attrs"),
Copyright: c.String("app-copyright"),
Description: c.String("app-description"),
Store: c.String("app-store"),
PocoVersion: pocoVersion(),
},
),
bundler.WithDirectory(c.String("directory")),
}
compression := c.String("compression")
if compression == "" {
compression = "xz"
}
opts = append(opts, bundler.WithCompression(compression))
b, err := bundler.New(opts...)
if err != nil {
pterm.Fatal.Println(err)
}
return b
}
func main() {
app := &cli.App{
Name: "poco",
Version: pocoVersion(),
Author: "Ettore Di Giacinto",
Usage: "poco (bundle|render|pack|unpack)",
Description: "poco bundles container images as portable static binaries",
UsageText: `
Poco can build portable, statically linked binaries from containers.
For example:
$ CGO_ENABLED=0 poco bundle --image alpine --output alpine
will create an alpine binary which contains the alpine image and will start by default /bin/sh.
To try it, run: ./alpine
Every generated binary has a help too and take several options, use the --help on the generated binary.
`,
Copyright: "Ettore Di Giacinto",
Commands: []cli.Command{
{
Flags: common(),
Name: "render",
Aliases: []string{"r"},
UsageText: "poco render --image foo /dst",
Usage: "render golang code from container images",
Description: `
Render golang generated files to the supplied dir
$ poco render --image foo /dst
`,
Action: func(c *cli.Context) error {
k := cliParse(c)
if c.Args().First() == "" {
return errors.New("need one parameter at least")
}
pterm.Info.Println("Rendering in", c.Args().First())
k.Render(c.Args().First())
return nil
},
},
{
Name: "extract",
Aliases: []string{"e"},
Usage: "extract a binary and its libraries into a folder",
UsageText: "extract <BIN> <DIR>",
Action: func(c *cli.Context) error {
src := c.Args()[0]
dst := c.Args()[1]
return extractor.Extract(extractor.WithFiles(src), extractor.WithOutputDir(dst))
},
},
{
Flags: common(),
Name: "unpack",
Aliases: []string{"u"},
Usage: "unpacks a container image into a directory",
UsageText: "unpack <IMAGE> <DIR>",
Action: func(c *cli.Context) error {
k := cliParse(c)
src := c.Args()[0]
dst := c.Args()[1]
pterm.Info.Printfln(
"Downloading image '%s' and unpacking into '%s' (local daemon: %t)",
src, dst, c.Bool("local"),
)
return k.DownloadImage(src, dst, c.Bool("local"))
},
},
{
Name: "pack",
Aliases: []string{"p"},
Flags: []cli.Flag{
&cli.StringFlag{
Name: "destination",
Usage: "Destination image tar",
Value: "output.tar",
},
&cli.StringFlag{
Name: "os",
Value: runtime.GOOS,
Usage: "Overrides default image OS",
},
&cli.StringFlag{
Name: "arch",
Value: runtime.GOARCH,
Usage: "Overrides default image ARCH",
},
},
Description: `
Packs files inside a tar which is consumable by docker.
E.g.
$ poco --destination out.tar foo/image:tar srcfile1 srcfile2 srcdir1 ...
$ docker load -i out.tar
$ docker push foo/image:tar ...
`,
Usage: "pack a directory as a container image",
Action: func(c *cli.Context) error {
if !c.Args().Present() {
return errors.New("need an image and source files to include inside the tar")
}
if c.Bool("debug") {
pterm.EnableDebugMessages()
}
dst := c.String("destination")
img := c.Args().First()
src := c.Args().Tail()
dir, err := os.MkdirTemp("", "containerbay")
if err != nil {
return err
}
defer os.RemoveAll(dir)
err = archiver.Archive(src, filepath.Join(dir, "archive.tar"))
if err != nil {
return err
}
pterm.Info.Printfln("Creating '%s' as '%s' from %v", dst, img, src)
return image.CreateTar(filepath.Join(dir, "archive.tar"), dst, img, c.String("arch"), c.String("os"))
},
},
{
Name: "pack-assets",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "C",
Usage: "Change dir",
Value: "",
},
&cli.StringFlag{
Name: "compression",
Usage: "Compression format",
Value: "zst",
},
&cli.StringFlag{
Name: "destination",
Usage: "Destination",
Value: "assets",
},
},
Description: `
Packs files inside a tar which is consumable by docker.
E.g.
$ poco pack-assets srcfile1 srcfile2 srcdir1
`,
Usage: "pack files as assets",
Action: func(c *cli.Context) error {
if !c.Args().Present() {
return errors.New("need an image and source files to include inside the tar")
}
if c.Bool("debug") {
pterm.EnableDebugMessages()
}
dst := c.String("destination")
src := c.Args()
compressionType := c.String("compression")
changeDir := c.String("C")
pterm.Info.Printfln(
"Creating '%s' from '%s', %s compression",
dst,
strings.Join(src, " "),
compressionType,
)
if path.Ext(dst) == "" {
dst = fmt.Sprintf("%s.tar.%s", dst, compressionType)
} else {
dst = fmt.Sprintf("%s.tar.%s", strings.ReplaceAll(dst, path.Ext(dst), ""), compressionType)
}
var cwd string
if changeDir != "" {
if !path.IsAbs(dst) {
var err error
cwd, err = os.Getwd()
if err != nil {
return err
}
}
os.Chdir(changeDir)
}
err := archiver.Archive(src, dst)
if err != nil {
return err
}
if changeDir != "" {
os.Chdir(cwd)
}
// This is to preserve '.' inside the resulting archive
if !path.IsAbs(dst) && changeDir != "" {
output := path.Join(changeDir, path.Base(dst))
defer os.RemoveAll(output)
return copy.Copy(output, path.Join(cwd, dst))
}
return nil
},
},
{
Flags: append(
common(),
&cli.StringFlag{
Name: "compression",
Usage: "Compression format",
Value: "zst",
},
),
Name: "bundle",
Aliases: []string{"b"},
UsageText: "bundle --image <IMAGE> --entrypoint /bin/sh",
Usage: "generate golang binary from container images",
Description: `Bundle containers into portable binaries
For example,
$ CGO_ENABLED=0 poco bundle --local --image kodi:latest --output kodi --entrypoint /usr/bin/kodi --app-mounts /sys --app-mounts /tmp --app-mounts /run --app-store '$HOME/.foo'
Creates a portable binary 'kodi' from the 'kodi:latest' image available in the local Docker daemon (--local).
It also associates to automatically mount /sys, /tmp and /run by default when starting and will unpack the binary content inside the user $HOME/.foo directory (be careful of the single quote).
`,
Action: func(c *cli.Context) (err error) {
k := cliParse(c)
pterm.Info.Printfln(
"Creating bundle '%s' (version %s) from image '%s' with entrypoint '%s'",
c.String("app-name"),
c.String("app-version"),
c.String("image"),
c.String("entrypoint"),
)
mounts := c.StringSlice("app-mounts")
if len(mounts) > 0 {
pterm.Info.Printfln(
"Default mounts: %s", strings.Join(mounts, " "),
)
}
return k.Build(c.String("output"))
},
},
},
}
err := app.Run(os.Args)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}