bambu_ftp.py 121 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676
  1. import asyncio
  2. import ftplib # nosec B402
  3. import logging
  4. import os
  5. import shutil
  6. import socket
  7. import ssl
  8. import threading
  9. import time
  10. import weakref
  11. from collections.abc import AsyncIterator, Awaitable, Callable
  12. from concurrent.futures import ThreadPoolExecutor
  13. from contextlib import asynccontextmanager
  14. from dataclasses import dataclass
  15. from datetime import datetime, timedelta, timezone
  16. from enum import Enum
  17. from ftplib import FTP, FTP_TLS # nosec B402
  18. from io import BytesIO
  19. from pathlib import Path
  20. from typing import TypeVar
  21. logger = logging.getLogger(__name__)
  22. T = TypeVar("T")
  23. # Every FTP call below is blocking ftplib work handed to a thread. They used to
  24. # run on asyncio's *default* executor, which is sized min(32, cpu_count + 4) —
  25. # six threads on a 2-core NAS — and is shared with every other ``to_thread`` /
  26. # ``run_in_executor`` caller in the app. That was survivable only because the
  27. # scheduler uploaded to exactly one printer at a time. Dispatching to several
  28. # printers at once (#2555) would park one thread per in-flight upload for
  29. # minutes at a stretch (a 41 MB 3MF at the ~150 KB/s a Bambu printer sustains
  30. # takes ~4 min), starving the default pool and stalling unrelated work.
  31. #
  32. # A dedicated pool keeps that blast radius inside the FTP layer: the scheduler's
  33. # own concurrency cap is what limits parallel uploads, and it can never exhaust
  34. # the executor everything else depends on. Threads are created lazily, so an
  35. # idle pool costs nothing.
  36. #
  37. # Sized well above `queue_max_concurrent_uploads` (max 16), because uploads are
  38. # not the only traffic here: SD browsing, timelapse/recording listing, cover
  39. # downloads, deletes and storage checks all run through this pool too, and on a
  40. # farm they fan out across every printer at once. The pool's work queue is
  41. # unbounded, so exceeding it does not fail — it queues. But `asyncio.wait_for`
  42. # starts its clock at submission, not at thread start, so a task that sits in the
  43. # queue can burn its whole timeout without ever running, and `list_files_async`
  44. # reports a timeout as an empty listing — a silent "this printer has no files".
  45. # Keep the headroom.
  46. _FTP_MAX_WORKERS = 48
  47. _ftp_executor = ThreadPoolExecutor(max_workers=_FTP_MAX_WORKERS, thread_name_prefix="bambu-ftp")
  48. # Overall upload deadline (#2529). A flat wall-clock cap punishes big files on
  49. # slow links rather than catching broken ones: a 96 MB 3MF at the ~75 KB/s an A1
  50. # sustains over WiFi legitimately needs ~20 minutes, and the old flat 600 s
  51. # declared it dead at ~70 MB. The deadline is therefore derived from the file
  52. # size against a deliberately pessimistic floor rate. This is a backstop, not the
  53. # failure detector — a link that has actually died is caught within
  54. # ``socket_timeout`` by the blocking ``sendall``, long before this fires.
  55. _UPLOAD_FLOOR_BYTES_PER_SEC = 25 * 1024
  56. _UPLOAD_MIN_TIMEOUT = 600.0
  57. # The same idea for the other direction (#2957). ``ftp_timeout`` is handed to
  58. # every download as BOTH the socket inactivity timeout and the whole-transfer
  59. # deadline, so its 30 s default is a cap on how big a file the printer is
  60. # allowed to serve. A reporter measured the same 5.4 MB 3MF at 45 s off a worn
  61. # P1S SD card and 25 s off a new one, and a 15.15 MB 3MF at 105 s; a 7.8 MB
  62. # archive in his older logs survived only because it finished inside the retry
  63. # grace. None of those transfers were unhealthy -- they were slow, which is what
  64. # the inactivity timeout is for and what a total deadline cannot tell apart.
  65. #
  66. # So the total deadline follows the file instead, at the same pessimistic floor
  67. # rate the upload path uses. The extension is granted only once the printer has
  68. # answered SIZE, which it can only do from a running worker: the queue wait that
  69. # #2572's cap exists to bound is not lengthened by any of this.
  70. _DOWNLOAD_FLOOR_BYTES_PER_SEC = 25 * 1024
  71. # ...but not without a ceiling. Print start no longer holds a pooled DB
  72. # connection while it downloads (it commits first, #2572); what it holds is the
  73. # archive itself, which only exists once this download ends, and the printer's
  74. # one FTPS slot, at the moment the printer serves files slowest -- an A1 in its
  75. # start-up routine managed ~87 KB/s (#3308). 300 s is ~7.5 MB at the floor rate
  76. # and covers a 15.15 MB / 105 s measurement three times over, because the floor
  77. # is pessimistic by design and a real link is not that slow. A file too big for
  78. # it gets a fallback archive at once and the archive recovery retry.
  79. _DOWNLOAD_MAX_TIMEOUT = 300.0
  80. # The archive recovery retry runs after print start, with the archive already
  81. # on the page, so a large 3MF may take longer there: ~22 MB at the floor rate,
  82. # ~78 MB at the A1's measured start-up rate.
  83. RECOVERY_DOWNLOAD_MAX_TIMEOUT = 900.0
  84. def _download_extension(size: int | None, base_timeout: float, ceiling: float = _DOWNLOAD_MAX_TIMEOUT) -> float:
  85. """Extra seconds to allow a download the printer says is this big.
  86. Zero when the size is unknown -- no SIZE reply means no transfer got under
  87. way, so the base deadline stands and a printer that is not answering still
  88. fails on schedule. Zero, too, once the base deadline is already the more
  89. generous of the two: this only ever lengthens a deadline.
  90. ``ceiling`` caps the whole deadline. It defaults to the 300 s print start
  91. can afford while it holds a database session; a caller that holds none and
  92. has its own budget (the printer file browser) passes that instead.
  93. """
  94. if not size or size <= 0:
  95. return 0.0
  96. return max(0.0, min(size / _DOWNLOAD_FLOOR_BYTES_PER_SEC, ceiling) - base_timeout)
  97. # How long a download will wait for another one on the same printer to finish
  98. # before going ahead alongside it (#2957). A P1S at print start is already
  99. # serving the print off the same SD card and talking MQTT to the slicer, and a
  100. # reporter watched Bambu Studio itself lose its connection while Bambuddy pulled
  101. # a 12 MB 3MF -- with a second Bambuddy transfer for the same file running at
  102. # the same time. 30 s covers the transfer sizes that actually overlap at print
  103. # start -- the reporter's 5.4 MB 3MF took 25 s off a healthy SD card -- and the
  104. # wait is deliberately no longer, because the gate is contention relief and not
  105. # a correctness control. Whoever cannot have it goes anyway, exactly as every
  106. # download did before this existed: a print must never lose its 3MF to queueing,
  107. # and the caller's own deadline stays untouched either way.
  108. _DOWNLOAD_GATE_WAIT_SECONDS = 30.0
  109. # How long to wait for a cancelled path-walk worker to unwind before releasing
  110. # the printer to the next download. It checks the flag once per 8 KiB chunk, so
  111. # this is one chunk on a link slow enough to have blown the deadline.
  112. _DOWNLOAD_UNWIND_SECONDS = 30.0
  113. def _discard_worker_outcome(worker: asyncio.Future) -> None:
  114. """Read a shielded worker's result so asyncio does not complain about it.
  115. ``asyncio.wait_for`` cancels the shield, not the executor thread behind it,
  116. so the worker future outlives the call and nobody is left to look at what it
  117. raised. An unretrieved exception surfaces later as a loop-level
  118. ``Future exception was never retrieved`` ERROR with a traceback, logged
  119. after the caller has already reported the real failure -- the same class of
  120. noise as #2968, and measurably reproducible with a transport error that
  121. lands just after the cap. The value is genuinely unwanted here; only the
  122. fact that something read it matters.
  123. """
  124. def _read(fut: asyncio.Future) -> None:
  125. if fut.cancelled():
  126. return
  127. exc = fut.exception()
  128. if exc is not None:
  129. logger.debug("FTP path-walk worker failed after its caller gave up: %s", exc)
  130. if worker.done():
  131. _read(worker)
  132. else:
  133. worker.add_done_callback(_read)
  134. # One heavy download at a time per printer. Keyed per event loop for the same
  135. # reason ``_upload_locks`` is: an asyncio.Lock binds to the loop that first
  136. # awaits it, and the test suite runs each case on a fresh loop.
  137. _download_locks: weakref.WeakKeyDictionary[asyncio.AbstractEventLoop, dict[str, asyncio.Lock]] = (
  138. weakref.WeakKeyDictionary()
  139. )
  140. def _download_lock(loop: asyncio.AbstractEventLoop, ip_address: str) -> asyncio.Lock:
  141. per_loop = _download_locks.setdefault(loop, {})
  142. lock = per_loop.get(ip_address)
  143. if lock is None:
  144. lock = asyncio.Lock()
  145. per_loop[ip_address] = lock
  146. return lock
  147. @asynccontextmanager
  148. async def _serialized_download(ip_address: str, what: str, *, enabled: bool = True) -> AsyncIterator[bool]:
  149. """Hold this printer's download gate for the block, or go without it.
  150. Yields whether the gate was actually held, which is what the tests assert on
  151. -- from the outside a serialized download and a concurrent one differ only
  152. in timing. The wait is its own budget rather than a slice of the caller's
  153. transfer deadline: a print-start download that queued behind a thumbnail
  154. would otherwise fail on a timer and leave the print with no archive, which
  155. is a worse outcome than the contention this is here to relieve.
  156. ``enabled=False`` skips the gate entirely, for the callers that documented
  157. themselves as lock-free before this existed -- see ``serialize`` on
  158. :func:`download_file_async`.
  159. """
  160. if not enabled:
  161. yield False
  162. return
  163. loop = asyncio.get_event_loop()
  164. lock = _download_lock(loop, ip_address)
  165. started = loop.time()
  166. held = False
  167. try:
  168. await asyncio.wait_for(lock.acquire(), timeout=_DOWNLOAD_GATE_WAIT_SECONDS)
  169. held = True
  170. waited = loop.time() - started
  171. if waited > 1.0:
  172. logger.info("Waited %.1fs for printer %s to finish its other download before %s", waited, ip_address, what)
  173. except TimeoutError:
  174. logger.warning(
  175. "Printer %s is still busy with another download after %ss — starting %s alongside it",
  176. ip_address,
  177. _DOWNLOAD_GATE_WAIT_SECONDS,
  178. what,
  179. )
  180. try:
  181. yield held
  182. finally:
  183. if held:
  184. lock.release()
  185. # How long to give the worker thread to notice the cancel flag, unwind, and
  186. # delete its partial file. It checks the flag once per CHUNK_SIZE, so on a link
  187. # slow enough to have hit the deadline this is one chunk plus the delete.
  188. _UPLOAD_CANCEL_GRACE = 60.0
  189. class UploadCancelled(Exception):
  190. """Raised inside the upload worker to abort an in-flight transfer.
  191. ``upload_file`` treats any exception from its progress callback as "stop
  192. now": it breaks out of the send loop, deletes the partial file from the
  193. printer, and re-raises. That is the only way to stop a transfer — an
  194. executor thread cannot be cancelled from the event loop, so a bare
  195. ``asyncio.wait_for`` leaves it streaming (see ``upload_file_async``).
  196. """
  197. class DownloadCancelled(Exception):
  198. """Raised in an FTP callback to stop a disk-backed download cooperatively."""
  199. class DownloadLimitExceeded(Exception):
  200. """Raised before an FTP callback writes beyond its caller-supplied limit."""
  201. class DownloadInsufficientSpace(Exception):
  202. """Raised before an FTP callback consumes the application's disk reserve."""
  203. class DownloadDeadlineExceeded(Exception):
  204. """A transfer overran the deadline derived from the size the printer reported.
  205. Never retried, for the reason ``UploadCancelled`` is not (#2529): the
  206. deadline was already stretched to fit the file at a floor rate no working
  207. link falls below, so another attempt would spend another full deadline
  208. reaching the same conclusion -- and ``on_print_start`` spends it holding a
  209. pooled database connection. Raised instead of returning False so
  210. ``with_ftp_retry`` can tell this apart from an ordinary failed attempt
  211. (#2957); callers that do not retry see it through their existing handlers,
  212. which is why the archive flow advances to its next candidate path.
  213. """
  214. def _parse_list_mtime(month: str, day: str, time_or_year: str, *, now_utc: datetime | None = None) -> datetime | None:
  215. """The time of an FTP LIST entry, naive, in the printer's own basis.
  216. "Nov 30 10:15" carries no year: it is the year the entry is not in the
  217. future in. Printers report UTC (tested X1C/H2D firmware; see
  218. printer_media.match_ipcam_chunks), so "now" is UTC, not the host's local
  219. clock -- on a host behind UTC an evening entry read as a future one and
  220. went a year back (DB-C8). A day of slack keeps firmware that reports its
  221. local time, up to 14 h ahead, in this year too. "Nov 30 2024" has a year
  222. and no time. None when the entry cannot be read; mtime is best-effort.
  223. """
  224. now_utc = now_utc or datetime.now(timezone.utc).replace(tzinfo=None)
  225. try:
  226. if ":" in time_or_year:
  227. mtime = datetime.strptime(f"{month} {day} {now_utc.year} {time_or_year}", "%b %d %Y %H:%M")
  228. if mtime > now_utc + timedelta(days=1):
  229. mtime = mtime.replace(year=now_utc.year - 1)
  230. return mtime
  231. return datetime.strptime(f"{month} {day} {time_or_year}", "%b %d %Y")
  232. except ValueError:
  233. return None
  234. @dataclass(frozen=True)
  235. class FileListResult:
  236. """A directory listing that distinguishes empty from unreachable."""
  237. files: list[dict]
  238. available: bool
  239. # The printer did not answer within the wait: slow, not necessarily gone
  240. # (a large /ipcam on a slow card), so not reported as unavailable (TO-C13).
  241. timed_out: bool = False
  242. # The printer answered that the directory does not exist (550). Still not
  243. # ``available``, but an answer about the card, not a failure to reach it.
  244. missing: bool = False
  245. # Listings still running, by printer and folder: a refresh joins the one in
  246. # progress instead of starting another thread, which ftplib cannot cancel and
  247. # which would otherwise pile up in the shared FTP pool (TO-C13).
  248. _inflight_listings: dict[tuple[str, str, str], tuple[asyncio.Future, threading.Event]] = {}
  249. class DeleteResult(Enum):
  250. """Outcome of an FTP delete attempt.
  251. Distinguishes "file isn't on the printer" (550, recovery impossible by
  252. retrying) from "delete failed for some other reason" (network, auth,
  253. transient FTP error — worth retrying). The post-print SD-card cleanup in
  254. main.py used to flatten both into ``False`` and log a "may linger" WARNING
  255. on every successful print where the printer self-cleaned its SD card
  256. before our cleanup ran (#1721 reporter's A1).
  257. """
  258. DELETED = "deleted"
  259. NOT_FOUND = "not_found"
  260. FAILED = "failed"
  261. # How long to stop opening FTPS connections to a printer after its TLS
  262. # handshake failed (#2780).
  263. #
  264. # ``WRONG_VERSION_NUMBER`` on port 990 means the printer answered with
  265. # something that is not a TLS record at all, so no path, retry or SSL option
  266. # gets further. Two support bundles show that state lasting for days: one X2D
  267. # served clean FTPS for five days, flipped on 2026-07-19, and then failed every
  268. # single handshake for the next eight (zero successes, 3511 failures).
  269. #
  270. # What it is NOT is a wedged file service, which is what this comment used to
  271. # claim. #2780's reporter power-cycled both affected printers and the state
  272. # survived it, and ``openssl s_client`` against the same port completes a clean
  273. # handshake and returns a valid certificate while Bambuddy is failing. The
  274. # leading theory is now a connection-count refusal — vsFTPd answers one in
  275. # cleartext, which is exactly this error to an implicit-TLS client, and answers
  276. # the global limit by accepting and never speaking, which is the handshake
  277. # timeout we also see. Unproven: confirming it needs a capture taken while a
  278. # printer is in the failing state.
  279. #
  280. # Without a gate every candidate path re-runs the same doomed handshake: the
  281. # 3MF lookup alone walks 6 filename variants x 5 directories x 4 retries, and
  282. # the cover and timelapse scans run their own sweeps on top. That is where
  283. # those thousands of failures come from — one wedged printer, hammered.
  284. #
  285. # Five minutes is short enough that a power-cycled printer is picked up on the
  286. # next print (and any successful connect clears the gate immediately), long
  287. # enough that a wedged one is contacted twice an hour instead of hundreds of
  288. # times a minute.
  289. _HANDSHAKE_COOLOFF_SECONDS = 300.0
  290. # How long to wait for a printer to say something in cleartext on the TLS port.
  291. # The failing case answers immediately -- the banner is the first thing a
  292. # vsFTPd refusal sends -- so this only ever elapses in full when the service has
  293. # gone back to speaking TLS and is waiting for a ClientHello that will not come.
  294. _CLEARTEXT_PROBE_TIMEOUT = 2.0
  295. def _read_cleartext_reply(ip_address: str, port: int) -> str | None:
  296. """Read what a printer answers the TLS port with, when it is not TLS.
  297. ``WRONG_VERSION_NUMBER`` means the peer's first bytes were not a TLS
  298. record -- measured, not inferred: a cleartext ``421`` banner reproduces
  299. that exact error and message, while a genuine version mismatch produces
  300. ``TLSV1_ALERT_PROTOCOL_VERSION`` instead (#2780).
  301. What it does not say is *which* cleartext message, and that is the part
  302. that would identify the fault. OpenSSL has already consumed those bytes by
  303. the time the error surfaces, so this opens one plain connection and reads
  304. them directly. Answering it from the reporter's own printers beats waiting
  305. on a packet capture from the one farm that can take one.
  306. Returns the reply, or None when the printer said nothing readable -- which
  307. is itself informative: a healthy implicit-FTPS service sends nothing until
  308. it has a ClientHello, so silence means the fault had already passed.
  309. """
  310. sock = None
  311. # One budget for connect *and* read. Given a timeout each, a printer that
  312. # is slow to accept would then get the full read window on top of it, and
  313. # the wait this adds to a failed connect would be double what it says.
  314. deadline = time.monotonic() + _CLEARTEXT_PROBE_TIMEOUT
  315. try:
  316. sock = socket.create_connection((ip_address, port), _CLEARTEXT_PROBE_TIMEOUT)
  317. sock.settimeout(max(0.05, deadline - time.monotonic()))
  318. # One read. A refusal is a single short line; anything longer is not
  319. # the thing being looked for, and this must not become a transfer.
  320. raw = sock.recv(256)
  321. except OSError as e:
  322. # Refused or reset is a different fact from "answered in cleartext",
  323. # and worth having in the log rather than flattened into silence.
  324. logger.debug("Cleartext probe of %s:%s could not connect: %s", ip_address, port, e)
  325. return None
  326. finally:
  327. if sock is not None:
  328. try:
  329. sock.close()
  330. except OSError:
  331. pass
  332. if not raw:
  333. return None
  334. # latin-1 cannot fail, and an FTP reply line is ASCII in practice. Control
  335. # characters are stripped so a stray byte cannot mangle the log line.
  336. text = raw.decode("latin-1").strip()
  337. return "".join(c for c in text if c.isprintable()) or None
  338. def _ftp_reply_code(error: BaseException) -> str | None:
  339. """The three-digit reply code an ftplib error carries, if it carries one.
  340. ``ftplib`` puts the server's whole reply line in the exception message, so
  341. the code is the first token: "553 Could not create file." Anything that is
  342. not three digits (an ``OSError``, a library-side message) has no code, and
  343. saying so beats inventing one.
  344. """
  345. head = str(error)[:3]
  346. return head if head.isdigit() else None
  347. class FtpFailureKind(Enum):
  348. """Why an FTP operation failed, at the granularity the client can tell.
  349. ``connect`` and ``upload_file`` already separate every one of these -- each
  350. has its own log line, and 553 even gets a spelled-out list of storage
  351. causes -- and then both returned a bare ``False``. So the dispatch that
  352. reports the failure to the operator had nothing to go on, and used one
  353. string for all of them: "check if SD card is inserted and properly
  354. formatted". #2899's reporter acted on that after a TLS handshake failure
  355. and restarted the printer, which could not have helped: the handshake never
  356. got near the printer's filesystem.
  357. """
  358. COOLOFF = "cooloff" # skipped without contacting the printer (#2780)
  359. HANDSHAKE = "handshake" # port 990 answered with something that is not TLS
  360. AUTH = "auth" # permanent refusal, typically a rejected access code
  361. TIMEOUT = "timeout"
  362. STORAGE = "storage" # 553/552 -- the case the SD-card advice was written for
  363. NOT_FOUND = "not_found" # 550
  364. NETWORK = "network" # socket dropped, or an FTP error with no clearer reading
  365. UNKNOWN = "unknown"
  366. @dataclass(frozen=True)
  367. class FtpFailure:
  368. """What went wrong, kept next to the log line that already said it."""
  369. kind: FtpFailureKind
  370. detail: str
  371. code: str | None = None # FTP reply code where the server gave one
  372. @dataclass
  373. class FtpFailureReport:
  374. """A slot the *caller* owns for the reason its upload failed.
  375. Deliberately not a per-IP dict on the client, the way ``_mode_cache`` and
  376. ``_handshake_blocked_until`` are. Those describe a printer, and are
  377. correct to share. This describes one operation, and a background timelapse
  378. fetch running beside a dispatch would overwrite the dispatch's reason with
  379. its own -- reporting the wrong cause with total confidence, which is the
  380. bug being fixed rather than a new way to hit it (#2899).
  381. """
  382. failure: FtpFailure | None = None
  383. class FileNotOnPrinterError(Exception):
  384. """Raised when a remote FTP path returns 550 (file not found).
  385. 550 means the file does not exist at that path — retrying the same path
  386. will never succeed. Callers use this sentinel with with_ftp_retry's
  387. non_retry_exceptions to immediately move on to the next candidate path
  388. instead of burning the full retry budget (up to 11 × 30s per path) on
  389. a lookup that cannot recover.
  390. """
  391. class ImplicitFTP_TLS(FTP_TLS):
  392. """FTP_TLS subclass for implicit FTPS (port 990) with model-specific SSL handling.
  393. X1C/P1S printers (vsFTPd) require SSL with session reuse on the data channel.
  394. A1/A1 Mini printers have issues with SSL on the data channel entirely and
  395. timeout waiting for transfer completion. Set skip_session_reuse=True for A1
  396. printers to skip SSL on the data channel (control channel remains encrypted).
  397. Optionally caps the SSL context's maximum TLS version to v1.2 (P2S firmware
  398. 01.02.00.00 needs this — see :mod:`ftp_profiles` and #1401).
  399. """
  400. def __init__(self, *args, skip_session_reuse: bool = False, cap_tls_v1_2: bool = False, **kwargs):
  401. super().__init__(*args, **kwargs)
  402. self._sock = None
  403. self.skip_session_reuse = skip_session_reuse
  404. self.ssl_context = ssl.create_default_context()
  405. self.ssl_context.check_hostname = False
  406. self.ssl_context.verify_mode = ssl.CERT_NONE
  407. # ``create_default_context()`` does NOT guarantee a protocol floor: it
  408. # leaves ``minimum_version`` at ``MINIMUM_SUPPORTED``, and what that
  409. # resolves to is a property of the OpenSSL build, not of this code.
  410. # Measured on identical OpenSSL 3.5.6: python:3.13-slim-trixie (our
  411. # Docker base) reports TLSv1_2, a bare-metal venv reports
  412. # MINIMUM_SUPPORTED. Docker users have therefore always been floored at
  413. # 1.2 — every Bambu model is reachable under that floor — while
  414. # bare-metal and appliance installs could silently negotiate TLS 1.0.
  415. # State the floor rather than inheriting it.
  416. self.ssl_context.minimum_version = ssl.TLSVersion.TLSv1_2
  417. if cap_tls_v1_2:
  418. # With the floor above this pins the connection to exactly TLS 1.2.
  419. self.ssl_context.maximum_version = ssl.TLSVersion.TLSv1_2
  420. def connect(self, host="", port=990, timeout=-999, source_address=None):
  421. """Connect to host, wrapping socket in TLS immediately (implicit FTPS)."""
  422. if host:
  423. self.host = host
  424. if port > 0:
  425. self.port = port
  426. if timeout != -999:
  427. self.timeout = timeout
  428. if source_address:
  429. self.source_address = source_address
  430. # Create and wrap socket immediately (implicit TLS)
  431. self.sock = socket.create_connection((self.host, self.port), self.timeout, source_address=self.source_address)
  432. self.sock = self.ssl_context.wrap_socket(self.sock, server_hostname=self.host)
  433. self.af = self.sock.family
  434. self.file = self.sock.makefile("r", encoding=self.encoding)
  435. self.welcome = self.getresp()
  436. return self.welcome
  437. def ntransfercmd(self, cmd, rest=None):
  438. """Override to wrap data connection in SSL for X1C/P1S only.
  439. X1C/P1S printers (vsFTPd) require SSL session reuse on the data channel.
  440. A1/A1 Mini printers have issues with SSL on the data channel entirely -
  441. they timeout waiting for the transfer completion response. For A1, we
  442. skip SSL wrapping on the data channel (control channel remains encrypted).
  443. """
  444. conn, size = FTP.ntransfercmd(self, cmd, rest)
  445. if self._prot_p and not self.skip_session_reuse:
  446. # X1C/P1S: Wrap data channel with SSL session reuse (required by vsFTPd)
  447. conn = self.ssl_context.wrap_socket(
  448. conn,
  449. server_hostname=self.host,
  450. session=self.sock.session,
  451. )
  452. # A1/A1 Mini (skip_session_reuse=True): Don't wrap data channel in SSL
  453. # The control channel remains encrypted via implicit FTPS
  454. return conn, size
  455. class BambuFTPClient:
  456. """FTP client for retrieving files from Bambu Lab printers."""
  457. FTP_PORT = 990
  458. # Default timeout in seconds (increased for A1 printers)
  459. DEFAULT_TIMEOUT = 30
  460. # Models that may need SSL mode fallback (try prot_p first, fall back to prot_c)
  461. # These models have varying FTP SSL behavior depending on firmware version
  462. A1_MODELS = ("A1", "A1 Mini")
  463. # Chunk size for manual upload transfer (64KB)
  464. # Smaller chunks provide smoother progress reporting — at typical printer FTP
  465. # speeds (~50-100KB/s) this gives a progress update roughly every second.
  466. CHUNK_SIZE = 64 * 1024
  467. # Cache for working FTP modes per printer IP
  468. # Maps IP -> "prot_p" or "prot_c"
  469. _mode_cache: dict[str, str] = {}
  470. # Printers whose FTPS handshake just failed, mapped to the monotonic time
  471. # their cool-off expires. See ``_HANDSHAKE_COOLOFF_SECONDS``.
  472. _handshake_blocked_until: dict[str, float] = {}
  473. # Which cool-off deadline each printer's "not attempted" warning was last
  474. # logged for, so the warning is said once per cool-off. See ``connect``.
  475. _handshake_skip_logged: dict[str, float] = {}
  476. def __init__(
  477. self,
  478. ip_address: str,
  479. access_code: str,
  480. timeout: float | None = None,
  481. printer_model: str | None = None,
  482. force_prot_c: bool = False,
  483. respect_handshake_cooloff: bool = True,
  484. records_handshake_cooloff: bool = True,
  485. ):
  486. """Set ``respect_handshake_cooloff=False`` for bounded, user-initiated work.
  487. The cool-off exists to stop an unbounded sweep re-running one doomed
  488. handshake a hundred times over (#2780). Dispatching a print is not
  489. that: it is one delete plus at most four upload attempts, with someone
  490. waiting on the result. Sharing the sweep's gate cost those attempts
  491. their whole retry budget, and failed every further job queued for that
  492. printer for the rest of the 300s window (#2898).
  493. Leave it at the default everywhere else. Opting out is only defensible
  494. because the caller's own connection count is bounded and small.
  495. ``records_handshake_cooloff=False`` keeps a failed handshake on this
  496. client from opening the cool-off for everyone: for a side check whose
  497. refusal says nothing about the printer's file service at large.
  498. """
  499. self.ip_address = ip_address
  500. self.access_code = access_code
  501. self.timeout = timeout if timeout is not None else self.DEFAULT_TIMEOUT
  502. self.printer_model = printer_model
  503. self.force_prot_c = force_prot_c
  504. self.respect_handshake_cooloff = respect_handshake_cooloff
  505. self.records_handshake_cooloff = records_handshake_cooloff
  506. # Why the last connect/upload on this client failed, for a caller that
  507. # only gets a bool back (#2899). Per instance, so it describes one
  508. # operation and cannot be overwritten by work against another printer.
  509. self.last_failure: FtpFailure | None = None
  510. self._ftp: ImplicitFTP_TLS | None = None
  511. # When the control socket to the printer was opened, so the close log
  512. # can say how long the session was held (#3009).
  513. self._connected_at: float | None = None
  514. def _get_cached_mode(self) -> str | None:
  515. """Get cached FTP mode for this printer."""
  516. return self._mode_cache.get(self.ip_address)
  517. @classmethod
  518. def cache_mode(cls, ip_address: str, mode: str):
  519. """Cache the working FTP mode for a printer."""
  520. cls._mode_cache[ip_address] = mode
  521. logger.info("FTP mode cached for %s: %s", ip_address, mode)
  522. def _should_use_prot_c(self) -> bool:
  523. """Determine if we should use prot_c (clear) mode."""
  524. # If explicitly forced, use prot_c
  525. if self.force_prot_c:
  526. return True
  527. # Check cache first
  528. cached = self._get_cached_mode()
  529. if cached:
  530. return cached == "prot_c"
  531. # Default: try prot_p first (will fall back if needed)
  532. return False
  533. @classmethod
  534. def handshake_blocked(cls, ip_address: str) -> bool:
  535. """True while *ip_address* is inside its post-handshake-failure cool-off.
  536. Public so a caller sweeping many candidate paths can stop after the
  537. first one rather than walking the rest against a printer that cannot
  538. complete a TLS handshake (#2780).
  539. """
  540. deadline = cls._handshake_blocked_until.get(ip_address)
  541. if deadline is None:
  542. return False
  543. if time.monotonic() >= deadline:
  544. # Drop it on the way past rather than leaving an entry per printer
  545. # this process has ever failed against.
  546. del cls._handshake_blocked_until[ip_address]
  547. cls._handshake_skip_logged.pop(ip_address, None)
  548. return False
  549. return True
  550. def connect(self) -> bool:
  551. """Connect to the printer FTP server (implicit FTPS on port 990).
  552. Returns False without touching the network while the printer is inside
  553. the cool-off a previous TLS handshake failure opened (#2780) -- unless
  554. this client was built with ``respect_handshake_cooloff=False``.
  555. """
  556. self.last_failure = None
  557. if self.respect_handshake_cooloff and self.handshake_blocked(self.ip_address):
  558. # WARNING, not DEBUG. This is the one connect() failure path that
  559. # reported without its cause, so at default log level four
  560. # reason-free "FTP connection failed" lines two seconds apart gave
  561. # no hint that nothing had been sent (#2898). Every caller reaching
  562. # here is already gated by handshake_blocked() at its own sweep
  563. # boundary, so this costs about one line per print, not a flood.
  564. deadline = self._handshake_blocked_until.get(self.ip_address)
  565. remaining = max(0.0, deadline - time.monotonic()) if deadline is not None else 0.0
  566. if deadline is not None and self._handshake_skip_logged.get(self.ip_address) != deadline:
  567. self._handshake_skip_logged[self.ip_address] = deadline
  568. logger.warning(
  569. "FTP connect to %s not attempted: its FTPS handshake failed recently and it is "
  570. "cooling off for another %.0fs. Nothing was sent to the printer.",
  571. self.ip_address,
  572. remaining,
  573. )
  574. else:
  575. # Said once already for this cool-off. Repeating it per candidate
  576. # path is the log flood #2780 set out to stop -- a download-zip
  577. # of 200 files would print the same sentence 200 times.
  578. logger.debug(
  579. "FTP connect to %s skipped: still cooling off for another %.0fs",
  580. self.ip_address,
  581. remaining,
  582. )
  583. self.last_failure = FtpFailure(
  584. FtpFailureKind.COOLOFF,
  585. f"cooling off for another {remaining:.0f}s after a recent FTPS handshake failure",
  586. )
  587. return False
  588. try:
  589. use_prot_c = self._should_use_prot_c()
  590. from backend.app.services.ftp_profiles import get_ftp_profile
  591. profile = get_ftp_profile(self.printer_model)
  592. logger.debug(
  593. f"FTP connecting to {self.ip_address}:{self.FTP_PORT} "
  594. f"(timeout={self.timeout}s, model={self.printer_model}, prot_c={use_prot_c}, "
  595. f"cap_tls_v1_2={profile.cap_tls_v1_2})"
  596. )
  597. self._ftp = ImplicitFTP_TLS(
  598. skip_session_reuse=use_prot_c,
  599. cap_tls_v1_2=profile.cap_tls_v1_2,
  600. )
  601. self._ftp.connect(self.ip_address, self.FTP_PORT, timeout=self.timeout)
  602. # Stamped here rather than after login: the socket exists from this
  603. # point on, and a session that dies during login is exactly the one
  604. # whose lifetime someone reading the log wants accounted for.
  605. self._connected_at = time.monotonic()
  606. logger.debug("FTP connected, logging in as bblp")
  607. self._ftp.login("bblp", self.access_code)
  608. if use_prot_c:
  609. # Use clear (unencrypted) data channel
  610. logger.debug("FTP logged in, setting prot_c (clear) and passive mode")
  611. self._ftp.prot_c()
  612. else:
  613. # Use protected (encrypted) data channel with session reuse
  614. logger.debug("FTP logged in, setting prot_p (protected) and passive mode")
  615. self._ftp.prot_p()
  616. self._ftp.set_pasv(True)
  617. # Log welcome message for debugging
  618. if hasattr(self._ftp, "welcome") and self._ftp.welcome:
  619. logger.debug("FTP server welcome: %s", self._ftp.welcome)
  620. logger.info(
  621. f"FTP connected successfully to {self.ip_address} (model={self.printer_model}, prot_c={use_prot_c})"
  622. )
  623. return True
  624. except ftplib.error_perm as e:
  625. logger.warning("FTP connection permission error to %s: %s", self.ip_address, e)
  626. self.last_failure = FtpFailure(FtpFailureKind.AUTH, str(e), _ftp_reply_code(e))
  627. self._abandon_connection("login rejected")
  628. return False
  629. except TimeoutError as e:
  630. logger.warning("FTP connection timed out to %s: %s", self.ip_address, e)
  631. self.last_failure = FtpFailure(FtpFailureKind.TIMEOUT, str(e))
  632. self._abandon_connection("connect timed out")
  633. return False
  634. except ssl.SSLError as e:
  635. # Not a transient failure and not something another path or another
  636. # retry can route around: the printer's file service answered port
  637. # 990 with something that isn't TLS. Say so once and stop knocking
  638. # for a while (#2780).
  639. #
  640. # Deliberately no advice about what to do. This message used to
  641. # tell the operator to restart the printer; #2780's reporter did
  642. # that twice, to no effect, and a single manual connect to the
  643. # same printer completes a clean handshake. We do not yet know the
  644. # trigger, so stating the observation and stopping there beats
  645. # sending people to do the one thing already known not to work.
  646. logger.warning(
  647. "FTP SSL error connecting to %s: %s — the printer answered port %s with something "
  648. "that is not TLS, so print files, covers and timelapses cannot be fetched from it.%s",
  649. self.ip_address,
  650. e,
  651. self.FTP_PORT,
  652. f" Pausing FTP to this printer for {_HANDSHAKE_COOLOFF_SECONDS:.0f}s."
  653. if self.records_handshake_cooloff
  654. else "",
  655. )
  656. # Close the dead socket before asking this printer for anything
  657. # else. The probe below opens a second connection, and the leading
  658. # theory for this failure is a printer out of connection slots --
  659. # holding a failed handshake open across that is the exact thing
  660. # #2780's cleanup was added to stop. Idempotent, so the call that
  661. # used to sit at the end of this branch simply moved up.
  662. self._abandon_connection("TLS handshake failed")
  663. # Ask the printer what it actually said, once per cool-off window.
  664. # Checked before the deadline below is written, so a live entry here
  665. # means an earlier failure already opened this window and already
  666. # asked -- which keeps a dispatch that ignores the cool-off from
  667. # probing on each of its four attempts.
  668. detail = str(e)
  669. if getattr(e, "reason", None) == "WRONG_VERSION_NUMBER" and not self.handshake_blocked(self.ip_address):
  670. reply = _read_cleartext_reply(self.ip_address, self.FTP_PORT)
  671. if reply:
  672. logger.warning(
  673. "Printer %s answered port %s in cleartext with: %s — that is what the TLS "
  674. "handshake read as a malformed record. Please include this line if you report it.",
  675. self.ip_address,
  676. self.FTP_PORT,
  677. reply,
  678. )
  679. detail = f"{e} (printer answered in cleartext: {reply})"
  680. else:
  681. logger.warning(
  682. "Printer %s sent nothing readable in cleartext on port %s, so its file service "
  683. "was speaking TLS again by the time we asked — the refusal was momentary.",
  684. self.ip_address,
  685. self.FTP_PORT,
  686. )
  687. if self.records_handshake_cooloff:
  688. self._handshake_blocked_until[self.ip_address] = time.monotonic() + _HANDSHAKE_COOLOFF_SECONDS
  689. self.last_failure = FtpFailure(FtpFailureKind.HANDSHAKE, detail)
  690. return False
  691. except (OSError, ftplib.Error) as e:
  692. logger.warning("FTP connection failed to %s: %s (type: %s)", self.ip_address, e, type(e).__name__)
  693. self.last_failure = FtpFailure(FtpFailureKind.NETWORK, str(e), _ftp_reply_code(e))
  694. self._abandon_connection("connect failed")
  695. return False
  696. def _held_for(self) -> str:
  697. """How long the control socket has been open, for the close log.
  698. "unknown" when :meth:`connect` never got as far as opening one -- the
  699. cool-off skip and a DNS/refused failure both land in
  700. :meth:`_abandon_connection` without a socket ever existing.
  701. """
  702. if self._connected_at is None:
  703. return "unknown"
  704. return f"{time.monotonic() - self._connected_at:.1f}s"
  705. def _abandon_connection(self, reason: str = "connection never became usable") -> None:
  706. """Drop a connection that never became usable, closing its socket.
  707. Every failure path in :meth:`connect` used to clear ``self._ftp`` and
  708. nothing else, leaving a connected socket for the garbage collector.
  709. That is survivable once; it is not survivable at this volume. A single
  710. print used to walk ~110 candidate paths, so a printer refusing FTPS
  711. got ~110 sockets opened and abandoned in a couple of minutes, and one
  712. support bundle recorded 1813 of them in a day (#2780). If the refusal
  713. is the printer running out of connection slots -- which fits the
  714. evidence better than a wedged service, since a single manual connect
  715. to the same printer succeeds -- then abandoning sockets is not just
  716. untidy, it is what keeps the printer refusing.
  717. Uses ``close()`` rather than ``quit()``: QUIT is a command, and there
  718. is no working control channel to send it on.
  719. """
  720. ftp = self._ftp
  721. self._ftp = None
  722. held = self._held_for()
  723. self._connected_at = None
  724. if ftp is None:
  725. return
  726. try:
  727. ftp.close()
  728. except (OSError, ftplib.Error, EOFError):
  729. pass # Best-effort; the socket may already be gone
  730. # See the note in ``disconnect``: every session that opens a socket
  731. # says how it closed, so the log carries matched pairs (#3009).
  732. logger.debug(
  733. "FTP session to %s closed without QUIT (%s), held %s",
  734. self.ip_address,
  735. reason,
  736. held,
  737. )
  738. def disconnect(self):
  739. """Disconnect from the FTP server."""
  740. if self._ftp:
  741. held = self._held_for()
  742. try:
  743. self._ftp.quit()
  744. except (OSError, ftplib.Error, EOFError) as e:
  745. # ``quit()`` sends QUIT and only then closes; when the send
  746. # raises, ftplib never reaches its own close and the socket
  747. # stays open. Close it here rather than leaving it to the GC.
  748. self._abandon_connection(f"QUIT failed: {e}")
  749. else:
  750. # One line per session, at DEBUG. Neither this method nor
  751. # ``_abandon_connection`` used to log anything at any level, so
  752. # a session closed cleanly and a socket genuinely left open
  753. # produced identical logs -- nothing. #3009 read that silence
  754. # after a print as proof the connections were never closed, and
  755. # nothing in the log could have shown otherwise. Now every
  756. # connect has a matching close, so the next person can settle it
  757. # from a support bundle instead of by inference.
  758. logger.debug(
  759. "FTP session to %s closed after QUIT, held %s",
  760. self.ip_address,
  761. held,
  762. )
  763. self._ftp = None
  764. self._connected_at = None
  765. def list_files(self, path: str = "/", *, raise_on_error: bool = False) -> list[dict]:
  766. """List files in a directory."""
  767. if not self._ftp:
  768. return []
  769. files = []
  770. try:
  771. self._ftp.cwd(path)
  772. items = []
  773. self._ftp.retrlines("LIST", items.append)
  774. for item in items:
  775. parts = item.split()
  776. if len(parts) >= 9:
  777. name = " ".join(parts[8:])
  778. is_dir = item.startswith("d")
  779. size = int(parts[4]) if not is_dir else 0
  780. # Parse modification time from FTP listing
  781. # Format: "Nov 30 10:15" or "Nov 30 2024"
  782. mtime = _parse_list_mtime(parts[5], parts[6], parts[7])
  783. file_entry = {
  784. "name": name,
  785. "is_directory": is_dir,
  786. "size": size,
  787. "path": f"{path.rstrip('/')}/{name}",
  788. }
  789. if mtime:
  790. file_entry["mtime"] = mtime
  791. files.append(file_entry)
  792. logger.debug("Listed %s files in %s", len(files), path)
  793. except (OSError, ftplib.Error) as e:
  794. logger.info("FTP list_files failed for %s: %s", path, e)
  795. if raise_on_error:
  796. raise
  797. return files
  798. def download_file(
  799. self,
  800. remote_path: str,
  801. expected_size: int | None = None,
  802. cancel_event: threading.Event | None = None,
  803. size_callback: Callable[[int], None] | None = None,
  804. report_missing: bool = False,
  805. ) -> bytes | None:
  806. """Download a file from the printer.
  807. ``expected_size`` is the byte count the directory listing reported for
  808. this file. Pass it whenever a short read must not be mistaken for a
  809. successful download: an FTPS data connection that closes early does
  810. not always raise, so ``retrbinary`` can hand back a partial buffer that
  811. looks like a perfectly good file to everything downstream. That is
  812. tolerable when the printer keeps its copy, and not tolerable when the
  813. caller goes on to delete the source (#2704).
  814. A zero-byte result is always treated as a failure, matching
  815. :meth:`download_to_file` — no caller has a use for an empty file.
  816. ``size_callback`` is handed the size the printer reports (SIZE) before
  817. the transfer starts, for a caller that sets its deadline from it.
  818. ``report_missing`` raises :class:`FileNotOnPrinterError` when RETR is
  819. answered 550, as :meth:`download_to_file` does, instead of returning
  820. None: every other caller reads a failed download as None.
  821. """
  822. if not self._ftp:
  823. return None
  824. if size_callback is not None:
  825. # Only a hint for the deadline: a SIZE refusal (missing command, a
  826. # file still being written) is left to RETR to judge.
  827. try:
  828. server_size = self._ftp.size(remote_path)
  829. except (OSError, ftplib.Error):
  830. server_size = None
  831. if server_size is not None and server_size > 0:
  832. size_callback(server_size)
  833. buffer = BytesIO()
  834. def _write(block: bytes) -> None:
  835. # Checked as data arrives: ``download_file_bytes_async`` sets it at
  836. # its deadline, so the transfer stops instead of running on in its
  837. # worker thread beside whatever the caller does next.
  838. if cancel_event is not None and cancel_event.is_set():
  839. raise DownloadCancelled(remote_path)
  840. buffer.write(block)
  841. try:
  842. self._ftp.retrbinary(f"RETR {remote_path}", _write)
  843. data = buffer.getvalue()
  844. except DownloadCancelled:
  845. raise
  846. except ftplib.error_perm as exc:
  847. if report_missing and str(exc).startswith("550"):
  848. raise FileNotOnPrinterError(f"{remote_path}: {exc}") from exc
  849. return None
  850. except (OSError, ftplib.Error):
  851. return None
  852. if not data:
  853. logger.warning("FTP download returned 0 bytes for %s", remote_path)
  854. return None
  855. if expected_size is not None and len(data) != expected_size:
  856. logger.warning(
  857. "FTP download of %s is short: got %s bytes, listing reported %s — treating as failed",
  858. remote_path,
  859. len(data),
  860. expected_size,
  861. )
  862. return None
  863. return data
  864. def download_to_file(
  865. self,
  866. remote_path: str,
  867. local_path: Path,
  868. *,
  869. expected_size: int | None = None,
  870. max_bytes: int | None = None,
  871. cancel_event: threading.Event | None = None,
  872. min_free_bytes: int | None = None,
  873. size_callback: Callable[[int], None] | None = None,
  874. ) -> bool:
  875. """Download a file with cooperative cancellation and byte bounds.
  876. ``size_callback`` is handed the size the printer reported for this file,
  877. once, before the transfer starts. The async wrappers use it to grow a
  878. whole-transfer deadline that was set before anyone knew how big the file
  879. was (#2957); it must not raise.
  880. """
  881. if not self._ftp:
  882. logger.warning("download_to_file called but FTP not connected")
  883. return False
  884. try:
  885. local_path.parent.mkdir(parents=True, exist_ok=True)
  886. # SIZE is the printer's own current view of the file and is more
  887. # trustworthy than a browser round-tripped listing hint. Some
  888. # firmware does not implement SIZE, so retain expected_size as a
  889. # compatibility fallback when the command is unavailable.
  890. try:
  891. server_size = self._ftp.size(remote_path)
  892. except (OSError, ftplib.Error):
  893. server_size = None
  894. authoritative_size = server_size if server_size is not None and server_size >= 0 else expected_size
  895. if max_bytes is not None and authoritative_size is not None and authoritative_size > max_bytes:
  896. raise DownloadLimitExceeded(remote_path)
  897. if min_free_bytes is not None and authoritative_size is not None:
  898. if shutil.disk_usage(local_path.parent).free < min_free_bytes + authoritative_size:
  899. raise DownloadInsufficientSpace(remote_path)
  900. if size_callback is not None and authoritative_size is not None and authoritative_size > 0:
  901. size_callback(authoritative_size)
  902. with open(local_path, "wb") as f:
  903. written = 0
  904. # retrbinary hands over 8 KiB at a time, so checking the volume
  905. # on every callback is ~30k statvfs calls per 250 MB chunk for a
  906. # reserve measured in hundreds of megabytes. Sampling every few
  907. # MB cannot overshoot it by more than one interval.
  908. free_check_interval = 8 * 1024 * 1024
  909. next_free_check = 0
  910. def _write(chunk: bytes) -> None:
  911. nonlocal written, next_free_check
  912. if cancel_event is not None and cancel_event.is_set():
  913. raise DownloadCancelled(remote_path)
  914. if max_bytes is not None and written + len(chunk) > max_bytes:
  915. raise DownloadLimitExceeded(remote_path)
  916. if min_free_bytes is not None and written >= next_free_check:
  917. next_free_check = written + free_check_interval
  918. if shutil.disk_usage(local_path.parent).free < min_free_bytes + free_check_interval:
  919. raise DownloadInsufficientSpace(remote_path)
  920. f.write(chunk)
  921. written += len(chunk)
  922. self._ftp.retrbinary(f"RETR {remote_path}", _write)
  923. f.flush()
  924. os.fsync(f.fileno())
  925. file_size = local_path.stat().st_size if local_path.exists() else 0
  926. if file_size == 0:
  927. logger.warning("FTP download returned 0 bytes for %s", remote_path)
  928. if local_path.exists():
  929. local_path.unlink()
  930. return False
  931. if authoritative_size is not None and file_size != authoritative_size:
  932. logger.warning(
  933. "FTP download of %s is short: got %s bytes, listing reported %s — treating as failed",
  934. remote_path,
  935. file_size,
  936. authoritative_size,
  937. )
  938. local_path.unlink(missing_ok=True)
  939. return False
  940. logger.info("Successfully downloaded %s to %s (%s bytes)", remote_path, local_path, file_size)
  941. return True
  942. except (OSError, ftplib.Error, DownloadCancelled, DownloadLimitExceeded, DownloadInsufficientSpace) as e:
  943. # Clean up partial file if it exists
  944. if local_path.exists():
  945. try:
  946. local_path.unlink()
  947. except OSError:
  948. pass # Best-effort partial file cleanup; not critical if removal fails
  949. # 550 means the file is not at this path. Surface as a sentinel so
  950. # with_ftp_retry can abandon this path immediately and the caller
  951. # can advance to the next candidate instead of retrying 11× at
  952. # 30s intervals (the pattern that cost #972's reporter ~48min).
  953. if isinstance(e, (DownloadCancelled, DownloadLimitExceeded, DownloadInsufficientSpace)):
  954. raise
  955. if isinstance(e, ftplib.error_perm) and str(e).startswith("550"):
  956. logger.info("FTP download failed for %s: %s (not on printer)", remote_path, e)
  957. raise FileNotOnPrinterError(f"{remote_path}: {e}") from e
  958. # Log at INFO level so we can see failures in normal logs
  959. logger.info("FTP download failed for %s: %s", remote_path, e)
  960. return False
  961. def upload_file(
  962. self,
  963. local_path: Path,
  964. remote_path: str,
  965. progress_callback: Callable[[int, int], None] | None = None,
  966. ) -> bool:
  967. """Upload a file to the printer with optional progress callback."""
  968. self.last_failure = None
  969. if not self._ftp:
  970. logger.warning("upload_file: FTP not connected")
  971. self.last_failure = FtpFailure(FtpFailureKind.UNKNOWN, "no FTP connection")
  972. return False
  973. try:
  974. file_size = local_path.stat().st_size if local_path.exists() else 0
  975. logger.info("FTP uploading %s (%s bytes) to %s", local_path, file_size, remote_path)
  976. uploaded = 0
  977. callback_exception: Exception | None = None
  978. # Use manual transfer instead of storbinary() for A1 compatibility
  979. # A1 printers have issues with storbinary's voidresp() hanging after transfer
  980. with open(local_path, "rb") as f:
  981. logger.debug("FTP STOR command starting for %s", remote_path)
  982. t0 = time.monotonic()
  983. conn = self._ftp.transfercmd(f"STOR {remote_path}")
  984. logger.info(
  985. "FTP data channel ready in %.1fs (PASV + TLS handshake)",
  986. time.monotonic() - t0,
  987. )
  988. # Set explicit socket options for reliable transfer
  989. conn.setblocking(True)
  990. conn.settimeout(self.timeout)
  991. try:
  992. while True:
  993. chunk = f.read(self.CHUNK_SIZE)
  994. if not chunk:
  995. logger.debug("FTP upload: final chunk reached")
  996. break
  997. conn.sendall(chunk)
  998. uploaded += len(chunk)
  999. logger.debug("FTP upload progress: %s/%s bytes", uploaded, file_size)
  1000. if progress_callback:
  1001. try:
  1002. progress_callback(uploaded, file_size)
  1003. except Exception as e:
  1004. callback_exception = e
  1005. logger.info(
  1006. "FTP upload callback requested stop for %s at %s/%s bytes: %s",
  1007. remote_path,
  1008. uploaded,
  1009. file_size,
  1010. e,
  1011. )
  1012. break
  1013. except OSError as e:
  1014. logger.error("FTP connection lost during upload: %s", e)
  1015. raise
  1016. finally:
  1017. try:
  1018. conn.close()
  1019. except OSError:
  1020. pass
  1021. # Wait for the server's 226 "Transfer complete" response to confirm
  1022. # the file has been flushed to the SD card. Without this, the printer
  1023. # may try to read an incomplete file when the print command is sent,
  1024. # causing 0500-C010 "MicroSD Card read/write exception" errors.
  1025. # See: https://bugs.python.org/issue25458 (ftplib response desync)
  1026. try:
  1027. old_timeout = self._ftp.sock.gettimeout()
  1028. # Use a generous timeout — H2D printers can take 30+ seconds
  1029. # to send the 226 after the data channel closes.
  1030. self._ftp.sock.settimeout(max(self.timeout, 60))
  1031. try:
  1032. resp = self._ftp.voidresp()
  1033. logger.info("FTP STOR confirmed for %s: %s", remote_path, resp.strip())
  1034. finally:
  1035. self._ftp.sock.settimeout(old_timeout)
  1036. except ftplib.Error as e:
  1037. # Some P2S firmware revisions return ftplib.Error (e.g. 426
  1038. # "Failure reading network stream") on voidresp() even when
  1039. # the file landed fully on the SD card — the TLS data
  1040. # channel close races the 226 confirmation (#1417 follow-up).
  1041. # Verify via SIZE: if the server-side file size matches what
  1042. # we just uploaded, the file is intact and we proceed with
  1043. # a warning. If not — or SIZE itself fails — the transfer
  1044. # was genuinely truncated and we must fail so the print
  1045. # command doesn't go out for a partial 3MF (the original
  1046. # reason this catch was tightened in the previous round).
  1047. try:
  1048. server_size = self._ftp.size(remote_path)
  1049. except (OSError, ftplib.Error) as size_err:
  1050. logger.debug("Post-error SIZE check failed: %s", size_err)
  1051. server_size = None
  1052. if server_size is not None and server_size == file_size:
  1053. # INFO, not WARNING: a 426 whose bytes verify is the normal
  1054. # way Bambu FTPS ends a transfer, not a fault. It fired 54
  1055. # times in one support bundle and every one was followed by
  1056. # a completed upload, which buried the 26 handshake failures
  1057. # in the same log that actually cost the user two prints
  1058. # (#2987). The unverified branch below is still an error.
  1059. logger.info(
  1060. "FTP STOR returned %s for %s but file is intact on the "
  1061. "printer (%s bytes match) — proceeding: %s",
  1062. type(e).__name__,
  1063. remote_path,
  1064. file_size,
  1065. e,
  1066. )
  1067. else:
  1068. logger.error(
  1069. "FTP STOR rejected by printer for %s: %s (%s); server size=%s expected=%s",
  1070. remote_path,
  1071. e,
  1072. type(e).__name__,
  1073. server_size,
  1074. file_size,
  1075. )
  1076. raise
  1077. except Exception as e:
  1078. # Timeout or socket-level error reading 226 — the data was sent
  1079. # on our side and the printer may still have written the file.
  1080. # H2D can take 30+ seconds to send 226 after the data channel
  1081. # closes, so we proceed with a warning rather than failing here.
  1082. logger.warning(
  1083. "FTP STOR confirmation not received for %s (proceeding): %s (%s)",
  1084. remote_path,
  1085. e,
  1086. type(e).__name__,
  1087. )
  1088. if callback_exception is None:
  1089. # A cancelled upload is deleted below; its size says nothing.
  1090. self._check_unconfirmed_upload(remote_path, file_size)
  1091. if callback_exception is not None:
  1092. cleanup_result: DeleteResult = DeleteResult.FAILED
  1093. try:
  1094. cleanup_result = self.delete_file(remote_path)
  1095. except Exception as cleanup_error:
  1096. logger.warning("FTP cancel cleanup failed for %s: %s", remote_path, cleanup_error)
  1097. # NOT_FOUND is success here — the partial file is gone (printer
  1098. # may have already swept on cancel), which is the goal.
  1099. if cleanup_result in (DeleteResult.DELETED, DeleteResult.NOT_FOUND):
  1100. logger.info("FTP cancel cleanup succeeded for %s (%s)", remote_path, cleanup_result.value)
  1101. raise callback_exception
  1102. raise RuntimeError(
  1103. f"Upload cancelled but failed to remove partial file {remote_path} from printer"
  1104. ) from callback_exception
  1105. elapsed = time.monotonic() - t0
  1106. speed_kbs = (file_size / 1024) / elapsed if elapsed > 0 else 0
  1107. logger.info(
  1108. "FTP upload complete: %s (%s bytes in %.1fs, %.0f KB/s)",
  1109. remote_path,
  1110. file_size,
  1111. elapsed,
  1112. speed_kbs,
  1113. )
  1114. return True
  1115. except ftplib.error_perm as e:
  1116. # Permanent FTP error (4xx/5xx response)
  1117. error_code = str(e)[:3] if str(e) else "unknown"
  1118. logger.error("FTP upload failed for %s: %s (error code: %s)", remote_path, e, error_code)
  1119. # 553 and 552 are the printer telling us about its own storage --
  1120. # the one case where advice about the card is worth giving, and
  1121. # the case the dispatch's blanket SD-card message was written for
  1122. # before it was applied to every failure alike (#2899).
  1123. if error_code == "553":
  1124. logger.error(
  1125. "FTP 553 error - Could not create file. Possible causes: "
  1126. "1) No SD card inserted, 2) SD card full, 3) SD card not formatted correctly (needs FAT32/exFAT), "
  1127. "4) Printer busy/not ready, 5) File path issue"
  1128. )
  1129. kind = FtpFailureKind.STORAGE
  1130. elif error_code == "550":
  1131. logger.error("FTP 550 error - File/directory not found or permission denied")
  1132. kind = FtpFailureKind.NOT_FOUND
  1133. elif error_code == "552":
  1134. logger.error("FTP 552 error - Storage quota exceeded (SD card full?)")
  1135. kind = FtpFailureKind.STORAGE
  1136. else:
  1137. kind = FtpFailureKind.UNKNOWN
  1138. self.last_failure = FtpFailure(kind, str(e), _ftp_reply_code(e))
  1139. return False
  1140. except (OSError, ftplib.Error) as e:
  1141. logger.error("FTP upload failed for %s: %s (type: %s)", remote_path, e, type(e).__name__)
  1142. code = _ftp_reply_code(e)
  1143. # 452 is "insufficient storage" -- a 4xx, so ftplib raises it as
  1144. # error_temp rather than error_perm, but it is the printer talking
  1145. # about its card just as 552/553 are. As NETWORK it would read as a
  1146. # connection problem, and the queue would say it retries by itself
  1147. # instead of asking for the card to be checked (#3210, #3409).
  1148. is_storage = isinstance(e, ftplib.Error) and code == "452"
  1149. kind = FtpFailureKind.STORAGE if is_storage else FtpFailureKind.NETWORK
  1150. self.last_failure = FtpFailure(kind, str(e), code)
  1151. return False
  1152. def _check_unconfirmed_upload(self, remote_path: str, expected_size: int) -> None:
  1153. """Read an upload's size back when its 226 never came.
  1154. The upload still counts (an H2D can take 30+ s to answer), but a
  1155. printer that kept a partial file should not go unnoticed. A fresh
  1156. connection, because this one may be waiting for that late reply.
  1157. """
  1158. server_size = _size_on_new_connection(self, remote_path)
  1159. if server_size is None:
  1160. logger.warning("FTP upload of %s could not be read back to check its size", remote_path)
  1161. elif server_size != expected_size:
  1162. logger.error(
  1163. "FTP upload of %s is %s bytes on the printer, expected %s: the file may be incomplete",
  1164. remote_path,
  1165. server_size,
  1166. expected_size,
  1167. )
  1168. else:
  1169. logger.info("FTP upload of %s verified on a new connection (%s bytes)", remote_path, server_size)
  1170. def delete_file(self, remote_path: str) -> DeleteResult:
  1171. """Delete a file from the printer.
  1172. Returns :class:`DeleteResult` distinguishing the file-not-found case
  1173. (550) from network / auth / transient FTP failure. Callers that just
  1174. want "did it work" should check ``result == DeleteResult.DELETED``.
  1175. """
  1176. if not self._ftp:
  1177. return DeleteResult.FAILED
  1178. try:
  1179. self._ftp.delete(remote_path)
  1180. return DeleteResult.DELETED
  1181. except ftplib.error_perm as e:
  1182. if str(e).startswith("550"):
  1183. logger.debug("FTP delete: %s not on printer (550)", remote_path)
  1184. return DeleteResult.NOT_FOUND
  1185. logger.warning("Failed to delete %s: %s", remote_path, e)
  1186. return DeleteResult.FAILED
  1187. except (OSError, ftplib.Error) as e:
  1188. logger.warning("Failed to delete %s: %s", remote_path, e)
  1189. return DeleteResult.FAILED
  1190. def get_file_size(self, remote_path: str) -> int | None:
  1191. """Get the size of a file."""
  1192. if not self._ftp:
  1193. return None
  1194. try:
  1195. return self._ftp.size(remote_path)
  1196. except (OSError, ftplib.Error):
  1197. return None
  1198. def get_storage_info(self) -> dict | None:
  1199. """Get storage information from the printer."""
  1200. if not self._ftp:
  1201. return None
  1202. result = {}
  1203. # Try AVBL command (available space) - some FTP servers support this
  1204. try:
  1205. response = self._ftp.sendcmd("AVBL")
  1206. logger.debug("AVBL response: %s", response)
  1207. # Response format: "213 <bytes available>"
  1208. if response.startswith("213"):
  1209. parts = response.split()
  1210. if len(parts) >= 2:
  1211. result["free_bytes"] = int(parts[1])
  1212. except (OSError, ftplib.Error) as e:
  1213. logger.debug("AVBL command not supported: %s", e)
  1214. # Try STAT command as fallback
  1215. try:
  1216. response = self._ftp.sendcmd("STAT")
  1217. logger.debug("STAT response: %s", response)
  1218. except (OSError, ftplib.Error):
  1219. pass # Both AVBL and STAT unsupported; storage info will rely on directory scan
  1220. # Calculate used space by listing root directories
  1221. try:
  1222. total_used = 0
  1223. dirs_to_scan = ["/cache", "/timelapse", "/model", "/data", "/data/Metadata", "/"]
  1224. for dir_path in dirs_to_scan:
  1225. try:
  1226. self._ftp.cwd(dir_path)
  1227. items = []
  1228. self._ftp.retrlines("LIST", items.append)
  1229. for item in items:
  1230. parts = item.split()
  1231. if len(parts) >= 5 and not item.startswith("d"):
  1232. try:
  1233. total_used += int(parts[4])
  1234. except ValueError:
  1235. pass # Skip entries with non-numeric size fields
  1236. except (OSError, ftplib.Error):
  1237. pass # Directory may not exist on this printer model; skip it
  1238. result["used_bytes"] = total_used
  1239. except (OSError, ftplib.Error):
  1240. pass # Storage scan failed; return whatever info was collected above
  1241. return result if result else None
  1242. def _size_on_new_connection(client: BambuFTPClient, remote_path: str) -> int | None:
  1243. """The size of ``remote_path`` read on a connection of its own, or None."""
  1244. fresh = BambuFTPClient(
  1245. client.ip_address,
  1246. client.access_code,
  1247. timeout=client.timeout,
  1248. printer_model=client.printer_model,
  1249. force_prot_c=client.force_prot_c,
  1250. # A second session while the first still waits for its reply may be
  1251. # refused (the printer's connection slots); that must not block the
  1252. # printer's downloads for the cool-off.
  1253. respect_handshake_cooloff=False,
  1254. records_handshake_cooloff=False,
  1255. )
  1256. fresh.FTP_PORT = client.FTP_PORT
  1257. try:
  1258. if not fresh.connect():
  1259. return None
  1260. return fresh.get_file_size(remote_path)
  1261. except Exception:
  1262. return None
  1263. finally:
  1264. fresh.disconnect()
  1265. def describe_upload_failure(failure: FtpFailure | None) -> str:
  1266. """One sentence for the operator, chosen from what actually went wrong.
  1267. Every upload failure used to get the same one: "Failed to upload file to
  1268. printer. Check if SD card is inserted and properly formatted
  1269. (FAT32/exFAT)." #2899's reporter got that after a TLS handshake failure and
  1270. restarted the printer, which could not have helped -- the handshake never
  1271. reached the printer's filesystem, and the state that produced it lives in
  1272. Bambuddy's own memory. #2780 had already removed advice from this failure's
  1273. *log* line for the same reason; it survived in the string people read.
  1274. So the card is named only where the printer itself raised storage, and
  1275. where nothing here can say more, this says so and points at the log rather
  1276. than picking a plausible cause. A wrong instruction costs more than a
  1277. vague one: it sends someone to work on hardware that is fine.
  1278. """
  1279. if failure is None:
  1280. return (
  1281. "Could not upload the file to the printer. See the server log for the reason — "
  1282. "it records what the printer's file service said."
  1283. )
  1284. if failure.kind is FtpFailureKind.STORAGE:
  1285. return (
  1286. f"The printer refused to store the file ({failure.code or 'storage error'}). Check that its SD card "
  1287. "or USB drive is inserted, has space free, and is formatted FAT32 or exFAT."
  1288. )
  1289. if failure.kind is FtpFailureKind.HANDSHAKE:
  1290. return (
  1291. "The printer's file service answered, but not with TLS, so no file could be sent to it. "
  1292. "Its SD card is not involved. This usually clears by itself; if it does not, power-cycling "
  1293. "the printer has not been found to help either, so please report it."
  1294. )
  1295. if failure.kind is FtpFailureKind.COOLOFF:
  1296. return (
  1297. "Bambuddy is holding off from this printer's file service after a recent failed TLS handshake, "
  1298. "so the file was not sent. This clears on its own within a few minutes."
  1299. )
  1300. if failure.kind is FtpFailureKind.AUTH:
  1301. return (
  1302. "The printer refused the file transfer connection. If the printer's access code changed, "
  1303. "update it on Bambuddy's Printers page."
  1304. )
  1305. if failure.kind is FtpFailureKind.TIMEOUT:
  1306. return (
  1307. "The printer's file service did not respond in time, so the file was not sent. "
  1308. "Check that the printer is on the network and reachable."
  1309. )
  1310. if failure.kind is FtpFailureKind.NOT_FOUND:
  1311. return (
  1312. "The printer rejected the upload path (550). See the server log — this is a Bambuddy-side "
  1313. "problem, not something to fix on the printer."
  1314. )
  1315. return (
  1316. "Could not upload the file to the printer. See the server log for the reason — "
  1317. "it records what the printer's file service said."
  1318. )
  1319. def ftps_handshake_blocked(ip_address: str) -> bool:
  1320. """True while this printer's FTPS handshake cool-off is still running.
  1321. Callers that walk a list of candidate paths use this to give up on the
  1322. remaining candidates: the failure is at the transport, below any path, so
  1323. every one of them would fail identically (#2780).
  1324. """
  1325. return BambuFTPClient.handshake_blocked(ip_address)
  1326. # Shared 3MF download cache (#972).
  1327. #
  1328. # Both the cover thumbnail endpoint (api/routes/printers.py) and the archive
  1329. # metadata flow (main.py) fetch the same 3MF file over FTP during a print.
  1330. # On slow / contended links (A1 Wi-Fi, large files) the duplicate transfers
  1331. # compete for the printer's single FTP socket and trigger 425 "can't open
  1332. # data channel" errors, feeding back into cause-2's retry storm.
  1333. #
  1334. # This cache stores the local path of a successfully-downloaded 3MF keyed
  1335. # by (printer_id, normalized_name). Whichever flow downloads first populates
  1336. # the cache; the other flow reuses the file read-only. Evicted on print
  1337. # completion so a later print with the same name re-downloads fresh bytes.
  1338. _threemf_path_cache: dict[tuple[int, str], Path] = {}
  1339. def normalize_3mf_name(name: str) -> str:
  1340. """Collapse various 3MF filename variants to a cache key.
  1341. Bambu tooling produces names as bare subtask ("Part"), with .3mf, with
  1342. .gcode.3mf, or (Studio-normalized) with spaces → underscores. All of
  1343. these refer to the same print job on the same printer, so they must
  1344. hash to the same cache key.
  1345. """
  1346. # Lowercase first so .3MF / .GCODE.3MF variants strip cleanly — a
  1347. # real-world case since Windows-side tooling sometimes uppercases
  1348. # extensions.
  1349. cleaned = name.strip().lower().replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  1350. return cleaned.replace(" ", "_")
  1351. def cache_3mf_download(printer_id: int, name: str, local_path: Path) -> None:
  1352. """Record a successfully-downloaded 3MF so a sibling flow can reuse it."""
  1353. _threemf_path_cache[(printer_id, normalize_3mf_name(name))] = local_path
  1354. def get_cached_3mf(printer_id: int, name: str) -> Path | None:
  1355. """Return a cached 3MF path for this printer/name if the file still exists."""
  1356. key = (printer_id, normalize_3mf_name(name))
  1357. cached = _threemf_path_cache.get(key)
  1358. if cached and cached.exists() and cached.stat().st_size > 0:
  1359. return cached
  1360. # Evict dead entry — the file was cleaned up (temp dir clean, manual
  1361. # deletion, restart) so the cache value is no longer usable.
  1362. if cached:
  1363. _threemf_path_cache.pop(key, None)
  1364. return None
  1365. def clear_3mf_cache(printer_id: int | None = None, delete_files: bool = True) -> None:
  1366. """Drop cache entries for one printer (or all with None).
  1367. When ``delete_files`` is True (default) the on-disk 3MF is removed as well
  1368. — called from on_print_complete so temp files don't accumulate across
  1369. prints. Tests that want to inspect the cache contents disable this.
  1370. Only paths inside ``archive_dir/temp`` are unlinked. The dispatch sites
  1371. added in #1166 also cache the live archive copy and library file bytes
  1372. so /cover can skip FTP — those are *user data*, never the cache's to
  1373. delete. Pre-fix this branch silently removed archive 3mfs on every print
  1374. completion (#1212 + private reports of "file disappeared overnight").
  1375. """
  1376. from backend.app.core.config import settings as _config_settings
  1377. temp_root = _config_settings.archive_dir / "temp"
  1378. def _is_temp_path(path: Path) -> bool:
  1379. try:
  1380. return path.is_relative_to(temp_root)
  1381. except (OSError, ValueError):
  1382. return False
  1383. def _maybe_unlink(path: Path) -> None:
  1384. if not delete_files or not path.exists():
  1385. return
  1386. if not _is_temp_path(path):
  1387. return
  1388. try:
  1389. path.unlink()
  1390. except OSError as exc:
  1391. logger.debug("3MF cache cleanup skipped %s: %s", path, exc)
  1392. if printer_id is None:
  1393. for path in list(_threemf_path_cache.values()):
  1394. _maybe_unlink(path)
  1395. _threemf_path_cache.clear()
  1396. return
  1397. for key in [k for k in _threemf_path_cache if k[0] == printer_id]:
  1398. _maybe_unlink(_threemf_path_cache[key])
  1399. _threemf_path_cache.pop(key, None)
  1400. async def download_file_async(
  1401. ip_address: str,
  1402. access_code: str,
  1403. remote_path: str,
  1404. local_path: Path,
  1405. timeout: float = 60.0,
  1406. socket_timeout: float | None = None,
  1407. printer_model: str | None = None,
  1408. expected_size: int | None = None,
  1409. max_bytes: int | None = None,
  1410. cancel_event: threading.Event | None = None,
  1411. min_free_bytes: int | None = None,
  1412. serialize: bool = True,
  1413. max_total_timeout: float = _DOWNLOAD_MAX_TIMEOUT,
  1414. ) -> bool:
  1415. """Async wrapper for downloading a file with timeout.
  1416. For A1/A1 Mini printers, automatically tries prot_p first, then falls back
  1417. to prot_c if the download fails. The working mode is cached for future operations.
  1418. ``timeout`` bounds the wait for a *result*, not the call: when it expires
  1419. this waits for the FTP worker thread to unwind before returning, because
  1420. the thread owns ``local_path`` until it does and a caller that came back
  1421. early would delete a file still being written. That wait is bounded by the
  1422. socket timeout, so pass ``socket_timeout`` on any path that must not block
  1423. indefinitely -- every caller here does.
  1424. Args:
  1425. ip_address: Printer IP address
  1426. access_code: Printer access code
  1427. remote_path: Remote file path on printer
  1428. local_path: Local path to save file
  1429. timeout: Overall operation timeout (asyncio)
  1430. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  1431. printer_model: Printer model for A1-specific workarounds
  1432. max_total_timeout: the most the size-based extension may stretch the
  1433. deadline to (see ``_download_extension``). The default suits print
  1434. start; the printer file browser passes its own job budget.
  1435. serialize: take this printer's download gate for the transfer (#2957).
  1436. Pass False from a path that must neither queue behind another
  1437. download nor make one queue behind it -- the printer file browser
  1438. is both, and says so: a preview must not wait out somebody else's
  1439. ten-gigabyte selection, and that selection must not hold the printer
  1440. for the twenty minutes it legitimately takes.
  1441. """
  1442. loop = asyncio.get_event_loop()
  1443. is_a1 = printer_model in BambuFTPClient.A1_MODELS if printer_model else False
  1444. # Per-attempt completion state: asyncio.wait_for cannot cancel
  1445. # run_in_executor threads, so on timeout the executor may still complete
  1446. # the download after we stop waiting. The thread flips `success` to True
  1447. # ONLY after the file is fully written — a post-timeout check lets us
  1448. # salvage the download without mistaking an in-progress partial write
  1449. # for a completed one. Each attempt gets its own dict and event so a
  1450. # zombie from an earlier attempt can't flip the flag for a later one.
  1451. # The event is set in `_download`'s finally block so the post-timeout
  1452. # path can wait for genuine thread completion instead of a fixed sleep.
  1453. class _CombinedCancelEvent:
  1454. def __init__(self, attempt_event: threading.Event):
  1455. self._attempt_event = attempt_event
  1456. def is_set(self) -> bool:
  1457. return self._attempt_event.is_set() or (cancel_event is not None and cancel_event.is_set())
  1458. def _download(
  1459. force_prot_c: bool,
  1460. completion: dict,
  1461. done: threading.Event,
  1462. attempt_cancel: threading.Event,
  1463. ) -> bool:
  1464. mode_str = "prot_c" if force_prot_c else "prot_p"
  1465. try:
  1466. combined_cancel = _CombinedCancelEvent(attempt_cancel)
  1467. if combined_cancel.is_set():
  1468. raise DownloadCancelled(remote_path)
  1469. client = BambuFTPClient(
  1470. ip_address,
  1471. access_code,
  1472. timeout=socket_timeout,
  1473. printer_model=printer_model,
  1474. force_prot_c=force_prot_c,
  1475. )
  1476. if client.connect():
  1477. try:
  1478. result = client.download_to_file(
  1479. remote_path,
  1480. local_path,
  1481. expected_size=expected_size,
  1482. max_bytes=max_bytes,
  1483. cancel_event=combined_cancel,
  1484. min_free_bytes=min_free_bytes,
  1485. size_callback=lambda n: completion.__setitem__("size", n),
  1486. )
  1487. if result:
  1488. BambuFTPClient.cache_mode(ip_address, mode_str)
  1489. completion["success"] = True
  1490. return result
  1491. finally:
  1492. client.disconnect()
  1493. return False
  1494. finally:
  1495. done.set()
  1496. async def _run(force_prot_c: bool) -> bool:
  1497. completion = {"success": False}
  1498. done = threading.Event()
  1499. attempt_cancel = threading.Event()
  1500. worker = loop.run_in_executor(_ftp_executor, _download, force_prot_c, completion, done, attempt_cancel)
  1501. # What this attempt was actually allowed, for the log lines below: the
  1502. # size-derived extension moves it after the fact.
  1503. allowed = timeout
  1504. extended = False
  1505. try:
  1506. try:
  1507. return await asyncio.wait_for(asyncio.shield(worker), timeout=timeout)
  1508. except TimeoutError:
  1509. # The deadline was set before anyone knew the file's size. Now
  1510. # the printer has told us, so give a transfer that is genuinely
  1511. # under way the time that size needs (#2957). Re-raises into the
  1512. # handler below when the size is unknown or already covered.
  1513. extension = _download_extension(completion.get("size"), timeout, max_total_timeout)
  1514. if extension <= 0:
  1515. raise
  1516. logger.info(
  1517. "FTP download of %s passed its %ss deadline but the printer reports %s bytes — "
  1518. "allowing %.0fs more rather than declaring a slow transfer dead (#2957)",
  1519. remote_path,
  1520. timeout,
  1521. completion.get("size"),
  1522. extension,
  1523. )
  1524. allowed = timeout + extension
  1525. extended = True
  1526. return await asyncio.wait_for(asyncio.shield(worker), timeout=extension)
  1527. except asyncio.CancelledError:
  1528. # Cancelling an asyncio Future cannot stop its executor thread. Set
  1529. # the callback-visible flag and do not let the caller unlink the
  1530. # staging file until the worker has genuinely unwound.
  1531. attempt_cancel.set()
  1532. try:
  1533. await asyncio.shield(worker)
  1534. except (DownloadCancelled, OSError, ftplib.Error):
  1535. pass
  1536. raise
  1537. except TimeoutError:
  1538. # Slow WiFi links commonly overshoot ftp_timeout by 10–30 s without
  1539. # actually being stuck, so starting attempt 2 now would just contend
  1540. # with the still-progressing RETR on attempt 1 and produce the
  1541. # zombie-write race reported in #1014 (file landed on disk minutes
  1542. # after the retry loop had already given up). Wait for the worker
  1543. # thread to genuinely finish — capped at 30 s so a truly stuck
  1544. # connection can't stall a whole attempt indefinitely, with a 0.5 s
  1545. # floor so artificially small test timeouts still give zombies a
  1546. # realistic window to finish.
  1547. grace = max(min(timeout, 30.0), 0.5)
  1548. # Deliberately the DEFAULT executor, not `_ftp_executor`: this thread
  1549. # blocks waiting on `_download`, which is itself an `_ftp_executor`
  1550. # worker. Parking waiters in the same bounded pool as the workers they
  1551. # wait for is how you build a deadlock — with enough concurrent
  1552. # timeouts the waiters would occupy every slot and the downloads they
  1553. # are waiting for could never be scheduled.
  1554. attempt_cancel.set()
  1555. await loop.run_in_executor(None, done.wait, grace)
  1556. # Wait for the thread either way. If the grace period was enough it
  1557. # returns at once; if it was not, the blocking socket still has to
  1558. # reach its own timeout, and returning before it does would let the
  1559. # caller unlink a file the executor is still writing.
  1560. try:
  1561. await asyncio.shield(worker)
  1562. except (DownloadCancelled, OSError, ftplib.Error):
  1563. pass
  1564. if completion["success"] and local_path.exists() and local_path.stat().st_size > 0:
  1565. logger.info(
  1566. "FTP download wait_for timed out after %ss for %s, but thread completed within %ss grace (%s bytes) — salvaging",
  1567. allowed,
  1568. remote_path,
  1569. grace,
  1570. local_path.stat().st_size,
  1571. )
  1572. return True
  1573. if extended:
  1574. # The transfer had already been given the time its own reported
  1575. # size needs. Retrying spends that again to learn the same
  1576. # thing, so say so rather than reporting an ordinary miss.
  1577. logger.warning(
  1578. "FTP download of %s did not finish inside the %ss its size bought it (plus %ss grace)",
  1579. remote_path,
  1580. allowed,
  1581. grace,
  1582. )
  1583. raise DownloadDeadlineExceeded(remote_path)
  1584. logger.warning(
  1585. "FTP download timed out after %ss (plus %ss grace) for %s",
  1586. allowed,
  1587. grace,
  1588. remote_path,
  1589. )
  1590. return False
  1591. # Check if we have a cached mode for this printer
  1592. cached_mode = BambuFTPClient._mode_cache.get(ip_address)
  1593. # The gate spans the prot_c fallback too: those are two attempts at one
  1594. # transfer, and letting go between them would hand the printer to a waiter
  1595. # mid-download (#2957).
  1596. async with _serialized_download(ip_address, f"a download of {remote_path}", enabled=serialize):
  1597. if cached_mode:
  1598. force_prot_c = cached_mode == "prot_c"
  1599. return await _run(force_prot_c)
  1600. # No cached mode - try prot_p first
  1601. if await _run(False):
  1602. return True
  1603. # Download failed - for A1 models, try prot_c fallback
  1604. if is_a1:
  1605. logger.info("FTP download failed with prot_p for A1 model, trying prot_c fallback...")
  1606. return await _run(True)
  1607. return False
  1608. async def download_file_try_paths_async(
  1609. ip_address: str,
  1610. access_code: str,
  1611. remote_paths: list[str],
  1612. local_path: Path,
  1613. socket_timeout: float | None = None,
  1614. printer_model: str | None = None,
  1615. timeout: float = 90.0,
  1616. max_total_timeout: float | None = None,
  1617. ) -> str | None:
  1618. """Try downloading a file from multiple paths using a single connection.
  1619. Returns the path that served the file, or ``None``. The path rather than a
  1620. bare flag because the caller usually cannot tell afterwards which candidate
  1621. hit, and on a printer that keeps uploads around for weeks that is the
  1622. difference between a diagnosable stale-copy match and an invisible one
  1623. (#1820). Callers testing it for truth are unaffected: a served path is
  1624. always a non-empty string.
  1625. Args:
  1626. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  1627. printer_model: Printer model for A1-specific workarounds
  1628. timeout: overall async cap. The per-socket timeout only bounds an
  1629. in-flight worker; it does NOT bound how long this coroutine waits
  1630. for a free slot in the fixed-size ``_ftp_executor``. On a large
  1631. farm where offline printers keep every worker busy on dead
  1632. connects, that queue wait is otherwise unbounded — and any caller
  1633. holding a DB connection while awaiting this would pin it until the
  1634. pool is exhausted (#2572). The cap converts that into a bounded
  1635. wait; the worker is then cancelled and waited out rather than
  1636. orphaned (#2957), so a DB-holding caller's worst case is the gate
  1637. wait plus this cap plus one unwind -- still bounded, and the
  1638. orphaned worker no longer keeps the printer's socket after it.
  1639. max_total_timeout: how far a path that answered SIZE may stretch that
  1640. cap (see ``_download_extension``), as ``download_file_async`` does.
  1641. None (the default) stretches nothing: a caller holding a DB session
  1642. keeps the bound above.
  1643. """
  1644. loop = asyncio.get_event_loop()
  1645. # An executor thread cannot be cancelled, so the cap alone used to leave a
  1646. # worker walking the remaining paths -- still holding the printer's FTP
  1647. # socket -- long after this coroutine had given up on it. A reporter's log
  1648. # shows one of those still going as the archive flow's own download landed,
  1649. # two Bambuddy transfers deep into a P1S that was mid-print (#2957). The
  1650. # flag stops it at the next chunk instead.
  1651. cancel = threading.Event()
  1652. done = threading.Event()
  1653. reported: dict = {}
  1654. def _download():
  1655. try:
  1656. client = BambuFTPClient(ip_address, access_code, timeout=socket_timeout, printer_model=printer_model)
  1657. if not client.connect():
  1658. return None
  1659. try:
  1660. # FileNotOnPrinterError signals "try the next path", not "give up" —
  1661. # this function's whole purpose is to walk a list of candidates
  1662. # over one connection. Only a real transport error should bubble.
  1663. for remote_path in remote_paths:
  1664. if cancel.is_set():
  1665. return None
  1666. try:
  1667. if client.download_to_file(
  1668. remote_path,
  1669. local_path,
  1670. cancel_event=cancel,
  1671. size_callback=lambda n: reported.__setitem__("size", n),
  1672. ):
  1673. return remote_path
  1674. except FileNotOnPrinterError:
  1675. continue
  1676. except DownloadCancelled:
  1677. return None
  1678. return None
  1679. finally:
  1680. client.disconnect()
  1681. finally:
  1682. done.set()
  1683. async with _serialized_download(ip_address, f"a {len(remote_paths)}-path lookup"):
  1684. worker = loop.run_in_executor(_ftp_executor, _download)
  1685. try:
  1686. try:
  1687. return await asyncio.wait_for(asyncio.shield(worker), timeout=timeout)
  1688. except TimeoutError:
  1689. # A path the printer is serving has told us its size: give it
  1690. # the time that size needs, as download_file_async does.
  1691. extension = (
  1692. _download_extension(reported.get("size"), timeout, max_total_timeout)
  1693. if max_total_timeout is not None
  1694. else 0.0
  1695. )
  1696. if extension <= 0:
  1697. raise
  1698. logger.info(
  1699. "FTP download_try_paths passed its %ss cap but the printer reports %s bytes — allowing %.0fs more",
  1700. timeout,
  1701. reported.get("size"),
  1702. extension,
  1703. )
  1704. timeout += extension
  1705. return await asyncio.wait_for(asyncio.shield(worker), timeout=extension)
  1706. except asyncio.CancelledError:
  1707. # The caller is going away and should not be made to wait, but the
  1708. # worker must not keep the printer to itself either.
  1709. cancel.set()
  1710. _discard_worker_outcome(worker)
  1711. raise
  1712. except TimeoutError:
  1713. logger.warning("FTP download_try_paths exceeded its %ss cap for %s (#2572)", timeout, ip_address)
  1714. cancel.set()
  1715. # Do not hand the printer to the next download while this worker is
  1716. # still on its socket. The DEFAULT executor, never ``_ftp_executor``:
  1717. # parking a waiter in the same bounded pool as the worker it waits
  1718. # for is how a deadlock gets built.
  1719. await loop.run_in_executor(None, done.wait, _DOWNLOAD_UNWIND_SECONDS)
  1720. _discard_worker_outcome(worker)
  1721. return None
  1722. def _upload_deadline(local_path: Path) -> float:
  1723. """Derive an upload deadline from the file size (#2529).
  1724. See ``_UPLOAD_FLOOR_BYTES_PER_SEC``. An unstat-able file falls back to the
  1725. floor timeout — ``upload_file`` will fail on the open() anyway.
  1726. """
  1727. try:
  1728. size = local_path.stat().st_size
  1729. except OSError:
  1730. return _UPLOAD_MIN_TIMEOUT
  1731. return max(_UPLOAD_MIN_TIMEOUT, size / _UPLOAD_FLOOR_BYTES_PER_SEC)
  1732. # One upload at a time per printer. Two concurrent STOR commands for the same
  1733. # remote path leave a corrupt file on the SD card, and the printer reads as
  1734. # flaky rather than busy (#2529). Held for the duration of a transfer, so a
  1735. # second dispatch to the same printer queues behind the first instead of racing
  1736. # it. Keyed per event loop: an asyncio.Lock binds to the loop that first awaits
  1737. # it, and the test suite runs each case on a fresh loop.
  1738. _upload_locks: weakref.WeakKeyDictionary[asyncio.AbstractEventLoop, dict[str, asyncio.Lock]] = (
  1739. weakref.WeakKeyDictionary()
  1740. )
  1741. def _upload_lock(loop: asyncio.AbstractEventLoop, ip_address: str) -> asyncio.Lock:
  1742. per_loop = _upload_locks.setdefault(loop, {})
  1743. lock = per_loop.get(ip_address)
  1744. if lock is None:
  1745. lock = asyncio.Lock()
  1746. per_loop[ip_address] = lock
  1747. return lock
  1748. async def upload_file_async(
  1749. ip_address: str,
  1750. access_code: str,
  1751. local_path: Path,
  1752. remote_path: str,
  1753. timeout: float | None = None,
  1754. progress_callback: Callable[[int, int], None] | None = None,
  1755. socket_timeout: float | None = None,
  1756. printer_model: str | None = None,
  1757. respect_handshake_cooloff: bool = True,
  1758. failure: FtpFailureReport | None = None,
  1759. ) -> bool:
  1760. """Async wrapper for uploading a file with timeout and progress callback.
  1761. For A1/A1 Mini printers, automatically tries prot_p first, then falls back
  1762. to prot_c if the upload fails. The working mode is cached for future uploads.
  1763. Args:
  1764. ip_address: Printer IP address
  1765. access_code: Printer access code
  1766. local_path: Local file path to upload
  1767. remote_path: Remote path on printer
  1768. timeout: Overall deadline. ``None`` (the default) derives it from the
  1769. file size — see ``_upload_deadline``. A caller that passes a number
  1770. gets exactly that, which is what the tests rely on.
  1771. progress_callback: Optional callback for progress updates
  1772. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  1773. printer_model: Printer model for A1-specific workarounds
  1774. respect_handshake_cooloff: see ``BambuFTPClient.__init__``. False for a
  1775. user-initiated upload, whose attempts are bounded and were being
  1776. spent against a cool-off that outlives them (#2898).
  1777. failure: caller-owned slot filled in with why the upload failed, so the
  1778. caller can say something true about it instead of guessing (#2899).
  1779. Passed through ``with_ftp_retry`` unchanged, so it ends up holding
  1780. the last attempt's reason -- which is the one that decided the
  1781. outcome.
  1782. """
  1783. loop = asyncio.get_event_loop()
  1784. is_a1 = printer_model in BambuFTPClient.A1_MODELS if printer_model else False
  1785. deadline = _upload_deadline(local_path) if timeout is None else timeout
  1786. # Set when the deadline expires. The worker checks it once per chunk.
  1787. cancel = threading.Event()
  1788. def _guarded_progress(uploaded: int, total: int) -> None:
  1789. if cancel.is_set():
  1790. raise UploadCancelled(f"upload of {remote_path} exceeded its {deadline:.0f}s deadline")
  1791. if progress_callback:
  1792. progress_callback(uploaded, total)
  1793. def _upload(force_prot_c: bool = False) -> bool:
  1794. mode_str = "prot_c" if force_prot_c else "prot_p"
  1795. logger.info(
  1796. f"FTP connecting to {ip_address} for upload (model={printer_model}, "
  1797. f"mode={mode_str}, socket_timeout={socket_timeout}s, deadline={deadline:.0f}s)..."
  1798. )
  1799. client = BambuFTPClient(
  1800. ip_address,
  1801. access_code,
  1802. timeout=socket_timeout,
  1803. printer_model=printer_model,
  1804. force_prot_c=force_prot_c,
  1805. respect_handshake_cooloff=respect_handshake_cooloff,
  1806. )
  1807. try:
  1808. if client.connect():
  1809. logger.info("FTP connected to %s", ip_address)
  1810. try:
  1811. result = client.upload_file(local_path, remote_path, _guarded_progress)
  1812. if result:
  1813. # Cache the working mode
  1814. BambuFTPClient.cache_mode(ip_address, mode_str)
  1815. return result
  1816. finally:
  1817. client.disconnect()
  1818. logger.warning("FTP connection failed to %s", ip_address)
  1819. return False
  1820. finally:
  1821. # In a finally so a transfer that leaves by raising -- a cancelled
  1822. # upload, a re-raised STOR rejection -- still reports what the
  1823. # client recorded on its way out.
  1824. if failure is not None and client.last_failure is not None:
  1825. failure.failure = client.last_failure
  1826. async def _attempt(force_prot_c: bool) -> bool:
  1827. """Run one upload attempt, and make a timeout actually stop the transfer.
  1828. ``asyncio.wait_for`` cancels the *future*, never the executor thread
  1829. behind it. Before #2529 a slow-but-healthy upload that overran the
  1830. deadline left that thread streaming: it kept pushing bytes, kept firing
  1831. the progress callback, and the retry above put a *second* STOR of the
  1832. same file onto the same printer. The reporter's 96 MB job ran four
  1833. concurrent transfers and never landed. So on timeout we signal the
  1834. worker (it raises ``UploadCancelled`` from the progress callback, which
  1835. breaks the send loop and deletes the partial file) and wait for it to
  1836. actually go.
  1837. """
  1838. fut = loop.run_in_executor(_ftp_executor, lambda: _upload(force_prot_c))
  1839. try:
  1840. return await asyncio.wait_for(asyncio.shield(fut), timeout=deadline)
  1841. except TimeoutError:
  1842. cancel.set()
  1843. logger.warning(
  1844. "FTP upload of %s exceeded its %.0fs deadline — cancelling the transfer",
  1845. remote_path,
  1846. deadline,
  1847. )
  1848. try:
  1849. await asyncio.wait_for(asyncio.shield(fut), timeout=_UPLOAD_CANCEL_GRACE)
  1850. except UploadCancelled:
  1851. logger.info("FTP upload of %s cancelled; partial file removed from the printer", remote_path)
  1852. except TimeoutError:
  1853. # The thread is wedged somewhere that never reaches the callback
  1854. # (a blocked sendall, say). Nothing more we can do from here —
  1855. # but consume the eventual result so asyncio doesn't log the
  1856. # future's exception as unretrieved when it is garbage-collected.
  1857. logger.error(
  1858. "FTP upload thread for %s did not stop within %.0fs of the cancel signal",
  1859. remote_path,
  1860. _UPLOAD_CANCEL_GRACE,
  1861. )
  1862. fut.add_done_callback(_swallow_future_result)
  1863. except Exception as e:
  1864. logger.warning("FTP upload of %s errored while cancelling: %s", remote_path, e)
  1865. # Raise rather than return False: a deadline expiry means the link
  1866. # sustained less than the floor rate for the whole transfer, and a
  1867. # retry would only spend another full deadline finding that out
  1868. # again — with check_queue serialized, four of those block the
  1869. # entire print queue for hours. ``with_ftp_retry`` never retries it.
  1870. raise UploadCancelled(
  1871. f"Upload of {remote_path} to {ip_address} exceeded its {deadline:.0f}s deadline "
  1872. f"(link sustained less than {_UPLOAD_FLOOR_BYTES_PER_SEC // 1024} KB/s)"
  1873. ) from None
  1874. async with _upload_lock(loop, ip_address):
  1875. # Check if we have a cached mode for this printer
  1876. cached_mode = BambuFTPClient._mode_cache.get(ip_address)
  1877. if cached_mode:
  1878. # Use cached mode
  1879. return await _attempt(cached_mode == "prot_c")
  1880. # No cached mode - try prot_p first
  1881. if await _attempt(False):
  1882. return True
  1883. # Upload failed - for A1 models, try prot_c fallback
  1884. if is_a1:
  1885. logger.info("FTP upload failed with prot_p for A1 model, trying prot_c fallback...")
  1886. return await _attempt(True)
  1887. return False
  1888. def _swallow_future_result(fut: asyncio.Future) -> None:
  1889. """Retrieve a future's exception so asyncio doesn't log it as unhandled."""
  1890. if not fut.cancelled():
  1891. fut.exception()
  1892. async def list_files_async(
  1893. ip_address: str,
  1894. access_code: str,
  1895. path: str = "/",
  1896. timeout: float = 30.0,
  1897. socket_timeout: float | None = None,
  1898. printer_model: str | None = None,
  1899. ) -> list[dict]:
  1900. """Async wrapper for listing files with timeout.
  1901. Args:
  1902. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  1903. printer_model: Printer model for A1-specific workarounds
  1904. """
  1905. loop = asyncio.get_event_loop()
  1906. def _list():
  1907. client = BambuFTPClient(ip_address, access_code, timeout=socket_timeout, printer_model=printer_model)
  1908. if client.connect():
  1909. try:
  1910. return client.list_files(path)
  1911. finally:
  1912. client.disconnect()
  1913. return []
  1914. try:
  1915. return await asyncio.wait_for(loop.run_in_executor(_ftp_executor, _list), timeout=timeout)
  1916. except TimeoutError:
  1917. logger.warning("FTP list_files timed out after %ss for %s", timeout, path)
  1918. return []
  1919. async def list_files_result_async(
  1920. ip_address: str,
  1921. access_code: str,
  1922. path: str = "/",
  1923. timeout: float = 30.0,
  1924. socket_timeout: float | None = None,
  1925. printer_model: str | None = None,
  1926. ) -> FileListResult:
  1927. """List a directory without collapsing transport failure into empty."""
  1928. loop = asyncio.get_event_loop()
  1929. key = (ip_address, access_code, path)
  1930. running = _inflight_listings.get(key)
  1931. if running is None or running[0].done():
  1932. # Set once the printer has answered: only then is a timeout a slow
  1933. # listing rather than a printer that is not there.
  1934. connected = threading.Event()
  1935. def _list() -> FileListResult:
  1936. client = BambuFTPClient(ip_address, access_code, timeout=socket_timeout, printer_model=printer_model)
  1937. if not client.connect():
  1938. return FileListResult(files=[], available=False)
  1939. connected.set()
  1940. try:
  1941. return FileListResult(files=client.list_files(path, raise_on_error=True), available=True)
  1942. except ftplib.error_perm as e:
  1943. return FileListResult(files=[], available=False, missing=str(e).startswith("550"))
  1944. except (OSError, ftplib.Error):
  1945. return FileListResult(files=[], available=False)
  1946. finally:
  1947. client.disconnect()
  1948. running = (loop.run_in_executor(_ftp_executor, _list), connected)
  1949. _inflight_listings[key] = running
  1950. def _forget(done: asyncio.Future, key: tuple[str, str, str] = key) -> None:
  1951. entry = _inflight_listings.get(key)
  1952. if entry is not None and entry[0] is done:
  1953. del _inflight_listings[key]
  1954. running[0].add_done_callback(_forget)
  1955. future, connected = running
  1956. try:
  1957. # shield: one caller giving up must not cancel the listing another
  1958. # caller joined.
  1959. result = await asyncio.wait_for(asyncio.shield(future), timeout=timeout)
  1960. except TimeoutError:
  1961. logger.warning("FTP list_files timed out after %ss for %s", timeout, path)
  1962. return FileListResult(files=[], available=False, timed_out=connected.is_set())
  1963. # Joined callers share the listing; each gets entries of its own to edit.
  1964. return FileListResult(files=[dict(f) for f in result.files], available=result.available, missing=result.missing)
  1965. async def find_remote_file_async(
  1966. ip_address: str,
  1967. access_code: str,
  1968. remote_paths: list[str],
  1969. timeout: float = 30.0,
  1970. socket_timeout: float | None = None,
  1971. printer_model: str | None = None,
  1972. ) -> str | None:
  1973. """First of *remote_paths* the printer actually has, or None.
  1974. Answers "is this file there?" without fetching it, over a single
  1975. connection: one listing per distinct directory, reused across the
  1976. candidates that share it, and stops at the first hit. Written for the
  1977. connection diagnostic (#2856), which needs the answer for a file that can
  1978. be tens of megabytes and has no use for its contents.
  1979. Listing rather than ``SIZE``: LIST is what every Bambu firmware here is
  1980. known to answer, and a ``SIZE`` the server simply does not implement would
  1981. read as "the file is missing".
  1982. """
  1983. loop = asyncio.get_event_loop()
  1984. def _find() -> str | None:
  1985. client = BambuFTPClient(ip_address, access_code, timeout=socket_timeout, printer_model=printer_model)
  1986. if not client.connect():
  1987. return None
  1988. try:
  1989. listed: dict[str, set[str]] = {}
  1990. for remote_path in remote_paths:
  1991. directory, _, name = remote_path.rpartition("/")
  1992. directory = directory or "/"
  1993. if directory not in listed:
  1994. listed[directory] = {
  1995. entry.get("name") for entry in client.list_files(directory) if not entry.get("is_directory")
  1996. }
  1997. if name in listed[directory]:
  1998. return remote_path
  1999. return None
  2000. finally:
  2001. client.disconnect()
  2002. try:
  2003. return await asyncio.wait_for(loop.run_in_executor(_ftp_executor, _find), timeout=timeout)
  2004. except TimeoutError:
  2005. logger.warning("FTP find_remote_file timed out after %ss on %s", timeout, ip_address)
  2006. return None
  2007. async def delete_file_async(
  2008. ip_address: str,
  2009. access_code: str,
  2010. remote_path: str,
  2011. socket_timeout: float | None = None,
  2012. printer_model: str | None = None,
  2013. timeout: float = 60.0,
  2014. respect_handshake_cooloff: bool = True,
  2015. ) -> DeleteResult:
  2016. """Async wrapper for deleting a file.
  2017. Returns :class:`DeleteResult` so callers can distinguish ``NOT_FOUND``
  2018. (550 — file isn't on the printer, no retry value) from ``FAILED``
  2019. (network / auth / transient — worth retrying or surfacing).
  2020. Args:
  2021. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  2022. printer_model: Printer model for A1-specific workarounds
  2023. timeout: overall async cap so a saturated ``_ftp_executor`` can't pin
  2024. the caller (and any DB connection it holds) indefinitely (#2572).
  2025. respect_handshake_cooloff: see ``BambuFTPClient.__init__``. The delete
  2026. that clears the way for a dispatch shares the upload's exemption --
  2027. it is one connection, and in #2898's trace it is the one that armed
  2028. the cool-off the upload then spent all four attempts against.
  2029. """
  2030. loop = asyncio.get_event_loop()
  2031. def _delete() -> DeleteResult:
  2032. client = BambuFTPClient(
  2033. ip_address,
  2034. access_code,
  2035. timeout=socket_timeout,
  2036. printer_model=printer_model,
  2037. respect_handshake_cooloff=respect_handshake_cooloff,
  2038. )
  2039. if client.connect():
  2040. try:
  2041. return client.delete_file(remote_path)
  2042. finally:
  2043. client.disconnect()
  2044. return DeleteResult.FAILED
  2045. try:
  2046. return await asyncio.wait_for(loop.run_in_executor(_ftp_executor, _delete), timeout=timeout)
  2047. except TimeoutError:
  2048. logger.warning("FTP delete_file exceeded its %ss cap for %s (#2572)", timeout, ip_address)
  2049. return DeleteResult.FAILED
  2050. async def download_file_bytes_async(
  2051. ip_address: str,
  2052. access_code: str,
  2053. remote_path: str,
  2054. socket_timeout: float | None = None,
  2055. printer_model: str | None = None,
  2056. timeout: float = 300.0,
  2057. expected_size: int | None = None,
  2058. report_missing: bool = False,
  2059. max_total_timeout: float = _DOWNLOAD_MAX_TIMEOUT,
  2060. ) -> bytes | None:
  2061. """Async wrapper for downloading file as bytes.
  2062. Args:
  2063. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  2064. printer_model: Printer model for A1-specific workarounds
  2065. timeout: overall async cap so a saturated ``_ftp_executor`` can't pin
  2066. the caller (and any DB connection it holds) indefinitely (#2572).
  2067. Raised to fit ``expected_size`` at the pessimistic floor rate when
  2068. that is longer (#3272): a 75 MB timelapse took 358 s on a healthy
  2069. P1S link, and a flat cap cannot tell slow from stuck. A dead link
  2070. is still caught by ``socket_timeout``.
  2071. expected_size: size from the directory listing; a mismatch fails the
  2072. download instead of returning a truncated file. See
  2073. :meth:`BambuFTPClient.download_file`.
  2074. report_missing: raise :class:`FileNotOnPrinterError` for a path the
  2075. printer says is not there, so a caller can answer 404 for that
  2076. and 502 for a download that failed.
  2077. max_total_timeout: without ``expected_size``, the size the printer
  2078. reports when the transfer starts stretches the deadline up to this
  2079. (see ``_download_extension``).
  2080. At the deadline the transfer is stopped and its thread waited for (bounded
  2081. by the socket timeout), so a retry never opens a second session beside it.
  2082. A deadline that fitted the file's size raises
  2083. :class:`DownloadDeadlineExceeded`, which ``with_ftp_retry`` does not retry.
  2084. """
  2085. # Unlike ``_download_extension`` there is no 300 s ceiling here: that one
  2086. # exists because ``on_print_start`` holds a DB session across its 3MF hunt.
  2087. # Every caller that passes a size releases its session before the transfer.
  2088. if expected_size and expected_size > 0:
  2089. timeout = max(timeout, expected_size / _DOWNLOAD_FLOOR_BYTES_PER_SEC)
  2090. loop = asyncio.get_event_loop()
  2091. cancel = threading.Event()
  2092. reported: dict[str, int] = {}
  2093. sized = bool(expected_size and expected_size > 0)
  2094. def _download():
  2095. if cancel.is_set():
  2096. return None
  2097. client = BambuFTPClient(ip_address, access_code, timeout=socket_timeout, printer_model=printer_model)
  2098. if client.connect():
  2099. try:
  2100. return client.download_file(
  2101. remote_path,
  2102. expected_size=expected_size,
  2103. cancel_event=cancel,
  2104. size_callback=None if sized else (lambda n: reported.__setitem__("size", n)),
  2105. report_missing=report_missing,
  2106. )
  2107. finally:
  2108. client.disconnect()
  2109. return None
  2110. async def _stop(worker) -> bytes | None:
  2111. """Tell the transfer to stop and wait for its thread to end.
  2112. Waited for unconditionally, like ``download_file_async``: a thread left
  2113. running would hold its FTP session while a retry opens another. The
  2114. wait is bounded by the socket timeout (a blocked read, then the QUIT).
  2115. A result that arrives meanwhile is kept; anything it raises is not the
  2116. caller's concern any more.
  2117. """
  2118. cancel.set()
  2119. try:
  2120. return await asyncio.shield(worker)
  2121. except Exception:
  2122. return None
  2123. worker = loop.run_in_executor(_ftp_executor, _download)
  2124. allowed = timeout
  2125. try:
  2126. try:
  2127. return await asyncio.wait_for(asyncio.shield(worker), timeout=timeout)
  2128. except TimeoutError:
  2129. # No listing size: the size the printer reported when the transfer
  2130. # started buys a slow link its time, as in download_file_async.
  2131. extension = 0.0 if sized else _download_extension(reported.get("size"), timeout, max_total_timeout)
  2132. if extension <= 0:
  2133. raise
  2134. allowed = timeout + extension
  2135. sized = True
  2136. return await asyncio.wait_for(asyncio.shield(worker), timeout=extension)
  2137. except asyncio.CancelledError:
  2138. await asyncio.shield(_stop(worker))
  2139. raise
  2140. except DownloadCancelled:
  2141. return None
  2142. except TimeoutError:
  2143. data = await _stop(worker)
  2144. if data:
  2145. # Finished inside the grace period: keep it.
  2146. return data
  2147. logger.warning(
  2148. "FTP download of %s (%s bytes) exceeded its %.0fs cap for %s",
  2149. remote_path,
  2150. expected_size or reported.get("size") or "unknown",
  2151. allowed,
  2152. ip_address,
  2153. )
  2154. if sized:
  2155. # The deadline already fitted the file at a floor rate no working
  2156. # link falls below: another attempt would reach the same end.
  2157. raise DownloadDeadlineExceeded(remote_path) from None
  2158. return None
  2159. async def remote_file_settled(
  2160. ip_address: str,
  2161. access_code: str,
  2162. remote_path: str,
  2163. downloaded_bytes: int,
  2164. *,
  2165. printer_model: str | None = None,
  2166. ) -> bool:
  2167. """Confirm the printer has finished writing the file we just downloaded.
  2168. Matching the download against the size from the directory listing proves we
  2169. received what the listing *said*, not that the file was *finished*. The
  2170. timelapse scan's first look happens seconds after the print ends, which is
  2171. exactly when the printer is writing the video — so a file still growing can
  2172. be listed at a partial size, served at that size, and pass the length check
  2173. as a complete video (#2704).
  2174. That was survivable while the printer kept its copy. It isn't now that a
  2175. successful attach deletes the source, so re-list afterwards: if the file has
  2176. grown, what we hold is a prefix and the caller should discard it and try
  2177. again on the next round.
  2178. Returns True when the remote file can no longer differ from what we hold —
  2179. the size still matches, or the file is gone from the listing entirely and
  2180. so cannot grow any further. Returns False when it has changed size, and on
  2181. a listing failure, because "we could not check" must not read as "safe to
  2182. delete".
  2183. """
  2184. directory, _, name = remote_path.rpartition("/")
  2185. files = await list_files_async(ip_address, access_code, directory or "/", printer_model=printer_model)
  2186. if not files:
  2187. logger.warning("[TIMELAPSE] Could not re-list %s to confirm %s is complete", directory or "/", name)
  2188. return False
  2189. for f in files:
  2190. if f.get("name") == name:
  2191. size = f.get("size")
  2192. if size == downloaded_bytes:
  2193. return True
  2194. logger.info(
  2195. "[TIMELAPSE] %s is still being written (%s bytes now, %s when downloaded) — will retry",
  2196. name,
  2197. size,
  2198. downloaded_bytes,
  2199. )
  2200. return False
  2201. # Vanished between the download and now. Nothing left that could grow, and
  2202. # nothing left to delete either.
  2203. logger.debug("[TIMELAPSE] %s is no longer on the printer after download", name)
  2204. return True
  2205. async def delete_archived_timelapse(
  2206. ip_address: str,
  2207. access_code: str,
  2208. remote_path: str,
  2209. *,
  2210. verified: bool,
  2211. printer_model: str | None = None,
  2212. printer_name: str = "",
  2213. ) -> bool:
  2214. """Remove a timelapse from the printer once it is safely in the archive.
  2215. Call this only after the attach succeeded (#2704). Keeping ``/timelapse``
  2216. down to just the unclaimed videos is what makes the snapshot diff
  2217. unambiguous rather than merely usually-right, and it stops P1S cards
  2218. filling with AVIs.
  2219. ``verified`` must say whether the downloaded byte count was checked against
  2220. the size the directory listing reported. It is required rather than
  2221. defaulted because this is the one irreversible step in the flow: an FTPS
  2222. data connection that closes early does not always raise, so an unverified
  2223. transfer can be a partial file that looks complete, and deleting the source
  2224. would then destroy the only good copy. The check lives here rather than at
  2225. each call site so no future caller can omit it.
  2226. Best-effort otherwise: a printer that refuses the delete keeps its copy, the
  2227. diff still excludes that filename next time because it is attached to an
  2228. archive, and nothing else in the flow cares. Returns True only on an actual
  2229. delete or a 550 (already gone).
  2230. """
  2231. if not verified:
  2232. logger.warning(
  2233. "[TIMELAPSE] Not deleting %s from printer %s: the download was never size-checked",
  2234. remote_path,
  2235. printer_name,
  2236. )
  2237. return False
  2238. for attempt in range(1, 4):
  2239. try:
  2240. result = await delete_file_async(ip_address, access_code, remote_path, printer_model=printer_model)
  2241. except Exception as e:
  2242. result = DeleteResult.FAILED
  2243. logger.warning("[TIMELAPSE] Delete attempt %d/3 raised for %s: %s", attempt, remote_path, e)
  2244. if result == DeleteResult.DELETED:
  2245. logger.info("[TIMELAPSE] Deleted %s from printer %s after archiving", remote_path, printer_name)
  2246. return True
  2247. if result == DeleteResult.NOT_FOUND:
  2248. # 550 never recovers by waiting — the printer already cleaned up.
  2249. logger.debug("[TIMELAPSE] %s already gone from printer %s", remote_path, printer_name)
  2250. return True
  2251. if attempt < 3:
  2252. await asyncio.sleep(2)
  2253. logger.warning(
  2254. "[TIMELAPSE] Could not delete %s from printer %s (it stays on the card; the archive copy is unaffected)",
  2255. remote_path,
  2256. printer_name,
  2257. )
  2258. return False
  2259. async def get_storage_info_async(
  2260. ip_address: str,
  2261. access_code: str,
  2262. socket_timeout: float | None = None,
  2263. printer_model: str | None = None,
  2264. timeout: float = 60.0,
  2265. ) -> dict | None:
  2266. """Async wrapper for getting storage info.
  2267. Args:
  2268. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  2269. printer_model: Printer model for A1-specific workarounds
  2270. timeout: overall async cap so a saturated ``_ftp_executor`` can't pin
  2271. the caller (and any DB connection it holds) indefinitely (#2572).
  2272. """
  2273. loop = asyncio.get_event_loop()
  2274. def _get_storage():
  2275. client = BambuFTPClient(ip_address, access_code, timeout=socket_timeout, printer_model=printer_model)
  2276. if client.connect():
  2277. try:
  2278. return client.get_storage_info()
  2279. finally:
  2280. client.disconnect()
  2281. return None
  2282. try:
  2283. return await asyncio.wait_for(loop.run_in_executor(_ftp_executor, _get_storage), timeout=timeout)
  2284. except TimeoutError:
  2285. logger.warning("FTP get_storage_info exceeded its %ss cap for %s (#2572)", timeout, ip_address)
  2286. return None
  2287. async def get_ftp_retry_settings() -> tuple[bool, int, float, float]:
  2288. """Get FTP retry settings from database.
  2289. Returns:
  2290. Tuple of (retry_enabled, retry_count, retry_delay, timeout)
  2291. """
  2292. from backend.app.api.routes.settings import get_setting
  2293. from backend.app.core.database import async_session
  2294. async with async_session() as db:
  2295. enabled = (await get_setting(db, "ftp_retry_enabled") or "true") == "true"
  2296. count = int(await get_setting(db, "ftp_retry_count") or "3")
  2297. delay = float(await get_setting(db, "ftp_retry_delay") or "2")
  2298. timeout = float(await get_setting(db, "ftp_timeout") or "30")
  2299. return enabled, count, delay, timeout
  2300. async def with_ftp_retry(
  2301. operation: Callable[..., Awaitable[T]],
  2302. *args,
  2303. max_retries: int = 3,
  2304. retry_delay: float = 2.0,
  2305. operation_name: str = "FTP operation",
  2306. non_retry_exceptions: tuple[type[BaseException], ...] = (),
  2307. cooloff_ip: str | None = None,
  2308. **kwargs,
  2309. ) -> T | None:
  2310. """Execute FTP operation with retry logic.
  2311. Args:
  2312. operation: Async function to execute
  2313. *args: Positional arguments for the operation
  2314. max_retries: Number of retry attempts (default: 3)
  2315. retry_delay: Seconds to wait between retries (default: 2.0)
  2316. operation_name: Name for logging purposes
  2317. non_retry_exceptions: Exception types that should immediately abort retries
  2318. cooloff_ip: printer IP whose FTPS handshake cool-off should end the loop
  2319. early. Pass it from any caller that respects the cool-off; leave it
  2320. unset for one that opted out, or the loop would stop on a gate its
  2321. own attempts are ignoring (#2898).
  2322. **kwargs: Keyword arguments for the operation
  2323. Returns:
  2324. Result of the operation, or None if all attempts fail
  2325. ``UploadCancelled`` is never retried, whatever the caller passes: it means
  2326. the transfer overran its size-derived deadline, so a retry would spend
  2327. another full deadline reaching the same conclusion (#2529).
  2328. ``DownloadDeadlineExceeded`` is the same thing in the other direction
  2329. (#2957) and is treated the same way.
  2330. """
  2331. last_error = None
  2332. attempts_made = 0
  2333. for attempt in range(max_retries + 1):
  2334. attempts_made = attempt + 1
  2335. try:
  2336. result = await operation(*args, **kwargs)
  2337. # Check for "falsy" success indicators
  2338. if result not in (False, None, []):
  2339. if attempt > 0:
  2340. logger.info("%s succeeded on attempt %s/%s", operation_name, attempt + 1, max_retries + 1)
  2341. return result
  2342. # Operation returned failure indicator
  2343. if attempt > 0:
  2344. logger.info("%s attempt %s/%s returned failure", operation_name, attempt + 1, max_retries + 1)
  2345. except (UploadCancelled, DownloadDeadlineExceeded):
  2346. raise
  2347. except Exception as e:
  2348. if non_retry_exceptions and isinstance(e, non_retry_exceptions):
  2349. raise
  2350. last_error = e
  2351. logger.warning("%s attempt %s/%s failed: %s", operation_name, attempt + 1, max_retries + 1, e)
  2352. # Don't wait after the last attempt
  2353. if attempt < max_retries:
  2354. # A cool-off outlasts this loop by two orders of magnitude, so once
  2355. # it is armed every remaining attempt returns False without opening
  2356. # a socket. Spending them anyway bought nothing and cost the caller
  2357. # `max_retries * retry_delay` seconds of sleeping, then reported the
  2358. # failure with the wrong reason (#2898).
  2359. if cooloff_ip and ftps_handshake_blocked(cooloff_ip):
  2360. logger.warning(
  2361. "%s: stopping after attempt %s/%s — %s is inside its FTPS handshake cool-off, "
  2362. "so the remaining attempts would not reach it",
  2363. operation_name,
  2364. attempt + 1,
  2365. max_retries + 1,
  2366. cooloff_ip,
  2367. )
  2368. break
  2369. logger.info("%s will retry in %ss...", operation_name, retry_delay)
  2370. await asyncio.sleep(retry_delay)
  2371. # attempts_made, not max_retries + 1: the loop can stop early on a cool-off,
  2372. # and reporting attempts that were never made is how #2898 read as a network
  2373. # problem when nothing had gone near the network.
  2374. logger.error("%s failed after %s attempts", operation_name, attempts_made)
  2375. if last_error:
  2376. logger.debug("Last error: %s", last_error)
  2377. return None