-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathTrueNASPlugin.pm
More file actions
4952 lines (4313 loc) · 192 KB
/
TrueNASPlugin.pm
File metadata and controls
4952 lines (4313 loc) · 192 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
package PVE::Storage::Custom::TrueNASPlugin;
use v5.36;
use strict;
use warnings;
# Plugin Version
our $VERSION = '1.2.6';
use JSON::PP qw(encode_json decode_json);
use URI::Escape qw(uri_escape);
use MIME::Base64 qw(encode_base64);
use Digest::SHA qw(sha1);
use IO::Socket::INET;
use IO::Socket::SSL;
use Time::HiRes qw(usleep);
use POSIX ();
use Socket qw(inet_ntoa);
use LWP::UserAgent;
use HTTP::Request;
use Cwd qw(abs_path);
use Sys::Syslog qw(openlog syslog);
use Carp qw(carp croak);
use PVE::Tools qw(run_command trim);
use PVE::Storage::Plugin;
use PVE::JSONSchema qw(get_standard_option);
use base qw(PVE::Storage::Plugin);
# Initialize syslog at compile time
BEGIN {
openlog('truenasplugin', 'pid', 'daemon');
}
# Null destructor package for fork-safe socket handling
# When a process forks, inherited sockets must not run their DESTROY methods
# as this corrupts the parent's SSL state. Reblessing into this class makes
# DESTROY a no-op, preventing segfaults during child process exit.
package PVE::Storage::Custom::TrueNASPlugin::NullDestructor;
sub DESTROY { } # Intentionally empty - prevents any cleanup
package PVE::Storage::Custom::TrueNASPlugin;
# Simple cache for API results (static data)
my %API_CACHE = ();
my $CACHE_TTL = 60; # 60 seconds
# Utility function to normalize TrueNAS API values
# Handles both scalar values and hash structures with parsed/raw fields
# Used throughout the plugin for consistent value extraction
sub _normalize_value {
my ($v) = @_;
return 0 if !defined $v;
return $v if !ref($v);
return $v->{parsed} // $v->{raw} // 0 if ref($v) eq 'HASH';
return 0;
}
# Performance and timing constants
# These values are tuned for modern systems and network conditions
use constant {
# Device settling timeouts (microseconds)
UDEV_SETTLE_TIMEOUT_US => 250_000, # udev settle grace period (250ms)
DEVICE_READY_TIMEOUT_US => 100_000, # device availability check (100ms)
DEVICE_RESCAN_DELAY_US => 150_000, # device rescan stabilization (150ms)
# Operation delays (seconds)
DEVICE_SETTLE_DELAY_S => 1, # post-connection/logout stabilization
JOB_POLL_DELAY_S => 1, # job status polling interval
# Job timeouts (seconds)
SNAPSHOT_DELETE_TIMEOUT_S => 15, # snapshot deletion job timeout
DATASET_DELETE_TIMEOUT_S => 30, # dataset deletion job timeout (increased for reliability)
DEVICE_CLEANUP_VERIFY_TIMEOUT_S => 5, # device cleanup verification timeout
DATASET_DELETE_RETRY_COUNT => 3, # max retries for dataset deletion on "busy" errors
};
sub _cache_key {
my ($storage_id, $method) = @_;
return "${storage_id}:${method}";
}
sub _get_cached {
my ($storage_id, $method) = @_;
my $key = _cache_key($storage_id, $method);
my $entry = $API_CACHE{$key};
return unless $entry;
# Check if cache entry is still valid
return unless (time() - $entry->{timestamp}) < $CACHE_TTL;
return $entry->{data};
}
sub _set_cache {
my ($storage_id, $method, $data) = @_;
my $key = _cache_key($storage_id, $method);
$API_CACHE{$key} = {
data => $data,
timestamp => time()
};
return $data;
}
sub _clear_cache {
my ($storage_id) = @_;
if ($storage_id) {
# Clear cache for specific storage
delete $API_CACHE{$_} for grep { /^\Q$storage_id\E:/ } keys %API_CACHE;
} else {
# Clear all cache
%API_CACHE = ();
}
}
# ======== Helper functions ========
sub _format_bytes {
my ($bytes) = @_;
return '0 B' if !defined $bytes || $bytes == 0;
my @units = qw(B KB MB GB TB PB);
my $unit_idx = 0;
my $size = $bytes;
while ($size >= 1024 && $unit_idx < $#units) {
$size /= 1024;
$unit_idx++;
}
return sprintf("%.2f %s", $size, $units[$unit_idx]);
}
# Parse ZFS blocksize string (e.g., "128K", "64K", "1M") to bytes
# Returns integer bytes, or 0 if invalid/undefined
sub _parse_blocksize {
my ($bs_str) = @_;
return 0 if !defined $bs_str || $bs_str eq '';
# Match: number followed by optional K/M/G suffix (case-insensitive)
if ($bs_str =~ /^(\d+)([KMG])?$/i) {
my ($num, $unit) = ($1, $2 // '');
my $bytes = int($num);
$bytes *= 1024 if uc($unit) eq 'K';
$bytes *= 1024 * 1024 if uc($unit) eq 'M';
$bytes *= 1024 * 1024 * 1024 if uc($unit) eq 'G';
return $bytes;
}
return 0; # Invalid format
}
# Debug logging helper - respects debug level from storage config
# Usage: _log($scfg, $level, $priority, $message)
# $level: 0=always, 1=light debug, 2=verbose debug
# $priority: syslog priority ('err', 'warning', 'info', 'debug')
sub _log {
my ($scfg, $level, $priority, $message) = @_;
# Level 0 messages (errors) are always logged
return syslog($priority, $message) if $level == 0;
# For level 1+, check debug configuration
my $debug_level = $scfg->{debug} // 0;
return if $level > $debug_level;
syslog($priority, $message);
}
# Normalize blocksize to uppercase format required by TrueNAS 25.10+
# Converts: 16k -> 16K, 128k -> 128K, etc.
# TrueNAS 25.10 requires: '512', '512B', '1K', '2K', '4K', '8K', '16K', '32K', '64K', '128K'
sub _normalize_blocksize {
my ($blocksize) = @_;
return undef if !defined $blocksize;
# Convert to uppercase (16k -> 16K, 64k -> 64K, etc.)
$blocksize = uc($blocksize);
return $blocksize;
}
# ======== Retry logic with exponential backoff ========
sub _is_retryable_error {
my ($error) = @_;
return 0 if !defined $error;
# Retry on network errors, timeouts, connection issues
return 1 if $error =~ /timeout|timed out/i;
return 1 if $error =~ /connection refused|connection reset|broken pipe/i;
return 1 if $error =~ /network is unreachable|host is unreachable/i;
return 1 if $error =~ /temporary failure|service unavailable/i;
return 1 if $error =~ /502 Bad Gateway|503 Service Unavailable|504 Gateway Timeout/i;
return 1 if $error =~ /rate limit/i;
return 1 if $error =~ /ssl.*error/i; # Transient SSL errors
return 1 if $error =~ /connection.*failed/i;
# Do NOT retry on authentication errors, not found, or validation errors
return 0 if $error =~ /401 Unauthorized|403 Forbidden|404 Not Found/i;
return 0 if $error =~ /ENOENT|InstanceNotFound|does not exist/i;
return 0 if $error =~ /invalid.*key|authentication.*failed/i;
return 0 if $error =~ /validation.*error|invalid.*parameter/i;
return 0 if $error =~ /EINVAL|Invalid params/i;
return 0; # Default: don't retry unknown errors
}
sub _retry_with_backoff {
my ($scfg, $operation_name, $code_ref) = @_;
my $max_retries = $scfg->{api_retry_max} // 3;
my $initial_delay = $scfg->{api_retry_delay} // 1;
my $attempt = 0;
my $last_error;
my $result;
while ($attempt <= $max_retries) {
$result = eval {
return $code_ref->();
};
$last_error = $@;
# Success - no error, return the result
return $result if !$last_error;
$attempt++;
# Check if error is retryable
if (!_is_retryable_error($last_error)) {
_log($scfg, 2, 'debug', "[TrueNAS] Non-retryable error for $operation_name: $last_error");
die $last_error; # Not retryable, fail immediately
}
# Max retries exhausted
if ($attempt > $max_retries) {
_log($scfg, 0, 'err', "[TrueNAS] Max retries ($max_retries) exhausted for $operation_name: $last_error");
die "Operation failed after $max_retries retries: $last_error";
}
# Calculate delay with exponential backoff
my $delay = $initial_delay * (2 ** ($attempt - 1));
# Add jitter (0-20% random variation) to prevent thundering herd
my $jitter = $delay * 0.2 * rand();
$delay += $jitter;
_log($scfg, 1, 'info', "[TrueNAS] Retry attempt $attempt/$max_retries for $operation_name after ${delay}s delay (error: $last_error)");
sleep($delay);
}
# Should never reach here, but just in case
die $last_error;
}
# ======== Storage plugin identity ========
# Storage API version - dynamically adapts to PVE version
# Supports PVE 8.x (APIVER 11) and PVE 9.x (APIVER 13)
sub api {
my $tested_apiver = 13; # Latest tested version (PVE 9.x)
# Get current system API version (safely, as PVE::Storage may not be loaded yet)
my $system_apiver = eval { require PVE::Storage; PVE::Storage::APIVER() } // 11;
my $system_apiage = eval { PVE::Storage::APIAGE() } // 2;
# If system API is within our tested range, return system version
# This ensures we never claim a higher version than the system supports
if ($system_apiver >= 11 && $system_apiver <= $tested_apiver) {
return $system_apiver;
}
# If we're within APIAGE of tested version, return tested version
if ($system_apiver - $system_apiage < $tested_apiver) {
return $tested_apiver;
}
# Fallback for very old systems (shouldn't happen with PVE 7+)
return 11;
}
sub type { return 'truenasplugin'; } # storage.cfg "type"
sub plugindata {
return {
content => [ { images => 1 }, { images => 1 } ],
format => [ { raw => 1 }, 'raw' ],
};
}
# ======== Config schema (only plugin-specific keys) ========
sub properties {
return {
# Transport & connection
api_transport => {
description => "API transport: 'ws' (JSON-RPC) or 'rest'.",
type => 'string', optional => 1,
},
api_host => {
description => "TrueNAS hostname or IP.",
type => 'string', format => 'pve-storage-server',
},
api_key => {
description => "TrueNAS user-linked API key.",
type => 'string',
},
api_scheme => {
description => "wss/ws for WS, https/http for REST (defaults: wss/https).",
type => 'string', optional => 1,
},
api_port => {
description => "TCP port (defaults: 443 for wss/https, 80 for ws/http).",
type => 'integer', optional => 1,
},
api_insecure => {
description => "Skip TLS certificate verification.",
type => 'boolean', optional => 1, default => 0,
},
prefer_ipv4 => {
description => "Prefer IPv4 (A records) when resolving api_host.",
type => 'boolean', optional => 1, default => 1,
},
# Placement
dataset => {
description => "Parent dataset for zvols (e.g. tank/proxmox).",
type => 'string',
},
zvol_blocksize => {
description => "ZVOL volblocksize (e.g. 16K, 64K).",
type => 'string', optional => 1,
},
# Transport mode selection
transport_mode => {
description => "Storage transport protocol: 'iscsi' or 'nvme-tcp'.",
type => 'string',
enum => ['iscsi', 'nvme-tcp'],
optional => 1,
default => 'iscsi',
},
# iSCSI target & portals
target_iqn => {
description => "Shared iSCSI Target IQN on TrueNAS (or target's short name) - required for iSCSI transport.",
type => 'string',
optional => 1,
},
discovery_portal => {
description => "Primary SendTargets portal (IP[:port] or [IPv6]:port).",
type => 'string',
},
portals => {
description => "Comma-separated additional portals.",
type => 'string', optional => 1,
},
# Initiator pathing
use_multipath => { type => 'boolean', optional => 1, default => 1 },
force_delete_on_inuse => {
description => 'Temporarily logout the target on this node to force delete when TrueNAS reports "target is in use".',
type => 'boolean',
default => 'false',
},
logout_on_free => {
description => 'After delete, logout the target if no LUNs remain for this node.',
type => 'boolean',
default => 'false',
},
use_by_path => { type => 'boolean', optional => 1, default => 0 },
ipv6_by_path => {
description => "Normalize IPv6 by-path names (enable only if using IPv6 portals).",
type => 'boolean', optional => 1, default => 0,
},
# Debug level
debug => {
description => "Debug level: 0=none (errors only), 1=light (function calls), 2=verbose (full trace)",
type => 'integer', optional => 1, default => 0, minimum => 0, maximum => 2,
},
# CHAP (optional - iSCSI only)
chap_user => { type => 'string', optional => 1 },
chap_password => { type => 'string', optional => 1 },
# NVMe/TCP parameters
subsystem_nqn => {
description => "NVMe subsystem NQN - required for nvme-tcp transport.",
type => 'string',
optional => 1,
},
hostnqn => {
description => "NVMe host NQN (optional, auto-generated from /etc/nvme/hostnqn if not specified).",
type => 'string',
optional => 1,
},
nvme_dhchap_secret => {
description => "DH-HMAC-CHAP host authentication key (format: DHHC-1:01:...) - optional.",
type => 'string',
optional => 1,
},
nvme_dhchap_ctrl_secret => {
description => "DH-HMAC-CHAP controller authentication key for bidirectional auth - optional.",
type => 'string',
optional => 1,
},
# Thin provisioning toggle (maps to TrueNAS sparse)
tn_sparse => {
description => "Create thin-provisioned zvols on TrueNAS (maps to 'sparse').",
type => 'boolean', optional => 1, default => 1,
},
# Live snapshot support
enable_live_snapshots => {
description => "Enable live snapshots with VM state storage on TrueNAS.",
type => 'boolean', optional => 1, default => 1,
},
# Volume chains for snapshots (enables vmstate support)
snapshot_volume_chains => {
description => "Use volume chains for snapshots (enables vmstate on iSCSI).",
type => 'boolean', optional => 1, default => 1,
},
# vmstate storage location
vmstate_storage => {
description => "Storage location for vmstate: 'shared' (TrueNAS iSCSI) or 'local' (node filesystem).",
type => 'string', optional => 1, default => 'local',
},
# Bulk operations for improved performance
enable_bulk_operations => {
description => "Enable bulk API operations for better performance (requires WebSocket transport).",
type => 'boolean', optional => 1, default => 1,
},
# Retry configuration
api_retry_max => {
description => "Maximum number of API call retries on transient failures.",
type => 'integer', optional => 1, default => 3,
},
api_retry_delay => {
description => "Initial retry delay in seconds (doubles with each retry).",
type => 'number', optional => 1, default => 1,
},
storage_lock_timeout => {
description => "Cluster lock timeout in seconds for storage operations. " .
"Increase for parallel bulk provisioning. Default: 120.",
type => 'integer', optional => 1, default => 120, minimum => 10, maximum => 600,
},
};
}
sub options {
return {
# Base storage options (do NOT add to properties)
disable => { optional => 1 },
nodes => { optional => 1 },
content => { optional => 1 },
shared => { optional => 1 },
# Connection (fixed to avoid orphaning volumes)
api_transport => { optional => 1, fixed => 1 },
api_host => { fixed => 1 },
api_key => { fixed => 1 },
api_scheme => { optional => 1, fixed => 1 },
api_port => { optional => 1, fixed => 1 },
api_insecure => { optional => 1, fixed => 1 },
prefer_ipv4 => { optional => 1 },
# Placement
dataset => { fixed => 1 },
zvol_blocksize => { optional => 1, fixed => 1 },
# Transport mode
transport_mode => { optional => 1, fixed => 1 },
# iSCSI target & portals
target_iqn => { optional => 1, fixed => 1 },
discovery_portal => { optional => 1, fixed => 1 },
portals => { optional => 1 },
force_delete_on_inuse => { optional => 1 },
logout_on_free => { optional => 1 },
# Initiator
use_multipath => { optional => 1 },
use_by_path => { optional => 1 },
ipv6_by_path => { optional => 1 },
# CHAP (iSCSI)
chap_user => { optional => 1 },
chap_password => { optional => 1 },
# NVMe/TCP parameters
subsystem_nqn => { optional => 1, fixed => 1 },
hostnqn => { optional => 1 },
nvme_dhchap_secret => { optional => 1 },
nvme_dhchap_ctrl_secret => { optional => 1 },
# Thin toggle
tn_sparse => { optional => 1 },
# Debug
debug => { optional => 1 },
# Live snapshots
enable_live_snapshots => { optional => 1 },
snapshot_volume_chains => { optional => 1 },
vmstate_storage => { optional => 1 },
# Bulk operations
enable_bulk_operations => { optional => 1 },
# Retry configuration
api_retry_max => { optional => 1 },
api_retry_delay => { optional => 1 },
# Concurrency
storage_lock_timeout => { optional => 1 },
};
}
# Force shared storage behavior for cluster migration support
sub check_config {
my ($class, $sectionId, $config, $create, $skipSchemaCheck) = @_;
my $opts = $class->SUPER::check_config($sectionId, $config, $create, $skipSchemaCheck);
# Always set shared=1 since this is block-based shared storage (iSCSI or NVMe/TCP)
$opts->{shared} = 1;
# Validate retry configuration parameters
if (defined $opts->{api_retry_max}) {
die "api_retry_max must be between 0 and 10 (got $opts->{api_retry_max})\n"
if $opts->{api_retry_max} < 0 || $opts->{api_retry_max} > 10;
}
if (defined $opts->{api_retry_delay}) {
die "api_retry_delay must be between 0.1 and 60 seconds (got $opts->{api_retry_delay})\n"
if $opts->{api_retry_delay} < 0.1 || $opts->{api_retry_delay} > 60;
}
# Validate dataset name follows ZFS naming conventions
if ($opts->{dataset}) {
# ZFS datasets: alphanumeric, underscore, hyphen, period, slash (for hierarchy)
if ($opts->{dataset} =~ /[^a-zA-Z0-9_\-\.\/]/) {
die "dataset name contains invalid characters: '$opts->{dataset}'\n" .
" Allowed characters: a-z A-Z 0-9 _ - . /\n";
}
# Must not start or end with slash
if ($opts->{dataset} =~ /^\/|\/$/) {
die "dataset name must not start or end with '/': '$opts->{dataset}'\n";
}
# Must not contain double slashes
if ($opts->{dataset} =~ /\/\//) {
die "dataset name must not contain '//': '$opts->{dataset}'\n";
}
# Must not be empty after trimming
if ($opts->{dataset} eq '') {
die "dataset name cannot be empty\n";
}
}
# Warn if using insecure transport (HTTP/WS instead of HTTPS/WSS)
if (defined $opts->{api_transport}) {
my $transport = lc($opts->{api_transport});
if ($transport eq 'rest' && defined $opts->{api_scheme}) {
my $scheme = lc($opts->{api_scheme});
if ($scheme eq 'http') {
syslog('warning',
"[TrueNAS] Storage '$sectionId' is using insecure HTTP transport. " .
"Consider using HTTPS for API communication."
);
}
} elsif ($transport eq 'ws') {
# WebSocket uses wss:// or ws:// - check if scheme is insecure
if (defined $opts->{api_scheme} && lc($opts->{api_scheme}) eq 'ws') {
syslog('warning',
"[TrueNAS] Storage '$sectionId' is using insecure WebSocket (ws://). " .
"Consider using secure WebSocket (wss://) for API communication."
);
}
}
}
# Validate required fields are present
if (!$opts->{api_host}) {
die "api_host is required\n";
}
if (!$opts->{api_key}) {
die "api_key is required\n";
}
if (!$opts->{dataset}) {
die "dataset is required\n";
}
# Validate transport mode and transport-specific parameters
my $mode = $opts->{transport_mode} // 'iscsi';
if ($mode eq 'iscsi') {
# iSCSI mode requires target_iqn and discovery_portal
if (!$opts->{target_iqn}) {
die "target_iqn is required for iSCSI transport\n";
}
if (!$opts->{discovery_portal}) {
die "discovery_portal is required for iSCSI transport\n";
}
# Warn if NVMe-specific parameters are set in iSCSI mode
if ($opts->{subsystem_nqn}) {
syslog('warning',
"[TrueNAS] Storage '$sectionId': subsystem_nqn is ignored in iSCSI mode"
);
}
if ($opts->{hostnqn}) {
syslog('warning',
"[TrueNAS] Storage '$sectionId': hostnqn is ignored in iSCSI mode"
);
}
} elsif ($mode eq 'nvme-tcp') {
# NVMe/TCP mode requires subsystem_nqn
if (!$opts->{subsystem_nqn}) {
die "subsystem_nqn is required for nvme-tcp transport\n";
}
# Validate NQN format (basic check)
if ($opts->{subsystem_nqn} !~ /^nqn\.\d{4}-\d{2}\./) {
die "subsystem_nqn must follow NVMe NQN format (e.g., nqn.2005-10.org.example:identifier)\n";
}
# Validate hostnqn format if provided
if ($opts->{hostnqn} && $opts->{hostnqn} !~ /^nqn\./) {
die "hostnqn must follow NVMe NQN format\n";
}
# Warn if iSCSI-specific parameters are set in NVMe mode
if ($opts->{target_iqn}) {
syslog('warning',
"[TrueNAS] Storage '$sectionId': target_iqn is ignored in nvme-tcp mode"
);
}
if ($opts->{chap_user} || $opts->{chap_password}) {
syslog('warning',
"[TrueNAS] Storage '$sectionId': CHAP parameters are ignored in nvme-tcp mode (use nvme_dhchap_secret instead)"
);
}
if ($opts->{use_by_path}) {
syslog('warning',
"[TrueNAS] Storage '$sectionId': use_by_path is ignored in nvme-tcp mode (UUID paths used)"
);
}
} else {
die "Invalid transport_mode '$mode': must be 'iscsi' or 'nvme-tcp'\n";
}
return $opts;
}
# ======== DNS/IPv4 helper ========
sub _host_ipv4($host) {
return $host if $host =~ /^\d+\.\d+\.\d+\.\d+$/; # already IPv4 literal
my @ent = Socket::gethostbyname($host); # A-record lookup
if (@ent && defined $ent[4]) {
my $ip = inet_ntoa($ent[4]);
return $ip if $ip;
}
return $host; # fallback (could be IPv6 literal or DNS)
}
# ======== REST client (fallback) ========
sub _ua($scfg) {
my $ua = LWP::UserAgent->new(
timeout => 30,
keep_alive=> 1,
ssl_opts => {
verify_hostname => !$scfg->{api_insecure},
SSL_verify_mode => $scfg->{api_insecure} ? 0x00 : 0x02,
}
);
return $ua;
}
sub _rest_base($scfg) {
my $scheme = ($scfg->{api_scheme} && $scfg->{api_scheme} =~ /^http$/i) ? 'http' : 'https';
my $port = $scfg->{api_port} // ($scheme eq 'https' ? 443 : 80);
return "$scheme://$scfg->{api_host}:$port/api/v2.0";
}
sub _rest_call($scfg, $method, $path, $payload=undef) {
return _retry_with_backoff($scfg, "REST $method $path", sub {
my $ua = _ua($scfg);
my $url = _rest_base($scfg) . $path;
my $req = HTTP::Request->new(uc($method) => $url);
$req->header('Authorization' => "Bearer $scfg->{api_key}");
$req->header('Content-Type' => 'application/json');
$req->content(encode_json($payload)) if defined $payload;
my $res = $ua->request($req);
die "TrueNAS REST $method $path failed: ".$res->status_line."\nBody: ".$res->decoded_content."\n"
if !$res->is_success;
my $content = $res->decoded_content // '';
return undef unless length($content);
my $decoded = eval { decode_json($content) };
if ($@ || !$decoded) {
my $len = length($content);
my $preview = substr($content, 0, 200);
_log(undef, 0, 'err', "[TrueNAS] REST JSON decode failed (len=$len): $@ Preview: $preview");
die "REST response decode failed: $@";
}
return $decoded;
});
}
# ======== WebSocket JSON-RPC client ========
# Connect to ws(s)://<host>/api/current; auth via auth.login_with_api_key.
sub _ws_defaults($scfg) {
my $scheme = $scfg->{api_scheme};
if (!$scheme) { $scheme = 'wss'; }
elsif ($scheme =~ /^https$/i) { $scheme = 'wss'; }
elsif ($scheme =~ /^http$/i) { $scheme = 'ws'; }
my $port = $scfg->{api_port} // (($scheme eq 'wss') ? 443 : 80);
return ($scheme, $port);
}
sub _ws_open($scfg) {
my ($scheme, $port) = _ws_defaults($scfg);
my $host = $scfg->{api_host};
my $peer = ($scfg->{prefer_ipv4} // 1) ? _host_ipv4($host) : $host;
my $path = '/api/current';
# Add small delay to avoid rate limiting
usleep(DEVICE_READY_TIMEOUT_US); # 100ms delay
my $sock;
if ($scheme eq 'wss') {
$sock = IO::Socket::SSL->new(
PeerHost => $peer,
PeerPort => $port,
SSL_verify_mode => $scfg->{api_insecure} ? 0x00 : 0x02,
SSL_hostname => $host,
Timeout => 15,
) or die "wss connect failed: $SSL_ERROR\n";
} else {
$sock = IO::Socket::INET->new(
PeerHost => $peer, PeerPort => $port, Proto => 'tcp', Timeout => 15,
) or die "ws connect failed: $!\n";
}
# WebSocket handshake
my $key_raw = join '', map { chr(int(rand(256))) } 1..16;
my $key_b64 = encode_base64($key_raw, '');
my $hosthdr = $host.":".$port;
my $req =
"GET $path HTTP/1.1\r\n".
"Host: $hosthdr\r\n".
"Upgrade: websocket\r\n".
"Connection: Upgrade\r\n".
"Sec-WebSocket-Key: $key_b64\r\n".
"Sec-WebSocket-Version: 13\r\n".
"\r\n";
print $sock $req;
my $resp = '';
while ($sock->sysread(my $buf, 1024)) {
$resp .= $buf;
last if $resp =~ /\r\n\r\n/s;
}
die "WebSocket handshake failed (no 101)" if $resp !~ m#^HTTP/1\.([01]) 101#;
my ($accept) = $resp =~ /Sec-WebSocket-Accept:\s*(\S+)/i;
my $expect = encode_base64(sha1($key_b64 . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'), '');
die "WebSocket handshake invalid accept key" if ($accept // '') ne $expect;
# Authenticate with API key (JSON-RPC)
my $conn = { sock => $sock, next_id => 1 };
_ws_rpc($conn, {
jsonrpc => "2.0", id => $conn->{next_id}++,
method => "auth.login_with_api_key",
params => [ $scfg->{api_key} ],
}) or die "TrueNAS auth.login_with_api_key failed";
return $conn;
}
# ---- WS framing helpers (text only) ----
sub _xor_mask {
my ($data, $mask) = @_;
my $len = length($data);
my $out = $data;
my $m0 = ord(substr($mask,0,1));
my $m1 = ord(substr($mask,1,1));
my $m2 = ord(substr($mask,2,1));
my $m3 = ord(substr($mask,3,1));
for (my $i=0; $i<$len; $i++) {
my $mi = ($i & 3) == 0 ? $m0 : ($i & 3) == 1 ? $m1 : ($i & 3) == 2 ? $m2 : $m3;
substr($out, $i, 1, chr( ord(substr($out, $i, 1)) ^ $mi ));
}
return $out;
}
sub _ws_send_text {
my ($sock, $payload) = @_;
my $fin_opcode = 0x81; # FIN + text
my $maskbit = 0x80; # client must mask
my $len = length($payload);
my $hdr = pack('C', $fin_opcode);
my $lenfield;
if ($len <= 125) { $lenfield = pack('C', $maskbit | $len); }
elsif ($len <= 0xFFFF) { $lenfield = pack('C n', $maskbit | 126, $len); }
else { $lenfield = pack('C Q>',$maskbit | 127, $len); }
my $mask = join '', map { chr(int(rand(256))) } 1..4;
my $masked = _xor_mask($payload, $mask);
my $frame = $hdr . $lenfield . $mask . $masked;
my $off = 0;
while ($off < length($frame)) {
my $w = $sock->syswrite($frame, length($frame) - $off, $off);
die "WS write failed: $!" unless defined $w;
$off += $w;
}
}
sub _ws_read_exact {
my ($sock, $ref, $want) = @_;
$$ref = '' if !defined $$ref;
my $got = 0;
while ($got < $want) {
my $r = $sock->sysread($$ref, $want - $got, $got);
return undef if !defined $r || $r == 0;
$got += $r;
}
return 1;
}
sub _ws_recv_text {
my $sock = shift;
my $message = ''; # Accumulator for fragmented messages
while (1) {
my $hdr;
_ws_read_exact($sock, \$hdr, 2) or die "WS read hdr failed";
my ($b1, $b2) = unpack('CC', $hdr);
my $fin = ($b1 & 0x80) ? 1 : 0; # FIN bit
my $opcode = $b1 & 0x0f;
my $masked = ($b2 & 0x80) ? 1 : 0; # server MUST NOT mask
my $len = ($b2 & 0x7f);
if ($len == 126) {
my $ext; _ws_read_exact($sock, \$ext, 2) or die "WS len16 read fail";
$len = unpack('n', $ext);
} elsif ($len == 127) {
my $ext; _ws_read_exact($sock, \$ext, 8) or die "WS len64 read fail";
$len = unpack('Q>', $ext);
}
my $mask_key = '';
if ($masked) { _ws_read_exact($sock, \$mask_key, 4) or die "WS unexpected mask"; }
my $payload = '';
if ($len > 0) {
_ws_read_exact($sock, \$payload, $len) or die "WS payload read fail";
if ($masked) { $payload = _xor_mask($payload, $mask_key); }
}
# Handle different frame types
if ($opcode == 0x01) {
# Text frame (start of message or unfragmented message)
$message = $payload;
return $message if $fin; # Complete unfragmented message
# Otherwise, continue reading continuation frames
} elsif ($opcode == 0x00) {
# Continuation frame
$message .= $payload;
return $message if $fin; # Complete fragmented message
} elsif ($opcode == 0x08) {
# Close frame
my $code = $len >= 2 ? unpack('n', substr($payload, 0, 2)) : 0;
my $reason = $len > 2 ? substr($payload, 2) : '';
die "WS closed by server (code: $code, reason: $reason)";
} elsif ($opcode == 0x09) {
# Ping frame - respond with pong
my $pong_hdr = pack('C', 0x8A); # FIN=1, opcode=0xA
my $pong_len;
if ($len <= 125) { $pong_len = pack('C', $len); }
elsif ($len <= 0xFFFF) { $pong_len = pack('C n', 126, $len); }
else { $pong_len = pack('C Q>', 127, $len); }
$sock->syswrite($pong_hdr . $pong_len . $payload);
# Continue reading next frame
} elsif ($opcode == 0x0A) {
# Pong frame - ignore and continue
} else {
die "WS: unexpected opcode $opcode";
}
}
}
sub _ws_rpc {
my ($conn, $obj) = @_;
my $text = encode_json($obj);
_ws_send_text($conn->{sock}, $text);
my $resp = _ws_recv_text($conn->{sock});
my $decoded = eval { decode_json($resp) };
if ($@ || !$decoded) {
my $len = length($resp // '');
my $preview = substr($resp // '', 0, 200);
_log(undef, 0, 'err', "[TrueNAS] JSON decode failed (len=$len): $@ Preview: $preview");
die "JSON-RPC decode failed: $@";
}
die "JSON-RPC error: ".encode_json($decoded->{error}) if exists $decoded->{error};
return $decoded->{result};
}
# ======== Persistent WebSocket Connection Management ========
my %_ws_connections; # Global connection cache
my $_ws_creator_pid = $$; # Track PID to detect fork
sub _ws_connection_key($scfg) {
# Create a unique key for this storage configuration
my $host = $scfg->{api_host};
my $key = $scfg->{api_key};
my $transport = $scfg->{api_transport} // 'ws';
return "$transport:$host:$key";
}
sub _ws_get_persistent($scfg) {
# Fork detection: if we're in a child process, inherited connections are invalid
# CRITICAL: When child exits, Perl's global destruction calls DESTROY on all objects,
# including inherited IO::Socket::SSL sockets. DESTROY calls SSL_free() which corrupts
# the parent's SSL state (shared via fork).
#
# SOLUTION: Rebless inherited sockets into NullDestructor class. This makes DESTROY
# a complete no-op - no SSL cleanup, no FD close, nothing. The socket will "leak"
# in the child process, but that's fine:
# - Child exits soon anyway
# - OS reclaims all resources on process exit
# - No corruption can occur because no cleanup code runs
#
# IMPORTANT: Do NOT clear %_ws_connections or set sock=undef - that triggers DESTROY!
# Just rebless and update the PID so new connections get created on next call.
if ($$ != $_ws_creator_pid) {
eval { _log($scfg, 2, 'debug', "[TrueNAS] Fork detected (creator PID $_ws_creator_pid, current PID $$), neutering inherited connections"); };
for my $conn (values %_ws_connections) {
if ($conn && $conn->{sock}) {
# Rebless socket into NullDestructor - makes DESTROY a complete no-op
# This prevents ALL cleanup code from running (SSL, IO::Socket, Perl IO layer)
bless $conn->{sock}, 'PVE::Storage::Custom::TrueNASPlugin::NullDestructor';
}
}
# Clear the hash so child creates fresh connections, but the neutered socket
# objects remain in memory until child exits (harmless - OS cleans up)
%_ws_connections = ();
$_ws_creator_pid = $$;
}
my $key = _ws_connection_key($scfg);
my $conn = $_ws_connections{$key};
# Test if existing connection is still alive
if ($conn && $conn->{sock}) {
# Quick connection test - try to send a ping
eval {
# Test with a lightweight method call
_ws_rpc($conn, {
jsonrpc => "2.0", id => 999999, method => "core.ping", params => [],
});
};
if ($@) {
# Connection is dead, close socket properly before removing from cache
# This prevents "free unreferenced scalar" errors from IO::Socket::SSL
if ($conn && $conn->{sock}) {
eval { $conn->{sock}->close(); };
}
delete $_ws_connections{$key};
$conn = undef;
}
}
# Create new connection if needed
if (!$conn) {
$conn = _ws_open($scfg);
$_ws_connections{$key} = $conn if $conn;
}
return $conn;
}
sub _ws_cleanup_connections() {
# Clean up all stored connections (called during shutdown)
# Fork safety: if we're in a child process, don't close parent's sockets
if ($$ != $_ws_creator_pid) {
# Neuter inherited sockets and clear hash (same pattern as _ws_get_persistent)
for my $conn (values %_ws_connections) {
if ($conn && $conn->{sock}) {
bless $conn->{sock}, 'PVE::Storage::Custom::TrueNASPlugin::NullDestructor';
}
}
%_ws_connections = ();
$_ws_creator_pid = $$;
return;
}
# Normal cleanup in parent process
for my $key (keys %_ws_connections) {
my $conn = $_ws_connections{$key};
if ($conn && $conn->{sock}) {
eval { $conn->{sock}->close(); };
}
}
%_ws_connections = ();
}
# ======== Ephemeral WebSocket Connection for Write Operations ========
# Creates a fresh, isolated connection for write operations to avoid
# race conditions when multiple processes share persistent connections.
# Each write operation gets its own connection that is closed after use.
sub _ws_open_ephemeral($scfg) {
# Create a new WebSocket connection that will NOT be cached
# This is identical to _ws_open() but the caller is responsible
# for closing it after use via _ws_close_ephemeral()
return _ws_open($scfg);
}
sub _ws_close_ephemeral($conn, $scfg = undef) {
# Close an ephemeral connection after use