๐Ÿ“ฆ langgenius / dify-plugin-daemon

๐Ÿ“„ setup_python_environment.go ยท 477 lines
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477package local_runtime

import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"os"
	"os/exec"
	"path"
	"path/filepath"
	"strconv"
	"strings"
	"sync"
	"time"

	routinepkg "github.com/langgenius/dify-plugin-daemon/pkg/routine"
	"github.com/langgenius/dify-plugin-daemon/pkg/utils/log"
	"github.com/langgenius/dify-plugin-daemon/pkg/utils/routine"
)

func (p *LocalPluginRuntime) prepareUV() (string, error) {
	if p.uvPath != "" {
		return p.uvPath, nil
	}

	// using `from uv._find_uv import find_uv_bin; print(find_uv_bin())` to find uv path
	cmd := exec.Command(p.defaultPythonInterpreterPath, "-c", "from uv._find_uv import find_uv_bin; print(find_uv_bin())")
	cmd.Dir = p.State.WorkingPath
	output, err := cmd.Output()
	if err != nil {
		return "", fmt.Errorf("failed to find uv path: %w", err)
	}
	return strings.TrimSpace(string(output)), nil
}

func (p *LocalPluginRuntime) preparePipArgs() []string {
	args := []string{"install"}

	if p.appConfig.PipMirrorUrl != "" {
		args = append(args, "-i", p.appConfig.PipMirrorUrl)
	}

	args = append(args, "-r", "requirements.txt")

	if p.appConfig.PipVerbose {
		args = append(args, "-vvv")
	}

	if p.appConfig.PipExtraArgs != "" {
		extraArgs := strings.Split(p.appConfig.PipExtraArgs, " ")
		args = append(args, extraArgs...)
	}

	args = append([]string{"pip"}, args...)

	return args
}

func (p *LocalPluginRuntime) prepareSyncArgs() []string {
	args := []string{"sync", "--no-dev"}

	if p.appConfig.PipMirrorUrl != "" {
		args = append(args, "-i", p.appConfig.PipMirrorUrl)
	}

	if p.appConfig.PipVerbose {
		args = append(args, "-v")
	}

	if p.appConfig.PipExtraArgs != "" {
		extraArgs := strings.Split(p.appConfig.PipExtraArgs, " ")
		args = append(args, extraArgs...)
	}

	return args
}

func (p *LocalPluginRuntime) detectDependencyFileType() (PythonDependencyFileType, error) {
	pyprojectPath := path.Join(p.State.WorkingPath, string(pyprojectTomlFile))
	requirementsPath := path.Join(p.State.WorkingPath, string(requirementsTxtFile))

	if _, err := os.Stat(pyprojectPath); err == nil {
		return pyprojectTomlFile, nil
	}

	if _, err := os.Stat(requirementsPath); err == nil {
		return requirementsTxtFile, nil
	}

	return "", fmt.Errorf("neither %s nor %s found in plugin directory", pyprojectTomlFile, requirementsTxtFile)
}

