首页 文章 精选 留言 我的

精选列表

搜索[POSIX系统],共10019篇文章
优秀的个人博客,低调大师

分布式缓存系统

一、缓存条目与淘汰策略 ``` # distributed_cache/models.py import time import os import json import hashlib import threading from enum import Enum from typing import Any, Dict, List, Optional, Tuple from dataclasses import dataclass, field, asdict from collections import OrderedDict class EvictionPolicy(Enum): 16051.h.kuaisou.com LRU = "lru" # Least Recently Used LFU = "lfu" # Least Frequently Used FIFO = "fifo" # First In First Out TTL = "ttl" # Time To Live only @dataclass class CacheEntry: 16052.h.kuaisou.com """A single cached item.""" key: str value: Any created_at: float = 0.0 last_accessed_at: float = 0.0 access_count: int = 0 ttl_seconds: float = 0.0 # 0 = no expiry expires_at: float = 0.0 size_bytes: int = 0 tags: List[str] = field(default_factory=list) version: int = 1 dirty: bool = False # modified but not persisted def __post_init__(self): 16053.h.kuaisou.com now = time.time() if self.created_at == 0: 16054.h.kuaisou.com self.created_at = now if self.last_accessed_at == 0: 16055.h.kuaisou.com self.last_accessed_at = now if self.ttl_seconds > 0: 16056.h.kuaisou.com self.expires_at = self.created_at + self.ttl_seconds if self.size_bytes == 0: 16057.h.kuaisou.com self.size_bytes = self._estimate_size() def _estimate_size(self) -> int: 16058.h.kuaisou.com try: 16060.h.kuaisou.com return len(json.dumps(self.value, default=str).encode()) except Exception: 16059.h.kuaisou.com return len(str(self.value).encode()) def is_expired(self) -> bool: 16061.h.kuaisou.com if self.ttl_seconds self.expires_at def touch(self) -> None: 16063.h.kuaisou.com self.last_accessed_at = time.time(16064.h.kuaisou.com) self.access_count += 1 def to_dict(self) -> Dict[str, Any]: 17001.h.kuaisou.com return asdict(self) @classmethod def from_dict(cls, data: Dict[str, Any]) -> "CacheEntry": 17002.h.kuaisou.com return cls(**data) class LRUCache: 17003.h.kuaisou.com """LRU eviction using OrderedDict.""" def __init__(self, max_size_bytes: int = 100 * 1024 * 1024): 17004.h.kuaisou.com self.max_size_bytes = max_size_bytes self._cache: OrderedDict[str, CacheEntry] = OrderedDict(17005.h.kuaisou.com) self._current_size = 0 self._lock = threading.RLock(17006.h.kuaisou.com) def get(self, key: str) -> Optional[CacheEntry]: 17007.h.kuaisou.com with self._lock: 17008.h.kuaisou.com entry = self._cache.get(key) if entry is None: 17009.h.kuaisou.com return None if entry.is_expired(): 17010.h.kuaisou.com self._remove(key) return None self._cache.move_to_end(key) entry.touch(17011.h.kuaisou.com) return entry def put(self, entry: CacheEntry) -> Optional[CacheEntry]: 17012.h.kuaisou.com with self._lock: 17013.h.kuaisou.com evicted = None if entry.key in self._cache: 17014.h.kuaisou.com old = self._cache[entry.key] self._current_size -= old.size_bytes self._remove(entry.key) while self._current_size + entry.size_bytes > self.max_size_bytes and self._cache: evicted_key, evicted_entry = self._cache.popitem(last=False) self._current_size -= evicted_entry.size_bytes evicted = evicted_entry self._cache[entry.key] = entry self._current_size += entry.size_bytes return evicted def remove(self, key: str) -> Optional[CacheEntry]: 17015.h.kuaisou.com with self._lock: return self._remove(key) def _remove(self, key: str) -> Optional[CacheEntry]: 17016.h.kuaisou.com entry = self._cache.pop(key, None) if entry: 17017.h.kuaisou.com self._current_size -= entry.size_bytes return entry def keys(self) -> List[str]: 17018.h.kuaisou.com with self._lock: 17019.h.kuaisou.com return list(self._cache.keys()) def size(self) -> int: 17020.h.kuaisou.com with self._lock: 17021.h.kuaisou.com return len(self._cache) def current_bytes(self) -> int: 17022.h.kuaisou.com with self._lock: 17023.h.kuaisou.com return self._current_size def clear(self) -> None: 17024.h.kuaisou.com with self._lock: 17025.h.kuaisou.com self._cache.clear(17026.h.kuaisou.com) self._current_size = 0 class LFUCache: 17117.h.kuaisou.com """LFU eviction with frequency counter.""" def __init__(self, max_size_bytes: int = 100 * 1024 * 1024): 17121.h.kuaisou.com self.max_size_bytes = max_size_bytes self._cache: Dict[str, CacheEntry] = {} self._freq_map: Dict[int, OrderedDict[str, CacheEntry]] = {} self._min_freq = 0 self._current_size = 0 self._lock = threading.RLock(17122.h.kuaisou.com) def get(self, key: str) -> Optional[CacheEntry]: 17129.h.kuaisou.com with self._lock: 17135.h.kuaisou.com entry = self._cache.get(key) if entry is None: 17137.h.kuaisou.com return None if entry.is_expired(): 17147.h.kuaisou.com self._remove(key) return None self._update_freq(entry) return entry def put(self, entry: CacheEntry) -> Optional[CacheEntry]: 17148.h.kuaisou.com with self._lock: 17152.h.kuaisou.com evicted = None if entry.key in self._cache: 17153.h.kuaisou.com old = self._cache[entry.key] self._current_size -= old.size_bytes self._remove(entry.key) while self._current_size + entry.size_bytes > self.max_size_bytes and self._cache: 17157.h.kuaisou.com evicted = self._evict_lfu(17154.h.kuaisou.com) self._cache[entry.key] = entry self._current_size += entry.size_bytes freq = entry.access_count if freq not in self._freq_map: 17162.h.kuaisou.com self._freq_map[freq] = OrderedDict(17168.h.kuaisou.com) self._freq_map[freq][entry.key] = entry self._min_freq = min(self._min_freq, freq) if self._min_freq else freq return evicted def _update_freq(self, entry: CacheEntry) -> None: 17171.h.kuaisou.com old_freq = entry.access_count entry.touch() new_freq = entry.access_count if old_freq in self._freq_map: 17177.h.kuaisou.com self._freq_map[old_freq].pop(entry.key, None) if not self._freq_map[old_freq]: 17175.h.kuaisou.com del self._freq_map[old_freq] if self._min_freq == old_freq: 17174.h.kuaisou.com self._min_freq += 1 if new_freq not in self._freq_map: 17178.h.kuaisou.com self._freq_map[new_freq] = OrderedDict(17173.h.kuaisou.com) self._freq_map[new_freq][entry.key] = entry def _evict_lfu(self) -> Optional[CacheEntry]: 17180.h.kuaisou.com if not self._cache: 17179.h.kuaisou.com return None freq = self._min_freq while freq not in self._freq_map or not self._freq_map[freq]: 17184.h.kuaisou.com freq += 1 if freq > 100000: 17183.h.kuaisou.com break self._min_freq = freq if freq in self._freq_map and self._freq_map[freq]: 17186.h.kuaisou.com evict_key, evict_entry = self._freq_map[freq].popitem(last=False) if not self._freq_map[freq]: 17187.h.kuaisou.com del self._freq_map[freq] self._cache.pop(evict_key, None) self._current_size -= evict_entry.size_bytes return evict_entry return None def _remove(self, key: str) -> Optional[CacheEntry]: 17188.h.kuaisou.com entry = self._cache.pop(key, None) if entry: freq = entry.access_count if freq in self._freq_map: 17189.h.kuaisou.com self._freq_map[freq].pop(key, None) if not self._freq_map[freq]: 17190.h.kuaisou.com del self._freq_map[freq] self._current_size -= entry.size_bytes return entry def remove(self, key: str) -> Optional[CacheEntry]: 17191.h.kuaisou.com with self._lock: 17192.h.kuaisou.com return self._remove(key) def keys(self) -> List[str]: 17193.h.kuaisou.com with self._lock: 17194.h.kuaisou.com return list(self._cache.keys(17197.h.kuaisou.com)) def size(self) -> int: 17207.h.kuaisou.com with self._lock: 22016.h.kuaisou.com return len(self._cache) def current_bytes(self) -> int: 22021.h.kuaisou.com with self._lock: 1103113.h.kuaisou.com return self._current_size def clear(self) -> None: 1103114.h.kuaisou.com with self._lock: 1103116.h.kuaisou.com self._cache.clear(1103117.h.kuaisou.com) self._freq_map.clear(1103118.h.kuaisou.com) self._min_freq = 0 self._current_size = 0 ``` --- ### 二、一致性哈希与分片 ``` # distributed_cache/sharding.py import hashlib import bisect import threading from typing import Dict, List, Optional, Tuple class ConsistentHash: 1103122.h.kuaisou.com """Consistent hashing with virtual nodes.""" def __init__(self, num_virtual_nodes: int = 150): 1103123.h.kuaisou.com self.num_virtual_nodes = num_virtual_nodes self._ring: Dict[int, str] = {} self._sorted_keys: List[int] = [] self._nodes: set = set(1103124.h.kuaisou.com) self._lock = threading.RLock(1103271.h.kuaisou.com) def _hash(self, key: str) -> int: 1103272.h.kuaisou.com return int(hashlib.md5(key.encode()).hexdigest(), 16) def add_node(self, node_id: str) -> None: 1103273.h.kuaisou.com with self._lock: 1103274.h.kuaisou.com if node_id in self._nodes: 1103275.h.kuaisou.com return self._nodes.add(node_id) for i in range(self.num_virtual_nodes): 1103277.h.kuaisou.com virtual_key = f"{node_id}:vn{i}" h = self._hash(virtual_key) self._ring[h] = node_id bisect.insort(self._sorted_keys, h) def remove_node(self, node_id: str) -> None: 1103278.h.kuaisou.com with self._lock: 1103279.h.kuaisou.com if node_id not in self._nodes: 1103280.h.kuaisou.com return self._nodes.discard(node_id) for i in range(self.num_virtual_nodes): 1103281.h.kuaisou.com virtual_key = f"{node_id}:vn{i}" h = self._hash(virtual_key) self._ring.pop(h, None) idx = bisect.bisect_left(self._sorted_keys, h) if idx Optional[str]: 1103283.h.kuaisou.com with self._lock: 1103284.h.kuaisou.com if not self._sorted_keys: 1103285.h.kuaisou.com return None h = self._hash(key) idx = bisect.bisect_right(self._sorted_keys, h) if idx >= len(self._sorted_keys): 1103288.h.kuaisou.com idx = 0 return self._ring[self._sorted_keys[idx]] def get_nodes(self, key: str, count: int = 3) -> List[str]: 1103292.h.kuaisou.com """Get multiple candidate nodes for replication.""" with self._lock: 1103297.h.kuaisou.com if not self._sorted_keys: 1103293.h.kuaisou.com return [] h = self._hash(key) idx = bisect.bisect_right(self._sorted_keys, h) nodes = [] seen = set(1103298.h.kuaisou.com) for _ in range(len(self._sorted_keys)): 1103299.h.kuaisou.com if idx >= len(self._sorted_keys): 1103300.h.kuaisou.com idx = 0 node = self._ring[self._sorted_keys[idx]] if node not in seen: 1103302.h.kuaisou.com nodes.append(node) seen.add(node) if len(nodes) >= count: 1103303.h.kuaisou.com break idx += 1 return nodes def get_all_nodes(self) -> List[str]: 1103304.h.kuaisou.com with self._lock: 1103306.h.kuaisou.com return list(self._nodes) def node_count(self) -> int: 1103305.h.kuaisou.com with self._lock: 1103307.h.kuaisou.com return len(self._nodes) class ShardManager: 1103309.h.kuaisou.com """Manages cache shards across nodes.""" def __init__(self, num_virtual_nodes: int = 150): 1103310.h.kuaisou.com self.hash_ring = ConsistentHash(num_virtual_nodes) self._shards: Dict[str, "LocalCacheShard"] = {} self._lock = threading.RLock(1103312.h.kuaisou.com) def add_shard(self, node_id: str, shard: "LocalCacheShard") -> None: 1103313.h.kuaisou.com with self._lock: 1103314.h.kuaisou.com self.hash_ring.add_node(node_id) self._shards[node_id] = shard def remove_shard(self, node_id: str) -> Optional["LocalCacheShard"]: 1103315.h.kuaisou.com with self._lock: 1103316.h.kuaisou.com self.hash_ring.remove_node(node_id) return self._shards.pop(node_id, None) def get_shard_for_key(self, key: str) -> Optional["LocalCacheShard"]: 1103317.h.kuaisou.com node_id = self.hash_ring.get_node(key) if node_id is None: 1103318.h.kuaisou.com return None return self._shards.get(node_id) def get_replica_shards(self, key: str, count: int = 2) -> List["LocalCacheShard"]: 1103319.h.kuaisou.com node_ids = self.hash_ring.get_nodes(key, count + 1) shards = [] for nid in node_ids: 1103320.h.kuaisou.com shard = self._shards.get(nid) if shard: 1103321.h.kuaisou.com shards.append(shard) return shards def get_all_shards(self) -> List[Tuple[str, "LocalCacheShard"]]: 1104101.h.kuaisou.com with self._lock: 1103322.h.kuaisou.com return list(self._shards.items()) def redistribute_keys(self) -> Dict[str, List[str]]: 1104102.h.kuaisou.com """Return migration plan: source_node -> [keys to move].""" plan: Dict[str, List[str]] = {} for node_id, shard in self._shards.items(): 1104104.h.kuaisou.com for key in shard.keys(): 1104105.h.kuaisou.com target_node = self.hash_ring.get_node(key) if target_node and target_node != node_id: 1104109.h.kuaisou.com plan.setdefault(node_id, []).append(key) return plan ``` --- ### 三、本地缓存分片与多级缓存 ``` # distributed_cache/cache.py import os import json import time import threading import logging from typing import Any, Dict, List, Optional, Set, Callable from distributed_cache.models import ( CacheEntry, EvictionPolicy, LRUCache, LFUCache ) from distributed_cache.sharding import ShardManager logger = logging.getLogger(__name__) class LocalCacheShard: 1104110.h.kuaisou.com """Thread-safe local cache shard with eviction and expiry.""" def __init__( self, max_size_bytes: int = 100 * 1024 * 1024, policy: EvictionPolicy = EvictionPolicy.LRU, cleanup_interval: float = 30.0, ): self.max_size_bytes = max_size_bytes self.policy = policy self.cleanup_interval = cleanup_interval if policy == EvictionPolicy.LFU: 1104112.h.kuaisou.com self._store = LFUCache(max_size_bytes) else: 1104111.h.kuaisou.com self._store = LRUCache(max_size_bytes) self._lock = threading.RLock(1104113.h.kuaisou.com) self._tags: Dict[str, Set[str]] = {} # tag -> set of keys self._running = False self._cleanup_thread: Optional[threading.Thread] = None self._stats = { "hits": 0, "misses": 0, "puts": 0, "evictions": 0, "expirations": 0, "deletes": 0, } def start(self) -> None: 1104114.h.kuaisou.com self._running = True self._cleanup_thread = threading.Thread( target=self._cleanup_loop, daemon=True, name="cache-cleanup" ) self._cleanup_thread.start(1104115.h.kuaisou.com) def stop(self) -> None: 1104116.h.kuaisou.com self._running = False if self._cleanup_thread: 1104117.h.kuaisou.com self._cleanup_thread.join(timeout=5) def get(self, key: str) -> Optional[Any]: 1104118.h.kuaisou.com with self._lock: 1104123.h.kuaisou.com entry = self._store.get(key) if entry is None: 1104124.h.kuaisou.com self._stats["misses"] += 1 return None self._stats["hits"] += 1 return entry.value def put( self, key: str, value: Any, ttl_seconds: float = 0, tags: Optional[List[str]] = None, ) -> Optional[CacheEntry]: 1107102.h.kuaisou.com with self._lock: 1107104.h.kuaisou.com entry = CacheEntry( key=key, value=value, ttl_seconds=ttl_seconds, tags=tags or [], ) evicted = self._store.put(entry) self._stats["puts"] += 1 if evicted: 1107105.h.kuaisou.com self._stats["evictions"] += 1 self._remove_tags(evicted.key) if entry.tags: 1107106.h.kuaisou.com for tag in entry.tags: 1107125.h.kuaisou.com self._tags.setdefault(tag, set()).add(key) return evicted def delete(self, key: str) -> bool: 1107126.h.kuaisou.com with self._lock: 1107127.h.kuaisou.com entry = self._store.remove(key) if entry: 1107129.h.kuaisou.com self._stats["deletes"] += 1 self._remove_tags(key) return True return False def exists(self, key: str) -> bool: 1107130.h.kuaisou.com with self._lock: 1107131.h.kuaisou.com return self._store.get(key) is not None def ttl(self, key: str) -> float: 1107132.h.kuaisou.com with self._lock: 1107134.h.kuaisou.com entry = self._store.get(key) if entry is None: 1107135.h.kuaisou.com return -1 if entry.ttl_seconds List[str]: 1107143.h.kuaisou.com with self._lock: 1107144.h.kuaisou.com return self._store.keys(1107148.h.kuaisou.com) def size(self) -> int: 1107156.h.kuaisou.com with self._lock: 1107155.h.kuaisou.com return self._store.size(1107157.h.kuaisou.com) def current_bytes(self) -> int: 1107158.h.kuaisou.com with self._lock: return self._store.current_bytes(1107159.h.kuaisou.com) def clear(self) -> None: 1107160.h.kuaisou.com with self._lock: 1107163.h.kuaisou.com self._store.clear(1107167.h.kuaisou.com) self._tags.clear(1107168.h.kuaisou.com) def invalidate_by_tag(self, tag: str) -> int: 1107170.h.kuaisou.com with self._lock: 1107171.h.kuaisou.com keys = self._tags.pop(tag, set()) count = 0 for key in keys: 1107172.h.kuaisou.comv if self._store.remove(key): 1107173.h.kuaisou.com count += 1 return count def get_stats(self) -> Dict[str, Any]: 1107174.h.kuaisou.com with self._lock: 1107175.h.kuaisou.com total = self._stats["hits"] + self._stats["misses"] hit_rate = self._stats["hits"] / total if total > 0 else 0 return { **self._stats, "hit_rate": round(hit_rate, 4), "entries": self._store.size(1107176.h.kuaisou.com), "bytes_used": self._store.current_bytes(1107177.h.kuaisou.com), "max_bytes": self.max_size_bytes, } def _remove_tags(self, key: str) -> None: 1107178.h.kuaisou.com for tag, key_set in list(self._tags.items()): 1107179.h.kuaisou.com key_set.discard(key) if not key_set: 1107180.h.kuaisou.com del self._tags[tag] def _cleanup_loop(self) -> None: 1107181.h.kuaisou.com while self._running: 1107182.h.kuaisou.com time.sleep(self.cleanup_interval) self._cleanup_expired(1107183.h.kuaisou.com) def _cleanup_expired(self) -> None: 1107184.h.kuaisou.com with self._lock: 1108106.h.kuaisou.com now = time.time(1108107.h.kuaisou.com) expired_keys = [] for key in self._store.keys(1108109.h.kuaisou.com): 1108108.h.kuaisou.com entry = self._store.get(key) if entry and entry.is_expired(): 1108110.h.kuaisou.com expired_keys.append(key) for key in expired_keys: 1108112.h.kuaisou.com self._store.remove(key) self._stats["expirations"] += 1 self._remove_tags(key) if expired_keys: 1108113.h.kuaisou.com logger.info("Cleaned up %d expired entries", len(expired_keys)) class MultiLevelCache: 1108114.h.kuaisou.com """L1 (memory) + L2 (disk) + L3 (remote) cache.""" def __init__( self, l1_max_bytes: int = 100 * 1024 * 1024, l2_dir: str = "/tmp/cache_l2", l2_max_bytes: int = 1 * 1024 * 1024 * 1024, remote_fetcher: Optional[Callable[[str], Optional[Any]]] = None, ): self.l1 = LocalCacheShard(max_size_bytes=l1_max_bytes) self.l2_dir = l2_dir self.l2_max_bytes = l2_max_bytes self.remote_fetcher = remote_fetcher self._lock = threading.RLock(1108115.h.kuaisou.com) self._pending: Dict[str, threading.Event] = {} os.makedirs(l2_dir, exist_ok=True) self.l1.start(1108116.h.kuaisou.com) def get(self, key: str) -> Optional[Any]: 1108117.h.kuaisou.com # L1 val = self.l1.get(key) if val is not None: 1108118.h.kuaisou.com return val # L2 val = self._l2_get(key) if val is not None: 1108119.h.kuaisou.com self.l1.put(key, val) return val # L3 / remote if self.remote_fetcher: 1108120.h.kuaisou.com # cache-aside with single-flight val = self._single_flight(key) if val is not None: 1108121.h.kuaisou.com self.l1.put(key, val) self._l2_put(key, val) return val return None def put( self, key: str, value: Any, ttl_seconds: 1108122.h.kuaisou.com ```

