Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SystemService and backend improvements #193

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 12 additions & 13 deletions karton/core/backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -274,20 +274,19 @@ def get_tasks(self, task_uid_list: List[str], chunk_size: int = 1000) -> List[Ta
if task_data is not None
]

def get_all_tasks(self, chunk_size: int = 1000) -> List[Task]:
def get_all_tasks(self, chunk_size: int = 1000) -> Iterator[Iterable[Task]]:
"""
Get all tasks registered in Redis
Get all tasks registered in Redis generator

Yielding slice of data to reduce RAM usage and prevent DoS

:param chunk_size: Size of chunks passed to the Redis MGET command
:return: List with Task objects
:return: Generator with Iterable[Task objects] of chunk_size length
"""
tasks = self.redis.keys(f"{KARTON_TASK_NAMESPACE}:*")
return [
Task.unserialize(task_data)
for chunk in chunks(tasks, chunk_size)
for task_data in self.redis.mget(chunk)
if task_data is not None
]

for chunk in chunks(tasks, chunk_size):
yield map(Task.unserialize, filter(None, self.redis.mget(chunk)))

def register_task(self, task: Task, pipe: Optional[Pipeline] = None) -> None:
"""
Expand Down Expand Up @@ -535,17 +534,17 @@ def increment_metrics(
rs.hincrby(metric.value, identity, 1)

def increment_metrics_list(
self, metric: KartonMetrics, identities: List[str]
self, metric: KartonMetrics, identities: Dict[str, int]
) -> None:
"""
Increments metrics for multiple identities via single pipeline

