1 /* Copyright 2020-2021 IGEL Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
7 * http://www.apache.org/licenses/LICENSE-2.0
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
16 #include "test-socket-client.h"
27 #include <sys/socket.h>
31 #include "dlm-protocol.h"
32 #include "socket-path.h"
34 #define DEFAULT_RECV_TIMEOUT (100) // timeout in ms to receive data from server
40 struct test_config *config;
43 static void send_lease_request(int socket, enum dlm_opcode opcode)
45 struct dlm_client_request req = {
48 send_dlm_client_request(socket, &req);
51 static void client_gst_socket_status(int socket_fd, struct test_config *config)
54 config->connection_completed = true;
56 struct pollfd pfd = {.fd = socket_fd, .events = POLLIN};
57 if (poll(&pfd, 1, config->recv_timeout) <= 0)
60 if (pfd.revents & POLLHUP)
61 config->connection_completed = false;
63 if (pfd.revents & POLLIN)
64 config->has_data = true;
69 static void *test_client_thread(void *arg)
71 struct client_state *cstate = arg;
72 struct test_config *config = cstate->config;
74 struct sockaddr_un address = {
75 .sun_family = AF_UNIX,
79 sockaddr_set_lease_server_path(&address, config->lease->name),
82 int client = socket(PF_UNIX, SOCK_SEQPACKET, 0);
83 ck_assert_int_ge(client, 0);
86 ret = connect(client, (struct sockaddr *)&address, sizeof(address));
88 printf("Connect failed;: %s\n", strerror(errno));
93 send_lease_request(client, DLM_GET_LEASE);
95 if (!config->recv_timeout)
96 config->recv_timeout = DEFAULT_RECV_TIMEOUT;
98 client_gst_socket_status(client, config);
100 if (config->has_data) {
101 config->received_fd = receive_lease_fd(client);
104 cstate->socket_fd = client;
105 send_lease_request(client, DLM_RELEASE_LEASE);
110 struct client_state *test_client_start(struct test_config *test_config)
112 struct client_state *cstate = malloc(sizeof(*cstate));
114 *cstate = (struct client_state){
115 .config = test_config,
118 pthread_create(&cstate->tid, NULL, test_client_thread, cstate);
123 void test_client_stop(struct client_state *cstate)
126 ck_assert_ptr_ne(cstate, NULL);
128 pthread_join(cstate->tid, NULL);
130 if (cstate->socket_fd >= 0)
131 close(cstate->socket_fd);
136 void test_config_cleanup(struct test_config *config)
138 if (config->has_data && config->received_fd >= 0)
139 close(config->received_fd);