Exemplo n.º 1
0
    def test_new_circuit_with_interval(self, validate_mock,
                                       scheduler_add_job_mock):
        """Test if add new circuit with interval."""
        scheduler_add_job_mock.return_value = True
        validate_mock.return_value = True
        interval = {
            'hours': 2,
            'minutes': 3
        }
        circuit_scheduler = CircuitSchedule(action="create", interval=interval)
        options = {"controller": get_controller_mock(),
                   "name": 'my evc1',
                   "uni_a": 'uni_a',
                   "uni_z": 'uni_z',
                   "start_date": "2019-08-09T19:25:06",
                   "circuit_scheduler": [circuit_scheduler]
                   }
        evc = EVC(**options)
        self.scheduler.add(evc)

        expected_parameters = {
            "id": circuit_scheduler.id,
            "hours": 2,
            "minutes": 3,
            "end_date": None,
            "start_date": datetime.datetime(
                2019, 8, 9, 19, 25, 6, 0, tzinfo=datetime.timezone.utc)
        }
        scheduler_add_job_mock.assert_called_once_with(evc.deploy, 'interval',
                                                       **expected_parameters)
Exemplo n.º 2
0
    def test_new_circuit_with_frequency(self, validate_mock,
                                        scheduler_add_job_mock,
                                        trigger_mock):
        """Test if add new circuit with frequency."""
        scheduler_add_job_mock.return_value = True
        validate_mock.return_value = True

        frequency = "* * * * *"
        circuit_scheduler = CircuitSchedule(action="create",
                                            frequency=frequency)

        trigger = CronTrigger.from_crontab(circuit_scheduler.frequency,
                                           timezone=utc)
        trigger_mock.return_value = trigger

        options = {"controller": get_controller_mock(),
                   "name": 'my evc1',
                   "uni_a": 'uni_a',
                   "uni_z": 'uni_z',
                   "start_date": "2019-08-09T19:25:06",
                   "circuit_scheduler": [circuit_scheduler]
                   }
        evc = EVC(**options)
        self.scheduler.add(evc)
        expected_parameters = {
            "id": circuit_scheduler.id,
            "end_date": None,
            "start_date": datetime.datetime(
                2019, 8, 9, 19, 25, 6, 0, tzinfo=datetime.timezone.utc)
        }
        scheduler_add_job_mock.assert_called_once_with(evc.deploy, trigger,
                                                       **expected_parameters)
Exemplo n.º 3
0
    def evc_from_dict(self, evc_dict):
        """Convert some dict values to instance of EVC classes.

        This method will convert: [UNI, Link]
        """
        data = evc_dict.copy()  # Do not modify the original dict

        for attribute, value in data.items():

            if 'uni' in attribute:
                try:
                    data[attribute] = self.uni_from_dict(value)
                except ValueError as exc:
                    raise ValueError(f'Error creating UNI: {exc}')

            if attribute == 'circuit_scheduler':
                data[attribute] = []
                for schedule in value:
                    data[attribute].append(CircuitSchedule.from_dict(schedule))

            if 'link' in attribute:
                if value:
                    data[attribute] = self.link_from_dict(value)

            if 'path' in attribute and attribute != 'dynamic_backup_path':
                if value:
                    data[attribute] = [
                        self.link_from_dict(link) for link in value
                    ]

        return EVC(self.controller, **data)
Exemplo n.º 4
0
 def test_new_circuit_with_run_time(
     self, validate_mock, scheduler_add_job_mock
 ):
     """Test if add new circuit with run_time."""
     scheduler_add_job_mock.return_value = True
     validate_mock.return_value = True
     time_fmt = "%Y-%m-%dT%H:%M:%S"
     date = datetime.datetime.now().strftime(time_fmt)
     circuit_scheduler = CircuitSchedule(action="remove", date=date)
     options = {
         "controller": get_controller_mock(),
         "name": "my evc1",
         "uni_a": "uni_a",
         "uni_z": "uni_z",
         "circuit_scheduler": [circuit_scheduler],
     }
     evc = EVC(**options)
     self.scheduler.add(evc)
     expected_parameters = {
         "id": circuit_scheduler.id,
         "run_date": circuit_scheduler.date,
     }
     scheduler_add_job_mock.assert_called_once_with(
         evc.remove, "date", **expected_parameters
     )
