/
modfunc.go
384 lines (337 loc) · 11.4 KB
/
modfunc.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
package core
import (
"context"
"encoding/json"
"fmt"
"strings"
"github.com/iancoleman/strcase"
bkgw "github.com/moby/buildkit/frontend/gateway/client"
"github.com/moby/buildkit/util/bklog"
"github.com/opencontainers/go-digest"
ocispecs "github.com/opencontainers/image-spec/specs-go/v1"
"go.opentelemetry.io/otel/propagation"
"github.com/dagger/dagger/analytics"
"github.com/dagger/dagger/core/pipeline"
"github.com/dagger/dagger/dagql"
"github.com/dagger/dagger/dagql/call"
"github.com/dagger/dagger/engine"
"github.com/dagger/dagger/engine/buildkit"
)
type ModuleFunction struct {
root *Query
mod *Module
objDef *ObjectTypeDef // may be nil for special functions like the module definition function call
runtime *Container
metadata *Function
returnType ModType
args map[string]*UserModFunctionArg
}
type UserModFunctionArg struct {
metadata *FunctionArg
modType ModType
}
func newModFunction(
ctx context.Context,
root *Query,
mod *Module,
modID *call.ID,
objDef *ObjectTypeDef,
runtime *Container,
metadata *Function,
) (*ModuleFunction, error) {
returnType, ok, err := mod.ModTypeFor(ctx, metadata.ReturnType, true)
if err != nil {
return nil, fmt.Errorf("failed to get mod type for function %q return type: %w", metadata.Name, err)
}
if !ok {
return nil, fmt.Errorf("failed to find mod type for function %q return type: %q", metadata.Name, metadata.ReturnType.ToType())
}
argTypes := make(map[string]*UserModFunctionArg, len(metadata.Args))
for _, argMetadata := range metadata.Args {
argModType, ok, err := mod.ModTypeFor(ctx, argMetadata.TypeDef, true)
if err != nil {
return nil, fmt.Errorf("failed to get mod type for function %q arg %q type: %w", metadata.Name, argMetadata.Name, err)
}
if !ok {
return nil, fmt.Errorf("failed to find mod type for function %q arg %q type", metadata.Name, argMetadata.Name)
}
argTypes[argMetadata.Name] = &UserModFunctionArg{
metadata: argMetadata,
modType: argModType,
}
}
return &ModuleFunction{
root: root,
mod: mod,
objDef: objDef,
runtime: runtime,
metadata: metadata,
returnType: returnType,
args: argTypes,
}, nil
}
type CallOpts struct {
Inputs []CallInput
ParentVal map[string]any
Cache bool
Pipeline pipeline.Path
SkipSelfSchema bool
}
type CallInput struct {
Name string
Value dagql.Typed
}
func (fn *ModuleFunction) recordCall(ctx context.Context) {
mod := fn.mod
if fn.metadata.Name == "" {
return
}
props := map[string]string{
"target_function": fn.metadata.Name,
}
moduleAnalyticsProps(mod, "target_", props)
if caller, err := mod.Query.CurrentModule(ctx); err == nil {
props["caller_type"] = "module"
moduleAnalyticsProps(caller, "caller_", props)
} else if dagql.IsInternal(ctx) {
props["caller_type"] = "internal"
} else {
props["caller_type"] = "direct"
}
analytics.Ctx(ctx).Capture(ctx, "module_call", props)
}
func (fn *ModuleFunction) Call(ctx context.Context, caller *call.ID, opts *CallOpts) (t dagql.Typed, rerr error) {
mod := fn.mod
lg := bklog.G(ctx).WithField("module", mod.Name()).WithField("function", fn.metadata.Name)
if fn.objDef != nil {
lg = lg.WithField("object", fn.objDef.Name)
}
ctx = bklog.WithLogger(ctx, lg)
// Capture analytics for the function call.
// Calls without function name are internal and excluded.
fn.recordCall(ctx)
callInputs := make([]*FunctionCallArgValue, len(opts.Inputs))
hasArg := map[string]bool{}
for i, input := range opts.Inputs {
normalizedName := gqlArgName(input.Name)
arg, ok := fn.args[normalizedName]
if !ok {
return nil, fmt.Errorf("failed to find arg %q", input.Name)
}
name := arg.metadata.OriginalName
converted, err := arg.modType.ConvertToSDKInput(ctx, input.Value)
if err != nil {
return nil, fmt.Errorf("failed to convert arg %q: %w", input.Name, err)
}
encoded, err := json.Marshal(converted)
if err != nil {
return nil, fmt.Errorf("failed to marshal arg %q: %w", input.Name, err)
}
callInputs[i] = &FunctionCallArgValue{
Name: name,
Value: encoded,
}
hasArg[name] = true
}
for _, arg := range fn.metadata.Args {
name := arg.OriginalName
if hasArg[name] || arg.DefaultValue == nil {
continue
}
callInputs = append(callInputs, &FunctionCallArgValue{
Name: name,
Value: arg.DefaultValue,
})
}
callerDigestInputs := []string{}
{
callerIDDigest := caller.Digest() // FIXME(vito) canonicalize, once all that's implemented
callerDigestInputs = append(callerDigestInputs, callerIDDigest.String())
}
if !opts.Cache {
// use the ServerID so that we bust cache once-per-session
clientMetadata, err := engine.ClientMetadataFromContext(ctx)
if err != nil {
return nil, fmt.Errorf("failed to get client metadata: %w", err)
}
callerDigestInputs = append(callerDigestInputs, clientMetadata.ServerID)
}
callerDigest := digest.FromString(strings.Join(callerDigestInputs, " "))
ctx = bklog.WithLogger(ctx, bklog.G(ctx).WithField("caller_digest", callerDigest.String()))
bklog.G(ctx).Debug("function call")
defer func() {
bklog.G(ctx).Debug("function call done")
if rerr != nil {
bklog.G(ctx).WithError(rerr).Error("function call errored")
}
}()
ctr := fn.runtime
metaDir := NewScratchDirectory(mod.Query, mod.Query.Platform)
ctr, err := ctr.WithMountedDirectory(ctx, modMetaDirPath, metaDir, "", false)
if err != nil {
return nil, fmt.Errorf("failed to mount mod metadata directory: %w", err)
}
ctr, err = ctr.UpdateImageConfig(ctx, func(cfg ocispecs.ImageConfig) ocispecs.ImageConfig {
// Used by the shim to associate logs to the function call instead of the
// exec /runtime process, which we hide.
tc := propagation.TraceContext{}
carrier := propagation.MapCarrier{}
tc.Inject(ctx, carrier)
for _, f := range tc.Fields() {
name := "DAGGER_FUNCTION_" + strcase.ToScreamingSnake(f)
if val, ok := carrier[f]; ok {
cfg.Env = append(cfg.Env, name+"="+val)
}
}
return cfg
})
if err != nil {
return nil, fmt.Errorf("failed to update image config: %w", err)
}
// Setup the Exec for the Function call and evaluate it
ctr, err = ctr.WithExec(ctx, ContainerExecOpts{
ModuleCallerDigest: callerDigest,
ExperimentalPrivilegedNesting: true,
NestedInSameSession: true,
})
if err != nil {
return nil, fmt.Errorf("failed to exec function: %w", err)
}
parentJSON, err := json.Marshal(opts.ParentVal)
if err != nil {
return nil, fmt.Errorf("failed to marshal parent value: %w", err)
}
callMeta := &FunctionCall{
Query: fn.root,
Name: fn.metadata.OriginalName,
Parent: parentJSON,
InputArgs: callInputs,
}
if fn.objDef != nil {
callMeta.ParentName = fn.objDef.OriginalName
}
var deps *ModDeps
if opts.SkipSelfSchema {
// Only serve the APIs of the deps of this module. This is currently only needed for the special
// case of the function used to get the definition of the module itself (which can't obviously
// be served the API its returning the definition of).
deps = mod.Deps
} else {
// by default, serve both deps and the module's own API to itself
deps = mod.Deps.Prepend(mod)
}
err = mod.Query.RegisterFunctionCall(ctx, callerDigest, deps, fn.mod, callMeta)
if err != nil {
return nil, fmt.Errorf("failed to register function call: %w", err)
}
_, err = ctr.Evaluate(ctx)
if err != nil {
if fn.metadata.OriginalName == "" {
return nil, fmt.Errorf("call constructor: %w", err)
} else {
return nil, fmt.Errorf("call function %q: %w", fn.metadata.OriginalName, err)
}
}
ctrOutputDir, err := ctr.Directory(ctx, modMetaDirPath)
if err != nil {
return nil, fmt.Errorf("failed to get function output directory: %w", err)
}
result, err := ctrOutputDir.Evaluate(ctx)
if err != nil {
return nil, fmt.Errorf("failed to evaluate function: %w", err)
}
if result == nil {
return nil, fmt.Errorf("function returned nil result")
}
// TODO: if any error happens below, we should really prune the cache of the result, otherwise
// we can end up in a state where we have a cached result with a dependency blob that we don't
// guarantee the continued existence of...
// Read the output of the function
outputBytes, err := result.Ref.ReadFile(ctx, bkgw.ReadRequest{
Filename: modMetaOutputPath,
})
if err != nil {
return nil, fmt.Errorf("failed to read function output file: %w", err)
}
var returnValue any
dec := json.NewDecoder(strings.NewReader(string(outputBytes)))
dec.UseNumber()
if err := dec.Decode(&returnValue); err != nil {
return nil, fmt.Errorf("failed to unmarshal result: %w", err)
}
returnValueTyped, err := fn.returnType.ConvertFromSDKResult(ctx, returnValue)
if err != nil {
return nil, fmt.Errorf("failed to convert return value: %w", err)
}
if err := fn.linkDependencyBlobs(ctx, result, returnValueTyped); err != nil {
return nil, fmt.Errorf("failed to link dependency blobs: %w", err)
}
return returnValueTyped, nil
}
func (fn *ModuleFunction) ReturnType() (ModType, error) {
return fn.returnType, nil
}
func (fn *ModuleFunction) ArgType(argName string) (ModType, error) {
arg, ok := fn.args[gqlArgName(argName)]
if !ok {
return nil, fmt.Errorf("failed to find arg %q", argName)
}
return arg.modType, nil
}
func moduleAnalyticsProps(mod *Module, prefix string, props map[string]string) {
props[prefix+"module_name"] = mod.Name()
source := mod.Source.Self
switch source.Kind {
case ModuleSourceKindLocal:
local := source.AsLocalSource.Value
props[prefix+"source_kind"] = "local"
props[prefix+"local_subpath"] = local.RootSubpath
case ModuleSourceKindGit:
git := source.AsGitSource.Value
props[prefix+"source_kind"] = "git"
props[prefix+"git_symbolic"] = git.Symbolic()
props[prefix+"git_clone_url"] = git.CloneURL()
props[prefix+"git_subpath"] = git.RootSubpath
props[prefix+"git_version"] = git.Version
props[prefix+"git_commit"] = git.Commit
}
}
// If the result of a Function call contains IDs of resources, we need to
// ensure that the cache entry for the Function call is linked for the cache
// entries of those resources if those entries aren't reproducible. Right now,
// the only unreproducible output are local dir imports, which are represented
// as blob:// sources. linkDependencyBlobs finds all such blob:// sources and
// adds a cache lease on that blob in the content store to the cacheResult of
// the function call.
//
// If we didn't do this, then it would be possible for Buildkit to prune the
// content pointed to by the blob:// source without pruning the function call
// cache entry. That would result callers being able to evaluate the result of
// a function call but hitting an error about missing content.
func (fn *ModuleFunction) linkDependencyBlobs(ctx context.Context, cacheResult *buildkit.Result, value dagql.Typed) error {
if value == nil {
return nil
}
pbDefs, err := collectPBDefinitions(ctx, value)
if err != nil {
return fmt.Errorf("failed to collect pb definitions: %w", err)
}
dependencyBlobs := map[digest.Digest]*ocispecs.Descriptor{}
for _, pbDef := range pbDefs {
dag, err := buildkit.DefToDAG(pbDef)
if err != nil {
return fmt.Errorf("failed to convert pb definition to dag: %w", err)
}
blobs, err := dag.BlobDependencies()
if err != nil {
return fmt.Errorf("failed to get blob dependencies: %w", err)
}
for k, v := range blobs {
dependencyBlobs[k] = v
}
}
if err := cacheResult.Ref.AddDependencyBlobs(ctx, dependencyBlobs); err != nil {
return fmt.Errorf("failed to add dependency blob: %w", err)
}
return nil
}