Skip to content

Fix moved_records not cleaned #1076

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 31 additions & 6 deletions src/watchdog/observers/inotify_c.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import time
import contextlib
import ctypes
import ctypes.util
Expand Down Expand Up @@ -167,7 +168,9 @@ def __init__(self, path: bytes, *, recursive: bool = False, event_mask: int | No
self._add_dir_watch(path, event_mask, recursive=recursive)
else:
self._add_watch(path, event_mask)
self._moved_from_events: dict[int, InotifyEvent] = {}
self._moved_from_events: dict[int, EventPathAndTime] = {}
thread_cleaner = threading.Thread(target=self.clear_move_records_older_than, args=(5,), daemon=True)
thread_cleaner.start()

@property
def event_mask(self) -> int:
Expand All @@ -189,9 +192,18 @@ def fd(self) -> int:
"""The file descriptor associated with the inotify instance."""
return self._inotify_fd

def clear_move_records(self) -> None:
"""Clear cached records of MOVED_FROM events"""
self._moved_from_events = {}
def clear_move_records_older_than(self, delay_sec: int) -> None:
"""Clears cached records of MOVED_FROM events older than delay_sec."""
sleep_max = 10
while True:
if len(self._moved_from_events) != 0:
item =next(iter(self._moved_from_events))
if self._moved_from_events[item].time < (time.time() - delay_sec):
del self._moved_from_events[item]
else:
time.sleep(delay_sec)
else:
time.sleep(sleep_max)

def source_for_move(self, destination_event: InotifyEvent) -> bytes | None:
"""The source path corresponding to the given MOVED_TO event.
Expand All @@ -208,8 +220,9 @@ def remember_move_from_event(self, event: InotifyEvent) -> None:
"""Save this event as the source event for future MOVED_TO events to
reference.
"""
self._moved_from_events[event.cookie] = event

path_and_time = EventPathAndTime(event.src_path)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is a parasite key

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

self._moved_from_events[event.cookie] = EventPathAndTime(event.src_path)
"""like this should be ok
"""

self._moved_from_events[event.cookie] = path_and_time

def add_watch(self, path: bytes) -> None:
"""Adds a watch for the given path.

Expand Down Expand Up @@ -586,3 +599,15 @@ def __repr__(self) -> str:
f" mask={self._get_mask_string(self.mask)}, cookie={self.cookie},"
f" name={os.fsdecode(self.name)!r}>"
)

class EventPathAndTime:
def __init__(self, src_path: bytes) -> None:
self._time = time.time()
self._src_path = src_path

@property
def src_path(self) -> bytes:
return self._src_path
@property
def time(self) -> float:
return self._time
20 changes: 20 additions & 0 deletions tests/threaded/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from __future__ import annotations

import contextlib
import gc
import os
import threading
from functools import partial

import pytest

from tests.utils import ExpectEvent, Helper, P, StartWatching, TestEventQueue


@pytest.fixture(autouse=True)
def _no_thread_leaks():
"""
A fixture override, disables thread counter from parent folder
"""


43 changes: 43 additions & 0 deletions tests/threaded/test_inotify_c.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
from __future__ import annotations

import pytest

from watchdog.utils import platform

if not platform.is_linux():
pytest.skip("GNU/Linux only.", allow_module_level=True)

import ctypes
import errno
import logging
import os
import select
import struct
from typing import TYPE_CHECKING
from unittest.mock import patch

from watchdog.events import DirCreatedEvent, DirDeletedEvent, DirModifiedEvent
from watchdog.observers.inotify_c import Inotify, InotifyConstants, InotifyEvent

if TYPE_CHECKING:
from ..utils import Helper, P, StartWatching, TestEventQueue

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)




def test_watch_file_move(p: P, event_queue: TestEventQueue, start_watching: StartWatching) -> None:
folder = p()
path = p("this_is_a_file")
path_moved = p("this_is_a_file2")
with open(path, "a"):
pass
start_watching(path=folder)
os.rename(path, path_moved)
event, _ = event_queue.get(timeout=5)
assert event.src_path == path
assert event.dest_path == path_moved
assert repr(event)