|
| 1 | +import logging |
| 2 | +import os |
| 3 | +import signal |
| 4 | +import subprocess |
| 5 | +import threading |
| 6 | +import uuid |
| 7 | +from collections.abc import Generator |
| 8 | +from queue import Queue |
| 9 | +from threading import Lock, Semaphore |
| 10 | +from typing import TypeVar |
| 11 | + |
| 12 | +from gevent.os import tp_read |
| 13 | +from pydantic import BaseModel, ValidationError |
| 14 | + |
| 15 | +from dify_plugin.config.integration_config import IntegrationConfig |
| 16 | +from dify_plugin.core.entities.plugin.request import ( |
| 17 | + PluginAccessAction, |
| 18 | + PluginInvokeType, |
| 19 | +) |
| 20 | +from dify_plugin.integration.entities import PluginGenericResponse, PluginInvokeRequest, ResponseType |
| 21 | +from dify_plugin.integration.exc import PluginStoppedError |
| 22 | + |
| 23 | +T = TypeVar("T") |
| 24 | + |
| 25 | +logger = logging.getLogger(__name__) |
| 26 | + |
| 27 | + |
| 28 | +class PluginRunner: |
| 29 | + """ |
| 30 | + A class that runs a plugin locally. |
| 31 | +
|
| 32 | + Usage: |
| 33 | + ```python |
| 34 | + with PluginRunner( |
| 35 | + config=IntegrationConfig(), |
| 36 | + plugin_package_path="./langgenius-agent_0.0.14.difypkg", |
| 37 | + ) as runner: |
| 38 | + for result in runner.invoke( |
| 39 | + PluginInvokeType.Agent, |
| 40 | + AgentActions.InvokeAgentStrategy, |
| 41 | + payload=request.AgentInvokeRequest( |
| 42 | + user_id="hello", |
| 43 | + agent_strategy_provider="agent", |
| 44 | + agent_strategy="function_calling", |
| 45 | + agent_strategy_params=agent_strategy_params, |
| 46 | + ), |
| 47 | + response_type=AgentInvokeMessage, |
| 48 | + ): |
| 49 | + assert result |
| 50 | + ``` |
| 51 | + """ |
| 52 | + |
| 53 | + R = TypeVar("R", bound=BaseModel) |
| 54 | + |
| 55 | + def __init__(self, config: IntegrationConfig, plugin_package_path: str, extra_args: list[str] | None = None): |
| 56 | + self.config = config |
| 57 | + self.plugin_package_path = plugin_package_path |
| 58 | + self.extra_args = extra_args or [] |
| 59 | + |
| 60 | + # create pipe to communicate with the plugin |
| 61 | + self.stdout_pipe_read, self.stdout_pipe_write = os.pipe() |
| 62 | + self.stderr_pipe_read, self.stderr_pipe_write = os.pipe() |
| 63 | + self.stdin_pipe_read, self.stdin_pipe_write = os.pipe() |
| 64 | + |
| 65 | + # stdin write lock |
| 66 | + self.stdin_write_lock = Lock() |
| 67 | + |
| 68 | + # setup stop flag |
| 69 | + self.stop_flag = False |
| 70 | + self.stop_flag_lock = Lock() |
| 71 | + |
| 72 | + logger.info(f"Running plugin from {plugin_package_path}") |
| 73 | + |
| 74 | + self.process = subprocess.Popen( # noqa: S603 |
| 75 | + [config.dify_cli_path, "plugin", "run", plugin_package_path, "--response-format", "json", *self.extra_args], |
| 76 | + stdout=self.stdout_pipe_write, |
| 77 | + stderr=self.stderr_pipe_write, |
| 78 | + stdin=self.stdin_pipe_read, |
| 79 | + ) |
| 80 | + |
| 81 | + logger.info(f"Plugin process created with pid {self.process.pid}") |
| 82 | + |
| 83 | + # wait for plugin to be ready |
| 84 | + self.ready_semaphore = Semaphore(0) |
| 85 | + |
| 86 | + # create a thread to read the stdout and stderr |
| 87 | + self.stdout_reader = threading.Thread(target=self._message_reader, args=(self.stdout_pipe_read,)) |
| 88 | + try: |
| 89 | + self.stdout_reader.start() |
| 90 | + except Exception as e: |
| 91 | + raise e |
| 92 | + |
| 93 | + self.q = dict[str, Queue[PluginGenericResponse | None]]() |
| 94 | + self.q_lock = Lock() |
| 95 | + |
| 96 | + # wait for the plugin to be ready |
| 97 | + self.ready_semaphore.acquire() |
| 98 | + |
| 99 | + logger.info("Plugin ready") |
| 100 | + |
| 101 | + def _close(self): |
| 102 | + with self.stop_flag_lock: |
| 103 | + if self.stop_flag: |
| 104 | + return |
| 105 | + |
| 106 | + # stop the plugin |
| 107 | + self.stop_flag = True |
| 108 | + |
| 109 | + # send signal SIGTERM to the plugin, so it can exit gracefully |
| 110 | + # do collect garbage like removing temporary files |
| 111 | + os.kill(self.process.pid, signal.SIGTERM) |
| 112 | + |
| 113 | + # wait for the plugin to exit |
| 114 | + self.process.wait() |
| 115 | + |
| 116 | + # close the pipes |
| 117 | + os.close(self.stdout_pipe_write) |
| 118 | + os.close(self.stderr_pipe_write) |
| 119 | + os.close(self.stdin_pipe_read) |
| 120 | + |
| 121 | + def _read_async(self, fd: int) -> bytes: |
| 122 | + # read data from stdin using tp_read in 64KB chunks. |
| 123 | + # the OS buffer for stdin is usually 64KB, so using a larger value doesn't make sense. |
| 124 | + b = tp_read(fd, 65536) |
| 125 | + if not b: |
| 126 | + raise PluginStoppedError() |
| 127 | + return b |
| 128 | + |
| 129 | + def _message_reader(self, pipe: int): |
| 130 | + # create a scanner to read the message line by line |
| 131 | + """Read messages line by line from the pipe.""" |
| 132 | + buffer = b"" |
| 133 | + try: |
| 134 | + while True: |
| 135 | + try: |
| 136 | + data = self._read_async(pipe) |
| 137 | + except PluginStoppedError: |
| 138 | + break |
| 139 | + |
| 140 | + if not data: |
| 141 | + continue |
| 142 | + |
| 143 | + buffer += data |
| 144 | + |
| 145 | + # if no b"\n" is in data, skip to the next iteration |
| 146 | + if data.find(b"\n") == -1: |
| 147 | + continue |
| 148 | + |
| 149 | + # process line by line and keep the last line if it is not complete |
| 150 | + lines = buffer.split(b"\n") |
| 151 | + buffer = lines[-1] |
| 152 | + |
| 153 | + lines = lines[:-1] |
| 154 | + for line in lines: |
| 155 | + line = line.strip() |
| 156 | + if not line: |
| 157 | + continue |
| 158 | + |
| 159 | + self._publish_message(line.decode("utf-8")) |
| 160 | + finally: |
| 161 | + self._close() |
| 162 | + |
| 163 | + def _publish_message(self, message: str): |
| 164 | + # parse the message |
| 165 | + try: |
| 166 | + parsed_message = PluginGenericResponse.model_validate_json(message) |
| 167 | + except ValidationError: |
| 168 | + return |
| 169 | + |
| 170 | + if not parsed_message.invoke_id: |
| 171 | + if parsed_message.type == ResponseType.PLUGIN_READY: |
| 172 | + self.ready_semaphore.release() |
| 173 | + elif parsed_message.type == ResponseType.ERROR: |
| 174 | + raise ValueError(parsed_message.response) |
| 175 | + elif parsed_message.type == ResponseType.INFO: |
| 176 | + logger.info(parsed_message.response) |
| 177 | + return |
| 178 | + |
| 179 | + with self.q_lock: |
| 180 | + if parsed_message.invoke_id not in self.q: |
| 181 | + return |
| 182 | + if parsed_message.type == ResponseType.PLUGIN_INVOKE_END: |
| 183 | + self.q[parsed_message.invoke_id].put(None) |
| 184 | + else: |
| 185 | + self.q[parsed_message.invoke_id].put(parsed_message) |
| 186 | + |
| 187 | + def _write_to_pipe(self, data: bytes): |
| 188 | + # split the data into chunks of 4096 bytes |
| 189 | + chunks = [data[i : i + 4096] for i in range(0, len(data), 4096)] |
| 190 | + with ( |
| 191 | + self.stdin_write_lock |
| 192 | + ): # a lock is needed to avoid race condition when facing multiple threads writing to the pipe. |
| 193 | + for chunk in chunks: |
| 194 | + os.write(self.stdin_pipe_write, chunk) |
| 195 | + |
| 196 | + def invoke( |
| 197 | + self, |
| 198 | + access_type: PluginInvokeType, |
| 199 | + access_action: PluginAccessAction, |
| 200 | + payload: BaseModel, |
| 201 | + response_type: type[R], |
| 202 | + ) -> Generator[R, None, None]: |
| 203 | + with self.stop_flag_lock: |
| 204 | + if self.stop_flag: |
| 205 | + raise PluginStoppedError() |
| 206 | + |
| 207 | + invoke_id = uuid.uuid4().hex |
| 208 | + request = PluginInvokeRequest( |
| 209 | + invoke_id=invoke_id, |
| 210 | + type=access_type, |
| 211 | + action=access_action, |
| 212 | + request=payload, |
| 213 | + ) |
| 214 | + |
| 215 | + q = Queue[PluginGenericResponse | None]() |
| 216 | + with self.q_lock: |
| 217 | + self.q[invoke_id] = q |
| 218 | + |
| 219 | + try: |
| 220 | + # send invoke request to the plugin |
| 221 | + self._write_to_pipe(request.model_dump_json().encode("utf-8") + b"\n") |
| 222 | + |
| 223 | + # wait for events |
| 224 | + while message := q.get(): |
| 225 | + if message.invoke_id == invoke_id: |
| 226 | + if message.type == ResponseType.PLUGIN_RESPONSE: |
| 227 | + yield response_type.model_validate(message.response) |
| 228 | + elif message.type == ResponseType.ERROR: |
| 229 | + raise ValueError(message.response) |
| 230 | + else: |
| 231 | + raise ValueError("Invalid response type") |
| 232 | + else: |
| 233 | + raise ValueError("Invalid invoke id") |
| 234 | + finally: |
| 235 | + with self.q_lock: |
| 236 | + del self.q[invoke_id] |
| 237 | + |
| 238 | + def __enter__(self): |
| 239 | + return self |
| 240 | + |
| 241 | + def __exit__(self, exc_type, exc_value, traceback): |
| 242 | + self._close() |
0 commit comments