sample_id
stringlengths
21
196
text
stringlengths
105
936k
metadata
dict
category
stringclasses
6 values
deepspeedai/DeepSpeed:deepspeed/runtime/torch_autocast.py
# Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: Apache-2.0 # DeepSpeed Team from typing import Iterable, Set, List, Union import importlib from contextlib import contextmanager import torch import deepspeed.comm as dist from deepspeed.utils import logger from deepspeed.accelerator import get_accelerator LOWER_PRECISION_SAFE_MODULES = [ torch.nn.Linear, torch.nn.Conv1d, torch.nn.Conv2d, torch.nn.Conv3d, ] PARAM_COMM_DTYPE_ATTR_NAME = "comm_dtype" _WARNED_NESTED_AUTOCAST = False # TODO: Avoid using global variables TORCH_AUTOCAST_INITIALIZED = False TORCH_AUTOCAST_DTYPE = None def _validate_auto_cast_settings(engine): assert not engine.zero_quantized_weights(), "Cannot enable both torch autocast and zero quantized weights" def init_autocast_params(engine, dtype: torch.dtype, torch_autocast_lower_precision_safe_modules: Union[None, List[str]]) -> None: _validate_auto_cast_settings(engine) model = engine.module if torch_autocast_lower_precision_safe_modules is None: lower_precision_safe_module_classes = LOWER_PRECISION_SAFE_MODULES else: lower_precision_safe_module_classes = [] for module_name in torch_autocast_lower_precision_safe_modules: try: package_name, class_name = module_name.rsplit('.', 1) module = importlib.import_module(package_name) class_ = getattr(module, class_name) lower_precision_safe_module_classes.append(class_) except Exception as e: raise ValueError(f"Failed to import lower precision safe module {module_name}: {e}") for module in model.modules(): if module.__class__ in lower_precision_safe_module_classes: for p in module.parameters(recurse=False): setattr(p, PARAM_COMM_DTYPE_ATTR_NAME, dtype) global TORCH_AUTOCAST_INITIALIZED TORCH_AUTOCAST_INITIALIZED = True global TORCH_AUTOCAST_DTYPE TORCH_AUTOCAST_DTYPE = dtype def is_autocast_initialized() -> bool: return TORCH_AUTOCAST_INITIALIZED def get_default_autocast_lower_precision_modules() -> List[str]: return [f"{cls.__module__}.{cls.__name__}" for cls in LOWER_PRECISION_SAFE_MODULES] def get_autocast_dtype() -> torch.dtype: return TORCH_AUTOCAST_DTYPE def has_comm_dtype(param: torch.nn.Parameter) -> bool: return hasattr(param, PARAM_COMM_DTYPE_ATTR_NAME) def get_comm_dtype(param: torch.nn.Parameter) -> torch.dtype: return getattr(param, PARAM_COMM_DTYPE_ATTR_NAME, param.dtype) def get_all_comm_dtypes(params: Iterable) -> Set[torch.dtype]: return {get_comm_dtype(p) for p in params} def sort_dtypes(dtypes: List[torch.dtype]) -> List[torch.dtype]: return sorted(dtypes, key=str) @contextmanager def autocast_if_enabled(engine): """Context manager for DeepSpeed autocast with conditional support. This function manages `torch.autocast` contexts under DeepSpeed, allowing autocast to be enabled or disabled dynamically based on runtime conditions. It ensures consistency when autocast is already active outside of DeepSpeed, or when it is configured within the DeepSpeed engine. Args: engine: DeepSpeed engine instance. """ global _WARNED_NESTED_AUTOCAST if torch.is_autocast_enabled(): if engine.torch_autocast_enabled(): if not _WARNED_NESTED_AUTOCAST: if dist.get_rank() == 0: logger.info( "torch.autocast is already enabled outside DeepSpeed. " "Switching to the configuration defined in `torch_autocast` section of DeepSpeed config.") _WARNED_NESTED_AUTOCAST = True with torch.autocast(device_type=get_accelerator().device_name(), dtype=engine.torch_autocast_dtype(), enabled=True): yield else: if not _WARNED_NESTED_AUTOCAST: if dist.get_rank() == 0: logger.warning( "torch.autocast is enabled outside DeepSpeed but disabled within the DeepSpeed engine. " "If you are using DeepSpeed's built-in mixed precision, the engine will follow the settings in bf16/fp16 section. " "To use torch's native autocast instead, configure the `torch_autocast` section in the DeepSpeed config." ) _WARNED_NESTED_AUTOCAST = True with torch.autocast(device_type=get_accelerator().device_name(), enabled=False): yield else: if engine.torch_autocast_enabled(): with torch.autocast(device_type=get_accelerator().device_name(), dtype=engine.torch_autocast_dtype(), enabled=True): yield else: yield
{ "repo_id": "deepspeedai/DeepSpeed", "file_path": "deepspeed/runtime/torch_autocast.py", "license": "Apache License 2.0", "lines": 103, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
deepspeedai/DeepSpeed:deepspeed/compile/input_storage.py
# Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: Apache-2.0 # DeepSpeed Team from typing import Any, Tuple, Optional from dataclasses import dataclass import torch @dataclass class TensorMetadata: """Metadata for a tensor to be stored in CPU memory""" shape: Tuple[int, ...] dtype: torch.dtype device: torch.device stride: Tuple[int, ...] storage_offset: int requires_grad: bool layout: torch.layout memory_format: torch.memory_format = torch.contiguous_format real_data: Optional[torch.Tensor] = None # Store actual tensor data when configured class InputStorage: """Storage class to keep real inputs in CPU memory with tensor metadata""" def __init__(self, keep_int_input_tensors: bool = False, keep_all_input_tensors: bool = False): self._stored_inputs: Any = None self._has_data: bool = False self._keep_int_input_tensors: bool = keep_int_input_tensors self._keep_all_input_tensors: bool = keep_all_input_tensors def _is_int_tensor(self, tensor: torch.Tensor) -> bool: """Check if tensor has integer dtype""" return tensor.dtype in [ torch.int8, torch.int16, torch.int32, torch.int64, torch.uint8, torch.uint16, torch.uint32, torch.uint64, torch.bool ] def _extract_tensor_metadata(self, tensor: torch.Tensor) -> TensorMetadata: """Extract metadata from a tensor""" # Get memory format safely try: memory_format = tensor.memory_format() if hasattr(tensor, 'memory_format') else torch.contiguous_format except Exception: memory_format = torch.contiguous_format # Store real data for tensors if configured to do so real_data = None if self._keep_all_input_tensors or (self._keep_int_input_tensors and self._is_int_tensor(tensor)): # Move to CPU to save GPU memory real_data = tensor.detach().cpu() return TensorMetadata(shape=tuple(tensor.shape), dtype=tensor.dtype, device=tensor.device, stride=tuple(tensor.stride()), storage_offset=tensor.storage_offset(), requires_grad=tensor.requires_grad, layout=tensor.layout, memory_format=memory_format, real_data=real_data) def _store_value(self, value: Any) -> Any: """ Recursively store a value, converting tensors to metadata and keeping non-tensors as-is """ if isinstance(value, torch.Tensor): return self._extract_tensor_metadata(value) elif isinstance(value, (list, tuple)): stored_items = [self._store_value(item) for item in value] return type(value)(stored_items) if isinstance(value, tuple) else stored_items elif isinstance(value, dict): return {k: self._store_value(v) for k, v in value.items()} else: # For non-tensor values (int, float, str, bool, etc.), store as-is return value def _materialize_value(self, stored_value: Any) -> Any: """ Recursively materialize a stored value, creating tensors from metadata and keeping non-tensors as-is """ if isinstance(stored_value, TensorMetadata): # If we have real data stored, use it if stored_value.real_data is not None: try: # Use the stored real data tensor = stored_value.real_data.clone() # Set stride if different from default and tensor is contiguous if tensor.stride() != stored_value.stride and len(stored_value.shape) > 0: try: # Create tensor with specific stride tensor = torch.as_strided(tensor, stored_value.shape, stored_value.stride, stored_value.storage_offset) except RuntimeError: # If stride setting fails, use default stride pass # Move to target device and set requires_grad tensor = tensor.to(device=stored_value.device) tensor.requires_grad_(stored_value.requires_grad) return tensor except Exception as e: # Fallback to dummy data if real data fails pass # Create a tensor with the stored metadata (original behavior for non-int tensors) # Use CPU first to avoid GPU memory issues, then move to target device try: tensor = torch.empty(stored_value.shape, dtype=stored_value.dtype, layout=stored_value.layout, device='cpu') # Fill with dummy data (ones) for profiling purposes tensor.fill_(1.0) # Set stride if different from default and tensor is contiguous if tensor.stride() != stored_value.stride and len(stored_value.shape) > 0: try: # Create tensor with specific stride tensor = torch.as_strided(tensor, stored_value.shape, stored_value.stride, stored_value.storage_offset) except RuntimeError: # If stride setting fails, use default stride pass # Move to target device and set requires_grad tensor = tensor.to(device=stored_value.device) tensor.requires_grad_(stored_value.requires_grad) return tensor except Exception as e: # Fallback: create a simple tensor if anything fails tensor = torch.ones(stored_value.shape, dtype=stored_value.dtype, device=stored_value.device) tensor.requires_grad_(stored_value.requires_grad) return tensor elif isinstance(stored_value, (list, tuple)): materialized_items = [self._materialize_value(item) for item in stored_value] return type(stored_value)(materialized_items) if isinstance(stored_value, tuple) else materialized_items elif isinstance(stored_value, dict): return {k: self._materialize_value(v) for k, v in stored_value.items()} else: # Non-tensor values are returned as-is return stored_value def put(self, real_inputs: Any) -> None: """ Store real inputs Args: real_inputs: The real inputs to store (can be tensors, lists, tuples, etc.) """ stored_inputs = self._store_value(real_inputs) self._stored_inputs = stored_inputs self._has_data = True def get(self) -> Any: """ Retrieve and materialize stored real inputs Returns: Materialized real inputs with actual tensors Raises: RuntimeError: If no inputs are stored """ if not self._has_data: raise RuntimeError("No inputs stored in InputStorage") return self._materialize_value(self._stored_inputs) def has_data(self) -> bool: """ Check if storage contains inputs Returns: True if inputs are stored, False otherwise """ return self._has_data def clear(self) -> None: """Clear stored inputs""" self._stored_inputs = None self._has_data = False
{ "repo_id": "deepspeedai/DeepSpeed", "file_path": "deepspeed/compile/input_storage.py", "license": "Apache License 2.0", "lines": 158, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
deepspeedai/DeepSpeed:tests/unit/runtime/half_precision/test_zero_optim_overflow.py
# Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: Apache-2.0 # DeepSpeed Team import torch import deepspeed from deepspeed.accelerator import get_accelerator import pytest import numpy as np from unit.common import DistributedTest from unit.simple_model import SimpleModel, random_dataloader from deepspeed.utils import safe_set_full_grad def has_inf_or_nan(x): float_x = x.float() nan = float_x.isnan() inf = float_x.isinf() inf_or_nan = nan.logical_or(inf) return inf_or_nan.float().max() def run_model_step(model, x_sample, y_label, grad_value): loss = model(x_sample, y_label) model.backward(loss) for p in model.parameters(): grad = torch.empty_like(p, dtype=p.dtype) grad.fill_(grad_value) safe_set_full_grad(p, grad) model.step() @pytest.mark.parametrize("zero_stage", [1, 2]) @pytest.mark.parametrize("offload_optimizer", [False, True]) class TestZeROFloat16(DistributedTest): world_size = 2 def test_no_overflow(self, zero_stage, offload_optimizer): if not get_accelerator().is_fp16_supported(): pytest.skip("fp16 is not supported") config_dict = { "train_micro_batch_size_per_gpu": 1, "steps_per_print": 1, "optimizer": { "type": "Adam", "params": { "lr": 0.00015 } }, "fp16": { "enabled": True, "loss_scale": 0, "initial_scale_power": 8, "loss_scale_window": 2 }, "zero_optimization": { "stage": zero_stage } } if offload_optimizer: config_dict["zero_optimization"]["offload_optimizer"] = {"device": "cpu"} hidden_dim = 10 model = SimpleModel(hidden_dim) model, optim, _, _ = deepspeed.initialize(config=config_dict, model=model, model_parameters=model.parameters()) expected_loss_scale = 2**8 expected_scale_window = 2 # Ensure the dynamic loss scaler is correctly configured. loss_scaler = optim.loss_scaler assert optim.dynamic_loss_scale == True assert loss_scaler.cur_scale == expected_loss_scale assert loss_scaler.scale_window == expected_scale_window num_iterations = 10 grad_values = np.random.uniform(-0.1, 0.1, num_iterations) data_loader = random_dataloader(model=model, total_samples=num_iterations, hidden_dim=hidden_dim, device=model.device, dtype=torch.float16) for i, (batch, grad_value) in enumerate(zip(data_loader, grad_values)): run_model_step(model, batch[0], batch[1], grad_value) assert loss_scaler.cur_scale == expected_loss_scale assert loss_scaler.cur_iter == (i + 1) if loss_scaler.cur_iter % expected_scale_window == 0: expected_loss_scale *= 2 def test_all_overflow(self, zero_stage, offload_optimizer): if not get_accelerator().is_fp16_supported(): pytest.skip("fp16 is not supported") overflow_gradients = [float('inf'), float('-inf')] + [float('nan')] * 6 initial_scale_power = len(overflow_gradients) config_dict = { "train_micro_batch_size_per_gpu": 1, "steps_per_print": 1, "optimizer": { "type": "Adam", "params": { "lr": 0.00015 } }, "fp16": { "enabled": True, "loss_scale": 0, "initial_scale_power": initial_scale_power, "loss_scale_window": 2, "hysteresis": 1, }, "zero_optimization": { "stage": zero_stage, } } if offload_optimizer: config_dict["zero_optimization"]["offload_optimizer"] = {"device": "cpu"} hidden_dim = 10 model = SimpleModel(hidden_dim) model, optim, _, _ = deepspeed.initialize(config=config_dict, model=model, model_parameters=model.parameters()) expected_loss_scale = 2**initial_scale_power expected_scale_window = 2 # Ensure the dynamic loss scaler is correctly configured. loss_scaler = optim.loss_scaler assert optim.dynamic_loss_scale == True assert loss_scaler.cur_scale == expected_loss_scale assert loss_scaler.scale_window == expected_scale_window data_loader = random_dataloader(model=model, total_samples=len(overflow_gradients), hidden_dim=hidden_dim, device=model.device, dtype=torch.float16) for i, (batch, grad_value) in enumerate(zip(data_loader, overflow_gradients)): run_model_step(model, batch[0], batch[1], grad_value) expected_loss_scale = max(expected_loss_scale / 2, 1) assert loss_scaler.cur_scale == expected_loss_scale assert loss_scaler.cur_iter == (i + 1) def test_some_overflow(self, zero_stage, offload_optimizer): if not get_accelerator().is_fp16_supported(): pytest.skip("fp16 is not supported") initial_scale_power = 8 config_dict = { "train_micro_batch_size_per_gpu": 1, "steps_per_print": 1, "optimizer": { "type": "Adam", "params": { "lr": 0.00015 } }, "fp16": { "enabled": True, "loss_scale": 0, "initial_scale_power": initial_scale_power, "loss_scale_window": 2, "hysteresis": 1, }, "zero_optimization": { "stage": zero_stage, } } if offload_optimizer: config_dict["zero_optimization"]["offload_optimizer"] = {"device": "cpu"} hidden_dim = 10 model = SimpleModel(hidden_dim) model, optim, _, _ = deepspeed.initialize(config=config_dict, model=model, model_parameters=model.parameters()) expected_loss_scale = 2**initial_scale_power expected_scale_window = 2 # Ensure the dynamic loss scaler is correctly configured. loss_scaler = optim.loss_scaler assert optim.dynamic_loss_scale == True assert loss_scaler.cur_scale == expected_loss_scale assert loss_scaler.scale_window == expected_scale_window expected_iteration = 0 # Run model with overflows to decrease scale overflow_gradients = [float('inf'), float('nan')] expected_iteration += len(overflow_gradients) data_loader = random_dataloader(model=model, total_samples=len(overflow_gradients), hidden_dim=hidden_dim, device=model.device, dtype=torch.float16) for batch, grad_value in zip(data_loader, overflow_gradients): run_model_step(model, batch[0], batch[1], grad_value) expected_loss_scale /= (2**len(overflow_gradients)) assert loss_scaler.cur_scale == expected_loss_scale assert loss_scaler.cur_iter == expected_iteration # Run model scale_window + 1 times to increase scale once normal_gradients = np.random.uniform(-0.1, 0.1, expected_scale_window + 1) expected_iteration += len(normal_gradients) data_loader = random_dataloader(model=model, total_samples=len(normal_gradients), hidden_dim=hidden_dim, device=model.device, dtype=torch.float16) for batch, grad_value in zip(data_loader, normal_gradients): run_model_step(model, batch[0], batch[1], grad_value) expected_loss_scale *= 2 assert loss_scaler.cur_scale == expected_loss_scale assert loss_scaler.cur_iter == expected_iteration # Run model with overflows to decrease scale overflow_gradients = [float('inf')] expected_iteration += len(overflow_gradients) data_loader = random_dataloader(model=model, total_samples=len(overflow_gradients), hidden_dim=hidden_dim, device=model.device, dtype=torch.float16) for batch, grad_value in zip(data_loader, overflow_gradients): run_model_step(model, batch[0], batch[1], grad_value) expected_loss_scale /= (2**len(overflow_gradients)) assert loss_scaler.cur_scale == expected_loss_scale assert loss_scaler.cur_iter == expected_iteration @pytest.mark.parametrize("zero_stage", [1, 2]) @pytest.mark.parametrize("offload_optimizer", [False, True]) class TestZeROBFloat16(DistributedTest): world_size = 2 def test_no_overflow(self, zero_stage, offload_optimizer): if not get_accelerator().is_bf16_supported(): pytest.skip("bf16 is not supported") config_dict = { "train_micro_batch_size_per_gpu": 1, "steps_per_print": 1, "optimizer": { "type": "Adam", "params": { "lr": 0.00015 } }, "bf16": { "enabled": True, }, "zero_optimization": { "stage": zero_stage } } if offload_optimizer: config_dict["zero_optimization"]["offload_optimizer"] = {"device": "cpu"} hidden_dim = 10 model = SimpleModel(hidden_dim) model, optim, _, _ = deepspeed.initialize(config=config_dict, model=model, model_parameters=model.parameters()) num_iterations = 10 grad_values = np.random.uniform(-0.1, 0.1, num_iterations) data_loader = random_dataloader(model=model, total_samples=num_iterations, hidden_dim=hidden_dim, device=model.device, dtype=torch.bfloat16) for i, (batch, grad_value) in enumerate(zip(data_loader, grad_values)): run_model_step(model, batch[0], batch[1], grad_value) assert model.skipped_steps == 0 assert all([not has_inf_or_nan(p) for p in model.parameters()]) def test_detect_grad_overflow(self, zero_stage, offload_optimizer): if not get_accelerator().is_bf16_supported(): pytest.skip("bf16 is not supported") config_dict = { "train_micro_batch_size_per_gpu": 1, "steps_per_print": 1, "optimizer": { "type": "Adam", "params": { "lr": 0.00015 } }, "bf16": { "enabled": True, "check_grad_overflow": True }, "zero_optimization": { "stage": zero_stage, } } if offload_optimizer: config_dict["zero_optimization"]["offload_optimizer"] = {"device": "cpu"} hidden_dim = 10 model = SimpleModel(hidden_dim) model, optim, _, _ = deepspeed.initialize(config=config_dict, model=model, model_parameters=model.parameters()) overflow_gradients = [float('inf'), float('-inf')] + [float('nan')] * 6 data_loader = random_dataloader(model=model, total_samples=len(overflow_gradients), hidden_dim=hidden_dim, device=model.device, dtype=torch.bfloat16) for i, (batch, grad_value) in enumerate(zip(data_loader, overflow_gradients)): run_model_step(model, batch[0], batch[1], grad_value) assert model.skipped_steps == (i + 1) assert all([not has_inf_or_nan(p) for p in model.parameters()]) def test_ignore_grad_overflow(self, zero_stage, offload_optimizer): if not get_accelerator().is_bf16_supported(): pytest.skip("bf16 is not supported") config_dict = { "train_micro_batch_size_per_gpu": 1, "steps_per_print": 1, "optimizer": { "type": "Adam", "params": { "lr": 0.00015 } }, "bf16": { "enabled": True, "check_grad_overflow": False }, "zero_optimization": { "stage": zero_stage, } } if offload_optimizer: config_dict["zero_optimization"]["offload_optimizer"] = {"device": "cpu"} hidden_dim = 10 model = SimpleModel(hidden_dim) model, optim, _, _ = deepspeed.initialize(config=config_dict, model=model, model_parameters=model.parameters()) overflow_gradients = [float('inf'), float('-inf')] + [float('nan')] * 6 data_loader = random_dataloader(model=model, total_samples=len(overflow_gradients), hidden_dim=hidden_dim, device=model.device, dtype=torch.bfloat16) for i, (batch, grad_value) in enumerate(zip(data_loader, overflow_gradients)): run_model_step(model, batch[0], batch[1], grad_value) assert model.skipped_steps == 0 assert all([has_inf_or_nan(p) for p in model.parameters()])
{ "repo_id": "deepspeedai/DeepSpeed", "file_path": "tests/unit/runtime/half_precision/test_zero_optim_overflow.py", "license": "Apache License 2.0", "lines": 308, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
deepspeedai/DeepSpeed:csrc/aio/py_test/ds_aio_constants.py
# Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: Apache-2.0 # DeepSpeed Team AIO_HANDLE = 'aio_handle' AIO_BASIC = 'aio_basic' TORCH_IO = 'torch_io' TORCH_FAST_IO = 'torch_fastio' VALID_ENGINES = [AIO_HANDLE, AIO_BASIC, TORCH_IO, TORCH_FAST_IO] BUFFER = 'buffer' BOUNCE_BUFFER = 'bounce_buffer' NUM_BYTES = 'num_bytes' FILE = 'file' HANDLE = 'handle' ELAPSED_SEC = 'elapsed_sec' FAST_IO_BUFFER = 'fast_io_buffer' USE_CPU_LOCKED_TENSOR = 'cpu_locked_tensor'
{ "repo_id": "deepspeedai/DeepSpeed", "file_path": "csrc/aio/py_test/ds_aio_constants.py", "license": "Apache License 2.0", "lines": 16, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
deepspeedai/DeepSpeed:csrc/aio/py_test/io_engine.py
# Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: Apache-2.0 # DeepSpeed Team import time from multiprocessing import Pool, Barrier from ds_aio_constants import AIO_BASIC, TORCH_FAST_IO, TORCH_IO from test_ds_aio_utils import report_results, task_log, task_barrier from ds_aio_handle import AIOHandle_Engine from ds_aio_basic import AIOBasic_Engine from torch_io import TorchIO_Engine from torch_fastio_engine import Torch_FastIO_Engine def prepare_operation(args, tid, read_op): if args.engine == TORCH_IO: io_engine = TorchIO_Engine(args, tid, read_op) elif args.engine == AIO_BASIC: io_engine = AIOBasic_Engine(args, tid, read_op) elif args.engine == TORCH_FAST_IO: io_engine = Torch_FastIO_Engine(args, tid, read_op) else: io_engine = AIOHandle_Engine(args, tid, read_op) return io_engine def prepare_read(pool_params): args, tid = pool_params return prepare_operation(args, tid, True) def prepare_write(pool_params): args, tid = pool_params return prepare_operation(args, tid, False) def post_operation(pool_params): _, _, io_engine = pool_params io_engine.fini() def read_operation(pool_params): args, tid, loop_id, io_engine = pool_params return io_engine.read(args, tid, loop_id) def write_operation(pool_params): args, tid, loop_id, io_engine = pool_params return io_engine.write(args, tid, loop_id) def get_schedule(args, read_op): schedule = {} if read_op: schedule['pre'] = prepare_read schedule['post'] = post_operation schedule['main'] = read_operation else: schedule['pre'] = prepare_write schedule['post'] = post_operation schedule['main'] = write_operation return schedule def io_engine_tasklet(pool_params): args, tid, read_op = pool_params num_processes = len(args.mapping_dict) # Create schedule schedule = get_schedule(args, read_op) task_log(tid, f'schedule = {schedule}') task_barrier(aio_barrier, num_processes) # Run pre task task_log(tid, 'running pre-task') io_engine = schedule["pre"]((args, tid)) task_barrier(aio_barrier, num_processes) # Run main tasks in a loop io_engine.ctxt["main_task_sec"] = [] for i in range(args.total_loops): task_log(tid, f'running main task {i}') start_time = time.time() schedule["main"]((args, tid, i, io_engine)) task_barrier(aio_barrier, num_processes) stop_time = time.time() io_engine.ctxt["main_task_sec"].append(stop_time - start_time) # Run post task task_log(tid, 'running post-task') schedule["post"]((args, tid, io_engine)) task_barrier(aio_barrier, num_processes) ctxt = io_engine.ctxt # return ctxt["main_task_sec"], ctxt["elapsed_sec"], ctxt["num_bytes"] * args.loops if args.include_warmup_time: e2e_latency_sec = sum(ctxt["main_task_sec"]) task_latency_sec = sum(ctxt["elapsed_sec"]) actual_loops = args.total_loops else: e2e_latency_sec = sum(ctxt["main_task_sec"][args.warmup_loops:]) task_latency_sec = sum(ctxt["elapsed_sec"][args.warmup_loops:]) actual_loops = args.loops l = ctxt["elapsed_sec"] task_log(tid, f'task_latency_sec = {l}') return e2e_latency_sec, task_latency_sec, ctxt["num_bytes"] * actual_loops def _init_takslet(b): global aio_barrier aio_barrier = b def io_engine_multiprocessing(args, read_op): num_processes = len(args.mapping_dict) b = Barrier(num_processes) pool_params = [(args, p, read_op) for p in range(num_processes)] with Pool(processes=num_processes, initializer=_init_takslet, initargs=(b, )) as p: pool_results = p.map(io_engine_tasklet, pool_params) report_results(args, read_op, pool_results)
{ "repo_id": "deepspeedai/DeepSpeed", "file_path": "csrc/aio/py_test/io_engine.py", "license": "Apache License 2.0", "lines": 94, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
deepspeedai/DeepSpeed:csrc/aio/py_test/torch_fastio_engine.py
# Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: Apache-2.0 # DeepSpeed Team import torch import os import time from deepspeed.ops.aio import AsyncIOBuilder from test_ds_aio_utils import task_log, create_filename, create_file, create_page_locked_tensor from ds_aio_constants import * from deepspeed.io import FastFileWriter class Torch_FastIO_Engine(object): def __init__(self, args, tid, read_op): assert read_op is False, 'Read operation is not currently supported' self.ctxt = self._create_context(args, tid, read_op) self.zipfile_serialization = not args.torch_legacy_save def fini(self): if self.ctxt[USE_CPU_LOCKED_TENSOR]: for buf in [BUFFER, FAST_IO_BUFFER]: self.ctxt[HANDLE].free_cpu_locked_tensor(self.ctxt[buf]) self.ctxt[BUFFER].detach() self.ctxt[BUFFER] = None def read(self, args, tid): start_time = time.time() torch.load(f=self.ctxt[FILE], map_location=self.ctxt[BUFFER].device) end_time = time.time() self.ctxt[ELAPSED_SEC] += end_time - start_time def write(self, args, tid): # Avoid overwriting existing files as it could be artificially faster if os.path.isfile(self.ctxt[FILE]): os.remove(self.ctxt[FILE]) ds_file_writer = FastFileWriter(file_path=self.ctxt[FILE], aio_handle=self.ctxt[HANDLE], pinned_tensor=self.ctxt[FAST_IO_BUFFER]) start_time = time.time() torch.save(obj=self.ctxt[BUFFER], f=ds_file_writer, _use_new_zipfile_serialization=self.zipfile_serialization) ds_file_writer.close() # Force flush to storage end_time = time.time() self.ctxt[ELAPSED_SEC] += end_time - start_time ds_file_writer._dump_state() def _create_context(self, args, tid, read_op): io_string = "Read" if read_op else "Write" device_id, folder = args.mapping_list[tid] filename = create_filename(folder, args.read, args.io_size, tid) if args.read and not (os.path.isfile(filename) and os.path.getsize(filename) == args.io_size): create_file(filename, args.io_size) io_parallel = args.io_parallel if args.io_parallel else 1 aio_handle = AsyncIOBuilder().load().aio_handle(args.block_size, args.queue_depth, args.single_submit, not args.sequential_requests, io_parallel) if args.gpu: buffer = torch.randint(high=128, size=(args.io_size, ), dtype=torch.uint8, device=f'cuda:{device_id}') else: buffer = create_page_locked_tensor(args.io_size, args.use_accelerator_pin_memory, aio_handle) task_log(tid, f'Allocate tensor of size {args.io_size} bytes') fast_io_buffer = create_page_locked_tensor(args.fast_io_size, args.use_accelerator_pin_memory, aio_handle) task_log(tid, 'created torch_fastio engine') ctxt = {} ctxt[FILE] = filename ctxt[NUM_BYTES] = args.io_size ctxt[BUFFER] = buffer ctxt[HANDLE] = aio_handle ctxt[FAST_IO_BUFFER] = fast_io_buffer ctxt[ELAPSED_SEC] = 0 ctxt[USE_CPU_LOCKED_TENSOR] = not args.use_accelerator_pin_memory task_log(tid, f'{io_string} file {filename} of size {args.io_size} bytes from buffer on device {buffer.device}', force=True) return ctxt
{ "repo_id": "deepspeedai/DeepSpeed", "file_path": "csrc/aio/py_test/torch_fastio_engine.py", "license": "Apache License 2.0", "lines": 67, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
deepspeedai/DeepSpeed:csrc/aio/py_test/torch_io.py
# Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: Apache-2.0 # DeepSpeed Team import torch import os import time from test_ds_aio_utils import task_log, create_filename, create_file, create_page_locked_tensor from ds_aio_constants import * class TorchIO_Engine(object): def __init__(self, args, tid, read_op): self.ctxt = self._create_context(args, tid, read_op) self.zipfile_serialization = not args.torch_legacy_save def fini(self): self.ctxt[BUFFER].detach() self.ctxt[BUFFER] = None def read(self, args, tid): start_time = time.time() torch.load(f=self.ctxt[FILE], map_location=self.ctxt[BUFFER].device) end_time = time.time() self.ctxt[ELAPSED_SEC] += end_time - start_time def write(self, args, tid): # Avoid overwriting existing files as it could be artificially faster if os.path.isfile(self.ctxt[FILE]): os.remove(self.ctxt[FILE]) start_time = time.time() torch.save(obj=self.ctxt[BUFFER], f=self.ctxt[FILE], _use_new_zipfile_serialization=self.zipfile_serialization) end_time = time.time() self.ctxt[ELAPSED_SEC] += end_time - start_time def _create_context(self, args, tid, read_op): io_string = "Read" if read_op else "Write" device_id, folder = args.mapping_list[tid] filename = create_filename(folder, args.read, args.io_size, tid) if args.read and not (os.path.isfile(filename) and os.path.getsize(filename) == args.io_size): create_file(filename, args.io_size) task_log(tid, f'Allocate tensor of size {args.io_size} bytes') if args.gpu: buffer = torch.randint(high=128, size=(args.io_size, ), dtype=torch.uint8, device=f'cuda:{device_id}') else: buffer = create_page_locked_tensor(args.io_size, True) task_log(tid, f'{io_string} file {filename} of size {args.io_size} bytes from buffer on device {buffer.device}', force=True) task_log(tid, 'created torch_io engine') ctxt = {} ctxt[FILE] = filename ctxt[NUM_BYTES] = args.io_size ctxt[BUFFER] = buffer ctxt[ELAPSED_SEC] = 0 return ctxt
{ "repo_id": "deepspeedai/DeepSpeed", "file_path": "csrc/aio/py_test/torch_io.py", "license": "Apache License 2.0", "lines": 49, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
deepspeedai/DeepSpeed:deepspeed/io/base_file_writer.py
# Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: Apache-2.0 # DeepSpeed Team from .constants import * BASE_STAT_KEYS = [ CLOSE_COUNT_KEY, FILENO_COUNT_KEY, FLUSH_COUNT_KEY, WRITE_COUNT_KEY, WRITE_BYTES_KEY, WRITE_SEC_KEY, WRITE_SPEED_KEY ] class BaseFileWriter(object): def __init__(self, file_path): self._file_path = file_path self._stats = {k: 0 for k in BASE_STAT_KEYS} def close(self): pass def fileno(self): pass def flush(self): pass def write(self, buffer): pass def file_path(self): return self._file_path def _incr_stats(self, key, incr=1): self._stats[key] += incr def _dump_state(self): if self._stats[WRITE_SEC_KEY] > 0: self._stats[WRITE_SPEED_KEY] = (self._stats[WRITE_BYTES_KEY] / self._stats[WRITE_SEC_KEY] / (1024**3)) state = self._stats state[FILE_PATH_KEY] = self.file_path() print(f'stats = {self._stats}')
{ "repo_id": "deepspeedai/DeepSpeed", "file_path": "deepspeed/io/base_file_writer.py", "license": "Apache License 2.0", "lines": 30, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
deepspeedai/DeepSpeed:deepspeed/io/base_io_buffer.py
# Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: Apache-2.0 # DeepSpeed Team import torch class Base_IO_Buffer(object): def __init__(self, pinned_tensor, dnvme_handle): assert pinned_tensor.numel() % dnvme_handle.get_alignment() == 0 self._dnvme_handle = dnvme_handle self._pinned_tensor = pinned_tensor def fill(self, src_tensor, src_offset): pass def drain(self, num_bytes, fd, file_offset): pass def is_empty(self): pass def is_full(self): pass def get_buffer(self): pass def get_offset(self): pass def get_aligned_num_bytes(self): pass def get_unaligned_num_bytes(self): pass def reset(self): pass def complete_ongoing_drain(self): pass def _drain(self, num_bytes, fd, file_offset, blocking=False): assert num_bytes <= self.get_offset() assert num_bytes % self._dnvme_handle.get_alignment() == 0 buffer = self.get_buffer() r = self._dnvme_handle.async_pwrite(torch.narrow(buffer, 0, 0, num_bytes), fd, file_offset) assert 0 == r if blocking: assert 1 == self._dnvme_handle.wait() @staticmethod def fill_buffer(src_tensor, src_offset, buffer_tensor, buffer_offset): src_bytes = src_tensor.numel() - src_offset assert src_bytes > 0 dst_bytes = buffer_tensor.numel() - buffer_offset copy_bytes = min(src_bytes, dst_bytes) assert (buffer_offset + copy_bytes) <= buffer_tensor.numel() if copy_bytes > 0: src_slice = torch.narrow(src_tensor, 0, src_offset, copy_bytes) dst_slice = torch.narrow(buffer_tensor, 0, buffer_offset, copy_bytes) dst_slice.data.copy_(src_slice.data) return copy_bytes
{ "repo_id": "deepspeedai/DeepSpeed", "file_path": "deepspeed/io/base_io_buffer.py", "license": "Apache License 2.0", "lines": 49, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
deepspeedai/DeepSpeed:deepspeed/io/constants.py
# Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: Apache-2.0 # DeepSpeed Team INVALID_FD = -1 FILE_PATH_KEY = 'path' FLUSH_COUNT_KEY = 'flush' WRITE_COUNT_KEY = 'write' CLOSE_COUNT_KEY = 'close' FILENO_COUNT_KEY = 'fileno' WRITE_BYTES_KEY = 'bytes' WRITE_SEC_KEY = 'write_secs' WRITE_SPEED_KEY = 'write_GB/s' AIO_WRITE_SEC_KEY = 'aio_write_secs' AIO_WRITE_BYTES_KEY = 'aio_bytes' AIO_SPEED_KEY = 'aio_GB/s' SLOW_WRITE_BYTES_KEY = 'slow_bytes' SLOW_WRITE_SEC_KEY = 'slow_write_secs' AIO_FILL_BUFFER_SEC_KEY = 'fill_buffer_secs' AIO_FILL_BUFFER_COUNT_KEY = 'fill_buffer_count' AIO_FILL_BUFFER_SPEED_KEY = 'fill_buffer_GB/s' SAVE_STORAGE_KEY = 'save_storage' SAVE_STORAGE_BYTES_KEY = 'save_storage_bytes' SAVE_STORAGE_SEC_KEY = 'save_storage_secs' STORAGE_OBJ_SIZE = 8 RANK_KEY = 'rank'
{ "repo_id": "deepspeedai/DeepSpeed", "file_path": "deepspeed/io/constants.py", "license": "Apache License 2.0", "lines": 25, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
deepspeedai/DeepSpeed:deepspeed/io/double_io_buffer.py
# Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: Apache-2.0 # DeepSpeed Team import torch from .base_io_buffer import Base_IO_Buffer NUM_BUFFERS = 2 INVALID_BUFFER_INDEX = -1 class Double_IO_Buffer(Base_IO_Buffer): def __init__(self, pinned_tensor, dnvme_handle): super(Double_IO_Buffer, self).__init__(pinned_tensor, dnvme_handle) assert self._pinned_tensor.numel() % (NUM_BUFFERS * self._dnvme_handle.get_alignment()) == 0 self._buffers = self._split_buffer() self._fill_index = 0 self._drain_index = INVALID_BUFFER_INDEX self._buffer_offset = 0 def fill(self, src_tensor, src_offset): self._validate_buffer_index(self._fill_index) copy_bytes = Base_IO_Buffer.fill_buffer(src_tensor, src_offset, self._buffers[self._fill_index], self._buffer_offset) self._buffer_offset += copy_bytes return copy_bytes def drain(self, num_bytes, fd, file_offset): self._validate_buffer_index(self._fill_index) self.complete_ongoing_drain() assert self._drain_index == INVALID_BUFFER_INDEX self._drain(num_bytes, fd, file_offset, blocking=False) self._drain_index = self._fill_index self._fill_index = (self._fill_index + 1) % NUM_BUFFERS self._buffer_offset = 0 def get_buffer(self): self._validate_buffer_index(self._fill_index) return self._buffers[self._fill_index] def get_offset(self): self._validate_buffer_index(self._fill_index) return self._buffer_offset def get_aligned_num_bytes(self): self._validate_buffer_index(self._fill_index) aligned_size = self._dnvme_handle.get_alignment() return (self._buffer_offset // aligned_size) * aligned_size def get_unaligned_num_bytes(self): self._validate_buffer_index(self._fill_index) return self._buffer_offset % self._dnvme_handle.get_alignment() def is_full(self): self._validate_buffer_index(self._fill_index) return self._buffer_offset == self._buffers[self._fill_index].numel() def is_empty(self): self._validate_buffer_index(self._fill_index) return self._buffer_offset == 0 and not self._is_ongoing_drain() def reset(self): self._buffer_offset = 0 def complete_ongoing_drain(self): if self._is_ongoing_drain(): self._wait_for_drain() def _split_buffer(self): buffer_size = self._pinned_tensor.numel() // NUM_BUFFERS return [torch.narrow(self._pinned_tensor, 0, (i * buffer_size), buffer_size) for i in range(NUM_BUFFERS)] def _validate_buffer_index(self, index): assert index in [0, 1] def _wait_for_drain(self): self._validate_buffer_index(self._drain_index) assert 1 == self._dnvme_handle.wait() self._drain_index = INVALID_BUFFER_INDEX def _is_ongoing_drain(self): return self._drain_index != INVALID_BUFFER_INDEX
{ "repo_id": "deepspeedai/DeepSpeed", "file_path": "deepspeed/io/double_io_buffer.py", "license": "Apache License 2.0", "lines": 64, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
deepspeedai/DeepSpeed:deepspeed/io/fast_file_writer.py
# Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: Apache-2.0 # DeepSpeed Team import os import torch import time from dataclasses import dataclass from .constants import * from .base_file_writer import BaseFileWriter from .single_io_buffer import Single_IO_Buffer from .double_io_buffer import Double_IO_Buffer from deepspeed.ops.op_builder import UtilsBuilder from deepspeed.accelerator import get_accelerator from .utils import (tensor_to_bytes, bytes_to_tensor, obj_serialization_details) FASTIO_STAT_KEYS = [ AIO_WRITE_SEC_KEY, AIO_WRITE_BYTES_KEY, AIO_SPEED_KEY, SLOW_WRITE_BYTES_KEY, SLOW_WRITE_SEC_KEY, AIO_FILL_BUFFER_COUNT_KEY, AIO_FILL_BUFFER_SEC_KEY, AIO_FILL_BUFFER_SPEED_KEY, SAVE_STORAGE_KEY, SAVE_STORAGE_BYTES_KEY, ] @dataclass class FastFileWriterConfig: dnvme_handle: object pinned_tensor: torch.Tensor double_buffer: bool = True num_parallel_writers: int = 1 writer_rank: int = 0 global_rank: int = 0 class FastFileWriter(BaseFileWriter): def __init__(self, file_path, config): super(FastFileWriter, self).__init__(file_path) self._aio_fd = os.open(self._file_path, flags=os.O_DIRECT | os.O_CREAT | os.O_WRONLY) self._dnvme_handle = config.dnvme_handle self._file_offset = 0 io_buffer_type = Double_IO_Buffer if config.double_buffer else Single_IO_Buffer self._io_buffer = io_buffer_type(config.pinned_tensor, self._dnvme_handle) self._cast_to_byte_tensor = UtilsBuilder().load().cast_to_byte_tensor self._get_serialization_details = obj_serialization_details() self._num_parallel_writers = config.num_parallel_writers self._writer_rank = config.writer_rank self._global_rank = config.global_rank for k in FASTIO_STAT_KEYS: self._stats[k] = 0 def write(self, buffer): assert self._file_offset % self._dnvme_handle.get_alignment() == 0 buffer_num_bytes = len(buffer) num_written_bytes = self._write_from_tensor(bytes_to_tensor(buffer)) assert buffer_num_bytes == num_written_bytes return buffer_num_bytes def split_index_list(self, storage_obj_list, num_splits): assert num_splits > 0 split_list = [-1] * num_splits # t[0] is data, t[1] is data_type tensor_bytes_list = [len(t[0]) for t in storage_obj_list] print(tensor_bytes_list) total_bytes = sum(tensor_bytes_list) bytes_per_group = total_bytes / num_splits split_counter = 0 tmp_size = 0 for i in range(len(tensor_bytes_list)): tmp_size += tensor_bytes_list[i] if tmp_size > bytes_per_group: split_list[split_counter] = i tmp_size = 0 split_counter += 1 if split_list[num_splits - 1] == -1: split_list[num_splits - 1] = len(tensor_bytes_list) return split_list def save_torch_storage_object_list(self, storage_obj_list, save_size): assert self._file_offset % self._dnvme_handle.get_alignment() == 0 num_bytes_written = self._save_storage_list(storage_obj_list, save_size) return num_bytes_written def close(self): self._fini() self._incr_stats(CLOSE_COUNT_KEY) def fileno(self): self._incr_stats(FILENO_COUNT_KEY) return INVALID_FD # self._aio_fd def flush(self): self._incr_stats(FLUSH_COUNT_KEY) def __del__(self): self._fini() assert self._aio_fd == INVALID_FD assert self._io_buffer.get_offset() == 0, \ f'__del__ assert: pinned_offset {self._io_buffer.get_offset()} != 0' assert self._file_offset == self._stats[WRITE_BYTES_KEY], \ f'__del__ assert: file_offset != write_bytes - {self._file_offset} != {self._stats[WRITE_BYTES_KEY]}' def _fini(self): if not self._io_buffer_is_empty(): self._force_drain() self._io_buffer.reset() self._aio_fd = INVALID_FD def _fill_io_buffer(self, src_tensor, src_offset): st = time.time() copy_bytes = self._io_buffer.fill(src_tensor, src_offset) self._incr_stats(AIO_FILL_BUFFER_SEC_KEY, time.time() - st) self._incr_stats(AIO_FILL_BUFFER_COUNT_KEY) return copy_bytes def _drain_io_buffer(self, num_bytes): st = time.time() self._io_buffer.drain(num_bytes, self._aio_fd, self._file_offset) self._incr_stats(AIO_WRITE_SEC_KEY, time.time() - st) self._incr_stats(AIO_WRITE_BYTES_KEY, num_bytes) self._file_offset += num_bytes def _io_buffer_is_full(self): return self._io_buffer.is_full() def _io_buffer_is_empty(self): return self._io_buffer.is_empty() def _force_drain(self): st = time.time() aligned_num_bytes = self._io_buffer.get_aligned_num_bytes() # Important to retrieve unaligned drain bytes and tensor before doing aligned drain because of the side effects. # TODO: Need to eliminate this dependency unaligned_num_bytes = self._io_buffer.get_unaligned_num_bytes() unaligned_tensor = torch.narrow(self._io_buffer.get_buffer(), 0, aligned_num_bytes, unaligned_num_bytes) if aligned_num_bytes > 0: self._drain_io_buffer(aligned_num_bytes) self._io_buffer.complete_ongoing_drain() self._incr_stats(AIO_WRITE_SEC_KEY, time.time() - st) if unaligned_num_bytes > 0: self._unaligned_drain(unaligned_tensor) self._incr_stats(WRITE_SEC_KEY, time.time() - st) def _unaligned_drain(self, unaligned_tensor): os.close(self._aio_fd) st = time.time() fp = open(self._file_path, 'ab') fp.write(tensor_to_bytes(unaligned_tensor.cpu())) fp.close() self._file_offset += unaligned_tensor.numel() self._incr_stats(SLOW_WRITE_SEC_KEY, time.time() - st) self._incr_stats(SLOW_WRITE_BYTES_KEY, unaligned_tensor.numel()) self._aio_fd = os.open(self._file_path, flags=os.O_DIRECT | os.O_WRONLY | os.O_APPEND) def _dump_state(self): if self._stats[AIO_WRITE_SEC_KEY] > 0: self._stats[AIO_SPEED_KEY] = (self._stats[AIO_WRITE_BYTES_KEY] / self._stats[AIO_WRITE_SEC_KEY] / (1024**3)) if self._stats[AIO_FILL_BUFFER_SEC_KEY] > 0: self._stats[AIO_FILL_BUFFER_SPEED_KEY] = (self._stats[AIO_WRITE_BYTES_KEY] / self._stats[AIO_FILL_BUFFER_SEC_KEY] / (1024**3)) super()._dump_state() def _update_write_stats(self, num_bytes, secs_latency): self._incr_stats(WRITE_COUNT_KEY) self._incr_stats(WRITE_BYTES_KEY, num_bytes) self._incr_stats(WRITE_SEC_KEY, secs_latency) def _write_from_tensor(self, buffer_tensor): st = time.time() buffer_offset = 0 while (buffer_offset < buffer_tensor.numel()): num_copied_bytes = self._fill_io_buffer(buffer_tensor, buffer_offset) if self._io_buffer_is_full(): self._drain_io_buffer(self._io_buffer.get_offset()) buffer_offset += num_copied_bytes self._update_write_stats(buffer_offset, time.time() - st) return buffer_offset def _save_storage_list(self, obj_list, save_size): byte_tensor_list, byte_tensor_nbytes = self._convert_to_byte_tensors(obj_list, save_size) if self._num_parallel_writers > 1: my_byte_tensor_list = self._partition_byte_tensors(byte_tensor_list, byte_tensor_nbytes, self._num_parallel_writers, self._writer_rank) else: my_byte_tensor_list = byte_tensor_list num_object_bytes_written = 0 for byte_tensor in my_byte_tensor_list: num_object_bytes_written += self._write_from_tensor(byte_tensor) self._incr_stats(SAVE_STORAGE_KEY, len(obj_list)) self._incr_stats(SAVE_STORAGE_BYTES_KEY, num_object_bytes_written) return num_object_bytes_written # Convert list of storage objects into list of byte tensors of object and size bytes def _convert_to_byte_tensors(self, obj_list, save_size): tensor_list = [] num_bytes = 0 for storage_obj in obj_list: details = self._get_serialization_details(storage_obj) if save_size: tensor_list.append( torch.tensor( details.size, dtype=torch.int64, ).to(get_accelerator().device_name())) tensor_list.append(torch.empty(0, dtype=details.dtype, device=details.obj.device).set_(details.obj)) num_bytes += details.nbytes if save_size: num_bytes += STORAGE_OBJ_SIZE * len(obj_list) return self._cast_to_byte_tensor(tensor_list), num_bytes def _partition_byte_tensors(self, byte_tensor_list, byte_tensor_nbytes, num_ranks, my_rank): assert my_rank >= 0, f'Invalid for rank number to be negative: {my_rank}' assert num_ranks > my_rank, f'Number of ranks {num_ranks} must be greater than rank {my_rank}' partition_size = int(byte_tensor_nbytes // num_ranks) num_remainder_bytes = byte_tensor_nbytes % num_ranks if num_remainder_bytes == 0: partition_start = partition_size * my_rank else: # Spread extra bytes evenly among early ranks if num_remainder_bytes > my_rank: partition_size += 1 partition_start = partition_size * my_rank else: # Account for allocation of extra bytes to earlier ranks partition_start = (partition_size * my_rank) + num_remainder_bytes partition_end = min(partition_start + partition_size, byte_tensor_nbytes) partition_tensor_list = [] current_offset = 0 for byte_tensor in byte_tensor_list: byte_tensor_end = current_offset + byte_tensor.numel() if current_offset < partition_end and byte_tensor_end > partition_start: fragment_start = max(current_offset, partition_start) fragment_end = min(byte_tensor_end, partition_end) assert fragment_start < fragment_end, \ f'fragment start {fragment_start} should be < fragment_end {fragment_end}' fragment_numel = fragment_end - fragment_start partition_tensor_list.append(byte_tensor.narrow(0, fragment_start - current_offset, fragment_numel)) current_offset += byte_tensor.numel() actual_partition_nbytes = sum([t.numel() for t in partition_tensor_list]) assert actual_partition_nbytes == partition_size, \ f'Incorrect partition bytes for rank {my_rank}, expected = {partition_size} actual = {actual_partition_nbytes}' return partition_tensor_list
{ "repo_id": "deepspeedai/DeepSpeed", "file_path": "deepspeed/io/fast_file_writer.py", "license": "Apache License 2.0", "lines": 222, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
deepspeedai/DeepSpeed:deepspeed/io/mock_file_writer.py
# Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: Apache-2.0 # DeepSpeed Team from .constants import * from .base_file_writer import BaseFileWriter from .utils import obj_serialization_details class MockFileWriter(BaseFileWriter): def __init__(self, file_path): super(MockFileWriter, self).__init__(file_path) self._fp = open(file_path, 'wb') self._stats[SAVE_STORAGE_KEY] = 0 self._stats[SAVE_STORAGE_BYTES_KEY] = 0 self._get_serialization_details = obj_serialization_details() def close(self): self._incr_stats(CLOSE_COUNT_KEY) self._fp.close() def fileno(self): self._incr_stats(FILENO_COUNT_KEY) return INVALID_FD # self._fp.fileno() def flush(self): self._incr_stats(FLUSH_COUNT_KEY) self._fp.flush() def write(self, buffer): return self._write(len(buffer)) def save_torch_storage_object_list(self, storage_obj_list, save_size): num_bytes = sum([self._save_torch_storage_object(obj, save_size) for obj in storage_obj_list]) return num_bytes def _save_torch_storage_object(self, storage_obj, save_size): details = self._get_serialization_details(storage_obj) self._incr_stats(SAVE_STORAGE_KEY) self._incr_stats(SAVE_STORAGE_BYTES_KEY, details.size) num_written_bytes = self._write(STORAGE_OBJ_SIZE) if save_size else 0 return num_written_bytes + self._write(details.size) def _write(self, num_bytes): self._incr_stats(WRITE_COUNT_KEY) self._incr_stats(WRITE_BYTES_KEY, num_bytes) return num_bytes
{ "repo_id": "deepspeedai/DeepSpeed", "file_path": "deepspeed/io/mock_file_writer.py", "license": "Apache License 2.0", "lines": 37, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
deepspeedai/DeepSpeed:deepspeed/io/py_file_writer.py
# Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: Apache-2.0 # DeepSpeed Team import time from .constants import * from .base_file_writer import BaseFileWriter class PyFileWriter(BaseFileWriter): def __init__(self, file_path): super(PyFileWriter, self).__init__(file_path) self._fp = open(file_path, 'wb') def close(self): self._incr_stats(CLOSE_COUNT_KEY) self._fp.close() def fileno(self): self._incr_stats(FILENO_COUNT_KEY) return INVALID_FD # self._fp.fileno() def flush(self): self._incr_stats(FLUSH_COUNT_KEY) self._fp.flush() def write(self, buffer): st = time.time() self._fp.write(buffer) self._incr_stats(WRITE_SEC_KEY, time.time() - st) self._incr_stats(WRITE_COUNT_KEY) self._incr_stats(WRITE_BYTES_KEY, len(buffer)) return len(buffer)
{ "repo_id": "deepspeedai/DeepSpeed", "file_path": "deepspeed/io/py_file_writer.py", "license": "Apache License 2.0", "lines": 26, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
deepspeedai/DeepSpeed:deepspeed/io/single_io_buffer.py
# Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: Apache-2.0 # DeepSpeed Team from .base_io_buffer import Base_IO_Buffer class Single_IO_Buffer(Base_IO_Buffer): def __init__(self, pinned_tensor, dnvme_handle): super(Single_IO_Buffer, self).__init__(pinned_tensor, dnvme_handle) self._pinned_offset = 0 def fill(self, src_tensor, src_offset): copy_bytes = Base_IO_Buffer.fill_buffer(src_tensor, src_offset, self._pinned_tensor, self._pinned_offset) self._pinned_offset += copy_bytes return copy_bytes def drain(self, num_bytes, fd, file_offset): self._drain(num_bytes, fd, file_offset, blocking=True) self._pinned_offset = 0 def get_buffer(self): return self._pinned_tensor def get_offset(self): return self._pinned_offset def get_aligned_num_bytes(self): aligned_size = self._dnvme_handle.get_alignment() return (self._pinned_offset // aligned_size) * aligned_size def get_unaligned_num_bytes(self): return self._pinned_offset % self._dnvme_handle.get_alignment() def is_full(self): return self._pinned_offset == self._pinned_tensor.numel() def is_empty(self): return self._pinned_offset == 0 def reset(self): self._pinned_offset = 0
{ "repo_id": "deepspeedai/DeepSpeed", "file_path": "deepspeed/io/single_io_buffer.py", "license": "Apache License 2.0", "lines": 30, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
deepspeedai/DeepSpeed:deepspeed/io/utils.py
# Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: Apache-2.0 # DeepSpeed Team import numpy import torch from dataclasses import dataclass @dataclass class serialize_details: obj: object dtype: torch.dtype size: int nbytes: int def tensor_to_bytes(tensor): return tensor.numpy().tobytes() def bytes_to_tensor(buffer): return torch.from_numpy(numpy.array(numpy.frombuffer(buffer, dtype=numpy.uint8))) def required_minimum_torch_version(major_version, minor_version): TORCH_MAJOR = int(torch.__version__.split('.')[0]) TORCH_MINOR = int(torch.__version__.split('.')[1]) if TORCH_MAJOR < major_version: return False return TORCH_MAJOR > major_version or TORCH_MINOR >= minor_version # torch < 1.12 def _legacy_obj_serialization_details(storage_obj): nbytes = storage_obj.element_size() * storage_obj.size() return serialize_details(obj=storage_obj, dtype=storage_obj.dtype, size=nbytes, nbytes=nbytes) # torch >= 1.12 def _new_obj_serialization_details(storage_obj): obj, dtype = storage_obj return serialize_details(obj=obj, dtype=dtype, size=obj.size() // torch._utils._element_size(dtype), nbytes=obj.size()) def obj_serialization_details(): if required_minimum_torch_version(1, 12): return _new_obj_serialization_details return _legacy_obj_serialization_details
{ "repo_id": "deepspeedai/DeepSpeed", "file_path": "deepspeed/io/utils.py", "license": "Apache License 2.0", "lines": 37, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
deepspeedai/DeepSpeed:deepspeed/nvme/ds_aio_constants.py
# Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: Apache-2.0 # DeepSpeed Team AIO_HANDLE = 'aio_handle' AIO_BASIC = 'aio_basic' TORCH_IO = 'torch_io' TORCH_FAST_IO = 'torch_fastio' VALID_ENGINES = [AIO_HANDLE, AIO_BASIC, TORCH_IO, TORCH_FAST_IO] BUFFER = 'buffer' BOUNCE_BUFFER = 'bounce_buffer' NUM_BYTES = 'num_bytes' FILE = 'file' HANDLE = 'handle' ELAPSED_SEC = 'elapsed_sec' FAST_IO_BUFFER = 'fast_io_buffer' USE_CPU_LOCKED_TENSOR = 'cpu_locked_tensor' USE_GDS = 'gds'
{ "repo_id": "deepspeedai/DeepSpeed", "file_path": "deepspeed/nvme/ds_aio_constants.py", "license": "Apache License 2.0", "lines": 17, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
deepspeedai/DeepSpeed:deepspeed/nvme/io_engine.py
# Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: Apache-2.0 # DeepSpeed Team import time from multiprocessing import Pool, Barrier from .ds_aio_constants import AIO_BASIC, TORCH_FAST_IO, TORCH_IO from .test_ds_aio_utils import report_results, task_log, task_barrier from .ds_aio_handle import AIOHandle_Engine from .ds_aio_basic import AIOBasic_Engine from .torch_io import TorchIO_Engine from .torch_fastio_engine import Torch_FastIO_Engine def prepare_operation(args, tid, read_op): if args.engine == TORCH_IO: io_engine = TorchIO_Engine(args, tid, read_op) elif args.engine == AIO_BASIC: io_engine = AIOBasic_Engine(args, tid, read_op) elif args.engine == TORCH_FAST_IO: io_engine = Torch_FastIO_Engine(args, tid, read_op) else: io_engine = AIOHandle_Engine(args, tid, read_op) return io_engine def prepare_read(pool_params): args, tid = pool_params return prepare_operation(args, tid, True) def prepare_write(pool_params): args, tid = pool_params return prepare_operation(args, tid, False) def post_operation(pool_params): _, _, io_engine = pool_params io_engine.fini() def read_operation(pool_params): args, tid, loop_id, io_engine = pool_params return io_engine.read(args, tid, loop_id) def write_operation(pool_params): args, tid, loop_id, io_engine = pool_params return io_engine.write(args, tid, loop_id) def get_schedule(args, read_op): schedule = {} if read_op: schedule['pre'] = prepare_read schedule['post'] = post_operation schedule['main'] = read_operation else: schedule['pre'] = prepare_write schedule['post'] = post_operation schedule['main'] = write_operation return schedule def io_engine_tasklet(pool_params): args, tid, read_op = pool_params num_processes = len(args.mapping_dict) # Create schedule schedule = get_schedule(args, read_op) task_log(tid, f'schedule = {schedule}') task_barrier(aio_barrier, num_processes) # Run pre task task_log(tid, 'running pre-task') io_engine = schedule["pre"]((args, tid)) task_barrier(aio_barrier, num_processes) # Run main tasks in a loop io_engine.ctxt["main_task_sec"] = [] for i in range(args.total_loops): task_log(tid, f'running main task {i}') start_time = time.time() schedule["main"]((args, tid, i, io_engine)) task_barrier(aio_barrier, num_processes) stop_time = time.time() io_engine.ctxt["main_task_sec"].append(stop_time - start_time) # Run post task task_log(tid, 'running post-task') schedule["post"]((args, tid, io_engine)) task_barrier(aio_barrier, num_processes) ctxt = io_engine.ctxt # return ctxt["main_task_sec"], ctxt["elapsed_sec"], ctxt["num_bytes"] * args.loops if args.include_warmup_time: e2e_latency_sec = sum(ctxt["main_task_sec"]) task_latency_sec = sum(ctxt["elapsed_sec"]) actual_loops = args.total_loops else: e2e_latency_sec = sum(ctxt["main_task_sec"][args.warmup_loops:]) task_latency_sec = sum(ctxt["elapsed_sec"][args.warmup_loops:]) actual_loops = args.loops l = ctxt["elapsed_sec"] task_log(tid, f'task_latency_sec = {l}') return e2e_latency_sec, task_latency_sec, ctxt["num_bytes"] * actual_loops def _init_takslet(b): global aio_barrier aio_barrier = b def io_engine_multiprocessing(args, read_op): num_processes = len(args.mapping_dict) b = Barrier(num_processes) pool_params = [(args, p, read_op) for p in range(num_processes)] with Pool(processes=num_processes, initializer=_init_takslet, initargs=(b, )) as p: pool_results = p.map(io_engine_tasklet, pool_params) report_results(args, read_op, pool_results)
{ "repo_id": "deepspeedai/DeepSpeed", "file_path": "deepspeed/nvme/io_engine.py", "license": "Apache License 2.0", "lines": 94, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
deepspeedai/DeepSpeed:deepspeed/nvme/torch_fastio_engine.py
# Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: Apache-2.0 # DeepSpeed Team import torch import os import time from deepspeed.ops.aio import AsyncIOBuilder from .test_ds_aio_utils import task_log, create_filename, create_file, create_page_locked_tensor from .ds_aio_constants import * from deepspeed.io import FastFileWriter class Torch_FastIO_Engine(object): def __init__(self, args, tid, read_op): assert read_op is False, 'Read operation is not currently supported' self.ctxt = self._create_context(args, tid, read_op) self.zipfile_serialization = not args.torch_legacy_save def fini(self): if self.ctxt[USE_CPU_LOCKED_TENSOR]: for buf in [BUFFER, FAST_IO_BUFFER]: self.ctxt[HANDLE].free_cpu_locked_tensor(self.ctxt[buf]) self.ctxt[BUFFER].detach() self.ctxt[BUFFER] = None def read(self, args, tid): start_time = time.time() torch.load(f=self.ctxt[FILE], map_location=self.ctxt[BUFFER].device) end_time = time.time() self.ctxt[ELAPSED_SEC] += end_time - start_time def write(self, args, tid): # Avoid overwriting existing files as it could be artificially faster if os.path.isfile(self.ctxt[FILE]): os.remove(self.ctxt[FILE]) ds_file_writer = FastFileWriter(file_path=self.ctxt[FILE], aio_handle=self.ctxt[HANDLE], pinned_tensor=self.ctxt[FAST_IO_BUFFER]) start_time = time.time() torch.save(obj=self.ctxt[BUFFER], f=ds_file_writer, _use_new_zipfile_serialization=self.zipfile_serialization) ds_file_writer.close() # Force flush to storage end_time = time.time() self.ctxt[ELAPSED_SEC] += end_time - start_time ds_file_writer._dump_state() def _create_context(self, args, tid, read_op): io_string = "Read" if read_op else "Write" device_id, folder = args.mapping_list[tid] filename = create_filename(folder, args.read, args.io_size, tid) if args.read and not (os.path.isfile(filename) and os.path.getsize(filename) == args.io_size): create_file(filename, args.io_size) io_parallel = args.io_parallel if args.io_parallel else 1 aio_handle = AsyncIOBuilder().load().aio_handle(args.block_size, args.queue_depth, args.single_submit, not args.sequential_requests, io_parallel) if args.gpu: buffer = torch.randint(high=128, size=(args.io_size, ), dtype=torch.uint8, device=f'cuda:{device_id}') else: buffer = create_page_locked_tensor(args.io_size, args.use_accelerator_pin_memory, aio_handle) task_log(tid, f'Allocate tensor of size {args.io_size} bytes') fast_io_buffer = create_page_locked_tensor(args.fast_io_size, args.use_accelerator_pin_memory, aio_handle) task_log(tid, 'created torch_fastio engine') ctxt = {} ctxt[FILE] = filename ctxt[NUM_BYTES] = args.io_size ctxt[BUFFER] = buffer ctxt[HANDLE] = aio_handle ctxt[FAST_IO_BUFFER] = fast_io_buffer ctxt[ELAPSED_SEC] = 0 ctxt[USE_CPU_LOCKED_TENSOR] = not args.use_accelerator_pin_memory task_log(tid, f'{io_string} file {filename} of size {args.io_size} bytes from buffer on device {buffer.device}', force=True) return ctxt
{ "repo_id": "deepspeedai/DeepSpeed", "file_path": "deepspeed/nvme/torch_fastio_engine.py", "license": "Apache License 2.0", "lines": 67, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
deepspeedai/DeepSpeed:deepspeed/nvme/torch_io.py
# Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: Apache-2.0 # DeepSpeed Team import torch import os import time from .test_ds_aio_utils import task_log, create_filename, create_file, create_page_locked_tensor from .ds_aio_constants import * class TorchIO_Engine(object): def __init__(self, args, tid, read_op): self.ctxt = self._create_context(args, tid, read_op) self.zipfile_serialization = not args.torch_legacy_save def fini(self): self.ctxt[BUFFER].detach() self.ctxt[BUFFER] = None def read(self, args, tid): start_time = time.time() torch.load(f=self.ctxt[FILE], map_location=self.ctxt[BUFFER].device) end_time = time.time() self.ctxt[ELAPSED_SEC] += end_time - start_time def write(self, args, tid): # Avoid overwriting existing files as it could be artificially faster if os.path.isfile(self.ctxt[FILE]): os.remove(self.ctxt[FILE]) start_time = time.time() torch.save(obj=self.ctxt[BUFFER], f=self.ctxt[FILE], _use_new_zipfile_serialization=self.zipfile_serialization) end_time = time.time() self.ctxt[ELAPSED_SEC] += end_time - start_time def _create_context(self, args, tid, read_op): io_string = "Read" if read_op else "Write" device_id, folder = args.mapping_list[tid] filename = create_filename(folder, args.read, args.io_size, tid) if args.read and not (os.path.isfile(filename) and os.path.getsize(filename) == args.io_size): create_file(filename, args.io_size) task_log(tid, f'Allocate tensor of size {args.io_size} bytes') if args.gpu: buffer = torch.randint(high=128, size=(args.io_size, ), dtype=torch.uint8, device=f'cuda:{device_id}') else: buffer = create_page_locked_tensor(args.io_size, True) task_log(tid, f'{io_string} file {filename} of size {args.io_size} bytes from buffer on device {buffer.device}', force=True) task_log(tid, 'created torch_io engine') ctxt = {} ctxt[FILE] = filename ctxt[NUM_BYTES] = args.io_size ctxt[BUFFER] = buffer ctxt[ELAPSED_SEC] = 0 return ctxt
{ "repo_id": "deepspeedai/DeepSpeed", "file_path": "deepspeed/nvme/torch_io.py", "license": "Apache License 2.0", "lines": 49, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
deepspeedai/DeepSpeed:deepspeed/runtime/checkpoint_engine/decoupled_checkpoint_engine.py
# Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: Apache-2.0 # DeepSpeed Team import torch import torch.multiprocessing as mp from deepspeed.runtime.checkpoint_engine.checkpoint_engine import \ CheckpointEngine, CheckpointCommitInfo from deepspeed.runtime.checkpoint_engine.fast_checkpoint_engine import FastCheckpointEngine from deepspeed import comm as dist from deepspeed.runtime.utils import get_checkpoint_folder_size from deepspeed.utils import logger from enum import Enum class DecoupledEvent(Enum): SAVE_EVENT = 1 COMMIT_EVENT = 2 EXIT_EVENT = 3 class CheckpointSize(object): def __init__(self): self._pre = None self._post = None self._gigabytes = None def gb_size(self): return self._gigabytes def set_pre_size(self, size): self._pre = size def set_post_size(self, size): self._post = size self._gigabytes = (self._post - self._pre) / (1024**3) def init_decoupled_checkpoint(config_params, dp_writer_config, save_event, save_queue, optimize_dp_state): try: checkpoint_engine = FastCheckpointEngine(config_params, dp_writer_config, optimize_dp_state) print('Created FastCheckpointEngine for Decoupled Checkpointing') save_path_list = [] while True: (save_info, event_type) = save_queue.get() if event_type == DecoupledEvent.SAVE_EVENT and save_info is not None: state_dict, save_path = save_info # print(f'Received decoupled checkpoint request for {save_path=}') save_path_list.append(save_path) checkpoint_engine.save(state_dict, save_path) del state_dict # print(f'Completed decoupled checkpoint request for {save_path=}') if event_type == DecoupledEvent.COMMIT_EVENT: # print(f'Recieved commit request for {save_path_list=}') save_path_list = [] save_event.set() if event_type == DecoupledEvent.EXIT_EVENT: # print(f'Received decoupled exit request') break except Exception as e: print(f'[{ENGINE_NAME}] Checkpoint subprocess crashed with error: {e}') raise ENGINE_NAME = "DecoupledCheckpointEngine" # Default timeout for checkpoint operations (5 minutes) DEFAULT_CHECKPOINT_TIMEOUT_SECONDS = 300 # Interval for checking process health while waiting PROCESS_HEALTH_CHECK_INTERVAL_SECONDS = 10 class DecoupledCheckpointEngine(CheckpointEngine): def __init__(self, config_params, dp_writer_config, optimize_dp_state): # Set spawn method if not already set (needed for CUDA tensor sharing) try: mp.set_start_method('spawn') except RuntimeError: pass # Already set, ignore super().__init__(config_params) self.name = ENGINE_NAME self.dp_writer_config = dp_writer_config self.commit_info = None self.checkpoint_size = CheckpointSize() self.global_rank = dist.get_rank() self.optimize_dp_state = optimize_dp_state self._cleanup_called = False if dp_writer_config is None: self.save_event = None self.save_queue = None self.ckpt_process = None self.local_rank = None print( f'[{ENGINE_NAME}]: No checkpoint process self.global_rank={self.global_rank} self.dp_writer_config={self.dp_writer_config}' ) else: self.save_event = mp.Event() self.save_queue = mp.SimpleQueue() engine_args = (config_params, dp_writer_config, self.save_event, self.save_queue, self.optimize_dp_state) self.ckpt_process = mp.Process(target=init_decoupled_checkpoint, args=engine_args) self.ckpt_process.start() self.local_rank = dp_writer_config.local_rank print( f'[{ENGINE_NAME}]: Create checkpoint process self.global_rank={self.global_rank} self.ckpt_process.pid={self.ckpt_process.pid} self.dp_writer_config={self.dp_writer_config}' ) def __del__(self): try: self.cleanup() except Exception: # Suppress exceptions in destructor to avoid crashes during shutdown pass def _check_process_alive(self): """Check if the checkpoint process is still alive. Note: Only call this when self.ckpt_process is not None. Some ranks don't have a checkpoint process by design (see Figure 6 in paper). """ return self.ckpt_process.is_alive() def _wait_for_event_with_timeout(self, timeout_seconds=DEFAULT_CHECKPOINT_TIMEOUT_SECONDS): """Wait for save_event with timeout and process health checks. Returns True if event was set, raises RuntimeError if process died or timeout occurred. """ elapsed = 0 while elapsed < timeout_seconds: if self.save_event.wait(timeout=PROCESS_HEALTH_CHECK_INTERVAL_SECONDS): return True elapsed += PROCESS_HEALTH_CHECK_INTERVAL_SECONDS # Check if process is still alive if not self._check_process_alive(): raise RuntimeError(f"[{ENGINE_NAME}] Checkpoint process died unexpectedly. " f"Check logs for OOM or other errors in the checkpoint subprocess.") raise RuntimeError(f"[{ENGINE_NAME}] Checkpoint commit timed out after {timeout_seconds} seconds. " f"Process alive: {self._check_process_alive()}") def create(self, info: CheckpointCommitInfo): self.commit_info = info if self.checkpoint_size.gb_size() is None: pre_size = get_checkpoint_folder_size(info.save_dir, info.tag, self.local_rank) self.checkpoint_size.set_pre_size(pre_size) def load(self, path: str, map_location=None): sd = torch.load(path, map_location=map_location) return sd def save(self, state_dict, path: str): if self.ckpt_process is None: return # Check process health before attempting to save if not self._check_process_alive(): return save_info = (state_dict, path) self.save_queue.put((save_info, DecoupledEvent.SAVE_EVENT)) def commit(self, info: CheckpointCommitInfo): # Use proper validation instead of assert (assert is disabled with python -O) if info != self.commit_info: raise ValueError(f"[{ENGINE_NAME}] Checkpoint commit info mismatch: " f"expected {self.commit_info}, got {info}") if self.ckpt_process is not None: # Check process health before waiting if not self._check_process_alive(): raise RuntimeError(f"[{ENGINE_NAME}] Cannot commit checkpoint: checkpoint process is not running.") self.save_queue.put((None, DecoupledEvent.COMMIT_EVENT)) # Wait with timeout and health checks instead of blocking forever self._wait_for_event_with_timeout() self.save_event.clear() self.commit_info = None if self.checkpoint_size.gb_size() is None: dist.barrier() post_size = get_checkpoint_folder_size(info.save_dir, info.tag, self.local_rank) self.checkpoint_size.set_post_size(post_size) assert self.checkpoint_size.gb_size() is not None, "Checkpoint size should be set after commit" if self.global_rank == 0: print( f'{self.name} self.global_rank={self.global_rank} created checkpoint of {round(self.checkpoint_size.gb_size(), 2)} GB' ) return True def get_commit_info(self): # print(f'getting commit info {self.commit_info=}') return self.commit_info def is_decoupled(self): return True def cleanup(self): # Prevent multiple cleanup calls (especially from __del__) if self._cleanup_called: return self._cleanup_called = True try: if self.get_commit_info() is not None: self.commit(self.commit_info) except Exception as e: logger.warning(f"[{ENGINE_NAME}] Error during commit in cleanup: {e}") if self.ckpt_process is not None: try: self.save_queue.put((None, DecoupledEvent.EXIT_EVENT)) except Exception: pass # Queue may be broken if process died # Join with timeout to avoid hanging forever self.ckpt_process.join(timeout=DEFAULT_CHECKPOINT_TIMEOUT_SECONDS) # If process didn't exit, terminate it forcefully if self.ckpt_process.is_alive(): logger.warning( f"[{ENGINE_NAME}] Checkpoint process did not exit within timeout, terminating forcefully.") self.ckpt_process.terminate() self.ckpt_process.join(timeout=5) # Brief wait after terminate # Last resort: kill if self.ckpt_process.is_alive(): self.ckpt_process.kill() self.ckpt_process = None self.save_queue = None def is_data_parallel_writer(self, dp_rank): return self.ckpt_process is not None
{ "repo_id": "deepspeedai/DeepSpeed", "file_path": "deepspeed/runtime/checkpoint_engine/decoupled_checkpoint_engine.py", "license": "Apache License 2.0", "lines": 192, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
deepspeedai/DeepSpeed:deepspeed/runtime/checkpoint_engine/fast_checkpoint_engine.py
# Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: Apache-2.0 # DeepSpeed Team import torch from deepspeed.runtime.checkpoint_engine.checkpoint_engine import \ CheckpointEngine, CheckpointCommitInfo from deepspeed.runtime.model_checkpointing import ( CHECKPOINT_WRITER, CHECKPOINT_SERIALIZATION, CheckpointWriterFactory, ) class FastCheckpointEngine(CheckpointEngine): def __init__(self, config_params, dp_writer_config, optimize_dp_state): super().__init__(config_params) self.name = 'FastCheckpointEngine' self.serialization_enabled = config_params.checkpoint_config[CHECKPOINT_SERIALIZATION] self.optimize_dp_state = optimize_dp_state if dp_writer_config is None: self._writer = None else: self._writer = CheckpointWriterFactory(writer_config=config_params.checkpoint_config[CHECKPOINT_WRITER], aio_config=config_params.aio_config, dp_writer_config=dp_writer_config) def create(self, info: CheckpointCommitInfo): pass def save(self, state_dict, path: str): if self._writer is None: return torch.save(obj=state_dict, f=self._writer.create_writer(path, self.optimize_dp_state), _use_new_zipfile_serialization=self.serialization_enabled) self._writer.release_writer() def load(self, path: str, map_location=None): sd = torch.load(path, map_location=map_location) return sd def commit(self, info: CheckpointCommitInfo): return True def is_data_parallel_writer(self, dp_rank): return self._writer is not None
{ "repo_id": "deepspeedai/DeepSpeed", "file_path": "deepspeed/runtime/checkpoint_engine/fast_checkpoint_engine.py", "license": "Apache License 2.0", "lines": 39, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
deepspeedai/DeepSpeed:deepspeed/runtime/checkpoint_engine/utils.py
# Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: Apache-2.0 # DeepSpeed Team from deepspeed.runtime.model_checkpointing.constants import * from deepspeed.runtime.model_checkpointing.utils import create_data_parallel_writer_config from deepspeed.utils import logger from deepspeed import comm as dist from .decoupled_checkpoint_engine import DecoupledCheckpointEngine from .fast_checkpoint_engine import FastCheckpointEngine from .torch_checkpoint_engine import TorchCheckpointEngine def create_checkpoint_engine(config_params, groups, zero_stage, has_moe_layers, optimize_dp_state): if config_params is not None: if config_params.checkpoint_config[CHECKPOINT_WRITER] is not None: writer_config = config_params.checkpoint_config[CHECKPOINT_WRITER] dp_writer_config = create_data_parallel_writer_config( groups=groups, parallel_unit=writer_config[CHECKPOINT_DATA_PARALLEL], zero_stage=zero_stage, has_moe_layers=has_moe_layers) if writer_config[CHECKPOINT_WRITER_DECOUPLED]: return DecoupledCheckpointEngine(config_params, dp_writer_config, optimize_dp_state) else: return FastCheckpointEngine(config_params, dp_writer_config, optimize_dp_state) if config_params is not None and config_params.nebula_config.enabled: try: from .nebula_checkpoint_engine import NebulaCheckpointEngine except ImportError as err: logger.error(f"No torch_nebula was found! Will fall back to torch.save. Details: {err}") return TorchCheckpointEngine(config_params) else: return NebulaCheckpointEngine(config_params=config_params.nebula_config) if config_params.datastates_config.enabled: try: from .datastates_checkpoint_engine import DataStatesCheckpointEngine return DataStatesCheckpointEngine(deepspeed_config=config_params, rank=dist.get_rank()) except ImportError as err: logger.error( f"No datastates engine found! Install from https://github.com/DataStates/datastates-llm. Will fall back to torch.save. Details: {err}" ) return TorchCheckpointEngine(config_params) return TorchCheckpointEngine(config_params)
{ "repo_id": "deepspeedai/DeepSpeed", "file_path": "deepspeed/runtime/checkpoint_engine/utils.py", "license": "Apache License 2.0", "lines": 41, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
deepspeedai/DeepSpeed:deepspeed/runtime/model_checkpointing/config.py
# Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: Apache-2.0 # DeepSpeed Team from deepspeed.runtime.config_utils import get_scalar_param from .constants import * VALID_VALUES = { CHECKPOINT_TAG_VALIDATION: CHECKPOINT_TAG_VALIDATION_MODES, CHECKPOINT_WRITER_TYPE: CHECKPOINT_WRITER_TYPES, CHECKPOINT_DATA_PARALLEL: CHECKPOINT_DATA_PARALLEL_UNITS } CHECKPOINT_DEFAULT_DICT = { CHECKPOINT_TAG_VALIDATION: CHECKPOINT_TAG_VALIDATION_DEFAULT, CHECKPOINT_SERIALIZATION: CHECKPOINT_SERIALIZATION_DEFAULT, CHECKPOINT_WRITER: CHECKPOINT_WRITER_DEFAULT } def _validate_config_values(config_name, config_dict, valid_values): for key, value in config_dict.items(): if value is None: continue if key in valid_values.keys(): assert value in valid_values[key], \ f"{config_name} contains invalid value {value} for {key}, expecting one of {valid_values[key]}" def _make_upper_case(value): return value if value is None else value.upper() def get_checkpoint_writer_config(param_dict): writer_dict = param_dict.get(CHECKPOINT_WRITER, None) if writer_dict is None: return CHECKPOINT_WRITER_DEFAULT writer_config = { CHECKPOINT_WRITER_TYPE: _make_upper_case(get_scalar_param(writer_dict, CHECKPOINT_WRITER_TYPE, CHECKPOINT_WRITER_TYPE_DEFAULT)), CHECKPOINT_IO_BUFFER_SIZE: get_scalar_param(writer_dict, CHECKPOINT_IO_BUFFER_SIZE, CHECKPOINT_IO_BUFFER_SIZE_DEFAULT), CHECKPOINT_IO_BUFFER_DOUBLE: get_scalar_param(writer_dict, CHECKPOINT_IO_BUFFER_DOUBLE, CHECKPOINT_IO_BUFFER_DOUBLE_DEFAULT), CHECKPOINT_IO_STATISTICS: get_scalar_param(writer_dict, CHECKPOINT_IO_STATISTICS, CHECKPOINT_IO_STATISTICS_DEFAULT), CHECKPOINT_DATA_PARALLEL: _make_upper_case(get_scalar_param(writer_dict, CHECKPOINT_DATA_PARALLEL, CHECKPOINT_DATA_PARALLEL_DEFAULT)), CHECKPOINT_WRITER_DECOUPLED: get_scalar_param(writer_dict, CHECKPOINT_WRITER_DECOUPLED, CHECKPOINT_WRITER_DECOUPLED_DEFAULT), CHECKPOINT_IO_MULTIPLIER: get_scalar_param(writer_dict, CHECKPOINT_IO_MULTIPLIER, CHECKPOINT_IO_MULTIPLIER_DEFAULT), } _validate_config_values(CHECKPOINT_WRITER, writer_config, VALID_VALUES) return writer_config def get_checkpoint_config(param_dict): checkpoint_dict = param_dict.get(CHECKPOINT, None) if checkpoint_dict is None: return CHECKPOINT_DEFAULT_DICT checkpoint_config = { CHECKPOINT_TAG_VALIDATION: get_scalar_param(checkpoint_dict, CHECKPOINT_TAG_VALIDATION, CHECKPOINT_TAG_VALIDATION_DEFAULT).upper(), CHECKPOINT_SERIALIZATION: get_scalar_param(checkpoint_dict, CHECKPOINT_SERIALIZATION, CHECKPOINT_SERIALIZATION_DEFAULT), CHECKPOINT_WRITER: get_checkpoint_writer_config(checkpoint_dict) } _validate_config_values(CHECKPOINT, checkpoint_config, VALID_VALUES) return checkpoint_config
{ "repo_id": "deepspeedai/DeepSpeed", "file_path": "deepspeed/runtime/model_checkpointing/config.py", "license": "Apache License 2.0", "lines": 60, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
deepspeedai/DeepSpeed:deepspeed/runtime/model_checkpointing/constants.py
# Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: Apache-2.0 # DeepSpeed Team ######################################### # Validation modes ######################################### class ValidationMode: WARN = "WARN" IGNORE = "IGNORE" FAIL = "FAIL" ######################################### # Checkpoint config params ######################################### # "checkpoint": {tag_validation=["Ignore"|"Warn"|"Fail"]} CHECKPOINT_FORMAT = ''' "checkpoint": { "tag_validation": [Ignore|Warn|Fail], "checkpoint_serialization": False, "writer": { "type": [mock|python|fast], "decoupled": [True|False] "io_buffer_size": 64e6, "io_buffer_double": True, "show_statistics": False, "data_parallel": [replica|socket|machine], "io_multiplier": 1, } } ''' CHECKPOINT = "checkpoint" CHECKPOINT_TAG_VALIDATION = "tag_validation" CHECKPOINT_TAG_VALIDATION_DEFAULT = ValidationMode.WARN CHECKPOINT_TAG_VALIDATION_MODES = [ValidationMode.WARN, ValidationMode.IGNORE, ValidationMode.FAIL] CHECKPOINT_SERIALIZATION = "checkpoint_serialization" CHECKPOINT_SERIALIZATION_DEFAULT = True CHECKPOINT_WRITER = "writer" CHECKPOINT_WRITER_DEFAULT = None CHECKPOINT_WRITER_TYPE = "type" class CheckpointWriterType: MOCK = "MOCK" PYTHON = "PYTHON" FAST = "FAST" CHECKPOINT_WRITER_TYPE_DEFAULT = CheckpointWriterType.FAST CHECKPOINT_WRITER_TYPES = [CheckpointWriterType.MOCK, CheckpointWriterType.PYTHON, CheckpointWriterType.FAST] CHECKPOINT_IO_BUFFER_SIZE = "io_buffer_size" CHECKPOINT_IO_BUFFER_SIZE_DEFAULT = 64 * (1024**2) CHECKPOINT_IO_BUFFER_DOUBLE = "io_buffer_double" CHECKPOINT_IO_BUFFER_DOUBLE_DEFAULT = True CHECKPOINT_IO_MULTIPLIER = "io_multiplier" CHECKPOINT_IO_MULTIPLIER_DEFAULT = 1 CHECKPOINT_IO_STATISTICS = "show_statistics" CHECKPOINT_IO_STATISTICS_DEFAULT = False CHECKPOINT_DATA_PARALLEL = "data_parallel" CHECKPOINT_DATA_PARALLEL_DEFAULT = None class CheckpointDataParallel: REPLICA = "REPLICA" SOCKET = "SOCKET" MACHINE = "MACHINE" CHECKPOINT_DATA_PARALLEL_UNITS = [ CheckpointDataParallel.REPLICA, CheckpointDataParallel.SOCKET, CheckpointDataParallel.MACHINE ] CHECKPOINT_WRITER_DECOUPLED = "decoupled" CHECKPOINT_WRITER_DECOUPLED_DEFAULT = False
{ "repo_id": "deepspeedai/DeepSpeed", "file_path": "deepspeed/runtime/model_checkpointing/constants.py", "license": "Apache License 2.0", "lines": 63, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
deepspeedai/DeepSpeed:deepspeed/runtime/model_checkpointing/data_parallel_writer_factory.py
# Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: Apache-2.0 # DeepSpeed Team from dataclasses import dataclass from deepspeed.checkpoint.reshape_utils import partition_data from deepspeed.runtime.zero.config import ZeroStageEnum from .constants import * @dataclass class DataParallelWriterConfig(object): world_size: int rank: int global_rank: int local_rank: int pure_dp: bool class DataParallelWriterFactory(object): def __init__(self, uni_parallel_info, parallel_unit): self._uni_parallel_info = uni_parallel_info self._parallel_unit = parallel_unit if parallel_unit == CheckpointDataParallel.SOCKET: self._num_resources = uni_parallel_info.num_sockets else: self._num_resources = uni_parallel_info.num_machines self._ranks_per_resource = max(1, self._uni_parallel_info.global_world_size // self._num_resources) def create_config(self, zero_stage, has_moe_layers): if zero_stage == ZeroStageEnum.weights: return self._create_config(1, 0) if has_moe_layers: writer_config = self._get_expert_data_parallel_config() else: writer_config = self._get_data_parallel_config() if writer_config is None and zero_stage >= ZeroStageEnum.optimizer_states: return self._create_config(1, 0) return writer_config def _create_config(self, world_size, rank): return DataParallelWriterConfig(world_size=world_size, rank=rank, global_rank=self._uni_parallel_info.global_rank, local_rank=self._uni_parallel_info.local_rank, pure_dp=self._uni_parallel_info.pure_dp) def _get_expert_data_parallel_config(self): ep_info = self._uni_parallel_info.ep_info if self._parallel_unit is None: dp_rank = ep_info.dp_rank return self._create_config(1, 0) if dp_rank == 0 else None assert self._uni_parallel_info.pure_dp, \ '3D parallelism is not yet supported for data parallel checkpointing.' if self._parallel_unit == CheckpointDataParallel.REPLICA or ep_info.ep_world_size == 1: return self._get_parallel_write_for_ddp(ep_info.dp_world_size, ep_info.dp_rank) return self._get_expert_parallel_write_for_2d() def _get_expert_parallel_write_for_2d(self): ep_info = self._uni_parallel_info.ep_info def _get_expert_slice_resources(expert_resources, resource_name): ep_world_size = ep_info.ep_world_size slices_per_resource = min(self._ranks_per_resource, ep_world_size) assert slices_per_resource <= len(expert_resources) ep_num_resources = len(expert_resources) assert ep_num_resources % slices_per_resource == 0, f'{resource_name}: Expected ep_num_resources={ep_num_resources} to multiple of slices_per_resource={slices_per_resource} for ep_world_size={ep_world_size}' slice_partitions = partition_data(expert_resources, slices_per_resource) # print( # f'edp_resource_partition: self._uni_parallel_info.global_rank={self._uni_parallel_info.global_rank} expert_resources={expert_resources} slices_per_resource={slices_per_resource} ep_world_size={ep_world_size} slice_partitions={slice_partitions}' # ) resource_index = ep_info.ep_rank % slice_resources return slice_partitions[resource_index] dp_ranks = ep_info.dp_peer_ranks expert_resources = [r // self._ranks_per_resource for r in dp_ranks] slice_resources = _get_expert_slice_resources(expert_resources, self._parallel_unit) assert all([idx < self._num_resources for idx in expert_resources]), \ f'Detected invalid resource index in expert_resources={expert_resources}, self._num_resources={self._num_resources}' return self._assign_resources_to_tensor_slice(slice_resources, ep_info.ep_rank, dp_ranks) def _get_data_parallel_config(self): mpu_info = self._uni_parallel_info.mpu_info if self._parallel_unit is None: dp_rank = self._uni_parallel_info.dp_rank if mpu_info is None else mpu_info.dp_rank return self._create_config(1, 0) if dp_rank == 0 else None if self._uni_parallel_info.pure_dp: return self._get_parallel_write_for_ddp(self._uni_parallel_info.global_world_size, self._uni_parallel_info.global_rank) if self._parallel_unit == CheckpointDataParallel.REPLICA: return self._create_config(mpu_info.dp_world_size, mpu_info.dp_rank) return self._get_parallel_write_for_3d() def _get_parallel_write_for_3d(self): mpu_info = self._uni_parallel_info.mpu_info my_global_rank = self._uni_parallel_info.global_rank def _expand_resources(resource_list, new_size): old_size = len(resource_list) if old_size >= new_size: return resource_list assert new_size % old_size == 0, f'Expect new_size={new_size} to be multiple of old_size={old_size}' multiplier = new_size // old_size new_resource_list = [] for r in resource_list: new_resource_list += [r] * multiplier # print(f'expand_resources: {my_global_rank=} {old_size=} {new_size=} {resource_list=} {new_resource_list=}') return new_resource_list # Getting resource partition for a tensor slice is a 2-step process # 1. Get resource partitions for all pipeline stages. A pipeline stage is a 2D grid of size TP x DP def _get_pipeline_stage_resources(resource_indices): num_resources = len(resource_indices) pp_world_size = mpu_info.pp_world_size if num_resources < pp_world_size: resource_indices = _expand_resources(resource_indices, pp_world_size) num_resources = pp_world_size global_resource_partitions = partition_data(resource_indices, pp_world_size) pp_rank = mpu_info.pp_rank return global_resource_partitions[pp_rank] # 2. Get resource partition for tensor slice. A tensor slice is a 1D vector of size DP def _get_tensor_slice_resources(resource_indices, resource_name): pipe_stage_resources = _get_pipeline_stage_resources(resource_indices) tp_world_size = mpu_info.tp_world_size if len(pipe_stage_resources) < tp_world_size: pipe_stage_resources = _expand_resources(pipe_stage_resources, tp_world_size) tp_num_resources = len(pipe_stage_resources) assert tp_num_resources % tp_world_size == 0, \ f'{resource_name}: Expected tp_num_resources={tp_num_resources} to multiple of tp_world_size={tp_world_size}' pipe_stage_resource_partitions = partition_data(pipe_stage_resources, tp_world_size) tp_rank = mpu_info.tp_rank return pipe_stage_resource_partitions[tp_rank] def _get_model_parallel_slice_resources(): # Get resources of my dp peer ranks resources = [(r // self._ranks_per_resource) for r in mpu_info.dp_peer_ranks] if len(resources) < self._ranks_per_resource: resources = _expand_resources(resources, self._ranks_per_resource) resource_partitions = partition_data(resources, self._ranks_per_resource) mp_rank = (mpu_info.pp_rank * mpu_info.tp_world_size) + mpu_info.tp_rank slice_rank = mp_rank % self._ranks_per_resource return resource_partitions[slice_rank] num_slices = mpu_info.tp_world_size * mpu_info.pp_world_size if num_slices > self._ranks_per_resource: slice_resources = _get_model_parallel_slice_resources() else: all_resources = list(range(self._num_resources)) slice_resources = _get_tensor_slice_resources(all_resources, self._parallel_unit) return self._assign_resources_to_tensor_slice(slice_resources, mpu_info.tp_rank, mpu_info.dp_peer_ranks) def _get_slice_writers(self, slice_resources, my_dp_ranks): resource_map = {} for res in slice_resources: resource_map[res] = [r for r in my_dp_ranks if (r // self._ranks_per_resource) == res] # Only one writer per resource, and we conventionally pick the first rank as writer. return [ranks[0] for ranks in resource_map.values()] def _assign_resources_to_tensor_slice(self, slice_resources, my_slice_index, my_dp_ranks): my_global_rank = self._uni_parallel_info.global_rank slice_writer_ranks = self._get_slice_writers(slice_resources, my_dp_ranks) my_resource_index = my_global_rank // self._ranks_per_resource print( f'resource_assign: my_global_rank={my_global_rank} my_slice_index={my_slice_index} my_dp_ranks={my_dp_ranks} slice_resources={slice_resources} slice_writer_ranks={slice_writer_ranks}' ) if my_resource_index in slice_resources and my_global_rank in slice_writer_ranks: my_writer_index = (my_global_rank - slice_writer_ranks[0]) // self._ranks_per_resource num_slice_writers = len(slice_writer_ranks) print( f'slice_writer: my_global_rank={my_global_rank} my_writer_index={my_writer_index} num_slice_writers={num_slice_writers}' ) return self._create_config(num_slice_writers, my_writer_index) return None def _get_parallel_write_for_ddp(self, dp_world_size, dp_rank): if self._parallel_unit == CheckpointDataParallel.REPLICA: return self._create_config(dp_world_size, dp_rank) num_machines = self._uni_parallel_info.num_machines if self._parallel_unit == CheckpointDataParallel.SOCKET: if dp_world_size == num_machines: # There is one rank per machine return self._create_config(num_machines, dp_rank) num_sockets = self._uni_parallel_info.num_sockets ranks_per_socket = dp_world_size // num_sockets if dp_rank % ranks_per_socket == 0: return self._create_config(num_sockets, dp_rank // ranks_per_socket) else: return None ranks_per_machine = dp_world_size // num_machines if dp_rank % ranks_per_machine == 0: return self._create_config(num_machines, self._uni_parallel_info.machine_rank) return None
{ "repo_id": "deepspeedai/DeepSpeed", "file_path": "deepspeed/runtime/model_checkpointing/data_parallel_writer_factory.py", "license": "Apache License 2.0", "lines": 172, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
deepspeedai/DeepSpeed:deepspeed/runtime/model_checkpointing/utils.py
# Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: Apache-2.0 # DeepSpeed Team import os from dataclasses import dataclass from deepspeed import comm as dist from deepspeed.constants import CROSS_RANK, CROSS_SIZE, LOCAL_RANK from .data_parallel_writer_factory import DataParallelWriterFactory # TODO: parse socket number from env. SOCKETS_PER_MACHINE = 2 @dataclass class MPUInfo(object): pp_world_size: int pp_rank: int tp_world_size: int tp_rank: int dp_world_size: int dp_peer_ranks: list dp_rank: int def _create_model_parallel_info(mpu): return MPUInfo(pp_world_size=mpu.get_pipeline_model_parallel_world_size(), pp_rank=mpu.get_pipeline_model_parallel_rank(), tp_world_size=mpu.get_tensor_model_parallel_world_size(), tp_rank=mpu.get_tensor_model_parallel_rank(), dp_world_size=mpu.get_data_parallel_world_size(), dp_peer_ranks=mpu.get_data_parallel_group_ranks(), dp_rank=mpu.get_data_parallel_rank()) @dataclass class ExpertParallelInfo(object): ep_world_size: int ep_rank: int dp_world_size: int dp_peer_ranks: list dp_rank: int def _create_expert_parallel_info(groups): group_name = groups._get_max_expert_size_name() return ExpertParallelInfo(ep_world_size=groups._get_expert_parallel_world_size(group_name), ep_rank=groups._get_expert_parallel_rank(group_name), dp_world_size=groups._get_expert_data_parallel_world_size(group_name), dp_peer_ranks=groups._get_expert_data_parallel_group_ranks(group_name), dp_rank=groups._get_expert_data_parallel_rank(group_name)) @dataclass class UniversalParallelInfo(object): global_world_size: int global_rank: int local_rank: int mpu_info: MPUInfo ep_info: ExpertParallelInfo pure_dp: bool num_machines: int machine_rank: int num_sockets: int def create_universal_parallel_info(groups, has_moe_layers): return UniversalParallelInfo(global_world_size=dist.get_world_size(), global_rank=dist.get_rank(), local_rank=int(os.environ[LOCAL_RANK]), mpu_info=None if groups.mpu is None else _create_model_parallel_info(groups.mpu), ep_info=_create_expert_parallel_info(groups) if has_moe_layers else None, pure_dp=groups.mpu is None or groups.mpu.get_data_parallel_world_size() == dist.get_world_size(), num_machines=int(os.environ[CROSS_SIZE]), machine_rank=int(os.environ[CROSS_RANK]), num_sockets=int(os.environ[CROSS_SIZE]) * SOCKETS_PER_MACHINE) def create_data_parallel_writer_config(groups, parallel_unit, zero_stage, has_moe_layers): uni_parallel_info = create_universal_parallel_info(groups, has_moe_layers) writer_factory = DataParallelWriterFactory(uni_parallel_info, parallel_unit) return writer_factory.create_config(zero_stage, has_moe_layers)
{ "repo_id": "deepspeedai/DeepSpeed", "file_path": "deepspeed/runtime/model_checkpointing/utils.py", "license": "Apache License 2.0", "lines": 67, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
deepspeedai/DeepSpeed:deepspeed/runtime/model_checkpointing/writer_factory.py
# Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: Apache-2.0 # DeepSpeed Team import torch from deepspeed.ops.op_builder import AsyncIOBuilder, GDSBuilder from deepspeed.io import MockFileWriter, PyFileWriter, FastFileWriter, FastFileWriterConfig from deepspeed.runtime.swap_tensor.constants import * from .constants import * from deepspeed.accelerator import get_accelerator class CheckpointWriterFactory(object): def __init__(self, writer_config, aio_config, dp_writer_config): self._type = writer_config[CHECKPOINT_WRITER_TYPE] self._io_buffer_size = writer_config[CHECKPOINT_IO_BUFFER_SIZE] self._io_buffer_double = writer_config[CHECKPOINT_IO_BUFFER_DOUBLE] self._data_parallel_writer = dp_writer_config self._io_multiplier = writer_config[CHECKPOINT_IO_MULTIPLIER] if self._data_parallel_writer.pure_dp: self._show_statistics = writer_config[CHECKPOINT_IO_STATISTICS] and self._data_parallel_writer is not None else: self._show_statistics = writer_config[CHECKPOINT_IO_STATISTICS] and self._data_parallel_writer is not None self._io_buffer = None self._dnvme_handle = None self._writer = None self._use_gds = False if self._type == CheckpointWriterType.FAST: self._use_gds = aio_config[AIO_USE_GDS] if self._use_gds: self._setup_for_gds(aio_config) else: self._setup_for_aio(aio_config) print( f'WriterFactory: self._data_parallel_writer={self._data_parallel_writer} self._show_statistics={self._show_statistics}' ) def create_writer(self, file_path, optimize_dp_state): assert self._writer is None, \ f'Cannot create checkpoint writer for {file_path} because writer is currently used for {self._writer.file_path()}.\ Must call writer.release() before reusing to avoid this error.' if self._type == CheckpointWriterType.MOCK: self._writer = MockFileWriter(file_path) elif self._type == CheckpointWriterType.PYTHON: self._writer = PyFileWriter(file_path) else: if optimize_dp_state: num_parallel_writers = self._data_parallel_writer.world_size * self._io_multiplier writer_rank = self._data_parallel_writer.rank file_path = f'{file_path}-{writer_rank}.{num_parallel_writers}' # print(f'create_dp_writer: {self._data_parallel_writer.global_rank=} {writer_rank=} {num_parallel_writers=} {file_path=}') else: num_parallel_writers = 1 writer_rank = 0 # print(f'create_rank0_writer: {self._data_parallel_writer.global_rank=} {writer_rank=} {num_parallel_writers=} {file_path=}') config = FastFileWriterConfig(dnvme_handle=self._dnvme_handle, pinned_tensor=self._io_buffer, double_buffer=self._io_buffer_double, num_parallel_writers=num_parallel_writers, writer_rank=writer_rank, global_rank=self._data_parallel_writer.global_rank) self._writer = FastFileWriter(file_path=file_path, config=config) return self._writer def release_writer(self): self._writer.close() if self._show_statistics: self._writer._dump_state() self._writer = None def _setup_for_aio(self, aio_config): self._io_buffer = torch.zeros(self._io_buffer_size, dtype=torch.uint8, device='cpu').pin_memory() self._dnvme_handle = AsyncIOBuilder().load().aio_handle( block_size=aio_config[AIO_BLOCK_SIZE], queue_depth=aio_config[AIO_QUEUE_DEPTH], single_submit=aio_config[AIO_SINGLE_SUBMIT], overlap_events=aio_config[AIO_OVERLAP_EVENTS], intra_op_parallelism=aio_config[AIO_INTRA_OP_PARALLELISM]) def _setup_for_gds(self, aio_config): self._io_buffer = torch.zeros(self._io_buffer_size, dtype=torch.uint8, device=get_accelerator().current_device_name()) self._dnvme_handle = GDSBuilder().load().gds_handle(block_size=aio_config[AIO_BLOCK_SIZE], queue_depth=aio_config[AIO_QUEUE_DEPTH], single_submit=aio_config[AIO_SINGLE_SUBMIT], overlap_events=aio_config[AIO_OVERLAP_EVENTS], intra_op_parallelism=aio_config[AIO_INTRA_OP_PARALLELISM]) self._dnvme_handle.pin_device_tensor(self._io_buffer)
{ "repo_id": "deepspeedai/DeepSpeed", "file_path": "deepspeed/runtime/model_checkpointing/writer_factory.py", "license": "Apache License 2.0", "lines": 82, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
deepspeedai/DeepSpeed:tests/unit/utils/test_byte_cast.py
# Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: Apache-2.0 # DeepSpeed Team import pytest import torch import deepspeed from deepspeed.ops.op_builder import UtilsBuilder from deepspeed.accelerator import get_accelerator from unit.common import DistributedTest if not deepspeed.ops.__compatible_ops__[UtilsBuilder.NAME]: pytest.skip(f'Skip tests since {UtilsBuilder.NAME} is not compatible', allow_module_level=True) def _validate_tensor_cast_properties(typed_tensor, byte_tensor): assert byte_tensor.dtype == torch.uint8 assert byte_tensor.numel() == typed_tensor.numel() * typed_tensor.element_size() assert byte_tensor.data_ptr() == typed_tensor.data_ptr() def _byte_cast_single_tensor(typed_tensor): util_ops = UtilsBuilder().load() byte_tensor = util_ops.cast_to_byte_tensor(typed_tensor) _validate_tensor_cast_properties(typed_tensor=typed_tensor, byte_tensor=byte_tensor) def _byte_cast_multiple_tensors(typed_tensor_list): util_ops = UtilsBuilder().load() byte_tensor_list = util_ops.cast_to_byte_tensor(typed_tensor_list) assert len(typed_tensor_list) == len(byte_tensor_list) for typed_tensor, byte_tensor in zip(typed_tensor_list, byte_tensor_list): _validate_tensor_cast_properties(typed_tensor=typed_tensor, byte_tensor=byte_tensor) @pytest.mark.parametrize( 'dtype', [torch.float32, torch.half, torch.bfloat16, torch.float64, torch.int32, torch.short, torch.int64], ) class TestCastSingleTensor(DistributedTest): world_size = 1 def test_byte_cast_accelerator_tensor(self, dtype): numel = 1024 typed_tensor = torch.empty(numel, dtype=dtype).to(get_accelerator().device_name()) _byte_cast_single_tensor(typed_tensor) @pytest.mark.parametrize("pinned_memory", [True, False]) def test_byte_cast_cpu_tensor(self, dtype, pinned_memory): numel = 1024 typed_tensor = torch.empty(numel, dtype=dtype, device='cpu') if pinned_memory: typed_tensor = typed_tensor.pin_memory() _byte_cast_single_tensor(typed_tensor) @pytest.mark.parametrize('tensor_count', [1, 8, 15]) class TestCastTensorList(DistributedTest): world_size = 1 def test_byte_cast_accelerator_tensor_list(self, tensor_count): typed_tensor_list = [torch.empty(1024, dtype=torch.half).to(get_accelerator().device_name())] * tensor_count _byte_cast_multiple_tensors(typed_tensor_list) def test_byte_cast_cpu_tensor_list(self, tensor_count): typed_tensor_list = [torch.empty(1024, dtype=torch.half, device='cpu')] * tensor_count _byte_cast_multiple_tensors(typed_tensor_list)
{ "repo_id": "deepspeedai/DeepSpeed", "file_path": "tests/unit/utils/test_byte_cast.py", "license": "Apache License 2.0", "lines": 51, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
deepspeedai/DeepSpeed:deepspeed/runtime/sequence_parallel/parallel_state_sp.py
# Copyright (c) The DeepSpeed Contributors # SPDX-License-Identifier: Apache-2.0 # DeepSpeed Team """ This is a slimmed-down version of parallel_state.py (mpu) from Megatron-Deepspeed """ from deepspeed import comm as dist # Sequence parallel groups to handle both data and sequence parallelisms. # These groups are used to reduce gradients and shard parameters and optimizer stages for ZeRO. _SEQUENCE_PARALLEL_GROUP = None _SEQUENCE_DATA_PARALLEL_GROUP = None def initialize_sequence_parallel(sequence_parallel_size: int) -> None: """Initialize sequence parallel groups.""" assert dist.is_initialized() world_size: int = dist.get_world_size() if world_size < sequence_parallel_size: raise RuntimeError(f"world_size ({world_size}) is less than sequence_parallel_size {sequence_parallel_size}") if sequence_parallel_size <= 1: raise ValueError(f"sequence_parallel_size must be greater than 1, got {sequence_parallel_size}") if world_size % sequence_parallel_size != 0: raise RuntimeError( f"world_size ({world_size}) is not divisible by sequence_parallel_size {sequence_parallel_size})") data_parallel_size: int = world_size // sequence_parallel_size sequence_data_parallel_size: int = sequence_parallel_size * data_parallel_size num_sequence_parallel_groups: int = world_size // sequence_parallel_size num_sequence_data_parallel_groups: int = world_size // sequence_parallel_size // data_parallel_size rank = dist.get_rank() # Build the sequence parallel groups. global _SEQUENCE_PARALLEL_GROUP assert _SEQUENCE_PARALLEL_GROUP is None, "sequence parallel group is already initialized" for i in range(num_sequence_parallel_groups): ranks = range(i * sequence_parallel_size, (i + 1) * sequence_parallel_size) group = dist.new_group(ranks) if rank in ranks: _SEQUENCE_PARALLEL_GROUP = group # Build the sequence data parallel groups. global _SEQUENCE_DATA_PARALLEL_GROUP assert _SEQUENCE_DATA_PARALLEL_GROUP is None, "sequence data parallel group is already initialized" all_data_sequence_parallel_group_ranks = [] for i in range(num_sequence_data_parallel_groups): ranks = range(i * sequence_data_parallel_size, (i + 1) * sequence_data_parallel_size) group = dist.new_group(ranks) all_data_sequence_parallel_group_ranks.append(list(ranks)) if rank in ranks: _SEQUENCE_DATA_PARALLEL_GROUP = group def get_sequence_parallel_group(): """Get the sequence parallel group the caller rank belongs to.""" assert _SEQUENCE_PARALLEL_GROUP is not None, "sequence parallel group is not initialized" return _SEQUENCE_PARALLEL_GROUP def get_sequence_data_parallel_group(): """Get the sequence parallel group the caller rank belongs to.""" assert _SEQUENCE_DATA_PARALLEL_GROUP is not None, "sequence data parallel group is not initialized" return _SEQUENCE_DATA_PARALLEL_GROUP def get_sequence_parallel_world_size(): """Return world size for the sequence parallel group.""" return dist.get_world_size(group=get_sequence_parallel_group()) def get_sequence_data_parallel_world_size(): """Return world size for the sequence parallel group.""" return dist.get_world_size(group=get_sequence_data_parallel_group()) def get_sequence_parallel_rank(): """Return my rank for the sequence parallel group.""" return dist.get_rank(group=get_sequence_parallel_group()) def get_sequence_data_parallel_rank(): """Return my rank for the sequence data parallel group.""" return dist.get_rank(group=get_sequence_data_parallel_group()) # since we only have 1 additional dimension over DP, we can just alias MP with SP get_model_parallel_rank = get_sequence_parallel_rank get_model_parallel_world_size = get_sequence_parallel_world_size get_model_parallel_group = get_sequence_parallel_group
{ "repo_id": "deepspeedai/DeepSpeed", "file_path": "deepspeed/runtime/sequence_parallel/parallel_state_sp.py", "license": "Apache License 2.0", "lines": 69, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
deepspeedai/DeepSpeed:deepspeed/runtime/sequence_parallel/ulysses_sp.py
# Copyright (c) The DeepSpeed Contributors # SPDX-License-Identifier: Apache-2.0 # DeepSpeed Team """ *** Arctic Long Sequence Training (ALST) components *** 1. Ulysses Sequence Parallelism for HF Transformers implements an efficient way of training on long sequences by employing sequence parallelism and attention head parallelism. 2. ALST enables even longer sequence lengths using a bag of tricks: - Activation checkpoint offload to CPU - Tiled MLP compute - Liger-kernel - PYTORCH_CUDA_ALLOC_CONF ALST features found in this module: - `UlyssesSPAttentionHF` - port of UlyssesAttention from Megatron-Deepspeed plus modern MHA-variations - `UlyssesSPDataLoaderAdapter` - DL adapter to shard the normal DL batches to be used by `UlyssesSPAttentionHF` - `SequenceTiledCompute` - generic autograd function to perform compute after tiling on the sequence dimension - `TiledMLP` - a specific autograd function to perform tiled MLP (it's much easier to understand before trying to grok `SequenceTiledCompute`) - `TiledFusedLogitsLoss` - a specific autograd function to perform loss computation without manifesting the full logits tensor and instead computing loss on shards of logits. This module implements Arctic Long Sequence Training: Scalable And Efficient Training For Multi-Million Token Sequences: https://arxiv.org/abs/2506.13996 For integration docs see: https://www.deepspeed.ai/tutorials/ulysses-alst-sequence-parallelism/ The other ALST features live inside https://github.com/snowflakedb/ArcticTraining/blob/main/projects/sequence-parallelism/ """ from collections import defaultdict, deque from deepspeed.runtime.utils import see_memory_usage from deepspeed.sequence.layer import _DimZeroAllToAll from deepspeed.utils.logging import logger from einops import rearrange from packaging import version from torch import Tensor from torch.utils.data import DataLoader from typing import Any from typing import Tuple import deepspeed.comm as dist import importlib.metadata import math import torch import torch.distributed.nn class UlyssesSPAttentionHF(torch.nn.Module): """Re-Implementation of deepspeed.sequence.layer.DistributedAttention. This implementation enforces the input shape to be standard [sl, bs, hc, hs] form. Any deviation from this shape will raise an error. The primary reason for the re-implementation is to make this less error prone, and remove what seemed like bugs in scenarios where batch size > 1 and when using different versions of flash attention each of which takes different input shape. Those should be handled by the actual attn implementation, and not by this module. This class then has been further adapted to work with HF Transformers' supported attention mechanism. Dimension annotation: bs = bs hc = head count hc_l = head count local hs = head_size sl = seqlen sl_l = seqlen local ws = world_size em = embedding (hidden size) em_l = embedding (hidden size) local Arguments: attn: normal attention implementation from transformers.modeling_utils.ALL_ATTENTION_FUNCTIONS seq_length_is_variable (bool): whether global seqlen may change between batches local_seq_length (int): local sequence length per GPU or None if seq_length_is_variable is True global_seq_length (int): actual sequence length or None if seq_length_is_variable is True batch_size (int): batch size attn_head_size (int): size of each attention head attn_head_count (int): total number of attention heads kv_head_count (int): total number of kv heads num_hidden_layers (int): total number of layers process_group (dist.ProcessGroup): Ulysses process group disable_in_eval (bool): whether to disable sequence parallelism during evaluation (default: False). When True, SP operations are bypassed during eval to avoid potential issues with frameworks like HF Trainer that may run eval with different data distribution. Extras: - set self.skip_all_but_last_attention_debug_mode to True to enable fast debug which will skip calling all core attn layers but the last one, it will produce garbage of course quality-wise. """ def __init__( self, attn, batch_size: int, attn_head_count: int, attn_head_size: int, kv_head_count: int, num_hidden_layers: int, process_group: dist.ProcessGroup, seq_length_is_variable: bool = False, local_seq_length: int = None, global_seq_length: int = None, disable_in_eval: bool = False, ) -> None: super().__init__() self.attn = attn self.process_group = process_group self.world_size = dist.get_world_size(process_group) self.sp_rank = dist.get_rank(process_group) self.batch_size = batch_size self.seq_length_is_variable = seq_length_is_variable self.local_seq_length = local_seq_length self.global_seq_length = global_seq_length self.disable_in_eval = disable_in_eval self.attn_head_size = attn_head_size self.attn_head_count = attn_head_count self.global_kv_head_count = kv_head_count self.num_hidden_layers = num_hidden_layers self.skip_all_but_last_attention_debug_mode = False self.rotating_layer_counter = 0 # used for dev work self.local_q_head_count = attn_head_count // self.world_size # if we have 4 kv heads and sp 8, we need to replicate kv heads 2x self.kv_replication_factor = self.world_size // kv_head_count if self.kv_replication_factor > 1: self.local_kv_head_count = 1 else: self.local_kv_head_count = kv_head_count // self.world_size transformers_version_min = "4.51.3" transformers_version_have = importlib.metadata.version("transformers") if version.parse(transformers_version_have) < version.parse(transformers_version_min): raise ValueError( f"transformers>={transformers_version_min} is required, but you have transformers=={transformers_version_have}" ) if self.attn_head_count % self.world_size != 0: raise ValueError(f"Attention head count {attn_head_count} is not divisible by SP size {self.world_size}") if not (self.global_kv_head_count % self.world_size == 0 or self.world_size % self.global_kv_head_count == 0): raise ValueError( f"KV attention head count {self.global_kv_head_count} is not divisible by SP size {self.world_size} or" " vice versa") if self.seq_length_is_variable: # the self.required_*_shape depending on the following will get updated in `forward` # use 1 as a placeholder for dim=0 to keep torch.Size happy local_seq_length = 1 global_seq_length = 1 # [sl_l bs hc hs] self.required_query_shape = torch.Size([local_seq_length, batch_size, attn_head_count, attn_head_size]) self.required_key_value_shape = torch.Size([local_seq_length, batch_size, kv_head_count, attn_head_size]) # [sl bs em_l] self.required_context_shape = torch.Size( [global_seq_length, batch_size, attn_head_size * attn_head_count // self.world_size]) def _combine_local_sequences(self, query, key, value) -> Tuple[Tensor, Tensor, Tensor]: def combine_sequence(input, head_type): """ expects inputs in shape: [sl_l bs hc hs] returns output in shape: [sl bs hc_l hs] local_head_count could be different for k,v vs q if it's not an MHA situation """ if head_type == "q": local_head_count = self.local_q_head_count else: # kv local_head_count = self.local_kv_head_count # MQA and some GQA cases: if self.kv_replication_factor > 1: # local_head_count *= self.kv_replication_factor # replicate heads to the kv_replication_factor on hc dimension [sl_l bs hc hs] - so dim=2 input = input.repeat_interleave(self.kv_replication_factor, dim=2) # [sl_l bs hc hs] -> [sl_l bs ws hc_l hs] input = input.reshape( [self.local_seq_length, self.batch_size, self.world_size, local_head_count, self.attn_head_size]) input = rearrange(input, "sl_l bs ws hc_l hs -> ws sl_l bs hc_l hs").contiguous() output = _DimZeroAllToAll.apply(self.process_group, input) # [ws sl_l bs hc_l hs] -> [sl bs hc_l hs] output = output.reshape([self.global_seq_length, *output.shape[2:]]).contiguous() # [sl bs hc_l hs] return output return ( combine_sequence(query, head_type="q"), combine_sequence(key, head_type="kv"), combine_sequence(value, head_type="kv"), ) def _partition_global_sequence(self, input) -> Tensor: """ expects input in shape: [sl bs em_l] returns output in shape: [sl_l bs em] """ # [sl bs em_l] -> [ws sl_l bs em_l] input = input.reshape([ self.world_size, self.local_seq_length, self.batch_size, self.attn_head_size * self.attn_head_count // self.world_size, ]).contiguous() output = _DimZeroAllToAll.apply(self.process_group, input) output = rearrange(output, "ws sl_l bs em_l -> sl_l bs ws em_l") # [sl_l bs ws em_l] -> [sl_l bs em] output = output.reshape([*output.shape[:2], -1]).contiguous() # [sl_l bs em] return output def forward( self, module: torch.nn.Module, query: Tensor, key: Tensor, value: Tensor, attention_mask: Tensor, *args: Any, **kwargs: Any, ) -> Tensor: """forward Arguments: query (Tensor): query input to the layer key (Tensor): key input to the layer value (Tensor): value input to the layer attention_mask (Tensor): Attention mask args: other args Returns: * output (Tensor): context output """ # HF incoming shapes are: # [batch_size, num_heads, seqlen, head_size] # UlyssesSPAttentionHF expects: # [seqlen, batch_size, num_heads, head_size] # print_rank0(f"{query.shape=}") # print_rank0(f"{key.shape=}") # print_rank0(f"{value.shape=}") # print_rank0(f"{self.required_input_shape=}") # Skip SP operations during eval if disable_in_eval is True # This avoids issues with frameworks like HF Trainer that may run eval with different data distribution if not module.training and self.disable_in_eval: return self.attn(module, query, key, value, attention_mask, *args, **kwargs) if self.seq_length_is_variable: current_local_seq_length = query.shape[2] self.local_seq_length = current_local_seq_length self.global_seq_length = current_local_seq_length * self.world_size # update the required seqlen shapes self.required_query_shape = torch.Size([self.local_seq_length] + list(self.required_query_shape)[1:]) self.required_key_value_shape = torch.Size([self.local_seq_length] + list(self.required_key_value_shape)[1:]) self.required_context_shape = torch.Size([self.global_seq_length] + list(self.required_context_shape)[1:]) # make the blocks contiguous as early as possible to minimize fragmentation query = rearrange(query, "bs hc sl hs -> sl bs hc hs") # .contiguous() key = rearrange(key, "bs hc sl hs -> sl bs hc hs") # .contiguous() value = rearrange(value, "bs hc sl hs -> sl bs hc hs") # .contiguous() # core attn like FA2 expects an unsharded `position_ids` - without which packed samples # will return loss=nan. # # XXX: need to figure out if we can do the same for SDPA - as it doesn't require this and # wants an attention mask, so possibly doing this for FA2 only? # # Ideally we would passing the original unsharded position_ids - but we have no way to pass # it here as HF Transformers drops unexpected keys in `batch` - so either we need to stash # it somewhere in UlyssesSPDataLoaderAdapter and retrieve it here or we could gather it once # per batch and stash it inside `module` arg - I already have a machinery to figure out # which layer number is being called below in the skip_all_but_last_attention_debug_mode # code where rotating_layer_counter is used - so we could calculate it on the first layer # and re-use on the remaining layers if "position_ids" in kwargs: position_ids_list = [torch.empty_like(kwargs["position_ids"]) for _ in range(self.world_size)] dist.all_gather(position_ids_list, kwargs["position_ids"], group=self.process_group) kwargs["position_ids"] = torch.cat(position_ids_list, dim=1) # please don't remove the white-space vertical alignment in the error message assert query.shape == self.required_query_shape, ( f"[{dist.get_rank()}]: query input tensor does not match the required shape\n " f" {self.required_query_shape}:\n {query.shape=}\n {key.shape=}\n {value.shape=}") assert key.shape == value.shape == self.required_key_value_shape, ( f"[{dist.get_rank()}]: key or value input tensor does not match the required shape\n " f" {self.required_key_value_shape}:\n {query.shape=}\n {key.shape=}\n {value.shape=}") # expects: [sl_l bs hc hs] query_layer, key_layer, value_layer = self._combine_local_sequences(query, key, value) # returns: [sl bs hc_l hs] query_layer = rearrange(query_layer, "sl bs hc_l hs -> bs hc_l sl hs").contiguous() key_layer = rearrange(key_layer, "sl bs hc_l hs -> bs hc_l sl hs").contiguous() value_layer = rearrange(value_layer, "sl bs hc_l hs -> bs hc_l sl hs").contiguous() # crucial in the case of MQA and some GQA cases we need to fix `module.num_key_value_groups` # XXX: could move this somewhere to do it only once per run if self.kv_replication_factor > 1: module.num_key_value_groups = query_layer.size(-3) // key_layer.size(-3) if not self.skip_all_but_last_attention_debug_mode: # expects: [bs hc_l sl hs] context_layer, attn_weights = self.attn(module, query_layer, key_layer, value_layer, attention_mask, *args, **kwargs) # returns [bs sl hc_l hs] else: # we need this hack during development in order to be able to check memory fitting w/o # waiting for 3h to compute 1.5M seqlen attention, because it's quadratic in dense # attention, so we skip all but the last core attention call - we want the last one to # still get the memory usage approximately close to the real memory usage. of course # the loss will be wrong when we do that. self.rotating_layer_counter = (self.rotating_layer_counter + 1) % self.num_hidden_layers # we detect the last layer by module counting since we know how many layers there are if self.rotating_layer_counter % self.num_hidden_layers == 0: # do the real pass context_layer, attn_weights = self.attn(module, query_layer, key_layer, value_layer, attention_mask, *args, **kwargs) else: # this feeds bogus data of the right shape - good enough for quick debug context_layer = rearrange(query_layer, "bs hc_l sl ... -> bs sl hc_l ...") attn_weights = None # [bs sl hc_l hs] -> [sl bs hc_l hs]' context_layer = rearrange(context_layer, "bs sl ... -> sl bs ...") context_layer = context_layer.reshape([*context_layer.shape[:2], -1]) assert ( context_layer.shape == self.required_context_shape ), f"The context shape {context_layer.shape} is not of the expected shape {self.required_context_shape}" # expects: [sl bs em_l] output = self._partition_global_sequence(context_layer) # returns: [sl_l bs em] output = rearrange(output, "sl_l bs ... -> bs sl_l ...") output = output.reshape([*output.shape[:2], -1]) # expects [bs sl em] return output, attn_weights @classmethod def register_with_transformers( cls, model_name_or_path, core_attn_implementation, sequence_parallel_size, micro_batch_size, seq_length=None, seq_length_is_variable=True, disable_in_eval=False, # deprecated max_length=None, ): """ Register "ulysses" attn_implementation with HF transformers and return mpu (Megatron-LM-style parallel state groups object). If sequence_parallel_size==1 do nothing and return None. Args: - model_name_or_path (object or str): model object, or HF hub model name, or model's local path - core_attn_implementation (str): which attention to use: flash_attention_2 or flash_attention_3 or sdpa - sequence_parallel_size (int): sequence parallelism dimension (if 1 it's disabled) - micro_batch_size (int): micro batch size - seq_length (int): set this argument if the sequence length is fixed in all batches - seq_length_is_variable (bool): whether global seqlen may change between batches an optimization flag - the default is `True` - disable_in_eval (bool): whether to disable sequence parallelism during evaluation (default: False). When True, SP operations are bypassed during eval to avoid issues with frameworks like HF Trainer that may run eval with different data distribution. - max_length (int): actual global sequence length - this argument is deprecated - use `seq_length` instead """ if sequence_parallel_size == 1: return None if max_length is not None: logger.warning( "The 'max_length` argument is deprecated and will be eventually removed, please use `seq_length` instead" ) if seq_length is None and max_length is not None: seq_length = max_length if not seq_length_is_variable and seq_length is None: raise ValueError( "Either `seq_length_is_variable` needs to be `True` or `seq_length` needs to be set to an integer value of the fixed batch size length." ) from transformers import AutoConfig from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS import deepspeed.runtime.sequence_parallel.parallel_state_sp as mpu mpu.initialize_sequence_parallel(sequence_parallel_size=sequence_parallel_size) from transformers import PreTrainedModel if hasattr(model_name_or_path, "config") or isinstance(model_name_or_path, PreTrainedModel): # we already have the model (or a PEFT wrapper with config attribute) hf_model_config = model_name_or_path.config else: # if we don't have the model yet at this stage hf_model_config = AutoConfig.from_pretrained(model_name_or_path) supported_attn_implementation = ["flash_attention_2", "flash_attention_3", "sdpa"] if core_attn_implementation not in supported_attn_implementation: # notes on the excluded ones: # - eager: The problem is that `eager` wants an attention_mask and it creates the wrong attention mask it seems if we don't provide one - it's possible that we could somehow solve this, but it's also unlikely someone will want to use the slow eager attention with sequence parallelism # - flex_attention: haven't tried raise ValueError( f"{core_attn_implementation} attn_implementation isn't currently supported by Ulysses sequence" f" parallelism. Set core_attn_implementation arg to one of {supported_attn_implementation}.") if core_attn_implementation not in ALL_ATTENTION_FUNCTIONS: raise ValueError( f"{core_attn_implementation} is not a valid attn_implementation. The choices are {ALL_ATTENTION_FUNCTIONS.valid_keys()}" ) core_attn_function = ALL_ATTENTION_FUNCTIONS[core_attn_implementation] if seq_length_is_variable: local_seq_length = None global_seq_length = None else: local_seq_length = seq_length // mpu.get_sequence_parallel_world_size() global_seq_length = seq_length uattn = UlyssesSPAttentionHF( attn=core_attn_function, batch_size=micro_batch_size, attn_head_count=hf_model_config.num_attention_heads, attn_head_size=getattr(hf_model_config, "head_dim", hf_model_config.hidden_size // hf_model_config.num_attention_heads), kv_head_count=hf_model_config.num_key_value_heads, num_hidden_layers=hf_model_config.num_hidden_layers, process_group=mpu.get_sequence_parallel_group(), seq_length_is_variable=seq_length_is_variable, local_seq_length=local_seq_length, global_seq_length=global_seq_length, disable_in_eval=disable_in_eval, ) def uattn_wrapper( module: torch.nn.Module, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, attention_mask: torch.Tensor, *args, **kwargs, ) -> Tuple[torch.Tensor, torch.Tensor]: # We are relaying on position_ids for SP to work so attention_mask has to be None # the problem is that HF currently doesn't know anything about ALL_ATTENTION_FUNCTIONS["ulysses"] so it doesn't make a special case like for "flash_attention_2" and "sdpa" and it creates an attention mask on the fly and it breaks things. attention_mask = None attn_output, attn_weights = uattn( module, query, key, value, attention_mask, # XXX: fixme *args, **kwargs, ) return attn_output, attn_weights # We don't do: ALL_ATTENTION_FUNCTIONS.register("ulysses", uattn_wrapper) # The problem with this approach is that we are missing on all the special use cases in HF Transformers that do things like: if self.config._attn_implementation == "flash_attention_2": ... # So instead we hack `ALL_ATTENTION_FUNCTIONS` to override all existing keys with our implementation, since it only gets used at the point of calling the attention and that's what we want, all other code branches relying on the original core `attn_implementation` will still be executed. This is what we called "Being John Malkovich" for key in ALL_ATTENTION_FUNCTIONS.keys(): ALL_ATTENTION_FUNCTIONS[key] = uattn_wrapper return mpu class UlyssesSPDataLoaderAdapter: def __init__( self, dl: DataLoader, sp_rank: int, sp_group, sp_world_size, device, ): """ This a DataLoader adapter which wraps around any existing DataLoader. It is used in conjunction with Ulysses to perform batch sharding on the sequence dimension. It gathers 1 sample from each participating rank, using the DL it wraps, then shards each of them and sends back to the ranks. So that when dl->iter->next is called, we end up with: - rank 0: getting batch 0 shard 0 - rank 1: getting batch 0 shard 1 ... - rank n: getting batch 0 shard n which is used to compute the batch (from rank0) using all SP ranks. When the next iteration starts and dl->iter->next is called, we end up with: - rank 0: getting batch 1 shard 0 - rank 1: getting batch 1 shard 1 ... - rank n: getting batch 1 shard n which is used to compute a second batch (from rank1) using all SP ranks. This continues until SP iterations are performed. At this point we need to get more data and so the above repeats. The key thing to understand is that all SP ranks participate in processing a single DL sample. So instead of normal DataParallel we perform a sort of SP over DP. When SP number of iterations is completed it's an equivalent of performing a single iteration with normal DP. If more tokens need to be consumed per step use the gradient accumulation feature. Ulysses expects the following dict keys in each DL batch (`dl->iter->next`): - `input_ids` - `position_ids` - `labels` Additional entries can be present. The tensors are expected to be of shape: `[batch_size, seqlen, ...]` The sharding happens on the seqlen (1st) dimension for all tensors in the batch, any non-tensor entries get copied to all ranks. `attention_mask` isn't used by Ulysses, because it's typically too large when it's 4D, and position_ids is just 1D, therefore it's much much smaller and consumes little GPU memory. Arguments: - `dl`: an existing DataLoader object to wrap - `sp_rank`: SP rank - `sp_group`: SP group - `sp_world_size`: SP world size - `device`: cuda device Returns: Another DataLoader object """ self.dl = dl self.sp_rank = sp_rank self.sp_group = sp_group self.sp_world_size = sp_world_size self.device = device self.iter = iter(dl) self.micro_batches: deque[Any] = deque() def __len__(self): return len(self.dl) * self.sp_world_size def __iter__(self): return self def __next__(self): if len(self.micro_batches) == 0: self.refill() return self.micro_batches.popleft() def refill(self): # reset the iterator if StopIteration arrives, and re-raise it to allow multiple epochs to run try: batch = next(self.iter) except StopIteration: self.iter = iter(self.dl) raise StopIteration micro_batches = defaultdict(dict) # XXX: replace with more efficient all-to-all? # we have batches of variable seqlen so in order to do all_gather on batches - we need to know the exact length of each tensor on each rank seqlen = torch.tensor(batch["input_ids"].shape[1], dtype=torch.int64, device=self.device) seqlens = [torch.zeros(1, dtype=torch.int64, device=self.device) for _ in range(self.sp_world_size)] dist.all_gather(seqlens, seqlen, group=self.sp_group) seqlens = [x[0].item() for x in seqlens] for k in batch.keys(): if torch.is_tensor(batch[k]): batch[k] = batch[k].to(self.device) if seqlen != batch[k].shape[1]: raise ValueError( f"{k}'s shape {batch[k].shape} must match input_ids's shape {batch['input_ids'].shape}") with torch.no_grad(): tensor_list = [ torch.zeros((batch[k].shape[0], seqlens[i]), dtype=batch[k].dtype, device=batch[k].device) for i in range(self.sp_world_size) ] dist.all_gather(tensor_list, batch[k], group=self.sp_group) else: tensor_list = [None for _ in range(self.sp_world_size)] dist.all_gather_object(tensor_list, batch[k], group=self.sp_group) for rank, tensor in enumerate(tensor_list): micro_batches[rank][k] = tensor del tensor_list del batch for batch in micro_batches.values(): seq_length = len(batch["input_ids"][0]) if seq_length % self.sp_world_size != 0: raise ValueError(f"batch's seqlen={seq_length} isn't divisible by sp-size={self.sp_world_size}") chunk_len = seq_length // self.sp_world_size # because we have to gather logits from all sp ranks we have to do the loss function ourselves # therefore remove labels to avoid an attempt to calculate loss by transformers labels = batch.pop("labels") labels = torch.nn.functional.pad(labels, (0, 1), value=-100) batch["shift_labels"] = labels[..., 1:].contiguous() # free up temp memory del labels # batch sharding for k in batch.keys(): # leave non-tensors alone if not torch.is_tensor(batch[k]): continue # at seqlen>10M and 32+ gpus this can take GBs of memory so keep the prefill buffer on cpu batch[k] = batch[k][:, chunk_len * self.sp_rank:chunk_len * (self.sp_rank + 1)].cpu() self.micro_batches.append(batch) def sequence_tiled_compute( fn, seqlen, shards, kwargs_to_shard, kwargs_to_pass, grad_requiring_tensor_key, compute_params=None, output_unshard_dimension=1, output_reduction="mean", ): """ This is a wrapper for SequenceTiledCompute which we need since torch.autograd.Function can't work with dicts of tensors (in backward it has to return a grad value and not a dict that may have a non-None grad value). It's also useful for setting default values which we can't do either in torch.autograd.Function. Args: - `fn`: the function to call on sharded inputs - `seqlen`: total seqlen of the seqlen dimension - `shards`: how many shards to use - `kwargs_to_shard`: this dict will be passed to `fn` as `**kwargs` after sharding on seqlen dimension - `kwargs_to_pass`: this dict will be passed to `fn` as is, as `**kwargs` - `grad_requiring_tensor_key`: which main key requires grads - `compute_params`: a list of weights engaged in the compute. Default: `None` (only needed when using DeepSpeed ZeRO) - `output_reduction`: None, "mean" or "sum": Default: "mean" - `output_unshard_dimension`: the dimension to concat the outputs on: Default: 1 (seqlen dim) Returns: - unsharded output with an optional reduction applied, depending on the `output_reduction` value: `None` - return the unsharded output tensor `"mean"` - apply mean `"sum"` - apply sum Please note that this implementation doesn't require DeepSpeed and can work without it. `compute_params` can remain `None` in such a case. """ args_to_shard = kwargs_to_shard.values() keys_to_shard = list(kwargs_to_shard.keys()) args_to_pass = kwargs_to_pass.values() keys_to_pass = list(kwargs_to_pass.keys()) return SequenceTiledCompute.apply( fn, seqlen, shards, keys_to_shard, keys_to_pass, grad_requiring_tensor_key, compute_params, output_unshard_dimension, output_reduction, *args_to_shard, *args_to_pass, ) class SequenceTiledCompute(torch.autograd.Function): """ A generic autograd function to perform a tiled compute. Please note this module re-computes `forward` in the `backward`. So the `forward` occurs twice each iteration. And if you're using activation checkpointing it then occurs trice. Please note that this implementation doesn't require DeepSpeed and can work without it. `compute_params` can remain `None` in such a case. For an easier to understand example see TiledMLP - which is the same as this autograd function but without the generalization code. """ @staticmethod def forward( ctx, fn, seqlen, shards, keys_to_shard, keys_to_pass, grad_requiring_tensor_key, compute_params, output_unshard_dimension, output_reduction, *args, ) -> torch.Tensor: """ for args and return values see `sequence_tiled_compute`'s doc Currently we assume that all kwargs_to_shard values have a shape of `[bs, seqlen, ...]` and we shard on seqlen dimension """ ctx.fn = fn ctx.seqlen = seqlen ctx.shards = shards ctx.grad_requiring_tensor_key = grad_requiring_tensor_key ctx.compute_params = [p for p in compute_params if p.requires_grad] ctx.output_unshard_dimension = output_unshard_dimension ctx.output_reduction = output_reduction with torch.no_grad(): args = list(args) ctx.total_args = len(args) ctx.grad_requiring_tensor_key_index = (keys_to_shard + keys_to_pass).index(grad_requiring_tensor_key) kwargs_to_shard = {k: args.pop(0) for k in keys_to_shard} kwargs_to_pass = {k: args.pop(0) for k in keys_to_pass} ctx.kwargs_to_shard = kwargs_to_shard ctx.kwargs_to_pass = kwargs_to_pass with torch.no_grad(): shard_step = math.ceil(seqlen / shards) output_shards = [] for i in range(shards): output = fn( **{ k: v[:, i * shard_step:(i + 1) * shard_step] for k, v in kwargs_to_shard.items() }, **kwargs_to_pass, ) output_shards.append(output) if output_unshard_dimension == 0: # this is just the shape=[1] loss use-case, not sure if it's generic enough output_unsharded = torch.cat([l.unsqueeze(0) for l in output_shards], dim=output_unshard_dimension) else: output_unsharded = torch.cat(output_shards, dim=output_unshard_dimension) # .clone().detach() if output_reduction is None: return output_unsharded elif output_reduction == "mean": return output_unsharded.mean() elif output_reduction == "sum": return output_unsharded.sum() else: raise ValueError(f"unknown value {output_reduction}: valid values are: none/mean/sum") @staticmethod def backward(ctx, *grads) -> torch.Tensor: fn = ctx.fn shards = ctx.shards kwargs_to_shard = ctx.kwargs_to_shard kwargs_to_pass = ctx.kwargs_to_pass output_reduction = ctx.output_reduction grad_requiring_tensor_key = ctx.grad_requiring_tensor_key grad_requiring_tensor_key_index = ctx.grad_requiring_tensor_key_index compute_params = ctx.compute_params output_unshard_dimension = ctx.output_unshard_dimension grad_requiring_tensor = kwargs_to_shard[grad_requiring_tensor_key] grad_requiring_tensor_requires_grad = grad_requiring_tensor.requires_grad grad_requiring_tensor = grad_requiring_tensor.detach() # detach() unsets `grad_requiring_tensor.requires_grad`, so restore it grad_requiring_tensor.requires_grad_(grad_requiring_tensor_requires_grad) incoming_grad = grads[0] # since we perform a reduction of outputs that doesn't get included in `autograd.backward` below we need to pre-adjust the incoming gradient. in the case of "sum" the gradient is 1.0, in the case of "mean" it's 1.0/num_elements, which in this case is 1/shards. if output_reduction == "mean": incoming_grad /= shards if grad_requiring_tensor.shape[0] == 1: grad_requiring_tensor_grad = torch.zeros_like(grad_requiring_tensor) else: grad_requiring_tensor_grad = torch.empty_like(grad_requiring_tensor) kwargs_to_shard_shards = {k: list(torch.chunk(v, chunks=shards, dim=1)) for k, v in kwargs_to_shard.items()} for i in range(shards): # when fn involves one or more model weights deepspeed will normally push a grad to # reduce per sub-module call, so since we only want it to add a grad for the last # shard's call, we signal to ZeRO not to add new gradients to reduce until the last # shard when all gradients have been accumulated. An example for such a call is # `model.lm_head(hidden_states)` if compute_params is not None: if i + 1 < shards: for param in compute_params: param.ds_grad_is_ready = False else: # last shard, can add the grad for param in compute_params: param.ds_grad_is_ready = True kwargs_to_shard_shard = {k: v[i] for k, v in kwargs_to_shard_shards.items()} grad_requiring_tensor_shard = kwargs_to_shard_shard[grad_requiring_tensor_key] grad_requiring_tensor_shard.requires_grad_(grad_requiring_tensor_requires_grad) # if seqlen is not exactly divisible by shards the last step will be shorter than shard_step shard_step = kwargs_to_shard_shards[grad_requiring_tensor_key][i].shape[1] shard_offset = i * kwargs_to_shard_shards[grad_requiring_tensor_key][0].shape[1] if grad_requiring_tensor.shape[0] == 1: # on narrow the shard's stride is unaffected with dim0==1 (bs) so we use the most efficient `narrow` alias: # this will enable gradual population of the pre-allocated # `grad_requiring_tensor_shard.grad` during `torch.autograd.backward` calls grad_requiring_tensor_shard.grad = grad_requiring_tensor_grad.narrow( 1, shard_offset, shard_step).view_as(grad_requiring_tensor_shard) with torch.enable_grad(): output = fn(**kwargs_to_shard_shard, **kwargs_to_pass) if output_unshard_dimension == 0: # loss use-case torch.autograd.backward(output, incoming_grad) else: incoming_grad_shard = (incoming_grad.narrow(1, shard_offset, shard_step).view_as(grad_requiring_tensor_shard)) torch.autograd.backward(output, incoming_grad_shard) if grad_requiring_tensor.shape[0] > 1: # this is less efficient than dim0==1 (bs) use case, due to a required copy to fix # the stride and needing a bit more memory for one shard's grad, since # narrow(dim=1, ...) while dim0>1 will lead to: # UserWarning: grad and param do not obey the gradient layout contract. This is not an error, but may impair performance. # when backward is called. grad_requiring_tensor_grad.narrow(1, shard_offset, shard_step).view_as(grad_requiring_tensor_shard).copy_( grad_requiring_tensor_shard.grad) # positional args grad_outputs = [None] * 9 # inject the grad for the position of forward input that is grad-requiring arg_outputs = [None] * ctx.total_args arg_outputs[grad_requiring_tensor_key_index] = grad_requiring_tensor_grad return tuple(grad_outputs + arg_outputs) class TiledMLP(torch.autograd.Function): """ Perform a tiled MLP computation to massively reduce memory usage needed to compute MLP when using very long sequence lengths. Please note this module re-computes `forward` in the `backward`. So the `forward` occurs twice each iteration. And if you're using activation checkpointing it then occurs trice. For a general tiled compute implementation that can handle any `forward` see `SequenceTiledCompute`. Args: - fn: the function to call on sharded inputs - `self`: the MLP nn.Module object - `x`: the input to MLP.forward (`hidden_states`) - `shards`: how many shards to use - compute_params: a list of weights engaged in the compute Default: `None` (only needed when using DeepSpeed ZeRO) Returns: - the computed `hidden_states` Here is an example that monkey patches HF Transformers' LLamaMLP: def tiled_mlp_forward(self, x): bs, seqlen, hidden = x.shape num_shards = math.ceil(seqlen / hidden) # to avoid deadlocks get all ranks to agree on the same num_shards by using the max value tensor = torch.tensor(num_shards, device=x.device) dist.all_reduce(tensor, op=dist.ReduceOp.MAX) num_shards = tensor.item() compute_params = [self.down_proj.weight, self.gate_proj.weight, self.up_proj.weight] def mlp_forward(self, x): return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x)) return TiledMLP.apply( mlp_forward, self, x, num_shards, compute_params, ) # this needs to be done before the model is instantiated from transformers.models.llama import modeling_llama modeling_llama.LlamaMLP.forward = tiled_mlp_forward """ @staticmethod def forward( ctx, fn, self, x, shards, compute_params, ) -> torch.Tensor: ctx.fn = fn ctx.self = self ctx.shards = shards ctx.compute_params = [p for p in compute_params if p.requires_grad] ctx.save_for_backward(x) # x.shape could be [bs, seqlen, hidden_size] or [seqlen, hidden_size] (moe experts) x_shards = list(torch.chunk(x, chunks=shards, dim=-2)) with torch.no_grad(): output_shards = [fn(self, x_shard) for x_shard in x_shards] output_unsharded = torch.cat(output_shards, dim=-2) return output_unsharded @staticmethod def backward(ctx, *grads) -> torch.Tensor: fn = ctx.fn (x, ) = ctx.saved_tensors self = ctx.self shards = ctx.shards compute_params = ctx.compute_params x_requires_grad = x.requires_grad x = x.detach() # detach() unsets `x.requires_grad`, so restore it x.requires_grad_(x_requires_grad) # x.shape could be [bs, seqlen, hidden_size] or [seqlen, hidden_size] (moe experts) hidden_size = x.shape[-1] x_shape_orig = x.shape # flatten bs+seqlen to avoid having stride issues when narrowing into seqlen w/ bs>1 x = x.view(-1, hidden_size) incoming_grad = grads[0].view(-1, hidden_size) x_grad = torch.zeros_like(x) x_shards = list(torch.chunk(x, chunks=shards, dim=0)) for i, x_shard in enumerate(x_shards): # Tell deepspeed not to add a new grad to its ipg bucket until the last shard is run # XXX: DDP, FSDP will need something similar to make it work if compute_params is not None: if i + 1 < shards: for param in compute_params: param.ds_grad_is_ready = False else: # last shard, can add the grad for param in compute_params: param.ds_grad_is_ready = True x_shard.requires_grad_(x_requires_grad) # if seqlen is not exactly divisible by shards the last step will be shorter than shard_step shard_step = x_shards[i].shape[0] shard_offset = i * x_shards[0].shape[0] x_shard.grad = x_grad.narrow(0, shard_offset, shard_step).view_as(x_shard) incoming_grad_shard = incoming_grad.narrow(0, shard_offset, shard_step).view_as(x_shard) with torch.enable_grad(): output = fn(self, x_shard) torch.autograd.backward(output, incoming_grad_shard) # unflatten x_grad = x_grad.view(x_shape_orig) return (None, None, x_grad, None, None) class TiledFusedLogitsLoss(torch.autograd.Function): """ Perform a tiled loss computation while not manifesting a full logits tensor to massively reduce memory usage. Args: - fn: the function to call on sharded inputs - `self`: the lm_head module object, often it will be `unwrapped_model.model.lm_head` - `x`: the input (typically `hidden_states`) - which gets sharded - `y`: the target (typically `labels` or `shift_labels`) - which gets sharded. - `mask`: an optional mask. It will be not passed to the `fn` if set to `None`. If not-`None` it'll be sharded with `x` and `y` - `shards`: how many shards to use - compute_params: a list of weights engaged in the compute Default: `None` (only needed when using DeepSpeed ZeRO) - output_reduction: "mean" or "sum". If the unmasked elements in `x` are of different sizes in different shards, it's recommended to use "sum" instead of "mean" and perform the balanced mean to the output. This would be the case if `x` is not evenly divisible by `shards` or if the mask may lead to a different number of unmasked elements. Returns: - the computed `loss` Note, that since this autograd function is typically the last one in the call stack, it performs `backward` inside `forward` and compensates for `output_reduction` artificially. This removes the need to re-run `forward` a second time inside `backward` For a generic tiled compute implementation that can handle many other types of `forward` see `SequenceTiledCompute`. An example: def loss_fn(self, x, y): logits = self.lm_head(x) return self.cross_entropy_loss(logits.view(-1, self.vocab_size), y.view(-1)) x = hidden_states y = shift_labels mask = None shards = 2 compute_params = [self.lm_head.weight] output_reduction = "mean" loss = TiledFusedLogitsLoss.apply( loss_fn, self, x, y, mask, shards, compute_params, output_reduction, ) """ @staticmethod def forward( ctx, fn, self, x, y, mask, shards, compute_params, output_reduction, ) -> torch.Tensor: if output_reduction not in ["mean", "sum"]: raise ValueError(f'unknown reduction {output_reduction}: valid values are: "mean"/"sum"') if x.dim() < 2: raise ValueError("x must be at least 2D [batch_size, seq_len, ...]") if y.dim() < 2: raise ValueError("y must be at least 2D [batch_size, seq_len, ...]") if x.shape[:2] != y.shape[:2]: raise ValueError("x and y batch/seq dims must match") if mask is not None: if mask.dim() != 2: raise ValueError(f"mask must be 2D [batch_size, seq_len], but got {mask.dim()}") if mask.shape != x.shape[:2]: raise ValueError(f"mask shape must match x and y batch/seq") compute_params = [p for p in compute_params if p.requires_grad] x_requires_grad = x.requires_grad x = x.detach().requires_grad_(x_requires_grad) bs, seqlen = x.shape[:2] # flatten bs+seqlen to avoid having stride issues when narrowing into seqlen w/ bs>1 x = x.view(-1, *x.shape[2:]) y = y.view(-1, *y.shape[2:]) if mask is not None: mask = mask.view(-1) incoming_grad = torch.tensor(1.0, dtype=x.dtype, device=x.device) # we are faking the incoming gradient, and since we perform a reduction outside of `autograd.backward` below we need to pre-adjust the incoming gradient. in the case of "sum" the gradient is 1.0, in the case of "mean" it's 1.0/num_elements, which in this case is 1/shards. if output_reduction == "mean": incoming_grad /= shards # XXX: deal with the use case of running in inference mode, where we don't need backward x_grad = torch.zeros_like(x) if x_requires_grad else None x_shards = list(torch.chunk(x, chunks=shards, dim=0)) y_shards = list(torch.chunk(y, chunks=shards, dim=0)) if mask is not None: mask_shards = list(torch.chunk(mask, chunks=shards, dim=0)) output_shards = [] for i, (x_shard, y_shard) in enumerate(zip(x_shards, y_shards)): # Tell deepspeed not to add a new grad to its ipg bucket until the last shard is run # XXX: DDP, FSDP will need something similar to make it work if compute_params is not None: if i + 1 < shards: for param in compute_params: param.ds_grad_is_ready = False else: # last shard, can add the grad for param in compute_params: param.ds_grad_is_ready = True x_shard.requires_grad_(x_requires_grad) # if seqlen is not exactly divisible by shards the last step will be shorter than shard_step shard_step = x_shards[i].shape[0] shard_offset = i * x_shards[0].shape[0] args = (self, x_shard, y_shard) if mask is not None: args += (mask_shards[i], ) if x_grad is not None: x_shard.grad = x_grad.narrow(0, shard_offset, shard_step).view_as(x_shard) with torch.enable_grad(): output = fn(*args) output_shards.append(output) torch.autograd.backward(output, incoming_grad) else: output = fn(*args) output_shards.append(output) output_unsharded = torch.cat([l.unsqueeze(0) for l in output_shards], dim=0) if output_reduction == "mean": output = output_unsharded.mean() elif output_reduction == "sum": output = output_unsharded.sum() # unflatten if x_grad is not None: x_grad = x_grad.view(bs, seqlen, *x_grad.shape[1:]) ctx.save_for_backward(x_grad.detach()) return output @staticmethod def backward(ctx, *grads) -> torch.Tensor: (x_grad, ) = ctx.saved_tensors # grads[0] should normally be 1.0 as it should be coming from loss.backward() if grads[0] != 1.0: x_grad *= grads[0] return (None, None, x_grad, None, None, None, None, None, None) class AutogradComputeMLP(torch.autograd.Function): """ This is a simplified example to override the normal MLP via an autograd function - then tiling can be added - this simplified version was useful to detect a leak in Deepspeed, so let's keep it. Here is an example of performing the monkey patching on LlamaMLP def mlp_forward_new(self, x): def mlp_forward(self, x): return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x)) return AutogradComputeMLP.apply(mlp_forward, self, x) from transformers.models.llama import modeling_llama modeling_llama.LlamaMLP.forward = mlp_forward_new """ @staticmethod def forward( ctx, fn, self, x, ) -> torch.Tensor: ctx.fn = fn ctx.self = self ctx.save_for_backward(x) with torch.no_grad(): return fn(self, x) @staticmethod def backward(ctx, *grads) -> torch.Tensor: fn = ctx.fn (x, ) = ctx.saved_tensors self = ctx.self x1 = x.detach() x1.requires_grad = x.requires_grad with torch.enable_grad(): output = fn(self, x1) torch.autograd.backward(output, grads[0]) return (None, None, x1.grad, None) ########################################################### ### below are older versions that some might still want ### ########################################################### class TiledLoss(torch.autograd.Function): @staticmethod def forward(ctx, loss_fn, logits, vocab_size, shift_labels, shards) -> torch.Tensor: """ This is a memory efficient loss autograd function that takes the existing logits and performs loss calculation in shards. This one is an SFT-aware version, therefore it takes care of special cases where the whole shard is made of -100 labels and which requires then a special care. Note: logits seqlen dimension doesn't have to be divisible by shards, the last shard will be shorter than the rest. The calculating of the number of shards is in the example. Here is an example of using it: def loss(self, batch) -> torch.Tensor: batch = to_device(batch, self.device) shift_labels = batch.pop("shift_labels") outputs = self.model(**batch, use_cache=False) logits = outputs.logits if all((shift_labels == -100).squeeze()): # this is the case where all labels in a micro-batch are -100 (very common for SFT if the seqlen is short) - CE returns `nan` in this case, so we don't want to call loss and instead create a differentiable loss `0` which will also set all the grads to `0` in `backward` - the effect of this is akin to a perfect score where the model needs no adjustment since grads will be all zeros. loss = (logits.sum() * 0.0).float() num_shards: Any = "auto" if num_shards == "auto": # parameterize to about 1GB fp32 logits shards slice_size_in_gb = 1 size_in_gb = logits.numel() * 4 / 2**30 # fp32 # the sp shard's seqlen sp shard can be easily not divisible by the derived number of chunked loss shards, so we use the uppper ceiling and allow the last chunk to be shorter than the rest num_shards = math.ceil(size_in_gb / slice_size_in_gb) # print(f"derived {num_shards} shards for size {size_in_gb}GB") if num_shards > 1: # if shards == 1 this will lead to a higher memory usage then calling the normal loss function, so don't do that. loss = TiledLoss.apply( self.model_unwrapped.loss_function, logits, self.model_unwrapped.config.vocab_size, shift_labels, num_shards, ) else: loss = self.model_unwrapped.loss_function( logits=logits, labels=None, vocab_size=self.model_unwrapped.config.vocab_size, shift_labels=shift_labels, ) return loss """ ctx.save_for_backward(logits, shift_labels) ctx.loss_fn = loss_fn ctx.vocab_size = vocab_size ctx.shards = shards with torch.no_grad(): seqlen = shift_labels.shape[1] shard_step = math.ceil(seqlen / shards) loss_shards = [] total_good_items = 0 # since -100s are ignored we have to perform a weighted average on each loss slice as each slice may contribute a different number of non- -100 labels # if seqlen / shards != 0 - the last chunk is just shorter than the rest but no data is ignored for i in range(shards): # XXX: here and everywhere don't make a copy, pass the slice or perhaps narrow/view? shift_labels_shard = shift_labels[:, i * shard_step:(i + 1) * shard_step] if all((shift_labels_shard == -100).squeeze()): continue # ignore this shard loss_shard = loss_fn( logits=logits[:, i * shard_step:(i + 1) * shard_step, :], labels=None, vocab_size=vocab_size, shift_labels=shift_labels_shard, ) good_items = sum((shift_labels_shard != -100).squeeze()) loss_shards.append(loss_shard * good_items) total_good_items += good_items total_loss = torch.cat([l.unsqueeze(0) for l in loss_shards], dim=0).sum() weighted_loss = total_loss / total_good_items return weighted_loss @staticmethod def backward(ctx, *grads) -> torch.Tensor: logits, shift_labels = ctx.saved_tensors loss_fn = ctx.loss_fn vocab_size = ctx.vocab_size shards = ctx.shards grad = grads[0] logits_grad = torch.zeros_like(logits) logits_shards = list(torch.chunk(logits, chunks=shards, dim=1)) shift_labels_shards = list(torch.chunk(shift_labels, chunks=shards, dim=1)) # if seqlen is not exactly divisible by shards the last step will be shorter than shard_step shard_step = logits_shards[0].shape[1] for i in range(shards): logits_shard = logits_shards.pop(0) shift_labels_shard = shift_labels_shards.pop(0) shard_offset = i * shard_step # this will enable gradual population of the pre-allocated `logits_shard.grad` during `torch.autograd.backward` calls logits_shard.grad = (logits_grad.narrow(1, shard_offset, shard_step).view_as(logits_shard)) with torch.enable_grad(): if all((shift_labels_shard == -100).squeeze()): # fake loss calculation, since CE will return nan, but grads will be set # a normal loss_fn upcasts logits to float so match it loss_shard = (logits_shard.sum() * 0.0).float() else: loss_shard = loss_fn( logits=logits_shard.requires_grad_(), labels=None, vocab_size=vocab_size, shift_labels=shift_labels_shard, ) torch.autograd.backward(loss_shard, grad) logits_grad /= shards # only logits (2nd arg) needs grads return None, logits_grad, None, None, None # This is the original implementation/integration of UlyssesSP into the training loop, which was superseded by using UlyssesSPDataLoaderAdapter which did all the sharding and pull the shards from the DL # # There are 2 issues with this implementation: # - it's complex and difficult to integrate into various training scenarios # - it could lead to a huge number of tokens per step - e.g. 32 ranks of 15M seqlen -> 0.5B token step - which is very wasteful # # Therefore if you want to use UlyssesSP via UlyssesSPFwdLossBwdWithLogits with its fwd/loss/bwd for those don't want to use UlyssesSPDataLoaderAdapter - here is how it should be installed into the sub-trainer class: # class SFTTrainer(Trainer): # def sp_fwd_loss_bwd(self, batch) -> torch.Tensor: # batch = to_device(batch, self.device) # # from arctic_training.trainer.trainer import UlyssesAttentionHFFwdLossBwdWithLogits # ulysses = UlyssesAttentionHFFwdLossBwdWithLogits( # model=self.model, # model_unwrapped=self.model_unwrapped, # device=self.device, # num_loss_logit_shards="auto", # ) # return ulysses.sp_fwd_loss_bwd(batch) class UlyssesSPFwdLossBwdWithLogits: def __init__(self, model, model_unwrapped, device, num_loss_logit_shards="auto", **kwargs): self.model = model self.model_unwrapped = model_unwrapped self.device = device self.num_loss_logit_shards = num_loss_logit_shards self.kwargs = kwargs from deepspeed.utils import groups self.sp_group = groups._get_sequence_parallel_group() self.sp_world_size = groups._get_sequence_parallel_world_size() self.sp_rank = groups._get_sequence_parallel_rank() def sp_fwd_loss_bwd(self, batch) -> torch.Tensor: see_memory_usage("entered sp_fwd_loss_bwd", force=True) # ensure shapes are correct if not (batch["input_ids"].shape == batch["position_ids"].shape == batch["labels"].shape): raise ValueError( f'Borked batch {batch["input_ids"].shape=} != {batch["position_ids"].shape=} !=' f' {batch["labels"].shape=}) in DataLoader->iter->next, cannot continue with Ulysses Sequence' " parallelism") # gather DL batches into super-batches # Important: DL doesn't always yield max_length batches. Different ranks may have different seqlen and each could be <= max_length (but always divisible by 256) micro_batches: list[Any] = defaultdict(dict) # Efficient gathering of batch inputs across ranks: # The problem is that our DL doesn't guarantee the same seqlen on all ranks and may give, 3x 1024 and 1x 768 on 4 gpus for max_length 1024. so 3 options we have to be able to gather batches are: # 1. use all_gather_object - which allows different shapes - but potentially introducing an undesired overhead - 2x pickle calls # 2. use all_gather and change DL pad to make sure that all ranks always get the same input shape - this creates its own overhead since if we say have ranks with seqlen 512, 768, 1024, 1024 - now we will need to process 4x 1024 seqlens # 3. use all_gather and post gathering truncate tensors to their intended length - another overhead of allocating and truncating tensors # using approach (1) for now but might want to benchmark later the other 2 approaches # XXX: if using all_gather_object we can gather the whole batch at once and not per-key! so can drop the loop for that approach # we have batches of variable seqlen so in order to do all_gather on batches - we need to know the exact length of each tensor on each rank seqlen = torch.tensor(batch["input_ids"].shape[1], dtype=torch.int64, device=self.device) # print(seqlen) seqlens = [torch.zeros(1, dtype=torch.int64, device=self.device) for _ in range(self.sp_world_size)] dist.all_gather(seqlens, seqlen, group=self.sp_group) seqlens = [x[0].item() for x in seqlens] for k in batch.keys(): batch[k] = batch[k].to(self.device) with torch.no_grad(): tensor_list = [ torch.zeros((batch[k].shape[0], seqlens[i]), dtype=batch[k].dtype, device=batch[k].device) for i in range(self.sp_world_size) ] dist.all_gather(tensor_list, batch[k], group=self.sp_group) # gathering on the data dimension # will be concatenating and later splitting again for the more general case # batch[k] = torch.cat(tensor_list, dim=1) for rank, tensor in enumerate(tensor_list): micro_batches[rank][k] = tensor del tensor_list del batch # we need to chunk twice - each time on SP size level # - the first time is because we artificially made the seqlen SP-times longer # - the second time is because of the Ulysses algorithm see_memory_usage("after gathering", force=False) self.model.set_gradient_accumulation_boundary(False) losses = [] for sub_step_id in range(self.sp_world_size): batch = micro_batches[sub_step_id] seq_length = len(batch["input_ids"][0]) if seq_length % self.sp_world_size != 0: raise ValueError( f"{sub_step_id=}: batch's seqlen={seq_length} isn't divisible by sp-size={self.sp_world_size}") chunk_len = int(seq_length / self.sp_world_size) # to enable the correct mean calculation across shards before sharding the micro batch: # 1. count the number of non- `-100`` elements per shard # 2. and subtract one more element because of label shifting non_skipped_items = {} for rank in range(self.sp_world_size): non_skipped = (batch["labels"][:, chunk_len * rank:chunk_len * (rank + 1)] != -100).sum().item() if non_skipped > 1: non_skipped -= 1 non_skipped_items[rank] = non_skipped # because we have to gather logits from all sp ranks we have to do the loss function ourselves # therefore remove labels to avoid an attempt to calculate loss by transformers labels = batch.pop("labels") labels = torch.nn.functional.pad(labels, (0, 1), value=-100) batch["shift_labels"] = labels[..., 1:].contiguous() # free up temp memory del labels # batch sharding for k in batch.keys(): batch[k] = batch[k][:, chunk_len * self.sp_rank:chunk_len * (self.sp_rank + 1)].to(self.device) shift_labels = batch.pop("shift_labels") outputs = self.forward(batch) loss = self.compute_loss(labels=None, shift_labels=shift_labels) # free up temp mem (e.g. outputs.logits are huge) del outputs # differentiable loss aggregation across ranks losses_per_rank = torch.distributed.nn.functional.all_gather(loss, group=self.sp_group) # since each shard may have a variable number of skipped elemented - need to calculate a weighted mean depending on each rank's contribution - this will also take care of loss=0 when all elements are -100 in a shard # XXX: not expecting a total of 0-non-skipped items for div loss = sum(losses_per_rank[rank] * non_skipped_items[rank] for rank in range(self.sp_world_size)) / sum(non_skipped_items.values()) self.backward() losses.append(loss.detach().item()) self.model.set_gradient_accumulation_boundary(True) # for per-iteration reporting if len(losses) == 0: loss = float("nan") else: loss = sum(losses) / len(losses) return loss def forward(self, batch): # critical: the labels shouldn't be in batch outputs = self.model(**batch, use_cache=False) self.logits = outputs.logits return outputs def compute_loss(self, labels, shift_labels): if all((shift_labels == -100).squeeze()): # this is the case where all labels in a micro-batch are -100 (very common for SFT) - CE returns `nan` in this case, so we don't want to call loss and instead create a differentiable loss `0` which will also set all the grads to `0` in `backward` - the effect of this is akin to a perfect score where the model needs no adjustment since grads will be all zeros. # XXX: should this be float and not the original dtype? loss = (self.logits.sum() * 0.0).float() else: if self.num_loss_logit_shards == "auto": # parameterize to about 1GB fp32 logits shards slice_size_in_gb = 1 # XXX: make configurable? size_in_gb = self.logits.numel() * 4 / 2**30 # fp32 # the sp shard's seqlen sp shard can be easily not divisible by the derived number of chunked loss shards, so we use the uppper ceiling and allow the last chunk to be shorter than the rest self.num_loss_logit_shards = math.ceil(size_in_gb / slice_size_in_gb) # print(f"derived {self.num_loss_logit_shards} shards for size {size_in_gb}GB") if self.num_loss_logit_shards > 1: loss = TiledLoss.apply( self.model_unwrapped.loss_function, self.logits, self.model_unwrapped.config.vocab_size, shift_labels, self.num_loss_logit_shards, ) else: # XXX: for some reason this fails with zero1 loss = self.model_unwrapped.loss_function( logits=self.logits, labels=None, vocab_size=self.model_unwrapped.config.vocab_size, shift_labels=shift_labels, ) self.loss = loss return loss def backward(self): self.model.backward(self.loss)
{ "repo_id": "deepspeedai/DeepSpeed", "file_path": "deepspeed/runtime/sequence_parallel/ulysses_sp.py", "license": "Apache License 2.0", "lines": 1227, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
license
deepspeedai/DeepSpeed:tests/unit/runtime/zero/test_zero_grad_clip.py
# Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: Apache-2.0 # DeepSpeed Team import torch import pytest import deepspeed from deepspeed.runtime.zero.stage3 import DeepSpeedZeroOptimizer_Stage3 from deepspeed.utils import safe_get_local_grad, safe_set_local_grad from deepspeed.accelerator import get_accelerator from unit.simple_model import SimpleModel import os def get_config(precision, clip_value, offload_device="cpu"): config = { "train_batch_size": 8, "steps_per_print": 1, "optimizer": { "type": "Adam", "params": { "lr": 1e-4 } }, "zero_optimization": { "stage": 3, "offload_optimizer": { "device": offload_device }, "contiguous_gradients": True, "overlap_comm": False, }, "gradient_clipping": 1.0, } if precision == "fp16": config["fp16"] = { "enabled": True, "loss_scale": 1024, "initial_scale_power": 10, } elif precision == "bf16": config["bf16"] = { "enabled": True, } return config @pytest.mark.parametrize("precision,clip_value,offload_device", [ ("fp16", 0.5, "cpu"), ("bf16", 0.05, "cpu"), ("fp16", 0.5, "none"), ("bf16", 0.05, "none"), ]) class TestZeroGradClip(): world_size = 1 def test_grad_clip_and_norm_update(self, precision, clip_value, offload_device): """Test custom gradient clipping with configurations and to check if the norm_groups are updated correctly""" config_dict = get_config(precision, clip_value, offload_device) model = SimpleModel(hidden_dim=10) # Set up distributed environment variables os.environ['LOCAL_RANK'] = '0' os.environ['RANK'] = '0' os.environ['WORLD_SIZE'] = '1' os.environ['MASTER_ADDR'] = '127.0.0.1' os.environ['MASTER_PORT'] = '29500' try: model_engine, optimizer, _, _ = deepspeed.initialize(args=None, model=model, config=config_dict, model_parameters=model.parameters(), dist_init_required=True) except Exception as e: pytest.skip("Could not initialize deepspeed") assert isinstance(optimizer, DeepSpeedZeroOptimizer_Stage3) torch.manual_seed(1670) inputs = torch.randn(8, 10, device=model_engine.device) targets = torch.randn(8, 10, device=model_engine.device) if model_engine.fp16_enabled() and get_accelerator().is_fp16_supported(): inputs = inputs.half() targets = targets.half() elif model_engine.bfloat16_enabled() and get_accelerator().is_bf16_supported(): inputs = inputs.bfloat16() targets = targets.bfloat16() else: pytest.skip("Unsupported precision") loss = model_engine(inputs, targets) model_engine.backward(loss) pre_clip_norm_groups = optimizer._get_norm_groups() pre_clip_global_norm = torch.linalg.vector_norm(torch.stack(pre_clip_norm_groups)) modified_count = 0 for param in model_engine.parameters(): if not hasattr(param, 'ds_id'): continue grad = safe_get_local_grad(param) if grad is not None: pre_clip_norm = grad.norm().item() clamped_grad = torch.clamp(grad, -clip_value, clip_value) post_clip_norm = clamped_grad.norm().item() if pre_clip_norm > clip_value: # Checks if the post-clip norm is less than the pre-clip norm assert post_clip_norm < pre_clip_norm, f"Post-clip norm should be < pre-clip norm for param {param.ds_id}" safe_set_local_grad(param, clamped_grad) modified_count += 1 # Get post-clip state post_clip_norm_groups = optimizer._get_norm_groups() post_clip_global_norm = torch.linalg.vector_norm(torch.stack(post_clip_norm_groups)) assert modified_count > 0, "No parameters were modified during clipping" assert post_clip_global_norm.item() < pre_clip_global_norm.item( ), f"Post-clip norm {post_clip_global_norm.item():.6f} should be < pre-clip norm {pre_clip_global_norm.item():.6f}" model_engine.step() final_norm = optimizer._global_grad_norm if pre_clip_global_norm.item() > clip_value: assert post_clip_global_norm.item() < pre_clip_global_norm.item( ), "Global norm should be reduced after clipping when pre-clip norm > clip_value"
{ "repo_id": "deepspeedai/DeepSpeed", "file_path": "tests/unit/runtime/zero/test_zero_grad_clip.py", "license": "Apache License 2.0", "lines": 109, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
dgtlmoon/changedetection.io:changedetectionio/api/Spec.py
import functools from flask import make_response from flask_restful import Resource @functools.cache def _get_spec_yaml(): """Build and cache the merged spec as a YAML string (only serialized once per process).""" import yaml from changedetectionio.api import build_merged_spec_dict return yaml.dump(build_merged_spec_dict(), default_flow_style=False, allow_unicode=True) class Spec(Resource): def get(self): """Return the merged OpenAPI spec including all registered processor extensions.""" return make_response( _get_spec_yaml(), 200, {'Content-Type': 'application/yaml'} )
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/api/Spec.py", "license": "Apache License 2.0", "lines": 17, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
dgtlmoon/changedetection.io:changedetectionio/blueprint/backups/restore.py
import io import json import os import shutil import tempfile import threading import zipfile from flask import Blueprint, render_template, flash, url_for, redirect, request from flask_babel import gettext, lazy_gettext as _l from wtforms import Form, BooleanField, SubmitField from flask_wtf.file import FileField, FileAllowed from loguru import logger from changedetectionio.flask_app import login_optionally_required class RestoreForm(Form): zip_file = FileField(_l('Backup zip file'), validators=[ FileAllowed(['zip'], _l('Must be a .zip backup file!')) ]) include_groups = BooleanField(_l('Include groups'), default=True) include_groups_replace_existing = BooleanField(_l('Replace existing groups of the same UUID'), default=True) include_watches = BooleanField(_l('Include watches'), default=True) include_watches_replace_existing = BooleanField(_l('Replace existing watches of the same UUID'), default=True) submit = SubmitField(_l('Restore backup')) def import_from_zip(zip_stream, datastore, include_groups, include_groups_replace, include_watches, include_watches_replace): """ Extract and import watches and groups from a backup zip stream. Mirrors the store's _load_watches / _load_tags loading pattern: - UUID dirs with tag.json → Tag.model + tag_obj.commit() - UUID dirs with watch.json → rehydrate_entity + watch_obj.commit() Returns a dict with counts: restored_groups, skipped_groups, restored_watches, skipped_watches. Raises zipfile.BadZipFile if the stream is not a valid zip. """ from changedetectionio.model import Tag restored_groups = 0 skipped_groups = 0 restored_watches = 0 skipped_watches = 0 current_tags = datastore.data['settings']['application'].get('tags', {}) current_watches = datastore.data['watching'] with tempfile.TemporaryDirectory() as tmpdir: logger.debug(f"Restore: extracting zip to {tmpdir}") with zipfile.ZipFile(zip_stream, 'r') as zf: zf.extractall(tmpdir) logger.debug("Restore: zip extracted, scanning UUID directories") for entry in os.scandir(tmpdir): if not entry.is_dir(): continue uuid = entry.name tag_json_path = os.path.join(entry.path, 'tag.json') watch_json_path = os.path.join(entry.path, 'watch.json') # --- Tags (groups) --- if include_groups and os.path.exists(tag_json_path): if uuid in current_tags and not include_groups_replace: logger.debug(f"Restore: skipping existing group {uuid} (replace not requested)") skipped_groups += 1 continue try: with open(tag_json_path, 'r', encoding='utf-8') as f: tag_data = json.load(f) except (json.JSONDecodeError, IOError) as e: logger.error(f"Restore: failed to read tag.json for {uuid}: {e}") continue title = tag_data.get('title', uuid) logger.debug(f"Restore: importing group '{title}' ({uuid})") # Mirror _load_tags: set uuid and force processor tag_data['uuid'] = uuid tag_data['processor'] = 'restock_diff' # Copy the UUID directory so data_dir exists for commit() dst_dir = os.path.join(datastore.datastore_path, uuid) if os.path.exists(dst_dir): shutil.rmtree(dst_dir) shutil.copytree(entry.path, dst_dir) tag_obj = Tag.model( datastore_path=datastore.datastore_path, __datastore=datastore.data, default=tag_data ) current_tags[uuid] = tag_obj tag_obj.commit() restored_groups += 1 logger.success(f"Restore: group '{title}' ({uuid}) restored") # --- Watches --- elif include_watches and os.path.exists(watch_json_path): if uuid in current_watches and not include_watches_replace: logger.debug(f"Restore: skipping existing watch {uuid} (replace not requested)") skipped_watches += 1 continue try: with open(watch_json_path, 'r', encoding='utf-8') as f: watch_data = json.load(f) except (json.JSONDecodeError, IOError) as e: logger.error(f"Restore: failed to read watch.json for {uuid}: {e}") continue url = watch_data.get('url', uuid) logger.debug(f"Restore: importing watch '{url}' ({uuid})") # Copy UUID directory first so data_dir and history files exist dst_dir = os.path.join(datastore.datastore_path, uuid) if os.path.exists(dst_dir): shutil.rmtree(dst_dir) shutil.copytree(entry.path, dst_dir) # Mirror _load_watches / rehydrate_entity watch_data['uuid'] = uuid watch_obj = datastore.rehydrate_entity(uuid, watch_data) current_watches[uuid] = watch_obj watch_obj.commit() restored_watches += 1 logger.success(f"Restore: watch '{url}' ({uuid}) restored") logger.debug(f"Restore: scan complete - groups {restored_groups} restored / {skipped_groups} skipped, " f"watches {restored_watches} restored / {skipped_watches} skipped") # Persist changedetection.json (includes the updated tags dict) logger.debug("Restore: committing datastore settings") datastore.commit() return { 'restored_groups': restored_groups, 'skipped_groups': skipped_groups, 'restored_watches': restored_watches, 'skipped_watches': skipped_watches, } def construct_restore_blueprint(datastore): restore_blueprint = Blueprint('restore', __name__, template_folder="templates") restore_threads = [] @login_optionally_required @restore_blueprint.route("/restore", methods=['GET']) def restore(): form = RestoreForm() return render_template("backup_restore.html", form=form, restore_running=any(t.is_alive() for t in restore_threads)) @login_optionally_required @restore_blueprint.route("/restore/start", methods=['POST']) def backups_restore_start(): if any(t.is_alive() for t in restore_threads): flash(gettext("A restore is already running, check back in a few minutes"), "error") return redirect(url_for('backups.restore.restore')) zip_file = request.files.get('zip_file') if not zip_file or not zip_file.filename: flash(gettext("No file uploaded"), "error") return redirect(url_for('backups.restore.restore')) if not zip_file.filename.lower().endswith('.zip'): flash(gettext("File must be a .zip backup file"), "error") return redirect(url_for('backups.restore.restore')) # Read into memory now — the request stream is gone once we return try: zip_bytes = io.BytesIO(zip_file.read()) zipfile.ZipFile(zip_bytes) # quick validity check before spawning zip_bytes.seek(0) except zipfile.BadZipFile: flash(gettext("Invalid or corrupted zip file"), "error") return redirect(url_for('backups.restore.restore')) include_groups = request.form.get('include_groups') == 'y' include_groups_replace = request.form.get('include_groups_replace_existing') == 'y' include_watches = request.form.get('include_watches') == 'y' include_watches_replace = request.form.get('include_watches_replace_existing') == 'y' restore_thread = threading.Thread( target=import_from_zip, kwargs={ 'zip_stream': zip_bytes, 'datastore': datastore, 'include_groups': include_groups, 'include_groups_replace': include_groups_replace, 'include_watches': include_watches, 'include_watches_replace': include_watches_replace, }, daemon=True, name="BackupRestore" ) restore_thread.start() restore_threads.append(restore_thread) flash(gettext("Restore started in background, check back in a few minutes.")) return redirect(url_for('backups.restore.restore')) return restore_blueprint
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/blueprint/backups/restore.py", "license": "Apache License 2.0", "lines": 170, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
dgtlmoon/changedetection.io:changedetectionio/model/Tags.py
import os import shutil from pathlib import Path from loguru import logger _SENTINEL = object() class TagsDict(dict): """Dict subclass that removes the corresponding tag.json file when a tag is deleted.""" def __init__(self, *args, datastore_path: str | os.PathLike, **kwargs) -> None: self._datastore_path = Path(datastore_path) super().__init__(*args, **kwargs) def __delitem__(self, key: str) -> None: super().__delitem__(key) tag_dir = self._datastore_path / key tag_json_file = tag_dir / "tag.json" if not os.path.exists(tag_json_file): logger.critical(f"Aborting deletion of directory '{tag_dir}' because '{tag_json_file}' does not exist.") return try: shutil.rmtree(tag_dir) logger.info(f"Deleted tag directory for tag {key!r}") except FileNotFoundError: pass except OSError as e: logger.error(f"Failed to delete tag directory for tag {key!r}: {e}") def pop(self, key: str, default=_SENTINEL): """Remove and return tag, deleting its tag.json file. Raises KeyError if missing and no default given.""" if key in self: value = self[key] del self[key] return value if default is _SENTINEL: raise KeyError(key) return default
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/model/Tags.py", "license": "Apache License 2.0", "lines": 33, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
dgtlmoon/changedetection.io:changedetectionio/model/schema_utils.py
""" Schema utilities for Watch and Tag models. Provides functions to extract readonly fields and properties from OpenAPI spec. Shared by both the model layer and API layer to avoid circular dependencies. """ import functools @functools.cache def get_openapi_schema_dict(): """ Get the raw OpenAPI spec dictionary for schema access. Returns the YAML dict directly (not the OpenAPI object). """ import os import yaml spec_path = os.path.join(os.path.dirname(__file__), '../../docs/api-spec.yaml') if not os.path.exists(spec_path): spec_path = os.path.join(os.path.dirname(__file__), '../docs/api-spec.yaml') with open(spec_path, 'r', encoding='utf-8') as f: return yaml.safe_load(f) @functools.cache def _resolve_readonly_fields(schema_name): """ Generic helper to resolve readOnly fields, including allOf inheritance. Args: schema_name: Name of the schema (e.g., 'Watch', 'Tag') Returns: frozenset: All readOnly field names including inherited ones """ spec_dict = get_openapi_schema_dict() schema = spec_dict['components']['schemas'].get(schema_name, {}) readonly_fields = set() # Handle allOf (schema inheritance) if 'allOf' in schema: for item in schema['allOf']: # Resolve $ref to parent schema if '$ref' in item: ref_path = item['$ref'].split('/')[-1] ref_schema = spec_dict['components']['schemas'].get(ref_path, {}) if 'properties' in ref_schema: for field_name, field_def in ref_schema['properties'].items(): if field_def.get('readOnly') is True: readonly_fields.add(field_name) # Check schema-specific properties if 'properties' in item: for field_name, field_def in item['properties'].items(): if field_def.get('readOnly') is True: readonly_fields.add(field_name) else: # Direct properties (no inheritance) if 'properties' in schema: for field_name, field_def in schema['properties'].items(): if field_def.get('readOnly') is True: readonly_fields.add(field_name) return frozenset(readonly_fields) @functools.cache def get_readonly_watch_fields(): """ Extract readOnly field names from Watch schema in OpenAPI spec. Returns readOnly fields from WatchBase (uuid, date_created) + Watch-specific readOnly fields. Used by: - model/watch_base.py: Track when writable fields are edited - api/Watch.py: Filter readonly fields from PUT requests """ return _resolve_readonly_fields('Watch') @functools.cache def get_readonly_tag_fields(): """ Extract readOnly field names from Tag schema in OpenAPI spec. Returns readOnly fields from WatchBase (uuid, date_created) + Tag-specific readOnly fields. """ return _resolve_readonly_fields('Tag')
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/model/schema_utils.py", "license": "Apache License 2.0", "lines": 71, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
dgtlmoon/changedetection.io:changedetectionio/tests/test_settings_tag_force_reprocess.py
#!/usr/bin/env python3 """ Test that changing global settings or tag configurations forces reprocessing. When settings or tag configurations change, all affected watches need to reprocess even if their content hasn't changed, because configuration affects the processing result. """ import os import time from flask import url_for from .util import wait_for_all_checks def test_settings_change_forces_reprocess(client, live_server, measure_memory_usage, datastore_path): """ Test that changing global settings clears all checksums to force reprocessing. """ # Setup test content test_html = """<html> <body> <p>Test content that stays the same</p> </body> </html> """ with open(os.path.join(datastore_path, "endpoint-content.txt"), "w") as f: f.write(test_html) test_url = url_for('test_endpoint', _external=True) # Add two watches datastore = client.application.config.get('DATASTORE') uuid1 = datastore.add_watch(url=test_url, extras={'title': 'Watch 1'}) uuid2 = datastore.add_watch(url=test_url, extras={'title': 'Watch 2'}) # Unpause watches datastore.data['watching'][uuid1]['paused'] = False datastore.data['watching'][uuid2]['paused'] = False # First check - establishes baseline client.get(url_for("ui.form_watch_checknow"), follow_redirects=True) wait_for_all_checks(client) # Verify checksum files were created checksum1 = os.path.join(datastore_path, uuid1, 'last-checksum.txt') checksum2 = os.path.join(datastore_path, uuid2, 'last-checksum.txt') assert os.path.isfile(checksum1), "First check should create checksum file for watch 1" assert os.path.isfile(checksum2), "First check should create checksum file for watch 2" # Change global settings (any setting will do) res = client.post( url_for("settings.settings_page"), data={ "application-empty_pages_are_a_change": "", "requests-time_between_check-minutes": 180, 'application-fetch_backend': "html_requests" }, follow_redirects=True ) assert b"Settings updated." in res.data # Give it a moment to process time.sleep(0.5) # Verify ALL checksum files were deleted assert not os.path.isfile(checksum1), "Settings change should delete checksum for watch 1" assert not os.path.isfile(checksum2), "Settings change should delete checksum for watch 2" # Next check should reprocess (not skip) and recreate checksums client.get(url_for("ui.form_watch_checknow"), follow_redirects=True) wait_for_all_checks(client) # Verify checksum files were recreated assert os.path.isfile(checksum1), "Reprocessing should recreate checksum file for watch 1" assert os.path.isfile(checksum2), "Reprocessing should recreate checksum file for watch 2" print("✓ Settings change forces reprocessing of all watches") def test_tag_change_forces_reprocess(client, live_server, measure_memory_usage, datastore_path): """ Test that changing a tag configuration clears checksums only for watches with that tag. """ # Setup test content test_html = """<html> <body> <p>Test content that stays the same</p> </body> </html> """ with open(os.path.join(datastore_path, "endpoint-content.txt"), "w") as f: f.write(test_html) test_url = url_for('test_endpoint', _external=True) # Create a tag datastore = client.application.config.get('DATASTORE') tag_uuid = datastore.add_tag('Test Tag') # Add watches - one with tag, one without uuid_with_tag = datastore.add_watch(url=test_url, extras={'title': 'Watch With Tag', 'tags': [tag_uuid]}) uuid_without_tag = datastore.add_watch(url=test_url, extras={'title': 'Watch Without Tag'}) # Unpause watches datastore.data['watching'][uuid_with_tag]['paused'] = False datastore.data['watching'][uuid_without_tag]['paused'] = False # First check - establishes baseline client.get(url_for("ui.form_watch_checknow"), follow_redirects=True) wait_for_all_checks(client) # Verify checksum files were created checksum_with = os.path.join(datastore_path, uuid_with_tag, 'last-checksum.txt') checksum_without = os.path.join(datastore_path, uuid_without_tag, 'last-checksum.txt') assert os.path.isfile(checksum_with), "First check should create checksum for tagged watch" assert os.path.isfile(checksum_without), "First check should create checksum for untagged watch" # Edit the tag (change notification_muted as an example) tag = datastore.data['settings']['application']['tags'][tag_uuid] res = client.post( url_for("tags.form_tag_edit_submit", uuid=tag_uuid), data={ 'title': 'Test Tag', 'notification_muted': 'y', 'overrides_watch': 'n' }, follow_redirects=True ) assert b"Updated" in res.data # Give it a moment to process time.sleep(0.5) # Verify ONLY the tagged watch's checksum was deleted assert not os.path.isfile(checksum_with), "Tag change should delete checksum for watch WITH tag" assert os.path.isfile(checksum_without), "Tag change should NOT delete checksum for watch WITHOUT tag" # Next check should reprocess tagged watch and recreate its checksum client.get(url_for("ui.form_watch_checknow"), follow_redirects=True) wait_for_all_checks(client) # Verify tagged watch's checksum was recreated assert os.path.isfile(checksum_with), "Reprocessing should recreate checksum for tagged watch" assert os.path.isfile(checksum_without), "Untagged watch should still have its checksum" print("✓ Tag change forces reprocessing only for watches with that tag") def test_tag_change_via_api_forces_reprocess(client, live_server, measure_memory_usage, datastore_path): """ Test that updating a tag via API also clears checksums for affected watches. """ # Setup test content test_html = """<html> <body> <p>Test content</p> </body> </html> """ with open(os.path.join(datastore_path, "endpoint-content.txt"), "w") as f: f.write(test_html) test_url = url_for('test_endpoint', _external=True) # Create a tag datastore = client.application.config.get('DATASTORE') tag_uuid = datastore.add_tag('API Test Tag') # Add watch with tag uuid_with_tag = datastore.add_watch(url=test_url, extras={'title': 'API Watch'}) datastore.data['watching'][uuid_with_tag]['paused'] = False datastore.data['watching'][uuid_with_tag]['tags'] = [tag_uuid] datastore.data['watching'][uuid_with_tag].commit() # First check client.get(url_for("ui.form_watch_checknow"), follow_redirects=True) wait_for_all_checks(client) # Verify checksum exists checksum_file = os.path.join(datastore_path, uuid_with_tag, 'last-checksum.txt') assert os.path.isfile(checksum_file), "First check should create checksum file" # Update tag via API res = client.put( f'/api/v1/tag/{tag_uuid}', json={'notification_muted': True}, headers={'x-api-key': datastore.data['settings']['application']['api_access_token']} ) assert res.status_code == 200, f"API call failed with status {res.status_code}: {res.data}" # Give it more time for async operations time.sleep(1.0) # Debug: Check if checksum still exists if os.path.isfile(checksum_file): # Read checksum to see if it changed with open(checksum_file, 'r') as f: checksum_content = f.read() print(f"Checksum still exists: {checksum_content}") # Verify checksum was deleted assert not os.path.isfile(checksum_file), "API tag update should delete checksum" print("✓ Tag update via API forces reprocessing")
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/tests/test_settings_tag_force_reprocess.py", "license": "Apache License 2.0", "lines": 164, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
dgtlmoon/changedetection.io:changedetectionio/tests/test_watch_edited_flag.py
#!/usr/bin/env python3 """ Test the watch edited flag functionality. This tests the private __watch_was_edited flag that tracks when writable watch fields are modified, which prevents skipping reprocessing when the watch configuration has changed. """ import os import time from flask import url_for from .util import live_server_setup, wait_for_all_checks def set_test_content(datastore_path): """Write test HTML content to endpoint-content.txt for test server.""" test_html = """<html> <body> <p>Test content for watch edited flag tests</p> <p>This content stays the same across checks</p> </body> </html> """ with open(os.path.join(datastore_path, "endpoint-content.txt"), "w") as f: f.write(test_html) def test_watch_edited_flag_lifecycle(client, live_server, measure_memory_usage, datastore_path): """ Test the full lifecycle of the was_edited flag: 1. Flag starts False when watch is created 2. Flag becomes True when writable fields are modified 3. Flag is reset False after worker processing 4. Flag stays False when readonly fields are modified """ # Setup - Add a watch test_url = url_for('test_endpoint', _external=True) res = client.post( url_for("ui.ui_views.form_quick_watch_add"), data={"url": test_url, "tags": "", "edit_and_watch_submit_button": "Edit > Watch"}, follow_redirects=True ) assert b"Watch added" in res.data or b"Updated watch" in res.data # Get the watch UUID datastore = client.application.config.get('DATASTORE') uuid = list(datastore.data['watching'].keys())[0] watch = datastore.data['watching'][uuid] # Reset flag after initial form submission (form sets fields which trigger the flag) watch.reset_watch_edited_flag() # Test 1: Flag should be False after reset assert not watch.was_edited, "Flag should be False after reset" # Test 2: Modify a writable field (title) - flag should become True watch['title'] = 'New Title' assert watch.was_edited, "Flag should be True after modifying writable field 'title'" # Test 3: Reset flag manually (simulating what worker does) watch.reset_watch_edited_flag() assert not watch.was_edited, "Flag should be False after reset" # Test 4: Modify another writable field (url) - flag should become True again watch['url'] = 'https://example.com' assert watch.was_edited, "Flag should be True after modifying writable field 'url'" # Test 5: Reset and modify a readonly field - flag should stay False watch.reset_watch_edited_flag() assert not watch.was_edited, "Flag should be False after reset" # Modify readonly field (uuid) - should not set flag old_uuid = watch['uuid'] watch['uuid'] = 'readonly-test-uuid' assert not watch.was_edited, "Flag should stay False when modifying readonly field 'uuid'" watch['uuid'] = old_uuid # Restore original # Note: Worker reset behavior is tested in test_check_removed_line_contains_trigger # and test_watch_edited_flag_prevents_skip print("✓ All watch edited flag lifecycle tests passed") def test_watch_edited_flag_dict_methods(client, live_server, measure_memory_usage, datastore_path): """ Test that the flag is set correctly by various dict methods: - __setitem__ (watch['key'] = value) - update() (watch.update({'key': value})) - setdefault() (watch.setdefault('key', default)) - pop() (watch.pop('key')) - __delitem__ (del watch['key']) """ # Setup - Add a watch test_url = url_for('test_endpoint', _external=True) res = client.post( url_for("ui.ui_views.form_quick_watch_add"), data={"url": test_url, "tags": "", "edit_and_watch_submit_button": "Edit > Watch"}, follow_redirects=True ) datastore = client.application.config.get('DATASTORE') uuid = list(datastore.data['watching'].keys())[0] watch = datastore.data['watching'][uuid] # Test __setitem__ watch.reset_watch_edited_flag() watch['title'] = 'Test via setitem' assert watch.was_edited, "Flag should be True after __setitem__ on writable field" # Test update() with dict watch.reset_watch_edited_flag() watch.update({'title': 'Test via update dict'}) assert watch.was_edited, "Flag should be True after update() with writable field" # Test update() with kwargs watch.reset_watch_edited_flag() watch.update(title='Test via update kwargs') assert watch.was_edited, "Flag should be True after update() kwargs with writable field" # Test setdefault() on new key watch.reset_watch_edited_flag() watch.setdefault('title', 'Should not be set') # Key exists, no change assert not watch.was_edited, "Flag should stay False when setdefault() doesn't change existing key" watch.setdefault('custom_field', 'New value') # New key assert watch.was_edited, "Flag should be True after setdefault() creates new writable field" # Test pop() on writable field watch.reset_watch_edited_flag() watch.pop('custom_field', None) assert watch.was_edited, "Flag should be True after pop() on writable field" # Test __delitem__ on writable field watch.reset_watch_edited_flag() watch['temp_field'] = 'temp' watch.reset_watch_edited_flag() # Reset after adding del watch['temp_field'] assert watch.was_edited, "Flag should be True after __delitem__ on writable field" print("✓ All dict methods correctly set the flag") def test_watch_edited_flag_prevents_skip(client, live_server, measure_memory_usage, datastore_path): """ Test that the was_edited flag prevents skipping reprocessing. When watch configuration is edited, it should reprocess even if content unchanged. After worker processing, flag should be reset and subsequent checks can skip. """ # Setup test content set_test_content(datastore_path) # Setup - Add a watch test_url = url_for('test_endpoint', _external=True) res = client.post( url_for("ui.ui_views.form_quick_watch_add"), data={"url": test_url, "tags": "", "edit_and_watch_submit_button": "Edit > Watch"}, follow_redirects=True ) assert b"Watch added" in res.data or b"Updated watch" in res.data datastore = client.application.config.get('DATASTORE') uuid = list(datastore.data['watching'].keys())[0] watch = datastore.data['watching'][uuid] # Unpause the watch (watches are paused by default in tests) watch['paused'] = False # Run first check to establish baseline client.get(url_for("ui.form_watch_checknow"), follow_redirects=True) wait_for_all_checks(client) # Verify first check completed successfully - checksum file should exist checksum_file = os.path.join(datastore_path, uuid, 'last-checksum.txt') assert os.path.isfile(checksum_file), "First check should create last-checksum.txt file" # Reset the was_edited flag (simulating clean state after processing) watch.reset_watch_edited_flag() assert not watch.was_edited, "Flag should be False after reset" # Run second check without any changes - should skip via checksumFromPreviousCheckWasTheSame client.get(url_for("ui.form_watch_checknow"), follow_redirects=True) wait_for_all_checks(client) # Verify it was skipped (last_check_status should indicate skip) # Note: The actual skip is tested in test_check_removed_line_contains_trigger # Here we're focused on the was_edited flag interaction # Now modify the watch - flag should become True watch['title'] = 'Modified Title' assert watch.was_edited, "Flag should be True after modifying watch" # Run third check - should NOT skip because was_edited=True even though content unchanged client.get(url_for("ui.form_watch_checknow"), follow_redirects=True) wait_for_all_checks(client) # After worker processing, the flag should be reset by the worker # This reset happens in the processor's run() method after processing completes assert not watch.was_edited, "Flag should be False after worker processing" print("✓ was_edited flag correctly prevents skip and is reset by worker") def test_watch_edited_flag_system_fields(client, live_server, measure_memory_usage, datastore_path): """ Test that system fields (readonly + additional system fields) don't trigger the flag. """ # Setup - Add a watch test_url = url_for('test_endpoint', _external=True) res = client.post( url_for("ui.ui_views.form_quick_watch_add"), data={"url": test_url, "tags": "", "edit_and_watch_submit_button": "Edit > Watch"}, follow_redirects=True ) datastore = client.application.config.get('DATASTORE') uuid = list(datastore.data['watching'].keys())[0] watch = datastore.data['watching'][uuid] # Test readonly fields from OpenAPI spec readonly_fields = ['uuid', 'date_created', 'last_viewed'] for field in readonly_fields: watch.reset_watch_edited_flag() if field in watch: old_value = watch[field] watch[field] = 'modified-readonly-value' assert not watch.was_edited, f"Flag should stay False when modifying readonly field '{field}'" watch[field] = old_value # Restore # Test additional system fields not in OpenAPI spec yet system_fields = ['last_check_status'] for field in system_fields: watch.reset_watch_edited_flag() watch[field] = 'system-value' assert not watch.was_edited, f"Flag should stay False when modifying system field '{field}'" # Test that content-type (readonly per OpenAPI) doesn't trigger flag watch.reset_watch_edited_flag() watch['content-type'] = 'text/html' assert not watch.was_edited, "Flag should stay False when modifying 'content-type' (readonly)" print("✓ System fields correctly don't trigger the flag")
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/tests/test_watch_edited_flag.py", "license": "Apache License 2.0", "lines": 194, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
dgtlmoon/changedetection.io:changedetectionio/processors/restock_diff/pure_python_extractor.py
""" Pure Python metadata extractor - no lxml, no memory leaks. This module provides a fast, memory-efficient alternative to extruct for common e-commerce metadata extraction. It handles: - JSON-LD (covers 80%+ of modern sites) - OpenGraph meta tags - Basic microdata attributes Uses Python's built-in html.parser instead of lxml/libxml2, avoiding C-level memory allocation issues. For edge cases, the main processor can fall back to extruct (with subprocess isolation on Linux). """ from html.parser import HTMLParser import json import re from loguru import logger class JSONLDExtractor(HTMLParser): """ Extract JSON-LD structured data from HTML. Finds all <script type="application/ld+json"> tags and parses their content. Handles multiple JSON-LD blocks on the same page. """ def __init__(self): super().__init__() self.in_jsonld = False self.data = [] # List of all parsed JSON-LD objects self.current_script = [] def handle_starttag(self, tag, attrs): if tag == 'script': # Check if this is a JSON-LD script tag for attr, value in attrs: if attr == 'type' and value == 'application/ld+json': self.in_jsonld = True self.current_script = [] break def handle_data(self, data): if self.in_jsonld: self.current_script.append(data) def handle_endtag(self, tag): if tag == 'script' and self.in_jsonld: # Parse the accumulated script content script_content = ''.join(self.current_script) if script_content.strip(): try: # Parse JSON (handles both objects and arrays) parsed = json.loads(script_content) if isinstance(parsed, list): self.data.extend(parsed) else: self.data.append(parsed) except json.JSONDecodeError as e: logger.debug(f"Failed to parse JSON-LD: {e}") pass self.in_jsonld = False self.current_script = [] class OpenGraphExtractor(HTMLParser): """ Extract OpenGraph meta tags from HTML. Finds <meta property="og:*"> tags commonly used for social media sharing. """ def __init__(self): super().__init__() self.og_data = {} def handle_starttag(self, tag, attrs): if tag == 'meta': attrs_dict = dict(attrs) prop = attrs_dict.get('property', '') # Extract OpenGraph properties if prop.startswith('og:'): content = attrs_dict.get('content', '') if content: self.og_data[prop] = content class MicrodataExtractor(HTMLParser): """ Extract basic microdata attributes from HTML. Finds elements with itemprop attributes. This is a simplified extractor that doesn't handle nested itemscope/itemtype hierarchies - for complex cases, use extruct as fallback. """ def __init__(self): super().__init__() self.microdata = {} self.current_itemprop = None def handle_starttag(self, tag, attrs): attrs_dict = dict(attrs) if 'itemprop' in attrs_dict: itemprop = attrs_dict['itemprop'] # Price/currency/availability can be in content/href attributes if itemprop == 'price': if 'content' in attrs_dict: self.microdata['price'] = attrs_dict['content'] else: self.current_itemprop = 'price' elif itemprop == 'priceCurrency': if 'content' in attrs_dict: self.microdata['currency'] = attrs_dict['content'] else: self.current_itemprop = 'priceCurrency' elif itemprop == 'availability': # Can be in href (link) or content (meta) if 'href' in attrs_dict: self.microdata['availability'] = attrs_dict['href'] elif 'content' in attrs_dict: self.microdata['availability'] = attrs_dict['content'] else: self.current_itemprop = 'availability' def handle_data(self, data): # Capture text content for itemprop elements if self.current_itemprop == 'price': # Try to extract numeric price from text try: price_text = re.sub(r'[^\d.]', '', data.strip()) if price_text: self.microdata['price'] = float(price_text) except ValueError: pass elif self.current_itemprop == 'priceCurrency': currency = data.strip() if currency: self.microdata['currency'] = currency elif self.current_itemprop == 'availability': availability = data.strip() if availability: self.microdata['availability'] = availability def handle_endtag(self, tag): # Reset current itemprop after closing tag self.current_itemprop = None def extract_metadata_pure_python(html_content): """ Extract structured metadata from HTML using pure Python parsers. Returns a dict with three keys: - 'json-ld': List of parsed JSON-LD objects - 'opengraph': Dict of OpenGraph properties - 'microdata': Dict of microdata properties Args: html_content: HTML string to parse Returns: dict: Extracted metadata in three formats """ result = { 'json-ld': [], 'opengraph': {}, 'microdata': {} } # Extract JSON-LD try: jsonld_extractor = JSONLDExtractor() jsonld_extractor.feed(html_content) result['json-ld'] = jsonld_extractor.data logger.trace(f"Pure Python: Found {len(jsonld_extractor.data)} JSON-LD blocks") except Exception as e: logger.debug(f"JSON-LD extraction failed: {e}") # Extract OpenGraph try: og_extractor = OpenGraphExtractor() og_extractor.feed(html_content) result['opengraph'] = og_extractor.og_data if result['opengraph']: logger.trace(f"Pure Python: Found {len(og_extractor.og_data)} OpenGraph tags") except Exception as e: logger.debug(f"OpenGraph extraction failed: {e}") # Extract Microdata try: microdata_extractor = MicrodataExtractor() microdata_extractor.feed(html_content) result['microdata'] = microdata_extractor.microdata if result['microdata']: logger.trace(f"Pure Python: Found microdata: {result['microdata']}") except Exception as e: logger.debug(f"Microdata extraction failed: {e}") return result def query_price_availability(extracted_data): """ Query extracted metadata for price and availability information. Uses jsonpath_ng to query JSON-LD data (same approach as extruct). Falls back to OpenGraph and microdata if JSON-LD doesn't have the data. Args: extracted_data: Dict from extract_metadata_pure_python() Returns: dict: {'price': float, 'currency': str, 'availability': str} """ from jsonpath_ng import parse result = {} # 1. Try JSON-LD first (most reliable and common) for data in extracted_data.get('json-ld', []): try: # Use jsonpath to find price/availability anywhere in the structure price_parse = parse('$..(price|Price)') availability_parse = parse('$..(availability|Availability)') currency_parse = parse('$..(priceCurrency|currency|priceCurrency)') price_results = [m.value for m in price_parse.find(data)] if price_results and not result.get('price'): # Handle various price formats price_val = price_results[0] if isinstance(price_val, (int, float)): result['price'] = float(price_val) elif isinstance(price_val, str): # Extract numeric value from string try: result['price'] = float(re.sub(r'[^\d.]', '', price_val)) except ValueError: pass avail_results = [m.value for m in availability_parse.find(data)] if avail_results and not result.get('availability'): result['availability'] = str(avail_results[0]) curr_results = [m.value for m in currency_parse.find(data)] if curr_results and not result.get('currency'): result['currency'] = str(curr_results[0]) # If we found price, this JSON-LD block is good if result.get('price'): logger.debug(f"Pure Python: Found price data in JSON-LD: {result}") break except Exception as e: logger.debug(f"Error querying JSON-LD: {e}") continue # 2. Try OpenGraph if JSON-LD didn't provide everything og_data = extracted_data.get('opengraph', {}) if not result.get('price') and 'og:price:amount' in og_data: try: result['price'] = float(og_data['og:price:amount']) except ValueError: pass if not result.get('currency') and 'og:price:currency' in og_data: result['currency'] = og_data['og:price:currency'] if not result.get('availability') and 'og:availability' in og_data: result['availability'] = og_data['og:availability'] # 3. Use microdata as last resort microdata = extracted_data.get('microdata', {}) if not result.get('price') and 'price' in microdata: result['price'] = microdata['price'] if not result.get('currency') and 'currency' in microdata: result['currency'] = microdata['currency'] if not result.get('availability') and 'availability' in microdata: result['availability'] = microdata['availability'] return result
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/processors/restock_diff/pure_python_extractor.py", "license": "Apache License 2.0", "lines": 234, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
dgtlmoon/changedetection.io:changedetectionio/model/persistence.py
""" Entity persistence mixin for Watch and Tag models. Provides file-based persistence using atomic writes. """ import functools import inspect @functools.lru_cache(maxsize=None) def _determine_entity_type(cls): """ Determine entity type from class hierarchy (cached at class level). Args: cls: The class to inspect Returns: str: Entity type ('watch', 'tag', etc.) Raises: ValueError: If entity type cannot be determined """ for base_class in inspect.getmro(cls): module_name = base_class.__module__ if module_name.startswith('changedetectionio.model.'): # Get last part after dot: "changedetectionio.model.Watch" -> "watch" return module_name.split('.')[-1].lower() raise ValueError( f"Cannot determine entity type for {cls.__module__}.{cls.__name__}. " f"Entity must inherit from a class in changedetectionio.model (Watch or Tag)." ) class EntityPersistenceMixin: """ Mixin providing file persistence for watch_base subclasses (Watch, Tag, etc.). This mixin provides the _save_to_disk() method required by watch_base.commit(). It automatically determines the correct filename and size limits based on class hierarchy. Usage: class model(EntityPersistenceMixin, watch_base): # in Watch.py pass class model(EntityPersistenceMixin, watch_base): # in Tag.py pass """ def _save_to_disk(self, data_dict, uuid): """ Save entity to disk using atomic write. Implements the abstract method required by watch_base.commit(). Automatically determines filename and size limits from class hierarchy. Args: data_dict: Dictionary to save uuid: UUID for logging Raises: ValueError: If entity type cannot be determined from class hierarchy """ # Import here to avoid circular dependency from changedetectionio.store.file_saving_datastore import save_entity_atomic # Determine entity type (cached at class level, not instance level) entity_type = _determine_entity_type(self.__class__) # Set filename and size limits based on entity type filename = f'{entity_type}.json' max_size_mb = 10 if entity_type == 'watch' else 1 # Save using generic function save_entity_atomic( self.data_dir, uuid, data_dict, filename=filename, entity_type=entity_type, max_size_mb=max_size_mb )
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/model/persistence.py", "license": "Apache License 2.0", "lines": 64, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
dgtlmoon/changedetection.io:changedetectionio/tests/test_commit_persistence.py
#!/usr/bin/env python3 """ Tests for immediate commit-based persistence system. Tests cover: - Watch.commit() persistence to disk - Concurrent commit safety (race conditions) - Processor config separation - Data loss prevention (settings, tags, watch modifications) """ import json import os import threading import time from flask import url_for from .util import wait_for_all_checks # ============================================================================== # 2. Commit() Persistence Tests # ============================================================================== def test_watch_commit_persists_to_disk(client, live_server): """Test that watch.commit() actually writes to watch.json immediately""" datastore = client.application.config.get('DATASTORE') # Create a watch uuid = datastore.add_watch(url='http://example.com', extras={'title': 'Original Title'}) watch = datastore.data['watching'][uuid] # Modify and commit watch['title'] = 'Modified Title' watch['paused'] = True watch.commit() # Read directly from disk (bypass datastore cache) watch_json_path = os.path.join(watch.data_dir, 'watch.json') assert os.path.exists(watch_json_path), "watch.json should exist on disk" with open(watch_json_path, 'r') as f: disk_data = json.load(f) assert disk_data['title'] == 'Modified Title', "Title should be persisted to disk" assert disk_data['paused'] == True, "Paused state should be persisted to disk" assert disk_data['uuid'] == uuid, "UUID should match" def test_watch_commit_survives_reload(client, live_server): """Test that committed changes survive datastore reload""" from changedetectionio.store import ChangeDetectionStore datastore = client.application.config.get('DATASTORE') datastore_path = datastore.datastore_path # Create and modify a watch uuid = datastore.add_watch(url='http://example.com', extras={'title': 'Test Watch'}) watch = datastore.data['watching'][uuid] watch['title'] = 'Persisted Title' watch['paused'] = True watch['tags'] = ['tag-1', 'tag-2'] watch.commit() # Simulate app restart - create new datastore instance datastore2 = ChangeDetectionStore(datastore_path=datastore_path) datastore2.reload_state( datastore_path=datastore_path, include_default_watches=False, version_tag='test' ) # Check data survived assert uuid in datastore2.data['watching'], "Watch should exist after reload" reloaded_watch = datastore2.data['watching'][uuid] assert reloaded_watch['title'] == 'Persisted Title', "Title should survive reload" assert reloaded_watch['paused'] == True, "Paused state should survive reload" assert reloaded_watch['tags'] == ['tag-1', 'tag-2'], "Tags should survive reload" def test_watch_commit_atomic_on_crash(client, live_server): """Test that atomic writes prevent corruption (temp file pattern)""" datastore = client.application.config.get('DATASTORE') uuid = datastore.add_watch(url='http://example.com', extras={'title': 'Original'}) watch = datastore.data['watching'][uuid] # First successful commit watch['title'] = 'First Save' watch.commit() # Verify watch.json exists and is valid watch_json_path = os.path.join(watch.data_dir, 'watch.json') with open(watch_json_path, 'r') as f: data = json.load(f) # Should not raise JSONDecodeError assert data['title'] == 'First Save' # Second commit - even if interrupted, original file should be intact # (atomic write uses temp file + rename, so original is never corrupted) watch['title'] = 'Second Save' watch.commit() with open(watch_json_path, 'r') as f: data = json.load(f) assert data['title'] == 'Second Save' def test_multiple_watches_commit_independently(client, live_server): """Test that committing one watch doesn't affect others""" datastore = client.application.config.get('DATASTORE') # Create multiple watches uuid1 = datastore.add_watch(url='http://example1.com', extras={'title': 'Watch 1'}) uuid2 = datastore.add_watch(url='http://example2.com', extras={'title': 'Watch 2'}) uuid3 = datastore.add_watch(url='http://example3.com', extras={'title': 'Watch 3'}) watch1 = datastore.data['watching'][uuid1] watch2 = datastore.data['watching'][uuid2] watch3 = datastore.data['watching'][uuid3] # Modify and commit only watch2 watch2['title'] = 'Modified Watch 2' watch2['paused'] = True watch2.commit() # Read all from disk def read_watch_json(uuid): watch = datastore.data['watching'][uuid] path = os.path.join(watch.data_dir, 'watch.json') with open(path, 'r') as f: return json.load(f) data1 = read_watch_json(uuid1) data2 = read_watch_json(uuid2) data3 = read_watch_json(uuid3) # Only watch2 should have changes assert data1['title'] == 'Watch 1', "Watch 1 should be unchanged" assert data1['paused'] == False, "Watch 1 should not be paused" assert data2['title'] == 'Modified Watch 2', "Watch 2 should be modified" assert data2['paused'] == True, "Watch 2 should be paused" assert data3['title'] == 'Watch 3', "Watch 3 should be unchanged" assert data3['paused'] == False, "Watch 3 should not be paused" # ============================================================================== # 3. Concurrency/Race Condition Tests # ============================================================================== def test_concurrent_watch_commits_dont_corrupt(client, live_server): """Test that simultaneous commits to same watch don't corrupt JSON""" datastore = client.application.config.get('DATASTORE') uuid = datastore.add_watch(url='http://example.com', extras={'title': 'Test'}) watch = datastore.data['watching'][uuid] errors = [] def modify_and_commit(field, value): try: watch[field] = value watch.commit() except Exception as e: errors.append(e) # Run 10 concurrent commits threads = [] for i in range(10): t = threading.Thread(target=modify_and_commit, args=('title', f'Title {i}')) threads.append(t) t.start() for t in threads: t.join() # Should not have any errors assert len(errors) == 0, f"Expected no errors, got: {errors}" # JSON file should still be valid (not corrupted) watch_json_path = os.path.join(watch.data_dir, 'watch.json') with open(watch_json_path, 'r') as f: data = json.load(f) # Should not raise JSONDecodeError assert data['uuid'] == uuid, "UUID should still be correct" assert 'Title' in data['title'], "Title should contain 'Title'" def test_concurrent_modifications_during_commit(client, live_server): """Test that modifying watch during commit doesn't cause RuntimeError""" datastore = client.application.config.get('DATASTORE') uuid = datastore.add_watch(url='http://example.com', extras={'title': 'Test'}) watch = datastore.data['watching'][uuid] errors = [] stop_flag = threading.Event() def keep_modifying(): """Continuously modify watch""" try: i = 0 while not stop_flag.is_set(): watch['title'] = f'Title {i}' watch['paused'] = i % 2 == 0 i += 1 time.sleep(0.001) except Exception as e: errors.append(('modifier', e)) def keep_committing(): """Continuously commit watch""" try: for _ in range(20): watch.commit() time.sleep(0.005) except Exception as e: errors.append(('committer', e)) # Start concurrent modification and commits modifier = threading.Thread(target=keep_modifying) committer = threading.Thread(target=keep_committing) modifier.start() committer.start() committer.join() stop_flag.set() modifier.join() # Should not have RuntimeError from dict changing during iteration runtime_errors = [e for source, e in errors if isinstance(e, RuntimeError)] assert len(runtime_errors) == 0, f"Should not have RuntimeError, got: {runtime_errors}" def test_datastore_lock_protects_commit_snapshot(client, live_server): """Test that datastore.lock prevents race conditions during deepcopy""" datastore = client.application.config.get('DATASTORE') uuid = datastore.add_watch(url='http://example.com', extras={'title': 'Test'}) watch = datastore.data['watching'][uuid] # Add some complex nested data watch['browser_steps'] = [ {'operation': 'click', 'selector': '#foo'}, {'operation': 'wait', 'seconds': 5} ] errors = [] commits_succeeded = [0] def rapid_commits(): try: for i in range(50): watch['title'] = f'Title {i}' watch.commit() commits_succeeded[0] += 1 time.sleep(0.001) except Exception as e: errors.append(e) # Multiple threads doing rapid commits threads = [threading.Thread(target=rapid_commits) for _ in range(3)] for t in threads: t.start() for t in threads: t.join() assert len(errors) == 0, f"Expected no errors, got: {errors}" assert commits_succeeded[0] == 150, f"Expected 150 commits, got {commits_succeeded[0]}" # Final JSON should be valid watch_json_path = os.path.join(watch.data_dir, 'watch.json') with open(watch_json_path, 'r') as f: data = json.load(f) assert data['uuid'] == uuid # ============================================================================== # 4. Processor Config Separation Tests # ============================================================================== def test_processor_config_never_in_watch_json(client, live_server): """Test that processor_config_* fields are filtered out of watch.json""" datastore = client.application.config.get('DATASTORE') uuid = datastore.add_watch( url='http://example.com', extras={ 'title': 'Test Watch', 'processor': 'restock_diff' } ) watch = datastore.data['watching'][uuid] # Try to set processor config fields (these should be filtered during commit) watch['processor_config_price_threshold'] = 10.0 watch['processor_config_some_setting'] = 'value' watch['processor_config_another'] = {'nested': 'data'} watch.commit() # Read watch.json from disk watch_json_path = os.path.join(watch.data_dir, 'watch.json') with open(watch_json_path, 'r') as f: data = json.load(f) # Verify processor_config_* fields are NOT in watch.json for key in data.keys(): assert not key.startswith('processor_config_'), \ f"Found {key} in watch.json - processor configs should be in separate file!" # Normal fields should still be there assert data['title'] == 'Test Watch' assert data['processor'] == 'restock_diff' def test_api_post_saves_processor_config_separately(client, live_server): """Test that API POST saves processor configs to {processor}.json""" import json from changedetectionio.processors import extract_processor_config_from_form_data # Get API key api_key = live_server.app.config['DATASTORE'].data['settings']['application'].get('api_access_token') # Create watch via API with processor config response = client.post( url_for("createwatch"), data=json.dumps({ 'url': 'http://example.com', 'processor': 'restock_diff', 'processor_config_price_threshold': 10.0, 'processor_config_in_stock_only': True }), headers={'content-type': 'application/json', 'x-api-key': api_key} ) assert response.status_code in (200, 201), f"Expected 200/201, got {response.status_code}" uuid = response.json.get('uuid') assert uuid, "Should return UUID" datastore = client.application.config.get('DATASTORE') watch = datastore.data['watching'][uuid] # Check that processor config file exists processor_config_path = os.path.join(watch.data_dir, 'restock_diff.json') assert os.path.exists(processor_config_path), "Processor config file should exist" with open(processor_config_path, 'r') as f: config = json.load(f) # Verify fields are saved WITHOUT processor_config_ prefix assert config.get('price_threshold') == 10.0, "Should have price_threshold (no prefix)" assert config.get('in_stock_only') == True, "Should have in_stock_only (no prefix)" assert 'processor_config_price_threshold' not in config, "Should NOT have prefixed keys" def test_api_put_saves_processor_config_separately(client, live_server): """Test that API PUT updates processor configs in {processor}.json""" import json datastore = client.application.config.get('DATASTORE') # Get API key api_key = live_server.app.config['DATASTORE'].data['settings']['application'].get('api_access_token') # Create watch uuid = datastore.add_watch( url='http://example.com', extras={'processor': 'restock_diff'} ) # Update via API with processor config response = client.put( url_for("watch", uuid=uuid), data=json.dumps({ 'processor_config_price_threshold': 15.0, 'processor_config_min_stock': 5 }), headers={'content-type': 'application/json', 'x-api-key': api_key} ) # PUT might return different status codes, 200 or 204 are both OK assert response.status_code in (200, 204), f"Expected 200/204, got {response.status_code}: {response.data}" watch = datastore.data['watching'][uuid] # Check processor config file processor_config_path = os.path.join(watch.data_dir, 'restock_diff.json') assert os.path.exists(processor_config_path), "Processor config file should exist" with open(processor_config_path, 'r') as f: config = json.load(f) assert config.get('price_threshold') == 15.0, "Should have updated price_threshold" assert config.get('min_stock') == 5, "Should have min_stock" def test_ui_edit_saves_processor_config_separately(client, live_server): """Test that processor_config_* fields never appear in watch.json (even from UI)""" datastore = client.application.config.get('DATASTORE') # Create watch uuid = datastore.add_watch( url='http://example.com', extras={'processor': 'text_json_diff', 'title': 'Test'} ) watch = datastore.data['watching'][uuid] # Simulate someone accidentally trying to set processor_config fields directly watch['processor_config_should_not_save'] = 'test_value' watch['processor_config_another_field'] = 123 watch['normal_field'] = 'this_should_save' watch.commit() # Check watch.json has NO processor_config_* fields (main point of this test) watch_json_path = os.path.join(watch.data_dir, 'watch.json') with open(watch_json_path, 'r') as f: watch_data = json.load(f) for key in watch_data.keys(): assert not key.startswith('processor_config_'), \ f"Found {key} in watch.json - processor configs should be filtered during commit" # Verify normal fields still save assert watch_data['normal_field'] == 'this_should_save', "Normal fields should save" assert watch_data['title'] == 'Test', "Original fields should still be there" def test_browser_steps_normalized_to_empty_list(client, live_server): """Test that meaningless browser_steps are normalized to [] during commit""" datastore = client.application.config.get('DATASTORE') uuid = datastore.add_watch(url='http://example.com') watch = datastore.data['watching'][uuid] # Set browser_steps to meaningless values watch['browser_steps'] = [ {'operation': 'Choose one', 'selector': ''}, {'operation': 'Goto site', 'selector': ''}, {'operation': '', 'selector': '#foo'} ] watch.commit() # Read from disk watch_json_path = os.path.join(watch.data_dir, 'watch.json') with open(watch_json_path, 'r') as f: data = json.load(f) # Should be normalized to empty list assert data['browser_steps'] == [], "Meaningless browser_steps should be normalized to []" # ============================================================================== # 5. Data Loss Prevention Tests # ============================================================================== def test_settings_persist_after_update(client, live_server): """Test that settings updates are committed and survive restart""" from changedetectionio.store import ChangeDetectionStore datastore = client.application.config.get('DATASTORE') datastore_path = datastore.datastore_path # Update settings directly (bypass form validation issues) datastore.data['settings']['application']['empty_pages_are_a_change'] = True datastore.data['settings']['application']['fetch_backend'] = 'html_requests' datastore.data['settings']['requests']['time_between_check']['minutes'] = 120 datastore.commit() # Simulate restart datastore2 = ChangeDetectionStore(datastore_path=datastore_path) datastore2.reload_state( datastore_path=datastore_path, include_default_watches=False, version_tag='test' ) # Verify settings survived assert datastore2.data['settings']['application']['empty_pages_are_a_change'] == True, "empty_pages_are_a_change should persist" assert datastore2.data['settings']['application']['fetch_backend'] == 'html_requests', "fetch_backend should persist" assert datastore2.data['settings']['requests']['time_between_check']['minutes'] == 120, "time_between_check should persist" def test_tag_mute_persists(client, live_server): """Test that tag mute/unmute operations persist""" from changedetectionio.store import ChangeDetectionStore datastore = client.application.config.get('DATASTORE') datastore_path = datastore.datastore_path # Add a tag tag_uuid = datastore.add_tag('Test Tag') # Mute the tag response = client.get(url_for("tags.mute", uuid=tag_uuid)) assert response.status_code == 302 # Redirect # Verify muted in memory assert datastore.data['settings']['application']['tags'][tag_uuid]['notification_muted'] == True # Simulate restart datastore2 = ChangeDetectionStore(datastore_path=datastore_path) datastore2.reload_state( datastore_path=datastore_path, include_default_watches=False, version_tag='test' ) # Verify mute state survived assert tag_uuid in datastore2.data['settings']['application']['tags'] assert datastore2.data['settings']['application']['tags'][tag_uuid]['notification_muted'] == True def test_tag_delete_removes_from_watches(client, live_server): """Test that deleting a tag removes it from all watches""" datastore = client.application.config.get('DATASTORE') # Create a tag tag_uuid = datastore.add_tag('Test Tag') # Create watches with this tag uuid1 = datastore.add_watch(url='http://example1.com') uuid2 = datastore.add_watch(url='http://example2.com') uuid3 = datastore.add_watch(url='http://example3.com') watch1 = datastore.data['watching'][uuid1] watch2 = datastore.data['watching'][uuid2] watch3 = datastore.data['watching'][uuid3] watch1['tags'] = [tag_uuid] watch1.commit() watch2['tags'] = [tag_uuid, 'other-tag'] watch2.commit() # watch3 has no tags # Delete the tag response = client.get(url_for("tags.delete", uuid=tag_uuid)) assert response.status_code == 302 # Wait for background thread to complete time.sleep(1) # Tag should be removed from settings assert tag_uuid not in datastore.data['settings']['application']['tags'] # Tag should be removed from watches and persisted def check_watch_tags(uuid): watch = datastore.data['watching'][uuid] watch_json_path = os.path.join(watch.data_dir, 'watch.json') with open(watch_json_path, 'r') as f: return json.load(f)['tags'] assert tag_uuid not in check_watch_tags(uuid1), "Tag should be removed from watch1" assert tag_uuid not in check_watch_tags(uuid2), "Tag should be removed from watch2" assert 'other-tag' in check_watch_tags(uuid2), "Other tags should remain in watch2" assert check_watch_tags(uuid3) == [], "Watch3 should still have empty tags" def test_watch_pause_unpause_persists(client, live_server): """Test that pause/unpause operations commit and persist""" datastore = client.application.config.get('DATASTORE') # Get API key api_key = live_server.app.config['DATASTORE'].data['settings']['application'].get('api_access_token') uuid = datastore.add_watch(url='http://example.com') watch = datastore.data['watching'][uuid] # Pause via API response = client.get(url_for("watch", uuid=uuid, paused='paused'), headers={'x-api-key': api_key}) assert response.status_code == 200 # Check persisted to disk watch_json_path = os.path.join(watch.data_dir, 'watch.json') with open(watch_json_path, 'r') as f: data = json.load(f) assert data['paused'] == True, "Pause should be persisted" # Unpause response = client.get(url_for("watch", uuid=uuid, paused='unpaused'), headers={'x-api-key': api_key}) assert response.status_code == 200 with open(watch_json_path, 'r') as f: data = json.load(f) assert data['paused'] == False, "Unpause should be persisted" def test_watch_mute_unmute_persists(client, live_server): """Test that mute/unmute operations commit and persist""" datastore = client.application.config.get('DATASTORE') # Get API key api_key = live_server.app.config['DATASTORE'].data['settings']['application'].get('api_access_token') uuid = datastore.add_watch(url='http://example.com') watch = datastore.data['watching'][uuid] # Mute via API response = client.get(url_for("watch", uuid=uuid, muted='muted'), headers={'x-api-key': api_key}) assert response.status_code == 200 # Check persisted to disk watch_json_path = os.path.join(watch.data_dir, 'watch.json') with open(watch_json_path, 'r') as f: data = json.load(f) assert data['notification_muted'] == True, "Mute should be persisted" # Unmute response = client.get(url_for("watch", uuid=uuid, muted='unmuted'), headers={'x-api-key': api_key}) assert response.status_code == 200 with open(watch_json_path, 'r') as f: data = json.load(f) assert data['notification_muted'] == False, "Unmute should be persisted" def test_ui_watch_edit_persists_all_fields(client, live_server): """Test that UI watch edit form persists all modified fields""" from changedetectionio.store import ChangeDetectionStore datastore = client.application.config.get('DATASTORE') datastore_path = datastore.datastore_path # Create watch uuid = datastore.add_watch(url='http://example.com') # Edit via UI with multiple field changes response = client.post( url_for("ui.ui_edit.edit_page", uuid=uuid), data={ 'url': 'http://updated-example.com', 'title': 'Updated Watch Title', 'time_between_check-hours': '2', 'time_between_check-minutes': '30', 'include_filters': '#content', 'fetch_backend': 'html_requests', 'method': 'POST', 'ignore_text': 'Advertisement\nTracking' }, follow_redirects=True ) assert b"Updated watch" in response.data or b"Saved" in response.data # Simulate restart datastore2 = ChangeDetectionStore(datastore_path=datastore_path) datastore2.reload_state( datastore_path=datastore_path, include_default_watches=False, version_tag='test' ) # Verify all fields survived watch = datastore2.data['watching'][uuid] assert watch['url'] == 'http://updated-example.com' assert watch['title'] == 'Updated Watch Title' assert watch['time_between_check']['hours'] == 2 assert watch['time_between_check']['minutes'] == 30 assert watch['fetch_backend'] == 'html_requests' assert watch['method'] == 'POST'
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/tests/test_commit_persistence.py", "license": "Apache License 2.0", "lines": 506, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
dgtlmoon/changedetection.io:changedetectionio/tests/plugins/test_processor.py
import time from flask import url_for from changedetectionio.tests.util import wait_for_all_checks def test_check_plugin_processor(client, live_server, measure_memory_usage, datastore_path): # requires os-int intelligence plugin installed (first basic one we test with) res = client.get(url_for("watchlist.index")) assert b'OSINT Reconnaissance' in res.data, "Must have the OSINT plugin installed at test time" assert b'<input checked id="processor-0" name="processor" type="radio" value="text_json_diff">' in res.data, "But the first text_json_diff processor should always be selected by default in quick watch form" res = client.post( url_for("ui.ui_views.form_quick_watch_add"), data={"url": 'http://127.0.0.1', "tags": '', 'processor': 'osint_recon'}, follow_redirects=True ) assert b"Watch added" in res.data client.get(url_for("ui.form_watch_checknow"), follow_redirects=True) wait_for_all_checks(client) res = client.get( url_for("ui.ui_preview.preview_page", uuid="first"), follow_redirects=True ) assert b'Target: http://127.0.0.1' in res.data assert b'DNSKEY Records' in res.data wait_for_all_checks(client) # Now change it to something that doesnt exist uuid = next(iter(live_server.app.config['DATASTORE'].data['watching'])) live_server.app.config['DATASTORE'].data['watching'][uuid]['processor'] = "now_missing" client.get(url_for("ui.form_watch_checknow"), follow_redirects=True) wait_for_all_checks(client) res = client.get(url_for("watchlist.index")) assert b"Exception: Processor module" in res.data and b'now_missing' in res.data, f'Should register that the plugin is missing for {uuid}'
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/tests/plugins/test_processor.py", "license": "Apache License 2.0", "lines": 30, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
dgtlmoon/changedetection.io:changedetectionio/tests/test_queue_handler.py
import os import time from flask import url_for from .util import set_original_response, wait_for_all_checks, wait_for_notification_endpoint_output from ..notification import valid_notification_formats from loguru import logger def test_queue_system(client, live_server, measure_memory_usage, datastore_path): """Test that multiple workers can process queue concurrently without blocking each other""" # (pytest) Werkzeug's threaded server uses ThreadPoolExecutor with a default limit of around 40 threads (or min(32, os.cpu_count() + 4)). items = os.cpu_count() +3 delay = 10 # Auto-queue is off here. live_server.app.config['DATASTORE'].data['settings']['application']['all_paused'] = True test_urls = [ f"{url_for('test_endpoint', _external=True)}?delay={delay}&id={i}&content=hello+test+content+{i}" for i in range(0, items) ] # Import 30 URLs to queue res = client.post( url_for("imports.import_page"), data={"urls": "\r\n".join(test_urls)}, follow_redirects=True ) assert f"{items} Imported".encode('utf-8') in res.data client.application.set_workers(items) start = time.time() res = client.get(url_for("ui.form_watch_checknow"), follow_redirects=True) time.sleep(delay/2) # Verify all workers are idle (no UUIDs being processed) from changedetectionio import worker_pool running_uuids = worker_pool.get_running_uuids() logger.debug( f"Should be atleast some workers running - {len(running_uuids)} UUIDs still being processed: {running_uuids}") assert len(running_uuids) != 0, f"Should be atleast some workers running - {len(running_uuids)} UUIDs still being processed: {running_uuids}" wait_for_all_checks(client) # all workers should be done in less than say 10 seconds (they take time to 'see' something is in the queue too) total_time = (time.time() - start) logger.debug(f"All workers finished {items} items in less than {delay} seconds per job. {total_time}s total") # if there was a bug in queue handler not running parallel, this would blow out to items*delay seconds assert total_time < delay + 10, f"All workers finished {items} items in less than {delay} seconds per job, total time {total_time}s" # Verify all workers are idle (no UUIDs being processed) from changedetectionio import worker_pool running_uuids = worker_pool.get_running_uuids() assert len(running_uuids) == 0, f"Expected all workers to be idle, but {len(running_uuids)} UUIDs still being processed: {running_uuids}"
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/tests/test_queue_handler.py", "license": "Apache License 2.0", "lines": 43, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
dgtlmoon/changedetection.io:changedetectionio/tests/test_api_notification_urls_validation.py
#!/usr/bin/env python3 """ Test notification_urls validation in Watch and Tag API endpoints. Ensures that invalid AppRise URLs are rejected when setting notification_urls. Valid AppRise notification URLs use specific protocols like: - posts://example.com - POST to HTTP endpoint - gets://example.com - GET to HTTP endpoint - mailto://user@example.com - Email - slack://token/channel - Slack - discord://webhook_id/webhook_token - Discord - etc. Invalid notification URLs: - https://example.com - Plain HTTPS is NOT a valid AppRise notification protocol - ftp://example.com - FTP is NOT a valid AppRise notification protocol - Plain URLs without proper AppRise protocol prefix """ from flask import url_for import json def test_watch_notification_urls_validation(client, live_server, measure_memory_usage, datastore_path): """Test that Watch PUT/POST endpoints validate notification_urls.""" api_key = live_server.app.config['DATASTORE'].data['settings']['application'].get('api_access_token') # Test 1: Create a watch with valid notification URLs valid_urls = ["posts://example.com/notify1", "posts://example.com/notify2"] res = client.post( url_for("createwatch"), data=json.dumps({ "url": "https://example.com", "notification_urls": valid_urls }), headers={'content-type': 'application/json', 'x-api-key': api_key} ) assert res.status_code == 201, "Should accept valid notification URLs on watch creation" watch_uuid = res.json['uuid'] # Verify the notification URLs were saved res = client.get( url_for("watch", uuid=watch_uuid), headers={'x-api-key': api_key} ) assert res.status_code == 200 assert set(res.json['notification_urls']) == set(valid_urls), "Valid notification URLs should be saved" # Test 2: Try to create a watch with invalid notification URLs (https:// is not valid) invalid_urls = ["https://example.com/webhook"] res = client.post( url_for("createwatch"), data=json.dumps({ "url": "https://example.com", "notification_urls": invalid_urls }), headers={'content-type': 'application/json', 'x-api-key': api_key} ) assert res.status_code == 400, "Should reject https:// notification URLs (not a valid AppRise protocol)" assert b"is not a valid AppRise URL" in res.data, "Should provide AppRise validation error message" # Test 2b: Also test other invalid protocols invalid_urls_ftp = ["ftp://not-apprise-url"] res = client.post( url_for("createwatch"), data=json.dumps({ "url": "https://example.com", "notification_urls": invalid_urls_ftp }), headers={'content-type': 'application/json', 'x-api-key': api_key} ) assert res.status_code == 400, "Should reject ftp:// notification URLs" assert b"is not a valid AppRise URL" in res.data, "Should provide AppRise validation error message" # Test 3: Update watch with valid notification URLs new_valid_urls = ["posts://newserver.com"] res = client.put( url_for("watch", uuid=watch_uuid), data=json.dumps({"notification_urls": new_valid_urls}), headers={'content-type': 'application/json', 'x-api-key': api_key} ) assert res.status_code == 200, "Should accept valid notification URLs on watch update" # Verify the notification URLs were updated res = client.get( url_for("watch", uuid=watch_uuid), headers={'x-api-key': api_key} ) assert res.status_code == 200 assert res.json['notification_urls'] == new_valid_urls, "Valid notification URLs should be updated" # Test 4: Try to update watch with invalid notification URLs (plain https:// not valid) invalid_https_url = ["https://example.com/webhook"] res = client.put( url_for("watch", uuid=watch_uuid), data=json.dumps({"notification_urls": invalid_https_url}), headers={'content-type': 'application/json', 'x-api-key': api_key} ) assert res.status_code == 400, "Should reject https:// notification URLs on watch update" assert b"is not a valid AppRise URL" in res.data, "Should provide AppRise validation error message" # Test 5: Update watch with non-list notification_urls (caught by OpenAPI schema validation) res = client.put( url_for("watch", uuid=watch_uuid), data=json.dumps({"notification_urls": "not-a-list"}), headers={'content-type': 'application/json', 'x-api-key': api_key} ) assert res.status_code == 400, "Should reject non-list notification_urls" assert b"Validation failed" in res.data or b"is not of type" in res.data # Test 6: Verify original URLs are preserved after failed update res = client.get( url_for("watch", uuid=watch_uuid), headers={'x-api-key': api_key} ) assert res.status_code == 200 assert res.json['notification_urls'] == new_valid_urls, "URLs should remain unchanged after validation failure" def test_tag_notification_urls_validation(client, live_server, measure_memory_usage, datastore_path): """Test that Tag PUT endpoint validates notification_urls.""" from changedetectionio.model import Tag api_key = live_server.app.config['DATASTORE'].data['settings']['application'].get('api_access_token') datastore = live_server.app.config['DATASTORE'] # Create a tag tag_uuid = datastore.add_tag(title="Test Tag") assert tag_uuid is not None # Test 1: Update tag with valid notification URLs valid_urls = ["posts://example.com/tag-notify"] res = client.put( url_for("tag", uuid=tag_uuid), data=json.dumps({"notification_urls": valid_urls}), headers={'content-type': 'application/json', 'x-api-key': api_key} ) assert res.status_code == 200, "Should accept valid notification URLs on tag update" # Verify the notification URLs were saved tag = datastore.data['settings']['application']['tags'][tag_uuid] assert tag['notification_urls'] == valid_urls, "Valid notification URLs should be saved to tag" # Test 2: Try to update tag with invalid notification URLs (https:// not valid) invalid_urls = ["https://example.com/webhook"] res = client.put( url_for("tag", uuid=tag_uuid), data=json.dumps({"notification_urls": invalid_urls}), headers={'content-type': 'application/json', 'x-api-key': api_key} ) assert res.status_code == 400, "Should reject https:// notification URLs on tag update" assert b"is not a valid AppRise URL" in res.data, "Should provide AppRise validation error message" # Test 3: Update tag with non-list notification_urls (caught by OpenAPI schema validation) res = client.put( url_for("tag", uuid=tag_uuid), data=json.dumps({"notification_urls": "not-a-list"}), headers={'content-type': 'application/json', 'x-api-key': api_key} ) assert res.status_code == 400, "Should reject non-list notification_urls" assert b"Validation failed" in res.data or b"is not of type" in res.data # Test 4: Verify original URLs are preserved after failed update tag = datastore.data['settings']['application']['tags'][tag_uuid] assert tag['notification_urls'] == valid_urls, "URLs should remain unchanged after validation failure"
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/tests/test_api_notification_urls_validation.py", "license": "Apache License 2.0", "lines": 142, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
dgtlmoon/changedetection.io:changedetectionio/store/base.py
""" Base classes for the datastore. This module defines the abstract interfaces that all datastore implementations must follow. """ from abc import ABC, abstractmethod from threading import Lock from loguru import logger class DataStore(ABC): """ Abstract base class for all datastore implementations. Defines the core interface that all datastores must implement for: - Loading and saving data - Managing watches - Handling settings - Providing data access """ lock = Lock() datastore_path = None @abstractmethod def reload_state(self, datastore_path, include_default_watches, version_tag): """ Load data from persistent storage. Args: datastore_path: Path to the datastore directory include_default_watches: Whether to create default watches if none exist version_tag: Application version string """ pass @abstractmethod def add_watch(self, url, **kwargs): """ Add a new watch. Args: url: URL to watch **kwargs: Additional watch parameters Returns: UUID of the created watch """ pass @abstractmethod def update_watch(self, uuid, update_obj): """ Update an existing watch. Args: uuid: Watch UUID update_obj: Dictionary of fields to update """ pass @abstractmethod def delete(self, uuid): """ Delete a watch. Args: uuid: Watch UUID to delete """ pass @property @abstractmethod def data(self): """ Access to the underlying data structure. Returns: Dictionary containing all datastore data """ pass
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/store/base.py", "license": "Apache License 2.0", "lines": 65, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
dgtlmoon/changedetection.io:changedetectionio/store/file_saving_datastore.py
""" File-based datastore with individual watch persistence and immediate commits. This module provides the FileSavingDataStore abstract class that implements: - Individual watch.json file persistence - Immediate commit-based persistence (watch.commit(), datastore.commit()) - Atomic file writes safe for NFS/NAS """ import glob import json import os import tempfile import time from loguru import logger from .base import DataStore from .. import strtobool # Try to import orjson for faster JSON serialization try: import orjson HAS_ORJSON = True except ImportError: HAS_ORJSON = False # Fsync configuration: Force file data to disk for crash safety # Default False to match legacy behavior (write-and-rename without fsync) # Set to True for mission-critical deployments requiring crash consistency FORCE_FSYNC_DATA_IS_CRITICAL = bool(strtobool(os.getenv('FORCE_FSYNC_DATA_IS_CRITICAL', 'False'))) # ============================================================================ # Helper Functions for Atomic File Operations # ============================================================================ def save_json_atomic(file_path, data_dict, label="file", max_size_mb=10): """ Save JSON data to disk using atomic write pattern. Generic helper for saving any JSON data (settings, watches, etc.) with: - Atomic write (temp file + rename) - Directory fsync for crash consistency (only for new files) - Size validation - Proper error handling Thread safety: Caller must hold datastore.lock to prevent concurrent modifications. Multi-process safety: Not supported - run only one app instance per datastore. Args: file_path: Full path to target JSON file data_dict: Dictionary to serialize label: Human-readable label for error messages (e.g., "watch", "settings") max_size_mb: Maximum allowed file size in MB Raises: ValueError: If serialized data exceeds max_size_mb OSError: If disk is full (ENOSPC) or other I/O error """ # Check if file already exists (before we start writing) # Directory fsync only needed for NEW files to persist the filename file_exists = os.path.exists(file_path) # Ensure parent directory exists parent_dir = os.path.dirname(file_path) os.makedirs(parent_dir, exist_ok=True) # Create temp file in same directory (required for NFS atomicity) fd, temp_path = tempfile.mkstemp( suffix='.tmp', prefix='json-', dir=parent_dir, text=False ) fd_closed = False try: # Serialize data t0 = time.time() if HAS_ORJSON: data = orjson.dumps(data_dict, option=orjson.OPT_INDENT_2) else: data = json.dumps(data_dict, indent=2, ensure_ascii=False).encode('utf-8') serialize_ms = (time.time() - t0) * 1000 # Safety check: validate size MAX_SIZE = max_size_mb * 1024 * 1024 data_size = len(data) if data_size > MAX_SIZE: raise ValueError( f"{label.capitalize()} data is unexpectedly large: {data_size / 1024 / 1024:.2f}MB " f"(max: {max_size_mb}MB). This indicates a bug or data corruption." ) # Write to temp file t1 = time.time() os.write(fd, data) write_ms = (time.time() - t1) * 1000 # Optional fsync: Force file data to disk for crash safety # Only if FORCE_FSYNC_DATA_IS_CRITICAL=True (default: False, matches legacy behavior) t2 = time.time() if FORCE_FSYNC_DATA_IS_CRITICAL: os.fsync(fd) file_fsync_ms = (time.time() - t2) * 1000 os.close(fd) fd_closed = True # Atomic rename t3 = time.time() os.replace(temp_path, file_path) rename_ms = (time.time() - t3) * 1000 # Sync directory to ensure filename metadata is durable # OPTIMIZATION: Only needed for NEW files. Existing files already have # directory entry persisted, so we only need file fsync for data durability. dir_fsync_ms = 0 if not file_exists: try: dir_fd = os.open(parent_dir, os.O_RDONLY) try: t4 = time.time() os.fsync(dir_fd) dir_fsync_ms = (time.time() - t4) * 1000 finally: os.close(dir_fd) except (OSError, AttributeError): # Windows doesn't support fsync on directories pass # Log timing breakdown for slow saves # total_ms = serialize_ms + write_ms + file_fsync_ms + rename_ms + dir_fsync_ms # if total_ms: # Log if save took more than 10ms # file_status = "new" if not file_exists else "update" # logger.trace( # f"Save timing breakdown ({total_ms:.1f}ms total, {file_status}): " # f"serialize={serialize_ms:.1f}ms, write={write_ms:.1f}ms, " # f"file_fsync={file_fsync_ms:.1f}ms, rename={rename_ms:.1f}ms, " # f"dir_fsync={dir_fsync_ms:.1f}ms, using_orjson={HAS_ORJSON}" # ) except OSError as e: # Cleanup temp file if not fd_closed: try: os.close(fd) except: pass if os.path.exists(temp_path): try: os.unlink(temp_path) except: pass # Provide helpful error messages if e.errno == 28: # ENOSPC raise OSError(f"Disk full: Cannot save {label}") from e elif e.errno == 122: # EDQUOT raise OSError(f"Disk quota exceeded: Cannot save {label}") from e else: raise OSError(f"I/O error saving {label}: {e}") from e except Exception as e: # Cleanup temp file if not fd_closed: try: os.close(fd) except: pass if os.path.exists(temp_path): try: os.unlink(temp_path) except: pass raise e def save_entity_atomic(entity_dir, uuid, entity_dict, filename, entity_type, max_size_mb): """ Save an entity (watch/tag) to disk using atomic write pattern. Generic function for saving any watch_base subclass (Watch, Tag, etc.). Args: entity_dir: Directory for this entity (e.g., /datastore/{uuid}) uuid: Entity UUID (for logging) entity_dict: Dictionary representation of the entity filename: JSON filename (e.g., 'watch.json', 'tag.json') entity_type: Type label for logging (e.g., 'watch', 'tag') max_size_mb: Maximum allowed file size in MB Raises: ValueError: If serialized data exceeds max_size_mb OSError: If disk is full (ENOSPC) or other I/O error """ entity_json = os.path.join(entity_dir, filename) save_json_atomic(entity_json, entity_dict, label=f"{entity_type} {uuid}", max_size_mb=max_size_mb) def save_watch_atomic(watch_dir, uuid, watch_dict): """ Save a watch to disk using atomic write pattern. Convenience wrapper around save_entity_atomic for watches. Kept for backwards compatibility. """ save_entity_atomic(watch_dir, uuid, watch_dict, "watch.json", "watch", max_size_mb=10) def load_watch_from_file(watch_json, uuid, rehydrate_entity_func): """ Load a watch from its JSON file. Args: watch_json: Path to the watch.json file uuid: Watch UUID rehydrate_entity_func: Function to convert dict to Watch object Returns: Watch object or None if failed """ try: # Check file size before reading file_size = os.path.getsize(watch_json) MAX_WATCH_SIZE = 10 * 1024 * 1024 # 10MB if file_size > MAX_WATCH_SIZE: logger.critical( f"CORRUPTED WATCH DATA: Watch {uuid} file is unexpectedly large: " f"{file_size / 1024 / 1024:.2f}MB (max: {MAX_WATCH_SIZE / 1024 / 1024}MB). " f"File: {watch_json}. This indicates a bug or data corruption. " f"Watch will be skipped." ) return None if HAS_ORJSON: with open(watch_json, 'rb') as f: watch_data = orjson.loads(f.read()) else: with open(watch_json, 'r', encoding='utf-8') as f: watch_data = json.load(f) # Rehydrate and return watch object watch_obj = rehydrate_entity_func(uuid, watch_data) return watch_obj except json.JSONDecodeError as e: logger.critical( f"CORRUPTED WATCH DATA: Failed to parse JSON for watch {uuid}. " f"File: {watch_json}. Error: {e}. " f"Watch will be skipped and may need manual recovery from backup." ) return None except ValueError as e: # orjson raises ValueError for invalid JSON if "invalid json" in str(e).lower() or HAS_ORJSON: logger.critical( f"CORRUPTED WATCH DATA: Failed to parse JSON for watch {uuid}. " f"File: {watch_json}. Error: {e}. " f"Watch will be skipped and may need manual recovery from backup." ) return None # Re-raise if it's not a JSON parsing error raise except FileNotFoundError: logger.error(f"Watch file not found: {watch_json} for watch {uuid}") return None except Exception as e: logger.error(f"Failed to load watch {uuid} from {watch_json}: {e}") return None def load_all_watches(datastore_path, rehydrate_entity_func): """ Load all watches from individual watch.json files. SYNCHRONOUS loading: Blocks until all watches are loaded. This ensures data consistency - web server won't accept requests until all watches are available. Progress logged every 100 watches. Args: datastore_path: Path to the datastore directory rehydrate_entity_func: Function to convert dict to Watch object Returns: Dictionary of uuid -> Watch object """ start_time = time.time() logger.info("Loading watches from individual watch.json files...") watching = {} if not os.path.exists(datastore_path): return watching # Find all watch.json files using glob (faster than manual directory traversal) glob_start = time.time() watch_files = glob.glob(os.path.join(datastore_path, "*", "watch.json")) glob_time = time.time() - glob_start total = len(watch_files) logger.debug(f"Found {total} watch.json files in {glob_time:.3f}s") loaded = 0 failed = 0 for watch_json in watch_files: # Extract UUID from path: /datastore/{uuid}/watch.json uuid_dir = os.path.basename(os.path.dirname(watch_json)) watch = load_watch_from_file(watch_json, uuid_dir, rehydrate_entity_func) if watch: watching[uuid_dir] = watch loaded += 1 if loaded % 100 == 0: logger.info(f"Loaded {loaded}/{total} watches...") else: # load_watch_from_file already logged the specific error failed += 1 elapsed = time.time() - start_time if failed > 0: logger.critical( f"LOAD COMPLETE: {loaded} watches loaded successfully, " f"{failed} watches FAILED to load (corrupted or invalid) " f"in {elapsed:.2f}s ({loaded/elapsed:.0f} watches/sec)" ) else: logger.info(f"Loaded {loaded} watches from disk in {elapsed:.2f}s ({loaded/elapsed:.0f} watches/sec)") return watching def load_tag_from_file(tag_json, uuid, rehydrate_entity_func): """ Load a tag from its JSON file. Args: tag_json: Path to the tag.json file uuid: Tag UUID rehydrate_entity_func: Function to convert dict to Tag object Returns: Tag object or None if failed """ try: # Check file size before reading file_size = os.path.getsize(tag_json) MAX_TAG_SIZE = 1 * 1024 * 1024 # 1MB if file_size > MAX_TAG_SIZE: logger.critical( f"CORRUPTED TAG DATA: Tag {uuid} file is unexpectedly large: " f"{file_size / 1024 / 1024:.2f}MB (max: {MAX_TAG_SIZE / 1024 / 1024}MB). " f"File: {tag_json}. This indicates a bug or data corruption. " f"Tag will be skipped." ) return None if HAS_ORJSON: with open(tag_json, 'rb') as f: tag_data = orjson.loads(f.read()) else: with open(tag_json, 'r', encoding='utf-8') as f: tag_data = json.load(f) tag_data['processor'] = 'restock_diff' # Rehydrate tag (convert dict to Tag object) # processor_override is set inside the rehydration function tag_obj = rehydrate_entity_func(uuid, tag_data) return tag_obj except json.JSONDecodeError as e: logger.critical( f"CORRUPTED TAG DATA: Failed to parse JSON for tag {uuid}. " f"File: {tag_json}. Error: {e}. " f"Tag will be skipped and may need manual recovery from backup." ) return None except ValueError as e: # orjson raises ValueError for invalid JSON if "invalid json" in str(e).lower() or HAS_ORJSON: logger.critical( f"CORRUPTED TAG DATA: Failed to parse JSON for tag {uuid}. " f"File: {tag_json}. Error: {e}. " f"Tag will be skipped and may need manual recovery from backup." ) return None # Re-raise if it's not a JSON parsing error raise except FileNotFoundError: logger.debug(f"Tag file not found: {tag_json} for tag {uuid}") return None except Exception as e: logger.error(f"Failed to load tag {uuid} from {tag_json}: {e}") return None def load_all_tags(datastore_path, rehydrate_entity_func): """ Load all tags from individual tag.json files. Tags are stored separately from settings in {uuid}/tag.json files. Args: datastore_path: Path to the datastore directory rehydrate_entity_func: Function to convert dict to Tag object Returns: Dictionary of uuid -> Tag object """ logger.info("Loading tags from individual tag.json files...") tags = {} if not os.path.exists(datastore_path): return tags # Find all tag.json files using glob tag_files = glob.glob(os.path.join(datastore_path, "*", "tag.json")) total = len(tag_files) if total == 0: logger.debug("No tag.json files found") return tags logger.debug(f"Found {total} tag.json files") loaded = 0 failed = 0 for tag_json in tag_files: # Extract UUID from path: /datastore/{uuid}/tag.json uuid_dir = os.path.basename(os.path.dirname(tag_json)) tag = load_tag_from_file(tag_json, uuid_dir, rehydrate_entity_func) if tag: tags[uuid_dir] = tag loaded += 1 else: # load_tag_from_file already logged the specific error failed += 1 if failed > 0: logger.warning(f"Loaded {loaded} tags, {failed} tags FAILED to load") else: logger.info(f"Loaded {loaded} tags from disk") return tags # ============================================================================ # FileSavingDataStore Class # ============================================================================ class FileSavingDataStore(DataStore): """ Abstract datastore that provides file persistence with immediate commits. Features: - Individual watch.json files (one per watch) - Immediate persistence via watch.commit() and datastore.commit() - Atomic file writes for crash safety Subclasses must implement: - rehydrate_entity(): Convert dict to Watch object - Access to internal __data structure for watch management """ def __init__(self): super().__init__() def _save_settings(self): """ Save settings to storage (polymorphic). Subclasses must implement for their backend. - File: changedetection.json - Redis: SET settings - SQL: UPDATE settings table """ raise NotImplementedError("Subclass must implement _save_settings") def _load_watches(self): """ Load all watches from storage (polymorphic). Subclasses must implement for their backend. - File: Read individual watch.json files - Redis: SCAN watch:* keys - SQL: SELECT * FROM watches """ raise NotImplementedError("Subclass must implement _load_watches") def _delete_watch(self, uuid): """ Delete a watch from storage (polymorphic). Subclasses must implement for their backend. - File: Delete {uuid}/ directory recursively - Redis: DEL watch:{uuid} - SQL: DELETE FROM watches WHERE uuid=? Args: uuid: Watch UUID to delete """ raise NotImplementedError("Subclass must implement _delete_watch")
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/store/file_saving_datastore.py", "license": "Apache License 2.0", "lines": 417, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
dgtlmoon/changedetection.io:changedetectionio/store/updates.py
""" Schema update migrations for the datastore. This module contains all schema version upgrade methods (update_1 through update_N). These are mixed into ChangeDetectionStore to keep the main store file focused. IMPORTANT: Each update could be run even when they have a new install and the schema is correct. Therefore - each `update_n` should be very careful about checking if it needs to actually run. """ import os import re import shutil import tarfile import time from loguru import logger from copy import deepcopy # Try to import orjson for faster JSON serialization try: import orjson HAS_ORJSON = True except ImportError: HAS_ORJSON = False from ..html_tools import TRANSLATE_WHITESPACE_TABLE from ..processors.restock_diff import Restock from ..blueprint.rss import RSS_CONTENT_FORMAT_DEFAULT from ..model import USE_SYSTEM_DEFAULT_NOTIFICATION_FORMAT_FOR_WATCH def create_backup_tarball(datastore_path, update_number): """ Create a tarball backup of the entire datastore structure before running an update. Includes: - All {uuid}/watch.json files - All {uuid}/tag.json files - changedetection.json (settings, if it exists) - url-watches.json (legacy format, if it exists) - Directory structure preserved Args: datastore_path: Path to datastore directory update_number: Update number being applied Returns: str: Path to created tarball, or None if backup failed Restoration: To restore from a backup: cd /path/to/datastore tar -xzf before-update-N-timestamp.tar.gz This will restore all watch.json and tag.json files and settings to their pre-update state. """ timestamp = int(time.time()) backup_filename = f"before-update-{update_number}-{timestamp}.tar.gz" backup_path = os.path.join(datastore_path, backup_filename) try: logger.info(f"Creating backup tarball: {backup_filename}") with tarfile.open(backup_path, "w:gz") as tar: # Backup changedetection.json if it exists (new format) changedetection_json = os.path.join(datastore_path, "changedetection.json") if os.path.isfile(changedetection_json): tar.add(changedetection_json, arcname="changedetection.json") logger.debug("Added changedetection.json to backup") # Backup url-watches.json if it exists (legacy format) url_watches_json = os.path.join(datastore_path, "url-watches.json") if os.path.isfile(url_watches_json): tar.add(url_watches_json, arcname="url-watches.json") logger.debug("Added url-watches.json to backup") # Backup all watch/tag directories with their JSON files # This preserves the UUID directory structure watch_count = 0 tag_count = 0 for entry in os.listdir(datastore_path): entry_path = os.path.join(datastore_path, entry) # Skip if not a directory if not os.path.isdir(entry_path): continue # Skip hidden directories and backup directories if entry.startswith('.') or entry.startswith('before-update-'): continue # Backup watch.json if exists watch_json = os.path.join(entry_path, "watch.json") if os.path.isfile(watch_json): tar.add(watch_json, arcname=f"{entry}/watch.json") watch_count += 1 if watch_count % 100 == 0: logger.debug(f"Backed up {watch_count} watch.json files...") # Backup tag.json if exists tag_json = os.path.join(entry_path, "tag.json") if os.path.isfile(tag_json): tar.add(tag_json, arcname=f"{entry}/tag.json") tag_count += 1 logger.success(f"Backup created: {backup_filename} ({watch_count} watches from disk, {tag_count} tags from disk)") return backup_path except Exception as e: logger.error(f"Failed to create backup tarball: {e}") # Try to clean up partial backup if os.path.exists(backup_path): try: os.unlink(backup_path) except: pass return None class DatastoreUpdatesMixin: """ Mixin class containing all schema update methods. This class is inherited by ChangeDetectionStore to provide schema migration functionality. Each update_N method upgrades the schema from version N-1 to version N. """ def get_updates_available(self): """ Discover all available update methods. Returns: list: Sorted list of update version numbers (e.g., [1, 2, 3, ..., 26]) """ import inspect updates_available = [] for i, o in inspect.getmembers(self, predicate=inspect.ismethod): m = re.search(r'update_(\d+)$', i) if m: updates_available.append(int(m.group(1))) updates_available.sort() return updates_available def run_updates(self, current_schema_version=None): import sys """ Run all pending schema updates sequentially. Args: current_schema_version: Optional current schema version. If provided, only run updates greater than this version. If None, uses the schema version from the datastore. If no schema version exists in datastore and it appears to be a fresh install, sets to latest update number (no updates needed). IMPORTANT: Each update could be run even when they have a new install and the schema is correct. Therefore - each `update_n` should be very careful about checking if it needs to actually run. Process: 1. Get list of available updates 2. For each update > current schema version: - Create backup of datastore - Run update method - Update schema version and commit settings - Commit all watches and tags 3. If any update fails, stop processing 4. All changes saved via individual .commit() calls """ updates_available = self.get_updates_available() if self.data.get('watching'): test_watch = self.data['watching'].get(next(iter(self.data.get('watching', {})))) from ..model.Watch import model if not isinstance(test_watch, model): import sys logger.critical("Cannot run updates! Watch structure must be re-hydrated back to a Watch model object!") sys.exit(1) if self.data['settings']['application'].get('tags',{}): test_tag = self.data['settings']['application'].get('tags',{}).get(next(iter(self.data['settings']['application'].get('tags',{})))) from ..model.Tag import model as tag_model if not isinstance(test_tag, tag_model): import sys logger.critical("Cannot run updates! Watch tag/group structure must be re-hydrated back to a Tag model object!") sys.exit(1) # Determine current schema version if current_schema_version is None: # Check if schema_version exists in datastore current_schema_version = self.data['settings']['application'].get('schema_version') if current_schema_version is None: # No schema version found - could be a fresh install or very old datastore # If this is a fresh/new config with no watches, assume it's up-to-date # and set to latest update number (no updates needed) if len(self.data['watching']) == 0: # Get the highest update number from available update methods latest_update = updates_available[-1] if updates_available else 0 logger.info(f"No schema version found and no watches exist - assuming fresh install, setting schema_version to {latest_update}") self.data['settings']['application']['schema_version'] = latest_update self.commit() return # No updates needed for fresh install else: # Has watches but no schema version - likely old datastore, run all updates logger.warning("No schema version found but watches exist - running all updates from version 0") current_schema_version = 0 logger.info(f"Current schema version: {current_schema_version}") updates_ran = [] for update_n in updates_available: if update_n > current_schema_version: logger.critical(f"Applying update_{update_n}") # Create tarball backup of entire datastore structure # This includes all watch.json files, settings, and preserves directory structure backup_path = create_backup_tarball(self.datastore_path, update_n) if backup_path: logger.info(f"Backup created at: {backup_path}") else: logger.warning("Backup creation failed, but continuing with update") try: update_method = getattr(self, f"update_{update_n}")() except Exception as e: logger.critical(f"Error while trying update_{update_n}") logger.exception(e) sys.exit(1) else: # Bump the version self.data['settings']['application']['schema_version'] = update_n self.commit() logger.success(f"Update {update_n} completed") # Track which updates ran updates_ran.append(update_n) # ============================================================================ # Individual Update Methods # ============================================================================ def update_1(self): """Convert minutes to seconds on settings and each watch.""" if self.data['settings']['requests'].get('minutes_between_check'): self.data['settings']['requests']['time_between_check']['minutes'] = self.data['settings']['requests']['minutes_between_check'] # Remove the default 'hours' that is set from the model self.data['settings']['requests']['time_between_check']['hours'] = None for uuid, watch in self.data['watching'].items(): if 'minutes_between_check' in watch: # Only upgrade individual watch time if it was set if watch.get('minutes_between_check', False): self.data['watching'][uuid]['time_between_check']['minutes'] = watch['minutes_between_check'] def update_2(self): """ Move the history list to a flat text file index. Better than SQLite because this list is only appended to, and works across NAS / NFS type setups. """ # @todo test running this on a newly updated one (when this already ran) for uuid, watch in self.data['watching'].items(): history = [] if watch.get('history', False): for d, p in watch['history'].items(): d = int(d) # Used to be keyed as str, we'll fix this now too history.append("{},{}\n".format(d, p)) if len(history): target_path = os.path.join(self.datastore_path, uuid) if os.path.exists(target_path): with open(os.path.join(target_path, "history.txt"), "w") as f: f.writelines(history) else: logger.warning(f"Datastore history directory {target_path} does not exist, skipping history import.") # No longer needed, dynamically pulled from the disk when needed. # But we should set it back to a empty dict so we don't break if this schema runs on an earlier version. # In the distant future we can remove this entirely self.data['watching'][uuid]['history'] = {} def update_3(self): """We incorrectly stored last_changed when there was not a change, and then confused the output list table.""" # see https://github.com/dgtlmoon/changedetection.io/pull/835 return def update_4(self): """`last_changed` not needed, we pull that information from the history.txt index.""" for uuid, watch in self.data['watching'].items(): try: # Remove it from the struct del(watch['last_changed']) except: continue return def update_5(self): """ If the watch notification body, title look the same as the global one, unset it, so the watch defaults back to using the main settings. In other words - the watch notification_title and notification_body are not needed if they are the same as the default one. """ current_system_body = self.data['settings']['application']['notification_body'].translate(TRANSLATE_WHITESPACE_TABLE) current_system_title = self.data['settings']['application']['notification_body'].translate(TRANSLATE_WHITESPACE_TABLE) for uuid, watch in self.data['watching'].items(): try: watch_body = watch.get('notification_body', '') if watch_body and watch_body.translate(TRANSLATE_WHITESPACE_TABLE) == current_system_body: # Looks the same as the default one, so unset it watch['notification_body'] = None watch_title = watch.get('notification_title', '') if watch_title and watch_title.translate(TRANSLATE_WHITESPACE_TABLE) == current_system_title: # Looks the same as the default one, so unset it watch['notification_title'] = None except Exception as e: continue return def update_7(self): """ We incorrectly used common header overrides that should only apply to Requests. These are now handled in content_fetcher::html_requests and shouldnt be passed to Playwright/Selenium. """ # These were hard-coded in early versions for v in ['User-Agent', 'Accept', 'Accept-Encoding', 'Accept-Language']: if self.data['settings']['headers'].get(v): del self.data['settings']['headers'][v] def update_8(self): """Convert filters to a list of filters css_filter -> include_filters.""" for uuid, watch in self.data['watching'].items(): try: existing_filter = watch.get('css_filter', '') if existing_filter: watch['include_filters'] = [existing_filter] except: continue return def update_9(self): """Convert old static notification tokens to jinja2 tokens.""" # Each watch # only { } not {{ or }} r = r'(?<!{){(?!{)(\w+)(?<!})}(?!})' for uuid, watch in self.data['watching'].items(): try: n_body = watch.get('notification_body', '') if n_body: watch['notification_body'] = re.sub(r, r'{{\1}}', n_body) n_title = watch.get('notification_title') if n_title: watch['notification_title'] = re.sub(r, r'{{\1}}', n_title) n_urls = watch.get('notification_urls') if n_urls: for i, url in enumerate(n_urls): watch['notification_urls'][i] = re.sub(r, r'{{\1}}', url) except: continue # System wide n_body = self.data['settings']['application'].get('notification_body') if n_body: self.data['settings']['application']['notification_body'] = re.sub(r, r'{{\1}}', n_body) n_title = self.data['settings']['application'].get('notification_title') if n_body: self.data['settings']['application']['notification_title'] = re.sub(r, r'{{\1}}', n_title) n_urls = self.data['settings']['application'].get('notification_urls') if n_urls: for i, url in enumerate(n_urls): self.data['settings']['application']['notification_urls'][i] = re.sub(r, r'{{\1}}', url) return def update_10(self): """Some setups may have missed the correct default, so it shows the wrong config in the UI, although it will default to system-wide.""" for uuid, watch in self.data['watching'].items(): try: if not watch.get('fetch_backend', ''): watch['fetch_backend'] = 'system' except: continue return def update_12(self): """Create tag objects and their references from existing tag text.""" i = 0 for uuid, watch in self.data['watching'].items(): # Split out and convert old tag string tag = watch.get('tag') if tag: tag_uuids = [] for t in tag.split(','): tag_uuids.append(self.add_tag(title=t)) self.data['watching'][uuid]['tags'] = tag_uuids def update_13(self): """#1775 - Update 11 did not update the records correctly when adding 'date_created' values for sorting.""" i = 0 for uuid, watch in self.data['watching'].items(): if not watch.get('date_created'): self.data['watching'][uuid]['date_created'] = i i += 1 return def update_14(self): """#1774 - protect xpath1 against migration.""" for awatch in self.data["watching"]: if self.data["watching"][awatch]['include_filters']: for num, selector in enumerate(self.data["watching"][awatch]['include_filters']): if selector.startswith('/'): self.data["watching"][awatch]['include_filters'][num] = 'xpath1:' + selector if selector.startswith('xpath:'): self.data["watching"][awatch]['include_filters'][num] = selector.replace('xpath:', 'xpath1:', 1) def update_15(self): """Use more obvious default time setting.""" for uuid in self.data["watching"]: if self.data["watching"][uuid]['time_between_check'] == self.data['settings']['requests']['time_between_check']: # What the old logic was, which was pretty confusing self.data["watching"][uuid]['time_between_check_use_default'] = True elif all(value is None or value == 0 for value in self.data["watching"][uuid]['time_between_check'].values()): self.data["watching"][uuid]['time_between_check_use_default'] = True else: # Something custom here self.data["watching"][uuid]['time_between_check_use_default'] = False def update_16(self): """Correctly set datatype for older installs where 'tag' was string and update_12 did not catch it.""" for uuid, watch in self.data['watching'].items(): if isinstance(watch.get('tags'), str): self.data['watching'][uuid]['tags'] = [] def update_17(self): """Migrate old 'in_stock' values to the new Restock.""" for uuid, watch in self.data['watching'].items(): if 'in_stock' in watch: watch['restock'] = Restock({'in_stock': watch.get('in_stock')}) del watch['in_stock'] def update_18(self): """Migrate old restock settings.""" for uuid, watch in self.data['watching'].items(): if not watch.get('restock_settings'): # So we enable price following by default self.data['watching'][uuid]['restock_settings'] = {'follow_price_changes': True} # Migrate and cleanoff old value self.data['watching'][uuid]['restock_settings']['in_stock_processing'] = 'in_stock_only' if watch.get( 'in_stock_only') else 'all_changes' if self.data['watching'][uuid].get('in_stock_only'): del (self.data['watching'][uuid]['in_stock_only']) def update_19(self): """Compress old elements.json to elements.deflate, saving disk, this compression is pretty fast.""" import zlib for uuid, watch in self.data['watching'].items(): json_path = os.path.join(self.datastore_path, uuid, "elements.json") deflate_path = os.path.join(self.datastore_path, uuid, "elements.deflate") if os.path.exists(json_path): with open(json_path, "rb") as f_j: with open(deflate_path, "wb") as f_d: logger.debug(f"Compressing {str(json_path)} to {str(deflate_path)}..") f_d.write(zlib.compress(f_j.read())) os.unlink(json_path) def update_20(self): """Migrate extract_title_as_title to use_page_title_in_list.""" for uuid, watch in self.data['watching'].items(): if self.data['watching'][uuid].get('extract_title_as_title'): self.data['watching'][uuid]['use_page_title_in_list'] = self.data['watching'][uuid].get('extract_title_as_title') del self.data['watching'][uuid]['extract_title_as_title'] if self.data['settings']['application'].get('extract_title_as_title'): # Ensure 'ui' key exists (defensive for edge cases where base_config merge didn't happen) if 'ui' not in self.data['settings']['application']: self.data['settings']['application']['ui'] = { 'use_page_title_in_list': True, 'open_diff_in_new_tab': True, 'socket_io_enabled': True, 'favicons_enabled': True } self.data['settings']['application']['ui']['use_page_title_in_list'] = self.data['settings']['application'].get('extract_title_as_title') def update_21(self): """Migrate timezone to scheduler_timezone_default.""" if self.data['settings']['application'].get('timezone'): self.data['settings']['application']['scheduler_timezone_default'] = self.data['settings']['application'].get('timezone') del self.data['settings']['application']['timezone'] def update_23(self): """Some notification formats got the wrong name type.""" def re_run(formats): sys_n_format = self.data['settings']['application'].get('notification_format') key_exists_as_value = next((k for k, v in formats.items() if v == sys_n_format), None) if key_exists_as_value: # key of "Plain text" logger.success(f"['settings']['application']['notification_format'] '{sys_n_format}' -> '{key_exists_as_value}'") self.data['settings']['application']['notification_format'] = key_exists_as_value for uuid, watch in self.data['watching'].items(): n_format = self.data['watching'][uuid].get('notification_format') key_exists_as_value = next((k for k, v in formats.items() if v == n_format), None) if key_exists_as_value and key_exists_as_value != USE_SYSTEM_DEFAULT_NOTIFICATION_FORMAT_FOR_WATCH: # key of "Plain text" logger.success(f"['watching'][{uuid}]['notification_format'] '{n_format}' -> '{key_exists_as_value}'") self.data['watching'][uuid]['notification_format'] = key_exists_as_value # should be 'text' or whatever for uuid, tag in self.data['settings']['application']['tags'].items(): n_format = self.data['settings']['application']['tags'][uuid].get('notification_format') key_exists_as_value = next((k for k, v in formats.items() if v == n_format), None) if key_exists_as_value and key_exists_as_value != USE_SYSTEM_DEFAULT_NOTIFICATION_FORMAT_FOR_WATCH: # key of "Plain text" logger.success( f"['settings']['application']['tags'][{uuid}]['notification_format'] '{n_format}' -> '{key_exists_as_value}'") self.data['settings']['application']['tags'][uuid][ 'notification_format'] = key_exists_as_value # should be 'text' or whatever from ..notification import valid_notification_formats formats = deepcopy(valid_notification_formats) re_run(formats) # And in previous versions, it was "text" instead of Plain text, Markdown instead of "Markdown to HTML" formats['text'] = 'Text' formats['markdown'] = 'Markdown' re_run(formats) def update_24(self): """RSS types should be inline with the same names as notification types.""" rss_format = self.data['settings']['application'].get('rss_content_format') if not rss_format or 'text' in rss_format: # might have been 'plaintext, 'plain text' or something self.data['settings']['application']['rss_content_format'] = RSS_CONTENT_FORMAT_DEFAULT elif 'html' in rss_format: self.data['settings']['application']['rss_content_format'] = 'htmlcolor' else: # safe fallback to text self.data['settings']['application']['rss_content_format'] = RSS_CONTENT_FORMAT_DEFAULT def update_25(self): """Different processors now hold their own history.txt.""" for uuid, watch in self.data['watching'].items(): processor = self.data['watching'][uuid].get('processor') if processor != 'text_json_diff': old_history_txt = os.path.join(self.datastore_path, "history.txt") target_history_name = f"history-{processor}.txt" if os.path.isfile(old_history_txt) and not os.path.isfile(target_history_name): new_history_txt = os.path.join(self.datastore_path, target_history_name) logger.debug(f"Renaming history index {old_history_txt} to {new_history_txt}...") shutil.move(old_history_txt, new_history_txt) def migrate_legacy_db_format(self): """ Migration: Individual watch persistence (COPY-based, safe rollback). Loads legacy url-watches.json format and migrates to: - {uuid}/watch.json (per watch) - changedetection.json (settings only) IMPORTANT: - A tarball backup (before-update-26-timestamp.tar.gz) is created before migration - url-watches.json is LEFT INTACT for rollback safety - Users can roll back by simply downgrading to the previous version - Or restore from tarball: tar -xzf before-update-26-*.tar.gz This is a dedicated migration release - users upgrade at their own pace. """ logger.critical("=" * 80) logger.critical("Running migration: Individual watch persistence (update_26)") logger.critical("COPY-based migration: url-watches.json will remain intact for rollback") logger.critical("=" * 80) # Populate settings from legacy data logger.info("Populating settings from legacy data...") watch_count = len(self.data['watching']) logger.success(f"Loaded {watch_count} watches from legacy format") # Phase 1: Save all watches to individual files logger.critical(f"Phase 1/4: Saving {watch_count} watches to individual watch.json files...") saved_count = 0 for uuid, watch in self.data['watching'].items(): try: watch.commit() saved_count += 1 if saved_count % 100 == 0: logger.info(f" Progress: {saved_count}/{watch_count} watches migrated...") except Exception as e: logger.error(f"Failed to save watch {uuid}: {e}") raise Exception( f"Migration failed: Could not save watch {uuid}. " f"url-watches.json remains intact, safe to retry. Error: {e}" ) logger.critical(f"Phase 1 complete: Saved {saved_count} watches") # Phase 2: Verify all files exist logger.critical("Phase 2/4: Verifying all watch.json files were created...") missing = [] for uuid in self.data['watching'].keys(): watch_json = os.path.join(self.datastore_path, uuid, "watch.json") if not os.path.isfile(watch_json): missing.append(uuid) if missing: raise Exception( f"Migration failed: {len(missing)} watch files missing: {missing[:5]}... " f"url-watches.json remains intact, safe to retry." ) logger.critical(f"Phase 2 complete: Verified {watch_count} watch files") # Phase 3: Create new settings file logger.critical("Phase 3/4: Creating changedetection.json...") try: self._save_settings() except Exception as e: logger.error(f"Failed to create changedetection.json: {e}") raise Exception( f"Migration failed: Could not create changedetection.json. " f"url-watches.json remains intact, safe to retry. Error: {e}" ) # Phase 4: Verify settings file exists logger.critical("Phase 4/4: Verifying changedetection.json exists...") changedetection_json_new_schema=os.path.join(self.datastore_path, "changedetection.json") if not os.path.isfile(changedetection_json_new_schema): import sys logger.critical("Migration failed, changedetection.json not found after update ran!") sys.exit(1) logger.critical("Phase 4 complete: Verified changedetection.json exists") # Success! Now reload from new format logger.critical("Reloading datastore from new format...") # write it to disk, it will be saved without ['watching'] in the JSON db because we find it from disk glob self._save_settings() logger.success("Datastore reloaded from new format successfully") logger.critical("=" * 80) logger.critical("MIGRATION COMPLETED SUCCESSFULLY!") logger.critical("=" * 80) logger.info("") logger.info("New format:") logger.info(f" - {watch_count} individual watch.json files created") logger.info(f" - changedetection.json created (settings only)") logger.info("") logger.info("Rollback safety:") logger.info(" - url-watches.json preserved for rollback") logger.info(" - To rollback: downgrade to previous version and restart") logger.info(" - No manual file operations needed") logger.info("") logger.info("Optional cleanup (after testing new version):") logger.info(f" - rm {os.path.join(self.datastore_path, 'url-watches.json')}") logger.info("") def update_26(self): self.migrate_legacy_db_format() # Re-run tag to JSON migration def update_29(self): """ Migrate tags to individual tag.json files. Tags are currently saved only in changedetection.json (settings). This migration ALSO saves them to individual {uuid}/tag.json files, similar to how watches are stored (dual storage). Benefits: - Allows atomic tag updates without rewriting entire settings - Enables independent tag versioning/backup - Maintains backwards compatibility (tags stay in settings too) """ logger.critical("=" * 80) logger.critical("Running migration: Individual tag persistence (update_28)") logger.critical("Creating individual tag.json files") logger.critical("=" * 80) tags = self.data['settings']['application'].get('tags', {}) tag_count = len(tags) if tag_count == 0: logger.info("No tags found, skipping migration") return logger.info(f"Migrating {tag_count} tags to individual tag.json files...") saved_count = 0 failed_count = 0 for uuid, tag_data in tags.items(): if os.path.isfile(os.path.join(self.datastore_path, uuid, "tag.json")): logger.debug(f"Tag {uuid} tag.json exists, skipping") continue try: tag_data.commit() saved_count += 1 if saved_count % 10 == 0: logger.info(f" Progress: {saved_count}/{tag_count} tags migrated...") except Exception as e: logger.error(f"Failed to save tag {uuid} ({tag_data.get('title', 'unknown')}): {e}") failed_count += 1 if failed_count > 0: logger.warning(f"Migration complete: {saved_count} tags saved, {failed_count} tags FAILED") else: logger.success(f"Migration complete: {saved_count} tags saved to individual tag.json files") # Tags remain in settings for backwards compatibility AND easy access # On next load, _load_tags() will read from tag.json files and merge with settings logger.info("Tags saved to both settings AND individual tag.json files") logger.info("Future tag edits will update both locations (dual storage)") logger.critical("=" * 80) # write it to disk, it will be saved without ['tags'] in the JSON db because we find it from disk glob # (left this out by accident in previous update, added tags={} in the changedetection.json save_to_disk) self._save_settings() def update_30(self): """Migrate restock_settings out of watch.json into restock_diff.json processor config file. Previously, restock_diff processor settings (in_stock_processing, follow_price_changes, etc.) were stored directly in the watch dict (watch.json). They now belong in a separate per-watch processor config file (restock_diff.json) consistent with the processor_config_* API system. For tags: restock_settings key is renamed to processor_config_restock_diff in the tag dict, matching what the API writes when updating a tag. Safe to re-run: skips watches that already have a restock_diff.json, skips tags that already have processor_config_restock_diff set. """ import json # --- Watches --- for uuid, watch in self.data['watching'].items(): if watch.get('processor') != 'restock_diff': continue restock_settings = watch.get('restock_settings') if not restock_settings: continue data_dir = watch.data_dir if data_dir: watch.ensure_data_dir_exists() filepath = os.path.join(data_dir, 'restock_diff.json') if not os.path.isfile(filepath): with open(filepath, 'w', encoding='utf-8') as f: json.dump({'restock_diff': restock_settings}, f, indent=2) logger.info(f"update_30: migrated restock_settings → {filepath}") del self.data['watching'][uuid]['restock_settings'] watch.commit() # --- Tags --- for tag_uuid, tag in self.data['settings']['application']['tags'].items(): restock_settings = tag.get('restock_settings') if not restock_settings or tag.get('processor_config_restock_diff'): continue tag['processor_config_restock_diff'] = restock_settings del tag['restock_settings'] tag.commit() logger.info(f"update_30: migrated tag {tag_uuid} restock_settings → processor_config_restock_diff")
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/store/updates.py", "license": "Apache License 2.0", "lines": 645, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
dgtlmoon/changedetection.io:changedetectionio/favicon_utils.py
""" Favicon utilities for changedetection.io Handles favicon MIME type detection with caching """ from functools import lru_cache @lru_cache(maxsize=1000) def get_favicon_mime_type(filepath): """ Detect MIME type of favicon by reading file content using puremagic. Results are cached to avoid repeatedly reading the same files. Args: filepath: Full path to the favicon file Returns: MIME type string (e.g., 'image/png') """ mime = None try: import puremagic with open(filepath, 'rb') as f: content_bytes = f.read(200) # Read first 200 bytes detections = puremagic.magic_string(content_bytes) if detections: mime = detections[0].mime_type except Exception: pass # Fallback to mimetypes if puremagic fails if not mime: import mimetypes mime, _ = mimetypes.guess_type(filepath) # Final fallback based on extension if not mime: mime = 'image/x-icon' if filepath.endswith('.ico') else 'image/png' return mime
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/favicon_utils.py", "license": "Apache License 2.0", "lines": 33, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
dgtlmoon/changedetection.io:changedetectionio/tests/test_api_security.py
#!/usr/bin/env python3 """ Comprehensive security and edge case tests for the API. Tests critical areas that were identified as gaps in the existing test suite. """ import time import json import threading import uuid as uuid_module from flask import url_for from .util import live_server_setup, wait_for_all_checks, delete_all_watches import os def set_original_response(datastore_path): test_return_data = """<html> <body> Some initial text<br> <p>Which is across multiple lines</p> </body> </html> """ with open(os.path.join(datastore_path, "endpoint-content.txt"), "w") as f: f.write(test_return_data) return None def is_valid_uuid(val): try: uuid_module.UUID(str(val)) return True except ValueError: return False # ============================================================================ # TIER 1: CRITICAL SECURITY TESTS # ============================================================================ def test_api_path_traversal_in_uuids(client, live_server, measure_memory_usage, datastore_path): """ Test that path traversal attacks via UUID parameter are blocked. Addresses CVE-like vulnerabilities where ../../../ in UUID could access arbitrary files. """ api_key = live_server.app.config['DATASTORE'].data['settings']['application'].get('api_access_token') set_original_response(datastore_path=datastore_path) test_url = url_for('test_endpoint', _external=True) # Create a valid watch first res = client.post( url_for("createwatch"), data=json.dumps({"url": test_url, "title": "Valid watch"}), headers={'content-type': 'application/json', 'x-api-key': api_key}, ) assert res.status_code == 201 valid_uuid = res.json.get('uuid') # Test 1: Path traversal with ../../../ res = client.get( f"/api/v1/watch/../../etc/passwd", headers={'x-api-key': api_key} ) assert res.status_code in [400, 404], "Path traversal should be rejected" # Test 2: Encoded path traversal res = client.get( "/api/v1/watch/..%2F..%2F..%2Fetc%2Fpasswd", headers={'x-api-key': api_key} ) assert res.status_code in [400, 404], "Encoded path traversal should be rejected" # Test 3: Double-encoded path traversal res = client.get( "/api/v1/watch/%2e%2e%2f%2e%2e%2f%2e%2e%2f", headers={'x-api-key': api_key} ) assert res.status_code in [400, 404], "Double-encoded traversal should be rejected" # Test 4: Try to access datastore file res = client.get( "/api/v1/watch/../url-watches.json", headers={'x-api-key': api_key} ) assert res.status_code in [400, 404], "Access to datastore should be blocked" # Test 5: Null byte injection res = client.get( f"/api/v1/watch/{valid_uuid}%00.json", headers={'x-api-key': api_key} ) # Should either work (ignoring null byte) or reject - but not crash assert res.status_code in [200, 400, 404] # Test 6: DELETE with path traversal res = client.delete( "/api/v1/watch/../../datastore/url-watches.json", headers={'x-api-key': api_key} ) assert res.status_code in [400, 404, 405], "DELETE with traversal should be blocked (405=method not allowed is also acceptable)" # Cleanup client.delete(url_for("watch", uuid=valid_uuid), headers={'x-api-key': api_key}) delete_all_watches(client) def test_api_injection_via_headers_and_proxy(client, live_server, measure_memory_usage, datastore_path): """ Test that injection attacks via headers and proxy fields are properly sanitized. Addresses XSS and injection vulnerabilities. """ api_key = live_server.app.config['DATASTORE'].data['settings']['application'].get('api_access_token') set_original_response(datastore_path=datastore_path) test_url = url_for('test_endpoint', _external=True) # Test 1: XSS in headers res = client.post( url_for("createwatch"), data=json.dumps({ "url": test_url, "headers": { "User-Agent": "<script>alert(1)</script>", "X-Custom": "'; DROP TABLE watches; --" } }), headers={'content-type': 'application/json', 'x-api-key': api_key}, ) # Headers are metadata used for HTTP requests, not HTML rendering # Storing them as-is is expected behavior assert res.status_code in [201, 400] if res.status_code == 201: watch_uuid = res.json.get('uuid') # Verify headers are stored (API returns JSON, not HTML, so no XSS risk) res = client.get(url_for("watch", uuid=watch_uuid), headers={'x-api-key': api_key}) assert res.status_code == 200 client.delete(url_for("watch", uuid=watch_uuid), headers={'x-api-key': api_key}) # Test 2: Null bytes in headers res = client.post( url_for("createwatch"), data=json.dumps({ "url": test_url, "headers": {"X-Test": "value\x00null"} }), headers={'content-type': 'application/json', 'x-api-key': api_key}, ) # Should handle null bytes gracefully (reject or sanitize) assert res.status_code in [201, 400] # Test 3: Malformed proxy string res = client.post( url_for("createwatch"), data=json.dumps({ "url": test_url, "proxy": "http://evil.com:8080@victim.com" }), headers={'content-type': 'application/json', 'x-api-key': api_key}, ) # Should reject invalid proxy format assert res.status_code == 400 # Test 4: Control characters in notification title res = client.post( url_for("createwatch"), data=json.dumps({ "url": test_url, "notification_title": "Test\r\nInjected-Header: value" }), headers={'content-type': 'application/json', 'x-api-key': api_key}, ) # Should accept but sanitize control characters if res.status_code == 201: watch_uuid = res.json.get('uuid') client.delete(url_for("watch", uuid=watch_uuid), headers={'x-api-key': api_key}) delete_all_watches(client) def test_api_large_payload_dos(client, live_server, measure_memory_usage, datastore_path): """ Test that excessively large payloads are rejected to prevent DoS. Addresses memory leak issues found in changelog. """ api_key = live_server.app.config['DATASTORE'].data['settings']['application'].get('api_access_token') set_original_response(datastore_path=datastore_path) test_url = url_for('test_endpoint', _external=True) # Test 1: Huge ignore_text array res = client.post( url_for("createwatch"), data=json.dumps({ "url": test_url, "ignore_text": ["a" * 10000] * 100 # 1MB of data }), headers={'content-type': 'application/json', 'x-api-key': api_key}, ) # Should either accept (with limits) or reject if res.status_code == 201: watch_uuid = res.json.get('uuid') client.delete(url_for("watch", uuid=watch_uuid), headers={'x-api-key': api_key}) # Test 2: Massive headers object huge_headers = {f"X-Header-{i}": "x" * 1000 for i in range(100)} res = client.post( url_for("createwatch"), data=json.dumps({ "url": test_url, "headers": huge_headers }), headers={'content-type': 'application/json', 'x-api-key': api_key}, ) # Should reject or truncate assert res.status_code in [201, 400, 413] if res.status_code == 201: watch_uuid = res.json.get('uuid') client.delete(url_for("watch", uuid=watch_uuid), headers={'x-api-key': api_key}) # Test 3: Huge browser_steps array res = client.post( url_for("createwatch"), data=json.dumps({ "url": test_url, "browser_steps": [ {"operation": "click", "selector": "#test" * 1000, "optional_value": ""} ] * 100 }), headers={'content-type': 'application/json', 'x-api-key': api_key}, ) # Should reject or limit assert res.status_code in [201, 400, 413] if res.status_code == 201: watch_uuid = res.json.get('uuid') client.delete(url_for("watch", uuid=watch_uuid), headers={'x-api-key': api_key}) # Test 4: Extremely long title res = client.post( url_for("createwatch"), data=json.dumps({ "url": test_url, "title": "x" * 100000 # 100KB title }), headers={'content-type': 'application/json', 'x-api-key': api_key}, ) # Should reject (exceeds maxLength: 5000) assert res.status_code == 400 delete_all_watches(client) def test_api_utf8_encoding_edge_cases(client, live_server, measure_memory_usage, datastore_path): """ Test UTF-8 encoding edge cases that have caused bugs on Windows. Addresses 18+ encoding bugs from changelog. """ api_key = live_server.app.config['DATASTORE'].data['settings']['application'].get('api_access_token') set_original_response(datastore_path=datastore_path) test_url = url_for('test_endpoint', _external=True) # Test 1: Unicode in title (should work) res = client.post( url_for("createwatch"), data=json.dumps({ "url": test_url, "title": "Test 中文 Ελληνικά 日本語 🔥" }), headers={'content-type': 'application/json', 'x-api-key': api_key}, ) assert res.status_code == 201 watch_uuid = res.json.get('uuid') # Verify it round-trips correctly res = client.get(url_for("watch", uuid=watch_uuid), headers={'x-api-key': api_key}) assert res.status_code == 200 assert "中文" in res.json.get('title') client.delete(url_for("watch", uuid=watch_uuid), headers={'x-api-key': api_key}) # Test 2: Unicode in URL query parameters res = client.post( url_for("createwatch"), data=json.dumps({ "url": test_url + "?search=日本語" }), headers={'content-type': 'application/json', 'x-api-key': api_key}, ) # Should handle URL encoding properly assert res.status_code in [201, 400] if res.status_code == 201: watch_uuid = res.json.get('uuid') client.delete(url_for("watch", uuid=watch_uuid), headers={'x-api-key': api_key}) # Test 3: Null byte in title (should be rejected or sanitized) res = client.post( url_for("createwatch"), data=json.dumps({ "url": test_url, "title": "Test\x00Title" }), headers={'content-type': 'application/json', 'x-api-key': api_key}, ) # Should handle gracefully assert res.status_code in [201, 400] if res.status_code == 201: watch_uuid = res.json.get('uuid') client.delete(url_for("watch", uuid=watch_uuid), headers={'x-api-key': api_key}) # Test 4: BOM (Byte Order Mark) in title res = client.post( url_for("createwatch"), data=json.dumps({ "url": test_url, "title": "\ufeffTest with BOM" }), headers={'content-type': 'application/json', 'x-api-key': api_key}, ) assert res.status_code in [201, 400] if res.status_code == 201: watch_uuid = res.json.get('uuid') client.delete(url_for("watch", uuid=watch_uuid), headers={'x-api-key': api_key}) delete_all_watches(client) def test_api_concurrency_race_conditions(client, live_server, measure_memory_usage, datastore_path): """ Test concurrent API requests to detect race conditions. Addresses 20+ concurrency bugs from changelog. """ api_key = live_server.app.config['DATASTORE'].data['settings']['application'].get('api_access_token') set_original_response(datastore_path=datastore_path) test_url = url_for('test_endpoint', _external=True) # Create a watch res = client.post( url_for("createwatch"), data=json.dumps({"url": test_url, "title": "Concurrency test"}), headers={'content-type': 'application/json', 'x-api-key': api_key}, ) assert res.status_code == 201 watch_uuid = res.json.get('uuid') wait_for_all_checks(client) # Test 1: Concurrent updates to same watch # Note: Flask test client is not thread-safe, so we test sequential updates instead # Real concurrency issues would be caught in integration tests with actual HTTP requests results = [] for i in range(10): try: r = client.put( url_for("watch", uuid=watch_uuid), data=json.dumps({"title": f"Title {i}"}), headers={'content-type': 'application/json', 'x-api-key': api_key}, ) results.append(r.status_code) except Exception as e: results.append(str(e)) # All updates should succeed (200) without crashes assert all(r == 200 for r in results), f"Some updates failed: {results}" # Test 2: Update while watch is being checked # Queue a recheck client.get( url_for("watch", uuid=watch_uuid, recheck=True), headers={'x-api-key': api_key} ) # Immediately update it res = client.put( url_for("watch", uuid=watch_uuid), data=json.dumps({"title": "Updated during check"}), headers={'content-type': 'application/json', 'x-api-key': api_key}, ) # Should succeed without error assert res.status_code == 200 # Test 3: Delete watch that's being processed # Create another watch res = client.post( url_for("createwatch"), data=json.dumps({"url": test_url}), headers={'content-type': 'application/json', 'x-api-key': api_key}, ) watch_uuid2 = res.json.get('uuid') # Queue it for checking client.get(url_for("watch", uuid=watch_uuid2, recheck=True), headers={'x-api-key': api_key}) # Immediately delete it res = client.delete(url_for("watch", uuid=watch_uuid2), headers={'x-api-key': api_key}) # Should succeed or return appropriate error assert res.status_code in [204, 404, 400] # Cleanup client.delete(url_for("watch", uuid=watch_uuid), headers={'x-api-key': api_key}) delete_all_watches(client) # ============================================================================ # TIER 2: IMPORTANT FUNCTIONALITY TESTS # ============================================================================ def test_api_time_validation_edge_cases(client, live_server, measure_memory_usage, datastore_path): """ Test time_between_check validation edge cases. """ api_key = live_server.app.config['DATASTORE'].data['settings']['application'].get('api_access_token') set_original_response(datastore_path=datastore_path) test_url = url_for('test_endpoint', _external=True) # Test 1: Zero interval res = client.post( url_for("createwatch"), data=json.dumps({ "url": test_url, "time_between_check_use_default": False, "time_between_check": {"seconds": 0} }), headers={'content-type': 'application/json', 'x-api-key': api_key}, ) assert res.status_code == 400, "Zero interval should be rejected" # Test 2: Negative interval res = client.post( url_for("createwatch"), data=json.dumps({ "url": test_url, "time_between_check_use_default": False, "time_between_check": {"seconds": -100} }), headers={'content-type': 'application/json', 'x-api-key': api_key}, ) assert res.status_code == 400, "Negative interval should be rejected" # Test 3: All fields null with use_default=false res = client.post( url_for("createwatch"), data=json.dumps({ "url": test_url, "time_between_check_use_default": False, "time_between_check": {"weeks": None, "days": None, "hours": None, "minutes": None, "seconds": None} }), headers={'content-type': 'application/json', 'x-api-key': api_key}, ) assert res.status_code == 400, "All null intervals should be rejected when not using default" # Test 4: Extremely large interval (overflow risk) res = client.post( url_for("createwatch"), data=json.dumps({ "url": test_url, "time_between_check_use_default": False, "time_between_check": {"weeks": 999999999} }), headers={'content-type': 'application/json', 'x-api-key': api_key}, ) # Should either accept (with limits) or reject assert res.status_code in [201, 400] if res.status_code == 201: watch_uuid = res.json.get('uuid') client.delete(url_for("watch", uuid=watch_uuid), headers={'x-api-key': api_key}) # Test 5: Valid minimal interval (should work) res = client.post( url_for("createwatch"), data=json.dumps({ "url": test_url, "time_between_check_use_default": False, "time_between_check": {"seconds": 60} }), headers={'content-type': 'application/json', 'x-api-key': api_key}, ) assert res.status_code == 201 watch_uuid = res.json.get('uuid') client.delete(url_for("watch", uuid=watch_uuid), headers={'x-api-key': api_key}) delete_all_watches(client) def test_api_browser_steps_validation(client, live_server, measure_memory_usage, datastore_path): """ Test browser_steps validation for invalid operations and structures. """ api_key = live_server.app.config['DATASTORE'].data['settings']['application'].get('api_access_token') set_original_response(datastore_path=datastore_path) test_url = url_for('test_endpoint', _external=True) # Test 1: Empty browser step res = client.post( url_for("createwatch"), data=json.dumps({ "url": test_url, "browser_steps": [ {"operation": "", "selector": "", "optional_value": ""} ] }), headers={'content-type': 'application/json', 'x-api-key': api_key}, ) # Should accept (empty is valid as null) assert res.status_code in [201, 400] if res.status_code == 201: watch_uuid = res.json.get('uuid') client.delete(url_for("watch", uuid=watch_uuid), headers={'x-api-key': api_key}) # Test 2: Invalid operation type res = client.post( url_for("createwatch"), data=json.dumps({ "url": test_url, "browser_steps": [ {"operation": "invalid_operation", "selector": "#test", "optional_value": ""} ] }), headers={'content-type': 'application/json', 'x-api-key': api_key}, ) # Should accept (validation happens at runtime) or reject assert res.status_code in [201, 400] if res.status_code == 201: watch_uuid = res.json.get('uuid') client.delete(url_for("watch", uuid=watch_uuid), headers={'x-api-key': api_key}) # Test 3: Missing required fields in browser step res = client.post( url_for("createwatch"), data=json.dumps({ "url": test_url, "browser_steps": [ {"operation": "click"} # Missing selector and optional_value ] }), headers={'content-type': 'application/json', 'x-api-key': api_key}, ) # Should be rejected due to schema validation assert res.status_code == 400 # Test 4: Extra fields in browser step res = client.post( url_for("createwatch"), data=json.dumps({ "url": test_url, "browser_steps": [ {"operation": "click", "selector": "#test", "optional_value": "", "extra_field": "value"} ] }), headers={'content-type': 'application/json', 'x-api-key': api_key}, ) # Should be rejected due to additionalProperties: false assert res.status_code == 400 delete_all_watches(client) def test_api_queue_manipulation(client, live_server, measure_memory_usage, datastore_path): """ Test queue behavior under stress and edge cases. """ api_key = live_server.app.config['DATASTORE'].data['settings']['application'].get('api_access_token') set_original_response(datastore_path=datastore_path) test_url = url_for('test_endpoint', _external=True) # Test 1: Create many watches rapidly watch_uuids = [] for i in range(20): res = client.post( url_for("createwatch"), data=json.dumps({"url": test_url, "title": f"Watch {i}"}), headers={'content-type': 'application/json', 'x-api-key': api_key}, ) if res.status_code == 201: watch_uuids.append(res.json.get('uuid')) assert len(watch_uuids) == 20, "Should be able to create 20 watches" # Test 2: Recheck all when watches exist res = client.get( url_for("createwatch", recheck_all='1'), headers={'x-api-key': api_key}, ) # Should return success (200 or 202 for background processing) assert res.status_code in [200, 202] # Test 3: Verify queue doesn't overflow with moderate load # The app has MAX_QUEUE_SIZE = 5000, we're well below that wait_for_all_checks(client) # Cleanup for uuid in watch_uuids: client.delete(url_for("watch", uuid=uuid), headers={'x-api-key': api_key}) delete_all_watches(client) # ============================================================================ # TIER 3: EDGE CASES & POLISH # ============================================================================ def test_api_history_edge_cases(client, live_server, measure_memory_usage, datastore_path): """ Test history API with invalid timestamps and edge cases. """ api_key = live_server.app.config['DATASTORE'].data['settings']['application'].get('api_access_token') set_original_response(datastore_path=datastore_path) test_url = url_for('test_endpoint', _external=True) # Create watch and generate history res = client.post( url_for("createwatch"), data=json.dumps({"url": test_url}), headers={'content-type': 'application/json', 'x-api-key': api_key}, ) watch_uuid = res.json.get('uuid') wait_for_all_checks(client) # Test 1: Get history with invalid timestamp res = client.get( url_for("watchsinglehistory", uuid=watch_uuid, timestamp="invalid"), headers={'x-api-key': api_key} ) assert res.status_code == 404, "Invalid timestamp should return 404" # Test 2: Future timestamp res = client.get( url_for("watchsinglehistory", uuid=watch_uuid, timestamp="9999999999"), headers={'x-api-key': api_key} ) assert res.status_code == 404, "Future timestamp should return 404" # Test 3: Negative timestamp res = client.get( url_for("watchsinglehistory", uuid=watch_uuid, timestamp="-1"), headers={'x-api-key': api_key} ) assert res.status_code == 404, "Negative timestamp should return 404" # Test 4: Diff with reversed timestamps (from > to) # First get actual timestamps res = client.get( url_for("watchhistory", uuid=watch_uuid), headers={'x-api-key': api_key} ) if len(res.json) >= 2: timestamps = sorted(res.json.keys()) # Try reversed order res = client.get( url_for("watchhistorydiff", uuid=watch_uuid, from_timestamp=timestamps[-1], to_timestamp=timestamps[0]), headers={'x-api-key': api_key} ) # Should either work (show reverse diff) or return error assert res.status_code in [200, 400] # Cleanup client.delete(url_for("watch", uuid=watch_uuid), headers={'x-api-key': api_key}) delete_all_watches(client) def test_api_notification_edge_cases(client, live_server, measure_memory_usage, datastore_path): """ Test notification configuration edge cases. """ api_key = live_server.app.config['DATASTORE'].data['settings']['application'].get('api_access_token') set_original_response(datastore_path=datastore_path) test_url = url_for('test_endpoint', _external=True) # Test 1: Invalid notification URL res = client.post( url_for("createwatch"), data=json.dumps({ "url": test_url, "notification_urls": ["invalid://url", "ftp://test.com"] }), headers={'content-type': 'application/json', 'x-api-key': api_key}, ) # Should accept (apprise validates at runtime) or reject assert res.status_code in [201, 400] if res.status_code == 201: watch_uuid = res.json.get('uuid') client.delete(url_for("watch", uuid=watch_uuid), headers={'x-api-key': api_key}) # Test 2: Invalid notification format res = client.post( url_for("createwatch"), data=json.dumps({ "url": test_url, "notification_format": "invalid_format" }), headers={'content-type': 'application/json', 'x-api-key': api_key}, ) # Should be rejected by schema assert res.status_code == 400 # Test 3: Empty notification arrays res = client.post( url_for("createwatch"), data=json.dumps({ "url": test_url, "notification_urls": [] }), headers={'content-type': 'application/json', 'x-api-key': api_key}, ) # Should accept (empty is valid) assert res.status_code == 201 watch_uuid = res.json.get('uuid') client.delete(url_for("watch", uuid=watch_uuid), headers={'x-api-key': api_key}) delete_all_watches(client) def test_api_tag_edge_cases(client, live_server, measure_memory_usage, datastore_path): """ Test tag/group API edge cases including XSS and path traversal. """ api_key = live_server.app.config['DATASTORE'].data['settings']['application'].get('api_access_token') # Test 1: Empty tag title res = client.post( url_for("tag"), data=json.dumps({"title": ""}), headers={'content-type': 'application/json', 'x-api-key': api_key}, ) # Should be rejected (empty title) assert res.status_code == 400 # Test 2: XSS in tag title res = client.post( url_for("tag"), data=json.dumps({"title": "<script>alert(1)</script>"}), headers={'content-type': 'application/json', 'x-api-key': api_key}, ) # Should accept but sanitize if res.status_code == 201: tag_uuid = res.json.get('uuid') # Verify title is stored safely res = client.get(url_for("tag", uuid=tag_uuid), headers={'x-api-key': api_key}) # Should be escaped or sanitized client.delete(url_for("tag", uuid=tag_uuid), headers={'x-api-key': api_key}) # Test 3: Path traversal in tag title res = client.post( url_for("tag"), data=json.dumps({"title": "../../etc/passwd"}), headers={'content-type': 'application/json', 'x-api-key': api_key}, ) # Should accept (it's just a string, not a path) if res.status_code == 201: tag_uuid = res.json.get('uuid') client.delete(url_for("tag", uuid=tag_uuid), headers={'x-api-key': api_key}) # Test 4: Very long tag title res = client.post( url_for("tag"), data=json.dumps({"title": "x" * 10000}), headers={'content-type': 'application/json', 'x-api-key': api_key}, ) # Should be rejected (exceeds maxLength) assert res.status_code == 400 def test_api_authentication_edge_cases(client, live_server, measure_memory_usage, datastore_path): """ Test API authentication edge cases. """ api_key = live_server.app.config['DATASTORE'].data['settings']['application'].get('api_access_token') set_original_response(datastore_path=datastore_path) test_url = url_for('test_endpoint', _external=True) # Test 1: Missing API key res = client.get(url_for("createwatch")) assert res.status_code == 403, "Missing API key should be forbidden" # Test 2: Invalid API key res = client.get( url_for("createwatch"), headers={'x-api-key': "invalid_key_12345"} ) assert res.status_code == 403, "Invalid API key should be forbidden" # Test 3: API key with special characters res = client.get( url_for("createwatch"), headers={'x-api-key': "key<script>alert(1)</script>"} ) assert res.status_code == 403, "Invalid API key should be forbidden" # Test 4: Very long API key res = client.get( url_for("createwatch"), headers={'x-api-key': "x" * 10000} ) assert res.status_code == 403, "Invalid API key should be forbidden" # Test 5: Case sensitivity of API key wrong_case_key = api_key.upper() if api_key.islower() else api_key.lower() res = client.get( url_for("createwatch"), headers={'x-api-key': wrong_case_key} ) # Should be forbidden (keys are case-sensitive) assert res.status_code == 403, "Wrong case API key should be forbidden" # Test 6: Valid API key should work res = client.get( url_for("createwatch"), headers={'x-api-key': api_key} ) assert res.status_code == 200, "Valid API key should work"
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/tests/test_api_security.py", "license": "Apache License 2.0", "lines": 702, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
dgtlmoon/changedetection.io:changedetectionio/tests/unit/test_html_to_text.py
#!/usr/bin/env python3 # coding=utf-8 """Unit tests for html_tools.html_to_text function.""" import hashlib import threading import unittest from queue import Queue from changedetectionio.html_tools import html_to_text class TestHtmlToText(unittest.TestCase): """Test html_to_text function for correctness and thread-safety.""" def test_basic_text_extraction(self): """Test basic HTML to text conversion.""" html = '<html><body><h1>Title</h1><p>Paragraph text.</p></body></html>' text = html_to_text(html) assert 'Title' in text assert 'Paragraph text.' in text assert '<' not in text # HTML tags should be stripped assert '>' not in text def test_empty_html(self): """Test handling of empty HTML.""" html = '<html><body></body></html>' text = html_to_text(html) # Should return empty or whitespace only assert text.strip() == '' def test_nested_elements(self): """Test extraction from nested HTML elements.""" html = ''' <html> <body> <div> <h1>Header</h1> <div> <p>First paragraph</p> <p>Second paragraph</p> </div> </div> </body> </html> ''' text = html_to_text(html) assert 'Header' in text assert 'First paragraph' in text assert 'Second paragraph' in text def test_anchor_tag_rendering(self): """Test anchor tag rendering option.""" html = '<html><body><a href="https://example.com">Link text</a></body></html>' # Without rendering anchors text_without = html_to_text(html, render_anchor_tag_content=False) assert 'Link text' in text_without assert 'https://example.com' not in text_without # With rendering anchors text_with = html_to_text(html, render_anchor_tag_content=True) assert 'Link text' in text_with assert 'https://example.com' in text_with or '[Link text]' in text_with def test_rss_mode(self): """Test RSS mode converts title tags to h1.""" html = '<item><title>RSS Title</title><description>Content</description></item>' # is_rss=True should convert <title> to <h1> text = html_to_text(html, is_rss=True) assert 'RSS Title' in text assert 'Content' in text def test_special_characters(self): """Test handling of special characters and entities.""" html = '<html><body><p>Test &amp; &lt;special&gt; characters</p></body></html>' text = html_to_text(html) # Entities should be decoded assert 'Test &' in text or 'Test &amp;' in text assert 'special' in text def test_whitespace_handling(self): """Test that whitespace is properly handled.""" html = '<html><body><p>Line 1</p><p>Line 2</p></body></html>' text = html_to_text(html) # Should have some separation between lines assert 'Line 1' in text assert 'Line 2' in text assert text.count('\n') >= 1 # At least one newline def test_deterministic_output(self): """Test that the same HTML always produces the same text.""" html = '<html><body><h1>Test</h1><p>Content here</p></body></html>' # Extract text multiple times results = [html_to_text(html) for _ in range(10)] # All results should be identical assert len(set(results)) == 1, "html_to_text should be deterministic" def test_thread_safety_determinism(self): """ Test that html_to_text produces deterministic output under high concurrency. This verifies that lxml's default parser (used by inscriptis.get_text) is thread-safe and produces consistent results when called from multiple threads simultaneously. """ html = ''' <html> <head><title>Test Page</title></head> <body> <h1>Main Heading</h1> <div class="content"> <p>First paragraph with <b>bold text</b>.</p> <p>Second paragraph with <i>italic text</i>.</p> <ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ul> </div> </body> </html> ''' results_queue = Queue() def worker(worker_id, iterations=10): """Worker that converts HTML to text multiple times.""" for i in range(iterations): text = html_to_text(html) md5 = hashlib.md5(text.encode('utf-8')).hexdigest() results_queue.put((worker_id, i, md5)) # Launch many threads simultaneously num_threads = 50 threads = [] for i in range(num_threads): t = threading.Thread(target=worker, args=(i,)) threads.append(t) t.start() # Wait for all threads to complete for t in threads: t.join() # Collect all MD5 results md5_values = [] while not results_queue.empty(): _, _, md5 = results_queue.get() md5_values.append(md5) # All MD5s should be identical unique_md5s = set(md5_values) assert len(unique_md5s) == 1, ( f"Thread-safety issue detected! Found {len(unique_md5s)} different MD5 values: {unique_md5s}. " "The thread-local parser fix may not be working correctly." ) print(f"✓ Thread-safety test passed: {len(md5_values)} conversions, all identical") def test_thread_safety_basic(self): """Verify basic thread safety - multiple threads can call html_to_text simultaneously.""" results = [] errors = [] def worker(): """Worker that converts HTML to text.""" try: html = '<html><body><h1>Test</h1><p>Content</p></body></html>' text = html_to_text(html) results.append(text) except Exception as e: errors.append(e) # Launch 10 threads simultaneously threads = [threading.Thread(target=worker) for _ in range(10)] for t in threads: t.start() for t in threads: t.join() # Should have no errors assert len(errors) == 0, f"Thread-safety errors occurred: {errors}" # All results should be identical assert len(set(results)) == 1, "All threads should produce identical output" print(f"✓ Basic thread-safety test passed: {len(results)} threads, no errors") def test_large_html_with_bloated_head(self): """ Test that html_to_text can handle large HTML documents with massive <head> bloat. SPAs often dump 10MB+ of styles, scripts, and other bloat into the <head> section. This can cause inscriptis to silently exit when processing very large documents. The fix strips <style>, <script>, <svg>, <noscript>, <link>, <meta>, and HTML comments before processing, allowing extraction of actual body content. """ # Generate massive style block (~5MB) large_style = '<style>' + '.class{color:red;}\n' * 200000 + '</style>\n' # Generate massive script block (~5MB) large_script = '<script>' + 'console.log("bloat");\n' * 200000 + '</script>\n' # Generate lots of SVG bloat (~3MB) svg_bloat = '<svg><path d="M0,0 L100,100"/></svg>\n' * 50000 # Generate meta/link tags (~2MB) meta_bloat = '<meta name="description" content="bloat"/>\n' * 50000 link_bloat = '<link rel="stylesheet" href="bloat.css"/>\n' * 50000 # Generate HTML comments (~1MB) comment_bloat = '<!-- This is bloat -->\n' * 50000 # Generate noscript bloat noscript_bloat = '<noscript>Enable JavaScript</noscript>\n' * 10000 # Build the large HTML document html = f'''<!DOCTYPE html> <html> <head> <title>Test Page</title> {large_style} {large_script} {svg_bloat} {meta_bloat} {link_bloat} {comment_bloat} {noscript_bloat} </head> <body> <h1>Important Heading</h1> <p>This is the actual content that should be extracted.</p> <div> <p>First paragraph with meaningful text.</p> <p>Second paragraph with more content.</p> </div> <footer>Footer text</footer> </body> </html> ''' # Verify the HTML is actually large (should be ~20MB+) html_size_mb = len(html) / (1024 * 1024) assert html_size_mb > 15, f"HTML should be >15MB, got {html_size_mb:.2f}MB" print(f" Testing {html_size_mb:.2f}MB HTML document with bloated head...") # This should not crash or silently exit text = html_to_text(html) # Verify we got actual text output (not empty/None) assert text is not None, "html_to_text returned None" assert len(text) > 0, "html_to_text returned empty string" # Verify the actual body content was extracted assert 'Important Heading' in text, "Failed to extract heading" assert 'actual content that should be extracted' in text, "Failed to extract paragraph" assert 'First paragraph with meaningful text' in text, "Failed to extract first paragraph" assert 'Second paragraph with more content' in text, "Failed to extract second paragraph" assert 'Footer text' in text, "Failed to extract footer" # Verify bloat was stripped (output should be tiny compared to input) text_size_kb = len(text) / 1024 assert text_size_kb < 1, f"Output too large ({text_size_kb:.2f}KB), bloat not stripped" # Verify no CSS, script content, or SVG leaked through assert 'color:red' not in text, "Style content leaked into text output" assert 'console.log' not in text, "Script content leaked into text output" assert '<path' not in text, "SVG content leaked into text output" assert 'bloat.css' not in text, "Link href leaked into text output" print(f" ✓ Successfully processed {html_size_mb:.2f}MB HTML -> {text_size_kb:.2f}KB text") def test_body_display_none_spa_pattern(self): """ Test that html_to_text can extract content from pages with display:none body. SPAs (Single Page Applications) often use <body style="display:none"> to hide content until JavaScript loads and renders the page. inscriptis respects CSS display rules, so without preprocessing, it would skip all content and return only newlines. The fix strips display:none and visibility:hidden styles from the body tag before processing, allowing text extraction from client-side rendered applications. """ # Test case 1: Basic display:none html1 = '''<!DOCTYPE html> <html lang="en"> <head><title>What's New – Fluxguard</title></head> <body style="display:none"> <h1>Important Heading</h1> <p>This is actual content that should be extracted.</p> <div> <p>First paragraph with meaningful text.</p> <p>Second paragraph with more content.</p> </div> </body> </html>''' text1 = html_to_text(html1) # Before fix: would return ~33 newlines, len(text) ~= 33 # After fix: should extract actual content, len(text) > 100 assert len(text1) > 100, f"Expected substantial text output, got {len(text1)} chars" assert 'Important Heading' in text1, "Failed to extract heading from display:none body" assert 'actual content' in text1, "Failed to extract paragraph from display:none body" assert 'First paragraph' in text1, "Failed to extract nested content" # Should not be mostly newlines newline_ratio = text1.count('\n') / len(text1) assert newline_ratio < 0.5, f"Output is mostly newlines ({newline_ratio:.2%}), content not extracted" # Test case 2: visibility:hidden (another hiding pattern) html2 = '<html><body style="visibility:hidden"><h1>Hidden Content</h1><p>Test paragraph.</p></body></html>' text2 = html_to_text(html2) assert 'Hidden Content' in text2, "Failed to extract content from visibility:hidden body" assert 'Test paragraph' in text2, "Failed to extract paragraph from visibility:hidden body" # Test case 3: Mixed styles (display:none with other CSS) html3 = '<html><body style="color: red; display:none; font-size: 12px"><p>Mixed style content</p></body></html>' text3 = html_to_text(html3) assert 'Mixed style content' in text3, "Failed to extract content from body with mixed styles" # Test case 4: Case insensitivity (DISPLAY:NONE uppercase) html4 = '<html><body style="DISPLAY:NONE"><p>Uppercase style</p></body></html>' text4 = html_to_text(html4) assert 'Uppercase style' in text4, "Failed to handle uppercase DISPLAY:NONE" # Test case 5: Space variations (display: none vs display:none) html5 = '<html><body style="display: none"><p>With spaces</p></body></html>' text5 = html_to_text(html5) assert 'With spaces' in text5, "Failed to handle 'display: none' with space" # Test case 6: Body with other attributes (class, id) html6 = '<html><body class="foo" style="display:none" id="bar"><p>With attributes</p></body></html>' text6 = html_to_text(html6) assert 'With attributes' in text6, "Failed to extract from body with multiple attributes" # Test case 7: Should NOT affect opacity:0 (which doesn't hide from inscriptis) html7 = '<html><body style="opacity:0"><p>Transparent content</p></body></html>' text7 = html_to_text(html7) # Opacity doesn't affect inscriptis text extraction, content should be there assert 'Transparent content' in text7, "Incorrectly stripped opacity:0 style" print(" ✓ All display:none body tag tests passed") def test_style_tag_with_svg_data_uri(self): """ Test that style tags containing SVG data URIs are properly stripped. Some WordPress and modern sites embed SVG as data URIs in CSS, which contains <svg> and </svg> tags within the style content. The regex must use backreferences to ensure <style> matches </style> (not </svg> inside the CSS). This was causing errors where the regex would match <style> and stop at the first </svg> it encountered inside a CSS data URI, breaking the HTML structure. """ # Real-world example from WordPress wp-block-image styles html = '''<!DOCTYPE html> <html> <head> <style id='wp-block-image-inline-css'> .wp-block-image>a,.wp-block-image>figure>a{display:inline-block}.wp-block-image img{box-sizing:border-box;height:auto;max-width:100%;vertical-align:bottom}@supports ((-webkit-mask-image:none) or (mask-image:none)) or (-webkit-mask-image:none){.wp-block-image.is-style-circle-mask img{border-radius:0;-webkit-mask-image:url('data:image/svg+xml;utf8,<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"><circle cx="50" cy="50" r="50"/></svg>');mask-image:url('data:image/svg+xml;utf8,<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"><circle cx="50" cy="50" r="50"/></svg>');mask-mode:alpha}} </style> </head> <body> <h1>Test Heading</h1> <p>This is the actual content that should be extracted.</p> <div class="wp-block-image"> <img src="test.jpg" alt="Test image"> </div> </body> </html>''' # This should not crash and should extract the body content text = html_to_text(html) # Verify the actual body content was extracted assert text is not None, "html_to_text returned None" assert len(text) > 0, "html_to_text returned empty string" assert 'Test Heading' in text, "Failed to extract heading" assert 'actual content that should be extracted' in text, "Failed to extract paragraph" # Verify CSS content was stripped (including the SVG data URI) assert '.wp-block-image' not in text, "CSS class selector leaked into text" assert 'mask-image' not in text, "CSS property leaked into text" assert 'data:image/svg+xml' not in text, "SVG data URI leaked into text" assert 'viewBox' not in text, "SVG attributes leaked into text" # Verify no broken HTML structure assert '<style' not in text, "Unclosed style tag in output" assert '</svg>' not in text, "SVG closing tag leaked into text" print(" ✓ Style tag with SVG data URI test passed") def test_style_tag_closes_correctly(self): """ Test that each tag type (style, script, svg) closes with the correct closing tag. Before the fix, the regex used (?:style|script|svg|noscript) for both opening and closing tags, which meant <style> could incorrectly match </svg> as its closing tag. With backreferences, <style> must close with </style>, <svg> with </svg>, etc. """ # Test nested tags where incorrect matching would break html = '''<!DOCTYPE html> <html> <head> <style> body { background: url('data:image/svg+xml,<svg><rect/></svg>'); } </style> <script> const svg = '<svg><path d="M0,0"/></svg>'; </script> </head> <body> <h1>Content</h1> <svg><circle cx="50" cy="50" r="40"/></svg> <p>After SVG</p> </body> </html>''' text = html_to_text(html) # Should extract body content assert 'Content' in text, "Failed to extract heading" assert 'After SVG' in text, "Failed to extract content after SVG" # Should strip all style/script/svg content assert 'background:' not in text, "Style content leaked" assert 'const svg' not in text, "Script content leaked" assert '<circle' not in text, "SVG element leaked" assert 'data:image/svg+xml' not in text, "Data URI leaked" print(" ✓ Tag closing validation test passed") def test_script_with_closing_tag_in_string_does_not_eat_content(self): """ Script tag containing </script> inside a JS string must not prematurely end the block. This is the classic regex failure mode: the old pattern would find the first </script> inside the JS string literal and stop there, leaving the tail of the script block (plus any following content) exposed as raw text. BS4 parses the HTML correctly. """ html = '''<html><body> <p>Before script</p> <script> var html = "<div>foo<\\/script><p>bar</p>"; var also = 1; </script> <p>AFTER SCRIPT</p> </body></html>''' text = html_to_text(html) assert 'Before script' in text assert 'AFTER SCRIPT' in text # Script internals must not leak assert 'var html' not in text assert 'var also' not in text def test_content_sandwiched_between_multiple_body_scripts(self): """Content between multiple script/style blocks in the body must all survive.""" html = '''<html><body> <script>var a = 1;</script> <p>CONTENT A</p> <style>.x { color: red; }</style> <p>CONTENT B</p> <script>var b = 2;</script> <p>CONTENT C</p> <style>.y { color: blue; }</style> <p>CONTENT D</p> </body></html>''' text = html_to_text(html) for label in ['CONTENT A', 'CONTENT B', 'CONTENT C', 'CONTENT D']: assert label in text, f"'{label}' was eaten by script/style stripping" assert 'var a' not in text assert 'var b' not in text assert 'color: red' not in text assert 'color: blue' not in text def test_unicode_and_international_content_preserved(self): """Non-ASCII content (umlauts, CJK, soft hyphens) must survive stripping.""" html = '''<html><body> <style>.x{color:red}</style> <p>German: Aus\xadge\xadbucht! — ANMELDUNG — Fan\xadday 2026</p> <p>Chinese: \u6ce8\u518c</p> <p>Japanese: \u767b\u9332</p> <p>Korean: \ub4f1\ub85d</p> <p>Emoji: \U0001f4e2</p> <script>var x = 1;</script> </body></html>''' text = html_to_text(html) assert 'ANMELDUNG' in text assert '\u6ce8\u518c' in text # Chinese assert '\u767b\u9332' in text # Japanese assert '\ub4f1\ub85d' in text # Korean def test_style_with_type_attribute_is_stripped(self): """<style type="text/css"> (with type attribute) must be stripped just like bare <style>.""" html = '''<html><body> <style type="text/css">.important { display: none; }</style> <p>VISIBLE CONTENT</p> </body></html>''' text = html_to_text(html) assert 'VISIBLE CONTENT' in text assert '.important' not in text assert 'display: none' not in text def test_ldjson_script_is_stripped(self): """<script type="application/ld+json"> must be stripped — raw JSON must not appear as text.""" html = '''<html><body> <script type="application/ld+json"> {"@type": "Product", "name": "Widget", "price": "9.99"} </script> <p>PRODUCT PAGE</p> </body></html>''' text = html_to_text(html) assert 'PRODUCT PAGE' in text assert '@type' not in text assert '"price"' not in text def test_inline_svg_is_stripped_entirely(self): """ Inline SVG elements in the body are stripped by BS4 before passing to inscriptis. SVGs can be huge (icon libraries, data visualisations) and produce garbage path-data text. The old regex code explicitly stripped <svg>; the BS4 path must do the same. """ html = '''<html><body> <p>Before SVG</p> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <path d="M14 5L7 12L14 19Z" fill="none"/> <circle cx="12" cy="12" r="10"/> </svg> <p>After SVG</p> </body></html>''' text = html_to_text(html) assert 'Before SVG' in text assert 'After SVG' in text assert 'M14 5L7' not in text, "SVG path data should not appear in text output" assert 'viewBox' not in text, "SVG attributes should not appear in text output" def test_tag_inside_json_data_attribute_does_not_eat_content(self): """ Tags inside JSON data attributes with JS-escaped closing tags must not eat real content. Real-world case: Elementor/JetEngine WordPress widgets embed HTML (including SVG icons) inside JSON data attributes like data-slider-atts. The HTML inside is JS-escaped, so closing tags appear as <\\/svg> rather than </svg>. The old regex approach would find <svg> inside the attribute value, then fail to find <\/svg> as a matching close tag, and scan forward to the next real </svg> in the DOM — eating tens of kilobytes of actual page content in the process. """ html = '''<!DOCTYPE html> <html> <head><title>Test</title></head> <body> <div class="slider" data-slider-atts="{&quot;prevArrow&quot;:&quot;<i class=\\&quot;icon\\&quot;><svg width=\\&quot;24\\&quot; height=\\&quot;24\\&quot; viewBox=\\&quot;0 0 24 24\\&quot; xmlns=\\&quot;http:\\/\\/www.w3.org\\/2000\\/svg\\&quot;><path d=\\&quot;M14 5L7 12L14 19\\&quot;\\/><\\/svg><\\/i>&quot;}"> </div> <div class="content"> <h1>IMPORTANT CONTENT</h1> <p>This text must not be eaten by the tag-stripping logic.</p> </div> <svg><circle cx="50" cy="50" r="40"/></svg> </body> </html>''' text = html_to_text(html) assert 'IMPORTANT CONTENT' in text, ( "Content after a JS-escaped tag in a data attribute was incorrectly stripped. " "The tag-stripping logic is matching <tag> inside attribute values and scanning " "forward to the next real closing tag in the DOM." ) assert 'This text must not be eaten' in text def test_script_inside_json_data_attribute_does_not_eat_content(self): """Same issue as above but with <script> embedded in a data attribute with JS-escaped closing tag.""" html = '''<!DOCTYPE html> <html> <head><title>Test</title></head> <body> <div data-config="{&quot;template&quot;:&quot;<script type=\\&quot;text\\/javascript\\&quot;>var x=1;<\\/script>&quot;}"> </div> <div> <h1>MUST SURVIVE</h1> <p>Real content after the data attribute with embedded script tag.</p> </div> <script>var real = 1;</script> </body> </html>''' text = html_to_text(html) assert 'MUST SURVIVE' in text, ( "Content after a JS-escaped <script> in a data attribute was incorrectly stripped." ) assert 'Real content after the data attribute' in text if __name__ == '__main__': # Can run this file directly for quick testing unittest.main()
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/tests/unit/test_html_to_text.py", "license": "Apache License 2.0", "lines": 512, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
dgtlmoon/changedetection.io:changedetectionio/blueprint/ui/diff.py
from flask import Blueprint, request, redirect, url_for, flash, render_template, make_response, send_from_directory from flask_babel import gettext import re import importlib from loguru import logger from markupsafe import Markup from changedetectionio.diff import ( REMOVED_STYLE, ADDED_STYLE, REMOVED_INNER_STYLE, ADDED_INNER_STYLE, REMOVED_PLACEMARKER_OPEN, REMOVED_PLACEMARKER_CLOSED, ADDED_PLACEMARKER_OPEN, ADDED_PLACEMARKER_CLOSED, CHANGED_PLACEMARKER_OPEN, CHANGED_PLACEMARKER_CLOSED, CHANGED_INTO_PLACEMARKER_OPEN, CHANGED_INTO_PLACEMARKER_CLOSED ) from changedetectionio.store import ChangeDetectionStore from changedetectionio.auth_decorator import login_optionally_required def construct_blueprint(datastore: ChangeDetectionStore): diff_blueprint = Blueprint('ui_diff', __name__, template_folder="../ui/templates") @diff_blueprint.app_template_filter('diff_unescape_difference_spans') def diff_unescape_difference_spans(content): """Emulate Jinja2's auto-escape, then selectively unescape our diff spans.""" from markupsafe import escape if not content: return Markup('') # Step 1: Escape everything like Jinja2 would (this makes it XSS-safe) escaped_content = escape(str(content)) # Step 2: Unescape only our exact diff spans generated by apply_html_color_to_body() # Pattern matches the exact structure: # <span style="{STYLE}" role="{ROLE}" aria-label="{LABEL}" title="{TITLE}"> # Unescape outer span opening tags with full attributes (role, aria-label, title) # Matches removed/added/changed/changed_into spans result = re.sub( rf'&lt;span style=&#34;({re.escape(REMOVED_STYLE)}|{re.escape(ADDED_STYLE)})&#34; ' rf'role=&#34;(deletion|insertion|note)&#34; ' rf'aria-label=&#34;([^&]+?)&#34; ' rf'title=&#34;([^&]+?)&#34;&gt;', r'<span style="\1" role="\2" aria-label="\3" title="\4">', str(escaped_content), flags=re.IGNORECASE ) # Unescape inner span opening tags (without additional attributes) # This matches the darker background styles for changed parts within lines result = re.sub( rf'&lt;span style=&#34;({re.escape(REMOVED_INNER_STYLE)}|{re.escape(ADDED_INNER_STYLE)})&#34;&gt;', r'<span style="\1">', result, flags=re.IGNORECASE ) # Unescape closing tags (but only as many as we opened) open_count = result.count('<span style=') close_count = str(escaped_content).count('&lt;/span&gt;') # Replace up to the number of spans we opened for _ in range(min(open_count, close_count)): result = result.replace('&lt;/span&gt;', '</span>', 1) return Markup(result) @diff_blueprint.route("/diff/<uuid_str:uuid>", methods=['GET']) @login_optionally_required def diff_history_page(uuid): """ Render the history/diff page for a watch. This route is processor-aware: it delegates rendering to the processor's difference.py module, allowing different processor types to provide custom visualizations: - text_json_diff: Text/HTML diff with syntax highlighting - restock_diff: Could show price charts and stock history - image_diff: Could show image comparison slider/overlay Each processor implements processors/{type}/difference.py::render() If a processor doesn't have a difference module, falls back to text_json_diff. """ if uuid == 'first': uuid = list(datastore.data['watching'].keys()).pop() try: watch = datastore.data['watching'][uuid] except KeyError: flash(gettext("No history found for the specified link, bad link?"), "error") return redirect(url_for('watchlist.index')) dates = list(watch.history.keys()) if not dates or len(dates) < 2: flash(gettext("Not enough history (2 snapshots required) to show difference page for this watch."), "error") return redirect(url_for('watchlist.index')) # Get the processor type for this watch processor_name = watch.get('processor', 'text_json_diff') # Try to get the processor's difference module (works for both built-in and plugin processors) from changedetectionio.processors import get_processor_submodule processor_module = get_processor_submodule(processor_name, 'difference') # Call the processor's render() function if processor_module and hasattr(processor_module, 'render'): return processor_module.render( watch=watch, datastore=datastore, request=request, url_for=url_for, render_template=render_template, flash=flash, redirect=redirect ) # Fallback: if processor doesn't have difference module, use text_json_diff as default from changedetectionio.processors.text_json_diff.difference import render as default_render return default_render( watch=watch, datastore=datastore, request=request, url_for=url_for, render_template=render_template, flash=flash, redirect=redirect ) @diff_blueprint.route("/diff/<uuid_str:uuid>/extract", methods=['GET']) @login_optionally_required def diff_history_page_extract_GET(uuid): """ Render the data extraction form for a watch. This route is processor-aware: it delegates to the processor's extract.py module, allowing different processor types to provide custom extraction interfaces. Each processor implements processors/{type}/extract.py::render_form() If a processor doesn't have an extract module, falls back to text_json_diff. """ if uuid == 'first': uuid = list(datastore.data['watching'].keys()).pop() try: watch = datastore.data['watching'][uuid] except KeyError: flash(gettext("No history found for the specified link, bad link?"), "error") return redirect(url_for('watchlist.index')) # Get the processor type for this watch processor_name = watch.get('processor', 'text_json_diff') # Try to get the processor's extract module (works for both built-in and plugin processors) from changedetectionio.processors import get_processor_submodule processor_module = get_processor_submodule(processor_name, 'extract') # Call the processor's render_form() function if processor_module and hasattr(processor_module, 'render_form'): return processor_module.render_form( watch=watch, datastore=datastore, request=request, url_for=url_for, render_template=render_template, flash=flash, redirect=redirect ) # Fallback: if processor doesn't have extract module, use base processors.extract as default from changedetectionio.processors.extract import render_form as default_render_form return default_render_form( watch=watch, datastore=datastore, request=request, url_for=url_for, render_template=render_template, flash=flash, redirect=redirect ) @diff_blueprint.route("/diff/<uuid_str:uuid>/extract", methods=['POST']) @login_optionally_required def diff_history_page_extract_POST(uuid): """ Process the data extraction request. This route is processor-aware: it delegates to the processor's extract.py module, allowing different processor types to provide custom extraction logic. Each processor implements processors/{type}/extract.py::process_extraction() If a processor doesn't have an extract module, falls back to text_json_diff. """ if uuid == 'first': uuid = list(datastore.data['watching'].keys()).pop() try: watch = datastore.data['watching'][uuid] except KeyError: flash(gettext("No history found for the specified link, bad link?"), "error") return redirect(url_for('watchlist.index')) # Get the processor type for this watch processor_name = watch.get('processor', 'text_json_diff') # Try to get the processor's extract module (works for both built-in and plugin processors) from changedetectionio.processors import get_processor_submodule processor_module = get_processor_submodule(processor_name, 'extract') # Call the processor's process_extraction() function if processor_module and hasattr(processor_module, 'process_extraction'): return processor_module.process_extraction( watch=watch, datastore=datastore, request=request, url_for=url_for, make_response=make_response, send_from_directory=send_from_directory, flash=flash, redirect=redirect ) # Fallback: if processor doesn't have extract module, use base processors.extract as default from changedetectionio.processors.extract import process_extraction as default_process_extraction return default_process_extraction( watch=watch, datastore=datastore, request=request, url_for=url_for, make_response=make_response, send_from_directory=send_from_directory, flash=flash, redirect=redirect ) @diff_blueprint.route("/diff/<uuid_str:uuid>/processor-asset/<string:asset_name>", methods=['GET']) @login_optionally_required def processor_asset(uuid, asset_name): """ Serve processor-specific binary assets (images, files, etc.). This route is processor-aware: it delegates to the processor's difference.py module, allowing different processor types to serve custom assets without embedding them as base64 in templates. This solves memory issues with large binary data (e.g., screenshots) by streaming them as separate HTTP responses instead of embedding in the HTML template. Each processor implements processors/{type}/difference.py::get_asset() which returns (binary_data, content_type, cache_control_header). Example URLs: - /diff/{uuid}/processor-asset/before - /diff/{uuid}/processor-asset/after - /diff/{uuid}/processor-asset/rendered_diff """ if uuid == 'first': uuid = list(datastore.data['watching'].keys()).pop() try: watch = datastore.data['watching'][uuid] except KeyError: flash(gettext("No history found for the specified link, bad link?"), "error") return redirect(url_for('watchlist.index')) # Get the processor type for this watch processor_name = watch.get('processor', 'text_json_diff') # Try to get the processor's difference module (works for both built-in and plugin processors) from changedetectionio.processors import get_processor_submodule processor_module = get_processor_submodule(processor_name, 'difference') # Call the processor's get_asset() function if processor_module and hasattr(processor_module, 'get_asset'): result = processor_module.get_asset( asset_name=asset_name, watch=watch, datastore=datastore, request=request ) if result is None: from flask import abort abort(404, description=f"Asset '{asset_name}' not found") binary_data, content_type, cache_control = result response = make_response(binary_data) response.headers['Content-Type'] = content_type if cache_control: response.headers['Cache-Control'] = cache_control return response else: logger.warning(f"Processor {processor_name} does not implement get_asset()") from flask import abort abort(404, description=f"Processor '{processor_name}' does not support assets") return diff_blueprint
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/blueprint/ui/diff.py", "license": "Apache License 2.0", "lines": 250, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
dgtlmoon/changedetection.io:changedetectionio/blueprint/ui/preview.py
from flask import Blueprint, request, url_for, flash, render_template, redirect from flask_babel import gettext import time from loguru import logger from changedetectionio.store import ChangeDetectionStore from changedetectionio.auth_decorator import login_optionally_required from changedetectionio import html_tools def construct_blueprint(datastore: ChangeDetectionStore): preview_blueprint = Blueprint('ui_preview', __name__, template_folder="../ui/templates") @preview_blueprint.route("/preview/<uuid_str:uuid>", methods=['GET']) @login_optionally_required def preview_page(uuid): """ Render the preview page for a watch. This route is processor-aware: it delegates rendering to the processor's preview.py module, allowing different processor types to provide custom visualizations: - text_json_diff: Text preview with syntax highlighting - image_ssim_diff: Image preview with proper rendering - restock_diff: Could show latest price/stock data Each processor implements processors/{type}/preview.py::render() If a processor doesn't have a preview module, falls back to default text preview. """ if uuid == 'first': uuid = list(datastore.data['watching'].keys()).pop() try: watch = datastore.data['watching'][uuid] except KeyError: flash(gettext("No history found for the specified link, bad link?"), "error") return redirect(url_for('watchlist.index')) # Get the processor type for this watch processor_name = watch.get('processor', 'text_json_diff') # Try to get the processor's preview module (works for both built-in and plugin processors) from changedetectionio.processors import get_processor_submodule processor_module = get_processor_submodule(processor_name, 'preview') # Call the processor's render() function if processor_module and hasattr(processor_module, 'render'): return processor_module.render( watch=watch, datastore=datastore, request=request, url_for=url_for, render_template=render_template, flash=flash, redirect=redirect ) # Fallback: if processor doesn't have preview module, use default text preview content = [] versions = [] timestamp = None system_uses_webdriver = datastore.data['settings']['application']['fetch_backend'] == 'html_webdriver' extra_stylesheets = [url_for('static_content', group='styles', filename='diff.css')] is_html_webdriver = False if (watch.get('fetch_backend') == 'system' and system_uses_webdriver) or watch.get('fetch_backend') == 'html_webdriver' or watch.get('fetch_backend', '').startswith('extra_browser_'): is_html_webdriver = True triggered_line_numbers = [] ignored_line_numbers = [] blocked_line_numbers = [] if datastore.data['watching'][uuid].history_n == 0 and (watch.get_error_text() or watch.get_error_snapshot()): flash(gettext("Preview unavailable - No fetch/check completed or triggers not reached"), "error") else: # So prepare the latest preview or not preferred_version = request.args.get('version') versions = list(watch.history.keys()) timestamp = versions[-1] if preferred_version and preferred_version in versions: timestamp = preferred_version try: versions = list(watch.history.keys()) content = watch.get_history_snapshot(timestamp=timestamp) triggered_line_numbers = html_tools.strip_ignore_text(content=content, wordlist=watch.get('trigger_text'), mode='line numbers' ) ignored_line_numbers = html_tools.strip_ignore_text(content=content, wordlist=watch.get('ignore_text'), mode='line numbers' ) blocked_line_numbers = html_tools.strip_ignore_text(content=content, wordlist=watch.get("text_should_not_be_present"), mode='line numbers' ) except Exception as e: content.append({'line': f"File doesnt exist or unable to read timestamp {timestamp}", 'classes': ''}) from changedetectionio.pluggy_interface import get_fetcher_capabilities capabilities = get_fetcher_capabilities(watch, datastore) output = render_template("preview.html", capabilities=capabilities, content=content, current_diff_url=watch['url'], current_version=timestamp, extra_stylesheets=extra_stylesheets, extra_title=f" - Diff - {watch.label} @ {timestamp}", highlight_ignored_line_numbers=ignored_line_numbers, highlight_triggered_line_numbers=triggered_line_numbers, highlight_blocked_line_numbers=blocked_line_numbers, history_n=watch.history_n, is_html_webdriver=is_html_webdriver, last_error=watch['last_error'], last_error_screenshot=watch.get_error_snapshot(), last_error_text=watch.get_error_text(), screenshot=watch.get_screenshot(), uuid=uuid, versions=versions, watch=watch, ) return output @preview_blueprint.route("/preview/<uuid_str:uuid>/processor-asset/<string:asset_name>", methods=['GET']) @login_optionally_required def processor_asset(uuid, asset_name): """ Serve processor-specific binary assets for preview (images, files, etc.). This route is processor-aware: it delegates to the processor's preview.py module, allowing different processor types to serve custom assets without embedding them as base64 in templates. This solves memory issues with large binary data by streaming them as separate HTTP responses instead of embedding in the HTML template. Each processor implements processors/{type}/preview.py::get_asset() which returns (binary_data, content_type, cache_control_header). Example URLs: - /preview/{uuid}/processor-asset/screenshot?version=123456789 """ from flask import make_response if uuid == 'first': uuid = list(datastore.data['watching'].keys()).pop() try: watch = datastore.data['watching'][uuid] except KeyError: flash(gettext("No history found for the specified link, bad link?"), "error") return redirect(url_for('watchlist.index')) # Get the processor type for this watch processor_name = watch.get('processor', 'text_json_diff') # Try to get the processor's preview module (works for both built-in and plugin processors) from changedetectionio.processors import get_processor_submodule processor_module = get_processor_submodule(processor_name, 'preview') # Call the processor's get_asset() function if processor_module and hasattr(processor_module, 'get_asset'): result = processor_module.get_asset( asset_name=asset_name, watch=watch, datastore=datastore, request=request ) if result is None: from flask import abort abort(404, description=f"Asset '{asset_name}' not found") binary_data, content_type, cache_control = result response = make_response(binary_data) response.headers['Content-Type'] = content_type if cache_control: response.headers['Cache-Control'] = cache_control return response else: logger.warning(f"Processor {processor_name} does not implement get_asset()") from flask import abort abort(404, description=f"Processor '{processor_name}' does not support assets") return preview_blueprint
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/blueprint/ui/preview.py", "license": "Apache License 2.0", "lines": 157, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
dgtlmoon/changedetection.io:changedetectionio/diff/tokenizers/natural_text.py
""" Simple word tokenizer using whitespace boundaries. This is a simpler tokenizer that treats all whitespace as token boundaries without special handling for HTML tags or other markup. """ from typing import List def tokenize_words(text: str) -> List[str]: """ Split text into words using simple whitespace boundaries. This is a simpler tokenizer that treats all whitespace as token boundaries without special handling for HTML tags. Args: text: Input text to tokenize Returns: List of tokens (words and whitespace) Examples: >>> tokenize_words("Hello world") ['Hello', ' ', 'world'] >>> tokenize_words("one two") ['one', ' ', ' ', 'two'] """ tokens = [] current = '' for char in text: if char.isspace(): if current: tokens.append(current) current = '' tokens.append(char) else: current += char if current: tokens.append(current) return tokens
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/diff/tokenizers/natural_text.py", "license": "Apache License 2.0", "lines": 34, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
dgtlmoon/changedetection.io:changedetectionio/diff/tokenizers/words_and_html.py
""" Tokenizer that preserves HTML tags as atomic units while splitting on whitespace. This tokenizer is specifically designed for HTML content where: - HTML tags should remain intact (e.g., '<p>', '<a href="...">') - Whitespace tokens are preserved for accurate diff reconstruction - Words are split on whitespace boundaries """ from typing import List def tokenize_words_and_html(text: str) -> List[str]: """ Split text into words and boundaries (spaces, HTML tags). This tokenizer preserves HTML tags as atomic units while splitting on whitespace. Useful for content that contains HTML markup. Args: text: Input text to tokenize Returns: List of tokens (words, spaces, HTML tags) Examples: >>> tokenize_words_and_html("<p>Hello world</p>") ['<p>', 'Hello', ' ', 'world', '</p>'] >>> tokenize_words_and_html("<a href='test.com'>link</a>") ['<a href=\\'test.com\\'>', 'link', '</a>'] """ tokens = [] current = '' in_tag = False for char in text: if char == '<': # Start of HTML tag if current: tokens.append(current) current = '' current = '<' in_tag = True elif char == '>' and in_tag: # End of HTML tag current += '>' tokens.append(current) current = '' in_tag = False elif char.isspace() and not in_tag: # Space outside of tag if current: tokens.append(current) current = '' tokens.append(char) else: current += char if current: tokens.append(current) return tokens
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/diff/tokenizers/words_and_html.py", "license": "Apache License 2.0", "lines": 51, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
dgtlmoon/changedetection.io:changedetectionio/is_safe_url.py
""" URL redirect validation module for preventing open redirect vulnerabilities. This module provides functionality to safely validate redirect URLs, ensuring they: 1. Point to internal routes only (no external redirects) 2. Are properly normalized (preventing browser parsing differences) 3. Match registered Flask routes (no fake/non-existent pages) 4. Are fully logged for security monitoring References: - https://flask-login.readthedocs.io/ (safe redirect patterns) - https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-v-user-logins - https://www.pythonkitchen.com/how-prevent-open-redirect-vulnerab-flask/ """ from urllib.parse import urlparse, urljoin from flask import request from loguru import logger def is_safe_url(target, app): """ Validate that a redirect URL is safe to prevent open redirect vulnerabilities. This follows Flask/Werkzeug best practices by ensuring the redirect URL: 1. Is a relative path starting with exactly one '/' 2. Does not start with '//' (double-slash attack) 3. Has no external protocol handlers 4. Points to a valid registered route in the application 5. Is properly normalized to prevent browser parsing differences Args: target: The URL to validate (e.g., '/settings', '/login#top') app: The Flask application instance (needed for route validation) Returns: bool: True if the URL is safe for redirection, False otherwise Examples: >>> is_safe_url('/settings', app) True >>> is_safe_url('//evil.com', app) False >>> is_safe_url('/settings#general', app) True >>> is_safe_url('/fake-page', app) False """ if not target: return False # Normalize the URL to prevent browser parsing differences # Strip whitespace and replace backslashes (which some browsers interpret as forward slashes) target = target.strip() target = target.replace('\\', '/') # First, check if it starts with // or more (double-slash attack) if target.startswith('//'): logger.warning(f"Blocked redirect attempt with double-slash: {target}") return False # Parse the URL to check for scheme and netloc parsed = urlparse(target) # Block any URL with a scheme (http://, https://, javascript:, etc.) if parsed.scheme: logger.warning(f"Blocked redirect attempt with scheme: {target}") return False # Block any URL with a network location (netloc) # This catches patterns like //evil.com, user@host, etc. if parsed.netloc: logger.warning(f"Blocked redirect attempt with netloc: {target}") return False # At this point, we have a relative URL with no scheme or netloc # Use urljoin to resolve it and verify it points to the same host ref_url = urlparse(request.host_url) test_url = urlparse(urljoin(request.host_url, target)) # Check: ensure the resolved URL has the same netloc as current host if not (test_url.scheme in ('http', 'https') and ref_url.netloc == test_url.netloc): logger.warning(f"Blocked redirect attempt with mismatched netloc: {target}") return False # Additional validation: Check if the URL matches a registered route # This prevents redirects to non-existent pages or unintended endpoints try: # Get the path without query string and fragment # Fragments (like #general) are automatically stripped by urlparse path = parsed.path # Create a URL adapter bound to the server name adapter = app.url_map.bind(ref_url.netloc) # Try to match the path to a registered route # This will raise NotFound if the route doesn't exist endpoint, values = adapter.match(path, return_rule=False) # Block redirects to static file endpoints - these are catch-all routes # that would match arbitrary paths, potentially allowing unintended redirects if endpoint in ('static_content', 'static', 'static_flags'): logger.warning(f"Blocked redirect to static endpoint: {target}") return False # Successfully matched a valid route logger.debug(f"Validated safe redirect to endpoint '{endpoint}': {target}") return True except Exception as e: # Route doesn't exist or can't be matched logger.warning(f"Blocked redirect to non-existent route: {target} (error: {e})") return False
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/is_safe_url.py", "license": "Apache License 2.0", "lines": 91, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
dgtlmoon/changedetection.io:changedetectionio/processors/base.py
import asyncio import re import hashlib from changedetectionio.browser_steps.browser_steps import browser_steps_get_valid_steps from changedetectionio.content_fetchers.base import Fetcher from changedetectionio.strtobool import strtobool from changedetectionio.validate_url import is_private_hostname from copy import deepcopy from abc import abstractmethod import os from urllib.parse import urlparse from loguru import logger SCREENSHOT_FORMAT_JPEG = 'JPEG' SCREENSHOT_FORMAT_PNG = 'PNG' class difference_detection_processor(): browser_steps = None datastore = None fetcher = None screenshot = None watch = None xpath_data = None preferred_proxy = None screenshot_format = SCREENSHOT_FORMAT_JPEG last_raw_content_checksum = None def __init__(self, datastore, watch_uuid): self.datastore = datastore self.watch_uuid = watch_uuid # Create a stable snapshot of the watch for processing # Why deepcopy? # 1. Prevents "dict changed during iteration" errors if watch is modified during processing # 2. Preserves Watch object with properties (.link, .is_pdf, etc.) - can't use dict() # 3. Safe now: Watch.__deepcopy__() shares datastore ref (no memory leak) but copies dict data self.watch = deepcopy(self.datastore.data['watching'].get(watch_uuid)) # Generic fetcher that should be extended (requests, playwright etc) self.fetcher = Fetcher() # Load the last raw content checksum from file self.read_last_raw_content_checksum() def update_last_raw_content_checksum(self, checksum): """ Save the raw content MD5 checksum to file. This is used for skip logic - avoid reprocessing if raw HTML unchanged. """ if not checksum: return watch = self.datastore.data['watching'].get(self.watch_uuid) if not watch: return data_dir = watch.data_dir if not data_dir: return watch.ensure_data_dir_exists() checksum_file = os.path.join(data_dir, 'last-checksum.txt') try: with open(checksum_file, 'w', encoding='utf-8') as f: f.write(checksum) self.last_raw_content_checksum = checksum except IOError as e: logger.warning(f"Failed to write checksum file for {self.watch_uuid}: {e}") def read_last_raw_content_checksum(self): """ Read the last raw content MD5 checksum from file. Returns None if file doesn't exist (first run) or can't be read. """ watch = self.datastore.data['watching'].get(self.watch_uuid) if not watch: self.last_raw_content_checksum = None return data_dir = watch.data_dir if not data_dir: self.last_raw_content_checksum = None return checksum_file = os.path.join(data_dir, 'last-checksum.txt') if not os.path.isfile(checksum_file): self.last_raw_content_checksum = None return try: with open(checksum_file, 'r', encoding='utf-8') as f: self.last_raw_content_checksum = f.read().strip() except IOError as e: logger.warning(f"Failed to read checksum file for {self.watch_uuid}: {e}") self.last_raw_content_checksum = None async def validate_iana_url(self): """Pre-flight SSRF check — runs DNS lookup in executor to avoid blocking the event loop. Covers all fetchers (requests, playwright, puppeteer, plugins) since every fetch goes through call_browser(). """ if strtobool(os.getenv('ALLOW_IANA_RESTRICTED_ADDRESSES', 'false')): return parsed = urlparse(self.watch.link) if not parsed.hostname: return loop = asyncio.get_running_loop() if await loop.run_in_executor(None, is_private_hostname, parsed.hostname): raise Exception( f"Fetch blocked: '{self.watch.link}' resolves to a private/reserved IP address. " f"Set ALLOW_IANA_RESTRICTED_ADDRESSES=true to allow." ) async def call_browser(self, preferred_proxy_id=None): from requests.structures import CaseInsensitiveDict url = self.watch.link # Protect against file:, file:/, file:// access, check the real "link" without any meta "source:" etc prepended. if re.search(r'^file:', url.strip(), re.IGNORECASE): if not strtobool(os.getenv('ALLOW_FILE_URI', 'false')): raise Exception( "file:// type access is denied for security reasons." ) await self.validate_iana_url() # Requests, playwright, other browser via wss:// etc, fetch_extra_something prefer_fetch_backend = self.watch.get('fetch_backend', 'system') # Proxy ID "key" preferred_proxy_id = preferred_proxy_id if preferred_proxy_id else self.datastore.get_preferred_proxy_for_watch( uuid=self.watch.get('uuid')) # Pluggable content self.fetcher if not prefer_fetch_backend or prefer_fetch_backend == 'system': prefer_fetch_backend = self.datastore.data['settings']['application'].get('fetch_backend') # In the case that the preferred fetcher was a browser config with custom connection URL.. # @todo - on save watch, if its extra_browser_ then it should be obvious it will use playwright (like if its requests now..) custom_browser_connection_url = None if prefer_fetch_backend.startswith('extra_browser_'): (t, key) = prefer_fetch_backend.split('extra_browser_') connection = list( filter(lambda s: (s['browser_name'] == key), self.datastore.data['settings']['requests'].get('extra_browsers', []))) if connection: prefer_fetch_backend = 'html_webdriver' custom_browser_connection_url = connection[0].get('browser_connection_url') # PDF should be html_requests because playwright will serve it up (so far) in a embedded page # @todo https://github.com/dgtlmoon/changedetection.io/issues/2019 # @todo needs test to or a fix if self.watch.is_pdf: prefer_fetch_backend = "html_requests" # Grab the right kind of 'fetcher', (playwright, requests, etc) from changedetectionio import content_fetchers if hasattr(content_fetchers, prefer_fetch_backend): # @todo TEMPORARY HACK - SWITCH BACK TO PLAYWRIGHT FOR BROWSERSTEPS if prefer_fetch_backend == 'html_webdriver' and self.watch.has_browser_steps: # This is never supported in selenium anyway logger.warning( "Using playwright fetcher override for possible puppeteer request in browsersteps, because puppetteer:browser steps is incomplete.") from changedetectionio.content_fetchers.playwright import fetcher as playwright_fetcher fetcher_obj = playwright_fetcher else: fetcher_obj = getattr(content_fetchers, prefer_fetch_backend) else: # What it referenced doesnt exist, Just use a default fetcher_obj = getattr(content_fetchers, "html_requests") proxy_url = None if preferred_proxy_id: # Custom browser endpoints should NOT have a proxy added if not prefer_fetch_backend.startswith('extra_browser_'): proxy_url = self.datastore.proxy_list.get(preferred_proxy_id).get('url') logger.debug(f"Selected proxy key '{preferred_proxy_id}' as proxy URL '{proxy_url}' for {url}") else: logger.debug("Skipping adding proxy data when custom Browser endpoint is specified. ") logger.debug(f"Using proxy '{proxy_url}' for {self.watch['uuid']}") # Now call the fetcher (playwright/requests/etc) with arguments that only a fetcher would need. # When browser_connection_url is None, it method should default to working out whats the best defaults (os env vars etc) self.fetcher = fetcher_obj(proxy_override=proxy_url, custom_browser_connection_url=custom_browser_connection_url, screenshot_format=self.screenshot_format ) if self.watch.has_browser_steps: self.fetcher.browser_steps = browser_steps_get_valid_steps(self.watch.get('browser_steps', [])) self.fetcher.browser_steps_screenshot_path = os.path.join(self.datastore.datastore_path, self.watch.get('uuid')) # Tweak the base config with the per-watch ones from changedetectionio.jinja2_custom import render as jinja_render request_headers = CaseInsensitiveDict() ua = self.datastore.data['settings']['requests'].get('default_ua') if ua and ua.get(prefer_fetch_backend): request_headers.update({'User-Agent': ua.get(prefer_fetch_backend)}) request_headers.update(self.watch.get('headers', {})) request_headers.update(self.datastore.get_all_base_headers()) request_headers.update(self.datastore.get_all_headers_in_textfile_for_watch(uuid=self.watch.get('uuid'))) # https://github.com/psf/requests/issues/4525 # Requests doesnt yet support brotli encoding, so don't put 'br' here, be totally sure that the user cannot # do this by accident. if 'Accept-Encoding' in request_headers and "br" in request_headers['Accept-Encoding']: request_headers['Accept-Encoding'] = request_headers['Accept-Encoding'].replace(', br', '') for header_name in request_headers: request_headers.update({header_name: jinja_render(template_str=request_headers.get(header_name))}) timeout = self.datastore.data['settings']['requests'].get('timeout') request_body = self.watch.get('body') if request_body: request_body = jinja_render(template_str=self.watch.get('body')) request_method = self.watch.get('method') ignore_status_codes = self.watch.get('ignore_status_codes', False) # Configurable per-watch or global extra delay before extracting text (for webDriver types) system_webdriver_delay = self.datastore.data['settings']['application'].get('webdriver_delay', None) if self.watch.get('webdriver_delay'): self.fetcher.render_extract_delay = self.watch.get('webdriver_delay') elif system_webdriver_delay is not None: self.fetcher.render_extract_delay = system_webdriver_delay if self.watch.get('webdriver_js_execute_code') is not None and self.watch.get('webdriver_js_execute_code').strip(): self.fetcher.webdriver_js_execute_code = self.watch.get('webdriver_js_execute_code') # Requests for PDF's, images etc should be passwd the is_binary flag is_binary = self.watch.is_pdf # And here we go! call the right browser with browser-specific settings empty_pages_are_a_change = self.datastore.data['settings']['application'].get('empty_pages_are_a_change', False) # All fetchers are now async await self.fetcher.run( current_include_filters=self.watch.get('include_filters'), empty_pages_are_a_change=empty_pages_are_a_change, fetch_favicon=self.watch.favicon_is_expired(), ignore_status_codes=ignore_status_codes, is_binary=is_binary, request_body=request_body, request_headers=request_headers, request_method=request_method, screenshot_format=self.screenshot_format, timeout=timeout, url=url, watch_uuid=self.watch_uuid, ) # @todo .quit here could go on close object, so we can run JS if change-detected await self.fetcher.quit(watch=self.watch) # After init, call run_changedetection() which will do the actual change-detection def get_extra_watch_config(self, filename): """ Read processor-specific JSON config file from watch data directory. Args: filename: Name of JSON file (e.g., "visual_ssim_score.json") Returns: dict: Parsed JSON data, or empty dict if file doesn't exist """ import json import os watch = self.datastore.data['watching'].get(self.watch_uuid) data_dir = watch.data_dir if not data_dir: return {} filepath = os.path.join(data_dir, filename) if not os.path.isfile(filepath): return {} try: with open(filepath, 'r', encoding='utf-8') as f: return json.load(f) except (json.JSONDecodeError, IOError) as e: logger.warning(f"Failed to read extra watch config {filename}: {e}") return {} def update_extra_watch_config(self, filename, data, merge=True): """ Write processor-specific JSON config file to watch data directory. Args: filename: Name of JSON file (e.g., "visual_ssim_score.json") data: Dictionary to serialize as JSON merge: If True, merge with existing data; if False, overwrite completely """ import json import os watch = self.datastore.data['watching'].get(self.watch_uuid) data_dir = watch.data_dir if not data_dir: logger.warning(f"Cannot save extra watch config {filename}: no data_dir") return # Ensure directory exists watch.ensure_data_dir_exists() filepath = os.path.join(data_dir, filename) try: # If merge is enabled, read existing data first existing_data = {} if merge and os.path.isfile(filepath): try: with open(filepath, 'r', encoding='utf-8') as f: existing_data = json.load(f) except (json.JSONDecodeError, IOError) as e: logger.warning(f"Failed to read existing config for merge: {e}") # Merge new data with existing if merge: existing_data.update(data) data_to_save = existing_data else: data_to_save = data # Write the data with open(filepath, 'w', encoding='utf-8') as f: json.dump(data_to_save, f, indent=2) except IOError as e: logger.error(f"Failed to write extra watch config {filename}: {e}") def get_raw_document_checksum(self): checksum = None if self.fetcher.content: checksum = hashlib.md5(self.fetcher.content.encode('utf-8')).hexdigest() return checksum @abstractmethod def run_changedetection(self, watch, force_reprocess=False): update_obj = {'last_notification_error': False, 'last_error': False} some_data = 'xxxxx' update_obj["previous_md5"] = hashlib.md5(some_data.encode('utf-8')).hexdigest() changed_detected = False return changed_detected, update_obj, ''.encode('utf-8')
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/processors/base.py", "license": "Apache License 2.0", "lines": 288, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
dgtlmoon/changedetection.io:changedetectionio/processors/extract.py
""" Base data extraction module for all processors. This module handles extracting data from watch history using regex patterns and exporting to CSV format. This is the default extractor that all processors (text_json_diff, restock_diff, etc.) can use by default or override. """ import os from flask_babel import gettext from loguru import logger def render_form(watch, datastore, request, url_for, render_template, flash, redirect, extract_form=None): """ Render the data extraction form. Args: watch: The watch object datastore: The ChangeDetectionStore instance request: Flask request object url_for: Flask url_for function render_template: Flask render_template function flash: Flask flash function redirect: Flask redirect function extract_form: Optional pre-built extract form (for error cases) Returns: Rendered HTML response with the extraction form """ from changedetectionio import forms uuid = watch.get('uuid') # Use provided form or create a new one if extract_form is None: extract_form = forms.extractDataForm( formdata=request.form, data={'extract_regex': request.form.get('extract_regex', '')} ) # Get error information for the template screenshot_url = watch.get_screenshot() system_uses_webdriver = datastore.data['settings']['application']['fetch_backend'] == 'html_webdriver' is_html_webdriver = False if (watch.get('fetch_backend') == 'system' and system_uses_webdriver) or watch.get('fetch_backend') == 'html_webdriver' or watch.get('fetch_backend', '').startswith('extra_browser_'): is_html_webdriver = True password_enabled_and_share_is_off = False if datastore.data['settings']['application'].get('password') or os.getenv("SALTED_PASS", False): password_enabled_and_share_is_off = not datastore.data['settings']['application'].get('shared_diff_access') # Use the shared default template from processors/templates/ # Processors can override this by creating their own extract.py with custom template logic output = render_template( "extract.html", uuid=uuid, extract_form=extract_form, watch_a=watch, last_error=watch['last_error'], last_error_screenshot=watch.get_error_snapshot(), last_error_text=watch.get_error_text(), screenshot=screenshot_url, is_html_webdriver=is_html_webdriver, password_enabled_and_share_is_off=password_enabled_and_share_is_off, extra_title=f" - {watch.label} - Extract Data", extra_stylesheets=[url_for('static_content', group='styles', filename='diff.css')], pure_menu_fixed=False ) return output def process_extraction(watch, datastore, request, url_for, make_response, send_from_directory, flash, redirect, extract_form=None): """ Process the data extraction request and return CSV file. Args: watch: The watch object datastore: The ChangeDetectionStore instance request: Flask request object url_for: Flask url_for function make_response: Flask make_response function send_from_directory: Flask send_from_directory function flash: Flask flash function redirect: Flask redirect function extract_form: Optional pre-built extract form Returns: CSV file download response or redirect to form on error """ from changedetectionio import forms uuid = watch.get('uuid') # Use provided form or create a new one if extract_form is None: extract_form = forms.extractDataForm( formdata=request.form, data={'extract_regex': request.form.get('extract_regex', '')} ) if not extract_form.validate(): flash(gettext("An error occurred, please see below."), "error") # render_template needs to be imported from Flask for this to work from flask import render_template as flask_render_template return render_form( watch=watch, datastore=datastore, request=request, url_for=url_for, render_template=flask_render_template, flash=flash, redirect=redirect, extract_form=extract_form ) extract_regex = request.form.get('extract_regex', '').strip() output = watch.extract_regex_from_all_history(extract_regex) if output: watch_dir = os.path.join(datastore.datastore_path, uuid) response = make_response(send_from_directory(directory=watch_dir, path=output, as_attachment=True)) response.headers['Content-type'] = 'text/csv' response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate' response.headers['Pragma'] = 'no-cache' response.headers['Expires'] = "0" return response flash(gettext('No matches found while scanning all of the watch history for that RegEx.'), 'error') return redirect(url_for('ui.ui_diff.diff_history_page_extract_GET', uuid=uuid))
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/processors/extract.py", "license": "Apache License 2.0", "lines": 109, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
dgtlmoon/changedetection.io:changedetectionio/processors/image_ssim_diff/difference.py
""" Screenshot diff visualization for fast image comparison processor. All image operations now use ImageDiffHandler abstraction for clean separation of concerns and easy backend swapping (LibVIPS, OpenCV, PIL, etc.). """ import os import json import time from flask_babel import gettext from loguru import logger from changedetectionio.processors.image_ssim_diff import SCREENSHOT_COMPARISON_THRESHOLD_OPTIONS_DEFAULT, PROCESSOR_CONFIG_NAME, \ OPENCV_BLUR_SIGMA # All image operations now use OpenCV via isolated_opencv subprocess handler # No direct handler imports needed - subprocess isolation handles everything # Maximum dimensions for diff visualization (can be overridden via environment variable) # Large screenshots don't need full resolution for visual inspection # Reduced defaults to minimize memory usage - 2000px height is plenty for diff viewing MAX_DIFF_HEIGHT = int(os.getenv('MAX_DIFF_HEIGHT', '8000')) MAX_DIFF_WIDTH = int(os.getenv('MAX_DIFF_WIDTH', '900')) def get_asset(asset_name, watch, datastore, request): """ Get processor-specific binary assets for streaming. Uses ImageDiffHandler for all image operations - no more multiprocessing needed as LibVIPS handles threading/memory internally. Supported assets: - 'before': The previous/from screenshot - 'after': The current/to screenshot - 'rendered_diff': The generated diff visualization with red highlights Args: asset_name: Name of the asset to retrieve ('before', 'after', 'rendered_diff') watch: Watch object datastore: Datastore object request: Flask request (for from_version/to_version query params) Returns: tuple: (binary_data, content_type, cache_control_header) or None if not found """ # Get version parameters from query string versions = list(watch.history.keys()) if len(versions) < 2: return None from_version = request.args.get('from_version', versions[-2] if len(versions) >= 2 else versions[0]) to_version = request.args.get('to_version', versions[-1]) # Validate versions exist if from_version not in versions: from_version = versions[-2] if len(versions) >= 2 else versions[0] if to_version not in versions: to_version = versions[-1] try: if asset_name == 'before': # Return the 'from' screenshot with bounding box if configured img_bytes = watch.get_history_snapshot(timestamp=from_version) img_bytes = _draw_bounding_box_if_configured(img_bytes, watch, datastore) mime_type = _detect_mime_type(img_bytes) return (img_bytes, mime_type, 'public, max-age=3600') elif asset_name == 'after': # Return the 'to' screenshot with bounding box if configured img_bytes = watch.get_history_snapshot(timestamp=to_version) img_bytes = _draw_bounding_box_if_configured(img_bytes, watch, datastore) mime_type = _detect_mime_type(img_bytes) return (img_bytes, mime_type, 'public, max-age=3600') elif asset_name == 'rendered_diff': # Generate diff in isolated subprocess to prevent memory leaks # Subprocess provides complete memory isolation from .image_handler import isolated_opencv as process_screenshot_handler img_bytes_from = watch.get_history_snapshot(timestamp=from_version) img_bytes_to = watch.get_history_snapshot(timestamp=to_version) # Get pixel difference threshold sensitivity (per-watch > global) # This controls how different a pixel must be (0-255 scale) to count as "changed" from changedetectionio import processors processor_instance = processors.difference_detection_processor(datastore, watch.get('uuid')) processor_config = processor_instance.get_extra_watch_config(PROCESSOR_CONFIG_NAME) pixel_difference_threshold_sensitivity = processor_config.get('pixel_difference_threshold_sensitivity') if not pixel_difference_threshold_sensitivity: pixel_difference_threshold_sensitivity = datastore.data['settings']['application'].get( 'pixel_difference_threshold_sensitivity', SCREENSHOT_COMPARISON_THRESHOLD_OPTIONS_DEFAULT) try: pixel_difference_threshold_sensitivity = int(pixel_difference_threshold_sensitivity) except (ValueError, TypeError): logger.warning( f"Invalid pixel_difference_threshold_sensitivity value '{pixel_difference_threshold_sensitivity}', using default") pixel_difference_threshold_sensitivity = SCREENSHOT_COMPARISON_THRESHOLD_OPTIONS_DEFAULT logger.debug(f"Pixel difference threshold sensitivity is {pixel_difference_threshold_sensitivity}") # Generate diff in isolated subprocess (async-safe) import asyncio import threading # Async-safe wrapper: runs coroutine in new thread with its own event loop def run_async_in_thread(): return asyncio.run( process_screenshot_handler.generate_diff_isolated( img_bytes_from, img_bytes_to, pixel_difference_threshold=int(pixel_difference_threshold_sensitivity), blur_sigma=OPENCV_BLUR_SIGMA, max_width=MAX_DIFF_WIDTH, max_height=MAX_DIFF_HEIGHT ) ) # Run in thread to avoid blocking event loop if called from async context result_container = [None] exception_container = [None] def thread_target(): try: result_container[0] = run_async_in_thread() except Exception as e: exception_container[0] = e thread = threading.Thread(target=thread_target, daemon=True, name="ImageDiff-Asset") thread.start() thread.join(timeout=60) if exception_container[0]: raise exception_container[0] diff_image_bytes = result_container[0] if diff_image_bytes: # Note: Bounding box drawing on diff not yet implemented return (diff_image_bytes, 'image/jpeg', 'public, max-age=300') else: logger.error("Failed to generate diff in subprocess") return None else: # Unknown asset return None except Exception as e: logger.error(f"Failed to get asset '{asset_name}': {e}") import traceback logger.error(traceback.format_exc()) return None def _detect_mime_type(img_bytes): """ Detect MIME type using puremagic (same as Watch.py). Args: img_bytes: Image bytes Returns: str: MIME type (e.g., 'image/png', 'image/jpeg') """ try: import puremagic detections = puremagic.magic_string(img_bytes[:2048]) if detections: mime_type = detections[0].mime_type logger.trace(f"Detected MIME type: {mime_type}") return mime_type else: logger.trace("No MIME type detected, using 'image/png' fallback") return 'image/png' except Exception as e: logger.warning(f"puremagic detection failed: {e}, using 'image/png' fallback") return 'image/png' def _draw_bounding_box_if_configured(img_bytes, watch, datastore): """ Draw blue bounding box on image if configured in processor settings. Uses isolated subprocess to prevent memory leaks from large images. Supports two modes: - "Select by element": Use include_filter to find xpath element bbox - "Draw area": Use manually drawn bounding_box from config Args: img_bytes: Image bytes (PNG) watch: Watch object datastore: Datastore object Returns: Image bytes (possibly with bounding box drawn) """ try: # Get processor configuration from changedetectionio import processors processor_instance = processors.difference_detection_processor(datastore, watch.get('uuid')) processor_name = watch.get('processor', 'default') config_filename = f'{processor_name}.json' processor_config = processor_instance.get_extra_watch_config(config_filename) if not processor_config: return img_bytes selection_mode = processor_config.get('selection_mode', 'draw') x, y, width, height = None, None, None, None # Mode 1: Select by element (use include_filter + xpath_data) if selection_mode == 'element': include_filters = watch.get('include_filters', []) if include_filters and len(include_filters) > 0: first_filter = include_filters[0].strip() # Get xpath_data from watch history history_keys = list(watch.history.keys()) if history_keys: latest_snapshot = watch.get_history_snapshot(timestamp=history_keys[-1]) xpath_data_path = watch.get_xpath_data_filepath(timestamp=history_keys[-1]) try: import gzip with gzip.open(xpath_data_path, 'rt') as f: xpath_data = json.load(f) # Find matching element for element in xpath_data.get('size_pos', []): if element.get('xpath') == first_filter and element.get('highlight_as_custom_filter'): x = element.get('left', 0) y = element.get('top', 0) width = element.get('width', 0) height = element.get('height', 0) logger.debug(f"Found element bbox for filter '{first_filter}': x={x}, y={y}, w={width}, h={height}") break except Exception as e: logger.warning(f"Failed to load xpath_data for element selection: {e}") # Mode 2: Draw area (use manually configured bbox) else: bounding_box = processor_config.get('bounding_box') if bounding_box: # Parse bounding box: "x,y,width,height" parts = [int(p.strip()) for p in bounding_box.split(',')] if len(parts) == 4: x, y, width, height = parts else: logger.warning(f"Invalid bounding box format: {bounding_box}") # If no bbox found, return original image if x is None or y is None or width is None or height is None: return img_bytes # Use isolated subprocess to prevent memory leaks from large images from .image_handler import isolated_opencv import asyncio import threading # Async-safe wrapper: runs coroutine in new thread with its own event loop # This prevents blocking when called from async context (update worker) def run_async_in_thread(): return asyncio.run( isolated_opencv.draw_bounding_box_isolated( img_bytes, x, y, width, height, color=(255, 0, 0), # Blue in BGR format thickness=3 ) ) # Always run in thread to avoid blocking event loop if called from async context result_container = [None] exception_container = [None] def thread_target(): try: result_container[0] = run_async_in_thread() except Exception as e: exception_container[0] = e thread = threading.Thread(target=thread_target, daemon=True, name="ImageDiff-BoundingBox") thread.start() thread.join(timeout=15) if exception_container[0]: raise exception_container[0] result = result_container[0] # Return result or original if subprocess failed return result if result else img_bytes except Exception as e: logger.warning(f"Failed to draw bounding box: {e}") import traceback logger.debug(traceback.format_exc()) return img_bytes def render(watch, datastore, request, url_for, render_template, flash, redirect): """ Render the screenshot comparison diff page. Uses ImageDiffHandler for all image operations. Args: watch: Watch object datastore: Datastore object request: Flask request url_for: Flask url_for function render_template: Flask render_template function flash: Flask flash function redirect: Flask redirect function Returns: Rendered template or redirect """ # Get version parameters (from_version, to_version) versions = list(watch.history.keys()) if len(versions) < 2: flash(gettext("Not enough history to compare. Need at least 2 snapshots."), "error") return redirect(url_for('watchlist.index')) # Default: compare latest two versions from_version = request.args.get('from_version', versions[-2] if len(versions) >= 2 else versions[0]) to_version = request.args.get('to_version', versions[-1]) # Validate versions exist if from_version not in versions: from_version = versions[-2] if len(versions) >= 2 else versions[0] if to_version not in versions: to_version = versions[-1] # Get pixel difference threshold sensitivity (per-watch > global > env default) pixel_difference_threshold_sensitivity = watch.get('pixel_difference_threshold_sensitivity') if not pixel_difference_threshold_sensitivity or pixel_difference_threshold_sensitivity == '': pixel_difference_threshold_sensitivity = datastore.data['settings']['application'].get('pixel_difference_threshold_sensitivity', SCREENSHOT_COMPARISON_THRESHOLD_OPTIONS_DEFAULT) # Convert to appropriate type try: pixel_difference_threshold_sensitivity = float(pixel_difference_threshold_sensitivity) except (ValueError, TypeError): logger.warning(f"Invalid pixel_difference_threshold_sensitivity value '{pixel_difference_threshold_sensitivity}', using default") pixel_difference_threshold_sensitivity = 30.0 # Get blur sigma blur_sigma = OPENCV_BLUR_SIGMA # Load screenshots from history try: img_bytes_from = watch.get_history_snapshot(timestamp=from_version) img_bytes_to = watch.get_history_snapshot(timestamp=to_version) except Exception as e: logger.error(f"Failed to load screenshots: {e}") flash(gettext("Failed to load screenshots: {}").format(e), "error") return redirect(url_for('watchlist.index')) # Calculate change percentage using isolated subprocess to prevent memory leaks (async-safe) now = time.time() try: from .image_handler import isolated_opencv as process_screenshot_handler import asyncio import threading # Async-safe wrapper: runs coroutine in new thread with its own event loop def run_async_in_thread(): return asyncio.run( process_screenshot_handler.calculate_change_percentage_isolated( img_bytes_from, img_bytes_to, pixel_difference_threshold=int(pixel_difference_threshold_sensitivity), blur_sigma=blur_sigma, max_width=MAX_DIFF_WIDTH, max_height=MAX_DIFF_HEIGHT ) ) # Run in thread to avoid blocking event loop if called from async context result_container = [None] exception_container = [None] def thread_target(): try: result_container[0] = run_async_in_thread() except Exception as e: exception_container[0] = e thread = threading.Thread(target=thread_target, daemon=True, name="ImageDiff-ChangePercentage") thread.start() thread.join(timeout=60) if exception_container[0]: raise exception_container[0] change_percentage = result_container[0] method_display = f"{process_screenshot_handler.IMPLEMENTATION_NAME} (pixel_diff_threshold: {pixel_difference_threshold_sensitivity:.0f})" logger.debug(f"Done change percentage calculation in {time.time() - now:.2f}s") except Exception as e: logger.error(f"Failed to calculate change percentage: {e}") import traceback logger.error(traceback.format_exc()) flash(gettext("Failed to calculate diff: {}").format(e), "error") return redirect(url_for('watchlist.index')) # Load historical data if available (for charts/visualization) comparison_data = {} comparison_config_path = os.path.join(watch.data_dir, "visual_comparison_data.json") if os.path.isfile(comparison_config_path): try: with open(comparison_config_path, 'r') as f: comparison_data = json.load(f) except Exception as e: logger.warning(f"Failed to load comparison history data: {e}") # Render custom template # Template path is namespaced to avoid conflicts with other processors # Images are now served via separate /processor-asset/ endpoints instead of base64 return render_template( 'image_ssim_diff/diff.html', change_percentage=change_percentage, comparison_data=comparison_data, # Full history for charts/visualization comparison_method=method_display, current_diff_url=watch['url'], from_version=from_version, percentage_different=change_percentage, threshold=pixel_difference_threshold_sensitivity, to_version=to_version, uuid=watch.get('uuid'), versions=versions, watch=watch, )
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/processors/image_ssim_diff/difference.py", "license": "Apache License 2.0", "lines": 358, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
dgtlmoon/changedetection.io:changedetectionio/processors/image_ssim_diff/edit_hook.py
""" Optional hook called when processor settings are saved in edit page. This hook analyzes the selected region to determine if template matching should be enabled for tracking content movement. Template matching is controlled via ENABLE_TEMPLATE_TRACKING env var (default: False). """ import io import os from loguru import logger from changedetectionio import strtobool from . import CROPPED_IMAGE_TEMPLATE_FILENAME # Template matching controlled via environment variable (default: disabled) # Set ENABLE_TEMPLATE_TRACKING=True to enable TEMPLATE_MATCHING_ENABLED = strtobool(os.getenv('ENABLE_TEMPLATE_TRACKING', 'False')) IMPORT_ERROR = "Template matching disabled (set ENABLE_TEMPLATE_TRACKING=True to enable)" def on_config_save(watch, processor_config, datastore): """ Called after processor config is saved in edit page. Analyzes the bounding box region to determine if it has enough visual features (texture/edges) to enable template matching for tracking content movement when page layout shifts. Args: watch: Watch object processor_config: Dict of processor-specific config datastore: Datastore object Returns: dict: Updated processor_config with auto_track_region setting """ # Check if template matching is globally enabled via ENV var if not TEMPLATE_MATCHING_ENABLED: logger.debug("Template tracking disabled via ENABLE_TEMPLATE_TRACKING env var") processor_config['auto_track_region'] = False return processor_config bounding_box = processor_config.get('bounding_box') if not bounding_box: # No bounding box, disable tracking processor_config['auto_track_region'] = False logger.debug("No bounding box set, disabled auto-tracking") return processor_config try: # Get the latest screenshot from watch history history_keys = list(watch.history.keys()) if len(history_keys) == 0: logger.warning("No screenshot history available yet, cannot analyze for tracking") processor_config['auto_track_region'] = False return processor_config # Get latest screenshot latest_timestamp = history_keys[-1] screenshot_bytes = watch.get_history_snapshot(timestamp=latest_timestamp) if not screenshot_bytes: logger.warning("Could not load screenshot for analysis") processor_config['auto_track_region'] = False return processor_config # Parse bounding box parts = [int(p.strip()) for p in bounding_box.split(',')] if len(parts) != 4: logger.warning("Invalid bounding box format") processor_config['auto_track_region'] = False return processor_config x, y, width, height = parts # Analyze the region for features/texture has_enough_features = analyze_region_features(screenshot_bytes, x, y, width, height) if has_enough_features: logger.info(f"Region has sufficient features for tracking - enabling auto_track_region") processor_config['auto_track_region'] = True # Save the template as cropped.jpg in watch data directory save_template_to_file(watch, screenshot_bytes, x, y, width, height) else: logger.info(f"Region lacks distinctive features - disabling auto_track_region") processor_config['auto_track_region'] = False # Remove old template file if exists template_path = os.path.join(watch.data_dir, CROPPED_IMAGE_TEMPLATE_FILENAME) if os.path.exists(template_path): os.remove(template_path) logger.debug(f"Removed old template file: {template_path}") return processor_config except Exception as e: logger.error(f"Error analyzing region for tracking: {e}") processor_config['auto_track_region'] = False return processor_config def analyze_region_features(screenshot_bytes, x, y, width, height): """ Analyze if a region has enough visual features for template matching. Uses OpenCV to detect corners/edges. If the region has distinctive features, template matching can reliably track it when it moves. Args: screenshot_bytes: Full screenshot as bytes x, y, width, height: Bounding box coordinates Returns: bool: True if region has enough features, False otherwise """ # Template matching disabled - would need OpenCV implementation for region analysis if not TEMPLATE_MATCHING_ENABLED: logger.warning(f"Cannot analyze region features: {IMPORT_ERROR}") return False # Note: Original implementation used LibVIPS handler to crop region, then OpenCV # for feature detection (goodFeaturesToTrack, Canny edge detection, variance). # If re-implementing, use OpenCV directly for both cropping and analysis. # Feature detection would use: cv2.goodFeaturesToTrack, cv2.Canny, np.var return False def save_template_to_file(watch, screenshot_bytes, x, y, width, height): """ Extract the template region and save as cropped_image_template.png in watch data directory. This is a convenience wrapper around handler.save_template() that handles watch directory setup and path construction. Args: watch: Watch object screenshot_bytes: Full screenshot as bytes x, y, width, height: Bounding box coordinates """ # Template matching disabled - would need OpenCV implementation for template saving if not TEMPLATE_MATCHING_ENABLED: logger.warning(f"Cannot save template: {IMPORT_ERROR}") return # Note: Original implementation used LibVIPS handler to crop and save region. # If re-implementing, use OpenCV (cv2.imdecode, crop with array slicing, cv2.imwrite). return
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/processors/image_ssim_diff/edit_hook.py", "license": "Apache License 2.0", "lines": 117, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
dgtlmoon/changedetection.io:changedetectionio/processors/image_ssim_diff/forms.py
""" Configuration forms for fast screenshot comparison processor. """ from wtforms import SelectField, StringField, validators, ValidationError, IntegerField from flask_babel import lazy_gettext as _l from changedetectionio.forms import processor_text_json_diff_form import re from changedetectionio.processors.image_ssim_diff import SCREENSHOT_COMPARISON_THRESHOLD_OPTIONS def validate_bounding_box(form, field): """Validate bounding box format: x,y,width,height with integers.""" if not field.data: return # Optional field if len(field.data) > 100: raise ValidationError(_l('Bounding box value is too long')) # Should be comma-separated integers if not re.match(r'^\d+,\d+,\d+,\d+$', field.data): raise ValidationError(_l('Bounding box must be in format: x,y,width,height (integers only)')) # Validate values are reasonable (not negative, not ridiculously large) parts = [int(p) for p in field.data.split(',')] for part in parts: if part < 0: raise ValidationError(_l('Bounding box values must be non-negative')) if part > 10000: # Reasonable max screen dimension raise ValidationError(_l('Bounding box values are too large')) def validate_selection_mode(form, field): """Validate selection mode value.""" if not field.data: return # Optional field if field.data not in ['element', 'draw']: raise ValidationError(_l('Selection mode must be either "element" or "draw"')) class processor_settings_form(processor_text_json_diff_form): """Form for fast image comparison processor settings.""" processor_config_min_change_percentage = IntegerField( _l('Minimum Change Percentage'), validators=[ validators.Optional(), validators.NumberRange(min=1, max=100, message=_l('Must be between 0 and 100')) ], render_kw={"placeholder": "Use global default (0.1)"} ) processor_config_pixel_difference_threshold_sensitivity = SelectField( _l('Pixel Difference Sensitivity'), choices=[ ('', _l('Use global default')) ] + SCREENSHOT_COMPARISON_THRESHOLD_OPTIONS, validators=[validators.Optional()], default='' ) # Processor-specific config fields (stored in separate JSON file) processor_config_bounding_box = StringField( _l('Bounding Box'), validators=[ validators.Optional(), validators.Length(max=100, message=_l('Bounding box value is too long')), validate_bounding_box ], render_kw={"style": "display: none;", "id": "bounding_box"} ) processor_config_selection_mode = StringField( _l('Selection Mode'), validators=[ validators.Optional(), validators.Length(max=20, message=_l('Selection mode value is too long')), validate_selection_mode ], render_kw={"style": "display: none;", "id": "selection_mode"} ) def extra_tab_content(self): """Tab label for processor-specific settings.""" return _l('Screenshot Comparison') def extra_form_content(self): """Render processor-specific form fields. @NOTE: prepend processor_config_* to the field name so it will save into its own datadir/uuid/image_ssim_diff.json and be read at process time """ return ''' {% from '_helpers.html' import render_field %} <fieldset> <legend>Screenshot Comparison Settings</legend> <div class="pure-control-group"> {{ render_field(form.processor_config_min_change_percentage) }} <span class="pure-form-message-inline"> <strong>What percentage of pixels must change to trigger a detection?</strong><br> For example, <strong>0.1%</strong> means if 0.1% or more of the pixels change, it counts as a change.<br> Lower values = more sensitive (detect smaller changes).<br> Higher values = less sensitive (only detect larger changes).<br> Leave blank to use global default (0.1%). </span> </div> <div class="pure-control-group"> {{ render_field(form.processor_config_pixel_difference_threshold_sensitivity) }} <span class="pure-form-message-inline"> <strong>How different must an individual pixel be to count as "changed"?</strong><br> <strong>Low sensitivity (75)</strong> = Only count pixels that changed significantly (0-255 scale).<br> <strong>High sensitivity (20)</strong> = Count pixels with small changes as different.<br> <strong>Very high (0)</strong> = Any pixel change counts.<br> Select "Use global default" to inherit the system-wide setting. </span> </div> </fieldset> '''
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/processors/image_ssim_diff/forms.py", "license": "Apache License 2.0", "lines": 100, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
dgtlmoon/changedetection.io:changedetectionio/processors/image_ssim_diff/image_handler/isolated_libvips.py
""" Subprocess-isolated image operations for memory leak prevention. LibVIPS accumulates C-level memory in long-running processes that cannot be reclaimed by Python's GC or libvips cache management. Using subprocess isolation ensures complete memory cleanup when the process exits. This module wraps LibvipsImageDiffHandler operations in multiprocessing for complete memory isolation without code duplication. Research: https://github.com/libvips/pyvips/issues/234 """ import multiprocessing # CRITICAL: Use 'spawn' context instead of 'fork' to avoid inheriting parent's # LibVIPS threading state which can cause hangs in gaussblur operations # https://docs.python.org/3/library/multiprocessing.html#contexts-and-start-methods def _worker_generate_diff(conn, img_bytes_from, img_bytes_to, threshold, blur_sigma, max_width, max_height): """ Worker: Generate diff visualization using LibvipsImageDiffHandler in isolated subprocess. This runs in a separate process for complete memory isolation. Uses print() instead of loguru to avoid forking issues. """ try: # Import handler inside worker from .libvips_handler import LibvipsImageDiffHandler print(f"[Worker] Initializing handler", flush=True) handler = LibvipsImageDiffHandler() # Load images using handler img_from = handler.load_from_bytes(img_bytes_from) img_to = handler.load_from_bytes(img_bytes_to) # Ensure same size w1, h1 = handler.get_dimensions(img_from) w2, h2 = handler.get_dimensions(img_to) if (w1, h1) != (w2, h2): img_from = handler.resize(img_from, w2, h2) # Downscale for faster diff visualization img_from = handler.resize(img_from, max_width, max_height) img_to = handler.resize(img_to, max_width, max_height) # Convert to grayscale gray_from = handler.to_grayscale(img_from) gray_to = handler.to_grayscale(img_to) # Optional blur - DISABLED due to LibVIPS threading issues in fork # gray_from = handler.gaussian_blur(gray_from, blur_sigma) # gray_to = handler.gaussian_blur(gray_to, blur_sigma) # Calculate difference diff = handler.absolute_difference(gray_from, gray_to) # Threshold to get mask _, diff_mask = handler.threshold(diff, int(threshold)) # Generate diff image with red overlay diff_image_bytes = handler.apply_red_overlay(img_to, diff_mask) print(f"[Worker] Generated diff ({len(diff_image_bytes)} bytes)", flush=True) conn.send(diff_image_bytes) except Exception as e: print(f"[Worker] Error: {e}", flush=True) import traceback traceback.print_exc() conn.send(None) finally: conn.close() def generate_diff_isolated(img_bytes_from, img_bytes_to, threshold, blur_sigma, max_width, max_height): """ Generate diff visualization in isolated subprocess for memory leak prevention. Args: img_bytes_from: Previous screenshot bytes img_bytes_to: Current screenshot bytes threshold: Pixel difference threshold blur_sigma: Gaussian blur sigma max_width: Maximum width for diff max_height: Maximum height for diff Returns: bytes: JPEG diff image or None on failure """ ctx = multiprocessing.get_context('spawn') parent_conn, child_conn = ctx.Pipe() p = ctx.Process( target=_worker_generate_diff, args=(child_conn, img_bytes_from, img_bytes_to, threshold, blur_sigma, max_width, max_height) ) p.start() result = None try: # Wait for result (30 second timeout) if parent_conn.poll(30): result = parent_conn.recv() except Exception as e: print(f"[Parent] Error receiving result: {e}", flush=True) finally: # Always close pipe first try: parent_conn.close() except: pass # Try graceful shutdown p.join(timeout=5) if p.is_alive(): print("[Parent] Process didn't exit gracefully, terminating", flush=True) p.terminate() p.join(timeout=3) # Force kill if still alive if p.is_alive(): print("[Parent] Process didn't terminate, killing", flush=True) p.kill() p.join(timeout=1) return result def calculate_change_percentage_isolated(img_bytes_from, img_bytes_to, threshold, blur_sigma, max_width, max_height): """ Calculate change percentage in isolated subprocess using handler. Returns: float: Change percentage """ ctx = multiprocessing.get_context('spawn') parent_conn, child_conn = ctx.Pipe() def _worker_calculate(conn): try: # Import handler inside worker from .libvips_handler import LibvipsImageDiffHandler handler = LibvipsImageDiffHandler() # Load images img_from = handler.load_from_bytes(img_bytes_from) img_to = handler.load_from_bytes(img_bytes_to) # Ensure same size w1, h1 = handler.get_dimensions(img_from) w2, h2 = handler.get_dimensions(img_to) if (w1, h1) != (w2, h2): img_from = handler.resize(img_from, w2, h2) # Downscale img_from = handler.resize(img_from, max_width, max_height) img_to = handler.resize(img_to, max_width, max_height) # Convert to grayscale gray_from = handler.to_grayscale(img_from) gray_to = handler.to_grayscale(img_to) # Optional blur gray_from = handler.gaussian_blur(gray_from, blur_sigma) gray_to = handler.gaussian_blur(gray_to, blur_sigma) # Calculate difference diff = handler.absolute_difference(gray_from, gray_to) # Threshold and get percentage change_percentage, _ = handler.threshold(diff, int(threshold)) conn.send(float(change_percentage)) except Exception as e: print(f"[Worker] Calculate error: {e}", flush=True) conn.send(0.0) finally: conn.close() p = ctx.Process(target=_worker_calculate, args=(child_conn,)) p.start() result = 0.0 try: if parent_conn.poll(30): result = parent_conn.recv() except Exception as e: print(f"[Parent] Calculate error receiving result: {e}", flush=True) finally: # Always close pipe first try: parent_conn.close() except: pass # Try graceful shutdown p.join(timeout=5) if p.is_alive(): print("[Parent] Calculate process didn't exit gracefully, terminating", flush=True) p.terminate() p.join(timeout=3) # Force kill if still alive if p.is_alive(): print("[Parent] Calculate process didn't terminate, killing", flush=True) p.kill() p.join(timeout=1) return result def compare_images_isolated(img_bytes_from, img_bytes_to, threshold, blur_sigma, min_change_percentage, crop_region=None): """ Compare images in isolated subprocess for change detection. Args: img_bytes_from: Previous screenshot bytes img_bytes_to: Current screenshot bytes threshold: Pixel difference threshold blur_sigma: Gaussian blur sigma min_change_percentage: Minimum percentage to trigger change detection crop_region: Optional tuple (left, top, right, bottom) for cropping both images Returns: tuple: (changed_detected, change_percentage) """ print(f"[Parent] Starting compare_images_isolated subprocess", flush=True) ctx = multiprocessing.get_context('spawn') parent_conn, child_conn = ctx.Pipe() def _worker_compare(conn): try: print(f"[Worker] Compare worker starting", flush=True) # Import handler inside worker from .libvips_handler import LibvipsImageDiffHandler print(f"[Worker] Initializing handler", flush=True) handler = LibvipsImageDiffHandler() # Load images print(f"[Worker] Loading images (from={len(img_bytes_from)} bytes, to={len(img_bytes_to)} bytes)", flush=True) img_from = handler.load_from_bytes(img_bytes_from) img_to = handler.load_from_bytes(img_bytes_to) print(f"[Worker] Images loaded", flush=True) # Crop if region specified if crop_region: print(f"[Worker] Cropping to region {crop_region}", flush=True) left, top, right, bottom = crop_region img_from = handler.crop(img_from, left, top, right, bottom) img_to = handler.crop(img_to, left, top, right, bottom) print(f"[Worker] Cropping completed", flush=True) # Ensure same size w1, h1 = handler.get_dimensions(img_from) w2, h2 = handler.get_dimensions(img_to) print(f"[Worker] Image dimensions: from={w1}x{h1}, to={w2}x{h2}", flush=True) if (w1, h1) != (w2, h2): print(f"[Worker] Resizing to match dimensions", flush=True) img_from = handler.resize(img_from, w2, h2) # Convert to grayscale print(f"[Worker] Converting to grayscale", flush=True) gray_from = handler.to_grayscale(img_from) gray_to = handler.to_grayscale(img_to) # Optional blur # NOTE: gaussblur can hang in forked subprocesses due to LibVIPS threading # Skip blur as a workaround - sigma=0.8 is subtle and comparison works without it if blur_sigma > 0: print(f"[Worker] Skipping blur (sigma={blur_sigma}) due to LibVIPS threading issues in fork", flush=True) # gray_from = handler.gaussian_blur(gray_from, blur_sigma) # gray_to = handler.gaussian_blur(gray_to, blur_sigma) # Calculate difference print(f"[Worker] Calculating difference", flush=True) diff = handler.absolute_difference(gray_from, gray_to) # Threshold and get percentage print(f"[Worker] Applying threshold ({threshold})", flush=True) change_percentage, _ = handler.threshold(diff, int(threshold)) # Determine if change detected changed_detected = change_percentage > min_change_percentage print(f"[Worker] Comparison complete: changed={changed_detected}, percentage={change_percentage:.2f}%", flush=True) conn.send((changed_detected, float(change_percentage))) except Exception as e: print(f"[Worker] Compare error: {e}", flush=True) import traceback traceback.print_exc() conn.send((False, 0.0)) finally: conn.close() p = ctx.Process(target=_worker_compare, args=(child_conn,)) print(f"[Parent] Starting subprocess (pid will be assigned)", flush=True) p.start() print(f"[Parent] Subprocess started (pid={p.pid}), waiting for result (30s timeout)", flush=True) result = (False, 0.0) try: if parent_conn.poll(30): print(f"[Parent] Result available, receiving", flush=True) result = parent_conn.recv() print(f"[Parent] Result received: {result}", flush=True) else: print(f"[Parent] Timeout waiting for result after 30s", flush=True) except Exception as e: print(f"[Parent] Compare error receiving result: {e}", flush=True) finally: # Always close pipe first try: parent_conn.close() except: pass # Try graceful shutdown import time print(f"[Parent] Waiting for subprocess to exit (5s timeout)", flush=True) join_start = time.time() p.join(timeout=5) join_elapsed = time.time() - join_start print(f"[Parent] First join took {join_elapsed:.2f}s", flush=True) if p.is_alive(): print("[Parent] Compare process didn't exit gracefully, terminating", flush=True) term_start = time.time() p.terminate() p.join(timeout=3) term_elapsed = time.time() - term_start print(f"[Parent] Terminate+join took {term_elapsed:.2f}s", flush=True) # Force kill if still alive if p.is_alive(): print("[Parent] Compare process didn't terminate, killing", flush=True) kill_start = time.time() p.kill() p.join(timeout=1) kill_elapsed = time.time() - kill_start print(f"[Parent] Kill+join took {kill_elapsed:.2f}s", flush=True) print(f"[Parent] Subprocess cleanup complete, returning result", flush=True) return result
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/processors/image_ssim_diff/image_handler/isolated_libvips.py", "license": "Apache License 2.0", "lines": 281, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
dgtlmoon/changedetection.io:changedetectionio/processors/image_ssim_diff/image_handler/isolated_opencv.py
""" OpenCV-based subprocess isolation for image comparison. OpenCV is much more stable in multiprocessing contexts than LibVIPS. No threading issues, no fork problems, picklable functions. """ import multiprocessing import numpy as np from .. import POLL_TIMEOUT_ABSOLUTE # Public implementation name for logging IMPLEMENTATION_NAME = "OpenCV" def _worker_compare(conn, img_bytes_from, img_bytes_to, pixel_difference_threshold, blur_sigma, crop_region): """ Worker function for image comparison (must be top-level for pickling with spawn). Args: conn: Pipe connection for sending results img_bytes_from: Previous screenshot bytes img_bytes_to: Current screenshot bytes pixel_difference_threshold: Pixel-level sensitivity (0-255) - how different must a pixel be to count as changed blur_sigma: Gaussian blur sigma crop_region: Optional (left, top, right, bottom) crop coordinates """ import time try: import cv2 # CRITICAL: Disable OpenCV threading to prevent thread explosion # With multiprocessing, each subprocess would otherwise spawn threads equal to CPU cores # This causes excessive thread counts and memory overhead # Research: https://medium.com/@rachittayal7/a-note-on-opencv-threads-performance-in-prod-d10180716fba cv2.setNumThreads(1) print(f"[{time.time():.3f}] [Worker] Compare worker starting (threads=1 for memory optimization)", flush=True) # Decode images from bytes print(f"[{time.time():.3f}] [Worker] Loading images (from={len(img_bytes_from)} bytes, to={len(img_bytes_to)} bytes)", flush=True) img_from = cv2.imdecode(np.frombuffer(img_bytes_from, np.uint8), cv2.IMREAD_COLOR) img_to = cv2.imdecode(np.frombuffer(img_bytes_to, np.uint8), cv2.IMREAD_COLOR) # Check if decoding succeeded if img_from is None: raise ValueError("Failed to decode 'from' image - may be corrupt or unsupported format") if img_to is None: raise ValueError("Failed to decode 'to' image - may be corrupt or unsupported format") print(f"[{time.time():.3f}] [Worker] Images loaded: from={img_from.shape}, to={img_to.shape}", flush=True) # Crop if region specified if crop_region: print(f"[{time.time():.3f}] [Worker] Cropping to region {crop_region}", flush=True) left, top, right, bottom = crop_region img_from = img_from[top:bottom, left:right] img_to = img_to[top:bottom, left:right] print(f"[{time.time():.3f}] [Worker] Cropped: from={img_from.shape}, to={img_to.shape}", flush=True) # Resize if dimensions don't match if img_from.shape != img_to.shape: print(f"[{time.time():.3f}] [Worker] Resizing to match dimensions", flush=True) img_from = cv2.resize(img_from, (img_to.shape[1], img_to.shape[0])) # Convert to grayscale print(f"[{time.time():.3f}] [Worker] Converting to grayscale", flush=True) gray_from = cv2.cvtColor(img_from, cv2.COLOR_BGR2GRAY) gray_to = cv2.cvtColor(img_to, cv2.COLOR_BGR2GRAY) # Optional Gaussian blur if blur_sigma > 0: print(f"[{time.time():.3f}] [Worker] Applying Gaussian blur (sigma={blur_sigma})", flush=True) # OpenCV uses kernel size, convert sigma to kernel size: size = 2 * round(3*sigma) + 1 ksize = int(2 * round(3 * blur_sigma)) + 1 if ksize % 2 == 0: # Must be odd ksize += 1 gray_from = cv2.GaussianBlur(gray_from, (ksize, ksize), blur_sigma) gray_to = cv2.GaussianBlur(gray_to, (ksize, ksize), blur_sigma) print(f"[{time.time():.3f}] [Worker] Blur applied (kernel={ksize}x{ksize})", flush=True) # Calculate absolute difference print(f"[{time.time():.3f}] [Worker] Calculating absolute difference", flush=True) diff = cv2.absdiff(gray_from, gray_to) # Apply threshold print(f"[{time.time():.3f}] [Worker] Applying pixel difference threshold ({pixel_difference_threshold})", flush=True) _, thresholded = cv2.threshold(diff, int(pixel_difference_threshold), 255, cv2.THRESH_BINARY) # Calculate change percentage total_pixels = thresholded.size changed_pixels = np.count_nonzero(thresholded) change_percentage = (changed_pixels / total_pixels) * 100.0 print(f"[{time.time():.3f}] [Worker] Comparison complete: percentage={change_percentage:.2f}%", flush=True) # Return only the score - let the caller decide if it's a "change" conn.send(float(change_percentage)) except Exception as e: print(f"[{time.time():.3f}] [Worker] Error: {e}", flush=True) import traceback traceback.print_exc() # Send error info as dict so parent can re-raise conn.send({'error': str(e), 'traceback': traceback.format_exc()}) finally: conn.close() async def compare_images_isolated(img_bytes_from, img_bytes_to, pixel_difference_threshold, blur_sigma, crop_region=None): """ Compare images in isolated subprocess using OpenCV (async-safe). Args: img_bytes_from: Previous screenshot bytes img_bytes_to: Current screenshot bytes pixel_difference_threshold: Pixel-level sensitivity (0-255) - how different must a pixel be to count as changed blur_sigma: Gaussian blur sigma crop_region: Optional (left, top, right, bottom) crop coordinates Returns: float: Change percentage (0-100) """ import time import asyncio print(f"[{time.time():.3f}] [Parent] Starting OpenCV comparison subprocess", flush=True) # Use spawn method for clean process (no fork issues) ctx = multiprocessing.get_context('spawn') parent_conn, child_conn = ctx.Pipe() p = ctx.Process( target=_worker_compare, args=(child_conn, img_bytes_from, img_bytes_to, pixel_difference_threshold, blur_sigma, crop_region) ) print(f"[{time.time():.3f}] [Parent] Starting subprocess", flush=True) p.start() print(f"[{time.time():.3f}] [Parent] Subprocess started (pid={p.pid}), waiting for result ({POLL_TIMEOUT_ABSOLUTE}s timeout)", flush=True) result = 0.0 try: # Async-friendly polling: check in small intervals without blocking event loop deadline = time.time() + POLL_TIMEOUT_ABSOLUTE while time.time() < deadline: # Run poll() in thread to avoid blocking event loop has_data = await asyncio.to_thread(parent_conn.poll, 0.1) if has_data: print(f"[{time.time():.3f}] [Parent] Result available, receiving", flush=True) result = await asyncio.to_thread(parent_conn.recv) # Check if result is an error dict if isinstance(result, dict) and 'error' in result: raise RuntimeError(f"Image comparison failed: {result['error']}") print(f"[{time.time():.3f}] [Parent] Result received: {result:.2f}%", flush=True) break await asyncio.sleep(0) # Yield control to event loop else: from loguru import logger logger.critical(f"[OpenCV subprocess] Timeout waiting for compare_images result after {POLL_TIMEOUT_ABSOLUTE}s (subprocess may be hung)") print(f"[{time.time():.3f}] [Parent] Timeout waiting for result after {POLL_TIMEOUT_ABSOLUTE}s", flush=True) raise TimeoutError(f"Image comparison subprocess timeout after {POLL_TIMEOUT_ABSOLUTE}s") except Exception as e: print(f"[{time.time():.3f}] [Parent] Error receiving result: {e}", flush=True) raise finally: # Always close pipe first try: parent_conn.close() except: pass # Try graceful shutdown (async-safe) print(f"[{time.time():.3f}] [Parent] Waiting for subprocess to exit (5s timeout)", flush=True) join_start = time.time() await asyncio.to_thread(p.join, 5) join_elapsed = time.time() - join_start print(f"[{time.time():.3f}] [Parent] First join took {join_elapsed:.2f}s", flush=True) if p.is_alive(): print(f"[{time.time():.3f}] [Parent] Process didn't exit gracefully, terminating", flush=True) term_start = time.time() p.terminate() await asyncio.to_thread(p.join, 3) term_elapsed = time.time() - term_start print(f"[{time.time():.3f}] [Parent] Terminate+join took {term_elapsed:.2f}s", flush=True) # Force kill if still alive if p.is_alive(): print(f"[{time.time():.3f}] [Parent] Process didn't terminate, killing", flush=True) kill_start = time.time() p.kill() await asyncio.to_thread(p.join, 1) kill_elapsed = time.time() - kill_start print(f"[{time.time():.3f}] [Parent] Kill+join took {kill_elapsed:.2f}s", flush=True) print(f"[{time.time():.3f}] [Parent] Subprocess cleanup complete, returning result", flush=True) return result def _worker_generate_diff(conn, img_bytes_from, img_bytes_to, pixel_difference_threshold, blur_sigma, max_width, max_height): """ Worker function for generating visual diff with red overlay. """ import time try: import cv2 cv2.setNumThreads(1) print(f"[{time.time():.3f}] [Worker] Generate diff worker starting", flush=True) # Decode images img_from = cv2.imdecode(np.frombuffer(img_bytes_from, np.uint8), cv2.IMREAD_COLOR) img_to = cv2.imdecode(np.frombuffer(img_bytes_to, np.uint8), cv2.IMREAD_COLOR) # Resize if needed to match dimensions if img_from.shape != img_to.shape: img_from = cv2.resize(img_from, (img_to.shape[1], img_to.shape[0])) # Downscale to max dimensions for faster processing h, w = img_to.shape[:2] if w > max_width or h > max_height: scale = min(max_width / w, max_height / h) new_w = int(w * scale) new_h = int(h * scale) img_from = cv2.resize(img_from, (new_w, new_h)) img_to = cv2.resize(img_to, (new_w, new_h)) # Convert to grayscale gray_from = cv2.cvtColor(img_from, cv2.COLOR_BGR2GRAY) gray_to = cv2.cvtColor(img_to, cv2.COLOR_BGR2GRAY) # Optional blur if blur_sigma > 0: ksize = int(2 * round(3 * blur_sigma)) + 1 if ksize % 2 == 0: ksize += 1 gray_from = cv2.GaussianBlur(gray_from, (ksize, ksize), blur_sigma) gray_to = cv2.GaussianBlur(gray_to, (ksize, ksize), blur_sigma) # Calculate difference diff = cv2.absdiff(gray_from, gray_to) # Apply threshold to get mask _, mask = cv2.threshold(diff, int(pixel_difference_threshold), 255, cv2.THRESH_BINARY) # Create red overlay on original 'to' image # Where mask is 255 (changed), blend 50% red overlay = img_to.copy() overlay[:, :, 2] = np.where(mask > 0, np.clip(overlay[:, :, 2] * 0.5 + 127, 0, 255).astype(np.uint8), overlay[:, :, 2]) overlay[:, :, 0:2] = np.where(mask[:, :, np.newaxis] > 0, (overlay[:, :, 0:2] * 0.5).astype(np.uint8), overlay[:, :, 0:2]) # Encode as JPEG _, encoded = cv2.imencode('.jpg', overlay, [cv2.IMWRITE_JPEG_QUALITY, 85]) diff_bytes = encoded.tobytes() print(f"[{time.time():.3f}] [Worker] Generated diff ({len(diff_bytes)} bytes)", flush=True) conn.send(diff_bytes) except Exception as e: print(f"[{time.time():.3f}] [Worker] Generate diff error: {e}", flush=True) import traceback traceback.print_exc() # Send error info as dict so parent can re-raise conn.send({'error': str(e), 'traceback': traceback.format_exc()}) finally: conn.close() async def generate_diff_isolated(img_bytes_from, img_bytes_to, pixel_difference_threshold, blur_sigma, max_width, max_height): """ Generate visual diff with red overlay in isolated subprocess (async-safe). Returns: bytes: JPEG diff image or None on failure """ import time import asyncio print(f"[{time.time():.3f}] [Parent] Starting generate_diff subprocess", flush=True) ctx = multiprocessing.get_context('spawn') parent_conn, child_conn = ctx.Pipe() p = ctx.Process( target=_worker_generate_diff, args=(child_conn, img_bytes_from, img_bytes_to, pixel_difference_threshold, blur_sigma, max_width, max_height) ) print(f"[{time.time():.3f}] [Parent] Starting subprocess", flush=True) p.start() print(f"[{time.time():.3f}] [Parent] Subprocess started (pid={p.pid}), waiting for result ({POLL_TIMEOUT_ABSOLUTE}s timeout)", flush=True) result = None try: # Async-friendly polling: check in small intervals without blocking event loop deadline = time.time() + POLL_TIMEOUT_ABSOLUTE while time.time() < deadline: # Run poll() in thread to avoid blocking event loop has_data = await asyncio.to_thread(parent_conn.poll, 0.1) if has_data: print(f"[{time.time():.3f}] [Parent] Result available, receiving", flush=True) result = await asyncio.to_thread(parent_conn.recv) # Check if result is an error dict if isinstance(result, dict) and 'error' in result: raise RuntimeError(f"Generate diff failed: {result['error']}") print(f"[{time.time():.3f}] [Parent] Result received ({len(result) if result else 0} bytes)", flush=True) break await asyncio.sleep(0) # Yield control to event loop else: from loguru import logger logger.critical(f"[OpenCV subprocess] Timeout waiting for generate_diff result after {POLL_TIMEOUT_ABSOLUTE}s (subprocess may be hung)") print(f"[{time.time():.3f}] [Parent] Timeout waiting for result after {POLL_TIMEOUT_ABSOLUTE}s", flush=True) raise TimeoutError(f"Generate diff subprocess timeout after {POLL_TIMEOUT_ABSOLUTE}s") except Exception as e: print(f"[{time.time():.3f}] [Parent] Error receiving diff: {e}", flush=True) raise finally: # Always close pipe first try: parent_conn.close() except: pass # Try graceful shutdown (async-safe) print(f"[{time.time():.3f}] [Parent] Waiting for subprocess to exit (5s timeout)", flush=True) join_start = time.time() await asyncio.to_thread(p.join, 5) join_elapsed = time.time() - join_start print(f"[{time.time():.3f}] [Parent] First join took {join_elapsed:.2f}s", flush=True) if p.is_alive(): print(f"[{time.time():.3f}] [Parent] Process didn't exit gracefully, terminating", flush=True) term_start = time.time() p.terminate() await asyncio.to_thread(p.join, 3) term_elapsed = time.time() - term_start print(f"[{time.time():.3f}] [Parent] Terminate+join took {term_elapsed:.2f}s", flush=True) if p.is_alive(): print(f"[{time.time():.3f}] [Parent] Process didn't terminate, killing", flush=True) kill_start = time.time() p.kill() await asyncio.to_thread(p.join, 1) kill_elapsed = time.time() - kill_start print(f"[{time.time():.3f}] [Parent] Kill+join took {kill_elapsed:.2f}s", flush=True) print(f"[{time.time():.3f}] [Parent] Subprocess cleanup complete, returning result", flush=True) return result def _worker_draw_bounding_box(conn, img_bytes, x, y, width, height, color, thickness): """ Worker function for drawing bounding box on image. """ import time try: import cv2 cv2.setNumThreads(1) print(f"[{time.time():.3f}] [Worker] Draw bounding box worker starting", flush=True) # Decode image img = cv2.imdecode(np.frombuffer(img_bytes, np.uint8), cv2.IMREAD_COLOR) if img is None: print(f"[{time.time():.3f}] [Worker] Failed to decode image", flush=True) conn.send(None) return # Draw rectangle (BGR format) cv2.rectangle(img, (x, y), (x + width, y + height), color, thickness) # Encode back to PNG _, encoded = cv2.imencode('.png', img) result_bytes = encoded.tobytes() print(f"[{time.time():.3f}] [Worker] Bounding box drawn ({len(result_bytes)} bytes)", flush=True) conn.send(result_bytes) except Exception as e: print(f"[{time.time():.3f}] [Worker] Draw bounding box error: {e}", flush=True) import traceback traceback.print_exc() # Send error info as dict so parent can re-raise conn.send({'error': str(e), 'traceback': traceback.format_exc()}) finally: conn.close() async def draw_bounding_box_isolated(img_bytes, x, y, width, height, color=(255, 0, 0), thickness=3): """ Draw bounding box on image in isolated subprocess (async-safe). Args: img_bytes: Image data as bytes x: Left coordinate y: Top coordinate width: Box width height: Box height color: BGR color tuple (default: blue) thickness: Line thickness in pixels Returns: bytes: PNG image with bounding box or None on failure """ import time import asyncio print(f"[{time.time():.3f}] [Parent] Starting draw_bounding_box subprocess", flush=True) ctx = multiprocessing.get_context('spawn') parent_conn, child_conn = ctx.Pipe() p = ctx.Process( target=_worker_draw_bounding_box, args=(child_conn, img_bytes, x, y, width, height, color, thickness) ) print(f"[{time.time():.3f}] [Parent] Starting subprocess", flush=True) p.start() print(f"[{time.time():.3f}] [Parent] Subprocess started (pid={p.pid}), waiting for result ({POLL_TIMEOUT_ABSOLUTE}s timeout)", flush=True) result = None try: # Async-friendly polling: check in small intervals without blocking event loop deadline = time.time() + POLL_TIMEOUT_ABSOLUTE while time.time() < deadline: # Run poll() in thread to avoid blocking event loop has_data = await asyncio.to_thread(parent_conn.poll, 0.1) if has_data: print(f"[{time.time():.3f}] [Parent] Result available, receiving", flush=True) # Run recv() in thread too result = await asyncio.to_thread(parent_conn.recv) # Check if result is an error dict if isinstance(result, dict) and 'error' in result: raise RuntimeError(f"Draw bounding box failed: {result['error']}") print(f"[{time.time():.3f}] [Parent] Result received ({len(result) if result else 0} bytes)", flush=True) break # Yield control to event loop await asyncio.sleep(0) else: from loguru import logger logger.critical(f"[OpenCV subprocess] Timeout waiting for draw_bounding_box result after {POLL_TIMEOUT_ABSOLUTE}s (subprocess may be hung)") print(f"[{time.time():.3f}] [Parent] Timeout waiting for result after {POLL_TIMEOUT_ABSOLUTE}s", flush=True) raise TimeoutError(f"Draw bounding box subprocess timeout after {POLL_TIMEOUT_ABSOLUTE}s") except Exception as e: print(f"[{time.time():.3f}] [Parent] Error receiving result: {e}", flush=True) raise finally: # Always close pipe first try: parent_conn.close() except: pass # Try graceful shutdown (run join in thread to avoid blocking) print(f"[{time.time():.3f}] [Parent] Waiting for subprocess to exit (3s timeout)", flush=True) join_start = time.time() await asyncio.to_thread(p.join, 3) join_elapsed = time.time() - join_start print(f"[{time.time():.3f}] [Parent] First join took {join_elapsed:.2f}s", flush=True) if p.is_alive(): print(f"[{time.time():.3f}] [Parent] Process didn't exit gracefully, terminating", flush=True) term_start = time.time() p.terminate() await asyncio.to_thread(p.join, 2) term_elapsed = time.time() - term_start print(f"[{time.time():.3f}] [Parent] Terminate+join took {term_elapsed:.2f}s", flush=True) if p.is_alive(): print(f"[{time.time():.3f}] [Parent] Process didn't terminate, killing", flush=True) kill_start = time.time() p.kill() await asyncio.to_thread(p.join, 1) kill_elapsed = time.time() - kill_start print(f"[{time.time():.3f}] [Parent] Kill+join took {kill_elapsed:.2f}s", flush=True) print(f"[{time.time():.3f}] [Parent] Subprocess cleanup complete, returning result", flush=True) return result def _worker_calculate_percentage(conn, img_bytes_from, img_bytes_to, pixel_difference_threshold, blur_sigma, max_width, max_height): """ Worker function for calculating change percentage. """ import time try: import cv2 cv2.setNumThreads(1) # Decode images img_from = cv2.imdecode(np.frombuffer(img_bytes_from, np.uint8), cv2.IMREAD_COLOR) img_to = cv2.imdecode(np.frombuffer(img_bytes_to, np.uint8), cv2.IMREAD_COLOR) # Resize if needed if img_from.shape != img_to.shape: img_from = cv2.resize(img_from, (img_to.shape[1], img_to.shape[0])) # Downscale to max dimensions h, w = img_to.shape[:2] if w > max_width or h > max_height: scale = min(max_width / w, max_height / h) new_w = int(w * scale) new_h = int(h * scale) img_from = cv2.resize(img_from, (new_w, new_h)) img_to = cv2.resize(img_to, (new_w, new_h)) # Convert to grayscale gray_from = cv2.cvtColor(img_from, cv2.COLOR_BGR2GRAY) gray_to = cv2.cvtColor(img_to, cv2.COLOR_BGR2GRAY) # Optional blur if blur_sigma > 0: ksize = int(2 * round(3 * blur_sigma)) + 1 if ksize % 2 == 0: ksize += 1 gray_from = cv2.GaussianBlur(gray_from, (ksize, ksize), blur_sigma) gray_to = cv2.GaussianBlur(gray_to, (ksize, ksize), blur_sigma) # Calculate difference diff = cv2.absdiff(gray_from, gray_to) # Apply threshold _, thresholded = cv2.threshold(diff, int(pixel_difference_threshold), 255, cv2.THRESH_BINARY) # Calculate percentage total_pixels = thresholded.size changed_pixels = np.count_nonzero(thresholded) change_percentage = (changed_pixels / total_pixels) * 100.0 conn.send(float(change_percentage)) except Exception as e: print(f"[{time.time():.3f}] [Worker] Calculate percentage error: {e}", flush=True) import traceback traceback.print_exc() # Send error info as dict so parent can re-raise conn.send({'error': str(e), 'traceback': traceback.format_exc()}) finally: conn.close() async def calculate_change_percentage_isolated(img_bytes_from, img_bytes_to, pixel_difference_threshold, blur_sigma, max_width, max_height): """ Calculate change percentage in isolated subprocess (async-safe). Returns: float: Change percentage """ import time import asyncio print(f"[{time.time():.3f}] [Parent] Starting calculate_percentage subprocess", flush=True) ctx = multiprocessing.get_context('spawn') parent_conn, child_conn = ctx.Pipe() p = ctx.Process( target=_worker_calculate_percentage, args=(child_conn, img_bytes_from, img_bytes_to, pixel_difference_threshold, blur_sigma, max_width, max_height) ) print(f"[{time.time():.3f}] [Parent] Starting subprocess", flush=True) p.start() print(f"[{time.time():.3f}] [Parent] Subprocess started (pid={p.pid}), waiting for result ({POLL_TIMEOUT_ABSOLUTE}s timeout)", flush=True) result = 0.0 try: # Async-friendly polling: check in small intervals without blocking event loop deadline = time.time() + POLL_TIMEOUT_ABSOLUTE while time.time() < deadline: # Run poll() in thread to avoid blocking event loop has_data = await asyncio.to_thread(parent_conn.poll, 0.1) if has_data: print(f"[{time.time():.3f}] [Parent] Result available, receiving", flush=True) result = await asyncio.to_thread(parent_conn.recv) # Check if result is an error dict if isinstance(result, dict) and 'error' in result: raise RuntimeError(f"Calculate change percentage failed: {result['error']}") print(f"[{time.time():.3f}] [Parent] Result received: {result:.2f}%", flush=True) break await asyncio.sleep(0) # Yield control to event loop else: from loguru import logger logger.critical(f"[OpenCV subprocess] Timeout waiting for calculate_change_percentage result after {POLL_TIMEOUT_ABSOLUTE}s (subprocess may be hung)") print(f"[{time.time():.3f}] [Parent] Timeout waiting for result after {POLL_TIMEOUT_ABSOLUTE}s", flush=True) raise TimeoutError(f"Calculate change percentage subprocess timeout after {POLL_TIMEOUT_ABSOLUTE}s") except Exception as e: print(f"[{time.time():.3f}] [Parent] Error receiving percentage: {e}", flush=True) raise finally: # Always close pipe first try: parent_conn.close() except: pass # Try graceful shutdown (async-safe) print(f"[{time.time():.3f}] [Parent] Waiting for subprocess to exit (5s timeout)", flush=True) join_start = time.time() await asyncio.to_thread(p.join, 5) join_elapsed = time.time() - join_start print(f"[{time.time():.3f}] [Parent] First join took {join_elapsed:.2f}s", flush=True) if p.is_alive(): print(f"[{time.time():.3f}] [Parent] Process didn't exit gracefully, terminating", flush=True) term_start = time.time() p.terminate() await asyncio.to_thread(p.join, 3) term_elapsed = time.time() - term_start print(f"[{time.time():.3f}] [Parent] Terminate+join took {term_elapsed:.2f}s", flush=True) if p.is_alive(): print(f"[{time.time():.3f}] [Parent] Process didn't terminate, killing", flush=True) kill_start = time.time() p.kill() await asyncio.to_thread(p.join, 1) kill_elapsed = time.time() - kill_start print(f"[{time.time():.3f}] [Parent] Kill+join took {kill_elapsed:.2f}s", flush=True) print(f"[{time.time():.3f}] [Parent] Subprocess cleanup complete, returning result", flush=True) return result
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/processors/image_ssim_diff/image_handler/isolated_opencv.py", "license": "Apache License 2.0", "lines": 522, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
dgtlmoon/changedetection.io:changedetectionio/processors/image_ssim_diff/image_handler/libvips_handler.py
""" LibVIPS implementation of ImageDiffHandler. Uses pyvips for high-performance image processing with streaming architecture and low memory footprint. Ideal for large screenshots (8000px+). """ from __future__ import annotations import os from typing import Tuple, Any, TYPE_CHECKING from loguru import logger if TYPE_CHECKING: import pyvips try: import pyvips PYVIPS_AVAILABLE = True except ImportError: PYVIPS_AVAILABLE = False logger.warning("pyvips not available - install with: pip install pyvips") from . import ImageDiffHandler class LibvipsImageDiffHandler(ImageDiffHandler): """ LibVIPS implementation using streaming architecture. Benefits: - 3x faster than ImageMagick - 5x less memory than PIL - Automatic multi-threading - Streaming - processes images in chunks """ def __init__(self): if not PYVIPS_AVAILABLE: raise ImportError("pyvips is not installed. Install with: pip install pyvips") def load_from_bytes(self, img_bytes: bytes) -> pyvips.Image: """Load image from bytes using libvips streaming.""" return pyvips.Image.new_from_buffer(img_bytes, '') def save_to_bytes(self, img: pyvips.Image, format: str = 'png', quality: int = 85) -> bytes: """ Save image to bytes using temp file. Note: Uses temp file instead of write_to_buffer() to avoid C memory leak. See: https://github.com/libvips/pyvips/issues/234 """ import tempfile format = format.lower() try: if format == 'png': suffix = '.png' write_args = {'compression': 6} elif format in ['jpg', 'jpeg']: suffix = '.jpg' write_args = {'Q': quality} else: raise ValueError(f"Unsupported format: {format}") # Use temp file to avoid write_to_buffer() memory leak with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp: temp_path = tmp.name # Write to file img.write_to_file(temp_path, **write_args) # Read bytes and clean up with open(temp_path, 'rb') as f: image_bytes = f.read() os.unlink(temp_path) return image_bytes except Exception as e: logger.error(f"Failed to save via temp file: {e}") # Fallback to write_to_buffer if temp file fails if format == 'png': return img.write_to_buffer('.png', compression=6) else: return img.write_to_buffer('.jpg', Q=quality) def crop(self, img: pyvips.Image, left: int, top: int, right: int, bottom: int) -> pyvips.Image: """Crop image using libvips.""" width = right - left height = bottom - top return img.crop(left, top, width, height) def resize(self, img: pyvips.Image, max_width: int, max_height: int) -> pyvips.Image: """ Resize image maintaining aspect ratio. Uses thumbnail_image for efficient downscaling with streaming. """ width, height = img.width, img.height if width <= max_width and height <= max_height: return img # Calculate scaling to fit within max dimensions width_ratio = max_width / width if width > max_width else 1.0 height_ratio = max_height / height if height > max_height else 1.0 ratio = min(width_ratio, height_ratio) new_width = int(width * ratio) new_height = int(height * ratio) logger.debug(f"Resizing image: {width}x{height} -> {new_width}x{new_height}") # thumbnail_image is faster than resize for downscaling return img.thumbnail_image(new_width, height=new_height) def get_dimensions(self, img: pyvips.Image) -> Tuple[int, int]: """Get image dimensions.""" return (img.width, img.height) def to_grayscale(self, img: pyvips.Image) -> pyvips.Image: """Convert to grayscale using 'b-w' colorspace.""" return img.colourspace('b-w') def gaussian_blur(self, img: pyvips.Image, sigma: float) -> pyvips.Image: """Apply Gaussian blur.""" if sigma > 0: return img.gaussblur(sigma) return img def absolute_difference(self, img1: pyvips.Image, img2: pyvips.Image) -> pyvips.Image: """ Calculate absolute difference using operator overloading. LibVIPS supports arithmetic operations between images. """ return (img1 - img2).abs() def threshold(self, img: pyvips.Image, threshold_value: int) -> Tuple[float, pyvips.Image]: """ Apply threshold and calculate change percentage. Uses ifthenelse for efficient thresholding. """ # Create binary mask: pixels above threshold = 255, others = 0 mask = (img > threshold_value).ifthenelse(255, 0) # Calculate percentage by averaging mask values # avg() returns mean pixel value (0-255) # Divide by 255 to get proportion, multiply by 100 for percentage mean_value = mask.avg() change_percentage = (mean_value / 255.0) * 100.0 return float(change_percentage), mask def apply_red_overlay(self, img: pyvips.Image, mask: pyvips.Image) -> bytes: """ Apply red overlay where mask is True (50% blend). Args: img: Color image (will be converted to RGB if needed) mask: Binary mask (255 where changed, 0 elsewhere) Returns: JPEG bytes with red overlay """ import tempfile # Ensure RGB colorspace if img.bands == 1: img = img.colourspace('srgb') # Normalize mask to 0-1 range for blending mask_normalized = mask / 255.0 # Split into R, G, B channels channels = img.bandsplit() r, g, b = channels[0], channels[1], channels[2] # Apply red overlay (50% blend): # Where mask is 1: blend 50% original with 50% red (255) # Where mask is 0: keep original r = r * (1 - mask_normalized * 0.5) + 127.5 * mask_normalized g = g * (1 - mask_normalized * 0.5) b = b * (1 - mask_normalized * 0.5) # Recombine channels result = r.bandjoin([g, b]) # CRITICAL: Use temp file instead of write_to_buffer() # write_to_buffer() leaks C memory that isn't returned to OS # See: https://github.com/libvips/pyvips/issues/234 try: with tempfile.NamedTemporaryFile(suffix='.jpg', delete=False) as tmp: temp_path = tmp.name # Write to file (doesn't leak like write_to_buffer) result.write_to_file(temp_path, Q=85) # Read bytes and clean up with open(temp_path, 'rb') as f: image_bytes = f.read() os.unlink(temp_path) return image_bytes except Exception as e: logger.error(f"Failed to write image via temp file: {e}") # Fallback to write_to_buffer if temp file fails return result.write_to_buffer('.jpg', Q=85) def close(self, img: pyvips.Image) -> None: """ LibVIPS uses automatic reference counting. No explicit cleanup needed - memory freed when references drop to zero. """ pass def find_template( self, img: pyvips.Image, template_img: pyvips.Image, original_bbox: Tuple[int, int, int, int], search_tolerance: float = 0.2 ) -> Tuple[int, int, int, int]: """ Find template in image using OpenCV template matching. Note: This temporarily converts to numpy for OpenCV operations since libvips doesn't have template matching built-in. """ import cv2 import numpy as np try: left, top, right, bottom = original_bbox width = right - left height = bottom - top # Calculate search region margin_x = int(width * search_tolerance) margin_y = int(height * search_tolerance) search_left = max(0, left - margin_x) search_top = max(0, top - margin_y) search_right = min(img.width, right + margin_x) search_bottom = min(img.height, bottom + margin_y) # Crop search region search_region = self.crop(img, search_left, search_top, search_right, search_bottom) # Convert to numpy arrays for OpenCV search_array = np.ndarray( buffer=search_region.write_to_memory(), dtype=np.uint8, shape=[search_region.height, search_region.width, search_region.bands] ) template_array = np.ndarray( buffer=template_img.write_to_memory(), dtype=np.uint8, shape=[template_img.height, template_img.width, template_img.bands] ) # Convert to grayscale if len(search_array.shape) == 3: search_gray = cv2.cvtColor(search_array, cv2.COLOR_RGB2GRAY) else: search_gray = search_array if len(template_array.shape) == 3: template_gray = cv2.cvtColor(template_array, cv2.COLOR_RGB2GRAY) else: template_gray = template_array logger.debug(f"Searching for template in region: ({search_left}, {search_top}) to ({search_right}, {search_bottom})") # Perform template matching result = cv2.matchTemplate(search_gray, template_gray, cv2.TM_CCOEFF_NORMED) min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result) logger.debug(f"Template matching confidence: {max_val:.2%}") # Check if match is good enough (80% confidence threshold) if max_val >= 0.8: # Calculate new bounding box in original image coordinates match_x = search_left + max_loc[0] match_y = search_top + max_loc[1] new_bbox = (match_x, match_y, match_x + width, match_y + height) # Calculate movement distance move_x = abs(match_x - left) move_y = abs(match_y - top) logger.info(f"Template found at ({match_x}, {match_y}), " f"moved {move_x}px horizontally, {move_y}px vertically, " f"confidence: {max_val:.2%}") return new_bbox else: logger.warning(f"Template match confidence too low: {max_val:.2%} (need 80%)") return None except Exception as e: logger.error(f"Template matching error: {e}") return None def save_template( self, img: pyvips.Image, bbox: Tuple[int, int, int, int], output_path: str ) -> bool: """ Save a cropped region as a template file. """ import os try: left, top, right, bottom = bbox width = right - left height = bottom - top # Ensure output directory exists os.makedirs(os.path.dirname(output_path), exist_ok=True) # Crop template region template = self.crop(img, left, top, right, bottom) # Save as PNG template.write_to_file(output_path, compression=6) logger.info(f"Saved template: {output_path} ({width}x{height}px)") return True except Exception as e: logger.error(f"Failed to save template: {e}") return False
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/processors/image_ssim_diff/image_handler/libvips_handler.py", "license": "Apache License 2.0", "lines": 264, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
dgtlmoon/changedetection.io:changedetectionio/processors/image_ssim_diff/preview.py
""" Preview rendering for SSIM screenshot processor. Renders images properly in the browser instead of showing raw bytes. """ from flask_babel import gettext from loguru import logger def get_asset(asset_name, watch, datastore, request): """ Get processor-specific binary assets for preview streaming. This function supports serving images as separate HTTP responses instead of embedding them as base64 in the HTML template, solving memory issues with large screenshots. Supported assets: - 'screenshot': The screenshot for the specified version Args: asset_name: Name of the asset to retrieve ('screenshot') watch: Watch object datastore: Datastore object request: Flask request (for version query param) Returns: tuple: (binary_data, content_type, cache_control_header) or None if not found """ if asset_name != 'screenshot': return None versions = list(watch.history.keys()) if len(versions) == 0: return None # Get the version from query string (default: latest) preferred_version = request.args.get('version') timestamp = versions[-1] if preferred_version and preferred_version in versions: timestamp = preferred_version try: screenshot_bytes = watch.get_history_snapshot(timestamp=timestamp) # Verify we got bytes (should always be bytes for image files) if not isinstance(screenshot_bytes, bytes): logger.error(f"Expected bytes but got {type(screenshot_bytes)} for screenshot at {timestamp}") return None # Detect image format using puremagic (same as Watch.py) try: import puremagic detections = puremagic.magic_string(screenshot_bytes[:2048]) if detections: mime_type = detections[0].mime_type logger.trace(f"Detected MIME type: {mime_type}") else: mime_type = 'image/png' # Default fallback except Exception as e: logger.warning(f"puremagic detection failed: {e}, using 'image/png' fallback") mime_type = 'image/png' return (screenshot_bytes, mime_type, 'public, max-age=10') except Exception as e: logger.error(f"Failed to load screenshot for preview asset: {e}") return None def render(watch, datastore, request, url_for, render_template, flash, redirect): """ Render the preview page for screenshot watches. Args: watch: Watch object datastore: Datastore object request: Flask request url_for: Flask url_for function render_template: Flask render_template function flash: Flask flash function redirect: Flask redirect function Returns: Rendered template or redirect """ versions = list(watch.history.keys()) if len(versions) == 0: flash(gettext("Preview unavailable - No snapshots captured yet"), "error") return redirect(url_for('watchlist.index')) # Get the version to display (default: latest) preferred_version = request.args.get('version') timestamp = versions[-1] if preferred_version and preferred_version in versions: timestamp = preferred_version # Render custom template for image preview # Screenshot is now served via separate /processor-asset/ endpoint instead of base64 # This significantly reduces memory usage by not embedding large images in HTML return render_template( 'image_ssim_diff/preview.html', watch=watch, uuid=watch.get('uuid'), versions=versions, timestamp=timestamp, current_diff_url=watch['url'] )
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/processors/image_ssim_diff/preview.py", "license": "Apache License 2.0", "lines": 88, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
dgtlmoon/changedetection.io:changedetectionio/processors/image_ssim_diff/processor.py
""" Core fast screenshot comparison processor. Uses OpenCV with subprocess isolation for high-performance, low-memory image processing. All operations run in isolated subprocesses for complete memory cleanup and stability. """ import hashlib import time from loguru import logger from changedetectionio.processors.exceptions import ProcessorException from . import SCREENSHOT_COMPARISON_THRESHOLD_OPTIONS_DEFAULT, PROCESSOR_CONFIG_NAME, OPENCV_BLUR_SIGMA from ..base import difference_detection_processor, SCREENSHOT_FORMAT_PNG # All image operations now use OpenCV via isolated_opencv subprocess handler # Template matching temporarily disabled pending OpenCV implementation # Translation marker for extraction def _(x): return x name = _('Visual / Image screenshot change detection') description = _('Compares screenshots using fast OpenCV algorithm, 10-100x faster than SSIM') del _ processor_weight = 2 list_badge_text = "Visual" class perform_site_check(difference_detection_processor): """Fast screenshot comparison processor using OpenCV.""" # Override to use PNG format for better image comparison (JPEG compression creates noise) screenshot_format = SCREENSHOT_FORMAT_PNG def run_changedetection(self, watch, force_reprocess=False): """ Perform screenshot comparison using OpenCV subprocess handler. Returns: tuple: (changed_detected, update_obj, screenshot_bytes) """ now = time.time() # Get the current screenshot if not self.fetcher.screenshot: raise ProcessorException( message="No screenshot available. Ensure the watch is configured to use a real browser.", url=watch.get('url') ) self.screenshot = self.fetcher.screenshot self.xpath_data = self.fetcher.xpath_data # Quick MD5 check - skip expensive comparison if images are identical from changedetectionio.content_fetchers.exceptions import checksumFromPreviousCheckWasTheSame current_md5 = hashlib.md5(self.screenshot).hexdigest() previous_md5 = watch.get('previous_md5') if previous_md5 and current_md5 == previous_md5: logger.debug(f"UUID: {watch.get('uuid')} - Screenshot MD5 unchanged ({current_md5}), skipping comparison") raise checksumFromPreviousCheckWasTheSame() else: logger.debug(f"UUID: {watch.get('uuid')} - Screenshot MD5 changed") # Check if bounding box is set (for drawn area mode) # Read from processor-specific config JSON file (named after processor) crop_region = None processor_config = self.get_extra_watch_config(PROCESSOR_CONFIG_NAME) bounding_box = processor_config.get('bounding_box') if processor_config else None # Get pixel difference threshold sensitivity (per-watch > global) # This controls how different a pixel must be (0-255 scale) to count as "changed" pixel_difference_threshold_sensitivity = processor_config.get('pixel_difference_threshold_sensitivity') if not pixel_difference_threshold_sensitivity: pixel_difference_threshold_sensitivity = self.datastore.data['settings']['application'].get('pixel_difference_threshold_sensitivity', SCREENSHOT_COMPARISON_THRESHOLD_OPTIONS_DEFAULT) try: pixel_difference_threshold_sensitivity = int(pixel_difference_threshold_sensitivity) except (ValueError, TypeError): logger.warning(f"Invalid pixel_difference_threshold_sensitivity value '{pixel_difference_threshold_sensitivity}', using default") pixel_difference_threshold_sensitivity = SCREENSHOT_COMPARISON_THRESHOLD_OPTIONS_DEFAULT # Get minimum change percentage (per-watch > global > env var default) # This controls what percentage of pixels must change to trigger a detection min_change_percentage = processor_config.get('min_change_percentage') if not min_change_percentage: min_change_percentage = self.datastore.data['settings']['application'].get('min_change_percentage', 1) try: min_change_percentage = int(min_change_percentage) except (ValueError, TypeError): logger.warning(f"Invalid min_change_percentage value '{min_change_percentage}', using default 0.1") min_change_percentage = 1 # Template matching for tracking content movement template_matching_enabled = processor_config.get('auto_track_region', False) #@@todo disabled for now if bounding_box: try: # Parse bounding box: "x,y,width,height" parts = [int(p.strip()) for p in bounding_box.split(',')] if len(parts) == 4: x, y, width, height = parts # Crop uses (left, top, right, bottom) crop_region = (max(0, x), max(0, y), x + width, y + height) logger.info(f"UUID: {watch.get('uuid')} - Bounding box enabled: cropping to region {crop_region} (x={x}, y={y}, w={width}, h={height})") else: logger.warning(f"UUID: {watch.get('uuid')} - Invalid bounding box format: {bounding_box} (expected 4 values)") except Exception as e: logger.warning(f"UUID: {watch.get('uuid')} - Failed to parse bounding box '{bounding_box}': {e}") # If no bounding box, check if visual selector (include_filters) is set for region-based comparison if not crop_region: include_filters = watch.get('include_filters', []) if include_filters and len(include_filters) > 0: # Get the first filter to use for cropping first_filter = include_filters[0].strip() if first_filter and self.xpath_data: try: import json # xpath_data is JSON string from browser xpath_data_obj = json.loads(self.xpath_data) if isinstance(self.xpath_data, str) else self.xpath_data # Find the bounding box for the first filter for element in xpath_data_obj.get('size_pos', []): # Match the filter with the element's xpath if element.get('xpath') == first_filter and element.get('highlight_as_custom_filter'): # Found the element - extract crop coordinates left = element.get('left', 0) top = element.get('top', 0) width = element.get('width', 0) height = element.get('height', 0) # Crop uses (left, top, right, bottom) crop_region = (max(0, left), max(0, top), left + width, top + height) logger.info(f"UUID: {watch.get('uuid')} - Visual selector enabled: cropping to region {crop_region} for filter: {first_filter}") break except Exception as e: logger.warning(f"UUID: {watch.get('uuid')} - Failed to parse xpath_data for visual selector: {e}") # Store original crop region for template matching original_crop_region = crop_region # Check if this is the first check (no previous history) history_keys = list(watch.history.keys()) if len(history_keys) == 0: # First check - save baseline, no comparison logger.info(f"UUID: {watch.get('uuid')} - First check for watch {watch.get('uuid')} - saving baseline screenshot") # LibVIPS uses automatic reference counting - no explicit cleanup needed update_obj = { 'previous_md5': hashlib.md5(self.screenshot).hexdigest(), 'last_error': False } logger.trace(f"Processed in {time.time() - now:.3f}s") return False, update_obj, self.screenshot # Get previous screenshot bytes from history previous_timestamp = history_keys[-1] previous_screenshot_bytes = watch.get_history_snapshot(timestamp=previous_timestamp) # Screenshots are stored as PNG, so this should be bytes if isinstance(previous_screenshot_bytes, str): # If it's a string (shouldn't be for screenshots, but handle it) previous_screenshot_bytes = previous_screenshot_bytes.encode('utf-8') # Template matching is temporarily disabled pending OpenCV implementation # crop_region calculated above will be used as-is # Perform comparison in isolated subprocess to prevent memory leaks try: from .image_handler import isolated_opencv as process_screenshot_handler # stuff in watch doesnt need to be there logger.debug(f"UUID: {watch.get('uuid')} - Starting isolated subprocess comparison (crop_region={crop_region})") # Compare using isolated subprocess with OpenCV (async-safe to avoid blocking event loop) # Pass raw bytes and crop region - subprocess handles all image operations import asyncio import threading # Async-safe wrapper: runs coroutine in new thread with its own event loop # This prevents blocking the async update worker's event loop def run_async_in_thread(): return asyncio.run( process_screenshot_handler.compare_images_isolated( img_bytes_from=previous_screenshot_bytes, img_bytes_to=self.screenshot, pixel_difference_threshold=pixel_difference_threshold_sensitivity, blur_sigma=OPENCV_BLUR_SIGMA, crop_region=crop_region # Pass crop region for isolated cropping ) ) # Run in thread to avoid blocking event loop when called from async update worker result_container = [None] exception_container = [None] def thread_target(): try: result_container[0] = run_async_in_thread() except Exception as e: exception_container[0] = e thread = threading.Thread(target=thread_target, daemon=True, name="ImageDiff-Processor") thread.start() thread.join(timeout=60) if exception_container[0]: raise exception_container[0] # Subprocess returns only the change score - we decide if it's a "change" change_score = result_container[0] if change_score is None: raise RuntimeError("Image comparison subprocess returned no result") changed_detected = change_score > min_change_percentage logger.info(f"UUID: {watch.get('uuid')} - {process_screenshot_handler.IMPLEMENTATION_NAME}: {change_score:.2f}% pixels changed, pixel_diff_threshold_sensitivity: {pixel_difference_threshold_sensitivity:.0f} score={change_score:.2f}%, min_change_threshold={min_change_percentage}%") except Exception as e: logger.error(f"UUID: {watch.get('uuid')} - Failed to compare screenshots: {e}") logger.trace(f"UUID: {watch.get('uuid')} - Processed in {time.time() - now:.3f}s") raise ProcessorException( message=f"UUID: {watch.get('uuid')} - Screenshot comparison failed: {e}", url=watch.get('url') ) # Return results update_obj = { 'previous_md5': hashlib.md5(self.screenshot).hexdigest(), 'last_error': False } if changed_detected: logger.info(f"UUID: {watch.get('uuid')} - Change detected using OpenCV! Score: {change_score:.2f}") else: logger.debug(f"UUID: {watch.get('uuid')} - No significant change using OpenCV. Score: {change_score:.2f}") logger.trace(f"UUID: {watch.get('uuid')} - Processed in {time.time() - now:.3f}s") return changed_detected, update_obj, self.screenshot
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/processors/image_ssim_diff/processor.py", "license": "Apache License 2.0", "lines": 196, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
dgtlmoon/changedetection.io:changedetectionio/processors/image_ssim_diff/util.py
""" DEPRECATED: All multiprocessing functions have been removed. The image_ssim_diff processor now uses LibVIPS via ImageDiffHandler abstraction, which provides superior performance and memory efficiency through streaming architecture and automatic threading. All image operations are now handled by: - imagehandler.py: Abstract base class defining the interface - libvips_handler.py: LibVIPS implementation with streaming and threading Historical note: This file previously contained multiprocessing workers for: - Template matching (find_region_with_template_matching_isolated) - Template regeneration (regenerate_template_isolated) - Image cropping (crop_image_isolated, crop_pil_image_isolated) These have been replaced by handler methods which are: - Faster (no subprocess overhead) - More memory efficient (LibVIPS streaming) - Cleaner (no multiprocessing deadlocks) - Better tested (no logger/forking issues) """
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/processors/image_ssim_diff/util.py", "license": "Apache License 2.0", "lines": 18, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
dgtlmoon/changedetection.io:changedetectionio/processors/text_json_diff/difference.py
""" History/diff rendering for text_json_diff processor. This module handles the visualization of text/HTML/JSON changes by rendering a side-by-side or unified diff view with syntax highlighting and change markers. """ import os import time from loguru import logger from changedetectionio import diff, strtobool from changedetectionio.diff import ( REMOVED_STYLE, ADDED_STYLE, REMOVED_INNER_STYLE, ADDED_INNER_STYLE, REMOVED_PLACEMARKER_OPEN, REMOVED_PLACEMARKER_CLOSED, ADDED_PLACEMARKER_OPEN, ADDED_PLACEMARKER_CLOSED, CHANGED_PLACEMARKER_OPEN, CHANGED_PLACEMARKER_CLOSED, CHANGED_INTO_PLACEMARKER_OPEN, CHANGED_INTO_PLACEMARKER_CLOSED ) from changedetectionio.notification.handler import apply_html_color_to_body def build_diff_cell_visualizer(content, resolution=100): """ Build a visual cell grid for the diff visualizer. Analyzes the content for placemarkers indicating changes and creates a grid of cells representing the document, with each cell marked as: - 'deletion' for removed content - 'insertion' for added content - 'mixed' for cells containing both deletions and insertions - empty string for cells with no changes Args: content: The diff content with placemarkers resolution: Number of cells to create (default 100) Returns: List of dicts with 'class' key for each cell's CSS class """ if not content: return [{'class': ''} for _ in range(resolution)] now = time.time() # Work with character positions for better accuracy content_length = len(content) if content_length == 0: return [{'class': ''} for _ in range(resolution)] chars_per_cell = max(1, content_length / resolution) # Track change type for each cell cell_data = {} # Placemarkers to detect change_markers = { REMOVED_PLACEMARKER_OPEN: 'deletion', ADDED_PLACEMARKER_OPEN: 'insertion', CHANGED_PLACEMARKER_OPEN: 'deletion', CHANGED_INTO_PLACEMARKER_OPEN: 'insertion', } # Find all occurrences of each marker for marker, change_type in change_markers.items(): pos = 0 while True: pos = content.find(marker, pos) if pos == -1: break # Calculate which cell this marker falls into cell_index = min(int(pos / chars_per_cell), resolution - 1) if cell_index not in cell_data: cell_data[cell_index] = change_type elif cell_data[cell_index] != change_type: # Mixed changes in this cell cell_data[cell_index] = 'mixed' pos += len(marker) # Build the cell list cells = [] for i in range(resolution): change_type = cell_data.get(i, '') cells.append({'class': change_type}) logger.debug(f"Built diff cell visualizer: {len([c for c in cells if c['class']])} cells with changes out of {resolution} in {time.time() - now:.2f}s") return cells # Diff display preferences configuration - single source of truth DIFF_PREFERENCES_CONFIG = { 'changesOnly': {'default': True, 'type': 'bool'}, 'ignoreWhitespace': {'default': False, 'type': 'bool'}, 'removed': {'default': True, 'type': 'bool'}, 'added': {'default': True, 'type': 'bool'}, 'replaced': {'default': True, 'type': 'bool'}, 'type': {'default': 'diffLines', 'type': 'value'}, } def render(watch, datastore, request, url_for, render_template, flash, redirect, extract_form=None): """ Render the history/diff view for text/JSON/HTML changes. Args: watch: The watch object datastore: The ChangeDetectionStore instance request: Flask request object url_for: Flask url_for function render_template: Flask render_template function flash: Flask flash function redirect: Flask redirect function extract_form: Optional pre-built extract form (for error cases) Returns: Rendered HTML response """ from changedetectionio import forms uuid = watch.get('uuid') extra_stylesheets = [url_for('static_content', group='styles', filename='diff.css')] # Use provided form or create a new one if extract_form is None: extract_form = forms.extractDataForm(formdata=request.form, data={'extract_regex': request.form.get('extract_regex', '')} ) history = watch.history dates = list(history.keys()) # If a "from_version" was requested, then find it (or the closest one) # Also set "from version" to be the closest version to the one that was last viewed. best_last_viewed_timestamp = watch.get_from_version_based_on_last_viewed from_version_timestamp = best_last_viewed_timestamp if best_last_viewed_timestamp else dates[-2] from_version = request.args.get('from_version', from_version_timestamp ) # Use the current one if nothing was specified to_version = request.args.get('to_version', str(dates[-1])) try: to_version_file_contents = watch.get_history_snapshot(timestamp=to_version) except Exception as e: logger.error(f"Unable to read watch history to-version for version {to_version}: {str(e)}") to_version_file_contents = f"Unable to read to-version at {to_version}.\n" try: from_version_file_contents = watch.get_history_snapshot(timestamp=from_version) except Exception as e: logger.error(f"Unable to read watch history from-version for version {from_version}: {str(e)}") from_version_file_contents = f"Unable to read to-version {from_version}.\n" screenshot_url = watch.get_screenshot() system_uses_webdriver = datastore.data['settings']['application']['fetch_backend'] == 'html_webdriver' is_html_webdriver = False if (watch.get('fetch_backend') == 'system' and system_uses_webdriver) or watch.get('fetch_backend') == 'html_webdriver' or watch.get('fetch_backend', '').startswith('extra_browser_'): is_html_webdriver = True password_enabled_and_share_is_off = False if datastore.data['settings']['application'].get('password') or os.getenv("SALTED_PASS", False): password_enabled_and_share_is_off = not datastore.data['settings']['application'].get('shared_diff_access') datastore.set_last_viewed(uuid, time.time()) # Parse diff preferences from request using config as single source of truth # Check if this is a user submission (any diff pref param exists in query string) user_submitted = any(key in request.args for key in DIFF_PREFERENCES_CONFIG.keys()) diff_prefs = {} for key, config in DIFF_PREFERENCES_CONFIG.items(): if user_submitted: # User submitted form - missing checkboxes are explicitly OFF if config['type'] == 'bool': diff_prefs[key] = strtobool(request.args.get(key, 'off')) else: diff_prefs[key] = request.args.get(key, config['default']) else: # Initial load - use defaults from config diff_prefs[key] = config['default'] content = diff.render_diff(previous_version_file_contents=from_version_file_contents, newest_version_file_contents=to_version_file_contents, include_replaced=diff_prefs['replaced'], include_added=diff_prefs['added'], include_removed=diff_prefs['removed'], include_equal=diff_prefs['changesOnly'], ignore_junk=diff_prefs['ignoreWhitespace'], word_diff=diff_prefs['type'] == 'diffWords', ) # Build cell grid visualizer before applying HTML color (so we can detect placemarkers) diff_cell_grid = build_diff_cell_visualizer(content) content = apply_html_color_to_body(n_body=content) offscreen_content = render_template("diff-offscreen-options.html") note = '' if str(from_version) != str(dates[-2]) or str(to_version) != str(dates[-1]): note = 'Note: You are not viewing the latest changes.' output = render_template("diff.html", #initial_scroll_line_number=100, bottom_horizontal_offscreen_contents=offscreen_content, content=content, current_diff_url=watch['url'], diff_cell_grid=diff_cell_grid, diff_prefs=diff_prefs, extra_classes='difference-page', extra_stylesheets=extra_stylesheets, extra_title=f" - {watch.label} - History", extract_form=extract_form, from_version=str(from_version), is_html_webdriver=is_html_webdriver, last_error=watch['last_error'], last_error_screenshot=watch.get_error_snapshot(), last_error_text=watch.get_error_text(), newest=to_version_file_contents, newest_version_timestamp=dates[-1], note=note, password_enabled_and_share_is_off=password_enabled_and_share_is_off, pure_menu_fixed=False, screenshot=screenshot_url, to_version=str(to_version), uuid=uuid, versions=dates, # All except current/last watch_a=watch, ) return output
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/processors/text_json_diff/difference.py", "license": "Apache License 2.0", "lines": 189, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
dgtlmoon/changedetection.io:changedetectionio/tests/test_rss_single_watch.py
#!/usr/bin/env python3 import time import os import xml.etree.ElementTree as ET from flask import url_for from .restock.test_restock import set_original_response from .util import live_server_setup, wait_for_all_checks, extract_rss_token_from_UI, extract_UUID_from_client, delete_all_watches, set_modified_response from ..notification import default_notification_format # Watch with no change should not break the output def test_rss_feed_empty(client, live_server, measure_memory_usage, datastore_path): set_original_response(datastore_path=datastore_path) rss_token = extract_rss_token_from_UI(client) test_url = url_for('test_endpoint', _external=True) uuid = client.application.config.get('DATASTORE').add_watch(url=test_url) # Request RSS feed for the single watch res = client.get( url_for("rss.rss_single_watch", uuid=uuid, token=rss_token, _external=True), follow_redirects=True ) assert res.status_code == 400 assert b'does not have enough history snapshots to show' in res.data delete_all_watches(client) def test_rss_single_watch_order(client, live_server, measure_memory_usage, datastore_path): """ Test that single watch RSS feed shows changes in correct order (newest first). """ # Create initial content def set_response(datastore_path, version): test_return_data = f"""<html> <body> <p>Version {version} content</p> </body> </html> """ with open(os.path.join(datastore_path, "endpoint-content.txt"), "w") as f: f.write(test_return_data) # Start with version 1 set_response(datastore_path, 1) # Add a watch test_url = url_for('test_endpoint', _external=True) + "?order_test=1" res = client.post( url_for("ui.ui_views.form_quick_watch_add"), data={"url": test_url, "tags": 'test-tag'}, follow_redirects=True ) assert b"Watch added" in res.data # Get the watch UUID watch_uuid = extract_UUID_from_client(client) # Wait for initial check wait_for_all_checks(client) # Create multiple versions by triggering changes for version in range(2, 6): # Create versions 2, 3, 4, 5 set_response(datastore_path, version) res = client.get(url_for("ui.form_watch_checknow"), follow_redirects=True) wait_for_all_checks(client) time.sleep(0.5) # Small delay to ensure different timestamps # Get RSS token rss_token = extract_rss_token_from_UI(client) # Request RSS feed for the single watch res = client.get( url_for("rss.rss_single_watch", uuid=watch_uuid, token=rss_token, _external=True), follow_redirects=True ) # Should return valid RSS assert res.status_code == 200 assert b"<?xml" in res.data or b"<rss" in res.data # Parse the RSS/XML root = ET.fromstring(res.data) # Find all items (RSS 2.0) or entries (Atom) items = root.findall('.//item') if not items: items = root.findall('.//{http://www.w3.org/2005/Atom}entry') # Should have multiple items assert len(items) >= 3, f"Expected at least 3 items, got {len(items)}" # Get the descriptions/content from first 3 items descriptions = [] for item in items[:3]: # Try RSS format first desc = item.findtext('description') if not desc: # Try Atom format content_elem = item.find('{http://www.w3.org/2005/Atom}content') if content_elem is not None: desc = content_elem.text descriptions.append(desc if desc else "") print(f"First item content (first 200 chars): {descriptions[0][:200] if descriptions[0] else 'None'}") print(f"Second item content (first 200 chars): {descriptions[1][:200] if descriptions[1] else 'None'}") print(f"Third item content (first 200 chars): {descriptions[2][:200] if descriptions[2] else 'None'}") # The FIRST item should contain the NEWEST change (Version 5) # The SECOND item should contain Version 4 # The THIRD item should contain Version 3 # Note: Content may include [edit watch] links and diff markup like "(added) 5" # So we check for "5 content" which appears in "Version 5 content" assert "5 content" in descriptions[0], \ f"First item should show newest change (with '5 content'), but got: {descriptions[0][:500]}" # Verify the order is correct assert "4 content" in descriptions[1], \ f"Second item should show Version 4 (with '4 content'), but got: {descriptions[1][:500]}" assert "3 content" in descriptions[2], \ f"Third item should show Version 3 (with '3 content'), but got: {descriptions[2][:500]}" # Clean up delete_all_watches(client) def test_rss_categories_from_tags(client, live_server, measure_memory_usage, datastore_path): """ Test that RSS feeds include category tags from watch tags. """ # Create initial content test_return_data = """<html> <body> <p>Test content for RSS categories</p> </body> </html> """ with open(os.path.join(datastore_path, "endpoint-content.txt"), "w") as f: f.write(test_return_data) # Create some tags first res = client.post( url_for("tags.form_tag_add"), data={"name": "Security"}, follow_redirects=True ) res = client.post( url_for("tags.form_tag_add"), data={"name": "Python"}, follow_redirects=True ) res = client.post( url_for("tags.form_tag_add"), data={"name": "Tech News"}, follow_redirects=True ) # Add a watch with tags test_url = url_for('test_endpoint', _external=True) + "?category_test=1" res = client.post( url_for("ui.ui_views.form_quick_watch_add"), data={"url": test_url, "tags": "Security, Python, Tech News"}, follow_redirects=True ) assert b"Watch added" in res.data # Get the watch UUID watch_uuid = extract_UUID_from_client(client) # Wait for initial check wait_for_all_checks(client) # Trigger one change test_return_data_v2 = """<html> <body> <p>Updated content for RSS categories</p> </body> </html> """ with open(os.path.join(datastore_path, "endpoint-content.txt"), "w") as f: f.write(test_return_data_v2) res = client.get(url_for("ui.form_watch_checknow"), follow_redirects=True) wait_for_all_checks(client) # Get RSS token rss_token = extract_rss_token_from_UI(client) # Test 1: Check single watch RSS feed res = client.get( url_for("rss.rss_single_watch", uuid=watch_uuid, token=rss_token, _external=True), follow_redirects=True ) assert res.status_code == 200 assert b"<?xml" in res.data or b"<rss" in res.data # Parse the RSS/XML root = ET.fromstring(res.data) # Find all items items = root.findall('.//item') assert len(items) >= 1, "Expected at least 1 item in RSS feed" # Get categories from first item categories = [cat.text for cat in items[0].findall('category')] print(f"Found categories in single watch RSS: {categories}") # Should have all three categories assert "Security" in categories, f"Expected 'Security' category, got: {categories}" assert "Python" in categories, f"Expected 'Python' category, got: {categories}" assert "Tech News" in categories, f"Expected 'Tech News' category, got: {categories}" assert len(categories) == 3, f"Expected 3 categories, got {len(categories)}: {categories}" # Test 2: Check main RSS feed res = client.get( url_for("rss.feed", token=rss_token, _external=True), follow_redirects=True ) assert res.status_code == 200 root = ET.fromstring(res.data) items = root.findall('.//item') assert len(items) >= 1, "Expected at least 1 item in main RSS feed" # Get categories from first item in main feed categories = [cat.text for cat in items[0].findall('category')] print(f"Found categories in main RSS feed: {categories}") # Should have all three categories assert "Security" in categories, f"Expected 'Security' category in main feed, got: {categories}" assert "Python" in categories, f"Expected 'Python' category in main feed, got: {categories}" assert "Tech News" in categories, f"Expected 'Tech News' category in main feed, got: {categories}" # Test 3: Check tag-specific RSS feed (should also have categories) # Get the tag UUID for "Security" and verify the tag feed also has categories from .util import get_UUID_for_tag_name security_tag_uuid = get_UUID_for_tag_name(client, name="Security") if security_tag_uuid: res = client.get( url_for("rss.rss_tag_feed", tag_uuid=security_tag_uuid, token=rss_token, _external=True), follow_redirects=True ) assert res.status_code == 200 root = ET.fromstring(res.data) items = root.findall('.//item') if len(items) >= 1: categories = [cat.text for cat in items[0].findall('category')] print(f"Found categories in tag RSS feed: {categories}") # Should still have all three categories assert "Security" in categories, f"Expected 'Security' category in tag feed, got: {categories}" assert "Python" in categories, f"Expected 'Python' category in tag feed, got: {categories}" assert "Tech News" in categories, f"Expected 'Tech News' category in tag feed, got: {categories}" # Clean up delete_all_watches(client) # RSS <description> should follow Main Settings -> Tag/Group -> Watch in that order of priority if set. def test_rss_single_watch_follow_notification_body(client, live_server, measure_memory_usage, datastore_path): rss_token = extract_rss_token_from_UI(client) res = client.post( url_for("settings.settings_page"), data={ "application-fetch_backend": "html_requests", "application-minutes_between_check": 180, "application-notification_body": 'Boo yeah hello from main settings notification body<br>\nTitle: {{ watch_title }} changed', "application-notification_format": default_notification_format, "application-rss_template_type" : 'notification_body', "application-notification_urls": "", }, follow_redirects=True ) assert b'Settings updated' in res.data set_original_response(datastore_path=datastore_path) # Add our URL to the import page test_url = url_for('test_endpoint', _external=True) uuid = client.application.config.get('DATASTORE').add_watch(url=test_url, tag="RSS-Custom") client.get(url_for("ui.form_watch_checknow"), follow_redirects=True) wait_for_all_checks(client) set_modified_response(datastore_path=datastore_path) client.get(url_for("ui.form_watch_checknow"), follow_redirects=True) wait_for_all_checks(client) # Request RSS feed for the single watch res = client.get( url_for("rss.rss_single_watch", uuid=uuid, token=rss_token, _external=True), follow_redirects=True ) # Should return valid RSS assert res.status_code == 200 assert b"<?xml" in res.data or b"<rss" in res.data # Check it took the notification body from main settings #### item_description = ET.fromstring(res.data).findall('.//item')[0].findtext('description') assert "Boo yeah hello from main settings notification body" in item_description assert "Title: modified head" in item_description ## Edit the tag notification_body, it should cascade up and become the RSS output res = client.post( url_for("tags.form_tag_edit_submit", uuid="first"), data={"name": "rss-custom", "notification_body": 'Hello from the group/tag level'}, follow_redirects=True ) assert b"Updated" in res.data res = client.get( url_for("rss.rss_single_watch", uuid=uuid, token=rss_token, _external=True), follow_redirects=True ) item_description = ET.fromstring(res.data).findall('.//item')[0].findtext('description') assert 'Hello from the group/tag level' in item_description # Override notification body at watch level and check #### res = client.post( url_for("ui.ui_edit.edit_page", uuid=uuid), data={"notification_body": "RSS body description set from watch level at notification body - {{ watch_title }}", "url": test_url, 'fetch_backend': "html_requests", "time_between_check_use_default": "y" }, follow_redirects=True ) assert b"Updated watch." in res.data res = client.get( url_for("rss.rss_single_watch", uuid=uuid, token=rss_token, _external=True), follow_redirects=True ) item_description = ET.fromstring(res.data).findall('.//item')[0].findtext('description') assert 'RSS body description set from watch level at notification body - modified head title' in item_description delete_all_watches(client)
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/tests/test_rss_single_watch.py", "license": "Apache License 2.0", "lines": 282, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
dgtlmoon/changedetection.io:changedetectionio/blueprint/rss/_util.py
""" Utility functions for RSS feed generation. """ from changedetectionio.notification.handler import process_notification from changedetectionio.notification_service import NotificationContextData, _check_cascading_vars from loguru import logger import datetime import pytz import re BAD_CHARS_REGEX = r'[\x00-\x08\x0B\x0C\x0E-\x1F]' def scan_invalid_chars_in_rss(content): """ Scan for invalid characters in RSS content. Returns True if invalid characters are found. """ for match in re.finditer(BAD_CHARS_REGEX, content): i = match.start() bad_char = content[i] hex_value = f"0x{ord(bad_char):02x}" # Grab context start = max(0, i - 20) end = min(len(content), i + 21) context = content[start:end].replace('\n', '\\n').replace('\r', '\\r') logger.warning(f"Invalid char {hex_value} at pos {i}: ...{context}...") # First match is enough return True return False def clean_entry_content(content): """ Remove invalid characters from RSS content. """ cleaned = re.sub(BAD_CHARS_REGEX, '', content) return cleaned def generate_watch_guid(watch, timestamp): """ Generate a unique GUID for a watch RSS entry. Args: watch: The watch object timestamp: The timestamp of the specific change this entry represents """ return f"{watch['uuid']}/{timestamp}" def validate_rss_token(datastore, request): """ Validate the RSS access token from the request. Returns: tuple: (is_valid, error_response) where error_response is None if valid """ app_rss_token = datastore.data['settings']['application'].get('rss_access_token') rss_url_token = request.args.get('token') if rss_url_token != app_rss_token: return False, ("Access denied, bad token", 403) return True, None def get_rss_template(datastore, watch, rss_content_format, default_html, default_plaintext): """Get the appropriate template for RSS content.""" if datastore.data['settings']['application'].get('rss_template_type') == 'notification_body': return _check_cascading_vars(datastore=datastore, var_name='notification_body', watch=watch) override = datastore.data['settings']['application'].get('rss_template_override') if override and override.strip(): return override elif 'text' in rss_content_format: return default_plaintext else: return default_html def get_watch_label(datastore, watch): """Get the label for a watch based on settings.""" if datastore.data['settings']['application']['ui'].get('use_page_title_in_list') or watch.get('use_page_title_in_list'): return watch.label else: return watch.get('url') def add_watch_categories(fe, watch, datastore): """Add category tags to a feed entry based on watch tags.""" for tag_uuid in watch.get('tags', []): tag = datastore.data['settings']['application'].get('tags', {}).get(tag_uuid) if tag and tag.get('title'): fe.category(term=tag.get('title')) def build_notification_context(watch, timestamp_from, timestamp_to, watch_label, n_body_template, rss_content_format): """Build the notification context object.""" return NotificationContextData(initial_data={ 'notification_urls': ['null://just-sending-a-null-test-for-the-render-in-RSS'], 'notification_body': n_body_template, 'timestamp_to': timestamp_to, 'timestamp_from': timestamp_from, 'watch_label': watch_label, 'notification_format': rss_content_format }) def render_notification(n_object, notification_service, watch, datastore, date_index_from=None, date_index_to=None): """Process and render the notification content.""" kwargs = {'n_object': n_object, 'watch': watch} if date_index_from is not None and date_index_to is not None: kwargs['date_index_from'] = date_index_from kwargs['date_index_to'] = date_index_to n_object = notification_service.queue_notification_for_watch(**kwargs) n_object['watch_mime_type'] = None res = process_notification(n_object=n_object, datastore=datastore) return res[0] def populate_feed_entry(fe, watch, content, guid, timestamp, link=None, title_suffix=None): """Populate a feed entry with content and metadata.""" watch_label = watch.get('url') # Already determined by caller # Set link if link: fe.link(link=link) # Set title if title_suffix: fe.title(title=f"{watch_label} - {title_suffix}") else: fe.title(title=watch_label) # Clean and set content if scan_invalid_chars_in_rss(content): content = clean_entry_content(content) fe.content(content=content, type='CDATA') # Set GUID fe.guid(guid, permalink=False) # Set pubDate using the timestamp of this specific change dt = datetime.datetime.fromtimestamp(int(timestamp)) dt = dt.replace(tzinfo=pytz.UTC) fe.pubDate(dt)
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/blueprint/rss/_util.py", "license": "Apache License 2.0", "lines": 118, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
dgtlmoon/changedetection.io:changedetectionio/blueprint/rss/main_feed.py
from flask import make_response, request, url_for, redirect def construct_main_feed_routes(rss_blueprint, datastore): """ Construct the main RSS feed routes. Args: rss_blueprint: The Flask blueprint to add routes to datastore: The ChangeDetectionStore instance """ # Some RSS reader situations ended up with rss/ (forward slash after RSS) due # to some earlier blueprint rerouting work, it should goto feed. @rss_blueprint.route("/", methods=['GET']) def extraslash(): return redirect(url_for('rss.feed')) # Import the login decorator if needed # from changedetectionio.auth_decorator import login_optionally_required @rss_blueprint.route("", methods=['GET']) def feed(): from feedgen.feed import FeedGenerator from loguru import logger import time from . import RSS_TEMPLATE_HTML_DEFAULT, RSS_TEMPLATE_PLAINTEXT_DEFAULT from ._util import (validate_rss_token, generate_watch_guid, get_rss_template, get_watch_label, build_notification_context, render_notification, populate_feed_entry, add_watch_categories) from ...notification_service import NotificationService now = time.time() # Validate token is_valid, error = validate_rss_token(datastore, request) if not is_valid: return error rss_content_format = datastore.data['settings']['application'].get('rss_content_format') limit_tag = request.args.get('tag', '').lower().strip() # Be sure limit_tag is a uuid for uuid, tag in datastore.data['settings']['application'].get('tags', {}).items(): if limit_tag == tag.get('title', '').lower().strip(): limit_tag = uuid # Sort by last_changed and add the uuid which is usually the key.. sorted_watches = [] # @todo needs a .itemsWithTag() or something - then we can use that in Jinaj2 and throw this away for uuid, watch in datastore.data['watching'].items(): # @todo tag notification_muted skip also (improve Watch model) if datastore.data['settings']['application'].get('rss_hide_muted_watches') and watch.get('notification_muted'): continue if limit_tag and not limit_tag in watch['tags']: continue sorted_watches.append(watch) sorted_watches.sort(key=lambda x: x.last_changed, reverse=False) fg = FeedGenerator() fg.title('changedetection.io') fg.description('Feed description') fg.link(href='https://changedetection.io') notification_service = NotificationService(datastore=datastore, notification_q=False) for watch in sorted_watches: dates = list(watch.history.keys()) # Re #521 - Don't bother processing this one if theres less than 2 snapshots, means we never had a change detected. if len(dates) < 2: continue if not watch.viewed: # Re #239 - GUID needs to be individual for each event # @todo In the future make this a configurable link back (see work on BASE_URL https://github.com/dgtlmoon/changedetection.io/pull/228) watch_label = get_watch_label(datastore, watch) timestamp_to = dates[-1] timestamp_from = dates[-2] guid = generate_watch_guid(watch, timestamp_to) # Because we are called via whatever web server, flask should figure out the right path diff_link = {'href': url_for('ui.ui_diff.diff_history_page', uuid=watch['uuid'], _external=True)} # Get template and build notification context n_body_template = get_rss_template(datastore, watch, rss_content_format, RSS_TEMPLATE_HTML_DEFAULT, RSS_TEMPLATE_PLAINTEXT_DEFAULT) n_object = build_notification_context(watch, timestamp_from, timestamp_to, watch_label, n_body_template, rss_content_format) # Render notification res = render_notification(n_object, notification_service, watch, datastore) # Create and populate feed entry fe = fg.add_entry() populate_feed_entry(fe, watch, res['body'], guid, timestamp_to, link=diff_link) fe.title(title=watch_label) # Override title to not include suffix add_watch_categories(fe, watch, datastore) response = make_response(fg.rss_str()) response.headers.set('Content-Type', 'application/rss+xml;charset=utf-8') logger.trace(f"RSS generated in {time.time() - now:.3f}s") return response
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/blueprint/rss/main_feed.py", "license": "Apache License 2.0", "lines": 82, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
dgtlmoon/changedetection.io:changedetectionio/blueprint/rss/single_watch.py
def construct_single_watch_routes(rss_blueprint, datastore): """ Construct RSS feed routes for single watches. Args: rss_blueprint: The Flask blueprint to add routes to datastore: The ChangeDetectionStore instance """ @rss_blueprint.route("/watch/<uuid_str:uuid>", methods=['GET']) def rss_single_watch(uuid): import time from flask import make_response, request, Response from flask_babel import lazy_gettext as _l from feedgen.feed import FeedGenerator from loguru import logger from . import RSS_TEMPLATE_HTML_DEFAULT, RSS_TEMPLATE_PLAINTEXT_DEFAULT from ._util import (validate_rss_token, get_rss_template, get_watch_label, build_notification_context, render_notification, populate_feed_entry, add_watch_categories) from ...notification_service import NotificationService """ Display the most recent changes for a single watch as RSS feed. Returns RSS XML with multiple entries showing diffs between consecutive snapshots. The number of entries is controlled by the rss_diff_length setting. """ now = time.time() # Validate token is_valid, error = validate_rss_token(datastore, request) if not is_valid: return error rss_content_format = datastore.data['settings']['application'].get('rss_content_format') if uuid == 'first': uuid = list(datastore.data['watching'].keys()).pop() # Get the watch by UUID watch = datastore.data['watching'].get(uuid) if not watch: return Response(_l("Watch with UUID %(uuid)s not found", uuid=uuid), status=404, mimetype='text/plain') # Check if watch has at least 2 history snapshots dates = list(watch.history.keys()) if len(dates) < 2: return Response(_l("Watch %(uuid)s does not have enough history snapshots to show changes (need at least 2)", uuid=uuid), status=400, mimetype='text/plain') # Get the number of diffs to include (default: 5) rss_diff_length = datastore.data['settings']['application'].get('rss_diff_length', 5) # Calculate how many diffs we can actually show (limited by available history) # We need at least 2 snapshots to create 1 diff max_possible_diffs = len(dates) - 1 num_diffs = min(rss_diff_length, max_possible_diffs) if rss_diff_length > 0 else max_possible_diffs # Create RSS feed fg = FeedGenerator() # Set title: use "label (url)" if label differs from url, otherwise just url watch_url = watch.get('url', '') watch_label = get_watch_label(datastore, watch) if watch_label != watch_url: feed_title = f'changedetection.io - {watch_label} ({watch_url})' else: feed_title = f'changedetection.io - {watch_url}' fg.title(feed_title) fg.description('Changes') fg.link(href='https://changedetection.io') # Loop through history and create RSS entries for each diff # Add entries in reverse order because feedgen reverses them # This way, the newest change appears first in the final RSS notification_service = NotificationService(datastore=datastore, notification_q=False) for i in range(num_diffs - 1, -1, -1): # Calculate indices for this diff (working backwards from newest) # i=0: compare dates[-2] to dates[-1] (most recent change) # i=1: compare dates[-3] to dates[-2] (previous change) # etc. date_index_to = -(i + 1) date_index_from = -(i + 2) timestamp_to = dates[date_index_to] timestamp_from = dates[date_index_from] # Get template and build notification context n_body_template = get_rss_template(datastore, watch, rss_content_format, RSS_TEMPLATE_HTML_DEFAULT, RSS_TEMPLATE_PLAINTEXT_DEFAULT) n_object = build_notification_context(watch, timestamp_from, timestamp_to, watch_label, n_body_template, rss_content_format) # Render notification with date indices res = render_notification(n_object, notification_service, watch, datastore, date_index_from, date_index_to) # Create and populate feed entry guid = f"{uuid}/{timestamp_to}" fe = fg.add_entry() title_suffix = f"Change @ {res['original_context']['change_datetime']}" populate_feed_entry(fe, watch, res.get('body', ''), guid, timestamp_to, link={'href': watch.get('url')}, title_suffix=title_suffix) add_watch_categories(fe, watch, datastore) response = make_response(fg.rss_str()) response.headers.set('Content-Type', 'application/rss+xml;charset=utf-8') logger.debug(f"RSS Single watch built in {time.time()-now:.2f}s") return response
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/blueprint/rss/single_watch.py", "license": "Apache License 2.0", "lines": 90, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
dgtlmoon/changedetection.io:changedetectionio/blueprint/rss/tag.py
def construct_tag_routes(rss_blueprint, datastore): """ Construct RSS feed routes for tags. Args: rss_blueprint: The Flask blueprint to add routes to datastore: The ChangeDetectionStore instance """ @rss_blueprint.route("/tag/<string:tag_uuid>", methods=['GET']) def rss_tag_feed(tag_uuid): from flask import make_response, request, url_for from feedgen.feed import FeedGenerator from . import RSS_TEMPLATE_HTML_DEFAULT, RSS_TEMPLATE_PLAINTEXT_DEFAULT from ._util import (validate_rss_token, generate_watch_guid, get_rss_template, get_watch_label, build_notification_context, render_notification, populate_feed_entry, add_watch_categories) from ...notification_service import NotificationService """ Display an RSS feed for all unviewed watches that belong to a specific tag. Returns RSS XML with entries for each unviewed watch with sufficient history. """ # Validate token is_valid, error = validate_rss_token(datastore, request) if not is_valid: return error rss_content_format = datastore.data['settings']['application'].get('rss_content_format') # Verify tag exists tag = datastore.data['settings']['application'].get('tags', {}).get(tag_uuid) if not tag: return f"Tag with UUID {tag_uuid} not found", 404 tag_title = tag.get('title', 'Unknown Tag') # Create RSS feed fg = FeedGenerator() fg.title(f'changedetection.io - {tag_title}') fg.description(f'Changes for watches tagged with {tag_title}') fg.link(href='https://changedetection.io') notification_service = NotificationService(datastore=datastore, notification_q=False) # Find all watches with this tag for uuid, watch in datastore.data['watching'].items(): #@todo This is wrong, it needs to sort by most recently changed and then limit it datastore.data['watching'].items().sorted(?) # So get all watches in this tag then sort # Skip if watch doesn't have this tag if tag_uuid not in watch.get('tags', []): continue # Skip muted watches if configured if datastore.data['settings']['application'].get('rss_hide_muted_watches') and watch.get('notification_muted'): continue # Check if watch has at least 2 history snapshots dates = list(watch.history.keys()) if len(dates) < 2: continue # Only include unviewed watches if not watch.viewed: # Include a link to the diff page (use uuid from loop, don't modify watch dict) diff_link = {'href': url_for('ui.ui_diff.diff_history_page', uuid=uuid, _external=True)} # Get watch label watch_label = get_watch_label(datastore, watch) # Get template and build notification context timestamp_to = dates[-1] timestamp_from = dates[-2] # Generate GUID for this entry guid = generate_watch_guid(watch, timestamp_to) n_body_template = get_rss_template(datastore, watch, rss_content_format, RSS_TEMPLATE_HTML_DEFAULT, RSS_TEMPLATE_PLAINTEXT_DEFAULT) n_object = build_notification_context(watch, timestamp_from, timestamp_to, watch_label, n_body_template, rss_content_format) # Render notification res = render_notification(n_object, notification_service, watch, datastore) # Create and populate feed entry fe = fg.add_entry() title_suffix = f"Change @ {res['original_context']['change_datetime']}" populate_feed_entry(fe, watch, res['body'], guid, timestamp_to, link=diff_link, title_suffix=title_suffix) add_watch_categories(fe, watch, datastore) response = make_response(fg.rss_str()) response.headers.set('Content-Type', 'application/rss+xml;charset=utf-8') return response
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/blueprint/rss/tag.py", "license": "Apache License 2.0", "lines": 75, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
dgtlmoon/changedetection.io:changedetectionio/tests/test_rss_group.py
#!/usr/bin/env python3 import time from flask import url_for from .util import live_server_setup, wait_for_all_checks, wait_for_watch_history, extract_rss_token_from_UI, get_UUID_for_tag_name, delete_all_watches import os def set_original_response(datastore_path): test_return_data = """<html> <body> Some initial text<br> <p>Watch 1 content</p> <p>Watch 2 content</p> </body> </html> """ with open(os.path.join(datastore_path, "endpoint-content.txt"), "w") as f: f.write(test_return_data) return None def set_modified_response(datastore_path): test_return_data = """<html> <body> Some initial text<br> <p>Watch 1 content MODIFIED</p> <p>Watch 2 content CHANGED</p> </body> </html> """ with open(os.path.join(datastore_path, "endpoint-content.txt"), "w") as f: f.write(test_return_data) return None def test_rss_group(client, live_server, measure_memory_usage, datastore_path): """ Test that RSS feed for a specific tag/group shows only watches in that group and displays changes correctly. """ set_original_response(datastore_path=datastore_path) # Create a tag/group res = client.post( url_for("tags.form_tag_add"), data={"name": "test-rss-group"}, follow_redirects=True ) assert b"Tag added" in res.data assert b"test-rss-group" in res.data # Get the tag UUID tag_uuid = get_UUID_for_tag_name(client, name="test-rss-group") assert tag_uuid is not None # Add first watch with the tag test_url_1 = url_for('test_endpoint', _external=True) + "?watch=1" res = client.post( url_for("ui.ui_views.form_quick_watch_add"), data={"url": test_url_1, "tags": 'test-rss-group'}, follow_redirects=True ) assert b"Watch added" in res.data # Add second watch with the tag test_url_2 = url_for('test_endpoint', _external=True) + "?watch=2" res = client.post( url_for("ui.ui_views.form_quick_watch_add"), data={"url": test_url_2, "tags": 'test-rss-group'}, follow_redirects=True ) assert b"Watch added" in res.data # Add a third watch WITHOUT the tag (should not appear in RSS) test_url_3 = url_for('test_endpoint', _external=True) + "?watch=3" res = client.post( url_for("ui.ui_views.form_quick_watch_add"), data={"url": test_url_3, "tags": 'other-tag'}, follow_redirects=True ) assert b"Watch added" in res.data # Wait for initial checks to complete wait_for_all_checks(client) # Ensure initial snapshots are saved assert wait_for_watch_history(client, min_history_count=1, timeout=10), "Watches did not save initial snapshots" # Trigger a change set_modified_response(datastore_path=datastore_path) # Recheck all watches res = client.get(url_for("ui.form_watch_checknow"), follow_redirects=True) wait_for_all_checks(client) # Ensure all watches have sufficient history for RSS generation assert wait_for_watch_history(client, min_history_count=2, timeout=10), "Watches did not accumulate sufficient history" # Get RSS token rss_token = extract_rss_token_from_UI(client) assert rss_token is not None # Request RSS feed for the specific tag/group using the new endpoint res = client.get( url_for("rss.rss_tag_feed", tag_uuid=tag_uuid, token=rss_token, _external=True), follow_redirects=True ) # Verify response is successful assert res.status_code == 200 assert b"<?xml" in res.data or b"<rss" in res.data # Verify the RSS feed contains the tag name in the title assert b"test-rss-group" in res.data # Verify watch 1 and watch 2 are in the RSS feed (they have the tag) assert b"watch=1" in res.data assert b"watch=2" in res.data # Verify watch 3 is NOT in the RSS feed (it doesn't have the tag) assert b"watch=3" not in res.data # Verify the changes are shown in the RSS feed assert b"MODIFIED" in res.data or b"CHANGED" in res.data # Verify it's actual RSS/XML format assert b"<rss" in res.data or b"<feed" in res.data # Test with invalid tag UUID - should return 404 res = client.get( url_for("rss.rss_tag_feed", tag_uuid="invalid-uuid-12345", token=rss_token, _external=True), follow_redirects=True ) assert res.status_code == 404 assert b"not found" in res.data # Test with invalid token - should return 403 res = client.get( url_for("rss.rss_tag_feed", tag_uuid=tag_uuid, token="wrong-token", _external=True), follow_redirects=True ) assert res.status_code == 403 assert b"Access denied" in res.data # Clean up delete_all_watches(client) res = client.get(url_for("tags.delete_all"), follow_redirects=True) assert b'All tags deleted' in res.data def test_rss_group_empty_tag(client, live_server, measure_memory_usage, datastore_path): """ Test that RSS feed for a tag with no watches returns valid but empty RSS. """ # Create a tag with no watches res = client.post( url_for("tags.form_tag_add"), data={"name": "empty-tag"}, follow_redirects=True ) assert b"Tag added" in res.data tag_uuid = get_UUID_for_tag_name(client, name="empty-tag") assert tag_uuid is not None # Get RSS token rss_token = extract_rss_token_from_UI(client) # Request RSS feed for empty tag res = client.get( url_for("rss.rss_tag_feed", tag_uuid=tag_uuid, token=rss_token, _external=True), follow_redirects=True ) # Should still return 200 with valid RSS assert res.status_code == 200 assert b"<?xml" in res.data or b"<rss" in res.data assert b"empty-tag" in res.data # Clean up res = client.get(url_for("tags.delete_all"), follow_redirects=True) assert b'All tags deleted' in res.data def test_rss_group_only_unviewed(client, live_server, measure_memory_usage, datastore_path): """ Test that RSS feed for a tag only shows unviewed watches. """ set_original_response(datastore_path=datastore_path) # Create a tag res = client.post( url_for("tags.form_tag_add"), data={"name": "unviewed-test"}, follow_redirects=True ) assert b"Tag added" in res.data tag_uuid = get_UUID_for_tag_name(client, name="unviewed-test") # Add two watches with the tag test_url_1 = url_for('test_endpoint', _external=True) + "?unviewed=1" res = client.post( url_for("ui.ui_views.form_quick_watch_add"), data={"url": test_url_1, "tags": 'unviewed-test'}, follow_redirects=True ) assert b"Watch added" in res.data test_url_2 = url_for('test_endpoint', _external=True) + "?unviewed=2" res = client.post( url_for("ui.ui_views.form_quick_watch_add"), data={"url": test_url_2, "tags": 'unviewed-test'}, follow_redirects=True ) assert b"Watch added" in res.data wait_for_all_checks(client) assert wait_for_watch_history(client, min_history_count=1, timeout=10), "Initial snapshots not saved" # Trigger changes set_modified_response(datastore_path=datastore_path) res = client.get(url_for("ui.form_watch_checknow"), follow_redirects=True) wait_for_all_checks(client) assert wait_for_watch_history(client, min_history_count=2, timeout=10), "History not accumulated" # Get RSS token rss_token = extract_rss_token_from_UI(client) # Request RSS feed - should show both watches (both unviewed) res = client.get( url_for("rss.rss_tag_feed", tag_uuid=tag_uuid, token=rss_token, _external=True), follow_redirects=True ) assert res.status_code == 200 assert b"unviewed=1" in res.data assert b"unviewed=2" in res.data # Mark all as viewed res = client.get(url_for('ui.mark_all_viewed'), follow_redirects=True) wait_for_all_checks(client) # Request RSS feed again - should be empty now (no unviewed watches) res = client.get( url_for("rss.rss_tag_feed", tag_uuid=tag_uuid, token=rss_token, _external=True), follow_redirects=True ) assert res.status_code == 200 # Should not contain the watch URLs anymore since they're viewed assert b"unviewed=1" not in res.data assert b"unviewed=2" not in res.data # Clean up delete_all_watches(client) res = client.get(url_for("tags.delete_all"), follow_redirects=True) assert b'All tags deleted' in res.data
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/tests/test_rss_group.py", "license": "Apache License 2.0", "lines": 209, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
dgtlmoon/changedetection.io:changedetectionio/tests/test_datastore_isolation.py
#!/usr/bin/env python3 """Test to verify client and live_server share the same datastore""" def test_client_and_live_server_share_datastore(client, live_server): """Verify that client and live_server use the same app and datastore.""" # They should be the SAME object assert client.application is live_server.app, "client.application and live_server.app should be the SAME object!" # They should share the same datastore client_datastore = client.application.config.get('DATASTORE') server_datastore = live_server.app.config.get('DATASTORE') assert client_datastore is server_datastore, \ f"Datastores are DIFFERENT objects! client={hex(id(client_datastore))} server={hex(id(server_datastore))}" print(f"✓ client.application and live_server.app are the SAME object") print(f"✓ Both use the same DATASTORE at {hex(id(client_datastore))}") print(f"✓ Datastore path: {client_datastore.datastore_path}")
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/tests/test_datastore_isolation.py", "license": "Apache License 2.0", "lines": 14, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
dgtlmoon/changedetection.io:changedetectionio/validate_url.py
import ipaddress import socket from functools import lru_cache from loguru import logger from urllib.parse import urlparse, urlunparse, parse_qsl, urlencode def normalize_url_encoding(url): """ Safely encode a URL's query parameters, regardless of whether they're already encoded. Why this is necessary: URLs can arrive in various states - some with already encoded query parameters (%20 for spaces), some with unencoded parameters (literal spaces), or a mix of both. The validators.url() function requires proper encoding, but simply encoding an already-encoded URL would double-encode it (e.g., %20 would become %2520). This function solves the problem by: 1. Parsing the URL to extract query parameters 2. parse_qsl() automatically decodes parameters if they're encoded 3. urlencode() re-encodes them properly 4. Returns a consistently encoded URL that will pass validation Example: - Input: "http://example.com/test?time=2025-10-28 09:19" (space not encoded) - Output: "http://example.com/test?time=2025-10-28+09%3A19" (properly encoded) - Input: "http://example.com/test?time=2025-10-28%2009:19" (already encoded) - Output: "http://example.com/test?time=2025-10-28+09%3A19" (properly encoded) Returns a properly encoded URL string. """ try: # Parse the URL into components (scheme, netloc, path, params, query, fragment) parsed = urlparse(url) # Parse query string - this automatically decodes it if encoded # parse_qsl handles both encoded and unencoded query strings gracefully query_params = parse_qsl(parsed.query, keep_blank_values=True) # Re-encode the query string properly using standard URL encoding encoded_query = urlencode(query_params, safe='') # Reconstruct the URL with properly encoded query string normalized = urlunparse(( parsed.scheme, parsed.netloc, parsed.path, parsed.params, encoded_query, # Use the re-encoded query parsed.fragment )) return normalized except Exception as e: # If parsing fails for any reason, return original URL logger.debug(f"URL normalization failed for '{url}': {e}") return url def is_private_hostname(hostname): """Return True if hostname resolves to an IANA-restricted (private/reserved) IP address. Unresolvable hostnames return False (allow them) — DNS may be temporarily unavailable or the domain not yet live. The actual DNS rebinding attack is mitigated by fetch-time re-validation in requests.py, not by blocking unresolvable domains at add-time. Never cached — callers that need fresh DNS resolution (e.g. at fetch time) can call this directly without going through the lru_cached is_safe_valid_url(). """ try: for info in socket.getaddrinfo(hostname, None): ip = ipaddress.ip_address(info[4][0]) if ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_reserved: logger.warning(f"Hostname '{hostname} - {ip} - ip.is_private = {ip.is_private}, ip.is_loopback = {ip.is_loopback}, ip.is_link_local = {ip.is_link_local}, ip.is_reserved = {ip.is_reserved}") return True except socket.gaierror as e: logger.warning(f"{hostname} error checking {str(e)}") return False logger.info(f"Hostname '{hostname}' is NOT private/IANA restricted.") return False def is_safe_valid_url(test_url): from changedetectionio import strtobool from changedetectionio.jinja2_custom import render as jinja_render import os import re import validators # Validate input type first - must be a non-empty string if test_url is None: logger.warning('URL validation failed: URL is None') return False if not isinstance(test_url, str): logger.warning(f'URL validation failed: URL must be a string, got {type(test_url).__name__}') return False if not test_url.strip(): logger.warning('URL validation failed: URL is empty or whitespace only') return False allow_file_access = strtobool(os.getenv('ALLOW_FILE_URI', 'false')) safe_protocol_regex = '^(http|https|ftp|file):' if allow_file_access else '^(http|https|ftp):' # See https://github.com/dgtlmoon/changedetection.io/issues/1358 # Remove 'source:' prefix so we dont get 'source:javascript:' etc # 'source:' is a valid way to tell us to return the source r = re.compile('^source:', re.IGNORECASE) test_url = r.sub('', test_url) # Check the actual rendered URL in case of any Jinja markup try: test_url = jinja_render(test_url) except Exception as e: logger.error(f'URL "{test_url}" is not correct Jinja2? {str(e)}') return False # Check query parameters and fragment if re.search(r'[<>]', test_url): logger.warning(f'URL "{test_url}" contains suspicious characters') return False # Normalize URL encoding - handle both encoded and unencoded query parameters test_url = normalize_url_encoding(test_url) # Be sure the protocol is safe (no file, etcetc) pattern = re.compile(os.getenv('SAFE_PROTOCOL_REGEX', safe_protocol_regex), re.IGNORECASE) if not pattern.match(test_url.strip()): logger.warning(f'URL "{test_url}" is not safe, aborting.') return False # If hosts that only contain alphanumerics are allowed ("localhost" for example) allow_simplehost = not strtobool(os.getenv('BLOCK_SIMPLEHOSTS', 'False')) try: if not test_url.strip().lower().startswith('file:') and not validators.url(test_url, simple_host=allow_simplehost): logger.warning(f'URL "{test_url}" failed validation, aborting.') return False except validators.ValidationError: logger.warning(f'URL f"{test_url}" failed validation, aborting.') return False return True
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/validate_url.py", "license": "Apache License 2.0", "lines": 116, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
dgtlmoon/changedetection.io:changedetectionio/notification/email_helpers.py
def as_monospaced_html_email(content: str, title: str) -> str: """ Wraps `content` in a minimal, email-safe HTML template that forces monospace rendering across Gmail, Hotmail, Apple Mail, etc. Args: content: The body text (plain text or HTML-like). title: The title plaintext Returns: A complete HTML document string suitable for sending as an email body. """ # All line feed types should be removed and then this function should only be fed <br>'s # Then it works with our <pre> styling without double linefeeds content = content.translate(str.maketrans('', '', '\r\n')) if title: import html title = html.escape(title) else: title = '' # 2. Full email-safe HTML html_email = f"""<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="x-apple-disable-message-reformatting"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!--[if mso]> <style> body, div, pre, td {{ font-family: "Courier New", Courier, monospace !important; }} </style> <![endif]--> <title>{title}</title> </head> <body style="-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%;"> <pre role="article" aria-roledescription="email" lang="en" style="font-family: monospace, 'Courier New', Courier; font-size: 0.9rem; white-space: pre-wrap; word-break: break-word;">{content}</pre> </body> </html>""" return html_email
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/notification/email_helpers.py", "license": "Apache License 2.0", "lines": 39, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
dgtlmoon/changedetection.io:changedetectionio/jinja2_custom/plugins/regex.py
""" Regex filter plugin for Jinja2 templates. Provides regex_replace filter for pattern-based string replacements in templates. """ import re import signal from loguru import logger def regex_replace(value: str, pattern: str, replacement: str = '', count: int = 0) -> str: """ Replace occurrences of a regex pattern in a string. Security: Protected against ReDoS (Regular Expression Denial of Service) attacks: - Limits input value size to prevent excessive processing - Uses timeout mechanism to prevent runaway regex operations - Validates pattern complexity to prevent catastrophic backtracking Args: value: The input string to perform replacements on pattern: The regex pattern to search for replacement: The replacement string (default: '') count: Maximum number of replacements (0 = replace all, default: 0) Returns: String with replacements applied, or original value on error Example: {{ "hello world" | regex_replace("world", "universe") }} {{ diff | regex_replace("<td>([^<]+)</td><td>([^<]+)</td>", "Label1: \\1\\nLabel2: \\2") }} Security limits: - Maximum input size: 10MB - Maximum pattern length: 500 characters - Operation timeout: 10 seconds - Dangerous nested quantifier patterns are rejected """ # Security limits MAX_INPUT_SIZE = 1024 * 1024 * 10 # 10MB max input size MAX_PATTERN_LENGTH = 500 # Maximum regex pattern length REGEX_TIMEOUT_SECONDS = 10 # Maximum time for regex operation # Validate input sizes value_str = str(value) if len(value_str) > MAX_INPUT_SIZE: logger.warning(f"regex_replace: Input too large ({len(value_str)} bytes), truncating") value_str = value_str[:MAX_INPUT_SIZE] if len(pattern) > MAX_PATTERN_LENGTH: logger.warning(f"regex_replace: Pattern too long ({len(pattern)} chars), rejecting") return value_str # Check for potentially dangerous patterns (basic checks) # Nested quantifiers like (a+)+ can cause catastrophic backtracking dangerous_patterns = [ r'\([^)]*\+[^)]*\)\+', # (x+)+ r'\([^)]*\*[^)]*\)\+', # (x*)+ r'\([^)]*\+[^)]*\)\*', # (x+)* r'\([^)]*\*[^)]*\)\*', # (x*)* ] for dangerous in dangerous_patterns: if re.search(dangerous, pattern): logger.warning(f"regex_replace: Potentially dangerous pattern detected: {pattern}") return value_str def timeout_handler(signum, frame): raise TimeoutError("Regex operation timed out") try: # Set up timeout for regex operation (Unix-like systems only) # This prevents ReDoS attacks old_handler = None if hasattr(signal, 'SIGALRM'): old_handler = signal.signal(signal.SIGALRM, timeout_handler) signal.alarm(REGEX_TIMEOUT_SECONDS) try: result = re.sub(pattern, replacement, value_str, count=count) finally: # Cancel the alarm if hasattr(signal, 'SIGALRM'): signal.alarm(0) if old_handler is not None: signal.signal(signal.SIGALRM, old_handler) return result except TimeoutError: logger.error(f"regex_replace: Regex operation timed out - possible ReDoS attack. Pattern: {pattern}") return value_str except re.error as e: logger.warning(f"regex_replace: Invalid regex pattern: {e}") return value_str except Exception as e: logger.error(f"regex_replace: Unexpected error: {e}") return value_str
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/jinja2_custom/plugins/regex.py", "license": "Apache License 2.0", "lines": 81, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
dgtlmoon/changedetection.io:changedetectionio/tests/test_xpath_default_namespace.py
#!/usr/bin/env python3 """ Unit tests for XPath default namespace handling in RSS/Atom feeds. Tests the fix for issue where //title/text() returns empty on feeds with default namespaces. Real-world test data from https://github.com/microsoft/PowerToys/releases.atom """ import sys import os import pytest sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import html_tools # Real-world Atom feed with default namespace from GitHub PowerToys releases # This is the actual format that was failing before the fix atom_feed_with_default_ns = """<?xml version="1.0" encoding="UTF-8"?> <feed xmlns="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" xml:lang="en-US"> <id>tag:github.com,2008:https://github.com/microsoft/PowerToys/releases</id> <link type="text/html" rel="alternate" href="https://github.com/microsoft/PowerToys/releases"/> <link type="application/atom+xml" rel="self" href="https://github.com/microsoft/PowerToys/releases.atom"/> <title>Release notes from PowerToys</title> <updated>2025-10-23T08:53:12Z</updated> <entry> <id>tag:github.com,2008:Repository/184456251/v0.95.1</id> <updated>2025-10-24T14:20:14Z</updated> <link rel="alternate" type="text/html" href="https://github.com/microsoft/PowerToys/releases/tag/v0.95.1"/> <title>Release 0.95.1</title> <content type="html">&lt;p&gt;This patch release fixes several important stability issues.&lt;/p&gt;</content> <author> <name>Jaylyn-Barbee</name> </author> </entry> <entry> <id>tag:github.com,2008:Repository/184456251/v0.95.0</id> <updated>2025-10-17T12:51:21Z</updated> <link rel="alternate" type="text/html" href="https://github.com/microsoft/PowerToys/releases/tag/v0.95.0"/> <title>Release v0.95.0</title> <content type="html">&lt;p&gt;New features, stability, optimization improvements.&lt;/p&gt;</content> <author> <name>Jaylyn-Barbee</name> </author> </entry> </feed>""" # RSS feed without default namespace rss_feed_no_default_ns = """<?xml version="1.0" encoding="UTF-8"?> <rss version="2.0"> <channel> <title>Channel Title</title> <description>Channel Description</description> <item> <title>Item 1 Title</title> <description>Item 1 Description</description> </item> <item> <title>Item 2 Title</title> <description>Item 2 Description</description> </item> </channel> </rss>""" # RSS 2.0 feed with namespace prefix (not default) rss_feed_with_ns_prefix = """<?xml version="1.0" encoding="UTF-8"?> <rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"> <channel> <title>Channel Title</title> <atom:link href="http://example.com/feed" rel="self" type="application/rss+xml"/> <item> <title>Item Title</title> <dc:creator>Author Name</dc:creator> </item> </channel> </rss>""" class TestXPathDefaultNamespace: """Test XPath queries on feeds with and without default namespaces.""" def test_atom_feed_simple_xpath_with_xpath_filter(self): """Test that //title/text() works on Atom feed with default namespace using xpath_filter.""" result = html_tools.xpath_filter('//title/text()', atom_feed_with_default_ns, is_xml=True) assert 'Release notes from PowerToys' in result assert 'Release 0.95.1' in result assert 'Release v0.95.0' in result def test_atom_feed_nested_xpath_with_xpath_filter(self): """Test nested XPath like //entry/title/text() on Atom feed.""" result = html_tools.xpath_filter('//entry/title/text()', atom_feed_with_default_ns, is_xml=True) assert 'Release 0.95.1' in result assert 'Release v0.95.0' in result # Should NOT include the feed title assert 'Release notes from PowerToys' not in result def test_atom_feed_other_elements_with_xpath_filter(self): """Test that other elements like //updated/text() work on Atom feed.""" result = html_tools.xpath_filter('//updated/text()', atom_feed_with_default_ns, is_xml=True) assert '2025-10-23T08:53:12Z' in result assert '2025-10-24T14:20:14Z' in result def test_rss_feed_without_namespace(self): """Test that //title/text() works on RSS feed without default namespace.""" result = html_tools.xpath_filter('//title/text()', rss_feed_no_default_ns, is_xml=True) assert 'Channel Title' in result assert 'Item 1 Title' in result assert 'Item 2 Title' in result def test_rss_feed_nested_xpath(self): """Test nested XPath on RSS feed without default namespace.""" result = html_tools.xpath_filter('//item/title/text()', rss_feed_no_default_ns, is_xml=True) assert 'Item 1 Title' in result assert 'Item 2 Title' in result # Should NOT include channel title assert 'Channel Title' not in result def test_rss_feed_with_prefixed_namespaces(self): """Test that feeds with namespace prefixes (not default) still work.""" result = html_tools.xpath_filter('//title/text()', rss_feed_with_ns_prefix, is_xml=True) assert 'Channel Title' in result assert 'Item Title' in result def test_local_name_workaround_still_works(self): """Test that local-name() workaround still works for Atom feeds.""" result = html_tools.xpath_filter('//*[local-name()="title"]/text()', atom_feed_with_default_ns, is_xml=True) assert 'Release notes from PowerToys' in result assert 'Release 0.95.1' in result def test_xpath1_filter_without_default_namespace(self): """Test xpath1_filter works on RSS without default namespace.""" result = html_tools.xpath1_filter('//title/text()', rss_feed_no_default_ns, is_xml=True) assert 'Channel Title' in result assert 'Item 1 Title' in result def test_xpath1_filter_with_default_namespace_returns_empty(self): """Test that xpath1_filter returns empty on Atom with default namespace (known limitation).""" result = html_tools.xpath1_filter('//title/text()', atom_feed_with_default_ns, is_xml=True) # xpath1_filter (lxml) doesn't support default namespaces, so this returns empty assert result == '' def test_xpath1_filter_local_name_workaround(self): """Test that xpath1_filter works with local-name() workaround on Atom feeds.""" result = html_tools.xpath1_filter('//*[local-name()="title"]/text()', atom_feed_with_default_ns, is_xml=True) assert 'Release notes from PowerToys' in result assert 'Release 0.95.1' in result if __name__ == '__main__': pytest.main([__file__, '-v'])
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/tests/test_xpath_default_namespace.py", "license": "Apache License 2.0", "lines": 132, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
dgtlmoon/changedetection.io:changedetectionio/notification/apprise_plugin/discord.py
""" Custom Discord plugin for changedetection.io Extends Apprise's Discord plugin to support custom colored embeds for removed/added content """ from apprise.plugins.discord import NotifyDiscord from apprise.decorators import notify from apprise.common import NotifyFormat from loguru import logger # Import placeholders from changedetection's diff module from ...diff import ( REMOVED_PLACEMARKER_OPEN, REMOVED_PLACEMARKER_CLOSED, ADDED_PLACEMARKER_OPEN, ADDED_PLACEMARKER_CLOSED, CHANGED_PLACEMARKER_OPEN, CHANGED_PLACEMARKER_CLOSED, CHANGED_INTO_PLACEMARKER_OPEN, CHANGED_INTO_PLACEMARKER_CLOSED, ) # Discord embed sidebar colors for different change types DISCORD_COLOR_UNCHANGED = 8421504 # Gray (#808080) DISCORD_COLOR_REMOVED = 16711680 # Red (#FF0000) DISCORD_COLOR_ADDED = 65280 # Green (#00FF00) DISCORD_COLOR_CHANGED = 16753920 # Orange (#FFA500) DISCORD_COLOR_CHANGED_INTO = 3447003 # Blue (#5865F2 - Discord blue) DISCORD_COLOR_WARNING = 16776960 # Yellow (#FFFF00) class NotifyDiscordCustom(NotifyDiscord): """ Custom Discord notification handler that supports multiple colored embeds for showing removed (red) and added (green) content separately. """ def send(self, body, title="", notify_type=None, attach=None, **kwargs): """ Override send method to create custom embeds with red/green colors for removed/added content when placeholders are present. """ # Check if body contains our diff placeholders has_removed = REMOVED_PLACEMARKER_OPEN in body has_added = ADDED_PLACEMARKER_OPEN in body has_changed = CHANGED_PLACEMARKER_OPEN in body has_changed_into = CHANGED_INTO_PLACEMARKER_OPEN in body # If we have diff placeholders and we're in markdown/html format, create custom embeds if (has_removed or has_added or has_changed or has_changed_into) and self.notify_format in (NotifyFormat.MARKDOWN, NotifyFormat.HTML): return self._send_with_colored_embeds(body, title, notify_type, attach, **kwargs) # Otherwise, use the parent class's default behavior return super().send(body, title, notify_type, attach, **kwargs) def _send_with_colored_embeds(self, body, title, notify_type, attach, **kwargs): """ Send Discord message with embeds in the original diff order. Preserves the sequence: unchanged -> removed -> added -> unchanged, etc. """ from datetime import datetime, timezone payload = { "tts": self.tts, "wait": self.tts is False, } if self.flags: payload["flags"] = self.flags # Acquire image_url image_url = self.image_url(notify_type) if self.avatar and (image_url or self.avatar_url): payload["avatar_url"] = self.avatar_url if self.avatar_url else image_url if self.user: payload["username"] = self.user # Associate our thread_id with our message params = {"thread_id": self.thread_id} if self.thread_id else None # Build embeds array preserving order embeds = [] # Add title as plain bold text in message content (not an embed) if title: payload["content"] = f"**{title}**" # Parse the body into ordered chunks chunks = self._parse_body_into_chunks(body) # Discord limits: # - Max 10 embeds per message # - Max 6000 characters total across all embeds # - Max 4096 characters per embed description max_embeds = 10 max_total_chars = 6000 max_embed_description = 4096 # All 10 embed slots are available for content max_content_embeds = max_embeds # Start character count total_chars = 0 # Create embeds from chunks in order (no titles, just color coding) for chunk_type, content in chunks: if not content.strip(): continue # Truncate individual embed description if needed if len(content) > max_embed_description: content = content[:max_embed_description - 3] + "..." # Check if we're approaching the embed count limit # We need room for the warning embed, so stop at max_content_embeds - 1 current_content_embeds = len(embeds) if current_content_embeds >= max_content_embeds - 1: # Add a truncation notice (this will be the 10th embed) embeds.append({ "description": "⚠️ Content truncated (Discord 10 embed limit reached) - Tip: Select 'Plain Text' or 'HTML' format for longer diffs", "color": DISCORD_COLOR_WARNING, }) break # Check if adding this embed would exceed total character limit if total_chars + len(content) > max_total_chars: # Add a truncation notice remaining_chars = max_total_chars - total_chars if remaining_chars > 100: # Add partial content if we have room truncated_content = content[:remaining_chars - 100] + "..." embeds.append({ "description": truncated_content, "color": (DISCORD_COLOR_UNCHANGED if chunk_type == "unchanged" else DISCORD_COLOR_REMOVED if chunk_type == "removed" else DISCORD_COLOR_ADDED), }) embeds.append({ "description": "⚠️ Content truncated (Discord 6000 char limit reached)\nTip: Select 'Plain Text' or 'HTML' format for longer diffs", "color": DISCORD_COLOR_WARNING, }) break if chunk_type == "unchanged": embeds.append({ "description": content, "color": DISCORD_COLOR_UNCHANGED, }) elif chunk_type == "removed": embeds.append({ "description": content, "color": DISCORD_COLOR_REMOVED, }) elif chunk_type == "added": embeds.append({ "description": content, "color": DISCORD_COLOR_ADDED, }) elif chunk_type == "changed": # Changed (old value) - use orange to distinguish from pure removal embeds.append({ "description": content, "color": DISCORD_COLOR_CHANGED, }) elif chunk_type == "changed_into": # Changed into (new value) - use blue to distinguish from pure addition embeds.append({ "description": content, "color": DISCORD_COLOR_CHANGED_INTO, }) total_chars += len(content) if embeds: payload["embeds"] = embeds # Send the payload using parent's _send method if not self._send(payload, params=params): return False # Handle attachments if present if attach and self.attachment_support: payload.update({ "tts": False, "wait": True, }) payload.pop("embeds", None) payload.pop("content", None) payload.pop("allow_mentions", None) for attachment in attach: self.logger.info(f"Posting Discord Attachment {attachment.name}") if not self._send(payload, params=params, attach=attachment): return False return True def _parse_body_into_chunks(self, body): """ Parse the body into ordered chunks of (type, content) tuples. Types: "unchanged", "removed", "added", "changed", "changed_into" Preserves the original order of the diff. """ chunks = [] position = 0 while position < len(body): # Find the next marker next_removed = body.find(REMOVED_PLACEMARKER_OPEN, position) next_added = body.find(ADDED_PLACEMARKER_OPEN, position) next_changed = body.find(CHANGED_PLACEMARKER_OPEN, position) next_changed_into = body.find(CHANGED_INTO_PLACEMARKER_OPEN, position) # Determine which marker comes first if next_removed == -1 and next_added == -1 and next_changed == -1 and next_changed_into == -1: # No more markers, rest is unchanged if position < len(body): chunks.append(("unchanged", body[position:])) break # Find the earliest marker next_marker_pos = None next_marker_type = None # Compare all marker positions to find the earliest markers = [] if next_removed != -1: markers.append((next_removed, "removed")) if next_added != -1: markers.append((next_added, "added")) if next_changed != -1: markers.append((next_changed, "changed")) if next_changed_into != -1: markers.append((next_changed_into, "changed_into")) if markers: next_marker_pos, next_marker_type = min(markers, key=lambda x: x[0]) # Add unchanged content before the marker if next_marker_pos > position: chunks.append(("unchanged", body[position:next_marker_pos])) # Find the closing marker if next_marker_type == "removed": open_marker = REMOVED_PLACEMARKER_OPEN close_marker = REMOVED_PLACEMARKER_CLOSED elif next_marker_type == "added": open_marker = ADDED_PLACEMARKER_OPEN close_marker = ADDED_PLACEMARKER_CLOSED elif next_marker_type == "changed": open_marker = CHANGED_PLACEMARKER_OPEN close_marker = CHANGED_PLACEMARKER_CLOSED else: # changed_into open_marker = CHANGED_INTO_PLACEMARKER_OPEN close_marker = CHANGED_INTO_PLACEMARKER_CLOSED close_pos = body.find(close_marker, next_marker_pos) if close_pos == -1: # No closing marker, take rest as this type content = body[next_marker_pos + len(open_marker):] chunks.append((next_marker_type, content)) break else: # Extract content between markers content = body[next_marker_pos + len(open_marker):close_pos] chunks.append((next_marker_type, content)) position = close_pos + len(close_marker) return chunks # Register the custom Discord handler with Apprise # This will override the built-in discord:// handler @notify(on="discord") def discord_custom_wrapper(body, title, notify_type, meta, body_format=None, *args, **kwargs): """ Wrapper function to make the custom Discord handler work with Apprise's decorator system. Note: This decorator approach may not work for overriding built-in plugins. The class-based approach above is the proper way to extend NotifyDiscord. """ logger.info("Custom Discord handler called") # This is here for potential future use with decorator-based registration return True
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/notification/apprise_plugin/discord.py", "license": "Apache License 2.0", "lines": 241, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
dgtlmoon/changedetection.io:changedetectionio/jinja2_custom/extensions/TimeExtension.py
""" Jinja2 TimeExtension - Custom date/time handling for templates. This extension provides the {% now %} tag for Jinja2 templates, offering timezone-aware date/time formatting with support for time offsets. Why This Extension Exists: The Arrow library has a now() function (arrow.now()), but Jinja2 templates cannot directly call Python functions - they need extensions or filters to expose functionality. This TimeExtension serves as a Jinja2-to-Arrow bridge that: 1. Makes Arrow accessible in templates - Jinja2 requires registering functions/tags through extensions. You cannot use arrow.now() directly in a template. 2. Provides template-friendly syntax - Instead of complex Python code, you get clean tags: {% now 'UTC' %} {% now 'UTC' + 'hours=2' %} {% now 'Europe/London', '%Y-%m-%d' %} 3. Adds convenience features on top of Arrow: - Default timezone from environment variable (TZ) or config - Default datetime format configuration - Offset syntax parsing: 'hours=2,minutes=30' → shift(hours=2, minutes=30) - Empty string timezone support to use configured defaults 4. Maintains security - Works within Jinja2's sandboxed environment so users cannot access arbitrary Python code or objects. Essentially, this is a Jinja2 wrapper around arrow.now() and arrow.shift() that provides user-friendly template syntax while maintaining security. Basic Usage: {% now 'UTC' %} # Output: Wed, 09 Dec 2015 23:33:01 Custom Format: {% now 'UTC', '%Y-%m-%d %H:%M:%S' %} # Output: 2015-12-09 23:33:01 Timezone Support: {% now 'America/New_York' %} {% now 'Europe/London' %} {% now '' %} # Uses default timezone from environment.default_timezone Time Offsets (Addition): {% now 'UTC' + 'hours=2' %} {% now 'UTC' + 'hours=2,minutes=30' %} {% now 'UTC' + 'days=1,hours=2,minutes=15,seconds=10' %} Time Offsets (Subtraction): {% now 'UTC' - 'minutes=11' %} {% now 'UTC' - 'days=2,minutes=33,seconds=1' %} Time Offsets with Custom Format: {% now 'UTC' + 'hours=2', '%Y-%m-%d %H:%M:%S' %} # Output: 2015-12-10 01:33:01 Weekday Support (for finding next/previous weekday): {% now 'UTC' + 'weekday=0' %} # Next Monday (0=Monday, 6=Sunday) {% now 'UTC' + 'weekday=4' %} # Next Friday Configuration: - Default timezone: Set via TZ environment variable or override environment.default_timezone - Default format: '%a, %d %b %Y %H:%M:%S' (can be overridden via environment.datetime_format) Environment Customization: from changedetectionio.jinja2_custom import create_jinja_env jinja2_env = create_jinja_env() jinja2_env.default_timezone = 'America/New_York' # Override default timezone jinja2_env.datetime_format = '%Y-%m-%d %H:%M' # Override default format Supported Offset Parameters: - years, months, weeks, days - hours, minutes, seconds, microseconds - weekday (0=Monday through 6=Sunday, must be integer) Note: This extension uses the Arrow library for timezone-aware datetime handling. All timezone names should be valid IANA timezone identifiers (e.g., 'America/New_York'). """ import arrow from jinja2 import nodes from jinja2.ext import Extension import os class TimeExtension(Extension): """ Jinja2 Extension providing the {% now %} tag for timezone-aware date/time rendering. This extension adds two attributes to the Jinja2 environment: - datetime_format: Default strftime format string (default: '%a, %d %b %Y %H:%M:%S') - default_timezone: Default timezone for rendering (default: TZ env var or 'UTC') Both can be overridden after environment creation by setting the attributes directly. """ tags = {'now'} def __init__(self, environment): """Jinja2 Extension constructor.""" super().__init__(environment) environment.extend( datetime_format='%a, %d %b %Y %H:%M:%S', default_timezone=os.getenv('TZ', 'UTC').strip() ) def _datetime(self, timezone, operator, offset, datetime_format): """ Get current datetime with time offset applied. Args: timezone: IANA timezone identifier (e.g., 'UTC', 'America/New_York') or empty string for default operator: '+' for addition or '-' for subtraction offset: Comma-separated offset parameters (e.g., 'hours=2,minutes=30') datetime_format: strftime format string or None to use environment default Returns: Formatted datetime string with offset applied Example: _datetime('UTC', '+', 'hours=2,minutes=30', '%Y-%m-%d %H:%M:%S') # Returns current time + 2.5 hours """ # Use default timezone if none specified if not timezone or timezone == '': timezone = self.environment.default_timezone d = arrow.now(timezone) # parse shift params from offset and include operator shift_params = {} for param in offset.split(','): interval, value = param.split('=') shift_params[interval.strip()] = float(operator + value.strip()) # Fix weekday parameter can not be float if 'weekday' in shift_params: shift_params['weekday'] = int(shift_params['weekday']) d = d.shift(**shift_params) if datetime_format is None: datetime_format = self.environment.datetime_format return d.strftime(datetime_format) def _now(self, timezone, datetime_format): """ Get current datetime without any offset. Args: timezone: IANA timezone identifier (e.g., 'UTC', 'America/New_York') or empty string for default datetime_format: strftime format string or None to use environment default Returns: Formatted datetime string for current time Example: _now('America/New_York', '%Y-%m-%d %H:%M:%S') # Returns current time in New York timezone """ # Use default timezone if none specified if not timezone or timezone == '': timezone = self.environment.default_timezone if datetime_format is None: datetime_format = self.environment.datetime_format return arrow.now(timezone).strftime(datetime_format) def parse(self, parser): """ Parse the {% now %} tag and generate appropriate AST nodes. This method is called by Jinja2 when it encounters a {% now %} tag. It parses the tag syntax and determines whether to call _now() or _datetime() based on whether offset operations (+ or -) are present. Supported syntax: {% now 'timezone' %} -> calls _now() {% now 'timezone', 'format' %} -> calls _now() {% now 'timezone' + 'offset' %} -> calls _datetime() {% now 'timezone' + 'offset', 'format' %} -> calls _datetime() {% now 'timezone' - 'offset', 'format' %} -> calls _datetime() Args: parser: Jinja2 parser instance Returns: nodes.Output: AST output node containing the formatted datetime string """ lineno = next(parser.stream).lineno node = parser.parse_expression() if parser.stream.skip_if('comma'): datetime_format = parser.parse_expression() else: datetime_format = nodes.Const(None) if isinstance(node, nodes.Add): call_method = self.call_method( '_datetime', [node.left, nodes.Const('+'), node.right, datetime_format], lineno=lineno, ) elif isinstance(node, nodes.Sub): call_method = self.call_method( '_datetime', [node.left, nodes.Const('-'), node.right, datetime_format], lineno=lineno, ) else: call_method = self.call_method( '_now', [node, datetime_format], lineno=lineno, ) return nodes.Output([call_method], lineno=lineno)
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/jinja2_custom/extensions/TimeExtension.py", "license": "Apache License 2.0", "lines": 172, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
dgtlmoon/changedetection.io:changedetectionio/jinja2_custom/safe_jinja.py
""" Safe Jinja2 render with max payload sizes See https://jinja.palletsprojects.com/en/3.1.x/sandbox/#security-considerations """ import jinja2.sandbox import typing as t import os from .extensions.TimeExtension import TimeExtension from .plugins import regex_replace JINJA2_MAX_RETURN_PAYLOAD_SIZE = 1024 * int(os.getenv("JINJA2_MAX_RETURN_PAYLOAD_SIZE_KB", 1024 * 10)) # Default extensions - can be overridden in create_jinja_env() DEFAULT_JINJA2_EXTENSIONS = [TimeExtension] def create_jinja_env(extensions=None, **kwargs) -> jinja2.sandbox.ImmutableSandboxedEnvironment: """ Create a sandboxed Jinja2 environment with our custom extensions and default timezone. Args: extensions: List of extension classes to use (defaults to DEFAULT_JINJA2_EXTENSIONS) **kwargs: Additional arguments to pass to ImmutableSandboxedEnvironment Returns: Configured Jinja2 environment """ if extensions is None: extensions = DEFAULT_JINJA2_EXTENSIONS jinja2_env = jinja2.sandbox.ImmutableSandboxedEnvironment( extensions=extensions, **kwargs ) # Get default timezone from environment variable default_timezone = os.getenv('TZ', 'UTC').strip() jinja2_env.default_timezone = default_timezone # Register custom filters jinja2_env.filters['regex_replace'] = regex_replace return jinja2_env # This is used for notifications etc, so actually it's OK to send custom HTML such as <a href> etc, but it should limit what data is available. # (Which also limits available functions that could be called) def render(template_str, **args: t.Any) -> str: jinja2_env = create_jinja_env() output = jinja2_env.from_string(template_str).render(args) return output[:JINJA2_MAX_RETURN_PAYLOAD_SIZE] def render_fully_escaped(content): """ Escape HTML content safely. MEMORY LEAK FIX: Use markupsafe.escape() directly instead of creating Jinja2 environments (was causing 1M+ compilations per page load). Simpler, faster, and no concerns about environment state. """ from markupsafe import escape return str(escape(content))
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/jinja2_custom/safe_jinja.py", "license": "Apache License 2.0", "lines": 48, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
dgtlmoon/changedetection.io:changedetectionio/tests/unit/test_time_extension.py
#!/usr/bin/env python3 """ Simple unit tests for TimeExtension that mimic how safe_jinja.py uses it. These tests demonstrate that the environment.default_timezone override works exactly as intended in the actual application code. """ import arrow from jinja2.sandbox import ImmutableSandboxedEnvironment from changedetectionio.jinja2_custom.extensions.TimeExtension import TimeExtension def test_default_timezone_override_like_safe_jinja(mocker): """ Test that mirrors exactly how safe_jinja.py uses the TimeExtension. This is the simplest demonstration that environment.default_timezone works. """ # Create environment (TimeExtension.__init__ sets default_timezone='UTC') jinja2_env = ImmutableSandboxedEnvironment(extensions=[TimeExtension]) # Override the default timezone - exactly like safe_jinja.py does jinja2_env.default_timezone = 'America/New_York' # Mock arrow.now to return a fixed time fixed_time = arrow.Arrow(2025, 1, 15, 12, 0, 0, tzinfo='America/New_York') mock = mocker.patch("changedetectionio.jinja2_custom.extensions.TimeExtension.arrow.now", return_value=fixed_time) # Use empty string timezone - should use the overridden default template_str = "{% now '' %}" output = jinja2_env.from_string(template_str).render() # Verify arrow.now was called with the overridden timezone mock.assert_called_with('America/New_York') assert '2025' in output assert 'Jan' in output def test_default_timezone_not_overridden(mocker): """ Test that without override, the default 'UTC' from __init__ is used. """ # Create environment (TimeExtension.__init__ sets default_timezone='UTC') jinja2_env = ImmutableSandboxedEnvironment(extensions=[TimeExtension]) # DON'T override - should use 'UTC' default # Mock arrow.now fixed_time = arrow.Arrow(2025, 1, 15, 17, 0, 0, tzinfo='UTC') mock = mocker.patch("changedetectionio.jinja2_custom.extensions.TimeExtension.arrow.now", return_value=fixed_time) # Use empty string timezone - should use 'UTC' default template_str = "{% now '' %}" output = jinja2_env.from_string(template_str).render() # Verify arrow.now was called with 'UTC' mock.assert_called_with('UTC') assert '2025' in output def test_datetime_format_override_like_safe_jinja(mocker): """ Test that environment.datetime_format can be overridden after creation. """ # Create environment (default format is '%a, %d %b %Y %H:%M:%S') jinja2_env = ImmutableSandboxedEnvironment(extensions=[TimeExtension]) # Override the datetime format jinja2_env.datetime_format = '%Y-%m-%d %H:%M:%S' # Mock arrow.now fixed_time = arrow.Arrow(2025, 1, 15, 14, 30, 45, tzinfo='UTC') mocker.patch("changedetectionio.jinja2_custom.extensions.TimeExtension.arrow.now", return_value=fixed_time) # Don't specify format - should use overridden default template_str = "{% now 'UTC' %}" output = jinja2_env.from_string(template_str).render() # Should use custom format YYYY-MM-DD HH:MM:SS assert output == '2025-01-15 14:30:45' def test_offset_with_overridden_timezone(mocker): """ Test that offset operations also respect the overridden default_timezone. """ jinja2_env = ImmutableSandboxedEnvironment(extensions=[TimeExtension]) # Override to use Europe/London jinja2_env.default_timezone = 'Europe/London' fixed_time = arrow.Arrow(2025, 1, 15, 10, 0, 0, tzinfo='Europe/London') mock = mocker.patch("changedetectionio.jinja2_custom.extensions.TimeExtension.arrow.now", return_value=fixed_time) # Use offset with empty timezone string template_str = "{% now '' + 'hours=2', '%Y-%m-%d %H:%M:%S' %}" output = jinja2_env.from_string(template_str).render() # Should have called arrow.now with Europe/London mock.assert_called_with('Europe/London') # Should be 10:00 + 2 hours = 12:00 assert output == '2025-01-15 12:00:00' def test_weekday_parameter_converted_to_int(mocker): """ Test that weekday parameter is properly converted from float to int. This is important because arrow.shift() requires weekday as int, not float. """ jinja2_env = ImmutableSandboxedEnvironment(extensions=[TimeExtension]) # Wednesday, Jan 15, 2025 fixed_time = arrow.Arrow(2025, 1, 15, 12, 0, 0, tzinfo='UTC') mocker.patch("changedetectionio.jinja2_custom.extensions.TimeExtension.arrow.now", return_value=fixed_time) # Add offset to next Monday (weekday=0) template_str = "{% now 'UTC' + 'weekday=0', '%A' %}" output = jinja2_env.from_string(template_str).render() # Should be Monday assert output == 'Monday' def test_multiple_offset_parameters(mocker): """ Test that multiple offset parameters can be combined in one expression. """ jinja2_env = ImmutableSandboxedEnvironment(extensions=[TimeExtension]) fixed_time = arrow.Arrow(2025, 1, 15, 10, 30, 45, tzinfo='UTC') mocker.patch("changedetectionio.jinja2_custom.extensions.TimeExtension.arrow.now", return_value=fixed_time) # Test multiple parameters: days, hours, minutes, seconds template_str = "{% now 'UTC' + 'days=1,hours=2,minutes=15,seconds=10', '%Y-%m-%d %H:%M:%S' %}" output = jinja2_env.from_string(template_str).render() # 2025-01-15 10:30:45 + 1 day + 2 hours + 15 minutes + 10 seconds # = 2025-01-16 12:45:55 assert output == '2025-01-16 12:45:55'
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/tests/unit/test_time_extension.py", "license": "Apache License 2.0", "lines": 103, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
dgtlmoon/changedetection.io:changedetectionio/tests/unit/test_time_handler.py
#!/usr/bin/env python3 """ Comprehensive tests for time_handler module refactored to use arrow. Run from project root: python3 -m pytest changedetectionio/tests/unit/test_time_handler.py -v """ import unittest import unittest.mock import arrow from changedetectionio import time_handler class TestAmIInsideTime(unittest.TestCase): """Tests for the am_i_inside_time function.""" def test_current_time_within_schedule(self): """Test that current time is detected as within schedule.""" # Get current time in a specific timezone timezone_str = 'Europe/Berlin' now = arrow.now(timezone_str) day_of_week = now.format('dddd') time_str = now.format('HH:00') # Current hour, 0 minutes duration = 60 # 60 minutes result = time_handler.am_i_inside_time( day_of_week=day_of_week, time_str=time_str, timezone_str=timezone_str, duration=duration ) self.assertTrue(result, f"Current time should be within {duration} minute window starting at {time_str}") def test_current_time_outside_schedule(self): """Test that time in the past is not within current schedule.""" timezone_str = 'Europe/Berlin' # Get yesterday's date yesterday = arrow.now(timezone_str).shift(days=-1) day_of_week = yesterday.format('dddd') time_str = yesterday.format('HH:mm') duration = 30 # Only 30 minutes result = time_handler.am_i_inside_time( day_of_week=day_of_week, time_str=time_str, timezone_str=timezone_str, duration=duration ) self.assertFalse(result, "Yesterday's time should not be within current schedule") def test_timezone_pacific_within_schedule(self): """Test with US/Pacific timezone.""" timezone_str = 'US/Pacific' now = arrow.now(timezone_str) day_of_week = now.format('dddd') time_str = now.format('HH:00') duration = 120 # 2 hours result = time_handler.am_i_inside_time( day_of_week=day_of_week, time_str=time_str, timezone_str=timezone_str, duration=duration ) self.assertTrue(result) def test_timezone_tokyo_within_schedule(self): """Test with Asia/Tokyo timezone.""" timezone_str = 'Asia/Tokyo' now = arrow.now(timezone_str) day_of_week = now.format('dddd') time_str = now.format('HH:00') duration = 90 # 1.5 hours result = time_handler.am_i_inside_time( day_of_week=day_of_week, time_str=time_str, timezone_str=timezone_str, duration=duration ) self.assertTrue(result) def test_schedule_crossing_midnight(self): """Test schedule that crosses midnight.""" timezone_str = 'UTC' now = arrow.now(timezone_str) # Set schedule to start 23:30 with 120 minute duration (crosses midnight) day_of_week = now.format('dddd') time_str = "23:30" duration = 120 # 2 hours - goes into next day # If we're at 00:15 the next day, we should still be in the schedule if now.hour == 0 and now.minute < 30: # We're in the time window that spilled over from yesterday result = time_handler.am_i_inside_time( day_of_week=day_of_week, time_str=time_str, timezone_str=timezone_str, duration=duration ) # This might be true or false depending on exact time self.assertIsInstance(result, bool) def test_invalid_day_of_week(self): """Test that invalid day raises ValueError.""" with self.assertRaises(ValueError) as context: time_handler.am_i_inside_time( day_of_week="Funday", time_str="12:00", timezone_str="UTC", duration=60 ) self.assertIn("Invalid day_of_week", str(context.exception)) def test_invalid_time_format(self): """Test that invalid time format raises ValueError.""" with self.assertRaises(ValueError) as context: time_handler.am_i_inside_time( day_of_week="Monday", time_str="25:99", timezone_str="UTC", duration=60 ) self.assertIn("Invalid time_str", str(context.exception)) def test_invalid_time_format_non_numeric(self): """Test that non-numeric time raises ValueError.""" with self.assertRaises(ValueError) as context: time_handler.am_i_inside_time( day_of_week="Monday", time_str="twelve:thirty", timezone_str="UTC", duration=60 ) self.assertIn("Invalid time_str", str(context.exception)) def test_invalid_timezone(self): """Test that invalid timezone raises ValueError.""" with self.assertRaises(ValueError) as context: time_handler.am_i_inside_time( day_of_week="Monday", time_str="12:00", timezone_str="Invalid/Timezone", duration=60 ) self.assertIn("Invalid timezone_str", str(context.exception)) def test_short_duration(self): """Test with very short duration (15 minutes default).""" timezone_str = 'UTC' now = arrow.now(timezone_str) day_of_week = now.format('dddd') time_str = now.format('HH:mm') duration = 15 # Default duration result = time_handler.am_i_inside_time( day_of_week=day_of_week, time_str=time_str, timezone_str=timezone_str, duration=duration ) self.assertTrue(result, "Current time should be within 15 minute window") def test_long_duration(self): """Test with long duration (24 hours).""" timezone_str = 'UTC' now = arrow.now(timezone_str) day_of_week = now.format('dddd') # Set time to current hour time_str = now.format('HH:00') duration = 1440 # 24 hours in minutes result = time_handler.am_i_inside_time( day_of_week=day_of_week, time_str=time_str, timezone_str=timezone_str, duration=duration ) self.assertTrue(result, "Current time should be within 24 hour window") def test_case_insensitive_day(self): """Test that day of week is case insensitive.""" timezone_str = 'UTC' now = arrow.now(timezone_str) day_of_week = now.format('dddd').lower() # lowercase day time_str = now.format('HH:00') duration = 60 result = time_handler.am_i_inside_time( day_of_week=day_of_week, time_str=time_str, timezone_str=timezone_str, duration=duration ) self.assertTrue(result, "Lowercase day should work") def test_edge_case_midnight(self): """Test edge case at exactly midnight.""" timezone_str = 'UTC' now = arrow.now(timezone_str) day_of_week = now.format('dddd') time_str = "00:00" duration = 60 result = time_handler.am_i_inside_time( day_of_week=day_of_week, time_str=time_str, timezone_str=timezone_str, duration=duration ) # Should be true if we're in the first hour of the day if now.hour == 0: self.assertTrue(result) def test_edge_case_end_of_day(self): """Test edge case near end of day.""" timezone_str = 'UTC' now = arrow.now(timezone_str) day_of_week = now.format('dddd') time_str = "23:45" duration = 30 # 30 minutes crosses midnight result = time_handler.am_i_inside_time( day_of_week=day_of_week, time_str=time_str, timezone_str=timezone_str, duration=duration ) # Result depends on current time self.assertIsInstance(result, bool) def test_24_hour_schedule_from_midnight(self): """Test 24-hour schedule starting at midnight covers entire day.""" timezone_str = 'UTC' # Test at a specific time: Monday 00:00 test_time = arrow.get('2024-01-01 00:00:00', 'YYYY-MM-DD HH:mm:ss').replace(tzinfo=timezone_str) day_of_week = test_time.format('dddd') # Monday # Mock current time for testing with unittest.mock.patch('arrow.now', return_value=test_time): result = time_handler.am_i_inside_time( day_of_week=day_of_week, time_str="00:00", timezone_str=timezone_str, duration=1440 # 24 hours ) self.assertTrue(result, "Should be active at start of 24-hour schedule") def test_24_hour_schedule_at_end_of_day(self): """Test 24-hour schedule is active at 23:59:59.""" timezone_str = 'UTC' # Test at Monday 23:59:59 test_time = arrow.get('2024-01-01 23:59:59', 'YYYY-MM-DD HH:mm:ss').replace(tzinfo=timezone_str) day_of_week = test_time.format('dddd') # Monday with unittest.mock.patch('arrow.now', return_value=test_time): result = time_handler.am_i_inside_time( day_of_week=day_of_week, time_str="00:00", timezone_str=timezone_str, duration=1440 # 24 hours ) self.assertTrue(result, "Should be active at end of 24-hour schedule") def test_24_hour_schedule_at_midnight_transition(self): """Test 24-hour schedule at exactly midnight transition.""" timezone_str = 'UTC' # Test at Tuesday 00:00:00 (end of Monday's 24-hour schedule) test_time = arrow.get('2024-01-02 00:00:00', 'YYYY-MM-DD HH:mm:ss').replace(tzinfo=timezone_str) monday = test_time.shift(days=-1).format('dddd') # Monday with unittest.mock.patch('arrow.now', return_value=test_time): result = time_handler.am_i_inside_time( day_of_week=monday, time_str="00:00", timezone_str=timezone_str, duration=1440 # 24 hours ) self.assertTrue(result, "Should include exactly midnight at end of 24-hour schedule") def test_schedule_crosses_midnight_before_midnight(self): """Test schedule crossing midnight - before midnight.""" timezone_str = 'UTC' # Monday 23:30 test_time = arrow.get('2024-01-01 23:30:00', 'YYYY-MM-DD HH:mm:ss').replace(tzinfo=timezone_str) day_of_week = test_time.format('dddd') # Monday with unittest.mock.patch('arrow.now', return_value=test_time): result = time_handler.am_i_inside_time( day_of_week=day_of_week, time_str="23:00", timezone_str=timezone_str, duration=120 # 2 hours (until 01:00 next day) ) self.assertTrue(result, "Should be active before midnight in cross-midnight schedule") def test_schedule_crosses_midnight_after_midnight(self): """Test schedule crossing midnight - after midnight.""" timezone_str = 'UTC' # Tuesday 00:30 test_time = arrow.get('2024-01-02 00:30:00', 'YYYY-MM-DD HH:mm:ss').replace(tzinfo=timezone_str) monday = test_time.shift(days=-1).format('dddd') # Monday with unittest.mock.patch('arrow.now', return_value=test_time): result = time_handler.am_i_inside_time( day_of_week=monday, time_str="23:00", timezone_str=timezone_str, duration=120 # 2 hours (until 01:00 Tuesday) ) self.assertTrue(result, "Should be active after midnight in cross-midnight schedule") def test_schedule_crosses_midnight_at_exact_end(self): """Test schedule crossing midnight at exact end time.""" timezone_str = 'UTC' # Tuesday 01:00 (exact end of Monday 23:00 + 120 minutes) test_time = arrow.get('2024-01-02 01:00:00', 'YYYY-MM-DD HH:mm:ss').replace(tzinfo=timezone_str) monday = test_time.shift(days=-1).format('dddd') # Monday with unittest.mock.patch('arrow.now', return_value=test_time): result = time_handler.am_i_inside_time( day_of_week=monday, time_str="23:00", timezone_str=timezone_str, duration=120 # 2 hours ) self.assertTrue(result, "Should include exact end time of schedule") def test_duration_60_minutes(self): """Test that duration of 60 minutes works correctly.""" timezone_str = 'UTC' test_time = arrow.get('2024-01-01 12:30:00', 'YYYY-MM-DD HH:mm:ss').replace(tzinfo=timezone_str) day_of_week = test_time.format('dddd') with unittest.mock.patch('arrow.now', return_value=test_time): result = time_handler.am_i_inside_time( day_of_week=day_of_week, time_str="12:00", timezone_str=timezone_str, duration=60 # Exactly 60 minutes ) self.assertTrue(result, "60-minute duration should work") def test_duration_at_exact_end_minute(self): """Test at exact end of 60-minute window.""" timezone_str = 'UTC' # Exactly 13:00 (end of 12:00 + 60 minutes) test_time = arrow.get('2024-01-01 13:00:00', 'YYYY-MM-DD HH:mm:ss').replace(tzinfo=timezone_str) day_of_week = test_time.format('dddd') with unittest.mock.patch('arrow.now', return_value=test_time): result = time_handler.am_i_inside_time( day_of_week=day_of_week, time_str="12:00", timezone_str=timezone_str, duration=60 ) self.assertTrue(result, "Should include exact end minute") def test_one_second_after_schedule_ends(self): """Test one second after schedule should end.""" timezone_str = 'UTC' # 13:00:01 (one second after 12:00 + 60 minutes) test_time = arrow.get('2024-01-01 13:00:01', 'YYYY-MM-DD HH:mm:ss').replace(tzinfo=timezone_str) day_of_week = test_time.format('dddd') with unittest.mock.patch('arrow.now', return_value=test_time): result = time_handler.am_i_inside_time( day_of_week=day_of_week, time_str="12:00", timezone_str=timezone_str, duration=60 ) self.assertFalse(result, "Should be False one second after schedule ends") def test_multi_day_schedule(self): """Test schedule longer than 24 hours (48 hours).""" timezone_str = 'UTC' # Tuesday 12:00 (36 hours after Monday 00:00) test_time = arrow.get('2024-01-02 12:00:00', 'YYYY-MM-DD HH:mm:ss').replace(tzinfo=timezone_str) monday = test_time.shift(days=-1).format('dddd') with unittest.mock.patch('arrow.now', return_value=test_time): result = time_handler.am_i_inside_time( day_of_week=monday, time_str="00:00", timezone_str=timezone_str, duration=2880 # 48 hours ) self.assertTrue(result, "Should support multi-day schedules") def test_schedule_one_minute_duration(self): """Test very short 1-minute schedule.""" timezone_str = 'UTC' test_time = arrow.get('2024-01-01 12:00:30', 'YYYY-MM-DD HH:mm:ss').replace(tzinfo=timezone_str) day_of_week = test_time.format('dddd') with unittest.mock.patch('arrow.now', return_value=test_time): result = time_handler.am_i_inside_time( day_of_week=day_of_week, time_str="12:00", timezone_str=timezone_str, duration=1 # Just 1 minute ) self.assertTrue(result, "1-minute schedule should work") def test_schedule_at_exact_start_time(self): """Test at exact start time (00:00:00.000000).""" timezone_str = 'UTC' test_time = arrow.get('2024-01-01 12:00:00.000000', 'YYYY-MM-DD HH:mm:ss.SSSSSS').replace(tzinfo=timezone_str) day_of_week = test_time.format('dddd') with unittest.mock.patch('arrow.now', return_value=test_time): result = time_handler.am_i_inside_time( day_of_week=day_of_week, time_str="12:00", timezone_str=timezone_str, duration=30 ) self.assertTrue(result, "Should include exact start time") def test_schedule_one_microsecond_before_start(self): """Test one microsecond before schedule starts.""" timezone_str = 'UTC' test_time = arrow.get('2024-01-01 11:59:59.999999', 'YYYY-MM-DD HH:mm:ss.SSSSSS').replace(tzinfo=timezone_str) day_of_week = test_time.format('dddd') with unittest.mock.patch('arrow.now', return_value=test_time): result = time_handler.am_i_inside_time( day_of_week=day_of_week, time_str="12:00", timezone_str=timezone_str, duration=30 ) self.assertFalse(result, "Should not include time before start") class TestIsWithinSchedule(unittest.TestCase): """Tests for the is_within_schedule function.""" def test_schedule_disabled(self): """Test that disabled schedule returns False.""" time_schedule_limit = {'enabled': False} result = time_handler.is_within_schedule(time_schedule_limit) self.assertFalse(result) def test_schedule_none(self): """Test that None schedule returns False.""" result = time_handler.is_within_schedule(None) self.assertFalse(result) def test_schedule_empty_dict(self): """Test that empty dict returns False.""" result = time_handler.is_within_schedule({}) self.assertFalse(result) def test_schedule_enabled_but_day_disabled(self): """Test schedule enabled but current day disabled.""" timezone_str = 'UTC' now = arrow.now(timezone_str) current_day = now.format('dddd').lower() time_schedule_limit = { 'enabled': True, 'timezone': timezone_str, current_day: { 'enabled': False, 'start_time': '09:00', 'duration': {'hours': 8, 'minutes': 0} } } result = time_handler.is_within_schedule(time_schedule_limit) self.assertFalse(result, "Disabled day should return False") def test_schedule_enabled_within_time(self): """Test schedule enabled and within time window.""" timezone_str = 'UTC' now = arrow.now(timezone_str) current_day = now.format('dddd').lower() current_hour = now.format('HH:00') time_schedule_limit = { 'enabled': True, 'timezone': timezone_str, current_day: { 'enabled': True, 'start_time': current_hour, 'duration': {'hours': 2, 'minutes': 0} } } result = time_handler.is_within_schedule(time_schedule_limit) self.assertTrue(result, "Current time should be within schedule") def test_schedule_enabled_outside_time(self): """Test schedule enabled but outside time window.""" timezone_str = 'UTC' now = arrow.now(timezone_str) current_day = now.format('dddd').lower() # Set time to 3 hours ago past_time = now.shift(hours=-3).format('HH:mm') time_schedule_limit = { 'enabled': True, 'timezone': timezone_str, current_day: { 'enabled': True, 'start_time': past_time, 'duration': {'hours': 1, 'minutes': 0} # Only 1 hour duration } } result = time_handler.is_within_schedule(time_schedule_limit) self.assertFalse(result, "3 hours ago with 1 hour duration should be False") def test_schedule_with_default_timezone(self): """Test schedule without timezone uses default.""" now = arrow.now('America/New_York') current_day = now.format('dddd').lower() current_hour = now.format('HH:00') time_schedule_limit = { 'enabled': True, # No timezone specified current_day: { 'enabled': True, 'start_time': current_hour, 'duration': {'hours': 2, 'minutes': 0} } } # Should use default UTC, but since we're testing with NY time, # the result depends on time difference result = time_handler.is_within_schedule( time_schedule_limit, default_tz='America/New_York' ) self.assertTrue(result, "Should work with default timezone") def test_schedule_different_timezones(self): """Test schedule works correctly across different timezones.""" # Test with Tokyo timezone timezone_str = 'Asia/Tokyo' now = arrow.now(timezone_str) current_day = now.format('dddd').lower() current_hour = now.format('HH:00') time_schedule_limit = { 'enabled': True, 'timezone': timezone_str, current_day: { 'enabled': True, 'start_time': current_hour, 'duration': {'hours': 1, 'minutes': 30} } } result = time_handler.is_within_schedule(time_schedule_limit) self.assertTrue(result) def test_schedule_with_minutes_in_duration(self): """Test schedule with minutes specified in duration.""" timezone_str = 'UTC' now = arrow.now(timezone_str) current_day = now.format('dddd').lower() current_time = now.format('HH:mm') time_schedule_limit = { 'enabled': True, 'timezone': timezone_str, current_day: { 'enabled': True, 'start_time': current_time, 'duration': {'hours': 0, 'minutes': 45} } } result = time_handler.is_within_schedule(time_schedule_limit) self.assertTrue(result, "Should handle minutes in duration") def test_schedule_with_timezone_whitespace(self): """Test that timezone with whitespace is handled.""" timezone_str = ' UTC ' now = arrow.now('UTC') current_day = now.format('dddd').lower() current_hour = now.format('HH:00') time_schedule_limit = { 'enabled': True, 'timezone': timezone_str, current_day: { 'enabled': True, 'start_time': current_hour, 'duration': {'hours': 1, 'minutes': 0} } } result = time_handler.is_within_schedule(time_schedule_limit) self.assertTrue(result, "Should handle timezone with whitespace") def test_schedule_with_60_minutes(self): """Test schedule with duration of 0 hours and 60 minutes.""" timezone_str = 'UTC' now = arrow.now(timezone_str) current_day = now.format('dddd').lower() current_hour = now.format('HH:00') time_schedule_limit = { 'enabled': True, 'timezone': timezone_str, current_day: { 'enabled': True, 'start_time': current_hour, 'duration': {'hours': 0, 'minutes': 60} # 60 minutes } } result = time_handler.is_within_schedule(time_schedule_limit) self.assertTrue(result, "Should accept 60 minutes as valid duration") def test_schedule_with_24_hours(self): """Test schedule with duration of 24 hours and 0 minutes.""" timezone_str = 'UTC' now = arrow.now(timezone_str) current_day = now.format('dddd').lower() start_hour = now.format('HH:00') time_schedule_limit = { 'enabled': True, 'timezone': timezone_str, current_day: { 'enabled': True, 'start_time': start_hour, 'duration': {'hours': 24, 'minutes': 0} # Full 24 hours } } result = time_handler.is_within_schedule(time_schedule_limit) self.assertTrue(result, "Should accept 24 hours as valid duration") def test_schedule_with_90_minutes(self): """Test schedule with duration of 0 hours and 90 minutes.""" timezone_str = 'UTC' now = arrow.now(timezone_str) current_day = now.format('dddd').lower() current_hour = now.format('HH:00') time_schedule_limit = { 'enabled': True, 'timezone': timezone_str, current_day: { 'enabled': True, 'start_time': current_hour, 'duration': {'hours': 0, 'minutes': 90} # 90 minutes = 1.5 hours } } result = time_handler.is_within_schedule(time_schedule_limit) self.assertTrue(result, "Should accept 90 minutes as valid duration") def test_schedule_24_hours_from_midnight(self): """Test 24-hour schedule from midnight using is_within_schedule.""" timezone_str = 'UTC' test_time = arrow.get('2024-01-01 12:00:00', 'YYYY-MM-DD HH:mm:ss').replace(tzinfo=timezone_str) current_day = test_time.format('dddd').lower() # monday time_schedule_limit = { 'enabled': True, 'timezone': timezone_str, current_day: { 'enabled': True, 'start_time': '00:00', 'duration': {'hours': 24, 'minutes': 0} } } with unittest.mock.patch('arrow.now', return_value=test_time): result = time_handler.is_within_schedule(time_schedule_limit) self.assertTrue(result, "24-hour schedule from midnight should cover entire day") def test_schedule_24_hours_at_end_of_day(self): """Test 24-hour schedule at 23:59 using is_within_schedule.""" timezone_str = 'UTC' test_time = arrow.get('2024-01-01 23:59:00', 'YYYY-MM-DD HH:mm:ss').replace(tzinfo=timezone_str) current_day = test_time.format('dddd').lower() time_schedule_limit = { 'enabled': True, 'timezone': timezone_str, current_day: { 'enabled': True, 'start_time': '00:00', 'duration': {'hours': 24, 'minutes': 0} } } with unittest.mock.patch('arrow.now', return_value=test_time): result = time_handler.is_within_schedule(time_schedule_limit) self.assertTrue(result, "Should be active at 23:59 in 24-hour schedule") def test_schedule_crosses_midnight_with_is_within_schedule(self): """Test schedule crossing midnight using is_within_schedule.""" timezone_str = 'UTC' # Tuesday 00:30 test_time = arrow.get('2024-01-02 00:30:00', 'YYYY-MM-DD HH:mm:ss').replace(tzinfo=timezone_str) # Get Monday as that's when the schedule started monday = test_time.shift(days=-1).format('dddd').lower() time_schedule_limit = { 'enabled': True, 'timezone': timezone_str, 'monday': { 'enabled': True, 'start_time': '23:00', 'duration': {'hours': 2, 'minutes': 0} # Until 01:00 Tuesday }, 'tuesday': { 'enabled': False, 'start_time': '09:00', 'duration': {'hours': 8, 'minutes': 0} } } with unittest.mock.patch('arrow.now', return_value=test_time): result = time_handler.is_within_schedule(time_schedule_limit) # Note: This checks Tuesday's schedule, not Monday's overlap # So it should be False because Tuesday is disabled self.assertFalse(result, "Should check current day (Tuesday), which is disabled") def test_schedule_with_mixed_hours_minutes(self): """Test schedule with both hours and minutes (23 hours 60 minutes = 24 hours).""" timezone_str = 'UTC' now = arrow.now(timezone_str) current_day = now.format('dddd').lower() current_hour = now.format('HH:00') time_schedule_limit = { 'enabled': True, 'timezone': timezone_str, current_day: { 'enabled': True, 'start_time': current_hour, 'duration': {'hours': 23, 'minutes': 60} # = 1440 minutes = 24 hours } } result = time_handler.is_within_schedule(time_schedule_limit) self.assertTrue(result, "Should handle 23 hours + 60 minutes = 24 hours") def test_schedule_48_hours(self): """Test schedule with 48-hour duration.""" timezone_str = 'UTC' now = arrow.now(timezone_str) current_day = now.format('dddd').lower() start_hour = now.format('HH:00') time_schedule_limit = { 'enabled': True, 'timezone': timezone_str, current_day: { 'enabled': True, 'start_time': start_hour, 'duration': {'hours': 48, 'minutes': 0} # 2 full days } } result = time_handler.is_within_schedule(time_schedule_limit) self.assertTrue(result, "Should support 48-hour (multi-day) schedules") class TestWeekdayEnum(unittest.TestCase): """Tests for the Weekday enum.""" def test_weekday_values(self): """Test that weekday enum has correct values.""" self.assertEqual(time_handler.Weekday.Monday, 0) self.assertEqual(time_handler.Weekday.Tuesday, 1) self.assertEqual(time_handler.Weekday.Wednesday, 2) self.assertEqual(time_handler.Weekday.Thursday, 3) self.assertEqual(time_handler.Weekday.Friday, 4) self.assertEqual(time_handler.Weekday.Saturday, 5) self.assertEqual(time_handler.Weekday.Sunday, 6) def test_weekday_string_access(self): """Test accessing weekday enum by string.""" self.assertEqual(time_handler.Weekday['Monday'], 0) self.assertEqual(time_handler.Weekday['Sunday'], 6) if __name__ == '__main__': unittest.main()
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/tests/unit/test_time_handler.py", "license": "Apache License 2.0", "lines": 683, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
dgtlmoon/changedetection.io:changedetectionio/rss_tools.py
""" RSS/Atom feed processing tools for changedetection.io """ from loguru import logger import re def cdata_in_document_to_text(html_content: str, render_anchor_tag_content=False) -> str: """ Process CDATA sections in HTML/XML content - inline replacement. Args: html_content: The HTML/XML content to process render_anchor_tag_content: Whether to render anchor tag content Returns: Processed HTML/XML content with CDATA sections replaced inline """ from xml.sax.saxutils import escape as xml_escape from .html_tools import html_to_text pattern = '<!\[CDATA\[(\s*(?:.(?<!\]\]>)\s*)*)\]\]>' def repl(m): text = m.group(1) return xml_escape(html_to_text(html_content=text, render_anchor_tag_content=render_anchor_tag_content)).strip() return re.sub(pattern, repl, html_content) # Jinja2 template for formatting RSS/Atom feed entries # Covers all common feedparser entry fields including namespaced elements # Outputs HTML that will be converted to text via html_to_text # @todo - This could be a UI setting in the future RSS_ENTRY_TEMPLATE = """<article class="rss-item" id="{{ entry.id|replace('"', '')|replace(' ', '-') }}">{%- if entry.title -%}Title: {{ entry.title }}<br>{%- endif -%} {%- if entry.link -%}<strong>Link:</strong> <a href="{{ entry.link }}">{{ entry.link }}</a><br> {%- endif -%} {%- if entry.id -%} <strong>Guid:</strong> {{ entry.id }}<br> {%- endif -%} {%- if entry.published -%} <strong>PubDate:</strong> {{ entry.published }}<br> {%- endif -%} {%- if entry.updated and entry.updated != entry.published -%} <strong>Updated:</strong> {{ entry.updated }}<br> {%- endif -%} {%- if entry.author -%} <strong>Author:</strong> {{ entry.author }}<br> {%- elif entry.author_detail and entry.author_detail.name -%} <strong>Author:</strong> {{ entry.author_detail.name }} {%- if entry.author_detail.email %} ({{ entry.author_detail.email }}){% endif -%} <br> {%- endif -%} {%- if entry.contributors -%} <strong>Contributors:</strong> {% for contributor in entry.contributors -%} {{ contributor.name if contributor.name else contributor }} {%- if not loop.last %}, {% endif -%} {%- endfor %}<br> {%- endif -%} {%- if entry.publisher -%} <strong>Publisher:</strong> {{ entry.publisher }}<br> {%- endif -%} {%- if entry.rights -%} <strong>Rights:</strong> {{ entry.rights }}<br> {%- endif -%} {%- if entry.license -%} <strong>License:</strong> {{ entry.license }}<br> {%- endif -%} {%- if entry.language -%} <strong>Language:</strong> {{ entry.language }}<br> {%- endif -%} {%- if entry.tags -%} <strong>Tags:</strong> {% for tag in entry.tags -%} {{ tag.term if tag.term else tag }} {%- if not loop.last %}, {% endif -%} {%- endfor %}<br> {%- endif -%} {%- if entry.category -%} <strong>Category:</strong> {{ entry.category }}<br> {%- endif -%} {%- if entry.comments -%} <strong>Comments:</strong> <a href="{{ entry.comments }}">{{ entry.comments }}</a><br> {%- endif -%} {%- if entry.slash_comments -%} <strong>Comment Count:</strong> {{ entry.slash_comments }}<br> {%- endif -%} {%- if entry.enclosures -%} <strong>Enclosures:</strong><br> {%- for enclosure in entry.enclosures %} - <a href="{{ enclosure.href }}">{{ enclosure.href }}</a> ({{ enclosure.type if enclosure.type else 'unknown type' }} {%- if enclosure.length %}, {{ enclosure.length }} bytes{% endif -%} )<br> {%- endfor -%} {%- endif -%} {%- if entry.media_content -%} <strong>Media:</strong><br> {%- for media in entry.media_content %} - <a href="{{ media.url }}">{{ media.url }}</a> {%- if media.type %} ({{ media.type }}){% endif -%} {%- if media.width and media.height %} {{ media.width }}x{{ media.height }}{% endif -%} <br> {%- endfor -%} {%- endif -%} {%- if entry.media_thumbnail -%} <strong>Thumbnail:</strong> <a href="{{ entry.media_thumbnail[0].url if entry.media_thumbnail[0].url else entry.media_thumbnail[0] }}">{{ entry.media_thumbnail[0].url if entry.media_thumbnail[0].url else entry.media_thumbnail[0] }}</a><br> {%- endif -%} {%- if entry.media_description -%} <strong>Media Description:</strong> {{ entry.media_description }}<br> {%- endif -%} {%- if entry.itunes_duration -%} <strong>Duration:</strong> {{ entry.itunes_duration }}<br> {%- endif -%} {%- if entry.itunes_author -%} <strong>Podcast Author:</strong> {{ entry.itunes_author }}<br> {%- endif -%} {%- if entry.dc_identifier -%} <strong>Identifier:</strong> {{ entry.dc_identifier }}<br> {%- endif -%} {%- if entry.dc_source -%} <strong>DC Source:</strong> {{ entry.dc_source }}<br> {%- endif -%} {%- if entry.dc_type -%} <strong>Type:</strong> {{ entry.dc_type }}<br> {%- endif -%} {%- if entry.dc_format -%} <strong>Format:</strong> {{ entry.dc_format }}<br> {%- endif -%} {%- if entry.dc_relation -%} <strong>Related:</strong> {{ entry.dc_relation }}<br> {%- endif -%} {%- if entry.dc_coverage -%} <strong>Coverage:</strong> {{ entry.dc_coverage }}<br> {%- endif -%} {%- if entry.source and entry.source.title -%} <strong>Source:</strong> {{ entry.source.title }} {%- if entry.source.link %} (<a href="{{ entry.source.link }}">{{ entry.source.link }}</a>){% endif -%} <br> {%- endif -%} {%- if entry.dc_content -%} <strong>Content:</strong> {{ entry.dc_content | safe }} {%- elif entry.content and entry.content[0].value -%} <strong>Content:</strong> {{ entry.content[0].value | safe }} {%- elif entry.summary -%} <strong>Summary:</strong> {{ entry.summary | safe }} {%- endif -%}</article> """ def format_rss_items(rss_content: str, render_anchor_tag_content=False) -> str: """ Format RSS/Atom feed items in a readable text format using feedparser and Jinja2. Converts RSS <item> or Atom <entry> elements to formatted text with all available fields: - Basic fields: title, link, id/guid, published date, updated date - Author fields: author, author_detail, contributors, publisher - Content fields: content, summary, description - Metadata: tags, category, rights, license - Media: enclosures, media_content, media_thumbnail - Dublin Core elements: dc:creator, dc:date, dc:publisher, etc. (mapped by feedparser) Args: rss_content: The RSS/Atom feed content render_anchor_tag_content: Whether to render anchor tag content in descriptions (unused, kept for compatibility) Returns: Formatted HTML content ready for html_to_text conversion """ try: import feedparser from changedetectionio.jinja2_custom import safe_jinja # Parse the feed - feedparser handles all RSS/Atom variants, CDATA, entity unescaping, etc. feed = feedparser.parse(rss_content) # Determine feed type for appropriate labels is_atom = feed.version and 'atom' in feed.version formatted_items = [] for entry in feed.entries: # Render the entry using Jinja2 template rendered = safe_jinja.render(RSS_ENTRY_TEMPLATE, entry=entry, is_atom=is_atom) formatted_items.append(rendered.strip()) # Wrap each item in a div with classes (first, last, item-N) items_html = [] total_items = len(formatted_items) for idx, item in enumerate(formatted_items): classes = ['rss-item'] if idx == 0: classes.append('first') if idx == total_items - 1: classes.append('last') classes.append(f'item-{idx + 1}') class_str = ' '.join(classes) items_html.append(f'<div class="{class_str}">{item}</div>') return '<html><body>\n' + "\n<br>".join(items_html) + '\n</body></html>' except Exception as e: logger.warning(f"Error formatting RSS items: {str(e)}") # Fall back to original content return rss_content
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/rss_tools.py", "license": "Apache License 2.0", "lines": 182, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
dgtlmoon/changedetection.io:changedetectionio/tests/test_rss_reader_mode.py
#!/usr/bin/env python3 import time import os from flask import url_for from .util import set_original_response, set_modified_response, live_server_setup, wait_for_all_checks, extract_rss_token_from_UI, \ extract_UUID_from_client, delete_all_watches def set_xmlns_purl_content(datastore_path, extra=""): data=f"""<rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="https://purl.org/dc/elements/1.1/" xmlns:media="http://search.yahoo.com/mrss/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"> <channel> <atom:link href="https://www.xxxxxxxtechxxxxx.com/feeds.xml" rel="self" type="application/rss+xml"/> <title> <![CDATA[ Latest from xxxxxxxtechxxxxx ]]> </title> <link>https://www.xxxxx.com</link> <description> <![CDATA[ All the latest content from the xxxxxxxtechxxxxx team ]]> </description> <lastBuildDate>Wed, 19 Nov 2025 15:00:00 +0000</lastBuildDate> <language>en</language> <item> <title> <![CDATA[ Sony Xperia 1 VII review: has Sony’s long-standing Xperia family lost what it takes to compete? ]]> </title> <dc:content> <![CDATA[ {{extra}} a little harder, dc-content. blue often quite tough and purple usually very difficult.</p><p>On the plus side, you don't technically need to solve the final one, as you'll be able to answer that one by a process of elimination. What's more, you can make up to four mistakes, which gives you a little bit of breathing room.</p><p>It's a little more involved than something like Wordle, however, and there are plenty of opportunities for the game to trip you up with tricks. For instance, watch out for homophones and other word games that could disguise the answers.</p><p>It's playable for free via the <a href="https://www.nytimes.com/games/strands" target="_blank">NYT Games site</a> on desktop or mobile.</p></article></section> ]]> </dc:content> <link>https://www.xxxxxxx.com/gaming/nyt-connections-today-answers-hints-20-november-2025</link> <description> <![CDATA[ Looking for NYT Connections answers and hints? Here's all you need to know to solve today's game, plus my commentary on the puzzles. ]]> </description> <guid isPermaLink="false">N2C2T6DztpWdxSdKpSUx89</guid> <enclosure url="https://cdn.mos.cms.futurecdn.net/RCGfdf3yhQ9W3MHbTRT6yk-1280-80.jpg" type="image/jpeg" length="0"/> <pubDate>Wed, 19 Nov 2025 15:00:00 +0000</pubDate> <category> <![CDATA[ Gaming ]]> </category> <dc:creator> <![CDATA[ Johnny Dee ]]> </dc:creator> <media:content type="image/jpeg" url="https://cdn.mos.cms.futurecdn.net/RCGfdf3yhQ9W3MHbTRT6yk-1280-80.jpg"> <media:credit> <![CDATA[ New York Times ]]> </media:credit> <media:text> <![CDATA[ NYT Connections homescreen on a phone, on a purple background ]]> </media:text> <media:title type="plain"> <![CDATA[ NYT Connections homescreen on a phone, on a purple background ]]> </media:title> </media:content> <media:thumbnail url="https://cdn.mos.cms.futurecdn.net/RCGfdf3yhQ9W3MHbTRT6yk-1280-80.jpg"/> </item> </channel> </rss> """ with open(os.path.join(datastore_path, "endpoint-content.txt"), "w") as f: f.write(data) def set_original_cdata_xml(datastore_path): test_return_data = """<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"> <channel> <title>Security Bulletins on wetscale</title> <link>https://wetscale.com/security-bulletins/</link> <description>Recent security bulletins from wetscale</description> <lastBuildDate>Fri, 10 Oct 2025 14:58:11 GMT</lastBuildDate> <docs>https://validator.w3.org/feed/docs/rss2.html</docs> <generator>wetscale.com</generator> <language>en-US</language> <copyright>© 2025 wetscale Inc. All rights reserved.</copyright> <atom:link href="https://wetscale.com/security-bulletins/index.xml" rel="self" type="application/rss+xml"/> <item> <title>TS-2025-005</title> <link>https://wetscale.com/security-bulletins/#ts-2025-005</link> <guid>https://wetscale.com/security-bulletins/#ts-2025-005</guid> <pubDate>Thu, 07 Aug 2025 00:00:00 GMT</pubDate> <description><p>Wet noodles escape<br><p>they also found themselves outside</p> </description> </item> <item> <title>TS-2025-004</title> <link>https://wetscale.com/security-bulletins/#ts-2025-004</link> <guid>https://wetscale.com/security-bulletins/#ts-2025-004</guid> <pubDate>Tue, 27 May 2025 00:00:00 GMT</pubDate> <description> <![CDATA[ <img class="type:primaryImage" src="https://testsite.com/701c981da04869e.jpg"/><p>The days of Terminator and The Matrix could be closer. But be positive.</p><p><a href="https://testsite.com">Read more link...</a></p> ]]> </description> </item> </channel> </rss> """ with open(os.path.join(datastore_path, "endpoint-content.txt"), "w") as f: f.write(test_return_data) def test_rss_reader_mode(client, live_server, measure_memory_usage, datastore_path): set_original_cdata_xml(datastore_path=datastore_path) # Rarely do endpoints give the right header, usually just text/xml, so we check also for <rss # This also triggers the automatic CDATA text parser so the RSS goes back a nice content list test_url = url_for('test_endpoint', content_type="text/xml; charset=UTF-8", _external=True) live_server.app.config['DATASTORE'].data['settings']['application']['rss_reader_mode'] = True # Add our URL to the import page uuid = client.application.config.get('DATASTORE').add_watch(url=test_url) client.get(url_for("ui.form_watch_checknow"), follow_redirects=True) wait_for_all_checks(client) watch = live_server.app.config['DATASTORE'].data['watching'][uuid] dates = list(watch.history.keys()) snapshot_contents = watch.get_history_snapshot(timestamp=dates[0]) assert 'Wet noodles escape' in snapshot_contents assert '<br>' not in snapshot_contents assert '&lt;' not in snapshot_contents assert 'The days of Terminator and The Matrix' in snapshot_contents assert 'PubDate: Thu, 07 Aug 2025 00:00:00 GMT' in snapshot_contents delete_all_watches(client) def test_rss_reader_mode_with_css_filters(client, live_server, measure_memory_usage, datastore_path): set_original_cdata_xml(datastore_path=datastore_path) # Rarely do endpoints give the right header, usually just text/xml, so we check also for <rss # This also triggers the automatic CDATA text parser so the RSS goes back a nice content list test_url = url_for('test_endpoint', content_type="text/xml; charset=UTF-8", _external=True) live_server.app.config['DATASTORE'].data['settings']['application']['rss_reader_mode'] = True # Add our URL to the import page uuid = client.application.config.get('DATASTORE').add_watch(url=test_url, extras={'include_filters': [".last"]}) client.get(url_for("ui.form_watch_checknow"), follow_redirects=True) wait_for_all_checks(client) watch = live_server.app.config['DATASTORE'].data['watching'][uuid] dates = list(watch.history.keys()) snapshot_contents = watch.get_history_snapshot(timestamp=dates[0]) assert 'Wet noodles escape' not in snapshot_contents assert '<br>' not in snapshot_contents assert '&lt;' not in snapshot_contents assert 'The days of Terminator and The Matrix' in snapshot_contents delete_all_watches(client) def test_xmlns_purl_content(client, live_server, measure_memory_usage, datastore_path): set_xmlns_purl_content(datastore_path=datastore_path) # Rarely do endpoints give the right header, usually just text/xml, so we check also for <rss # This also triggers the automatic CDATA text parser so the RSS goes back a nice content list #test_url = url_for('test_endpoint', content_type="text/xml; charset=UTF-8", _external=True) # Because NO utf-8 was specified here, we should be able to recover it in requests or other somehow. test_url = url_for('test_endpoint', content_type="text/xml;", _external=True) live_server.app.config['DATASTORE'].data['settings']['application']['rss_reader_mode'] = True # Add our URL to the import page uuid = client.application.config.get('DATASTORE').add_watch(url=test_url, extras={'include_filters': [".last"]}) client.get(url_for("ui.form_watch_checknow"), follow_redirects=True) wait_for_all_checks(client) watch = live_server.app.config['DATASTORE'].data['watching'][uuid] dates = list(watch.history.keys()) snapshot_contents = watch.get_history_snapshot(timestamp=dates[0]) assert "Title: Sony Xperia 1 VII review: has Sony’s long-standing Xperia family lost what it takes to compete?" in snapshot_contents assert "dc-content" in snapshot_contents
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/tests/test_rss_reader_mode.py", "license": "Apache License 2.0", "lines": 144, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
dgtlmoon/changedetection.io:changedetectionio/processors/magic.py
""" Content Type Detection and Stream Classification This module provides intelligent content-type detection for changedetection.io. It addresses the common problem where HTTP Content-Type headers are missing, incorrect, or too generic, which would otherwise cause the wrong processor to be used. The guess_stream_type class combines: 1. HTTP Content-Type headers (when available and reliable) 2. Python-magic library for MIME detection (analyzing actual file content) 3. Content-based pattern matching for text formats (HTML tags, XML declarations, etc.) This multi-layered approach ensures accurate detection of RSS feeds, JSON, HTML, PDF, plain text, CSV, YAML, and XML formats - even when servers provide misleading headers. Used by: processors/text_json_diff/processor.py and other content processors """ # When to apply the 'cdata to real HTML' hack RSS_XML_CONTENT_TYPES = [ "application/rss+xml", "application/rdf+xml", "application/atom+xml", "text/rss+xml", # rare, non-standard "application/x-rss+xml", # legacy (older feed software) "application/x-atom+xml", # legacy (older Atom) ] # JSON Content-types JSON_CONTENT_TYPES = [ "application/activity+json", "application/feed+json", "application/json", "application/ld+json", "application/vnd.api+json", ] # Generic XML Content-types (non-RSS/Atom) XML_CONTENT_TYPES = [ "text/xml", "application/xml", ] HTML_PATTERNS = ['<!doctype html', '<html', '<head', '<body', '<script', '<iframe', '<div'] from loguru import logger class guess_stream_type(): is_pdf = False is_json = False is_html = False is_plaintext = False is_rss = False is_csv = False is_xml = False # Generic XML, not RSS/Atom is_yaml = False def __init__(self, http_content_header, content): import re magic_content_header = http_content_header test_content = content[:200].lower().strip() # Remove whitespace between < and tag name for robust detection (handles '< html', '<\nhtml', etc.) test_content_normalized = re.sub(r'<\s+', '<', test_content) # Use puremagic for lightweight MIME detection (saves ~14MB vs python-magic) magic_result = None try: import puremagic # puremagic needs bytes, so encode if we have a string content_bytes = content[:200].encode('utf-8') if isinstance(content, str) else content[:200] # puremagic returns a list of PureMagic objects with confidence scores detections = puremagic.magic_string(content_bytes) if detections: # Get the highest confidence detection mime = detections[0].mime_type logger.debug(f"Guessing mime type, original content_type '{http_content_header}', mime type detected '{mime}'") if mime and "/" in mime: magic_result = mime # Ignore generic/fallback mime types if mime in ['application/octet-stream', 'application/x-empty', 'binary']: logger.debug(f"Ignoring generic mime type '{mime}' from puremagic library") # Trust puremagic for non-text types immediately elif mime not in ['text/html', 'text/plain']: magic_content_header = mime except Exception as e: logger.warning(f"Error getting a more precise mime type from 'puremagic' library ({str(e)}), using content-based detection") # Content-based detection (most reliable for text formats) # Check for HTML patterns first - if found, override magic's text/plain has_html_patterns = any(p in test_content_normalized for p in HTML_PATTERNS) # Always trust headers first if 'text/plain' in http_content_header: self.is_plaintext = True if any(s in http_content_header for s in RSS_XML_CONTENT_TYPES): self.is_rss = True elif any(s in http_content_header for s in JSON_CONTENT_TYPES): self.is_json = True elif 'pdf' in magic_content_header: self.is_pdf = True # magic will call a rss document 'xml' # Rarely do endpoints give the right header, usually just text/xml, so we check also for <rss # This also triggers the automatic CDATA text parser so the RSS goes back a nice content list elif '<rss' in test_content_normalized or '<feed' in test_content_normalized or any(s in magic_content_header for s in RSS_XML_CONTENT_TYPES) or '<rdf:' in test_content_normalized: self.is_rss = True elif has_html_patterns or http_content_header == 'text/html': self.is_html = True elif any(s in magic_content_header for s in JSON_CONTENT_TYPES): self.is_json = True elif any(s in http_content_header for s in XML_CONTENT_TYPES): # Only mark as generic XML if not already detected as RSS if not self.is_rss: self.is_xml = True elif test_content_normalized.startswith('<?xml') or any(s in magic_content_header for s in XML_CONTENT_TYPES): # Generic XML that's not RSS/Atom (RSS/Atom checked above) self.is_xml = True elif '%pdf-1' in test_content: self.is_pdf = True elif http_content_header.startswith('text/'): self.is_plaintext = True # Only trust magic for 'text' if no other patterns matched elif 'text' in magic_content_header: self.is_plaintext = True # If magic says text/plain and we found no HTML patterns, trust it elif magic_result == 'text/plain': self.is_plaintext = True logger.debug(f"Trusting magic's text/plain result (no HTML patterns detected)")
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/processors/magic.py", "license": "Apache License 2.0", "lines": 113, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
dgtlmoon/changedetection.io:changedetectionio/tests/test_api_openapi.py
#!/usr/bin/env python3 """ OpenAPI validation tests for ChangeDetection.io API This test file specifically verifies that OpenAPI validation is working correctly by testing various scenarios that should trigger validation errors. """ import time import json from flask import url_for from .util import live_server_setup, wait_for_all_checks, delete_all_watches def test_openapi_merged_spec_contains_restock_fields(): """ Unit test: verify that build_merged_spec_dict() correctly merges the restock_diff processor api.yaml into the base spec so that WatchBase.properties includes processor_config_restock_diff with all expected sub-fields. No live server required. """ from changedetectionio.api import build_merged_spec_dict spec = build_merged_spec_dict() schemas = spec['components']['schemas'] # The merged schema for processor_config_restock_diff should exist assert 'processor_config_restock_diff' in schemas, \ "processor_config_restock_diff schema missing from merged spec" restock_schema = schemas['processor_config_restock_diff'] props = restock_schema.get('properties', {}) expected_fields = { 'in_stock_processing', 'follow_price_changes', 'price_change_min', 'price_change_max', 'price_change_threshold_percent', } missing = expected_fields - set(props.keys()) assert not missing, f"Missing fields in processor_config_restock_diff schema: {missing}" # in_stock_processing must be an enum with the three valid values enum_values = set(props['in_stock_processing'].get('enum', [])) assert enum_values == {'in_stock_only', 'all_changes', 'off'}, \ f"Unexpected enum values for in_stock_processing: {enum_values}" # WatchBase.properties must carry a $ref to the restock schema so the # validation middleware can enforce it on every POST/PUT to /watch watchbase_props = schemas['WatchBase']['properties'] assert 'processor_config_restock_diff' in watchbase_props, \ "processor_config_restock_diff not wired into WatchBase.properties" ref = watchbase_props['processor_config_restock_diff'].get('$ref', '') assert 'processor_config_restock_diff' in ref, \ f"WatchBase.processor_config_restock_diff should $ref the schema, got: {ref}" def test_openapi_validation_invalid_content_type_on_create_watch(client, live_server, measure_memory_usage, datastore_path): """Test that creating a watch with invalid content-type triggers OpenAPI validation error.""" api_key = live_server.app.config['DATASTORE'].data['settings']['application'].get('api_access_token') # Try to create a watch with JSON data but without proper content-type header res = client.post( url_for("createwatch"), data=json.dumps({"url": "https://example.com", "title": "Test Watch"}), headers={'x-api-key': api_key}, # Missing 'content-type': 'application/json' follow_redirects=True ) # Should get 400 error due to OpenAPI validation failure assert res.status_code == 400, f"Expected 400 but got {res.status_code}" assert b"Validation failed" in res.data, "Should contain validation error message" delete_all_watches(client) def test_openapi_validation_missing_required_field_create_watch(client, live_server, measure_memory_usage, datastore_path): """Test that creating a watch without required URL field triggers OpenAPI validation error.""" api_key = live_server.app.config['DATASTORE'].data['settings']['application'].get('api_access_token') # Try to create a watch without the required 'url' field res = client.post( url_for("createwatch"), data=json.dumps({"title": "Test Watch Without URL"}), # Missing required 'url' field headers={'x-api-key': api_key, 'content-type': 'application/json'}, follow_redirects=True ) # Should get 400 error due to missing required field assert res.status_code == 400, f"Expected 400 but got {res.status_code}" assert b"Validation failed" in res.data, "Should contain validation error message" delete_all_watches(client) def test_openapi_validation_invalid_field_in_request_body(client, live_server, measure_memory_usage, datastore_path): """Test that including invalid fields triggers OpenAPI validation error.""" api_key = live_server.app.config['DATASTORE'].data['settings']['application'].get('api_access_token') # First create a valid watch res = client.post( url_for("createwatch"), data=json.dumps({"url": "https://example.com", "title": "Test Watch"}), headers={'x-api-key': api_key, 'content-type': 'application/json'}, follow_redirects=True ) assert res.status_code == 201, "Watch creation should succeed" # Get the watch list to find the UUID res = client.get( url_for("createwatch"), headers={'x-api-key': api_key} ) assert res.status_code == 200 watch_uuid = list(res.json.keys())[0] # Now try to update the watch with an invalid field res = client.put( url_for("watch", uuid=watch_uuid), headers={'x-api-key': api_key, 'content-type': 'application/json'}, data=json.dumps({ "title": "Updated title", "invalid_field_that_doesnt_exist": "this should cause validation error" }), ) # Should get 400 error due to invalid field (this will be caught by internal validation) # Note: This tests the flow where OpenAPI validation passes but internal validation catches it assert res.status_code == 400, f"Expected 400 but got {res.status_code}" # Backend validation now returns "Unknown field(s):" message assert b"Unknown field" in res.data, \ "Should contain validation error about unknown fields" delete_all_watches(client) def test_openapi_validation_import_wrong_content_type(client, live_server, measure_memory_usage, datastore_path): """Test that import endpoint with wrong content-type triggers OpenAPI validation error.""" api_key = live_server.app.config['DATASTORE'].data['settings']['application'].get('api_access_token') # Try to import URLs with JSON content-type instead of text/plain res = client.post( url_for("import") + "?tag=test-import", data='https://website1.com\nhttps://website2.com', headers={'x-api-key': api_key, 'content-type': 'application/json'}, # Wrong content-type follow_redirects=True ) # Should get 400 error due to content-type mismatch assert res.status_code == 400, f"Expected 400 but got {res.status_code}" assert b"Validation failed" in res.data, "Should contain validation error message" delete_all_watches(client) def test_openapi_validation_import_correct_content_type_succeeds(client, live_server, measure_memory_usage, datastore_path): """Test that import endpoint with correct content-type succeeds (positive test).""" api_key = live_server.app.config['DATASTORE'].data['settings']['application'].get('api_access_token') # Import URLs with correct text/plain content-type res = client.post( url_for("import") + "?tag=test-import", data='https://website1.com\nhttps://website2.com', headers={'x-api-key': api_key, 'content-type': 'text/plain'}, # Correct content-type follow_redirects=True ) # Should succeed assert res.status_code == 200, f"Expected 200 but got {res.status_code}" assert len(res.json) == 2, "Should import 2 URLs" delete_all_watches(client) def test_openapi_validation_get_requests_bypass_validation(client, live_server, measure_memory_usage, datastore_path): """Test that GET requests bypass OpenAPI validation entirely.""" api_key = live_server.app.config['DATASTORE'].data['settings']['application'].get('api_access_token') # Disable API token requirement first res = client.post( url_for("settings.settings_page"), data={ "requests-time_between_check-minutes": 180, "application-fetch_backend": "html_requests", "application-api_access_token_enabled": "" }, follow_redirects=True ) assert b"Settings updated." in res.data # Make GET request to list watches - should succeed even without API key or content-type res = client.get(url_for("createwatch")) # No headers needed for GET assert res.status_code == 200, f"GET requests should succeed without OpenAPI validation, got {res.status_code}" # Should return JSON with watch list (empty in this case) assert isinstance(res.json, dict), "Should return JSON dictionary for watch list" delete_all_watches(client) def test_openapi_validation_create_tag_missing_required_title(client, live_server, measure_memory_usage, datastore_path): """Test that creating a tag without required title triggers OpenAPI validation error.""" api_key = live_server.app.config['DATASTORE'].data['settings']['application'].get('api_access_token') # Try to create a tag without the required 'title' field res = client.post( url_for("tag"), data=json.dumps({"notification_urls": ["mailto:test@example.com"]}), # Missing required 'title' field headers={'x-api-key': api_key, 'content-type': 'application/json'}, follow_redirects=True ) # Should get 400 error due to missing required field assert res.status_code == 400, f"Expected 400 but got {res.status_code}" assert b"Validation failed" in res.data, "Should contain validation error message" delete_all_watches(client) def test_openapi_validation_watch_update_allows_partial_updates(client, live_server, measure_memory_usage, datastore_path): """Test that watch updates allow partial updates without requiring all fields (positive test).""" #xxx api_key = live_server.app.config['DATASTORE'].data['settings']['application'].get('api_access_token') # First create a valid watch res = client.post( url_for("createwatch"), data=json.dumps({"url": "https://example.com", "title": "Test Watch"}), headers={'x-api-key': api_key, 'content-type': 'application/json'}, follow_redirects=True ) assert res.status_code == 201, "Watch creation should succeed" # Get the watch list to find the UUID res = client.get( url_for("createwatch"), headers={'x-api-key': api_key} ) assert res.status_code == 200 watch_uuid = list(res.json.keys())[0] # Update only the title (partial update) - should succeed res = client.put( url_for("watch", uuid=watch_uuid), headers={'x-api-key': api_key, 'content-type': 'application/json'}, data=json.dumps({"title": "Updated Title Only"}), # Only updating title, not URL ) # Should succeed because UpdateWatch schema allows partial updates assert res.status_code == 200, f"Partial updates should succeed, got {res.status_code}" # Verify the update worked res = client.get( url_for("watch", uuid=watch_uuid), headers={'x-api-key': api_key} ) assert res.status_code == 200 assert res.json.get('title') == 'Updated Title Only', "Title should be updated" assert res.json.get('url') == 'https://example.com', "URL should remain unchanged" delete_all_watches(client)
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/tests/test_api_openapi.py", "license": "Apache License 2.0", "lines": 206, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
dgtlmoon/changedetection.io:changedetectionio/widgets/ternary_boolean.py
from wtforms import Field from markupsafe import Markup from flask_babel import lazy_gettext as _l class TernaryNoneBooleanWidget: """ A widget that renders a horizontal radio button group with either two options (Yes/No) or three options (Yes/No/Default), depending on the field's boolean_mode setting. """ def __call__(self, field, **kwargs): html = ['<div class="ternary-radio-group pure-form">'] field_id = kwargs.pop('id', field.id) boolean_mode = getattr(field, 'boolean_mode', False) # Get custom text or use defaults yes_text = getattr(field, 'yes_text', _l('Yes')) no_text = getattr(field, 'no_text', _l('No')) none_text = getattr(field, 'none_text', _l('Main settings')) # True option checked_true = ' checked' if field.data is True else '' html.append(f''' <label class="ternary-radio-option"> <input type="radio" name="{field.name}" value="true" id="{field_id}_true"{checked_true} class="pure-radio"> <span class="ternary-radio-label pure-button-primary">{yes_text}</span> </label> ''') # False option checked_false = ' checked' if field.data is False else '' html.append(f''' <label class="ternary-radio-option"> <input type="radio" name="{field.name}" value="false" id="{field_id}_false"{checked_false} class="pure-radio"> <span class="ternary-radio-label">{no_text}</span> </label> ''') # None option (only show if not in boolean mode) if not boolean_mode: checked_none = ' checked' if field.data is None else '' html.append(f''' <label class="ternary-radio-option"> <input type="radio" name="{field.name}" value="none" id="{field_id}_none"{checked_none} class="pure-radio"> <span class="ternary-radio-label ternary-default">{none_text}</span> </label> ''') html.append('</div>') return Markup(''.join(html)) class TernaryNoneBooleanField(Field): """ A field that can handle True, False, or None values, represented as a horizontal radio group. When boolean_mode=True, it acts like a BooleanField (only Yes/No options). When boolean_mode=False (default), it shows Yes/No/Default options. Custom text can be provided for each option: - yes_text: Text for True option (default: "Yes") - no_text: Text for False option (default: "No") - none_text: Text for None option (default: "Default") """ widget = TernaryNoneBooleanWidget() def __init__(self, label=None, validators=None, false_values=None, boolean_mode=False, yes_text=None, no_text=None, none_text=None, **kwargs): super(TernaryNoneBooleanField, self).__init__(label, validators, **kwargs) self.boolean_mode = boolean_mode self.yes_text = yes_text if yes_text is not None else _l('Yes') self.no_text = no_text if no_text is not None else _l('No') self.none_text = none_text if none_text is not None else _l('Main settings') if false_values is None: self.false_values = {'false', ''} else: self.false_values = false_values def process_formdata(self, valuelist): if not valuelist or not valuelist[0]: # In boolean mode, default to False instead of None self.data = False if self.boolean_mode else None elif valuelist[0].lower() == 'true': self.data = True elif valuelist[0].lower() == 'false': self.data = False elif valuelist[0].lower() == 'none': # In boolean mode, treat 'none' as False self.data = False if self.boolean_mode else None else: self.data = False if self.boolean_mode else None def _value(self): if self.data is True: return 'true' elif self.data is False: return 'false' else: # In boolean mode, None should be treated as False if self.boolean_mode: return 'false' else: return 'none'
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/widgets/ternary_boolean.py", "license": "Apache License 2.0", "lines": 89, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
dgtlmoon/changedetection.io:changedetectionio/widgets/test_custom_text.py
#!/usr/bin/env python3 import sys import os from changedetectionio.model import USE_SYSTEM_DEFAULT_NOTIFICATION_FORMAT_FOR_WATCH sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../..')) from changedetectionio.widgets import TernaryNoneBooleanField from wtforms import Form class TestForm(Form): # Default text default_field = TernaryNoneBooleanField('Default Field', default=None) # Custom text with HTML icons notification_field = TernaryNoneBooleanField( 'Notifications', default=False, yes_text='🔕 Muted', no_text='🔔 Unmuted', none_text='⚙️ System default' ) # HTML with styling styled_field = TernaryNoneBooleanField( 'Status', default=None, yes_text='<strong style="color: green;">✅ Active</strong>', no_text='<strong style="color: red;">❌ Inactive</strong>', none_text='<em style="color: gray;">🔧 Auto</em>' ) # Boolean mode with custom text boolean_field = TernaryNoneBooleanField( 'Boolean Field', default=True, boolean_mode=True, yes_text="Enabled", no_text="Disabled" ) # FontAwesome example fontawesome_field = TernaryNoneBooleanField( 'Notifications with FontAwesome', default=None, yes_text='<i class="fa fa-bell-slash"></i> Muted', no_text='<i class="fa fa-bell"></i> Unmuted', none_text='<i class="fa fa-cogs"></i> System default' ) def test_custom_text(): """Test custom text functionality""" form = TestForm() print("=== Testing TernaryNoneBooleanField Custom Text ===") # Test default field print("\n--- Default Field ---") default_field = form.default_field default_html = default_field.widget(default_field) print(f"Contains 'Yes': {'Yes' in default_html}") print(f"Contains 'No': {'No' in default_html}") print(f"Contains 'Default': {'Default' in default_html}") assert 'Yes' in default_html and 'No' in default_html and 'Default' in default_html # Test custom text field print("\n--- Custom Text Field with Emojis ---") notification_field = form.notification_field notification_html = notification_field.widget(notification_field) print(f"Contains '🔕 Muted': {'🔕 Muted' in notification_html}") print(f"Contains '🔔 Unmuted': {'🔔 Unmuted' in notification_html}") print(f"Contains '⚙️ System default': {'⚙️ System default' in notification_html}") print(f"Does NOT contain 'Yes': {'Yes' not in notification_html}") print(f"Does NOT contain 'No': {'No' not in notification_html}") assert '🔕 Muted' in notification_html and '🔔 Unmuted' in notification_html assert 'Yes' not in notification_html and 'No' not in notification_html # Test HTML styling print("\n--- HTML Styled Field ---") styled_field = form.styled_field styled_html = styled_field.widget(styled_field) print(f"Contains HTML tags: {'<strong' in styled_html}") print(f"Contains color styling: {'color: green' in styled_html}") print(f"Contains emojis: {'✅' in styled_html and '❌' in styled_html}") assert '<strong' in styled_html and 'color: green' in styled_html # Test boolean mode with custom text print("\n--- Boolean Field with Custom Text ---") boolean_field = form.boolean_field boolean_html = boolean_field.widget(boolean_field) print(f"Contains 'Enabled': {'Enabled' in boolean_html}") print(f"Contains 'Disabled': {'Disabled' in boolean_html}") print(f"Does NOT contain 'System default': {'System default' not in boolean_html}") print(f"Does NOT contain 'Default': {'Default' not in boolean_html}") assert 'Enabled' in boolean_html and 'Disabled' in boolean_html assert USE_SYSTEM_DEFAULT_NOTIFICATION_FORMAT_FOR_WATCH not in boolean_html and 'Default' not in boolean_html # Test FontAwesome field print("\n--- FontAwesome Icons Field ---") fontawesome_field = form.fontawesome_field fontawesome_html = fontawesome_field.widget(fontawesome_field) print(f"Contains FontAwesome classes: {'fa fa-bell' in fontawesome_html}") print(f"Contains multiple FA icons: {'fa fa-bell-slash' in fontawesome_html and 'fa fa-cogs' in fontawesome_html}") assert 'fa fa-bell' in fontawesome_html print("\n✅ All custom text tests passed!") print("\n--- Example Usage ---") print("TernaryNoneBooleanField('Status', yes_text='🟢 Online', no_text='🔴 Offline', none_text='🟡 Auto')") print("TernaryNoneBooleanField('Notifications', yes_text='<i class=\"fa fa-bell-slash\"></i> Muted', ...)") def test_data_processing(): """Test that custom text doesn't affect data processing""" print("\n=== Testing Data Processing ===") form = TestForm() field = form.notification_field # Test form data processing field.process_formdata(['true']) assert field.data is True, "Custom text should not affect data processing" print("✅ True processing works with custom text") field.process_formdata(['false']) assert field.data is False, "Custom text should not affect data processing" print("✅ False processing works with custom text") field.process_formdata(['none']) assert field.data is None, "Custom text should not affect data processing" print("✅ None processing works with custom text") print("✅ All data processing tests passed!") if __name__ == '__main__': test_custom_text() test_data_processing()
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/widgets/test_custom_text.py", "license": "Apache License 2.0", "lines": 113, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
dgtlmoon/changedetection.io:changedetectionio/queue_handlers.py
from blinker import signal from loguru import logger from typing import Dict, List, Any, Optional import heapq import queue import threading # Janus is no longer required - we use pure threading.Queue for multi-loop support # try: # import janus # except ImportError: # pass # Not needed anymore class RecheckPriorityQueue: """ Thread-safe priority queue supporting multiple async event loops. ARCHITECTURE: - Multiple async workers, each with its own event loop in its own thread - Hybrid sync/async design for maximum scalability - Sync interface for ticker thread (threading.Queue) - Async interface for workers (asyncio.Event - NO executor threads!) SCALABILITY: - Scales to 100-200+ workers without executor thread exhaustion - Async workers wait on asyncio.Event (pure coroutines, no threads) - Sync callers use threading.Queue (backward compatible) WHY NOT JANUS: - Janus binds to ONE event loop at creation time - Our architecture has 15+ workers, each with separate event loops - Workers in different threads/loops cannot share janus async interface WHY NOT RUN_IN_EXECUTOR: - With 200 workers, run_in_executor() would block 200 threads - Exhausts ThreadPoolExecutor, starves Flask HTTP handlers - Pure async approach uses 0 threads while waiting """ def __init__(self, maxsize: int = 0): try: import asyncio # Sync interface: threading.Queue for ticker thread and Flask routes self._notification_queue = queue.Queue(maxsize=maxsize if maxsize > 0 else 0) # Priority storage - thread-safe self._priority_items = [] self._lock = threading.RLock() # No event signaling needed - pure polling approach # Workers check queue every 50ms (latency acceptable: 0-500ms) # Scales to 1000+ workers: each sleeping worker = ~4KB coroutine, not thread # Signals for UI updates self.queue_length_signal = signal('queue_length') logger.debug("RecheckPriorityQueue initialized successfully") except Exception as e: logger.critical(f"CRITICAL: Failed to initialize RecheckPriorityQueue: {str(e)}") raise # SYNC INTERFACE (for ticker thread) def put(self, item, block: bool = True, timeout: Optional[float] = None): """Thread-safe sync put with priority ordering""" logger.trace(f"RecheckQueue.put() called for item: {self._get_item_uuid(item)}, block={block}, timeout={timeout}") try: # CRITICAL: Add to both priority storage AND notification queue atomically # to prevent desynchronization where item exists but no notification with self._lock: heapq.heappush(self._priority_items, item) # Add notification - use blocking with timeout for safety # Notification queue is unlimited size, so should never block in practice # but timeout ensures we detect any unexpected issues (deadlock, etc) try: self._notification_queue.put(True, block=True, timeout=5.0) except Exception as notif_e: # Notification failed - MUST remove from priority_items to keep in sync # This prevents "Priority queue inconsistency" errors in get() logger.critical(f"CRITICAL: Notification queue put failed, removing from priority_items: {notif_e}") self._priority_items.remove(item) heapq.heapify(self._priority_items) raise # Re-raise to be caught by outer exception handler # Signal emission after successful queue - log but don't fail the operation # Item is already safely queued, so signal failure shouldn't affect queue state try: self._emit_put_signals(item) except Exception as signal_e: logger.error(f"Failed to emit put signals but item queued successfully: {signal_e}") logger.trace(f"Successfully queued item: {self._get_item_uuid(item)}") return True except Exception as e: logger.critical(f"CRITICAL: Failed to put item {self._get_item_uuid(item)}: {type(e).__name__}: {str(e)}") # Item should have been cleaned up in the inner try/except if notification failed return False def get(self, block: bool = True, timeout: Optional[float] = None): """Thread-safe sync get with priority ordering""" logger.trace(f"RecheckQueue.get() called, block={block}, timeout={timeout}") import queue as queue_module try: # Wait for notification (this doesn't return the actual item, just signals availability) self._notification_queue.get(block=block, timeout=timeout) # Get highest priority item with self._lock: if not self._priority_items: logger.critical(f"CRITICAL: Queue notification received but no priority items available") raise Exception("Priority queue inconsistency") item = heapq.heappop(self._priority_items) # Signal emission after successful retrieval - log but don't lose the item # Item is already retrieved, so signal failure shouldn't affect queue state try: self._emit_get_signals() except Exception as signal_e: logger.error(f"Failed to emit get signals but item retrieved successfully: {signal_e}") logger.trace(f"RecheckQueue.get() successfully retrieved item: {self._get_item_uuid(item)}") return item except queue_module.Empty: # Queue is empty with timeout - expected behavior logger.trace(f"RecheckQueue.get() timed out - queue is empty (timeout={timeout})") raise # noqa except Exception as e: # Re-raise without logging - caller (worker) will handle and log appropriately logger.trace(f"RecheckQueue.get() failed with exception: {type(e).__name__}: {str(e)}") raise # ASYNC INTERFACE (for workers) async def async_put(self, item, executor=None): """Async put with priority ordering - uses thread pool to avoid blocking Args: item: Item to add to queue executor: Optional ThreadPoolExecutor. If None, uses default pool. """ logger.trace(f"RecheckQueue.async_put() called for item: {self._get_item_uuid(item)}, executor={executor}") import asyncio try: # Use run_in_executor to call sync put without blocking event loop loop = asyncio.get_event_loop() result = await loop.run_in_executor( executor, # Use provided executor or default lambda: self.put(item, block=True, timeout=5.0) ) logger.trace(f"RecheckQueue.async_put() successfully queued item: {self._get_item_uuid(item)}") return result except Exception as e: logger.critical(f"CRITICAL: Failed to async put item {self._get_item_uuid(item)}: {str(e)}") return False async def async_get(self, executor=None, timeout=1.0): """ Efficient async get using executor for blocking call. HYBRID APPROACH: Best of both worlds - Uses run_in_executor for efficient blocking (no polling overhead) - Single timeout (no double-timeout race condition) - Scales well: executor sized to match worker count With FETCH_WORKERS=10: 10 threads blocked max (acceptable) With FETCH_WORKERS=200: Need executor with 200+ threads (see worker_pool.py) Args: executor: ThreadPoolExecutor (sized to match worker count) timeout: Maximum time to wait in seconds Returns: Item from queue Raises: queue.Empty: If timeout expires with no item available """ logger.trace(f"RecheckQueue.async_get() called, timeout={timeout}") import asyncio try: # Use run_in_executor to call sync get efficiently # No outer asyncio.wait_for wrapper = no double timeout issue! loop = asyncio.get_event_loop() item = await loop.run_in_executor( executor, lambda: self.get(block=True, timeout=timeout) ) logger.trace(f"RecheckQueue.async_get() successfully retrieved item: {self._get_item_uuid(item)}") return item except queue.Empty: logger.trace(f"RecheckQueue.async_get() timed out - queue is empty") raise except Exception as e: logger.critical(f"CRITICAL: Failed to async get item from queue: {type(e).__name__}: {str(e)}") raise # UTILITY METHODS def qsize(self) -> int: """Get current queue size""" try: with self._lock: return len(self._priority_items) except Exception as e: logger.critical(f"CRITICAL: Failed to get queue size: {str(e)}") return 0 def empty(self) -> bool: """Check if queue is empty""" return self.qsize() == 0 def get_queued_uuids(self) -> list: """Get list of all queued UUIDs efficiently with single lock""" try: with self._lock: return [item.item['uuid'] for item in self._priority_items if hasattr(item, 'item') and 'uuid' in item.item] except Exception as e: logger.critical(f"CRITICAL: Failed to get queued UUIDs: {str(e)}") return [] def clear(self): """Clear all items from both priority storage and notification queue""" try: with self._lock: # Clear priority items self._priority_items.clear() # Drain all notifications to prevent stale notifications # This is critical for test cleanup to prevent queue desynchronization drained = 0 while not self._notification_queue.empty(): try: self._notification_queue.get_nowait() drained += 1 except queue.Empty: break if drained > 0: logger.debug(f"Cleared queue: removed {drained} notifications") return True except Exception as e: logger.critical(f"CRITICAL: Failed to clear queue: {str(e)}") return False def close(self): """Close the queue""" try: # Nothing to close for threading.Queue logger.debug("RecheckPriorityQueue closed successfully") except Exception as e: logger.critical(f"CRITICAL: Failed to close RecheckPriorityQueue: {str(e)}") # COMPATIBILITY METHODS (from original implementation) @property def queue(self): """Provide compatibility with original queue access""" try: with self._lock: return list(self._priority_items) except Exception as e: logger.critical(f"CRITICAL: Failed to get queue list: {str(e)}") return [] def get_uuid_position(self, target_uuid: str) -> Dict[str, Any]: """Find position of UUID in queue""" try: with self._lock: queue_list = list(self._priority_items) total_items = len(queue_list) if total_items == 0: return {'position': None, 'total_items': 0, 'priority': None, 'found': False} # Find target item for item in queue_list: if (hasattr(item, 'item') and isinstance(item.item, dict) and item.item.get('uuid') == target_uuid): # Count items with higher priority position = sum(1 for other in queue_list if other.priority < item.priority) return { 'position': position, 'total_items': total_items, 'priority': item.priority, 'found': True } return {'position': None, 'total_items': total_items, 'priority': None, 'found': False} except Exception as e: logger.critical(f"CRITICAL: Failed to get UUID position for {target_uuid}: {str(e)}") return {'position': None, 'total_items': 0, 'priority': None, 'found': False} def get_all_queued_uuids(self, limit: Optional[int] = None, offset: int = 0) -> Dict[str, Any]: """Get all queued UUIDs with pagination""" try: with self._lock: queue_list = sorted(self._priority_items) # Sort by priority total_items = len(queue_list) if total_items == 0: return {'items': [], 'total_items': 0, 'returned_items': 0, 'has_more': False} # Apply pagination end_idx = min(offset + limit, total_items) if limit else total_items items_to_process = queue_list[offset:end_idx] result = [] for position, item in enumerate(items_to_process, start=offset): if (hasattr(item, 'item') and isinstance(item.item, dict) and 'uuid' in item.item): result.append({ 'uuid': item.item['uuid'], 'position': position, 'priority': item.priority }) return { 'items': result, 'total_items': total_items, 'returned_items': len(result), 'has_more': (offset + len(result)) < total_items } except Exception as e: logger.critical(f"CRITICAL: Failed to get all queued UUIDs: {str(e)}") return {'items': [], 'total_items': 0, 'returned_items': 0, 'has_more': False} def get_queue_summary(self) -> Dict[str, Any]: """Get queue summary statistics""" try: with self._lock: queue_list = list(self._priority_items) total_items = len(queue_list) if total_items == 0: return { 'total_items': 0, 'priority_breakdown': {}, 'immediate_items': 0, 'clone_items': 0, 'scheduled_items': 0 } immediate_items = clone_items = scheduled_items = 0 priority_counts = {} for item in queue_list: priority = item.priority priority_counts[priority] = priority_counts.get(priority, 0) + 1 if priority == 1: immediate_items += 1 elif priority == 5: clone_items += 1 elif priority > 100: scheduled_items += 1 return { 'total_items': total_items, 'priority_breakdown': priority_counts, 'immediate_items': immediate_items, 'clone_items': clone_items, 'scheduled_items': scheduled_items, 'min_priority': min(priority_counts.keys()) if priority_counts else None, 'max_priority': max(priority_counts.keys()) if priority_counts else None } except Exception as e: logger.critical(f"CRITICAL: Failed to get queue summary: {str(e)}") return {'total_items': 0, 'priority_breakdown': {}, 'immediate_items': 0, 'clone_items': 0, 'scheduled_items': 0} # PRIVATE METHODS def _get_item_uuid(self, item) -> str: """Safely extract UUID from item for logging""" try: if hasattr(item, 'item') and isinstance(item.item, dict): return item.item.get('uuid', 'unknown') except Exception: pass return 'unknown' def _emit_put_signals(self, item): """Emit signals when item is added""" try: # Watch update signal if hasattr(item, 'item') and isinstance(item.item, dict) and 'uuid' in item.item: watch_check_update = signal('watch_check_update') if watch_check_update: watch_check_update.send(watch_uuid=item.item['uuid']) # Queue length signal if self.queue_length_signal: self.queue_length_signal.send(length=self.qsize()) except Exception as e: logger.critical(f"CRITICAL: Failed to emit put signals: {str(e)}") def _emit_get_signals(self): """Emit signals when item is removed""" try: if self.queue_length_signal: self.queue_length_signal.send(length=self.qsize()) except Exception as e: logger.critical(f"CRITICAL: Failed to emit get signals: {str(e)}") class NotificationQueue: """ Ultra-reliable notification queue using pure janus. CRITICAL DESIGN NOTE: Both sync_q and async_q are required because: - sync_q: Used by Flask routes, ticker threads, and other synchronous code - async_q: Used by async workers and coroutines DO NOT REMOVE EITHER INTERFACE - they bridge different execution contexts. See RecheckPriorityQueue docstring above for detailed explanation. Simple wrapper around janus with bulletproof error handling. """ def __init__(self, maxsize: int = 0, datastore=None): try: # Use pure threading.Queue to avoid event loop binding issues self._notification_queue = queue.Queue(maxsize=maxsize if maxsize > 0 else 0) self.notification_event_signal = signal('notification_event') self.datastore = datastore # For checking all_muted setting self._lock = threading.RLock() logger.debug("NotificationQueue initialized successfully") except Exception as e: logger.critical(f"CRITICAL: Failed to initialize NotificationQueue: {str(e)}") raise def set_datastore(self, datastore): """Set datastore reference after initialization (for circular dependency handling)""" self.datastore = datastore def put(self, item: Dict[str, Any], block: bool = True, timeout: Optional[float] = None): """Thread-safe sync put with signal emission""" logger.trace(f"NotificationQueue.put() called for item: {item.get('uuid', 'unknown')}, block={block}, timeout={timeout}") try: # Check if all notifications are muted if self.datastore and self.datastore.data['settings']['application'].get('all_muted', False): logger.debug(f"Notification blocked - all notifications are muted: {item.get('uuid', 'unknown')}") return False with self._lock: self._notification_queue.put(item, block=block, timeout=timeout) self._emit_notification_signal(item) logger.trace(f"NotificationQueue.put() successfully queued notification: {item.get('uuid', 'unknown')}") return True except Exception as e: logger.critical(f"CRITICAL: Failed to put notification {item.get('uuid', 'unknown')}: {str(e)}") return False async def async_put(self, item: Dict[str, Any], executor=None): """Async put with signal emission - uses thread pool Args: item: Notification item to queue executor: Optional ThreadPoolExecutor """ logger.trace(f"NotificationQueue.async_put() called for item: {item.get('uuid', 'unknown')}, executor={executor}") import asyncio try: # Check if all notifications are muted if self.datastore and self.datastore.data['settings']['application'].get('all_muted', False): logger.debug(f"Notification blocked - all notifications are muted: {item.get('uuid', 'unknown')}") return False loop = asyncio.get_event_loop() await loop.run_in_executor(executor, lambda: self.put(item, block=True, timeout=5.0)) logger.trace(f"NotificationQueue.async_put() successfully queued notification: {item.get('uuid', 'unknown')}") return True except Exception as e: logger.critical(f"CRITICAL: Failed to async put notification {item.get('uuid', 'unknown')}: {str(e)}") return False def get(self, block: bool = True, timeout: Optional[float] = None): """Thread-safe sync get""" logger.trace(f"NotificationQueue.get() called, block={block}, timeout={timeout}") try: with self._lock: item = self._notification_queue.get(block=block, timeout=timeout) logger.trace(f"NotificationQueue.get() retrieved item: {item.get('uuid', 'unknown') if isinstance(item, dict) else 'unknown'}") return item except queue.Empty as e: logger.trace(f"NotificationQueue.get() timed out - queue is empty (timeout={timeout})") raise e except Exception as e: logger.critical(f"CRITICAL: Failed to get notification: {type(e).__name__}: {str(e)}") raise e async def async_get(self, executor=None): """Async get - uses thread pool Args: executor: Optional ThreadPoolExecutor """ logger.trace(f"NotificationQueue.async_get() called, executor={executor}") import asyncio try: loop = asyncio.get_event_loop() item = await loop.run_in_executor(executor, lambda: self.get(block=True, timeout=1.0)) logger.trace(f"NotificationQueue.async_get() retrieved item: {item.get('uuid', 'unknown') if isinstance(item, dict) else 'unknown'}") return item except queue.Empty as e: logger.trace(f"NotificationQueue.async_get() timed out - queue is empty") raise e except Exception as e: logger.critical(f"CRITICAL: Failed to async get notification: {type(e).__name__}: {str(e)}") raise e def qsize(self) -> int: """Get current queue size""" try: with self._lock: return self._notification_queue.qsize() except Exception as e: logger.critical(f"CRITICAL: Failed to get notification queue size: {str(e)}") return 0 def empty(self) -> bool: """Check if queue is empty""" return self.qsize() == 0 def close(self): """Close the queue""" try: # Nothing to close for threading.Queue logger.debug("NotificationQueue closed successfully") except Exception as e: logger.critical(f"CRITICAL: Failed to close NotificationQueue: {str(e)}") def _emit_notification_signal(self, item: Dict[str, Any]): """Emit notification signal""" try: if self.notification_event_signal and isinstance(item, dict): watch_uuid = item.get('uuid') if watch_uuid: self.notification_event_signal.send(watch_uuid=watch_uuid) else: self.notification_event_signal.send() except Exception as e: logger.critical(f"CRITICAL: Failed to emit notification signal: {str(e)}")
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/queue_handlers.py", "license": "Apache License 2.0", "lines": 463, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
dgtlmoon/changedetection.io:changedetectionio/notification_service.py
#!/usr/bin/env python3 """ Notification Service Module Extracted from update_worker.py to provide standalone notification functionality for both sync and async workers """ import datetime import pytz from loguru import logger import time from changedetectionio.notification import default_notification_format, valid_notification_formats def _check_cascading_vars(datastore, var_name, watch): """ Check notification variables in cascading priority: Individual watch settings > Tag settings > Global settings """ from changedetectionio.notification import ( USE_SYSTEM_DEFAULT_NOTIFICATION_FORMAT_FOR_WATCH, default_notification_body, default_notification_title ) # Would be better if this was some kind of Object where Watch can reference the parent datastore etc v = watch.get(var_name) if v and not watch.get('notification_muted'): if var_name == 'notification_format' and v == USE_SYSTEM_DEFAULT_NOTIFICATION_FORMAT_FOR_WATCH: return datastore.data['settings']['application'].get('notification_format') return v tags = datastore.get_all_tags_for_watch(uuid=watch.get('uuid')) if tags: for tag_uuid, tag in tags.items(): v = tag.get(var_name) if v and not tag.get('notification_muted'): return v if datastore.data['settings']['application'].get(var_name): return datastore.data['settings']['application'].get(var_name) # Otherwise could be defaults if var_name == 'notification_format': return USE_SYSTEM_DEFAULT_NOTIFICATION_FORMAT_FOR_WATCH if var_name == 'notification_body': return default_notification_body if var_name == 'notification_title': return default_notification_title return None class FormattableTimestamp(str): """ A str subclass representing a formatted datetime. As a plain string it renders with the default format, but can also be called with a custom format argument in Jinja2 templates: {{ change_datetime }} → '2024-01-15 10:30:00 UTC' {{ change_datetime(format='%Y') }} → '2024' {{ change_datetime(format='%A') }} → 'Monday' {{ change_datetime(format='%Y-%m-%d') }} → '2024-01-15' Being a str subclass means it is natively JSON serializable. """ _DEFAULT_FORMAT = '%Y-%m-%d %H:%M:%S %Z' def __new__(cls, timestamp): dt = datetime.datetime.fromtimestamp(int(timestamp), tz=pytz.UTC) local_tz = datetime.datetime.now().astimezone().tzinfo dt_local = dt.astimezone(local_tz) try: formatted = dt_local.strftime(cls._DEFAULT_FORMAT) except Exception: formatted = dt_local.isoformat() instance = super().__new__(cls, formatted) instance._dt = dt_local return instance def __call__(self, format=_DEFAULT_FORMAT): try: return self._dt.strftime(format) except Exception: return self._dt.isoformat() class FormattableDiff(str): """ A str subclass representing a rendered diff. As a plain string it renders with the default options for that variant, but can be called with custom arguments in Jinja2 templates: {{ diff }} → default diff output {{ diff(lines=5) }} → truncate to 5 lines {{ diff(added_only=true) }} → only show added lines {{ diff(removed_only=true) }} → only show removed lines {{ diff(context=3) }} → 3 lines of context around changes {{ diff(word_diff=false) }} → line-level diff instead of word-level {{ diff(lines=10, added_only=true) }} → combine args {{ diff_added(lines=5) }} → works on any diff_* variant too Being a str subclass means it is natively JSON serializable. """ def __new__(cls, prev_snapshot, current_snapshot, **base_kwargs): if prev_snapshot or current_snapshot: from changedetectionio import diff as diff_module rendered = diff_module.render_diff(prev_snapshot, current_snapshot, **base_kwargs) else: rendered = '' instance = super().__new__(cls, rendered) instance._prev = prev_snapshot instance._current = current_snapshot instance._base_kwargs = base_kwargs return instance def __call__(self, lines=None, added_only=False, removed_only=False, context=0, word_diff=None, case_insensitive=False, ignore_junk=False): from changedetectionio import diff as diff_module kwargs = dict(self._base_kwargs) if added_only: kwargs['include_removed'] = False if removed_only: kwargs['include_added'] = False if context: kwargs['context_lines'] = int(context) if word_diff is not None: kwargs['word_diff'] = bool(word_diff) if case_insensitive: kwargs['case_insensitive'] = True if ignore_junk: kwargs['ignore_junk'] = True result = diff_module.render_diff(self._prev or '', self._current or '', **kwargs) if lines is not None: result = '\n'.join(result.splitlines()[:int(lines)]) return result # What is passed around as notification context, also used as the complete list of valid {{ tokens }} class NotificationContextData(dict): def __init__(self, initial_data=None, **kwargs): # ValidateJinja2Template() validates against the keynames of this dict to check for valid tokens in the body (user submission) super().__init__({ 'base_url': None, 'change_datetime': FormattableTimestamp(time.time()), 'current_snapshot': None, 'diff': FormattableDiff('', ''), 'diff_clean': FormattableDiff('', '', include_change_type_prefix=False), 'diff_added': FormattableDiff('', '', include_removed=False), 'diff_added_clean': FormattableDiff('', '', include_removed=False, include_change_type_prefix=False), 'diff_full': FormattableDiff('', '', include_equal=True), 'diff_full_clean': FormattableDiff('', '', include_equal=True, include_change_type_prefix=False), 'diff_patch': FormattableDiff('', '', patch_format=True), 'diff_removed': FormattableDiff('', '', include_added=False), 'diff_removed_clean': FormattableDiff('', '', include_added=False, include_change_type_prefix=False), 'diff_url': None, 'markup_text_links_to_html_links': False, # If automatic conversion of plaintext to HTML should happen 'notification_timestamp': time.time(), 'prev_snapshot': None, 'preview_url': None, 'screenshot': None, 'timestamp_from': None, 'timestamp_to': None, 'triggered_text': None, 'uuid': 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX', # Converted to 'watch_uuid' in create_notification_parameters 'watch_mime_type': None, 'watch_tag': None, 'watch_title': None, 'watch_url': 'https://WATCH-PLACE-HOLDER/', 'watch_uuid': 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX', # Converted to 'watch_uuid' in create_notification_parameters }) # Apply any initial data passed in self.update({'watch_uuid': self.get('uuid')}) if initial_data: self.update(initial_data) # Apply any keyword arguments if kwargs: self.update(kwargs) n_format = self.get('notification_format') if n_format and not valid_notification_formats.get(n_format): raise ValueError(f'Invalid notification format: "{n_format}"') def set_random_for_validation(self): import random, string """Randomly fills all dict keys with random strings (for validation/testing). So we can test the output in the notification body """ for key in self.keys(): if key in ['uuid', 'time', 'watch_uuid', 'change_datetime'] or key.startswith('diff'): continue rand_str = 'RANDOM-PLACEHOLDER-'+''.join(random.choices(string.ascii_letters + string.digits, k=12)) self[key] = rand_str def __setitem__(self, key, value): if key == 'notification_format' and isinstance(value, str) and not value.startswith('RANDOM-PLACEHOLDER-'): if not valid_notification_formats.get(value): raise ValueError(f'Invalid notification format: "{value}"') super().__setitem__(key, value) def add_rendered_diff_to_notification_vars(notification_scan_text:str, prev_snapshot:str, current_snapshot:str, word_diff:bool): """ Efficiently renders only the diff placeholders that are actually used in the notification text. Scans the notification template for diff placeholder usage (diff, diff_added, diff_clean, etc.) and only renders those specific variants, avoiding expensive render_diff() calls for unused placeholders. Uses LRU caching to avoid duplicate renders when multiple placeholders share the same arguments. Args: notification_scan_text: The notification template text to scan for placeholders prev_snapshot: Previous version of content for diff comparison current_snapshot: Current version of content for diff comparison word_diff: Whether to use word-level (True) or line-level (False) diffing Returns: dict: Only the diff placeholders that were found in notification_scan_text, with rendered content """ import re now = time.time() # Define base kwargs for each diff variant — these become the stored defaults # on the FormattableDiff object, so {{ diff(lines=5) }} overrides on top of them diff_specs = { 'diff': {'word_diff': word_diff}, 'diff_clean': {'word_diff': word_diff, 'include_change_type_prefix': False}, 'diff_added': {'word_diff': word_diff, 'include_removed': False}, 'diff_added_clean': {'word_diff': word_diff, 'include_removed': False, 'include_change_type_prefix': False}, 'diff_full': {'word_diff': word_diff, 'include_equal': True}, 'diff_full_clean': {'word_diff': word_diff, 'include_equal': True, 'include_change_type_prefix': False}, 'diff_patch': {'word_diff': word_diff, 'patch_format': True}, 'diff_removed': {'word_diff': word_diff, 'include_added': False}, 'diff_removed_clean': {'word_diff': word_diff, 'include_added': False, 'include_change_type_prefix': False}, } ret = {} rendered_count = 0 # Only create FormattableDiff objects for diff keys actually used in the notification text for key in NotificationContextData().keys(): if key.startswith('diff') and key in diff_specs: # Check if this placeholder is actually used in the notification text pattern = rf"(?<![A-Za-z0-9_]){re.escape(key)}(?![A-Za-z0-9_])" if re.search(pattern, notification_scan_text, re.IGNORECASE): ret[key] = FormattableDiff(prev_snapshot, current_snapshot, **diff_specs[key]) rendered_count += 1 if rendered_count: logger.trace(f"Rendered {rendered_count} diff placeholder(s) {sorted(ret.keys())} in {time.time() - now:.3f}s") return ret def set_basic_notification_vars(current_snapshot, prev_snapshot, watch, triggered_text, timestamp_changed=None): n_object = { 'current_snapshot': current_snapshot, 'prev_snapshot': prev_snapshot, 'screenshot': watch.get_screenshot() if watch and watch.get('notification_screenshot') else None, 'change_datetime': FormattableTimestamp(timestamp_changed) if timestamp_changed else None, 'triggered_text': triggered_text, 'uuid': watch.get('uuid') if watch else None, 'watch_url': watch.get('url') if watch else None, 'watch_uuid': watch.get('uuid') if watch else None, 'watch_mime_type': watch.get('content-type') } # The \n's in the content from the above will get converted to <br> etc depending on the notification format if watch: n_object.update(watch.extra_notification_token_values()) return n_object class NotificationService: """ Standalone notification service that handles all notification functionality previously embedded in the update_worker class """ def __init__(self, datastore, notification_q): self.datastore = datastore self.notification_q = notification_q def queue_notification_for_watch(self, n_object: NotificationContextData, watch, date_index_from=-2, date_index_to=-1): """ Queue a notification for a watch with full diff rendering and template variables """ from changedetectionio.notification import USE_SYSTEM_DEFAULT_NOTIFICATION_FORMAT_FOR_WATCH if not isinstance(n_object, NotificationContextData): raise TypeError(f"Expected NotificationContextData, got {type(n_object)}") dates = [] trigger_text = '' if watch: watch_history = watch.history dates = list(watch_history.keys()) trigger_text = watch.get('trigger_text', []) # Add text that was triggered if len(dates): snapshot_contents = watch.get_history_snapshot(timestamp=dates[-1]) else: snapshot_contents = "No snapshot/history available, the watch should fetch atleast once." # If we ended up here with "System default" if n_object.get('notification_format') == USE_SYSTEM_DEFAULT_NOTIFICATION_FORMAT_FOR_WATCH: n_object['notification_format'] = self.datastore.data['settings']['application'].get('notification_format') triggered_text = '' if len(trigger_text): from . import html_tools triggered_text = html_tools.get_triggered_text(content=snapshot_contents, trigger_text=trigger_text) if triggered_text: triggered_text = '\n'.join(triggered_text) # Could be called as a 'test notification' with only 1 snapshot available prev_snapshot = "Example text: example test\nExample text: change detection is cool\nExample text: some more examples\n" current_snapshot = "Example text: example test\nExample text: change detection is fantastic\nExample text: even more examples\nExample text: a lot more examples" if len(dates) > 1: prev_snapshot = watch.get_history_snapshot(timestamp=dates[date_index_from]) current_snapshot = watch.get_history_snapshot(timestamp=dates[date_index_to]) n_object.update(set_basic_notification_vars(current_snapshot=current_snapshot, prev_snapshot=prev_snapshot, watch=watch, triggered_text=triggered_text, timestamp_changed=dates[date_index_to])) if self.notification_q: logger.debug("Queued notification for sending") self.notification_q.put(n_object) else: logger.debug("Not queued, no queue defined. Just returning processed data") return n_object def send_content_changed_notification(self, watch_uuid): """ Send notification when content changes are detected """ n_object = NotificationContextData() watch = self.datastore.data['watching'].get(watch_uuid) if not watch: return watch_history = watch.history dates = list(watch_history.keys()) # Theoretically it's possible that this could be just 1 long, # - In the case that the timestamp key was not unique if len(dates) == 1: raise ValueError( "History index had 2 or more, but only 1 date loaded, timestamps were not unique? maybe two of the same timestamps got written, needs more delay?" ) # Should be a better parent getter in the model object # Prefer - Individual watch settings > Tag settings > Global settings (in that order) # this change probably not needed? n_object['notification_urls'] = _check_cascading_vars(self.datastore, 'notification_urls', watch) n_object['notification_title'] = _check_cascading_vars(self.datastore,'notification_title', watch) n_object['notification_body'] = _check_cascading_vars(self.datastore,'notification_body', watch) n_object['notification_format'] = _check_cascading_vars(self.datastore,'notification_format', watch) # (Individual watch) Only prepare to notify if the rules above matched queued = False if n_object and n_object.get('notification_urls'): queued = True count = watch.get('notification_alert_count', 0) + 1 self.datastore.update_watch(uuid=watch_uuid, update_obj={'notification_alert_count': count}) self.queue_notification_for_watch(n_object=n_object, watch=watch) return queued def send_filter_failure_notification(self, watch_uuid): """ Send notification when CSS/XPath filters fail consecutively """ threshold = self.datastore.data['settings']['application'].get('filter_failure_notification_threshold_attempts') watch = self.datastore.data['watching'].get(watch_uuid) if not watch: return filter_list = ", ".join(watch['include_filters']) # @todo - This could be a markdown template on the disk, apprise will convert the markdown to HTML+Plaintext parts in the email, and then 'markup_text_links_to_html_links' is not needed body = f"""Hello, Your configured CSS/xPath filters of '{filter_list}' for {{{{watch_url}}}} did not appear on the page after {threshold} attempts. It's possible the page changed layout and the filter needs updating ( Try the 'Visual Selector' tab ) Edit link: {{{{base_url}}}}/edit/{{{{watch_uuid}}}} Thanks - Your omniscient changedetection.io installation. """ n_object = NotificationContextData({ 'notification_title': 'Changedetection.io - Alert - CSS/xPath filter was not present in the page', 'notification_body': body, 'notification_format': _check_cascading_vars(self.datastore, 'notification_format', watch), }) n_object['markup_text_links_to_html_links'] = n_object.get('notification_format').startswith('html') if len(watch['notification_urls']): n_object['notification_urls'] = watch['notification_urls'] elif len(self.datastore.data['settings']['application']['notification_urls']): n_object['notification_urls'] = self.datastore.data['settings']['application']['notification_urls'] # Only prepare to notify if the rules above matched if 'notification_urls' in n_object: n_object.update({ 'watch_url': watch['url'], 'uuid': watch_uuid, 'screenshot': None }) self.notification_q.put(n_object) logger.debug(f"Sent filter not found notification for {watch_uuid}") else: logger.debug(f"NOT sending filter not found notification for {watch_uuid} - no notification URLs") def send_step_failure_notification(self, watch_uuid, step_n): """ Send notification when browser steps fail consecutively """ watch = self.datastore.data['watching'].get(watch_uuid, False) if not watch: return threshold = self.datastore.data['settings']['application'].get('filter_failure_notification_threshold_attempts') step = step_n + 1 # @todo - This could be a markdown template on the disk, apprise will convert the markdown to HTML+Plaintext parts in the email, and then 'markup_text_links_to_html_links' is not needed # {{{{ }}}} because this will be Jinja2 {{ }} tokens body = f"""Hello, Your configured browser step at position {step} for the web page watch {{{{watch_url}}}} did not appear on the page after {threshold} attempts, did the page change layout? The element may have moved and needs editing, or does it need a delay added? Edit link: {{{{base_url}}}}/edit/{{{{watch_uuid}}}} Thanks - Your omniscient changedetection.io installation. """ n_object = NotificationContextData({ 'notification_title': f"Changedetection.io - Alert - Browser step at position {step} could not be run", 'notification_body': body, 'notification_format': self._check_cascading_vars('notification_format', watch), }) n_object['markup_text_links_to_html_links'] = n_object.get('notification_format').startswith('html') if len(watch['notification_urls']): n_object['notification_urls'] = watch['notification_urls'] elif len(self.datastore.data['settings']['application']['notification_urls']): n_object['notification_urls'] = self.datastore.data['settings']['application']['notification_urls'] # Only prepare to notify if the rules above matched if 'notification_urls' in n_object: n_object.update({ 'watch_url': watch['url'], 'uuid': watch_uuid }) self.notification_q.put(n_object) logger.error(f"Sent step not found notification for {watch_uuid}") # Convenience functions for creating notification service instances def create_notification_service(datastore, notification_q): """ Factory function to create a NotificationService instance """ return NotificationService(datastore, notification_q)
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/notification_service.py", "license": "Apache License 2.0", "lines": 394, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
dgtlmoon/changedetection.io:changedetectionio/realtime/events.py
from flask_socketio import emit from loguru import logger from blinker import signal def register_watch_operation_handlers(socketio, datastore): """Register Socket.IO event handlers for watch operations""" @socketio.on('watch_operation') def handle_watch_operation(data): """Handle watch operations like pause, mute, recheck via Socket.IO""" try: op = data.get('op') uuid = data.get('uuid') logger.debug(f"Socket.IO: Received watch operation '{op}' for UUID {uuid}") if not op or not uuid: emit('operation_result', {'success': False, 'error': 'Missing operation or UUID'}) return # Check if watch exists if not datastore.data['watching'].get(uuid): emit('operation_result', {'success': False, 'error': 'Watch not found'}) return watch = datastore.data['watching'][uuid] # Perform the operation if op == 'pause': watch.toggle_pause() logger.info(f"Socket.IO: Toggled pause for watch {uuid}") elif op == 'mute': watch.toggle_mute() logger.info(f"Socket.IO: Toggled mute for watch {uuid}") elif op == 'recheck': # Import here to avoid circular imports from changedetectionio.flask_app import update_q from changedetectionio import queuedWatchMetaData from changedetectionio import worker_pool worker_pool.queue_item_async_safe(update_q, queuedWatchMetaData.PrioritizedItem(priority=1, item={'uuid': uuid})) logger.info(f"Socket.IO: Queued recheck for watch {uuid}") else: emit('operation_result', {'success': False, 'error': f'Unknown operation: {op}'}) return # Send signal to update UI watch_check_update = signal('watch_check_update') if watch_check_update: watch_check_update.send(watch_uuid=uuid) # Send success response to client emit('operation_result', {'success': True, 'operation': op, 'uuid': uuid}) except Exception as e: logger.error(f"Socket.IO error in handle_watch_operation: {str(e)}") emit('operation_result', {'success': False, 'error': str(e)})
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/realtime/events.py", "license": "Apache License 2.0", "lines": 46, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
dgtlmoon/changedetection.io:changedetectionio/custom_queue.py
import queue import asyncio from blinker import signal from loguru import logger class NotificationQueue(queue.Queue): """ Extended Queue that sends a 'notification_event' signal when notifications are added. This class extends the standard Queue and adds a signal emission after a notification is put into the queue. The signal includes the watch UUID if available. """ def __init__(self, maxsize=0): super().__init__(maxsize) try: self.notification_event_signal = signal('notification_event') except Exception as e: logger.critical(f"Exception creating notification_event signal: {e}") def put(self, item, block=True, timeout=None): # Call the parent's put method first super().put(item, block, timeout) # After putting the notification in the queue, emit signal with watch UUID try: if self.notification_event_signal and isinstance(item, dict): watch_uuid = item.get('uuid') if watch_uuid: # Send the notification_event signal with the watch UUID self.notification_event_signal.send(watch_uuid=watch_uuid) logger.trace(f"NotificationQueue: Emitted notification_event signal for watch UUID {watch_uuid}") else: # Send signal without UUID for system notifications self.notification_event_signal.send() logger.trace("NotificationQueue: Emitted notification_event signal for system notification") except Exception as e: logger.error(f"Exception emitting notification_event signal: {e}") class SignalPriorityQueue(queue.PriorityQueue): """ Extended PriorityQueue that sends a signal when items with a UUID are added. This class extends the standard PriorityQueue and adds a signal emission after an item is put into the queue. If the item contains a UUID, the signal is sent with that UUID as a parameter. """ def __init__(self, maxsize=0): super().__init__(maxsize) try: self.queue_length_signal = signal('queue_length') except Exception as e: logger.critical(f"Exception: {e}") def put(self, item, block=True, timeout=None): # Call the parent's put method first super().put(item, block, timeout) # After putting the item in the queue, check if it has a UUID and emit signal if hasattr(item, 'item') and isinstance(item.item, dict) and 'uuid' in item.item: uuid = item.item['uuid'] # Get the signal and send it if it exists watch_check_update = signal('watch_check_update') if watch_check_update: # NOTE: This would block other workers from .put/.get while this signal sends # Signal handlers may iterate the queue/datastore while holding locks watch_check_update.send(watch_uuid=uuid) # Send queue_length signal with current queue size try: if self.queue_length_signal: self.queue_length_signal.send(length=self.qsize()) except Exception as e: logger.critical(f"Exception: {e}") def get(self, block=True, timeout=None): # Call the parent's get method first item = super().get(block, timeout) # Send queue_length signal with current queue size try: if self.queue_length_signal: self.queue_length_signal.send(length=self.qsize()) except Exception as e: logger.critical(f"Exception: {e}") return item def get_uuid_position(self, target_uuid): """ Find the position of a watch UUID in the priority queue. Optimized for large queues - O(n) complexity instead of O(n log n). Args: target_uuid: The UUID to search for Returns: dict: Contains position info or None if not found - position: 0-based position in queue (0 = next to be processed) - total_items: total number of items in queue - priority: the priority value of the found item """ with self.mutex: queue_list = list(self.queue) total_items = len(queue_list) if total_items == 0: return { 'position': None, 'total_items': 0, 'priority': None, 'found': False } # Find the target item and its priority first - O(n) target_item = None target_priority = None for item in queue_list: if (hasattr(item, 'item') and isinstance(item.item, dict) and item.item.get('uuid') == target_uuid): target_item = item target_priority = item.priority break if target_item is None: return { 'position': None, 'total_items': total_items, 'priority': None, 'found': False } # Count how many items have higher priority (lower numbers) - O(n) position = 0 for item in queue_list: # Items with lower priority numbers are processed first if item.priority < target_priority: position += 1 elif item.priority == target_priority and item != target_item: # For same priority, count items that come before this one # (Note: this is approximate since heap order isn't guaranteed for equal priorities) position += 1 return { 'position': position, 'total_items': total_items, 'priority': target_priority, 'found': True } def get_all_queued_uuids(self, limit=None, offset=0): """ Get UUIDs currently in the queue with their positions. For large queues, use limit/offset for pagination. Args: limit: Maximum number of items to return (None = all) offset: Number of items to skip (for pagination) Returns: dict: Contains items and metadata - items: List of dicts with uuid, position, and priority - total_items: Total number of items in queue - returned_items: Number of items returned - has_more: Whether there are more items after this page """ with self.mutex: queue_list = list(self.queue) total_items = len(queue_list) if total_items == 0: return { 'items': [], 'total_items': 0, 'returned_items': 0, 'has_more': False } # For very large queues, warn about performance if total_items > 1000 and limit is None: logger.warning(f"Getting all {total_items} queued items without limit - this may be slow") # Sort only if we need exact positions (expensive for large queues) if limit is not None and limit <= 100: # For small requests, we can afford to sort queue_items = sorted(queue_list) end_idx = min(offset + limit, len(queue_items)) if limit else len(queue_items) items_to_process = queue_items[offset:end_idx] result = [] for position, item in enumerate(items_to_process, start=offset): if (hasattr(item, 'item') and isinstance(item.item, dict) and 'uuid' in item.item): result.append({ 'uuid': item.item['uuid'], 'position': position, 'priority': item.priority }) return { 'items': result, 'total_items': total_items, 'returned_items': len(result), 'has_more': (offset + len(result)) < total_items } else: # For large requests, return items with approximate positions # This is much faster O(n) instead of O(n log n) result = [] processed = 0 skipped = 0 for item in queue_list: if (hasattr(item, 'item') and isinstance(item.item, dict) and 'uuid' in item.item): if skipped < offset: skipped += 1 continue if limit and processed >= limit: break # Approximate position based on priority comparison approx_position = sum(1 for other in queue_list if other.priority < item.priority) result.append({ 'uuid': item.item['uuid'], 'position': approx_position, # Approximate 'priority': item.priority }) processed += 1 return { 'items': result, 'total_items': total_items, 'returned_items': len(result), 'has_more': (offset + len(result)) < total_items, 'note': 'Positions are approximate for performance with large queues' } def get_queue_summary(self): """ Get a quick summary of queue state without expensive operations. O(n) complexity - fast even for large queues. Returns: dict: Queue summary statistics """ with self.mutex: queue_list = list(self.queue) total_items = len(queue_list) if total_items == 0: return { 'total_items': 0, 'priority_breakdown': {}, 'immediate_items': 0, 'clone_items': 0, 'scheduled_items': 0 } # Count items by priority type - O(n) immediate_items = 0 # priority 1 clone_items = 0 # priority 5 scheduled_items = 0 # priority > 100 (timestamps) priority_counts = {} for item in queue_list: priority = item.priority priority_counts[priority] = priority_counts.get(priority, 0) + 1 if priority == 1: immediate_items += 1 elif priority == 5: clone_items += 1 elif priority > 100: scheduled_items += 1 return { 'total_items': total_items, 'priority_breakdown': priority_counts, 'immediate_items': immediate_items, 'clone_items': clone_items, 'scheduled_items': scheduled_items, 'min_priority': min(priority_counts.keys()) if priority_counts else None, 'max_priority': max(priority_counts.keys()) if priority_counts else None } class AsyncSignalPriorityQueue(asyncio.PriorityQueue): """ Async version of SignalPriorityQueue that sends signals when items are added/removed. This class extends asyncio.PriorityQueue and maintains the same signal behavior as the synchronous version for real-time UI updates. """ def __init__(self, maxsize=0): super().__init__(maxsize) try: self.queue_length_signal = signal('queue_length') except Exception as e: logger.critical(f"Exception: {e}") async def put(self, item): # Call the parent's put method first await super().put(item) # After putting the item in the queue, check if it has a UUID and emit signal if hasattr(item, 'item') and isinstance(item.item, dict) and 'uuid' in item.item: uuid = item.item['uuid'] # Get the signal and send it if it exists watch_check_update = signal('watch_check_update') if watch_check_update: # NOTE: This would block other workers from .put/.get while this signal sends # Signal handlers may iterate the queue/datastore while holding locks watch_check_update.send(watch_uuid=uuid) # Send queue_length signal with current queue size try: if self.queue_length_signal: self.queue_length_signal.send(length=self.qsize()) except Exception as e: logger.critical(f"Exception: {e}") async def get(self): # Call the parent's get method first item = await super().get() # Send queue_length signal with current queue size try: if self.queue_length_signal: self.queue_length_signal.send(length=self.qsize()) except Exception as e: logger.critical(f"Exception: {e}") return item @property def queue(self): """ Provide compatibility with sync PriorityQueue.queue access Returns the internal queue for template access """ return self._queue if hasattr(self, '_queue') else [] def get_uuid_position(self, target_uuid): """ Find the position of a watch UUID in the async priority queue. Optimized for large queues - O(n) complexity instead of O(n log n). Args: target_uuid: The UUID to search for Returns: dict: Contains position info or None if not found - position: 0-based position in queue (0 = next to be processed) - total_items: total number of items in queue - priority: the priority value of the found item """ queue_list = list(self._queue) total_items = len(queue_list) if total_items == 0: return { 'position': None, 'total_items': 0, 'priority': None, 'found': False } # Find the target item and its priority first - O(n) target_item = None target_priority = None for item in queue_list: if (hasattr(item, 'item') and isinstance(item.item, dict) and item.item.get('uuid') == target_uuid): target_item = item target_priority = item.priority break if target_item is None: return { 'position': None, 'total_items': total_items, 'priority': None, 'found': False } # Count how many items have higher priority (lower numbers) - O(n) position = 0 for item in queue_list: if item.priority < target_priority: position += 1 elif item.priority == target_priority and item != target_item: position += 1 return { 'position': position, 'total_items': total_items, 'priority': target_priority, 'found': True } def get_all_queued_uuids(self, limit=None, offset=0): """ Get UUIDs currently in the async queue with their positions. For large queues, use limit/offset for pagination. Args: limit: Maximum number of items to return (None = all) offset: Number of items to skip (for pagination) Returns: dict: Contains items and metadata (same structure as sync version) """ queue_list = list(self._queue) total_items = len(queue_list) if total_items == 0: return { 'items': [], 'total_items': 0, 'returned_items': 0, 'has_more': False } # Same logic as sync version but without mutex if limit is not None and limit <= 100: queue_items = sorted(queue_list) end_idx = min(offset + limit, len(queue_items)) if limit else len(queue_items) items_to_process = queue_items[offset:end_idx] result = [] for position, item in enumerate(items_to_process, start=offset): if (hasattr(item, 'item') and isinstance(item.item, dict) and 'uuid' in item.item): result.append({ 'uuid': item.item['uuid'], 'position': position, 'priority': item.priority }) return { 'items': result, 'total_items': total_items, 'returned_items': len(result), 'has_more': (offset + len(result)) < total_items } else: # Fast approximate positions for large queues result = [] processed = 0 skipped = 0 for item in queue_list: if (hasattr(item, 'item') and isinstance(item.item, dict) and 'uuid' in item.item): if skipped < offset: skipped += 1 continue if limit and processed >= limit: break approx_position = sum(1 for other in queue_list if other.priority < item.priority) result.append({ 'uuid': item.item['uuid'], 'position': approx_position, 'priority': item.priority }) processed += 1 return { 'items': result, 'total_items': total_items, 'returned_items': len(result), 'has_more': (offset + len(result)) < total_items, 'note': 'Positions are approximate for performance with large queues' } def get_queue_summary(self): """ Get a quick summary of async queue state. O(n) complexity - fast even for large queues. """ queue_list = list(self._queue) total_items = len(queue_list) if total_items == 0: return { 'total_items': 0, 'priority_breakdown': {}, 'immediate_items': 0, 'clone_items': 0, 'scheduled_items': 0 } immediate_items = 0 clone_items = 0 scheduled_items = 0 priority_counts = {} for item in queue_list: priority = item.priority priority_counts[priority] = priority_counts.get(priority, 0) + 1 if priority == 1: immediate_items += 1 elif priority == 5: clone_items += 1 elif priority > 100: scheduled_items += 1 return { 'total_items': total_items, 'priority_breakdown': priority_counts, 'immediate_items': immediate_items, 'clone_items': clone_items, 'scheduled_items': scheduled_items, 'min_priority': min(priority_counts.keys()) if priority_counts else None, 'max_priority': max(priority_counts.keys()) if priority_counts else None }
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/custom_queue.py", "license": "Apache License 2.0", "lines": 452, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
dgtlmoon/changedetection.io:changedetectionio/realtime/socket_server.py
import timeago from flask_socketio import SocketIO from flask_babel import gettext, get_locale import time import os from loguru import logger from blinker import signal from changedetectionio import strtobool from changedetectionio.languages import get_timeago_locale class SignalHandler: """A standalone class to receive signals""" def __init__(self, socketio_instance, datastore): self.socketio_instance = socketio_instance self.datastore = datastore # Connect to the watch_check_update signal from changedetectionio.flask_app import watch_check_update as wcc wcc.connect(self.handle_signal, weak=False) # logger.info("SignalHandler: Connected to signal from direct import") # Connect to the queue_length signal queue_length_signal = signal('queue_length') queue_length_signal.connect(self.handle_queue_length, weak=False) # logger.info("SignalHandler: Connected to queue_length signal") watch_delete_signal = signal('watch_deleted') watch_delete_signal.connect(self.handle_deleted_signal, weak=False) watch_favicon_bumped_signal = signal('watch_favicon_bump') watch_favicon_bumped_signal.connect(self.handle_watch_bumped_favicon_signal, weak=False) watch_small_status_comment_signal = signal('watch_small_status_comment') watch_small_status_comment_signal.connect(self.handle_watch_small_status_update, weak=False) # Connect to the notification_event signal notification_event_signal = signal('notification_event') notification_event_signal.connect(self.handle_notification_event, weak=False) logger.info("SignalHandler: Connected to notification_event signal") def handle_watch_small_status_update(self, *args, **kwargs): """Small simple status update, for example 'Connecting...'""" watch_uuid = kwargs.get('watch_uuid') status = kwargs.get('status') if watch_uuid and status: logger.debug(f"Socket.IO: Received watch small status update '{status}' for UUID {watch_uuid}") # Emit the status update to all connected clients self.socketio_instance.emit("watch_small_status_comment", { "uuid": watch_uuid, "status": status, "event_timestamp": time.time() }) def handle_signal(self, *args, **kwargs): logger.trace(f"SignalHandler: Signal received with {len(args)} args and {len(kwargs)} kwargs") # Safely extract the watch UUID from kwargs watch_uuid = kwargs.get('watch_uuid') app_context = kwargs.get('app_context') if watch_uuid: # Get the watch object from the datastore watch = self.datastore.data['watching'].get(watch_uuid) if watch: if app_context: # note with app_context.app_context(): with app_context.test_request_context(): # Forward to handle_watch_update with the watch parameter handle_watch_update(self.socketio_instance, watch=watch, datastore=self.datastore) else: handle_watch_update(self.socketio_instance, watch=watch, datastore=self.datastore) logger.trace(f"Signal handler processed watch UUID {watch_uuid}") else: logger.warning(f"Watch UUID {watch_uuid} not found in datastore") def handle_watch_bumped_favicon_signal(self, *args, **kwargs): watch_uuid = kwargs.get('watch_uuid') if watch_uuid: # Emit the queue size to all connected clients self.socketio_instance.emit("watch_bumped_favicon", { "uuid": watch_uuid, "event_timestamp": time.time() }) logger.debug(f"Watch UUID {watch_uuid} got its favicon updated") def handle_deleted_signal(self, *args, **kwargs): watch_uuid = kwargs.get('watch_uuid') if watch_uuid: # Emit the queue size to all connected clients self.socketio_instance.emit("watch_deleted", { "uuid": watch_uuid, "event_timestamp": time.time() }) logger.debug(f"Watch UUID {watch_uuid} was deleted") def handle_queue_length(self, *args, **kwargs): """Handle queue_length signal and emit to all clients""" try: queue_length = kwargs.get('length', 0) logger.debug(f"SignalHandler: Queue length update received: {queue_length}") # Emit the queue size to all connected clients self.socketio_instance.emit("queue_size", { "q_length": queue_length, "event_timestamp": time.time() }) except Exception as e: logger.error(f"Socket.IO error in handle_queue_length: {str(e)}") def handle_notification_event(self, *args, **kwargs): """Handle notification_event signal and emit to all clients""" try: watch_uuid = kwargs.get('watch_uuid') logger.debug(f"SignalHandler: Notification event received for watch UUID: {watch_uuid}") # Emit the notification event to all connected clients self.socketio_instance.emit("notification_event", { "watch_uuid": watch_uuid, "event_timestamp": time.time() }) logger.trace(f"Socket.IO: Emitted notification_event for watch UUID {watch_uuid}") except Exception as e: logger.error(f"Socket.IO error in handle_notification_event: {str(e)}") def handle_watch_update(socketio, **kwargs): """Handle watch update signal from blinker""" try: watch = kwargs.get('watch') datastore = kwargs.get('datastore') # Emit the watch update to all connected clients from changedetectionio.flask_app import update_q from changedetectionio.flask_app import _jinja2_filter_datetime from changedetectionio import worker_pool # Get list of watches that are currently running running_uuids = worker_pool.get_running_uuids() # Get list of watches in the queue (efficient single-lock method) queue_list = update_q.get_queued_uuids() # Get the error texts from the watch error_texts = watch.compile_error_texts() # Create a simplified watch data object to send to clients watch_data = { 'checking_now': True if watch.get('uuid') in running_uuids else False, 'error_text': error_texts, 'event_timestamp': time.time(), 'fetch_time': watch.get('fetch_time'), 'has_error': True if error_texts else False, 'has_favicon': True if watch.get_favicon_filename() else False, 'history_n': watch.history_n, 'last_changed_text': timeago.format(int(watch.last_changed), time.time(), get_timeago_locale(str(get_locale()))) if watch.history_n >= 2 and int(watch.last_changed) > 0 else gettext('Not yet'), 'last_checked': watch.get('last_checked'), 'last_checked_text': _jinja2_filter_datetime(watch), 'notification_muted': True if watch.get('notification_muted') else False, 'paused': True if watch.get('paused') else False, 'queued': True if watch.get('uuid') in queue_list else False, 'unviewed': watch.has_unviewed, 'uuid': watch.get('uuid'), } errored_count = 0 for watch_uuid_iter, watch_iter in datastore.data['watching'].items(): if watch_iter.get('last_error'): errored_count += 1 general_stats = { 'count_errors': errored_count, 'unread_changes_count': datastore.unread_changes_count } # Debug what's being emitted # logger.debug(f"Emitting 'watch_update' event for {watch.get('uuid')}, data: {watch_data}") # Emit to all clients (no 'broadcast' parameter needed - it's the default behavior) socketio.emit("watch_update", {'watch': watch_data}) socketio.emit("general_stats_update", general_stats) # Log after successful emit - use watch_data['uuid'] to avoid variable shadowing issues logger.trace(f"Socket.IO: Emitted update for watch {watch_data['uuid']}, Checking now: {watch_data['checking_now']}") except Exception as e: logger.error(f"Socket.IO error in handle_watch_update: {str(e)}") def init_socketio(app, datastore): """Initialize SocketIO with the main Flask app""" import platform import sys # Platform-specific async_mode selection for better stability system = platform.system().lower() python_version = sys.version_info # Check for SocketIO mode configuration via environment variable # Default is 'threading' for best cross-platform compatibility socketio_mode = os.getenv('SOCKETIO_MODE', 'threading').lower() if socketio_mode == 'gevent': # Use gevent mode (higher concurrency but platform limitations) try: import gevent async_mode = 'gevent' logger.info(f"SOCKETIO_MODE=gevent: Using {async_mode} mode for Socket.IO") except ImportError: async_mode = 'threading' logger.warning(f"SOCKETIO_MODE=gevent but gevent not available, falling back to {async_mode} mode") elif socketio_mode == 'threading': # Use threading mode (default - best compatibility) async_mode = 'threading' logger.info(f"SOCKETIO_MODE=threading: Using {async_mode} mode for Socket.IO") else: # Invalid mode specified, use default async_mode = 'threading' logger.warning(f"Invalid SOCKETIO_MODE='{socketio_mode}', using default {async_mode} mode for Socket.IO") # Log platform info for debugging logger.info(f"Platform: {system}, Python: {python_version.major}.{python_version.minor}, Socket.IO mode: {async_mode}") # Restrict SocketIO CORS to same origin by default, can be overridden with env var cors_origins = os.environ.get('SOCKETIO_CORS_ORIGINS', None) socketio = SocketIO(app, async_mode=async_mode, cors_allowed_origins=cors_origins, # None means same-origin only logger=strtobool(os.getenv('SOCKETIO_LOGGING', 'False')), engineio_logger=strtobool(os.getenv('SOCKETIO_LOGGING', 'False')), # Disable WebSocket compression to prevent memory accumulation # Flask-Compress already handles HTTP response compression engineio_options={'http_compression': False, 'compression_threshold': 0}) # Set up event handlers logger.info("Socket.IO: Registering connect event handler") @socketio.on('checkbox-operation') def event_checkbox_operations(data): from changedetectionio.blueprint.ui import _handle_operations from changedetectionio import queuedWatchMetaData from changedetectionio import worker_pool from changedetectionio.flask_app import update_q, watch_check_update import threading logger.trace(f"Got checkbox operations event: {data}") datastore = socketio.datastore def run_operation(): """Run the operation in a background thread to avoid blocking the socket.io event loop""" try: _handle_operations( op=data.get('op'), uuids=data.get('uuids'), datastore=datastore, extra_data=data.get('extra_data'), worker_pool=worker_pool, update_q=update_q, queuedWatchMetaData=queuedWatchMetaData, watch_check_update=watch_check_update, emit_flash=False ) except Exception as e: logger.error(f"Error in checkbox operation thread: {e}") # Start operation in a disposable daemon thread thread = threading.Thread(target=run_operation, daemon=True, name=f"checkbox-op-{data.get('op')}") thread.start() @socketio.on('connect') def handle_connect(): """Handle client connection""" # logger.info("Socket.IO: CONNECT HANDLER CALLED - Starting connection process") from flask import request from flask_login import current_user from changedetectionio.flask_app import update_q # Access datastore from socketio datastore = socketio.datastore # logger.info(f"Socket.IO: Current user authenticated: {current_user.is_authenticated if hasattr(current_user, 'is_authenticated') else 'No current_user'}") # Check if authentication is required and user is not authenticated has_password_enabled = datastore.data['settings']['application'].get('password') or os.getenv("SALTED_PASS", False) # logger.info(f"Socket.IO: Password enabled: {has_password_enabled}") if has_password_enabled and not current_user.is_authenticated: logger.warning("Socket.IO: Rejecting unauthenticated connection") return False # Reject the connection # Send the current queue size to the newly connected client try: queue_size = update_q.qsize() socketio.emit("queue_size", { "q_length": queue_size, "event_timestamp": time.time() }, room=request.sid) # Send only to this client logger.debug(f"Socket.IO: Sent initial queue size {queue_size} to new client") except Exception as e: logger.error(f"Socket.IO error sending initial queue size: {str(e)}") logger.info("Socket.IO: Client connected") # logger.info("Socket.IO: Registering disconnect event handler") @socketio.on('disconnect') def handle_disconnect(): """Handle client disconnection""" logger.info("Socket.IO: Client disconnected") # Create a dedicated signal handler that will receive signals and emit them to clients signal_handler = SignalHandler(socketio, datastore) # Register watch operation event handlers from .events import register_watch_operation_handlers register_watch_operation_handlers(socketio, datastore) # Store the datastore reference on the socketio object for later use socketio.datastore = datastore # No stop event needed for threading mode - threads check app.config.exit directly # Add a shutdown method to the socketio object def shutdown(): """Shutdown the SocketIO server fast and aggressively""" try: logger.info("Socket.IO: Fast shutdown initiated...") logger.info("Socket.IO: Fast shutdown complete") except Exception as e: logger.error(f"Socket.IO error during shutdown: {str(e)}") # Attach the shutdown method to the socketio object socketio.shutdown = shutdown logger.info("Socket.IO initialized and attached to main Flask app") logger.info(f"Socket.IO: Registered event handlers: {socketio.handlers if hasattr(socketio, 'handlers') else 'No handlers found'}") return socketio
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/realtime/socket_server.py", "license": "Apache License 2.0", "lines": 279, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
dgtlmoon/changedetection.io:changedetectionio/tests/test_basic_socketio.py
#!/usr/bin/env python3 import time from flask import url_for from .util import ( set_original_response, set_modified_response, live_server_setup, wait_for_all_checks, delete_all_watches ) from loguru import logger def run_socketio_watch_update_test(client, live_server, password_mode="", datastore_path=""): """Test that the socketio emits a watch update event when content changes""" # Set up the test server set_original_response(datastore_path=datastore_path) # Get the SocketIO instance from the app from changedetectionio.flask_app import app socketio = app.extensions['socketio'] # Create a test client for SocketIO socketio_test_client = socketio.test_client(app, flask_test_client=client) if password_mode == "not logged in, should exit on connect": assert not socketio_test_client.is_connected(), "Failed to connect to Socket.IO server because it should bounce this connect" return assert socketio_test_client.is_connected(), "Failed to connect to Socket.IO server" print("Successfully connected to Socket.IO server") # Add our URL to the import page res = client.post( url_for("imports.import_page"), data={"urls": url_for('test_endpoint', _external=True)}, follow_redirects=True ) assert b"1 Imported" in res.data res = client.get(url_for("watchlist.index")) assert url_for('test_endpoint', _external=True).encode() in res.data # Wait for initial check to complete wait_for_all_checks(client) # Clear any initial messages socketio_test_client.get_received() # Make a change to trigger an update set_modified_response(datastore_path=datastore_path) # Force recheck res = client.get(url_for("ui.form_watch_checknow"), follow_redirects=True) assert b'Queued 1 watch for rechecking.' in res.data # Wait for the watch to be checked wait_for_all_checks(client) has_watch_update = False has_unviewed_update = False got_general_stats_update = False for i in range(10): # Get received events received = socketio_test_client.get_received() if received: logger.info(f"Received {len(received)} events after {i+1} seconds") for event in received: if event['name'] == 'watch_update': has_watch_update = True if event['name'] == 'general_stats_update': got_general_stats_update = True if has_unviewed_update: break # Force a recheck every 5 seconds to ensure events are emitted # if i > 0 and i % 5 == 0: # print(f"Still waiting for events, forcing another recheck...") # res = client.get(url_for("ui.form_watch_checknow"), follow_redirects=True) # assert b'Queued 1 watch for rechecking.' in res.data # wait_for_all_checks(client) # print(f"Waiting for unviewed update event... {i+1}/{max_wait}") time.sleep(1) # Verify we received watch_update events assert has_watch_update, "No watch_update events received" # Verify we received an unviewed event assert got_general_stats_update, "Got general stats update event" # Alternatively, check directly if the watch in the datastore is marked as unviewed from changedetectionio.flask_app import app datastore = app.config.get('DATASTORE') watch_uuid = next(iter(live_server.app.config['DATASTORE'].data['watching'])) # Get the watch from the datastore watch = datastore.data['watching'].get(watch_uuid) assert watch, f"Watch {watch_uuid} not found in datastore" assert watch.has_unviewed, "The watch was not marked as unviewed after content change" # Clean up delete_all_watches(client) def test_everything(live_server, client, measure_memory_usage, datastore_path): # live_server_setup(live_server) # Setup on conftest per function run_socketio_watch_update_test(password_mode="", live_server=live_server, client=client, datastore_path=datastore_path) ############################ Password required auth check ############################## # Enable password check and diff page access bypass res = client.post( url_for("settings.settings_page"), data={"application-password": "foobar", "requests-time_between_check-minutes": 180, 'application-fetch_backend': "html_requests"}, follow_redirects=True ) assert b"Password protection enabled." in res.data run_socketio_watch_update_test(password_mode="not logged in, should exit on connect", live_server=live_server, client=client, datastore_path=datastore_path) res = client.post( url_for("login"), data={"password": "foobar"}, follow_redirects=True ) # Yes we are correctly logged in assert b"LOG OUT" in res.data run_socketio_watch_update_test(password_mode="should be like normal", live_server=live_server, client=client, datastore_path=datastore_path)
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/tests/test_basic_socketio.py", "license": "Apache License 2.0", "lines": 103, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
dgtlmoon/changedetection.io:changedetectionio/tests/proxy_list/test_proxy_noconnect.py
#!/usr/bin/env python3 from flask import url_for from ..util import live_server_setup, wait_for_all_checks import os from ... import strtobool # Just to be sure the UI outputs the right error message on proxy connection failed # docker run -p 4444:4444 --rm --shm-size="2g" selenium/standalone-chrome:4 # PLAYWRIGHT_DRIVER_URL=ws://127.0.0.1:3000 pytest tests/proxy_list/test_proxy_noconnect.py # FAST_PUPPETEER_CHROME_FETCHER=True PLAYWRIGHT_DRIVER_URL=ws://127.0.0.1:3000 pytest tests/proxy_list/test_proxy_noconnect.py # WEBDRIVER_URL=http://127.0.0.1:4444/wd/hub pytest tests/proxy_list/test_proxy_noconnect.py def test_proxy_noconnect_custom(client, live_server, measure_memory_usage, datastore_path): # live_server_setup(live_server) # Setup on conftest per function # Goto settings, add our custom one res = client.post( url_for("settings.settings_page"), data={ "requests-time_between_check-minutes": 180, "application-ignore_whitespace": "y", "application-fetch_backend": 'html_webdriver' if os.getenv('PLAYWRIGHT_DRIVER_URL') or os.getenv("WEBDRIVER_URL") else 'html_requests', "requests-extra_proxies-0-proxy_name": "custom-test-proxy", # test:awesome is set in tests/proxy_list/squid-passwords.txt "requests-extra_proxies-0-proxy_url": "http://127.0.0.1:3128", }, follow_redirects=True ) assert b"Settings updated." in res.data test_url = "https://changedetection.io" res = client.post( url_for("ui.ui_views.form_quick_watch_add"), data={"url": test_url, "tags": '', 'edit_and_watch_submit_button': 'Edit > Watch'}, follow_redirects=True ) assert b"Watch added in Paused state, saving will unpause" in res.data options = { "url": test_url, "fetch_backend": "html_webdriver" if os.getenv('PLAYWRIGHT_DRIVER_URL') or os.getenv("WEBDRIVER_URL") else "html_requests", "proxy": "ui-0custom-test-proxy", "time_between_check_use_default": "y", } res = client.post( url_for("ui.ui_edit.edit_page", uuid="first", unpause_on_save=1), data=options, follow_redirects=True ) assert b"unpaused" in res.data import time wait_for_all_checks(client) # Requests default check_string = b'Cannot connect to proxy' if os.getenv('PLAYWRIGHT_DRIVER_URL') or strtobool(os.getenv('FAST_PUPPETEER_CHROME_FETCHER', 'False')) or os.getenv("WEBDRIVER_URL"): check_string = b'ERR_PROXY_CONNECTION_FAILED' res = client.get(url_for("watchlist.index")) #with open("/tmp/debug.html", 'wb') as f: # f.write(res.data) assert check_string in res.data
{ "repo_id": "dgtlmoon/changedetection.io", "file_path": "changedetectionio/tests/proxy_list/test_proxy_noconnect.py", "license": "Apache License 2.0", "lines": 55, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
django/django:django/contrib/admin/templatetags/admin_filters.py
from django import template from django.contrib.admin.options import EMPTY_VALUE_STRING from django.contrib.admin.utils import display_for_value from django.template.defaultfilters import stringfilter register = template.Library() @register.filter @stringfilter def to_object_display_value(value): return display_for_value(str(value), EMPTY_VALUE_STRING)
{ "repo_id": "django/django", "file_path": "django/contrib/admin/templatetags/admin_filters.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 9, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
django/django:tests/check_framework/urls/good_error_handler_deferred_annotations.py
from typing import TYPE_CHECKING if TYPE_CHECKING: from django.http.request import HttpRequest urlpatterns = [] handler400 = __name__ + ".good_handler_deferred_annotations" handler403 = __name__ + ".good_handler_deferred_annotations" handler404 = __name__ + ".good_handler_deferred_annotations" handler500 = __name__ + ".good_handler_deferred_annotations" def good_handler_deferred_annotations(request: HttpRequest, exception=None): pass
{ "repo_id": "django/django", "file_path": "tests/check_framework/urls/good_error_handler_deferred_annotations.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 10, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
django/django:scripts/check_migrations.py
import sys from pathlib import Path def main(): repo_root = Path(__file__).resolve().parent.parent sys.path[:0] = [str(repo_root / "tests"), str(repo_root)] from runtests import ALWAYS_INSTALLED_APPS, get_apps_to_install, get_test_modules import django from django.apps import apps from django.core.management import call_command django.setup() test_modules = list(get_test_modules(gis_enabled=False)) installed_apps = list(ALWAYS_INSTALLED_APPS) for app in get_apps_to_install(test_modules): # Check against the list to prevent duplicate errors. if app not in installed_apps: installed_apps.append(app) apps.set_installed_apps(installed_apps) # Note: We don't use check=True here because --check calls sys.exit(1) # instead of raising CommandError when migrations are missing. call_command("makemigrations", "--check", verbosity=3) if __name__ == "__main__": main()
{ "repo_id": "django/django", "file_path": "scripts/check_migrations.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 22, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
django/django:tests/backends/postgresql/test_features.py
import unittest from django.db import connection from django.test import TestCase @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL tests") class FeaturesTests(TestCase): def test_max_query_params_respects_server_side_params(self): if connection.features.uses_server_side_binding: limit = 2**16 - 1 else: limit = None self.assertEqual(connection.features.max_query_params, limit)
{ "repo_id": "django/django", "file_path": "tests/backends/postgresql/test_features.py", "license": "BSD 3-Clause \"New\" or \"Revised\" License", "lines": 11, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test