diff --git a/src/LibreQoS.py b/src/LibreQoS.py index 37a6ce5b..f3d03c8a 100755 --- a/src/LibreQoS.py +++ b/src/LibreQoS.py @@ -27,7 +27,8 @@ from liblqos_python import is_lqosd_alive, clear_ip_mappings, delete_ip_mapping, interface_a, interface_b, enable_actual_shell_commands, use_bin_packing_to_balance_cpu, monitor_mode_only, \ run_shell_commands_as_sudo, generated_pn_download_mbps, generated_pn_upload_mbps, queues_available_override, \ on_a_stick, get_tree_weights, get_weights, is_network_flat, get_libreqos_directory, enable_insight_topology, \ - fast_queues_fq_codel, \ + fast_queues_fq_codel, hash_to_i64, fetch_planner_remote, store_planner_remote, \ + read_planner_cbor, write_planner_cbor, \ Bakery # Optional: urgent issue submission (available in newer liblqos_python) @@ -37,6 +38,338 @@ except Exception: def submit_urgent_issue(*_args, **_kwargs): return False +# Optional: check if Insight is enabled (available in newer liblqos_python) +try: + from liblqos_python import is_insight_enabled # type: ignore +except Exception: + def is_insight_enabled(*_args, **_kwargs): + return False + +class Planner: + """ + Planner: lightweight state manager to reduce churn between runs. + + PUBLIC methods: + - getState(): dict — current planner state (default or loaded) + - persist(): None — save the planner state to planner.cbor + """ + + # Print the Insight planning banner only once per process + _insight_banner_printed = False + + def __init__(self, queuesAvailable: int, onAStick: bool, siteNamesSet, siteCount: int): + self.path = os.path.join(get_libreqos_directory(), 'planner.cbor') + now_ts = time.time() + + # Informational banner when Insight-enhanced planning is in use + try: + if is_insight_enabled() and not Planner._insight_banner_printed: + logging.info("Using Insight enhanced planning (remote planner state enabled).") + Planner._insight_banner_printed = True + except Exception: + pass + + loaded = self._load_state(queuesAvailable, onAStick, siteCount) + # Normalize site names by hashing to i64 for storage (no strings retained) + normalized_site_names = [] + try: + normalized_site_names = sorted([int(hash_to_i64(str(x))) for x in list(siteNamesSet)]) + except Exception: + normalized_site_names = [] + + self._is_default = False + if loaded is None: + # Missing/invalid state: default + self.state = self._default_state(normalized_site_names, siteCount, queuesAvailable, onAStick, now_ts) + self._is_default = True + return + + # Validate loaded state and decide if we should rebuild + should_rebuild, _reason = self._should_rebuild( + loaded, normalized_site_names, siteCount, queuesAvailable, onAStick, now_ts + ) + if should_rebuild: + self.state = self._default_state(normalized_site_names, siteCount, queuesAvailable, onAStick, now_ts) + self._is_default = True + else: + # Accept loaded state, convert legacy string keys to hashed if needed, rebuild ephemeral fields, and update dynamic fields + st = dict(loaded) + st['updated_at'] = now_ts + # Convert site_names (list) to hashed ints if necessary + try: + raw_names = st.get('site_names', []) + hashed = [] + for x in raw_names: + try: + hashed.append(int(x)) + except Exception: + hashed.append(int(hash_to_i64(str(x)))) + st['site_names'] = sorted(list(set(hashed))) + except Exception: + st['site_names'] = [] + # Convert site_map keys to ints (hash) when possible + try: + sm0 = st.get('site_map') if isinstance(st, dict) else None + sm: dict = {} + if isinstance(sm0, dict): + for k, v in sm0.items(): + try: + key_int = int(k) + except Exception: + key_int = int(hash_to_i64(str(k))) + sm[key_int] = v + st['site_map'] = sm + except Exception: + st['site_map'] = {} + # Convert circuit_map keys to ints (hash) when possible + try: + cm0 = st.get('circuit_map') if isinstance(st, dict) else None + cm: dict = {} + if isinstance(cm0, dict): + for k, v in cm0.items(): + try: + key_int = int(k) + except Exception: + key_int = int(hash_to_i64(str(k))) + cm[key_int] = v + st['circuit_map'] = cm + except Exception: + st['circuit_map'] = {} + # Rebuild free_minors from hashed maps + try: + q = int(st.get('queuesAvailable', 0)) + sm = st.get('site_map') if isinstance(st, dict) else None + cm = st.get('circuit_map') if isinstance(st, dict) else None + st['free_minors'] = self._rebuild_free_minors(q, sm if isinstance(sm, dict) else {}, cm if isinstance(cm, dict) else {}) + except Exception: + st['free_minors'] = [[] for _ in range(int(st.get('queuesAvailable', 0)))] + self.state = st + self._is_default = False + + + def getState(self): + return self.state + + def persist(self): + """Persist planner state. + + - When Insight is enabled, persists remotely via `store_planner_remote`. + - Otherwise, writes a local compressed CBOR file at `planner.cbor`. + - Ephemeral fields such as `free_minors` are never persisted. + """ + try: + to_save = dict(self.state) + if 'free_minors' in to_save: + try: + to_save.pop('free_minors') + except Exception: + pass + # Prefer Insight when enabled; otherwise persist to local CBOR for stability + use_remote = False + try: + use_remote = bool(is_insight_enabled()) + except Exception: + use_remote = False + if use_remote: + store_planner_remote(to_save) + else: + # Best-effort local persistence to planner.cbor + try: + write_planner_cbor(self.path, to_save) + except Exception as e: + warnings.warn(f"Failed to write planner.cbor locally: {e}", stacklevel=2) + except Exception as e: + warnings.warn(f"Failed to write planner.cbor: {e}", stacklevel=2) + + def _default_state(self, site_names_sorted, site_count, queues_available, on_a_stick_flag, now_ts): + """Build a default planner state. + + Notes + - Minor IDs 1..3 are globally reserved: + 1 = root qdisc, 2 = default class, 3 = site classes + - Circuits and any ephemeral classes use 4+. + - `free_minors` is per-CPU and rebuilt on load; it is not persisted. + """ + try: + # Reserve minors 1..3 globally: + # - 1 is used by root qdisc + # - 2 is used by the default class under root + # - 3 is used for site classes + # Circuits and any ephemeral classes must use 4+ + free_minors = [list(range(4, 0x10000)) for _ in range(int(queues_available))] + except Exception: + free_minors = [] + return { + 'algo_version': 'v1', + 'updated_at': float(now_ts), + 'queuesAvailable': int(queues_available), + 'on_a_stick': bool(on_a_stick_flag), + 'site_count': int(site_count), + 'site_names': list(site_names_sorted), # list of i64 hashes + 'site_map': {}, # site_hash(i64) -> { cpu:int, major:int, minor:int } + 'circuit_map': {}, # circuit_hash(i64) -> { cpu:int, minor:int } + 'free_minors': free_minors, # ephemeral: rebuilt on load; not persisted to disk + } + + def _load_state(self, queues_available, on_a_stick_flag, site_count): + """Load planner state. + + - If Insight is enabled, fetch from remote; otherwise load local CBOR. + - Validates that minimum required keys exist. + - Normalizes `updated_at` when remote to avoid needless rebuilds based on age alone. + """ + try: + # Try Insight first if enabled; otherwise fall back to local CBOR + use_remote = False + try: + use_remote = bool(is_insight_enabled()) + except Exception: + use_remote = False + if use_remote: + try: + data = fetch_planner_remote(int(queues_available), bool(on_a_stick_flag), int(site_count)) + if isinstance(data, dict): + for k in ['queuesAvailable', 'site_count', 'site_names']: + if k not in data: + return None + # Normalize dynamic fields for rebuild check + try: + data['updated_at'] = float(time.time()) + except Exception: + pass + return data + except Exception: + pass + return None + else: + try: + data = read_planner_cbor(self.path) + if isinstance(data, dict): + for k in ['queuesAvailable', 'site_count', 'site_names']: + if k not in data: + return None + return data + except Exception: + pass + return None + except Exception: + return None + + def _rebuild_free_minors(self, queues_available, site_map, circuit_map): + """ + Recompute free_minors per CPU from persisted mappings. + - Start with full range [4..0xFFFF] for each CPU (1..3 reserved) + - Remove any minors referenced by site_map or circuit_map on the corresponding CPU + Returns: list[list[int]] sized by queues_available + """ + try: + q = max(0, int(queues_available)) + except Exception: + q = 0 + # See rationale above; reserve minors 1..3. + free = [set(range(4, 0x10000)) for _ in range(q)] + # Remove site minors + try: + for name, entry in site_map.items(): + try: + cpu = int(entry.get('cpu', -1)) + minor = int(entry.get('minor', -1)) + if 0 <= cpu < q and 3 <= minor <= 0xFFFF: + if minor in free[cpu]: + free[cpu].discard(minor) + except Exception: + continue + except Exception: + pass + # Remove circuit minors + try: + for cid, entry in circuit_map.items(): + try: + cpu = int(entry.get('cpu', -1)) + minor = int(entry.get('minor', -1)) + if 0 <= cpu < q and 3 <= minor <= 0xFFFF: + if minor in free[cpu]: + free[cpu].discard(minor) + except Exception: + continue + except Exception: + pass + # Convert to sorted lists + return [sorted(list(s)) for s in free] + + def _should_rebuild(self, loaded, site_names_sorted, site_count, queues_available, on_a_stick_flag, now_ts): + # Age check + try: + updated_at = float(loaded.get('updated_at', 0.0)) + except Exception: + updated_at = 0.0 + # Consider planner state stale only after 7 days to avoid churn when + # remote planner objects are otherwise valid but old. + if (float(now_ts) - updated_at) > (7 * 24 * 3600): + return True, 'stale_planner_state' + + # queuesAvailable change + try: + if int(loaded.get('queuesAvailable', -1)) != int(queues_available): + return True, 'queues_available_changed' + except Exception: + return True, 'queues_available_invalid' + + # on-a-stick changed + try: + if bool(loaded.get('on_a_stick', False)) != bool(on_a_stick_flag): + return True, 'on_a_stick_changed' + except Exception: + return True, 'on_a_stick_invalid' + + # Site count changed + try: + if int(loaded.get('site_count', -1)) != int(site_count): + return True, 'site_count_changed' + except Exception: + return True, 'site_count_invalid' + + # Site set changed (order ignored). Compare hashed ints + try: + raw_loaded = loaded.get('site_names', []) + loaded_sites = set() + for x in raw_loaded: + try: + loaded_sites.add(int(x)) + except Exception: + loaded_sites.add(int(hash_to_i64(str(x)))) + current_sites = set([int(x) for x in site_names_sorted]) + if loaded_sites != current_sites: + return True, 'site_names_changed' + except Exception: + return True, 'site_names_invalid' + + return False, None + +def _greedy_binpack(items, bin_ids, capacities): + """ + Simple greedy binpacking without state: + - items: list of dicts with keys 'id' and 'weight' + - bin_ids: list of bin identifiers + - capacities: dict mapping bin_id -> capacity (float) + Returns: dict mapping item_id -> bin_id + """ + # Normalize inputs + cap = {str(b): float(capacities.get(b, 1.0)) for b in bin_ids} + loads = {str(b): 0.0 for b in bin_ids} + # Sort items: heavier first, deterministic by id + sorted_items = sorted( + [(str(it.get('id')), float(it.get('weight', 1.0))) for it in items], + key=lambda t: (-t[1], t[0]) + ) + assignment = {} + for it_id, w in sorted_items: + # Choose the bin with lowest load/cap ratio; tie-breaker: lexicographic bin id + best_bin = min(bin_ids, key=lambda b: (loads[str(b)]/max(cap[str(b)], 1e-9), str(b))) + assignment[it_id] = str(best_bin) + loads[str(best_bin)] += w + return assignment + R2Q = 10 #MAX_R2Q = 200_000 MAX_R2Q = 60_000 # See https://lartc.vger.kernel.narkive.com/NKaH1ZNG/htb-quantum-of-class-100001-is-small-consider-r2q-change @@ -390,6 +723,12 @@ def loadSubscriberCircuits(shapedDevicesFile): knownCircuitIDs = [] counterForCircuitsWithoutParentNodes = 0 dictForCircuitsWithoutParentNodes = {} + # If the network is flat, treat any explicit parent_site in CSV as 'none' + # so circuits are assigned to Generated_PN_* bins automatically when switching to flat. + try: + flat_mode_csv = bool(is_network_flat()) + except Exception: + flat_mode_csv = False with open(shapedDevicesFile) as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') # Remove comments if any @@ -413,6 +752,18 @@ def loadSubscriberCircuits(shapedDevicesFile): token = left + '/' + right sqm_override_token = token circuitID, circuitName, deviceID, deviceName, ParentNode, mac, ipv4_input, ipv6_input, downloadMin, uploadMin, downloadMax, uploadMax, comment = row[0:13] + # In flat mode, override any non-empty, non-Generated_PN_* ParentNode to 'none' + try: + if flat_mode_csv: + pn = (ParentNode or '').strip() + pn_lower = pn.lower() + if (pn != '' + and pn_lower != 'none' + and not pn.startswith('Generated_PN_') + and not pn_lower.startswith('generated_pn_')): + ParentNode = 'none' + except Exception: + pass # If in monitorOnlyMode, override bandwidth rates to where no shaping will actually occur if monitor_mode_only() == True: downloadMin = 10000 @@ -630,6 +981,12 @@ def refreshShapers(): upstream_bandwidth_capacity_upload_mbps(), ) + # Detect flat mode once for reuse in traversal (network.json contains only implicit Root) + try: + flat_mode = bool(is_network_flat()) + except Exception: + flat_mode = False + # Pull rx/tx queues / CPU cores available # Handling the case when the number of queues for interfaces are different @@ -653,6 +1010,46 @@ def refreshShapers(): data[elem]['uploadBandwidthMbpsMin'] = 100000 overrideNetworkBandwidths(network) + # Initialize planner (state is read/validated here; behavior not yet changed) + try: + # Use the same notion of "sites" that Planner persists to site_map: + # - For tiered networks, these are depth-1 nodes (children of top-level nodes) + # - For flat networks, fallback to top-level keys (Generated_PN_* are created later) + def collect_site_names_tiered(n): + """Collect depth-1 site names for tiered networks. + + Falls back to top-level keys when no children are present. + Returns a set of string site names. + """ + names = set() + try: + for k, v in n.items(): + if not isinstance(v, dict): + continue + ch = v.get('children') + if isinstance(ch, dict): + names.update(str(ck) for ck in ch.keys()) + except Exception: + names = set() + if not names: + try: + names = {str(k) for k, v in n.items() if isinstance(v, dict)} + except Exception: + names = set() + return names + + current_site_names = set() + try: + if isinstance(network, dict): + current_site_names = collect_site_names_tiered(network) if not flat_mode else set( + [str(k) for k, v in network.items() if isinstance(v, dict)] + ) + except Exception: + current_site_names = set() + planner = Planner(queuesAvailable, on_a_stick(), current_site_names, len(current_site_names)) + except Exception as e: + warnings.warn(f"Planner initialization failed: {e}", stacklevel=2) + # Generate Parent Nodes. Spread ShapedDevices.csv which lack defined ParentNode across these (balance across CPUs) print("Generating parent nodes") generatedPNs = [] @@ -672,132 +1069,99 @@ def refreshShapers(): } generatedPNs.append(genPNname) if use_bin_packing_to_balance_cpu(): - print("Using internal planner to sort circuits by CPU core") - # Build item list with weights for circuits lacking a ParentNode - items = [] - try: - weights = get_weights() - except Exception as e: - warnings.warn("get_weights() failed; defaulting to equal weights (" + str(e) + ")", stacklevel=2) - weights = None - weight_by_circuit_id = {} - if weights is not None: + if is_insight_enabled(): + print("Using greedy binpacking to sort circuits by CPU core") + # Build item list with weights for circuits lacking a ParentNode + items = [] try: - for w in weights: - weight_by_circuit_id[str(w.circuit_id)] = float(w.weight) - except Exception: - pass - for circuit in subscriberCircuits: - if circuit.get('ParentNode') == 'none' and 'idForCircuitsWithoutParentNodes' in circuit: - item_id = circuit['idForCircuitsWithoutParentNodes'] - # Prefer provided weights; default to 1.0 - w = dictForCircuitsWithoutParentNodes.get(item_id, 1.0) - # If a specific circuit weight exists, prefer it - if 'circuitID' in circuit and str(circuit['circuitID']) in weight_by_circuit_id: - w = weight_by_circuit_id[str(circuit['circuitID'])] - # Ignore placeholder default rates for weight purposes + weights = get_weights() + except Exception as e: + warnings.warn("get_weights() failed; defaulting to equal weights (" + str(e) + ")", stacklevel=2) + weights = None + weight_by_circuit_id = {} + if weights is not None: try: - default_rate = float(generated_pn_download_mbps()) - max_dl = float(circuit.get('maxDownload', 0)) - if abs(max_dl - default_rate) < 1e-6: - w = 0.0 + for w in weights: + weight_by_circuit_id[str(w.circuit_id)] = float(w.weight) except Exception: pass - items.append({"id": item_id, "weight": float(w)}) + for circuit in subscriberCircuits: + # Treat blank or 'none' (any case) as unassigned parent in flat mode handling + pn_val = str(circuit.get('ParentNode', '')).strip().lower() + if (pn_val in ('', 'none')) and ('idForCircuitsWithoutParentNodes' in circuit): + item_id = circuit['idForCircuitsWithoutParentNodes'] + # Prefer provided weights; default to 1.0 + w = dictForCircuitsWithoutParentNodes.get(item_id, 1.0) + # If a specific circuit weight exists, prefer it + if 'circuitID' in circuit and str(circuit['circuitID']) in weight_by_circuit_id: + w = weight_by_circuit_id[str(circuit['circuitID'])] + # Ignore placeholder default rates for weight purposes + try: + default_rate = float(generated_pn_download_mbps()) + max_dl = float(circuit.get('maxDownload', 0)) + if abs(max_dl - default_rate) < 1e-6: + w = 0.0 + except Exception: + pass + items.append({"id": item_id, "weight": float(w)}) - # Prepare bins and capacities - bins_list = [{"id": pn} for pn in generatedPNs] - capacities = {pn: 1.0 for pn in generatedPNs} + # Prepare capacities (equal split by default) + capacities = {pn: 1.0 for pn in generatedPNs} - # Load planner state - try: - import bin_planner - except ImportError: - bin_planner = None - # Store planner state directly in lqos_directory (no hidden subdirs) - state_path = os.path.join(get_libreqos_directory(), "planner_state.json") - state = {} - if bin_planner is not None: - state = bin_planner.load_state(state_path) - now_ts = time.time() - prev_assign = {} - last_change_ts = {} - if isinstance(state, dict): - prev_assign = state.get("assignments", {}) or {} - last_change_ts = state.get("last_change_ts", {}) or {} - # Filter previous assignments to only items/bins in this context - item_ids = {str(it["id"]) for it in items} - valid_bins = set(capacities.keys()) - prev_assign = {iid: b for iid, b in prev_assign.items() if iid in item_ids and b in valid_bins} - last_change_ts = {iid: last_change_ts.get(iid, 0.0) for iid in item_ids} - - # Planner parameters - params = { - "candidate_set_size": 4, - "headroom": 0.05, - "alpha": 0.1, - "hysteresis_threshold": 0.03, - "cooldown_seconds": 3600, - "move_budget_per_run": max(1, min(32, int(0.01 * max(1, len(items))))), - "salt": state.get("salt", "default_salt") if isinstance(state, dict) else "default_salt", - "last_change_ts_by_item": last_change_ts, - } - if monitor_mode_only() == True: - params["move_budget_per_run"] = 0 + # Compute greedy assignments and apply + assignments = _greedy_binpack(items, generatedPNs, capacities) + for circuit in subscriberCircuits: + pn_val = str(circuit.get('ParentNode', '')).strip().lower() + if (pn_val in ('', 'none')) and ('idForCircuitsWithoutParentNodes' in circuit): + item_id = circuit['idForCircuitsWithoutParentNodes'] + if item_id in assignments: + circuit['ParentNode'] = assignments[item_id] - if bin_planner is not None: - assignments, changed = bin_planner.plan_assignments( - items, bins_list, capacities, prev_assign, now_ts, params - ) + print("Finished binpacking generated parent nodes") else: - # Fallback to simple greedy if planner unavailable - bin_loads = {pn: 0.0 for pn in generatedPNs} - pairs = [(str(it["id"]), float(it["weight"])) for it in items] - pairs.sort(key=lambda iw: (-iw[1], str(iw[0]))) - assignments = {} - for item_id, w in pairs: - target_pn = min(bin_loads.items(), key=lambda kv: (kv[1], kv[0]))[0] - assignments[item_id] = target_pn - bin_loads[target_pn] += w - changed = list(assignments.keys()) - - # Apply assignments to circuits - for circuit in subscriberCircuits: - if circuit.get('ParentNode') == 'none' and 'idForCircuitsWithoutParentNodes' in circuit: - item_id = circuit['idForCircuitsWithoutParentNodes'] - if item_id in assignments: - circuit['ParentNode'] = assignments[item_id] - - # Update and save state - if bin_planner is not None and isinstance(state, dict): - if state.get("salt") is None: - state["salt"] = "default_salt" - if "assignments" not in state or not isinstance(state["assignments"], dict): - state["assignments"] = {} - if "last_change_ts" not in state or not isinstance(state["last_change_ts"], dict): - state["last_change_ts"] = {} - for iid, b in assignments.items(): - # record last change time if changed - if iid in changed: - state["last_change_ts"][iid] = now_ts - state["assignments"][iid] = b + warn_msg = "Binpacking is enabled, but requires an Insight subscription." + print("Warning: " + warn_msg) try: - print(f"Saving planner state to {state_path} (generated PNs)") - bin_planner.save_state(state_path, state) - except Exception as e: - warnings.warn(f"Failed to save planner state at {state_path}: {e}", stacklevel=2) - - print("Finished planning generated parent nodes") + submit_urgent_issue("LibreQoS", "Warning", "BINPACKING_REQUIRES_INSIGHT", warn_msg, "{}", "BINPACKING_REQUIRES_INSIGHT_PARENT_NODES") + except Exception: + pass + # Fallback: round-robin assignment when Insight is not enabled + genPNcounter = 0 + for circuit in subscriberCircuits: + pn_val = str(circuit.get('ParentNode', '')).strip().lower() + if pn_val in ('', 'none'): + circuit['ParentNode'] = generatedPNs[genPNcounter] + genPNcounter += 1 + if genPNcounter >= queuesAvailable: + genPNcounter = 0 else: genPNcounter = 0 for circuit in subscriberCircuits: - if circuit['ParentNode'] == 'none': + pn_val = str(circuit.get('ParentNode', '')).strip().lower() + if pn_val in ('', 'none'): circuit['ParentNode'] = generatedPNs[genPNcounter] genPNcounter += 1 if genPNcounter >= queuesAvailable: genPNcounter = 0 print("Generated parent nodes created") + # Safety pass: ensure every circuit has a valid ParentNode key present in the current network + try: + available_nodes = set([str(k) for k in network.keys()]) if isinstance(network, dict) else set() + except Exception: + available_nodes = set() + if len(available_nodes) > 0 and len(generatedPNs) > 0: + rr = 0 + for circuit in subscriberCircuits: + try: + pn_raw = str(circuit.get('ParentNode', '')).strip() + pn_lower = pn_raw.lower() + if pn_raw == '' or pn_lower == 'none' or pn_raw not in available_nodes: + circuit['ParentNode'] = generatedPNs[rr] + rr = (rr + 1) % len(generatedPNs) + except Exception: + pass + # Find the bandwidth minimums for each node by combining mimimums of devices lower in that node's hierarchy def findBandwidthMins(data, depth): tabs = ' ' * depth @@ -884,6 +1248,26 @@ def refreshShapers(): ensure_min_less_than_max(network) + # Populate transient site speeds for planner reuse (not persisted) + try: + if 'planner' in locals() and isinstance(planner, Planner): + speeds = {} + if isinstance(network, dict): + for key, val in network.items(): + if isinstance(val, dict): + try: + speeds[str(key)] = { + 'dl_max': float(val.get('downloadBandwidthMbps', 0)), + 'ul_max': float(val.get('uploadBandwidthMbps', 0)), + 'dl_min': float(val.get('downloadBandwidthMbpsMin', val.get('downloadBandwidthMbps', 0))), + 'ul_min': float(val.get('uploadBandwidthMbpsMin', val.get('uploadBandwidthMbps', 0))), + } + except Exception: + pass + planner._site_speeds = speeds + except Exception: + pass + # Compress network.json. HTB only supports 8 levels of HTB depth. Compress to 8 layers if beyond 8. def flattenB(data): newDict = {} @@ -916,18 +1300,19 @@ def refreshShapers(): return newDict network = flattenA(network, 1) - # Prepare planner weights (actual weighting may come from Insight or CSV defaults) + # Prepare planner weights only when Insight is enabled; otherwise avoid LTS chatter weight_by_circuit_id = {} - try: - weights = get_weights() - for w in weights: - try: - weight_by_circuit_id[str(w.circuit_id)] = float(w.weight) - except Exception: - pass - except Exception: - # If we can't get weights, leave mapping empty; UI will fall back - weight_by_circuit_id = {} + if is_insight_enabled(): + try: + weights = get_weights() + for w in weights: + try: + weight_by_circuit_id[str(w.circuit_id)] = float(w.weight) + except Exception: + pass + except Exception: + # If we can't get weights, leave mapping empty; UI will fall back + weight_by_circuit_id = {} # Group circuits by parent node. Reduces runtime for section below this one. circuits_by_parent_node = {} @@ -950,7 +1335,10 @@ def refreshShapers(): # Parse network structure and add devices from ShapedDevices.csv print("Parsing network structure and tallying devices") parentNodes = [] + site_insert_counter = 0 minorByCPUpreloaded = {} + node_refs = {} + circuits_start_minor = {} knownClassIDs = [] nodes_requiring_min_squashing = {} # Track minor counter by CPU. This way we can have > 32000 hosts (htb has u16 limit to minor handle) @@ -960,6 +1348,7 @@ def refreshShapers(): for x in range(queuesAvailable): minorByCPUpreloaded[x+1] = 3 def traverseNetwork(data, depth, major, minorByCPU, queue, parentClassID, upParentClassID, parentMaxDL, parentMaxUL, parentMinDL, parentMinUL): + nonlocal site_insert_counter # ClassID Assignment Strategy: # - Nodes and circuits are processed in alphabetical order for stability # - Each node gets a unique minor number that increments sequentially @@ -990,9 +1379,52 @@ def refreshShapers(): # data[node]['up_cpuNum'] = hex(queue-1+stickOffset) # traverseNetwork(data[node]['children'], depth, major, minorByCPU, queue, parentClassID, upParentClassID, parentMaxDL, parentMaxUL) # continue - circuitsForThisNetworkNode = [] - nodeClassID = hex(major) + ':' + hex(minorByCPU[queue]) - upNodeClassID = hex(major+stickOffset) + ':' + hex(minorByCPU[queue]) + # Prefer reusing previously-assigned site minor from planner.site_map (keyed by hashed site name); + # else try planner free_minors for this CPU; else fallback to sequential counter + chosen_minor = None + try: + if ('planner' in locals() or 'planner' in globals()) and isinstance(planner, Planner) and (not getattr(planner, '_is_default', False)): + st = planner.getState() + cpu_index = int(queue - 1) + # 1) Attempt reuse from site_map when CPU/major match + try: + site_map = st.get('site_map') if isinstance(st, dict) else None + if isinstance(site_map, dict): + key_hash = int(hash_to_i64(str(node))) + entry = site_map.get(key_hash) + if isinstance(entry, dict): + saved_cpu = int(entry.get('cpu', -1)) + saved_major = int(entry.get('major', -1)) + saved_minor = int(entry.get('minor', -1)) + if saved_cpu == cpu_index and saved_major == int(major) and saved_minor >= 3: + chosen_minor = saved_minor + # Remove from free list if present + try: + fm = st.get('free_minors') + if isinstance(fm, list) and 0 <= cpu_index < len(fm) and isinstance(fm[cpu_index], list) and saved_minor in fm[cpu_index]: + fm[cpu_index].remove(saved_minor) + except Exception: + pass + except Exception: + pass + # 2) If no reuse, allocate from free list for this CPU (depth >= 1 only) + if chosen_minor is None and depth >= 1: + try: + fm = st.get('free_minors') if isinstance(st, dict) else None + if isinstance(fm, list) and 0 <= cpu_index < len(fm) and isinstance(fm[cpu_index], list) and len(fm[cpu_index]) > 0: + chosen_minor = int(fm[cpu_index].pop(0)) + except Exception: + chosen_minor = None + except Exception: + chosen_minor = None + if chosen_minor is None: + try: + chosen_minor = int(minorByCPU[queue]) + except Exception: + chosen_minor = 3 + + nodeClassID = hex(major) + ':' + hex(chosen_minor) + upNodeClassID = hex(major+stickOffset) + ':' + hex(chosen_minor) data[node]['classid'] = nodeClassID data[node]['up_classid'] = upNodeClassID if depth == 0: @@ -1016,9 +1448,49 @@ def refreshShapers(): # Calculations are done in findBandwidthMins() to determine optimal HTB rates (mins) and ceils (maxs) data[node]['classMajor'] = hex(major) data[node]['up_classMajor'] = hex(major + stickOffset) - data[node]['classMinor'] = hex(minorByCPU[queue]) + data[node]['classMinor'] = hex(chosen_minor) data[node]['cpuNum'] = hex(queue-1) data[node]['up_cpuNum'] = hex(queue-1+stickOffset) + # Index node by name for later circuit attachment + try: + node_refs[str(node)] = data[node] + except Exception: + pass + + # Notify planner of site details where applicable (insert-only) + try: + if ('planner' in locals() or 'planner' in globals()) and isinstance(planner, Planner): + name_s = str(node) + synthetic = (not flat_mode) and (name_s.startswith('Generated_PN_') or name_s.startswith('CpueQueue')) + # Capture site mapping for non-synthetic nodes at depth 0/1 (tiered), + # or depth 0 in flat mode. + if (not synthetic) and ((depth in (0, 1)) or (flat_mode and depth == 0)): + st = planner.getState() + if 'site_map' not in st or not isinstance(st['site_map'], dict): + st['site_map'] = {} + # Store as integers for ease of later use + cpu_int = int(queue - 1) + major_int = int(major) + minor_int = int(chosen_minor) + site_key = int(hash_to_i64(str(node))) + st['site_map'][site_key] = { + 'cpu': cpu_int, + 'major': major_int, + 'minor': minor_int, + 'insertion_order': int(site_insert_counter), + } + site_insert_counter += 1 + # Remove the site's minor from the planner's free list for this CPU + try: + fm = st.get('free_minors') + if isinstance(fm, list) and 0 <= cpu_int < len(fm) and isinstance(fm[cpu_int], list): + if int(minor_int) in fm[cpu_int]: + fm[cpu_int].remove(int(minor_int)) + except Exception: + pass + except Exception: + # Planner is optional; ignore errors during capture + pass thisParentNode = { "parentNodeName": node, "classID": nodeClassID, @@ -1037,9 +1509,10 @@ def refreshShapers(): except Exception: pass raise ValueError(f"Minor class ID overflow on CPU {queue}: {minorByCPU[queue]} exceeds limit of 65535") - # If a device from ShapedDevices.csv lists this node as its Parent Node, attach it as a leaf to this node HTB + # If a device from ShapedDevices.csv lists this node as its Parent Node, + # record starting minor and reserve enough minors to keep classid sequence stable. if node in circuits_by_parent_node: - # If mins of circuits combined exceed min of parent node - set to 1 + # Determine if we need to squash mins at TC time (record only) override_min_down = None override_min_up = None if monitor_mode_only() == False: @@ -1050,79 +1523,13 @@ def refreshShapers(): if ((override_min_down * len(circuits_by_parent_node[node])) > data[node]['downloadBandwidthMbpsMin']) or ((override_min_up * len(circuits_by_parent_node[node])) > data[node]['uploadBandwidthMbpsMin']): logging.info("Even with this change, minimums will exceed the min rate of the parent node. Using 10 kbps as the minimum for these circuits instead.", stacklevel=2) nodes_requiring_min_squashing[node] = True - # Sort circuits by name for stable ordering - sorted_circuits = sorted(circuits_by_parent_node[node], - key=lambda c: c.get('circuitName', c.get('circuitID', ''))) - for circuit in sorted_circuits: - if node == circuit['ParentNode']: - if monitor_mode_only() == False: - if circuit['maxDownload'] > data[node]['downloadBandwidthMbps']: - logging.info("downloadMax of Circuit ID [" + circuit['circuitID'] + "] exceeded that of its parent node. Reducing to that of its parent node now.", stacklevel=2) - if circuit['maxUpload'] > data[node]['uploadBandwidthMbps']: - logging.info("uploadMax of Circuit ID [" + circuit['circuitID'] + "] exceeded that of its parent node. Reducing to that of its parent node now.", stacklevel=2) - parentString = hex(major) + ':' - flowIDstring = hex(major) + ':' + hex(minorByCPU[queue]) - upFlowIDstring = hex(major + stickOffset) + ':' + hex(minorByCPU[queue]) - circuit['classid'] = flowIDstring - circuit['up_classid'] = upFlowIDstring - logging.info("Added up_classid to circuit: " + circuit['up_classid']) - # Create circuit dictionary to be added to network structure, eventually output as queuingStructure.json - maxDownload = min(circuit['maxDownload'],data[node]['downloadBandwidthMbps']) - maxUpload = min(circuit['maxUpload'],data[node]['uploadBandwidthMbps']) - if override_min_down: - circuit['minDownload'] = 1 - if override_min_up: - circuit['minUpload'] = 1 - minDownload = min(circuit['minDownload'],maxDownload) - minUpload = min(circuit['minUpload'],maxUpload) - thisNewCircuitItemForNetwork = { - 'maxDownload' : maxDownload, - 'maxUpload' : maxUpload, - 'minDownload' : minDownload, - 'minUpload' : minUpload, - "circuitID": circuit['circuitID'], - "circuitName": circuit['circuitName'], - "ParentNode": circuit['ParentNode'], - "devices": circuit['devices'], - "classid": flowIDstring, - "up_classid" : upFlowIDstring, - "classMajor": hex(major), - "up_classMajor" : hex(major + stickOffset), - "classMinor": hex(minorByCPU[queue]), - "comment": circuit['comment'] - } - # Attach the planner weight used by the planner/UI summary - # Priority: explicit weight -> fallback to maxDownload - try: - cid = str(circuit.get('circuitID','')) - w = None - if cid in weight_by_circuit_id: - w = float(weight_by_circuit_id[cid]) - if w is None: - w = float(maxDownload) - # Treat 1000 as a sentinel default from Insight; use maxDownload instead - if abs(w - 1000.0) < 1e-6: - w = float(maxDownload) - # If the circuit's configured rate equals the generated PN default, - # ignore it for weight purposes. - try: - default_rate = float(generated_pn_download_mbps()) - if abs(float(maxDownload) - default_rate) < 1e-6: - w = 0.0 - except Exception: - pass - thisNewCircuitItemForNetwork['planner_weight'] = w - except Exception: - pass - # Preserve optional per-circuit SQM override for downstream bakery call - if 'sqm' in circuit and circuit['sqm']: - thisNewCircuitItemForNetwork['sqm'] = circuit['sqm'] - # Generate TC commands to be executed later - thisNewCircuitItemForNetwork['devices'] = circuit['devices'] - circuitsForThisNetworkNode.append(thisNewCircuitItemForNetwork) - minorByCPU[queue] = minorByCPU[queue] + 1 - if len(circuitsForThisNetworkNode) > 0: - data[node]['circuits'] = circuitsForThisNetworkNode + # Record starting minor for circuits under this node + circuits_start_minor[str(node)] = int(minorByCPU[queue]) + # Increment minor counter by number of circuits to keep classid allocation stable + try: + minorByCPU[queue] = minorByCPU[queue] + len(circuits_by_parent_node[node]) + except Exception: + pass # Add padding for future circuit additions (applies to all nodes) # This ensures space is reserved even for nodes without circuits @@ -1157,125 +1564,398 @@ def refreshShapers(): # If we're in binpacking mode, we need to sort the network structure a bit if use_bin_packing_to_balance_cpu() and not is_network_flat(): - print("Planner is enabled, so we're going to sort your network across CPU queues.") - # Build items from top-level nodes with weights - items = [] - try: - weights = get_tree_weights() - except Exception as e: - warnings.warn("get_tree_weights() failed; defaulting to equal weights (" + str(e) + ")", stacklevel=2) - weights = None - weight_by_name = {} - if weights is not None: + if not is_insight_enabled(): + warn_msg2 = "Binpacking is enabled, but requires an Insight subscription." + print("Warning: " + warn_msg2) try: - for w in weights: - weight_by_name[str(w.name)] = float(w.weight) + submit_urgent_issue("LibreQoS", "Warning", "BINPACKING_REQUIRES_INSIGHT", warn_msg2, "{}", "BINPACKING_REQUIRES_INSIGHT_SITE_DISTRIBUTION") except Exception: pass - for node in network: - w = weight_by_name.get(str(node), 1.0) - items.append({"id": str(node), "weight": float(w)}) + else: + # Decide reuse vs greedy + reuse_planner = False + try: + if 'planner' in locals() and isinstance(planner, Planner): + st = planner.getState() + if isinstance(st, dict) and isinstance(st.get('site_map', None), dict) and (not getattr(planner, '_is_default', False)): + reuse_planner = True + except Exception: + reuse_planner = False + + if reuse_planner: + print("Rebuilding CPU bins from planner map (stable).") + cpu_keys = ["CpueQueue" + str(cpu) for cpu in range(queuesAvailable)] + binnedNetwork = {} + for cpu in range(queuesAvailable): + cpuKey = "CpueQueue" + str(cpu) + binnedNetwork[cpuKey] = { + 'downloadBandwidthMbps': generated_pn_download_mbps(), + 'uploadBandwidthMbps': generated_pn_upload_mbps(), + 'type': 'site', + 'downloadBandwidthMbpsMin': generated_pn_download_mbps(), + 'uploadBandwidthMbpsMin': generated_pn_upload_mbps(), + 'children': {}, + 'name': cpuKey + } + # Build name->node map from current (flattened) network + def map_all_nodes(data, out): + if isinstance(data, dict): + for key, val in data.items(): + if key == 'children': + continue + if isinstance(val, dict): + try: + out[str(key)] = val + except Exception: + pass + if 'children' in val and isinstance(val['children'], dict): + map_all_nodes(val['children'], out) + all_nodes = {} + map_all_nodes(network, all_nodes) + # Hash map for current names + name_hash_to_name = {} + try: + for nm in list(all_nodes.keys()): + try: + name_hash_to_name[int(hash_to_i64(str(nm)))] = str(nm) + except Exception: + pass + except Exception: + pass + # Group sites by CPU and order by insertion_order + st = planner.getState() + cpu_to_sites = {cpu: [] for cpu in range(queuesAvailable)} + for name, entry in st['site_map'].items(): + try: + cpu = int(entry.get('cpu', 0)) + ins = int(entry.get('insertion_order', 0)) + # name may be hashed int or legacy string; coerce to hash int + try: + name_hash = int(name) + except Exception: + name_hash = int(hash_to_i64(str(name))) + cpu_to_sites.setdefault(cpu, []).append((ins, name_hash)) + except Exception: + pass + for cpu, lst in cpu_to_sites.items(): + lst.sort(key=lambda t: t[0]) + cpuKey = "CpueQueue" + str(cpu) + for _, site_hash in lst: + site_name = name_hash_to_name.get(int(site_hash)) + if site_name is None: + continue + node_obj = all_nodes.get(site_name) + if node_obj is None: + continue + # Ensure speeds reflect current network.json + try: + speeds = getattr(planner, '_site_speeds', {}).get(site_name) + if isinstance(speeds, dict): + node_obj['downloadBandwidthMbps'] = speeds.get('dl_max', node_obj.get('downloadBandwidthMbps')) + node_obj['uploadBandwidthMbps'] = speeds.get('ul_max', node_obj.get('uploadBandwidthMbps')) + node_obj['downloadBandwidthMbpsMin'] = speeds.get('dl_min', node_obj.get('downloadBandwidthMbpsMin', node_obj.get('downloadBandwidthMbps'))) + node_obj['uploadBandwidthMbpsMin'] = speeds.get('ul_min', node_obj.get('uploadBandwidthMbpsMin', node_obj.get('uploadBandwidthMbps'))) + except Exception: + pass + binnedNetwork[cpuKey]['children'][site_name] = node_obj + network = binnedNetwork + else: + print("Using greedy binpacking to distribute sites across CPU queues.") + # Build items from top-level nodes with weights + items = [] + try: + weights = get_tree_weights() + except Exception as e: + warnings.warn("get_tree_weights() failed; defaulting to equal weights (" + str(e) + ")", stacklevel=2) + weights = None + weight_by_name = {} + if weights is not None: + try: + for w in weights: + weight_by_name[str(w.name)] = float(w.weight) + except Exception: + pass + for node in network: + w = weight_by_name.get(str(node), 1.0) + items.append({"id": str(node), "weight": float(w)}) + + # Prepare bins and capacities + cpu_keys = ["CpueQueue" + str(cpu) for cpu in range(queuesAvailable)] + capacities = {key: 1.0 for key in cpu_keys} + + # Greedy assignment of sites to CPU bins + assignment = _greedy_binpack(items, cpu_keys, capacities) + for x in range(queuesAvailable): + key = "CpueQueue" + str(x) + assigned = [name for name, tgt in assignment.items() if tgt == key] + print("Bin " + str(x) + " = ", assigned) + + # Build the binned network structure + binnedNetwork = {} + for cpu in range(queuesAvailable): + cpuKey = "CpueQueue" + str(cpu) + binnedNetwork[cpuKey] = { + 'downloadBandwidthMbps': generated_pn_download_mbps(), + 'uploadBandwidthMbps': generated_pn_upload_mbps(), + 'type': 'site', + 'downloadBandwidthMbpsMin': generated_pn_download_mbps(), + 'uploadBandwidthMbpsMin': generated_pn_upload_mbps(), + 'children': {}, + 'name': cpuKey + } + for node in network: + tgt = assignment.get(node) + if tgt is None: + tgt = "CpueQueue" + str(queuesAvailable - 1) + binnedNetwork[tgt]['children'][node] = network[node] + network = binnedNetwork - # Prepare bins and capacities - cpu_keys = ["CpueQueue" + str(cpu) for cpu in range(queuesAvailable)] - bins_list = [{"id": key} for key in cpu_keys] - capacities = {key: 1.0 for key in cpu_keys} + # Here is the actual call to the recursive traverseNetwork() function. finalMinor is not used. + minorByCPU = traverseNetwork(network, 0, major=1, minorByCPU=minorByCPUpreloaded, queue=1, parentClassID=None, upParentClassID=None, parentMaxDL=upstream_bandwidth_capacity_download_mbps(), parentMaxUL=upstream_bandwidth_capacity_upload_mbps(), parentMinDL=upstream_bandwidth_capacity_download_mbps(), parentMinUL=upstream_bandwidth_capacity_upload_mbps()) - # Load planner state + # Hoisted pass: attach circuits to built site tree using reserved minors + # Prepare a stale set of prior circuits to detect removals + stale_circuits = set() + try: + if 'planner' in locals() and isinstance(planner, Planner): + st0 = planner.getState() + cmap = st0.get('circuit_map') if isinstance(st0, dict) else None + if isinstance(cmap, dict): + # Keep keys as stored (may be ints or legacy strings) + stale_circuits = set(cmap.keys()) + except Exception: + stale_circuits = set() + for node_name, circuit_list in circuits_by_parent_node.items(): + if node_name not in node_refs: + continue + node = node_refs[node_name] + # Determine major/cpu try: - import bin_planner - except ImportError: - bin_planner = None - # Store planner state directly in lqos_directory (no hidden subdirs) - state_path = os.path.join(get_libreqos_directory(), "planner_state.json") - state = {} - if bin_planner is not None: - state = bin_planner.load_state(state_path) - now_ts = time.time() - prev_assign = {} - last_change_ts = {} - if isinstance(state, dict): - prev_assign = state.get("assignments", {}) or {} - last_change_ts = state.get("last_change_ts", {}) or {} - item_ids = {str(it["id"]) for it in items} - valid_bins = set(capacities.keys()) - prev_assign = {iid: b for iid, b in prev_assign.items() if iid in item_ids and b in valid_bins} - last_change_ts = {iid: last_change_ts.get(iid, 0.0) for iid in item_ids} - - params = { - "candidate_set_size": 4, - "headroom": 0.05, - "alpha": 0.1, - "hysteresis_threshold": 0.03, - "cooldown_seconds": 3600, - "move_budget_per_run": max(1, min(32, int(0.01 * max(1, len(items))))), - "salt": state.get("salt", "default_salt") if isinstance(state, dict) else "default_salt", - "last_change_ts_by_item": last_change_ts, - } - if monitor_mode_only() == True: - params["move_budget_per_run"] = 0 - - if bin_planner is not None: - assignment, changed = bin_planner.plan_assignments( - items, bins_list, capacities, prev_assign, now_ts, params - ) - else: - # Fallback to simple greedy if planner unavailable - bin_loads = {key: 0.0 for key in cpu_keys} - pairs = [(str(it["id"]), float(it["weight"])) for it in items] - pairs.sort(key=lambda nw: (-nw[1], nw[0])) - assignment = {} - for name, w in pairs: - target = min(bin_loads.items(), key=lambda kv: (kv[1], kv[0]))[0] - assignment[name] = target - bin_loads[target] += w - changed = list(assignment.keys()) - - for x in range(queuesAvailable): - key = "CpueQueue" + str(x) - assigned = [name for name, tgt in assignment.items() if tgt == key] - print("Bin " + str(x) + " = ", assigned) - - # Build the binned network structure - binnedNetwork = {} - for cpu in range(queuesAvailable): - cpuKey = "CpueQueue" + str(cpu) - binnedNetwork[cpuKey] = { - 'downloadBandwidthMbps': generated_pn_download_mbps(), - 'uploadBandwidthMbps': generated_pn_upload_mbps(), - 'type': 'site', - 'downloadBandwidthMbpsMin': generated_pn_download_mbps(), - 'uploadBandwidthMbpsMin': generated_pn_upload_mbps(), - 'children': {}, - 'name': cpuKey + major_int = int(node.get('classMajor', '0x0'), 16) + except Exception: + major_int = 0 + try: + if node_name in circuits_start_minor: + start_minor = int(circuits_start_minor.get(node_name)) + else: + # Fallback: never start circuits at the site's own minor; advance by at least +1 + site_minor = int(node.get('classMinor', '0x0'), 16) + start_minor = max(4, site_minor + 1) + except Exception: + start_minor = 4 + # Precompute override flags (same logic as before) + override_min_down = None + override_min_up = None + if monitor_mode_only() == False: + try: + if (circuit_min_down_combined_by_parent_node[node_name] > node['downloadBandwidthMbpsMin']) or (circuit_min_up_combined_by_parent_node[node_name] > node['uploadBandwidthMbpsMin']): + override_min_down = 1 + override_min_up = 1 + except Exception: + pass + # Sort circuits by name for stable ordering + sorted_circuits = sorted(circuit_list, key=lambda c: c.get('circuitName', c.get('circuitID', ''))) + circuits_for_node = [] + current_minor = start_minor + # Planner reuse toggle for circuits + use_planner_circuits = False + st = {} + cpu_int = 0 + try: + if 'planner' in locals() and isinstance(planner, Planner) and (not getattr(planner, '_is_default', False)): + st = planner.getState() + use_planner_circuits = isinstance(st, dict) and isinstance(st.get('circuit_map', None), dict) + except Exception: + use_planner_circuits = False + # CPU index for this node (from hex string) + try: + cpu_int = int(node.get('cpuNum', '0x0'), 16) + except Exception: + cpu_int = 0 + for circuit in sorted_circuits: + if node_name != circuit.get('ParentNode'): + continue + # Mark as present this run (not stale) + try: + cid_raw = circuit.get('circuitID', '') + # Discard both hashed and string forms to be robust across versions + try: + stale_circuits.discard(int(hash_to_i64(str(cid_raw)))) + except Exception: + pass + try: + stale_circuits.discard(str(cid_raw)) + except Exception: + pass + except Exception: + pass + # Bound to parent's maxima + maxDownload = min(circuit['maxDownload'], node['downloadBandwidthMbps']) + maxUpload = min(circuit['maxUpload'], node['uploadBandwidthMbps']) + # Apply override min=1 if needed (further squashing to 0.01 happens at TC emission) + if override_min_down: + circuit['minDownload'] = 1 + if override_min_up: + circuit['minUpload'] = 1 + minDownload = min(circuit['minDownload'], maxDownload) + minUpload = min(circuit['minUpload'], maxUpload) + # Choose minor: reuse from planner if available, else take from free list, else fall back to sequential + chosen_minor = None + if use_planner_circuits: + try: + cid_raw = circuit['circuitID'] + entry = None + # Prefer hashed lookup + try: + entry = st['circuit_map'].get(int(hash_to_i64(str(cid_raw)))) + except Exception: + entry = None + if entry is None: + # Fallback to legacy string key (pre-hash) + entry = st['circuit_map'].get(str(cid_raw)) + if isinstance(entry, dict): + saved_major = int(entry.get('major', major_int)) + saved_minor = int(entry.get('minor', -1)) + saved_parent = str(entry.get('parent_site', node_name)) + # Reuse only if this circuit still belongs to this node and major matches + if saved_parent == str(node_name) and saved_major == int(major_int) and saved_minor >= 4: + chosen_minor = saved_minor + # Remove from free list if present + try: + fm = st.get('free_minors') + if isinstance(fm, list) and 0 <= cpu_int < len(fm) and isinstance(fm[cpu_int], list) and saved_minor in fm[cpu_int]: + fm[cpu_int].remove(saved_minor) + except Exception: + pass + except Exception: + pass + if chosen_minor is None: + # Allocate from free list for this CPU + try: + fm = st.get('free_minors') if isinstance(st, dict) else None + if isinstance(fm, list) and 0 <= cpu_int < len(fm) and isinstance(fm[cpu_int], list) and len(fm[cpu_int]) > 0: + chosen_minor = int(fm[cpu_int].pop(0)) + except Exception: + chosen_minor = None + if chosen_minor is None: + # Fallback to reserved sequential range; ensure we never collide with the site's minor (<3 reserved) + chosen_minor = max(4, int(current_minor)) + current_minor = chosen_minor + 1 + flowIDstring = hex(major_int) + ':' + hex(chosen_minor) + upFlowIDstring = hex(major_int + stickOffset) + ':' + hex(chosen_minor) + item = { + 'maxDownload': maxDownload, + 'maxUpload': maxUpload, + 'minDownload': minDownload, + 'minUpload': minUpload, + 'circuitID': circuit['circuitID'], + 'circuitName': circuit['circuitName'], + 'ParentNode': circuit['ParentNode'], + 'devices': circuit['devices'], + 'classid': flowIDstring, + 'up_classid': upFlowIDstring, + 'classMajor': hex(major_int), + 'up_classMajor': hex(major_int + stickOffset), + 'classMinor': hex(chosen_minor), + 'comment': circuit['comment'] } - for node in network: - tgt = assignment.get(node) - if tgt is None: - tgt = "CpueQueue" + str(queuesAvailable - 1) - binnedNetwork[tgt]['children'][node] = network[node] - network = binnedNetwork - - # Update and save state - if bin_planner is not None and isinstance(state, dict): - if state.get("salt") is None: - state["salt"] = "default_salt" - if "assignments" not in state or not isinstance(state["assignments"], dict): - state["assignments"] = {} - if "last_change_ts" not in state or not isinstance(state["last_change_ts"], dict): - state["last_change_ts"] = {} - for iid, b in assignment.items(): - if iid in changed: - state["last_change_ts"][iid] = now_ts - state["assignments"][iid] = b + # Planner/UI weight try: - print(f"Saving planner state to {state_path} (top-level CPU binning)") - bin_planner.save_state(state_path, state) - except Exception as e: - warnings.warn(f"Failed to save planner state at {state_path}: {e}", stacklevel=2) + cid = str(circuit.get('circuitID', '')) + w = None + if cid in weight_by_circuit_id: + w = float(weight_by_circuit_id[cid]) + if w is None: + w = float(maxDownload) + if abs(w - 1000.0) < 1e-6: + w = float(maxDownload) + try: + default_rate = float(generated_pn_download_mbps()) + if abs(float(maxDownload) - default_rate) < 1e-6: + w = 0.0 + except Exception: + pass + item['planner_weight'] = w + except Exception: + pass + # SQM override copy-through + if 'sqm' in circuit and circuit['sqm']: + item['sqm'] = circuit['sqm'] + circuits_for_node.append(item) + # Insert circuit details into planner's circuit_map for future reuse + try: + if 'planner' in locals() and isinstance(planner, Planner): + st = planner.getState() + if 'circuit_map' not in st or not isinstance(st['circuit_map'], dict): + st['circuit_map'] = {} + st['circuit_map'][int(hash_to_i64(str(circuit['circuitID'])))] = { + 'cpu': int(cpu_int), + 'major': int(major_int), + 'minor': int(chosen_minor), + 'parent_site': str(node_name), + 'sqm': str(circuit['sqm']) if 'sqm' in circuit and circuit['sqm'] else '', + } + # Remove used minor from the planner's free list for this CPU, if present + try: + fm = st.get('free_minors') + if isinstance(fm, list) and 0 <= cpu_int < len(fm) and isinstance(fm[cpu_int], list): + if int(chosen_minor) in fm[cpu_int]: + fm[cpu_int].remove(int(chosen_minor)) + except Exception: + pass + except Exception: + pass + if current_minor > 0xFFFF: + msg = f"Minor class ID overflow while attaching circuits on node {node_name}: {current_minor} exceeds TC u16 limit." + logging.error(msg) + try: + ctx = json.dumps({"node": str(node_name), "minor": int(current_minor)}) + submit_urgent_issue("LibreQoS", "Error", "TC_U16_OVERFLOW", msg, ctx, f"TC_U16_OVERFLOW_NODE_{str(node_name)}") + except Exception: + pass + raise ValueError(msg) + if len(circuits_for_node) > 0: + node['circuits'] = circuits_for_node - # Here is the actual call to the recursive traverseNetwork() function. finalMinor is not used. - minorByCPU = traverseNetwork(network, 0, major=1, minorByCPU=minorByCPUpreloaded, queue=1, parentClassID=None, upParentClassID=None, parentMaxDL=upstream_bandwidth_capacity_download_mbps(), parentMaxUL=upstream_bandwidth_capacity_upload_mbps(), parentMinDL=upstream_bandwidth_capacity_download_mbps(), parentMinUL=upstream_bandwidth_capacity_upload_mbps()) + # Any circuits left in stale_circuits are removed this run: reclaim their minors + try: + if 'planner' in locals() and isinstance(planner, Planner) and len(stale_circuits) > 0: + st_final = planner.getState() + cmap = st_final.get('circuit_map') if isinstance(st_final, dict) else None + fm = st_final.get('free_minors') if isinstance(st_final, dict) else None + if isinstance(cmap, dict): + for cid in list(stale_circuits): + try: + entry = cmap.get(cid) + if entry is None: + # Attempt both string/int conversions for robustness + try: + entry = cmap.get(str(cid)) + except Exception: + entry = None + if entry is None: + try: + entry = cmap.get(int(cid)) + except Exception: + entry = None + if isinstance(entry, dict): + cpu = int(entry.get('cpu', 0)) + minor = int(entry.get('minor', -1)) + if isinstance(fm, list) and 0 <= cpu < len(fm) and isinstance(fm[cpu], list): + if minor >= 3 and minor <= 0xFFFF and (minor not in fm[cpu]): + fm[cpu].append(minor) + # Remove from circuit_map + try: + cmap.pop(cid, None) + except Exception: + try: + cmap.pop(str(cid), None) + except Exception: + pass + except Exception: + pass + except Exception: + pass bakery = Bakery() bakery.start_batch() # Initializes the bakery transaction @@ -1327,33 +2007,23 @@ def refreshShapers(): linuxTCcommands.append(command) - # Parse network structure. For each tier, generate commands to create corresponding HTB and leaf classes. Prepare commands for execution later - # Define lists for hash filters + # Parse network structure. Emit all site HTB classes before any circuits for clarity. print("Preparing TC commands") - def traverseNetwork(data): - - # Cake needs help handling rates lower than 5 Mbps - def sqmFixupRate(rate:int, sqm:str) -> str: - # If we aren't using cake, just return the sqm string - if not sqm.startswith("cake") or "rtt" in sqm: - return sqm - - # If we are using cake, we need to fixup the rate - # Based on: 1 MTU is 1500 bytes, or 12,000 bits. - # At 1 Mbps, (1,000 bits per ms) transmitting an MTU takes 12ms. Add 3ms for overhead, and we get 15ms. - # So 15ms divided by 5 (for 1%) multiplied by 100 yields 300ms. - # The same formula gives 180ms at 2Mbps - # 140ms at 3Mbps - # 120ms at 4Mbps - match rate: - case 1: return sqm + " rtt 300" - case 2: return sqm + " rtt 180" - case 3: return sqm + " rtt 140" - case 4: return sqm + " rtt 120" - case _: return sqm + def emit_sites(data): for node in sorted(data.keys()): site_name = data[node]['name'] if 'name' in data[node] else node + # Avoid creating Bakery sites for Generated_PN_* or CpueQueue* when not in flat mode + try: + name_s = str(site_name) + if (not is_network_flat()) and (name_s.startswith('Generated_PN_') or name_s.startswith('CpueQueue')): + # Recurse into children to ensure real sites are still emitted + if 'children' in data[node]: + sorted_children = dict(sorted(data[node]['children'].items())) + emit_sites(sorted_children) + continue + except Exception: + pass bakery.add_site( site_name, data[node]['parentClassID'], @@ -1364,19 +2034,36 @@ def refreshShapers(): data[node]['downloadBandwidthMbps'], data[node]['uploadBandwidthMbps'], ) + # Legacy TC output for reference command = 'class add dev ' + interface_a() + ' parent ' + data[node]['parentClassID'] + ' classid ' + data[node]['classMinor'] + ' htb rate '+ format_rate_for_tc(data[node]['downloadBandwidthMbpsMin']) + ' ceil '+ format_rate_for_tc(data[node]['downloadBandwidthMbps']) + ' prio 3' + quantum(data[node]['downloadBandwidthMbps']) linuxTCcommands.append(command) - logging.info("Up ParentClassID: " + data[node]['up_parentClassID']) - logging.info("ClassMinor: " + data[node]['classMinor']) command = 'class add dev ' + interface_b() + ' parent ' + data[node]['up_parentClassID'] + ' classid ' + data[node]['classMinor'] + ' htb rate '+ format_rate_for_tc(data[node]['uploadBandwidthMbpsMin']) + ' ceil '+ format_rate_for_tc(data[node]['uploadBandwidthMbps']) + ' prio 3' + quantum(data[node]['uploadBandwidthMbps']) linuxTCcommands.append(command) + if 'children' in data[node]: + sorted_children = dict(sorted(data[node]['children'].items())) + emit_sites(sorted_children) + + def emit_circuits(data): + # Cake needs help handling rates lower than 5 Mbps + def sqmFixupRate(rate:int, sqm:str) -> str: + # If we aren't using cake, just return the sqm string + if not sqm.startswith("cake") or "rtt" in sqm: + return sqm + match rate: + case 1: return sqm + " rtt 300" + case 2: return sqm + " rtt 180" + case 3: return sqm + " rtt 140" + case 4: return sqm + " rtt 120" + case _: return sqm + + for node in sorted(data.keys()): if 'circuits' in data[node]: - # Sort circuits by name for stable ordering - sorted_circuits = sorted(data[node]['circuits'], - key=lambda c: c.get('circuitName', c.get('circuitID', ''))) + sorted_circuits = sorted( + data[node]['circuits'], + key=lambda c: c.get('circuitName', c.get('circuitID', '')) + ) for circuit in sorted_circuits: # If circuit mins exceed node mins - handle low min rates of 1 to mean 10 kbps. - # Avoid changing minDownload or minUpload because they are used in queuingStructure.json, and must remain integers. min_down = circuit['minDownload'] min_up = circuit['minUpload'] if node in nodes_requiring_min_squashing: @@ -1384,7 +2071,7 @@ def refreshShapers(): min_down = 0.01 if min_up == 1: min_up = 0.01 - # Ensure min < max for circuits as well + # Ensure min < max try: max_down = float(circuit['maxDownload']) max_up = float(circuit['maxUpload']) @@ -1397,31 +2084,23 @@ def refreshShapers(): mu = min_up if md >= max_down: new_md = (max_down - 1.0) if max_down >= 1.0 else max(0.01, max_down - 0.01) - # Too noisy in practice; keep as debug for diagnostics logging.debug(f"Circuit '{circuit.get('circuitID','unknown')}' min download ({md}) >= max ({max_down}); lowering min to {new_md}") min_down = new_md if mu >= max_up: new_mu = (max_up - 1.0) if max_up >= 1.0 else max(0.01, max_up - 0.01) - # Too noisy in practice; keep as debug for diagnostics logging.debug(f"Circuit '{circuit.get('circuitID','unknown')}' min upload ({mu}) >= max ({max_up}); lowering min to {new_mu}") min_up = new_mu - # Generate TC commands to be executed later + + # Comment and IP aggregation (for legacy output and mappings) tcComment = " # CircuitID: " + circuit['circuitID'] + " DeviceIDs: " - for device in circuit['devices']: - tcComment = '' #tcComment + device['deviceID'] + ', ' - if 'devices' in circuit: - if 'comment' in circuit['devices'][0]: - tcComment = '' # tcComment + '| Comment: ' + circuit['devices'][0]['comment'] tcComment = tcComment.replace("\n", "") circuit_name = circuit['circuitID'] if 'circuitID' in circuit else "unknown" - # Collect all IP addresses for this circuit ip_list = [] for device in circuit['devices']: if device['ipv4s']: ip_list.extend(device['ipv4s']) if device['ipv6s']: ip_list.extend(device['ipv6s']) - # Concatenate IPs with comma separator ip_addresses_str = ','.join(ip_list) sqm_override = circuit['sqm'] if 'sqm' in circuit else None @@ -1439,14 +2118,12 @@ def refreshShapers(): ip_addresses_str, sqm_override, ) + # Legacy TC output for reference command = 'class add dev ' + interface_a() + ' parent ' + data[node]['classid'] + ' classid ' + circuit['classMinor'] + ' htb rate '+ format_rate_for_tc(min_down) + ' ceil '+ format_rate_for_tc(circuit['maxDownload']) + ' prio 3' + quantum(circuit['maxDownload']) + tcComment linuxTCcommands.append(command) - # Only add CAKE / fq_codel qdisc if monitorOnlyMode is Off if monitor_mode_only() == False: - # SQM Fixup for lower rates (and per-circuit override) def effective_sqm_str(rate, override, direction): base = sqm() - # Resolve per-direction token from override string chosen = None if override: try: @@ -1460,7 +2137,6 @@ def refreshShapers(): chosen = ov except Exception: chosen = None - # If no explicit token for this direction, use default behavior if not chosen: try: thresh = fast_queues_fq_codel() @@ -1484,9 +2160,7 @@ def refreshShapers(): linuxTCcommands.append(command) command = 'class add dev ' + interface_b() + ' parent ' + data[node]['up_classid'] + ' classid ' + circuit['classMinor'] + ' htb rate '+ format_rate_for_tc(min_up) + ' ceil '+ format_rate_for_tc(circuit['maxUpload']) + ' prio 3' + quantum(circuit['maxUpload']) linuxTCcommands.append(command) - # Only add CAKE / fq_codel qdisc if monitorOnlyMode is Off if monitor_mode_only() == False: - # SQM Fixup for lower rates (and per-circuit override) sqm_override = circuit['sqm'] if 'sqm' in circuit else None useSqm = effective_sqm_str(circuit['maxUpload'], sqm_override, 'up') if useSqm != '': @@ -1496,26 +2170,22 @@ def refreshShapers(): if device['ipv4s']: for ipv4 in device['ipv4s']: ipMapBatch.add_ip_mapping(str(ipv4), circuit['classid'], data[node]['cpuNum'], False) - #xdpCPUmapCommands.append('./bin/xdp_iphash_to_cpu_cmdline add --ip ' + str(ipv4) + ' --cpu ' + data[node]['cpuNum'] + ' --classid ' + circuit['classid']) if on_a_stick(): ipMapBatch.add_ip_mapping(str(ipv4), circuit['up_classid'], data[node]['up_cpuNum'], True) - #xdpCPUmapCommands.append('./bin/xdp_iphash_to_cpu_cmdline add --ip ' + str(ipv4) + ' --cpu ' + data[node]['up_cpuNum'] + ' --classid ' + circuit['up_classid'] + ' --upload 1') if device['ipv6s']: for ipv6 in device['ipv6s']: ipMapBatch.add_ip_mapping(str(ipv6), circuit['classid'], data[node]['cpuNum'], False) - #xdpCPUmapCommands.append('./bin/xdp_iphash_to_cpu_cmdline add --ip ' + str(ipv6) + ' --cpu ' + data[node]['cpuNum'] + ' --classid ' + circuit['classid']) if on_a_stick(): ipMapBatch.add_ip_mapping(str(ipv6), circuit['up_classid'], data[node]['up_cpuNum'], True) - #xdpCPUmapCommands.append('./bin/xdp_iphash_to_cpu_cmdline add --ip ' + str(ipv6) + ' --cpu ' + data[node]['up_cpuNum'] + ' --classid ' + circuit['up_classid'] + ' --upload 1') if device['deviceName'] not in devicesShaped: devicesShaped.append(device['deviceName']) - # Recursive call this function for children nodes attached to this node if 'children' in data[node]: - # Sort children to ensure consistent traversal order sorted_children = dict(sorted(data[node]['children'].items())) - traverseNetwork(sorted_children) - # Here is the actual call to the recursive traverseNetwork() function. - traverseNetwork(network) + emit_circuits(sorted_children) + + # Emit site HTB classes first, then circuits + emit_sites(network) + emit_circuits(network) # Save queuingStructure queuingStructure = {} @@ -1631,6 +2301,15 @@ def refreshShapers(): print("\tXDP filters: \t " + "{:g}".format(round(xdpFilterTimeSeconds,4)) + " seconds") + # Persist planner state (if initialized) + try: + if 'planner' in locals() and isinstance(planner, Planner): + # Do not mutate 'site_names' here; it must reflect the original invariant + # used to decide planner rebuild (e.g., depth-1 names for tiered). + planner.persist() + except Exception as e: + warnings.warn(f"Planner persist failed: {e}", stacklevel=2) + # Done print("refreshShapers completed on " + datetime.now().strftime("%d/%m/%Y %H:%M:%S")) @@ -1697,8 +2376,6 @@ def refreshShapersUpdateOnly(): devicesChanged = True if newlyUpdatedSubscriberCircuitsByID[circuitID]['ParentNode'] != lastLoadedSubscriberCircuitsByID[circuitID]['ParentNode']: devicesChanged = True - else: - devicesChanged = True for circuitID, circuit in newlyUpdatedSubscriberCircuitsByID.items(): if (circuitID not in lastLoadedSubscriberCircuitsByID): devicesChanged = True @@ -1763,22 +2440,10 @@ if __name__ == '__main__': help="Clear ip filters, qdiscs, and xdp setup if any", action=argparse.BooleanOptionalAction, ) - parser.add_argument( - '--planner-reset', - help="Delete planner state file before running", - action=argparse.BooleanOptionalAction, - ) args = parser.parse_args() logging.basicConfig(level=args.loglevel) - if getattr(args, 'planner_reset', False): - try: - state_path = os.path.join(get_libreqos_directory(), "planner_state.json") - if os.path.exists(state_path): - os.remove(state_path) - print(f"Removed planner state: {state_path}") - except Exception as e: - print(f"Warning: could not remove planner state: {e}") + # Planner reset no longer applicable (stateful planner removed) if args.validate: status = validateNetworkAndDevices() diff --git a/src/README.md b/src/README.md index b85aeee4..10834468 100644 --- a/src/README.md +++ b/src/README.md @@ -4,6 +4,6 @@ See [wiki here](https://github.com/LibreQoE/LibreQoS/wiki/v1.4) -## Planner (binpacking replacement) +## Binpacking -LibreQoS now uses an internal planner for assigning circuits and nodes to CPU queues and generated parent nodes. The planner favors stable, stateful assignments to minimize churn and reduce rebuilds, replacing the previous external binpacking dependency. +LibreQoS assigns circuits and sites to CPU queues using a simple, deterministic greedy binpacking approach. We continue to use Insight (lts) to provide weights when available, but assignments themselves are computed on each run without keeping long‑term state. diff --git a/src/bakery_integration_test.py b/src/bakery_integration_test.py new file mode 100644 index 00000000..8bd1abbe --- /dev/null +++ b/src/bakery_integration_test.py @@ -0,0 +1,631 @@ +#!/usr/bin/env python3 +""" +LibreQoS + Bakery integration test harness + +Purpose +- Verify incremental vs full Bakery reload behavior for both tiered and flat topologies + by driving LibreQoS.py and inspecting lqosd logs. + +Important +- This test applies real TC/XDP changes via lqosd. Use on a test box or during a + maintenance window. It is NOT intended for production service units under systemd. + +Manual steps (run in two terminals) +1) Start lqosd manually as root with logs to a file: + sudo RUST_LOG=info lqosd 2>&1 | tee /tmp/lqosd.log + - Ensure /etc/lqos.conf interfaces and bandwidths are set correctly for this host. + - Stop systemd units first if they are enabled (optional): + sudo systemctl stop lqosd lqos_scheduler lqos_api +2) In another terminal from this directory (LibreQoS/src), run the tests: + python3 bakery_integration_test.py --log-file /tmp/lqosd.log + - You can limit scope with --tiered-only or --flat-only. + +What this script does +- Backs up `network.json` and `ShapedDevices.csv` in the current directory. +- Writes small tiered and flat fixtures and calls LibreQoS.refreshShapers() after each change. +- Parses lqosd logs to decide whether a full reload occurred or an incremental update happened. +- Restores your original files at the end unless --no-restore is used. + +Notes +- The first commit after (re)starting lqosd will do a full reload (MQ init). The + test allows that and asserts the subsequent expected behaviors. +- Flat networks do not have explicit sites, so site add/remove checks are skipped there. + +Usage examples +- Tiered + Flat (default): + python3 bakery_integration_test.py --log-file /tmp/lqosd.log +- Tiered only: + python3 bakery_integration_test.py --log-file /tmp/lqosd.log --tiered-only +- Flat only: + python3 bakery_integration_test.py --log-file /tmp/lqosd.log --flat-only + +Exit code +- 0 on success, 1 on assertion failure or precondition failure. +""" + +from __future__ import annotations + +import argparse +import contextlib +import csv +import json +import os +import re +import shutil +import sys +import time +from dataclasses import dataclass +from typing import Dict, List, Optional, Tuple + + +# Import LibreQoS and lqosd helpers without invoking the __main__ block +try: + import LibreQoS # type: ignore +except Exception as e: + print(f"ERROR: Failed to import LibreQoS.py: {e}") + sys.exit(1) + +try: + from liblqos_python import is_lqosd_alive # type: ignore + # Optional: bus log message helper (newer liblqos_python) + try: + from liblqos_python import log_info # type: ignore + except Exception: + log_info = None # type: ignore +except Exception: + # Provide a soft fallback if binding is unavailable + def is_lqosd_alive() -> bool: + return False + +def _mark_step(name: str) -> None: + msg = f"STARTING TEST ({name})" + try: + if 'log_info' in globals() and callable(log_info): # type: ignore[name-defined] + try: + ok = log_info(msg) # type: ignore[misc] + if not ok: + print(msg) + except Exception: + print(msg) + else: + print(msg) + except Exception: + print(msg) + + +# ----------------------- +# Log parsing and waiting +# ----------------------- + +FULL_RELOAD_PAT = re.compile(r"Bakery: Full reload triggered") +FULL_RELOAD_SUMMARY_PAT = re.compile(r"Bakery full reload:.*") +MQ_INIT_PAT = re.compile(r"MQ not created, performing full reload\.") +CHANGES_PAT = re.compile( + r"Bakery changes: sites_speed=(\d+), circuits_added=(\d+), removed=(\d+), speed=(\d+), ip=(\d+)" +) +NO_CHANGES_PAT = re.compile(r"No changes detected in batch, skipping processing\.") + + +@dataclass +class LogResult: + full_reload: bool + mq_init: bool + changes: Optional[Dict[str, int]] + raw_lines: List[str] + + +class LogReader: + def __init__(self, path: str): + self.path = path + + def snapshot(self) -> int: + try: + return os.path.getsize(self.path) + except Exception: + return 0 + + def read_since(self, offset: int) -> List[str]: + lines: List[str] = [] + try: + with open(self.path, "r", errors="replace") as f: + f.seek(offset) + for line in f: + lines.append(line.rstrip("\n")) + except Exception: + pass + return lines + + def wait_for_events(self, offset: int, timeout_s: float = 20.0) -> LogResult: + deadline = time.time() + timeout_s + print(f"Waiting for Bakery events (timeout {timeout_s:.1f}s)...") + collected: List[str] = [] + full_reload = False + mq_init = False + changes: Optional[Dict[str, int]] = None + printed_sleep_note = False + + while time.time() < deadline: + new_lines = self.read_since(offset) + if new_lines: + collected.extend(new_lines) + # Seek to last byte each time + offset += sum(len(l) + 1 for l in new_lines) + + # Parse new chunk + for ln in new_lines: + if FULL_RELOAD_PAT.search(ln) or FULL_RELOAD_SUMMARY_PAT.search(ln): + full_reload = True + if MQ_INIT_PAT.search(ln): + mq_init = True + m = CHANGES_PAT.search(ln) + if m: + changes = { + "sites_speed": int(m.group(1)), + "circuits_added": int(m.group(2)), + "removed": int(m.group(3)), + "speed": int(m.group(4)), + "ip": int(m.group(5)), + } + # Heuristic: stop when we saw an outcome (changes or full reload or no changes) + if changes or full_reload or any(NO_CHANGES_PAT.search(x) for x in new_lines): + break + + if not printed_sleep_note: + print("No new logs yet; sleeping 0.4s...") + printed_sleep_note = True + time.sleep(0.4) + + return LogResult(full_reload=full_reload, mq_init=mq_init, changes=changes, raw_lines=collected) + + +# ----------------------- +# Fixtures and mutators +# ----------------------- + +TIERED_NETWORK_BASE = { + "Site_A": { + "downloadBandwidthMbps": 100, + "uploadBandwidthMbps": 100, + "type": "Site", + "children": { + "AP_A": { + "downloadBandwidthMbps": 50, + "uploadBandwidthMbps": 50, + "type": "AP", + } + }, + }, +} + + +def write_network_json(obj: dict) -> None: + with open("network.json", "w") as f: + json.dump(obj, f, indent=2) + + +CSV_HEADER = [ + "Circuit ID", + "Circuit Name", + "Device ID", + "Device Name", + "Parent Node", + "MAC", + "IPv4", + "IPv6", + "Download Min Mbps", + "Upload Min Mbps", + "Download Max Mbps", + "Upload Max Mbps", + "Comment", + "sqm", +] + + +def write_circuits(rows: List[Dict[str, str | int | float]]) -> None: + with open("ShapedDevices.csv", "w", newline="") as f: + w = csv.DictWriter(f, fieldnames=CSV_HEADER) + w.writeheader() + for r in rows: + w.writerow(r) + + +def tiered_circuits_base() -> List[Dict[str, str | int | float]]: + # Two circuits hanging off AP_A + return [ + { + "Circuit ID": "1", + "Circuit Name": "C1", + "Device ID": "1", + "Device Name": "D1", + "Parent Node": "AP_A", + "MAC": "", + "IPv4": "100.64.0.1", + "IPv6": "", + "Download Min Mbps": 1, + "Upload Min Mbps": 1, + "Download Max Mbps": 10, + "Upload Max Mbps": 10, + "Comment": "", + "sqm": "", + }, + { + "Circuit ID": "2", + "Circuit Name": "C2", + "Device ID": "2", + "Device Name": "D2", + "Parent Node": "AP_A", + "MAC": "", + "IPv4": "100.64.0.2", + "IPv6": "", + "Download Min Mbps": 1, + "Upload Min Mbps": 1, + "Download Max Mbps": 10, + "Upload Max Mbps": 10, + "Comment": "", + "sqm": "", + }, + ] + + +def flat_network_base() -> dict: + # Flat = empty object + return {} + + +def flat_circuits_base() -> List[Dict[str, str | int | float]]: + # Parent Node is ignored when flat, but we still populate a value. + return [ + { + "Circuit ID": "10", + "Circuit Name": "F1", + "Device ID": "10", + "Device Name": "FD1", + "Parent Node": "none", + "MAC": "", + "IPv4": "100.64.1.1", + "IPv6": "", + "Download Min Mbps": 1, + "Upload Min Mbps": 1, + "Download Max Mbps": 10, + "Upload Max Mbps": 10, + "Comment": "", + "sqm": "", + }, + { + "Circuit ID": "11", + "Circuit Name": "F2", + "Device ID": "11", + "Device Name": "FD2", + "Parent Node": "none", + "MAC": "", + "IPv4": "100.64.1.2", + "IPv6": "", + "Download Min Mbps": 1, + "Upload Min Mbps": 1, + "Download Max Mbps": 10, + "Upload Max Mbps": 10, + "Comment": "", + "sqm": "", + }, + ] + + +# ----------------------- +# Test runner utilities +# ----------------------- + + +def run_refresh_and_wait(log: LogReader, timeout_s: float) -> LogResult: + offset = log.snapshot() + # Call the core refresh function; this does not require running as __main__ + LibreQoS.refreshShapers() + # Allow lqosd time to process the commit and log + print("Sleeping 0.5s to allow lqosd to commit and log...") + time.sleep(0.5) + return log.wait_for_events(offset, timeout_s=timeout_s) + + +def assert_no_full_reload(tag: str, res: LogResult, step_started_at: Optional[float] = None) -> Tuple[bool, str]: + if res.full_reload and not res.mq_init: + ts = ( + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(step_started_at)) + + f" (epoch {step_started_at:.3f})" + if step_started_at is not None + else "unknown" + ) + return False, f"{tag}: Unexpected full reload detected (step started {ts})" + return True, f"{tag}: OK (no full reload)" + + +def assert_full_reload(tag: str, res: LogResult, step_started_at: Optional[float] = None) -> Tuple[bool, str]: + if not res.full_reload: + ts = ( + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(step_started_at)) + + f" (epoch {step_started_at:.3f})" + if step_started_at is not None + else "unknown" + ) + return False, f"{tag}: Expected full reload, but none detected (step started {ts})" + return True, f"{tag}: OK (full reload)" + + +def with_backups(paths: List[str]): + class _Ctx: + def __enter__(self): + self.baks = [] + for p in paths: + if os.path.exists(p): + bak = p + ".bak.integration" + shutil.copyfile(p, bak) + self.baks.append((p, bak)) + return self + + def __exit__(self, exc_type, exc, tb): + # Restore originals + for p, bak in self.baks: + try: + shutil.move(bak, p) + except Exception: + pass + # Remove any remaining temp backups + for p in paths: + bak = p + ".bak.integration" + with contextlib.suppress(Exception): + if os.path.exists(bak): + os.remove(bak) + + return _Ctx() + + +# ----------------------- +# Scenarios +# ----------------------- + + +def run_tiered_suite(log: LogReader, timeout_s: float, results: List[str]) -> bool: + ok = True + + # Baseline + write_network_json(TIERED_NETWORK_BASE) + rows = tiered_circuits_base() + write_circuits(rows) + res = run_refresh_and_wait(log, timeout_s) + # First run likely MQ init/full reload; do not assert here + results.append("tiered: baseline: " + ("ok (initial run)")) + + # Site speed change (same site name & location) + _mark_step("tiered: site speed change") + net2 = json.loads(json.dumps(TIERED_NETWORK_BASE)) + net2["Site_A"]["downloadBandwidthMbps"] = 120 + net2["Site_A"]["uploadBandwidthMbps"] = 110 + write_network_json(net2) + step_t0 = time.time() + res = run_refresh_and_wait(log, timeout_s) + passed, msg = assert_no_full_reload("tiered: site speed change", res, step_t0) + results.append(msg) + ok &= passed + + # Circuit speed change + _mark_step("flat: circuit speed change") + _mark_step("tiered: circuit speed change") + rows2 = json.loads(json.dumps(rows)) + rows2[0]["Download Max Mbps"] = 20 + rows2[0]["Upload Max Mbps"] = 15 + write_circuits(rows2) + step_t0 = time.time() + res = run_refresh_and_wait(log, timeout_s) + passed, msg = assert_no_full_reload("tiered: circuit speed change", res, step_t0) + results.append(msg) + ok &= passed + + # Circuit SQM change + _mark_step("flat: circuit SQM change") + _mark_step("tiered: circuit SQM change") + rows3 = json.loads(json.dumps(rows2)) + rows3[1]["sqm"] = "cake/fq_codel" + write_circuits(rows3) + step_t0 = time.time() + res = run_refresh_and_wait(log, timeout_s) + passed, msg = assert_no_full_reload("tiered: circuit SQM change", res, step_t0) + results.append(msg) + ok &= passed + + # Add circuit + _mark_step("flat: add circuit") + _mark_step("tiered: add circuit") + rows4 = json.loads(json.dumps(rows3)) + rows4.append({ + "Circuit ID": "3", + "Circuit Name": "C3", + "Device ID": "3", + "Device Name": "D3", + "Parent Node": "AP_A", + "MAC": "", + "IPv4": "100.64.0.3", + "IPv6": "", + "Download Min Mbps": 1, + "Upload Min Mbps": 1, + "Download Max Mbps": 10, + "Upload Max Mbps": 10, + "Comment": "", + "sqm": "", + }) + write_circuits(rows4) + step_t0 = time.time() + res = run_refresh_and_wait(log, timeout_s) + passed, msg = assert_no_full_reload("tiered: add circuit", res, step_t0) + results.append(msg) + ok &= passed + + # Remove circuit + _mark_step("flat: remove circuit") + _mark_step("tiered: remove circuit") + rows5 = [r for r in rows4 if r["Circuit ID"] != "3"] + write_circuits(rows5) + step_t0 = time.time() + res = run_refresh_and_wait(log, timeout_s) + passed, msg = assert_no_full_reload("tiered: remove circuit", res, step_t0) + results.append(msg) + ok &= passed + + # Add site (should trigger full reload) + _mark_step("tiered: add site") + net3 = json.loads(json.dumps(net2)) + net3["Site_B"] = { + "downloadBandwidthMbps": 80, + "uploadBandwidthMbps": 80, + "type": "Site", + "children": {}, + } + write_network_json(net3) + step_t0 = time.time() + res = run_refresh_and_wait(log, timeout_s) + passed, msg = assert_full_reload("tiered: add site", res, step_t0) + results.append(msg) + ok &= passed + + # Remove site (should trigger full reload) + _mark_step("tiered: remove site") + net4 = json.loads(json.dumps(net3)) + del net4["Site_B"] + write_network_json(net4) + step_t0 = time.time() + res = run_refresh_and_wait(log, timeout_s) + passed, msg = assert_full_reload("tiered: remove site", res, step_t0) + results.append(msg) + ok &= passed + + return ok + + +def run_flat_suite(log: LogReader, timeout_s: float, results: List[str]) -> bool: + ok = True + + # Baseline + write_network_json(flat_network_base()) + rows = flat_circuits_base() + write_circuits(rows) + res = run_refresh_and_wait(log, timeout_s) + results.append("flat: baseline: ok (initial run or structural change)") + + # Circuit speed change + step_t0 = time.time() + rows2 = json.loads(json.dumps(rows)) + rows2[0]["Download Max Mbps"] = 25 + rows2[0]["Upload Max Mbps"] = 20 + write_circuits(rows2) + res = run_refresh_and_wait(log, timeout_s) + passed, msg = assert_no_full_reload("flat: circuit speed change", res, step_t0) + results.append(msg) + ok &= passed + + # Circuit SQM change + step_t0 = time.time() + rows3 = json.loads(json.dumps(rows2)) + rows3[1]["sqm"] = "fq_codel/cake" + write_circuits(rows3) + res = run_refresh_and_wait(log, timeout_s) + passed, msg = assert_no_full_reload("flat: circuit SQM change", res, step_t0) + results.append(msg) + ok &= passed + + # Add circuit + step_t0 = time.time() + rows4 = json.loads(json.dumps(rows3)) + rows4.append({ + "Circuit ID": "12", + "Circuit Name": "F3", + "Device ID": "12", + "Device Name": "FD3", + "Parent Node": "none", + "MAC": "", + "IPv4": "100.64.1.3", + "IPv6": "", + "Download Min Mbps": 1, + "Upload Min Mbps": 1, + "Download Max Mbps": 10, + "Upload Max Mbps": 10, + "Comment": "", + "sqm": "", + }) + write_circuits(rows4) + res = run_refresh_and_wait(log, timeout_s) + passed, msg = assert_no_full_reload("flat: add circuit", res, step_t0) + results.append(msg) + ok &= passed + + # Remove circuit + step_t0 = time.time() + rows5 = [r for r in rows4 if r["Circuit ID"] != "12"] + write_circuits(rows5) + res = run_refresh_and_wait(log, timeout_s) + passed, msg = assert_no_full_reload("flat: remove circuit", res, step_t0) + results.append(msg) + ok &= passed + + return ok + + +# ----------------------- +# Main +# ----------------------- + + +def main() -> int: + ap = argparse.ArgumentParser(description="LibreQoS/Bakery integration tests") + ap.add_argument("--log-file", required=True, help="Path to lqosd log file (stdout/tee capture)") + ap.add_argument("--timeout", type=float, default=25.0, help="Wait time per step (seconds)") + g = ap.add_mutually_exclusive_group() + g.add_argument("--tiered-only", action="store_true", help="Run tiered cases only") + g.add_argument("--flat-only", action="store_true", help="Run flat cases only") + ap.add_argument("--no-restore", action="store_true", help="Do not restore original files (debugging)") + + args = ap.parse_args() + + # Pre-flight guidance + if not os.path.exists(args.log_file): + print("ERROR: Log file not found. Please run lqosd with logs, e.g.:") + print(" sudo RUST_LOG=info lqosd 2>&1 | tee /tmp/lqosd.log") + return 1 + + if not is_lqosd_alive(): + print("WARNING: lqosd does not appear to be running. This test will not observe Bakery logs.") + print("Start lqosd and re-run, or continue if already started but lib binding cannot detect it.") + + log = LogReader(args.log_file) + results: List[str] = [] + overall_ok = True + + files = ["network.json", "ShapedDevices.csv"] + ctx = contextlib.nullcontext() + if not args.no_restore: + ctx = with_backups(files) + + with ctx: + # Run tiered suite + if not args.flat_only: + ok = run_tiered_suite(log, args.timeout, results) + overall_ok &= ok + + # Run flat suite + if not args.tiered_only: + ok = run_flat_suite(log, args.timeout, results) + overall_ok &= ok + + print("Results:") + for r in results: + print(f"- {r}") + + if not overall_ok: + print("One or more checks failed. See lqosd logs for details.") + print("Tips:") + print("- Start a fresh lqosd before the run to get a clean baseline") + print("- Confirm RUST_LOG includes 'info' level (or 'debug') for lqos_bakery") + print("- Verify /etc/lqos.conf is correct for your interfaces") + return 1 + + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/bin_planner.py b/src/bin_planner.py deleted file mode 100644 index f1b4a478..00000000 --- a/src/bin_planner.py +++ /dev/null @@ -1,277 +0,0 @@ -""" -Internal planner for stable, damped item-to-bin assignments. - -This module exposes a minimal interface initially, to be expanded in later -steps. The baseline implementation uses a simple greedy balancing strategy -as a placeholder to replace the external binpacking dependency. -""" - -from typing import Dict, List, Tuple, Any, Iterable -import hashlib -import math -import json -import os -import time - - -def plan_assignments( - items: List[Dict[str, Any]], - bins: List[Dict[str, Any]], - capacities: Dict[str, float], - previous_assignments: Dict[str, str], - now_ts: float, - params: Dict[str, Any], -) -> Tuple[Dict[str, str], List[str]]: - """ - Compute item -> bin assignments with a repair-oriented approach. - - items: list of { "id": str, "weight": float } - bins: list of { "id": str } - capacities: { bin_id: capacity_float } - previous_assignments: { item_id: bin_id } - now_ts: current UNIX timestamp - params: planner parameters (optional keys): - - candidate_set_size: int - - headroom: float in [0,1) - - alpha: float >= 0 - - hysteresis_threshold: float >= 0 - - cooldown_seconds: int >= 0 - - move_budget_per_run: int >= 0 - - salt: str - - last_change_ts_by_item: { item_id: unix_ts } - - movement_penalty_k: float >= 0 (default 0) - - penalty_tau_seconds: float > 0 (default 3600) - - Returns (assignments, changed_items) - """ - # Defaults - L = int(params.get("candidate_set_size", 4)) - headroom = float(params.get("headroom", 0.05)) - alpha = float(params.get("alpha", 0.1)) - hysteresis = float(params.get("hysteresis_threshold", 0.03)) - cooldown_s = int(params.get("cooldown_seconds", 3600)) - salt = str(params.get("salt", "default_salt")) - last_change_ts = params.get("last_change_ts_by_item", {}) or {} - penalty_k = float(params.get("movement_penalty_k", 0.0)) - penalty_tau = float(params.get("penalty_tau_seconds", 3600.0)) - - bin_ids: List[str] = [b["id"] for b in bins] - cap = {bid: float(capacities.get(bid, 1.0)) for bid in bin_ids} - # Avoid zero/negative capacity - for bid, c in list(cap.items()): - if c <= 0: - cap[bid] = 1e-9 - - # Normalize items - item_list: List[Tuple[str, float]] = [] - for it in items: - it_id = str(it.get("id")) - w = float(it.get("weight", 1.0)) - item_list.append((it_id, w)) - - # Current assignment: keep valid previous assignments - assignment: Dict[str, str] = {} - load: Dict[str, float] = {bid: 0.0 for bid in bin_ids} - for it_id, w in item_list: - prev = previous_assignments.get(it_id) - if prev in cap: - assignment[it_id] = prev - load[prev] += w - - # Cold start: assign items without previous placement via greedy using HRW candidates - missing = [(it_id, w) for it_id, w in item_list if it_id not in assignment] - weights_by_bin = {bid: cap[bid] for bid in bin_ids} - missing.sort(key=lambda t: (-t[1], t[0])) - initially_assigned: List[str] = [] - for it_id, w in missing: - candidates = hrw_candidates(it_id, bin_ids, weights_by_bin, max(L, 1), salt) - # Choose the least loaded among candidates; break ties by HRW rank, not lexicographic bin id - if candidates: - rank = {bid: idx for idx, bid in enumerate(candidates)} - tgt = min(candidates, key=lambda bid: (load[bid] / cap[bid], rank[bid])) - else: - # As a fallback, rank all bins by HRW order to avoid lexicographic bias - all_rank_list = hrw_candidates(it_id, bin_ids, weights_by_bin, len(bin_ids), salt) - all_rank = {bid: idx for idx, bid in enumerate(all_rank_list)} - tgt = min(bin_ids, key=lambda bid: (load[bid] / cap[bid], all_rank.get(bid, 1_000_000))) - assignment[it_id] = tgt - load[tgt] += w - initially_assigned.append(it_id) - - def score(loads: Dict[str, float]) -> float: - s = 0.0 - for bid in bin_ids: - denom = cap[bid] * max(1.0 - headroom, 1e-6) - lj = loads[bid] / denom - over = max(0.0, lj - 1.0) - s += over * over - # Add a small balancing term - if alpha > 0.0: - for bid in bin_ids: - lj = loads[bid] / cap[bid] - s += alpha * (lj * lj) - return s - - # Initial score - base_score = score(load) - - # Decide moves by considering HRW top-L candidates per item - move_budget = params.get("move_budget_per_run") - if move_budget is None: - move_budget = max(1, min(32, int(0.01 * max(1, len(item_list))))) - moves_left = int(move_budget) - - # Worklist: heavier items first - work = sorted(item_list, key=lambda t: (-t[1], t[0])) - changed_items: List[str] = [] - - for it_id, w in work: - if moves_left <= 0: - break - cur = assignment.get(it_id) - candidates = hrw_candidates(it_id, bin_ids, weights_by_bin, max(L, 1), salt) - # Ensure current bin is considered - if cur and cur not in candidates: - candidates.append(cur) - best_gain = 0.0 - best_tgt = cur - for tgt in candidates: - if tgt == cur: - continue - # simulate move - if cur: - load[cur] -= w - load[tgt] += w - new_score = score(load) - # revert - load[tgt] -= w - if cur: - load[cur] += w - gain = base_score - new_score - if gain > best_gain: - best_gain = gain - best_tgt = tgt - - if best_tgt and best_tgt != cur: - # Cooldown check - last_ts = float(last_change_ts.get(it_id, 0.0)) - age = max(0.0, float(now_ts) - last_ts) - if age < float(cooldown_s): - continue - # Movement penalty - penalty = 0.0 - if penalty_k > 0.0 and penalty_tau > 0.0: - penalty = penalty_k * float(w) * math.exp(-age / penalty_tau) - net_gain = best_gain - penalty - # Hysteresis threshold: relative to base_score magnitude or absolute small value if base is tiny - threshold = max(hysteresis * max(1.0, base_score), 1e-6) - if net_gain >= threshold: - # apply move - if cur: - load[cur] -= w - load[best_tgt] += w - assignment[it_id] = best_tgt - changed_items.append(it_id) - # update base score and budget - base_score -= best_gain - moves_left -= 1 - - # Mark initial placements as changes so callers can timestamp them - for iid in initially_assigned: - if iid not in changed_items: - changed_items.append(iid) - - return assignment, changed_items - - -def load_state(path: str) -> Dict[str, Any]: - """ - Load planner state from JSON. If missing or invalid, return a fresh state. - """ - fresh = { - "algo_version": "v1", - "salt": None, - "assignments": {}, - "last_change_ts": {}, - "updated_at": None, - } - try: - if not os.path.exists(path): - return fresh - with open(path, 'r', encoding='utf-8') as f: - data = json.load(f) - # Minimal validation - if not isinstance(data, dict): - return fresh - for k in ["algo_version", "salt", "assignments", "last_change_ts", "updated_at"]: - if k not in data: - data[k] = fresh.get(k) - if data.get("salt") is None: - data["salt"] = _generate_salt() - # TTL: invalidate if older than 24 hours - try: - updated_at = float(data.get("updated_at") or 0.0) - if updated_at <= 0.0: - return data - now = time.time() - if (now - updated_at) > 24 * 3600: - # Regenerate: return a fresh state with a new salt - fresh["salt"] = _generate_salt() - return fresh - except Exception: - # If parsing fails, return fresh - fresh["salt"] = _generate_salt() - return fresh - return data - except Exception: - return fresh - - -def save_state(path: str, state: Dict[str, Any]) -> None: - """ - Save planner state to JSON. Creates parent directory if necessary. - """ - try: - os.makedirs(os.path.dirname(path), exist_ok=True) - except Exception: - pass - state = dict(state) - state["updated_at"] = time.time() - if state.get("salt") is None: - state["salt"] = _generate_salt() - with open(path, 'w', encoding='utf-8') as f: - json.dump(state, f, indent=2, sort_keys=True) - - -def _generate_salt() -> str: - return hashlib.sha256(str(time.time_ns()).encode('utf-8')).hexdigest() - - -def hrw_candidates( - item_id: str, - bin_ids: List[str], - weights_by_bin: Dict[str, float], - L: int, - salt: str, -) -> List[str]: - """ - Weighted Rendezvous (HRW) hashing: return top-L candidate bins for an item. - - score(bin) = weight(bin) / -ln(U), where U derives deterministically from - SHA-256(salt || item_id || bin_id). - """ - scores: List[Tuple[float, str]] = [] - for bid in bin_ids: - w = float(weights_by_bin.get(bid, 1.0)) - # Deterministic uniform in (0,1) - h = hashlib.sha256((salt + '|' + str(item_id) + '|' + str(bid)).encode('utf-8')).digest() - # Use first 8 bytes for a 64-bit integer - r = int.from_bytes(h[:8], byteorder='big', signed=False) - # Map to (0,1). Avoid 0 by adding a tiny epsilon. - U = max((r / 2**64), 1e-12) - score = w / (-math.log(U)) if U < 1.0 else float('inf') - scores.append((score, bid)) - scores.sort(key=lambda t: (-t[0], t[1])) - if L <= 0: - return [] - return [bid for _, bid in scores[:min(L, len(scores))]] diff --git a/src/build_dpkg.sh b/src/build_dpkg.sh index 54044266..f0167bb0 100755 --- a/src/build_dpkg.sh +++ b/src/build_dpkg.sh @@ -24,7 +24,6 @@ LQOS_FILES=( integrationRestHttp.py integrationSonar.py integrationSplynx.py - bin_planner.py integrationUISP.py LibreQoS.py lqos.example diff --git a/src/build_rust.sh b/src/build_rust.sh index 64e3193e..e7c79070 100755 --- a/src/build_rust.sh +++ b/src/build_rust.sh @@ -98,13 +98,7 @@ popd > /dev/null || exit cp rust/target/$TARGET/liblqos_python.so ./liblqos_python.so.new mv liblqos_python.so.new liblqos_python.so -# Ensure the internal planner module is present for LibreQoS.py -if [ ! -f "bin_planner.py" ]; then - echo "Warning: bin_planner.py not found in $(pwd). The planner will be unavailable to LibreQoS.py." - echo "If you are updating a running system, make sure bin_planner.py is deployed alongside LibreQoS.py." -else - echo "bin_planner.py present." -fi + # Update the lqos_api binary echo "Updating lqos_api binary..." diff --git a/src/rust/Cargo.lock b/src/rust/Cargo.lock index 61cf32fd..e4777ff4 100644 --- a/src/rust/Cargo.lock +++ b/src/rust/Cargo.lock @@ -1969,14 +1969,17 @@ name = "lqos_python" version = "0.1.0" dependencies = [ "anyhow", + "base64", "chrono", "lqos_bus", "lqos_config", "lqos_utils", + "miniz_oxide", "nix", "pyo3", "reqwest", "serde", + "serde_cbor", "sysinfo", "tempfile", "tokio", diff --git a/src/rust/lqos_bakery/src/diff/sites.rs b/src/rust/lqos_bakery/src/diff/sites.rs index 08a9c187..7a60c4e5 100644 --- a/src/rust/lqos_bakery/src/diff/sites.rs +++ b/src/rust/lqos_bakery/src/diff/sites.rs @@ -1,7 +1,7 @@ use crate::BakeryCommands; use std::collections::HashMap; use std::sync::Arc; -use tracing::warn; +use tracing::{warn, info, debug}; pub(crate) enum SiteDiffResult { RebuildRequired, @@ -27,11 +27,15 @@ pub(crate) fn diff_sites( if old_sites.len() != new_sites.len() { // There is a difference in the number of sites. // Therefore, we must rebuild the entire site configuration. + let old_keys: Vec = old_sites.keys().cloned().collect(); + let new_keys: Vec = new_sites.keys().copied().collect(); warn!( "Site count mismatch: old {} vs new {}", old_sites.len(), new_sites.len() ); + debug!("Old site hashes: {:?}", old_keys); + debug!("New site hashes: {:?}", new_keys); return SiteDiffResult::RebuildRequired; } @@ -45,6 +49,19 @@ pub(crate) fn diff_sites( "Structural difference detected for site hash: {}", site_hash ); + // Log a concise before/after for diagnostics + // Extract relevant fields + // old + let (ocpu, opar, oup, omin) = match old_cmd.as_ref() { + crate::BakeryCommands::AddSite { parent_class_id, up_parent_class_id, class_minor, .. } => (0i32, parent_class_id.as_tc_string(), up_parent_class_id.as_tc_string(), *class_minor), + _ => (0, String::new(), String::new(), 0), + }; + // new + let (ncpu, npar, nup, nmin) = match new_cmd.as_ref() { + crate::BakeryCommands::AddSite { parent_class_id, up_parent_class_id, class_minor, .. } => (0i32, parent_class_id.as_tc_string(), up_parent_class_id.as_tc_string(), *class_minor), + _ => (0, String::new(), String::new(), 0), + }; + debug!("Site hash {} change: parent={}→{}, up_parent={}→{}, minor=0x{:x}→0x{:x}", site_hash, opar, npar, oup, nup, omin, nmin); return SiteDiffResult::RebuildRequired; } // If the speeds have changed, we need to store the change. diff --git a/src/rust/lqos_bakery/src/utils.rs b/src/rust/lqos_bakery/src/utils.rs index 03dea8b9..5401dc66 100644 --- a/src/rust/lqos_bakery/src/utils.rs +++ b/src/rust/lqos_bakery/src/utils.rs @@ -44,9 +44,17 @@ pub(crate) fn execute_in_memory(command_buffer: &Vec>, purpose: &str let error_str = String::from_utf8_lossy(&output.stderr); if !error_str.is_empty() { + // Add line numbers to aid debugging with tc -batch's reported line numbers + let mut numbered = String::new(); + for (i, line) in lines.lines().enumerate() { + // tc -batch reports 1-based line numbers + numbered.push_str(&format!("{:>4}: {}\n", i + 1, line)); + } let message = format!( - "Command error for ({purpose}): {:?}.Error: {error_str}\n{lines}", - error_str.trim() + "Command error for ({purpose}): {:?}. Error: {}\nCommands with line numbers:\n{}", + error_str.trim(), + error_str.trim(), + numbered ); error!(message); } diff --git a/src/rust/lqos_bus/src/bus/request.rs b/src/rust/lqos_bus/src/bus/request.rs index 7a2b5fc0..922aeb6b 100644 --- a/src/rust/lqos_bus/src/bus/request.rs +++ b/src/rust/lqos_bus/src/bus/request.rs @@ -336,6 +336,9 @@ pub enum BusRequest { /// Announce a scheduler error SchedulerError(String), + /// Write an informational message to the lqosd logs + LogInfo(String), + /// Check the scheduler status CheckSchedulerStatus, @@ -360,6 +363,9 @@ pub enum BusRequest { /// Clear a specific urgent issue by ID ClearUrgentIssue(u64), + + /// Is Insight Enabled? + CheckInsight, } /// Defines the parts of the blackboard diff --git a/src/rust/lqos_bus/src/bus/response.rs b/src/rust/lqos_bus/src/bus/response.rs index 4b58b175..d4d958ca 100644 --- a/src/rust/lqos_bus/src/bus/response.rs +++ b/src/rust/lqos_bus/src/bus/response.rs @@ -213,4 +213,7 @@ pub enum BusResponse { /// List of urgent issues UrgentIssues(Vec), + + /// Is Insight Enabled? + InsightStatus(bool), } diff --git a/src/rust/lqos_python/Cargo.toml b/src/rust/lqos_python/Cargo.toml index 71a04e32..b9b07722 100644 --- a/src/rust/lqos_python/Cargo.toml +++ b/src/rust/lqos_python/Cargo.toml @@ -20,6 +20,9 @@ nix = { workspace = true } reqwest = { workspace = true } serde = { workspace = true } chrono = "0.4.33" +serde_cbor = { workspace = true } +base64 = "0.22" +miniz_oxide = { workspace = true } [dev-dependencies] tempfile = "3.10" diff --git a/src/rust/lqos_python/src/device_weights.rs b/src/rust/lqos_python/src/device_weights.rs index 03193c03..01d7600d 100644 --- a/src/rust/lqos_python/src/device_weights.rs +++ b/src/rust/lqos_python/src/device_weights.rs @@ -13,8 +13,10 @@ use anyhow::Result; use lqos_config::{ConfigShapedDevices, ShapedDevice, load_config}; +use lqos_bus::{BusRequest, BusResponse}; use pyo3::pyclass; use serde::{Deserialize, Serialize}; +use std::time::Duration; /// This struct is used to send a request to the Long Term Stats API #[derive(Serialize, Deserialize)] @@ -63,7 +65,15 @@ fn get_weights_from_lts( let url = format!("https://{}/shaper_api/deviceWeights", base_url); // Make a BLOCKING reqwest call (we're not in an async context) - let response = reqwest::blocking::Client::new() + // Allow invalid certs for self-hosted Insight instances (non-default URL) + let allow_insecure = !url.starts_with("https://insight.libreqos.com"); + let client = reqwest::blocking::Client::builder() + .timeout(Duration::from_secs(5)) + .connect_timeout(Duration::from_secs(3)) + .danger_accept_invalid_certs(allow_insecure) + .build()?; + + let response = client .post(url) .json(&request) .send()? @@ -97,8 +107,20 @@ fn get_weights_from_shaped_devices() -> Result> { /// This function is used to determine if we should use the Long Term Stats API to get the weights fn use_lts_weights() -> bool { - let config = load_config().unwrap(); - config.long_term_stats.gather_stats && config.long_term_stats.license_key.is_some() + // Basic config gates first + let Ok(config) = load_config() else { return false }; + if !(config.long_term_stats.gather_stats && config.long_term_stats.license_key.is_some()) { + return false; + } + // Ask lqosd (via bus) whether Insight is actually enabled/licensed + if let Ok(responses) = crate::blocking::run_query(vec![BusRequest::CheckInsight]) { + for resp in responses.into_iter() { + if let BusResponse::InsightStatus(enabled) = resp { + return enabled; + } + } + } + false } /// This function is used to get the device weights from the Long Term Stats API and the ShapedDevices.csv file @@ -139,8 +161,6 @@ pub(crate) fn get_weights_rust() -> Result> { } else { eprintln!("Failed to get weights from LTS: {:?}", weights); } - } else { - eprintln!("Not using LTS weights. Using weights from ShapedDevices.csv"); } Ok(shaped_devices_weights) diff --git a/src/rust/lqos_python/src/lib.rs b/src/rust/lqos_python/src/lib.rs index 5774d612..65018b37 100644 --- a/src/rust/lqos_python/src/lib.rs +++ b/src/rust/lqos_python/src/lib.rs @@ -15,6 +15,467 @@ use anyhow::{Error, Result}; use blocking::run_query; use sysinfo::System; mod device_weights; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; +use base64::engine::general_purpose::STANDARD as BASE64_STANDARD; +use base64::Engine as _; +use std::time::Duration; + +// ===== Planner CBOR I/O ===== + +#[derive(Serialize, Deserialize, Clone, Debug, Default)] +struct PlannerSiteEntry { + cpu: i64, + major: i64, + minor: i64, + #[serde(default)] + insertion_order: Option, +} + +#[derive(Serialize, Deserialize, Clone, Debug, Default)] +struct PlannerCircuitEntry { + cpu: i64, + major: i64, + minor: i64, + #[serde(default)] + parent_site: String, + #[serde(default)] + sqm: String, +} + +#[derive(Serialize, Deserialize, Clone, Debug, Default)] +struct PlannerStateSerde { + #[serde(default = "default_algo_version")] + algo_version: String, + #[serde(default)] + updated_at: f64, + #[serde(default)] + queuesAvailable: i64, + #[serde(default)] + on_a_stick: bool, + #[serde(default)] + site_count: i64, + #[serde(default)] + site_names: Vec, + #[serde(default)] + site_map: BTreeMap, + #[serde(default)] + circuit_map: BTreeMap, +} + +fn default_algo_version() -> String { "v1".to_string() } + +fn to_i64_any(v: &pyo3::Bound<'_, pyo3::types::PyAny>) -> Option { + if let Ok(n) = v.extract::() { return Some(n); } + if let Ok(s) = v.extract::() { return s.parse::().ok(); } + None +} + +fn get_string(d: &pyo3::Bound<'_, pyo3::types::PyDict>, key: &str, default: String) -> String { + match d.get_item(key) { + Ok(Some(v)) => v.extract::().unwrap_or(default), + _ => default, + } +} + +fn get_f64(d: &pyo3::Bound<'_, pyo3::types::PyDict>, key: &str, default: f64) -> f64 { + match d.get_item(key) { + Ok(Some(v)) => v.extract::().unwrap_or(default), + _ => default, + } +} + +fn get_i64(d: &pyo3::Bound<'_, pyo3::types::PyDict>, key: &str, default: i64) -> i64 { + match d.get_item(key) { + Ok(Some(v)) => v.extract::().unwrap_or(default), + _ => default, + } +} + +fn get_bool(d: &pyo3::Bound<'_, pyo3::types::PyDict>, key: &str, default: bool) -> bool { + match d.get_item(key) { + Ok(Some(v)) => v.extract::().unwrap_or(default), + _ => default, + } +} + +#[pyfunction] +fn write_planner_cbor(py: Python, path: String, state: PyObject) -> PyResult { + use std::fs; + use std::io::Write; + let dict = state.downcast_bound::(py)?; + // Build strongly typed struct, preserving integer keys + let algo_version = get_string(&dict, "algo_version", default_algo_version()); + let updated_at = get_f64(&dict, "updated_at", 0.0); + let queues_available = get_i64(&dict, "queuesAvailable", 0); + let on_a_stick = get_bool(&dict, "on_a_stick", false); + let site_count = get_i64(&dict, "site_count", 0); + let mut site_names: Vec = Vec::new(); + if let Ok(Some(sn)) = dict.get_item("site_names") { + if let Ok(list) = sn.downcast::() { + for item in list.iter() { + if let Some(n) = to_i64_any(&item) { site_names.push(n); } + } + } + } + // site_map + let mut site_map: BTreeMap = BTreeMap::new(); + if let Ok(Some(sm_any)) = dict.get_item("site_map") { + if let Ok(sm_dict) = sm_any.downcast::() { + for (k, v) in sm_dict.iter() { + if let Some(key) = to_i64_any(&k) { + if let Ok(entry) = v.downcast::() { + let cpu = get_i64(&entry, "cpu", 0); + let major = get_i64(&entry, "major", 0); + let minor = get_i64(&entry, "minor", 0); + let insertion_order = match entry.get_item("insertion_order") { + Ok(Some(x)) => x.extract::().ok(), + _ => None, + }; + site_map.insert(key, PlannerSiteEntry { cpu, major, minor, insertion_order }); + } + } + } + } + } + // circuit_map + let mut circuit_map: BTreeMap = BTreeMap::new(); + if let Ok(Some(cm_any)) = dict.get_item("circuit_map") { + if let Ok(cm_dict) = cm_any.downcast::() { + for (k, v) in cm_dict.iter() { + if let Some(key) = to_i64_any(&k) { + if let Ok(entry) = v.downcast::() { + let cpu = get_i64(&entry, "cpu", 0); + let major = get_i64(&entry, "major", 0); + let minor = get_i64(&entry, "minor", 0); + let parent_site = get_string(&entry, "parent_site", String::new()); + let sqm = get_string(&entry, "sqm", String::new()); + circuit_map.insert(key, PlannerCircuitEntry { cpu, major, minor, parent_site, sqm }); + } + } + } + } + } + + let to_save = PlannerStateSerde { + algo_version, + updated_at, + queuesAvailable: queues_available, + on_a_stick, + site_count, + site_names, + site_map, + circuit_map, + }; + + let cbor_bytes = serde_cbor::to_vec(&to_save).map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("CBOR encode failed: {e:?}")))?; + // Compress using the standard deflate scheme used elsewhere in the project + let bytes = miniz_oxide::deflate::compress_to_vec(&cbor_bytes, 10); + let path_tmp = format!("{}.tmp", &path); + { + let mut f = fs::File::create(&path_tmp).map_err(|e| pyo3::exceptions::PyOSError::new_err(format!("Open {path_tmp} failed: {e:?}")))?; + f.write_all(&bytes).map_err(|e| pyo3::exceptions::PyOSError::new_err(format!("Write {path_tmp} failed: {e:?}")))?; + f.flush().ok(); + } + // Atomic replace + fs::rename(&path_tmp, &path).map_err(|e| pyo3::exceptions::PyOSError::new_err(format!("Rename {path_tmp} -> {path} failed: {e:?}")))?; + // Optionally, remove legacy JSON file – leave for migration + Ok(true) +} + +#[pyfunction] +fn read_planner_cbor(py: Python, path: String) -> PyResult> { + use std::fs; + use std::path::Path; + if !Path::new(&path).exists() { + return Ok(None); + } + let bytes = match fs::read(&path) { + Ok(b) => b, + Err(_) => return Ok(None), + }; + // Attempt decompress-then-decode; fall back to raw CBOR for backward compatibility + let decoded: PlannerStateSerde = if let Ok(decompressed) = miniz_oxide::inflate::decompress_to_vec(&bytes) { + match serde_cbor::from_slice(&decompressed) { + Ok(v) => v, + Err(_) => return Ok(None), + } + } else { + match serde_cbor::from_slice(&bytes) { + Ok(v) => v, + Err(_) => return Ok(None), + } + }; + // Convert to Python dict structure + let out = pyo3::types::PyDict::new(py); + out.set_item("algo_version", decoded.algo_version).ok(); + out.set_item("updated_at", decoded.updated_at).ok(); + out.set_item("queuesAvailable", decoded.queuesAvailable).ok(); + out.set_item("on_a_stick", decoded.on_a_stick).ok(); + out.set_item("site_count", decoded.site_count).ok(); + // site_names list + let list = pyo3::types::PyList::new(py, decoded.site_names).unwrap(); + out.set_item("site_names", list).ok(); + // site_map + let sm = pyo3::types::PyDict::new(py); + for (k, v) in decoded.site_map.into_iter() { + let entry = pyo3::types::PyDict::new(py); + entry.set_item("cpu", v.cpu).ok(); + entry.set_item("major", v.major).ok(); + entry.set_item("minor", v.minor).ok(); + if let Some(ins) = v.insertion_order { entry.set_item("insertion_order", ins).ok(); } + sm.set_item(k, entry).ok(); + } + out.set_item("site_map", sm).ok(); + // circuit_map + let cm = pyo3::types::PyDict::new(py); + for (k, v) in decoded.circuit_map.into_iter() { + let entry = pyo3::types::PyDict::new(py); + entry.set_item("cpu", v.cpu).ok(); + entry.set_item("major", v.major).ok(); + entry.set_item("minor", v.minor).ok(); + entry.set_item("parent_site", v.parent_site).ok(); + entry.set_item("sqm", v.sqm).ok(); + cm.set_item(k, entry).ok(); + } + out.set_item("circuit_map", cm).ok(); + Ok(Some(out.into_any().unbind())) +} + +// ===== Remote planner fetch/store over Insight web API ===== + +#[derive(Serialize, Deserialize)] +struct FetchPlannerRequest { + org_key: String, + node_id: String, + queues_available: u32, + on_a_stick: bool, + site_count: u32, +} + +#[derive(Serialize, Deserialize)] +#[serde(tag = "type", content = "content")] // allow robust parsing if needed +enum FetchPlannerResponse { + NoPlan, + PlanBase64(String), +} + +#[derive(Serialize, Deserialize)] +struct PersistPlannerRequest { + org_key: String, + node_id: String, + queues_available: u32, + on_a_stick: bool, + site_count: u32, + body_base64: String, +} + +fn base_url_from_config() -> anyhow::Result { + let config = lqos_config::load_config()?; + let base = config + .long_term_stats + .lts_url + .clone() + .unwrap_or_else(|| "insight.libreqos.com".to_string()); + Ok(format!("https://{}/shaper_api", base)) +} + +fn license_and_node_from_config() -> anyhow::Result<(String, String)> { + let config = lqos_config::load_config()?; + let org_key = config + .long_term_stats + .license_key + .clone() + .ok_or_else(|| anyhow::anyhow!("No Insight license key configured"))?; + let node_id = config.node_id.clone(); + Ok((org_key, node_id)) +} + +#[pyfunction] +fn fetch_planner_remote( + py: Python, + queues_available: i64, + on_a_stick: bool, + site_count: i64, +) -> PyResult> { + // Build request + let (org_key, node_id) = match license_and_node_from_config() { + Ok(v) => v, + Err(_) => return Ok(None), + }; + let base_url = match base_url_from_config() { + Ok(v) => v, + Err(_) => return Ok(None), + }; + let req = FetchPlannerRequest { + org_key, + node_id, + queues_available: queues_available.max(0) as u32, + on_a_stick, + site_count: site_count.max(0) as u32, + }; + let url = format!("{}/fetchPlanner", base_url); + // Send + // Allow invalid certs for self-hosted Insight instances (non-default URL) + let allow_insecure = !base_url.starts_with("https://insight.libreqos.com"); + let client = match reqwest::blocking::Client::builder() + .timeout(Duration::from_secs(5)) + .connect_timeout(Duration::from_secs(3)) + .danger_accept_invalid_certs(allow_insecure) + .build() { + Ok(c) => c, + Err(_) => return Ok(None), + }; + let resp = match client.post(&url).json(&req).send() { + Ok(r) => r, + Err(_) => return Ok(None), + }; + if !resp.status().is_success() { + return Ok(None); + } + let parsed: FetchPlannerResponse = match resp.json() { + Ok(v) => v, + Err(_) => return Ok(None), + }; + // Handle response + match parsed { + FetchPlannerResponse::NoPlan => Ok(None), + FetchPlannerResponse::PlanBase64(b64) => { + let Ok(bytes) = BASE64_STANDARD.decode(b64.as_bytes()) else { return Ok(None) }; + // Attempt decompress-then-decode; fall back to raw CBOR + let decoded: PlannerStateSerde = if let Ok(decompressed) = miniz_oxide::inflate::decompress_to_vec(&bytes) { + match serde_cbor::from_slice(&decompressed) { Ok(v) => v, Err(_) => return Ok(None) } + } else { + match serde_cbor::from_slice(&bytes) { Ok(v) => v, Err(_) => return Ok(None) } + }; + // Convert to Python dict + let out = pyo3::types::PyDict::new(py); + out.set_item("algo_version", decoded.algo_version).ok(); + out.set_item("updated_at", decoded.updated_at).ok(); + out.set_item("queuesAvailable", decoded.queuesAvailable).ok(); + out.set_item("on_a_stick", decoded.on_a_stick).ok(); + out.set_item("site_count", decoded.site_count).ok(); + let list = pyo3::types::PyList::new(py, decoded.site_names).unwrap(); + out.set_item("site_names", list).ok(); + let sm = pyo3::types::PyDict::new(py); + for (k, v) in decoded.site_map.into_iter() { + let entry = pyo3::types::PyDict::new(py); + entry.set_item("cpu", v.cpu).ok(); + entry.set_item("major", v.major).ok(); + entry.set_item("minor", v.minor).ok(); + if let Some(ins) = v.insertion_order { entry.set_item("insertion_order", ins).ok(); } + sm.set_item(k, entry).ok(); + } + out.set_item("site_map", sm).ok(); + let cm = pyo3::types::PyDict::new(py); + for (k, v) in decoded.circuit_map.into_iter() { + let entry = pyo3::types::PyDict::new(py); + entry.set_item("cpu", v.cpu).ok(); + entry.set_item("major", v.major).ok(); + entry.set_item("minor", v.minor).ok(); + entry.set_item("parent_site", v.parent_site).ok(); + entry.set_item("sqm", v.sqm).ok(); + cm.set_item(k, entry).ok(); + } + out.set_item("circuit_map", cm).ok(); + Ok(Some(out.into_any().unbind())) + } + } +} + +#[pyfunction] +fn store_planner_remote(py: Python, state: PyObject) -> PyResult { + // Extract needed values and serialize as compressed CBOR + let dict = state.downcast_bound::(py)?; + let algo_version = get_string(&dict, "algo_version", default_algo_version()); + let updated_at = get_f64(&dict, "updated_at", 0.0); + let queues_available = get_i64(&dict, "queuesAvailable", 0); + let on_a_stick = get_bool(&dict, "on_a_stick", false); + let site_count = get_i64(&dict, "site_count", 0); + // site_names + let mut site_names: Vec = Vec::new(); + if let Ok(Some(sn)) = dict.get_item("site_names") { + if let Ok(list) = sn.downcast::() { + for item in list.iter() { + if let Some(n) = to_i64_any(&item) { site_names.push(n); } + } + } + } + // site_map + let mut site_map: BTreeMap = BTreeMap::new(); + if let Ok(Some(sm_any)) = dict.get_item("site_map") { + if let Ok(sm_dict) = sm_any.downcast::() { + for (k, v) in sm_dict.iter() { + if let Some(key) = to_i64_any(&k) { + if let Ok(entry) = v.downcast::() { + let cpu = get_i64(&entry, "cpu", 0); + let major = get_i64(&entry, "major", 0); + let minor = get_i64(&entry, "minor", 0); + let insertion_order = match entry.get_item("insertion_order") { Ok(Some(x)) => x.extract::().ok(), _ => None }; + site_map.insert(key, PlannerSiteEntry { cpu, major, minor, insertion_order }); + } + } + } + } + } + // circuit_map + let mut circuit_map: BTreeMap = BTreeMap::new(); + if let Ok(Some(cm_any)) = dict.get_item("circuit_map") { + if let Ok(cm_dict) = cm_any.downcast::() { + for (k, v) in cm_dict.iter() { + if let Some(key) = to_i64_any(&k) { + if let Ok(entry) = v.downcast::() { + let cpu = get_i64(&entry, "cpu", 0); + let major = get_i64(&entry, "major", 0); + let minor = get_i64(&entry, "minor", 0); + let parent_site = get_string(&entry, "parent_site", String::new()); + let sqm = get_string(&entry, "sqm", String::new()); + circuit_map.insert(key, PlannerCircuitEntry { cpu, major, minor, parent_site, sqm }); + } + } + } + } + } + let to_save = PlannerStateSerde { + algo_version, + updated_at, + queuesAvailable: queues_available, + on_a_stick, + site_count, + site_names, + site_map, + circuit_map, + }; + let cbor_bytes = serde_cbor::to_vec(&to_save).map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("CBOR encode failed: {e:?}")))?; + let bytes = miniz_oxide::deflate::compress_to_vec(&cbor_bytes, 10); + let body_base64 = BASE64_STANDARD.encode(&bytes); + + let (org_key, node_id) = match license_and_node_from_config() { Ok(v) => v, Err(_) => return Ok(false) }; + let base_url = match base_url_from_config() { Ok(v) => v, Err(_) => return Ok(false) }; + let url = format!("{}/storePlanner", base_url); + let req = PersistPlannerRequest { + org_key, + node_id, + queues_available: queues_available.max(0) as u32, + on_a_stick, + site_count: site_count.max(0) as u32, + body_base64, + }; + // Allow invalid certs for self-hosted Insight instances (non-default URL) + let allow_insecure = !base_url.starts_with("https://insight.libreqos.com"); + let client = match reqwest::blocking::Client::builder() + .timeout(Duration::from_secs(5)) + .connect_timeout(Duration::from_secs(3)) + .danger_accept_invalid_certs(allow_insecure) + .build() { + Ok(c) => c, + Err(_) => return Ok(false), + }; + match client.put(&url).json(&req).send() { + Ok(resp) if resp.status().is_success() => Ok(true), + _ => Ok(false), + } +} const LOCK_FILE: &str = "/run/lqos/libreqos.lock"; @@ -118,6 +579,14 @@ fn liblqos_python(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_function(wrap_pyfunction!(scheduler_alive, m)?)?; m.add_function(wrap_pyfunction!(scheduler_error, m)?)?; m.add_function(wrap_pyfunction!(submit_urgent_issue, m)?)?; + m.add_function(wrap_pyfunction!(is_insight_enabled, m)?)?; + m.add_function(wrap_pyfunction!(log_info, m)?)?; + m.add_function(wrap_pyfunction!(hash_to_i64, m)?)?; + // Planner remote fetch/store for Insight integration + m.add_function(wrap_pyfunction!(fetch_planner_remote, m)?)?; + m.add_function(wrap_pyfunction!(store_planner_remote, m)?)?; + m.add_function(wrap_pyfunction!(write_planner_cbor, m)?)?; + m.add_function(wrap_pyfunction!(read_planner_cbor, m)?)?; m.add_class::()?; Ok(()) @@ -1217,3 +1686,34 @@ fn submit_urgent_issue( } Ok(false) } + +/// Log an informational message via the lqosd bus (appears in lqosd logs). +#[pyfunction] +fn log_info(_py: Python, message: String) -> PyResult { + if let Ok(reply) = run_query(vec![BusRequest::LogInfo(message)]) { + for resp in reply.iter() { + if let BusResponse::Ack = resp { + return Ok(true); + } + } + } + Ok(false) +} + +#[pyfunction] +pub fn is_insight_enabled() -> PyResult { + let Ok(responses) = run_query(vec![BusRequest::CheckInsight]) else { + return Ok(false) + }; + for resp in responses { + if let BusResponse::InsightStatus(enabled) = resp { + return Ok(enabled) + } + } + Ok(false) +} + +#[pyfunction] +pub fn hash_to_i64(text: String) -> PyResult { + Ok(lqos_utils::hash_to_i64(&text)) +} diff --git a/src/rust/lqosd/src/lts2_sys/mod.rs b/src/rust/lqosd/src/lts2_sys/mod.rs index 9308688b..2398e384 100644 --- a/src/rust/lqosd/src/lts2_sys/mod.rs +++ b/src/rust/lqosd/src/lts2_sys/mod.rs @@ -140,9 +140,40 @@ pub fn site_cake_marks(data: &[shared_types::SiteCakeMarks]) -> Result<()> { } pub fn get_lts_license_status() -> (LtsStatus, i32) { - let remaining = lts2_client::get_lts_license_trial_remaining().unwrap_or(0); - let status = lts2_client::get_lts_license_status().unwrap_or(-1); - (LtsStatus::from_i32(status), remaining) + // Use async path under the hood to avoid blocking inside a Tokio runtime. + // If we're already inside a runtime, switch to a blocking section and run a tiny + // current-thread runtime there; otherwise, build a small runtime and block_on. + if tokio::runtime::Handle::try_current().is_ok() { + tokio::task::block_in_place(|| { + let rt = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("Failed to build temporary Tokio runtime"); + rt.block_on(async { + let remaining = lts2_client::get_lts_license_trial_remaining_async() + .await + .unwrap_or(0); + let status = lts2_client::get_lts_license_status_async() + .await + .unwrap_or(-1); + (LtsStatus::from_i32(status), remaining) + }) + }) + } else { + let rt = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("Failed to build temporary Tokio runtime"); + rt.block_on(async { + let remaining = lts2_client::get_lts_license_trial_remaining_async() + .await + .unwrap_or(0); + let status = lts2_client::get_lts_license_status_async() + .await + .unwrap_or(-1); + (LtsStatus::from_i32(status), remaining) + }) + } } pub async fn get_lts_license_status_async() -> (LtsStatus, i32) { diff --git a/src/rust/lqosd/src/main.rs b/src/rust/lqosd/src/main.rs index 25d82f56..01c37c11 100644 --- a/src/rust/lqosd/src/main.rs +++ b/src/rust/lqosd/src/main.rs @@ -67,7 +67,8 @@ use crate::throughput_tracker::THROUGHPUT_TRACKER; use crate::throughput_tracker::flow_data::{ALL_FLOWS, RECENT_FLOWS}; use lqos_stormguard::STORMGUARD_STATS; use tracing::level_filters::LevelFilter; - +use crate::lts2_sys::get_lts_license_status; +use crate::lts2_sys::shared_types::LtsStatus; // Use MiMalloc only on supported platforms // #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] // #[global_allocator] @@ -638,6 +639,10 @@ fn handle_bus_requests(requests: &[BusRequest], responses: &mut Vec tool_status::scheduler_error(Some(error.clone())); BusResponse::Ack } + BusRequest::LogInfo(msg) => { + info!("BUS LOG: {}", msg); + BusResponse::Ack + } BusRequest::CheckSchedulerStatus => { let running = tool_status::is_scheduler_available(); let error = tool_status::scheduler_error_message(); @@ -655,6 +660,13 @@ fn handle_bus_requests(requests: &[BusRequest], responses: &mut Vec urgent::clear(*id); BusResponse::Ack } + BusRequest::CheckInsight => { + let (status, _) = get_lts_license_status(); + match status { + LtsStatus::Invalid | LtsStatus::NotChecked => BusResponse::InsightStatus(false), + _ => BusResponse::InsightStatus(true) + } + } }); } } diff --git a/src/rust/uisp_integration/src/uisp_types/uisp_device.rs b/src/rust/uisp_integration/src/uisp_types/uisp_device.rs index 291935c5..75aa745e 100644 --- a/src/rust/uisp_integration/src/uisp_types/uisp_device.rs +++ b/src/rust/uisp_integration/src/uisp_types/uisp_device.rs @@ -41,6 +41,9 @@ impl UispDevice { Ok(p) => p, Err(_) => return false, }; + if prefix_len > 32 { + return false; // invalid prefix for IPv4 + } // Parse the IP address let ip: Ipv4Addr = match ip_str.parse() { @@ -58,7 +61,12 @@ impl UispDevice { return false; } - let host_mask = (1u32 << host_bits) - 1; + // Build a host mask safely; shifting by 32 would overflow, so special-case /0 + let host_mask = if host_bits >= 32 { + u32::MAX + } else { + (1u32 << host_bits) - 1 + }; // Check if all host bits are zero (ip_bits & host_mask) == 0 @@ -272,6 +280,7 @@ mod tests { assert!(UispDevice::is_network_address("5.5.6.0/24")); assert!(UispDevice::is_network_address("192.168.0.0/23")); assert!(UispDevice::is_network_address("10.10.10.128/25")); // 128 = 10000000, network for /25 + assert!(UispDevice::is_network_address("0.0.0.0/0")); // Only 0.0.0.0/0 is a network address for /0 // Host addresses (should return false) assert!(!UispDevice::is_network_address("192.168.1.1/24")); @@ -282,6 +291,7 @@ mod tests { assert!(!UispDevice::is_network_address("5.5.6.1/24")); assert!(!UispDevice::is_network_address("192.168.0.1/23")); assert!(!UispDevice::is_network_address("10.10.10.129/25")); // 129 = 10000001, host in /25 + assert!(!UispDevice::is_network_address("1.2.3.4/0")); // /0 but not all host bits zero // Special cases assert!(!UispDevice::is_network_address("192.168.1.1/32")); // /32 is always a host @@ -290,5 +300,6 @@ mod tests { assert!(!UispDevice::is_network_address("")); // Empty string assert!(!UispDevice::is_network_address("not-an-ip/24")); // Invalid IP assert!(!UispDevice::is_network_address("192.168.1.0/invalid")); // Invalid prefix + assert!(!UispDevice::is_network_address("192.168.1.0/33")); // Invalid IPv4 prefix length } } -- knotmirror 0.0.1 From 5e610e271a97636b7f487702c16764e89a65f811 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Fri, 14 Nov 2025 11:29:45 -0600 Subject: [PATCH 02/15] WIP: MQ setup order was flipped? Increase deviceWeight call timeouts. --- src/rust/lqos_bakery/src/commands.rs | 24 +++++++++++++--------- src/rust/lqos_python/src/device_weights.rs | 4 ++-- 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/src/rust/lqos_bakery/src/commands.rs b/src/rust/lqos_bakery/src/commands.rs index 6ccb2474..caa9d17d 100644 --- a/src/rust/lqos_bakery/src/commands.rs +++ b/src/rust/lqos_bakery/src/commands.rs @@ -350,11 +350,12 @@ impl BakeryCommands { format!("0x{:x}:1", queue + 1), "htb".to_string(), "rate".to_string(), - format_rate_for_tc(config.queues.uplink_bandwidth_mbps), + // On ISP-facing (downlink) side, use downlink capacity + format_rate_for_tc(config.queues.downlink_bandwidth_mbps), "ceil".to_string(), - format_rate_for_tc(config.queues.uplink_bandwidth_mbps), + format_rate_for_tc(config.queues.downlink_bandwidth_mbps), "quantum".to_string(), - quantum(config.queues.uplink_bandwidth_mbps, r2q), + quantum(config.queues.downlink_bandwidth_mbps, r2q), ]); // command = 'qdisc add dev ' + thisInterface + ' parent ' + hex(queue+1) + ':1 ' + sqm() let mut class = vec![ @@ -370,7 +371,8 @@ impl BakeryCommands { // Default class - traffic gets passed through this limiter with lower priority if it enters the top HTB without a specific class. // command = 'class add dev ' + thisInterface + ' parent ' + hex(queue+1) + ':1 classid ' + hex(queue+1) + ':2 htb rate ' + format_rate_for_tc(round((upstream_bandwidth_capacity_download_mbps()-1)/4)) + ' ceil ' + format_rate_for_tc(upstream_bandwidth_capacity_download_mbps()-1) + ' prio 5' + quantum(upstream_bandwidth_capacity_download_mbps()) - let mbps = config.queues.uplink_bandwidth_mbps as f64; + // Default class parameters should also reflect downlink capacity on ISP-facing side + let mbps = config.queues.downlink_bandwidth_mbps as f64; let mbps_quarter = (mbps - 1.0) / 4.0; let mbps_minus_one = mbps - 1.0; result.push(vec![ @@ -390,7 +392,7 @@ impl BakeryCommands { "prio".to_string(), "5".to_string(), "quantum".to_string(), - quantum(config.queues.uplink_bandwidth_mbps, r2q), + quantum(config.queues.downlink_bandwidth_mbps, r2q), ]); // command = 'qdisc add dev ' + thisInterface + ' parent ' + hex(queue+1) + ':2 ' + sqm() let mut default_class = vec![ @@ -462,11 +464,12 @@ impl BakeryCommands { format!("0x{:x}:1", queue + stick_offset + 1), "htb".to_string(), "rate".to_string(), - format_rate_for_tc(config.queues.downlink_bandwidth_mbps), + // Internet-facing (uplink) side should use uplink capacity + format_rate_for_tc(config.queues.uplink_bandwidth_mbps), "ceil".to_string(), - format_rate_for_tc(config.queues.downlink_bandwidth_mbps), + format_rate_for_tc(config.queues.uplink_bandwidth_mbps), "quantum".to_string(), - quantum(config.queues.downlink_bandwidth_mbps, r2q), + quantum(config.queues.uplink_bandwidth_mbps, r2q), ]); // command = 'qdisc add dev ' + thisInterface + ' parent ' + hex(queue+stickOffset+1) + ':1 ' + sqm() let mut class = vec![ @@ -481,7 +484,8 @@ impl BakeryCommands { result.push(class); // Default class - traffic gets passed through this limiter with lower priority if it enters the top HTB without a specific class. // command = 'class add dev ' + thisInterface + ' parent ' + hex(queue+stickOffset+1) + ':1 classid ' + hex(queue+stickOffset+1) + ':2 htb rate ' + format_rate_for_tc(round((upstream_bandwidth_capacity_upload_mbps()-1)/4)) + ' ceil ' + format_rate_for_tc(upstream_bandwidth_capacity_upload_mbps()-1) + ' prio 5' + quantum(upstream_bandwidth_capacity_upload_mbps()) - let mbps = config.queues.downlink_bandwidth_mbps as f64; + // Default class parameters should reflect uplink capacity on Internet-facing side + let mbps = config.queues.uplink_bandwidth_mbps as f64; let mbps_quarter = (mbps - 1.0) / 4.0; let mbps_minus_one = mbps - 1.0; result.push(vec![ @@ -501,7 +505,7 @@ impl BakeryCommands { "prio".to_string(), "5".to_string(), "quantum".to_string(), - quantum(config.queues.downlink_bandwidth_mbps, r2q), + quantum(config.queues.uplink_bandwidth_mbps, r2q), ]); // command = 'qdisc add dev ' + thisInterface + ' parent ' + hex(queue+stickOffset+1) + ':2 ' + sqm() let mut default_class = vec![ diff --git a/src/rust/lqos_python/src/device_weights.rs b/src/rust/lqos_python/src/device_weights.rs index 01d7600d..6edf052e 100644 --- a/src/rust/lqos_python/src/device_weights.rs +++ b/src/rust/lqos_python/src/device_weights.rs @@ -68,8 +68,8 @@ fn get_weights_from_lts( // Allow invalid certs for self-hosted Insight instances (non-default URL) let allow_insecure = !url.starts_with("https://insight.libreqos.com"); let client = reqwest::blocking::Client::builder() - .timeout(Duration::from_secs(5)) - .connect_timeout(Duration::from_secs(3)) + .timeout(Duration::from_secs(10)) + .connect_timeout(Duration::from_secs(6)) .danger_accept_invalid_certs(allow_insecure) .build()?; -- knotmirror 0.0.1 From 74147619e75b79d3cae3bfaecf0c320aa6538fd9 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Fri, 14 Nov 2025 11:37:38 -0600 Subject: [PATCH 03/15] WIP: Kill the mold linker (it is failing hard with newer Rust builds on older Linux) --- src/rust/.cargo/config.toml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/rust/.cargo/config.toml b/src/rust/.cargo/config.toml index b0de9249..19fcb266 100644 --- a/src/rust/.cargo/config.toml +++ b/src/rust/.cargo/config.toml @@ -1,3 +1,3 @@ -[target.x86_64-unknown-linux-gnu] -linker = "/usr/bin/clang" -rustflags = ["-C", "link-arg=--ld-path=/usr/bin/mold"] +#[target.x86_64-unknown-linux-gnu] +#linker = "/usr/bin/clang" +#rustflags = ["-C", "link-arg=--ld-path=/usr/bin/mold"] -- knotmirror 0.0.1 From 1c3545ac25006611054c4456ab24f032666f2fb1 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Fri, 14 Nov 2025 12:16:56 -0600 Subject: [PATCH 04/15] WIP: Fixup the Generated_PN items that shouldn't have been binpacked to begin with! --- src/LibreQoS.py | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/src/LibreQoS.py b/src/LibreQoS.py index f3d03c8a..5b9090be 100755 --- a/src/LibreQoS.py +++ b/src/LibreQoS.py @@ -1644,6 +1644,12 @@ def refreshShapers(): site_name = name_hash_to_name.get(int(site_hash)) if site_name is None: continue + # Skip synthetic default PN containers in site binning + try: + if str(site_name).startswith('Generated_PN_'): + continue + except Exception: + pass node_obj = all_nodes.get(site_name) if node_obj is None: continue @@ -1658,6 +1664,22 @@ def refreshShapers(): except Exception: pass binnedNetwork[cpuKey]['children'][site_name] = node_obj + # After placing real sites, guarantee one Generated_PN per CPU + try: + for idx, pn in enumerate(generatedPNs): + cpuKey = "CpueQueue" + str(idx if idx < queuesAvailable else queuesAvailable-1) + node_obj = network.get(pn) if isinstance(network, dict) else None + if node_obj is None: + node_obj = { + 'downloadBandwidthMbps': generated_pn_download_mbps(), + 'uploadBandwidthMbps': generated_pn_upload_mbps(), + 'type': 'site', + 'downloadBandwidthMbpsMin': generated_pn_download_mbps(), + 'uploadBandwidthMbpsMin': generated_pn_upload_mbps(), + } + binnedNetwork[cpuKey]['children'][pn] = node_obj + except Exception: + pass network = binnedNetwork else: print("Using greedy binpacking to distribute sites across CPU queues.") @@ -1676,6 +1698,12 @@ def refreshShapers(): except Exception: pass for node in network: + # Exclude Generated_PN_* from site binpacking entirely + try: + if str(node).startswith('Generated_PN_'): + continue + except Exception: + pass w = weight_by_name.get(str(node), 1.0) items.append({"id": str(node), "weight": float(w)}) @@ -1704,10 +1732,31 @@ def refreshShapers(): 'name': cpuKey } for node in network: + try: + if str(node).startswith('Generated_PN_'): + continue + except Exception: + pass tgt = assignment.get(node) if tgt is None: tgt = "CpueQueue" + str(queuesAvailable - 1) binnedNetwork[tgt]['children'][node] = network[node] + # After placing real sites, guarantee one Generated_PN per CPU + try: + for idx, pn in enumerate(generatedPNs): + cpuKey = "CpueQueue" + str(idx if idx < queuesAvailable else queuesAvailable-1) + node_obj = network.get(pn) if isinstance(network, dict) else None + if node_obj is None: + node_obj = { + 'downloadBandwidthMbps': generated_pn_download_mbps(), + 'uploadBandwidthMbps': generated_pn_upload_mbps(), + 'type': 'site', + 'downloadBandwidthMbpsMin': generated_pn_download_mbps(), + 'uploadBandwidthMbpsMin': generated_pn_upload_mbps(), + } + binnedNetwork[cpuKey]['children'][pn] = node_obj + except Exception: + pass network = binnedNetwork # Here is the actual call to the recursive traverseNetwork() function. finalMinor is not used. -- knotmirror 0.0.1 From bb752ad7f8c29da076dc3928bb3193450bc9c806 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Fri, 14 Nov 2025 12:50:00 -0600 Subject: [PATCH 05/15] WIP: Integration test now includes testing the generatedPNs. --- src/bakery_integration_test.py | 351 +++++++++++++++++++++++++++++++++ 1 file changed, 351 insertions(+) diff --git a/src/bakery_integration_test.py b/src/bakery_integration_test.py index 8bd1abbe..e3398193 100644 --- a/src/bakery_integration_test.py +++ b/src/bakery_integration_test.py @@ -56,6 +56,7 @@ import sys import time from dataclasses import dataclass from typing import Dict, List, Optional, Tuple +import subprocess # Import LibreQoS and lqosd helpers without invoking the __main__ block @@ -72,6 +73,20 @@ try: from liblqos_python import log_info # type: ignore except Exception: log_info = None # type: ignore + # Optional helpers for interface name and PN speeds + try: + from liblqos_python import interface_a # type: ignore + except Exception: + interface_a = None # type: ignore + try: + from liblqos_python import interface_b # type: ignore + except Exception: + interface_b = None # type: ignore + try: + from liblqos_python import generated_pn_download_mbps, generated_pn_upload_mbps # type: ignore + except Exception: + generated_pn_download_mbps = None # type: ignore + generated_pn_upload_mbps = None # type: ignore except Exception: # Provide a soft fallback if binding is unavailable def is_lqosd_alive() -> bool: @@ -325,6 +340,321 @@ def run_refresh_and_wait(log: LogReader, timeout_s: float) -> LogResult: return log.wait_for_events(offset, timeout_s=timeout_s) +# ----------------------- +# TC and structure checks +# ----------------------- + +def _tc(args: List[str]) -> Tuple[int, str, str]: + try: + proc = subprocess.run(["/sbin/tc"] + args, capture_output=True, text=True, check=False) + return proc.returncode, proc.stdout, proc.stderr + except Exception as e: + return 127, "", str(e) + + +def check_default_classes_present_on_iface() -> Tuple[bool, str]: + """Verify that on the first interface, default classes exist: class :2 parent :1. + + Returns (passed, message). + """ + if not interface_a or not callable(interface_a): # type: ignore[name-defined] + return False, "tc check: interface_a() binding unavailable" + try: + iface = interface_a() # type: ignore[misc] + except Exception as e: + return False, f"tc check: failed to get interface_a(): {e}" + rc, out, err = _tc(["class", "show", "dev", iface]) + if rc != 0: + return False, f"tc check: 'tc class show dev {iface}' failed: {err.strip()}" + # Look for any line where child is :2 and parent is same major :1 + pat = re.compile(r"^class\s+htb\s+(\w+):2\s+parent\s+\1:1\b", re.MULTILINE) + if pat.search(out): + return True, f"tc check: default class present on {iface}" + return False, f"tc check: default class not found on {iface}" + + +def _load_queuing_structure() -> Optional[dict]: + try: + with open("queuingStructure.json", "r") as f: + return json.load(f) + except Exception: + return None + + +def assert_generated_pns_present() -> Tuple[bool, List[str]]: + msgs: List[str] = [] + qs = _load_queuing_structure() + if not isinstance(qs, dict): + return False, ["queuingStructure.json not found or unreadable"] + net = qs.get("Network") + if not isinstance(net, dict): + return False, ["queuingStructure.json has no 'Network' dict"] + gpns = qs.get("generatedPNs") + if not isinstance(gpns, list) or not gpns: + return False, ["No generatedPNs listed in queuingStructure.json"] + # Two shapes are valid: + # 1) Binpacked: Generated_PN_* appear under CpueQueue* children. + # 2) Non-binpacked: Generated_PN_* appear at top-level of Network. + cpu_bins = [(k, v) for k, v in net.items() if isinstance(k, str) and k.startswith("CpueQueue")] + if cpu_bins: + found_under_cpu = 0 + for k, v in cpu_bins: + ch = v.get("children") if isinstance(v, dict) else None + if isinstance(ch, dict) and any(isinstance(nm, str) and nm.startswith("Generated_PN_") for nm in ch.keys()): + found_under_cpu += 1 + if found_under_cpu == 0: + return False, ["No Generated_PN_* found under any CpueQueue* in queuingStructure.json"] + msgs.append(f"generated PN presence: found under {found_under_cpu} CPU bins") + return True, msgs + # Top-level fallback + top_level_pn = [k for k in net.keys() if isinstance(k, str) and k.startswith("Generated_PN_")] + if not top_level_pn: + return False, ["No Generated_PN_* found at top-level of queuingStructure.json"] + msgs.append(f"generated PN presence: found {len(top_level_pn)} at top-level") + return True, msgs + + +def _find_pn_nodes(net: Dict[str, dict]) -> List[Tuple[str, dict]]: + result: List[Tuple[str, dict]] = [] + def walk(node_map: Dict[str, dict]): + for k, v in node_map.items(): + if not isinstance(v, dict): + continue + if isinstance(k, str) and k.startswith("Generated_PN_"): + result.append((k, v)) + ch = v.get("children") if isinstance(v, dict) else None + if isinstance(ch, dict): + walk(ch) + walk(net) + return result + + +def _hex_to_int(s: str) -> Optional[int]: + try: + if isinstance(s, str): + return int(s, 16) if s.startswith("0x") else int(s) + if isinstance(s, int): + return int(s) + except Exception: + return None + return None + + +def _parse_tc_rate_to_mbps(token: str, unit: Optional[str]) -> float: + try: + val = float(token) + except Exception: + return -1.0 + mult = 1.0 + if unit is None or unit == "": + # tc typically prints explicit units; be conservative and treat as mbit + mult = 1.0 + else: + u = unit.upper() + if u == 'G': + mult = 1000.0 + elif u == 'M': + mult = 1.0 + elif u == 'K': + mult = 0.001 + else: + mult = 1.0 + return val * mult + + +def _read_htb_rate_ceil_mbps(iface: str, major: int, minor: int) -> Optional[Tuple[float, float, str]]: + rc, out, err = _tc(["class", "show", "dev", iface]) + if rc != 0: + return None + # Match the exact class line for major:minor in decimal + cls_pat = re.compile(rf"^class\s+htb\s+{major}:{minor}\b.*$", re.MULTILINE) + m = cls_pat.search(out) + if not m: + return None + line = m.group(0) + # Extract rate and ceil tokens + rpat = re.compile(r"rate\s+([0-9]+(?:\.[0-9]+)?)([GMK])?bit.*?ceil\s+([0-9]+(?:\.[0-9]+)?)([GMK])?bit") + mm = rpat.search(line) + if not mm: + return None + rate_mbps = _parse_tc_rate_to_mbps(mm.group(1), mm.group(2)) + ceil_mbps = _parse_tc_rate_to_mbps(mm.group(3), mm.group(4)) + return rate_mbps, ceil_mbps, line + + +def check_generated_pn_tc_bandwidths() -> Tuple[bool, List[str]]: + msgs: List[str] = [] + qs = _load_queuing_structure() + if not isinstance(qs, dict): + return False, ["PN tc check: queuingStructure.json not found"] + net = qs.get("Network") + if not isinstance(net, dict): + return False, ["PN tc check: queuingStructure has no 'Network'"] + # Resolve PN config + if not generated_pn_download_mbps or not generated_pn_upload_mbps: + return False, ["PN tc check: PN defaults not available via bindings"] + try: + expect_dl = float(generated_pn_download_mbps()) + expect_ul = float(generated_pn_upload_mbps()) + except Exception as e: + return False, [f"PN tc check: failed reading PN defaults: {e}"] + # Enumerate PN nodes + pn_nodes = _find_pn_nodes(net) + if not pn_nodes: + return False, ["PN tc check: no Generated_PN_* nodes found in structure"] + # Interfaces + if not interface_a or not callable(interface_a): + return False, ["PN tc check: interface_a() binding unavailable"] + try: + ifa = interface_a() + except Exception as e: + return False, [f"PN tc check: failed to read interface_a(): {e}"] + ifb = None + if interface_b and callable(interface_b): + try: + ifb = interface_b() + except Exception: + ifb = None + # Check each PN on downlink side (interface_a) + ok_all = True + for name, node in pn_nodes: + maj_hex = node.get("classMajor") + min_hex = node.get("classMinor") + # Fallback to parse from classid if needed + if (maj_hex is None or min_hex is None) and isinstance(node.get("classid"), str): + try: + maj_s, min_s = str(node["classid"]).split(":", 1) + maj_hex = maj_hex or maj_s + min_hex = min_hex or min_s + except Exception: + pass + maj = _hex_to_int(maj_hex) if isinstance(maj_hex, str) else _hex_to_int(str(maj_hex)) + mnr = _hex_to_int(min_hex) if isinstance(min_hex, str) else _hex_to_int(str(min_hex)) + if maj is None or mnr is None: + msgs.append(f"PN tc check: {name} missing classMajor/classMinor") + ok_all = False + continue + res = _read_htb_rate_ceil_mbps(ifa, maj, mnr) + if not res: + msgs.append(f"PN tc check: {name} class {maj}:{mnr} not found on {ifa}") + ok_all = False + continue + rate_mbps, ceil_mbps, line = res + msgs.append(f"PN {name} {ifa} class {maj}:{mnr} rate={rate_mbps:.1f} ceil={ceil_mbps:.1f} (expected {expect_dl:.1f}) | {line.strip()}") + # Allow small tolerance due to rounding + if abs(rate_mbps - expect_dl) > 1.0 or abs(ceil_mbps - expect_dl) > 1.0: + ok_all = False + # Check uplink side if available + if ifb: + for name, node in pn_nodes: + up_maj_hex = node.get("up_classMajor") + min_hex = node.get("classMinor") + if (up_maj_hex is None or min_hex is None) and isinstance(node.get("up_classid"), str): + try: + upm_s, mins = str(node["up_classid"]).split(":", 1) + up_maj_hex = up_maj_hex or upm_s + min_hex = min_hex or mins + except Exception: + pass + upmaj = _hex_to_int(up_maj_hex) if isinstance(up_maj_hex, str) else _hex_to_int(str(up_maj_hex)) + mnr = _hex_to_int(min_hex) if isinstance(min_hex, str) else _hex_to_int(str(min_hex)) + if upmaj is None or mnr is None: + msgs.append(f"PN tc check: {name} missing up_classMajor/classMinor") + ok_all = False + continue + res = _read_htb_rate_ceil_mbps(ifb, upmaj, mnr) + if not res: + msgs.append(f"PN tc check: {name} class {upmaj}:{mnr} not found on {ifb}") + ok_all = False + continue + rate_mbps, ceil_mbps, line = res + msgs.append(f"PN {name} {ifb} class {upmaj}:{mnr} rate={rate_mbps:.1f} ceil={ceil_mbps:.1f} (expected {expect_ul:.1f}) | {line.strip()}") + if abs(rate_mbps - expect_ul) > 1.0 or abs(ceil_mbps - expect_ul) > 1.0: + ok_all = False + return ok_all, msgs + + +def _walk_nodes_for_circuit(node_map: Dict[str, dict], circuit_id: str) -> Optional[Tuple[str, dict]]: + for name, node in node_map.items(): + if not isinstance(node, dict): + continue + if "circuits" in node and isinstance(node["circuits"], list): + for c in node["circuits"]: + try: + if str(c.get("circuitID", "")) == str(circuit_id): + return name, c + except Exception: + pass + ch = node.get("children") if isinstance(node, dict) else None + if isinstance(ch, dict): + found = _walk_nodes_for_circuit(ch, circuit_id) + if found: + return found + return None + + +def test_orphan_circuit_assignment(csv_rows: List[Dict[str, object]]) -> Tuple[bool, List[str]]: + """Append an orphan circuit (ParentNode=none) with max speeds below PN defaults, + refresh, and assert it landed under a Generated_PN_* with its original max speeds. + """ + msgs: List[str] = [] + # Determine PN defaults; require the bindings + if not generated_pn_download_mbps or not generated_pn_upload_mbps: # type: ignore[name-defined] + return False, ["PN default speeds unavailable via bindings"] + try: + pn_dl = int(generated_pn_download_mbps()) # type: ignore[misc] + pn_ul = int(generated_pn_upload_mbps()) # type: ignore[misc] + except Exception as e: + return False, [f"Failed to read PN defaults: {e}"] + # Choose conservative orphan speeds strictly below PN defaults + orphan_dl = max(1, min(25, pn_dl - 1)) + orphan_ul = max(1, min(25, pn_ul - 1)) + orphan_id = "99901" + orphan_row: Dict[str, object] = { + "Circuit ID": orphan_id, + "Circuit Name": "ORPHAN_TEST", + "Device ID": "99901", + "Device Name": "OD1", + "Parent Node": "none", + "MAC": "", + "IPv4": "100.64.250.1", + "IPv6": "", + "Download Min Mbps": 1, + "Upload Min Mbps": 1, + "Download Max Mbps": orphan_dl, + "Upload Max Mbps": orphan_ul, + "Comment": "", + "sqm": "", + } + rows2 = list(csv_rows) + [orphan_row] + write_circuits(rows2) + # Trigger refresh + LibreQoS.refreshShapers() + time.sleep(0.5) + # Load structure + qs = _load_queuing_structure() + if not isinstance(qs, dict): + return False, ["queuingStructure.json not found after orphan test"] + net = qs.get("Network") + if not isinstance(net, dict): + return False, ["queuingStructure.json missing 'Network' after orphan test"] + found = _walk_nodes_for_circuit(net, orphan_id) + if not found: + return False, ["Orphan circuit not found in queuing structure"] + parent_name, circuit = found + if not str(parent_name).startswith("Generated_PN_"): + return False, [f"Orphan circuit parent is not a Generated_PN_*: {parent_name}"] + try: + md = float(circuit.get("maxDownload", -1)) + mu = float(circuit.get("maxUpload", -1)) + except Exception: + return False, ["Orphan circuit missing maxDownload/maxUpload in structure"] + if int(md) != orphan_dl or int(mu) != orphan_ul: + return False, [f"Orphan circuit speeds mismatch (got {md}/{mu}, expected {orphan_dl}/{orphan_ul})"] + msgs.append(f"orphan circuit assigned to {parent_name} with speeds {orphan_dl}/{orphan_ul} Mbps") + return True, msgs + + def assert_no_full_reload(tag: str, res: LogResult, step_started_at: Optional[float] = None) -> Tuple[bool, str]: if res.full_reload and not res.mq_init: ts = ( @@ -405,6 +735,27 @@ def run_tiered_suite(log: LogReader, timeout_s: float, results: List[str]) -> bo results.append(msg) ok &= passed + # Sanity: verify defaults, PN presence, and orphan assignment behavior on tiered setup + _mark_step("sanity: default classes present on interface_a") + passed, msg = check_default_classes_present_on_iface() + results.append(msg) + ok &= passed + + _mark_step("sanity: generated PN items present") + passed2, msgs = assert_generated_pns_present() + results.extend(msgs) + ok &= passed2 + + _mark_step("sanity: orphan circuit assigned under Generated_PN with original speeds") + passed3, msgs3 = test_orphan_circuit_assignment(rows) + results.extend(msgs3) + ok &= passed3 + + _mark_step("sanity: PN HTB rates match PN defaults") + passed4, msgs4 = check_generated_pn_tc_bandwidths() + results.extend(msgs4) + ok &= passed4 + # Circuit speed change _mark_step("flat: circuit speed change") _mark_step("tiered: circuit speed change") -- knotmirror 0.0.1 From 08ef5c0e82cee0abe8d1f61a0586c7d728097fb3 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Fri, 14 Nov 2025 12:56:10 -0600 Subject: [PATCH 06/15] WIP: Verified that generated_pn classes are actually in the tree now. --- src/LibreQoS.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/LibreQoS.py b/src/LibreQoS.py index 5b9090be..726abcd9 100755 --- a/src/LibreQoS.py +++ b/src/LibreQoS.py @@ -2062,10 +2062,12 @@ def refreshShapers(): def emit_sites(data): for node in sorted(data.keys()): site_name = data[node]['name'] if 'name' in data[node] else node - # Avoid creating Bakery sites for Generated_PN_* or CpueQueue* when not in flat mode + # Avoid creating Bakery sites for CpueQueue* (CPU bin containers) when not in flat mode. + # Generated_PN_* must be real HTB parents (one per CPU) so circuits under them have valid parents; + # therefore, do NOT skip Generated_PN_* here. try: name_s = str(site_name) - if (not is_network_flat()) and (name_s.startswith('Generated_PN_') or name_s.startswith('CpueQueue')): + if (not is_network_flat()) and (name_s.startswith('CpueQueue')): # Recurse into children to ensure real sites are still emitted if 'children' in data[node]: sorted_children = dict(sorted(data[node]['children'].items())) -- knotmirror 0.0.1 From fab66c630737c9b2736a0eed32814c2b632dee9c Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Fri, 14 Nov 2025 13:49:20 -0600 Subject: [PATCH 07/15] WIP: lqosd bakery build errors are logged to /tmp, some tweaks around default item generation. --- src/bakery_integration_test.py | 150 +++++++++++++++++++++++++++ src/rust/lqos_bakery/src/commands.rs | 12 ++- src/rust/lqos_bakery/src/utils.rs | 25 ++++- 3 files changed, 179 insertions(+), 8 deletions(-) diff --git a/src/bakery_integration_test.py b/src/bakery_integration_test.py index e3398193..a2ae7c53 100644 --- a/src/bakery_integration_test.py +++ b/src/bakery_integration_test.py @@ -373,6 +373,24 @@ def check_default_classes_present_on_iface() -> Tuple[bool, str]: return False, f"tc check: default class not found on {iface}" +def check_default_classes_present_on_iface_b() -> Tuple[bool, str]: + """Same as above but for interface_b when available.""" + if not interface_b or not callable(interface_b): # type: ignore[name-defined] + return True, "tc check: interface_b() unavailable; skipping" + try: + iface = interface_b() # type: ignore[misc] + except Exception as e: + return False, f"tc check: failed to get interface_b(): {e}" + rc, out, err = _tc(["class", "show", "dev", iface]) + if rc != 0: + return False, f"tc check: 'tc class show dev {iface}' failed: {err.strip()}" + # Match: class htb :2 parent :1 + pat = re.compile(r"^class\s+htb\s+(\w+):2\s+parent\s+\1:1\b", re.MULTILINE) + if pat.search(out): + return True, f"tc check: default class present on {iface}" + return False, f"tc check: default class not found on {iface}" + + def _load_queuing_structure() -> Optional[dict]: try: with open("queuingStructure.json", "r") as f: @@ -574,6 +592,130 @@ def check_generated_pn_tc_bandwidths() -> Tuple[bool, List[str]]: return ok_all, msgs +def _class_has_parent(iface: str, maj: int, mnr: int, pmaj: int, pmnr: int) -> Tuple[bool, Optional[str]]: + """Robustly verify that class maj:mnr has parent pmaj:pmnr on iface. + + Accepts both decimal and 0x-prefixed hex forms as printed by tc. + Returns (True, line) when parent matches, else (False, line or None). + """ + rc, out, err = _tc(["class", "show", "dev", iface]) + if rc != 0: + return False, f"tc error: {err.strip()}" + # Find the specific class line first + cls_pat = re.compile(rf"^class\s+htb\s+{maj}:{mnr}\b.*$", re.MULTILINE) + m = cls_pat.search(out) + if not m: + return False, None + line = m.group(0) + # Extract parent handle (supports hex or decimal) + p = re.search(r"parent\s+([0-9A-Fa-fx]+):([0-9A-Fa-fx]+)\b", line) + if not p: + return False, line + def _to_int(tok: str) -> Optional[int]: + try: + s = tok.strip() + if s.lower().startswith("0x"): + return int(s, 16) + return int(s) + except Exception: + return None + pmj = _to_int(p.group(1)) + pmn = _to_int(p.group(2)) + if pmj is None or pmn is None: + return False, line + return (pmj == pmaj and pmn == pmnr), line + + +def check_orphan_tc_attachment(orphan_id: str = "99901") -> Tuple[bool, List[str]]: + msgs: List[str] = [] + qs = _load_queuing_structure() + if not isinstance(qs, dict): + return False, ["orphan tc check: queuingStructure.json not found"] + net = qs.get("Network") + if not isinstance(net, dict): + return False, ["orphan tc check: missing 'Network'"] + found = _walk_nodes_for_circuit(net, orphan_id) + if not found: + return False, ["orphan tc check: orphan circuit not found in structure"] + parent_name, circuit = found + # Locate PN node object + def _find_node(node_map: Dict[str, dict], name: str) -> Optional[dict]: + for k, v in node_map.items(): + if k == name and isinstance(v, dict): + return v + ch = v.get("children") if isinstance(v, dict) else None + if isinstance(ch, dict): + got = _find_node(ch, name) + if got is not None: + return got + return None + pn_node = _find_node(net, parent_name) + if not isinstance(pn_node, dict): + return False, [f"orphan tc check: PN node '{parent_name}' not found"] + # Downlink + if not interface_a or not callable(interface_a): + return False, ["orphan tc check: interface_a() unavailable"] + try: + ifa = interface_a() + except Exception as e: + return False, [f"orphan tc check: failed to get interface_a(): {e}"] + maj_hex = circuit.get("classMajor") + cmin_hex = circuit.get("classMinor") + pmaj_hex = pn_node.get("classMajor") + pmin_hex = pn_node.get("classMinor") + maj = _hex_to_int(maj_hex if isinstance(maj_hex, str) else str(maj_hex)) + cmin = _hex_to_int(cmin_hex if isinstance(cmin_hex, str) else str(cmin_hex)) + pmaj = _hex_to_int(pmaj_hex if isinstance(pmaj_hex, str) else str(pmaj_hex)) + pmin = _hex_to_int(pmin_hex if isinstance(pmin_hex, str) else str(pmin_hex)) + if None in (maj, cmin, pmaj, pmin): + return False, ["orphan tc check: missing classMajor/classMinor for PN or circuit (downlink)"] + ok_dl, line_dl = _class_has_parent(ifa, maj, cmin, pmaj, pmin) + if not ok_dl: + # Diagnostic hook: show the actual class line if present + diag = _read_htb_rate_ceil_mbps(ifa, maj, cmin) + if diag: + _, _, raw = diag + msgs.append( + f"orphan tc check: downlink class {maj}:{cmin} not attached to parent {pmaj}:{pmin} on {ifa} | {raw}" + ) + else: + msgs.append( + f"orphan tc check: downlink class {maj}:{cmin} not attached to parent {pmaj}:{pmin} on {ifa} (class not found)" + ) + return False, msgs + msgs.append(f"orphan tc check: {ifa} class {maj}:{cmin} parent {pmaj}:{pmin} | {line_dl}") + # Uplink (optional) + if interface_b and callable(interface_b): + try: + ifb = interface_b() + upm_hex = circuit.get("up_classMajor") + upmaj = _hex_to_int(upm_hex if isinstance(upm_hex, str) else str(upm_hex)) + # Circuit minor is same + up_pmaj_hex = pn_node.get("up_classMajor") + up_pmaj = _hex_to_int(up_pmaj_hex if isinstance(up_pmaj_hex, str) else str(up_pmaj_hex)) + if None not in (upmaj, cmin, up_pmaj, pmin): + ok_ul, line_ul = _class_has_parent(ifb, upmaj, cmin, up_pmaj, pmin) + if ok_ul: + msgs.append(f"orphan tc check: {ifb} class {upmaj}:{cmin} parent {up_pmaj}:{pmin} | {line_ul}") + else: + # Diagnostic hook: show the actual class line if present + diag_ul = _read_htb_rate_ceil_mbps(ifb, upmaj, cmin) + if diag_ul: + _, _, raw_ul = diag_ul + msgs.append( + f"orphan tc check: uplink class {upmaj}:{cmin} not attached to parent {up_pmaj}:{pmin} on {ifb} | {raw_ul}" + ) + else: + msgs.append( + f"orphan tc check: uplink class {upmaj}:{cmin} not attached to parent {up_pmaj}:{pmin} on {ifb} (class not found)" + ) + else: + msgs.append("orphan tc check: uplink IDs missing; skipping uplink parent check") + except Exception: + msgs.append("orphan tc check: interface_b() failed; skipping uplink parent check") + return True, msgs + + def _walk_nodes_for_circuit(node_map: Dict[str, dict], circuit_id: str) -> Optional[Tuple[str, dict]]: for name, node in node_map.items(): if not isinstance(node, dict): @@ -740,6 +882,10 @@ def run_tiered_suite(log: LogReader, timeout_s: float, results: List[str]) -> bo passed, msg = check_default_classes_present_on_iface() results.append(msg) ok &= passed + # Also validate interface_b when available + passed_b, msg_b = check_default_classes_present_on_iface_b() + results.append(msg_b) + ok &= passed_b _mark_step("sanity: generated PN items present") passed2, msgs = assert_generated_pns_present() @@ -755,6 +901,10 @@ def run_tiered_suite(log: LogReader, timeout_s: float, results: List[str]) -> bo passed4, msgs4 = check_generated_pn_tc_bandwidths() results.extend(msgs4) ok &= passed4 + _mark_step("sanity: orphan circuit HTB attached to PN parent in tc") + passed5, msgs5 = check_orphan_tc_attachment("99901") + results.extend(msgs5) + ok &= passed5 # Circuit speed change _mark_step("flat: circuit speed change") diff --git a/src/rust/lqos_bakery/src/commands.rs b/src/rust/lqos_bakery/src/commands.rs index caa9d17d..651a6f46 100644 --- a/src/rust/lqos_bakery/src/commands.rs +++ b/src/rust/lqos_bakery/src/commands.rs @@ -540,9 +540,11 @@ impl BakeryCommands { command = 'class add dev ' + interface_b() + ' parent ' + data[node]['up_parentClassID'] + ' classid ' + data[node]['classMinor'] + ' htb rate '+ format_rate_for_tc(data[node]['uploadBandwidthMbpsMin']) + ' ceil '+ format_rate_for_tc(data[node]['uploadBandwidthMbps']) + ' prio 3' + quantum(data[node]['uploadBandwidthMbps']) */ + // In builder mode, these site classes are being created for the first time. + // Use 'add' rather than 'replace' to avoid failures on fresh builds. result.push(vec![ "class".to_string(), - "replace".to_string(), + "add".to_string(), "dev".to_string(), config.isp_interface(), "parent".to_string(), @@ -564,7 +566,7 @@ impl BakeryCommands { ]); result.push(vec![ "class".to_string(), - "replace".to_string(), + "add".to_string(), "dev".to_string(), config.internet_interface(), "parent".to_string(), @@ -685,9 +687,10 @@ impl BakeryCommands { pass */ if do_htb { + let verb = if execution_mode == ExecutionMode::Builder { "add" } else { "replace" }; result.push(vec![ "class".to_string(), - "replace".to_string(), + verb.to_string(), "dev".to_string(), config.isp_interface(), "parent".to_string(), @@ -728,9 +731,10 @@ impl BakeryCommands { } if do_htb { + let verb = if execution_mode == ExecutionMode::Builder { "add" } else { "replace" }; result.push(vec![ "class".to_string(), - "replace".to_string(), + verb.to_string(), "dev".to_string(), config.internet_interface(), "parent".to_string(), diff --git a/src/rust/lqos_bakery/src/utils.rs b/src/rust/lqos_bakery/src/utils.rs index 5401dc66..fae7e29b 100644 --- a/src/rust/lqos_bakery/src/utils.rs +++ b/src/rust/lqos_bakery/src/utils.rs @@ -50,13 +50,30 @@ pub(crate) fn execute_in_memory(command_buffer: &Vec>, purpose: &str // tc -batch reports 1-based line numbers numbered.push_str(&format!("{:>4}: {}\n", i + 1, line)); } - let message = format!( - "Command error for ({purpose}): {:?}. Error: {}\nCommands with line numbers:\n{}", - error_str.trim(), + let detailed = format!( + "Command error for ({purpose}): {}\nCommands with line numbers:\n{}", error_str.trim(), numbered ); - error!(message); + // Log to console + error!(detailed); + + // Also persist to /tmp for easier debugging of large batches + let ts = current_timestamp(); + let path_ts = Path::new("/tmp").join(format!("lqos_bakery_failed_{}.txt", ts)); + if let Ok(mut f) = File::create(&path_ts) { + let _ = f.write_all(detailed.as_bytes()); + let _ = f.flush(); + error!("Bakery wrote numbered command failure to {}", path_ts.display()); + } else { + error!("Bakery failed to write numbered command failure file: {}", path_ts.display()); + } + // Convenience: keep a rolling 'last error' file + let path_last = Path::new("/tmp/lqos_bakery_last_error.txt"); + if let Ok(mut f) = File::create(&path_last) { + let _ = f.write_all(detailed.as_bytes()); + let _ = f.flush(); + } } drop(lock); // Explicitly drop the lock to release it. This happens automatically at the end of the scope, but it's good to be explicit. -- knotmirror 0.0.1 From aac14414fa5bb52fb0cd4784a76f4f115b7fee37 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Fri, 14 Nov 2025 13:59:31 -0600 Subject: [PATCH 08/15] WIP: Include interface direction check for speeds in integration tests. --- src/bakery_integration_test.py | 86 ++++++++++++++++++++++++++++++++-- 1 file changed, 83 insertions(+), 3 deletions(-) diff --git a/src/bakery_integration_test.py b/src/bakery_integration_test.py index a2ae7c53..c277a870 100644 --- a/src/bakery_integration_test.py +++ b/src/bakery_integration_test.py @@ -716,6 +716,80 @@ def check_orphan_tc_attachment(orphan_id: str = "99901") -> Tuple[bool, List[str return True, msgs +def check_circuit_direction_ceil(circuit_id: str) -> Tuple[bool, List[str]]: + """Verify that the circuit's ceil values are applied to the correct interfaces: + - interface_a (downlink): ceil == maxDownload + - interface_b (uplink): ceil == maxUpload + Tolerance of 0.6 Mbps to account for rounding. + """ + msgs: List[str] = [] + qs = _load_queuing_structure() + if not isinstance(qs, dict): + return False, ["direction check: queuingStructure.json not found"] + net = qs.get("Network") + if not isinstance(net, dict): + return False, ["direction check: queuingStructure has no 'Network'"] + found = _walk_nodes_for_circuit(net, circuit_id) + if not found: + return False, [f"direction check: circuit {circuit_id} not found in structure"] + parent_name, circuit = found + # Interfaces + if not interface_a or not callable(interface_a): + return False, ["direction check: interface_a() binding unavailable"] + try: + ifa = interface_a() + except Exception as e: + return False, [f"direction check: failed to get interface_a(): {e}"] + ifb = None + if interface_b and callable(interface_b): + try: + ifb = interface_b() + except Exception: + ifb = None + # IDs + maj_hex = circuit.get("classMajor") + mnr_hex = circuit.get("classMinor") + upm_hex = circuit.get("up_classMajor") + maj = _hex_to_int(maj_hex if isinstance(maj_hex, str) else str(maj_hex)) + mnr = _hex_to_int(mnr_hex if isinstance(mnr_hex, str) else str(mnr_hex)) + upm = _hex_to_int(upm_hex if isinstance(upm_hex, str) else str(upm_hex)) + if None in (maj, mnr): + return False, [f"direction check: circuit {circuit_id} missing down IDs"] + # Expectations + try: + max_dl = float(circuit.get("maxDownload", -1)) + max_ul = float(circuit.get("maxUpload", -1)) + except Exception: + return False, ["direction check: circuit missing maxDownload/maxUpload"] + # Read downlink + ok = True + res_dl = _read_htb_rate_ceil_mbps(ifa, maj, mnr) + if not res_dl: + msgs.append(f"direction check: {ifa} class {maj}:{mnr} not found for circuit {circuit_id}") + ok = False + else: + rate_mbps, ceil_mbps, line = res_dl + msgs.append( + f"direction check: {circuit_id} down {ifa} ceil={ceil_mbps:.1f} expect={max_dl:.1f} | {line}" + ) + if abs(ceil_mbps - max_dl) > 0.6: + ok = False + # Read uplink + if ifb and upm is not None: + res_ul = _read_htb_rate_ceil_mbps(ifb, upm, mnr) + if not res_ul: + msgs.append(f"direction check: {ifb} class {upm}:{mnr} not found for circuit {circuit_id}") + ok = False + else: + rate_mbps, ceil_mbps, line = res_ul + msgs.append( + f"direction check: {circuit_id} up {ifb} ceil={ceil_mbps:.1f} expect={max_ul:.1f} | {line}" + ) + if abs(ceil_mbps - max_ul) > 0.6: + ok = False + return ok, msgs + + def _walk_nodes_for_circuit(node_map: Dict[str, dict], circuit_id: str) -> Optional[Tuple[str, dict]]: for name, node in node_map.items(): if not isinstance(node, dict): @@ -748,9 +822,10 @@ def test_orphan_circuit_assignment(csv_rows: List[Dict[str, object]]) -> Tuple[b pn_ul = int(generated_pn_upload_mbps()) # type: ignore[misc] except Exception as e: return False, [f"Failed to read PN defaults: {e}"] - # Choose conservative orphan speeds strictly below PN defaults - orphan_dl = max(1, min(25, pn_dl - 1)) - orphan_ul = max(1, min(25, pn_ul - 1)) + # Choose asymmetric orphan speeds strictly below PN defaults to verify direction mapping clearly. + # Target 50/20 Mbps, but cap to PN defaults minus 1 to stay valid on smaller configs. + orphan_dl = max(1, min(50, pn_dl - 1)) + orphan_ul = max(1, min(20, pn_ul - 1)) orphan_id = "99901" orphan_row: Dict[str, object] = { "Circuit ID": orphan_id, @@ -918,6 +993,11 @@ def run_tiered_suite(log: LogReader, timeout_s: float, results: List[str]) -> bo passed, msg = assert_no_full_reload("tiered: circuit speed change", res, step_t0) results.append(msg) ok &= passed + # Verify direction mapping for Circuit ID 1 (max DL=20, UL=15) + _mark_step("sanity: circuit direction mapping (ceil)") + passed_dir, msgs_dir = check_circuit_direction_ceil("1") + results.extend(msgs_dir) + ok &= passed_dir # Circuit SQM change _mark_step("flat: circuit SQM change") -- knotmirror 0.0.1 From 70e3e0f8c69c1797aa75435ea36b9a7c660e7911 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Fri, 14 Nov 2025 14:23:03 -0600 Subject: [PATCH 09/15] WIP: We had incorrect output for low speed with cake RTT overrides. Includes an integration test to catch it. --- src/bakery_integration_test.py | 107 +++++++++++++++++++++++++ src/rust/lqos_bakery/src/commands.rs | 13 +-- src/rust/lqos_bakery/src/queue_math.rs | 16 ++-- 3 files changed, 122 insertions(+), 14 deletions(-) diff --git a/src/bakery_integration_test.py b/src/bakery_integration_test.py index c277a870..6cf33e3c 100644 --- a/src/bakery_integration_test.py +++ b/src/bakery_integration_test.py @@ -499,6 +499,9 @@ def _read_htb_rate_ceil_mbps(iface: str, major: int, minor: int) -> Optional[Tup ceil_mbps = _parse_tc_rate_to_mbps(mm.group(3), mm.group(4)) return rate_mbps, ceil_mbps, line +def _qdisc_show(iface: str) -> Tuple[int, str, str]: + return _tc(["qdisc", "show", "dev", iface]) + def check_generated_pn_tc_bandwidths() -> Tuple[bool, List[str]]: msgs: List[str] = [] @@ -999,6 +1002,110 @@ def run_tiered_suite(log: LogReader, timeout_s: float, results: List[str]) -> bo results.extend(msgs_dir) ok &= passed_dir + # Add a low-rate circuit to trigger cake RTT tokens and verify units (e.g., 180ms) + _mark_step("sanity: add low-rate circuit for RTT check") + low_id = "99" + rows_lr = json.loads(json.dumps(rows2)) + rows_lr.append({ + "Circuit ID": low_id, + "Circuit Name": "LOWRATE", + "Device ID": "99", + "Device Name": "LD1", + "Parent Node": "AP_A", + "MAC": "", + "IPv4": "100.64.0.99", + "IPv6": "", + "Download Min Mbps": 1, + "Upload Min Mbps": 1, + "Download Max Mbps": 2, + "Upload Max Mbps": 2, + "Comment": "", + "sqm": "", + }) + write_circuits(rows_lr) + _ = run_refresh_and_wait(log, timeout_s) + # Check RTT tokens on cake qdisc for low-rate circuit + def _check_lowrate_rtt(cid: str) -> Tuple[bool, List[str]]: + msgs: List[str] = [] + qs = _load_queuing_structure() + if not isinstance(qs, dict): + return False, ["low-rate rtt: queuingStructure.json not found"] + net = qs.get("Network") + if not isinstance(net, dict): + return False, ["low-rate rtt: queuingStructure has no 'Network'"] + found = _walk_nodes_for_circuit(net, cid) + if not found: + return False, ["low-rate rtt: circuit not found in structure"] + parent_name, circuit = found + # Resolve interfaces + try: + ifa = interface_a() + except Exception as e: + return False, [f"low-rate rtt: failed to get interface_a(): {e}"] + ifb = None + if interface_b and callable(interface_b): + try: + ifb = interface_b() + except Exception: + ifb = None + # IDs + maj = _hex_to_int(str(circuit.get("classMajor"))) + mnr = _hex_to_int(str(circuit.get("classMinor"))) + upm = _hex_to_int(str(circuit.get("up_classMajor"))) + ok_local = True + # Downlink + rc, out, err = _qdisc_show(ifa) + if rc != 0: + msgs.append(f"low-rate rtt: 'tc qdisc show dev {ifa}' failed: {err.strip()}") + ok_local = False + else: + pat = re.compile(rf"^qdisc\s+\S+\s+\S+:\s+parent\s+{maj}:{mnr}\b.*$", re.MULTILINE) + m = pat.search(out) + if m: + line = m.group(0) + if "cake" in line.lower(): + if re.search(r"\brtt\s+\d+\s*ms\b", line, re.IGNORECASE): + msgs.append(f"low-rate rtt: down {ifa} OK | {line}") + else: + msgs.append(f"low-rate rtt: down {ifa} missing 'rtt ms' in cake line | {line}") + ok_local = False + else: + msgs.append(f"low-rate rtt: down {ifa} non-cake qdisc (RTT N/A) | {line}") + else: + msgs.append(f"low-rate rtt: {ifa} no qdisc for parent {maj}:{mnr}") + ok_local = False + # Uplink + if ifb and upm is not None: + rc2, out2, err2 = _qdisc_show(ifb) + if rc2 != 0: + msgs.append(f"low-rate rtt: 'tc qdisc show dev {ifb}' failed: {err2.strip()}") + ok_local = False + else: + pat2 = re.compile(rf"^qdisc\s+\S+\s+\S+:\s+parent\s+{upm}:{mnr}\b.*$", re.MULTILINE) + m2 = pat2.search(out2) + if m2: + line2 = m2.group(0) + if "cake" in line2.lower(): + if re.search(r"\brtt\s+\d+\s*ms\b", line2, re.IGNORECASE): + msgs.append(f"low-rate rtt: up {ifb} OK | {line2}") + else: + msgs.append(f"low-rate rtt: up {ifb} missing 'rtt ms' in cake line | {line2}") + ok_local = False + else: + msgs.append(f"low-rate rtt: up {ifb} non-cake qdisc (RTT N/A) | {line2}") + else: + msgs.append(f"low-rate rtt: {ifb} no qdisc for parent {upm}:{mnr}") + ok_local = False + return ok_local, msgs + + passed_lr, msgs_lr = _check_lowrate_rtt(low_id) + results.extend(msgs_lr) + ok &= passed_lr + # Remove the low-rate circuit + rows3 = [r for r in rows_lr if r["Circuit ID"] != low_id] + write_circuits(rows3) + _ = run_refresh_and_wait(log, timeout_s) + # Circuit SQM change _mark_step("flat: circuit SQM change") _mark_step("tiered: circuit SQM change") diff --git a/src/rust/lqos_bakery/src/commands.rs b/src/rust/lqos_bakery/src/commands.rs index 651a6f46..0ad4198c 100644 --- a/src/rust/lqos_bakery/src/commands.rs +++ b/src/rust/lqos_bakery/src/commands.rs @@ -540,11 +540,10 @@ impl BakeryCommands { command = 'class add dev ' + interface_b() + ' parent ' + data[node]['up_parentClassID'] + ' classid ' + data[node]['classMinor'] + ' htb rate '+ format_rate_for_tc(data[node]['uploadBandwidthMbpsMin']) + ' ceil '+ format_rate_for_tc(data[node]['uploadBandwidthMbps']) + ' prio 3' + quantum(data[node]['uploadBandwidthMbps']) */ - // In builder mode, these site classes are being created for the first time. - // Use 'add' rather than 'replace' to avoid failures on fresh builds. + // Use 'replace' for idempotency: it adds when absent and updates when present. result.push(vec![ "class".to_string(), - "add".to_string(), + "replace".to_string(), "dev".to_string(), config.isp_interface(), "parent".to_string(), @@ -566,7 +565,7 @@ impl BakeryCommands { ]); result.push(vec![ "class".to_string(), - "add".to_string(), + "replace".to_string(), "dev".to_string(), config.internet_interface(), "parent".to_string(), @@ -687,7 +686,8 @@ impl BakeryCommands { pass */ if do_htb { - let verb = if execution_mode == ExecutionMode::Builder { "add" } else { "replace" }; + // Use 'replace' for idempotency across repeated batches + let verb = "replace"; result.push(vec![ "class".to_string(), verb.to_string(), @@ -731,7 +731,8 @@ impl BakeryCommands { } if do_htb { - let verb = if execution_mode == ExecutionMode::Builder { "add" } else { "replace" }; + // Use 'replace' for idempotency across repeated batches + let verb = "replace"; result.push(vec![ "class".to_string(), verb.to_string(), diff --git a/src/rust/lqos_bakery/src/queue_math.rs b/src/rust/lqos_bakery/src/queue_math.rs index 12fbe7ab..ede66254 100644 --- a/src/rust/lqos_bakery/src/queue_math.rs +++ b/src/rust/lqos_bakery/src/queue_math.rs @@ -125,16 +125,16 @@ pub(crate) fn sqm_rate_fixup(rate: f32, config: &Arc) -> Ve if rate <= 1.0 { result.push("rtt".to_string()); - result.push("300".to_string()); + result.push("300ms".to_string()); } else if rate <= 2.0 { result.push("rtt".to_string()); - result.push("180".to_string()); + result.push("180ms".to_string()); } else if rate <= 3.0 { result.push("rtt".to_string()); - result.push("140".to_string()); + result.push("140ms".to_string()); } else if rate <= 4.0 { result.push("rtt".to_string()); - result.push("120".to_string()); + result.push("120ms".to_string()); } result } @@ -172,16 +172,16 @@ pub(crate) fn sqm_tokens_for( // Mirror the thresholds used in sqm_rate_fixup if rate <= 1.0 { base.push("rtt".to_string()); - base.push("300".to_string()); + base.push("300ms".to_string()); } else if rate <= 2.0 { base.push("rtt".to_string()); - base.push("180".to_string()); + base.push("180ms".to_string()); } else if rate <= 3.0 { base.push("rtt".to_string()); - base.push("140".to_string()); + base.push("140ms".to_string()); } else if rate <= 4.0 { base.push("rtt".to_string()); - base.push("120".to_string()); + base.push("120ms".to_string()); } } base -- knotmirror 0.0.1 From 1ab478273d3c601901c16701fe0959e2d7567536 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Fri, 14 Nov 2025 14:33:28 -0600 Subject: [PATCH 10/15] WIP: Integration test includes IP mapping tests. --- src/bakery_integration_test.py | 174 +++++++++++++++++++++++++++++++++ 1 file changed, 174 insertions(+) diff --git a/src/bakery_integration_test.py b/src/bakery_integration_test.py index 6cf33e3c..83aee8f3 100644 --- a/src/bakery_integration_test.py +++ b/src/bakery_integration_test.py @@ -87,6 +87,10 @@ try: except Exception: generated_pn_download_mbps = None # type: ignore generated_pn_upload_mbps = None # type: ignore + try: + from liblqos_python import on_a_stick # type: ignore + except Exception: + on_a_stick = None # type: ignore except Exception: # Provide a soft fallback if binding is unavailable def is_lqosd_alive() -> bool: @@ -503,6 +507,136 @@ def _qdisc_show(iface: str) -> Tuple[int, str, str]: return _tc(["qdisc", "show", "dev", iface]) +# ----------------------- +# IP mapping checks +# ----------------------- + +def _list_ip_mappings() -> Tuple[bool, str, List[Tuple[str, int, str]]]: + """Return (ok, message, entries) where entries are (ip, cpu, tc) from the mapper. + Uses ./bin/xdp_iphash_to_cpu_cmdline list. When unavailable, returns ok=False with reason. + """ + tool = os.path.join(".", "bin", "xdp_iphash_to_cpu_cmdline") + if not os.path.exists(tool): + return False, "ipmap check: mapping tool not found", [] + try: + proc = subprocess.run([tool, "list"], capture_output=True, text=True, check=False) + except Exception as e: + return False, f"ipmap check: failed to run mapping tool: {e}", [] + out = (proc.stdout or "") + err = (proc.stderr or "").strip() + if "Socket" in out or "Socket" in err: + return False, "ipmap check: lqosd bus socket not found; skipping", [] + entries: List[Tuple[str, int, str]] = [] + # Lines look like: " CPU: TC: " + pat = re.compile(r"^\s*([0-9A-Fa-f:.]+)/\d+\s+CPU:\s+(\d+)\s+TC:\s+([0-9A-Fa-f]+:[0-9A-Fa-f]+)\s*$") + for line in out.splitlines(): + m = pat.match(line) + if m: + ip = m.group(1) + cpu = int(m.group(2)) + tc = m.group(3).lower() + entries.append((ip, cpu, tc)) + return True, "", entries + + +def _expect_handles_for_circuit(parent_node: dict, circuit: dict) -> Tuple[str, Optional[str], Optional[int]]: + """Compute expected down/up tc handle strings (hex without 0x) and CPU from structure.""" + def hx(v): + try: + return int(str(v), 16) + except Exception: + return None + maj = hx(circuit.get("classMajor")) + mnr = hx(circuit.get("classMinor")) + upm = hx(circuit.get("up_classMajor")) + cpu = hx(parent_node.get("cpuNum")) + down_tc = f"{maj:x}:{mnr:x}" if maj is not None and mnr is not None else "" + up_tc = f"{upm:x}:{mnr:x}" if upm is not None and mnr is not None else None + return down_tc, up_tc, cpu + + +def _find_parent_node(net: Dict[str, dict], name: str) -> Optional[dict]: + for k, v in net.items(): + if k == name and isinstance(v, dict): + return v + ch = v.get("children") if isinstance(v, dict) else None + if isinstance(ch, dict): + got = _find_parent_node(ch, name) + if got is not None: + return got + return None + + +def check_ip_mappings_for_circuit(circuit_id: str) -> Tuple[bool, List[str]]: + """Ensure that all IPv4s for this circuit are mapped to the correct down (and up if on-a-stick) tc handles.""" + ok_tool, msg, entries = _list_ip_mappings() + msgs: List[str] = [] + if not ok_tool: + return True, [msg] # soft-skip + qs = _load_queuing_structure() + if not isinstance(qs, dict): + return False, ["ipmap check: queuingStructure.json not found"] + net = qs.get("Network") + if not isinstance(net, dict): + return False, ["ipmap check: queuingStructure has no 'Network'"] + found = _walk_nodes_for_circuit(net, circuit_id) + if not found: + return False, [f"ipmap check: circuit {circuit_id} not found in structure"] + parent_name, circuit = found + parent_node = _find_parent_node(net, parent_name) + if not isinstance(parent_node, dict): + return False, [f"ipmap check: parent node '{parent_name}' not found"] + down_tc, up_tc, cpu = _expect_handles_for_circuit(parent_node, circuit) + # Collect expected IPv4s + ips: List[str] = [] + for dev in circuit.get("devices", []): + try: + for ip in dev.get("ipv4s", []): + ips.append(str(ip)) + except Exception: + pass + if not ips: + return True, [f"ipmap check: circuit {circuit_id} has no IPv4s; skipping"] + # Evaluate mappings + ok = True + on_stick = False + try: + on_stick = bool(on_a_stick()) if callable(on_a_stick) else False # type: ignore[misc] + except Exception: + on_stick = False + for ip in ips: + # Find all entries matching this IP + ents = [(i, c, t) for (i, c, t) in entries if i == ip] + if not ents: + msgs.append(f"ipmap check: missing mapping for {ip}") + ok = False + continue + # Down must exist + if any(t == down_tc for (_i, _c, t) in ents): + msgs.append(f"ipmap check: {ip} -> {down_tc} present") + else: + msgs.append(f"ipmap check: {ip} missing down tc {down_tc}") + ok = False + # Up mapping (only if on-a-stick) + if on_stick and up_tc: + if any(t == up_tc for (_i, _c, t) in ents): + msgs.append(f"ipmap check: {ip} -> {up_tc} present (upload)") + else: + msgs.append(f"ipmap check: {ip} missing up tc {up_tc}") + ok = False + return ok, msgs + + +def check_ip_mapping_absent(ip: str) -> Tuple[bool, List[str]]: + ok_tool, msg, entries = _list_ip_mappings() + if not ok_tool: + return True, [msg] # soft-skip + present = any(i == ip for (i, _c, _t) in entries) + if present: + return False, [f"ipmap check: unexpected mapping remains for {ip}"] + return True, [f"ipmap check: {ip} successfully absent"] + + def check_generated_pn_tc_bandwidths() -> Tuple[bool, List[str]]: msgs: List[str] = [] qs = _load_queuing_structure() @@ -974,6 +1108,11 @@ def run_tiered_suite(log: LogReader, timeout_s: float, results: List[str]) -> bo passed3, msgs3 = test_orphan_circuit_assignment(rows) results.extend(msgs3) ok &= passed3 + # Mapping for orphan circuit + _mark_step("sanity: orphan circuit ip mappings") + passed3b, msgs3b = check_ip_mappings_for_circuit("99901") + results.extend(msgs3b) + ok &= passed3b _mark_step("sanity: PN HTB rates match PN defaults") passed4, msgs4 = check_generated_pn_tc_bandwidths() @@ -1001,6 +1140,31 @@ def run_tiered_suite(log: LogReader, timeout_s: float, results: List[str]) -> bo passed_dir, msgs_dir = check_circuit_direction_ceil("1") results.extend(msgs_dir) ok &= passed_dir + # IP mappings persist for circuit 1 + _mark_step("sanity: circuit ip mappings (no change)") + passed_map1, msgs_map1 = check_ip_mappings_for_circuit("1") + results.extend(msgs_map1) + ok &= passed_map1 + + # Circuit IP change (should not trigger full reload); verify mapping moves + _mark_step("tiered: circuit IP change (no full reload)") + rows_ip = json.loads(json.dumps(rows2)) + old_ip = rows_ip[0]["IPv4"] + rows_ip[0]["IPv4"] = "100.64.0.11" + new_ip = rows_ip[0]["IPv4"] + write_circuits(rows_ip) + step_t0 = time.time() + res = run_refresh_and_wait(log, timeout_s) + passed, msg = assert_no_full_reload("tiered: circuit IP change", res, step_t0) + results.append(msg) + ok &= passed + # Verify mapping updated + passed_map_new, msgs_map_new = check_ip_mappings_for_circuit("1") + results.extend(msgs_map_new) + ok &= passed_map_new + passed_map_old, msgs_map_old = check_ip_mapping_absent(str(old_ip)) + results.extend(msgs_map_old) + ok &= passed_map_old # Add a low-rate circuit to trigger cake RTT tokens and verify units (e.g., 180ms) _mark_step("sanity: add low-rate circuit for RTT check") @@ -1144,6 +1308,11 @@ def run_tiered_suite(log: LogReader, timeout_s: float, results: List[str]) -> bo passed, msg = assert_no_full_reload("tiered: add circuit", res, step_t0) results.append(msg) ok &= passed + # Mapping for added circuit C3 + _mark_step("sanity: added circuit ip mappings") + passed_map_add, msgs_map_add = check_ip_mappings_for_circuit("3") + results.extend(msgs_map_add) + ok &= passed_map_add # Remove circuit _mark_step("flat: remove circuit") @@ -1155,6 +1324,11 @@ def run_tiered_suite(log: LogReader, timeout_s: float, results: List[str]) -> bo passed, msg = assert_no_full_reload("tiered: remove circuit", res, step_t0) results.append(msg) ok &= passed + # Mapping removed + _mark_step("sanity: removed circuit ip unmapped") + passed_unmap, msgs_unmap = check_ip_mapping_absent("100.64.0.3") + results.extend(msgs_unmap) + ok &= passed_unmap # Add site (should trigger full reload) _mark_step("tiered: add site") -- knotmirror 0.0.1 From 8b596af3db0baa3df58aadaa8fe86b070b770989 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Fri, 14 Nov 2025 14:48:10 -0600 Subject: [PATCH 11/15] WIP: Issue with overlapping minor numbers not being properly in the free list. Includes test against it. --- src/LibreQoS.py | 38 +++++++++++++++++----- src/bakery_integration_test.py | 58 ++++++++++++++++++++++++++++++++++ 2 files changed, 88 insertions(+), 8 deletions(-) diff --git a/src/LibreQoS.py b/src/LibreQoS.py index 726abcd9..f3a67333 100755 --- a/src/LibreQoS.py +++ b/src/LibreQoS.py @@ -1480,14 +1480,17 @@ def refreshShapers(): 'insertion_order': int(site_insert_counter), } site_insert_counter += 1 - # Remove the site's minor from the planner's free list for this CPU - try: - fm = st.get('free_minors') - if isinstance(fm, list) and 0 <= cpu_int < len(fm) and isinstance(fm[cpu_int], list): - if int(minor_int) in fm[cpu_int]: - fm[cpu_int].remove(int(minor_int)) - except Exception: - pass + # Always reserve the site's minor in the free list, even for synthetic nodes + try: + st = planner.getState() + fm = st.get('free_minors') + cpu_int = int(queue - 1) + minor_int = int(chosen_minor) + if isinstance(fm, list) and 0 <= cpu_int < len(fm) and isinstance(fm[cpu_int], list): + if int(minor_int) in fm[cpu_int]: + fm[cpu_int].remove(int(minor_int)) + except Exception: + pass except Exception: # Planner is optional; ignore errors during capture pass @@ -1889,6 +1892,25 @@ def refreshShapers(): if chosen_minor is None: # Fallback to reserved sequential range; ensure we never collide with the site's minor (<3 reserved) chosen_minor = max(4, int(current_minor)) + # Guard against collision with the parent site's own minor (e.g., 0xd) + try: + site_minor = int(node.get('classMinor', '0x0'), 16) + except Exception: + site_minor = -1 + if chosen_minor == site_minor: + chosen_minor += 1 + # Also guard against collisions within this node's already-assigned circuits + try: + used_minors = set() + for c in circuits_for_node: + try: + used_minors.add(int(str(c.get('classMinor', '0x0')), 16)) + except Exception: + pass + while chosen_minor in used_minors: + chosen_minor += 1 + except Exception: + pass current_minor = chosen_minor + 1 flowIDstring = hex(major_int) + ':' + hex(chosen_minor) upFlowIDstring = hex(major_int + stickOffset) + ':' + hex(chosen_minor) diff --git a/src/bakery_integration_test.py b/src/bakery_integration_test.py index 83aee8f3..05f0c60b 100644 --- a/src/bakery_integration_test.py +++ b/src/bakery_integration_test.py @@ -507,6 +507,55 @@ def _qdisc_show(iface: str) -> Tuple[int, str, str]: return _tc(["qdisc", "show", "dev", iface]) +def check_no_site_circuit_minor_collisions() -> Tuple[bool, List[str]]: + """Verify that no circuit under any node shares the same classMinor as its parent node. + + This guards against regressions where a circuit could be assigned the site/PN's minor, + causing qdiscs to attach at the site handle instead of the circuit handle. + """ + msgs: List[str] = [] + qs = _load_queuing_structure() + if not isinstance(qs, dict): + return False, ["minor collision check: queuingStructure.json not found"] + net = qs.get("Network") + if not isinstance(net, dict): + return False, ["minor collision check: queuingStructure has no 'Network'"] + + def hx(v) -> Optional[int]: + try: + s = str(v) + return int(s, 16) if s.startswith("0x") else int(s) + except Exception: + return None + + ok = True + + def walk(node_map: Dict[str, dict]): + nonlocal ok + for name, node in node_map.items(): + if not isinstance(node, dict): + continue + site_minor = hx(node.get("classMinor")) + if isinstance(node.get("circuits"), list) and site_minor is not None: + for c in node.get("circuits", []): + try: + cmin = hx(c.get("classMinor")) + cid = str(c.get("circuitID", "")) + if cmin is not None and cmin == site_minor: + msgs.append(f"minor collision check: circuit {cid} under '{name}' shares site minor 0x{site_minor:x}") + ok = False + except Exception: + pass + ch = node.get("children") + if isinstance(ch, dict): + walk(ch) + + walk(net) + if ok: + msgs.append("minor collision check: no site/circuit minor collisions detected") + return ok, msgs + + # ----------------------- # IP mapping checks # ----------------------- @@ -1104,6 +1153,11 @@ def run_tiered_suite(log: LogReader, timeout_s: float, results: List[str]) -> bo results.extend(msgs) ok &= passed2 + _mark_step("sanity: no site/circuit minor collisions") + passed2b, msgs2b = check_no_site_circuit_minor_collisions() + results.extend(msgs2b) + ok &= passed2b + _mark_step("sanity: orphan circuit assigned under Generated_PN with original speeds") passed3, msgs3 = test_orphan_circuit_assignment(rows) results.extend(msgs3) @@ -1118,6 +1172,10 @@ def run_tiered_suite(log: LogReader, timeout_s: float, results: List[str]) -> bo passed4, msgs4 = check_generated_pn_tc_bandwidths() results.extend(msgs4) ok &= passed4 + _mark_step("sanity: no site/circuit minor collisions (post-orphan)") + passed4b, msgs4b = check_no_site_circuit_minor_collisions() + results.extend(msgs4b) + ok &= passed4b _mark_step("sanity: orphan circuit HTB attached to PN parent in tc") passed5, msgs5 = check_orphan_tc_attachment("99901") results.extend(msgs5) -- knotmirror 0.0.1 From 2f4b83025c08d64a9cf7ded3338e1995136ed53e Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Fri, 14 Nov 2025 15:36:34 -0600 Subject: [PATCH 12/15] WIP: Better diagnostics --- src/LibreQoS.py | 52 ++++++++++++++------------ src/rust/lqos_bakery/src/diff/sites.rs | 11 +++--- src/rust/lqos_python/src/lib.rs | 11 ++++-- 3 files changed, 42 insertions(+), 32 deletions(-) diff --git a/src/LibreQoS.py b/src/LibreQoS.py index f3a67333..0937271c 100755 --- a/src/LibreQoS.py +++ b/src/LibreQoS.py @@ -79,16 +79,28 @@ class Planner: self._is_default = False if loaded is None: - # Missing/invalid state: default + # Missing/invalid planner state: build a fresh default and record why. + try: + if is_insight_enabled(): + logging.warning("Planner: no existing plan available from Insight/local store; using default plan.") + else: + logging.warning("Planner: no existing plan available (Insight disabled); using default plan.") + except Exception: + pass self.state = self._default_state(normalized_site_names, siteCount, queuesAvailable, onAStick, now_ts) self._is_default = True return # Validate loaded state and decide if we should rebuild - should_rebuild, _reason = self._should_rebuild( + should_rebuild, reason = self._should_rebuild( loaded, normalized_site_names, siteCount, queuesAvailable, onAStick, now_ts ) if should_rebuild: + # Existing planner state is not compatible with the current configuration. + try: + logging.warning(f"Planner: discarding existing plan; reason={reason}. Falling back to default plan.") + except Exception: + pass self.state = self._default_state(normalized_site_names, siteCount, queuesAvailable, onAStick, now_ts) self._is_default = True else: @@ -153,9 +165,9 @@ class Planner: def persist(self): """Persist planner state. - - When Insight is enabled, persists remotely via `store_planner_remote`. - - Otherwise, writes a local compressed CBOR file at `planner.cbor`. - - Ephemeral fields such as `free_minors` are never persisted. + Insight-only feature: when Insight is enabled, planner state is + persisted remotely via `store_planner_remote`. Ephemeral fields such + as `free_minors` are never persisted. """ try: to_save = dict(self.state) @@ -164,7 +176,8 @@ class Planner: to_save.pop('free_minors') except Exception: pass - # Prefer Insight when enabled; otherwise persist to local CBOR for stability + # Insight-only feature: when Insight is disabled, skip persistence + # entirely so planner reuse remains an Insight capability. use_remote = False try: use_remote = bool(is_insight_enabled()) @@ -173,11 +186,9 @@ class Planner: if use_remote: store_planner_remote(to_save) else: - # Best-effort local persistence to planner.cbor - try: - write_planner_cbor(self.path, to_save) - except Exception as e: - warnings.warn(f"Failed to write planner.cbor locally: {e}", stacklevel=2) + # No local fallback; skip persistence entirely when Insight is + # not enabled so that planner reuse remains an Insight feature. + pass except Exception as e: warnings.warn(f"Failed to write planner.cbor: {e}", stacklevel=2) @@ -214,12 +225,15 @@ class Planner: def _load_state(self, queues_available, on_a_stick_flag, site_count): """Load planner state. - - If Insight is enabled, fetch from remote; otherwise load local CBOR. + Insight-only feature: if Insight is enabled, fetch planner state from + the remote API. When Insight is disabled, no planner state is used. + - Validates that minimum required keys exist. - - Normalizes `updated_at` when remote to avoid needless rebuilds based on age alone. + - Normalizes `updated_at` when remote to avoid needless rebuilds based + on age alone. """ try: - # Try Insight first if enabled; otherwise fall back to local CBOR + # Try Insight first if enabled; otherwise treat as no state use_remote = False try: use_remote = bool(is_insight_enabled()) @@ -242,15 +256,7 @@ class Planner: pass return None else: - try: - data = read_planner_cbor(self.path) - if isinstance(data, dict): - for k in ['queuesAvailable', 'site_count', 'site_names']: - if k not in data: - return None - return data - except Exception: - pass + # Insight is disabled or unavailable: no planner state is used. return None except Exception: return None diff --git a/src/rust/lqos_bakery/src/diff/sites.rs b/src/rust/lqos_bakery/src/diff/sites.rs index 7a60c4e5..bf452d9e 100644 --- a/src/rust/lqos_bakery/src/diff/sites.rs +++ b/src/rust/lqos_bakery/src/diff/sites.rs @@ -49,19 +49,20 @@ pub(crate) fn diff_sites( "Structural difference detected for site hash: {}", site_hash ); - // Log a concise before/after for diagnostics - // Extract relevant fields - // old + // Log a concise before/after for diagnostics at warn! level so operators + // can see why the site is considered structurally different. let (ocpu, opar, oup, omin) = match old_cmd.as_ref() { crate::BakeryCommands::AddSite { parent_class_id, up_parent_class_id, class_minor, .. } => (0i32, parent_class_id.as_tc_string(), up_parent_class_id.as_tc_string(), *class_minor), _ => (0, String::new(), String::new(), 0), }; - // new let (ncpu, npar, nup, nmin) = match new_cmd.as_ref() { crate::BakeryCommands::AddSite { parent_class_id, up_parent_class_id, class_minor, .. } => (0i32, parent_class_id.as_tc_string(), up_parent_class_id.as_tc_string(), *class_minor), _ => (0, String::new(), String::new(), 0), }; - debug!("Site hash {} change: parent={}→{}, up_parent={}→{}, minor=0x{:x}→0x{:x}", site_hash, opar, npar, oup, nup, omin, nmin); + warn!( + "Site hash {} change detail: parent={}→{}, up_parent={}→{}, minor=0x{:x}→0x{:x}", + site_hash, opar, npar, oup, nup, omin, nmin + ); return SiteDiffResult::RebuildRequired; } // If the speeds have changed, we need to store the change. diff --git a/src/rust/lqos_python/src/lib.rs b/src/rust/lqos_python/src/lib.rs index 65018b37..fa5614ac 100644 --- a/src/rust/lqos_python/src/lib.rs +++ b/src/rust/lqos_python/src/lib.rs @@ -319,8 +319,10 @@ fn fetch_planner_remote( // Allow invalid certs for self-hosted Insight instances (non-default URL) let allow_insecure = !base_url.starts_with("https://insight.libreqos.com"); let client = match reqwest::blocking::Client::builder() - .timeout(Duration::from_secs(5)) - .connect_timeout(Duration::from_secs(3)) + // Use a generous timeout similar to deviceWeights to tolerate + // slow or distant Insight instances when fetching planner state. + .timeout(Duration::from_secs(10)) + .connect_timeout(Duration::from_secs(6)) .danger_accept_invalid_certs(allow_insecure) .build() { Ok(c) => c, @@ -464,8 +466,9 @@ fn store_planner_remote(py: Python, state: PyObject) -> PyResult { // Allow invalid certs for self-hosted Insight instances (non-default URL) let allow_insecure = !base_url.starts_with("https://insight.libreqos.com"); let client = match reqwest::blocking::Client::builder() - .timeout(Duration::from_secs(5)) - .connect_timeout(Duration::from_secs(3)) + // Match the extended planner fetch timeout for symmetry. + .timeout(Duration::from_secs(10)) + .connect_timeout(Duration::from_secs(6)) .danger_accept_invalid_certs(allow_insecure) .build() { Ok(c) => c, -- knotmirror 0.0.1 From 2fc4258bdbd4ac0b0b2697aa73bdec540c93d291 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Fri, 14 Nov 2025 16:24:09 -0600 Subject: [PATCH 13/15] WIP: Better diagnostics and better generated_pn --- src/LibreQoS.py | 123 +++++++++++++++------------ src/bakery_integration_test.py | 102 +++++++++++++++++----- src/rust/lqos_bakery/src/commands.rs | 24 ++++-- 3 files changed, 166 insertions(+), 83 deletions(-) diff --git a/src/LibreQoS.py b/src/LibreQoS.py index 0937271c..bbf6185e 100755 --- a/src/LibreQoS.py +++ b/src/LibreQoS.py @@ -28,7 +28,6 @@ from liblqos_python import is_lqosd_alive, clear_ip_mappings, delete_ip_mapping, run_shell_commands_as_sudo, generated_pn_download_mbps, generated_pn_upload_mbps, queues_available_override, \ on_a_stick, get_tree_weights, get_weights, is_network_flat, get_libreqos_directory, enable_insight_topology, \ fast_queues_fq_codel, hash_to_i64, fetch_planner_remote, store_planner_remote, \ - read_planner_cbor, write_planner_cbor, \ Bakery # Optional: urgent issue submission (available in newer liblqos_python) @@ -51,14 +50,13 @@ class Planner: PUBLIC methods: - getState(): dict — current planner state (default or loaded) - - persist(): None — save the planner state to planner.cbor + - persist(): None — persist planner state via Insight when enabled """ # Print the Insight planning banner only once per process _insight_banner_printed = False def __init__(self, queuesAvailable: int, onAStick: bool, siteNamesSet, siteCount: int): - self.path = os.path.join(get_libreqos_directory(), 'planner.cbor') now_ts = time.time() # Informational banner when Insight-enhanced planning is in use @@ -82,7 +80,7 @@ class Planner: # Missing/invalid planner state: build a fresh default and record why. try: if is_insight_enabled(): - logging.warning("Planner: no existing plan available from Insight/local store; using default plan.") + logging.warning("Planner: no existing plan available from Insight; using default plan.") else: logging.warning("Planner: no existing plan available (Insight disabled); using default plan.") except Exception: @@ -167,7 +165,7 @@ class Planner: Insight-only feature: when Insight is enabled, planner state is persisted remotely via `store_planner_remote`. Ephemeral fields such - as `free_minors` are never persisted. + as `free_minors` are never persisted, and no local CBOR files are used. """ try: to_save = dict(self.state) @@ -190,23 +188,23 @@ class Planner: # not enabled so that planner reuse remains an Insight feature. pass except Exception as e: - warnings.warn(f"Failed to write planner.cbor: {e}", stacklevel=2) + warnings.warn(f"Failed to persist planner state to Insight: {e}", stacklevel=2) def _default_state(self, site_names_sorted, site_count, queues_available, on_a_stick_flag, now_ts): """Build a default planner state. Notes - Minor IDs 1..3 are globally reserved: - 1 = root qdisc, 2 = default class, 3 = site classes - - Circuits and any ephemeral classes use 4+. + 1 = root qdisc, 2 = default class, 3 = per-CPU Generated_PN_* site classes + - All other sites, circuits, and any ephemeral classes use 4+. - `free_minors` is per-CPU and rebuilt on load; it is not persisted. """ try: # Reserve minors 1..3 globally: # - 1 is used by root qdisc # - 2 is used by the default class under root - # - 3 is used for site classes - # Circuits and any ephemeral classes must use 4+ + # - 3 is used for per-CPU Generated_PN_* site classes + # All other site and circuit classes must use 4+ free_minors = [list(range(4, 0x10000)) for _ in range(int(queues_available))] except Exception: free_minors = [] @@ -280,7 +278,7 @@ class Planner: try: cpu = int(entry.get('cpu', -1)) minor = int(entry.get('minor', -1)) - if 0 <= cpu < q and 3 <= minor <= 0xFFFF: + if 0 <= cpu < q and 4 <= minor <= 0xFFFF: if minor in free[cpu]: free[cpu].discard(minor) except Exception: @@ -293,7 +291,7 @@ class Planner: try: cpu = int(entry.get('cpu', -1)) minor = int(entry.get('minor', -1)) - if 0 <= cpu < q and 3 <= minor <= 0xFFFF: + if 0 <= cpu < q and 4 <= minor <= 0xFFFF: if minor in free[cpu]: free[cpu].discard(minor) except Exception: @@ -1348,11 +1346,12 @@ def refreshShapers(): knownClassIDs = [] nodes_requiring_min_squashing = {} # Track minor counter by CPU. This way we can have > 32000 hosts (htb has u16 limit to minor handle) - # Minor numbers start at 3 to reserve 1 for root qdisc and 2 for default class + # Minor numbers start at 4 to reserve: + # 1 = root qdisc, 2 = default class, 3 = per-CPU Generated_PN_* sites # With CIRCUIT_PADDING, we leave gaps between nodes to allow future circuit additions # without disrupting existing ClassID assignments. This maintains stability across reloads. for x in range(queuesAvailable): - minorByCPUpreloaded[x+1] = 3 + minorByCPUpreloaded[x+1] = 4 def traverseNetwork(data, depth, major, minorByCPU, queue, parentClassID, upParentClassID, parentMaxDL, parentMaxUL, parentMinDL, parentMinUL): nonlocal site_insert_counter # ClassID Assignment Strategy: @@ -1385,49 +1384,64 @@ def refreshShapers(): # data[node]['up_cpuNum'] = hex(queue-1+stickOffset) # traverseNetwork(data[node]['children'], depth, major, minorByCPU, queue, parentClassID, upParentClassID, parentMaxDL, parentMaxUL) # continue - # Prefer reusing previously-assigned site minor from planner.site_map (keyed by hashed site name); - # else try planner free_minors for this CPU; else fallback to sequential counter - chosen_minor = None + # Prefer fixed, low minors for Generated_PN_* per CPU so they are + # visually obvious and stable. For all other nodes, prefer reusing + # previously-assigned site minors from planner.site_map; else try + # planner free_minors for this CPU; else fallback to sequential + # counter starting at 4. + name_s = str(node) + is_generated_pn = False try: - if ('planner' in locals() or 'planner' in globals()) and isinstance(planner, Planner) and (not getattr(planner, '_is_default', False)): - st = planner.getState() - cpu_index = int(queue - 1) - # 1) Attempt reuse from site_map when CPU/major match - try: - site_map = st.get('site_map') if isinstance(st, dict) else None - if isinstance(site_map, dict): - key_hash = int(hash_to_i64(str(node))) - entry = site_map.get(key_hash) - if isinstance(entry, dict): - saved_cpu = int(entry.get('cpu', -1)) - saved_major = int(entry.get('major', -1)) - saved_minor = int(entry.get('minor', -1)) - if saved_cpu == cpu_index and saved_major == int(major) and saved_minor >= 3: - chosen_minor = saved_minor - # Remove from free list if present - try: - fm = st.get('free_minors') - if isinstance(fm, list) and 0 <= cpu_index < len(fm) and isinstance(fm[cpu_index], list) and saved_minor in fm[cpu_index]: - fm[cpu_index].remove(saved_minor) - except Exception: - pass - except Exception: - pass - # 2) If no reuse, allocate from free list for this CPU (depth >= 1 only) - if chosen_minor is None and depth >= 1: - try: - fm = st.get('free_minors') if isinstance(st, dict) else None - if isinstance(fm, list) and 0 <= cpu_index < len(fm) and isinstance(fm[cpu_index], list) and len(fm[cpu_index]) > 0: - chosen_minor = int(fm[cpu_index].pop(0)) - except Exception: - chosen_minor = None + is_generated_pn = name_s.startswith('Generated_PN_') except Exception: - chosen_minor = None - if chosen_minor is None: + is_generated_pn = False + + chosen_minor = None + # Fixed minor for Generated_PN_*: always 3 per CPU, independent of + # planner state and traversal order. + if is_generated_pn: + chosen_minor = 3 + else: try: - chosen_minor = int(minorByCPU[queue]) + if ('planner' in locals() or 'planner' in globals()) and isinstance(planner, Planner) and (not getattr(planner, '_is_default', False)): + st = planner.getState() + cpu_index = int(queue - 1) + # 1) Attempt reuse from site_map when CPU/major match + try: + site_map = st.get('site_map') if isinstance(st, dict) else None + if isinstance(site_map, dict): + key_hash = int(hash_to_i64(str(node))) + entry = site_map.get(key_hash) + if isinstance(entry, dict): + saved_cpu = int(entry.get('cpu', -1)) + saved_major = int(entry.get('major', -1)) + saved_minor = int(entry.get('minor', -1)) + if saved_cpu == cpu_index and saved_major == int(major) and saved_minor >= 4: + chosen_minor = saved_minor + # Remove from free list if present + try: + fm = st.get('free_minors') + if isinstance(fm, list) and 0 <= cpu_index < len(fm) and isinstance(fm[cpu_index], list) and saved_minor in fm[cpu_index]: + fm[cpu_index].remove(saved_minor) + except Exception: + pass + except Exception: + pass + # 2) If no reuse, allocate from free list for this CPU (depth >= 1 only) + if chosen_minor is None and depth >= 1: + try: + fm = st.get('free_minors') if isinstance(st, dict) else None + if isinstance(fm, list) and 0 <= cpu_index < len(fm) and isinstance(fm[cpu_index], list) and len(fm[cpu_index]) > 0: + chosen_minor = int(fm[cpu_index].pop(0)) + except Exception: + chosen_minor = None except Exception: - chosen_minor = 3 + chosen_minor = None + if chosen_minor is None: + try: + chosen_minor = int(minorByCPU[queue]) + except Exception: + chosen_minor = 4 nodeClassID = hex(major) + ':' + hex(chosen_minor) upNodeClassID = hex(major+stickOffset) + ':' + hex(chosen_minor) @@ -2019,7 +2033,8 @@ def refreshShapers(): cpu = int(entry.get('cpu', 0)) minor = int(entry.get('minor', -1)) if isinstance(fm, list) and 0 <= cpu < len(fm) and isinstance(fm[cpu], list): - if minor >= 3 and minor <= 0xFFFF and (minor not in fm[cpu]): + # Reserve 1..3 globally; only return minors >=4 to the free list + if minor >= 4 and minor <= 0xFFFF and (minor not in fm[cpu]): fm[cpu].append(minor) # Remove from circuit_map try: diff --git a/src/bakery_integration_test.py b/src/bakery_integration_test.py index 05f0c60b..7cc81463 100644 --- a/src/bakery_integration_test.py +++ b/src/bakery_integration_test.py @@ -488,12 +488,28 @@ def _read_htb_rate_ceil_mbps(iface: str, major: int, minor: int) -> Optional[Tup rc, out, err = _tc(["class", "show", "dev", iface]) if rc != 0: return None - # Match the exact class line for major:minor in decimal - cls_pat = re.compile(rf"^class\s+htb\s+{major}:{minor}\b.*$", re.MULTILINE) - m = cls_pat.search(out) - if not m: + # Match the class line for this major/minor, accepting decimal or hex forms. + cls_pat = re.compile(r"^class\s+htb\s+([0-9A-Fa-fx]+):([0-9A-Fa-fx]+)\b.*$", re.MULTILINE) + + def _to_int(tok: str) -> Optional[int]: + try: + s = tok.strip() + if s.lower().startswith("0x"): + return int(s, 16) + return int(s) + except Exception: + return None + + line = None + for m in cls_pat.finditer(out): + mj_tok, mn_tok = m.group(1), m.group(2) + mj = _to_int(mj_tok) + mn = _to_int(mn_tok) + if mj == major and mn == minor: + line = m.group(0) + break + if line is None: return None - line = m.group(0) # Extract rate and ceil tokens rpat = re.compile(r"rate\s+([0-9]+(?:\.[0-9]+)?)([GMK])?bit.*?ceil\s+([0-9]+(?:\.[0-9]+)?)([GMK])?bit") mm = rpat.search(line) @@ -787,16 +803,9 @@ def _class_has_parent(iface: str, maj: int, mnr: int, pmaj: int, pmnr: int) -> T rc, out, err = _tc(["class", "show", "dev", iface]) if rc != 0: return False, f"tc error: {err.strip()}" - # Find the specific class line first - cls_pat = re.compile(rf"^class\s+htb\s+{maj}:{mnr}\b.*$", re.MULTILINE) - m = cls_pat.search(out) - if not m: - return False, None - line = m.group(0) - # Extract parent handle (supports hex or decimal) - p = re.search(r"parent\s+([0-9A-Fa-fx]+):([0-9A-Fa-fx]+)\b", line) - if not p: - return False, line + # Find the specific class line first (accept decimal or hex handles) + cls_pat = re.compile(r"^class\s+htb\s+([0-9A-Fa-fx]+):([0-9A-Fa-fx]+)\b.*$", re.MULTILINE) + def _to_int(tok: str) -> Optional[int]: try: s = tok.strip() @@ -805,6 +814,21 @@ def _class_has_parent(iface: str, maj: int, mnr: int, pmaj: int, pmnr: int) -> T return int(s) except Exception: return None + + line = None + for m in cls_pat.finditer(out): + mj_tok, mn_tok = m.group(1), m.group(2) + mj = _to_int(mj_tok) + mn = _to_int(mn_tok) + if mj == maj and mn == mnr: + line = m.group(0) + break + if line is None: + return False, None + # Extract parent handle (supports hex or decimal) + p = re.search(r"parent\s+([0-9A-Fa-fx]+):([0-9A-Fa-fx]+)\b", line) + if not p: + return False, line pmj = _to_int(p.group(1)) pmn = _to_int(p.group(2)) if pmj is None or pmn is None: @@ -1281,10 +1305,26 @@ def run_tiered_suite(log: LogReader, timeout_s: float, results: List[str]) -> bo msgs.append(f"low-rate rtt: 'tc qdisc show dev {ifa}' failed: {err.strip()}") ok_local = False else: - pat = re.compile(rf"^qdisc\s+\S+\s+\S+:\s+parent\s+{maj}:{mnr}\b.*$", re.MULTILINE) - m = pat.search(out) - if m: - line = m.group(0) + pat = re.compile(r"^qdisc\s+\S+\s+\S+:\s+parent\s+([0-9A-Fa-fx]+):([0-9A-Fa-fx]+)\b.*$", re.MULTILINE) + + def _to_int(tok: str) -> Optional[int]: + try: + s = tok.strip() + if s.lower().startswith("0x"): + return int(s, 16) + return int(s) + except Exception: + return None + + line = None + for m in pat.finditer(out): + mj_tok, mn_tok = m.group(1), m.group(2) + mj = _to_int(mj_tok) + mn = _to_int(mn_tok) + if mj == maj and mn == mnr: + line = m.group(0) + break + if line is not None: if "cake" in line.lower(): if re.search(r"\brtt\s+\d+\s*ms\b", line, re.IGNORECASE): msgs.append(f"low-rate rtt: down {ifa} OK | {line}") @@ -1303,10 +1343,26 @@ def run_tiered_suite(log: LogReader, timeout_s: float, results: List[str]) -> bo msgs.append(f"low-rate rtt: 'tc qdisc show dev {ifb}' failed: {err2.strip()}") ok_local = False else: - pat2 = re.compile(rf"^qdisc\s+\S+\s+\S+:\s+parent\s+{upm}:{mnr}\b.*$", re.MULTILINE) - m2 = pat2.search(out2) - if m2: - line2 = m2.group(0) + pat2 = re.compile(r"^qdisc\s+\S+\s+\S+:\s+parent\s+([0-9A-Fa-fx]+):([0-9A-Fa-fx]+)\b.*$", re.MULTILINE) + + def _to_int2(tok: str) -> Optional[int]: + try: + s = tok.strip() + if s.lower().startswith("0x"): + return int(s, 16) + return int(s) + except Exception: + return None + + line2 = None + for m2 in pat2.finditer(out2): + mj_tok, mn_tok = m2.group(1), m2.group(2) + mj = _to_int2(mj_tok) + mn = _to_int2(mn_tok) + if mj == upm and mn == mnr: + line2 = m2.group(0) + break + if line2 is not None: if "cake" in line2.lower(): if re.search(r"\brtt\s+\d+\s*ms\b", line2, re.IGNORECASE): msgs.append(f"low-rate rtt: up {ifb} OK | {line2}") diff --git a/src/rust/lqos_bakery/src/commands.rs b/src/rust/lqos_bakery/src/commands.rs index 0ad4198c..24f40692 100644 --- a/src/rust/lqos_bakery/src/commands.rs +++ b/src/rust/lqos_bakery/src/commands.rs @@ -529,6 +529,10 @@ impl BakeryCommands { params: AddSiteParams, ) -> Option>> { let mut result = Vec::new(); + // Derive major IDs from parent handles so classids are fully qualified + // and consistent with queuingStructure.json (classMajor/classMinor). + let (down_major, _) = params.parent_class_id.get_major_minor(); + let (up_major, _) = params.up_parent_class_id.get_major_minor(); /* bakery.add_site(data[node]['parentClassID'], data[node]['up_parentClassID'], data[node]['classMinor'], format_rate_for_tc(data[node]['downloadBandwidthMbpsMin']), format_rate_for_tc(data[node]['uploadBandwidthMbpsMin']), format_rate_for_tc(data[node]['downloadBandwidthMbps']), format_rate_for_tc(data[node]['uploadBandwidthMbps']), quantum(data[node]['downloadBandwidthMbps']), quantum(data[node]['uploadBandwidthMbps'])) @@ -549,7 +553,7 @@ impl BakeryCommands { "parent".to_string(), params.parent_class_id.as_tc_string(), "classid".to_string(), - format!("0x{:x}", params.class_minor), + format!("0x{:x}:0x{:x}", down_major, params.class_minor), "htb".to_string(), "rate".to_string(), format_rate_for_tc_f32(params.download_bandwidth_min), @@ -571,7 +575,7 @@ impl BakeryCommands { "parent".to_string(), params.up_parent_class_id.as_tc_string(), "classid".to_string(), - format!("0x{:x}", params.class_minor), + format!("0x{:x}:0x{:x}", up_major, params.class_minor), "htb".to_string(), "rate".to_string(), format_rate_for_tc_f32(params.upload_bandwidth_min), @@ -696,7 +700,7 @@ impl BakeryCommands { "parent".to_string(), params.parent_class_id.as_tc_string(), "classid".to_string(), - format!("0x{:x}", params.class_minor), + format!("0x{:x}:0x{:x}", params.class_major, params.class_minor), "htb".to_string(), "rate".to_string(), format_rate_for_tc_f32(params.download_bandwidth_min), @@ -741,7 +745,7 @@ impl BakeryCommands { "parent".to_string(), params.up_parent_class_id.as_tc_string(), "classid".to_string(), - format!("0x{:x}", params.class_minor), + format!("0x{:x}:0x{:x}", params.up_class_major, params.class_minor), "htb".to_string(), "rate".to_string(), format_rate_for_tc_f32(params.upload_bandwidth_min), @@ -896,7 +900,11 @@ impl BakeryCommands { "parent".to_string(), parent_class_id.as_tc_string(), "classid".to_string(), - format!("0x{class_minor:x}"), + format!( + "0x{:x}:0x{:x}", + parent_class_id.get_major_minor().0, + class_minor + ), ]); result.push(vec![ "class".to_string(), @@ -906,7 +914,11 @@ impl BakeryCommands { "parent".to_string(), up_parent_class_id.as_tc_string(), "classid".to_string(), - format!("0x{class_minor:x}"), + format!( + "0x{:x}:0x{:x}", + up_parent_class_id.get_major_minor().0, + class_minor + ), ]); } -- knotmirror 0.0.1 From 91ef48a1fc61d2455f4d0175675c83df9e9afd18 Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Sat, 15 Nov 2025 08:41:21 -0600 Subject: [PATCH 14/15] WIP: Better diagnostics and better generated_pn --- src/bakery_integration_test.py | 32 +++++++++++++++++++++------- src/rust/lqos_bakery/src/commands.rs | 17 +++++---------- 2 files changed, 29 insertions(+), 20 deletions(-) diff --git a/src/bakery_integration_test.py b/src/bakery_integration_test.py index 7cc81463..a33e5488 100644 --- a/src/bakery_integration_test.py +++ b/src/bakery_integration_test.py @@ -492,11 +492,15 @@ def _read_htb_rate_ceil_mbps(iface: str, major: int, minor: int) -> Optional[Tup cls_pat = re.compile(r"^class\s+htb\s+([0-9A-Fa-fx]+):([0-9A-Fa-fx]+)\b.*$", re.MULTILINE) def _to_int(tok: str) -> Optional[int]: + s = tok.strip() + # Accept decimal, 0x-prefixed hex, or bare hex (e.g. "f") try: - s = tok.strip() if s.lower().startswith("0x"): return int(s, 16) - return int(s) + try: + return int(s) # decimal + except Exception: + return int(s, 16) # bare hex except Exception: return None @@ -807,11 +811,15 @@ def _class_has_parent(iface: str, maj: int, mnr: int, pmaj: int, pmnr: int) -> T cls_pat = re.compile(r"^class\s+htb\s+([0-9A-Fa-fx]+):([0-9A-Fa-fx]+)\b.*$", re.MULTILINE) def _to_int(tok: str) -> Optional[int]: + s = tok.strip() + # Accept decimal, 0x-prefixed hex, or bare hex (e.g. "f") try: - s = tok.strip() if s.lower().startswith("0x"): return int(s, 16) - return int(s) + try: + return int(s) # decimal + except Exception: + return int(s, 16) # bare hex except Exception: return None @@ -1308,11 +1316,15 @@ def run_tiered_suite(log: LogReader, timeout_s: float, results: List[str]) -> bo pat = re.compile(r"^qdisc\s+\S+\s+\S+:\s+parent\s+([0-9A-Fa-fx]+):([0-9A-Fa-fx]+)\b.*$", re.MULTILINE) def _to_int(tok: str) -> Optional[int]: + s = tok.strip() + # Accept decimal, 0x-prefixed hex, or bare hex (e.g. "f") try: - s = tok.strip() if s.lower().startswith("0x"): return int(s, 16) - return int(s) + try: + return int(s) # decimal + except Exception: + return int(s, 16) # bare hex except Exception: return None @@ -1346,11 +1358,15 @@ def run_tiered_suite(log: LogReader, timeout_s: float, results: List[str]) -> bo pat2 = re.compile(r"^qdisc\s+\S+\s+\S+:\s+parent\s+([0-9A-Fa-fx]+):([0-9A-Fa-fx]+)\b.*$", re.MULTILINE) def _to_int2(tok: str) -> Optional[int]: + s = tok.strip() + # Accept decimal, 0x-prefixed hex, or bare hex (e.g. "f") try: - s = tok.strip() if s.lower().startswith("0x"): return int(s, 16) - return int(s) + try: + return int(s) # decimal + except Exception: + return int(s, 16) # bare hex except Exception: return None diff --git a/src/rust/lqos_bakery/src/commands.rs b/src/rust/lqos_bakery/src/commands.rs index 24f40692..55c4891d 100644 --- a/src/rust/lqos_bakery/src/commands.rs +++ b/src/rust/lqos_bakery/src/commands.rs @@ -613,18 +613,11 @@ impl BakeryCommands { let mut do_sqm; if execution_mode == ExecutionMode::Builder { - // In builder mode, if we're fully lazy - we don't do anything. - match config.queues.lazy_queues.as_ref() { - None | Some(LazyQueueMode::No) => { - do_htb = true; - do_sqm = true; - } - Some(LazyQueueMode::Full) => return None, - Some(LazyQueueMode::Htb) => { - do_htb = true; - do_sqm = false; // Only HTB, no SQM - } - } + // Initial tree build: always create HTB + SQM classes for circuits, + // regardless of lazy queue mode. Laziness applies to live updates + // (ExecutionMode::LiveUpdate) and pruning, not the first full build. + do_htb = true; + do_sqm = true; } else { // We're in live update mode match config.queues.lazy_queues.as_ref() { -- knotmirror 0.0.1 From 8764262e0c33c7827eda442ea5456813de1dd95d Mon Sep 17 00:00:00 2001 From: Herbert Wolverson Date: Sat, 15 Nov 2025 09:12:00 -0600 Subject: [PATCH 15/15] WIP: Integration test includes a "realistic" scenario with a big tree. --- src/bakery_integration_test.py | 442 ++++++++++++++++++++++++++++++++- 1 file changed, 438 insertions(+), 4 deletions(-) diff --git a/src/bakery_integration_test.py b/src/bakery_integration_test.py index a33e5488..db8a481d 100644 --- a/src/bakery_integration_test.py +++ b/src/bakery_integration_test.py @@ -329,6 +329,190 @@ def flat_circuits_base() -> List[Dict[str, str | int | float]]: ] +REALISTIC_TIERED_NETWORK = { + "NET1": { + "downloadBandwidthMbps": 900, + "uploadBandwidthMbps": 600, + "type": "Site", + "children": { + "NET1-1": { + "downloadBandwidthMbps": 400, + "uploadBandwidthMbps": 250, + "type": "Site", + "children": { + "NET1-1-1": { + "downloadBandwidthMbps": 180, + "uploadBandwidthMbps": 90, + "type": "AP", + }, + "NET1-1-2": { + "downloadBandwidthMbps": 160, + "uploadBandwidthMbps": 80, + "type": "AP", + }, + }, + }, + "NET1-2": { + "downloadBandwidthMbps": 350, + "uploadBandwidthMbps": 210, + "type": "AP", + }, + }, + }, + "NET2": { + "downloadBandwidthMbps": 800, + "uploadBandwidthMbps": 500, + "type": "Site", + "children": { + "NET2-1": { + "downloadBandwidthMbps": 300, + "uploadBandwidthMbps": 200, + "type": "Site", + "children": { + "NET2-1-1": { + "downloadBandwidthMbps": 150, + "uploadBandwidthMbps": 75, + "type": "AP", + }, + }, + }, + "NET2-2": { + "downloadBandwidthMbps": 220, + "uploadBandwidthMbps": 110, + "type": "AP", + }, + }, + }, + "NET3": { + "downloadBandwidthMbps": 700, + "uploadBandwidthMbps": 450, + "type": "Site", + "children": { + "NET3-1": { + "downloadBandwidthMbps": 260, + "uploadBandwidthMbps": 150, + "type": "AP", + }, + "NET3-2": { + "downloadBandwidthMbps": 240, + "uploadBandwidthMbps": 130, + "type": "AP", + }, + }, + }, +} + + +def _collect_nodes_from_network(net: Dict[str, dict]) -> List[Tuple[str, int, int]]: + """Flatten a nested network dict into (name, dl, ul) tuples.""" + nodes: List[Tuple[str, int, int]] = [] + + def walk(node_map: Dict[str, dict]) -> None: + for name, node in node_map.items(): + if not isinstance(node, dict): + continue + dl = node.get("downloadBandwidthMbps") + ul = node.get("uploadBandwidthMbps") + try: + dl_int = int(dl) if dl is not None else 0 + except Exception: + dl_int = 0 + try: + ul_int = int(ul) if ul is not None else 0 + except Exception: + ul_int = 0 + nodes.append((name, dl_int, ul_int)) + ch = node.get("children") + if isinstance(ch, dict): + walk(ch) + + walk(net) + return nodes + + +def realistic_tiered_circuits_base() -> List[Dict[str, str | int | float]]: + """Return asymmetric circuits for a realistic multi-site tree. + + At least two circuits are attached to each node, plus a pool of + orphan circuits that will be assigned to generated PNs. + """ + rows: List[Dict[str, str | int | float]] = [] + nodes = _collect_nodes_from_network(REALISTIC_TIERED_NETWORK) + circuit_id = 2001 + base_third_octet = 10 + + # Two circuits per node in the tree + for idx, (parent_name, dl, ul) in enumerate(nodes): + third = base_third_octet + idx + for j in range(2): + # Keep circuit rates comfortably below the parent and asymmetric + if dl > 0: + max_dl = int(max(5, dl * (0.4 - 0.03 * j))) + else: + max_dl = 10 + if ul > 0: + max_ul = int(max(2, ul * (0.3 - 0.03 * j))) + else: + max_ul = 5 + if max_ul >= max_dl: + max_ul = max(1, max_dl - 1) + + ip_addr = f"100.64.{third}.{j + 1}" + row: Dict[str, str | int | float] = { + "Circuit ID": str(circuit_id), + "Circuit Name": f"CIRCUIT_{circuit_id:04d}", + "Device ID": str(circuit_id), + "Device Name": f"DEV_{circuit_id:04d}", + "Parent Node": parent_name, + "MAC": "", + "IPv4": ip_addr, + "IPv6": "", + "Download Min Mbps": 1, + "Upload Min Mbps": 1, + "Download Max Mbps": max_dl, + "Upload Max Mbps": max_ul, + "Comment": "", + "sqm": "", + } + rows.append(row) + circuit_id += 1 + + # Add a pool of orphan circuits that will be placed under generated PNs + pn_dl_default = 100 + pn_ul_default = 50 + if generated_pn_download_mbps and generated_pn_upload_mbps: # type: ignore[name-defined] + try: + pn_dl_default = int(generated_pn_download_mbps()) # type: ignore[misc] + pn_ul_default = int(generated_pn_upload_mbps()) # type: ignore[misc] + except Exception: + pass + orphan_dl = max(5, min(80, pn_dl_default - 5)) + orphan_ul = max(2, min(30, pn_ul_default - 5, orphan_dl - 1)) + + for k in range(10): + ip_addr = f"100.64.250.{k + 1}" + row = { + "Circuit ID": str(circuit_id), + "Circuit Name": f"ORPHAN_{circuit_id:04d}", + "Device ID": str(circuit_id), + "Device Name": f"DEV_ORPHAN_{circuit_id:04d}", + "Parent Node": "none", + "MAC": "", + "IPv4": ip_addr, + "IPv6": "", + "Download Min Mbps": 1, + "Upload Min Mbps": 1, + "Download Max Mbps": orphan_dl, + "Upload Max Mbps": orphan_ul, + "Comment": "", + "sqm": "", + } + rows.append(row) + circuit_id += 1 + + return rows + + # ----------------------- # Test runner utilities # ----------------------- @@ -934,6 +1118,95 @@ def check_orphan_tc_attachment(orphan_id: str = "99901") -> Tuple[bool, List[str return True, msgs +def check_site_direction_ceil(node_name: str, expected_dl: Optional[float] = None, expected_ul: Optional[float] = None) -> Tuple[bool, List[str]]: + """Verify that a site's HTB ceilings match its configured asymmetric bandwidths. + + - interface_a (downlink): ceil == downloadBandwidthMbps + - interface_b (uplink): ceil == uploadBandwidthMbps + """ + msgs: List[str] = [] + qs = _load_queuing_structure() + if not isinstance(qs, dict): + return False, ["site direction check: queuingStructure.json not found"] + net = qs.get("Network") + if not isinstance(net, dict): + return False, ["site direction check: queuingStructure has no 'Network'"] + node = _find_parent_node(net, node_name) + if not isinstance(node, dict): + return False, [f"site direction check: node '{node_name}' not found in structure"] + + # Determine expected rates + try: + node_dl = float(node.get("downloadBandwidthMbps", -1)) + node_ul = float(node.get("uploadBandwidthMbps", -1)) + except Exception: + return False, [f"site direction check: node '{node_name}' missing downloadBandwidthMbps/uploadBandwidthMbps"] + if expected_dl is None: + expected_dl = node_dl + if expected_ul is None: + expected_ul = node_ul + + ok = True + if abs(node_dl - expected_dl) > 0.1 or abs(node_ul - expected_ul) > 0.1: + msgs.append( + f"site direction check: node '{node_name}' bandwidths {node_dl}/{node_ul} Mbps do not match expected {expected_dl}/{expected_ul} Mbps" + ) + ok = False + + # Interfaces + if not interface_a or not callable(interface_a): + return False, ["site direction check: interface_a() binding unavailable"] + try: + ifa = interface_a() + except Exception as e: + return False, [f"site direction check: failed to get interface_a(): {e}"] + ifb = None + if interface_b and callable(interface_b): + try: + ifb = interface_b() + except Exception: + ifb = None + + # IDs + maj_hex = node.get("classMajor") + mnr_hex = node.get("classMinor") + upm_hex = node.get("up_classMajor") + maj = _hex_to_int(maj_hex if isinstance(maj_hex, str) else str(maj_hex)) + mnr = _hex_to_int(mnr_hex if isinstance(mnr_hex, str) else str(mnr_hex)) + upm = _hex_to_int(upm_hex if isinstance(upm_hex, str) else str(upm_hex)) + if None in (maj, mnr): + return False, [f"site direction check: node '{node_name}' missing down IDs"] + + # Downlink + res_dl = _read_htb_rate_ceil_mbps(ifa, maj, mnr) + if not res_dl: + msgs.append(f"site direction check: {ifa} class {maj}:{mnr} not found for node '{node_name}'") + ok = False + else: + rate_mbps, ceil_mbps, line = res_dl + msgs.append( + f"site direction check: {node_name} down {ifa} ceil={ceil_mbps:.1f} expect={expected_dl:.1f} | {line}" + ) + if abs(ceil_mbps - expected_dl) > 0.6: + ok = False + + # Uplink + if ifb and upm is not None: + res_ul = _read_htb_rate_ceil_mbps(ifb, upm, mnr) + if not res_ul: + msgs.append(f"site direction check: {ifb} class {upm}:{mnr} not found for node '{node_name}'") + ok = False + else: + rate_mbps, ceil_mbps, line = res_ul + msgs.append( + f"site direction check: {node_name} up {ifb} ceil={ceil_mbps:.1f} expect={expected_ul:.1f} | {line}" + ) + if abs(ceil_mbps - expected_ul) > 0.6: + ok = False + + return ok, msgs + + def check_circuit_direction_ceil(circuit_id: str) -> Tuple[bool, List[str]]: """Verify that the circuit's ceil values are applied to the correct interfaces: - interface_a (downlink): ceil == maxDownload @@ -1490,6 +1763,157 @@ def run_tiered_suite(log: LogReader, timeout_s: float, results: List[str]) -> bo return ok +def run_realistic_tiered_suite(log: LogReader, timeout_s: float, results: List[str]) -> bool: + ok = True + + # Baseline: write realistic network and circuits (including orphans) + _mark_step("realistic: baseline") + write_network_json(REALISTIC_TIERED_NETWORK) + rows = realistic_tiered_circuits_base() + write_circuits(rows) + res = run_refresh_and_wait(log, timeout_s) + # First run may include MQ init/full reload; do not assert here + results.append("realistic: baseline: ok (initial run)") + + # Sanity: generated PNs and orphan behavior + _mark_step("realistic: generated PN items present") + passed_gpns, msgs_gpns = assert_generated_pns_present() + results.extend(msgs_gpns) + ok &= passed_gpns + + # Use one orphan circuit from the base set (last 10 entries) + orphan_candidate: Optional[str] = None + for r in reversed(rows): + if str(r.get("Parent Node")) == "none": + orphan_candidate = str(r.get("Circuit ID")) + break + if orphan_candidate is not None: + _mark_step("realistic: orphan circuit HTB attached to PN parent") + passed_orphan_tc, msgs_orphan_tc = check_orphan_tc_attachment(orphan_candidate) + results.extend(msgs_orphan_tc) + ok &= passed_orphan_tc + + _mark_step("realistic: orphan circuit ip mappings") + passed_orphan_map, msgs_orphan_map = check_ip_mappings_for_circuit(orphan_candidate) + results.extend(msgs_orphan_map) + ok &= passed_orphan_map + + _mark_step("realistic: no site/circuit minor collisions") + passed_coll, msgs_coll = check_no_site_circuit_minor_collisions() + results.extend(msgs_coll) + ok &= passed_coll + + # Site speed change on a mid-tree site (NET2-1) + _mark_step("realistic: site speed change") + net2 = json.loads(json.dumps(REALISTIC_TIERED_NETWORK)) + try: + net2["NET2"]["children"]["NET2-1"]["downloadBandwidthMbps"] = 360 + net2["NET2"]["children"]["NET2-1"]["uploadBandwidthMbps"] = 240 + except Exception: + results.append("realistic: site speed change: failed to modify NET2-1 speeds in fixture") + return False + write_network_json(net2) + step_t0 = time.time() + res = run_refresh_and_wait(log, timeout_s) + passed, msg = assert_no_full_reload("realistic: site speed change", res, step_t0) + results.append(msg) + ok &= passed + + _mark_step("realistic: site direction mapping (NET2-1)") + passed_site, msgs_site = check_site_direction_ceil("NET2-1", expected_dl=360.0, expected_ul=240.0) + results.extend(msgs_site) + ok &= passed_site + + # Circuit speed change for a deep leaf circuit (under NET1-1-1) + _mark_step("realistic: circuit speed change") + rows2 = json.loads(json.dumps(rows)) + target_idx: Optional[int] = None + for idx, r in enumerate(rows2): + if r.get("Parent Node") == "NET1-1-1": + target_idx = idx + break + if target_idx is None: + results.append("realistic: circuit speed change: no circuit found under NET1-1-1") + return False + target_id = str(rows2[target_idx]["Circuit ID"]) + try: + old_dl = float(rows2[target_idx]["Download Max Mbps"]) + old_ul = float(rows2[target_idx]["Upload Max Mbps"]) + except Exception: + old_dl = 10.0 + old_ul = 5.0 + rows2[target_idx]["Download Max Mbps"] = old_dl + 30.0 + rows2[target_idx]["Upload Max Mbps"] = old_ul + 10.0 + write_circuits(rows2) + step_t0 = time.time() + res = run_refresh_and_wait(log, timeout_s) + passed, msg = assert_no_full_reload("realistic: circuit speed change", res, step_t0) + results.append(msg) + ok &= passed + + _mark_step("realistic: circuit direction mapping (ceil)") + passed_dir, msgs_dir = check_circuit_direction_ceil(target_id) + results.extend(msgs_dir) + ok &= passed_dir + + _mark_step("realistic: circuit ip mappings (no change)") + passed_map, msgs_map = check_ip_mappings_for_circuit(target_id) + results.extend(msgs_map) + ok &= passed_map + + # Add circuit under a different leaf (NET3-2) + _mark_step("realistic: add circuit") + rows3 = json.loads(json.dumps(rows2)) + new_circuit_id = "99901" + new_circuit_ip = "100.64.200.1" + rows3.append({ + "Circuit ID": new_circuit_id, + "Circuit Name": "CIRCUIT_ADDED_99901", + "Device ID": new_circuit_id, + "Device Name": "DEV_ADDED_99901", + "Parent Node": "NET3-2", + "MAC": "", + "IPv4": new_circuit_ip, + "IPv6": "", + "Download Min Mbps": 1, + "Upload Min Mbps": 1, + "Download Max Mbps": 90, + "Upload Max Mbps": 30, + "Comment": "", + "sqm": "", + }) + write_circuits(rows3) + step_t0 = time.time() + res = run_refresh_and_wait(log, timeout_s) + if res.full_reload and not res.mq_init: + results.append("realistic: add circuit: full reload (allowed for larger tree)") + else: + results.append("realistic: add circuit: OK (no full reload)") + + _mark_step("realistic: added circuit ip mappings") + passed_add_map, msgs_add_map = check_ip_mappings_for_circuit(new_circuit_id) + results.extend(msgs_add_map) + ok &= passed_add_map + + # Remove the added circuit + _mark_step("realistic: remove circuit") + rows4 = [r for r in rows3 if str(r.get("Circuit ID")) != new_circuit_id] + write_circuits(rows4) + step_t0 = time.time() + res = run_refresh_and_wait(log, timeout_s) + if res.full_reload and not res.mq_init: + results.append("realistic: remove circuit: full reload (allowed for larger tree)") + else: + results.append("realistic: remove circuit: OK (no full reload)") + + _mark_step("realistic: removed circuit ip unmapped") + passed_unmap, msgs_unmap = check_ip_mapping_absent(new_circuit_ip) + results.extend(msgs_unmap) + ok &= passed_unmap + + return ok + + def run_flat_suite(log: LogReader, timeout_s: float, results: List[str]) -> bool: ok = True @@ -1570,6 +1994,7 @@ def main() -> int: g = ap.add_mutually_exclusive_group() g.add_argument("--tiered-only", action="store_true", help="Run tiered cases only") g.add_argument("--flat-only", action="store_true", help="Run flat cases only") + g.add_argument("--realistic-only", action="store_true", help="Run realistic tiered cases only") ap.add_argument("--no-restore", action="store_true", help="Do not restore original files (debugging)") args = ap.parse_args() @@ -1594,16 +2019,25 @@ def main() -> int: ctx = with_backups(files) with ctx: - # Run tiered suite - if not args.flat_only: + if args.tiered_only: + ok = run_tiered_suite(log, args.timeout, results) + overall_ok &= ok + elif args.flat_only: + ok = run_flat_suite(log, args.timeout, results) + overall_ok &= ok + elif args.realistic_only: + ok = run_realistic_tiered_suite(log, args.timeout, results) + overall_ok &= ok + else: ok = run_tiered_suite(log, args.timeout, results) overall_ok &= ok - # Run flat suite - if not args.tiered_only: ok = run_flat_suite(log, args.timeout, results) overall_ok &= ok + ok = run_realistic_tiered_suite(log, args.timeout, results) + overall_ok &= ok + print("Results:") for r in results: print(f"- {r}")