LINE Solver (C++)
Templated C++ port of the LINE queueing solver
Loading...
Searching...
No Matches
sym_engines.h
Go to the documentation of this file.
1/*
2 * Copyright (c) 2012-2026, QORE Lab, Imperial College London
3 * All rights reserved.
4 */
5#ifndef LINE_API_SYM_SYM_ENGINES_H
6#define LINE_API_SYM_SYM_ENGINES_H
7
8/**
9 * @file
10 * @ingroup api_sym
11 * Resolves the symbolic backend to use, and owns the container that serves it.
12 *
13 * Port of jline.api.sym.SymEngines. Resolution order, the same in MATLAB
14 * (SAGE.m), the JAR and Python (line_solver.api.sym):
15 * 1. an explicit URL, from solver options or the `requested` argument;
16 * 2. the LINE_SAGE_URL environment variable;
17 * 3. a line-sage-rest service already listening on a conventional port;
18 * 4. a container started here from a locally present image;
19 * 5. nothing, in which case the caller keeps whatever native algebra it has,
20 * or reports that no backend is configured.
21 *
22 * STEP 3 VERIFIES IDENTITY THROUGH /api/v1/info rather than trusting the port:
23 * every imperialqore line-*-rest service listens on 8080 inside its container
24 * and was published on host port 8080 before the allocation in
25 * line/io/line_ports.h, so a health probe alone would happily accept the LQNS service and then fail on the
26 * first symbolic request with an unrecognizable error.
27 *
28 * The container started in step 4 is reused for the life of the process and
29 * stopped by an atexit handler. It is bound to an ephemeral host port, so
30 * several processes, or a process alongside a hand-started service, do not
31 * collide. An atexit handler does NOT run on a signal or on _exit, so a
32 * container may outlive a killed process; `docker ps` shows it under the name
33 * `line-sage-rest-<port>` and it was started with --rm, so stopping it removes it.
34 *
35 * A PULL HAPPENS ONLY ON EXPLICIT OPT-IN, i.e. the "sage" keyword or a named
36 * image. Bare "auto"/"true"/"" keep the native backend unless the image is
37 * already local, so leaving the symbolic option on auto never triggers a
38 * multi-gigabyte download, and the pull itself is refused when the Docker
39 * storage location is short of space (see line/io/docker_image.h).
40 *
41 * DIVERGENCE FROM THE JAR: an https:// URL is refused by name rather than used,
42 * because this port's HTTP client has no TLS (see line/util/http.h). Refusing
43 * loudly is the point -- reporting "no backend" for a service that is up and
44 * merely unreachable over plaintext would send the caller looking in the wrong
45 * place.
46 */
47
48#include <cctype>
49#include <cstddef>
50#include <cstdlib>
51#include <cstring>
52#include <ctime>
53#include <iostream>
54#include <memory>
55#include <mutex>
56#include <string>
57#include <vector>
58
59#include <netinet/in.h>
60#include <sys/socket.h>
61#include <unistd.h>
62
66#include "line/io/line_ports.h"
67#include "line/util/error.h"
69
70namespace line {
71namespace sym {
72
73/** Image serving the symbolic REST API. */
74inline const char* const SYM_DOCKER_IMAGE = "imperialqore/line-sage-rest:latest";
75/** Environment variable naming a service to use. */
76inline const char* const SYM_URL_ENV = "LINE_SAGE_URL";
77/** Seconds to wait for a container to report healthy. */
78inline constexpr int SYM_STARTUP_TIMEOUT_SECONDS = 120;
79
80/** Fallback tags, tried in order after SYM_DOCKER_IMAGE. */
81inline std::vector<std::string> sym_docker_image_candidates() {
82 return std::vector<std::string>{"imperialqore/line-sage-rest:latest",
83 "imperialqore/line-sage-rest"};
84}
85
86/**
87 * Ports probed for an already running service, in order: the allocated host
88 * port (line/io/line_ports.h) first; 8085 (the old test-harness port) and the
89 * legacy 8080 stay so a service started by an older release or by hand is
90 * still found.
91 */
92inline std::vector<int> sym_probe_ports() {
93 return std::vector<int>{ports::SAGE_PORT, 8085, ports::LEGACY_PORT};
94}
95
96namespace detail {
97
98/** Process-wide record of the container this process started, if any. */
99struct SymState {
100 std::mutex mutex;
101 std::shared_ptr<SageRestEngine> started;
102 std::string container;
103 bool atexitRegistered = false;
104};
105
106inline SymState& sym_state() {
107 static SymState state;
108 return state;
109}
110
111inline std::string lower(const std::string& s) {
112 std::string out(s);
113 for (std::size_t i = 0; i < out.size(); ++i)
114 out[i] = static_cast<char>(std::tolower(out[i]));
115 return out;
116}
117
118/** An unused local TCP port, obtained the way the JAR does: bind port 0. */
119inline int free_port() {
120 const int fd = ::socket(AF_INET, SOCK_STREAM, 0);
121 if (fd < 0) throw SymEngineError("SymEngines: cannot open a socket to pick a free port");
122 struct sockaddr_in addr;
123 std::memset(&addr, 0, sizeof(addr));
124 addr.sin_family = AF_INET;
125 addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
126 addr.sin_port = 0;
127 if (::bind(fd, reinterpret_cast<struct sockaddr*>(&addr), sizeof(addr)) != 0) {
128 ::close(fd);
129 throw SymEngineError("SymEngines: cannot bind a free port");
130 }
131 socklen_t len = sizeof(addr);
132 if (::getsockname(fd, reinterpret_cast<struct sockaddr*>(&addr), &len) != 0) {
133 ::close(fd);
134 throw SymEngineError("SymEngines: cannot read the bound port");
135 }
136 const int port = static_cast<int>(ntohs(addr.sin_port));
137 ::close(fd);
138 return port;
139}
140
141/** Checks that a service is line-sage-rest and not another line-*-rest one. */
142inline bool is_sage_service(const SageRestEngine& engine) {
143 try {
144 return engine.info().contains("sage_version");
145 } catch (const Error&) {
146 return false;
147 }
148}
149
150/**
151 * True if this service serves every route the client calls, saying what is
152 * missing when it does not.
153 *
154 * A service that is line-sage-rest, healthy and arithmetically sound can still
155 * be OLDER THAN THE CLIENT, and accepting it defers the failure to the first
156 * request needing a route it does not have. Refusing here sends the caller down
157 * the same path as "no service at all" -- the native algebra, or a skip -- and
158 * says why. See SageRestEngine::missingRoutes for the run that motivated it.
159 */
160inline bool serves_required_routes(const SageRestEngine& engine) {
161 std::vector<std::string> missing;
162 try {
163 missing = engine.missingRoutes();
164 } catch (const Error&) {
165 return false;
166 }
167 if (missing.empty()) return true;
168 std::cerr << "[LINE] Ignoring the line-sage-rest service at " << engine.getBaseUrl()
169 << ": it is older than this client and does not serve ";
170 for (std::size_t i = 0; i < missing.size(); ++i)
171 std::cerr << (i ? ", " : "") << missing[i];
172 std::cerr << ". Refresh it with 'docker pull " << SYM_DOCKER_IMAGE << "'." << std::endl;
173 return false;
174}
175
176inline void sleep_millis(long millis) {
177 struct timespec ts;
178 ts.tv_sec = millis / 1000;
179 ts.tv_nsec = (millis % 1000) * 1000000L;
180 ::nanosleep(&ts, nullptr);
181}
182
183} // namespace detail
184
185/** Stops the container started by this process, if any. */
186inline void sym_stop_container() {
187 detail::SymState& st = detail::sym_state();
188 std::lock_guard<std::mutex> guard(st.mutex);
189 if (st.container.empty()) return;
190 util::capture({"docker", "stop", "-t", "1", st.container}, 30);
191 st.container.clear();
192 st.started.reset();
193}
194
195/**
196 * @return the first locally present image tag, or the empty string if none is
197 */
198inline std::string sym_find_image() {
199 const std::vector<std::string> candidates = sym_docker_image_candidates();
200 for (std::size_t i = 0; i < candidates.size(); ++i)
201 if (io::docker_has_local_image(candidates[i])) return candidates[i];
202 return std::string();
203}
204
205namespace detail {
206
207/**
208 * Pulls `target` if the Docker storage location has room; returns the tag on
209 * success, else the empty string. On refusal the caller keeps its native
210 * algebra rather than failing.
211 */
212inline std::string pull_image(const std::string& target) {
213 if (!io::docker_has_storage_for(target)) {
214 std::cerr << "[LINE] Skipping docker pull of " << target
215 << ": insufficient free space at the Docker storage location; "
216 << "keeping the native symbolic backend." << std::endl;
217 return std::string();
218 }
219 std::cout << "[LINE] Pulling Docker image " << target << " (this may take a while)..."
220 << std::endl;
221 if (io::docker_pull(target) && io::docker_has_local_image(target)) return target;
222 return std::string();
223}
224
225/** Starts the service in a container and waits for it to report healthy. */
226inline std::shared_ptr<SageRestEngine> start_container(const std::string& image) {
227 const int port = free_port();
228 const std::string name = "line-sage-rest-" + std::to_string(port);
229 const util::ProcResult run =
230 util::capture({"docker", "run", "-d", "--rm", "--name", name, "-p",
231 std::to_string(port) + ":8080", image},
232 120);
233 if (run.exitCode != 0 || util::trim(run.out).empty())
234 throw SymEngineError("SymEngines: could not start " + image);
235
236 SymState& st = sym_state();
237 {
238 std::lock_guard<std::mutex> guard(st.mutex);
239 st.container = name;
240 if (!st.atexitRegistered) {
241 std::atexit(&sym_stop_container);
242 st.atexitRegistered = true;
243 }
244 }
245
246 std::shared_ptr<SageRestEngine> engine =
247 std::make_shared<SageRestEngine>("http://localhost:" + std::to_string(port));
248 for (int waited = 0; waited < SYM_STARTUP_TIMEOUT_SECONDS * 1000; waited += 500) {
249 if (engine->isAvailable()) {
250 if (serves_required_routes(*engine) && engine->isUsable()) {
251 std::lock_guard<std::mutex> guard(st.mutex);
252 st.started = engine;
253 return engine;
254 }
255 // Booted, but its arithmetic dies on this CPU. Keeping it running
256 // would only cost memory, and returning it would hand the caller a
257 // backend that kills every request.
259 throw SymEngineError("SymEngines: container " + name +
260 " answers but cannot evaluate on this CPU");
261 }
262 sleep_millis(500);
263 }
265 throw SymEngineError("SymEngines: container " + name + " did not become healthy within " +
266 std::to_string(SYM_STARTUP_TIMEOUT_SECONDS) + " s");
267}
268
269} // namespace detail
270
271/**
272 * Resolves an engine.
273 *
274 * @param requested "" or "auto" to search, a URL to use a specific service,
275 * "none"/"native" to disable the backend, or an image name to start
276 * @return an engine, or a null pointer if no backend could be resolved
277 */
278inline std::shared_ptr<SymEngine> sym_resolve(const std::string& requested = "auto") {
279 const std::string req = util::trim(requested);
280 const std::string reqLower = detail::lower(req);
281 // "native" is a documented value, not an image name
282 if (reqLower == "none" || reqLower == "off" || reqLower == "native") return std::shared_ptr<SymEngine>();
283
284 if (req.compare(0, 8, "https://") == 0)
285 throw UnsupportedError(ErrorKind{"Https"},
286 "SymEngines: this port's HTTP client has no TLS, so the symbolic service must be "
287 "reached over http://; terminate TLS in front of it or use a local container");
288 if (req.compare(0, 7, "http://") == 0) {
289 std::shared_ptr<SageRestEngine> engine = std::make_shared<SageRestEngine>(req);
290 return engine->isAvailable() && detail::serves_required_routes(*engine) && engine->isUsable()
291 ? engine
292 : std::shared_ptr<SymEngine>();
293 }
294
295 const char* env = std::getenv(SYM_URL_ENV);
296 if (env != nullptr && !util::trim(env).empty()) {
297 const std::string url = util::trim(env);
298 if (url.compare(0, 8, "https://") == 0) {
299 std::cerr << "[LINE] Ignoring " << SYM_URL_ENV
300 << ": this port's HTTP client has no TLS." << std::endl;
301 } else {
302 std::shared_ptr<SageRestEngine> engine = std::make_shared<SageRestEngine>(url);
303 if (engine->isAvailable() && detail::serves_required_routes(*engine) &&
304 engine->isUsable())
305 return engine;
306 }
307 }
308
309 {
310 detail::SymState& st = detail::sym_state();
311 std::shared_ptr<SageRestEngine> cached;
312 {
313 std::lock_guard<std::mutex> guard(st.mutex);
314 cached = st.started;
315 }
316 if (cached && cached->isAvailable() && cached->isUsable()) return cached;
317 }
318
319 const std::vector<int> ports = sym_probe_ports();
320 for (std::size_t i = 0; i < ports.size(); ++i) {
321 std::shared_ptr<SageRestEngine> engine =
322 std::make_shared<SageRestEngine>("http://localhost:" + std::to_string(ports[i]));
323 if (detail::is_sage_service(*engine) && detail::serves_required_routes(*engine) &&
324 engine->isUsable())
325 return engine;
326 }
327
328 const bool search =
329 req.empty() || reqLower == "auto" || reqLower == "true" || reqLower == "sage";
330 std::string image = search ? sym_find_image() : req;
331 if (image.empty() && reqLower == "sage")
332 image = detail::pull_image(SYM_DOCKER_IMAGE);
333 else if (!search && !image.empty() && !io::docker_has_local_image(image))
334 image = detail::pull_image(image);
335 if (image.empty()) return std::shared_ptr<SymEngine>();
336
337 try {
338 return detail::start_container(image);
339 } catch (const Error&) {
340 return std::shared_ptr<SymEngine>();
341 }
342}
343
344} // namespace sym
345} // namespace line
346
347#endif // LINE_API_SYM_SYM_ENGINES_H
Base error for the multiprecision C++ port.
Definition error.h:73
UnsupportedError(const std::string &what)
Definition error.h:119
SymEngineError(const std::string &what)
Definition sym_engine.h:43
Docker primitives for the backends that legitimately ship an image.
The exception types the port throws.
Host ports of the LINE service containers.
bool docker_has_storage_for(const std::string &image)
bool docker_has_local_image(const std::string &image)
bool docker_pull(const std::string &image)
Pulls an image, streaming Docker's progress to stdout and stderr.
std::string name(const Element *el, const std::string &key="name")
constexpr int LEGACY_PORT
Host port every service used before the allocation; a verified fallback only.
Definition line_ports.h:45
constexpr int SAGE_PORT
imperialqore/line-sage-rest.
Definition line_ports.h:64
const char *const SYM_URL_ENV
Environment variable naming a service to use.
Definition sym_engines.h:76
constexpr int SYM_STARTUP_TIMEOUT_SECONDS
Seconds to wait for a container to report healthy.
Definition sym_engines.h:78
std::string sym_find_image()
std::shared_ptr< SymEngine > sym_resolve(const std::string &requested="auto")
Resolves an engine.
std::vector< int > sym_probe_ports()
Ports probed for an already running service, in order: the allocated host port (line/io/line_ports....
Definition sym_engines.h:92
const char *const SYM_DOCKER_IMAGE
Image serving the symbolic REST API.
Definition sym_engines.h:74
std::vector< std::string > sym_docker_image_candidates()
Fallback tags, tried in order after SYM_DOCKER_IMAGE.
Definition sym_engines.h:81
void sym_stop_container()
Stops the container started by this process, if any.
ProcResult capture(const std::vector< std::string > &argv, int timeoutSeconds, bool mergeStderr=false)
Runs a command, capturing stdout and discarding stderr.
Definition subprocess.h:82
std::string trim(const std::string &s)
Trims ASCII whitespace from both ends, as Java's String.trim() does.
Definition subprocess.h:181
Conservation laws of a layered queueing network, enumerated from its structure.
Definition aoi_dist2ph.h:51
SymEngine backed by the line-sage-rest service.
The <kind> part of a LINE:<category>:<kind> identifier (see _kb/17-error-vocabulary....
Definition error.h:37
Running an external command and capturing its output, with a deadline.
Computer algebra operations LINE needs, as seen by this port.