redisctl 0.10.1

Unified CLI for Redis Cloud and Enterprise
Documentation
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
use crate::error::RedisCtlError;
use anyhow::{Context, Result as AnyhowResult};
use clap::Subcommand;
use redisctl_core::Config;
use serde_json::Value;
use std::path::Path;

use crate::cli::OutputFormat;

#[derive(Debug, Subcommand)]
pub enum LicenseCommands {
    /// Get current license information
    Get,
    /// Update license with JSON data
    #[command(after_help = "EXAMPLES:
    # Update license with key
    redisctl enterprise license update --license-key ABC123...

    # Using JSON file
    redisctl enterprise license update --data @license.json")]
    Update {
        /// License key string
        #[arg(long)]
        license_key: Option<String>,
        /// License data as JSON string or @file.json (optional)
        #[arg(long, value_name = "FILE|JSON")]
        data: Option<String>,
    },
    /// Upload license file
    Upload {
        /// Path to license file
        #[arg(long)]
        file: String,
    },
    /// Validate license
    #[command(after_help = "EXAMPLES:
    # Validate license key
    redisctl enterprise license validate --license-key ABC123...

    # Validate from JSON
    redisctl enterprise license validate --data @license.json")]
    Validate {
        /// License key string to validate
        #[arg(long)]
        license_key: Option<String>,
        /// License data as JSON string or @file.json (optional)
        #[arg(long, value_name = "FILE|JSON")]
        data: Option<String>,
    },
    /// Check license expiration
    Expiry,
    /// List licensed features
    Features,
    /// Show license usage and limits
    Usage,
}

impl LicenseCommands {
    #[allow(dead_code)]
    pub async fn execute(
        &self,
        config: &Config,
        profile_name: Option<&str>,
        output_format: OutputFormat,
        query: Option<&str>,
    ) -> AnyhowResult<()> {
        let conn_manager = crate::connection::ConnectionManager::new(config.clone());

        match self {
            Self::Get => {
                handle_get_license(&conn_manager, profile_name, output_format, query).await
            }
            Self::Update { license_key, data } => {
                handle_update_license(
                    &conn_manager,
                    profile_name,
                    license_key.as_deref(),
                    data.as_deref(),
                    output_format,
                    query,
                )
                .await
            }
            Self::Upload { file } => {
                handle_upload_license(&conn_manager, profile_name, file, output_format, query).await
            }
            Self::Validate { license_key, data } => {
                handle_validate_license(
                    &conn_manager,
                    profile_name,
                    license_key.as_deref(),
                    data.as_deref(),
                    output_format,
                    query,
                )
                .await
            }
            Self::Expiry => {
                handle_license_expiry(&conn_manager, profile_name, output_format, query).await
            }
            Self::Features => {
                handle_license_features(&conn_manager, profile_name, output_format, query).await
            }
            Self::Usage => {
                handle_license_usage(&conn_manager, profile_name, output_format, query).await
            }
        }
    }
}

async fn handle_get_license(
    conn_mgr: &crate::connection::ConnectionManager,
    profile_name: Option<&str>,
    output_format: OutputFormat,
    query: Option<&str>,
) -> AnyhowResult<()> {
    let client = conn_mgr.create_enterprise_client(profile_name).await?;

    let response = client
        .get::<Value>("/v1/license")
        .await
        .map_err(RedisCtlError::from)?;

    let response = if let Some(q) = query {
        super::utils::apply_jmespath(&response, q)?
    } else {
        response
    };

    super::utils::print_formatted_output(response, output_format).map_err(|e| anyhow::anyhow!(e))
}