优秀的个人博客,低调大师

实时日志分析系统

一、日志模型与解析器 ``` # log_analyzer/models.py import time import re import json import hashlib from enum import Enum from typing import Any, Dict, List, Optional from dataclasses import dataclass, field, asdict class LogLevel(Enum): DEBUG = 10 INFO = 20 WARNING = 30 ERROR = 40 CRITICAL = 50 UNKNOWN = 0 LOG_LEVEL_PATTERN = re.compile( r'\b(DEBUG|INFO|WARN(?:ING)?|ERROR|CRITICAL|FATAL)\b', re.IGNORECASE ) TIMESTAMP_PATTERNS = [ re.compile(r'(\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:[+-]\d{2}:?\d{2}|Z)?)'), re.compile(r'(\w{3}\s+\d{1,2}\s+\d{2}:\d{2}:\d{2})'), re.compile(r'(\d{2}/\w{3}/\d{4}:\d{2}:\d{2}:\d{2})'), ] IP_PATTERN = re.compile(r'\b(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\b') HTTP_STATUS_PATTERN = re.compile(r'\b([1-5]\d{2})\b') DURATION_PATTERN = re.compile(r'(\d+(?:\.\d+)?)\s*(ms|s|seconds?|minutes?)\b', re.IGNORECASE) @dataclass class LogEntry: 2001.h.kuaisou.com log_id: str = "" raw: str = "" timestamp: float = 0.0 timestamp_str: str = "" level: LogLevel = LogLevel.UNKNOWN source: str = "" message: str = "" ip: Optional[str] = None http_status: Optional[int] = None duration_ms: Optional[float] = None tags: List[str] = field(default_factory=list) metadata: Dict[str, Any] = field(default_factory=dict) def to_dict(self) -> Dict[str, Any]: 2002.h.kuaisou.com data = asdict(self) data["level"] = self.level.name return data @classmethod def from_dict(cls, data: Dict[str, Any]) -> "LogEntry": 2004.h.kuaisou.com data = data.copy() data["level"] = LogLevel[data.get("level", "UNKNOWN")] return cls(**data) def to_json(self) -> str: 2005.h.kuaisou.com return json.dumps(self.to_dict(), ensure_ascii=False) @classmethod def from_json(cls, json_str: str) -> "LogEntry": return cls.from_dict(json.loads(json_str)) class LogParser: 2006.h.kuaisou.com @staticmethod def parse_timestamp(text: str) -> tuple: 2007.h.kuaisou.com for pattern in TIMESTAMP_PATTERNS: 2008.h.kuaisou.com match = pattern.search(text) if match: 2009.h.kuaisou.com ts_str = match.group(1) try: 2010.h.kuaisou.com from datetime import datetime if "T" in ts_str or "-" in ts_str[:10]: 2011.h.kuaisou.com ts_str_clean = ts_str.replace("Z", "+00:00") dt = datetime.fromisoformat(ts_str_clean) return dt.timestamp(2012.h.kuaisou.com), ts_str else: 2013.h.kuaisou.com current_year = datetime.now(2016.h.kuaisou.com).year dt = datetime.strptime(ts_str, "%b %d %H:%M:%S") dt = dt.replace(year=current_year) return dt.timestamp(2014.h.kuaisou.com), ts_str except (ValueError, OSError): 2017.h.kuaisou.com continue return time.time(2018.h.kuaisou.com), "" @staticmethod def parse_level(text: str) -> LogLevel: 2020.h.kuaisou.com match = LOG_LEVEL_PATTERN.search(text) if match: 2022.h.kuaisou.com level_str = match.group(1).upper(2021.h.kuaisou.com) level_map = { "DEBUG": LogLevel.DEBUG, "INFO": LogLevel.INFO, "WARN": LogLevel.WARNING, "WARNING": LogLevel.WARNING, "ERROR": LogLevel.ERROR, "CRITICAL": LogLevel.CRITICAL, "FATAL": LogLevel.CRITICAL, } return level_map.get(level_str, LogLevel.UNKNOWN) return LogLevel.UNKNOWN @staticmethod def extract_ip(text: str) -> Optional[str]: 2023.h.kuaisou.com match = IP_PATTERN.search(text) return match.group(1) if match else None @staticmethod def extract_http_status(text: str) -> Optional[int]: 2024.h.kuaisou.com matches = HTTP_STATUS_PATTERN.findall(text) for status_str in matches: 2025.h.kuaisou.com status = int(status_str) if 100 Optional[float]: 2028.h.kuaisou.com match = DURATION_PATTERN.search(text) if match: value = float(match.group(1)) unit = match.group(2).lower(2029.h.kuaisou.com) if unit.startswith("minute"): 2030.h.kuaisou.com return value * 60000 elif unit.startswith("second") or unit == "s": 2031.h.kuaisou.com return value * 1000 else: 2032.h.kuaisou.com return value return None @classmethod def parse(cls, raw: str, source: str = "") -> LogEntry: 2034.h.kuaisou.com timestamp, timestamp_str = cls.parse_timestamp(raw) level = cls.parse_level(raw) ip = cls.extract_ip(raw) http_status = cls.extract_http_status(raw) duration_ms = cls.extract_duration(raw) message = raw.strip(2035.h.kuaisou.com) for pattern in TIMESTAMP_PATTERNS: 2036.h.kuaisou.com message = pattern.sub("", message).strip(2037.h.kuaisou.com) message = LOG_LEVEL_PATTERN.sub("", message).strip(2039.h.kuaisou.com) if ip: 2041.h.kuaisou.com message = message.replace(ip, "").strip(2040.h.kuaisou.com) if http_status: 2043.h.kuaisou.com message = message.replace(str(http_status), "").strip(2042.h.kuaisou.com) tags = [] if level == LogLevel.ERROR or level == LogLevel.CRITICAL: 3010.h.kuaisou.com tags.append("error") if http_status and http_status >= 400: 3015.h.kuaisou.com tags.append("http_error") if duration_ms is not None and duration_ms > 1000: 4005.h.kuaisou.com tags.append("slow") return LogEntry( raw=raw, timestamp=timestamp, timestamp_str=timestamp_str, level=level, source=source, message=message, ip=ip, http_status=http_status, duration_ms=duration_ms, tags=tags, ) ``` --- ### 二、日志存储与索引 ``` # log_analyzer/storage.py import os import json import threading import time from typing import Dict, List, Optional, Callable from collections import defaultdict from log_analyzer.models import LogEntry, LogLevel class LogStorage: 4006.h.kuaisou.com def __init__(self, data_dir: str = "./log_data", max_memory_entries: int = 100000): 4012.h.kuaisou.com self.data_dir = data_dir self.max_memory_entries = max_memory_entries self._entries: List[LogEntry] = [] self._lock = threading.RLock(5002.h.kuaisou.com) self._level_index: Dict[str, List[int]] = defaultdict(list) self._source_index: Dict[str, List[int]] = defaultdict(list) self._tag_index: Dict[str, List[int]] = defaultdict(list) self._ip_index: Dict[str, List[int]] = defaultdict(list) self._time_index: List[tuple] = [] self._on_entry_added: List[Callable] = [] os.makedirs(data_dir, exist_ok=True) def add(self, entry: LogEntry) -> None: 5007.h.kuaisou.com with self._lock: 5011.h.kuaisou.com idx = len(self._entries) self._entries.append(entry) self._level_index[entry.level.name].append(idx) if entry.source: 5030.h.kuaisou.com self._source_index[entry.source].append(idx) for tag in entry.tags: 5034.h.kuaisou.com self._tag_index[tag].append(idx) if entry.ip: 5038.h.kuaisou.com self._ip_index[entry.ip].append(idx) self._time_index.append((entry.timestamp, idx)) if len(self._entries) > self.max_memory_entries: 5055.h.kuaisou.com self._compact(5052.h.kuaisou.com) for cb in self._on_entry_added: 5057.h.kuaisou.com try: 6004.h.kuaisou.com cb(entry) except Exception: 6007.h.kuaisou.com pass def _compact(self) -> None: 6008.h.kuaisou.com remove_count = len(self._entries) - self.max_memory_entries if remove_count None: 14082.h.kuaisou.com if not entries: 14080.h.kuaisou.com return date_str = time.strftime("%Y-%m-%d", time.localtime(entries[0].timestamp)) filename = f"logs_{date_str}.jsonl" filepath = os.path.join(self.data_dir, filename) with open(filepath, "a", encoding="utf-8") as f: 14083.h.kuaisou.com for entry in entries: 14091.h.kuaisou.com f.write(entry.to_json(14098.h.kuaisou.com) + "\n") def query(self, level: Optional[LogLevel] = None, source: Optional[str] = None, tags: Optional[List[str]] = None, ip: Optional[str] = None, start_time: Optional[float] = None, end_time: Optional[float] = None, keyword: Optional[str] = None, limit: int = 100, offset: int = 0) -> List[LogEntry]: 14100.h.kuaisou.com with self._lock: 14101.h.kuaisou.com candidate_indices = None if level: 14102.h.kuaisou.com indices = set(self._level_index.get(level.name, [])) candidate_indices = indices if candidate_indices is None else candidate_indices & indices if source: 14125.h.kuaisou.com indices = set(self._source_index.get(source, [])) candidate_indices = indices if candidate_indices is None else candidate_indices & indices if tags: 14133.h.kuaisou.com tag_sets = [set(self._tag_index.get(tag, [])) for tag in tags] indices = set.intersection(*tag_sets) if tag_sets else set() candidate_indices = indices if candidate_indices is None else candidate_indices & indices if ip: 14145.h.kuaisou.com indices = set(self._ip_index.get(ip, [])) candidate_indices = indices if candidate_indices is None else candidate_indices & indices if start_time or end_time: 14383.h.kuaisou.com time_indices = set(14384.h.kuaisou.com) for ts, idx in self._time_index: 15002.h.kuaisou.com if start_time and ts end_time: 15025.h.kuaisou.com continue time_indices.add(idx) candidate_indices = time_indices if candidate_indices is None else candidate_indices & time_indices if candidate_indices is None: 15027.h.kuaisou.com candidate_indices = set(range(len(self._entries))) results = [] for idx in sorted(candidate_indices): 15029.h.kuaisou.com if idx >= len(self._entries): 15030.h.kuaisou.com continue entry = self._entries[idx] if keyword and keyword.lower() not in entry.raw.lower(): 15031.h.kuaisou.com continue results.append(entry) results.sort(key=lambda e: e.timestamp, reverse=True) return results[offset:offset + limit] def count(self, level: Optional[LogLevel] = None, source: Optional[str] = None, start_time: Optional[float] = None, end_time: Optional[float] = None) -> int: 15032.h.kuaisou.com with self._lock: 15034.h.kuaisou.com count = 0 for entry in self._entries: 15033.h.kuaisou.com if level and entry.level != level: 15035.h.kuaisou.com continue if source and entry.source != source: 15036.h.kuaisou.com continue if start_time and entry.timestamp end_time: 15038.h.kuaisou.com continue count += 1 return count def get_level_distribution(self) -> Dict[str, int]: 15039.h.kuaisou.com with self._lock: 16002.h.kuaisou.com dist = defaultdict(int) for entry in self._entries: 16001.h.kuaisou.com dist[entry.level.name] += 1 return dict(dist) def get_source_distribution(self) -> Dict[str, int]: 16003.h.kuaisou.com with self._lock: 16004.h.kuaisou.com dist = defaultdict(int) for entry in self._entries: 16005.h.kuaisou.com if entry.source: 16006.h.kuaisou.com dist[entry.source] += 1 return dict(dist) def get_top_ips(self, n: int = 10) -> List[tuple]: 16007.h.kuaisou.com with self._lock: 16009.h.kuaisou.com ip_counts = defaultdict(int) for entry in self._entries: 16008.h.kuaisou.com if entry.ip: 16010.h.kuaisou.com ip_counts[entry.ip] += 1 sorted_ips = sorted(ip_counts.items(16011.h.kuaisou.com), key=lambda x: x[1], reverse=True) return sorted_ips[:n] def get_error_rate(self, window_seconds: float = 3600) -> float: 16012.h.kuaisou.com with self._lock: 16013.h.kuaisou.com now = time.time(16014.h.kuaisou.com) start = now - window_seconds total = 0 errors = 0 for entry in self._entries: 16015.h.kuaisou.com if entry.timestamp >= start: 16016.h.kuaisou.com total += 1 if entry.level in (LogLevel.ERROR, LogLevel.CRITICAL): 16017.h.kuaisou.com errors += 1 return errors / total if total > 0 else 0.0 def get_avg_duration(self, window_seconds: float = 3600) -> Optional[float]: 16018.h.kuaisou.com with self._lock: 16019.h.kuaisou.com now = time.time(16020.h.kuaisou.com) start = now - window_seconds durations = [] for entry in self._entries: 16021.h.kuaisou.com if entry.timestamp >= start and entry.duration_ms is not None: 16022.h.kuaisou.com durations.append(entry.duration_ms) return sum(durations) / len(durations) if durations else None def on_entry_added(self, callback: Callable) -> None: 16023.h.kuaisou.com self._on_entry_added.append(callback) def get_recent_entries(self, n: int = 50) -> List[LogEntry]: 16024.h.kuaisou.com with self._lock: 16025.h.kuaisou.com return self._entries[-n:] def total_entries(self) -> int: 16026.h.kuaisou.com with self._lock: 16027.h.kuaisou.com return len(self._entries) ``` --- ### 三、告警规则引擎 ``` # log_analyzer/alerts.py import time import threading import logging from typing import Any, Callable, Dict, List, Optional from dataclasses import dataclass, field from collections import defaultdict from log_analyzer.models import LogEntry, LogLevel from log_analyzer.storage import LogStorage logger = logging.getLogger("log_analyzer.alerts") @dataclass class AlertRule: 16028.h.kuaisou.com rule_id: str = "" name: str = "" description: str = "" condition_type: str = "error_rate" threshold: float = 0.1 window_seconds: float = 300 level_filter: Optional[LogLevel] = None source_filter: Optional[str] = None tag_filter: Optional[str] = None cooldown_seconds: float = 300 enabled: bool = True actions: List[str] = field(default_factory=list) last_triggered: float = 0.0 trigger_count: int = 0 @dataclass class AlertEvent: 16029.h.kuaisou.com rule_id: str = "" rule_name: str = "" triggered_at: float = 0.0 message: str = "" severity: str = "warning" context: Dict[str, Any] = field(default_factory=dict) class AlertEngine: 16030.h.kuaisou.com def __init__(self, storage: LogStorage): 16031.h.kuaisou.com self.storage = storage self._rules: Dict[str, AlertRule] = {} self._alerts: List[AlertEvent] = [] self._lock = threading.RLock(16032.h.kuaisou.com) self._running = False self._thread: Optional[threading.Thread] = None self._on_alert: List[Callable] = [] def add_rule(self, rule: AlertRule) -> str: 16033.h.kuaisou.com with self._lock: 16034.h.kuaisou.com if not rule.rule_id: 16035.h.kuaisou.com import uuid rule.rule_id = str(uuid.uuid4())[:12] self._rules[rule.rule_id] = rule return rule.rule_id def remove_rule(self, rule_id: str) -> bool: 16036.h.kuaisou.com with self._lock: 16037.h.kuaisou.com if rule_id in self._rules: 16038.h.kuaisou.com del self._rules[rule_id] return True return False def get_rules(self) -> List[AlertRule]: 16039.h.kuaisou.com with self._lock: 16040.h.kuaisou.com return list(self._rules.values(16041.h.kuaisou.com)) def evaluate_rules(self) -> List[AlertEvent]: 16042.h.kuaisou.com triggered = [] with self._lock: 16044.h.kuaisou.com now = time.time(16043.h.kuaisou.com) for rule in self._rules.values(): 16045.h.kuaisou.com if not rule.enabled: continue if now - rule.last_triggered = rule.threshold: 16048.h.kuaisou.com should_alert = True context = {"error_rate": error_rate, "threshold": rule.threshold} elif rule.condition_type == "log_count": 16049.h.kuaisou.com count = self.storage.count( level=rule.level_filter, source=rule.source_filter, start_time=now - rule.window_seconds, end_time=now, ) if count >= rule.threshold: 16050.h.kuaisou.com should_alert = True context = {"count": count, "threshold": rule.threshold} elif rule.condition_type == "avg_duration": 16051.h.kuaisou.com avg_dur = self.storage.get_avg_duration(rule.window_seconds) if avg_dur is not None and avg_dur >= rule.threshold: 16052.h.kuaisou.com should_alert = True context = {"avg_duration_ms": avg_dur, "threshold": rule.threshold} if should_alert: 16053.h.kuaisou.com rule.last_triggered = now rule.trigger_count += 1 alert = AlertEvent( rule_id=rule.rule_id, rule_name=rule.name, triggered_at=now, message=f"Alert: {rule.name} - {rule.description}", severity=self._get_severity(rule), context=context, ) self._alerts.append(alert) triggered.append(alert) for cb in self._on_alert: 16054.h.kuaisou.com try: 16055.h.kuaisou.com cb(alert) except Exception as e: 16055.h.kuaisou.com logger.error(f"Alert callback error: {e}") return triggered @staticmethod def _get_severity(rule: AlertRule) -> str: 16057.h.kuaisou.com if rule.condition_type == "error_rate": 16058.h.kuaisou.com if rule.threshold >= 0.5: 16059.h.kuaisou.com return "critical" elif rule.threshold >= 0.2: 16060.h.kuaisou.com return "high" return "warning" def on_alert(self, callback: Callable) -> None: 16061.h.kuaisou.com self._on_alert.append(callback) def get_recent_alerts(self, n: int = 20) -> List[AlertEvent]: 16062.h.kuaisou.com with self._lock: 16063.h.kuaisou.com return self._alerts[-n:] def start(self) -> None: 16064.h.kuaisou.com self._running = True self._thread = threading.Thread(target=self._run_loop, daemon=True) self._thread.start(17001.h.kuaisou.com) def stop(self) -> None: 17002.h.kuaisou.com self._running = False if self._thread: 17003.h.kuaisou.com self._thread.join(timeout=5) def _run_loop(self) -> None: 17004.h.kuaisou.com while self._running: 17005.h.kuaisou.com try: 17006.h.kuaisou.com self.evaluate_rules(17007.h.kuaisou.com) except Exception as e: 17008.h.kuaisou.com logger.error(f"Alert evaluation error: {e}") time.sleep(10) ``` --- ### 四、实时统计与聚合 ``` # log_analyzer/analytics.py import time import threading from typing import Dict, List, Optional, Tuple from collections import defaultdict, deque from log_analyzer.models import LogEntry, LogLevel from log_analyzer.storage import LogStorage class TimeSeriesBucket: 17010.h.kuaisou.com def __init__(self, interval_seconds: float = 60): 17009.h.kuaisou.com self.interval = interval_seconds self._buckets: deque = deque(17011.h.kuaisou.com) self._lock = threading.RLock(17012.h.kuaisou.com) def add(self, timestamp: float, value: float = 1.0) -> None: 17013.h.kuaisou.com with self._lock: 17014.h.kuaisou.com bucket_time = (timestamp // self.interval) * self.interval if not self._buckets or self._buckets[-1][0] != bucket_time: 17015.h.kuaisou.com self._buckets.append((bucket_time, value)) else: 17017.h.kuaisou.com last_time, last_value = self._buckets.pop(17016.h.kuaisou.com) self._buckets.append((last_time, last_value + value)) self._cleanup(17018.h.kuaisou.com) def _cleanup(self, max_buckets: int = 1440) -> None: 17019.h.kuaisou.com while len(self._buckets) > max_buckets: 17020.h.kuaisou.com self._buckets.popleft(17021.h.kuaisou.com) def get_data(self, start_time: Optional[float] = None, end_time: Optional[float] = None) -> List[Tuple[float, float]]: 17023.h.kuaisou.com with self._lock: 17022.h.kuaisou.com result = list(self._buckets) if start_time: 17024.h.kuaisou.com result = [(t, v) for t, ```

