server-models.h 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  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. int port = 0;
  49. server_model_status status = SERVER_MODEL_STATUS_UNLOADED;
  50. int64_t last_used = 0; // for LRU unloading
  51. std::vector<std::string> args; // args passed to the model instance, will be populated by render_args()
  52. int exit_code = 0; // exit code of the model instance process (only valid if status == FAILED)
  53. bool is_active() const {
  54. return status == SERVER_MODEL_STATUS_LOADED || status == SERVER_MODEL_STATUS_LOADING;
  55. }
  56. bool is_failed() const {
  57. return status == SERVER_MODEL_STATUS_UNLOADED && exit_code != 0;
  58. }
  59. void update_args(common_preset_context & ctx_presets, std::string bin_path);
  60. };
  61. struct subprocess_s;
  62. struct server_models {
  63. private:
  64. struct instance_t {
  65. std::shared_ptr<subprocess_s> subproc; // shared between main thread and monitoring thread
  66. std::thread th;
  67. server_model_meta meta;
  68. FILE * stdin_file = nullptr;
  69. };
  70. std::mutex mutex;
  71. std::condition_variable cv;
  72. std::map<std::string, instance_t> mapping;
  73. common_preset_context ctx_preset;
  74. common_params base_params;
  75. std::string bin_path;
  76. std::vector<std::string> base_env;
  77. common_preset base_preset; // base preset from llama-server CLI args
  78. void update_meta(const std::string & name, const server_model_meta & meta);
  79. // unload least recently used models if the limit is reached
  80. void unload_lru();
  81. // not thread-safe, caller must hold mutex
  82. void add_model(server_model_meta && meta);
  83. public:
  84. server_models(const common_params & params, int argc, char ** argv, char ** envp);
  85. void load_models();
  86. // check if a model instance exists (thread-safe)
  87. bool has_model(const std::string & name);
  88. // return a copy of model metadata (thread-safe)
  89. std::optional<server_model_meta> get_meta(const std::string & name);
  90. // return a copy of all model metadata (thread-safe)
  91. std::vector<server_model_meta> get_all_meta();
  92. // load and unload model instances
  93. // these functions are thread-safe
  94. void load(const std::string & name);
  95. void unload(const std::string & name);
  96. void unload_all();
  97. // update the status of a model instance (thread-safe)
  98. void update_status(const std::string & name, server_model_status status);
  99. // wait until the model instance is fully loaded (thread-safe)
  100. // return when the model is loaded or failed to load
  101. void wait_until_loaded(const std::string & name);
  102. // load the model if not loaded, otherwise do nothing (thread-safe)
  103. // return false if model is already loaded; return true otherwise (meta may need to be refreshed)
  104. bool ensure_model_loaded(const std::string & name);
  105. // proxy an HTTP request to the model instance
  106. server_http_res_ptr proxy_request(const server_http_req & req, const std::string & method, const std::string & name, bool update_last_used);
  107. // notify the router server that a model instance is ready
  108. // return the monitoring thread (to be joined by the caller)
  109. static std::thread setup_child_server(const std::function<void(int)> & shutdown_handler);
  110. };
  111. struct server_models_routes {
  112. common_params params;
  113. json webui_settings = json::object();
  114. server_models models;
  115. server_models_routes(const common_params & params, int argc, char ** argv, char ** envp)
  116. : params(params), models(params, argc, argv, envp) {
  117. if (!this->params.webui_config_json.empty()) {
  118. try {
  119. webui_settings = json::parse(this->params.webui_config_json);
  120. } catch (const std::exception & e) {
  121. LOG_ERR("%s: failed to parse webui config: %s\n", __func__, e.what());
  122. throw;
  123. }
  124. }
  125. init_routes();
  126. }
  127. void init_routes();
  128. // handlers using lambda function, so that they can capture `this` without `std::bind`
  129. server_http_context::handler_t get_router_props;
  130. server_http_context::handler_t proxy_get;
  131. server_http_context::handler_t proxy_post;
  132. server_http_context::handler_t get_router_models;
  133. server_http_context::handler_t post_router_models_load;
  134. server_http_context::handler_t post_router_models_unload;
  135. };
  136. /**
  137. * A simple HTTP proxy that forwards requests to another server
  138. * and relays the responses back.
  139. */
  140. struct server_http_proxy : server_http_res {
  141. std::function<void()> cleanup = nullptr;
  142. public:
  143. server_http_proxy(const std::string & method,
  144. const std::string & host,
  145. int port,
  146. const std::string & path,
  147. const std::map<std::string, std::string> & headers,
  148. const std::string & body,
  149. const std::function<bool()> should_stop);
  150. ~server_http_proxy() {
  151. if (cleanup) {
  152. cleanup();
  153. }
  154. }
  155. private:
  156. std::thread thread;
  157. struct msg_t {
  158. std::map<std::string, std::string> headers;
  159. int status = 0;
  160. std::string data;
  161. std::string content_type;
  162. };
  163. };