func (p *LocalPluginRuntime) installDependencies(
	uvPath string,
	dependencyFileType PythonDependencyFileType,
) error {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
	defer cancel()

	var args []string
	switch dependencyFileType {
	case pyprojectTomlFile:
		args = p.prepareSyncArgs()
		log.Info("installing plugin dependencies", "plugin", p.Config.Identity(), "method", "uv sync", "file", pyprojectTomlFile)
	case requirementsTxtFile:
		args = p.preparePipArgs()
		log.Info("installing plugin dependencies", "plugin", p.Config.Identity(), "method", "uv pip install", "file", requirementsTxtFile)
	default:
		return fmt.Errorf("unsupported dependency file type: %s", dependencyFileType)
	}

	virtualEnvPath := path.Join(p.State.WorkingPath, ".venv")
	cmd := exec.CommandContext(ctx, uvPath, args...)
	cmd.Env = append(cmd.Env, "VIRTUAL_ENV="+virtualEnvPath, "PATH="+os.Getenv("PATH"))
	if p.appConfig.HttpProxy != "" {
		cmd.Env = append(cmd.Env, fmt.Sprintf("HTTP_PROXY=%s", p.appConfig.HttpProxy))
	}
	if p.appConfig.HttpsProxy != "" {
		cmd.Env = append(cmd.Env, fmt.Sprintf("HTTPS_PROXY=%s", p.appConfig.HttpsProxy))
	}
	if p.appConfig.NoProxy != "" {
		cmd.Env = append(cmd.Env, fmt.Sprintf("NO_PROXY=%s", p.appConfig.NoProxy))
	}
	cmd.Dir = p.State.WorkingPath

	// get stdout and stderr
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		return fmt.Errorf("failed to get stdout: %s", err)
	}
	defer stdout.Close()

	stderr, err := cmd.StderrPipe()
	if err != nil {
		return fmt.Errorf("failed to get stderr: %s", err)
	}
	defer stderr.Close()

	// start command
	if err := cmd.Start(); err != nil {
		return fmt.Errorf("failed to start command: %s", err)
	}

	defer func() {
		if cmd.Process != nil {
			cmd.Process.Kill()
		}
	}()

	var errMsg strings.Builder
	var wg sync.WaitGroup
	wg.Add(2)

	lastActiveAt := time.Now()

	routine.Submit(routinepkg.Labels{
		routinepkg.RoutineLabelKeyModule: "plugin_manager",
		routinepkg.RoutineLabelKeyMethod: "InitPythonEnvironment",
	}, func() {
		defer wg.Done()
		// read stdout
		buf := make([]byte, 1024)
		for {
			n, err := stdout.Read(buf)
			if err != nil {
				break
			}
			// FIXME: move the log to separated layer
			log.Info("installing plugin", "plugin", p.Config.Identity(), "output", string(buf[:n]))
			lastActiveAt = time.Now()
		}
	})

	routine.Submit(routinepkg.Labels{
		routinepkg.RoutineLabelKeyModule: "plugin_manager",
		routinepkg.RoutineLabelKeyMethod: "InitPythonEnvironment",
	}, func() {
		defer wg.Done()
		// read stderr
		buf := make([]byte, 1024)
		for {
			n, err := stderr.Read(buf)
			if err != nil && err != os.ErrClosed {
				lastActiveAt = time.Now()
				errMsg.WriteString(string(buf[:n]))
				break
			} else if err == os.ErrClosed {
				break
			}

			if n > 0 {
				errMsg.WriteString(string(buf[:n]))
				lastActiveAt = time.Now()
			}
		}
	})

	routine.Submit(routinepkg.Labels{
		routinepkg.RoutineLabelKeyModule: "plugin_manager",
		routinepkg.RoutineLabelKeyMethod: "InitPythonEnvironment",
	}, func() {
		ticker := time.NewTicker(5 * time.Second)
		defer ticker.Stop()
		for range ticker.C {
			if cmd.ProcessState != nil && cmd.ProcessState.Exited() {
				break
			}

			if time.Since(lastActiveAt) > time.Duration(
				p.appConfig.PythonEnvInitTimeout,
			)*time.Second {
				cmd.Process.Kill()
				errMsg.WriteString(fmt.Sprintf(
					"init process exited due to no activity for %d seconds",
					p.appConfig.PythonEnvInitTimeout,
				))
				break
			}
		}
	})

	wg.Wait()

	if err := cmd.Wait(); err != nil {
		return fmt.Errorf("failed to install dependencies: %s, output: %s", err, errMsg.String())
	}

	return nil
}

type PythonVirtualEnvironment struct {
	pythonInterpreterPath string
}

var (
	ErrVirtualEnvironmentNotFound = errors.New("virtual environment not found")
	ErrVirtualEnvironmentInvalid  = errors.New("virtual environment is invalid")
)

type PythonDependencyFileType string

const (
	pyprojectTomlFile   PythonDependencyFileType = "pyproject.toml"
	requirementsTxtFile PythonDependencyFileType = "requirements.txt"
)

