Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add validate operation and set current working directory for process #66

Merged
merged 1 commit into from
Apr 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 6 additions & 9 deletions dsc/assertion.resource.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,11 @@
"exitCodes": {
"0": "Success"
},
"schema": {
"command": {
"executable": "dsc",
"args": [
"schema",
"-t",
"configuration-and-resources"
]
}
"validate": {
"executable": "dsc",
"args": [
"config",
"validate"
]
}
}
15 changes: 6 additions & 9 deletions dsc/group.resource.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,11 @@
"exitCodes": {
"0": "Success"
},
"schema": {
"command": {
"executable": "dsc",
"args": [
"schema",
"-t",
"configuration-and-resources"
]
}
"validate": {
"executable": "dsc",
"args": [
"config",
"validate"
]
}
}
15 changes: 6 additions & 9 deletions dsc/parallel.resource.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,11 @@
"exitCodes": {
"0": "Success"
},
"schema": {
"command": {
"executable": "dsc",
"args": [
"schema",
"-t",
"configuration-and-resources"
]
}
"validate": {
"executable": "dsc",
"args": [
"config",
"validate"
]
}
}
2 changes: 2 additions & 0 deletions dsc/src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ pub enum ConfigSubCommand {
Set,
#[clap(name = "test", about = "Test the current configuration")]
Test,
#[clap(name = "validate", about = "Validate the current configuration")]
Validate,
}

#[derive(Debug, PartialEq, Eq, Subcommand)]
Expand Down
10 changes: 7 additions & 3 deletions dsc/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,10 @@ fn handle_config_subcommand(subcommand: &ConfigSubCommand, format: &Option<Outpu
eprintln!("Testing configuration... NOT IMPLEMENTED YET");
exit(EXIT_DSC_ERROR);
},
ConfigSubCommand::Validate => {
eprintln!("Validate configuration.. NOT IMPLEMENTED YET");
exit(EXIT_DSC_ERROR);
}
}
}

Expand Down Expand Up @@ -192,7 +196,7 @@ fn handle_resource_subcommand(subcommand: &ResourceSubCommand, format: &Option<O
ResourceSubCommand::Schema { resource } => {
handle_resource_schema(&mut dsc, resource, format);
},
}
}
}

fn handle_resource_get(dsc: &mut DscManager, resource: &str, input: &Option<String>, stdin: &Option<String>, format: &Option<OutputFormat>) {
Expand Down Expand Up @@ -259,7 +263,7 @@ fn handle_resource_test(dsc: &mut DscManager, resource: &str, input: &Option<Str
eprintln!("Error: {err}");
exit(EXIT_DSC_ERROR);
}
}
}
}

fn handle_resource_schema(dsc: &mut DscManager, resource: &str, format: &Option<OutputFormat>) {
Expand All @@ -280,7 +284,7 @@ fn handle_resource_schema(dsc: &mut DscManager, resource: &str, format: &Option<
eprintln!("Error: {err}");
exit(EXIT_DSC_ERROR);
}
}
}
}

