Repository navigation
Expand file tree
/
Copy pathwatch_and_copy.py
More file actions
executable file
·261 lines (210 loc) · 7.76 KB
/
Copy pathwatch_and_copy.py
File metadata and controls
executable file
·261 lines (210 loc) · 7.76 KB
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
#!/usr/bin/env python3
"""
Surveille un répertoire source (récursivement) et copie tout nouveau fichier
créé dans un répertoire destination (à plat, sans préserver la structure).
Les répertoires source/destination peuvent être fournis en ligne de commande,
sinon ils sont lus dans config.json (à côté de ce script).
Des motifs de fichiers optionnels (ex. "*.pdf") permettent de ne copier que les
fichiers dont le nom correspond (insensible à la casse). Sans motif, tous les
fichiers sont copiés.
Usage:
python watch_and_copy.py run [<source_dir> <dest_dir> [<motif>...]] # foreground
python watch_and_copy.py start [<source_dir> <dest_dir> [<motif>...]] # daemon
python watch_and_copy.py stop
python watch_and_copy.py status
python watch_and_copy.py restart [<source_dir> <dest_dir> [<motif>...]] # daemon
"""
import os
import sys
import json
import shutil
import signal
import fnmatch
import logging
from pathlib import Path
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
PID_FILE = Path("/tmp/watch_and_copy.pid")
LOG_FILE = Path("/tmp/watch_and_copy.log")
CONFIG_FILE = Path("/etc/watch_and_copy/config.json")
def load_config() -> dict:
if not CONFIG_FILE.exists():
return {}
with open(CONFIG_FILE, "r", encoding="utf-8") as f:
return json.load(f)
def setup_logging(foreground: bool = False):
logging.basicConfig(
filename=None if foreground else LOG_FILE,
level=logging.INFO,
format="%(asctime)s %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
def parse_patterns(raw) -> list[str]:
"""Accepte une chaîne ("*.pdf" ou "*.pdf,*.docx") ou une liste de motifs."""
if not raw:
return []
if isinstance(raw, str):
raw = raw.split(",")
return [p.strip() for p in raw if p and p.strip()]
class CopyOnCreate(FileSystemEventHandler):
def __init__(self, dest: Path, patterns: list[str] | None = None):
self.dest = dest
self.patterns = [p.lower() for p in (patterns or [])]
def matches(self, name: str) -> bool:
if not self.patterns:
return True
name = name.lower()
return any(fnmatch.fnmatchcase(name, p) for p in self.patterns)
def on_created(self, event):
if event.is_directory:
return
src = Path(event.src_path if isinstance(event.src_path, str) else event.src_path.decode())
if not self.matches(src.name):
return
dst = self.dest / src.name
if dst.exists():
logging.info(f"Ignoré {src} : {dst} existe déjà")
return
shutil.copy2(src, dst)
logging.info(f"Copié {src} → {dst}")
def daemonize():
# Double fork pour détacher du terminal
if os.fork() > 0:
sys.exit(0)
os.setsid()
if os.fork() > 0:
sys.exit(0)
# Redirige stdin/stdout/stderr vers /dev/null
devnull = os.open(os.devnull, os.O_RDWR)
for fd in (0, 1, 2):
os.dup2(devnull, fd)
os.close(devnull)
PID_FILE.write_text(str(os.getpid()))
def get_pid() -> int | None:
if PID_FILE.exists():
try:
return int(PID_FILE.read_text().strip())
except ValueError:
return None
return None
def do_run(source: Path, dest: Path, patterns: list[str]):
"""Lance la surveillance en foreground (Ctrl+C pour arrêter)."""
if not source.is_dir():
print(f"Erreur : répertoire source introuvable : {source}")
sys.exit(1)
dest.mkdir(parents=True, exist_ok=True)
setup_logging(foreground=True)
logging.info(f"Surveillance de : {source}")
logging.info(f"Destination : {dest}")
logging.info(f"Filtre : {', '.join(patterns) or 'tous les fichiers'}")
logging.info("Ctrl+C pour arrêter.")
observer = Observer()
observer.schedule(CopyOnCreate(dest, patterns), str(source), recursive=True)
observer.start()
try:
observer.join()
except KeyboardInterrupt:
observer.stop()
observer.join()
logging.info("Arrêté.")
def do_start(source: Path, dest: Path, patterns: list[str]):
if get_pid() is not None:
print("Le daemon tourne déjà. Utilisez 'restart' pour le relancer.")
sys.exit(1)
if not source.is_dir():
print(f"Erreur : répertoire source introuvable : {source}")
sys.exit(1)
dest.mkdir(parents=True, exist_ok=True)
print(f"Démarrage du daemon…")
print(f" Source : {source}")
print(f" Destination : {dest}")
print(f" Filtre : {', '.join(patterns) or 'tous les fichiers'}")
print(f" Logs : {LOG_FILE}")
print(f" PID : {PID_FILE}")
daemonize()
setup_logging()
logging.info(f"Daemon démarré (PID {os.getpid()})")
logging.info(f"Surveillance de : {source}")
logging.info(f"Destination : {dest}")
logging.info(f"Filtre : {', '.join(patterns) or 'tous les fichiers'}")
observer = Observer()
observer.schedule(CopyOnCreate(dest, patterns), str(source), recursive=True)
observer.start()
def on_signal(signum, frame):
observer.stop()
signal.signal(signal.SIGTERM, on_signal)
signal.signal(signal.SIGINT, on_signal)
observer.join()
PID_FILE.unlink(missing_ok=True)
logging.info("Daemon arrêté.")
def do_stop():
pid = get_pid()
if pid is None:
print("Le daemon n'est pas en cours d'exécution.")
sys.exit(1)
try:
os.kill(pid, signal.SIGTERM)
PID_FILE.unlink(missing_ok=True)
print(f"Daemon arrêté (PID {pid}).")
except ProcessLookupError:
print(f"Processus {pid} introuvable — nettoyage du fichier PID.")
PID_FILE.unlink(missing_ok=True)
def do_status():
pid = get_pid()
if pid is None:
print("Daemon : arrêté")
return
try:
os.kill(pid, 0)
print(f"Daemon : en cours d'exécution (PID {pid})")
print(f"Logs : {LOG_FILE}")
except ProcessLookupError:
print(f"Daemon : arrêté (fichier PID périmé)")
PID_FILE.unlink(missing_ok=True)
USAGE = (
f"Usage: {sys.argv[0]} run [<source> <dest> [<motif>...]] # foreground\n"
f" {sys.argv[0]} start [<source> <dest> [<motif>...]] # daemon\n"
f" {sys.argv[0]} stop\n"
f" {sys.argv[0]} status\n"
f" {sys.argv[0]} restart [<source> <dest> [<motif>...]] # daemon\n"
f"\n"
f"<motif> : filtre sur le nom de fichier, ex. '*.pdf' (à mettre entre guillemets).\n"
f"Si <source>/<dest> sont omis, ils sont lus dans {CONFIG_FILE}\n"
f"(clés source_dir, dest_dir et patterns optionnel)."
)
def main():
if len(sys.argv) < 2:
print(USAGE)
sys.exit(1)
cmd = sys.argv[1]
if cmd == "stop":
do_stop()
elif cmd == "status":
do_status()
elif cmd in ("run", "start", "restart"):
if len(sys.argv) >= 4:
source_raw, dest_raw = sys.argv[2], sys.argv[3]
patterns = parse_patterns(sys.argv[4:])
elif len(sys.argv) == 2:
config = load_config()
source_raw, dest_raw = config.get("source_dir"), config.get("dest_dir")
patterns = parse_patterns(config.get("patterns"))
if not source_raw or not dest_raw:
print(f"Erreur : source_dir/dest_dir manquants dans {CONFIG_FILE}")
sys.exit(1)
else:
print(USAGE)
sys.exit(1)
source = Path(source_raw).resolve()
dest = Path(dest_raw).resolve()
if cmd == "run":
do_run(source, dest, patterns)
else:
if cmd == "restart":
do_stop()
do_start(source, dest, patterns)
else:
print(USAGE)
sys.exit(1)
if __name__ == "__main__":
main()