server-models.h 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. #pragma once
  2. #include "common.h"
  3. #include "preset.h"
  4. #include "server-common.h"
  5. #include "server-http.h"
  6. #include <mutex>
  7. #include <condition_variable>
  8. #include <functional>
  9. #include <memory>
  10. /**
  11. * state diagram:
  12. *
  13. * UNLOADED ──► LOADING ──► LOADED
  14. * ▲ │ │
  15. * └───failed───┘ │
  16. * ▲ │
  17. * └────────unloaded─────────┘
  18. */
  19. enum server_model_status {
  20. // TODO: also add downloading state when the logic is added
  21. SERVER_MODEL_STATUS_UNLOADED,
  22. SERVER_MODEL_STATUS_LOADING,
  23. SERVER_MODEL_STATUS_LOADED
  24. };
  25. static server_model_status server_model_status_from_string(const std::string & status_str) {
  26. if (status_str == "unloaded") {
  27. return SERVER_MODEL_STATUS_UNLOADED;
  28. }
  29. if (status_str == "loading") {
  30. return SERVER_MODEL_STATUS_LOADING;
  31. }
  32. if (status_str == "loaded") {
  33. return SERVER_MODEL_STATUS_LOADED;
  34. }
  35. throw std::runtime_error("invalid server model status");
  36. }
  37. static std::string server_model_status_to_string(server_model_status status) {
  38. switch (status) {
  39. case SERVER_MODEL_STATUS_UNLOADED: return "unloaded";
  40. case SERVER_MODEL_STATUS_LOADING: return "loading";
  41. case SERVER_MODEL_STATUS_LOADED: return "loaded";
  42. default: return "unknown";
  43. }
  44. }
  45. struct server_model_meta {
  46. common_preset preset;
  47. std::string name;
  48. std::string path;
  49. std::string path_mmproj; // only available if in_cache=false
  50. bool in_cache = false; // if true, use -hf; use -m otherwise
  51. int port = 0;
  52. server_model_status status = SERVER_MODEL_STATUS_UNLOADED;
  53. int64_t last_used = 0; // for LRU unloading
  54. std::vector<std::string> args; // args passed to the model instance, will be populated by render_args()
  55. int exit_code = 0; // exit code of the model instance process (only valid if status == FAILED)
  56. bool is_active() const {
  57. return status == SERVER_MODEL_STATUS_LOADED || status == SERVER_MODEL_STATUS_LOADING;
  58. }
  59. bool is_failed() const {
  60. return status == SERVER_MODEL_STATUS_UNLOADED && exit_code != 0;
  61. }
  62. };
  63. // the server_presets struct holds the presets read from presets.ini
  64. // as well as base args from the router server
  65. struct server_presets {
  66. common_presets presets;
  67. common_params_context ctx_params;
  68. std::map<common_arg, std::string> base_args;
  69. std::map<std::string, common_arg> control_args; // args reserved for server control
  70. server_presets(int argc, char ** argv, common_params & base_params, const std::string & models_dir);
  71. common_preset get_preset(const std::string & name);
  72. void render_args(server_model_meta & meta);
  73. };
  74. struct subprocess_s;
  75. struct server_models {
  76. private:
  77. struct instance_t {
  78. std::shared_ptr<subprocess_s> subproc; // shared between main thread and monitoring thread
  79. std::thread th;
  80. server_model_meta meta;
  81. FILE * stdin_file = nullptr;
  82. };
  83. std::mutex mutex;
  84. std::condition_variable cv;
  85. std::map<std::string, instance_t> mapping;
  86. common_params base_params;
  87. std::vector<std::string> base_args;
  88. std::vector<std::string> base_env;
  89. server_presets presets;
  90. void update_meta(const std::string & name, const server_model_meta & meta);
  91. // unload least recently used models if the limit is reached
  92. void unload_lru();
  93. // not thread-safe, caller must hold mutex
  94. void add_model(server_model_meta && meta);
  95. public:
  96. server_models(const common_params & params, int argc, char ** argv, char ** envp);
  97. void load_models();
  98. // check if a model instance exists
  99. bool has_model(const std::string & name);
  100. // return a copy of model metadata
  101. std::optional<server_model_meta> get_meta(const std::string & name);
  102. // return a copy of all model metadata
  103. std::vector<server_model_meta> get_all_meta();
  104. void load(const std::string & name);
  105. void unload(const std::string & name);
  106. void unload_all();
  107. // update the status of a model instance
  108. void update_status(const std::string & name, server_model_status status);
  109. // wait until the model instance is fully loaded
  110. // return when the model is loaded or failed to load
  111. void wait_until_loaded(const std::string & name);
  112. // load the model if not loaded, otherwise do nothing
  113. // return false if model is already loaded; return true otherwise (meta may need to be refreshed)
  114. bool ensure_model_loaded(const std::string & name);
  115. // proxy an HTTP request to the model instance
  116. server_http_res_ptr proxy_request(const server_http_req & req, const std::string & method, const std::string & name, bool update_last_used);
  117. // notify the router server that a model instance is ready
  118. // return the monitoring thread (to be joined by the caller)
  119. static std::thread setup_child_server(const std::function<void(int)> & shutdown_handler);
  120. };
  121. struct server_models_routes {
  122. common_params params;
  123. json webui_settings = json::object();
  124. server_models models;
  125. server_models_routes(const common_params & params, int argc, char ** argv, char ** envp)
  126. : params(params), models(params, argc, argv, envp) {
  127. if (!this->params.webui_config_json.empty()) {
  128. try {
  129. webui_settings = json::parse(this->params.webui_config_json);
  130. } catch (const std::exception & e) {
  131. LOG_ERR("%s: failed to parse webui config: %s\n", __func__, e.what());
  132. throw;
  133. }
  134. }
  135. init_routes();
  136. }
  137. void init_routes();
  138. // handlers using lambda function, so that they can capture `this` without `std::bind`
  139. server_http_context::handler_t get_router_props;
  140. server_http_context::handler_t proxy_get;
  141. server_http_context::handler_t proxy_post;
  142. server_http_context::handler_t get_router_models;
  143. server_http_context::handler_t post_router_models_load;
  144. server_http_context::handler_t post_router_models_unload;
  145. };
  146. /**
  147. * A simple HTTP proxy that forwards requests to another server
  148. * and relays the responses back.
  149. */
  150. struct server_http_proxy : server_http_res {
  151. std::function<void()> cleanup = nullptr;
  152. public:
  153. server_http_proxy(const std::string & method,
  154. const std::string & host,
  155. int port,
  156. const std::string & path,
  157. const std::map<std::string, std::string> & headers,
  158. const std::string & body,
  159. const std::function<bool()> should_stop);
  160. ~server_http_proxy() {
  161. if (cleanup) {
  162. cleanup();
  163. }
  164. }
  165. private:
  166. std::thread thread;
  167. struct msg_t {
  168. std::map<std::string, std::string> headers;
  169. int status = 0;
  170. std::string data;
  171. std::string content_type;
  172. };
  173. };