Skip to content

Commit

Permalink
Merge pull request #1 from 5genesis/debugging
Browse files Browse the repository at this point in the history
Debugging
  • Loading branch information
NaniteBased authored Oct 19, 2020
2 parents 700ae98 + af69362 commit 4eabb95
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 13 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
**19/10/2020** [Version 1.0.4]

- Fix handling of ping process closure
- Improve debugging and error handling

**20/04/2020** [Version 1.0.3]

- Allow setting the ping interval (-i) and TTL (-t)
Expand Down
14 changes: 8 additions & 6 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@
app = Flask(__name__)


def errorResponse(message, error):
print(f'{message}: {error}')
return jsonify({'Status': 'Error', 'Message': message, 'Error': f'{error}'}), 403


@app.route('/Ping/<address>', methods=['GET'])
def Ping(address: str):
try:
Expand All @@ -13,8 +18,7 @@ def Ping(address: str):
ping.Ping(address, interval, size, ttl)
return jsonify({'Status': 'Success', 'Message': 'Successfully executed ping'})
except Exception as error:
print(f'{error}')
return jsonify({'Status': 'Error', 'Message': 'Error executing ping', 'Error': f'{error}'}), 403
return errorResponse('Error executing ping', error)


@app.route('/Close', methods=['GET'])
Expand All @@ -23,8 +27,7 @@ def Close():
ping.Close()
return jsonify({'Status': 'Success', 'Message': 'Successfully closed ping'})
except Exception as error:
print(f'{error}')
return jsonify({'Status': 'Error', 'Message': 'Error closing ping', 'Error': f'{error}'}), 403
return errorResponse('Error closing ping', error)


@app.route('/LastJsonResult', methods=['GET'])
Expand All @@ -33,8 +36,7 @@ def LastJsonResult():
return jsonify({'Status': 'Success', 'Message': 'Successfully retrieved last json result',
'Result': ping.LastJsonResult()})
except Exception as error:
print(f'{error}')
return jsonify({'Status': 'Error', 'Message': 'Error retrieving last json result', 'Error': f'{error}'}), 403
return errorResponse('Error retrieving last json result', error)


@app.route('/StartDateTime', methods=['GET'])
Expand Down
19 changes: 12 additions & 7 deletions pingExecutor/pingExecutor.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,18 @@
import subprocess
import pingparsing
from textwrap import dedent
from typing import List, Dict
from typing import List, Dict, Optional
from datetime import datetime, timedelta, timezone
from threading import Thread
from pprint import pprint


class ping:
isRunning = False
jsonResult: Dict = {}
error: List[str] = []
startTime: datetime = None
processPID: int = -1
processPID: Optional[int] = None

@classmethod
def Ping(cls, address: str, interval: float, size: int, ttl: int):
Expand All @@ -29,13 +30,9 @@ def Ping(cls, address: str, interval: float, size: int, ttl: int):

@classmethod
def Close(cls):
if not cls.isRunning or cls.processPID == -1:
if not cls.isRunning or cls.processPID is None:
raise RuntimeError('ping is not running')

os.kill(cls.processPID, signal.SIGTERM)
cls.processPID = -1
cls.isRunning = False
return 1

@classmethod
def LastJsonResult(cls):
Expand All @@ -61,6 +58,7 @@ def execute(cls, parameters: List[str], interval: float) -> None:
raise RuntimeError('ping already running')

params = ['ping', *parameters]
print(f'Final CLI paramenters: {params}')
Thread(target=cls.async_task, args=(params, interval)).start()
return None

Expand All @@ -76,6 +74,8 @@ def stdout(cls, process: subprocess.Popen, interval: float):
except Exception as e:
line = f'DECODING EXCEPTION: {e}'

print(line)

if 'error' in line or 'failed' in line:
cls.error.append(line)

Expand Down Expand Up @@ -106,10 +106,14 @@ def stdout(cls, process: subprocess.Popen, interval: float):
cls.jsonResult = {'total': len(icmp_replies), 'success': len(icmp_replies)-len(lostPings),
'icmp_replies': icmp_replies}

print("Final JSON results")
pprint(cls.jsonResult)

@classmethod
def async_task(cls, params: List[str], interval: float):
cls.isRunning = True
cls.error = []
cls.jsonResult = {}
cls.startTime = datetime.now(timezone.utc)
try:
process = subprocess.Popen(params, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
Expand All @@ -121,5 +125,6 @@ def async_task(cls, params: List[str], interval: float):
print(f'Error in process: {e}')
finally:
cls.isRunning = False
cls.processPID = None

print('ping finished')

0 comments on commit 4eabb95

Please sign in to comment.