juiz_app 0.0.3

JUIZ utility command-line application package
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
//! juizローダーアプリ


mod process;
mod execution_context;
mod setup;
mod default_juiz_conf;
mod container;
mod container_process;

use std::path::PathBuf;

use execution_context::{on_execution_context, EcSubCommands};
use container::{on_container, ContSubCommands};
use container_process::{on_container_process, ContProcSubCommands};

use juiz_core::prelude::*;
use juiz_core::utils::yaml_conf_load;
use juiz_core::{ env_logger, log};
use crate::process::{on_process, ProcSubCommands};
use crate::setup::{on_setup, SetupSubCommands};

use clap::{Parser, Subcommand};


/// Simple program to greet a person
#[derive(Parser, Debug, Clone)]
#[command(author, version, about, long_about = None)]
#[clap(
    name = "juiz",
    author = "Yuki Suga",
    version = "v1.0.0",
    about = "JUIZ command-line tool"
)]
struct Args {
    /// Name of the person to greet
    #[arg(short = 'd', help = "Daemonize JUIZ server. This option automatically enables http server (-b option). If you want to supress, use -q option.")]
    daemonize: bool,

    #[arg(short = 'r', default_value="true", help = "Recursively walk subsystems.")]
    recursive: bool,

    #[arg(short = 'q', default_value="false", help = "Stop HTTP Broker. Default(false). This option is used with -d option only. If you use this with -b option, http server will start.")]
    stop_http_broker: bool,

    #[arg(short = 'b', help = "Start HTTP Broker. Default(false)")]
    start_http_broker: bool,

    #[arg(short = 'f', default_value = "./juiz.conf", help = "Input system definition file path")]
    filepath: String,

    #[arg(short = 's', help = "Host of server (ex., http://localhost:8000)")]
    server: Option<String>,

    #[arg(long = "process", help = "ProcessModule loader mode.")]
    process: Option<String>,

    #[arg(long = "container", help = "ContainerModule loader mode.")]
    container: Option<String>,

    #[arg(long = "container_process", help = "ContainerProcessModule loader mode.")]
    container_process: Option<String>,

    #[arg(long = "component", help = "ComponentModule loader mode.")]
    component: Option<String>,

    #[arg(short = 'l', help = "Module Language", default_value="rust")]
    module_language: String,

    #[arg(short = '1', long = "c1", help = "Create one instance for evely manually loaded module", default_value="false")]
    module_create: bool,

    #[arg(short = 'c', long = "create", value_delimiter=',', help = "Pass typeName to create one instance for evely manually loaded module")]
    create_instance: Vec<String>,


    #[arg(short = 'e', help = "Execute manually loaded module once", default_value="false")]
    module_execute: bool,

    #[arg(long = "print", help = "print output of execute. Use -e option with this.", default_value="false")]
    module_execute_print: bool,

    #[arg(short = 'm', help = "Print manifest of loaded module", default_value="false")]
    module_manifest_print: bool,

    #[clap(subcommand)]
    subcommand: Option<SubCommands>,
}


#[derive(Debug, Subcommand, Clone)]
enum SubCommands {
    // Setup tools
    #[clap(arg_required_else_help = false)]
    Setup {
        #[clap(subcommand)]
        subcommand: SetupSubCommands
    },

    // Process tools
    #[clap(arg_required_else_help = false)]
    Process {
        #[clap(subcommand)]
        subcommand: ProcSubCommands
    },

    // Container tools
    #[clap(arg_required_else_help = false)]
    Container {
        #[clap(subcommand)]
        subcommand: ContSubCommands
    },

    // Container tools
    #[clap(arg_required_else_help = false)]
    ContainerProcess {
        #[clap(subcommand)]
        subcommand: ContProcSubCommands
    },

    // Container tools
    #[clap(arg_required_else_help = false)]
    Ec {
        #[clap(subcommand)]
        subcommand: EcSubCommands
    },
}


