itsi-scheduler 0.2.18 → 0.2.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. checksums.yaml +4 -4
  2. data/Cargo.lock +1 -1
  3. data/ext/itsi_scheduler/Cargo.toml +1 -1
  4. data/ext/itsi_scheduler/extconf.rb +7 -4
  5. data/ext/itsi_server/Cargo.toml +1 -1
  6. data/ext/itsi_server/src/server/serve_strategy/cluster_mode.rs +5 -1
  7. data/ext/itsi_server/src/server/signal.rs +34 -12
  8. data/lib/itsi/scheduler/version.rb +1 -1
  9. metadata +2 -32
  10. data/ext/itsi_error/target/debug/build/clang-sys-da71b0344e568175/out/common.rs +0 -355
  11. data/ext/itsi_error/target/debug/build/clang-sys-da71b0344e568175/out/dynamic.rs +0 -276
  12. data/ext/itsi_error/target/debug/build/clang-sys-da71b0344e568175/out/macros.rs +0 -49
  13. data/ext/itsi_error/target/debug/build/rb-sys-49f554618693db24/out/bindings-0.9.110-mri-arm64-darwin23-3.4.2.rs +0 -8865
  14. data/ext/itsi_error/target/debug/incremental/itsi_error-1mmt5sux7jb0i/s-h510z7m8v9-0bxu7yd.lock +0 -0
  15. data/ext/itsi_error/target/debug/incremental/itsi_error-2vn3jey74oiw0/s-h5113n0e7e-1v5qzs6.lock +0 -0
  16. data/ext/itsi_error/target/debug/incremental/itsi_error-37uv9dicz7awp/s-h510ykifhe-0tbnep2.lock +0 -0
  17. data/ext/itsi_error/target/debug/incremental/itsi_error-37uv9dicz7awp/s-h510yyocpj-0tz7ug7.lock +0 -0
  18. data/ext/itsi_error/target/debug/incremental/itsi_error-37uv9dicz7awp/s-h510z0xc8g-14ol18k.lock +0 -0
  19. data/ext/itsi_error/target/debug/incremental/itsi_error-3g5qf4y7d54uj/s-h5113n0e7d-1trk8on.lock +0 -0
  20. data/ext/itsi_error/target/debug/incremental/itsi_error-3lpfftm45d3e2/s-h510z7m8r3-1pxp20o.lock +0 -0
  21. data/ext/itsi_error/target/debug/incremental/itsi_error-3o4qownhl3d7n/s-h510ykifek-1uxasnk.lock +0 -0
  22. data/ext/itsi_error/target/debug/incremental/itsi_error-3o4qownhl3d7n/s-h510yyocki-11u37qm.lock +0 -0
  23. data/ext/itsi_error/target/debug/incremental/itsi_error-3o4qownhl3d7n/s-h510z0xc93-0pmy0zm.lock +0 -0
  24. data/ext/itsi_rb_helpers/target/debug/build/clang-sys-da71b0344e568175/out/common.rs +0 -355
  25. data/ext/itsi_rb_helpers/target/debug/build/clang-sys-da71b0344e568175/out/dynamic.rs +0 -276
  26. data/ext/itsi_rb_helpers/target/debug/build/clang-sys-da71b0344e568175/out/macros.rs +0 -49
  27. data/ext/itsi_rb_helpers/target/debug/build/rb-sys-eb9ed4ff3a60f995/out/bindings-0.9.110-mri-arm64-darwin23-3.4.2.rs +0 -8865
  28. data/ext/itsi_rb_helpers/target/debug/incremental/itsi_rb_helpers-040pxg6yhb3g3/s-h5113n7a1b-03bwlt4.lock +0 -0
  29. data/ext/itsi_rb_helpers/target/debug/incremental/itsi_rb_helpers-131g1u4dzkt1a/s-h51113xnh3-1eik1ip.lock +0 -0
  30. data/ext/itsi_rb_helpers/target/debug/incremental/itsi_rb_helpers-131g1u4dzkt1a/s-h5111704jj-0g4rj8x.lock +0 -0
  31. data/ext/itsi_rb_helpers/target/debug/incremental/itsi_rb_helpers-1q2d3drtxrzs5/s-h5113n79yl-0bxcqc5.lock +0 -0
  32. data/ext/itsi_rb_helpers/target/debug/incremental/itsi_rb_helpers-374a9h7ovycj0/s-h51113xoox-10de2hp.lock +0 -0
  33. data/ext/itsi_rb_helpers/target/debug/incremental/itsi_rb_helpers-374a9h7ovycj0/s-h5111704w7-0vdq7gq.lock +0 -0
  34. data/ext/itsi_tracing/target/debug/incremental/itsi_tracing-0994n8rpvvt9m/s-h510hfz1f6-1kbycmq.lock +0 -0
  35. data/ext/itsi_tracing/target/debug/incremental/itsi_tracing-0bob7bf4yq34i/s-h5113125h5-0lh4rag.lock +0 -0
  36. data/ext/itsi_tracing/target/debug/incremental/itsi_tracing-2fcodulrxbbxo/s-h510h2infk-0hp5kjw.lock +0 -0
  37. data/ext/itsi_tracing/target/debug/incremental/itsi_tracing-2iak63r1woi1l/s-h510h2in4q-0kxfzw1.lock +0 -0
  38. data/ext/itsi_tracing/target/debug/incremental/itsi_tracing-2kk4qj9gn5dg2/s-h5113124kv-0enwon2.lock +0 -0
  39. data/ext/itsi_tracing/target/debug/incremental/itsi_tracing-2mwo0yas7dtw4/s-h510hfz1ha-1udgpei.lock +0 -0
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: fac0124df4d981948e915496a34f6d508c9d8c68fc13286d7a6400927e2cd3d1
4
- data.tar.gz: 860ac83fee517bdef9291ba85119bca438e3c21ed04b1cac759f3e8d86a3cc39
3
+ metadata.gz: 76b92c7f107bc7d654a167f20894d1620aac46f99fcbd71762046bc470c54340
4
+ data.tar.gz: 6c7de92626beb50c4e0966213f6be45098f0d2e8229d6e683460c8af5aaf548e
5
5
  SHA512:
