Whamcloud - gitweb
LU-16915 tests: except sanity-sec test_51
[fs/lustre-release.git] / lustre / tests / socketserver
1 #!/usr/bin/env python3
2 # SPDX-License-Identifier: GPL-2.0
3
4 #
5 # This file is part of Lustre, http://www.lustre.org/
6 #
7 # lustre/tests/socketserver
8 #
9 # Domain socket server, used to test that domain sockets
10 # work on lustre.
11 #
12 # Rewrite in Python: Timothy Day <timday@amazon.com>
13 #
14
15 import os
16 import socket
17 import sys
18
19
20 # Define a function for logging messages
21 def logmsg(msg):
22         print(f"{sys.argv[0]} {os.getpid()}: {msg} at {os.popen('date').read().strip()}")
23
24
25 # Get the socket path from the command-line argument,
26 # or ask the user to input one
27 if len(sys.argv) > 1:
28         socket_path = sys.argv[1]
29 else:
30         socket_path = input("Enter socket path: ")
31
32 try:
33         # Create a Unix domain socket with a specified file path
34         sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
35
36         # Bind the socket to the Unix domain socket file
37         sock.bind(socket_path)
38
39         # Listen for incoming connections on the socket
40         sock.listen(socket.SOMAXCONN)
41
42         # Fork a child process to handle the connection
43         pid = os.fork()
44
45         if pid > 0:
46                 # Parent process
47                 logmsg(f"server started on {socket_path}")
48                 sys.exit(0)
49         elif pid < 0:
50                 # Fork failed
51                 logmsg(f"fork failed: {pid}")
52                 sys.exit(1)
53
54         # Accept an incoming connection
55         client_sock, _ = sock.accept()
56
57         logmsg(f"connection on {socket_path}")
58
59         # Send a message to the client and close
60         # the client socket
61         client_sock.send(b"This is a message from the server!\n")
62         client_sock.close()
63
64 except socket.error as e:
65         logmsg(f"Socket error: {e}")
66
67 finally:
68         sock.close()