fn do_task_once(system: &mut System, args: Args) -> JuizResult<()> {
    // println!("System started once");
    let language = args.module_language;
    let create_every = args.module_create;
    let execute = args.module_execute;
    let print = args.module_execute_print;
    let module_manifest_print = args.module_manifest_print;
    let create_instance = args.create_instance;
    if let Some(process_path) = args.process {
        let pm: ProcessManifest = system.core_broker().lock_mut()?.system_load_process(language, process_path)?.try_into()?;
        if module_manifest_print {
            println!("{pm:?}");
        }
        if create_every {
            let process_proxy = create_process_by_pm(system, &pm)?;
            if execute {
                let v = process_proxy.lock_mut()?.execute()?;
                if print {
                    println!("{v:?}");
                }
            }
        } else {
            for create_type_name in create_instance.iter() {
                if pm.type_name == create_type_name.as_str() {
                    let process_proxy = create_process_by_pm(system, &pm)?;
                    if execute {
                        let v = process_proxy.lock_mut()?.execute()?;
                        if print {
                            println!("{v:?}");
                        }
                    }
                }
            }
        }
    } else if let Some(container_path) = args.container {
        let cm: ContainerManifest = system.core_broker().lock_mut()?.system_load_container(language.clone(), container_path)?.try_into()?;
        let mut container_id = None;
        if module_manifest_print {
            println!("{cm:?}");
        }
        if create_every {
            let container_ptr = create_container_by_cm(system, &cm)?;
            container_id = Some(container_ptr.identifier().clone());
        } else {
            for create_type_name in create_instance.iter() {
                if cm.type_name == create_type_name.as_str() {
                    let container_ptr = create_container_by_cm(system, &cm)?;
                    container_id = Some(container_ptr.identifier().clone());
                    break;
                }
            }
        }
        if let Some(container_process_path) = args.container_process {
            let pm: ProcessManifest = system.core_broker().lock_mut()?.system_load_container_process(language, container_process_path)?.try_into()?;
            if module_manifest_print {
                println!("{pm:?}");
            }
            if create_every {
                let process_proxy = create_container_process_by_cid_and_pm(system, container_id.unwrap(), &pm)?;
                if execute {
                    let v = process_proxy.lock_mut()?.execute()?;
                    if print {
                        println!("{v:?}");
                    }
                }
            } else {
                if let Some(cid) = container_id {
                    for create_type_name in create_instance.iter() {
                        if pm.type_name == create_type_name.as_str() {
                            let process_proxy = create_container_process_by_cid_and_pm(system, cid.clone(), &pm)?;
                            if execute {
                                let v = process_proxy.lock_mut()?.execute()?;
                                if print {
                                    println!("{v:?}");
                                }
                            }
                        }
                    }
                }
            }
        }
    } else if let Some(component_path) = args.component {
        let compm: ComponentManifest = system.core_broker().lock_mut()?.system_load_component(language, component_path)?.try_into()?;
        if module_manifest_print {
            println!("{compm:}");
        }
        for pm in compm.processes.iter() {
            let proc = create_process_by_pm(system, pm)?;
            if execute {
                let v = proc.lock_mut()?.execute()?;
                if print {
                    println!("{v:?}");
                }
            }
        }
        for cm in compm.containers.iter() {
            let cont = create_container_by_cm(system, cm)?;
            let cid = cont.identifier().clone();
            for pm in cm.processes.iter() {
                let cproc = create_container_process_by_cid_and_pm(system, cid.clone(), pm)?;
                if execute {
                    let v = cproc.lock_mut()?.execute()?;
                    if print {
                        println!("{v:?}");
                    }
                }
            }
        }
    }
    Ok(())
}



fn do_task(system: &mut System, args: Args) -> JuizResult<()> {
    // println!("System started");
    let language = args.module_language;
    let create = args.module_create;
    let execute = args.module_execute;
    let print = args.module_execute_print;
    let module_manifest_print = args.module_manifest_print;
    if let Some(process_path) = args.process {
        let pm: ProcessManifest = system.core_broker().lock_mut()?.system_load_process(language, process_path)?.try_into()?;
        if module_manifest_print {
            println!("{pm:?}");
        }
        if create {
            let type_name = pm.type_name;
            let prof = system.core_broker().lock_mut()?.process_create(ProcessManifest::new(type_name.as_str()).name(format!("{}0", type_name).as_str()))?;
            if execute {
                let identifier = obj_get_str(&prof, "identifier")?;
                let process_proxy = system.core_broker().lock()?.worker().process_from_identifier(&identifier.to_owned())?;
                let v = process_proxy.lock_mut()?.execute()?;
                if print {
                    println!("{v:?}");
                }
            }
        }
    }  else if let Some(container_path) = args.container {
        let cm: ContainerManifest = system.core_broker().lock_mut()?.system_load_container(language.clone(), container_path)?.try_into()?;
        let mut container_id = None;
        if module_manifest_print {
            println!("{cm:?}");
        }if create {
            let type_name = cm.type_name;
            let name = format!("{}0", type_name);
            let  mut cp = CapsuleMap::new();
            cp.insert("name".to_owned(), jvalue!(name).into());
            cp.insert("type_name".to_owned(), jvalue!(type_name).into());
            let cont_prof = system.core_broker().lock_mut()?.container_create(cp)?;
            container_id = Some(obj_get_str(&cont_prof, "identifier")?.to_owned());
        }
        if let Some(container_process_path) = args.container_process {
            let pm: ProcessManifest = system.core_broker().lock_mut()?.system_load_container_process(language, container_process_path)?.try_into()?;
            if module_manifest_print {
                println!("{pm:?}");
            }
            if create {
                let type_name = pm.type_name;
                let prof = system.core_broker().lock_mut()?.container_process_create(&container_id.unwrap(), ProcessManifest::new(type_name.as_str()).name(format!("{}0", type_name).as_str()))?;
                if execute {
                    let identifier = obj_get_str(&prof, "identifier")?;
                    let process_proxy = system.core_broker().lock()?.worker().any_process_from_identifier(&identifier.to_owned())?;
                    let v = process_proxy.lock_mut()?.execute()?;
                    if print {
                        println!("{v:?}");
                    }
                }
            }
        }
    } else if let Some(component_path) = args.component {
        let compm: ComponentManifest = system.core_broker().lock_mut()?.system_load_component(language, component_path)?.try_into()?;
        if module_manifest_print {
            println!("{compm:}");
        }
        for pm in compm.processes.iter() {
            if create {
                let proc = create_process_by_pm(system, pm)?;
                if execute {
                    let v = proc.lock_mut()?.execute()?;
                    if print {
                        println!("{v:?}");
                    }
                }
            }
        }
        for cm in compm.containers.iter() {
            if create {
                let cont = create_container_by_cm(system, cm)?;
                let cid = cont.identifier().clone();
                for pm in cm.processes.iter() {
                    let cproc = create_container_process_by_cid_and_pm(system, cid.clone(), pm)?;
                    if execute {
                        let v = cproc.lock_mut()?.execute()?;
                        if print {
                            println!("{v:?}");
                        }
                    }
                }
            }
        }
    }
    Ok(())
}