Exemplo n.º 5
0
 def test_as_dict(self):
     """Test method as_dict from circuit_schedule."""
     options = {
         "id": 234243242,
         "action": "create",
         "frequency": "1 * * * *"
     }
     circuit_schedule_dict = CircuitSchedule(**options).as_dict()
     self.assertEqual(options, circuit_schedule_dict)
Exemplo n.º 6
0
 def test_with_frequency(self):
     """Test create circuit schedule with frequency."""
     options = {
         "action": "create",
         "frequency": "1 * * * *"
     }
     circuit_schedule = CircuitSchedule(**options)
     self.assertEqual("create", circuit_schedule.action)
     self.assertEqual(options["frequency"], circuit_schedule.frequency)
Exemplo n.º 7
0
 def test_with_date(self):
     """Test create circuit schedule with date."""
     time_fmt = "%Y-%m-%dT%H:%M:%S"
     options = {
         "action": "create",
         "date": datetime.datetime.now().strftime(time_fmt)
     }
     circuit_schedule = CircuitSchedule(**options)
     self.assertEqual("create", circuit_schedule.action)
     self.assertEqual(options["date"], circuit_schedule.date)
Exemplo n.º 8
0
 def test_with_interval(self):
     """Test create circuit schedule with interval."""
     options = {
         "action": "create",
         "interval": {
             "hours": 2
         }
     }
     circuit_schedule = CircuitSchedule(**options)
     self.assertEqual("create", circuit_schedule.action)
     self.assertEqual(options["interval"], circuit_schedule.interval)
Exemplo n.º 9
0
 def test_from_dict(self):
     """Test create circuit schedule from dict."""
     circuit_schedule_dict = {
         "id": 52342432,
         "action": "create",
         "frequency": "1 * * * *"
     }
     circuit_schedule = CircuitSchedule.from_dict(circuit_schedule_dict)
     self.assertEqual(circuit_schedule.id, circuit_schedule_dict["id"])
     self.assertEqual(circuit_schedule.action,
                      circuit_schedule_dict["action"])
     self.assertEqual(circuit_schedule.frequency,
                      circuit_schedule_dict["frequency"])
Exemplo n.º 10
0
    def update_schedule(self, schedule_id):
        """Update a schedule.

        Change all attributes from the given schedule from a EVC circuit.
        The schedule ID is preserved as default.
        Payload example:
            {
              "date": "2019-08-07T14:52:10.967Z",
              "interval": "string",
              "frequency": "1 * * *",
              "action": "create"
            }
        """
        log.debug('update_schedule /v2/evc/schedule/%s', schedule_id)

        # Try to find a circuit schedule
        evc, found_schedule = self._find_evc_by_schedule_id(schedule_id)

        # Can not modify circuits deleted and archived
        if not found_schedule:
            result = f'schedule_id {schedule_id} not found'
            log.debug('update_schedule result %s %s', result, 404)
            raise NotFound(result)
        if evc.archived:
            result = f'Circuit {evc.id} is archived. Update is forbidden.'
            log.debug('update_schedule result %s %s', result, 403)
            raise Forbidden(result)

        data = self.json_from_request('update_schedule')

        new_schedule = CircuitSchedule.from_dict(data)
        new_schedule.id = found_schedule.id
        # Remove the old schedule
        evc.circuit_scheduler.remove(found_schedule)
        # Append the modified schedule
        evc.circuit_scheduler.append(new_schedule)

        # Cancel all schedule jobs
        self.sched.cancel_job(found_schedule.id)
        # Add the new circuit schedule
        self.sched.add_circuit_job(evc, new_schedule)
        # Save EVC to the storehouse
        evc.sync()

        result = new_schedule.as_dict()
        status = 200

        log.debug('update_schedule result %s %s', result, status)
        return jsonify(result), status