6
- metadata.gz: 6a8d221f21d7dba3cea0659e350b378534ac1720471c2d132e85402920940065e0fca70fecaba35890654ec57da91283090ad7b771f4dcd016ee5c057e99aeae
7
- data.tar.gz: a0ac27575945761c81cc0c613da84fb7c8efd1be5d3aed3f3db4436668994d1d838ab29f49e578bf50c2f70c1aa86c456863ce36cf64ee0c3db4a1aadef542a3
6
+ metadata.gz: 05f07e2cb3bd393b5d9561779d236055d14e851131eff1926d06170731c282a0aaf8e33b4d95fc5b809d28525d3af538b9a11a08da3c23d14e3fea0dc68de480
7
+ data.tar.gz: 0f243dcbffe1c137874733a9f08f98922d6fec72b2d34b42046edd2f872c6e5a95d1bc5073f8b87ecd70a20a912b72e222dfe12b837fccc8f49edb04ad188637
data/Cargo.lock CHANGED
@@ -213,7 +213,7 @@ checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c"
213
213
 
214
214
  [[package]]
215
215
  name = "itsi-scheduler"
216
- version = "0.2.18"
216
+ version = "0.2.20"
217
217
  dependencies = [
218
218
  "bytes",
219
219
  "derive_more",
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "itsi-scheduler"
3
- version = "0.2.18"
3
+ version = "0.2.20"
4
4
  edition = "2021"
5
5
  authors = ["Wouter Coppieters <wc@pico.net.nz>"]
6
6
  license = "MIT"
@@ -1,8 +1,11 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require "mkmf"
4
- require "rb_sys/mkmf"
3
+ require 'mkmf'
4
+ require 'rb_sys/mkmf'
5
5
 
6
- create_rust_makefile("itsi/scheduler/itsi_scheduler") do |r|
7
- r.extra_rustflags = ["-C target-cpu=native"]
6
+ create_rust_makefile('itsi/scheduler/itsi_scheduler') do |r|
7
+ r.extra_rustflags = ['-C target-cpu=native']
8
+ r.env = {
9
+ 'BINDGEN_EXTRA_CLANG_ARGS' => '-include stdbool.h -std=c99'
10
+ }
8
11
  end
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "itsi-server"
3
- version = "0.2.18"
3
+ version = "0.2.20"
4
4
  edition = "2021"
5
5
  authors = ["Wouter Coppieters <wc@pico.net.nz>"]
6
6
  license = "MIT"
@@ -377,9 +377,13 @@ impl ClusterMode {
377
377
  }
378
378
  lifecycle_event = lifecycle_rx.recv() => match lifecycle_event{
379
379
  Ok(lifecycle_event) => {
380
+ debug!("Cluster mode received lifecycle event: {:?}", lifecycle_event);
380
381
  if let Err(e) = self_ref.clone().handle_lifecycle_event(lifecycle_event).await{
381
382
  match e {
382
- ItsiError::Break => break,
383
+ ItsiError::Break => {
384
+ debug!("Lifecycle event triggered shutdown, breaking cluster monitor loop");
385
+ break;
386
+ },
383
387
  _ => error!("Error in handle_lifecycle_event {:?}", e)
384
388
  }
385
389
  }
@@ -1,11 +1,12 @@
1
1
  use std::{
2
2
  collections::VecDeque,
3
- sync::atomic::{AtomicBool, AtomicI8},
3
+ sync::atomic::{AtomicBool, AtomicI8, Ordering},
4
4
  };
5
5
 
6
6
  use nix::libc::{self, sighandler_t};
7
7
  use parking_lot::Mutex;
8
8
  use tokio::sync::broadcast;
9
+ use tracing::{debug, warn};
9
10
 
10
11
  use super::lifecycle_event::LifecycleEvent;
11
12
 
@@ -21,12 +22,14 @@ pub fn subscribe_runtime_to_signals() -> broadcast::Receiver<LifecycleEvent> {
21
22
  if let Some(sender) = guard.as_ref() {
22
23
  return sender.subscribe();
23
24
  }
24
- let (sender, receiver) = broadcast::channel(5);
25
+ let (sender, receiver) = broadcast::channel(32);
25
26
  let sender_clone = sender.clone();
26
27
  std::thread::spawn(move || {
27
- std::thread::sleep(std::time::Duration::from_millis(50));
28
+ std::thread::sleep(std::time::Duration::from_millis(10));
28
29
  for event in PENDING_QUEUE.lock().drain(..) {
29
- sender_clone.send(event).ok();
30
+ if let Err(e) = sender_clone.send(event) {
31
+ eprintln!("Warning: Failed to send pending lifecycle event {:?}", e);
32
+ }
30
33
  }
31
34
  });
32
35
 
@@ -41,22 +44,36 @@ pub fn unsubscribe_runtime() {
41
44
 
42
45
  pub fn send_lifecycle_event(event: LifecycleEvent) {
43
46
  if let Some(sender) = SIGNAL_HANDLER_CHANNEL.lock().as_ref() {
44
- sender.send(event).ok();
47
+ if let Err(e) = sender.send(event) {
48
+ // Channel full or receivers dropped - this is a critical error for shutdown signals
49
+ eprintln!("Critical: Failed to send lifecycle event {:?}", e);
50
+ // For shutdown events, try to force exit if channel delivery fails
51
+ if matches!(
52
+ e.0,
53
+ LifecycleEvent::Shutdown | LifecycleEvent::ForceShutdown
54
+ ) {
55
+ eprintln!("Emergency shutdown due to signal delivery failure");
56
+ std::process::exit(1);
57
+ }
58
+ }
45
59
  } else {
46
60
  PENDING_QUEUE.lock().push_back(event);
47
61
  }
48
62
  }
49
63
 
50
64
  fn receive_signal(signum: i32, _: sighandler_t) {
51
- SIGINT_COUNT.fetch_add(-1, std::sync::atomic::Ordering::SeqCst);
65
+ debug!("Received signal: {}", signum);
66
+ SIGINT_COUNT.fetch_add(-1, Ordering::SeqCst);
52
67
  let event = match signum {
53
68
  libc::SIGTERM | libc::SIGINT => {
54
- SHUTDOWN_REQUESTED.store(true, std::sync::atomic::Ordering::SeqCst);
55
- SIGINT_COUNT.fetch_add(2, std::sync::atomic::Ordering::SeqCst);
56
- if SIGINT_COUNT.load(std::sync::atomic::Ordering::SeqCst) < 2 {
69
+ debug!("Received shutdown signal (SIGTERM/SIGINT)");
70
+ SHUTDOWN_REQUESTED.store(true, Ordering::SeqCst);
71
+ SIGINT_COUNT.fetch_add(2, Ordering::SeqCst);
72
+ if SIGINT_COUNT.load(Ordering::SeqCst) < 2 {
73
+ debug!("First shutdown signal, requesting graceful shutdown");
57
74
  Some(LifecycleEvent::Shutdown)
58
75
  } else {
59
- // Not messing about. Force shutdown.
76
+ warn!("Multiple shutdown signals received, forcing immediate shutdown");
60
77
  Some(LifecycleEvent::ForceShutdown)
61
78
  }
62
79
  }
@@ -70,13 +87,17 @@ fn receive_signal(signum: i32, _: sighandler_t) {
70
87
  };
71
88
 
72
89
  if let Some(event) = event {
90
+ debug!("Signal {} mapped to lifecycle event: {:?}", signum, event);
73
91
  send_lifecycle_event(event);
92
+ } else {
93
+ debug!("Signal {} not mapped to any lifecycle event", signum);
74
94
  }
75
95
  }
76
96
 
77
97
  pub fn reset_signal_handlers() -> bool {
78
- SIGINT_COUNT.store(0, std::sync::atomic::Ordering::SeqCst);
79
- SHUTDOWN_REQUESTED.store(false, std::sync::atomic::Ordering::SeqCst);
98
+ debug!("Resetting signal handlers");
99
+ SIGINT_COUNT.store(0, Ordering::SeqCst);
100
+ SHUTDOWN_REQUESTED.store(false, Ordering::SeqCst);
80
101
 
81
102
  unsafe {
82
103
  libc::signal(libc::SIGTERM, receive_signal as usize);
@@ -92,6 +113,7 @@ pub fn reset_signal_handlers() -> bool {
92
113
  }
93
114
 
94
115
  pub fn clear_signal_handlers() {
116
+ debug!("Clearing signal handlers");
95
117
  unsafe {
96
118
  libc::signal(libc::SIGTERM, libc::SIG_DFL);
97
119
  libc::signal(libc::SIGINT, libc::SIG_DFL);
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Itsi
4
4
  class Scheduler
5
- VERSION = "0.2.18"
5
+ VERSION = "0.2.20"
6
6
  end
7
7
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: itsi-scheduler
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.2.18
4
+ version: 0.2.20
5
5
  platform: ruby
6
6
  authors:
7
7
  - Wouter Coppieters
@@ -61,36 +61,12 @@ files:
61
61
  - ext/itsi_error/Cargo.lock
62
62
  - ext/itsi_error/Cargo.toml
63
63
  - ext/itsi_error/src/lib.rs
64
- - ext/itsi_error/target/debug/build/clang-sys-da71b0344e568175/out/common.rs
65
- - ext/itsi_error/target/debug/build/clang-sys-da71b0344e568175/out/dynamic.rs
66
- - ext/itsi_error/target/debug/build/clang-sys-da71b0344e568175/out/macros.rs
67
- - ext/itsi_error/target/debug/build/rb-sys-49f554618693db24/out/bindings-0.9.110-mri-arm64-darwin23-3.4.2.rs
68
- - ext/itsi_error/target/debug/incremental/itsi_error-1mmt5sux7jb0i/s-h510z7m8v9-0bxu7yd.lock
69
- - ext/itsi_error/target/debug/incremental/itsi_error-2vn3jey74oiw0/s-h5113n0e7e-1v5qzs6.lock
70
- - ext/itsi_error/target/debug/incremental/itsi_error-37uv9dicz7awp/s-h510ykifhe-0tbnep2.lock
71
- - ext/itsi_error/target/debug/incremental/itsi_error-37uv9dicz7awp/s-h510yyocpj-0tz7ug7.lock
72
- - ext/itsi_error/target/debug/incremental/itsi_error-37uv9dicz7awp/s-h510z0xc8g-14ol18k.lock
73
- - ext/itsi_error/target/debug/incremental/itsi_error-3g5qf4y7d54uj/s-h5113n0e7d-1trk8on.lock
74
- - ext/itsi_error/target/debug/incremental/itsi_error-3lpfftm45d3e2/s-h510z7m8r3-1pxp20o.lock
75
- - ext/itsi_error/target/debug/incremental/itsi_error-3o4qownhl3d7n/s-h510ykifek-1uxasnk.lock
76
- - ext/itsi_error/target/debug/incremental/itsi_error-3o4qownhl3d7n/s-h510yyocki-11u37qm.lock
77
- - ext/itsi_error/target/debug/incremental/itsi_error-3o4qownhl3d7n/s-h510z0xc93-0pmy0zm.lock
78
64
  - ext/itsi_instrument_entry/Cargo.toml
79
65
  - ext/itsi_instrument_entry/src/lib.rs
80
66
  - ext/itsi_rb_helpers/Cargo.lock
81
67
  - ext/itsi_rb_helpers/Cargo.toml
82
68
  - ext/itsi_rb_helpers/src/heap_value.rs
83
69
  - ext/itsi_rb_helpers/src/lib.rs
84
- - ext/itsi_rb_helpers/target/debug/build/clang-sys-da71b0344e568175/out/common.rs
85
- - ext/itsi_rb_helpers/target/debug/build/clang-sys-da71b0344e568175/out/dynamic.rs
86
- - ext/itsi_rb_helpers/target/debug/build/clang-sys-da71b0344e568175/out/macros.rs
87
- - ext/itsi_rb_helpers/target/debug/build/rb-sys-eb9ed4ff3a60f995/out/bindings-0.9.110-mri-arm64-darwin23-3.4.2.rs
88
- - ext/itsi_rb_helpers/target/debug/incremental/itsi_rb_helpers-040pxg6yhb3g3/s-h5113n7a1b-03bwlt4.lock
89
- - ext/itsi_rb_helpers/target/debug/incremental/itsi_rb_helpers-131g1u4dzkt1a/s-h51113xnh3-1eik1ip.lock
90
- - ext/itsi_rb_helpers/target/debug/incremental/itsi_rb_helpers-131g1u4dzkt1a/s-h5111704jj-0g4rj8x.lock
91
- - ext/itsi_rb_helpers/target/debug/incremental/itsi_rb_helpers-1q2d3drtxrzs5/s-h5113n79yl-0bxcqc5.lock
92
- - ext/itsi_rb_helpers/target/debug/incremental/itsi_rb_helpers-374a9h7ovycj0/s-h51113xoox-10de2hp.lock
93
- - ext/itsi_rb_helpers/target/debug/incremental/itsi_rb_helpers-374a9h7ovycj0/s-h5111704w7-0vdq7gq.lock
94
70
  - ext/itsi_scheduler/Cargo.toml
95
71
  - ext/itsi_scheduler/src/itsi_scheduler.rs
96
72
  - ext/itsi_scheduler/src/itsi_scheduler/io_helpers.rs
@@ -174,12 +150,6 @@ files:
174
150
  - ext/itsi_tracing/Cargo.lock
175
151
  - ext/itsi_tracing/Cargo.toml
176
152
  - ext/itsi_tracing/src/lib.rs
177
- - ext/itsi_tracing/target/debug/incremental/itsi_tracing-0994n8rpvvt9m/s-h510hfz1f6-1kbycmq.lock
178
- - ext/itsi_tracing/target/debug/incremental/itsi_tracing-0bob7bf4yq34i/s-h5113125h5-0lh4rag.lock
179
- - ext/itsi_tracing/target/debug/incremental/itsi_tracing-2fcodulrxbbxo/s-h510h2infk-0hp5kjw.lock
180
- - ext/itsi_tracing/target/debug/incremental/itsi_tracing-2iak63r1woi1l/s-h510h2in4q-0kxfzw1.lock
181
- - ext/itsi_tracing/target/debug/incremental/itsi_tracing-2kk4qj9gn5dg2/s-h5113124kv-0enwon2.lock
182
- - ext/itsi_tracing/target/debug/incremental/itsi_tracing-2mwo0yas7dtw4/s-h510hfz1ha-1udgpei.lock
183
153
  - itsi-scheduler-100.png
184
154
  - lib/itsi/schedule_refinement.rb
185
155
  - lib/itsi/scheduler.rb
@@ -205,7 +175,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
205
175
  - !ruby/object:Gem::Version
206
176
  version: 3.1.11
207
177
  requirements: []
208
- rubygems_version: 3.6.7
178
+ rubygems_version: 3.6.9
209
179
  specification_version: 4
210
180
  summary: Itsi Scheduler - A light-weight Fiber Scheduler implementation for Ruby.
211
181
  test_files: []
@@ -1,355 +0,0 @@
1
- // SPDX-License-Identifier: Apache-2.0
2
-
3
- use std::cell::RefCell;
4
- use std::collections::HashMap;
5
- use std::env;
6
- use std::path::{Path, PathBuf};
7
- use std::process::Command;
8
-
9
- use glob::{MatchOptions, Pattern};
10
-
11
- //================================================
12
- // Commands
13
- //================================================
14
-
15
- thread_local! {
16
- /// The errors encountered by the build script while executing commands.
17
- static COMMAND_ERRORS: RefCell<HashMap<String, Vec<String>>> = RefCell::default();
18
- }
19
-
20
- /// Adds an error encountered by the build script while executing a command.
21
- fn add_command_error(name: &str, path: &str, arguments: &[&str], message: String) {
22
- COMMAND_ERRORS.with(|e| {
23
- e.borrow_mut()
24
- .entry(name.into())
25
- .or_default()
26
- .push(format!(
27
- "couldn't execute `{} {}` (path={}) ({})",
28
- name,
29
- arguments.join(" "),
30
- path,
31
- message,
32
- ))
33
- });
34
- }
35
-
36
- /// A struct that prints the errors encountered by the build script while
37
- /// executing commands when dropped (unless explictly discarded).
38
- ///
39
- /// This is handy because we only want to print these errors when the build
40
- /// script fails to link to an instance of `libclang`. For example, if
41
- /// `llvm-config` couldn't be executed but an instance of `libclang` was found
42
- /// anyway we don't want to pollute the build output with irrelevant errors.
43
- #[derive(Default)]
44
- pub struct CommandErrorPrinter {
45
- discard: bool,
46
- }
47
-
48
- impl CommandErrorPrinter {
49
- pub fn discard(mut self) {
50
- self.discard = true;
51
- }
52
- }
53
-
54
- impl Drop for CommandErrorPrinter {
55
- fn drop(&mut self) {
56
- if self.discard {
57
- return;
58
- }
59
-
60
- let errors = COMMAND_ERRORS.with(|e| e.borrow().clone());
61
-
62
- if let Some(errors) = errors.get("llvm-config") {
63
- println!(
64
- "cargo:warning=could not execute `llvm-config` one or more \
65
- times, if the LLVM_CONFIG_PATH environment variable is set to \
66
- a full path to valid `llvm-config` executable it will be used \
67
- to try to find an instance of `libclang` on your system: {}",
68
- errors
69
- .iter()
70
- .map(|e| format!("\"{}\"", e))
71
- .collect::<Vec<_>>()
72
- .join("\n "),
73
- )
74
- }
75
-
76
- if let Some(errors) = errors.get("xcode-select") {
77
- println!(
78
- "cargo:warning=could not execute `xcode-select` one or more \
79
- times, if a valid instance of this executable is on your PATH \
80
- it will be used to try to find an instance of `libclang` on \
81
- your system: {}",
82
- errors
83
- .iter()
84
- .map(|e| format!("\"{}\"", e))
85
- .collect::<Vec<_>>()
86
- .join("\n "),
87
- )
88
- }
89
- }
90
- }
91
-
92
- #[cfg(test)]
93
- lazy_static::lazy_static! {
94
- pub static ref RUN_COMMAND_MOCK: std::sync::Mutex<
95
- Option<Box<dyn Fn(&str, &str, &[&str]) -> Option<String> + Send + Sync + 'static>>,
96
- > = std::sync::Mutex::new(None);
97
- }
98
-
99
- /// Executes a command and returns the `stdout` output if the command was
100
- /// successfully executed (errors are added to `COMMAND_ERRORS`).
101
- fn run_command(name: &str, path: &str, arguments: &[&str]) -> Option<String> {
102
- #[cfg(test)]
103
- if let Some(command) = &*RUN_COMMAND_MOCK.lock().unwrap() {
104
- return command(name, path, arguments);
105
- }
106
-
107
- let output = match Command::new(path).args(arguments).output() {
108
- Ok(output) => output,
109
- Err(error) => {
110
- let message = format!("error: {}", error);
111
- add_command_error(name, path, arguments, message);
112
- return None;
113
- }
114
- };
115
-
116
- if output.status.success() {
117
- Some(String::from_utf8_lossy(&output.stdout).into_owned())
118
- } else {
119
- let message = format!("exit code: {}", output.status);
120
- add_command_error(name, path, arguments, message);
121
- None
122
- }
123
- }
124
-
125
- /// Executes the `llvm-config` command and returns the `stdout` output if the
126
- /// command was successfully executed (errors are added to `COMMAND_ERRORS`).
127
- pub fn run_llvm_config(arguments: &[&str]) -> Option<String> {
128
- let path = env::var("LLVM_CONFIG_PATH").unwrap_or_else(|_| "llvm-config".into());
129
- run_command("llvm-config", &path, arguments)
130
- }
131
-
132
- /// Executes the `xcode-select` command and returns the `stdout` output if the
133
- /// command was successfully executed (errors are added to `COMMAND_ERRORS`).
134
- pub fn run_xcode_select(arguments: &[&str]) -> Option<String> {
135
- run_command("xcode-select", "xcode-select", arguments)
136
- }
137
-
138
- //================================================
139
- // Search Directories
140
- //================================================
141
- // These search directories are listed in order of
142
- // preference, so if multiple `libclang` instances
143
- // are found when searching matching directories,
144
- // the `libclang` instances from earlier
145
- // directories will be preferred (though version
146
- // takes precedence over location).
147
- //================================================
148
-
149
- /// `libclang` directory patterns for Haiku.
150
- const DIRECTORIES_HAIKU: &[&str] = &[
151
- "/boot/home/config/non-packaged/develop/lib",
152
- "/boot/home/config/non-packaged/lib",
153
- "/boot/system/non-packaged/develop/lib",
154
- "/boot/system/non-packaged/lib",
155
- "/boot/system/develop/lib",
156
- "/boot/system/lib",
157
- ];
158
-
159
- /// `libclang` directory patterns for Linux (and FreeBSD).
160
- const DIRECTORIES_LINUX: &[&str] = &[
161
- "/usr/local/llvm*/lib*",
162
- "/usr/local/lib*/*/*",
163
- "/usr/local/lib*/*",
164
- "/usr/local/lib*",
165
- "/usr/lib*/*/*",
166
- "/usr/lib*/*",
167
- "/usr/lib*",
168
- ];
169
-
170
- /// `libclang` directory patterns for macOS.
171
- const DIRECTORIES_MACOS: &[&str] = &[
172
- "/usr/local/opt/llvm*/lib/llvm*/lib",
173
- "/Library/Developer/CommandLineTools/usr/lib",
174
- "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib",
175
- "/usr/local/opt/llvm*/lib",
176
- ];
177
-
178
- /// `libclang` directory patterns for Windows.
179
- ///
180
- /// The boolean indicates whether the directory pattern should be used when
181
- /// compiling for an MSVC target environment.
182
- const DIRECTORIES_WINDOWS: &[(&str, bool)] = &[
183
- // LLVM + Clang can be installed using Scoop (https://scoop.sh).
184
- // Other Windows package managers install LLVM + Clang to other listed
185
- // system-wide directories.
186
- ("C:\\Users\\*\\scoop\\apps\\llvm\\current\\lib", true),
187
- ("C:\\MSYS*\\MinGW*\\lib", false),
188
- ("C:\\Program Files*\\LLVM\\lib", true),
189
- ("C:\\LLVM\\lib", true),
190
- // LLVM + Clang can be installed as a component of Visual Studio.
191
- // https://github.com/KyleMayes/clang-sys/issues/121
192
- ("C:\\Program Files*\\Microsoft Visual Studio\\*\\VC\\Tools\\Llvm\\**\\lib", true),
193
- ];
194
-
195
- /// `libclang` directory patterns for illumos
196
- const DIRECTORIES_ILLUMOS: &[&str] = &[
197
- "/opt/ooce/llvm-*/lib",
198
- "/opt/ooce/clang-*/lib",
199
- ];
200
-
201
- //================================================
202
- // Searching
203
- //================================================
204
-
205
- /// Finds the files in a directory that match one or more filename glob patterns
206
- /// and returns the paths to and filenames of those files.
207
- fn search_directory(directory: &Path, filenames: &[String]) -> Vec<(PathBuf, String)> {
208
- // Escape the specified directory in case it contains characters that have
209
- // special meaning in glob patterns (e.g., `[` or `]`).
210
- let directory = Pattern::escape(directory.to_str().unwrap());
211
- let directory = Path::new(&directory);
212
-
213
- // Join the escaped directory to the filename glob patterns to obtain
214
- // complete glob patterns for the files being searched for.
215
- let paths = filenames
216
- .iter()
217
- .map(|f| directory.join(f).to_str().unwrap().to_owned());
218
-
219
- // Prevent wildcards from matching path separators to ensure that the search
220
- // is limited to the specified directory.
221
- let mut options = MatchOptions::new();
222
- options.require_literal_separator = true;
223
-
224
- paths
225
- .map(|p| glob::glob_with(&p, options))
226
- .filter_map(Result::ok)
227
- .flatten()
228
- .filter_map(|p| {
229
- let path = p.ok()?;
230
- let filename = path.file_name()?.to_str().unwrap();
231
-
232
- // The `libclang_shared` library has been renamed to `libclang-cpp`
233
- // in Clang 10. This can cause instances of this library (e.g.,
234
- // `libclang-cpp.so.10`) to be matched by patterns looking for
235
- // instances of `libclang`.
236
- if filename.contains("-cpp.") {
237
- return None;
238
- }
239
-
240
- Some((path.parent().unwrap().to_owned(), filename.into()))
241
- })
242
- .collect::<Vec<_>>()
243
- }
244
-
245
- /// Finds the files in a directory (and any relevant sibling directories) that
246
- /// match one or more filename glob patterns and returns the paths to and
247
- /// filenames of those files.
248
- fn search_directories(directory: &Path, filenames: &[String]) -> Vec<(PathBuf, String)> {
249
- let mut results = search_directory(directory, filenames);
250
-
251
- // On Windows, `libclang.dll` is usually found in the LLVM `bin` directory
252
- // while `libclang.lib` is usually found in the LLVM `lib` directory. To
253
- // keep things consistent with other platforms, only LLVM `lib` directories
254
- // are included in the backup search directory globs so we need to search
255
- // the LLVM `bin` directory here.
256
- if target_os!("windows") && directory.ends_with("lib") {
257
- let sibling = directory.parent().unwrap().join("bin");
258
- results.extend(search_directory(&sibling, filenames));
259
- }
260
-
261
- results
262
- }
263
-
264
- /// Finds the `libclang` static or dynamic libraries matching one or more
265
- /// filename glob patterns and returns the paths to and filenames of those files.
266
- pub fn search_libclang_directories(filenames: &[String], variable: &str) -> Vec<(PathBuf, String)> {
267
- // Search only the path indicated by the relevant environment variable
268
- // (e.g., `LIBCLANG_PATH`) if it is set.
269
- if let Ok(path) = env::var(variable).map(|d| Path::new(&d).to_path_buf()) {
270
- // Check if the path is a matching file.
271
- if let Some(parent) = path.parent() {
272
- let filename = path.file_name().unwrap().to_str().unwrap();
273
- let libraries = search_directories(parent, filenames);
274
- if libraries.iter().any(|(_, f)| f == filename) {
275
- return vec![(parent.into(), filename.into())];
276
- }
277
- }
278
-
279
- // Check if the path is directory containing a matching file.
280
- return search_directories(&path, filenames);
281
- }
282
-
283
- let mut found = vec![];
284
-
285
- // Search the `bin` and `lib` directories in the directory returned by
286
- // `llvm-config --prefix`.
287
- if let Some(output) = run_llvm_config(&["--prefix"]) {
288
- let directory = Path::new(output.lines().next().unwrap()).to_path_buf();
289
- found.extend(search_directories(&directory.join("bin"), filenames));
290
- found.extend(search_directories(&directory.join("lib"), filenames));
291
- found.extend(search_directories(&directory.join("lib64"), filenames));
292
- }
293
-
294
- // Search the toolchain directory in the directory returned by
295
- // `xcode-select --print-path`.
296
- if target_os!("macos") {
297
- if let Some(output) = run_xcode_select(&["--print-path"]) {
298
- let directory = Path::new(output.lines().next().unwrap()).to_path_buf();
299
- let directory = directory.join("Toolchains/XcodeDefault.xctoolchain/usr/lib");
300
- found.extend(search_directories(&directory, filenames));
301
- }
302
- }
303
-
304
- // Search the directories in the `LD_LIBRARY_PATH` environment variable.
305
- if let Ok(path) = env::var("LD_LIBRARY_PATH") {
306
- for directory in env::split_paths(&path) {
307
- found.extend(search_directories(&directory, filenames));
308
- }
309
- }
310
-
311
- // Determine the `libclang` directory patterns.
312
- let directories: Vec<&str> = if target_os!("haiku") {
313
- DIRECTORIES_HAIKU.into()
314
- } else if target_os!("linux") || target_os!("freebsd") {
315
- DIRECTORIES_LINUX.into()
316
- } else if target_os!("macos") {
317
- DIRECTORIES_MACOS.into()
318
- } else if target_os!("windows") {
319
- let msvc = target_env!("msvc");
320
- DIRECTORIES_WINDOWS
321
- .iter()
322
- .filter(|d| d.1 || !msvc)
323
- .map(|d| d.0)
324
- .collect()
325
- } else if target_os!("illumos") {
326
- DIRECTORIES_ILLUMOS.into()
327
- } else {
328
- vec![]
329
- };
330
-
331
- // We use temporary directories when testing the build script so we'll
332
- // remove the prefixes that make the directories absolute.
333
- let directories = if test!() {
334
- directories
335
- .iter()
336
- .map(|d| d.strip_prefix('/').or_else(|| d.strip_prefix("C:\\")).unwrap_or(d))
337
- .collect::<Vec<_>>()
338
- } else {
339
- directories
340
- };
341
-
342
- // Search the directories provided by the `libclang` directory patterns.
343
- let mut options = MatchOptions::new();
344
- options.case_sensitive = false;
345
- options.require_literal_separator = true;
346
- for directory in directories.iter() {
347
- if let Ok(directories) = glob::glob_with(directory, options) {
348
- for directory in directories.filter_map(Result::ok).filter(|p| p.is_dir()) {
349
- found.extend(search_directories(&directory, filenames));
350
- }
351
- }
352
- }
353
-
354
- found
355
- }