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
|
use crate::get_store;
use crate::plugins::plugin_map::{PluginEnv, PluginMap, RunningPlugin, Subscriptions};
use crate::plugins::plugin_worker::{plugin_worker, RunningWorker};
use crate::plugins::zellij_exports::{wasi_write_object, zellij_exports};
use crate::plugins::PluginId;
use highway::{HighwayHash, PortableHash};
use log::info;
use std::{
collections::{HashMap, HashSet},
fs,
path::PathBuf,
sync::{Arc, Mutex},
};
use url::Url;
use wasmer::{AsStoreRef, Instance, Module, Store};
use wasmer_wasi::{Pipe, WasiState};
use zellij_utils::prost::Message;
use crate::{
logging_pipe::LoggingPipe, screen::ScreenInstruction, thread_bus::ThreadSenders,
ui::loading_indication::LoadingIndication, ClientId,
};
use zellij_utils::plugin_api::action::ProtobufPluginConfiguration;
use zellij_utils::{
consts::{ZELLIJ_CACHE_DIR, ZELLIJ_SESSION_CACHE_DIR, ZELLIJ_TMP_DIR},
data::PluginCapabilities,
errors::prelude::*,
input::command::TerminalAction,
input::layout::Layout,
input::plugins::PluginConfig,
ipc::ClientAttributes,
pane_size::Size,
};
macro_rules! display_loading_stage {
($loading_stage:ident, $loading_indication:expr, $senders:expr, $plugin_id:expr) => {{
$loading_indication.$loading_stage();
drop(
$senders.send_to_screen(ScreenInstruction::UpdatePluginLoadingStage(
$plugin_id,
$loading_indication.clone(),
)),
);
}};
}
pub struct PluginLoader<'a> {
plugin_cache: Arc<Mutex<HashMap<PathBuf, Module>>>,
plugin_path: PathBuf,
loading_indication: &'a mut LoadingIndication,
senders: ThreadSenders,
plugin_id: PluginId,
client_id: ClientId,
store: Arc<Mutex<Store>>,
plugin: PluginConfig,
plugin_dir: &'a PathBuf,
tab_index: usize,
plugin_own_data_dir: PathBuf,
size: Size,
wasm_blob_on_hd: Option<(Vec<u8>, PathBuf)>,
path_to_default_shell: PathBuf,
zellij_cwd: PathBuf,
capabilities: PluginCapabilities,
client_attributes: ClientAttributes,
default_shell: Option<TerminalAction>,
default_layout: Box<Layout>,
}
impl<'a> PluginLoader<'a> {
pub fn reload_plugin_from_memory(
plugin_id: PluginId,
plugin_dir: PathBuf,
plugin_cache: Arc<Mutex<HashMap<PathBuf, Module>>>,
senders: ThreadSenders,
store: Arc<Mutex<Store>>,
plugin_map: Arc<Mutex<PluginMap>>,
connected_clients: Arc<Mutex<Vec<ClientId>>>,
loading_indication: &mut LoadingIndication,
path_to_default_shell: PathBuf,
zellij_cwd: PathBuf,
capabilities: PluginCapabilities,
client_attributes: ClientAttributes,
default_shell: Option<TerminalAction>,
default_layout: Box<Layout>,
) -> Result<()> {
let err_context = || format!("failed to reload plugin {plugin_id} from memory");
let mut connected_clients: Vec<ClientId> =
connected_clients.lock().unwrap().iter().copied().collect();
if connected_clients.is_empty() {
return Err(anyhow!("No connected clients, cannot reload plugin"));
}
let first_client_id = connected_clients.remove(0);
let mut plugin_loader = PluginLoader::new_from_existing_plugin_attributes(
&plugin_cache,
&plugin_map,
loading_indication,
&senders,
plugin_id,
first_client_id,
store,
&plugin_dir,
path_to_default_shell,
zellij_cwd,
capabilities,
client_attributes,
default_shell,
default_layout,
)?;
plugin_loader
.load_module_from_memory()
.and_then(|module| plugin_loader.create_plugin_environment(module))
.and_then(|(store, instance, plugin_env, subscriptions)| {
plugin_loader.load_plugin_instance(
store,
&instance,
&plugin_env,
&plugin_map,
&subscriptions,
)
})
.and_then(|_| {
plugin_loader.clone_instance_for_other_clients(&connected_clients, &plugin_map)
})
.with_context(err_context)?;
display_loading_stage!(end, loading_indication, senders, plugin_id);
Ok(())
}
pub fn start_plugin(
plugin_id: PluginId,
client_id: ClientId,
plugin: &PluginConfig,
tab_index: usize,
plugin_dir: PathBuf,
plugin_cache: Arc<Mutex<HashMap<PathBuf, Module>>>,
senders: ThreadSenders,
store: Arc<Mutex<Store>>,
plugin_map: Arc<Mutex<PluginMap>>,
size: Size,
connected_clients: Arc<Mutex<Vec<ClientId>>>,
loading_indication: &mut LoadingIndication,
path_to_default_shell: PathBuf,
zellij_cwd: PathBuf,
capabilities: PluginCapabilities,
client_attributes: ClientAttributes,
default_shell: Option<TerminalAction>,
default_layout: Box<Layout>,
) -> Result<()> {
let err_context = || format!("failed to start plugin {plugin_id} for client {client_id}");
let mut plugin_loader = PluginLoader::new(
&plugin_cache,
loading_indication,
&senders,
plugin_id,
client_id,
store.clone(),
plugin.clone(),
&plugin_dir,
tab_index,
size,
path_to_default_shell,
zellij_cwd,
capabilities,
client_attributes,
default_shell,
default_layout,
)?;
plugin_loader
.load_module_from_memory()
.or_else(|_e| plugin_loader.load_module_from_hd_cache())
.or_else(|_e| plugin_loader.compile_module())
.and_then(|module| plugin_loader.create_plugin_environment(module))
.and_then(|(store, instance, plugin_env, subscriptions)| {
plugin_loader.load_plugin_instance(
store,
&instance,
&plugin_env,
&plugin_map,
&subscriptions,
)
})
.and_then(|_| {
plugin_loader.clone_instance_for_other_clients(
&connected_clients.lock().unwrap(),
&plugin_map,
)
})
.with_context(err_context)?;
display_loading_stage!(end, loading_indication, senders, plugin_id);
Ok(())
}
pub fn add_client(
client_id: ClientId,
plugin_dir: PathBuf,
plugin_cache: Arc<Mutex<HashMap<PathBuf, Module>>>,
senders: ThreadSenders,
store: Arc<Mutex<Store>>,
plugin_map: Arc<Mutex<PluginMap>>,
connected_clients: Arc<Mutex<Vec<ClientId>>>,
loading_indication: &mut LoadingIndication,
path_to_default_shell: PathBuf,
zellij_cwd: PathBuf,
capabilities: PluginCapabilities,
client_attributes: ClientAttributes,
default_shell: Option<TerminalAction>,
default_layout: Box<Layout>,
) -> Result<()> {
let mut new_plugins = HashSet::new();
for plugin_id in plugin_map.lock().unwrap().plugin_ids() {
new_plugins.insert((plugin_id, client_id));
}
for (plugin_id, existing_client_id) in new_plugins {
let mut plugin_loader = PluginLoader::new_from_different_client_id(
&plugin_cache,
&plugin_map,
loading_indication,
&senders,
plugin_id,
existing_client_id,
store.clone(),
&plugin_dir,
path_to_default_shell.clone(),
zellij_cwd.clone(),
capabilities.clone(),
client_attributes.clone(),
default_shell.clone(),
default_layout.clone(),
)?;
plugin_loader
.load_module_from_memory()
.and_then(|module| plugin_loader.create_plugin_environment(module))
.and_then(|(store, instance, plugin_env, subscriptions)| {
plugin_loader.load_plugin_instance(
store,
&instance,
&plugin_env,
&plugin_map,
&subscriptions,
)
})?
}
connected_clients.lock().unwrap().push(client_id);
Ok(())
}
pub fn reload_plugin(
plugin_id: PluginId,
plugin_dir: PathBuf,
plugin_cache: Arc<Mutex<HashMap<PathBuf, Module>>>,
senders: ThreadSenders,
store: Arc<Mutex<Store>>,
plugin_map: Arc<Mutex<PluginMap>>,
connected_clients: Arc<Mutex<Vec<ClientId>>>,
loading_indication: &mut LoadingIndication,
path_to_default_shell: PathBuf,
zellij_cwd: PathBuf,
capabilities: PluginCapabilities,
client_attributes: ClientAttributes,
default_shell: Option<TerminalAction>,
default_layout: Box<Layout>,
) -> Result<()> {
let err_context = || format!("failed to reload plugin id {plugin_id}");
let mut connected_clients: Vec<ClientId> =
connected_clients.lock().unwrap().iter().copied().collect();
if connected_clients.is_empty() {
return Err(anyhow!("No connected clients, cannot reload plugin"));
}
let first_client_id = connected_clients.remove(0);
let mut plugin_loader = PluginLoader::new_from_existing_plugin_attributes(
&plugin_cache,
&plugin_map,
loading_indication,
&senders,
plugin_id,
first_client_id,
store.clone(),
&plugin_dir,
path_to_default_shell,
zellij_cwd,
capabilities,
client_attributes,
default_shell,
default_layout,
)?;
plugin_loader
.compile_module()
.and_then(|module| plugin_loader.create_plugin_environment(module))
.and_then(|(store, instance, plugin_env, subscriptions)| {
plugin_loader.load_plugin_instance(
store,
&instance,
&plugin_env,
&plugin_map,
&subscriptions,
)
})
.and_then(|_| {
plugin_loader.clone_instance_for_other_clients(&connected_clients, &plugin_map)
})
.with_context(err_context)?;
display_loading_stage!(end, loading_indication, senders, plugin_id);
Ok(())
}
pub fn new(
plugin_cache: &Arc<Mutex<HashMap<PathBuf, Module>>>,
loading_indication: &'a mut LoadingIndication,
senders: &ThreadSenders,
plugin_id: PluginId,
client_id: ClientId,
store: Arc<Mutex<Store>>,
plugin: PluginConfig,
plugin_dir: &'a PathBuf,
tab_index: usize,
size: Size,
path_to_default_shell: PathBuf,
zellij_cwd: PathBuf,
capabilities: PluginCapabilities,
client_attributes: ClientAttributes,
default_shell: Option<TerminalAction>,
default_layout: Box<Layout>,
) -> Result<Self> {
let plugin_own_data_dir = ZELLIJ_SESSION_CACHE_DIR
.join(Url::from(&plugin.location).to_string())
.join(format!("{}-{}", plugin_id, client_id));
create_plugin_fs_entries(&plugin_own_data_dir)?;
let plugin_path = plugin.path.clone();
Ok(PluginLoader {
plugin_cache: plugin_cache.clone(),
plugin_path,
loading_indication,
senders: senders.clone(),
plugin_id,
client_id,
store: store.clone(),
plugin,
plugin_dir,
tab_index,
plugin_own_data_dir,
size,
wasm_blob_on_hd: None,
path_to_default_shell,
zellij_cwd,
capabilities,
client_attributes,
default_shell,
default_layout,
})
}
pub fn new_from_existing_plugin_attributes(
plugin_cache: &Arc<Mutex<HashMap<PathBuf, Module>>>,
plugin_map: &Arc<Mutex<PluginMap>>,
loading_indication: &'a mut LoadingIndication,
senders: &ThreadSenders,
plugin_id: PluginId,
client_id: ClientId,
store: Arc<Mutex<Store>>,
plugin_dir: &'a PathBuf,
path_to_default_shell: PathBuf,
zellij_cwd: PathBuf,
capabilities: PluginCapabilities,
client_attributes: ClientAttributes,
default_shell: Option<TerminalAction>,
default_layout: Box<Layout>,
) -> Result<Self> {
let err_context = || "Failed to find existing plugin";
let (running_plugin, _subscriptions, _workers) = {
let mut plugin_map = plugin_map.lock().unwrap();
plugin_map
.remove_single_plugin(plugin_id, client_id)
.with_context(err_context)?
};
let running_plugin = running_plugin.lock().unwrap();
let tab_index = running_plugin.plugin_env.tab_index;
let size = Size {
rows: running_plugin.rows,
cols: running_plugin.columns,
};
let plugin_config = running_plugin.plugin_env.plugin.clone();
loading_indication.set_name(running_plugin.plugin_env.name());
PluginLoader::new(
plugin_cache,
loading_indication,
senders,
plugin_id,
client_id,
store,
plugin_config,
plugin_dir,
tab_index,
size,
path_to_default_shell,
zellij_cwd,
capabilities,
client_attributes,
default_shell,
default_layout,
)
}
pub fn new_from_different_client_id(
plugin_cache: &Arc<Mutex<HashMap<PathBuf, Module>>>,
plugin_map: &Arc<Mutex<PluginMap>>,
loading_indication: &'a mut LoadingIndication,
senders: &ThreadSenders,
plugin_id: PluginId,
client_id: ClientId,
store: Arc<Mutex<Store>>,
plugin_dir: &'a PathBuf,
path_to_default_shell: PathBuf,
zellij_cwd: PathBuf,
capabilities: PluginCapabilities,
client_attributes: ClientAttributes,
default_shell: Option<TerminalAction>,
default_layout: Box<Layout>,
) -> Result<Self> {
let err_context = || "Failed to find existing plugin";
let running_plugin = {
let plugin_map = plugin_map.lock().unwrap();
plugin_map
.get_running_plugin(plugin_id, None)
.with_context(err_context)?
.clone()
};
let running_plugin = running_plugin.lock().unwrap();
let tab_index = running_plugin.plugin_env.tab_index;
let size = Size {
rows: running_plugin.rows,
cols: running_plugin.columns,
};
let plugin_config = running_plugin.plugin_env.plugin.clone();
loading_indication.set_name(running_plugin.plugin_env.name());
PluginLoader::new(
plugin_cache,
loading_indication,
senders,
plugin_id,
client_id,
store.clone(),
plugin_config,
plugin_dir,
tab_index,
size,
path_to_default_shell,
zellij_cwd,
capabilities,
client_attributes,
default_shell,
default_layout,
)
}
pub fn load_module_from_memory(&mut self) -> Result<Module> {
display_loading_stage!(
indicate_loading_plugin_from_memory,
self.loading_indication,
self.senders,
self.plugin_id
);
let module = self
.plugin_cache
.lock()
.unwrap()
.remove(&self.plugin_path)
.ok_or(anyhow!("Plugin is not stored in memory"))?;
display_loading_stage!(
indicate_loading_plugin_from_memory_success,
self.loading_indication,
self.senders,
self.plugin_id
);
Ok(module)
}
pub fn load_module_from_hd_cache(&mut self) -> Result<Module> {
display_loading_stage!(
indicate_loading_plugin_from_memory_notfound,
self.loading_indication,
self.senders,
self.plugin_id
);
display_loading_stage!(
indicate_loading_plugin_from_hd_cache,
self.loading_indication,
self.senders,
self.plugin_id
);
let (_wasm_bytes, cached_path) = self.plugin_bytes_and_cache_path()?;
let timer = std::time::Instant::now();
let module = unsafe {
Module::deserialize_from_file(&self.store.lock().unwrap().as_store_ref(), &cached_path)?
};
log::info!(
"Loaded plugin '{}' from cache folder at '{}' in {:?}",
self.plugin_path.display(),
ZELLIJ_CACHE_DIR.display(),
timer.elapsed(),
);
display_loading_stage!(
indicate_loading_plugin_from_hd_cache_success,
self.loading_indication,
self.senders,
self.plugin_id
);
Ok(module)
}
pub fn compile_module(&mut self) -> Result<Module> {
display_loading_stage!(
indicate_loading_plugin_from_hd_cache_notfound,
self.loading_indication,
self.senders,
self.plugin_id
);
display_loading_stage!(
indicate_compiling_plugin,
self.loading_indication,
self.senders,
self.plugin_id
);
let (wasm_bytes, cached_path) = self.plugin_bytes_and_cache_path()?;
let timer = std::time::Instant::now();
let err_context = || "failed to recover cache dir";
let module = fs::create_dir_all(ZELLIJ_CACHE_DIR.to_owned())
.map_err(anyError::new)
.and_then(|_| {
// compile module
Module::new(&self.store.lock().unwrap().as_store_ref(), &wasm_bytes)
.map_err(anyError::new)
})
.and_then(|m| {
// serialize module to HD cache for faster loading in the future
m.serialize_to_file(&cached_path).map_err(anyError::new)?;
log::info!(
"Compiled plugin '{}' in {:?}",
self.plugin_path.display(),
timer.elapsed()
);
Ok(m)
})
.with_context(err_context)?;
Ok(module)
}
pub fn create_plugin_environment(
&mut self,
module: Module,
) -> Result<(Store, Instance, PluginEnv, Arc<Mutex<Subscriptions>>)> {
let (store, instance, plugin_env, subscriptions) =
self.create_plugin_instance_env_and_subscriptions(&module)?;
// Only do an insert when everything went well!
let cloned_plugin = self.plugin.clone();
self.plugin_cache
.lock()
.unwrap()
.insert(cloned_plugin.path, module);
Ok((store, instance, plugin_env, subscriptions))
}
pub fn create_plugin_instance_and_wasi_env_for_worker(
&mut self,
) -> Result<(Store, Instance, PluginEnv)> {
let err_context = || {
format!(
"Failed to create instance and plugin env for worker {}",
self.plugin_id
)
};
let module = self
.plugin_cache
.lock()
.unwrap()
.get(&self.plugin.path)
.with_context(err_context)?
.clone();
let (store, instance, plugin_env, _subscriptions) =
self.create_plugin_instance_env_and_subscriptions(&module)?;
Ok((store, instance, plugin_env))
}
pub fn load_plugin_instance(
&mut self,
store: Store,
instance: &Instance,
plugin_env: &PluginEnv,
plugin_map: &Arc<Mutex<PluginMap>>,
subscriptions: &Arc<Mutex<Subscriptions>>,
) -> Result<()> {
let err_context = || format!("failed to load plugin from instance {instance:#?}");
let main_user_instance = instance.clone();
let main_user_env = plugin_env.clone();
display_loading_stage!(
indicate_starting_plugin,
self.loading_indication,
self.senders,
self.plugin_id
);
let start_function = instance
.exports
.get_function("_start")
.with_context(err_context)?;
let load_function = instance
.exports
.get_function("load")
.with_context(err_context)?;
let mut workers = HashMap::new();
for (function_name, _exported_function) in instance.exports.iter().functions() {
if function_name.ends_with("_worker") {
let plugin_config = self.plugin.clone();
let (mut store, instance, plugin_env) =
self.create_plugin_instance_and_wasi_env_for_worker()?;
let start_function_for_worker = instance
.exports
.get_function("_start")
.with_context(err_context)?;
start_function_for_worker
.call(&mut store, &[])
.with_context(err_context)?;
let worker =
RunningWorker::new(store, instance, &function_name, plugin_config, plugin_env);
let worker_sender = plugin_worker(worker);
workers.insert(function_name.into(), worker_sender);
}
}
let plugin = Arc::new(Mutex::new(RunningPlugin::new(
store,
main_user_instance,
main_user_env,
self.size.rows,
self.size.cols,
)));
plugin_map.lock().unwrap().insert(
self.plugin_id,
self.client_id,
plugin.clone(),
subscriptions.clone(),
workers,
);
start_function
.call(&mut plugin.lock().unwrap().store, &[])
.with_context(err_context)?;
let protobuf_plugin_configuration: ProtobufPluginConfiguration = self
.plugin
.userspace_configuration
.clone()
.try_into()
.map_err(|e| anyhow!("Failed to serialize user configuration: {:?}", e))?;
let protobuf_bytes = protobuf_plugin_configuration.encode_to_vec();
wasi_write_object(
&plugin_env.wasi_env,
&protobuf_bytes,
// &self.plugin.userspace_configuration.inner(),
)
.with_context(err_context)?;
load_function
.call(&mut plugin.lock().unwrap().store, &[])
.with_context(err_context)?;
display_loading_stage!(
indicate_starting_plugin_success,
self.loading_indication,
self.senders,
self.plugin_id
);
display_loading_stage!(
indicate_writing_plugin_to_cache,
self.loading_indication,
self.senders,
self.plugin_id
);
display_loading_stage!(
indicate_writing_plugin_to_cache_success,
self.loading_indication,
self.senders,
self.plugin_id
);
Ok(())
}
pub fn clone_instance_for_other_clients(
&mut self,
connected_clients: &[ClientId],
plugin_map: &Arc<Mutex<PluginMap>>,
) -> Result<()> {
if !connected_clients.is_empty() {
display_loading_stage!(
indicate_cloning_plugin_for_other_clients,
self.loading_indication,
self.senders,
self.plugin_id
);
for client_id in connected_clients {
if client_id == &self.client_id {
// don't reload the plugin once more for ourselves
continue;
}
let mut loading_indication = LoadingIndication::new("".into());
let mut plugin_loader_for_client = PluginLoader::new_from_different_client_id(
&self.plugin_cache.clone(),
&plugin_map,
&mut loading_indication,
&self.senders.clone(),
self.plugin_id,
*client_id,
self.store.clone(),
&self.plugin_dir,
self.path_to_default_shell.clone(),
self.zellij_cwd.clone(),
self.capabilities.clone(),
self.client_attributes.clone(),
self.default_shell.clone(),
self.default_layout.clone(),
)?;
plugin_loader_for_client
.load_module_from_memory()
.and_then(|module| plugin_loader_for_client.create_plugin_environment(module))
.and_then(|(store, instance, plugin_env, subscriptions)| {
plugin_loader_for_client.load_plugin_instance(
store,
&instance,
&plugin_env,
plugin_map,
&subscriptions,
)
})?
}
display_loading_stage!(
indicate_cloning_plugin_for_other_clients_success,
self.loading_indication,
self.senders,
self.plugin_id
);
}
Ok(())
}
fn plugin_bytes_and_cache_path(&mut self) -> Result<(Vec<u8>, PathBuf)> {
match self.wasm_blob_on_hd.as_ref() {
Some((wasm_bytes, cached_path)) => Ok((wasm_bytes.clone(), cached_path.clone())),
None => {
if self.plugin._allow_exec_host_cmd {
info!(
"Plugin({:?}) is able to run any host command, this may lead to some security issues!",
self.plugin.path
);
}
// The plugins blob as stored on the filesystem
let wasm_bytes = self.plugin.resolve_wasm_bytes(&self.plugin_dir)?;
let hash: String = PortableHash::default()
.hash256(&wasm_bytes)
.iter()
.map(ToString::to_string)
.collect();
let cached_path = ZELLIJ_CACHE_DIR.join(&hash);
self.wasm_blob_on_hd = Some((wasm_bytes.clone(), cached_path.clone()));
Ok((wasm_bytes, cached_path))
},
}
}
fn create_plugin_instance_env_and_subscriptions(
&self,
module: &Module,
) -> Result<(Store, Instance, PluginEnv, Arc<Mutex<Subscriptions>>)> {
let err_context = || {
format!(
"Failed to create instance, plugin env and subscriptions for plugin {}",
self.plugin_id
)
};
let mut store = get_store();
let store_mut = &mut store;
let mut wasi_env = WasiState::new("Zellij")
.env("CLICOLOR_FORCE", "1")
.map_dir("/host", self.zellij_cwd.clone())
.and_then(|wasi| wasi.map_dir("/data", &self.plugin_own_data_dir))
.and_then(|wasi| wasi.map_dir("/tmp", ZELLIJ_TMP_DIR.as_path()))
.and_then(|wasi| {
wasi.stdin(Box::new(Pipe::new()))
.stdout(Box::new(Pipe::new()))
.stderr(Box::new(LoggingPipe::new(
&self.plugin.location.to_string(),
self.plugin_id,
)))
.finalize(store_mut)
})
.with_context(err_context)?;
let wasi = wasi_env
.import_object(store_mut, &module)
.with_context(err_context)?;
let mut mut_plugin = self.plugin.clone();
mut_plugin.set_tab_index(self.tab_index);
let plugin_env = PluginEnv {
plugin_id: self.plugin_id,
client_id: self.client_id,
plugin: mut_plugin,
permissions: Arc::new(Mutex::new(None)),
senders: self.senders.clone(),
wasi_env: wasi_env.data_mut(store_mut).clone(),
plugin_own_data_dir: self.plugin_own_data_dir.clone(),
tab_index: self.tab_index,
path_to_default_shell: self.path_to_default_shell.clone(),
capabilities: self.capabilities.clone(),
client_attributes: self.client_attributes.clone(),
default_shell: self.default_shell.clone(),
default_layout: self.default_layout.clone(),
};
let subscriptions = Arc::new(Mutex::new(HashSet::new()));
let mut zellij = zellij_exports(store_mut, &plugin_env, &subscriptions);
zellij.extend(&wasi);
let instance = Instance::new(store_mut, &module, &zellij).with_context(err_context)?;
wasi_env.initialize(store_mut, &instance)?;
Ok((store, instance, plugin_env, subscriptions))
}
}
fn create_plugin_fs_entries(plugin_own_data_dir: &PathBuf) -> Result<()> {
let err_context = || "failed to create plugin fs entries";
// Create filesystem entries mounted into WASM.
// We create them here to get expressive error messages in case they fail.
fs::create_dir_all(&plugin_own_data_dir)
.with_context(|| format!("failed to create datadir in {plugin_own_data_dir:?}"))
.with_context(err_context)?;
fs::create_dir_all(ZELLIJ_TMP_DIR.as_path())
.with_context(|| format!("failed to create tmpdir at {:?}", &ZELLIJ_TMP_DIR.as_path()))
.with_context(err_context)?;
Ok(())
}
|