5#ifndef LINE_API_SYM_SYM_ENGINES_H
6#define LINE_API_SYM_SYM_ENGINES_H
59#include <netinet/in.h>
60#include <sys/socket.h>
82 return std::vector<std::string>{
"imperialqore/line-sage-rest:latest",
83 "imperialqore/line-sage-rest"};
101 std::shared_ptr<SageRestEngine> started;
102 std::string container;
103 bool atexitRegistered =
false;
106inline SymState& sym_state() {
107 static SymState state;
111inline std::string lower(
const std::string& s) {
113 for (std::size_t i = 0; i < out.size(); ++i)
114 out[i] =
static_cast<char>(std::tolower(out[i]));
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);
127 if (::bind(fd,
reinterpret_cast<struct sockaddr*
>(&addr),
sizeof(addr)) != 0) {
131 socklen_t len =
sizeof(addr);
132 if (::getsockname(fd,
reinterpret_cast<struct sockaddr*
>(&addr), &len) != 0) {
136 const int port =
static_cast<int>(ntohs(addr.sin_port));
142inline bool is_sage_service(
const SageRestEngine& engine) {
144 return engine.info().contains(
"sage_version");
145 }
catch (
const Error&) {
160inline bool serves_required_routes(
const SageRestEngine& engine) {
161 std::vector<std::string> missing;
163 missing = engine.missingRoutes();
164 }
catch (
const Error&) {
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;
176inline void sleep_millis(
long millis) {
178 ts.tv_sec = millis / 1000;
179 ts.tv_nsec = (millis % 1000) * 1000000L;
180 ::nanosleep(&ts,
nullptr);
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();
200 for (std::size_t i = 0; i < candidates.size(); ++i)
202 return std::string();
212inline std::string pull_image(
const std::string& 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();
219 std::cout <<
"[LINE] Pulling Docker image " << target <<
" (this may take a while)..."
222 return std::string();
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 =
231 std::to_string(port) +
":8080", image},
233 if (run.exitCode != 0 ||
util::trim(run.out).empty())
236 SymState& st = sym_state();
238 std::lock_guard<std::mutex> guard(st.mutex);
240 if (!st.atexitRegistered) {
242 st.atexitRegistered =
true;
246 std::shared_ptr<SageRestEngine> engine =
247 std::make_shared<SageRestEngine>(
"http://localhost:" + std::to_string(port));
249 if (engine->isAvailable()) {
250 if (serves_required_routes(*engine) && engine->isUsable()) {
251 std::lock_guard<std::mutex> guard(st.mutex);
260 " answers but cannot evaluate on this CPU");
265 throw SymEngineError(
"SymEngines: container " + name +
" did not become healthy within " +
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);
282 if (reqLower ==
"none" || reqLower ==
"off" || reqLower ==
"native")
return std::shared_ptr<SymEngine>();
284 if (req.compare(0, 8,
"https://") == 0)
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()
292 : std::shared_ptr<SymEngine>();
298 if (url.compare(0, 8,
"https://") == 0) {
300 <<
": this port's HTTP client has no TLS." << std::endl;
302 std::shared_ptr<SageRestEngine> engine = std::make_shared<SageRestEngine>(url);
303 if (engine->isAvailable() && detail::serves_required_routes(*engine) &&
310 detail::SymState& st = detail::sym_state();
311 std::shared_ptr<SageRestEngine> cached;
313 std::lock_guard<std::mutex> guard(st.mutex);
316 if (cached && cached->isAvailable() && cached->isUsable())
return cached;
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) &&
329 req.empty() || reqLower ==
"auto" || reqLower ==
"true" || reqLower ==
"sage";
331 if (image.empty() && reqLower ==
"sage")
334 image = detail::pull_image(image);
335 if (image.empty())
return std::shared_ptr<SymEngine>();
338 return detail::start_container(image);
339 }
catch (
const Error&) {
340 return std::shared_ptr<SymEngine>();
Base error for the multiprecision C++ port.
UnsupportedError(const std::string &what)
SymEngineError(const std::string &what)
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.
constexpr int SAGE_PORT
imperialqore/line-sage-rest.
const char *const SYM_URL_ENV
Environment variable naming a service to use.
constexpr int SYM_STARTUP_TIMEOUT_SECONDS
Seconds to wait for a container to report healthy.
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....
const char *const SYM_DOCKER_IMAGE
Image serving the symbolic REST API.
std::vector< std::string > sym_docker_image_candidates()
Fallback tags, tried in order after SYM_DOCKER_IMAGE.
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.
std::string trim(const std::string &s)
Trims ASCII whitespace from both ends, as Java's String.trim() does.
Conservation laws of a layered queueing network, enumerated from its structure.
SymEngine backed by the line-sage-rest service.
The <kind> part of a LINE:<category>:<kind> identifier (see _kb/17-error-vocabulary....
Running an external command and capturing its output, with a deadline.
Computer algebra operations LINE needs, as seen by this port.