SQLClient.cpp 7.7 KB

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