mirror of
https://github.com/windmill-labs/windmill.git
synced 2026-08-18 16:02:10 +00:00
161dbbc6d6
* feat: add stream output feature to SSE job updates Adds stream_output field to JobUpdate struct that extracts log lines starting with '[wm_stream]:' from job logs. Regular logs now exclude stream lines, which are captured separately for specialized handling. - Added stream_output: Option<String> field to JobUpdate struct - Created extract_stream_output_from_logs() function to filter stream lines - Modified get_job_update_data() to use stream extraction logic - SSE clients now receive both new_logs and stream_output in job updates Co-authored-by: Ruben Fiszel <rubenfiszel@users.noreply.github.com> * feat: rename stream_output to stream and handle newlines as \n - Renamed `stream_output` field to `stream` in JobUpdate struct - Updated extract_stream_output_from_logs to extract_stream_from_logs - Changed stream output to join with literal \n instead of actual newlines - Stream lines are properly excluded from regular new_logs 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Ruben Fiszel <rubenfiszel@users.noreply.github.com> * decision tree nits * push ee ref * push ee ref * fix: fix id renaming in apps * remove duplicate caching (#6285) * feat: migrate audit log ids to bigints (blocking migration for EE) * fix(mcp): add proper check for mcp routes (#6282) * add proper check for mcp routes * cleaner * apply to flow * fix add checks scopes --------- Co-authored-by: dieriba <dieriba.pro@gmail.com> * chore(main): release 1.514.0 (#6283) * chore(main): release 1.514.0 * Apply automatic changes --------- Co-authored-by: rubenfiszel <275584+rubenfiszel@users.noreply.github.com> * fix: pin tokio to 1.46.1 and aws-sdks-ts * pin rustls to 0.23.29 + pin aws-sdk * chore(main): release 1.514.1 (#6288) * chore(main): release 1.514.1 * Apply automatic changes --------- Co-authored-by: rubenfiszel <275584+rubenfiszel@users.noreply.github.com> * fix: improve docker logs collection in docker mode * support $res: string in form inputs of arrays * fix import nit * fix: fix DynSelect * nits * fix: resource-type-ts-parser (#6289) * fix: resource types as arg in typescript handle imported defined types * Update nix flake (#6291) * merge * Small UI fixes (#6294) * fix step history not refreshing with staticInputs * fix array of obj not showing up in json editor in test this step * datatable scales correctly in DisplayResult and scrolling is much more usable * avoid next button disapearing and changing layout / hurting ux * nits * fix bug when renaming module A to B then module C to A, C takes the schema of A * fix bug with comments in sql repl * fix aggrid theme randomly not loading * bindable script * better delete button in db manager * property select doesnt exist * fix all warnings * delete $flowStateStore[id] on delete * feat(cli): generate cursor rules on init (#6270) * create cursor rules on init * change gen * add missing resource-type command * add resource type command in guidance * add schema option * revert * nit * nit * add flow guidance * nit * chore(main): release 1.515.0 (#6292) * chore(main): release 1.515.0 * Apply automatic changes --------- Co-authored-by: rubenfiszel <275584+rubenfiszel@users.noreply.github.com> * fix: improved logs for script * nits logs * chore(main): release 1.515.1 (#6295) * chore(main): release 1.515.1 * Apply automatic changes --------- Co-authored-by: rubenfiszel <275584+rubenfiszel@users.noreply.github.com> * merge * even more indexer tracings * add more tracing logs * feat: prevent too large results (>500Mb) from OOMing database * nit naming * feat: add CA certificate update at startup via environment variable (#6280) * feat: add CA certificate update at startup via environment variable Add support for running 'update-ca-certificates' at binary startup when RUN_UPDATE_CA_CERTIFICATE_AT_START environment variable is set to "true". - Check for RUN_UPDATE_CA_CERTIFICATE_AT_START env var on startup - Execute update-ca-certificates command if env var is set to "true" - Log success/failure appropriately with tracing - Continue startup even if CA certificate update fails - Non-blocking implementation with proper error handling Fixes #6279 Co-authored-by: Ruben Fiszel <rubenfiszel@users.noreply.github.com> * refactor: extract CA certificate update logic into separate function Extract the CA certificate update logic from windmill_main() into a dedicated update_ca_certificates_if_requested() function for better code organization and maintainability. Co-authored-by: Ruben Fiszel <rubenfiszel@users.noreply.github.com> * improvements --------- Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com> Co-authored-by: Ruben Fiszel <rubenfiszel@users.noreply.github.com> Co-authored-by: Alexander Petric <alpetric@users.noreply.github.com> Co-authored-by: Alexander Petric <alex@windmill.dev> * fix: indexer collection of job logs before indexing (#6300) * Add flume as dependecy for indexer * Update ee-repo-ref * Remove flags from cargo.toml * Update ee-repo-ref * Update ee-repo-ref * fix rust sdk build error (#6305) Signed-off-by: pyranota <pyra@duck.com> * fix broken audit logs filter (#6304) * rename to from to * goto fix * default to false if field not present operator settings (#6301) * git sync UI improvements (#6303) * ui improvements round 1 * modal cleanup * init * UI refactor * UI cleanup + refactor * legacy cleanup * success model -> github actions, non-ee warnings * sqlx * npm check * ee warning everywhere * last comments * formatting * no hardcoded theme * claude review improvemenets * fix: no process relative imports for scripts with codebase * fix: sqs oidc authentication disconnect #6307 * handle metadata for new scripts happen after commit * handle_deployment_metadata in a task * nits * chore: add windmill-utils-internal package (#6299) * add utils package * naming * cleaning * add docs * remove log * use autogenerated types * remove old * fix * cleaning * add docs * chore(main): release 1.516.0 (#6298) * chore(main): release 1.516.0 * Apply automatic changes --------- Co-authored-by: rubenfiszel <275584+rubenfiszel@users.noreply.github.com> * merge * indexer improvements * upgrade tantivy to 0.24.2 * use tantivy fork * nit warnings * fix oss build * improve indexer * chore: use windmill-utils-internal for cli (#6297) * add utils package * naming * cleaning * simplify assignPath * rename old files * same for locks * create on confirm * default true * use replaceinlinescripts from utils * use extractscriptfromflows * make it compile * cleaning * use argsigtojson * fix * fix missing await * cleaner * cleaning * cleaning * use in frontend * add docs * testing * remove log * use autogenerated types * remove old * fix * cleaning * adapt usage * draft * better build script * fix build * revert to default creation * add docs * remove and rename * make everything work * add await * only if not installed * add vs code setting * add to publish action * fix bc * safer use of sep * fix * do not rename on push * no publish on release * use published package on frontend * nit * Add dependencies to run sqlx prepare to nix flake (#6309) * feat(cli): wmill-lock.yaml v2 for easier git merge diffs * merge * merge * all * all * rm warnings * fix styling on aichatinput (#6312) * fix: use with_capacity back presusre for tantivy directory multipart writes (#6313) * use with capacity for tantivy directory multi part uploads * Update ee repo ref * Update ee-repo-ref * Update ee-repo-ref * chore(main): release 1.517.0 (#6310) * chore(main): release 1.517.0 * Apply automatic changes --------- Co-authored-by: rubenfiszel <275584+rubenfiszel@users.noreply.github.com> * fix typo on cli build (#6314) * cleanup * feat(utils): add flow.yaml validation function (#6316) * add validateflow function * cleaner code * preprocess json * cleaning * create specific package * cleaning * add tests * fix: cleanup concurrency_counter automatically + remove orphans keys automatically * fix: add disabled support to resource picker in schema forms * fix: add wm_labels to tracing spans * all * merge * all * fix: delete empty git connection (#6318) * fix checks * bun handling * all * all? * all * all * update * all * update * check * fix history * all * all * all * Remove leftover debug tracing statements - Remove commented debug trace in jobs.rs for stream output - Remove commented debug trace in result_stream.rs for stream processing Co-authored-by: Ruben Fiszel <rubenfiszel@users.noreply.github.com> * fix test * all * handle iter * fix --------- Signed-off-by: pyranota <pyra@duck.com> Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com> Co-authored-by: Ruben Fiszel <rubenfiszel@users.noreply.github.com> Co-authored-by: Ruben Fiszel <ruben@windmill.dev> Co-authored-by: centdix <40307056+centdix@users.noreply.github.com> Co-authored-by: dieriba <dieriba.pro@gmail.com> Co-authored-by: rubenfiszel <275584+rubenfiszel@users.noreply.github.com> Co-authored-by: wendrul <53628737+wendrul@users.noreply.github.com> Co-authored-by: Diego Imbert <70353967+diegoimbert@users.noreply.github.com> Co-authored-by: Alexander Petric <alpetric@users.noreply.github.com> Co-authored-by: Alexander Petric <alex@windmill.dev> Co-authored-by: pyranota <92104930+pyranota@users.noreply.github.com>
646 lines
18 KiB
Rust
646 lines
18 KiB
Rust
use anyhow::anyhow;
|
|
use serde_json::value::RawValue;
|
|
#[cfg(feature = "csharp")]
|
|
use std::{io, path::Path, process::Stdio};
|
|
|
|
use std::collections::HashMap;
|
|
use uuid::Uuid;
|
|
#[cfg(feature = "csharp")]
|
|
use windmill_parser_csharp::parse_csharp_reqs;
|
|
|
|
#[cfg(feature = "csharp")]
|
|
use itertools::Itertools;
|
|
#[cfg(feature = "csharp")]
|
|
use tokio::{fs::File, io::AsyncReadExt, process::Command};
|
|
#[cfg(feature = "csharp")]
|
|
use windmill_common::{
|
|
utils::calculate_hash,
|
|
worker::{save_cache, write_file},
|
|
};
|
|
|
|
use windmill_common::error::{self, Error};
|
|
#[cfg(feature = "csharp")]
|
|
use windmill_queue::append_logs;
|
|
|
|
use windmill_queue::CanceledBy;
|
|
|
|
#[cfg(feature = "csharp")]
|
|
use crate::{
|
|
common::{
|
|
check_executor_binary_exists, create_args_and_out_file, get_reserved_variables,
|
|
read_result, start_child_process,
|
|
},
|
|
handle_child::handle_child,
|
|
CSHARP_CACHE_DIR, DISABLE_NSJAIL, DISABLE_NUSER, DOTNET_PATH, HOME_ENV, NSJAIL_PATH,
|
|
NUGET_CONFIG, PATH_ENV, TZ_ENV,
|
|
};
|
|
|
|
use crate::common::OccupancyMetrics;
|
|
use windmill_common::client::AuthedClient;
|
|
|
|
#[cfg(windows)]
|
|
use crate::SYSTEM_ROOT;
|
|
|
|
#[cfg(feature = "csharp")]
|
|
const NSJAIL_CONFIG_RUN_CSHARP_CONTENT: &str = include_str!("../nsjail/run.csharp.config.proto");
|
|
|
|
#[cfg(feature = "csharp")]
|
|
#[cfg(windows)]
|
|
const DOTNET_ROOT_DEFAULT: &str = "C:\\Program Files\\dotnet";
|
|
|
|
#[cfg(feature = "csharp")]
|
|
#[cfg(unix)]
|
|
const DOTNET_ROOT_DEFAULT: &str = "/usr/share/dotnet";
|
|
|
|
#[cfg(feature = "csharp")]
|
|
lazy_static::lazy_static! {
|
|
static ref DOTNET_ROOT: String = std::env::var("DOTNET_ROOT").unwrap_or_else(|_| DOTNET_ROOT_DEFAULT.to_string());
|
|
}
|
|
|
|
#[cfg(feature = "csharp")]
|
|
const CSHARP_OBJECT_STORE_PREFIX: &str = "csharpbin/";
|
|
|
|
#[cfg(feature = "csharp")]
|
|
pub async fn generate_nuget_lockfile(
|
|
job_id: &Uuid,
|
|
code: &str,
|
|
mem_peak: &mut i32,
|
|
canceled_by: &mut Option<CanceledBy>,
|
|
job_dir: &str,
|
|
conn: &Connection,
|
|
worker_name: &str,
|
|
w_id: &str,
|
|
occupancy_metrics: &mut OccupancyMetrics,
|
|
) -> error::Result<String> {
|
|
check_executor_binary_exists("dotnet", DOTNET_PATH.as_str(), "C#")?;
|
|
|
|
if let Some(nuget_config) = NUGET_CONFIG.read().await.clone() {
|
|
write_file(job_dir, "nuget.config", &nuget_config)?;
|
|
}
|
|
|
|
let (reqs, lines_to_remove) = parse_csharp_reqs(code);
|
|
|
|
gen_cs_proj(code, job_dir, reqs, lines_to_remove)?;
|
|
|
|
let mut gen_lockfile_cmd = Command::new(DOTNET_PATH.as_str());
|
|
gen_lockfile_cmd
|
|
.current_dir(job_dir)
|
|
.args(vec!["restore", "--use-lock-file"])
|
|
.stdout(Stdio::piped())
|
|
.stderr(Stdio::piped());
|
|
#[cfg(windows)]
|
|
gen_lockfile_cmd
|
|
.env("SystemRoot", SYSTEM_ROOT.as_str())
|
|
.env("SystemRoot", SYSTEM_ROOT.as_str())
|
|
.env(
|
|
"TMP",
|
|
std::env::var("TMP").unwrap_or_else(|_| "C:\\tmp".to_string()),
|
|
)
|
|
.env("USERPROFILE", crate::USERPROFILE_ENV.as_str())
|
|
.env(
|
|
"APPDATA",
|
|
std::env::var("APPDATA")
|
|
.unwrap_or_else(|_| format!("{}\\AppData\\Roaming", HOME_ENV.as_str())),
|
|
)
|
|
.env(
|
|
"ProgramFiles",
|
|
std::env::var("ProgramFiles").unwrap_or_else(|_| String::from("C:\\Program Files")),
|
|
)
|
|
.env(
|
|
"LOCALAPPDATA",
|
|
std::env::var("LOCALAPPDATA")
|
|
.unwrap_or_else(|_| format!("{}\\AppData\\Local", HOME_ENV.as_str())),
|
|
);
|
|
|
|
let gen_lockfile_process = start_child_process(gen_lockfile_cmd, DOTNET_PATH.as_str()).await?;
|
|
handle_child(
|
|
job_id,
|
|
conn,
|
|
mem_peak,
|
|
canceled_by,
|
|
gen_lockfile_process,
|
|
false,
|
|
worker_name,
|
|
w_id,
|
|
"dotnet restore",
|
|
None,
|
|
false,
|
|
&mut Some(occupancy_metrics),
|
|
None,
|
|
)
|
|
.await?;
|
|
|
|
if let Err(e) = std::fs::remove_file(Path::new(job_dir).join("nuget.config")) {
|
|
if e.kind() != io::ErrorKind::NotFound {
|
|
Err(anyhow!("Error erasing nuget.config: {}", e))?;
|
|
}
|
|
}
|
|
|
|
let path_lock = format!("{job_dir}/packages.lock.json");
|
|
let mut file = File::open(path_lock).await?;
|
|
let mut req_content = String::new();
|
|
file.read_to_string(&mut req_content).await?;
|
|
Ok(req_content)
|
|
}
|
|
|
|
#[cfg(not(feature = "csharp"))]
|
|
pub async fn generate_nuget_lockfile(
|
|
_job_id: &Uuid,
|
|
_code: &str,
|
|
_mem_peak: &mut i32,
|
|
_canceled_by: &mut Option<CanceledBy>,
|
|
_job_dir: &str,
|
|
_conn: &Connection,
|
|
_worker_name: &str,
|
|
_w_id: &str,
|
|
_occupancy_metrics: &mut OccupancyMetrics,
|
|
) -> error::Result<String> {
|
|
Err(anyhow!("C# is not available because the feature is not enabled").into())
|
|
}
|
|
|
|
#[cfg(feature = "csharp")]
|
|
fn gen_cs_proj(
|
|
code: &str,
|
|
job_dir: &str,
|
|
reqs: Vec<(String, Option<String>)>,
|
|
lines_to_remove: Vec<usize>,
|
|
) -> anyhow::Result<()> {
|
|
let code = remove_lines_from_text(code, lines_to_remove);
|
|
|
|
let pkgs = reqs
|
|
.into_iter()
|
|
.map(|(pkg, vrsion_o)| {
|
|
let version = vrsion_o
|
|
.map(|v| format!("Version=\"{v}\""))
|
|
.unwrap_or("".to_string());
|
|
format!(" <PackageReference Include=\"{pkg}\" {version}/>")
|
|
})
|
|
.join("\n");
|
|
|
|
let item_group = if pkgs.is_empty() {
|
|
"".to_string()
|
|
} else {
|
|
format!(
|
|
r#" <ItemGroup>
|
|
{pkgs}
|
|
</ItemGroup>
|
|
"#
|
|
)
|
|
};
|
|
|
|
write_file(
|
|
job_dir,
|
|
"Main.csproj",
|
|
&format!(
|
|
r#"<Project Sdk="Microsoft.NET.Sdk">
|
|
<PropertyGroup>
|
|
<OutputType>Exe</OutputType>
|
|
<TargetFramework>net9.0</TargetFramework>
|
|
<ImplicitUsings>enable</ImplicitUsings>
|
|
<StartupObject>WindmillScriptCSharpInternal.Wrapper</StartupObject>
|
|
<RestorePackagesWithLockFile>true</RestorePackagesWithLockFile>
|
|
</PropertyGroup>
|
|
{item_group}
|
|
</Project>
|
|
"#
|
|
),
|
|
)?;
|
|
|
|
write_file(job_dir, "Script.cs", code.as_str())?;
|
|
|
|
let sig_meta = windmill_parser_csharp::parse_csharp_sig_meta(code.as_str())?;
|
|
let sig = sig_meta.main_sig;
|
|
let spread = &sig
|
|
.args
|
|
.clone()
|
|
.into_iter()
|
|
.map(|x| format!("parsedArgs.{}", &x.name))
|
|
.join(", ");
|
|
let args_class_body = &sig
|
|
.args
|
|
.into_iter()
|
|
.map(|x| {
|
|
Ok(format!(
|
|
" public {} {} {{ get; set; }}",
|
|
x.otyp
|
|
.ok_or(anyhow!("Type not found for argument {}", x.name))?,
|
|
&x.name,
|
|
))
|
|
})
|
|
.collect::<Result<Vec<String>, anyhow::Error>>()?
|
|
.join("\n");
|
|
|
|
let class_name = sig_meta.class_name.unwrap_or("Script".to_string());
|
|
|
|
let script_call = match (sig_meta.is_async, sig_meta.returns_void) {
|
|
(true, true) => format!(
|
|
r#"
|
|
{class_name}.Main({spread}).Wait();
|
|
File.WriteAllText("result.json", "null");
|
|
"#
|
|
),
|
|
(false, true) => format!(
|
|
r#"
|
|
{class_name}.Main({spread});
|
|
File.WriteAllText("result.json", "null");
|
|
"#
|
|
),
|
|
|
|
(false, false) => format!(
|
|
r#"
|
|
var result = {class_name}.Main({spread});
|
|
|
|
var jsonResult = JsonSerializer.Serialize(result);
|
|
|
|
File.WriteAllText("result.json", jsonResult);"#
|
|
),
|
|
(true, false) => format!(
|
|
r#"
|
|
var result = {class_name}.Main({spread}).Result;
|
|
|
|
var jsonResult = JsonSerializer.Serialize(result);
|
|
|
|
File.WriteAllText("result.json", jsonResult);"#
|
|
),
|
|
};
|
|
|
|
write_file(
|
|
job_dir,
|
|
"Wrapper.cs",
|
|
&format!(
|
|
r#"using System;
|
|
using System.IO;
|
|
using System.Text.Json;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace WindmillScriptCSharpInternal {{
|
|
|
|
struct Args {{
|
|
{args_class_body}
|
|
}}
|
|
|
|
class Wrapper
|
|
{{
|
|
static void Main(string[] args)
|
|
{{
|
|
using FileStream fs = File.OpenRead("args.json");
|
|
Args parsedArgs = JsonSerializer.Deserialize<Args>(fs);
|
|
|
|
try
|
|
{{
|
|
{script_call}
|
|
}}
|
|
catch (Exception ex)
|
|
{{
|
|
Console.Error.WriteLine("Unhandeled Exception: " + ex.ToString());
|
|
Environment.Exit(1);
|
|
}}
|
|
}}
|
|
}}
|
|
}}
|
|
"#,
|
|
),
|
|
)?;
|
|
|
|
Ok(())
|
|
}
|
|
|
|
#[cfg(feature = "csharp")]
|
|
async fn build_cs_proj(
|
|
job_id: &Uuid,
|
|
mem_peak: &mut i32,
|
|
canceled_by: &mut Option<CanceledBy>,
|
|
job_dir: &str,
|
|
conn: &Connection,
|
|
worker_name: &str,
|
|
w_id: &str,
|
|
base_internal_url: &str,
|
|
hash: &str,
|
|
occupancy_metrics: &mut OccupancyMetrics,
|
|
) -> error::Result<String> {
|
|
if let Some(nuget_config) = NUGET_CONFIG.read().await.clone() {
|
|
write_file(job_dir, "nuget.config", &nuget_config)?;
|
|
}
|
|
|
|
let mut build_cs_cmd = Command::new(DOTNET_PATH.as_str());
|
|
build_cs_cmd
|
|
.current_dir(job_dir)
|
|
.env_clear()
|
|
.env("PATH", PATH_ENV.as_str())
|
|
.env("BASE_INTERNAL_URL", base_internal_url)
|
|
.env("HOME", HOME_ENV.as_str())
|
|
.env("DOTNET_CLI_TELEMETRY_OPTOUT", "true")
|
|
.env("DOTNET_NOLOGO", "true")
|
|
.env("DOTNET_ROOT", DOTNET_ROOT.as_str())
|
|
.args(vec![
|
|
"publish",
|
|
"--configuration",
|
|
"Release",
|
|
"-o",
|
|
job_dir,
|
|
"--no-self-contained",
|
|
"-p:PublishSingleFile=true",
|
|
"-p:IncludeNativeLibrariesForSelfExtract=true",
|
|
])
|
|
.stdout(Stdio::piped())
|
|
.stderr(Stdio::piped());
|
|
|
|
#[cfg(windows)]
|
|
build_cs_cmd
|
|
.env("SystemRoot", SYSTEM_ROOT.as_str())
|
|
.env(
|
|
"TMP",
|
|
std::env::var("TMP").unwrap_or_else(|_| "C:\\tmp".to_string()),
|
|
)
|
|
.env("USERPROFILE", crate::USERPROFILE_ENV.as_str())
|
|
.env(
|
|
"APPDATA",
|
|
std::env::var("APPDATA")
|
|
.unwrap_or_else(|_| format!("{}\\AppData\\Roaming", HOME_ENV.as_str())),
|
|
)
|
|
.env(
|
|
"ProgramFiles",
|
|
std::env::var("ProgramFiles").unwrap_or_else(|_| String::from("C:\\Program Files")),
|
|
)
|
|
.env(
|
|
"LOCALAPPDATA",
|
|
std::env::var("LOCALAPPDATA")
|
|
.unwrap_or_else(|_| format!("{}\\AppData\\Local", HOME_ENV.as_str())),
|
|
);
|
|
|
|
let build_cs_process = start_child_process(build_cs_cmd, DOTNET_PATH.as_str()).await?;
|
|
handle_child(
|
|
job_id,
|
|
conn,
|
|
mem_peak,
|
|
canceled_by,
|
|
build_cs_process,
|
|
false,
|
|
worker_name,
|
|
w_id,
|
|
"dotnet publish",
|
|
None,
|
|
false,
|
|
&mut Some(occupancy_metrics),
|
|
None,
|
|
)
|
|
.await?;
|
|
append_logs(job_id, w_id, "\n\n", conn).await;
|
|
if let Err(e) = std::fs::remove_file(Path::new(job_dir).join("nuget.config")) {
|
|
if e.kind() != io::ErrorKind::NotFound {
|
|
Err(anyhow!("Error erasing nuget.config: {}", e))?;
|
|
}
|
|
}
|
|
|
|
let bin_path = format!("{}/{hash}", CSHARP_CACHE_DIR);
|
|
#[cfg(unix)]
|
|
let target = format!("{job_dir}/Main");
|
|
#[cfg(windows)]
|
|
let target = format!("{job_dir}/Main.exe");
|
|
|
|
match save_cache(
|
|
&bin_path,
|
|
&format!("{CSHARP_OBJECT_STORE_PREFIX}{hash}"),
|
|
&target,
|
|
false,
|
|
)
|
|
.await
|
|
{
|
|
Err(e) => {
|
|
let em = format!("could not save {job_dir}/Main to C# cache: {e:?}",);
|
|
tracing::error!(em);
|
|
Ok(em)
|
|
}
|
|
Ok(logs) => Ok(logs),
|
|
}
|
|
}
|
|
|
|
#[cfg(feature = "csharp")]
|
|
fn remove_lines_from_text(contents: &str, indices_to_remove: Vec<usize>) -> String {
|
|
let mut result = Vec::new();
|
|
|
|
for (i, line) in contents.lines().enumerate() {
|
|
if !indices_to_remove.contains(&i) {
|
|
result.push(line);
|
|
}
|
|
}
|
|
|
|
result.join("\n")
|
|
}
|
|
|
|
use windmill_common::worker::Connection;
|
|
use windmill_queue::MiniPulledJob;
|
|
|
|
#[cfg(not(feature = "csharp"))]
|
|
pub async fn handle_csharp_job(
|
|
_mem_peak: &mut i32,
|
|
_canceled_by: &mut Option<CanceledBy>,
|
|
_job: &MiniPulledJob,
|
|
_conn: &Connection,
|
|
_client: &AuthedClient,
|
|
_parent_runnable_path: Option<String>,
|
|
_inner_content: &str,
|
|
_job_dir: &str,
|
|
_requirements_o: Option<&String>,
|
|
_shared_mount: &str,
|
|
_base_internal_url: &str,
|
|
_worker_name: &str,
|
|
_envs: HashMap<String, String>,
|
|
_occupancy_metrics: &mut OccupancyMetrics,
|
|
) -> Result<Box<RawValue>, Error> {
|
|
Err(anyhow!("C# is not available because the feature is not enabled").into())
|
|
}
|
|
#[cfg(feature = "csharp")]
|
|
pub async fn handle_csharp_job(
|
|
mem_peak: &mut i32,
|
|
canceled_by: &mut Option<CanceledBy>,
|
|
job: &MiniPulledJob,
|
|
conn: &Connection,
|
|
client: &AuthedClient,
|
|
parent_runnable_path: Option<String>,
|
|
inner_content: &str,
|
|
job_dir: &str,
|
|
requirements_o: Option<&String>,
|
|
shared_mount: &str,
|
|
base_internal_url: &str,
|
|
worker_name: &str,
|
|
envs: HashMap<String, String>,
|
|
occupancy_metrics: &mut OccupancyMetrics,
|
|
) -> Result<Box<RawValue>, Error> {
|
|
check_executor_binary_exists("dotnet", DOTNET_PATH.as_str(), "C#")?;
|
|
|
|
let hash = calculate_hash(&format!(
|
|
"{}{}",
|
|
inner_content,
|
|
requirements_o.unwrap_or(&String::new())
|
|
));
|
|
let bin_path = format!("{}/{hash}", CSHARP_CACHE_DIR);
|
|
let remote_path = format!("{CSHARP_OBJECT_STORE_PREFIX}{hash}");
|
|
|
|
let (cache, cache_logs) =
|
|
windmill_common::worker::load_cache(&bin_path, &remote_path, false).await;
|
|
|
|
let cache_logs = if cache {
|
|
#[cfg(unix)]
|
|
{
|
|
let target = format!("{job_dir}/Main");
|
|
let symlink = std::os::unix::fs::symlink(&bin_path, &target);
|
|
symlink.map_err(|e| {
|
|
Error::ExecutionErr(format!(
|
|
"could not copy cached binary from {bin_path} to {job_dir}/Main: {e:?}"
|
|
))
|
|
})?;
|
|
}
|
|
|
|
cache_logs
|
|
} else {
|
|
let logs1 = format!("{cache_logs}\n\n--- DOTNET BUILD ---\n");
|
|
append_logs(&job.id, &job.workspace_id, logs1, conn).await;
|
|
|
|
let (reqs, lines_to_remove) = parse_csharp_reqs(inner_content);
|
|
for req in &reqs {
|
|
append_logs(
|
|
&job.id,
|
|
&job.workspace_id,
|
|
format!(
|
|
"Requirement detected: {} {}\n",
|
|
req.0,
|
|
req.1.as_ref().unwrap_or(&"".to_string())
|
|
),
|
|
conn,
|
|
)
|
|
.await;
|
|
}
|
|
|
|
gen_cs_proj(inner_content, job_dir, reqs, lines_to_remove)?;
|
|
|
|
if let Some(reqs) = requirements_o {
|
|
if !reqs.is_empty() {
|
|
write_file(job_dir, "packages.lock.json", &reqs)?;
|
|
}
|
|
}
|
|
|
|
build_cs_proj(
|
|
&job.id,
|
|
mem_peak,
|
|
canceled_by,
|
|
job_dir,
|
|
conn,
|
|
worker_name,
|
|
&job.workspace_id,
|
|
base_internal_url,
|
|
&hash,
|
|
occupancy_metrics,
|
|
)
|
|
.await?
|
|
};
|
|
|
|
create_args_and_out_file(client, job, job_dir, conn).await?;
|
|
|
|
let logs2 = format!("{cache_logs}\n\n--- C# CODE EXECUTION ---\n");
|
|
append_logs(&job.id, &job.workspace_id, format!("{}\n", logs2), conn).await;
|
|
|
|
let reserved_variables =
|
|
get_reserved_variables(job, &client.token, conn, parent_runnable_path).await?;
|
|
|
|
let child = if !*DISABLE_NSJAIL {
|
|
write_file(
|
|
job_dir,
|
|
"run.config.proto",
|
|
&NSJAIL_CONFIG_RUN_CSHARP_CONTENT
|
|
.replace("{JOB_DIR}", job_dir)
|
|
.replace("{CACHE_DIR}", CSHARP_CACHE_DIR)
|
|
.replace("{CACHE_HASH}", &hash)
|
|
.replace("{CLONE_NEWUSER}", &(!*DISABLE_NUSER).to_string())
|
|
.replace("{SHARED_MOUNT}", shared_mount),
|
|
)?;
|
|
let mut nsjail_cmd = Command::new(NSJAIL_PATH.as_str());
|
|
nsjail_cmd
|
|
.current_dir(job_dir)
|
|
.env_clear()
|
|
.envs(envs)
|
|
.envs(reserved_variables)
|
|
.env("PATH", PATH_ENV.as_str())
|
|
.env("TZ", TZ_ENV.as_str())
|
|
.env("BASE_INTERNAL_URL", base_internal_url)
|
|
.env("DOTNET_CLI_TELEMETRY_OPTOUT", "true")
|
|
.env("DOTNET_NOLOGO", "true")
|
|
.env("DOTNET_ROOT", DOTNET_ROOT.as_str())
|
|
.args(vec!["--config", "run.config.proto", "--", "/tmp/main"])
|
|
.stdout(Stdio::piped())
|
|
.stderr(Stdio::piped());
|
|
|
|
#[cfg(windows)]
|
|
nsjail_cmd.env("SystemRoot", SYSTEM_ROOT.as_str());
|
|
|
|
start_child_process(nsjail_cmd, NSJAIL_PATH.as_str()).await?
|
|
} else {
|
|
#[cfg(unix)]
|
|
let compiled_executable_name = "./Main".to_string();
|
|
#[cfg(windows)]
|
|
let compiled_executable_name = if cache {
|
|
bin_path.to_string()
|
|
} else {
|
|
format!("{job_dir}/Main.exe")
|
|
};
|
|
let mut run_csharp = Command::new(&compiled_executable_name);
|
|
run_csharp
|
|
.current_dir(job_dir)
|
|
.env_clear()
|
|
.envs(envs)
|
|
.envs(reserved_variables)
|
|
.env("PATH", PATH_ENV.as_str())
|
|
.env("TZ", TZ_ENV.as_str())
|
|
.env("DOTNET_CLI_TELEMETRY_OPTOUT", "true")
|
|
.env("DOTNET_NOLOGO", "true")
|
|
.env("DOTNET_ROOT", DOTNET_ROOT.as_str())
|
|
.env("BASE_INTERNAL_URL", base_internal_url)
|
|
.env("HOME", HOME_ENV.as_str())
|
|
.stdout(Stdio::piped())
|
|
.stderr(Stdio::piped());
|
|
#[cfg(windows)]
|
|
run_csharp
|
|
.env("SystemRoot", SYSTEM_ROOT.as_str())
|
|
.env("SystemRoot", SYSTEM_ROOT.as_str())
|
|
.env(
|
|
"TMP",
|
|
std::env::var("TMP").unwrap_or_else(|_| "C:\\tmp".to_string()),
|
|
)
|
|
.env("USERPROFILE", crate::USERPROFILE_ENV.as_str())
|
|
.env(
|
|
"APPDATA",
|
|
std::env::var("APPDATA")
|
|
.unwrap_or_else(|_| format!("{}\\AppData\\Roaming", HOME_ENV.as_str())),
|
|
)
|
|
.env(
|
|
"ProgramFiles",
|
|
std::env::var("ProgramFiles").unwrap_or_else(|_| String::from("C:\\Program Files")),
|
|
)
|
|
.env(
|
|
"LOCALAPPDATA",
|
|
std::env::var("LOCALAPPDATA")
|
|
.unwrap_or_else(|_| format!("{}\\AppData\\Local", HOME_ENV.as_str())),
|
|
);
|
|
|
|
start_child_process(run_csharp, &compiled_executable_name).await?
|
|
};
|
|
|
|
handle_child(
|
|
&job.id,
|
|
conn,
|
|
mem_peak,
|
|
canceled_by,
|
|
child,
|
|
!*DISABLE_NSJAIL,
|
|
worker_name,
|
|
&job.workspace_id,
|
|
"csharp run",
|
|
job.timeout,
|
|
false,
|
|
&mut Some(occupancy_metrics),
|
|
None,
|
|
)
|
|
.await?;
|
|
read_result(job_dir, None).await
|
|
}
|