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 register_application #126

Merged
merged 1 commit into from
Feb 9, 2025
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
4 changes: 3 additions & 1 deletion Cargo.lock

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

23 changes: 23 additions & 0 deletions common/src/apis.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,16 @@ pub struct Application {
pub working_directory: String,
}

#[derive(Clone, Debug, Default)]
pub struct ApplicationAttributes {
pub shim: Shim,
pub url: Option<String>,
pub command: Option<String>,
pub arguments: Vec<String>,
pub environments: Vec<String>,
pub working_directory: String,
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash, strum_macros::Display)]
pub enum SessionState {
#[default]
Expand Down Expand Up @@ -481,6 +491,19 @@ impl From<&Application> for rpc::Application {
}
}

impl From<rpc::ApplicationSpec> for ApplicationAttributes {
fn from(spec: rpc::ApplicationSpec) -> Self {
Self {
shim: spec.shim().into(),
url: spec.url.clone(),
command: spec.command.clone(),
arguments: spec.arguments.clone(),
environments: spec.environments.clone(),
working_directory: spec.working_directory.clone().unwrap_or_default(),
}
}
}

impl From<ApplicationState> for rpc::ApplicationState {
fn from(s: ApplicationState) -> Self {
match s {
Expand Down
6 changes: 5 additions & 1 deletion flmctl/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,8 @@ sqlx = { workspace = true }
clap = { version = "4.1", features = ["derive"] }
chrono = "0.4"

url = {version = "2.5"}
url = {version = "2.5"}

serde = "1.0"
serde_yaml = "0.9"
serde_derive = "1.0"
4 changes: 2 additions & 2 deletions flmctl/src/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,10 @@ async fn list_application(conn: Connection) -> Result<(), Box<dyn Error>> {
println!(
"{:<15}{:<15}{:<15}{:<15}{:<30}",
app.name,
app.shim.to_string(),
app.attributes.shim.to_string(),
app.state.to_string(),
app.creation_time.format("%T"),
app.command.clone().unwrap_or("-".to_string())
app.attributes.command.clone().unwrap_or("-".to_string())
);
}

Expand Down
16 changes: 16 additions & 0 deletions flmctl/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ mod create;
mod helper;
mod list;
mod migrate;
mod register;
mod unregister;
mod view;

#[derive(Parser)]
Expand Down Expand Up @@ -77,6 +79,18 @@ enum Commands {
#[arg(short, long)]
sql: String,
},
/// Register an application
Register {
/// The yaml file of the application
#[arg(short, long)]
file: String,
},
/// Unregister the application from Flame
Unregister {
/// The name of the application
#[arg(short, long)]
name: String,
},
}

#[tokio::main]
Expand All @@ -97,6 +111,8 @@ async fn main() -> Result<(), Box<dyn Error>> {
Some(Commands::Create { app, slots }) => create::run(&ctx, app, slots).await?,
Some(Commands::View { session }) => view::run(&ctx, session).await?,
Some(Commands::Migrate { url, sql }) => migrate::run(&ctx, url, sql).await?,
Some(Commands::Register { file }) => register::run(&ctx, file).await?,
Some(Commands::Unregister { name }) => unregister::run(&ctx, name).await?,
_ => helper::run().await?,
};

Expand Down
88 changes: 88 additions & 0 deletions flmctl/src/register.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
/*
Copyright 2025 The Flame Authors.
Licensed 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 std::{fs, path::Path};

use serde_derive::{Deserialize, Serialize};

use common::ctx::FlameContext;
use flame_client::{self as flame, ApplicationAttributes, FlameError, Shim};

#[derive(Debug, Clone, Serialize, Deserialize)]
struct MetadataYaml {
pub name: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct SpecYaml {
pub shim: Option<String>,
pub url: Option<String>,
pub command: Option<String>,
pub arguments: Option<Vec<String>>,
pub environments: Option<Vec<String>>,
pub working_directory: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct ApplicationYaml {
pub metadata: MetadataYaml,
pub spec: SpecYaml,
}

pub async fn run(ctx: &FlameContext, path: &String) -> Result<(), FlameError> {
if !Path::new(&path).is_file() {
return Err(FlameError::InvalidConfig(format!(
"<{}> is not a file",
path
)));
}

let contents =
fs::read_to_string(path.clone()).map_err(|e| FlameError::Internal(e.to_string()))?;
let app: ApplicationYaml =
serde_yaml::from_str(&contents).map_err(|e| FlameError::Internal(e.to_string()))?;

let app_attr = ApplicationAttributes::try_from(&app)?;

let conn = flame::connect(&ctx.endpoint).await?;

conn.register_application(app.metadata.name, app_attr)
.await?;
Ok(())
}

impl TryFrom<&ApplicationYaml> for ApplicationAttributes {
type Error = FlameError;

fn try_from(yaml: &ApplicationYaml) -> Result<Self, Self::Error> {
let shim = match yaml
.spec
.shim
.clone()
.unwrap_or(String::from("grpc"))
.to_lowercase()
.as_str()
{
"grpc" => Ok(Shim::Grpc),
_ => Err(FlameError::InvalidConfig("unsupported shim".to_string())),
}?;

Ok(Self {
shim,
url: yaml.spec.url.clone(),
command: yaml.spec.command.clone(),
arguments: yaml.spec.arguments.clone().unwrap_or_default(),
environments: yaml.spec.environments.clone().unwrap_or_default(),
working_directory: yaml.spec.working_directory.clone(),
})
}
}
20 changes: 20 additions & 0 deletions flmctl/src/unregister.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/*
Copyright 2025 The Flame Authors.
Licensed 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 std::error::Error;

use common::ctx::FlameContext;

pub async fn run(_: &FlameContext, _: &String) -> Result<(), Box<dyn Error>> {
todo!()
}
1 change: 0 additions & 1 deletion flmping/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ edition = "2021"
flame-client = { path = "../sdk/rust/client" }
flame-service = { path = "../sdk/rust/service" }

rpc = { path = "../rpc" }
common = { path = "../common" }

tokio = { workspace = true }
Expand Down
76 changes: 70 additions & 6 deletions sdk/rust/client/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,21 @@ use std::sync::{Arc, Mutex};

use bytes::Bytes;
use chrono::{DateTime, TimeZone, Utc};

use futures::TryFutureExt;
use prost::Enumeration;
use thiserror::Error;
use tokio_stream::StreamExt;
use tonic::transport::Channel;
use tonic::transport::Endpoint;
use tonic::Request;
use tonic::Status;

use self::rpc::frontend_client::FrontendClient as FlameFrontendClient;
use self::rpc::{
CloseSessionRequest, CreateSessionRequest, CreateTaskRequest, GetTaskRequest,
ListApplicationRequest, ListSessionRequest, SessionSpec, TaskSpec, WatchTaskRequest,
ApplicationSpec, CloseSessionRequest, CreateSessionRequest, CreateTaskRequest, GetTaskRequest,
ListApplicationRequest, ListSessionRequest, RegisterApplicationRequest, SessionSpec, TaskSpec,
WatchTaskRequest,
};
use crate::flame as rpc;
use crate::trace::TraceFn;
Expand Down Expand Up @@ -131,12 +134,24 @@ pub struct SessionAttributes {
pub common_data: Option<CommonData>,
}

#[derive(Clone)]
pub struct ApplicationAttributes {
pub shim: Shim,

pub url: Option<String>,
pub command: Option<String>,
pub arguments: Vec<String>,
pub environments: Vec<String>,
pub working_directory: Option<String>,
}

#[derive(Clone)]
pub struct Application {
pub name: ApplicationID,

pub attributes: ApplicationAttributes,

pub state: ApplicationState,
pub shim: Shim,
pub command: Option<String>,
pub creation_time: DateTime<Utc>,
}

Expand Down Expand Up @@ -214,6 +229,30 @@ impl Connection {
.collect())
}

pub async fn register_application(
&self,
name: String,
app: ApplicationAttributes,
) -> Result<(), FlameError> {
let mut client = FlameClient::new(self.channel.clone());

let req = RegisterApplicationRequest {
name,
application: Some(ApplicationSpec::from(app)),
};

let res = client
.register_application(Request::new(req))
.await?
.into_inner();

if res.return_code < 0 {
Err(FlameError::Network(res.message.unwrap_or_default()))
} else {
Ok(())
}
}

pub async fn list_application(&self) -> Result<Vec<Application>, FlameError> {
let mut client = FlameClient::new(self.channel.clone());
let app_list = client.list_application(ListApplicationRequest {}).await?;
Expand Down Expand Up @@ -384,14 +423,39 @@ impl From<&rpc::Application> for Application {

Self {
name: metadata.name,
shim: Shim::from(spec.shim()),
attributes: ApplicationAttributes::from(spec),
state: ApplicationState::from(status.state()),
command: spec.command.clone(),
creation_time,
}
}
}

impl From<ApplicationAttributes> for ApplicationSpec {
fn from(app: ApplicationAttributes) -> Self {
Self {
shim: app.shim.into(),
url: app.url.clone(),
command: app.command.clone(),
arguments: app.arguments.clone(),
environments: app.environments.clone(),
working_directory: app.working_directory.clone(),
}
}
}

impl From<ApplicationSpec> for ApplicationAttributes {
fn from(app: ApplicationSpec) -> Self {
Self {
shim: app.shim().into(),
url: app.url.clone(),
command: app.command.clone(),
arguments: app.arguments.clone(),
environments: app.environments.clone(),
working_directory: app.working_directory.clone(),
}
}
}

impl From<rpc::Shim> for Shim {
fn from(shim: rpc::Shim) -> Self {
match shim {
Expand Down
Loading
Loading