:param metric: Operation metric type
:param identities: List of Karton service identities
:param identities: Dict of Karton service identities mapped to their count
"""
p = self.redis.pipeline()
for identity in identities:
p.hincrby(metric.value, identity, 1)
for identity, increment in identities.items():
p.hincrby(metric.value, identity, increment)
p.execute()

def get_metrics(self, metric: KartonMetrics) -> Dict[str, int]:
Expand Down
150 changes: 77 additions & 73 deletions karton/system/system.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import argparse
import json
import time
from collections import Counter
from typing import List, Optional

from karton.core.__version__ import __version__
Expand Down Expand Up @@ -53,15 +54,15 @@ def gc_collect_resources(self) -> None:
resources_to_remove = set(self.backend.list_objects(karton_bucket))
# Note: it is important to get list of resources before getting list of tasks!
# Task is created before resource upload to lock the reference to the resource.
tasks = self.backend.get_all_tasks()
for task in tasks:
for resource in task.iterate_resources():
# If resource is referenced by task: remove it from set
if (
resource.bucket == karton_bucket
and resource.uid in resources_to_remove
):
resources_to_remove.remove(resource.uid)
for task_slice in self.backend.get_all_tasks():
for task in task_slice:
for resource in task.iterate_resources():
# If resource is referenced by task: remove it from set
if (
resource.bucket == karton_bucket
and resource.uid in resources_to_remove
):
resources_to_remove.remove(resource.uid)
# Remove unreferenced resources
if resources_to_remove:
self.backend.remove_objects(karton_bucket, resources_to_remove)
Expand All @@ -88,68 +89,69 @@ def gc_collect_tasks(self) -> None:
# Collects finished tasks
root_tasks = set()
running_root_tasks = set()
tasks = self.backend.get_all_tasks()

enqueued_task_uids = self.backend.get_task_ids_from_queue(KARTON_TASKS_QUEUE)

current_time = time.time()
to_delete = []

for task in tasks:
root_tasks.add(task.root_uid)
if (
task.status == TaskState.DECLARED
and task.uid not in enqueued_task_uids
and task.last_update is not None
and current_time > task.last_update + self.task_dispatched_timeout
):
to_delete.append(task)
self.log.warning(
"Task %s is in Dispatched state more than %d seconds. "
"Killed. (origin: %s)",
task.uid,
self.task_dispatched_timeout,
task.headers.get("origin", "<unknown>"),
)
elif (
task.status == TaskState.STARTED
and task.last_update is not None
and current_time > task.last_update + self.task_started_timeout
):
to_delete.append(task)
self.log.warning(
"Task %s is in Started state more than %d seconds. "
"Killed. (receiver: %s)",
task.uid,
self.task_started_timeout,
task.headers.get("receiver", "<unknown>"),
for tasks_slice in self.backend.get_all_tasks():
to_delete = []
for task in tasks_slice:
root_tasks.add(task.root_uid)
if (
task.status == TaskState.DECLARED
and task.uid not in enqueued_task_uids
and task.last_update is not None
and current_time > task.last_update + self.task_dispatched_timeout
):
to_delete.append(task)
self.log.warning(
"Task %s is in Dispatched state more than %d seconds. "
"Killed. (origin: %s)",
task.uid,
self.task_dispatched_timeout,
task.headers.get("origin", "<unknown>"),
)
elif (
task.status == TaskState.STARTED
and task.last_update is not None
and current_time > task.last_update + self.task_started_timeout
):
to_delete.append(task)
self.log.warning(
"Task %s is in Started state more than %d seconds. "
"Killed. (receiver: %s)",
task.uid,
self.task_started_timeout,
task.headers.get("receiver", "<unknown>"),
)
elif task.status == TaskState.FINISHED:
to_delete.append(task)
self.log.debug("GC: Finished task %s", task.uid)
elif (
task.status == TaskState.CRASHED
and task.last_update is not None
and current_time > task.last_update + self.task_crashed_timeout
):
to_delete.append(task)
self.log.debug(
"GC: Task %s is in Crashed state more than %d seconds. "
"Killed. (receiver: %s)",
task.uid,
self.task_crashed_timeout,
task.headers.get("receiver", "<unknown>"),
)
else:
running_root_tasks.add(task.root_uid)

if to_delete:
to_increment = Counter(
[task.headers.get("receiver", "unknown") for task in to_delete]
)
elif task.status == TaskState.FINISHED:
to_delete.append(task)
self.log.debug("GC: Finished task %s", task.uid)
elif (
task.status == TaskState.CRASHED
and task.last_update is not None
and current_time > task.last_update + self.task_crashed_timeout
):
to_delete.append(task)
self.log.debug(
"GC: Task %s is in Crashed state more than %d seconds. "
"Killed. (receiver: %s)",
task.uid,
self.task_crashed_timeout,
task.headers.get("receiver", "<unknown>"),
self.backend.delete_tasks(to_delete)
self.backend.increment_metrics_list(
KartonMetrics.TASK_GARBAGE_COLLECTED, to_increment
)
else:
running_root_tasks.add(task.root_uid)

if to_delete:
to_increment = [
task.headers.get("receiver", "unknown") for task in to_delete
]
self.backend.delete_tasks(to_delete)
self.backend.increment_metrics_list(
KartonMetrics.TASK_GARBAGE_COLLECTED, to_increment
)

for finished_root_task in root_tasks.difference(running_root_tasks):
# TODO: Notification needed
Expand Down Expand Up @@ -250,14 +252,16 @@ def loop(self) -> None:

with self.graceful_killer():
while not self.shutdown:
if self.enable_router:
# This will wait for up to 5s, so this is not a busy loop
self.process_routing()
if self.enable_gc:
# This will only do anything once every self.gc_interval seconds
self.gc_collect()
if not self.enable_router:
time.sleep(1) # Avoid a busy loop
try:
if self.enable_router:
# This will wait for up to 5s, so this is not a busy loop
self.process_routing()
finally:
if self.enable_gc:
# This will only do anything once every self.gc_interval seconds
self.gc_collect()
if not self.enable_router:
time.sleep(1) # Avoid a busy loop

@classmethod
def args_parser(cls) -> argparse.ArgumentParser:
Expand Down