xflow.framework 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
xflow/framework/ssh.py ADDED
@@ -0,0 +1,372 @@
1
+ # Copyright (c) 2025-2026, zhaowcheng <zhaowcheng@163.com>
2
+
3
+ """
4
+ SSH 模块。
5
+ """
6
+
7
+ import time
8
+ import socket
9
+
10
+ from typing import Generator, Optional, Dict, Union, Callable
11
+ from select import select
12
+ from contextlib import contextmanager
13
+ from pathlib import Path, PurePosixPath
14
+
15
+ from decorator import decorator
16
+ from paramiko import SSHClient, AutoAddPolicy, SFTPClient
17
+ from paramiko.ssh_exception import (AuthenticationException,
18
+ NoValidConnectionsError,
19
+ SSHException)
20
+
21
+ from xflow.framework.errors import SSHConnectError, CommandError
22
+ from xflow.framework.utils import remove_ansi_escape_chars, remove_unprintable_chars
23
+
24
+
25
+ @decorator
26
+ def autopen(func, *args, **kwargs):
27
+ """
28
+ 自动连接器。
29
+ """
30
+ conn: SSHConnection = args[0]
31
+ conn.open()
32
+ return func(*args, **kwargs)
33
+
34
+
35
+ class CommandResult(str):
36
+ """
37
+ 命令输出结果。
38
+ """
39
+ def __new__(cls, out: str, rc: int = 0, cmd: str = '') -> str:
40
+ """
41
+ :param out: 输出。
42
+ :param rc: 返回码。
43
+ :param cmd: 执行的命令。
44
+ """
45
+ out = remove_ansi_escape_chars(out)
46
+ out = remove_unprintable_chars(out)
47
+ out = '\n'.join(out.splitlines())
48
+ o = str.__new__(cls, out.strip())
49
+ o.__rc = rc
50
+ o.__cmd = cmd
51
+ return o
52
+
53
+ @property
54
+ def rc(self) -> int:
55
+ """
56
+ 返回码。
57
+ """
58
+ return self.__rc
59
+
60
+ @property
61
+ def cmd(self) -> str:
62
+ """
63
+ 执行的命令。
64
+ """
65
+ return self.__cmd
66
+
67
+ def getfield(
68
+ self,
69
+ key: str,
70
+ col: int,
71
+ sep: str = None
72
+ ) -> Optional[str]:
73
+ """
74
+ 从输出中获取指定字段。
75
+
76
+ :param key: 用来筛选行的关键字。
77
+ :param col: 筛选行中字段所在的列号(从 1 开始)。
78
+ :param sep: 用来分割行的符号。
79
+
80
+ >>> r = CommandResult('''\\
81
+ ... UID PID CMD
82
+ ... postgres 45 /opt/pgsql/bin/postgres
83
+ ... postgres 51 postgres: checkpointer process
84
+ ... postgres 52 postgres: writer process
85
+ ... postgres 53 postgres: wal writer process''', 0, '')
86
+ >>> r.getfield('/opt/pgsql', 2)
87
+ '45'
88
+ >>> r.getfield('checkpointer', 1, sep=':')
89
+ 'postgres 51 postgres'
90
+ """
91
+ matchline = ''
92
+ lines = self.splitlines()
93
+ if isinstance(key, str):
94
+ for line in self.splitlines():
95
+ if key in line:
96
+ matchline = line
97
+ elif isinstance(key, int):
98
+ matchline = lines[key-1]
99
+ if matchline:
100
+ fields = matchline.split(sep)
101
+ return fields[col-1].strip()
102
+
103
+ def getcol(
104
+ self,
105
+ col: int,
106
+ sep: str = None
107
+ ) -> list:
108
+ """
109
+ 从输出中获取指定列。
110
+
111
+ :param col: 列号(从 1 开始)。
112
+ :param sep: 用来分割行的符号。
113
+
114
+ >>> r = CommandResult('''\\
115
+ ... UID PID CMD
116
+ ... postgres 45 /opt/pgsql/bin/postgres
117
+ ... postgres 51 postgres: checkpointer process
118
+ ... postgres 52 postgres: writer process
119
+ ... postgres 53 postgres: wal writer process''', 0, '')
120
+ >>> r.getcol(2)
121
+ ['PID', '45', '51', '52', '53']
122
+ """
123
+ fields = []
124
+ for line in self.splitlines():
125
+ segs = line.split(sep)
126
+ if col <= len(segs):
127
+ fields.append(segs[col-1])
128
+ return fields
129
+
130
+
131
+ class SSHConnection(object):
132
+ """
133
+ SSH 连接。
134
+ """
135
+ def __init__(
136
+ self,
137
+ ip: str,
138
+ user: str,
139
+ password: str,
140
+ port: int = 22,
141
+ envs: Optional[Dict[str, str]] = None
142
+ ):
143
+ """
144
+ :param ip: IP 地址。
145
+ :param user: 用户名。
146
+ :param password: 用户密码。
147
+ :param port: SSH 端口。
148
+ :param envs: 连接的默认环境变量,其中:
149
+ `LANG` 默认值为 `en_US.UTF-8`。
150
+ `LANGUAGE` 默认值为 `en_US.UTF-8`。
151
+ """
152
+ self._ip = ip
153
+ self._user = user
154
+ self._password = password
155
+ self._port = port
156
+ self._envs = envs or {}
157
+ self._connstr = f'ssh://{user}@{ip}:{port}'
158
+ self._cwd: str = ''
159
+ self._sshclient = SSHClient()
160
+ self._sshclient.set_missing_host_key_policy(AutoAddPolicy())
161
+ self._sftpclient: SFTPClient = None
162
+ for k, v in {'LANG': 'en_US.UTF-8',
163
+ 'LANGUAGE': 'en_US.UTF-8'}.items():
164
+ self._envs.setdefault(k, v)
165
+
166
+ def _progress_bar_generator(
167
+ self,
168
+ method: str,
169
+ local: Union[str, Path],
170
+ remote: Union[str, PurePosixPath],
171
+ interval: int = 1
172
+ ) -> Callable:
173
+ """
174
+ 文件传输进度展示函数生成器。
175
+
176
+ :param method: 传输方法,`get` 或 `put`。
177
+ :param local: 本地文件路径。
178
+ :param remote: 远端文件路径。
179
+ :param interval: 展示间隔(秒)。
180
+ :return: 进度展示函数。
181
+ """
182
+ local = Path(local)
183
+ remote = PurePosixPath(remote)
184
+ premsg = {
185
+ 'get': f'Get {local} <= {remote}',
186
+ 'put': f'Put {local} => {remote}'
187
+ }[method]
188
+ anchor = {'start': int(time.time()), 'last': None}
189
+ def progress_bar(transferred: int, total: int):
190
+ def getsize(b: int) -> str:
191
+ kb = b // 1024
192
+ mb = round(kb / 1024, 1)
193
+ gb = round(mb / 1024, 2)
194
+ if gb >= 1:
195
+ return f'{gb}GB'
196
+ elif mb >= 1:
197
+ return f'{mb}MB'
198
+ elif kb >= 1:
199
+ return f'{kb}KB'
200
+ else:
201
+ return f'{b}B'
202
+ totalsize = getsize(total)
203
+ transsize = getsize(transferred)
204
+ percent = int(transferred / total * 100)
205
+ now = int(time.time())
206
+ if (now - anchor['start']) % interval == 0 \
207
+ and now != anchor['last'] or percent == 100:
208
+ print(f'[{self._connstr}] {premsg} {transsize}/{totalsize} {percent}%')
209
+ anchor['last'] = now
210
+ return progress_bar
211
+
212
+ def open(self) -> None:
213
+ """
214
+ 开启连接。
215
+ """
216
+ transport = self._sshclient.get_transport()
217
+ if transport and transport.active:
218
+ return
219
+ timeout = 10
220
+ try:
221
+ print(f'[{self._connstr}] Connecting...')
222
+ self._sshclient.connect(self._ip,
223
+ port=self._port,
224
+ username=self._user,
225
+ password=self._password,
226
+ timeout=10)
227
+ self._sftpclient = self._sshclient.open_sftp()
228
+ print(f'[{self._connstr}] Connected')
229
+ except AuthenticationException:
230
+ raise SSHConnectError(
231
+ f'Authentication failed when SSH connect to {self._ip} with user `{self._user}`, '
232
+ f'please check whether the username and password are correct.'
233
+ ) from None
234
+ except socket.timeout:
235
+ raise SSHConnectError(
236
+ f'Timed out when SSH connect to {self._ip}({timeout}s), '
237
+ 'please check whether the network is normal.'
238
+ ) from None
239
+ except NoValidConnectionsError:
240
+ raise SSHConnectError(
241
+ f'Could not connect to port {self._port} on {self._ip}, '
242
+ 'please check whether the port is opened.'
243
+ ) from None
244
+ except SSHException as e:
245
+ msg = str(e)
246
+ if 'Error reading SSH protocol banner' in msg:
247
+ raise SSHConnectError(
248
+ f'Read SSH protocol banner failed when connect to port {self._port} '
249
+ f'on {self._ip}, please check whether the port is correct.'
250
+ ) from None
251
+ raise e from None
252
+
253
+ def close(self) -> None:
254
+ """
255
+ 关闭连接。
256
+ """
257
+ self._sshclient.close()
258
+ self._sftpclient.close()
259
+
260
+ @autopen()
261
+ def exec(
262
+ self,
263
+ cmd: str,
264
+ envs: Optional[Dict[str, str]] = None
265
+ ) -> CommandResult:
266
+ """
267
+ 执行命令。
268
+
269
+ :param cmd: 被执行的命令。
270
+ :param envs: 环境变量。
271
+ :return: 命令输出。
272
+
273
+ :raises:
274
+ `CommandError` -- 命令返回码不为 0。
275
+
276
+ >>> exec('ls /home') # successful # doctest: +SKIP
277
+ >>> exec('ls /errpath') # CommandError # doctest: +SKIP
278
+ """
279
+ envs = envs or {}
280
+ environment = self._envs.copy()
281
+ environment.update(envs)
282
+ print(f'[{self._connstr}:{self._cwd or "~"}] {cmd}')
283
+ stdin, stdout, stderr = self._sshclient.exec_command(
284
+ f'cd {self._cwd} && {cmd}' if self._cwd else cmd,
285
+ get_pty=True,
286
+ environment=environment)
287
+ output = ''
288
+ encoding = environment['LANG'].split('.')[-1]
289
+ while True:
290
+ rlist, _, _ = select([stdout.channel], [], [], 0.1)
291
+ if stdout.channel in rlist:
292
+ data = stdout.channel.recv(1024).decode(encoding=encoding, errors='ignore')
293
+ if data == '':
294
+ break
295
+ output += data
296
+ print(data, end='')
297
+ rc = stdout.channel.recv_exit_status()
298
+ if rc != 0:
299
+ raise CommandError(f'ExitCode {rc}: `{cmd}`')
300
+ return CommandResult(output, rc=rc, cmd=cmd)
301
+
302
+ @contextmanager
303
+ def dir(self, path: str | PurePosixPath) -> Generator[None, None, None]:
304
+ """
305
+ 切换工作目录。
306
+
307
+ >>> with dir('/my/workdir'): # doctest: +SKIP
308
+ ... d = exec('pwd') # doctest: +SKIP
309
+ ... # doctest: +SKIP
310
+ >>> d # doctest: +SKIP
311
+ '/my/workdir' # doctest: +SKIP
312
+ """
313
+ try:
314
+ self._cwd = str(path)
315
+ yield
316
+ finally:
317
+ self._cwd = ''
318
+
319
+ @autopen()
320
+ def getfile(
321
+ self,
322
+ rfile: Union[str, PurePosixPath],
323
+ ldir: Union[str, Path]
324
+ ) -> None:
325
+ """
326
+ 从远端下载文件 `rfile` 到本地目录 `ldir`。
327
+
328
+ :param rfile: 远端文件。
329
+ :param ldir: 本地目录。
330
+
331
+ >>> getfile('/tmp/myfile', '/home') # /home/myfile
332
+ >>> getfile('/tmp/myfile', 'D:\\') # D:\\myfile
333
+ """
334
+ rfile = PurePosixPath(rfile)
335
+ ldir = Path(ldir)
336
+ lfile = ldir.joinpath(rfile.name)
337
+ self._sftpclient.get(str(rfile), str(lfile),
338
+ callback=self._progress_bar_generator('get', lfile, rfile))
339
+
340
+ @autopen()
341
+ def putfile(
342
+ self,
343
+ lfile: Union[str, Path],
344
+ rdir: Union[str, PurePosixPath]
345
+ ) -> None:
346
+ """
347
+ 上传本地文件 `lfile` 到远端目录 `rdir`。
348
+
349
+ :param lfile: 本地文件。
350
+ :param rdir: 远端目录。
351
+
352
+ >>> putfile('/home/myfile', '/tmp') # /tmp/myfile
353
+ >>> putfile('D:\\myfile', '/tmp') # /tmp/myfile
354
+ """
355
+ lfile = Path(lfile)
356
+ rdir = PurePosixPath(rdir)
357
+ rfile = rdir.joinpath(lfile.name)
358
+ self._sftpclient.put(str(lfile), str(rfile),
359
+ callback=self._progress_bar_generator('put', lfile, rfile))
360
+
361
+ @autopen()
362
+ def exists(self, path: Union[str, PurePosixPath]) -> bool:
363
+ """
364
+ 检查远端路径是否存在。
365
+ """
366
+ try:
367
+ self._sftpclient.stat(str(path))
368
+ return True
369
+ except FileNotFoundError:
370
+
371
+ return False
372
+
@@ -0,0 +1,215 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[codz]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py.cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ #uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ #poetry.lock
109
+ #poetry.toml
110
+
111
+ # pdm
112
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
113
+ # pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
114
+ # https://pdm-project.org/en/latest/usage/project/#working-with-version-control
115
+ #pdm.lock
116
+ #pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # pixi
121
+ # Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
122
+ #pixi.lock
123
+ # Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
124
+ # in the .venv directory. It is recommended not to include this directory in version control.
125
+ .pixi
126
+
127
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
128
+ __pypackages__/
129
+
130
+ # Celery stuff
131
+ celerybeat-schedule
132
+ celerybeat.pid
133
+
134
+ # SageMath parsed files
135
+ *.sage.py
136
+
137
+ # Environments
138
+ .env
139
+ .envrc
140
+ .venv
141
+ env/
142
+ venv/
143
+ ENV/
144
+ env.bak/
145
+ venv.bak/
146
+
147
+ # Spyder project settings
148
+ .spyderproject
149
+ .spyproject
150
+
151
+ # Rope project settings
152
+ .ropeproject
153
+
154
+ # mkdocs documentation
155
+ /site
156
+
157
+ # mypy
158
+ .mypy_cache/
159
+ .dmypy.json
160
+ dmypy.json
161
+
162
+ # Pyre type checker
163
+ .pyre/
164
+
165
+ # pytype static type analyzer
166
+ .pytype/
167
+
168
+ # Cython debug symbols
169
+ cython_debug/
170
+
171
+ # PyCharm
172
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
173
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
174
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
175
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
176
+ #.idea/
177
+
178
+ # Abstra
179
+ # Abstra is an AI-powered process automation framework.
180
+ # Ignore directories containing user credentials, local state, and settings.
181
+ # Learn more at https://abstra.io/docs
182
+ .abstra/
183
+
184
+ # Visual Studio Code
185
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
186
+ # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
187
+ # and can be added to the global gitignore or merged into this file. However, if you prefer,
188
+ # you could uncomment the following to ignore the entire vscode folder
189
+ # .vscode/
190
+
191
+ # Ruff stuff:
192
+ .ruff_cache/
193
+
194
+ # PyPI configuration file
195
+ .pypirc
196
+
197
+ # Cursor
198
+ # Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to
199
+ # exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
200
+ # refer to https://docs.cursor.com/context/ignore-files
201
+ .cursorignore
202
+ .cursorindexingignore
203
+
204
+ # Marimo
205
+ marimo/_static/
206
+ marimo/_lsp/
207
+ __marimo__/
208
+
209
+
210
+ # IDE config files
211
+ .vscode/
212
+ .idea/
213
+
214
+ # workdir
215
+ workdir/
File without changes
@@ -0,0 +1,41 @@
1
+ # Docker 服务端列表
2
+ dockers:
3
+ - name: docker1
4
+ ip: 192.168.10.100
5
+ port: 2375
6
+ tls:
7
+ cacert: /path/to/ca-cert.pem # CA 证书(可选项)
8
+ clientcert: /path/to/client-cert.pem # 客户端证书(可选项,但提供 clientkey 时则必须提供该选项)
9
+ clientkey: /path/to/client-key.pem # 客户端私钥(可选项,但提供 clientcert 时则必须提供该选项)
10
+
11
+ # 节点列表
12
+ nodes:
13
+ - name: el7-x86_64 # 必须唯一
14
+ workdir: /home/xflow/workdir
15
+ envs:
16
+ PATH: /usr/local/pgsql/bin:$PATH
17
+ LD_LIBRARY_PATH: /usr/local/pgsql/lib:$LD_LIBRARY_PATH
18
+ PGPORT: 5432
19
+ # 以下是非 docker 类型节点的必填项。
20
+ ip: 192.168.10.10
21
+ sshport: 22
22
+ user: xflow # docker 类型节点时可选,不填将使用容器默认用户。
23
+ password: xflow@123
24
+ # 以下是 docker 类型节点的必填项。
25
+ docker:
26
+ image:
27
+ container:
28
+ - name: ubt22-aarch64
29
+ workdir: /home/xflow/workdir
30
+ envs:
31
+ # 以下是非 docker 类型节点的必填项。
32
+ ip:
33
+ sshport:
34
+ user: xflow # docker 类型节点时可选,不填将使用容器默认用户。
35
+ password: xflow@123
36
+ # 以下是 docker 类型节点的必填项。
37
+ docker: docker1 # docker 服务端名称。
38
+ container: # 容器名,和 image 为互斥项,如果指定则用该容器作为节点。
39
+ image: ubuntu-22.04 # 镜像名,和 container 为互斥项,如果指定则每次用该镜像启动一个新容器作为节点。
40
+ runargs: # 启动参数,当使用镜像启动容器时可以指定。
41
+ command: nix-daemon # 启动命令
File without changes
@@ -0,0 +1,60 @@
1
+ from xflow.framework.pipeline import Pipeline
2
+
3
+
4
+ class example(Pipeline):
5
+ """
6
+ pipeline 示例。
7
+ """
8
+ class Options(Pipeline.Options):
9
+ """
10
+ 流水线参数,根据需要自行定义。
11
+ """
12
+ pyver: int = Pipeline.Option(desc='Python version.',
13
+ default=3)
14
+ packtype: str = Pipeline.Option(desc='Package type.',
15
+ default='onedir',
16
+ choices=('onefile', 'onedir'))
17
+
18
+ def setup(self) -> None:
19
+ """
20
+ 前置步骤。
21
+ """
22
+ self.options: __class__.Options # 用于类型推断
23
+ super().setup()
24
+
25
+ def stage1(self) -> None:
26
+ """
27
+ 拉取代码。
28
+ """
29
+ self.node.exec('git clone https://ghfast.top/https://github.com/zhaowcheng/xbot.framework.git')
30
+
31
+ def stage2(self) -> None:
32
+ """
33
+ 编译代码。
34
+ """
35
+ with self.node.dir('xbot.framework'):
36
+ self.node.exec(f'python{self.options.pyver} -m venv venv')
37
+ self.node.exec('venv/bin/pip install -r requirements.txt')
38
+ self.node.exec('venv/bin/pip install pyinstaller')
39
+ self.node.exec(f'venv/bin/python -m PyInstaller --{self.options.packtype} -n xbot xbot/framework/main.py')
40
+
41
+ def stage3(self) -> None:
42
+ """
43
+ 打包。
44
+ """
45
+ self.node.putfile(
46
+ './requirements.txt',
47
+ self.node.cwd.joinpath('xbot.framework', 'dist')
48
+ )
49
+ with self.node.dir('xbot.framework/dist'):
50
+ self.node.exec('tar czvf xbot.tar.gz xbot/')
51
+ self.node.getfile(
52
+ self.node.cwd.joinpath('xbot.framework', 'dist', 'xbot.tar.gz'),
53
+ self.cwd
54
+ )
55
+
56
+ def teardown(self) -> None:
57
+ """
58
+ 后置步骤。
59
+ """
60
+ super().teardown()