async fn handle_update_license(
    conn_mgr: &crate::connection::ConnectionManager,
    profile_name: Option<&str>,
    license_key: Option<&str>,
    data: Option<&str>,
    output_format: OutputFormat,
    query: Option<&str>,
) -> AnyhowResult<()> {
    let client = conn_mgr.create_enterprise_client(profile_name).await?;

    // Start with JSON from --data if provided, otherwise empty object
    let mut json_data = if let Some(data_str) = data {
        super::utils::read_json_data(data_str)?
    } else {
        serde_json::json!({})
    };

    let data_obj = json_data.as_object_mut().unwrap();

    // CLI parameters override JSON values
    if let Some(key) = license_key {
        data_obj.insert("license".to_string(), serde_json::json!(key));
    }

    let response = client
        .put::<_, Value>("/v1/license", &json_data)
        .await
        .map_err(RedisCtlError::from)?;

    let response = if let Some(q) = query {
        super::utils::apply_jmespath(&response, q)?
    } else {
        response
    };

    super::utils::print_formatted_output(response, output_format).map_err(|e| anyhow::anyhow!(e))
}

async fn handle_upload_license(
    conn_mgr: &crate::connection::ConnectionManager,
    profile_name: Option<&str>,
    file: &str,
    output_format: OutputFormat,
    query: Option<&str>,
) -> AnyhowResult<()> {
    let client = conn_mgr.create_enterprise_client(profile_name).await?;

    // Read the license file
    let path = Path::new(file);
    if !path.exists() {
        anyhow::bail!("License file not found: {}", file);
    }

    let license_content = std::fs::read_to_string(path)
        .with_context(|| format!("Failed to read license file: {}", file))?;

    // Try to parse as JSON first
    let license_data = if let Ok(json) = serde_json::from_str::<Value>(&license_content) {
        json
    } else {
        // If not JSON, wrap the content as a license string
        serde_json::json!({
            "license": license_content.trim()
        })
    };

    let response = client
        .put::<_, Value>("/v1/license", &license_data)
        .await
        .map_err(RedisCtlError::from)?;

    let response = if let Some(q) = query {
        super::utils::apply_jmespath(&response, q)?
    } else {
        response
    };

    super::utils::print_formatted_output(response, output_format).map_err(|e| anyhow::anyhow!(e))
}

async fn handle_validate_license(
    conn_mgr: &crate::connection::ConnectionManager,
    profile_name: Option<&str>,
    license_key: Option<&str>,
    data: Option<&str>,
    output_format: OutputFormat,
    query: Option<&str>,
) -> AnyhowResult<()> {
    let client = conn_mgr.create_enterprise_client(profile_name).await?;

    // Start with JSON from --data if provided, otherwise empty object
    let mut json_data = if let Some(data_str) = data {
        super::utils::read_json_data(data_str)?
    } else {
        serde_json::json!({})
    };

    let data_obj = json_data.as_object_mut().unwrap();

    // CLI parameters override JSON values
    if let Some(key) = license_key {
        data_obj.insert("license".to_string(), serde_json::json!(key));
    }

    // The validation endpoint might not exist, so we'll use the regular PUT with dry_run if available
    // Otherwise, we'll just try to parse and validate the license locally
    let response = client
        .put::<_, Value>("/v1/license?dry_run=true", &json_data)
        .await
        .or_else(|_| -> Result<Value, anyhow::Error> {
            // If dry_run is not supported, just get current license and check format
            Ok(serde_json::json!({
                "valid": json_data.get("license").is_some() || json_data.get("key").is_some(),
                "message": "License format appears valid (server validation not available)"
            }))
        })
        .context("Failed to validate license")?;

    let response = if let Some(q) = query {
        super::utils::apply_jmespath(&response, q)?
    } else {
        response
    };

    super::utils::print_formatted_output(response, output_format).map_err(|e| anyhow::anyhow!(e))
}