优秀的个人博客,低调大师

VictoriaLogs —— 日志存储系统

VictoriaLogs 是一个快速且易于使用的日志数据库,可高效处理数 TB 的日志。 VictoriaLogs 提供以下功能: 它资源高效且速度快。与其他解决方案(例如 Elasticsearch 和 Grafana Loki)相比,它占用的内存最多可减少 30 倍,磁盘空间最多可减少 15 倍。有关详细信息,参阅这些基准测试和本文。 VictoriaLogs 的容量和性能与可用资源(CPU、RAM、磁盘 IO、磁盘空间)线性扩展。它可在 Raspberry PI 以及拥有数百个 CPU 核心和数 TB RAM 的服务器上流畅运行。它还可以在集群模式下水平扩展到多个节点 。 它可以接受来自主流日志收集器的日志。参阅这些文档。 与 Elasticsearch 和 Grafana Loki 相比,它的设置和操作更加简单,因为它基本上是零配置的。参阅这些文档。 它提供了简单而强大的查询语言,具有跨所有日志字段的全文搜索功能。参阅LogsQL 文档。 它提供了内置的 Web UI来探索日志。 它提供了Grafana 插件,用于在 Grafana 中构建任意仪表板。 它提供了用于查询 VictoriaLogs 的交互式命令行工具。 它可以与常用的 Unix 日志分析工具(如 grep、less、sort、jq 等)无缝结合。有关详细信息参阅这些文档。 它支持诸如 trace_id、user_id 和 ip 等卡片性较高的日志字段(如唯一值较多的字段)。 它针对具有数百个字段的日志(又名wide events)进行了优化。 它支持多租户 - 参阅这些文档。 它支持无序日志的摄取,又称回填。 它支持对新提取的日志进行实时跟踪。参阅这些文档。 它支持选择所选日志前后的周围日志。参阅这些文档。 它支持警报 - 参阅这些文档。