const (
	envPath          = ".venv"
	envPythonPath    = envPath + "/bin/python"
	envValidFlagFile = envPath + "/dify/plugin.json"
)

func (p *LocalPluginRuntime) checkPythonVirtualEnvironment() (*PythonVirtualEnvironment, error) {
	if _, err := os.Stat(path.Join(p.State.WorkingPath, envPath)); err != nil {
		return nil, ErrVirtualEnvironmentNotFound
	}

	pythonPath, err := filepath.Abs(path.Join(p.State.WorkingPath, envPythonPath))
	if err != nil {
		return nil, fmt.Errorf("failed to find python: %s", err)
	}

	if _, err := os.Stat(pythonPath); err != nil {
		return nil, fmt.Errorf("failed to find python: %s", err)
	}

	// check if dify/plugin.json exists
	if _, err := os.Stat(path.Join(p.State.WorkingPath, envValidFlagFile)); err != nil {
		return nil, ErrVirtualEnvironmentInvalid
	}

	return &PythonVirtualEnvironment{
		pythonInterpreterPath: pythonPath,
	}, nil
}

func (p *LocalPluginRuntime) deleteVirtualEnvironment() error {
	// check if virtual environment exists
	if _, err := os.Stat(path.Join(p.State.WorkingPath, envPath)); err != nil {
		return nil
	}

	return os.RemoveAll(path.Join(p.State.WorkingPath, envPath))
}

func (p *LocalPluginRuntime) createVirtualEnvironment(
	uvPath string,
) (*PythonVirtualEnvironment, error) {
	cmd := exec.Command(uvPath, "venv", envPath, "--python", "3.12")
	cmd.Dir = p.State.WorkingPath
	b := bytes.NewBuffer(nil)
	cmd.Stdout = b
	cmd.Stderr = b
	if err := cmd.Run(); err != nil {
		return nil, fmt.Errorf("failed to create virtual environment: %s, output: %s", err, b.String())
	}

	pythonPath, err := filepath.Abs(path.Join(p.State.WorkingPath, envPythonPath))
	if err != nil {
		return nil, fmt.Errorf("failed to find python: %s", err)
	}

	if _, err := os.Stat(pythonPath); err != nil {
		return nil, fmt.Errorf("failed to find python: %s", err)
	}

	// try find pyproject.toml or requirements.txt
	dependencyFileType, err := p.detectDependencyFileType()
	if err != nil {
		return nil, fmt.Errorf("failed to find dependency file: %s", err)
	}

	log.Info("detected dependency file", "plugin", p.Config.Identity(), "file", dependencyFileType)

	return &PythonVirtualEnvironment{
		pythonInterpreterPath: pythonPath,
	}, nil
}

func (p *LocalPluginRuntime) getRequirementsPath() string {
	return path.Join(p.State.WorkingPath, string(requirementsTxtFile))
}

func (p *LocalPluginRuntime) getDependencyFilePath() (string, error) {
	dependencyFileType, err := p.detectDependencyFileType()
	if err != nil {
		return "", err
	}
	return path.Join(p.State.WorkingPath, string(dependencyFileType)), nil
}

func (p *LocalPluginRuntime) markVirtualEnvironmentAsValid() error {
	// pluginIdentityPath is a file that contains the timestamp of the virtual environment
	// which is used to mark the virtual environment as valid (All dependencies were installed)

	pluginJsonPath := path.Join(p.State.WorkingPath, envValidFlagFile)

	if err := os.MkdirAll(path.Dir(pluginJsonPath), 0755); err != nil {
		return fmt.Errorf("failed to create %s/dify directory: %s", envPath, err)
	}

	// write plugin.json
	if err := os.WriteFile(
		pluginJsonPath,
		[]byte(`{"timestamp":`+strconv.FormatInt(time.Now().Unix(), 10)+`}`),
		0644,
	); err != nil {
		return fmt.Errorf("failed to write plugin.json: %s", err)
	}

	return nil
}

