1
0

server-models.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089
  1. #include "server-common.h"
  2. #include "server-models.h"
  3. #include "preset.h"
  4. #include "download.h"
  5. #include <cpp-httplib/httplib.h> // TODO: remove this once we use HTTP client from download.h
  6. #include <sheredom/subprocess.h>
  7. #include <functional>
  8. #include <algorithm>
  9. #include <thread>
  10. #include <mutex>
  11. #include <condition_variable>
  12. #include <cstring>
  13. #include <atomic>
  14. #include <chrono>
  15. #include <queue>
  16. #include <filesystem>
  17. #include <cstring>
  18. #ifdef _WIN32
  19. #include <winsock2.h>
  20. #else
  21. #include <sys/socket.h>
  22. #include <netinet/in.h>
  23. #include <arpa/inet.h>
  24. #include <unistd.h>
  25. #endif
  26. #if defined(__APPLE__) && defined(__MACH__)
  27. // macOS: use _NSGetExecutablePath to get the executable path
  28. #include <mach-o/dyld.h>
  29. #include <limits.h>
  30. #endif
  31. #define CMD_ROUTER_TO_CHILD_EXIT "cmd_router_to_child:exit"
  32. #define CMD_CHILD_TO_ROUTER_READY "cmd_child_to_router:ready"
  33. // address for child process, this is needed because router may run on 0.0.0.0
  34. // ref: https://github.com/ggml-org/llama.cpp/issues/17862
  35. #define CHILD_ADDR "127.0.0.1"
  36. static std::filesystem::path get_server_exec_path() {
  37. #if defined(_WIN32)
  38. wchar_t buf[32768] = { 0 }; // Large buffer to handle long paths
  39. DWORD len = GetModuleFileNameW(nullptr, buf, _countof(buf));
  40. if (len == 0 || len >= _countof(buf)) {
  41. throw std::runtime_error("GetModuleFileNameW failed or path too long");
  42. }
  43. return std::filesystem::path(buf);
  44. #elif defined(__APPLE__) && defined(__MACH__)
  45. char small_path[PATH_MAX];
  46. uint32_t size = sizeof(small_path);
  47. if (_NSGetExecutablePath(small_path, &size) == 0) {
  48. // resolve any symlinks to get absolute path
  49. try {
  50. return std::filesystem::canonical(std::filesystem::path(small_path));
  51. } catch (...) {
  52. return std::filesystem::path(small_path);
  53. }
  54. } else {
  55. // buffer was too small, allocate required size and call again
  56. std::vector<char> buf(size);
  57. if (_NSGetExecutablePath(buf.data(), &size) == 0) {
  58. try {
  59. return std::filesystem::canonical(std::filesystem::path(buf.data()));
  60. } catch (...) {
  61. return std::filesystem::path(buf.data());
  62. }
  63. }
  64. throw std::runtime_error("_NSGetExecutablePath failed after buffer resize");
  65. }
  66. #else
  67. char path[FILENAME_MAX];
  68. ssize_t count = readlink("/proc/self/exe", path, FILENAME_MAX);
  69. if (count <= 0) {
  70. throw std::runtime_error("failed to resolve /proc/self/exe");
  71. }
  72. return std::filesystem::path(std::string(path, count));
  73. #endif
  74. }
  75. struct local_model {
  76. std::string name;
  77. std::string path;
  78. std::string path_mmproj;
  79. };
  80. static std::vector<local_model> list_local_models(const std::string & dir) {
  81. if (!std::filesystem::exists(dir) || !std::filesystem::is_directory(dir)) {
  82. throw std::runtime_error(string_format("error: '%s' does not exist or is not a directory\n", dir.c_str()));
  83. }
  84. std::vector<local_model> models;
  85. auto scan_subdir = [&models](const std::string & subdir_path, const std::string & name) {
  86. auto files = fs_list(subdir_path, false);
  87. common_file_info model_file;
  88. common_file_info first_shard_file;
  89. common_file_info mmproj_file;
  90. for (const auto & file : files) {
  91. if (string_ends_with(file.name, ".gguf")) {
  92. if (file.name.find("mmproj") != std::string::npos) {
  93. mmproj_file = file;
  94. } else if (file.name.find("-00001-of-") != std::string::npos) {
  95. first_shard_file = file;
  96. } else {
  97. model_file = file;
  98. }
  99. }
  100. }
  101. // single file model
  102. local_model model{
  103. /* name */ name,
  104. /* path */ first_shard_file.path.empty() ? model_file.path : first_shard_file.path,
  105. /* path_mmproj */ mmproj_file.path // can be empty
  106. };
  107. if (!model.path.empty()) {
  108. models.push_back(model);
  109. }
  110. };
  111. auto files = fs_list(dir, true);
  112. for (const auto & file : files) {
  113. if (file.is_dir) {
  114. scan_subdir(file.path, file.name);
  115. } else if (string_ends_with(file.name, ".gguf")) {
  116. // single file model
  117. std::string name = file.name;
  118. string_replace_all(name, ".gguf", "");
  119. local_model model{
  120. /* name */ name,
  121. /* path */ file.path,
  122. /* path_mmproj */ ""
  123. };
  124. models.push_back(model);
  125. }
  126. }
  127. return models;
  128. }
  129. //
  130. // server_presets
  131. //
  132. server_presets::server_presets(int argc, char ** argv, common_params & base_params, const std::string & presets_path)
  133. : ctx_params(common_params_parser_init(base_params, LLAMA_EXAMPLE_SERVER)) {
  134. if (!presets_path.empty()) {
  135. presets = common_presets_load(presets_path, ctx_params);
  136. SRV_INF("Loaded %zu presets from %s\n", presets.size(), presets_path.c_str());
  137. }
  138. // populate reserved args (will be appended by the router)
  139. for (auto & opt : ctx_params.options) {
  140. if (opt.env == nullptr) {
  141. continue;
  142. }
  143. std::string env = opt.env;
  144. if (env == "LLAMA_ARG_PORT" ||
  145. env == "LLAMA_ARG_HOST" ||
  146. env == "LLAMA_ARG_ALIAS" ||
  147. env == "LLAMA_ARG_API_KEY" ||
  148. env == "LLAMA_ARG_MODELS_DIR" ||
  149. env == "LLAMA_ARG_MODELS_MAX" ||
  150. env == "LLAMA_ARG_MODELS_PRESET" ||
  151. env == "LLAMA_ARG_MODEL" ||
  152. env == "LLAMA_ARG_MMPROJ" ||
  153. env == "LLAMA_ARG_HF_REPO" ||
  154. env == "LLAMA_ARG_NO_MODELS_AUTOLOAD") {
  155. control_args[env] = opt;
  156. }
  157. }
  158. // read base args from router's argv
  159. common_params_to_map(argc, argv, LLAMA_EXAMPLE_SERVER, base_args);
  160. // remove any router-controlled args from base_args
  161. for (const auto & cargs : control_args) {
  162. auto it = base_args.find(cargs.second);
  163. if (it != base_args.end()) {
  164. base_args.erase(it);
  165. }
  166. }
  167. }
  168. common_preset server_presets::get_preset(const std::string & name) {
  169. auto it = presets.find(name);
  170. if (it != presets.end()) {
  171. return it->second;
  172. }
  173. return common_preset();
  174. }
  175. void server_presets::render_args(server_model_meta & meta) {
  176. common_preset preset = meta.preset; // copy
  177. // merging 3 kinds of args:
  178. // 1. model-specific args (from preset)
  179. // force removing control args if any
  180. for (auto & cargs : control_args) {
  181. if (preset.options.find(cargs.second) != preset.options.end()) {
  182. SRV_WRN("Preset '%s' contains reserved arg '%s', removing it\n", preset.name.c_str(), cargs.second.args[0]);
  183. preset.options.erase(cargs.second);
  184. }
  185. }
  186. // 2. base args (from router)
  187. // inherit from base args
  188. for (const auto & [arg, value] : base_args) {
  189. preset.options[arg] = value;
  190. }
  191. // 3. control args (from router)
  192. // set control values
  193. preset.options[control_args["LLAMA_ARG_HOST"]] = CHILD_ADDR;
  194. preset.options[control_args["LLAMA_ARG_PORT"]] = std::to_string(meta.port);
  195. preset.options[control_args["LLAMA_ARG_ALIAS"]] = meta.name;
  196. if (meta.in_cache) {
  197. preset.options[control_args["LLAMA_ARG_HF_REPO"]] = meta.name;
  198. } else {
  199. preset.options[control_args["LLAMA_ARG_MODEL"]] = meta.path;
  200. if (!meta.path_mmproj.empty()) {
  201. preset.options[control_args["LLAMA_ARG_MMPROJ"]] = meta.path_mmproj;
  202. }
  203. }
  204. meta.args = preset.to_args();
  205. // add back the binary path at the front
  206. meta.args.insert(meta.args.begin(), get_server_exec_path().string());
  207. }
  208. //
  209. // server_models
  210. //
  211. server_models::server_models(
  212. const common_params & params,
  213. int argc,
  214. char ** argv,
  215. char ** envp) : base_params(params), presets(argc, argv, base_params, params.models_preset) {
  216. for (int i = 0; i < argc; i++) {
  217. base_args.push_back(std::string(argv[i]));
  218. }
  219. for (char ** env = envp; *env != nullptr; env++) {
  220. base_env.push_back(std::string(*env));
  221. }
  222. GGML_ASSERT(!base_args.empty());
  223. // set binary path
  224. try {
  225. base_args[0] = get_server_exec_path().string();
  226. } catch (const std::exception & e) {
  227. LOG_WRN("failed to get server executable path: %s\n", e.what());
  228. LOG_WRN("using original argv[0] as fallback: %s\n", base_args[0].c_str());
  229. }
  230. load_models();
  231. }
  232. void server_models::add_model(server_model_meta && meta) {
  233. if (mapping.find(meta.name) != mapping.end()) {
  234. throw std::runtime_error(string_format("model '%s' appears multiple times", meta.name.c_str()));
  235. }
  236. presets.render_args(meta); // populate meta.args
  237. std::string name = meta.name;
  238. mapping[name] = instance_t{
  239. /* subproc */ std::make_shared<subprocess_s>(),
  240. /* th */ std::thread(),
  241. /* meta */ std::move(meta)
  242. };
  243. }
  244. static std::vector<local_model> list_custom_path_models(server_presets & presets) {
  245. // detect any custom-path models in presets
  246. std::vector<local_model> custom_models;
  247. for (auto & [model_name, preset] : presets.presets) {
  248. local_model model;
  249. model.name = model_name;
  250. std::vector<common_arg> to_erase;
  251. for (auto & [arg, value] : preset.options) {
  252. std::string env(arg.env ? arg.env : "");
  253. if (env == "LLAMA_ARG_MODEL") {
  254. model.path = value;
  255. to_erase.push_back(arg);
  256. }
  257. if (env == "LLAMA_ARG_MMPROJ") {
  258. model.path_mmproj = value;
  259. to_erase.push_back(arg);
  260. }
  261. }
  262. for (auto & arg : to_erase) {
  263. preset.options.erase(arg);
  264. }
  265. if (!model.name.empty() && !model.path.empty()) {
  266. custom_models.push_back(model);
  267. }
  268. }
  269. return custom_models;
  270. }
  271. // TODO: allow refreshing cached model list
  272. void server_models::load_models() {
  273. // loading models from 3 sources:
  274. // 1. cached models
  275. auto cached_models = common_list_cached_models();
  276. for (const auto & model : cached_models) {
  277. server_model_meta meta{
  278. /* preset */ presets.get_preset(model.to_string()),
  279. /* name */ model.to_string(),
  280. /* path */ model.manifest_path,
  281. /* path_mmproj */ "", // auto-detected when loading
  282. /* in_cache */ true,
  283. /* port */ 0,
  284. /* status */ SERVER_MODEL_STATUS_UNLOADED,
  285. /* last_used */ 0,
  286. /* args */ std::vector<std::string>(),
  287. /* exit_code */ 0
  288. };
  289. add_model(std::move(meta));
  290. }
  291. // 2. local models specificed via --models-dir
  292. if (!base_params.models_dir.empty()) {
  293. auto local_models = list_local_models(base_params.models_dir);
  294. for (const auto & model : local_models) {
  295. if (mapping.find(model.name) != mapping.end()) {
  296. // already exists in cached models, skip
  297. continue;
  298. }
  299. server_model_meta meta{
  300. /* preset */ presets.get_preset(model.name),
  301. /* name */ model.name,
  302. /* path */ model.path,
  303. /* path_mmproj */ model.path_mmproj,
  304. /* in_cache */ false,
  305. /* port */ 0,
  306. /* status */ SERVER_MODEL_STATUS_UNLOADED,
  307. /* last_used */ 0,
  308. /* args */ std::vector<std::string>(),
  309. /* exit_code */ 0
  310. };
  311. add_model(std::move(meta));
  312. }
  313. }
  314. // 3. custom-path models specified in presets
  315. auto custom_models = list_custom_path_models(presets);
  316. for (const auto & model : custom_models) {
  317. server_model_meta meta{
  318. /* preset */ presets.get_preset(model.name),
  319. /* name */ model.name,
  320. /* path */ model.path,
  321. /* path_mmproj */ model.path_mmproj,
  322. /* in_cache */ false,
  323. /* port */ 0,
  324. /* status */ SERVER_MODEL_STATUS_UNLOADED,
  325. /* last_used */ 0,
  326. /* args */ std::vector<std::string>(),
  327. /* exit_code */ 0
  328. };
  329. add_model(std::move(meta));
  330. }
  331. // log available models
  332. SRV_INF("Available models (%zu) (*: custom preset)\n", mapping.size());
  333. for (const auto & [name, inst] : mapping) {
  334. SRV_INF(" %c %s\n", inst.meta.preset.name.empty() ? ' ' : '*', name.c_str());
  335. }
  336. }
  337. void server_models::update_meta(const std::string & name, const server_model_meta & meta) {
  338. std::lock_guard<std::mutex> lk(mutex);
  339. auto it = mapping.find(name);
  340. if (it != mapping.end()) {
  341. it->second.meta = meta;
  342. }
  343. cv.notify_all(); // notify wait_until_loaded
  344. }
  345. bool server_models::has_model(const std::string & name) {
  346. std::lock_guard<std::mutex> lk(mutex);
  347. return mapping.find(name) != mapping.end();
  348. }
  349. std::optional<server_model_meta> server_models::get_meta(const std::string & name) {
  350. std::lock_guard<std::mutex> lk(mutex);
  351. auto it = mapping.find(name);
  352. if (it != mapping.end()) {
  353. return it->second.meta;
  354. }
  355. return std::nullopt;
  356. }
  357. static int get_free_port() {
  358. #ifdef _WIN32
  359. WSADATA wsaData;
  360. if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
  361. return -1;
  362. }
  363. typedef SOCKET native_socket_t;
  364. #define INVALID_SOCKET_VAL INVALID_SOCKET
  365. #define CLOSE_SOCKET(s) closesocket(s)
  366. #else
  367. typedef int native_socket_t;
  368. #define INVALID_SOCKET_VAL -1
  369. #define CLOSE_SOCKET(s) close(s)
  370. #endif
  371. native_socket_t sock = socket(AF_INET, SOCK_STREAM, 0);
  372. if (sock == INVALID_SOCKET_VAL) {
  373. #ifdef _WIN32
  374. WSACleanup();
  375. #endif
  376. return -1;
  377. }
  378. struct sockaddr_in serv_addr;
  379. std::memset(&serv_addr, 0, sizeof(serv_addr));
  380. serv_addr.sin_family = AF_INET;
  381. serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
  382. serv_addr.sin_port = htons(0);
  383. if (bind(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) != 0) {
  384. CLOSE_SOCKET(sock);
  385. #ifdef _WIN32
  386. WSACleanup();
  387. #endif
  388. return -1;
  389. }
  390. #ifdef _WIN32
  391. int namelen = sizeof(serv_addr);
  392. #else
  393. socklen_t namelen = sizeof(serv_addr);
  394. #endif
  395. if (getsockname(sock, (struct sockaddr*)&serv_addr, &namelen) != 0) {
  396. CLOSE_SOCKET(sock);
  397. #ifdef _WIN32
  398. WSACleanup();
  399. #endif
  400. return -1;
  401. }
  402. int port = ntohs(serv_addr.sin_port);
  403. CLOSE_SOCKET(sock);
  404. #ifdef _WIN32
  405. WSACleanup();
  406. #endif
  407. return port;
  408. }
  409. // helper to convert vector<string> to char **
  410. // pointers are only valid as long as the original vector is valid
  411. static std::vector<char *> to_char_ptr_array(const std::vector<std::string> & vec) {
  412. std::vector<char *> result;
  413. result.reserve(vec.size() + 1);
  414. for (const auto & s : vec) {
  415. result.push_back(const_cast<char*>(s.c_str()));
  416. }
  417. result.push_back(nullptr);
  418. return result;
  419. }
  420. std::vector<server_model_meta> server_models::get_all_meta() {
  421. std::lock_guard<std::mutex> lk(mutex);
  422. std::vector<server_model_meta> result;
  423. result.reserve(mapping.size());
  424. for (const auto & [name, inst] : mapping) {
  425. result.push_back(inst.meta);
  426. }
  427. return result;
  428. }
  429. void server_models::unload_lru() {
  430. if (base_params.models_max <= 0) {
  431. return; // no limit
  432. }
  433. // remove one of the servers if we passed the models_max (least recently used - LRU)
  434. std::string lru_model_name = "";
  435. int64_t lru_last_used = ggml_time_ms();
  436. size_t count_active = 0;
  437. {
  438. std::lock_guard<std::mutex> lk(mutex);
  439. for (const auto & m : mapping) {
  440. if (m.second.meta.is_active()) {
  441. count_active++;
  442. if (m.second.meta.last_used < lru_last_used) {
  443. lru_model_name = m.first;
  444. lru_last_used = m.second.meta.last_used;
  445. }
  446. }
  447. }
  448. }
  449. if (!lru_model_name.empty() && count_active >= (size_t)base_params.models_max) {
  450. SRV_INF("models_max limit reached, removing LRU name=%s\n", lru_model_name.c_str());
  451. unload(lru_model_name);
  452. }
  453. }
  454. void server_models::load(const std::string & name) {
  455. if (!has_model(name)) {
  456. throw std::runtime_error("model name=" + name + " is not found");
  457. }
  458. unload_lru();
  459. std::lock_guard<std::mutex> lk(mutex);
  460. auto meta = mapping[name].meta;
  461. if (meta.status != SERVER_MODEL_STATUS_UNLOADED) {
  462. SRV_INF("model %s is not ready\n", name.c_str());
  463. return;
  464. }
  465. // prepare new instance info
  466. instance_t inst;
  467. inst.meta = meta;
  468. inst.meta.port = get_free_port();
  469. inst.meta.status = SERVER_MODEL_STATUS_LOADING;
  470. inst.meta.last_used = ggml_time_ms();
  471. if (inst.meta.port <= 0) {
  472. throw std::runtime_error("failed to get a port number");
  473. }
  474. inst.subproc = std::make_shared<subprocess_s>();
  475. {
  476. SRV_INF("spawning server instance with name=%s on port %d\n", inst.meta.name.c_str(), inst.meta.port);
  477. presets.render_args(inst.meta); // update meta.args
  478. std::vector<std::string> child_args = inst.meta.args; // copy
  479. std::vector<std::string> child_env = base_env; // copy
  480. child_env.push_back("LLAMA_SERVER_ROUTER_PORT=" + std::to_string(base_params.port));
  481. SRV_INF("%s", "spawning server instance with args:\n");
  482. for (const auto & arg : child_args) {
  483. SRV_INF(" %s\n", arg.c_str());
  484. }
  485. inst.meta.args = child_args; // save for debugging
  486. std::vector<char *> argv = to_char_ptr_array(child_args);
  487. std::vector<char *> envp = to_char_ptr_array(child_env);
  488. // TODO @ngxson : maybe separate stdout and stderr in the future
  489. // so that we can use stdout for commands and stderr for logging
  490. int options = subprocess_option_no_window | subprocess_option_combined_stdout_stderr;
  491. int result = subprocess_create_ex(argv.data(), options, envp.data(), inst.subproc.get());
  492. if (result != 0) {
  493. throw std::runtime_error("failed to spawn server instance");
  494. }
  495. inst.stdin_file = subprocess_stdin(inst.subproc.get());
  496. }
  497. // start a thread to manage the child process
  498. // captured variables are guaranteed to be destroyed only after the thread is joined
  499. inst.th = std::thread([this, name, child_proc = inst.subproc, port = inst.meta.port]() {
  500. // read stdout/stderr and forward to main server log
  501. bool state_received = false; // true if child state received
  502. FILE * p_stdout_stderr = subprocess_stdout(child_proc.get());
  503. if (p_stdout_stderr) {
  504. char buffer[4096];
  505. while (fgets(buffer, sizeof(buffer), p_stdout_stderr) != nullptr) {
  506. LOG("[%5d] %s", port, buffer);
  507. if (!state_received && std::strstr(buffer, CMD_CHILD_TO_ROUTER_READY) != nullptr) {
  508. // child process is ready
  509. this->update_status(name, SERVER_MODEL_STATUS_LOADED);
  510. state_received = true;
  511. }
  512. }
  513. } else {
  514. SRV_ERR("failed to get stdout/stderr of child process for name=%s\n", name.c_str());
  515. }
  516. // we reach here when the child process exits
  517. int exit_code = 0;
  518. subprocess_join(child_proc.get(), &exit_code);
  519. subprocess_destroy(child_proc.get());
  520. // update PID and status
  521. {
  522. std::lock_guard<std::mutex> lk(mutex);
  523. auto it = mapping.find(name);
  524. if (it != mapping.end()) {
  525. auto & meta = it->second.meta;
  526. meta.exit_code = exit_code;
  527. meta.status = SERVER_MODEL_STATUS_UNLOADED;
  528. }
  529. cv.notify_all();
  530. }
  531. SRV_INF("instance name=%s exited with status %d\n", name.c_str(), exit_code);
  532. });
  533. // clean up old process/thread if exists
  534. {
  535. auto & old_instance = mapping[name];
  536. // old process should have exited already, but just in case, we clean it up here
  537. if (subprocess_alive(old_instance.subproc.get())) {
  538. SRV_WRN("old process for model name=%s is still alive, this is unexpected\n", name.c_str());
  539. subprocess_terminate(old_instance.subproc.get()); // force kill
  540. }
  541. if (old_instance.th.joinable()) {
  542. old_instance.th.join();
  543. }
  544. }
  545. mapping[name] = std::move(inst);
  546. cv.notify_all();
  547. }
  548. static void interrupt_subprocess(FILE * stdin_file) {
  549. // because subprocess.h does not provide a way to send SIGINT,
  550. // we will send a command to the child process to exit gracefully
  551. if (stdin_file) {
  552. fprintf(stdin_file, "%s\n", CMD_ROUTER_TO_CHILD_EXIT);
  553. fflush(stdin_file);
  554. }
  555. }
  556. void server_models::unload(const std::string & name) {
  557. std::lock_guard<std::mutex> lk(mutex);
  558. auto it = mapping.find(name);
  559. if (it != mapping.end()) {
  560. if (it->second.meta.is_active()) {
  561. SRV_INF("unloading model instance name=%s\n", name.c_str());
  562. interrupt_subprocess(it->second.stdin_file);
  563. // status change will be handled by the managing thread
  564. } else {
  565. SRV_WRN("model instance name=%s is not loaded\n", name.c_str());
  566. }
  567. }
  568. }
  569. void server_models::unload_all() {
  570. std::vector<std::thread> to_join;
  571. {
  572. std::lock_guard<std::mutex> lk(mutex);
  573. for (auto & [name, inst] : mapping) {
  574. if (inst.meta.is_active()) {
  575. SRV_INF("unloading model instance name=%s\n", name.c_str());
  576. interrupt_subprocess(inst.stdin_file);
  577. // status change will be handled by the managing thread
  578. }
  579. // moving the thread to join list to avoid deadlock
  580. to_join.push_back(std::move(inst.th));
  581. }
  582. }
  583. for (auto & th : to_join) {
  584. if (th.joinable()) {
  585. th.join();
  586. }
  587. }
  588. }
  589. void server_models::update_status(const std::string & name, server_model_status status) {
  590. // for now, we only allow updating to LOADED status
  591. if (status != SERVER_MODEL_STATUS_LOADED) {
  592. throw std::runtime_error("invalid status value");
  593. }
  594. auto meta = get_meta(name);
  595. if (meta.has_value()) {
  596. meta->status = status;
  597. update_meta(name, meta.value());
  598. }
  599. }
  600. void server_models::wait_until_loaded(const std::string & name) {
  601. std::unique_lock<std::mutex> lk(mutex);
  602. cv.wait(lk, [this, &name]() {
  603. auto it = mapping.find(name);
  604. if (it != mapping.end()) {
  605. return it->second.meta.status != SERVER_MODEL_STATUS_LOADING;
  606. }
  607. return false;
  608. });
  609. }
  610. bool server_models::ensure_model_loaded(const std::string & name) {
  611. auto meta = get_meta(name);
  612. if (!meta.has_value()) {
  613. throw std::runtime_error("model name=" + name + " is not found");
  614. }
  615. if (meta->status == SERVER_MODEL_STATUS_LOADED) {
  616. return false; // already loaded
  617. }
  618. if (meta->status == SERVER_MODEL_STATUS_UNLOADED) {
  619. SRV_INF("model name=%s is not loaded, loading...\n", name.c_str());
  620. load(name);
  621. }
  622. SRV_INF("waiting until model name=%s is fully loaded...\n", name.c_str());
  623. wait_until_loaded(name);
  624. // check final status
  625. meta = get_meta(name);
  626. if (!meta.has_value() || meta->is_failed()) {
  627. throw std::runtime_error("model name=" + name + " failed to load");
  628. }
  629. return true;
  630. }
  631. server_http_res_ptr server_models::proxy_request(const server_http_req & req, const std::string & method, const std::string & name, bool update_last_used) {
  632. auto meta = get_meta(name);
  633. if (!meta.has_value()) {
  634. throw std::runtime_error("model name=" + name + " is not found");
  635. }
  636. if (meta->status != SERVER_MODEL_STATUS_LOADED) {
  637. throw std::invalid_argument("model name=" + name + " is not loaded");
  638. }
  639. if (update_last_used) {
  640. std::unique_lock<std::mutex> lk(mutex);
  641. mapping[name].meta.last_used = ggml_time_ms();
  642. }
  643. SRV_INF("proxying request to model %s on port %d\n", name.c_str(), meta->port);
  644. auto proxy = std::make_unique<server_http_proxy>(
  645. method,
  646. CHILD_ADDR,
  647. meta->port,
  648. req.path,
  649. req.headers,
  650. req.body,
  651. req.should_stop);
  652. return proxy;
  653. }
  654. std::thread server_models::setup_child_server(const std::function<void(int)> & shutdown_handler) {
  655. // send a notification to the router server that a model instance is ready
  656. common_log_pause(common_log_main());
  657. fflush(stdout);
  658. fprintf(stdout, "%s\n", CMD_CHILD_TO_ROUTER_READY);
  659. fflush(stdout);
  660. common_log_resume(common_log_main());
  661. // setup thread for monitoring stdin
  662. return std::thread([shutdown_handler]() {
  663. // wait for EOF on stdin
  664. SRV_INF("%s", "child server monitoring thread started, waiting for EOF on stdin...\n");
  665. bool eof = false;
  666. while (true) {
  667. std::string line;
  668. if (!std::getline(std::cin, line)) {
  669. // EOF detected, that means the router server is unexpectedly exit or killed
  670. eof = true;
  671. break;
  672. }
  673. if (line.find(CMD_ROUTER_TO_CHILD_EXIT) != std::string::npos) {
  674. SRV_INF("%s", "exit command received, exiting...\n");
  675. shutdown_handler(0);
  676. break;
  677. }
  678. }
  679. if (eof) {
  680. SRV_INF("%s", "EOF on stdin detected, forcing shutdown...\n");
  681. exit(1);
  682. }
  683. });
  684. }
  685. //
  686. // server_models_routes
  687. //
  688. static void res_ok(std::unique_ptr<server_http_res> & res, const json & response_data) {
  689. res->status = 200;
  690. res->data = safe_json_to_str(response_data);
  691. }
  692. static void res_err(std::unique_ptr<server_http_res> & res, const json & error_data) {
  693. res->status = json_value(error_data, "code", 500);
  694. res->data = safe_json_to_str({{ "error", error_data }});
  695. }
  696. static bool router_validate_model(const std::string & name, server_models & models, bool models_autoload, std::unique_ptr<server_http_res> & res) {
  697. if (name.empty()) {
  698. res_err(res, format_error_response("model name is missing from the request", ERROR_TYPE_INVALID_REQUEST));
  699. return false;
  700. }
  701. auto meta = models.get_meta(name);
  702. if (!meta.has_value()) {
  703. res_err(res, format_error_response("model not found", ERROR_TYPE_INVALID_REQUEST));
  704. return false;
  705. }
  706. if (models_autoload) {
  707. models.ensure_model_loaded(name);
  708. } else {
  709. if (meta->status != SERVER_MODEL_STATUS_LOADED) {
  710. res_err(res, format_error_response("model is not loaded", ERROR_TYPE_INVALID_REQUEST));
  711. return false;
  712. }
  713. }
  714. return true;
  715. }
  716. static bool is_autoload(const common_params & params, const server_http_req & req) {
  717. std::string autoload = req.get_param("autoload");
  718. if (autoload.empty()) {
  719. return params.models_autoload;
  720. } else {
  721. return autoload == "true" || autoload == "1";
  722. }
  723. }
  724. void server_models_routes::init_routes() {
  725. this->get_router_props = [this](const server_http_req & req) {
  726. std::string name = req.get_param("model");
  727. if (name.empty()) {
  728. // main instance
  729. auto res = std::make_unique<server_http_res>();
  730. res_ok(res, {
  731. // TODO: add support for this on web UI
  732. {"role", "router"},
  733. {"max_instances", 4}, // dummy value for testing
  734. // this is a dummy response to make sure webui doesn't break
  735. {"model_alias", "llama-server"},
  736. {"model_path", "none"},
  737. {"default_generation_settings", {
  738. {"params", json{}},
  739. {"n_ctx", 0},
  740. }},
  741. });
  742. return res;
  743. }
  744. return proxy_get(req);
  745. };
  746. this->proxy_get = [this](const server_http_req & req) {
  747. std::string method = "GET";
  748. std::string name = req.get_param("model");
  749. bool autoload = is_autoload(params, req);
  750. auto error_res = std::make_unique<server_http_res>();
  751. if (!router_validate_model(name, models, autoload, error_res)) {
  752. return error_res;
  753. }
  754. return models.proxy_request(req, method, name, false);
  755. };
  756. this->proxy_post = [this](const server_http_req & req) {
  757. std::string method = "POST";
  758. json body = json::parse(req.body);
  759. std::string name = json_value(body, "model", std::string());
  760. bool autoload = is_autoload(params, req);
  761. auto error_res = std::make_unique<server_http_res>();
  762. if (!router_validate_model(name, models, autoload, error_res)) {
  763. return error_res;
  764. }
  765. return models.proxy_request(req, method, name, true); // update last usage for POST request only
  766. };
  767. this->post_router_models_load = [this](const server_http_req & req) {
  768. auto res = std::make_unique<server_http_res>();
  769. json body = json::parse(req.body);
  770. std::string name = json_value(body, "model", std::string());
  771. auto model = models.get_meta(name);
  772. if (!model.has_value()) {
  773. res_err(res, format_error_response("model is not found", ERROR_TYPE_NOT_FOUND));
  774. return res;
  775. }
  776. if (model->status == SERVER_MODEL_STATUS_LOADED) {
  777. res_err(res, format_error_response("model is already loaded", ERROR_TYPE_INVALID_REQUEST));
  778. return res;
  779. }
  780. models.load(name);
  781. res_ok(res, {{"success", true}});
  782. return res;
  783. };
  784. this->get_router_models = [this](const server_http_req &) {
  785. auto res = std::make_unique<server_http_res>();
  786. json models_json = json::array();
  787. auto all_models = models.get_all_meta();
  788. std::time_t t = std::time(0);
  789. for (const auto & meta : all_models) {
  790. json status {
  791. {"value", server_model_status_to_string(meta.status)},
  792. {"args", meta.args},
  793. };
  794. if (!meta.preset.name.empty()) {
  795. status["preset"] = meta.preset.to_ini();
  796. }
  797. if (meta.is_failed()) {
  798. status["exit_code"] = meta.exit_code;
  799. status["failed"] = true;
  800. }
  801. models_json.push_back(json {
  802. {"id", meta.name},
  803. {"object", "model"}, // for OAI-compat
  804. {"owned_by", "llamacpp"}, // for OAI-compat
  805. {"created", t}, // for OAI-compat
  806. {"in_cache", meta.in_cache},
  807. {"path", meta.path},
  808. {"status", status},
  809. // TODO: add other fields, may require reading GGUF metadata
  810. });
  811. }
  812. res_ok(res, {
  813. {"data", models_json},
  814. {"object", "list"},
  815. });
  816. return res;
  817. };
  818. this->post_router_models_unload = [this](const server_http_req & req) {
  819. auto res = std::make_unique<server_http_res>();
  820. json body = json::parse(req.body);
  821. std::string name = json_value(body, "model", std::string());
  822. auto model = models.get_meta(name);
  823. if (!model.has_value()) {
  824. res_err(res, format_error_response("model is not found", ERROR_TYPE_INVALID_REQUEST));
  825. return res;
  826. }
  827. if (model->status != SERVER_MODEL_STATUS_LOADED) {
  828. res_err(res, format_error_response("model is not loaded", ERROR_TYPE_INVALID_REQUEST));
  829. return res;
  830. }
  831. models.unload(name);
  832. res_ok(res, {{"success", true}});
  833. return res;
  834. };
  835. }
  836. //
  837. // server_http_proxy
  838. //
  839. // simple implementation of a pipe
  840. // used for streaming data between threads
  841. template<typename T>
  842. struct pipe_t {
  843. std::mutex mutex;
  844. std::condition_variable cv;
  845. std::queue<T> queue;
  846. std::atomic<bool> writer_closed{false};
  847. std::atomic<bool> reader_closed{false};
  848. void close_write() {
  849. writer_closed.store(true, std::memory_order_relaxed);
  850. cv.notify_all();
  851. }
  852. void close_read() {
  853. reader_closed.store(true, std::memory_order_relaxed);
  854. cv.notify_all();
  855. }
  856. bool read(T & output, const std::function<bool()> & should_stop) {
  857. std::unique_lock<std::mutex> lk(mutex);
  858. constexpr auto poll_interval = std::chrono::milliseconds(500);
  859. while (true) {
  860. if (!queue.empty()) {
  861. output = std::move(queue.front());
  862. queue.pop();
  863. return true;
  864. }
  865. if (writer_closed.load()) {
  866. return false; // clean EOF
  867. }
  868. if (should_stop()) {
  869. close_read(); // signal broken pipe to writer
  870. return false; // cancelled / reader no longer alive
  871. }
  872. cv.wait_for(lk, poll_interval);
  873. }
  874. }
  875. bool write(T && data) {
  876. std::lock_guard<std::mutex> lk(mutex);
  877. if (reader_closed.load()) {
  878. return false; // broken pipe
  879. }
  880. queue.push(std::move(data));
  881. cv.notify_one();
  882. return true;
  883. }
  884. };
  885. static std::string to_lower_copy(const std::string & value) {
  886. std::string lowered(value.size(), '\0');
  887. std::transform(value.begin(), value.end(), lowered.begin(), [](unsigned char c) { return std::tolower(c); });
  888. return lowered;
  889. }
  890. static bool should_strip_proxy_header(const std::string & header_name) {
  891. // Headers that get duplicated when router forwards child responses
  892. if (header_name == "server" ||
  893. header_name == "transfer-encoding" ||
  894. header_name == "content-length" || // quick fix for https://github.com/ggml-org/llama.cpp/issues/17710
  895. header_name == "keep-alive") {
  896. return true;
  897. }
  898. // Router injects CORS, child also sends them: duplicate
  899. if (header_name.rfind("access-control-", 0) == 0) {
  900. return true;
  901. }
  902. return false;
  903. }
  904. server_http_proxy::server_http_proxy(
  905. const std::string & method,
  906. const std::string & host,
  907. int port,
  908. const std::string & path,
  909. const std::map<std::string, std::string> & headers,
  910. const std::string & body,
  911. const std::function<bool()> should_stop) {
  912. // shared between reader and writer threads
  913. auto cli = std::make_shared<httplib::Client>(host, port);
  914. auto pipe = std::make_shared<pipe_t<msg_t>>();
  915. // setup Client
  916. cli->set_connection_timeout(0, 200000); // 200 milliseconds
  917. this->status = 500; // to be overwritten upon response
  918. this->cleanup = [pipe]() {
  919. pipe->close_read();
  920. pipe->close_write();
  921. };
  922. // wire up the receive end of the pipe
  923. this->next = [pipe, should_stop](std::string & out) -> bool {
  924. msg_t msg;
  925. bool has_next = pipe->read(msg, should_stop);
  926. if (!msg.data.empty()) {
  927. out = std::move(msg.data);
  928. }
  929. return has_next; // false if EOF or pipe broken
  930. };
  931. // wire up the HTTP client
  932. // note: do NOT capture `this` pointer, as it may be destroyed before the thread ends
  933. httplib::ResponseHandler response_handler = [pipe, cli](const httplib::Response & response) {
  934. msg_t msg;
  935. msg.status = response.status;
  936. for (const auto & [key, value] : response.headers) {
  937. const auto lowered = to_lower_copy(key);
  938. if (should_strip_proxy_header(lowered)) {
  939. continue;
  940. }
  941. if (lowered == "content-type") {
  942. msg.content_type = value;
  943. continue;
  944. }
  945. msg.headers[key] = value;
  946. }
  947. return pipe->write(std::move(msg)); // send headers first
  948. };
  949. httplib::ContentReceiverWithProgress content_receiver = [pipe](const char * data, size_t data_length, size_t, size_t) {
  950. // send data chunks
  951. // returns false if pipe is closed / broken (signal to stop receiving)
  952. return pipe->write({{}, 0, std::string(data, data_length), ""});
  953. };
  954. // prepare the request to destination server
  955. httplib::Request req;
  956. {
  957. req.method = method;
  958. req.path = path;
  959. for (const auto & [key, value] : headers) {
  960. req.set_header(key, value);
  961. }
  962. req.body = body;
  963. req.response_handler = response_handler;
  964. req.content_receiver = content_receiver;
  965. }
  966. // start the proxy thread
  967. SRV_DBG("start proxy thread %s %s\n", req.method.c_str(), req.path.c_str());
  968. this->thread = std::thread([cli, pipe, req]() {
  969. auto result = cli->send(std::move(req));
  970. if (result.error() != httplib::Error::Success) {
  971. auto err_str = httplib::to_string(result.error());
  972. SRV_ERR("http client error: %s\n", err_str.c_str());
  973. pipe->write({{}, 500, "", ""}); // header
  974. pipe->write({{}, 0, "proxy error: " + err_str, ""}); // body
  975. }
  976. pipe->close_write(); // signal EOF to reader
  977. SRV_DBG("%s", "client request thread ended\n");
  978. });
  979. this->thread.detach();
  980. // wait for the first chunk (headers)
  981. {
  982. msg_t header;
  983. if (pipe->read(header, should_stop)) {
  984. SRV_DBG("%s", "received response headers\n");
  985. this->status = header.status;
  986. this->headers = std::move(header.headers);
  987. if (!header.content_type.empty()) {
  988. this->content_type = std::move(header.content_type);
  989. }
  990. } else {
  991. SRV_DBG("%s", "no response headers received (request cancelled?)\n");
  992. }
  993. }
  994. }