-
Notifications
You must be signed in to change notification settings - Fork 556
/
main.go
320 lines (280 loc) · 9.47 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
// Runtime module for the Python SDK
package main
import (
"context"
_ "embed"
"fmt"
"path"
"strings"
"github.com/iancoleman/strcase"
)
const (
DefaultVersion = "3.11"
DefaultImage = "python:%s-slim"
DefaultDigest = "sha256:ce81dc539f0aedc9114cae640f8352fad83d37461c24a3615b01f081d0c0583a"
ModSourceDirPath = "/src"
RuntimeExecutablePath = "/runtime"
GenDir = "sdk"
GenPath = "src/dagger/client/gen.py"
SchemaPath = "/schema.json"
VenvPath = "/opt/venv"
LockFilePath = "requirements.lock"
MainFilePath = "src/main/__init__.py"
MainObjectName = "Main"
)
// UserConfig is the custom user configuration that users can add to their pyproject.toml.
//
// For example:
// ```toml
// [tool.dagger]
// use-uv = false
// ```
type UserConfig struct {
// UseUv is for choosing the faster uv tool instead of pip to install packages.
UseUv bool `toml:"use-uv"`
// UvVersion is the version of the uv tool to use.
//
// By default, it's pinned to a specific version in each dagger version,
// can be useful to get a newer version to fix a bug or get a new feature.
UvVersion string `toml:"uv-version"`
// BaseImage is the image reference to use for the container.
BaseImage string `toml:"base-image"`
}
func New(
// Directory with the Python SDK source code.
// +optional
sdkSourceDir *Directory,
) *PythonSdk {
if sdkSourceDir == nil {
sdkSourceDir = dag.Directory()
}
return &PythonSdk{
Discovery: NewDiscovery(UserConfig{
UseUv: true,
UvVersion: getRequirement("uv"),
}),
// TODO: get an sdist build of the SDK into the engine rather than
// duplicating which files to include in the engine's publishing task.
SDKSourceDir: sdkSourceDir.WithoutDirectory("runtime"),
Container: dag.Container(),
}
}
//go:embed template/main.py
var tplMain string
// Functions for building the runtime module for the Python SDK.
//
// The server interacts directly with the ModuleRuntime and Codegen functions.
// The others were built to be composable and chainable to facilitate the
// creation of extension modules (custom SDKs that depend on this one).
type PythonSdk struct {
// Directory with the Python SDK source code
SDKSourceDir *Directory
// List of patterns to allways include when loading Python modules
RequiredPaths []string
// Resulting container after each composing step
Container *Container
// Discovery holds the logic for getting more information from the target module
// +private
Discovery *Discovery
}
// Generated code for the Python module
func (m *PythonSdk) Codegen(ctx context.Context, modSource *ModuleSource, introspectionJSON string) (*GeneratedCode, error) {
ctr, err := m.Common(ctx, modSource, introspectionJSON)
if err != nil {
return nil, err
}
return dag.GeneratedCode(ctr.Directory(ModSourceDirPath)).
WithVCSGeneratedPaths(
[]string{GenDir + "/**"},
).
WithVCSIgnoredPaths(
[]string{GenDir},
), nil
}
// Container for executing the Python module runtime
func (m *PythonSdk) ModuleRuntime(
ctx context.Context,
modSource *ModuleSource,
introspectionJSON string,
) (*Container, error) {
ctr, err := m.Common(ctx, modSource, introspectionJSON)
if err != nil {
return nil, err
}
return ctr.WithEntrypoint([]string{RuntimeExecutablePath}), nil
}
// Common steps for the ModuleRuntime and Codegen functions.
func (m *PythonSdk) Common(ctx context.Context, modSource *ModuleSource, introspectionJSON string) (*Container, error) {
// The following functions were built to be composable in a granular way,
// to allow a custom SDK to depend on this one and hook into before or
// after major steps in the process. For example, you can get the base
// container, add system packages, use the new one with `WithContainer`,
// and then continue with the rest of the steps. Without this, you'd need
// to copy the entire function and modify it.
// In extension modules, Load is chainable.
m, err := m.Load(ctx, modSource)
if err != nil {
return nil, err
}
ctr := m.
WithBase().
WithTemplate().
WithSDK(introspectionJSON).
WithSource().
Container
return ctr, nil
}
// Get all the needed information from the module's metadata and source files
func (m *PythonSdk) Load(ctx context.Context, modSource *ModuleSource) (*PythonSdk, error) {
if err := m.Discovery.Load(ctx, modSource); err != nil {
return nil, fmt.Errorf("runtime module load: %w", err)
}
return m, nil
}
// Initialize the container with the base image and installer
//
// Workdir is set to the module's source directory.
func (m *PythonSdk) WithBase() *PythonSdk {
base := dag.Container().
From(m.BaseImage()).
WithEnvVariable("DAGGER_BASE_IMAGE", m.BaseImage()).
WithEnvVariable("PYTHONUNBUFFERED", "1").
WithEnvVariable("PIP_DISABLE_PIP_VERSION_CHECK", "1").
WithEnvVariable("PIP_ROOT_USER_ACTION", "ignore").
WithMountedCache("/root/.cache/pip", m.cacheVolume("pip")).
// for debugging
WithDefaultTerminalCmd([]string{"/bin/bash"})
if m.UseUv() {
uv := base.
WithEnvVariable("PYTHONDONTWRITEBYTECODE", "1").
WithNewFile("reqs.txt", ContainerWithNewFileOpts{
Contents: "uv" + m.Discovery.UserConfig().UvVersion,
}).
WithExec([]string{"pip", "install", "-r", "/reqs.txt"}).
File("/usr/local/bin/uv")
base = base.
WithFile("/usr/local/bin/uv", uv).
WithMountedCache("/root/.cache/uv", m.cacheVolume("uv")).
// Use a clean venv with uv
WithExec([]string{"uv", "venv", VenvPath}).
WithEnvVariable("VIRTUAL_ENV", VenvPath).
WithEnvVariable("PATH", "$VIRTUAL_ENV/bin:$PATH", ContainerWithEnvVariableOpts{
Expand: true,
})
}
m.Container = base.WithWorkdir(path.Join(ModSourceDirPath, m.Discovery.SubPath))
return m
}
// Add the template files, to skafold a new module
//
// The following files are added:
// - /runtime
// - pyproject.toml
// - requirements.lock
// - src/main/__init__.py
func (m *PythonSdk) WithTemplate() *PythonSdk {
template := dag.CurrentModule().Source().Directory("template")
d := m.Discovery
m.Container = m.Container.WithFile(
RuntimeExecutablePath,
template.File("runtime.py"),
ContainerWithFileOpts{Permissions: 0o755},
)
// NB: We can't detect if it's a new module with `dagger develop --sdk`
// if there's also a pyproject.toml file to customize the base container.
//
// The reason for adding sources only on new modules is because it's
// been reported that it's surprising for users to delete the pyhton
// file on the host and not fail on `dagger functions` and `dagger call`,
// if we always recreate from the template. That's because only `init`
// and `develop` export the generated files back to the host, potentially
// creating a discrepancy.
//
// Throwing an error on missing files when not a new module is less
// surprising, which is done during discovery.
if d.IsInit {
toml := "pyproject.toml"
// On `dagger init --sdk`, one can first set a `pyproject.toml` to
// change the base image, but if it's `dagger develop --sdk` the
// existence of this file will exclude the rest from being added.
if !d.HasFile(toml) {
d.AddFile(toml, template.File(toml))
}
if m.UseUv() && !d.HasFile(LockFilePath) {
sdkToml := path.Join(GenDir, toml)
d.AddLockFile(m.Container.
WithMountedFile(sdkToml, m.SDKSourceDir.File(toml)).
WithMountedFile(toml, d.GetFile(toml)).
WithExec([]string{
"uv", "pip", "compile", "-q",
"--generate-hashes",
"-o", LockFilePath,
sdkToml,
toml,
}).
File(LockFilePath),
)
}
if !d.HasFile("*.py") {
d.AddNewFile(
MainFilePath,
strings.ReplaceAll(tplMain, MainObjectName, strcase.ToCamel(d.ModName)),
)
}
}
return m
}
// Add the SDK package to the source directory
//
// This includes regenerating the client for the current API schema.
func (m *PythonSdk) WithSDK(introspectionJSON string) *PythonSdk {
// "codegen" dir included in the exported sdk directory to support
// extending the runtime module in a custom SDK.
m.Discovery.AddDirectory(GenDir, m.SDKSourceDir)
// Allow empty introspection to facilitate debugging the container with a
// `dagger call module-runtime terminal` command.
if introspectionJSON != "" {
genFile := m.Container.
WithMountedDirectory("/codegen", m.SDKSourceDir.Directory("codegen")).
WithWorkdir("/codegen").
With(m.install("-r", LockFilePath)).
WithNewFile(SchemaPath, ContainerWithNewFileOpts{
Contents: introspectionJSON,
}).
WithExec([]string{
"python", "-m", "codegen", "generate", "-i", SchemaPath, "-o", "/gen.py",
}).
File("/gen.py")
m.Discovery.AddFile(path.Join(GenDir, GenPath), genFile)
}
return m
}
// Add the module's source files and install
func (m *PythonSdk) WithSource() *PythonSdk {
toml := "pyproject.toml"
sdkToml := path.Join(GenDir, toml)
ctr := m.Container.WithMountedDirectory(ModSourceDirPath, m.Discovery.ContextDir)
// Support installing directly from a requirements.lock file to allow
// pinning dependencies.
if m.Discovery.HasFile(LockFilePath) {
if m.UseUv() && !m.Discovery.IsInit {
ctr = ctr.WithExec([]string{
"uv", "pip", "compile", "-q",
"--generate-hashes",
"-o", LockFilePath,
sdkToml,
toml,
})
}
// Install from lock separately to editable installs because of hashes.
ctr = ctr.With(m.install("-r", LockFilePath))
}
// Install the SDK as editable because of the generated client
ctr = ctr.With(m.install("-e", "./sdk", "-e", "."))
cmd := []string{"pip", "check"}
if m.UseUv() {
cmd = append([]string{"uv"}, cmd...)
}
m.Container = ctr.WithExec(cmd)
return m
}