|
| 1 | +""" |
| 2 | +Manager for all collectors |
| 3 | +Can start, stop, and get info on running collectors |
| 4 | +And manages the retrieval of collector info |
| 5 | +""" |
| 6 | + |
| 7 | +import threading |
| 8 | +import uuid |
| 9 | +from typing import Dict, List, Optional |
| 10 | + |
| 11 | +from collector_manager.ExampleCollector import ExampleCollector |
| 12 | +from collector_manager.enums import Status |
| 13 | + |
| 14 | + |
| 15 | +# Collector Manager Class |
| 16 | +class CollectorManager: |
| 17 | + def __init__(self): |
| 18 | + self.collectors: Dict[str, ExampleCollector] = {} |
| 19 | + |
| 20 | + def list_collectors(self) -> List[str]: |
| 21 | + return ["example_collector"] |
| 22 | + |
| 23 | + def start_collector( |
| 24 | + self, |
| 25 | + name: str, |
| 26 | + config: Optional[dict] = None |
| 27 | + ) -> str: |
| 28 | + cid = str(uuid.uuid4()) |
| 29 | + # The below would need to become more sophisticated |
| 30 | + # As we may load different collectors depending on the name |
| 31 | + collector = ExampleCollector(name, config) |
| 32 | + self.collectors[cid] = collector |
| 33 | + thread = threading.Thread(target=collector.run, daemon=True) |
| 34 | + thread.start() |
| 35 | + return cid |
| 36 | + |
| 37 | + def get_status(self, cid: Optional[str] = None) -> str | List[str]: |
| 38 | + if cid: |
| 39 | + collector = self.collectors.get(cid) |
| 40 | + if not collector: |
| 41 | + return f"Collector with CID {cid} not found." |
| 42 | + return f"{cid} ({collector.name}) - {collector.status}" |
| 43 | + else: |
| 44 | + return [ |
| 45 | + f"{cid} ({collector.name}) - {collector.status}" |
| 46 | + for cid, collector in self.collectors.items() |
| 47 | + ] |
| 48 | + |
| 49 | + def get_info(self, cid: str) -> str: |
| 50 | + collector = self.collectors.get(cid) |
| 51 | + if not collector: |
| 52 | + return f"Collector with CID {cid} not found." |
| 53 | + logs = "\n".join(collector.logs[-3:]) # Show the last 3 logs |
| 54 | + return f"{cid} ({collector.name}) - {collector.status}\nLogs:\n{logs}" |
| 55 | + |
| 56 | + def close_collector(self, cid: str) -> str: |
| 57 | + collector = self.collectors.get(cid) |
| 58 | + if not collector: |
| 59 | + return f"Collector with CID {cid} not found." |
| 60 | + match collector.status: |
| 61 | + case Status.RUNNING: |
| 62 | + collector.stop() |
| 63 | + return f"Collector {cid} stopped." |
| 64 | + case Status.COMPLETED: |
| 65 | + data = collector.data |
| 66 | + del self.collectors[cid] |
| 67 | + return f"Collector {cid} harvested. Data: {data}" |
| 68 | + case _: |
| 69 | + return f"Cannot close collector {cid} with status {collector.status}." |
| 70 | + |
0 commit comments