Exemplo n.º 11
0
    def _evc_dict_with_instances(self, evc_dict):
        """Convert some dict values to instance of EVC classes.

        This method will convert: [UNI, Link]
        """
        data = evc_dict.copy()  # Do not modify the original dict

        for attribute, value in data.items():
            # Get multiple attributes.
            # Ex: uni_a, uni_z
            if "uni" in attribute:
                try:
                    data[attribute] = self._uni_from_dict(value)
                except ValueError:
                    result = "Error creating UNI: Invalid value"
                    raise BadRequest(result) from BadRequest

            if attribute == "circuit_scheduler":
                data[attribute] = []
                for schedule in value:
                    data[attribute].append(CircuitSchedule.from_dict(schedule))

            # Get multiple attributes.
            # Ex: primary_links,
            #     backup_links,
            #     current_links_cache,
            #     primary_links_cache,
            #     backup_links_cache
            if "links" in attribute:
                data[attribute] = [
                    self._link_from_dict(link) for link in value
                ]

            # Ex: current_path,
            #     primary_path,
            #     backup_path
            if "path" in attribute and attribute != "dynamic_backup_path":
                data[attribute] = Path(
                    [self._link_from_dict(link) for link in value]
                )

        return data
Exemplo n.º 12
0
    def _evc_dict_with_instances(self, evc_dict):
        """Convert some dict values to instance of EVC classes.

        This method will convert: [UNI, Link]
        """
        data = evc_dict.copy()  # Do not modify the original dict

        for attribute, value in data.items():
            # Get multiple attributes.
            # Ex: uni_a, uni_z
            if 'uni' in attribute:
                try:
                    data[attribute] = self._uni_from_dict(value)
                except ValueError as exc:
                    raise ValueError(f'Error creating UNI: {exc}')

            if attribute == 'circuit_scheduler':
                data[attribute] = []
                for schedule in value:
                    data[attribute].append(CircuitSchedule.from_dict(schedule))

            # Get multiple attributes.
            # Ex: primary_links,
            #     backup_links,
            #     current_links_cache,
            #     primary_links_cache,
            #     backup_links_cache
            if 'links' in attribute:
                data[attribute] = [
                    self._link_from_dict(link) for link in value
                ]

            # Get multiple attributes.
            # Ex: current_path,
            #     primary_path,
            #     backup_path
            if 'path' in attribute and attribute != 'dynamic_backup_path':
                data[attribute] = Path(
                    [self._link_from_dict(link) for link in value])

        return data
Exemplo n.º 13
0
    def create_schedule(self):
        """
        Create a new schedule for a given circuit.

        This service do no check if there are conflicts with another schedule.
        Payload example:
            {
              "circuit_id":"aa:bb:cc",
              "schedule": {
                "date": "2019-08-07T14:52:10.967Z",
                "interval": "string",
                "frequency": "1 * * * *",
                "action": "create"
              }
            }
        """
        log.debug('create_schedule /v2/evc/schedule/')

        json_data = self.json_from_request('create_schedule')
        try:
            circuit_id = json_data['circuit_id']
        except TypeError:
            result = 'The payload should have a dictionary.'
            log.debug('create_schedule result %s %s', result, 400)
            raise BadRequest(result)
        except KeyError:
            result = 'Missing circuit_id.'
            log.debug('create_schedule result %s %s', result, 400)
            raise BadRequest(result)

        try:
            schedule_data = json_data['schedule']
        except KeyError:
            result = 'Missing schedule data.'
            log.debug('create_schedule result %s %s', result, 400)
            raise BadRequest(result)

        # Get EVC from circuits buffer
        circuits = self._get_circuits_buffer()

        # get the circuit
        evc = circuits.get(circuit_id)

        # get the circuit
        if not evc:
            result = f'circuit_id {circuit_id} not found'
            log.debug('create_schedule result %s %s', result, 404)
            raise NotFound(result)
        # Can not modify circuits deleted and archived
        if evc.archived:
            result = f'Circuit {circuit_id} is archived. Update is forbidden.'
            log.debug('create_schedule result %s %s', result, 403)
            raise Forbidden(result)

        # new schedule from dict
        new_schedule = CircuitSchedule.from_dict(schedule_data)

        # If there is no schedule, create the list
        if not evc.circuit_scheduler:
            evc.circuit_scheduler = []

        # Add the new schedule
        evc.circuit_scheduler.append(new_schedule)

        # Add schedule job
        self.sched.add_circuit_job(evc, new_schedule)

        # save circuit to storehouse
        evc.sync()

        result = new_schedule.as_dict()
        status = 201

        log.debug('create_schedule result %s %s', result, status)
        return jsonify(result), status
Exemplo n.º 14
0
 def test_id(self):
     """Test method id with different values."""
     self.assertNotEqual(CircuitSchedule().id, CircuitSchedule().id)