fn create_process_by_pm(system: &mut System, pm: &ProcessManifest) -> JuizResult<ProcessPtr> {
    let type_name = pm.type_name.clone();
    let prof = system.core_broker().lock_mut()?.process_create(ProcessManifest::new(type_name.as_str()).name(format!("{}0", type_name).as_str()))?;
    let pid = Some(obj_get_str(&prof, "identifier")?.to_owned());
    system.core_broker().lock_mut()?.worker_mut().process_from_identifier(&pid.unwrap())
}

fn create_container_by_cm(system: &mut System, cm: &ContainerManifest) -> JuizResult<ContainerPtr> {
    let type_name = cm.type_name.clone();
    let name = format!("{}0", type_name);
    let  mut cp = CapsuleMap::new();
    cp.insert("name".to_owned(), jvalue!(name).into());
    cp.insert("type_name".to_owned(), jvalue!(type_name).into());
    let cont_prof = system.core_broker().lock_mut()?.container_create(cp)?;
    let container_id = Some(obj_get_str(&cont_prof, "identifier")?.to_owned());
    system.core_broker().lock_mut()?.worker_mut().container_from_identifier(&container_id.unwrap())
}

fn create_container_process_by_cid_and_pm(system: &mut System, cid: Identifier, pm: &ProcessManifest) -> JuizResult<ProcessPtr> {
    let type_name = pm.type_name.clone();
    let prof = system.core_broker().lock_mut()?.container_process_create(&cid, ProcessManifest::new(type_name.as_str()).name(format!("{}0", type_name).as_str()))?;
    let pid = Some(obj_get_str(&prof, "identifier")?.to_owned());
    system.core_broker().lock_mut()?.worker_mut().any_process_from_identifier(&pid.unwrap())
}

fn main() -> () {
    env_logger::init();
    match do_once() {
        Ok(_) => (),
        Err(e) => println!("Error:{:?}", e)
    }
}

fn do_once() -> JuizResult<()>{
    log::trace!("main::do_once called");
    let args = Args::parse();
    let manifest = yaml_conf_load(args.filepath.clone())?;
    let flag_start = if args.daemonize { true } else { args.start_http_broker };
    let manifest_filepath = PathBuf::from(args.filepath.as_str().to_string());
    let working_dir = manifest_filepath.parent().unwrap();
    let server = args.server.clone();
    // サブコマンドが指定されていない場合は単純に起動。
    if args.subcommand.is_none() {
        if args.daemonize {
            return System::new(manifest)?
                .set_working_dir(working_dir)
                .start_http_broker(flag_start)
                .setup()?
                .add_subsystem_by_id(server)?
                .run_and_do(|system| { 
                    do_task(system, args)
                });
        } else {
            return System::new(manifest)?
                .set_working_dir(working_dir)
                .start_http_broker(flag_start)
                .setup()?
                .add_subsystem_by_id(server)?
                .run_and_do_once(|system| {
                    do_task_once(system, args)
                });
        }
    }
    // サブコマンドがある場合
    let command = args.clone().subcommand.unwrap();
    match command {
        SubCommands::Setup{ subcommand } => { 
            on_setup(manifest, subcommand, args)
        },
        SubCommands::Process { subcommand } => {
            on_process(manifest, working_dir, subcommand, args)
        },
        SubCommands::Container { subcommand } => {
            on_container(manifest, working_dir, subcommand, args)
        },
        SubCommands::ContainerProcess { subcommand } => {
            on_container_process(manifest, working_dir, subcommand, args)
        },
        SubCommands::Ec { subcommand } => {
            on_execution_context(manifest, working_dir, subcommand, args)
        },
        /* _ => {
            return Ok(())
        } */
    }
}