2021-01-05 16:05:44 +00:00
|
|
|
from datetime import datetime
|
|
|
|
from typing import Optional
|
|
|
|
|
2021-01-05 15:53:44 +00:00
|
|
|
from pymongo.database import Database
|
|
|
|
|
|
|
|
|
|
|
|
def _add_active_duration(db: Database):
|
|
|
|
active_duration = "active_duration"
|
|
|
|
query = {active_duration: {"$eq": None}}
|
|
|
|
collection = db["task"]
|
|
|
|
for doc in collection.find(
|
2021-01-05 16:05:44 +00:00
|
|
|
filter=query, projection=[active_duration, "status", "started", "completed"]
|
2021-01-05 15:53:44 +00:00
|
|
|
):
|
|
|
|
started = doc.get("started")
|
2021-01-05 16:05:44 +00:00
|
|
|
completed = doc.get("completed")
|
|
|
|
running = doc.get("status") == "running"
|
|
|
|
if started and doc.get(active_duration) is None:
|
2021-01-05 15:53:44 +00:00
|
|
|
collection.update_one(
|
|
|
|
{"_id": doc["_id"]},
|
2021-01-05 16:05:44 +00:00
|
|
|
{"$set": {active_duration: _get_active_duration(completed, running, started)}},
|
2021-01-05 15:53:44 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
2021-01-05 16:05:44 +00:00
|
|
|
def _get_active_duration(
|
|
|
|
completed: datetime, running: bool, started: datetime
|
|
|
|
) -> Optional[float]:
|
|
|
|
if running:
|
|
|
|
return (datetime.utcnow() - started).total_seconds()
|
|
|
|
elif completed:
|
|
|
|
return (completed - started).total_seconds()
|
|
|
|
else:
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
2021-01-05 15:53:44 +00:00
|
|
|
def migrate_backend(db: Database):
|
|
|
|
"""
|
|
|
|
Add active_duration field to tasks
|
|
|
|
"""
|
|
|
|
_add_active_duration(db)
|