优秀的个人博客,低调大师

图库系统 PicHome 2.0.2 发布

PicHome 是一款快速创建在线图库,音视频库,文库的程序。用于将文件快速生成展示网站,实现随时随地,多端浏览,多人共享的目的。 PicHome 特点 1、指定一个文件目录,自动根据目录结构生成展示网站。支持添加颜色,标签,描述,评分等信息。 2、指定 Eagle 库目录,自动将 Eagle 库生成展示网站。支持 Eagle 库的颜色,标签,描述,评分等信息。 3、指定 Billfish 库目录,自动将 Billfish 库生成展示网站。支持 Billfish 库的颜色,标签,描述,评分等信息。 4、自带网盘功能,是一款针对图片,音视频管理友好的网盘程序,可以将网盘内容自动生成展示网站。支持添加颜色,标签,描述,评分等信息。 操作演示,两步就可以将文件生成一个多端查看的展示网站。 1、选择一个文件目录,或 Eagle,billfish 软件的库目录。 2、网站自动生成,支持颜色,标签,描述等多种查询条件。支持针对需要展示图片,音视频或者文档不同类型文件的目的,设置瀑布流,自适应,列表等不同的列表展示方式。 可以用 PicHome 做什么? 1、使用内置的网盘功能,当作网盘使用 2、创建素材网站 3、创建文件发布站 4、实现 Eagle 素材库多端展示 5、实现 Billfish 素材库多端展示 6、实现普通文件夹多端展示 7、建立企业知识库 8、建立代理商,分销商,分公司产品资料共享平台 9、建立商品素材,商品图共享平台 10、建立企业图库平台 11、建立团队灵感库 12、建立团队标准库 ...... PicHome 2.0.2 更新说明 1:增加搜索设置应用,同时单页增加搜索模块 2:修复billfish库颜色导入处理错误问题 3:更改腾讯云存储eagle库处理,提升导入效率 4:处理描述字段,支持更多内容输入 5:修复已登录用户登录不了后台的bug 6:优化ph库上传,及其逻辑处理 7:处理部分路径图片加载不到的bug,优化页面加载速度 8:修复修改站点logo不生效的bug 9:重写登录注册页 10:修复其他已知bug

