1 | """Module responsible for handling schedulers.""" |
||
2 | 1 | from uuid import uuid4 |
|
3 | |||
4 | 1 | from apscheduler.jobstores.base import JobLookupError |
|
5 | 1 | from apscheduler.schedulers.background import BackgroundScheduler |
|
6 | 1 | from apscheduler.triggers.cron import CronTrigger |
|
7 | from pytz import utc |
||
8 | |||
9 | 1 | from kytos.core import log |
|
10 | |||
11 | |||
12 | 1 | class CircuitSchedule: |
|
13 | """Schedule events.""" |
||
14 | 1 | ||
15 | 1 | def __init__(self, **kwargs): |
|
16 | 1 | """Create a CircuitSchedule object.""" |
|
17 | 1 | self._id = kwargs.get("id", uuid4().hex) |
|
18 | 1 | self.date = kwargs.get("date", None) |
|
19 | # The minimum number of seconds to wait between retries |
||
20 | 1 | self.interval = kwargs.get("interval", None) |
|
21 | # Frequency uses Cron format. Ex: "* * * * * *" |
||
22 | self.frequency = kwargs.get("frequency", None) |
||
23 | 1 | self.action = kwargs.get("action", "create") |
|
24 | |||
25 | 1 | @property |
|
26 | def id(self): # pylint: disable=invalid-name |
||
27 | 1 | """Return this EVC's ID.""" |
|
28 | return self._id |
||
29 | 1 | ||
30 | @id.setter |
||
31 | 1 | def id(self, value): # pylint: disable=invalid-name |
|
32 | 1 | """Set this EVC's ID.""" |
|
33 | 1 | self._id = value |
|
34 | 1 | ||
35 | def as_dict(self): |
||
36 | 1 | """Return a dictionary representing an circuit schedule object.""" |
|
37 | circuit_scheduler_dict = {"id": self.id, "action": self.action} |
||
38 | 1 | ||
39 | if self.date: |
||
40 | circuit_scheduler_dict["date"] = self.date |
||
41 | 1 | if self.frequency: |
|
42 | circuit_scheduler_dict["frequency"] = self.frequency |
||
43 | if self.interval: |
||
44 | 1 | circuit_scheduler_dict["interval"] = self.interval |
|
45 | |||
46 | return circuit_scheduler_dict |
||
47 | 1 | ||
48 | @classmethod |
||
49 | 1 | def from_dict(cls, data): |
|
50 | 1 | """Return a CircuitSchedule object from dict.""" |
|
51 | return cls(**data) |
||
52 | 1 | ||
53 | |||
54 | 1 | class Scheduler: |
|
55 | """Class to schedule the circuits rules. |
||
56 | 1 | ||
57 | It is responsible to create/remove schedule jobs based on |
||
58 | 1 | Circuit Schedules. |
|
59 | 1 | """ |
|
60 | 1 | ||
61 | def __init__(self): |
||
62 | 1 | """Create a new schedule structure.""" |
|
63 | 1 | self.scheduler = BackgroundScheduler(timezone=utc) |
|
64 | 1 | self.scheduler.start() |
|
65 | 1 | ||
66 | def shutdown(self): |
||
67 | 1 | """Shutdown the scheduler.""" |
|
68 | 1 | self.scheduler.shutdown(wait=False) |
|
69 | 1 | ||
70 | def add(self, circuit): |
||
71 | 1 | """ |
|
72 | Add all circuit_scheduler from specific circuit. |
||
73 | |||
74 | 1 | Args: |
|
75 | 1 | circuit (napps.kytos.mef_eline.models.EVCBase): EVC circuit |
|
76 | 1 | ||
77 | """ |
||
78 | 1 | for circuit_scheduler in circuit.circuit_scheduler: |
|
79 | 1 | self.add_circuit_job(circuit, circuit_scheduler) |
|
80 | |||
81 | 1 | def remove(self, circuit): |
|
82 | """Remove all scheduler from a circuit.""" |
||
83 | 1 | for job in circuit.circuit_scheduler: |
|
84 | self.cancel_job(job.id) |
||
85 | |||
86 | def add_circuit_job(self, circuit, circuit_scheduler): |
||
87 | """ |
||
88 | Prepare the Circuit data to be added to the Scheduler. |
||
89 | |||
90 | :param circuit(napps.kytos.mef_eline.models.EVCBase): EVC circuit |
||
91 | :param circuit_scheduler (CircuitSchedule): Circuit schedule data |
||
92 | :return: |
||
93 | """ |
||
94 | if circuit_scheduler.action == "create": |
||
95 | job_call = circuit.deploy |
||
96 | elif circuit_scheduler.action == "remove": |
||
97 | job_call = circuit.remove |
||
98 | else: |
||
99 | raise ValueError("Scheduler action must be 'create' or 'remove'") |
||
100 | |||
101 | data = {"id": circuit_scheduler.id} |
||
102 | if circuit_scheduler.date: |
||
103 | data.update({"run_date": circuit_scheduler.date}) |
||
104 | else: |
||
105 | data.update( |
||
106 | { |
||
107 | "start_date": circuit.start_date, |
||
108 | "end_date": circuit.end_date, |
||
109 | } |
||
110 | ) |
||
111 | |||
112 | if circuit_scheduler.interval: |
||
113 | data.update(circuit_scheduler.interval) |
||
114 | |||
115 | self.add_job(circuit_scheduler, job_call, data) |
||
116 | |||
117 | def add_job(self, circuit_scheduler, job_call, data): |
||
118 | """ |
||
119 | Add a specific cron job to the scheduler. |
||
120 | |||
121 | Args: |
||
122 | circuit_scheduler: CircuitSchedule object |
||
123 | job_call: function to be called by the job |
||
124 | data: Dict to pass to the job_call as parameter |
||
125 | if job_call is a date, the template is like: |
||
126 | {'id': <ID>, 'run_date': date } or |
||
127 | {'id': <ID>, 'start_date': date, 'end_date': date } |
||
128 | if job_call is an interval, the template is like: |
||
129 | { 'id': <ID>, |
||
130 | 'hours': 2, |
||
131 | 'minutes': 3 |
||
132 | } |
||
133 | if job_call is frequency, the template is the cron format. |
||
134 | |||
135 | """ |
||
136 | if circuit_scheduler.date: |
||
137 | self.scheduler.add_job(job_call, "date", **data) |
||
138 | |||
139 | elif circuit_scheduler.interval: |
||
140 | self.scheduler.add_job(job_call, "interval", **data) |
||
141 | |||
142 | elif circuit_scheduler.frequency: |
||
143 | cron = CronTrigger.from_crontab( |
||
144 | circuit_scheduler.frequency, timezone=utc |
||
145 | ) |
||
146 | self.scheduler.add_job(job_call, cron, **data) |
||
147 | |||
148 | def cancel_job(self, circuit_scheduler_id): |
||
149 | """Cancel a specific job from scheduler.""" |
||
150 | try: |
||
151 | self.scheduler.remove_job(circuit_scheduler_id) |
||
152 | except JobLookupError as job_error: |
||
153 | # Job was not found... Maybe someone already remove it. |
||
154 | log.error(f"Scheduler error cancelling job. {0}".format(job_error)) |
||
155 |