You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@skywalking.apache.org by wu...@apache.org on 2023/01/20 06:52:06 UTC

[skywalking-php] branch master updated: Add configuration option `skywalking_agent.runtime_dir`. (#47)

This is an automated email from the ASF dual-hosted git repository.

wusheng pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/skywalking-php.git


The following commit(s) were added to refs/heads/master by this push:
     new 9d2d05a  Add configuration option `skywalking_agent.runtime_dir`. (#47)
9d2d05a is described below

commit 9d2d05a717b2bc17aabc8ca2107781d02241eb45
Author: jmjoy <jm...@apache.org>
AuthorDate: Fri Jan 20 14:52:00 2023 +0800

    Add configuration option `skywalking_agent.runtime_dir`. (#47)
---
 docs/en/setup/service-agent/php-agent/README.md | 24 +++++++-----
 src/lib.rs                                      |  8 ++++
 src/module.rs                                   | 49 ++++++++++++++++++++-----
 src/util.rs                                     | 37 +++----------------
 src/worker.rs                                   |  6 +--
 5 files changed, 70 insertions(+), 54 deletions(-)

diff --git a/docs/en/setup/service-agent/php-agent/README.md b/docs/en/setup/service-agent/php-agent/README.md
index 6549752..ba963b0 100644
--- a/docs/en/setup/service-agent/php-agent/README.md
+++ b/docs/en/setup/service-agent/php-agent/README.md
@@ -55,27 +55,31 @@ make install
 ## Configure php.ini
 
 ```ini
-[skywalking]
+[skywalking_agent]
 extension=skywalking_agent.so
 
-# Enable skywalking extension or not.
+; Enable skywalking_agent extension or not.
 skywalking_agent.enable = On
 
-# Log file path.
-skywalking_agent.log_file = /tmp/skywalking_agent.log
+; Log file path.
+skywalking_agent.log_file = /tmp/skywalking-agent.log
 
-# Log level: one of `OFF`, `TRACE`, `DEBUG`, `INFO`, `WARN`, `ERROR`.
+; Log level: one of `OFF`, `TRACE`, `DEBUG`, `INFO`, `WARN`, `ERROR`.
 skywalking_agent.log_level = INFO
 
-# Address of skywalking oap server.
+; Address of skywalking oap server.
 skywalking_agent.server_addr = http://0.0.0.0:11800
 
-# Application service name.
+; Application service name.
 skywalking_agent.service_name = hello-skywalking
 
-# Skywalking version.
+; Skywalking version.
 skywalking_agent.skywalking_version = 8
 
-# Skywalking worker threads, 0 will auto set as the cpu core size.
-# skywalking_agent.worker_threads = 3
+; Skywalking worker threads, 0 will auto set as the cpu core size,
+; default is 0.
+; skywalking_agent.worker_threads = 3
+
+; Skywalking agent runtime directory, default is /tmp/skywalking-agent.
+; skywalking_agent.runtime_dir = /tmp/skywalking-agent
 ```
diff --git a/src/lib.rs b/src/lib.rs
index 56a4c4f..9f279b6 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -54,6 +54,9 @@ const SKYWALKING_AGENT_LOG_LEVEL: &str = "skywalking_agent.log_level";
 /// Log file of skywalking agent.
 const SKYWALKING_AGENT_LOG_FILE: &str = "skywalking_agent.log_file";
 
+/// Skywalking agent runtime directory.
+const SKYWALKING_AGENT_RUNTIME_DIR: &str = "skywalking_agent.runtime_dir";
+
 #[php_get_module]
 pub fn get_module() -> Module {
     let mut module = Module::new(
@@ -86,6 +89,11 @@ pub fn get_module() -> Module {
         "/tmp/skywalking-agent.log".to_string(),
         Policy::System,
     );
+    module.add_ini(
+        SKYWALKING_AGENT_RUNTIME_DIR,
+        "/tmp/skywalking-agent".to_string(),
+        Policy::System,
+    );
 
     // Hooks.
     module.on_module_init(module::init);
diff --git a/src/module.rs b/src/module.rs
index 364655b..e724c9c 100644
--- a/src/module.rs
+++ b/src/module.rs
@@ -19,7 +19,8 @@ use crate::{
     util::{get_sapi_module_name, IPS},
     worker::init_worker,
     SKYWALKING_AGENT_ENABLE, SKYWALKING_AGENT_LOG_FILE, SKYWALKING_AGENT_LOG_LEVEL,
-    SKYWALKING_AGENT_SERVICE_NAME, SKYWALKING_AGENT_SKYWALKING_VERSION,
+    SKYWALKING_AGENT_RUNTIME_DIR, SKYWALKING_AGENT_SERVICE_NAME,
+    SKYWALKING_AGENT_SKYWALKING_VERSION,
 };
 use once_cell::sync::Lazy;
 use phper::{arrays::ZArr, ini::ini_get, sys};
@@ -27,7 +28,15 @@ use skywalking::{
     common::random_generator::RandomGenerator,
     trace::tracer::{self, Tracer},
 };
-use std::{borrow::ToOwned, env, ffi::CStr, path::Path, str::FromStr, time::SystemTime};
+use std::{
+    borrow::ToOwned,
+    ffi::{CStr, OsStr},
+    fs,
+    os::unix::prelude::OsStrExt,
+    path::{Path, PathBuf},
+    str::FromStr,
+    time::SystemTime,
+};
 use tracing::{error, info, metadata::LevelFilter};
 use tracing_subscriber::FmtSubscriber;
 
@@ -44,17 +53,28 @@ pub static SERVICE_INSTANCE: Lazy<String> =
 pub static SKYWALKING_VERSION: Lazy<i64> =
     Lazy::new(|| ini_get::<i64>(SKYWALKING_AGENT_SKYWALKING_VERSION));
 
-pub static SOCKET_FILE_PATH: Lazy<String> = Lazy::new(|| {
+pub static RUNTIME_DIR: Lazy<PathBuf> = Lazy::new(|| {
+    let mut path = PathBuf::new();
+    if let Some(dir) = ini_get::<Option<&CStr>>(SKYWALKING_AGENT_RUNTIME_DIR) {
+        let dir = dir.to_bytes();
+        if !dir.is_empty() {
+            path.push(OsStr::from_bytes(dir));
+        }
+    }
+    path
+});
+
+pub static SOCKET_FILE_PATH: Lazy<PathBuf> = Lazy::new(|| {
+    let mut dir = RUNTIME_DIR.clone();
+
     let dur = SystemTime::now()
         .duration_since(SystemTime::UNIX_EPOCH)
         .expect("Get timestamp failed")
         .as_micros();
-    format!(
-        "{}/{}_{:x}.sock",
-        env::temp_dir().display(),
-        env!("CARGO_CRATE_NAME"),
-        dur
-    )
+
+    dir.push(format!("{:x}.sock", dur));
+
+    dir
 });
 
 pub fn init() {
@@ -81,13 +101,22 @@ pub fn init() {
         return;
     }
 
+    if RUNTIME_DIR.as_os_str().is_empty() {
+        error!("The skywalking agent runtime directory must not be empty");
+        return;
+    }
+    if let Err(err) = fs::create_dir_all(&*RUNTIME_DIR) {
+        error!(?err, "Create runtime directory failed");
+        return;
+    }
+
     Lazy::force(&SOCKET_FILE_PATH);
     init_worker();
 
     tracer::set_global_tracer(Tracer::new(
         service_name,
         service_instance,
-        Reporter::new(SOCKET_FILE_PATH.as_str()),
+        Reporter::new(&*SOCKET_FILE_PATH),
     ));
 
     register_execute_functions();
diff --git a/src/util.rs b/src/util.rs
index 984f5c1..7dd575c 100644
--- a/src/util.rs
+++ b/src/util.rs
@@ -14,12 +14,13 @@
 // limitations under the License.
 
 use anyhow::anyhow;
-use chrono::Local;
 use once_cell::sync::Lazy;
 use phper::{sys, values::ZVal};
 use std::{
     ffi::CStr,
+    os::unix::prelude::OsStrExt,
     panic::{catch_unwind, UnwindSafe},
+    path::Path,
 };
 use systemstat::{IpAddr, Platform, System};
 
@@ -59,33 +60,6 @@ pub static IPS: Lazy<Vec<String>> = Lazy::new(|| {
         .unwrap_or_else(|| vec!["127.0.0.1".to_owned()])
 });
 
-// TODO Maybe report_instance_properties used.
-#[allow(dead_code)]
-pub static HOST_NAME: Lazy<String> = Lazy::new(|| {
-    hostname::get()
-        .ok()
-        .and_then(|hostname| hostname.into_string().ok())
-        .unwrap_or_else(|| "unknown".to_string())
-});
-
-// TODO Maybe report_instance_properties used.
-#[allow(dead_code)]
-pub const OS_NAME: &str = if cfg!(target_os = "linux") {
-    "Linux"
-} else if cfg!(target_os = "windows") {
-    "Windows"
-} else if cfg!(target_os = "macos") {
-    "Macos"
-} else {
-    "Unknown"
-};
-
-// TODO Maybe report_instance_properties used.
-#[allow(dead_code)]
-pub fn current_formatted_time() -> String {
-    Local::now().format("%Y-%m-%d %H:%M:%S").to_string()
-}
-
 pub fn z_val_to_string(zv: &ZVal) -> Option<String> {
     zv.as_z_str()
         .and_then(|zs| zs.to_str().ok())
@@ -113,10 +87,11 @@ pub fn get_sapi_module_name() -> &'static CStr {
     unsafe { CStr::from_ptr(sys::sapi_module.name) }
 }
 
-pub fn change_permission(f: &str, mode: libc::mode_t) {
+pub fn change_permission(f: impl AsRef<Path>, mode: libc::mode_t) {
+    let f = f.as_ref().as_os_str().as_bytes();
     let mut path = Vec::with_capacity(f.len() + 1);
-    path.extend_from_slice(f.as_bytes());
-    path.push(0);
+    path.extend_from_slice(f);
+    path.push(b'\0');
     unsafe {
         libc::chmod(path.as_ptr().cast(), mode);
     }
diff --git a/src/worker.rs b/src/worker.rs
index 1e6bb94..bdafdc7 100644
--- a/src/worker.rs
+++ b/src/worker.rs
@@ -114,10 +114,10 @@ async fn start_worker(server_addr: String) -> anyhow::Result<()> {
     let mut sig_term = signal(SignalKind::terminate())?;
     let mut sig_int = signal(SignalKind::interrupt())?;
 
-    let socket_file = SOCKET_FILE_PATH.as_str();
+    let socket_file = &*SOCKET_FILE_PATH;
 
     let fut = async move {
-        debug!(socket_file, "Bind unix stream");
+        debug!(?socket_file, "Bind unix stream");
         let listener = UnixListener::bind(socket_file)?;
         change_permission(socket_file, 0o777);
 
@@ -242,7 +242,7 @@ impl Drop for WorkerExitGuard {
     fn drop(&mut self) {
         match Lazy::get(&SOCKET_FILE_PATH) {
             Some(socket_file) => {
-                info!(socket_file, "Remove socket file");
+                info!(?socket_file, "Remove socket file");
                 if let Err(err) = fs::remove_file(socket_file) {
                     error!(?err, "Remove socket file failed");
                 }