From 9d1372aea87ec0c9abdecbbe28f008ea4174c9fc Mon Sep 17 00:00:00 2001 From: hans362 Date: Sun, 5 Feb 2023 14:31:16 +0800 Subject: [PATCH] :tada: First commit --- .gitignore | 3 ++ agent.py | 71 ++++++++++++++++++++++++++++++++++++++++++++++++ requirements.txt | 2 ++ 3 files changed, 76 insertions(+) create mode 100644 agent.py create mode 100644 requirements.txt diff --git a/.gitignore b/.gitignore index b6e4761..4963aa6 100644 --- a/.gitignore +++ b/.gitignore @@ -127,3 +127,6 @@ dmypy.json # Pyre type checker .pyre/ + +# WSL launcher +launch.bat \ No newline at end of file diff --git a/agent.py b/agent.py new file mode 100644 index 0000000..ef643a6 --- /dev/null +++ b/agent.py @@ -0,0 +1,71 @@ +import argparse +import requests +from ping3 import ping + + +def RegisterAgent(apiEndpoint, secret, name): + try: + response = requests.get( + apiEndpoint + '/registerAgent?secret='+secret+'&name='+name) + if response.status_code == 200: + return response.json()['agentId'] + else: + raise Exception('Error registering agent') + except Exception as e: + print(e) + return None + + +def GetNodeList(apiEndpoint, secret): + try: + response = requests.get(apiEndpoint + '/getNodeList?secret='+secret) + if response.status_code == 200: + return response.json()['nodes'] + else: + raise Exception('Error getting node list') + except Exception as e: + print(e) + return None + + +def RegisterRecord(apiEndpoint, secret, agentId, nodeId, lantency): + try: + response = requests.get(apiEndpoint + '/registerRecord?secret=' + + secret+'&agentId='+agentId+'&nodeId='+nodeId+'&lantency='+lantency) + if not response.status_code == 200: + raise Exception('Error registering record') + except Exception as e: + print(e) + + +# Accept args from command line +parser = argparse.ArgumentParser() +parser.add_argument('-a', '--apiEndpoint', + help='API Endpoint URL. eg. https://pinging.vercel.app/api', required=True) +parser.add_argument( + '-s', '--secret', help='Agent Secret. eg. 9cWxVbX35UL2Dhj4', required=True) +parser.add_argument('-n', '--name', help='Agent Friendly Name', required=True) +args = parser.parse_args() + +# Register agent +agentId = RegisterAgent(args.apiEndpoint, args.secret, args.name) +if agentId == None: + print('Agent registration failed') + exit() + +# Get node list +nodeList = GetNodeList(args.apiEndpoint, args.secret) +if nodeList == None: + print('Failed to get node list') + exit() + +# Ping nodes +for node in nodeList: + print('Pinging ' + node['hostname']) + lantency = ping(node['hostname'], unit='ms') + if lantency == None or lantency == False: + lantency = -1 + lantency = int(lantency) + print('Lantency: ' + str(lantency)) + RegisterRecord(args.apiEndpoint, args.secret, + str(agentId), str(node['id']), str(lantency)) diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..702e477 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,2 @@ +ping3==4.0.4 +requests==2.22.0