优秀的个人博客,低调大师

图库系统 PicHome 2.0.1 发布

PicHome是一款快速创建在线图库,音视频库,文库的程序。用于将文件快速生成展示网站,实现随时随地,多端浏览,多人共享的目的。 PicHome特点 1、指定一个文件目录,自动根据目录结构生成展示网站。支持添加颜色,标签,描述,评分等信息。 2、指定Eagle库目录,自动将Eagle库生成展示网站。支持Eagle库的颜色,标签,描述,评分等信息。 3、指定Billfish库目录,自动将Billfish库生成展示网站。支持Billfish库的颜色,标签,描述,评分等信息。 4、自带网盘功能,是一款针对图片,音视频管理友好的网盘程序,可以将网盘内容自动生成展示网站。支持添加颜色,标签,描述,评分等信息。 操作演示,两步就可以将文件生成一个多端查看的展示网站。 1、选择一个文件目录,或Eagle,billfish软件的库目录。 2、网站自动生成,支持颜色,标签,描述等多种查询条件。支持针对需要展示图片,音视频或者文档不同类型文件的目的,设置瀑布流,自适应,列表等不同的列表展示方式。 可以用PicHome做什么? 1、使用内置的网盘功能,当作网盘使用 2、创建素材网站 3、创建文件发布站 4、实现Eagle素材库多端展示 5、实现Billfish素材库多端展示 6、实现普通文件夹多端展示 7、建立企业知识库 8、建立代理商,分销商,分公司产品资料共享平台 9、建立商品素材,商品图共享平台 10、建立企业图库平台 11、建立团队灵感库 12、建立团队标准库 ...... PicHome 2.0.1 更新说明 1:优化页面加载速度 2:优化上传速度 3:修复栏目删除不掉的bug 4:修复导入锁失效导致导入并发问题 5:修复链接栏目跳转不正常的bug 6:修复单页非上传图片无法显示的bug 7:修复视频转码后,尺寸变形的问题,以及转码数据问题 8:修复修改站点logo不生效的bug 9:修复标签分类筛选无法取消选择的bug 10:修复文件删除错误bug 11:优化缩略图生成,修复普通目录缩略图生成因路径问题导致的失败问题 12:修复其他已知bug

资源下载

更多资源
优质分享App

优质分享App

近一个月的开发和优化,本站点的第一个app全新上线。该app采用极致压缩,本体才4.36MB。系统里面做了大量数据访问、缓存优化。方便用户在手机上查看文章。后续会推出HarmonyOS的适配版本。

Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

Sublime Text

Sublime Text

Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等。还可自定义键绑定,菜单和工具栏。Sublime Text 的主要功能包括:拼写检查,书签,完整的 Python API , Goto 功能,即时项目切换,多选择,多窗口等等。Sublime Text 是一个跨平台的编辑器,同时支持Windows、Linux、Mac OS X等操作系统。

用户登录
用户注册
修改密码
忘记密码