opendrone-bin-sync-agent 0.1.0__tar.gz
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.
- opendrone_bin_sync_agent-0.1.0/.gitignore +229 -0
- opendrone_bin_sync_agent-0.1.0/PKG-INFO +6 -0
- opendrone_bin_sync_agent-0.1.0/README.md +42 -0
- opendrone_bin_sync_agent-0.1.0/pyproject.toml +29 -0
- opendrone_bin_sync_agent-0.1.0/src/opendrone_bin_sync_agent/__init__.py +1 -0
- opendrone_bin_sync_agent-0.1.0/src/opendrone_bin_sync_agent/__main__.py +3 -0
- opendrone_bin_sync_agent-0.1.0/src/opendrone_bin_sync_agent/agent.py +188 -0
- opendrone_bin_sync_agent-0.1.0/src/opendrone_bin_sync_agent/backend.py +71 -0
- opendrone_bin_sync_agent-0.1.0/src/opendrone_bin_sync_agent/cli.py +90 -0
- opendrone_bin_sync_agent-0.1.0/src/opendrone_bin_sync_agent/config.py +71 -0
- opendrone_bin_sync_agent-0.1.0/src/opendrone_bin_sync_agent/files.py +154 -0
- opendrone_bin_sync_agent-0.1.0/src/opendrone_bin_sync_agent/state.py +83 -0
- opendrone_bin_sync_agent-0.1.0/tests/test_config_files_state.py +245 -0
- opendrone_bin_sync_agent-0.1.0/tests/test_sync_agent.py +651 -0
- opendrone_bin_sync_agent-0.1.0/uv.lock +189 -0
|
@@ -0,0 +1,229 @@
|
|
|
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
|
+
*.lcov
|
|
51
|
+
.hypothesis/
|
|
52
|
+
.pytest_cache/
|
|
53
|
+
cover/
|
|
54
|
+
|
|
55
|
+
# Translations
|
|
56
|
+
*.mo
|
|
57
|
+
*.pot
|
|
58
|
+
|
|
59
|
+
# Django stuff:
|
|
60
|
+
*.log
|
|
61
|
+
local_settings.py
|
|
62
|
+
db.sqlite3
|
|
63
|
+
db.sqlite3-journal
|
|
64
|
+
|
|
65
|
+
# Flask stuff:
|
|
66
|
+
instance/
|
|
67
|
+
.webassets-cache
|
|
68
|
+
|
|
69
|
+
# Scrapy stuff:
|
|
70
|
+
.scrapy
|
|
71
|
+
|
|
72
|
+
# Sphinx documentation
|
|
73
|
+
docs/_build/
|
|
74
|
+
|
|
75
|
+
# PyBuilder
|
|
76
|
+
.pybuilder/
|
|
77
|
+
target/
|
|
78
|
+
|
|
79
|
+
# Jupyter Notebook
|
|
80
|
+
.ipynb_checkpoints
|
|
81
|
+
|
|
82
|
+
# IPython
|
|
83
|
+
profile_default/
|
|
84
|
+
ipython_config.py
|
|
85
|
+
|
|
86
|
+
# pyenv
|
|
87
|
+
# For a library or package, you might want to ignore these files since the code is
|
|
88
|
+
# intended to run in multiple environments; otherwise, check them in:
|
|
89
|
+
# .python-version
|
|
90
|
+
|
|
91
|
+
# pipenv
|
|
92
|
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
|
93
|
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
|
94
|
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
|
95
|
+
# install all needed dependencies.
|
|
96
|
+
# Pipfile.lock
|
|
97
|
+
|
|
98
|
+
# uv
|
|
99
|
+
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
|
100
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
101
|
+
# commonly ignored for libraries.
|
|
102
|
+
# uv.lock
|
|
103
|
+
|
|
104
|
+
# poetry
|
|
105
|
+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
|
106
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
107
|
+
# commonly ignored for libraries.
|
|
108
|
+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
|
109
|
+
# poetry.lock
|
|
110
|
+
# poetry.toml
|
|
111
|
+
|
|
112
|
+
# pdm
|
|
113
|
+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
|
114
|
+
# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
|
|
115
|
+
# https://pdm-project.org/en/latest/usage/project/#working-with-version-control
|
|
116
|
+
# pdm.lock
|
|
117
|
+
# pdm.toml
|
|
118
|
+
.pdm-python
|
|
119
|
+
.pdm-build/
|
|
120
|
+
|
|
121
|
+
# pixi
|
|
122
|
+
# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
|
|
123
|
+
# pixi.lock
|
|
124
|
+
# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
|
|
125
|
+
# in the .venv directory. It is recommended not to include this directory in version control.
|
|
126
|
+
.pixi/*
|
|
127
|
+
!.pixi/config.toml
|
|
128
|
+
|
|
129
|
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
|
130
|
+
__pypackages__/
|
|
131
|
+
|
|
132
|
+
# Celery stuff
|
|
133
|
+
celerybeat-schedule*
|
|
134
|
+
celerybeat.pid
|
|
135
|
+
|
|
136
|
+
# Redis
|
|
137
|
+
*.rdb
|
|
138
|
+
*.aof
|
|
139
|
+
*.pid
|
|
140
|
+
|
|
141
|
+
# RabbitMQ
|
|
142
|
+
mnesia/
|
|
143
|
+
rabbitmq/
|
|
144
|
+
rabbitmq-data/
|
|
145
|
+
|
|
146
|
+
# ActiveMQ
|
|
147
|
+
activemq-data/
|
|
148
|
+
|
|
149
|
+
# SageMath parsed files
|
|
150
|
+
*.sage.py
|
|
151
|
+
|
|
152
|
+
# Environments
|
|
153
|
+
.env
|
|
154
|
+
.envrc
|
|
155
|
+
.venv
|
|
156
|
+
env/
|
|
157
|
+
venv/
|
|
158
|
+
ENV/
|
|
159
|
+
env.bak/
|
|
160
|
+
venv.bak/
|
|
161
|
+
|
|
162
|
+
# Conda environments
|
|
163
|
+
conda-meta/
|
|
164
|
+
|
|
165
|
+
# Spyder project settings
|
|
166
|
+
.spyderproject
|
|
167
|
+
.spyproject
|
|
168
|
+
|
|
169
|
+
# Rope project settings
|
|
170
|
+
.ropeproject
|
|
171
|
+
|
|
172
|
+
# mkdocs/Zensical documentation
|
|
173
|
+
/site
|
|
174
|
+
|
|
175
|
+
# mypy
|
|
176
|
+
.mypy_cache/
|
|
177
|
+
.dmypy.json
|
|
178
|
+
dmypy.json
|
|
179
|
+
|
|
180
|
+
# Pyre type checker
|
|
181
|
+
.pyre/
|
|
182
|
+
|
|
183
|
+
# pytype static type analyzer
|
|
184
|
+
.pytype/
|
|
185
|
+
|
|
186
|
+
# Cython debug symbols
|
|
187
|
+
cython_debug/
|
|
188
|
+
|
|
189
|
+
# PyCharm
|
|
190
|
+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
|
191
|
+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
|
192
|
+
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
|
193
|
+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
|
194
|
+
# .idea/
|
|
195
|
+
|
|
196
|
+
# Abstra
|
|
197
|
+
# Abstra is an AI-powered process automation framework.
|
|
198
|
+
# Ignore directories containing user credentials, local state, and settings.
|
|
199
|
+
# Learn more at https://abstra.io/docs
|
|
200
|
+
.abstra/
|
|
201
|
+
|
|
202
|
+
# Visual Studio Code
|
|
203
|
+
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore that
|
|
204
|
+
# can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
|
|
205
|
+
# and can be added to the global gitignore or merged into this file. However, if you prefer, you
|
|
206
|
+
# could uncomment the following to ignore the entire vscode folder
|
|
207
|
+
# .vscode/
|
|
208
|
+
# Temporary file for partial code execution
|
|
209
|
+
tempCodeRunnerFile.py
|
|
210
|
+
|
|
211
|
+
# Ruff stuff:
|
|
212
|
+
.ruff_cache/
|
|
213
|
+
|
|
214
|
+
# PyPI configuration file
|
|
215
|
+
.pypirc
|
|
216
|
+
|
|
217
|
+
# Marimo
|
|
218
|
+
marimo/_static/
|
|
219
|
+
marimo/_lsp/
|
|
220
|
+
__marimo__/
|
|
221
|
+
|
|
222
|
+
# Streamlit
|
|
223
|
+
.streamlit/secrets.toml
|
|
224
|
+
|
|
225
|
+
# OpenDrone local data
|
|
226
|
+
.env
|
|
227
|
+
*.db
|
|
228
|
+
*.db-journal
|
|
229
|
+
data/
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# OpenDrone BIN Sync Agent
|
|
2
|
+
|
|
3
|
+
The agent watches a local folder for stable ArduPilot DataFlash `.BIN` files and uploads them to an OpenDrone API. It does not read MAVLink or Mission Planner `.tlog` files. It leaves source logs untouched and stores retry state in a local SQLite database.
|
|
4
|
+
|
|
5
|
+
## Requirements
|
|
6
|
+
|
|
7
|
+
- Python 3.12 or newer.
|
|
8
|
+
- [`uv`](https://docs.astral.sh/uv/getting-started/installation/) to install the command-line application.
|
|
9
|
+
- Read access to the folder where completed `.BIN` logs are available.
|
|
10
|
+
- Network access from the listener machine to the OpenDrone API.
|
|
11
|
+
|
|
12
|
+
## Install and run
|
|
13
|
+
|
|
14
|
+
Install the published command with:
|
|
15
|
+
|
|
16
|
+
```sh
|
|
17
|
+
uv tool install opendrone-bin-sync-agent
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Then configure a watch folder, API URL, and local state database path:
|
|
21
|
+
|
|
22
|
+
```sh
|
|
23
|
+
opendrone-bin-sync-agent \
|
|
24
|
+
--watch-dir "/path/to/completed/BIN/logs" \
|
|
25
|
+
--api-url "https://your-opendrone-host" \
|
|
26
|
+
--state-db "$HOME/.local/share/opendrone/bin-sync-agent.sqlite3"
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
On Windows PowerShell, quote paths with single quotes and use an expanded environment variable for the state file:
|
|
30
|
+
|
|
31
|
+
```powershell
|
|
32
|
+
opendrone-bin-sync-agent `
|
|
33
|
+
--watch-dir 'C:\Users\you\Documents\Mission Planner\logs' `
|
|
34
|
+
--api-url 'https://your-opendrone-host' `
|
|
35
|
+
--state-db "$env:LOCALAPPDATA\OpenDrone\bin-sync-agent.sqlite3"
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
The listener stays in the foreground until stopped with `Ctrl+C`. Read the Descargas page on your OpenDrone instance for operator setup, Mission Planner folder handoff, and troubleshooting.
|
|
39
|
+
|
|
40
|
+
## Release
|
|
41
|
+
|
|
42
|
+
Update `project.version` in `pyproject.toml`, review the package contents, and push a matching `bin-sync-agent-v<version>` tag. The GitHub Actions workflow builds the wheel and source distribution, then publishes them to PyPI using trusted publishing. Before the first release, configure the GitHub repository as a trusted publisher for the `opendrone-bin-sync-agent` PyPI project and create the `pypi` GitHub Actions environment. Never publish from an ordinary branch build.
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "opendrone-bin-sync-agent"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Synchronize completed ArduPilot DataFlash logs to OpenDrone"
|
|
5
|
+
requires-python = ">=3.12"
|
|
6
|
+
dependencies = ["httpx>=0.27,<1"]
|
|
7
|
+
|
|
8
|
+
[project.scripts]
|
|
9
|
+
opendrone-bin-sync-agent = "opendrone_bin_sync_agent.cli:main"
|
|
10
|
+
|
|
11
|
+
[dependency-groups]
|
|
12
|
+
dev = ["pytest>=8.3,<9", "ruff>=0.8,<1"]
|
|
13
|
+
|
|
14
|
+
[build-system]
|
|
15
|
+
requires = ["hatchling"]
|
|
16
|
+
build-backend = "hatchling.build"
|
|
17
|
+
|
|
18
|
+
[tool.hatch.build.targets.wheel]
|
|
19
|
+
packages = ["src/opendrone_bin_sync_agent"]
|
|
20
|
+
|
|
21
|
+
[tool.pytest.ini_options]
|
|
22
|
+
testpaths = ["tests"]
|
|
23
|
+
|
|
24
|
+
[tool.ruff]
|
|
25
|
+
line-length = 100
|
|
26
|
+
target-version = "py312"
|
|
27
|
+
|
|
28
|
+
[tool.ruff.lint]
|
|
29
|
+
select = ["E", "F", "I", "UP", "B"]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Standalone OpenDrone DataFlash synchronization agent."""
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
"""Durable polling agent for stable DataFlash log files."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
from opendrone_bin_sync_agent.backend import (
|
|
7
|
+
BackendRejected,
|
|
8
|
+
BackendUnavailable,
|
|
9
|
+
OpenDroneClient,
|
|
10
|
+
)
|
|
11
|
+
from opendrone_bin_sync_agent.config import AgentConfig
|
|
12
|
+
from opendrone_bin_sync_agent.files import (
|
|
13
|
+
FileIdentity,
|
|
14
|
+
FolderScanner,
|
|
15
|
+
SourceChangedError,
|
|
16
|
+
StabilityTracker,
|
|
17
|
+
create_snapshot,
|
|
18
|
+
sha256_file,
|
|
19
|
+
)
|
|
20
|
+
from opendrone_bin_sync_agent.state import AgentStateStore
|
|
21
|
+
|
|
22
|
+
logger = logging.getLogger(__name__)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class SyncAgent:
|
|
26
|
+
def __init__(
|
|
27
|
+
self,
|
|
28
|
+
config: AgentConfig,
|
|
29
|
+
*,
|
|
30
|
+
backend_client: OpenDroneClient | None = None,
|
|
31
|
+
state: AgentStateStore | None = None,
|
|
32
|
+
) -> None:
|
|
33
|
+
self.config = config
|
|
34
|
+
self.backend = backend_client or OpenDroneClient(config.api_url)
|
|
35
|
+
self.state = state or AgentStateStore(config.state_db_path)
|
|
36
|
+
self.scanner = FolderScanner(config.watch_dir)
|
|
37
|
+
self.stability = StabilityTracker(config.stability_seconds)
|
|
38
|
+
self.state.recover_interrupted()
|
|
39
|
+
|
|
40
|
+
def scan_once(self, now: float | None = None) -> None:
|
|
41
|
+
try:
|
|
42
|
+
candidates = self.scanner.discover()
|
|
43
|
+
except OSError as exc:
|
|
44
|
+
logger.warning("Cannot scan watched folder %s: %s", self.config.watch_dir, exc)
|
|
45
|
+
return
|
|
46
|
+
for path in candidates:
|
|
47
|
+
try:
|
|
48
|
+
stable_identity = self.stability.stable_identity(path, now=now)
|
|
49
|
+
if stable_identity is None:
|
|
50
|
+
continue
|
|
51
|
+
self._sync(path, stable_identity)
|
|
52
|
+
except OSError as exc:
|
|
53
|
+
self.stability.invalidate(path)
|
|
54
|
+
logger.warning("Cannot process watched file %s: %s", path, exc)
|
|
55
|
+
|
|
56
|
+
def _sync(self, source_path: Path, expected_identity: FileIdentity) -> None:
|
|
57
|
+
try:
|
|
58
|
+
snapshot = create_snapshot(source_path)
|
|
59
|
+
except (FileNotFoundError, SourceChangedError):
|
|
60
|
+
self.stability.invalidate(source_path)
|
|
61
|
+
return
|
|
62
|
+
|
|
63
|
+
try:
|
|
64
|
+
if snapshot.source_identity != expected_identity:
|
|
65
|
+
self.stability.invalidate(source_path)
|
|
66
|
+
return
|
|
67
|
+
|
|
68
|
+
existing = self.state.get_version(source_path, snapshot.sha256)
|
|
69
|
+
if existing is not None and existing["state"] in {"synced", "failed"}:
|
|
70
|
+
return
|
|
71
|
+
|
|
72
|
+
self.state.save_version(
|
|
73
|
+
path=source_path,
|
|
74
|
+
sha256=snapshot.sha256,
|
|
75
|
+
size_bytes=snapshot.size_bytes,
|
|
76
|
+
mtime_ns=snapshot.mtime_ns,
|
|
77
|
+
state="uploading",
|
|
78
|
+
flight_id=existing["flight_id"] if existing else None,
|
|
79
|
+
last_error=None,
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
try:
|
|
83
|
+
if existing and existing["flight_id"]:
|
|
84
|
+
response = self.backend.get_flight(existing["flight_id"])
|
|
85
|
+
else:
|
|
86
|
+
response = self.backend.upload_file(snapshot.snapshot_path, source_path.name)
|
|
87
|
+
except BackendUnavailable as exc:
|
|
88
|
+
self._save_pending(snapshot, str(exc))
|
|
89
|
+
return
|
|
90
|
+
except BackendRejected as exc:
|
|
91
|
+
self._save_failed(snapshot, str(exc))
|
|
92
|
+
return
|
|
93
|
+
|
|
94
|
+
status = response.get("status")
|
|
95
|
+
flight_id = response.get("id")
|
|
96
|
+
if not flight_id:
|
|
97
|
+
self._save_pending(snapshot, "OpenDrone API response did not include a flight id")
|
|
98
|
+
return
|
|
99
|
+
|
|
100
|
+
if response.get("sha256") != snapshot.sha256:
|
|
101
|
+
self._save_failed(
|
|
102
|
+
snapshot,
|
|
103
|
+
"OpenDrone API response checksum did not match the uploaded file",
|
|
104
|
+
flight_id=flight_id,
|
|
105
|
+
)
|
|
106
|
+
return
|
|
107
|
+
|
|
108
|
+
if not self._source_matches_snapshot(snapshot):
|
|
109
|
+
self.state.save_version(
|
|
110
|
+
path=source_path,
|
|
111
|
+
sha256=snapshot.sha256,
|
|
112
|
+
size_bytes=snapshot.size_bytes,
|
|
113
|
+
mtime_ns=snapshot.mtime_ns,
|
|
114
|
+
state="pending",
|
|
115
|
+
flight_id=flight_id,
|
|
116
|
+
last_error="Watched file changed during upload; checking its current version",
|
|
117
|
+
)
|
|
118
|
+
self.stability.invalidate(source_path)
|
|
119
|
+
return
|
|
120
|
+
|
|
121
|
+
if status == "ready":
|
|
122
|
+
self.state.save_version(
|
|
123
|
+
path=source_path,
|
|
124
|
+
sha256=snapshot.sha256,
|
|
125
|
+
size_bytes=snapshot.size_bytes,
|
|
126
|
+
mtime_ns=snapshot.mtime_ns,
|
|
127
|
+
state="synced",
|
|
128
|
+
flight_id=flight_id,
|
|
129
|
+
)
|
|
130
|
+
logger.info("Vuelo sincronizado: %s (id %s)", source_path.name, flight_id)
|
|
131
|
+
elif status == "failed":
|
|
132
|
+
self._save_failed(
|
|
133
|
+
snapshot,
|
|
134
|
+
str(response.get("error_summary") or "OpenDrone could not process the log"),
|
|
135
|
+
flight_id=flight_id,
|
|
136
|
+
)
|
|
137
|
+
else:
|
|
138
|
+
logger.info("Vuelo recibido; procesamiento pendiente: %s", source_path.name)
|
|
139
|
+
self.state.save_version(
|
|
140
|
+
path=source_path,
|
|
141
|
+
sha256=snapshot.sha256,
|
|
142
|
+
size_bytes=snapshot.size_bytes,
|
|
143
|
+
mtime_ns=snapshot.mtime_ns,
|
|
144
|
+
state="processing",
|
|
145
|
+
flight_id=flight_id,
|
|
146
|
+
)
|
|
147
|
+
finally:
|
|
148
|
+
snapshot.cleanup()
|
|
149
|
+
|
|
150
|
+
def _source_matches_snapshot(self, snapshot) -> bool:
|
|
151
|
+
try:
|
|
152
|
+
return sha256_file(
|
|
153
|
+
snapshot.source_path, expected_identity=snapshot.source_identity
|
|
154
|
+
) == snapshot.sha256
|
|
155
|
+
except (FileNotFoundError, OSError, SourceChangedError):
|
|
156
|
+
return False
|
|
157
|
+
|
|
158
|
+
def _save_pending(self, snapshot, error: str) -> None:
|
|
159
|
+
logger.warning(
|
|
160
|
+
"Sincronización pendiente para %s; se reintentará: %s",
|
|
161
|
+
snapshot.source_path.name,
|
|
162
|
+
error,
|
|
163
|
+
)
|
|
164
|
+
self.state.save_version(
|
|
165
|
+
path=snapshot.source_path,
|
|
166
|
+
sha256=snapshot.sha256,
|
|
167
|
+
size_bytes=snapshot.size_bytes,
|
|
168
|
+
mtime_ns=snapshot.mtime_ns,
|
|
169
|
+
state="pending",
|
|
170
|
+
flight_id=None,
|
|
171
|
+
last_error=error,
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
def _save_failed(self, snapshot, error: str, flight_id: str | None = None) -> None:
|
|
175
|
+
logger.error("Error al sincronizar %s: %s", snapshot.source_path.name, error)
|
|
176
|
+
self.state.save_version(
|
|
177
|
+
path=snapshot.source_path,
|
|
178
|
+
sha256=snapshot.sha256,
|
|
179
|
+
size_bytes=snapshot.size_bytes,
|
|
180
|
+
mtime_ns=snapshot.mtime_ns,
|
|
181
|
+
state="failed",
|
|
182
|
+
flight_id=flight_id,
|
|
183
|
+
last_error=error,
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
def close(self) -> None:
|
|
187
|
+
self.backend.close()
|
|
188
|
+
self.state.close()
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""HTTP client for the existing OpenDrone flight API."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
import httpx
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class BackendUnavailable(RuntimeError):
|
|
10
|
+
"""A transient backend/network error that should leave the version pending."""
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class BackendRejected(RuntimeError):
|
|
14
|
+
"""A terminal client error returned by the backend."""
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class OpenDroneClient:
|
|
18
|
+
def __init__(
|
|
19
|
+
self,
|
|
20
|
+
api_url: str,
|
|
21
|
+
*,
|
|
22
|
+
transport: httpx.BaseTransport | None = None,
|
|
23
|
+
timeout_seconds: float = 30,
|
|
24
|
+
) -> None:
|
|
25
|
+
self._client = httpx.Client(
|
|
26
|
+
base_url=api_url.rstrip("/"),
|
|
27
|
+
transport=transport,
|
|
28
|
+
timeout=timeout_seconds,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
def upload_file(self, path: Path, filename: str) -> dict[str, Any]:
|
|
32
|
+
try:
|
|
33
|
+
with path.open("rb") as source:
|
|
34
|
+
response = self._client.post(
|
|
35
|
+
"/api/v1/flights",
|
|
36
|
+
data={"origin": "agent"},
|
|
37
|
+
files={"file": (filename, source, "application/octet-stream")},
|
|
38
|
+
)
|
|
39
|
+
except httpx.RequestError as exc:
|
|
40
|
+
raise BackendUnavailable("Could not reach OpenDrone API") from exc
|
|
41
|
+
return self._read_response(response)
|
|
42
|
+
|
|
43
|
+
def get_flight(self, flight_id: str) -> dict[str, Any]:
|
|
44
|
+
try:
|
|
45
|
+
response = self._client.get(f"/api/v1/flights/{flight_id}")
|
|
46
|
+
except httpx.RequestError as exc:
|
|
47
|
+
raise BackendUnavailable("Could not reach OpenDrone API") from exc
|
|
48
|
+
return self._read_response(response)
|
|
49
|
+
|
|
50
|
+
@staticmethod
|
|
51
|
+
def _read_response(response: httpx.Response) -> dict[str, Any]:
|
|
52
|
+
if response.status_code >= 500 or response.status_code in {408, 429}:
|
|
53
|
+
raise BackendUnavailable(f"OpenDrone API returned HTTP {response.status_code}")
|
|
54
|
+
try:
|
|
55
|
+
body = response.json()
|
|
56
|
+
except ValueError as exc:
|
|
57
|
+
if response.is_error:
|
|
58
|
+
message = f"OpenDrone API returned HTTP {response.status_code}"
|
|
59
|
+
raise BackendRejected(message) from exc
|
|
60
|
+
raise BackendUnavailable("OpenDrone API returned an invalid response") from exc
|
|
61
|
+
if response.is_error:
|
|
62
|
+
detail = body.get("detail") if isinstance(body, dict) else None
|
|
63
|
+
message = detail.get("message") if isinstance(detail, dict) else detail
|
|
64
|
+
safe_message = message or f"OpenDrone API returned HTTP {response.status_code}"
|
|
65
|
+
raise BackendRejected(str(safe_message))
|
|
66
|
+
if not isinstance(body, dict):
|
|
67
|
+
raise BackendUnavailable("OpenDrone API returned an invalid response")
|
|
68
|
+
return body
|
|
69
|
+
|
|
70
|
+
def close(self) -> None:
|
|
71
|
+
self._client.close()
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""Command-line entry point for the standalone agent."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import logging
|
|
5
|
+
import os
|
|
6
|
+
import signal
|
|
7
|
+
import sys
|
|
8
|
+
from collections.abc import Mapping, Sequence
|
|
9
|
+
from threading import Event
|
|
10
|
+
|
|
11
|
+
from opendrone_bin_sync_agent.agent import SyncAgent
|
|
12
|
+
from opendrone_bin_sync_agent.config import AgentConfig
|
|
13
|
+
|
|
14
|
+
logger = logging.getLogger("opendrone_bin_sync_agent")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def parse_options(
|
|
18
|
+
argv: Sequence[str] | None = None,
|
|
19
|
+
*,
|
|
20
|
+
environ: Mapping[str, str] | None = None,
|
|
21
|
+
) -> tuple[AgentConfig, bool]:
|
|
22
|
+
parser = argparse.ArgumentParser(
|
|
23
|
+
prog="opendrone-bin-sync-agent",
|
|
24
|
+
description="Watch a folder and synchronize stable ArduPilot .BIN logs to OpenDrone.",
|
|
25
|
+
)
|
|
26
|
+
parser.add_argument("--watch-dir", help="Folder containing completed .BIN logs")
|
|
27
|
+
parser.add_argument("--api-url", help="OpenDrone backend base URL")
|
|
28
|
+
parser.add_argument("--state-db", help="Path to the agent's local SQLite database")
|
|
29
|
+
parser.add_argument("--stability-seconds", type=float)
|
|
30
|
+
parser.add_argument("--scan-seconds", type=float)
|
|
31
|
+
parser.add_argument(
|
|
32
|
+
"--once",
|
|
33
|
+
action="store_true",
|
|
34
|
+
help="Scan once and exit (a first observation still needs a later scan to become stable)",
|
|
35
|
+
)
|
|
36
|
+
args = parser.parse_args(argv)
|
|
37
|
+
|
|
38
|
+
values = dict(os.environ if environ is None else environ)
|
|
39
|
+
option_to_env = {
|
|
40
|
+
"watch_dir": "OPENDRONE_SYNC_WATCH_DIR",
|
|
41
|
+
"api_url": "OPENDRONE_API_URL",
|
|
42
|
+
"state_db": "OPENDRONE_SYNC_DB_PATH",
|
|
43
|
+
"stability_seconds": "OPENDRONE_SYNC_STABILITY_SECONDS",
|
|
44
|
+
"scan_seconds": "OPENDRONE_SYNC_SCAN_SECONDS",
|
|
45
|
+
}
|
|
46
|
+
for option_name, env_name in option_to_env.items():
|
|
47
|
+
value = getattr(args, option_name)
|
|
48
|
+
if value is not None:
|
|
49
|
+
values[env_name] = str(value)
|
|
50
|
+
return AgentConfig.from_environment(values), args.once
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
54
|
+
try:
|
|
55
|
+
config, single_scan = parse_options(argv)
|
|
56
|
+
except ValueError as exc:
|
|
57
|
+
print(f"Configuration error: {exc}", file=sys.stderr)
|
|
58
|
+
return 2
|
|
59
|
+
|
|
60
|
+
agent = SyncAgent(config)
|
|
61
|
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
|
62
|
+
stop_requested = Event()
|
|
63
|
+
previous_handlers = {}
|
|
64
|
+
|
|
65
|
+
def request_stop(_signum, _frame):
|
|
66
|
+
stop_requested.set()
|
|
67
|
+
|
|
68
|
+
try:
|
|
69
|
+
logger.info(
|
|
70
|
+
"Listener activo: observando %s y enviando a %s",
|
|
71
|
+
config.watch_dir,
|
|
72
|
+
config.api_url,
|
|
73
|
+
)
|
|
74
|
+
for signum in (signal.SIGINT, signal.SIGTERM):
|
|
75
|
+
previous_handlers[signum] = signal.signal(signum, request_stop)
|
|
76
|
+
while not stop_requested.is_set():
|
|
77
|
+
logger.info("Escaneando archivos .BIN en %s", config.watch_dir)
|
|
78
|
+
agent.scan_once()
|
|
79
|
+
if single_scan:
|
|
80
|
+
break
|
|
81
|
+
stop_requested.wait(config.scan_seconds)
|
|
82
|
+
finally:
|
|
83
|
+
for signum, previous_handler in previous_handlers.items():
|
|
84
|
+
signal.signal(signum, previous_handler)
|
|
85
|
+
agent.close()
|
|
86
|
+
return 0
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
if __name__ == "__main__":
|
|
90
|
+
raise SystemExit(main())
|