fn get_schema(dsc_type: DscType) -> RootSchema {
Expand Down
3 changes: 2 additions & 1 deletion dsc_lib/src/discovery/command_discovery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ impl ResourceDiscovery for CommandDiscovery {
let manifest = serde_json::from_value::<ResourceManifest>(provider_resource.manifest.clone().unwrap())?;
// invoke the list command
let list_command = manifest.provider.unwrap().list;
let (exit_code, stdout, stderr) = invoke_command(&list_command.executable, list_command.args, None)?;
let (exit_code, stdout, stderr) = invoke_command(&list_command.executable, list_command.args, None, Some(&provider_resource.directory))?;
if exit_code != 0 {
return Err(DscError::Operation(format!("Failed to list resources for provider {provider}: {exit_code} {stderr}")));
}
Expand Down Expand Up @@ -113,6 +113,7 @@ fn import_manifest(path: &Path) -> Result<DscResource, DscError> {
type_name: manifest.resource_type.clone(),
implemented_as: ImplementedAs::Command,
path: path.to_str().unwrap().to_string(),
directory: path.parent().unwrap().to_str().unwrap().to_string(),
manifest: Some(serde_json::to_value(manifest)?),
..Default::default()
};
Expand Down
40 changes: 22 additions & 18 deletions dsc_lib/src/dscresources/command_resource.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@ pub const EXIT_PROCESS_TERMINATED: i32 = 0x102;
/// # Errors
///
/// Error returned if the resource does not successfully get the current state
pub fn invoke_get(resource: &ResourceManifest, filter: &str) -> Result<GetResult, DscError> {
pub fn invoke_get(resource: &ResourceManifest, cwd: &str, filter: &str) -> Result<GetResult, DscError> {
if !filter.is_empty() && resource.get.input.is_some() {
verify_json(resource, filter)?;
verify_json(resource, cwd, filter)?;
}

let (exit_code, stdout, stderr) = invoke_command(&resource.get.executable, resource.get.args.clone(), Some(filter))?;
let (exit_code, stdout, stderr) = invoke_command(&resource.get.executable, resource.get.args.clone(), Some(filter), Some(cwd))?;
if exit_code != 0 {
return Err(DscError::Command(resource.resource_type.clone(), exit_code, stderr));
}
Expand All @@ -46,15 +46,15 @@ pub fn invoke_get(resource: &ResourceManifest, filter: &str) -> Result<GetResult
/// # Errors
///
/// Error returned if the resource does not successfully set the desired state
pub fn invoke_set(resource: &ResourceManifest, desired: &str) -> Result<SetResult, DscError> {
pub fn invoke_set(resource: &ResourceManifest, cwd: &str, desired: &str) -> Result<SetResult, DscError> {
let Some(set) = &resource.set else {
return Err(DscError::NotImplemented("set".to_string()));
};

verify_json(resource, desired)?;
verify_json(resource, cwd, desired)?;
// if resource doesn't implement a pre-test, we execute test first to see if a set is needed
if !set.pre_test.unwrap_or_default() {
let test_result = invoke_test(resource, desired)?;
let test_result = invoke_test(resource, cwd, desired)?;
if test_result.diff_properties.is_none() {
return Ok(SetResult {
before_state: test_result.expected_state,
Expand All @@ -64,15 +64,15 @@ pub fn invoke_set(resource: &ResourceManifest, desired: &str) -> Result<SetResul
}
}

let (exit_code, stdout, stderr) = invoke_command(&resource.get.executable, resource.get.args.clone(), Some(desired))?;
let (exit_code, stdout, stderr) = invoke_command(&resource.get.executable, resource.get.args.clone(), Some(desired), Some(cwd))?;
let pre_state: Value = if exit_code == 0 {
serde_json::from_str(&stdout)?
}
else {
return Err(DscError::Command(resource.resource_type.clone(), exit_code, stderr));
};

let (exit_code, stdout, stderr) = invoke_command(&set.executable, set.args.clone(), Some(desired))?;
let (exit_code, stdout, stderr) = invoke_command(&set.executable, set.args.clone(), Some(desired), Some(cwd))?;
if exit_code != 0 {
return Err(DscError::Command(resource.resource_type.clone(), exit_code, stderr));
}
Expand Down Expand Up @@ -108,7 +108,7 @@ pub fn invoke_set(resource: &ResourceManifest, desired: &str) -> Result<SetResul
},
None => {
// perform a get and compare the result to the expected state
let get_result = invoke_get(resource, desired)?;
let get_result = invoke_get(resource, cwd, desired)?;
// for changed_properties, we compare post state to pre state
let diff_properties = get_diff( &get_result.actual_state, &pre_state);
Ok(SetResult {
Expand All @@ -130,13 +130,13 @@ pub fn invoke_set(resource: &ResourceManifest, desired: &str) -> Result<SetResul
/// # Errors
///
/// Error is returned if the underlying command returns a non-zero exit code.
pub fn invoke_test(resource: &ResourceManifest, expected: &str) -> Result<TestResult, DscError> {
pub fn invoke_test(resource: &ResourceManifest, cwd: &str, expected: &str) -> Result<TestResult, DscError> {
let Some(test) = resource.test.as_ref() else {
return Err(DscError::NotImplemented("test".to_string()));
};

verify_json(resource, expected)?;
let (exit_code, stdout, stderr) = invoke_command(&test.executable, test.args.clone(), Some(expected))?;
verify_json(resource, cwd, expected)?;
let (exit_code, stdout, stderr) = invoke_command(&test.executable, test.args.clone(), Some(expected), Some(cwd))?;
if exit_code != 0 {
return Err(DscError::Command(resource.resource_type.clone(), exit_code, stderr));
}
Expand Down Expand Up @@ -171,7 +171,7 @@ pub fn invoke_test(resource: &ResourceManifest, expected: &str) -> Result<TestRe
},
None => {
// perform a get and compare the result to the expected state
let get_result = invoke_get(resource, expected)?;
let get_result = invoke_get(resource, cwd, expected)?;
let diff_properties = get_diff(&expected_value, &get_result.actual_state);
Ok(TestResult {
expected_state: expected_value,
Expand All @@ -191,14 +191,14 @@ pub fn invoke_test(resource: &ResourceManifest, expected: &str) -> Result<TestRe
/// # Errors
///
/// Error if schema is not available or if there is an error getting the schema
pub fn get_schema(resource: &ResourceManifest) -> Result<String, DscError> {
pub fn get_schema(resource: &ResourceManifest, cwd: &str) -> Result<String, DscError> {
let Some(schema_kind) = resource.schema.as_ref() else {
return Err(DscError::SchemaNotAvailable(resource.resource_type.clone()));
};

match schema_kind {
SchemaKind::Command(ref command) => {
let (exit_code, stdout, stderr) = invoke_command(&command.executable, command.args.clone(), None)?;
let (exit_code, stdout, stderr) = invoke_command(&command.executable, command.args.clone(), None, Some(cwd))?;
if exit_code != 0 {
return Err(DscError::Command(resource.resource_type.clone(), exit_code, stderr));
}
Expand Down Expand Up @@ -229,11 +229,12 @@ pub fn get_schema(resource: &ResourceManifest) -> Result<String, DscError> {
/// * `executable` - The command to execute
/// * `args` - Optional arguments to pass to the command
/// * `input` - Optional input to pass to the command
/// * `cwd` - Optional working directory to execute the command in
///
/// # Errors
///
/// Error is returned if the command fails to execute or stdin/stdout/stderr cannot be opened.
pub fn invoke_command(executable: &str, args: Option<Vec<String>>, input: Option<&str>) -> Result<(i32, String, String), DscError> {
pub fn invoke_command(executable: &str, args: Option<Vec<String>>, input: Option<&str>, cwd: Option<&str>) -> Result<(i32, String, String), DscError> {
let mut command = Command::new(executable);
if input.is_some() {
command.stdin(Stdio::piped());
Expand All @@ -243,6 +244,9 @@ pub fn invoke_command(executable: &str, args: Option<Vec<String>>, input: Option
if let Some(args) = args {
command.args(args);
}
if let Some(cwd) = cwd {
command.current_dir(cwd);
}

let mut child = command.spawn()?;
if input.is_some() {
Expand Down Expand Up @@ -273,8 +277,8 @@ pub fn invoke_command(executable: &str, args: Option<Vec<String>>, input: Option
Ok((exit_code, stdout, stderr))
}

fn verify_json(resource: &ResourceManifest, json: &str) -> Result<(), DscError> {
let schema = get_schema(resource)?;
fn verify_json(resource: &ResourceManifest, cwd: &str, json: &str) -> Result<(), DscError> {
let schema = get_schema(resource, cwd)?;
let schema: Value = serde_json::from_str(&schema)?;
let compiled_schema = match JSONSchema::compile(&schema) {
Ok(schema) => schema,
Expand Down
11 changes: 7 additions & 4 deletions dsc_lib/src/dscresources/dscresource.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ pub struct DscResource {
pub version: String,
/// The file path to the resource.
pub path: String,
// The directory path to the resource.
pub directory: String,
/// The implementation of the resource.
#[serde(rename="implementedAs")]
pub implemented_as: ImplementedAs,
Expand Down Expand Up @@ -46,6 +48,7 @@ impl DscResource {
type_name: String::new(),
version: String::new(),
path: String::new(),
directory: String::new(),
implemented_as: ImplementedAs::Command,
author: None,
properties: Vec::new(),
Expand Down Expand Up @@ -115,7 +118,7 @@ impl Invoke for DscResource {
return Err(DscError::MissingManifest(self.type_name.clone()));
};
let resource_manifest = serde_json::from_value::<ResourceManifest>(manifest.clone())?;
command_resource::invoke_get(&resource_manifest, filter)
command_resource::invoke_get(&resource_manifest, &self.directory, filter)
},
}
}
Expand All @@ -130,7 +133,7 @@ impl Invoke for DscResource {
return Err(DscError::MissingManifest(self.type_name.clone()));
};
let resource_manifest = serde_json::from_value::<ResourceManifest>(manifest.clone())?;
command_resource::invoke_set(&resource_manifest, desired)
command_resource::invoke_set(&resource_manifest, &self.directory, desired)
},
}
}
Expand Down Expand Up @@ -159,7 +162,7 @@ impl Invoke for DscResource {
Ok(test_result)
}
else {
command_resource::invoke_test(&resource_manifest, expected)
command_resource::invoke_test(&resource_manifest, &self.directory, expected)
}
},
}
Expand All @@ -175,7 +178,7 @@ impl Invoke for DscResource {
return Err(DscError::MissingManifest(self.type_name.clone()));
};
let resource_manifest = serde_json::from_value::<ResourceManifest>(manifest.clone())?;
command_resource::get_schema(&resource_manifest)
command_resource::get_schema(&resource_manifest, &self.directory)
},
}
}
Expand Down
3 changes: 3 additions & 0 deletions test_group_resource/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ fn main() {
version: "1.0.0".to_string(),
implemented_as: ImplementedAs::Custom("TestResource".to_string()),
path: "test_resource1".to_string(),
directory: "test_directory".to_string(),
author: Some("Microsoft".to_string()),
properties: vec!["Property1".to_string(), "Property2".to_string()],
requires: Some("Test/TestGroup".to_string()),
Expand All @@ -30,6 +31,7 @@ fn main() {
version: "1.0.1".to_string(),
implemented_as: ImplementedAs::Custom("TestResource".to_string()),
path: "test_resource2".to_string(),
directory: "test_directory".to_string(),
author: Some("Microsoft".to_string()),
properties: vec!["Property1".to_string(), "Property2".to_string()],
requires: Some("Test/TestGroup".to_string()),
Expand All @@ -46,6 +48,7 @@ fn main() {
version: "1.0.0".to_string(),
implemented_as: ImplementedAs::Custom("TestResource".to_string()),
path: "test_resource1".to_string(),
directory: "test_directory".to_string(),
author: Some("Microsoft".to_string()),
properties: vec!["Property1".to_string(), "Property2".to_string()],
requires: None,
Expand Down