server-models.h 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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
  87. bool has_model(const std::string & name);
  88. // return a copy of model metadata
  89. std::optional<server_model_meta> get_meta(const std::string & name);
  90. // return a copy of all model metadata
  91. std::vector<server_model_meta> get_all_meta();
  92. void load(const std::string & name);
  93. void unload(const std::string & name);
  94. void unload_all();
  95. // update the status of a model instance
  96. void update_status(const std::string & name, server_model_status status);
  97. // wait until the model instance is fully loaded
  98. // return when the model is loaded or failed to load
  99. void wait_until_loaded(const std::string & name);
  100. // load the model if not loaded, otherwise do nothing
  101. // return false if model is already loaded; return true otherwise (meta may need to be refreshed)
  102. bool ensure_model_loaded(const std::string & name);
  103. // proxy an HTTP request to the model instance
  104. server_http_res_ptr proxy_request(const server_http_req & req, const std::string & method, const std::string & name, bool update_last_used);
  105. // notify the router server that a model instance is ready
  106. // return the monitoring thread (to be joined by the caller)
  107. static std::thread setup_child_server(const std::function<void(int)> & shutdown_handler);
  108. };
  109. struct server_models_routes {
  110. common_params params;
  111. json webui_settings = json::object();
  112. server_models models;
  113. server_models_routes(const common_params & params, int argc, char ** argv, char ** envp)
  114. : params(params), models(params, argc, argv, envp) {
  115. if (!this->params.webui_config_json.empty()) {
  116. try {
  117. webui_settings = json::parse(this->params.webui_config_json);
  118. } catch (const std::exception & e) {
  119. LOG_ERR("%s: failed to parse webui config: %s\n", __func__, e.what());
  120. throw;
  121. }
  122. }
  123. init_routes();
  124. }
  125. void init_routes();
  126. // handlers using lambda function, so that they can capture `this` without `std::bind`
  127. server_http_context::handler_t get_router_props;
  128. server_http_context::handler_t proxy_get;
  129. server_http_context::handler_t proxy_post;
  130. server_http_context::handler_t get_router_models;
  131. server_http_context::handler_t post_router_models_load;
  132. server_http_context::handler_t post_router_models_unload;
  133. };
  134. /**
  135. * A simple HTTP proxy that forwards requests to another server
  136. * and relays the responses back.
  137. */
  138. struct server_http_proxy : server_http_res {
  139. std::function<void()> cleanup = nullptr;
  140. public:
  141. server_http_proxy(const std::string & method,
  142. const std::string & host,
  143. int port,
  144. const std::string & path,
  145. const std::map<std::string, std::string> & headers,
  146. const std::string & body,
  147. const std::function<bool()> should_stop);
  148. ~server_http_proxy() {
  149. if (cleanup) {
  150. cleanup();
  151. }
  152. }
  153. private:
  154. std::thread thread;
  155. struct msg_t {
  156. std::map<std::string, std::string> headers;
  157. int status = 0;
  158. std::string data;
  159. std::string content_type;
  160. };
  161. };