SQLClient.cpp 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. /*
  2. * Copyright (c) 2021, Jan de Visser <jan@de-visser.net>
  3. * Copyright (c) 2022, the SerenityOS developers.
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/ByteString.h>
  8. #include <AK/ScopeGuard.h>
  9. #include <AK/String.h>
  10. #include <LibSQL/SQLClient.h>
  11. #if !defined(AK_OS_SERENITY)
  12. # include <LibCore/Directory.h>
  13. # include <LibCore/SocketAddress.h>
  14. # include <LibCore/StandardPaths.h>
  15. # include <LibCore/System.h>
  16. # include <LibFileSystem/FileSystem.h>
  17. # include <signal.h>
  18. #endif
  19. namespace SQL {
  20. #if !defined(AK_OS_SERENITY)
  21. // This is heavily based on how SystemServer's Service creates its socket.
  22. static ErrorOr<int> create_database_socket(ByteString const& socket_path)
  23. {
  24. if (FileSystem::exists(socket_path))
  25. TRY(Core::System::unlink(socket_path));
  26. # ifdef SOCK_NONBLOCK
  27. auto socket_fd = TRY(Core::System::socket(AF_LOCAL, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0));
  28. # else
  29. auto socket_fd = TRY(Core::System::socket(AF_LOCAL, SOCK_STREAM, 0));
  30. int option = 1;
  31. TRY(Core::System::ioctl(socket_fd, FIONBIO, &option));
  32. TRY(Core::System::fcntl(socket_fd, F_SETFD, FD_CLOEXEC));
  33. # endif
  34. # if !defined(AK_OS_BSD_GENERIC) && !defined(AK_OS_GNU_HURD)
  35. TRY(Core::System::fchmod(socket_fd, 0600));
  36. # endif
  37. auto socket_address = Core::SocketAddress::local(socket_path);
  38. auto socket_address_un = socket_address.to_sockaddr_un().release_value();
  39. TRY(Core::System::bind(socket_fd, reinterpret_cast<sockaddr*>(&socket_address_un), sizeof(socket_address_un)));
  40. TRY(Core::System::listen(socket_fd, 16));
  41. return socket_fd;
  42. }
  43. static ErrorOr<void> launch_server(ByteString const& socket_path, ByteString const& pid_path, Vector<String> candidate_server_paths)
  44. {
  45. auto server_fd_or_error = create_database_socket(socket_path);
  46. if (server_fd_or_error.is_error()) {
  47. warnln("Failed to create a database socket at {}: {}", socket_path, server_fd_or_error.error());
  48. return server_fd_or_error.release_error();
  49. }
  50. auto server_fd = server_fd_or_error.value();
  51. sigset_t original_set;
  52. sigset_t setting_set;
  53. sigfillset(&setting_set);
  54. (void)pthread_sigmask(SIG_BLOCK, &setting_set, &original_set);
  55. auto server_pid = TRY(Core::System::fork());
  56. if (server_pid == 0) {
  57. (void)pthread_sigmask(SIG_SETMASK, &original_set, nullptr);
  58. TRY(Core::System::setsid());
  59. TRY(Core::System::signal(SIGCHLD, SIG_IGN));
  60. server_pid = TRY(Core::System::fork());
  61. if (server_pid != 0) {
  62. auto server_pid_file = TRY(Core::File::open(pid_path, Core::File::OpenMode::Write));
  63. TRY(server_pid_file->write_until_depleted(ByteString::number(server_pid).bytes()));
  64. TRY(Core::System::kill(getpid(), SIGTERM));
  65. }
  66. server_fd = TRY(Core::System::dup(server_fd));
  67. auto takeover_string = ByteString::formatted("SQLServer:{}", server_fd);
  68. TRY(Core::System::setenv("SOCKET_TAKEOVER"sv, takeover_string, true));
  69. ErrorOr<void> result;
  70. for (auto const& server_path : candidate_server_paths) {
  71. auto arguments = Array {
  72. server_path.bytes_as_string_view(),
  73. "--pid-file"sv,
  74. pid_path,
  75. };
  76. result = Core::System::exec(arguments[0], arguments, Core::System::SearchInPath::Yes);
  77. if (!result.is_error())
  78. break;
  79. }
  80. if (result.is_error()) {
  81. warnln("Could not launch any of {}: {}", candidate_server_paths, result.error());
  82. TRY(Core::System::unlink(pid_path));
  83. }
  84. VERIFY_NOT_REACHED();
  85. }
  86. VERIFY(server_pid > 0);
  87. auto wait_err = Core::System::waitpid(server_pid);
  88. (void)pthread_sigmask(SIG_SETMASK, &original_set, nullptr);
  89. if (wait_err.is_error())
  90. return wait_err.release_error();
  91. return {};
  92. }
  93. static ErrorOr<bool> should_launch_server(ByteString const& pid_path)
  94. {
  95. if (!FileSystem::exists(pid_path))
  96. return true;
  97. Optional<pid_t> pid;
  98. {
  99. auto server_pid_file = Core::File::open(pid_path, Core::File::OpenMode::Read);
  100. if (server_pid_file.is_error()) {
  101. warnln("Could not open SQLServer PID file '{}': {}", pid_path, server_pid_file.error());
  102. return server_pid_file.release_error();
  103. }
  104. auto contents = server_pid_file.value()->read_until_eof();
  105. if (contents.is_error()) {
  106. warnln("Could not read SQLServer PID file '{}': {}", pid_path, contents.error());
  107. return contents.release_error();
  108. }
  109. pid = StringView { contents.value() }.to_number<pid_t>();
  110. }
  111. if (!pid.has_value()) {
  112. warnln("SQLServer PID file '{}' exists, but with an invalid PID", pid_path);
  113. TRY(Core::System::unlink(pid_path));
  114. return true;
  115. }
  116. if (kill(*pid, 0) < 0) {
  117. warnln("SQLServer PID file '{}' exists with PID {}, but process cannot be found", pid_path, *pid);
  118. TRY(Core::System::unlink(pid_path));
  119. return true;
  120. }
  121. return false;
  122. }
  123. ErrorOr<NonnullRefPtr<SQLClient>> SQLClient::launch_server_and_create_client(Vector<String> candidate_server_paths)
  124. {
  125. auto runtime_directory = TRY(Core::StandardPaths::runtime_directory());
  126. auto socket_path = ByteString::formatted("{}/SQLServer.socket", runtime_directory);
  127. auto pid_path = ByteString::formatted("{}/SQLServer.pid", runtime_directory);
  128. if (TRY(should_launch_server(pid_path)))
  129. TRY(launch_server(socket_path, pid_path, move(candidate_server_paths)));
  130. auto socket = TRY(Core::LocalSocket::connect(move(socket_path)));
  131. TRY(socket->set_blocking(true));
  132. return adopt_nonnull_ref_or_enomem(new (nothrow) SQLClient(move(socket)));
  133. }
  134. #endif
  135. void SQLClient::execution_success(u64 statement_id, u64 execution_id, Vector<ByteString> const& column_names, bool has_results, size_t created, size_t updated, size_t deleted)
  136. {
  137. if (!on_execution_success) {
  138. outln("{} row(s) created, {} updated, {} deleted", created, updated, deleted);
  139. return;
  140. }
  141. ExecutionSuccess success {
  142. .statement_id = statement_id,
  143. .execution_id = execution_id,
  144. .column_names = move(const_cast<Vector<ByteString>&>(column_names)),
  145. .has_results = has_results,
  146. .rows_created = created,
  147. .rows_updated = updated,
  148. .rows_deleted = deleted,
  149. };
  150. on_execution_success(move(success));
  151. }
  152. void SQLClient::execution_error(u64 statement_id, u64 execution_id, SQLErrorCode const& code, ByteString const& message)
  153. {
  154. if (!on_execution_error) {
  155. warnln("Execution error for statement_id {}: {} ({})", statement_id, message, to_underlying(code));
  156. return;
  157. }
  158. ExecutionError error {
  159. .statement_id = statement_id,
  160. .execution_id = execution_id,
  161. .error_code = code,
  162. .error_message = move(const_cast<ByteString&>(message)),
  163. };
  164. on_execution_error(move(error));
  165. }
  166. void SQLClient::next_result(u64 statement_id, u64 execution_id, Vector<Value> const& row)
  167. {
  168. ScopeGuard guard { [&]() { async_ready_for_next_result(statement_id, execution_id); } };
  169. if (!on_next_result) {
  170. StringBuilder builder;
  171. builder.join(", "sv, row, "\"{}\""sv);
  172. outln("{}", builder.string_view());
  173. return;
  174. }
  175. ExecutionResult result {
  176. .statement_id = statement_id,
  177. .execution_id = execution_id,
  178. .values = move(const_cast<Vector<Value>&>(row)),
  179. };
  180. on_next_result(move(result));
  181. }
  182. void SQLClient::results_exhausted(u64 statement_id, u64 execution_id, size_t total_rows)
  183. {
  184. if (!on_results_exhausted) {
  185. outln("{} total row(s)", total_rows);
  186. return;
  187. }
  188. ExecutionComplete success {
  189. .statement_id = statement_id,
  190. .execution_id = execution_id,
  191. .total_rows = total_rows,
  192. };
  193. on_results_exhausted(move(success));
  194. }
  195. }