-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpython-layer-audit.txt
More file actions
3483 lines (2686 loc) · 79.1 KB
/
Copy pathpython-layer-audit.txt
File metadata and controls
3483 lines (2686 loc) · 79.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
===== PYTHON LAYER STRUCTURE =====
python-layer/core/api_provider.py
python-layer/core/go_client.py
python-layer/core/__init__.py
python-layer/core/mock_provider.py
python-layer/core/models.py
python-layer/core/provider.py
python-layer/data/mock_data.json
python-layer/forecast/capacity_pipeline.py
python-layer/forecast/capacity.py
python-layer/forecast/evaluation.py
python-layer/forecast/forecast.py
python-layer/forecast/growth.py
python-layer/forecast/__init__.py
python-layer/forecast/metrics.py
python-layer/forecast/model.py
python-layer/forecast/pipeline.py
python-layer/.gitkeep
python-layer/README.md
python-layer/recommend/engine.py
python-layer/recommend/__init__.py
python-layer/recommend/pipeline.py
python-layer/recommend/rules.py
python-layer/requirements-lock.txt
python-layer/requirements.txt
python-layer/service.py
python-layer/test_capacity.py
python-layer/test_forecast.py
python-layer/test_full_forecast.py
python-layer/test_growth.py
python-layer/test_model_evaluation.py
python-layer/test_provider.py
python-layer/test_recommendation_pipeline.py
python-layer/test_recommendations.py
python-layer/tests/test_forecast.py
python-layer/tests/test_recommendations.py
===== PYTHON SOURCE =====
============================================================
FILE: python-layer/core/__init__.py
============================================================
============================================================
FILE: python-layer/core/mock_provider.py
============================================================
import json
from datetime import datetime
from pathlib import Path
from typing import List, Dict
from .provider import DataProvider
from .models import (
Snapshot,
StaleFile,
DuplicateCluster,
Action,
)
class MockDataProvider(DataProvider):
"""
Loads storage optimizer data from the local mock JSON dataset.
This provider is used during Windows development.
"""
def __init__(self, data_path: str | Path):
self.data_path = Path(data_path)
if not self.data_path.exists():
raise FileNotFoundError(
f"Mock dataset not found: {self.data_path}"
)
with self.data_path.open("r", encoding="utf-8") as file:
self.data = json.load(file)
def get_snapshots(self) -> List[Snapshot]:
snapshots = []
for item in self.data.get("snapshots", []):
snapshots.append(
Snapshot(
id=item["id"],
scanned_at=datetime.fromisoformat(
item["scanned_at"]
),
root_path=item["root_path"],
total_files=item["total_files"],
total_bytes=item["total_bytes"],
)
)
return snapshots
def get_category_stats(self) -> Dict[str, Dict[str, int]]:
stats = self.data.get("stats", {})
return stats.get("categories", {})
def get_stale_files(self, days: int = 30) -> List[StaleFile]:
stale_data = self.data.get("stale_files", {})
files = []
for item in stale_data.get("files", []):
files.append(
StaleFile(
path=item["path"],
size_bytes=item["size_bytes"],
last_accessed=datetime.fromisoformat(
item["last_accessed"]
),
staleness_score=item["staleness_score"],
)
)
return files
def get_duplicates(self) -> List[DuplicateCluster]:
duplicate_data = self.data.get("duplicates", {})
clusters = []
for item in duplicate_data.get("clusters", []):
clusters.append(
DuplicateCluster(
hash=item["hash"],
file_count=item["file_count"],
total_bytes=item["total_bytes"],
wasted_bytes=item["wasted_bytes"],
files=item["files"],
)
)
return clusters
def get_action_history(self) -> List[Action]:
actions = []
for item in self.data.get("actions_history", []):
actions.append(
Action(
id=item["id"],
action=item["action"],
path=item["path"],
size_bytes=item["size_bytes"],
created_at=datetime.fromisoformat(
item["created_at"]
),
)
)
return actions
============================================================
FILE: python-layer/core/models.py
============================================================
from dataclasses import dataclass
from datetime import datetime
from typing import List, Dict, Any
@dataclass
class Snapshot:
id: int
scanned_at: datetime
root_path: str
total_files: int
total_bytes: int
@dataclass
class CategoryStats:
files: int
bytes: int
@dataclass
class StaleFile:
path: str
size_bytes: int
last_accessed: datetime
staleness_score: float
@dataclass
class DuplicateCluster:
hash: str
file_count: int
total_bytes: int
wasted_bytes: int
files: List[str]
@dataclass
class Action:
id: int
action: str
path: str
size_bytes: int
created_at: datetime
============================================================
FILE: python-layer/core/provider.py
============================================================
from abc import ABC, abstractmethod
from typing import List, Dict
from .models import (
Snapshot,
StaleFile,
DuplicateCluster,
Action,
)
class DataProvider(ABC):
"""
Abstract interface for storage optimizer data.
The forecasting and recommendation layers will depend
on this interface rather than directly on the Go API
or mock data.
"""
@abstractmethod
def get_snapshots(self) -> List[Snapshot]:
pass
@abstractmethod
def get_category_stats(self) -> Dict[str, Dict[str, int]]:
pass
@abstractmethod
def get_stale_files(self, days: int = 30) -> List[StaleFile]:
pass
@abstractmethod
def get_duplicates(self) -> List[DuplicateCluster]:
pass
@abstractmethod
def get_action_history(self) -> List[Action]:
pass
============================================================
FILE: python-layer/core/go_client.py
============================================================
from typing import Any
import requests
class GoCoreClient:
"""Client for the Go storage optimizer core API."""
def __init__(
self,
base_url: str = "http://127.0.0.1:8080",
timeout: float = 10.0,
):
self.base_url = base_url.rstrip("/")
self.timeout = timeout
def _get(self, path: str) -> Any:
response = requests.get(
f"{self.base_url}{path}",
timeout=self.timeout,
)
response.raise_for_status()
return response.json()
def _post(
self,
path: str,
payload: dict | None = None,
) -> Any:
response = requests.post(
f"{self.base_url}{path}",
json=payload,
timeout=self.timeout,
)
response.raise_for_status()
return response.json()
def health(self) -> dict:
return self._get("/api/v1/health")
def duplicates(self) -> dict:
return self._get("/api/v1/duplicates")
def stale(self, days: int = 30) -> dict:
return self._get(
f"/api/v1/stale?days={days}"
)
def snapshots(self, limit: int = 100) -> dict:
return self._get(
f"/api/v1/snapshots?limit={limit}"
)
============================================================
FILE: python-layer/core/api_provider.py
============================================================
from datetime import datetime
from typing import Any
import requests
from .models import (
StorageSnapshot,
)
class GoCoreAPIError(Exception):
"""Raised when the Go Core API cannot be reached or returns an error."""
class GoCoreProvider:
"""
Python-side client for the Go Core REST API.
The Python layer never accesses SQLite directly.
All filesystem/storage information comes from Go Core.
"""
def __init__(
self,
base_url: str = "http://127.0.0.1:8080/api/v1",
timeout: float = 10.0,
):
self.base_url = base_url.rstrip("/")
self.timeout = timeout
def _get(
self,
endpoint: str,
params: dict[str, Any] | None = None,
) -> dict[str, Any]:
url = f"{self.base_url}/{endpoint.lstrip('/')}"
try:
response = requests.get(
url,
params=params,
timeout=self.timeout,
)
except requests.RequestException as exc:
raise GoCoreAPIError(
f"Unable to connect to Go Core at {url}: {exc}"
) from exc
if not response.ok:
raise GoCoreAPIError(
f"Go Core returned HTTP {response.status_code}: "
f"{response.text}"
)
try:
return response.json()
except ValueError as exc:
raise GoCoreAPIError(
f"Go Core returned invalid JSON from {url}"
) from exc
def health(self) -> dict[str, Any]:
return self._get("health")
def get_stats(self) -> dict[str, Any]:
return self._get("stats")
def get_snapshots(
self,
limit: int = 50,
root: str | None = None,
) -> list[dict[str, Any]]:
params = {
"limit": limit,
}
if root:
params["root"] = root
result = self._get(
"snapshots",
params=params,
)
return result.get("snapshots", [])
def get_duplicates(
self,
full: bool = False,
workers: int | None = None,
) -> dict[str, Any]:
params = {
"full": str(full).lower(),
}
if workers:
params["workers"] = workers
return self._get(
"files/duplicates",
params=params,
)
def get_stale(
self,
days: int = 30,
min_score: float = 0.05,
limit: int = 50,
) -> dict[str, Any]:
return self._get(
"files/stale",
params={
"days": days,
"min_score": min_score,
"limit": limit,
},
)
============================================================
FILE: python-layer/forecast/__init__.py
============================================================
============================================================
FILE: python-layer/forecast/capacity.py
============================================================
from dataclasses import dataclass
from datetime import datetime
from typing import List
from .model import ForecastPoint
@dataclass
class CapacityPrediction:
total_capacity_bytes: int
current_bytes: int
current_utilization_percent: float
threshold_90_bytes: int
threshold_100_bytes: int
date_at_90_percent: datetime | None
date_at_100_percent: datetime | None
days_until_90_percent: float | None
days_until_100_percent: float | None
def find_threshold_date(
forecast_points: List[ForecastPoint],
threshold_bytes: int,
) -> datetime | None:
"""
Find the first forecast date where predicted storage
reaches or exceeds the requested threshold.
"""
for point in forecast_points:
if point.predicted_bytes >= threshold_bytes:
return point.date
return None
def calculate_days_until(
current_date: datetime,
target_date: datetime | None,
) -> float | None:
if target_date is None:
return None
difference = (
target_date - current_date
).total_seconds()
return difference / 86400
def calculate_capacity_prediction(
current_bytes: int,
current_date: datetime,
total_capacity_bytes: int,
forecast_points: List[ForecastPoint],
) -> CapacityPrediction:
if total_capacity_bytes <= 0:
raise ValueError(
"Total capacity must be greater than zero."
)
if current_bytes < 0:
raise ValueError(
"Current storage cannot be negative."
)
threshold_90 = int(
total_capacity_bytes * 0.90
)
threshold_100 = total_capacity_bytes
date_90 = find_threshold_date(
forecast_points,
threshold_90,
)
date_100 = find_threshold_date(
forecast_points,
threshold_100,
)
utilization = (
current_bytes
/ total_capacity_bytes
) * 100
return CapacityPrediction(
total_capacity_bytes=total_capacity_bytes,
current_bytes=current_bytes,
current_utilization_percent=utilization,
threshold_90_bytes=threshold_90,
threshold_100_bytes=threshold_100,
date_at_90_percent=date_90,
date_at_100_percent=date_100,
days_until_90_percent=calculate_days_until(
current_date,
date_90,
),
days_until_100_percent=calculate_days_until(
current_date,
date_100,
),
)
============================================================
FILE: python-layer/forecast/capacity_pipeline.py
============================================================
from pathlib import Path
from core.mock_provider import MockDataProvider
from .forecast import forecast_storage
from .capacity import calculate_capacity_prediction
def run_capacity_prediction(
total_capacity_bytes: int,
forecast_days: int = 365,
):
"""
Generate storage forecasts and determine when the
disk reaches 90% and 100% capacity.
"""
provider = MockDataProvider(
Path("data/mock_data.json")
)
snapshots = provider.get_snapshots()
forecast_result = forecast_storage(
snapshots,
forecast_days=forecast_days,
validation_size=3,
)
current_snapshot = snapshots[-1]
capacity_prediction = (
calculate_capacity_prediction(
current_bytes=current_snapshot.total_bytes,
current_date=current_snapshot.scanned_at,
total_capacity_bytes=total_capacity_bytes,
forecast_points=forecast_result.forecast_points,
)
)
return forecast_result, capacity_prediction
============================================================
FILE: python-layer/forecast/evaluation.py
============================================================
from dataclasses import dataclass
from typing import List
import numpy as np
from core.models import Snapshot
from .metrics import (
calculate_mae,
calculate_rmse,
)
from .model import (
LinearForecastModel,
PolynomialForecastModel,
HoltWintersForecastModel,
)
@dataclass
class ModelEvaluation:
model_name: str
mae_bytes: float
rmse_bytes: float
def evaluate_linear(
train: List[Snapshot],
test: List[Snapshot],
) -> ModelEvaluation:
model = LinearForecastModel()
model.fit(train)
test_dates = [
snapshot.scanned_at
for snapshot in test
]
actual = np.array([
snapshot.total_bytes
for snapshot in test
])
predicted = model.predict(
test_dates
)
return ModelEvaluation(
model_name="Linear Regression",
mae_bytes=calculate_mae(
actual,
predicted,
),
rmse_bytes=calculate_rmse(
actual,
predicted,
),
)
def evaluate_polynomial(
train: List[Snapshot],
test: List[Snapshot],
degree: int = 2,
) -> ModelEvaluation:
model = PolynomialForecastModel(
degree=degree
)
model.fit(train)
test_dates = [
snapshot.scanned_at
for snapshot in test
]
actual = np.array([
snapshot.total_bytes
for snapshot in test
])
predicted = model.predict(
test_dates
)
return ModelEvaluation(
model_name=f"Polynomial Regression (degree={degree})",
mae_bytes=calculate_mae(
actual,
predicted,
),
rmse_bytes=calculate_rmse(
actual,
predicted,
),
)
def evaluate_holt_winters(
train: List[Snapshot],
test: List[Snapshot],
) -> ModelEvaluation:
model = HoltWintersForecastModel()
model.fit(train)
actual = np.array([
snapshot.total_bytes
for snapshot in test
])
predicted = model.predict(
len(test)
)
return ModelEvaluation(
model_name="Holt-Winters",
mae_bytes=calculate_mae(
actual,
predicted,
),
rmse_bytes=calculate_rmse(
actual,
predicted,
),
)
def evaluate_models(
snapshots: List[Snapshot],
test_size: int = 3,
) -> List[ModelEvaluation]:
if len(snapshots) <= test_size:
raise ValueError(
"Not enough snapshots for validation."
)
snapshots = sorted(
snapshots,
key=lambda snapshot: snapshot.scanned_at,
)
train = snapshots[:-test_size]
test = snapshots[-test_size:]
results = []
results.append(
evaluate_linear(
train,
test,
)
)
results.append(
evaluate_polynomial(
train,
test,
)
)
results.append(
evaluate_holt_winters(
train,
test,
)
)
return results
============================================================
FILE: python-layer/forecast/forecast.py
============================================================
from dataclasses import dataclass
from datetime import datetime
from typing import List
from core.models import Snapshot
from .evaluation import evaluate_models
from .pipeline import (
create_future_dates,
forecast_linear,
forecast_polynomial,
forecast_holt_winters,
)
from .model import ForecastPoint
@dataclass
class ForecastResult:
model_name: str
forecast_points: List[ForecastPoint]
mae_bytes: float
rmse_bytes: float
def forecast_storage(
snapshots: List[Snapshot],
forecast_days: int = 30,
validation_size: int = 3,
) -> ForecastResult:
"""
Select the best forecasting model using chronological
validation and generate future storage predictions.
"""
if len(snapshots) < validation_size + 3:
raise ValueError(
"Not enough snapshots for forecasting."
)
snapshots = sorted(
snapshots,
key=lambda snapshot: snapshot.scanned_at,
)
# ----------------------------------------
# 1. Evaluate candidate models
# ----------------------------------------
evaluations = evaluate_models(
snapshots,
test_size=validation_size,
)
# ----------------------------------------
# 2. Select model with lowest MAE
# ----------------------------------------
best = min(
evaluations,
key=lambda result: result.mae_bytes,
)
# ----------------------------------------
# 3. Generate future dates
# ----------------------------------------
latest_date = snapshots[-1].scanned_at
future_dates = create_future_dates(
latest_date,
forecast_days,
)
# ----------------------------------------
# 4. Train selected model on ALL data
# ----------------------------------------
if best.model_name == "Linear Regression":
forecast_points = forecast_linear(
snapshots,
future_dates,
)
elif best.model_name == "Polynomial Regression (degree=2)":
forecast_points = forecast_polynomial(
snapshots,
future_dates,
degree=2,
)
elif best.model_name == "Holt-Winters":
forecast_points = forecast_holt_winters(
snapshots,
future_dates,
)
else:
raise RuntimeError(
f"Unknown model: {best.model_name}"
)
return ForecastResult(
model_name=best.model_name,
forecast_points=forecast_points,
mae_bytes=best.mae_bytes,
rmse_bytes=best.rmse_bytes,
)
============================================================
FILE: python-layer/forecast/growth.py
============================================================
from dataclasses import dataclass
from datetime import datetime
from typing import List
from core.models import Snapshot
@dataclass
class GrowthMetrics:
current_bytes: int
current_files: int
total_growth_bytes: int
total_growth_percent: float
daily_growth_rate_bytes: float
weekly_growth_rate_bytes: float
average_daily_growth_bytes: float
growth_volatility_bytes: float
snapshot_count: int
@dataclass
class GrowthPoint:
timestamp: datetime
bytes: int
growth_bytes: int
growth_rate_bytes_per_day: float
def calculate_growth_points(
snapshots: List[Snapshot],
) -> List[GrowthPoint]:
"""
Calculate growth between consecutive storage snapshots.
"""
if len(snapshots) < 2:
return []
snapshots = sorted(
snapshots,
key=lambda snapshot: snapshot.scanned_at,
)
points = []
for previous, current in zip(
snapshots,
snapshots[1:],
):
time_difference = (
current.scanned_at - previous.scanned_at
)
days = time_difference.total_seconds() / 86400
if days <= 0:
continue
growth_bytes = (
current.total_bytes
- previous.total_bytes
)
daily_growth = growth_bytes / days
points.append(
GrowthPoint(
timestamp=current.scanned_at,
bytes=current.total_bytes,
growth_bytes=growth_bytes,
growth_rate_bytes_per_day=daily_growth,
)
)
return points
def calculate_growth_metrics(
snapshots: List[Snapshot],
) -> GrowthMetrics:
"""
Calculate overall storage growth metrics.
"""
if not snapshots:
raise ValueError(
"At least one snapshot is required"
)
snapshots = sorted(
snapshots,
key=lambda snapshot: snapshot.scanned_at,
)
latest = snapshots[-1]
earliest = snapshots[0]
total_growth_bytes = (
latest.total_bytes
- earliest.total_bytes
)
if earliest.total_bytes > 0:
total_growth_percent = (
total_growth_bytes
/ earliest.total_bytes
) * 100