-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy patherrors.rs
More file actions
345 lines (301 loc) · 12.9 KB
/
Copy patherrors.rs
File metadata and controls
345 lines (301 loc) · 12.9 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
//! Error types for the Test Subcommand
//!
//! This module defines error types that can occur during CLI test command execution.
//! All errors follow the project's error handling principles by providing clear,
//! contextual, and actionable error messages with `.help()` methods.
use thiserror::Error;
use crate::application::command_handlers::test::errors::TestCommandHandlerError;
use crate::domain::environment::name::EnvironmentNameError;
use crate::presentation::cli::views::progress::ProgressReporterError;
use crate::presentation::cli::views::ViewRenderError;
/// Test command specific errors
///
/// This enum contains all error variants specific to the test command,
/// including environment validation, repository access, and validation failures.
/// Each variant includes relevant context and actionable error messages.
#[derive(Debug, Error)]
pub enum TestSubcommandError {
// ===== Environment Validation Errors =====
/// Environment name validation failed
///
/// The provided environment name doesn't meet the validation requirements.
/// Use `.help()` for detailed troubleshooting steps.
#[error("Invalid environment name '{name}': {source}
Tip: Environment names must be 1-63 characters, start with letter/digit, contain only letters/digits/hyphens")]
InvalidEnvironmentName {
name: String,
#[source]
source: EnvironmentNameError,
},
/// Environment not found or inaccessible
///
/// The environment couldn't be loaded from persistent storage.
/// Use `.help()` for detailed troubleshooting steps.
#[error(
"Environment '{name}' not found in data directory '{data_dir}'
Tip: Check if environment exists: ls -la {data_dir}/"
)]
EnvironmentNotFound { name: String, data_dir: String },
/// Environment does not have instance IP set
///
/// The environment is missing the instance IP, which means it hasn't been provisioned yet.
/// Use `.help()` for detailed troubleshooting steps.
#[error(
"Environment '{name}' does not have instance IP set
Tip: Environment must be provisioned before testing"
)]
MissingInstanceIp { name: String },
// ===== Validation Operation Errors =====
/// Validation operation failed
///
/// The validation process encountered an error during execution.
/// Use `.help()` for detailed troubleshooting steps.
#[error(
"Validation failed for environment '{name}': {source}
Tip: Check logs and try running with --log-output file-and-stderr for more details"
)]
ValidationFailed {
name: String,
#[source]
source: Box<TestCommandHandlerError>,
},
// ===== Internal Errors =====
/// Progress reporting failed
///
/// Failed to report progress to the user due to an internal error.
/// This indicates a critical internal error.
#[error(
"Failed to report progress: {source}
Tip: This is a critical bug - please report it with full logs using --log-output file-and-stderr"
)]
ProgressReportingFailed {
#[source]
source: ProgressReporterError,
},
/// Output formatting failed (JSON serialization error).
/// This indicates an internal error in data serialization.
#[error(
"Failed to format output: {reason}\nTip: This is a critical bug - please report it with full logs using --log-output file-and-stderr"
)]
OutputFormatting { reason: String },
}
// ============================================================================
// ERROR CONVERSIONS
// ============================================================================
impl From<ProgressReporterError> for TestSubcommandError {
fn from(source: ProgressReporterError) -> Self {
Self::ProgressReportingFailed { source }
}
}
impl From<ViewRenderError> for TestSubcommandError {
fn from(e: ViewRenderError) -> Self {
Self::OutputFormatting {
reason: e.to_string(),
}
}
}
impl TestSubcommandError {
/// Get detailed troubleshooting guidance for this error
///
/// This method provides comprehensive troubleshooting steps that can be
/// displayed to users when they need more help resolving the error.
///
/// # Example
///
/// Using with Container and `ExecutionContext` (recommended):
///
/// ```ignore
/// use std::path::Path;
/// use std::sync::Arc;
/// use torrust_tracker_deployer_lib::bootstrap::Container;
/// use torrust_tracker_deployer_lib::presentation::cli::dispatch::ExecutionContext;
/// use torrust_tracker_deployer_lib::presentation::cli::controllers::test;
/// use torrust_tracker_deployer_lib::presentation::cli::views::VerbosityLevel;
///
/// # #[tokio::main]
/// # async fn main() {
/// let container = Container::new(VerbosityLevel::Normal, Path::new("."));
/// let context = ExecutionContext::new(Arc::new(container), global_args);
///
/// if let Err(e) = context
/// .container()
/// .create_test_controller()
/// .execute("test-env")
/// .await
/// {
/// eprintln!("Error: {e}");
/// eprintln!("\nTroubleshooting:\n{}", e.help());
/// }
/// # }
/// ```
///
/// Direct usage (for testing):
///
/// ```ignore
/// use std::path::{Path, PathBuf};
/// use std::sync::Arc;
/// use parking_lot::ReentrantMutex;
/// use std::cell::RefCell;
/// use torrust_tracker_deployer_lib::presentation::cli::controllers::test::handler::TestCommandController;
/// use torrust_tracker_deployer_lib::presentation::cli::views::{UserOutput, VerbosityLevel};
/// use torrust_tracker_deployer_lib::infrastructure::persistence::file_repository_factory::FileRepositoryFactory;
/// use torrust_tracker_deployer_lib::presentation::cli::controllers::constants::DEFAULT_LOCK_TIMEOUT;
/// use torrust_tracker_deployer_lib::presentation::cli::input::cli::OutputFormat;
///
/// # #[tokio::main]
/// # async fn main() {
/// let output = Arc::new(ReentrantMutex::new(RefCell::new(UserOutput::new(VerbosityLevel::Normal))));
/// let data_dir = PathBuf::from("./data");
/// let file_repository_factory = FileRepositoryFactory::new(DEFAULT_LOCK_TIMEOUT);
/// let repository = file_repository_factory.create(data_dir);
/// if let Err(e) = TestCommandController::new(repository, output).execute("test-env", OutputFormat::Text).await {
/// eprintln!("Error: {e}");
/// eprintln!("\nTroubleshooting:\n{}", e.help());
/// }
/// # }
/// ```
#[must_use]
#[allow(clippy::too_many_lines)] // Help text is comprehensive for user guidance
pub fn help(&self) -> &'static str {
match self {
Self::InvalidEnvironmentName { .. } => {
"Invalid Environment Name - Detailed Troubleshooting:
1. Check environment name format:
- Length: Must be 1-63 characters
- Start: Must begin with a letter or digit
- Characters: Only letters, digits, and hyphens allowed
- No special characters: Avoid spaces, underscores, dots
2. Valid examples:
- 'production'
- 'staging-01'
- 'dev-environment'
3. Invalid examples:
- 'prod_01' (underscore not allowed)
- '-production' (cannot start with hyphen)
- 'prod.env' (dots not allowed)
For more information, see environment naming documentation."
}
Self::EnvironmentNotFound { .. } => {
"Environment Not Found - Detailed Troubleshooting:
1. Verify environment exists:
- List environments: ls -la data/
- Check for environment.json file in data/<environment-name>/
2. Check file permissions:
- Read permission: chmod +r data/<environment-name>/environment.json
- Directory access: chmod +rx data/<environment-name>/
3. Create environment first:
- Run: torrust-tracker-deployer create <environment-name>
4. Verify data directory:
- Ensure data/ directory exists
- Check disk space: df -h"
}
Self::MissingInstanceIp { .. } => {
"Missing Instance IP - Detailed Troubleshooting:
1. Environment must be provisioned before testing:
- Run: torrust-tracker-deployer provision <environment-name>
2. Verify provisioning status:
- Check environment state in data/<environment-name>/environment.json
- Look for 'instance_ip' field
3. Common causes:
- Environment was created but never provisioned
- Previous provision operation failed
- Manual modification of environment.json
4. Next steps:
- Provision the environment: torrust-tracker-deployer provision <environment-name>
- Or destroy and recreate: torrust-tracker-deployer destroy <environment-name>"
}
Self::ValidationFailed { .. } => {
"Validation Failed - Detailed Troubleshooting:
1. Check validation logs for specific failure:
- Re-run with verbose logging:
torrust-tracker-deployer test <environment-name> --log-output file-and-stderr
2. Common validation failures:
- Cloud-init not completed: Wait for instance initialization
- Docker not installed: Run configure command
- Docker Compose not installed: Run configure command
3. Remediation steps:
- If cloud-init failed: Destroy and re-provision
- If Docker/Compose missing: Run configure command
torrust-tracker-deployer configure <environment-name>
4. Check instance status:
- Verify instance is running
- Check SSH connectivity
- Review system logs on the instance"
}
Self::ProgressReportingFailed { .. } => {
"Progress Reporting Failed - Critical Internal Error:
This is a critical bug that should be reported to the development team.
1. Gather diagnostic information:
- Re-run command with full logging:
torrust-tracker-deployer test <environment-name> --log-output file-and-stderr
- Capture all error output
2. Report the issue:
- Include full error message
- Include command that triggered the error
- Include environment information (OS, version)
- Attach log files from data/logs/
3. Temporary workaround:
- None available - this indicates a serious internal error
- Try restarting the application
For bug reports, visit:
https://github.com/torrust/torrust-tracker-deployer/issues"
}
Self::OutputFormatting { .. } => {
"Output Formatting Failed - Critical Internal Error:\n\nThis error should not occur during normal operation. It indicates a bug in the output formatting system.\n\n1. Immediate actions:\n - Save full error output\n - Copy log files from data/logs/\n - Note the exact command and output format being used\n\n2. Report the issue:\n - Create GitHub issue with full details\n - Include: command, output format (--output-format), error output, logs\n - Describe steps to reproduce\n\n3. Temporary workarounds:\n - Try using different output format (text vs json)\n - Try running command again\n\nPlease report it so we can fix it."
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_should_display_help_message_when_environment_name_is_invalid() {
let error = TestSubcommandError::InvalidEnvironmentName {
name: "invalid_name".to_string(),
source: EnvironmentNameError::InvalidFormat {
attempted_name: "invalid_name".to_string(),
reason: "contains underscore".to_string(),
valid_examples: vec!["dev".to_string(), "staging".to_string()],
},
};
let help = error.help();
assert!(help.contains("Invalid Environment Name"));
assert!(help.contains("1-63 characters"));
assert!(help.contains("Valid examples"));
}
#[test]
fn it_should_display_help_message_when_environment_not_found() {
let error = TestSubcommandError::EnvironmentNotFound {
name: "test-env".to_string(),
data_dir: "/path/to/data".to_string(),
};
let help = error.help();
assert!(help.contains("Environment Not Found"));
assert!(help.contains("ls -la data/"));
assert!(help.contains("torrust-tracker-deployer create"));
}
#[test]
fn it_should_display_help_message_when_instance_ip_is_missing() {
let error = TestSubcommandError::MissingInstanceIp {
name: "test-env".to_string(),
};
let help = error.help();
assert!(help.contains("Missing Instance IP"));
assert!(help.contains("torrust-tracker-deployer provision"));
}
#[test]
fn it_should_display_help_message_when_validation_fails() {
let error = TestSubcommandError::ValidationFailed {
name: "test-env".to_string(),
source: Box::new(TestCommandHandlerError::MissingInstanceIp {
environment_name: "test-env".to_string(),
}),
};
let help = error.help();
assert!(help.contains("Validation Failed"));
assert!(help.contains("--log-output file-and-stderr"));
assert!(help.contains("Cloud-init"));
assert!(help.contains("Docker"));
}
}