- развертывает узлы контейнерной лаборатории.
- Назначает IP-адреса узлам
Скопируйте необходимые файлы на каждый узел и создайте файл конфигурации для агента Serf. - Запустите агенты Serf
- Присоединяйте узлы к кластеру с помощью Serf
который выдает Curl: (52) Пустой ответ от сервера. Когда я проверил журналы, я обнаружил, что там написано
[INFO] agent.ipc: Accepted client: 10.0.1.11:52128
[ERR] agent.ipc: failed to decode request header: msgpack decode error [pos 1]: only encoded map or array can be decoded into a struct
Поэтому я думаю, что делаю здесь что-то не так, чего мне пока не удалось понять.
Итак, при дальнейшем чтении я наткнулся на протокол RPC. Я думаю, мне нужно использовать команды рукопожатия и get-coordinate. Итак, я попытался установить MsgPack и попробовал использовать некоторый код даже из чатгпт, но все равно это не работает. Я не могу понять, почему это постоянно терпит неудачу. У меня есть RPC в каждом узле (0.0.0.0:7373). Честно говоря, я просто хочу найти самый простой способ получить координаты этих работающих серф-узлов. Прошу любых советов или указаний по этому поводу.
Код, который я использовал:
Я пробовал так много раз, но получал одни и те же ошибки, и я вариантов нет.
import socket
import msgpack
def send_rpc_request(command, body=None):
"""
Sends an RPC request to the Serf agent.
:param command: The command to execute (e.g., "get-coordinate" or "handshake").
:param body: The request body (e.g., {"Node": "serf1"} or {"Version": 1}).
:return: The response from the Serf RPC server.
"""
# RPC server address and port
rpc_address = "172.20.20.2" # IP address of the Serf node
rpc_port = 7373
# Create the request header
header = {
"Command": command,
"Seq": 0 # Sequence number for tracking requests
}
# Serialize the header and body using MessagePack
payload = msgpack.packb(header)
if body:
payload += msgpack.packb(body)
# Create a TCP connection to the RPC server
try:
with socket.create_connection((rpc_address, rpc_port)) as sock:
# Send the serialized request (Handshake first)
print(f"Sending handshake to {rpc_address}:{rpc_port} with body: {body}")
sock.sendall(payload)
# Receive and deserialize the handshake response
response = sock.recv(4096)
print(f"Raw response: {response}") # Print raw response for debugging
unpacked_response = msgpack.unpackb(response, strict_map_key=False)
# Check if handshake was successful
if unpacked_response.get('Error', '') == "":
print(f"Handshake successful: {unpacked_response}")
else:
print(f"Handshake failed: {unpacked_response}")
return None # No point continuing if handshake fails
# Now send the actual command (get-coordinate) after handshake is successful
print(f"Sending '{command}' request for node {body['Node']}")
# Ensure proper format for the request body
coordinate_payload = msgpack.packb({
"Command": "get-coordinate",
"Seq": 1 # New sequence number for this request
})
# Check that the body parameter has the correct format
coordinate_body = {"Node": body["Node"]}
# Double-check the Node parameter is formatted correctly
print(f"Sending get-coordinate request body: {coordinate_body}")
coordinate_payload += msgpack.packb(coordinate_body)
# Send the get-coordinate request
sock.sendall(coordinate_payload) # Send the second request for coordinates
# Receive and deserialize the response for get-coordinate
response = sock.recv(4096)
unpacked_response = msgpack.unpackb(response, strict_map_key=False)
return unpacked_response
except Exception as e:
return {"Error": str(e)}
# Step 1: Send handshake with version information
handshake_response = send_rpc_request("handshake", {"Version": 1}) # First, send the handshake
if handshake_response:
print("Handshake Response:", handshake_response)
# Step 2: Send the get-coordinate request for "serf2" only if handshake is successful
coordinate_response = send_rpc_request("get-coordinate", {"Node": "serf2"})
print("Coordinate Response:", coordinate_response)
Ответ:
python3 script.py
Sending handshake to 172.20.20.2:7373 with body: {'Version': 1}
Raw response: b'\x82\xa5Error\xa0\xa3Seq\x00'
Handshake successful: {'Error': '', 'Seq': 0}
Handshake Response: {'Error': "'Node'"}
Sending handshake to 172.20.20.2:7373 with body: {'Node': 'serf2'}
Raw response: b'\x82\xa5Error\xb2Handshake required\xa3Seq\x00'
Handshake failed: {'Error': 'Handshake required', 'Seq': 0}
Coordinate Response: None
Подробнее здесь: https://stackoverflow.com/questions/792 ... erf-agents
Мобильная версия