Skip to content

Commit

Permalink
fix build err.
Browse files Browse the repository at this point in the history
Signed-off-by: Klaus Ma <[email protected]>
  • Loading branch information
k82cn committed Dec 6, 2024
1 parent 4786797 commit 3506b89
Show file tree
Hide file tree
Showing 26 changed files with 362 additions and 650 deletions.
23 changes: 23 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions hcactl/src/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@ See the License for the specific language governing permissions and
limitations under the License.
*/

use ::libhca;
use libonm::hca;

pub fn run() -> Result<(), color_eyre::Report> {
let hcas = libhca::list_pci_devices()?;
let hcas = hca::list_pci_devices()?;

for hca in hcas {
println!("----------------------------------------------");
Expand Down
23 changes: 22 additions & 1 deletion libonm/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,28 @@ version = "0.1.0"
edition = "2021"

[dependencies]
tracing = { workspace = true }
tracing-subscriber = { workspace = true }

clap = { workspace = true }
serde = { workspace = true }
toml = { workspace = true }
tokio = { workspace = true }
async-trait = { workspace = true }
thiserror = { workspace = true }
serde_json = { workspace = true }

reqwest = { workspace = true }
http = { workspace = true }
bytes = { workspace = true }
base64 = { workspace = true }
url = { workspace = true }

numeric_cast = "0.2"
libudev = "0.3"
scopeguard = "1.2"


[build-dependencies]
bindgen = "0.70"
cc = "1.0"
cc = "1.0"
15 changes: 0 additions & 15 deletions libonm/src/hca/Cargo.toml

This file was deleted.

4 changes: 3 additions & 1 deletion libonm/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
pub mod hca;
pub mod sm;
pub mod xpu;
pub mod sm;

mod rest;
182 changes: 182 additions & 0 deletions libonm/src/rest.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
use bytes::Bytes;
use http::Method;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use thiserror::Error;
use url::Url;

use reqwest::{header::HeaderValue, header::ACCEPT, header::CONTENT_TYPE};

pub struct RestClient {
address: String,
user: String,
password: String,
}

pub struct RestConfig {
pub address: String,
pub username: String,
pub password: String,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct EmptyResponse {}

#[derive(Error, Debug)]
pub enum RestError {
#[error("{0}")]
Internal(String),
#[error("{0}")]
Json(String),
#[error("{0}")]
Http(String),
#[error("'{0}' not found")]
NotFound(String),
#[error("failed to auth '{0}'")]
AuthFailure(String),
#[error("invalid configuration '{0}'")]
InvalidConfig(String),
}

impl From<reqwest::Error> for RestError {
fn from(value: reqwest::Error) -> Self {
tracing::debug!("{:?}", value);
RestError::Http(value.to_string())
}
}

impl From<serde_json::Error> for RestError {
fn from(value: serde_json::Error) -> Self {
tracing::debug!("{:?}", value);
RestError::Json(value.to_string())
}
}

impl From<std::io::Error> for RestError {
fn from(value: std::io::Error) -> Self {
RestError::Http(value.to_string())
}
}

impl RestClient {
pub fn new(config: &RestConfig) -> Result<Self, RestError> {
let url = Url::parse(&config.address)
.map_err(|_| RestError::InvalidConfig("invalid url".to_string()))?;
let host = url
.host_str()
.ok_or(RestError::InvalidConfig("invalid host".to_string()))?;
let port = url.port().unwrap_or(443);
let address = format!("{}:{}", host, port);

Ok(RestClient {
address,
user: config.username.clone(),
password: config.password.clone(),
})
}

pub async fn get<'a, T: DeserializeOwned>(&self, path: &str) -> Result<T, RestError> {
let resp = self.execute_request(Method::GET, path, None).await?;
let data = serde_json::from_str(&resp)
.map_err(|_| RestError::InvalidConfig("invalid response".to_string()))?;

Ok(data)
}

pub async fn list<'a, T: DeserializeOwned>(&self, path: &str) -> Result<Vec<T>, RestError> {
let resp = self.execute_request(Method::GET, path, None).await?;
let data = serde_json::from_str(&resp)
.map_err(|_| RestError::InvalidConfig("invalid response".to_string()))?;

Ok(data)
}

pub async fn put<'a, S: Serialize, T: DeserializeOwned>(
&self,
path: &str,
o: &S,
) -> Result<T, RestError> {
let input = serde_json::to_string(o)
.map_err(|_| RestError::InvalidConfig("invalid input".to_string()))?;
let resp = self.execute_request(Method::PUT, path, Some(input)).await?;

let data = serde_json::from_str(&resp)
.map_err(|_| RestError::InvalidConfig("invalid response".to_string()))?;

Ok(data)
}

pub async fn post<'a, S: Serialize, T: DeserializeOwned>(
&self,
path: &str,
o: &S,
) -> Result<T, RestError> {
let input = serde_json::to_string(o)
.map_err(|_| RestError::InvalidConfig("invalid input".to_string()))?;
let resp = self
.execute_request(Method::POST, path, Some(input))
.await?;

let data = serde_json::from_str(&resp)
.map_err(|_| RestError::InvalidConfig("invalid response".to_string()))?;

Ok(data)
}

pub async fn delete<'a, T: DeserializeOwned>(&self, path: &str) -> Result<T, RestError> {
let resp = self.execute_request(Method::DELETE, path, None).await?;

let data = serde_json::from_str(&resp)
.map_err(|_| RestError::InvalidConfig("invalid response".to_string()))?;

Ok(data)
}

pub async fn patch<'a, S: Serialize, T: DeserializeOwned>(
&self,
path: &str,
o: &S,
) -> Result<T, RestError> {
let input = serde_json::to_string(o)
.map_err(|_| RestError::InvalidConfig("invalid input".to_string()))?;
let resp = self
.execute_request(Method::PATCH, path, Some(input))
.await?;

let data = serde_json::from_str(&resp)
.map_err(|_| RestError::InvalidConfig("invalid response".to_string()))?;

Ok(data)
}

async fn execute_request(
&self,
method: Method,
path: &str,
data: Option<String>,
) -> Result<String, RestError> {
let schema = "https";
let url = format!("{}://{}/{}", schema, self.address, path.trim_matches('/'));

let body = Bytes::from(data.clone().unwrap_or(String::new()));
tracing::debug!(
"Method: {method}, URL: {url}, Auth: <{0}/{1}>, Body: <{2}>",
self.user,
self.password,
data.unwrap_or(String::new())
);

let client = reqwest::ClientBuilder::new()
.danger_accept_invalid_certs(true)
.build()?;
let req = client
.request(method, url)
.header(ACCEPT, HeaderValue::from_static("application/json"))
.header(CONTENT_TYPE, HeaderValue::from_static("application/json"))
.body(body)
.basic_auth(&self.user, Some(self.password.clone()))
.build()?;
let resp = client.execute(req).await?;

Ok(resp.text().await?)
}
}
Loading

0 comments on commit 3506b89

Please sign in to comment.