async fn handle_license_expiry(
    conn_mgr: &crate::connection::ConnectionManager,
    profile_name: Option<&str>,
    output_format: OutputFormat,
    query: Option<&str>,
) -> AnyhowResult<()> {
    let client = conn_mgr.create_enterprise_client(profile_name).await?;

    let license = client
        .get::<Value>("/v1/license")
        .await
        .map_err(RedisCtlError::from)?;

    // Extract expiration information
    let expiry_info = serde_json::json!({
        "expired": license.get("expired").and_then(|v| v.as_bool()).unwrap_or(false),
        "expiration_date": license.get("expiration_date").and_then(|v| v.as_str()).unwrap_or("unknown"),
        "days_remaining": calculate_days_remaining(license.get("expiration_date").and_then(|v| v.as_str())),
        "warning": should_warn_expiry(license.get("expiration_date").and_then(|v| v.as_str())),
    });

    let response = if let Some(q) = query {
        super::utils::apply_jmespath(&expiry_info, q)?
    } else {
        expiry_info
    };

    super::utils::print_formatted_output(response, output_format).map_err(|e| anyhow::anyhow!(e))
}

async fn handle_license_features(
    conn_mgr: &crate::connection::ConnectionManager,
    profile_name: Option<&str>,
    output_format: OutputFormat,
    query: Option<&str>,
) -> AnyhowResult<()> {
    let client = conn_mgr.create_enterprise_client(profile_name).await?;

    let license = client
        .get::<Value>("/v1/license")
        .await
        .map_err(RedisCtlError::from)?;

    // Extract feature information
    let features = if let Some(features) = license.get("features") {
        features.clone()
    } else {
        // Construct features from license capabilities
        serde_json::json!({
            "shards_limit": license.get("shards_limit"),
            "ram_limit": license.get("ram_limit"),
            "flash_enabled": license.get("flash_enabled"),
            "rack_awareness": license.get("rack_awareness"),
            "multi_ip": license.get("multi_ip"),
            "ipv6": license.get("ipv6"),
            "redis_pack": license.get("redis_pack"),
            "modules": license.get("modules"),
        })
    };

    let response = if let Some(q) = query {
        super::utils::apply_jmespath(&features, q)?
    } else {
        features
    };

    super::utils::print_formatted_output(response, output_format).map_err(|e| anyhow::anyhow!(e))
}

async fn handle_license_usage(
    conn_mgr: &crate::connection::ConnectionManager,
    profile_name: Option<&str>,
    output_format: OutputFormat,
    query: Option<&str>,
) -> AnyhowResult<()> {
    let client = conn_mgr.create_enterprise_client(profile_name).await?;

    // Get license information
    let license = client
        .get::<Value>("/v1/license")
        .await
        .map_err(RedisCtlError::from)?;

    // Get cluster stats for current usage
    let cluster = client
        .get::<Value>("/v1/cluster")
        .await
        .map_err(RedisCtlError::from)?;

    // Calculate usage vs limits
    let usage_info = serde_json::json!({
        "shards": {
            "limit": license.get("shards_limit").and_then(|v| v.as_i64()).unwrap_or(0),
            "used": cluster.get("shards_used").and_then(|v| v.as_i64()).unwrap_or(0),
            "available": calculate_available(
                license.get("shards_limit").and_then(|v| v.as_i64()),
                cluster.get("shards_used").and_then(|v| v.as_i64())
            ),
        },
        "ram": {
            "limit_bytes": license.get("ram_limit").and_then(|v| v.as_i64()).unwrap_or(0),
            "limit_gb": bytes_to_gb(license.get("ram_limit").and_then(|v| v.as_i64()).unwrap_or(0)),
            "used_bytes": cluster.get("ram_used").and_then(|v| v.as_i64()).unwrap_or(0),
            "used_gb": bytes_to_gb(cluster.get("ram_used").and_then(|v| v.as_i64()).unwrap_or(0)),
            "available_bytes": calculate_available(
                license.get("ram_limit").and_then(|v| v.as_i64()),
                cluster.get("ram_used").and_then(|v| v.as_i64())
            ),
            "available_gb": bytes_to_gb(calculate_available(
                license.get("ram_limit").and_then(|v| v.as_i64()),
                cluster.get("ram_used").and_then(|v| v.as_i64())
            )),
        },
        "nodes": {
            "limit": license.get("nodes_limit").and_then(|v| v.as_i64()).unwrap_or(0),
            "used": cluster.get("nodes_count").and_then(|v| v.as_i64()).unwrap_or(0),
        },
        "expiration": {
            "date": license.get("expiration_date").and_then(|v| v.as_str()).unwrap_or("unknown"),
            "expired": license.get("expired").and_then(|v| v.as_bool()).unwrap_or(false),
        }
    });

    let response = if let Some(q) = query {
        super::utils::apply_jmespath(&usage_info, q)?
    } else {
        usage_info
    };

    super::utils::print_formatted_output(response, output_format).map_err(|e| anyhow::anyhow!(e))
}

