Test Failed
Pull Request — master (#64)
by
unknown
02:52
created

build.main.Main.execute()   A

Complexity

Conditions 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nop 1
dl 0
loc 2
rs 10
c 0
b 0
f 0
ccs 0
cts 0
cp 0
crap 2
1
"""Main module of kytos/maintenance Kytos Network Application.
2
3
This NApp creates maintenance windows, allowing the maintenance of network
4
devices (switch, link, and interface) without receiving alerts.
5
"""
6 1
from datetime import datetime, timedelta
7
8 1
import pytz
9 1
from flask import jsonify, request, current_app
10 1
from napps.kytos.maintenance.models import MaintenanceID
11 1
from napps.kytos.maintenance.models import MaintenanceWindow as MW
12 1
from napps.kytos.maintenance.models import Scheduler, Status, OverlapError
13
from pydantic import ValidationError
14 1
from werkzeug.exceptions import BadRequest, NotFound, UnsupportedMediaType
15
16
from kytos.core import KytosNApp, rest
17 1
18
19
class Main(KytosNApp):
20
    """Main class of kytos/maintenance NApp.
21
22
    This class is the entry point for this napp.
23 1
    """
24
25
    def setup(self):
26
        """Replace the '__init__' method for the KytosNApp subclass.
27
28
        The setup method is automatically called by the controller when your
29
        application is loaded.
30
31 1
        So, if you have any setup routine, insert it here.
32 1
        """
33
        self.scheduler = Scheduler.new_scheduler(self.controller)
34 1
        self.scheduler.start()
35
36
    def execute(self):
37
        """Run after the setup method execution.
38
39
        You can also use this method in loop mode if you add to the above setup
40
        method a line like the following example:
41
42
            self.execute_as_loop(30)  # 30-second interval.
43 1
        """
44
45
    def shutdown(self):
46
        """Run when your napp is unloaded.
47
48
        If you have some cleanup procedure, insert it here.
49 1
        """
50 1
        self.scheduler.shutdown()
51 1
52
    @rest('/v1', methods=['GET'])
53 1
    def get_all_mw(self):
54 1
        """Return all maintenance windows."""
55
        maintenances = self.scheduler.list_maintenances()
56
        return current_app.response_class(
57 1
            f"{maintenances.json()}\n",
58 1
            mimetype=current_app.config["JSONIFY_MIMETYPE"],
59 1
        ), 200
60 1
61
    @rest('/v1/<mw_id>', methods=['GET'])
62 1
    def get_mw(self, mw_id: MaintenanceID):
63 1
        """Return one maintenance window."""
64
        window = self.scheduler.get_maintenance(mw_id)
65 1
        if window:
66 1
           return current_app.response_class(
67 1
                f"{window.json()}\n",
68
                mimetype=current_app.config["JSONIFY_MIMETYPE"],
69 1
            ), 200
70 1
        raise NotFound(f'Maintenance with id {mw_id} not found')
71
72
    @rest('/v1', methods=['POST'])
73 1
    def create_mw(self):
74 1
        """Create a new maintenance window."""
75 1
        data: dict = request.get_json()
76 1
        if not data:
77 1
            raise UnsupportedMediaType('The request does not have a json')
78 1
        try:
79 1
            maintenance = MW.parse_obj(data)
80 1
            force = data.get('force', False)
81 1
        except ValidationError as err:
82
            raise BadRequest(f'{err.errors()[0]["msg"]}') from err
83 1
        try:
84 1
            self.scheduler.add(maintenance, force = force)
85
        except OverlapError as err:
86 1
            raise BadRequest(f'{err}') from err
87 1
        return jsonify({'mw_id': maintenance.id}), 201
88 1
89 1
    @rest('/v1/<mw_id>', methods=['PATCH'])
90 1
    def update_mw(self, mw_id: MaintenanceID):
91 1
        """Update a maintenance window."""
92 1
        data = request.get_json()
93 1
        if not data:
94
            raise UnsupportedMediaType('The request does not have a json')
95 1
        old_maintenance = self.scheduler.get_maintenance(mw_id)
96 1
        if old_maintenance is None:
97 1
            raise NotFound(f'Maintenance with id {mw_id} not found')
98 1
        if old_maintenance.status == Status.RUNNING:
99 1
            raise BadRequest('Updating a running maintenance is not allowed')
100 1
        try:
101 1
            new_maintenance = MW.parse_obj({**old_maintenance.dict(), **data})
102
        except ValidationError as err:
103 1
            raise BadRequest(f'{err.errors()[0]["msg"]}') from err
104 1
        if new_maintenance.id != old_maintenance.id:
105
            raise BadRequest('Updated id must match old id')
106 1
        self.scheduler.update(new_maintenance)
107 1
        return jsonify({'response': f'Maintenance {mw_id} updated'}), 200
108 1
109 1
    @rest('/v1/<mw_id>', methods=['DELETE'])
110 1
    def remove_mw(self, mw_id: MaintenanceID):
111 1
        """Delete a maintenance window."""
112 1
        maintenance = self.scheduler.get_maintenance(mw_id)
113 1
        if maintenance is None:
114 1
            raise NotFound(f'Maintenance with id {mw_id} not found')
115
        if maintenance.status == Status.RUNNING:
116
            raise BadRequest('Deleting a running maintenance is not allowed')
117 1
        self.scheduler.remove(mw_id)
118 1
        return jsonify({'response': f'Maintenance with id {mw_id} '
119
                                    f'successfully removed'}), 200
120 1
121 1
    @rest('/v1/<mw_id>/end', methods=['PATCH'])
122 1
    def end_mw(self, mw_id: MaintenanceID):
123 1
        """Finish a maintenance window right now."""
124 1
        maintenance = self.scheduler.get_maintenance(mw_id)
125 1
        if maintenance is None:
126 1
            raise NotFound(f'Maintenance with id {mw_id} not found')
127
        if maintenance.status == Status.PENDING:
128 1
            raise BadRequest(
129 1
                f'Maintenance window {mw_id} has not yet started'
130
            )
131 1
        if maintenance.status == Status.FINISHED:
132 1
            raise BadRequest(
133 1
                f'Maintenance window {mw_id} has already finished'
134
            )
135
        self.scheduler.end_maintenance_early(mw_id)
136 1
        return jsonify({'response': f'Maintenance window {mw_id} '
137 1
                                    f'finished'}), 200
138
139 1
    @rest('/v1/<mw_id>/extend', methods=['PATCH'])
140 1
    def extend_mw(self, mw_id):
141 1
        """Extend a running maintenance window."""
142 1
        data = request.get_json()
143 1
        if not data:
144 1
            raise UnsupportedMediaType('The request does not have a json')
145 1
        maintenance = self.scheduler.get_maintenance(mw_id)
146 1
        if maintenance is None:
147 1
            raise NotFound(f'Maintenance with id {mw_id} not found')
148 1
        if 'minutes' not in data:
149 1
            raise BadRequest('Minutes of extension must be sent')
150 1
        if maintenance.status == Status.PENDING:
151
            raise BadRequest(
152 1
                f'Maintenance window {mw_id} has not yet started'
153 1
            )
154
        if maintenance.status == Status.FINISHED:
155 1
            raise BadRequest(
156 1
                f'Maintenance window {mw_id} has already finished'
157
            )
158 1
        try:
159 1
            maintenance_end = maintenance.end + \
160 1
                timedelta(minutes=data['minutes'])
161 1
            new_maintenance = maintenance.copy(
162 1
                update = {'end': maintenance_end}
163
            )
164
        except TypeError as exc:
165
            raise BadRequest('Minutes of extension must be integer') from exc
166
167
        self.scheduler.update(new_maintenance)
168
        return jsonify({'response': f'Maintenance {mw_id} extended'}), 200
169