-
Notifications
You must be signed in to change notification settings - Fork 307
Expand file tree
/
Copy pathfastflowlm_server.cpp
More file actions
688 lines (579 loc) · 26.3 KB
/
fastflowlm_server.cpp
File metadata and controls
688 lines (579 loc) · 26.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
#include "lemon/backends/fastflowlm_server.h"
#include "lemon/system_info.h"
#include "lemon/error_types.h"
#include "lemon/utils/process_manager.h"
#include "lemon/utils/http_client.h"
#include "lemon/utils/path_utils.h"
#include "lemon/utils/version_utils.h"
#include "lemon/utils/json_utils.h"
#include <iostream>
#include <filesystem>
#include <cstdlib>
#include <thread>
#include <chrono>
#include <sstream>
#include <lemon/utils/aixlog.hpp>
#ifdef _WIN32
#include <windows.h>
#include <comdef.h>
#include <Wbemidl.h>
#include <shellapi.h>
#include "../utils/wmi_helper.h"
#pragma comment(lib, "wbemuuid.lib")
#else
#include <sys/utsname.h>
#endif
// URL to direct users to for driver updates
static const std::string DRIVER_INSTALL_URL = "https://lemonade-server.ai/driver_install.html";
namespace fs = std::filesystem;
namespace lemon {
namespace backends {
FastFlowLMServer::FastFlowLMServer(const std::string& log_level, ModelManager* model_manager,
BackendManager* backend_manager)
: WrappedServer("FastFlowLM", log_level, model_manager, backend_manager) {
}
FastFlowLMServer::~FastFlowLMServer() {
unload();
}
void FastFlowLMServer::install(const std::string& backend) {
#ifndef _WIN32
auto status = SystemInfoCache::get_flm_status();
throw std::runtime_error(
"Visit the documentation for installation instructions. " +
std::string(status.action.empty() ? "" : status.action));
#else
LOG(INFO, "FastFlowLM") << "[FastFlowLM] Checking FLM installation..." << std::endl;
try {
install_flm_if_needed();
// Verify flm is now available
std::string flm_path = get_flm_path();
if (flm_path.empty()) {
throw std::runtime_error("FLM installation failed - not found in PATH");
}
LOG(INFO, "FastFlowLM") << "FLM ready at: " << flm_path << std::endl;
// Signal system-info to re-evaluate FLM status
SystemInfoCache::invalidate_recipes();
} catch (const std::exception& e) {
// Fallback: show manual installation instructions
std::string required_version = get_flm_required_version();
LOG(ERROR, "FastFlowLM") << "FLM installation failed: " << e.what() << std::endl;
LOG(ERROR, "FastFlowLM") << "Please install FLM " << required_version << " manually:" << std::endl;
LOG(ERROR, "FastFlowLM") << " https://github.com/FastFlowLM/FastFlowLM/releases/download/"
<< required_version << "/flm-setup.exe" << std::endl;
LOG(ERROR, "FastFlowLM") << "After installation, restart your terminal and try again." << std::endl;
throw;
}
#endif
}
std::string FastFlowLMServer::download_model(const std::string& checkpoint, bool do_not_upgrade) {
LOG(INFO, "FastFlowLM") << "Pulling model with FLM: " << checkpoint << std::endl;
// Use flm pull command to download the model
std::string flm_path = get_flm_path();
if (flm_path.empty()) {
throw std::runtime_error("FLM not found");
}
std::vector<std::string> args = {"pull", checkpoint};
if (!do_not_upgrade) {
args.push_back("--force");
}
LOG(INFO, "ProcessManager") << "Starting process: \"" << flm_path << "\"";
for (const auto& arg : args) {
LOG(INFO, "ProcessManager") << " \"" << arg << "\"";
}
LOG(INFO, "ProcessManager") << std::endl;
// Run flm pull command (with debug output if enabled)
auto handle = utils::ProcessManager::start_process(flm_path, args, "", is_debug());
// Wait for download to complete
if (!utils::ProcessManager::is_running(handle)) {
int exit_code = utils::ProcessManager::get_exit_code(handle);
LOG(ERROR, "FastFlowLM") << "FLM pull failed with exit code: " << exit_code << std::endl;
throw std::runtime_error("FLM pull failed");
}
// Wait for process to complete
int timeout_seconds = 300; // 5 minutes
LOG(INFO, "FastFlowLM") << "Waiting for model download to complete..." << std::endl;
for (int i = 0; i < timeout_seconds * 10; ++i) {
if (!utils::ProcessManager::is_running(handle)) {
int exit_code = utils::ProcessManager::get_exit_code(handle);
if (exit_code != 0) {
LOG(ERROR, "FastFlowLM") << "FLM pull failed with exit code: " << exit_code << std::endl;
throw std::runtime_error("FLM pull failed with exit code: " + std::to_string(exit_code));
}
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
// Print progress every 5 seconds
if (i % 50 == 0 && i > 0) {
LOG(INFO, "FastFlowLM") << "Still downloading... (" << (i/10) << "s elapsed)" << std::endl;
}
}
LOG(INFO, "FastFlowLM") << "Model pull completed successfully" << std::endl;
return checkpoint;
}
void FastFlowLMServer::load(const std::string& model_name,
const ModelInfo& model_info,
const RecipeOptions& options,
bool do_not_upgrade) {
LOG(INFO, "FastFlowLM") << "Loading model: " << model_name << std::endl;
// Get FLM-specific options from RecipeOptions
int ctx_size = options.get_option("ctx_size");
std::string flm_args = options.get_option("flm_args");
std::cout << "[FastFlowLM] Options: ctx_size=" << ctx_size;
if (!flm_args.empty()) {
std::cout << ", flm_args=\"" << flm_args << "\"";
}
std::cout << std::endl;
// Note: checkpoint_ is set by Router via set_model_metadata() before load() is called
// We use checkpoint_ (base class field) for FLM API calls
// Check FLM is ready via system-info (single source of truth)
auto status = SystemInfoCache::get_flm_status();
if (!status.is_ready()) {
throw std::runtime_error(status.error_string());
}
// Download model if needed
download_model(model_info.checkpoint(), do_not_upgrade);
// Choose a port
port_ = choose_port();
// Get flm executable path
std::string flm_path = get_flm_path();
// Construct flm serve command based on model type
// Bind to localhost only for security
std::vector<std::string> args;
if (model_type_ == ModelType::AUDIO) {
// ASR mode: flm serve --asr 1
args = {
"serve",
"--asr", "1",
"--port", std::to_string(port_),
"--host", "127.0.0.1",
"--quiet"
};
} else if (model_type_ == ModelType::EMBEDDING) {
// Embedding mode: flm serve --embed 1
args = {
"serve",
"--embed", "1",
"--port", std::to_string(port_),
"--host", "127.0.0.1",
"--quiet"
};
} else {
// LLM mode (default): flm serve <checkpoint> --ctx-len N
args = {
"serve",
model_info.checkpoint(),
"--ctx-len", std::to_string(ctx_size),
"--port", std::to_string(port_),
"--host", "127.0.0.1",
"--quiet"
};
}
// Parse and append custom flm_args if provided
if (!flm_args.empty()) {
std::istringstream iss(flm_args);
std::string token;
while (iss >> token) {
args.push_back(token);
}
}
LOG(INFO, "FastFlowLM") << "Starting flm-server..." << std::endl;
LOG(INFO, "ProcessManager") << "Starting process: \"" << flm_path << "\"";
for (const auto& arg : args) {
LOG(INFO, "ProcessManager") << " \"" << arg << "\"";
}
LOG(INFO, "ProcessManager") << std::endl;
process_handle_ = utils::ProcessManager::start_process(flm_path, args, "", is_debug(), true, {}, server_name_);
LOG(INFO, "ProcessManager") << "Process started successfully" << std::endl;
// Wait for flm-server to be ready
bool ready = wait_for_ready();
if (!ready) {
utils::ProcessManager::stop_process(process_handle_);
process_handle_ = {nullptr, 0}; // Reset to prevent double-stop on destructor
throw std::runtime_error("flm-server failed to start");
}
is_loaded_ = true;
LOG(INFO, "FastFlowLM") << "Model loaded on port " << port_ << std::endl;
}
void FastFlowLMServer::unload() {
LOG(INFO, "FastFlowLM") << "Unloading model..." << std::endl;
if (is_loaded_ && process_handle_.pid != 0) {
utils::ProcessManager::stop_process(process_handle_);
process_handle_ = {nullptr, 0};
port_ = 0;
is_loaded_ = false;
}
}
bool FastFlowLMServer::wait_for_ready() {
// FLM doesn't have a health endpoint, so we use /api/tags to check if it's up
std::string tags_url = get_base_url() + "/api/tags";
LOG(INFO, "FastFlowLM") << "Waiting for " + server_name_ + " to be ready..." << std::endl;
const int max_attempts = 300; // 5 minutes timeout (large models can take time to load)
for (int attempt = 0; attempt < max_attempts; ++attempt) {
// Check if process is still running
if (!utils::ProcessManager::is_running(process_handle_)) {
LOG(ERROR, "FastFlowLM") << server_name_ << " process has terminated!" << std::endl;
int exit_code = utils::ProcessManager::get_exit_code(process_handle_);
LOG(ERROR, "FastFlowLM") << "Process exit code: " << exit_code << std::endl;
LOG(ERROR, "FastFlowLM") << "Troubleshooting tips:" << std::endl;
LOG(ERROR, "FastFlowLM") << " 1. Check if FLM is installed correctly: flm --version" << std::endl;
LOG(ERROR, "FastFlowLM") << " 2. Try running: flm serve <model> --ctx-len 8192 --port 8001" << std::endl;
LOG(ERROR, "FastFlowLM") << " 3. Check NPU drivers are installed (Windows only)" << std::endl;
return false;
}
// Try to reach the /api/tags endpoint
if (utils::HttpClient::is_reachable(tags_url, 1)) {
LOG(INFO, "FastFlowLM") << server_name_ + " is ready!" << std::endl;
return true;
}
// Sleep 1 second between attempts
std::this_thread::sleep_for(std::chrono::seconds(1));
}
LOG(ERROR, "FastFlowLM") << server_name_ << " failed to start within "
<< max_attempts << " seconds" << std::endl;
return false;
}
json FastFlowLMServer::chat_completion(const json& request) {
if (model_type_ == ModelType::AUDIO || model_type_ == ModelType::EMBEDDING) {
return ErrorResponse::from_exception(
UnsupportedOperationException("Chat completion", "FLM " + model_type_to_string(model_type_) + " model")
);
}
// FLM requires the checkpoint name in the request (e.g., "gemma3:4b")
// (whereas llama-server ignores the model name field)
json modified_request = request;
modified_request["model"] = checkpoint_; // Use base class checkpoint field
return forward_request("/v1/chat/completions", modified_request);
}
json FastFlowLMServer::completion(const json& request) {
if (model_type_ == ModelType::AUDIO || model_type_ == ModelType::EMBEDDING) {
return ErrorResponse::from_exception(
UnsupportedOperationException("Text completion", "FLM " + model_type_to_string(model_type_) + " model")
);
}
// FLM requires the checkpoint name in the request (e.g., "lfm2:1.2b")
// (whereas llama-server ignores the model name field)
json modified_request = request;
modified_request["model"] = checkpoint_; // Use base class checkpoint field
return forward_request("/v1/completions", modified_request);
}
json FastFlowLMServer::embeddings(const json& request) {
if (model_type_ == ModelType::AUDIO) {
return ErrorResponse::from_exception(
UnsupportedOperationException("Embeddings", "FLM " + model_type_to_string(model_type_) + " model")
);
}
return forward_request("/v1/embeddings", request);
}
json FastFlowLMServer::reranking(const json& request) {
if (model_type_ != ModelType::LLM) {
return ErrorResponse::from_exception(
UnsupportedOperationException("Reranking", "FLM " + model_type_to_string(model_type_) + " model")
);
}
return forward_request("/v1/rerank", request);
}
json FastFlowLMServer::audio_transcriptions(const json& request) {
if (model_type_ != ModelType::AUDIO) {
return ErrorResponse::from_exception(
UnsupportedOperationException("Audio transcription", "FLM " + model_type_to_string(model_type_) + " model")
);
}
try {
// Extract audio data from request (same format as WhisperServer)
if (!request.contains("file_data")) {
throw std::runtime_error("Missing 'file_data' in request");
}
std::string audio_data = request["file_data"].get<std::string>();
std::string filename = request.value("filename", "audio.wav");
// Determine content type from filename extension
std::filesystem::path filepath(filename);
std::string ext = filepath.extension().string();
std::string content_type = "audio/wav";
if (ext == ".mp3") content_type = "audio/mpeg";
else if (ext == ".m4a") content_type = "audio/mp4";
else if (ext == ".ogg") content_type = "audio/ogg";
else if (ext == ".flac") content_type = "audio/flac";
else if (ext == ".webm") content_type = "audio/webm";
// Build multipart fields for FLM's /v1/audio/transcriptions endpoint
std::vector<utils::MultipartField> fields;
// Audio file field
fields.push_back({
"file",
audio_data,
filepath.filename().string(),
content_type
});
// Model field (required by OpenAI API format)
fields.push_back({"model", checkpoint_, "", ""});
// Optional parameters
if (request.contains("language")) {
fields.push_back({"language", request["language"].get<std::string>(), "", ""});
}
if (request.contains("prompt")) {
fields.push_back({"prompt", request["prompt"].get<std::string>(), "", ""});
}
if (request.contains("response_format")) {
fields.push_back({"response_format", request["response_format"].get<std::string>(), "", ""});
}
if (request.contains("temperature")) {
fields.push_back({"temperature", std::to_string(request["temperature"].get<double>()), "", ""});
}
return forward_multipart_request("/v1/audio/transcriptions", fields);
} catch (const std::exception& e) {
return json{
{"error", {
{"message", std::string("Transcription failed: ") + e.what()},
{"type", "audio_processing_error"}
}}
};
}
}
json FastFlowLMServer::responses(const json& request) {
// Responses API is not supported for FLM backend
return ErrorResponse::from_exception(
UnsupportedOperationException("Responses API", "flm")
);
}
void FastFlowLMServer::forward_streaming_request(const std::string& endpoint,
const std::string& request_body,
httplib::DataSink& sink,
bool sse,
long timeout_seconds) {
// Streaming is only supported for LLM models
if (model_type_ == ModelType::AUDIO || model_type_ == ModelType::EMBEDDING) {
std::string error_msg = "data: {\"error\":{\"message\":\"Streaming not supported for FLM "
+ model_type_to_string(model_type_) + " model\",\"type\":\"unsupported_operation\"}}\n\n";
sink.write(error_msg.c_str(), error_msg.size());
return;
}
// FLM requires the checkpoint name in the model field (e.g., "gemma3:4b"),
// not the Lemonade model name (e.g., "Gemma3-4b-it-FLM")
try {
json request = json::parse(request_body);
request["model"] = checkpoint_; // Use base class checkpoint field
std::string modified_body = request.dump();
// Call base class with modified request
WrappedServer::forward_streaming_request(endpoint, modified_body, sink, sse, timeout_seconds);
} catch (const json::exception& e) {
// If JSON parsing fails, forward original request
WrappedServer::forward_streaming_request(endpoint, request_body, sink, sse, timeout_seconds);
}
}
std::string FastFlowLMServer::get_flm_path() {
// Use shared utility function to find flm executable
// (find_flm_executable refreshes PATH from registry on Windows)
std::string flm_path = utils::find_flm_executable();
if (!flm_path.empty()) {
LOG(INFO, "FastFlowLM") << "Found flm at: " << flm_path << std::endl;
} else {
LOG(ERROR, "FastFlowLM") << "flm not found in PATH" << std::endl;
}
return flm_path;
}
std::string FastFlowLMServer::get_flm_required_version() {
// Get required FLM version from backend_versions.json
std::string config_path = utils::get_resource_path("resources/backend_versions.json");
try {
json config = utils::JsonUtils::load_from_file(config_path);
if (!config.contains("flm") || !config["flm"].is_object()) {
LOG(ERROR, "FastFlowLM") << "backend_versions.json is missing 'flm' section" << std::endl;
return "v0.9.23"; // Fallback default
}
const auto& flm_config = config["flm"];
if (!flm_config.contains("npu") || !flm_config["npu"].is_string()) {
LOG(ERROR, "FastFlowLM") << "backend_versions.json is missing 'flm.npu'" << std::endl;
return "v0.9.23"; // Fallback default
}
return flm_config["npu"].get<std::string>();
} catch (const std::exception& e) {
LOG(ERROR, "FastFlowLM") << "Error reading backend_versions.json: " << e.what() << std::endl;
return "v0.9.23"; // Fallback default
}
}
bool FastFlowLMServer::install_flm_if_needed() {
#ifdef _WIN32
std::string required_version = get_flm_required_version();
std::string current_version = SystemInfo::get_flm_version();
const char* ci_mode = std::getenv("LEMONADE_CI_MODE");
bool is_ci_mode = ci_mode && (
std::string(ci_mode) == "1" ||
std::string(ci_mode) == "true" ||
std::string(ci_mode) == "TRUE" ||
std::string(ci_mode) == "yes" ||
std::string(ci_mode) == "True");
// Parse versions using utility (handles 'v' prefix automatically)
utils::Version required = utils::Version::parse(required_version);
utils::Version current = utils::Version::parse(current_version);
// Case 1: Already have required version or newer
if (!current.empty() && current >= required) {
LOG(INFO, "FastFlowLM") << "FLM " << current_version
<< " is installed (required: " << required_version << ")" << std::endl;
return false; // No upgrade performed
}
// Case 2: Need to install or upgrade
bool is_upgrade = !current_version.empty() && current_version != "unknown";
if (is_upgrade) {
LOG(INFO, "FastFlowLM") << "Upgrading FLM " << current_version
<< " → " << required_version << "..." << std::endl;
} else {
LOG(INFO, "FastFlowLM") << "Installing FLM " << required_version
<< "..." << std::endl;
}
// Determine installer path
char temp_path[MAX_PATH];
GetTempPathA(MAX_PATH, temp_path);
std::string installer_path = std::string(temp_path) + "flm-setup.exe";
// Delete any existing installer file to avoid collisions
// We must succeed here to prevent running a stale installer
if (fs::exists(installer_path)) {
LOG(INFO, "FastFlowLM") << "Removing existing installer at: " << installer_path << std::endl;
try {
fs::remove(installer_path);
} catch (const std::exception& e) {
throw std::runtime_error(
"Could not remove existing installer at " + installer_path + ": " + e.what() +
". Please delete it manually and try again.");
}
// Verify it's actually gone
if (fs::exists(installer_path)) {
throw std::runtime_error(
"Failed to remove existing installer at " + installer_path +
". Please delete it manually and try again.");
}
}
if (!download_flm_installer(installer_path)) {
throw std::runtime_error("Failed to download FLM installer");
}
// Run installer in silent mode for upgrades and CI.
// Fresh installs outside CI keep GUI behavior for local users.
bool force_silent = is_upgrade || is_ci_mode;
if (is_ci_mode && !is_upgrade) {
LOG(INFO, "FastFlowLM") << "CI mode detected, forcing silent FLM installation..." << std::endl;
}
run_flm_installer(installer_path, force_silent);
// Verify installation by calling flm --version again
if (!verify_flm_installation(required_version)) {
throw std::runtime_error("FLM installation verification failed");
}
// Cleanup installer
try {
fs::remove(installer_path);
} catch (...) {
// Ignore cleanup errors
}
LOG(INFO, "FastFlowLM") << "Successfully installed FLM "
<< required_version << std::endl;
#endif
return true; // FLM was installed or upgraded
}
bool FastFlowLMServer::download_flm_installer(const std::string& output_path) {
// Get required version and build download URL
std::string version = get_flm_required_version();
const std::string url =
"https://github.com/FastFlowLM/FastFlowLM/releases/download/" + version + "/flm-setup.exe";
LOG(INFO, "FastFlowLM") << "Downloading FLM " << version << " installer..." << std::endl;
LOG(INFO, "FastFlowLM") << "URL: " << url << std::endl;
// Use default throttled progress callback
utils::ProgressCallback http_progress_cb = utils::create_throttled_progress_callback();
auto result = utils::HttpClient::download_file(url, output_path, http_progress_cb);
if (result.success) {
LOG(INFO, "FastFlowLM") << "Downloaded installer to "
<< output_path << std::endl;
} else {
LOG(ERROR, "FastFlowLM") << "Failed to download installer: "
<< result.error_message << std::endl;
}
return result.success;
}
void FastFlowLMServer::run_flm_installer(const std::string& installer_path, bool silent) {
std::vector<std::string> args;
if (silent) {
args.push_back("/VERYSILENT");
args.push_back("/SUPPRESSMSGBOXES");
args.push_back("/NORESTART");
LOG(INFO, "FastFlowLM") << "Running FLM installer in silent mode..." << std::endl;
} else {
LOG(INFO, "FastFlowLM") << "Launching installer GUI. "
<< "Please complete the installation..." << std::endl;
}
// Launch installer and wait for completion
auto handle = utils::ProcessManager::start_process(installer_path, args, "", false);
LOG(INFO, "FastFlowLM") << "Waiting for installer to complete..." << std::endl;
// Wait for installer to complete
int timeout_seconds = 300; // 5 minutes
for (int i = 0; i < timeout_seconds * 2; ++i) {
if (!utils::ProcessManager::is_running(handle)) {
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(500));
// Print progress every 10 seconds
if (!silent && i % 20 == 0 && i > 0) {
LOG(INFO, "FastFlowLM") << "Still waiting... (" << (i/2) << "s elapsed)" << std::endl;
}
}
int exit_code = utils::ProcessManager::get_exit_code(handle);
if (exit_code != 0) {
throw std::runtime_error(
"FLM installer failed with exit code: " + std::to_string(exit_code));
}
LOG(INFO, "FastFlowLM") << "Installer completed successfully" << std::endl;
}
void FastFlowLMServer::refresh_environment_path() {
#ifdef _WIN32
// Refresh PATH from Windows registry
HKEY hKey;
if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,
"SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment",
0, KEY_READ, &hKey) == ERROR_SUCCESS) {
char buffer[32767];
DWORD bufferSize = sizeof(buffer);
if (RegQueryValueExA(hKey, "PATH", nullptr, nullptr,
reinterpret_cast<LPBYTE>(buffer), &bufferSize) == ERROR_SUCCESS) {
std::string new_path = buffer;
// Append to existing PATH instead of replacing
const char* current_path = getenv("PATH");
if (current_path) {
new_path = new_path + ";" + std::string(current_path);
}
_putenv(("PATH=" + new_path).c_str());
}
RegCloseKey(hKey);
}
// Add default FLM installation path if not already in PATH
const std::string flm_dir = "C:\\Program Files\\flm";
if (fs::exists(flm_dir)) {
const char* current_path = getenv("PATH");
std::string current_path_str = current_path ? current_path : "";
if (current_path_str.find(flm_dir) == std::string::npos) {
_putenv(("PATH=" + flm_dir + ";" + current_path_str).c_str());
}
}
#endif
}
bool FastFlowLMServer::verify_flm_installation(const std::string& expected_version, int max_retries) {
LOG(INFO, "FastFlowLM") << "Verifying installation..." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(2)); // Initial wait
for (int attempt = 0; attempt < max_retries; ++attempt) {
refresh_environment_path();
std::string current = SystemInfo::get_flm_version();
utils::Version current_ver = utils::Version::parse(current);
utils::Version expected_ver = utils::Version::parse(expected_version);
if (!current_ver.empty() && !expected_ver.empty() && current_ver >= expected_ver) {
LOG(INFO, "FastFlowLM") << "Verification successful: FLM "
<< current << std::endl;
return true;
}
if (attempt < max_retries - 1) {
LOG(INFO, "FastFlowLM") << "FLM not yet available (got: '" << current
<< "'), retrying... (" << (attempt + 1) << "/" << max_retries << ")" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(3));
}
}
LOG(ERROR, "FastFlowLM") << "FLM installation completed but 'flm' "
<< "is not available in PATH or version check failed" << std::endl;
LOG(INFO, "FastFlowLM") << "Expected version: " << expected_version << std::endl;
LOG(INFO, "FastFlowLM") << "Please restart your terminal or add FLM to your PATH manually." << std::endl;
return false;
}
} // namespace backends
} // namespace lemon