// Helper functions
pub fn calculate_days_remaining(expiration_date: Option<&str>) -> i64 {
    if let Some(date_str) = expiration_date {
        // Try parsing as ISO8601 datetime first (e.g., "2025-10-15T00:18:29Z")
        if let Ok(datetime) = chrono::DateTime::parse_from_rfc3339(date_str) {
            let today = chrono::Local::now().naive_local().date();
            let exp_date = datetime.naive_local().date();
            let duration = exp_date.signed_duration_since(today);
            return duration.num_days();
        }
        // Fall back to parsing as date only (e.g., "2025-10-15")
        if let Ok(exp_date) = chrono::NaiveDate::parse_from_str(date_str, "%Y-%m-%d") {
            let today = chrono::Local::now().naive_local().date();
            let duration = exp_date.signed_duration_since(today);
            return duration.num_days();
        }
    }
    -1
}

pub fn should_warn_expiry(expiration_date: Option<&str>) -> bool {
    let days = calculate_days_remaining(expiration_date);
    (0..=30).contains(&days)
}

pub fn calculate_available(limit: Option<i64>, used: Option<i64>) -> i64 {
    match (limit, used) {
        (Some(l), Some(u)) => (l - u).max(0),
        _ => 0,
    }
}

pub fn bytes_to_gb(bytes: i64) -> f64 {
    bytes as f64 / (1024.0 * 1024.0 * 1024.0)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_license_command_structure() {
        // Test that all license commands can be constructed

        // Get command
        let _cmd = LicenseCommands::Get;

        // Update command
        let _cmd = LicenseCommands::Update {
            license_key: Some("ABC123".to_string()),
            data: None,
        };

        // Upload command
        let _cmd = LicenseCommands::Upload {
            file: "/path/to/license".to_string(),
        };

        // Validate command
        let _cmd = LicenseCommands::Validate {
            license_key: Some("ABC123".to_string()),
            data: None,
        };

        // Expiry command
        let _cmd = LicenseCommands::Expiry;

        // Features command
        let _cmd = LicenseCommands::Features;

        // Usage command
        let _cmd = LicenseCommands::Usage;
    }

    #[test]
    fn test_calculate_days_remaining() {
        // Test with invalid date
        assert_eq!(calculate_days_remaining(None), -1);
        assert_eq!(calculate_days_remaining(Some("invalid")), -1);

        // Test with valid date (would need mocking for actual date comparison)
        // For now, just verify it doesn't panic
        let _ = calculate_days_remaining(Some("2025-12-31"));
    }

    #[test]
    fn test_bytes_to_gb() {
        assert_eq!(bytes_to_gb(0), 0.0);
        assert_eq!(bytes_to_gb(1073741824), 1.0); // 1 GB
        assert_eq!(bytes_to_gb(2147483648), 2.0); // 2 GB
    }

    #[test]
    fn test_calculate_available() {
        assert_eq!(calculate_available(Some(100), Some(30)), 70);
        assert_eq!(calculate_available(Some(50), Some(60)), 0); // Can't be negative
        assert_eq!(calculate_available(None, Some(10)), 0);
        assert_eq!(calculate_available(Some(100), None), 0);
    }
}