server-models.h 6.5 KB

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