func (p *LocalPluginRuntime) preCompile(
	pythonPath string,
) error {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
	defer cancel()

	compileArgs := []string{"-m", "compileall"}
	if p.appConfig.PythonCompileAllExtraArgs != "" {
		compileArgs = append(compileArgs, strings.Split(p.appConfig.PythonCompileAllExtraArgs, " ")...)
	}
	compileArgs = append(compileArgs, ".")

	// pre-compile the plugin to avoid costly compilation on first invocation
	compileCmd := exec.CommandContext(ctx, pythonPath, compileArgs...)
	compileCmd.Dir = p.State.WorkingPath

	// get stdout and stderr
	compileStdout, err := compileCmd.StdoutPipe()
	if err != nil {
		return fmt.Errorf("failed to get stdout: %s", err)
	}
	defer compileStdout.Close()

	compileStderr, err := compileCmd.StderrPipe()
	if err != nil {
		return fmt.Errorf("failed to get stderr: %s", err)
	}
	defer compileStderr.Close()

	// start command
	if err := compileCmd.Start(); err != nil {
		return fmt.Errorf("failed to start command: %s", err)
	}
	defer func() {
		if compileCmd.Process != nil {
			compileCmd.Process.Kill()
		}
	}()

	var compileErrMsg strings.Builder
	var compileWg sync.WaitGroup
	compileWg.Add(2)

	routine.Submit(routinepkg.Labels{
		routinepkg.RoutineLabelKeyModule: "plugin_manager",
		routinepkg.RoutineLabelKeyMethod: "InitPythonEnvironment",
	}, func() {
		defer compileWg.Done()
		// read compileStdout
		for {
			buf := make([]byte, 102400)
			n, err := compileStdout.Read(buf)
			if err != nil {
				break
			}
			// split to first line
			lines := strings.Split(string(buf[:n]), "\n")

			for len(lines) > 0 && len(lines[0]) == 0 {
				lines = lines[1:]
			}

			if len(lines) > 0 {
				if len(lines) > 1 {
					log.Info("pre-compiling plugin", "plugin", p.Config.Identity(), "file", lines[0], "more", true)
				} else {
					log.Info("pre-compiling plugin", "plugin", p.Config.Identity(), "file", lines[0])
				}
			}
		}
	})

	routine.Submit(routinepkg.Labels{
		routinepkg.RoutineLabelKeyModule: "plugin_manager",
		routinepkg.RoutineLabelKeyMethod: "InitPythonEnvironment",
	}, func() {
		defer compileWg.Done()
		// read stderr
		buf := make([]byte, 1024)
		for {
			n, err := compileStderr.Read(buf)
			if err != nil {
				break
			}
			compileErrMsg.WriteString(string(buf[:n]))
		}
	})

	compileWg.Wait()
	if err := compileCmd.Wait(); err != nil {
		// skip the error if the plugin is not compiled
		// ISSUE: for some weird reasons, plugins may reference to a broken sdk but it works well itself
		// we need to skip it but log the messages
		// https://github.com/langgenius/dify/issues/16292
		log.Warn("failed to pre-compile the plugin", "error", compileErrMsg.String())
	}

	log.Info("pre-loaded the plugin", "plugin", p.Config.Identity())

	// import dify_plugin to speedup the first launching
	// ISSUE: it takes too long to setup all the deps, that's why we choose to preload it
	importCmd := exec.CommandContext(ctx, pythonPath, "-c", "import dify_plugin")
	importCmd.Dir = p.State.WorkingPath
	importCmd.Output()

	return nil
}

func (p *LocalPluginRuntime) getVirtualEnvironmentPythonPath() (string, error) {
	// get the absolute path of the python interpreter

	pythonPath, err := filepath.Abs(path.Join(p.State.WorkingPath, envPythonPath))
	if err != nil {
		return "", fmt.Errorf("failed to join python path: %s", err)
	}

	if _, err := os.Stat(pythonPath); err != nil {
		return "", ErrVirtualEnvironmentNotFound
	}

	return pythonPath, nil
}