Exemplo n.º 15
0
    def test_as_dict(self):
        """Test the method as_dict."""
        attributes = {
            "controller":
            get_controller_mock(),
            "id":
            "custom_id",
            "name":
            "custom_name",
            "uni_a":
            get_uni_mocked(is_valid=True),
            "uni_z":
            get_uni_mocked(is_valid=True),
            "start_date":
            "2018-08-21T18:44:54",
            "end_date":
            "2018-08-21T18:44:55",
            "primary_links": [],
            "request_time":
            "2018-08-21T19:10:41",
            "creation_time":
            "2018-08-21T18:44:54",
            "owner":
            "my_name",
            "circuit_scheduler": [
                CircuitSchedule.from_dict({
                    "id": 234243247,
                    "action": "create",
                    "frequency": "1 * * * *",
                }),
                CircuitSchedule.from_dict({
                    "id": 234243239,
                    "action": "create",
                    "interval": {
                        "hours": 2
                    },
                }),
            ],
            "enabled":
            True,
            "priority":
            2,
        }
        evc = EVC(**attributes)

        expected_dict = {
            "id":
            "custom_id",
            "name":
            "custom_name",
            "uni_a":
            attributes["uni_a"].as_dict(),
            "uni_z":
            attributes["uni_z"].as_dict(),
            "start_date":
            "2018-08-21T18:44:54",
            "end_date":
            "2018-08-21T18:44:55",
            "bandwidth":
            0,
            "primary_links": [],
            "backup_links": [],
            "current_path": [],
            "primary_path": [],
            "backup_path": [],
            "dynamic_backup_path":
            False,
            "request_time":
            "2018-08-21T19:10:41",
            "creation_time":
            "2018-08-21T18:44:54",
            "circuit_scheduler": [
                {
                    "id": 234243247,
                    "action": "create",
                    "frequency": "1 * * * *",
                },
                {
                    "id": 234243239,
                    "action": "create",
                    "interval": {
                        "hours": 2
                    },
                },
            ],
            "active":
            False,
            "enabled":
            True,
            "priority":
            2,
        }
        actual_dict = evc.as_dict()
        for name, value in expected_dict.items():
            actual = actual_dict.get(name)
            self.assertEqual(value, actual)
Exemplo n.º 16
0
    def test_as_dict(self):
        """Test the method as_dict."""
        attributes = {
            "controller": get_controller_mock(),
            "id": "custom_id",
            "name": "custom_name",
            "uni_a": get_uni_mocked(is_valid=True),
            "uni_z": get_uni_mocked(is_valid=True),
            "start_date": '2018-08-21T18:44:54',
            "end_date": '2018-08-21T18:44:55',
            'primary_links': [],
            'request_time': '2018-08-21T19:10:41',
            'creation_time': '2018-08-21T18:44:54',
            'owner': "my_name",
            'circuit_scheduler': [
                CircuitSchedule.from_dict({"id": 234243247, "action": "create",
                                          "frequency": "1 * * * *"}),
                CircuitSchedule.from_dict({"id": 234243239, "action": "create",
                                          "interval": {"hours": 2}})
            ],
            'enabled': True,
            'priority': 2
        }
        evc = EVC(**attributes)

        expected_dict = {
            'id': 'custom_id',
            'name': 'custom_name',
            'uni_a': attributes['uni_a'].as_dict(),
            'uni_z': attributes['uni_z'].as_dict(),
            'start_date': '2018-08-21T18:44:54',
            'end_date': '2018-08-21T18:44:55',
            'bandwidth': 0,
            'primary_links': [],
            'backup_links': [],
            'current_path': [],
            'primary_path': [],
            'backup_path': [],
            'dynamic_backup_path': False,
            'request_time': '2018-08-21T19:10:41',
            'creation_time': '2018-08-21T18:44:54',
            'circuit_scheduler': [
                {
                    "id": 234243247,
                    "action": "create",
                    "frequency": "1 * * * *"
                },
                {
                    "id": 234243239,
                    "action": "create",
                    "interval": {
                        "hours": 2
                    }
                }
            ],
            'active': False,
            'enabled': True,
            'priority': 2
        }
        actual_dict = evc.as_dict()
        for name, value in expected_dict.items():
            actual = actual_dict.get(name)
            self.assertEqual(value, actual)