Newer Older
f16725e 3 months ago History
991 lines | 37.293kb
Bogdan Timofte authored 3 months ago
1
# autoSMART Development Guide
2

            
3
## 📚 Developer Documentation Index
4

            
5
This document serves as the complete guide for developers working on autoSMART. It includes development environment setup, architecture documentation, testing procedures, and developer-specific changelog.
6

            
7
### Quick Navigation
8
- [Codebase Structure](#codebase-structure)
9
- [Development Environment Setup](#development-environment-setup)
10
- [Architecture Overview](#architecture-overview)
11
- [Database Development](#database-development)
12
- [Module Development](#module-development)
13
- [Testing Strategies](#testing-strategies)
14
- [Deployment Procedures](#deployment-procedures)
15
- [Developer Changelog](#developer-changelog)
16
- [Technical Reference](#technical-reference)
17

            
18
## 📁 Codebase Structure
19

            
20
autoSMART follows a modular architecture with clear separation of concerns. Below is the complete directory structure and file descriptions:
21

            
22
### Project Root
23
```
24
autoSMART/
25
├── README.md                    # Symlink to docs/README.md (end-user documentation)
26
├── .deployignore               # Files excluded from production deployment
27
├── config/                     # Configuration files and templates
28
├── docs/                       # Documentation (mixed deployment)
29
├── lib/                        # Perl modules and core libraries
30
├── scripts/                    # Executable scripts and utilities
31
└── sql/                        # Database schema and SQL files
32
```
33

            
34
### 📁 `/config/` - Configuration Management
35
Configuration files are organized by scope and environment:
36

            
37
```
38
config/
39
├── cluster.conf                # Cluster-wide settings (shared across nodes)
40
├── cluster-ebony.conf         # Node-specific configuration for ebony
41
├── database.conf              # PostgreSQL connection settings
42
├── openai.conf               # OpenAI API configuration and prompts
43
├── smart.conf                # SMART parameter thresholds and monitoring rules
44
├── default                   # Default/template configuration
45
└── debug-ebony.sh           # Development debugging script for ebony node
46
```
47

            
48
#### Configuration File Details
49
- **`cluster.conf`** (88 lines):
50
  - Cluster topology and node definitions
51
  - Node hostnames, IP addresses, and roles
52
  - Shared monitoring parameters across cluster
53
  - Global system settings and defaults
54
  - Inter-node communication configuration
55

            
56
- **`database.conf`** (30 lines):
57
  - PostgreSQL connection parameters (host, port, database, credentials)
58
  - Connection pooling settings and timeouts
59
  - Database-specific optimizations and tuning parameters
60
  - SSL configuration and security settings
61

            
62
- **`openai.conf`** (50 lines):
63
  - OpenAI API key and model configuration
64
  - Prompt templates for failure prediction analysis
65
  - Response parsing rules and confidence thresholds
66
  - Rate limiting and cost management settings
67
  - Fallback configurations for API failures
68

            
69
- **`smart.conf`** (57 lines):
70
  - SMART parameter monitoring thresholds for different drive types
71
  - Critical parameter definitions and escalation rules
72
  - Alert generation rules and notification preferences
73
  - Parameter collection intervals and scheduling
74
  - Drive type specific monitoring configurations
75

            
76
- **`default`** (107 lines):
77
  - Default/template configuration for new node deployments
78
  - Standard parameter values and system defaults
79
  - Configuration validation rules and constraints
80
  - Example configurations with detailed comments
81

            
82
- **`cluster-ebony.conf`** (13 lines):
83
  - Node-specific configuration overrides for ebony node
84
  - Local network settings and hardware-specific parameters
85
  - Custom thresholds for specific hardware configurations
86

            
87
- **`debug-ebony.sh`** (29 lines):
88
  - Development debugging utilities for ebony node
89
  - Test data generation and validation scripts
90
  - Development environment setup and configuration
91
  - Debugging tools and diagnostic utilities
92

            
93
### 📁 `/lib/` - Core Perl Modules
94
Core business logic implemented as reusable Perl modules:
95

            
96
```
97
lib/
98
├── SmartCollector.pm          # SMART data collection and hardware tracking
99
└── PredictionEngine.pm        # AI-powered failure prediction engine
100
```
101

            
102
#### Module Architecture
103
- **`SmartCollector.pm`** (802 lines):
104
  - **Hardware Identification**: Device detection using serial numbers and model names
105
  - **SMART Data Collection**: Integration with smartmontools for comprehensive parameter collection
106
  - **Migration Detection**: Algorithms to detect when drives move between nodes or device paths
107
  - **Differential Storage**: Intelligent storage system that only saves changed parameters
108
  - **Database Layer**: PostgreSQL integration with connection pooling and error handling
109
  - **Storage Efficiency**: Real-time monitoring of storage optimization effectiveness
110
  - **Configuration Management**: Dynamic configuration loading and validation
111
  - **Error Handling**: Comprehensive error handling with detailed logging
112

            
113
- **`PredictionEngine.pm`** (607 lines):
114
  - **OpenAI Integration**: Direct API communication with GPT models
115
  - **Prompt Engineering**: Sophisticated prompt templates for failure prediction
116
  - **Response Processing**: Parsing and validation of AI-generated predictions
117
  - **Confidence Scoring**: Statistical analysis of prediction reliability
118
  - **Timeline Estimation**: Failure time prediction with confidence intervals
119
  - **Cost Optimization**: API usage optimization and request batching
120
  - **Error Recovery**: Robust error handling for API failures and rate limits
121

            
122
### 📁 `/scripts/` - Executable Components
123
Production scripts and development utilities:
124

            
125
```
126
scripts/
127
├── autosmart-collector.pl      # Main data collection daemon
128
├── autosmart-predictor.pl      # AI prediction processing
129
├── autosmart-report.pl         # Report generation engine
130
├── autosmart-migration-report.pl # Hardware migration analysis
131
├── smart-collector-daemon.pl   # Background collection service
132
├── deploy.sh                   # Unified deployment script
133
├── deploy-production.sh        # Production cluster deployment
134
├── install.sh                  # Symlink to deploy.sh for compatibility
135
├── uninstall.sh               # Complete system removal
136
├── monitor-cluster.sh          # Cluster health monitoring
137
├── test-smart-collection.pl    # SMART collection testing
138
├── test-differential-storage.pl # Storage optimization testing
139
├── test-db-connection.pl       # Database connectivity testing
140
└── simple-smart-test.pl        # Basic SMART functionality test
141
```
142

            
143
#### Script Categories
144

            
145
##### Production Scripts
146
- **`autosmart-collector.pl`** (348 lines):
147
  - Main collection daemon that runs on each node
148
  - Scheduled SMART data collection and processing
149
  - Hardware detection and migration tracking
150
  - Integration with SmartCollector.pm module
151
  - Command-line options for daemon mode, single-run, and debugging
152

            
153
- **`autosmart-predictor.pl`** (483 lines):
154
  - Processes collected data for AI predictions
155
  - Batch processing of pending SMART readings
156
  - Integration with PredictionEngine.pm for OpenAI communication
157
  - Prediction result storage and confidence tracking
158

            
159
- **`autosmart-report.pl`** (662 lines):
160
  - Generates comprehensive health reports and alerts
161
  - Configurable report formats (summary, detailed, trend analysis)
162
  - Email notification system for critical alerts
163
  - Historical data analysis and trend detection
164

            
165
- **`smart-collector-daemon.pl`** (252 lines):
166
  - Background service wrapper for collector
167
  - Process management and restart capabilities
168
  - Log rotation and system integration
169
  - Service status monitoring and health checks
170

            
171
##### Deployment Scripts
172
- **`deploy.sh`** (697 lines):
173
  - Unified deployment for single node or cluster
174
  - Supports install, uninstall, and cluster deployment modes
175
  - Automatic dependency checking and installation
176
  - Configuration template deployment and customization
177
  - System service registration and startup
178

            
179
- **`deploy-production.sh`** (116 lines):
180
  - Production-specific deployment procedures
181
  - Multi-node cluster deployment automation
182
  - Production safety checks and validation
183
  - Rollback capabilities for failed deployments
184

            
185
- **`uninstall.sh`** (187 lines):
186
  - Complete system cleanup and removal
187
  - Service stopping and deregistration
188
  - File and directory cleanup
189
  - Database cleanup options (configurable)
190

            
191
- **`monitor-cluster.sh`** (515 lines):
192
  - Ongoing cluster health monitoring
193
  - Node status verification and reporting
194
  - Service health checks across all cluster nodes
195
  - Automated restart capabilities for failed services
196

            
197
##### Development & Testing Scripts
198
- **`test-smart-collection.pl`** (132 lines):
199
  - Validates SMART data collection functionality
200
  - Tests hardware detection and identification
201
  - Verifies database connectivity and data storage
202
  - Performance benchmarking for collection operations
203

            
204
- **`test-differential-storage.pl`** (270 lines):
205
  - Comprehensive testing of storage optimization
206
  - Validates differential storage algorithms
207
  - Tests change detection and storage efficiency
208
  - Performance analysis and optimization verification
209

            
210
- **`test-db-connection.pl`** (55 lines):
211
  - Database connectivity verification
212
  - Connection pooling and timeout testing
213
  - SQL execution validation
214
  - Database performance testing
215

            
216
- **`simple-smart-test.pl`** (144 lines):
217
  - Basic functionality testing
218
  - Quick validation of core components
219
  - Integration testing for development
220
  - Smoke testing for deployment validation
221

            
222
##### Analysis Scripts
223
- **`autosmart-migration-report.pl`** (615 lines):
224
  - Hardware migration tracking and analysis
225
  - Migration pattern detection and reporting
226
  - Historical migration data analysis
227
  - Migration-related issue identification and troubleshooting
228

            
229
### 📁 `/sql/` - Database Schema
230
PostgreSQL database definitions and utilities:
231

            
232
```
233
sql/
234
├── schema.sql                  # Complete production database schema
235
└── schema-fixed.sql           # Schema with specific fixes/patches
236
```
237

            
238
#### Database Schema Components
239
- **Core Tables**:
240
  - `hdd_inventory`: Hardware identification and location tracking
241
  - `smart_readings`: SMART parameter data with differential storage
242
  - `hdd_migrations`: Drive movement logging between nodes/paths
243
- **AI Integration**:
244
  - `predictions`: AI-generated failure predictions with confidence scores
245
  - `alert_history`: Alert notification tracking and escalation
246
- **Configuration**:
247
  - `smart_thresholds`: Configurable parameter thresholds and alert rules
248
  - `system_config`: System-wide configuration parameters
249
- **Optimization**:
250
  - Differential storage functions (`should_store_smart_reading()`)
251
  - Reconstructed views (`smart_readings_reconstructed`)
252
  - Change detection algorithms with SHA256 checksums
253
- **Indexing**:
254
  - Performance-optimized indexes for temporal queries
255
  - Hardware identification indexes for fast lookups
256
  - Composite indexes for complex query patterns
257

            
258
##### Schema Files Details
259
- **`schema.sql`** (726 lines):
260
  - Complete production database schema
261
  - Full table definitions with constraints and indexes
262
  - PostgreSQL functions for differential storage
263
  - Views for data reconstruction and reporting
264
  - Trigger definitions for automated processes
265

            
266
- **`schema-fixed.sql`** (423 lines):
267
  - Schema patches and specific fixes
268
  - Migration scripts for schema updates
269
  - Performance optimization adjustments
270
  - Compatibility fixes for different PostgreSQL versions
271

            
272
### 📁 `/docs/` - Documentation
273
Documentation organized by audience and deployment status:
274

            
275
```
276
docs/
277
├── README.md                   # End-user guide (DEPLOYED)
278
├── INSTALLATION.md             # Setup and configuration (DEPLOYED)
279
├── CHANGELOG.md               # Release notes for end-users (DEPLOYED)
280
├── API.md                     # OpenAI API configuration (DEPLOYED)
281
├── DEVELOPMENT.md             # Developer guide (NOT DEPLOYED)
282
└── DIFFERENTIAL_STORAGE.md    # Technical storage details (NOT DEPLOYED)
283
```
284

            
285
#### Documentation Deployment Strategy
286
- **Deployed docs**: End-user facing documentation
287
- **Non-deployed docs**: Developer and technical implementation details
288

            
289
### 🔧 Key File Relationships
290

            
291
#### Data Flow Architecture
292
```
293
smartmontools → SmartCollector.pm → PostgreSQL → PredictionEngine.pm → OpenAI API
294
     ↓               ↓                    ↓              ↓
295
autosmart-collector.pl → Database → autosmart-predictor.pl → Reports
296
```
297

            
298
#### Configuration Hierarchy
299
```
300
cluster.conf (global) → node-specific.conf → smart.conf → openai.conf
301
                                ↓
302
                        Individual script configurations
303
```
304

            
305
#### Module Dependencies
306
```
307
autosmart-collector.pl
308
├── SmartCollector.pm
309
├── database.conf
310
├── smart.conf
311
└── cluster.conf
312

            
313
autosmart-predictor.pl
314
├── PredictionEngine.pm
315
├── SmartCollector.pm (for data access)
316
├── openai.conf
317
└── database.conf
318
```
319

            
320
### 📊 Codebase Metrics
321

            
322
#### File Type Distribution
323
- **Perl Scripts**: 8 production scripts + 4 test scripts (12 total)
324
- **Perl Modules**: 2 core modules (1,409 total lines)
325
- **Shell Scripts**: 5 deployment/management scripts (1,645 total lines)
326
- **SQL Files**: 2 schema files (1,149 total lines)
327
- **Configuration**: 7 configuration files (374 total lines)
328
- **Documentation**: 5 documentation files
329

            
330
#### Code Complexity by Lines of Code
331
- **SmartCollector.pm**: 802 lines (High complexity - hardware integration, differential storage)
332
- **PredictionEngine.pm**: 607 lines (Medium complexity - API integration, data processing)
333
- **Database Schema**: 726 lines (High complexity - advanced PostgreSQL features)
334
- **Deploy Scripts**: 697 lines each (Medium complexity - system integration)
335
- **Report Generation**: 662 lines (Medium complexity - data analysis and formatting)
336
- **Migration Analysis**: 615 lines (Medium complexity - pattern detection)
337
- **Cluster Monitoring**: 515 lines (Medium complexity - distributed system monitoring)
338

            
339
#### Total Codebase Size
340
- **Production Code**: ~4,500 lines (Perl modules + production scripts)
341
- **Deployment & Management**: ~1,800 lines (deployment and monitoring scripts)
342
- **Testing Code**: ~600 lines (test scripts and utilities)
343
- **Database Schema**: ~1,150 lines (PostgreSQL schema and functions)
344
- **Configuration**: ~375 lines (configuration templates and examples)
345
- **Total**: ~8,400+ lines of code
346

            
347
#### Testing Coverage Areas
348
- **Unit Tests**: Module-specific functionality testing
349
- **Integration Tests**: End-to-end data flow validation
350
- **Performance Tests**: Storage efficiency and query optimization benchmarks
351
- **Deployment Tests**: Installation and configuration validation across environments
352
- **Regression Tests**: Automated testing for core functionality preservation
353

            
354
### 🏗️ Development Workflow
355

            
356
#### Getting Started with Development
357
1. **Clone Repository**: Set up local development environment
358
2. **Database Setup**: Configure PostgreSQL connection to development database
359
3. **Perl Dependencies**: Install required CPAN modules
360
4. **Configuration**: Copy and customize configuration templates
361
5. **Testing**: Run test suite to verify setup
362

            
363
#### Adding New Features
364
1. **Module Development**: Extend existing Perl modules or create new ones
365
2. **Script Integration**: Create or modify scripts to use new functionality
366
3. **Database Changes**: Update schema if new data structures are needed
367
4. **Testing**: Add comprehensive tests for new functionality
368
5. **Documentation**: Update both end-user and developer documentation
369

            
370
#### Code Organization Principles
371
- **Separation of Concerns**: Each module and script has a specific, well-defined responsibility
372
- **Configuration-Driven**: System behavior is controlled through configuration files rather than hard-coded values
373
- **Database-Centric**: PostgreSQL serves as the central data store with business logic in database functions
374
- **Modular Design**: Components can be developed, tested, and deployed independently
375
- **Error Handling**: Comprehensive error handling and logging throughout all components
376
- **Performance-First**: Optimized for high-volume data collection and processing
377
- **Scalability**: Designed to scale across multiple nodes in a cluster environment
378

            
379
#### Development Patterns Used
380
- **Factory Pattern**: Configuration-based object creation in Perl modules
381
- **Observer Pattern**: Event-driven processing for hardware changes and alerts
382
- **Strategy Pattern**: Configurable algorithms for different drive types and thresholds
383
- **Template Method**: Standardized data processing pipelines with customizable steps
384
- **Singleton Pattern**: Database connection management and configuration loading
385
- **Command Pattern**: Script-based operations with standardized interfaces
386

            
387
#### Code Quality Standards
388
- **Perl Best Practices**: Strict warnings, proper scoping, and defensive programming
389
- **Database Normalization**: Proper relational design with referential integrity
390
- **Configuration Validation**: Input validation and sanitization throughout
391
- **Error Recovery**: Graceful degradation and automatic recovery mechanisms
392
- **Performance Monitoring**: Built-in performance metrics and optimization tracking
393
- **Security Practices**: SQL injection prevention, input validation, and secure configuration management
394

            
395
## 🏗️ Development Environment Setup
396

            
397
### Prerequisites
398

            
399
#### System Requirements
400
- **Operating System**: Linux/macOS (tested on macOS, deployed on Proxmox VE)
401
- **Perl**: Version 5.20+ with CPAN access
402
- **PostgreSQL**: Version 13+ with JSONB and extension support
403
- **Git**: For version control and collaboration
404

            
405
#### Development Database
406
```bash
407
# Current test database configuration
408
Host: 192.168.2.102
409
Database: autosmart
410
User: postgres
411
Password: (no password)
412
Port: 5432
413
```
414

            
415
#### Required Perl Modules
416
```bash
417
# Core database modules
418
cpan install DBI DBD::Pg
419

            
420
# JSON processing
421
cpan install JSON::XS
422

            
423
# System utilities
424
cpan install Config::Simple File::Slurp Time::HiRes
425

            
426
# Security and hashing
427
cpan install Digest::SHA
428

            
429
# HTTP/API clients (for OpenAI integration)
430
cpan install LWP::UserAgent HTTP::Request::Common
431

            
432
# Optional: Development and testing
433
cpan install Data::Dumper Test::More Test::Exception
434
```
435

            
436
### Development Workflow
437

            
438
#### 1. Environment Setup
439
```bash
440
# Clone the project
441
cd /Users/bogdan/Documents/workspace/
442
git clone <autoSMART-repo>
443
cd autoSMART
444

            
445
# Set environment variables
446
export AUTOSMART_DB_HOST=192.168.2.102
447
export AUTOSMART_DB_NAME=autosmart
448
export AUTOSMART_DB_USER=postgres
449
export AUTOSMART_DB_PASS=
450
export AUTOSMART_DB_PORT=5432
451

            
452
# Optional: OpenAI API key for AI features
453
export OPENAI_API_KEY=your-api-key-here
454
```
455

            
456
#### 2. Database Setup
457
```bash
458
# Initialize the database schema
459
psql -h 192.168.2.102 -U postgres -d autosmart -f sql/schema.sql
460

            
461
# Verify installation
462
psql -h 192.168.2.102 -U postgres -d autosmart -c "\\dt"
463
```
464

            
465
#### 3. Testing Environment
466
```bash
467
# Run the differential storage test suite
468
cd scripts/
469
perl test-differential-storage.pl
470

            
471
# Test database connectivity
472
perl -e "
473
use DBI;
474
my \$dsn = 'DBI:Pg:dbname=autosmart;host=192.168.2.102;port=5432';
475
my \$dbh = DBI->connect(\$dsn, 'postgres', '', {RaiseError => 1});
476
print \"Database connection successful!\\n\";
477
\$dbh->disconnect();
478
"
479
```
480

            
481
## 🧩 Architecture Overview
482

            
483
### System Components
484

            
485
```
486
autoSMART Architecture
487
┌─────────────────────────────────────────────────────────────┐
488
│                    Proxmox Cluster                          │
489
├─────────────────────┬─────────────────────┬─────────────────┤
490
│      Node 1         │       Node 2        │      Node 3     │
491
│                     │                     │                 │
492
│ ┌─── SmartCollector ┤ ┌─── SmartCollector ┤ ┌─── SmartCollector
493
│ │   - HDD Scanning  │ │   - HDD Scanning  │ │   - HDD Scanning
494
│ │   - SMART Reading │ │   - SMART Reading │ │   - SMART Reading
495
│ │   - Migration Det │ │   - Migration Det │ │   - Migration Det
496
│ └─── Data Storage   │ └─── Data Storage   │ └─── Data Storage
497
└─────────────────────┴─────────────────────┴─────────────────┘
498
                               │
499
                      ┌────────▼─────────┐
500
                      │   PostgreSQL DB   │
501
                      │                  │
502
                      │ • HDD Inventory  │
503
                      │ • SMART Readings │
504
                      │ • Migrations     │
505
                      │ • AI Predictions │
506
                      └────────┬─────────┘
507
                               │
508
                    ┌──────────▼───────────┐
509
                    │    SmartAnalyzer     │
510
                    │                      │
511
                    │ • OpenAI API         │
512
                    │ • Failure Prediction │
513
                    │ • Pattern Analysis   │
514
                    └──────────┬───────────┘
515
                               │
516
                    ┌──────────▼───────────┐
517
                    │    SmartReporter     │
518
                    │                      │
519
                    │ • Alert Generation   │
520
                    │ • Report Creation    │
521
                    │ • Dashboard Data     │
522
                    └──────────────────────┘
523
```
524

            
525
### Data Flow
526

            
527
1. **Collection Phase**:
528
   - SmartCollector scans HDDs on each node
529
   - Hardware identification (serial + model)
530
   - Migration detection if HDD moved
531
   - Differential storage decision
532
   - Store only changed/critical data
533

            
534
2. **Analysis Phase**:
535
   - SmartAnalyzer processes stored data
536
   - Historical pattern analysis
537
   - OpenAI API calls for predictions
538
   - Risk assessment and trending
539

            
540
3. **Reporting Phase**:
541
   - SmartReporter generates alerts
542
   - Dashboard data preparation
543
   - Health reports creation
544
   - Maintenance recommendations
545

            
546
## 🔧 Module Development
547

            
548
### SmartCollector.pm Development
549

            
550
#### Key Methods to Understand
551
```perl
552
# Hardware identification and migration detection
553
sub _detect_or_create_hdd($drive_info, $smart_data)
554

            
555
# Differential storage decision making
556
sub _should_store_reading($hdd_id, $smart_data)
557

            
558
# Optimized data storage
559
sub _insert_smart_reading_differential($hdd_id, $drive_info, $smart_data, $storage_info)
560
```
561

            
562
#### Adding New Features
563
1. **New SMART Parameters**:
564
   ```perl
565
   # Add parameter processing in collect_smart_data()
566
   if ($line =~ /New_Parameter.*\s+(\d+)/) {
567
       $smart_data->{parameters}{'New_Parameter'} = $1;
568
   }
569
   ```
570

            
571
2. **Custom Manufacturer Detection**:
572
   ```perl
573
   # Extend _detect_manufacturer() method
574
   sub _detect_manufacturer {
575
       my ($self, $model) = @_;
576
       return 'Custom_Manufacturer' if $model =~ /CUSTOM_PATTERN/;
577
       # ... existing logic
578
   }
579
   ```
580

            
581
### SmartAnalyzer.pm Development
582

            
583
#### AI Integration Patterns
584
```perl
585
# OpenAI API call structure
586
sub _call_openai_api {
587
    my ($self, $prompt, $smart_data) = @_;
588

            
589
    my $request = HTTP::Request->new(POST => 'https://api.openai.com/v1/chat/completions');
590
    $request->header('Authorization' => "Bearer $self->{openai_api_key}");
591
    $request->header('Content-Type' => 'application/json');
592

            
593
    my $payload = {
594
        model => "gpt-4",
595
        messages => [
596
            {
597
                role => "system",
598
                content => "You are an expert in HDD failure prediction..."
599
            },
600
            {
601
                role => "user",
602
                content => $prompt
603
            }
604
        ]
605
    };
606

            
607
    # ... handle response
608
}
609
```
610

            
611
## 🗃️ Database Development
612

            
613
### Schema Evolution
614

            
615
#### Adding New Tables
616
```sql
617
-- Always include migration scripts
618
CREATE TABLE new_feature (
619
    id SERIAL PRIMARY KEY,
620
    hdd_id INTEGER REFERENCES hdd_inventory(id),
621
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
622
);
623

            
624
-- Add indexes for performance
625
CREATE INDEX idx_new_feature_hdd_id ON new_feature(hdd_id);
626
```
627

            
628
#### Modifying Existing Tables
629
```sql
630
-- Use ALTER statements for compatibility
631
ALTER TABLE smart_readings ADD COLUMN new_field VARCHAR(100);
632
CREATE INDEX CONCURRENTLY idx_smart_readings_new_field ON smart_readings(new_field);
633
```
634

            
635
### Query Optimization
636

            
637
#### Efficient SMART Data Queries
638
```sql
639
-- Use the reconstructed view for complete data
640
SELECT * FROM smart_readings_reconstructed
641
WHERE hdd_id = $1
642
  AND timestamp > NOW() - INTERVAL '30 days'
643
ORDER BY timestamp DESC;
644

            
645
-- Use raw table for storage statistics
646
SELECT reading_type, COUNT(*)
647
FROM smart_readings
648
WHERE timestamp > NOW() - INTERVAL '7 days'
649
GROUP BY reading_type;
650
```
651

            
652
## 🧪 Testing Guidelines
653

            
654
### Unit Testing
655
```perl
656
# Example test structure
657
use Test::More tests => 5;
658
use lib '../lib';
659
use SmartCollector;
660

            
661
my $collector = SmartCollector->new({
662
    db_host => '192.168.2.102',
663
    db_name => 'autosmart_test',
664
    # ... test config
665
});
666

            
667
# Test hardware identification
668
my $hdd_id = $collector->_detect_or_create_hdd($drive_info, $smart_data);
669
ok($hdd_id > 0, "HDD identification successful");
670

            
671
# Test differential storage
672
my $storage_decision = $collector->_should_store_reading($hdd_id, $smart_data);
673
ok($storage_decision->{store}, "Storage decision made");
674
```
675

            
676
### Integration Testing
677
```bash
678
# Run the comprehensive test suite
679
cd scripts/
680
perl test-differential-storage.pl
681

            
682
# Test with real hardware (if available)
683
perl collect-smart-data.pl --test-mode --device /dev/sdb
684
```
685

            
686
### Performance Testing
687
```sql
688
-- Test query performance
689
EXPLAIN ANALYZE
690
SELECT * FROM smart_readings_reconstructed
691
WHERE hdd_id IN (1,2,3,4,5)
692
  AND timestamp > NOW() - INTERVAL '90 days';
693

            
694
-- Monitor storage efficiency
695
SELECT
696
    reading_type,
697
    COUNT(*) as readings,
698
    AVG(length(parameters_json::text)) as avg_size_bytes
699
FROM smart_readings
700
WHERE timestamp > NOW() - INTERVAL '24 hours'
701
GROUP BY reading_type;
702
```
703

            
704
## 🔍 Debugging and Troubleshooting
705

            
706
### Logging System
707
```perl
708
# Enable debug logging
709
$ENV{AUTOSMART_DEBUG} = 3;  # Maximum verbosity
710

            
711
# Log levels:
712
# 1 = Errors only
713
# 2 = Warnings and errors
714
# 3 = Info, warnings, errors
715
# 4 = Debug everything
716
```
717

            
718
### Common Issues
719

            
720
#### Database Connection Problems
721
```bash
722
# Test database connectivity
723
psql -h 192.168.2.102 -U postgres -d autosmart -c "SELECT version();"
724

            
725
# Check permissions
726
psql -h 192.168.2.102 -U postgres -d autosmart -c "\\dp smart_readings"
727
```
728

            
729
#### SMART Data Collection Issues
730
```bash
731
# Test smartctl access
732
sudo smartctl -a /dev/sda
733

            
734
# Check permissions
735
ls -la /dev/sd*
736
```
737

            
738
#### Migration Detection Problems
739
```sql
740
-- Check migration logs
741
SELECT * FROM hdd_migrations
742
ORDER BY detected_at DESC
743
LIMIT 10;
744

            
745
-- Verify HDD inventory
746
SELECT serial_number, model_name, current_device_path, current_node_id
747
FROM hdd_inventory
748
WHERE status = 'active';
749
```
750

            
751
## 📊 Performance Monitoring
752

            
753
### Database Performance
754
```sql
755
-- Monitor table sizes
756
SELECT schemaname, tablename,
757
       pg_size_pretty(pg_total_relation_size(schemaname||'.'||tablename)) as size
758
FROM pg_tables
759
WHERE schemaname = 'public'
760
ORDER BY pg_total_relation_size(schemaname||'.'||tablename) DESC;
761

            
762
-- Monitor query performance
763
SELECT query, mean_time, calls
764
FROM pg_stat_statements
765
WHERE query LIKE '%smart_readings%'
766
ORDER BY mean_time DESC;
767
```
768

            
769
### Application Performance
770
```perl
771
# Add timing to critical operations
772
use Time::HiRes qw(time);
773

            
774
my $start_time = time();
775
my $result = $self->collect_smart_data($device_path);
776
my $duration = time() - $start_time;
777

            
778
$self->_log("SMART collection took ${duration}s for $device_path", 3);
779
```
780

            
781
## 🚀 Deployment Guidelines
782

            
783
### Production Deployment
784
1. **Database Setup**:
785
   - Use dedicated PostgreSQL server
786
   - Configure proper backup strategy
787
   - Set up monitoring and alerting
788

            
789
2. **Security Configuration**:
790
   - Use dedicated database users with minimal privileges
791
   - Secure API keys and configuration files
792
   - Enable SSL connections for database
793

            
794
3. **Performance Tuning**:
795
   - Configure PostgreSQL for time-series workload
796
   - Set up proper indexing strategy
797
   - Monitor and optimize slow queries
798

            
799
### Proxmox Integration
800
```bash
801
# Install on cluster nodes
802
for node in pve01 pve02 pve03; do
803
    scp -r autoSMART/ root@$node:/etc/pve/
804
done
805

            
806
# Configure systemd services
807
systemctl enable autosmart-collector
808
systemctl start autosmart-collector
809
```
810

            
811
## 📚 Additional Resources
812

            
813
### Useful Commands
814
```bash
815
# Monitor system in real-time
816
watch -n 30 'psql -h 192.168.2.102 -U postgres -d autosmart -c "SELECT COUNT(*) FROM smart_readings WHERE timestamp > NOW() - INTERVAL '\''1 hour'\''"'
817

            
818
# Generate performance report
819
psql -h 192.168.2.102 -U postgres -d autosmart -f sql/performance-report.sql
820
```
821

            
822
### Development Tools
823
- **pgAdmin**: Database administration and query development
824
- **Perl::Critic**: Code quality analysis
825
- **Perl::Tidy**: Code formatting
826
- **Git**: Version control with feature branches
827

            
828
## 📝 Developer Changelog
829

            
830
This section contains detailed technical changes, internal API modifications, and development-specific information that is not relevant for end-users.
831

            
832
### [1.0.0] - 2025-08-15 - Development Details
833

            
834
#### 🏗️ Architecture Changes
835
- **Database Schema Evolution**: Complete redesign from simple SMART storage to differential storage architecture
836
- **Hardware Tracking Implementation**: Added `hdd_inventory` and `hdd_migrations` tables for hardware-based identification
837
- **Differential Storage Engine**: Implemented `should_store_smart_reading()` PostgreSQL function with configurable change detection
838
- **Migration Detection Algorithm**: Created automatic hardware migration detection using serial numbers and model matching
839

            
840
#### 🔧 Internal API Changes
841
- **SmartCollector.pm Refactor**:
842
  - Added hardware identification methods (`identify_hardware()`, `detect_migration()`)
843
  - Implemented differential storage integration (`should_store_reading()`)
844
  - Added storage efficiency monitoring
845
  - Breaking change: Constructor now requires database handle
846
- **Database Functions**:
847
  - Added `should_store_smart_reading(jsonb, text, text, interval, text[])` function
848
  - Added `smart_readings_reconstructed` view for seamless data access
849
  - Added migration tracking triggers
850
- **Configuration Schema**:
851
  - Split configuration into cluster-wide (`cluster.conf`) and node-specific (`autosmart.conf`)
852
  - Added differential storage parameters (`force_storage_interval`, `critical_parameters`)
853

            
854
#### 🧪 Testing Infrastructure
855
- **Differential Storage Test Suite**: Added comprehensive test coverage in `test-differential-storage.pl`
856
- **Migration Detection Tests**: Validated hardware tracking across different scenarios
857
- **Performance Benchmarks**: Established baseline performance metrics for storage efficiency
858
- **Database Integration Tests**: Added tests for PostgreSQL function behavior
859

            
860
#### 📊 Performance Optimizations
861
- **Storage Efficiency**: Achieved 60-80% database size reduction through differential storage
862
- **Query Optimization**: Added proper indexing for hardware tracking and temporal queries
863
- **Background Processing**: Implemented non-blocking collection and analysis workflows
864
- **Memory Management**: Optimized Perl module memory usage for long-running processes
865

            
866
#### 🔒 Security Enhancements
867
- **Configuration Security**: Separated sensitive configuration from shared cluster config
868
- **Database Security**: Implemented proper user permissions and access controls
869
- **API Key Management**: Secure storage and rotation procedures for OpenAI API keys
870
- **Audit Trail**: Complete logging of all system changes and data access
871

            
872
#### 🐛 Known Technical Issues
873
- **Large Dataset Performance**: Initial data collection on large clusters may require tuning
874
- **Migration Detection Edge Cases**: Rare scenarios with identical drives may need manual verification
875
- **PostgreSQL Version Compatibility**: Requires PostgreSQL 13+ for JSONB and advanced indexing features
876
- **Perl Module Dependencies**: Some CPAN modules may require system-level library installation
877

            
878
#### 🔮 Technical Roadmap
879
- **Phase 2**: Real-time streaming data collection with Apache Kafka
880
- **Phase 3**: Machine learning model training on historical data
881
- **Phase 4**: Integration with Proxmox VE API for automated responses
882
- **Phase 5**: Multi-tenant architecture for managed service providers
883

            
884
#### 💻 Development Environment Notes
885
- **Test Database**: Currently using `192.168.2.102` for development and testing
886
- **Perl Version**: Developed and tested on Perl 5.32+
887
- **PostgreSQL Extensions**: Requires `uuid-ossp` and `btree_gin` extensions
888
- **Development Workflow**: Feature branch development with PR reviews required
889

            
890
## 🔧 Technical Reference for Developers
891

            
892
### Database Schema Reference
893
- **Primary location**: `../sql/schema.sql`
894
- **Documentation**: [DIFFERENTIAL_STORAGE.md](DIFFERENTIAL_STORAGE.md), [MIGRATION_DETECTION.md](MIGRATION_DETECTION.md)
895
- **Sample queries**: `../sql/sample-queries.sql`
896
- **Migration scripts**: `../sql/migrations/`
897

            
898
### Perl Module Architecture
899
- **SmartCollector.pm**: Data collection and hardware tracking
900
  - Hardware manufacturer detection
901
  - Migration detection and logging
902
  - Differential storage integration
903
  - Storage efficiency monitoring
904
- **SmartAnalyzer.pm**: AI-powered analysis and predictions
905
- **SmartReporter.pm**: Report generation and alerting
906
- **Module documentation**: Inline POD documentation in each module
907

            
908
### Configuration Management
909
- **Cluster config**: `../config/cluster.conf` (shared across all nodes)
910
- **Node config**: `../config/defaults/autosmart` (node-specific settings)
911
- **OpenAI config**: `../config/openai.conf` (API configuration)
912
- **Configuration documentation**: [INSTALLATION.md](INSTALLATION.md)
913

            
914
### Scripts and Development Tools
915
- **Collection**: `../scripts/collect-smart-data.pl`
916
- **Analysis**: `../scripts/analyze-smart-data.pl`
917
- **Reporting**: `../scripts/generate-reports.pl`
918
- **Testing**: `../scripts/test-differential-storage.pl`
919
- **Deployment**: `../scripts/deploy.sh`, `../scripts/deploy-production.sh`
920

            
921
### Development Scenarios
922

            
923
#### Scenario 1: Adding New SMART Parameters
924
**Files to modify**:
925
1. `lib/SmartCollector.pm` - Add parameter collection logic
926
2. `sql/schema.sql` - Update parameter definitions if needed
927
3. `scripts/test-differential-storage.pl` - Add parameter tests
928
4. `docs/DIFFERENTIAL_STORAGE.md` - Document parameter behavior
929

            
930
#### Scenario 2: Implementing New AI Prediction Models
931
**Files to modify**:
932
1. `lib/SmartAnalyzer.pm` - Add new prediction algorithms
933
2. `docs/API.md` - Update API integration patterns
934
3. `scripts/analyze-smart-data.pl` - Add model selection logic
935
4. `sql/schema.sql` - Add prediction result tables if needed
936

            
937
#### Scenario 3: Performance Optimization
938
**Areas to investigate**:
939
1. `docs/DIFFERENTIAL_STORAGE.md` - Storage optimization techniques
940
2. `sql/schema.sql` - Index optimization
941
3. `lib/SmartCollector.pm` - Collection efficiency
942
4. PostgreSQL query performance using `EXPLAIN ANALYZE`
943

            
944
#### Scenario 4: Adding New Hardware Support
945
**Files to modify**:
946
1. `lib/SmartCollector.pm` - Hardware detection logic
947
2. `docs/MIGRATION_DETECTION.md` - Hardware tracking specifications
948
3. `scripts/test-differential-storage.pl` - Hardware-specific tests
949
4. Configuration templates for new hardware types
950

            
951
### Code Quality Guidelines
952

            
953
#### Perl Coding Standards
954
```perl
955
# Use strict and warnings
956
use strict;
957
use warnings;
958

            
959
# Consistent indentation (4 spaces)
960
sub example_function {
961
    my ($self, $param) = @_;
962

            
963
    # Clear variable names
964
    my $smart_data = $self->collect_smart_data($param);
965

            
966
    # Error handling
967
    return unless defined $smart_data;
968

            
969
    return $smart_data;
970
}
971
```
972

            
973
#### Database Development Patterns
974
```sql
975
-- Use transactions for data consistency
976
BEGIN;
977
    -- Multiple related operations
978
    INSERT INTO hdd_inventory (...) VALUES (...);
979
    INSERT INTO smart_readings (...) VALUES (...);
980
COMMIT;
981

            
982
-- Use proper indexing
983
CREATE INDEX CONCURRENTLY idx_smart_readings_timestamp
984
ON smart_readings(timestamp DESC, serial_number);
985

            
986
-- Use parameterized queries to prevent SQL injection
987
my $sth = $dbh->prepare("SELECT * FROM smart_readings WHERE serial_number = ?");
988
$sth->execute($serial_number);
989
```
990

            
991
This development guide provides the foundation for extending and maintaining the autoSMART system. Follow these guidelines to ensure code quality, performance, and reliability.