Skip to content

Commit

Permalink
Fix format
Browse files Browse the repository at this point in the history
  • Loading branch information
punamverma committed Dec 19, 2024
1 parent 7e7584f commit ab2493e
Show file tree
Hide file tree
Showing 5 changed files with 65 additions and 32 deletions.
6 changes: 1 addition & 5 deletions monitoring/position_reporter/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,7 @@ def require_config_value(config_key: str) -> None:
fmt = "%(asctime)s, %(filename)s:%(lineno)-4s | %(message)s"
datefmt = "%Y-%m-%d:%H:%M:%S"
# Configure the root logger
logging.basicConfig(
format=fmt,
datefmt=datefmt,
level=logging.INFO
)
logging.basicConfig(format=fmt, datefmt=datefmt, level=logging.INFO)

AUTH_SPEC = "POS_REP_AUTH_SPEC"
import_environment_variable(AUTH_SPEC)
Expand Down
4 changes: 3 additions & 1 deletion monitoring/position_reporter/gunicorn.conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,9 @@ def post_request(worker: Worker, req: Request, environ: dict, resp: Response):
def worker_abort(worker: Worker):
"""gunicorn server hook called when a worker received the SIGABRT signal."""
logging.debug(
"gunicorn worker_abort from worker {} (OS PID {})".format(worker.pid, os.getpid())
"gunicorn worker_abort from worker {} (OS PID {})".format(
worker.pid, os.getpid()
)
)


Expand Down
56 changes: 41 additions & 15 deletions monitoring/position_reporter/position_reports/sender.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,32 +6,43 @@
import json

from implicitdict import StringBasedDateTime
from monitoring.position_reporter.position_reports.position_report import PositionReport, PositionReportPlan, \
PositionReportsPlan
from monitoring.position_reporter.position_reports.position_report import (
PositionReport,
PositionReportPlan,
PositionReportsPlan,
)
from monitoring.monitorlib.infrastructure import AuthAdapter


def get_position_report_from_plan(pr: PositionReportPlan, time_measured: datetime.datetime) -> PositionReport:
def get_position_report_from_plan(
pr: PositionReportPlan, time_measured: datetime.datetime
) -> PositionReport:
return PositionReport(
latitude=pr.latitude,
longitude=pr.longitude,
altitude=pr.latitude,
time_measured=StringBasedDateTime(time_measured),
speed=pr.speed,
track=pr.track
track=pr.track,
)


async def post_position(pos_base_url: str, pr: PositionReport, client: aiohttp.ClientSession):
async def post_position(
pos_base_url: str, pr: PositionReport, client: aiohttp.ClientSession
):
logging.info(f"Posted position to {pos_base_url} : \n{json.dumps(pr, indent=4)}")
async with client.post(url=pos_base_url, data=json.dumps(pr)) as response:
content = await response.text()
logging.info(f"Response status received: {response.status}")
logging.debug(f"Response received: {content}")


async def send_positions_periodically(pos_base_url: str, prs: PositionReportsPlan, client: aiohttp.ClientSession,
time_start: datetime.datetime):
async def send_positions_periodically(
pos_base_url: str,
prs: PositionReportsPlan,
client: aiohttp.ClientSession,
time_start: datetime.datetime,
):
tasks = []
prev_time = time_start
i = 0
Expand All @@ -48,12 +59,20 @@ async def send_positions_periodically(pos_base_url: str, prs: PositionReportsPla
results = await asyncio.gather(*tasks)


async def send_position_reports_async(req_id: str, pos_base_url: str, auth_client: AuthAdapter,
prs: PositionReportsPlan,
time_start: datetime.datetime):
auth_token = auth_client.get_headers(url=pos_base_url, scopes=["interuss.flight_data.position"])
async def send_position_reports_async(
req_id: str,
pos_base_url: str,
auth_client: AuthAdapter,
prs: PositionReportsPlan,
time_start: datetime.datetime,
):
auth_token = auth_client.get_headers(
url=pos_base_url, scopes=["interuss.flight_data.position"]
)
async with aiohttp.ClientSession(headers=auth_token) as client:
task2 = asyncio.create_task(send_positions_periodically(pos_base_url, prs, client, time_start))
task2 = asyncio.create_task(
send_positions_periodically(pos_base_url, prs, client, time_start)
)
await task2
logging.info("All position reports sent")

Expand All @@ -63,13 +82,20 @@ async def send_position_reports_async(req_id: str, pos_base_url: str, auth_clien
logging.info(f"==Req id {req_id} : Sent all position reports.")


def send_position_reports(req_id: str, pos_url: str, auth_client: AuthAdapter, prs: PositionReportsPlan,
time_start: datetime.datetime):
def send_position_reports(
req_id: str,
pos_url: str,
auth_client: AuthAdapter,
prs: PositionReportsPlan,
time_start: datetime.datetime,
):
logging.info(f"Start req id {req_id} at {time_start}")
wait_to_start = time_start - datetime.datetime.now()
if wait_to_start.total_seconds() >= 0:
time.sleep(wait_to_start.total_seconds())

loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(send_position_reports_async(req_id, pos_url, auth_client, prs, time_start))
loop.run_until_complete(
send_position_reports_async(req_id, pos_url, auth_client, prs, time_start)
)
29 changes: 20 additions & 9 deletions monitoring/position_reporter/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,23 +8,25 @@
from implicitdict import ImplicitDict

from monitoring.position_reporter import get_auth_client
from monitoring.position_reporter.position_reports.position_report import PositionReportsPlan
from monitoring.position_reporter.position_reports.position_report import (
PositionReportsPlan,
)
from monitoring.position_reporter.position_reports.sender import send_position_reports
from monitoring.position_reporter import webapp


@webapp.route('/status', methods=["GET"])
@webapp.route("/status", methods=["GET"])
def status():
# req = flask.request.json
res = {
"status": "Ready",
"api_name": "Position Report Plan Interface",
"api_version": "v0.1.0"
"api_version": "v0.1.0",
}
return flask.jsonify(res), 200


@webapp.route('/send_pos', methods=['POST'])
@webapp.route("/send_pos", methods=["POST"])
def send_pos():
# Start a new thread to send the periodic POST requests
req_plan = flask.request.json
Expand All @@ -39,10 +41,19 @@ def send_pos():

logging.info(f"Time start for positions - {time_start}")

threading.Thread(target=send_position_reports,
kwargs={"req_id": req_id, "pos_url": positions_plan.pos_url, "auth_client": get_auth_client(),
"prs": positions_plan.positions, "time_start": time_start}).start()

logging.info(f"******* End of req id {req_id} main thread - {threading.current_thread().name}")
threading.Thread(
target=send_position_reports,
kwargs={
"req_id": req_id,
"pos_url": positions_plan.pos_url,
"auth_client": get_auth_client(),
"prs": positions_plan.positions,
"time_start": time_start,
},
).start()

logging.info(
f"******* End of req id {req_id} main thread - {threading.current_thread().name}"
)

return f"Completed POST requests to {positions_plan.pos_url} at {datetime.datetime.now()}"
2 changes: 0 additions & 2 deletions monitoring/position_reporter/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@


class PositionReporter(flask.Flask):

def __init__(self, *args, **kwargs):
self._pid = os.getpid()
super(PositionReporter, self).__init__(*args, **kwargs)
Expand All @@ -24,4 +23,3 @@ def shutdown(self, signal_number: Optional[int], stack):
logging.debug(
f"Process {os.getpid()} stopped with signal {signal_number} while MockUSS server was not stopping"
)

0 comments on commit ab2493e

Please sign in to comment.