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 plugin for memcached. #27

Merged
merged 8 commits into from
Oct 27, 2022
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
2 changes: 1 addition & 1 deletion .github/workflows/rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ jobs:
tools: php-config, composer:v2
extensions: >
bcmath, calendar, ctype, dom, exif, gettext, iconv, intl, json, mbstring,
mysqli, mysqlnd, opcache, pdo, pdo_mysql, phar, posix, readline,
mysqli, mysqlnd, opcache, pdo, pdo_mysql, phar, posix, readline, memcached,
swoole-${{ matrix.version.swoole }}, xml, xmlreader, xmlwriter, yaml, zip

- name: Setup php-fpm for Linux
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ SkyWalking PHP Agent requires SkyWalking 8.4+ and PHP 7.2+
* [x] [cURL](https://www.php.net/manual/en/book.curl.php#book.curl)
* [x] [PDO](https://www.php.net/manual/en/book.pdo.php)
* [x] [MySQL Improved](https://www.php.net/manual/en/book.mysqli.php)
* [ ] [Memcached](https://www.php.net/manual/en/book.memcached.php)
* [x] [Memcached](https://www.php.net/manual/en/book.memcached.php)
* [ ] [phpredis](https://github.com/phpredis/phpredis)
* [ ] [php-amqp](https://github.com/php-amqp/php-amqp)
* [ ] [php-rdkafka](https://github.com/arnaud-lb/php-rdkafka)
Expand Down
1 change: 1 addition & 0 deletions Vagrantfile
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ Vagrant.configure("2") do |config|
config.vm.network "forwarded_port", guest: 12800, host: 12800
config.vm.network "forwarded_port", guest: 3306, host: 3306
config.vm.network "forwarded_port", guest: 6379, host: 6379
config.vm.network "forwarded_port", guest: 11211, host: 11211

config.vm.synced_folder ".", "/vagrant"

Expand Down
5 changes: 5 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,8 @@ services:
- "6379:6379"
environment:
- REDIS_PASSWORD=password

memcached:
image: memcached:1.6.17
ports:
- "11211:11211"
1 change: 1 addition & 0 deletions docs/en/setup/service-agent/php-agent/Supported-list.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ The following plugins provide the distributed tracing capability.
* [cURL](https://www.php.net/manual/en/book.curl.php#book.curl)
* [PDO](https://www.php.net/manual/en/book.pdo.php)
* [MySQL Improved](https://www.php.net/manual/en/book.mysqli.php)
* [Memcached](https://www.php.net/manual/en/book.memcached.php)

## Support PHP library

Expand Down
1 change: 1 addition & 0 deletions src/component.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,4 @@ pub const COMPONENT_PHP_CURL_ID: i32 = 8002;
pub const COMPONENT_PHP_PDO_ID: i32 = 8003;
pub const COMPONENT_PHP_MYSQLI_ID: i32 = 8004;
pub const COMPONENT_PHP_PREDIS_ID: i32 = 8006;
pub const COMPONENT_PHP_MEMCACHED_ID: i32 = 20;
2 changes: 2 additions & 0 deletions src/plugin/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
// limitations under the License.

mod plugin_curl;
mod plugin_memcached;
mod plugin_mysqli;
mod plugin_pdo;
mod plugin_predis;
Expand All @@ -31,6 +32,7 @@ static PLUGINS: Lazy<Vec<Box<DynPlugin>>> = Lazy::new(|| {
Box::new(plugin_swoole::SwooleServerPlugin::default()),
Box::new(plugin_swoole::SwooleHttpResponsePlugin::default()),
Box::new(plugin_predis::PredisPlugin::default()),
Box::new(plugin_memcached::MemcachedPlugin::default()),
]
});

Expand Down
248 changes: 248 additions & 0 deletions src/plugin/plugin_memcached.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,248 @@
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use super::Plugin;
use crate::{
component::COMPONENT_PHP_MEMCACHED_ID,
context::RequestContext,
execute::{get_this_mut, AfterExecuteHook, BeforeExecuteHook},
};
use anyhow::{bail, Context};
use once_cell::sync::Lazy;
use phper::{functions::call, values::ExecuteData};
use skywalking::{skywalking_proto::v3::SpanLayer, trace::span::Span};
use tracing::{debug, warn};

static MEC_KEYS_COMMANDS: Lazy<Vec<String>> = Lazy::new(|| {
[
"set",
"setByKey",
"setMulti",
"setMultiByKey",
"add",
"addByKey",
"replace",
"replaceByKey",
"append",
"appendByKey",
"prepend",
"prependByKey",
"get",
"getByKey",
"getMulti",
"getMultiByKey",
"getAllKeys",
"delete",
"deleteByKey",
"deleteMulti",
"deleteMultiByKey",
"increment",
"incrementByKey",
"decrement",
"decrementByKey",
"getStats",
"isPersistent",
"isPristine",
"flush",
"flushBuffers",
"getDelayed",
"getDelayedByKey",
"fetch",
"fetchAll",
"addServer",
"addServers",
"getOption",
"setOption",
"setOptions",
"getResultCode",
"getServerList",
"resetServerList",
"getVersion",
"quit",
"setSaslAuthData",
"touch",
"touchByKey",
]
.into_iter()
.map(str::to_ascii_lowercase)
.collect()
});

static MEC_STR_KEYS_COMMANDS: Lazy<Vec<String>> = Lazy::new(|| {
[
"set",
"setByKey",
"setMulti",
"setMultiByKey",
"add",
"addByKey",
"replace",
"replaceByKey",
"append",
"appendByKey",
"prepend",
"prependByKey",
"get",
"getByKey",
"getMulti",
"getMultiByKey",
"getAllKeys",
"delete",
"deleteByKey",
"deleteMulti",
"deleteMultiByKey",
"increment",
"incrementByKey",
"decrement",
"decrementByKey",
]
.into_iter()
.map(str::to_ascii_lowercase)
.collect()
});

#[derive(Default, Clone)]
pub struct MemcachedPlugin;

impl Plugin for MemcachedPlugin {
fn class_names(&self) -> Option<&'static [&'static str]> {
Some(&["Memcached"])
}

fn function_name_prefix(&self) -> Option<&'static str> {
None
}

fn hook(
&self, class_name: Option<&str>, function_name: &str,
) -> Option<(
Box<crate::execute::BeforeExecuteHook>,
Box<crate::execute::AfterExecuteHook>,
)> {
match (class_name, function_name) {
(Some(class_name @ "Memcached"), f)
if MEC_KEYS_COMMANDS.contains(&f.to_ascii_lowercase()) =>
{
Some(self.hook_memcached_methods(class_name, function_name))
}
_ => None,
}
}
}

impl MemcachedPlugin {
fn hook_memcached_methods(
&self, class_name: &str, function_name: &str,
) -> (Box<BeforeExecuteHook>, Box<AfterExecuteHook>) {
let class_name = class_name.to_owned();
let function_name = function_name.to_owned();
(
Box::new(move |request_id, execute_data| {
let peer = if MEC_STR_KEYS_COMMANDS.contains(&function_name.to_ascii_lowercase()) {
let mut f = || {
let key = {
let key = execute_data.get_parameter(0);
if !key.get_type_info().is_string() {
// The `*Multi` methods will failed here.
bail!("The argument key of {} isn't string", &function_name);
}
key.clone()
};
let this = get_this_mut(execute_data)?;
let info = this.call(&"getServerByKey".to_ascii_lowercase(), [key])?;
let info = info.as_z_arr().context("Server isn't array")?;
let host = info
.get("host")
.context("Server host not exists")?
.as_z_str()
.context("Server host isn't string")?
.to_str()?;
let port = info
.get("port")
.context("Server port not exists")?
.as_long()
.context("Server port isn't long")?;
Ok::<_, anyhow::Error>(format!("{}:{}", host, port))
};
match f() {
Ok(peer) => peer,
Err(err) => {
warn!(?err, "Get peer failed");
"".to_owned()
}
}
} else {
"".to_owned()
};

debug!(peer, "Get memcached peer");

let span = RequestContext::try_with_global_ctx(request_id, |ctx| {
let mut span =
ctx.create_exit_span(&format!("{}->{}", class_name, function_name), &peer);
span.with_span_object_mut(|obj| {
obj.set_span_layer(SpanLayer::Cache);
obj.component_id = COMPONENT_PHP_MEMCACHED_ID;
obj.add_tag("db.type", "memcached");

match get_command(execute_data, &function_name) {
Ok(cmd) => {
obj.add_tag("memcached.command", cmd);
}
Err(err) => {
warn!(?err, "get command failed");
}
}
});
Ok(span)
})?;

Ok(Box::new(span) as _)
}),
Box::new(|_, span, _, return_value| {
let mut span = span.downcast::<Span>().unwrap();
if let Some(b) = return_value.as_bool() {
if !b {
span.with_span_object_mut(|span| {
span.is_error = true;
});
}
}
Ok(())
}),
)
}
}

fn get_command(execute_data: &mut ExecuteData, function_name: &str) -> anyhow::Result<String> {
let num_args = execute_data.num_args();
let mut items = Vec::with_capacity(num_args + 1);
items.push(function_name.to_owned());

for i in 0..num_args {
let parameter = execute_data.get_parameter(i);
let s = if parameter.get_type_info().is_array() {
let result = call("json_encode", [parameter.clone()])?;
result.expect_z_str()?.to_str()?.to_string()
} else {
let mut parameter = parameter.clone();
parameter.convert_to_string();
parameter.expect_z_str()?.to_str()?.to_string()
};
items.push(s)
}

Ok(items.join(" "))
}
Loading