forked from openshift-knative/kn-plugin-func
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontainerize_go.go
More file actions
201 lines (175 loc) · 4.85 KB
/
containerize_go.go
File metadata and controls
201 lines (175 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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
package oci
import (
"archive/tar"
"compress/gzip"
"fmt"
"io"
"io/fs"
"os"
"os/exec"
slashpath "path"
"path/filepath"
"strings"
v1 "github.com/google/go-containerregistry/pkg/v1"
"github.com/google/go-containerregistry/pkg/v1/tarball"
fn "knative.dev/func/pkg/functions"
)
// Build the source code as Go, cross compiled for the given platform, placing
// the statically linked binary in a tarred layer and return the Descriptor
// and Layer metadata.
func buildGoLayer(cfg *buildConfig, p v1.Platform) (desc v1.Descriptor, layer v1.Layer, err error) {
// Executable
exe, err := goBuild(cfg, p) // Compile binary returning its path
if err != nil {
return
}
// Tarball
target := path(cfg.buildDir(), fmt.Sprintf("execlayer.%v.%v.tar.gz", p.OS, p.Architecture))
if err = newExecTarball(exe, target, cfg.verbose); err != nil {
return
}
// Layer
if layer, err = tarball.LayerFromFile(target); err != nil {
return
}
// Descriptor
if desc, err = newDescriptor(layer); err != nil {
return
}
desc.Platform = &p
// Blob
blob := path(cfg.blobsDir(), desc.Digest.Hex)
if cfg.verbose {
fmt.Printf("mv %v %v\n", rel(cfg.buildDir(), target), rel(cfg.buildDir(), blob))
}
err = os.Rename(target, blob)
return
}
func goBuild(cfg *buildConfig, p v1.Platform) (binPath string, err error) {
gobin, args, outpath, err := goBuildCmd(p, cfg)
if err != nil {
return
}
envs := goBuildEnvs(cfg.f, p)
if cfg.verbose {
fmt.Printf("%v %v\n", gobin, strings.Join(args, " "))
} else {
fmt.Printf(" %v\n", filepath.Base(outpath))
}
cmd := exec.CommandContext(cfg.ctx, gobin, "mod", "tidy")
cmd.Env = envs
cmd.Dir = cfg.buildDir()
cmd.Stderr = os.Stderr
cmd.Stdout = os.Stdout
err = cmd.Run()
if err != nil {
return "", fmt.Errorf("cannot sync deps: %w", err)
}
// Build the function
cmd = exec.CommandContext(cfg.ctx, gobin, args...)
cmd.Env = envs
cmd.Dir = cfg.buildDir()
cmd.Stderr = os.Stderr
cmd.Stdout = os.Stdout
return outpath, cmd.Run()
}
func goBuildCmd(p v1.Platform, cfg *buildConfig) (gobin string, args []string, outpath string, err error) {
/* TODO: Use Build Command override from the function if provided
* A future PR will include the ability to specify a
* f.Build.BuildCommand, or BuildArgs for use here to customize
* This will be useful when, for example, the function is written in
* Go and the function developer needs Libc compatibility, in which case
* the default command will need to be replaced with:
* go build -ldflags "-linkmode 'external' -extldflags '-static'"
* Pseudocode:
* if BuildArgs or BuildCommand
* Validate command or args are safe to run
* no other commands injected
* does not contain Go's "toolexec"
* does not specify the output path
* Either replace or append to gobin
*/
// Use the binary specified FUNC_GO_PATH if defined
gobin = os.Getenv("FUNC_GO_PATH") // TODO: move to main and plumb through
if gobin == "" {
gobin = "go"
}
// Build as ./func/builds/$PID/result/f.$OS.$Architecture
name := fmt.Sprintf("f.%v.%v", p.OS, p.Architecture)
if p.Variant != "" {
name = name + "." + p.Variant
}
outpath = path(cfg.buildDir(), "result", name)
args = []string{"build", "-o", outpath}
return gobin, args, outpath, nil
}
func goBuildEnvs(f fn.Function, p v1.Platform) (envs []string) {
pegged := []string{
"CGO_ENABLED=0",
"GOOS=" + p.OS,
"GOARCH=" + p.Architecture,
}
if p.Variant != "" && p.Architecture == "arm" {
pegged = append(pegged, "GOARM="+strings.TrimPrefix(p.Variant, "v"))
} else if p.Variant != "" && p.Architecture == "amd64" {
pegged = append(pegged, "GOAMD64="+p.Variant)
}
isPegged := func(env string) bool {
for _, v := range pegged {
name := strings.Split(v, "=")[0]
if strings.HasPrefix(env, name) {
return true
}
}
return false
}
envs = append(envs, pegged...)
for _, env := range os.Environ() {
if !isPegged(env) {
envs = append(envs, env)
}
}
return envs
}
func newExecTarball(source, target string, verbose bool) error {
targetFile, err := os.Create(target)
if err != nil {
return err
}
defer targetFile.Close()
gw := gzip.NewWriter(targetFile)
defer gw.Close()
tw := tar.NewWriter(gw)
defer tw.Close()
info, err := os.Stat(source)
if err != nil {
return err
}
header, err := tar.FileInfoHeader(info, info.Name())
if err != nil {
return err
}
header.Mode = (header.Mode & ^int64(fs.ModePerm)) | 0755
header.Name = slashpath.Join("/func", "f")
// TODO: should we set file timestamps to the build start time of cfg.t?
// header.ModTime = timestampArgument
if err = tw.WriteHeader(header); err != nil {
return err
}
if verbose {
fmt.Printf("→ %v \n", header.Name)
}
file, err := os.Open(source)
if err != nil {
return err
}
defer file.Close()
i, err := io.Copy(tw, file)
if err != nil {
return err
}
if verbose {
fmt.Printf(" wrote %v bytes \n", i)
}
return nil
}