Esempio n. 1
0
    def upload(self,
               engine,
               timeout=5,
               wait_for_finish=False,
               preserve_connections=True,
               generate_snapshot=True,
               **kw):
        """
        Upload policy to specific device. Using wait for finish
        returns a poller thread for monitoring progress::

            policy = FirewallPolicy('_NSX_Master_Default')
            poller = policy.upload('myfirewall', wait_for_finish=True)
            while not poller.done():
                poller.wait(3)
                print(poller.task.progress)
            print("Task finished: %s" % poller.message())

        :param str engine: name of device to upload policy to
        :param bool preserve_connections: flag to preserve connections (True by default)
        :param bool generate_snapshot: flag to generate snapshot (True by default)
        :raises: TaskRunFailed
        :return: TaskOperationPoller
        """
        return Task.execute(self,
                            "upload",
                            params={"filter": engine},
                            json={
                                "preserve_connections": preserve_connections,
                                "snapshot_creation": generate_snapshot,
                            },
                            timeout=timeout,
                            wait_for_finish=wait_for_finish,
                            **kw)
    def export_elements(self,
                        filename='export_elements.zip',
                        typeof='all',
                        timeout=5,
                        max_tries=36):
        """
        Export elements from SMC.

        Valid types are:
        all (All Elements)|nw (Network Elements)|ips (IPS Elements)|
        sv (Services)|rb (Security Policies)|al (Alerts)|
        vpn (VPN Elements)

        :param type: type of element
        :param filename: Name of file for export
        :raises TaskRunFailed: failure during export with reason
        :rtype: DownloadTask
        """
        valid_types = ['all', 'nw', 'ips', 'sv', 'rb', 'al', 'vpn']
        if typeof not in valid_types:
            typeof = 'all'

        return Task.download(self,
                             'export_elements',
                             filename,
                             timeout=timeout,
                             max_tries=max_tries,
                             params={
                                 'recursive': True,
                                 'type': typeof
                             })
Esempio n. 3
0
    def upload(self, policy=None, wait_for_finish=False, sleep=3):
        """ 
        Upload policy to engine. This is used when a new policy is required
        for an engine, or this is the first time a policy is pushed to an engine.
        If an engine already has a policy and the intent is to re-push, then use
        :py:func:`refresh` instead.
        The policy argument can use a wildcard * to specify in the event a full 
        name is not known::
        
            engine = Engine('myfw')
            task = engine.upload('Amazon*', wait_for_finish=True)
            for message in task:
                print message
        
        :param str policy: name of policy to upload to engine; if None, current policy
        :param boolean wait_for_finish: whether to wait for async responses
        :param int sleep: number of seconds to sleep if wait_for_finish=True
        :raises: :py:class:`smc.api.exceptions.TaskRunFailed`
        :return: generator yielding updates on progress
        """
        element = prepared_request(TaskRunFailed,
                                   href=self._link('upload'),
                                   params={
                                       'filter': policy
                                   }).create()

        return task_handler(Task(**element.json),
                            wait_for_finish=wait_for_finish,
                            sleep=sleep)
Esempio n. 4
0
    def export_elements(self,
                        filename="export_elements.zip",
                        typeof="all",
                        timeout=5,
                        max_tries=36):
        """
        Export elements from SMC.

        Valid types are:
        all (All Elements)|nw (Network Elements)|ips (IPS Elements)|
        sv (Services)|rb (Security Policies)|al (Alerts)|
        vpn (VPN Elements)

        :param type: type of element
        :param filename: Name of file for export
        :raises TaskRunFailed: failure during export with reason
        :rtype: DownloadTask
        """
        valid_types = ["all", "nw", "ips", "sv", "rb", "al", "vpn"]
        if typeof not in valid_types:
            typeof = "all"

        return Task.download(
            self,
            "export_elements",
            filename,
            timeout=timeout,
            max_tries=max_tries,
            params={
                "recursive": True,
                "type": typeof
            },
        )
Esempio n. 5
0
 def generate(self, start_time=0, end_time=0, 
         senders=None, wait_for_finish=False, timeout=5, **kw):  # @ReservedAssignment
     """
     Generate the report and optionally wait for results.
     You can optionally add filters to the report by providing the senders
     argument as a list of type Element::
     
         report = ReportDesign('Firewall Weekly Summary')
         begin = datetime_to_ms(datetime.strptime("2018-02-03T00:00:00", "%Y-%m-%dT%H:%M:%S"))
         end = datetime_to_ms(datetime.strptime("2018-02-04T00:00:00", "%Y-%m-%dT%H:%M:%S"))
         report.generate(start_time=begin, end_time=end, senders=[Engine('vm')])
     
     :param int period_begin: milliseconds time defining start time for report
     :param int period_end: milliseconds time defining end time for report
     :param senders: filter targets to use when generating report
     :type senders: list(Element)
     :param bool wait_for_finish: enable polling for results
     :param int timeout: timeout between polling
     :raises TaskRunFailed: refresh failed, possibly locked policy
     :rtype: TaskOperationPoller
     """
     if start_time and end_time:
         kw.setdefault('params', {}).update(
             {'start_time': start_time,
              'end_time': end_time})
     if senders:
         kw.setdefault('json', {}).update({'senders': element_resolver(senders)})
     return Task.execute(self, 'generate',
         timeout=timeout, wait_for_finish=wait_for_finish, **kw)
Esempio n. 6
0
    def download(self, timeout=5, wait_for_finish=False):
        """
        Download Package or Engine Update

        :param int timeout: timeout between queries
        :raises TaskRunFailed: failure during task status
        :rtype: TaskOperationPoller
        """
        return Task.execute(self, 'download', timeout=timeout,
            wait_for_finish=wait_for_finish)
Esempio n. 7
0
 def generate(self, timeout=5, wait_for_finish=False, **kw):
     """
     Generate the report and optionally wait for results.
     
     :param int timeout: timeout between queries
     :param bool wait_for_finish: enable polling for results
     :raises TaskRunFailed: refresh failed, possibly locked policy
     :rtype: TaskOperationPoller
     """
     return Task.execute(self, 'generate',
         timeout=timeout, wait_for_finish=wait_for_finish, **kw)
Esempio n. 8
0
 def remove_from_master_node(self, wait_for_finish=False, timeout=20, **kw):
     """
     Remove this VSS Context from it's parent VSS Container.
     This is required before calling VSSContext.delete(). It preps
     the engine for removal.
     
     :param bool wait_for_finish: wait for the task to finish
     :param int timeout: how long to wait if delay
     :type: TaskOperationPoller
     """
     return Task.execute(self, 'remove_from_master_node',
         timeout=timeout, wait_for_finish=wait_for_finish, **kw)
Esempio n. 9
0
    def activate(self, resource=None, timeout=3, wait_for_finish=False):
        """
        Activate this package on the SMC

        :param list resource: node href's to activate on. Resource is only
               required for software upgrades
        :param int timeout: timeout between queries
        :raises TaskRunFailed: failure during activation (downloading, etc)
        :rtype: TaskOperationPoller
        """
        return Task.execute(self, 'activate', json={'resource': resource},
            timeout=timeout, wait_for_finish=wait_for_finish)
Esempio n. 10
0
    def import_elements(self, import_file):
        """
        Import elements into SMC. Specify the fully qualified path
        to the import file.

        :param str import_file: system level path to file
        :raises: ActionCommandFailed
        :return: None
        """
        import_follower = Task(
            self.make_request(
                method="create",
                resource="import_elements",
                files={"import_file": open(import_file, "rb")},
            ))
        in_progress = import_follower.data.in_progress
        progress = import_follower.progress
        while in_progress is True:
            time.sleep(1)
            logger.info("[{}] XML Import task => {}%".format(
                "{:%H:%M:%S.%f}".format(datetime.now())[:-3], progress))
            in_progress = import_follower.update_status().data.in_progress
            progress = import_follower.update_status().progress
            succeed = import_follower.update_status().success
            last_message = import_follower.update_status().last_message

        if not succeed:
            logger.info("[{}] XML Import task failed:{}".format(
                "{:%H:%M:%S.%f}".format(datetime.now())[:-3], last_message))
            raise ActionCommandFailed(last_message)

        logger.info("[{}] XML Import task succeed".format(
            "{:%H:%M:%S.%f}".format(datetime.now())[:-3]))
Esempio n. 11
0
 def start(self):
     """
     Start the scheduled task now. Task can then be tracked by
     using common Task methods.
     
     :raises ActionCommandFailed: failed starting task
     :return: return as a generic Task
     :rtype: Task
     """
     return Task(
         self.make_request(ActionCommandFailed,
                           method='create',
                           resource='start'))
Esempio n. 12
0
    def import_elements(self, import_file):
        """
        Import elements into SMC. Specify the fully qualified path
        to the import file.
        
        :param str import_file: system level path to file
        :raises: ActionCommandFailed
        :return: None
        """
        import_follower = Task(
            self.make_request(method='create',
                              resource='import_elements',
                              files={'import_file': open(import_file, 'rb')}))
        in_progress = import_follower.data.in_progress
        progress = import_follower.progress
        while in_progress is True:
            time.sleep(1)
            logger.info("[{}] XML Import task => {}%".format(
                '{:%H:%M:%S.%f}'.format(datetime.now())[:-3], progress))
            in_progress = import_follower.update_status().data.in_progress
            progress = import_follower.update_status().progress

        logger.info("[{}] XML Import task finished".format(
            '{:%H:%M:%S.%f}'.format(datetime.now())[:-3]))
Esempio n. 13
0
    def upload(self, engine, timeout=5, wait_for_finish=False, **kw):
        """
        Upload policy to specific device. Using wait for finish
        returns a poller thread for monitoring progress::

            policy = FirewallPolicy('_NSX_Master_Default')
            poller = policy.upload('myfirewall', wait_for_finish=True)
            while not poller.done():
                poller.wait(3)
                print(poller.task.progress)
            print("Task finished: %s" % poller.message())

        :param str engine: name of device to upload policy to
        :raises: TaskRunFailed
        :return: TaskOperationPoller
        """
        return Task.execute(self, 'upload', params={'filter': engine},
            timeout=timeout, wait_for_finish=wait_for_finish, **kw)
Esempio n. 14
0
    def refresh(self, timeout=3, wait_for_finish=False, **kw):
        """
        Refresh existing policy on specified device. This is an asynchronous
        call that will return a 'follower' link that can be queried to
        determine the status of the task.
        ::

            poller = engine.refresh()
            while not poller.done():
                poller.wait(5)
                print('Percentage complete {}%'.format(poller.task.progress))

        :param int timeout: timeout between queries
        :raises TaskRunFailed: refresh failed, possibly locked policy
        :rtype: TaskOperationPoller
        """
        return Task.execute(self, 'refresh',
            timeout=timeout, wait_for_finish=wait_for_finish, **kw)
Esempio n. 15
0
    def upload(self, engine, timeout=5, wait_for_finish=False, **kw):
        """
        Upload policy to specific device. Using wait for finish
        returns a poller thread for monitoring progress::

            policy = FirewallPolicy('_NSX_Master_Default')
            poller = policy.upload('myfirewall', wait_for_finish=True)
            while not poller.done():
                poller.wait(3)
                print(poller.task.progress)
            print("Task finished: %s" % poller.message())

        :param str engine: name of device to upload policy to
        :raises: TaskRunFailed
        :return: TaskOperationPoller
        """
        return Task.execute(self, 'upload', params={'filter': engine},
            timeout=timeout, wait_for_finish=wait_for_finish, **kw)
Esempio n. 16
0
 def policy_waiter(self, follower):
     """
     Wait for policy upload
     """
     logger.info('Uploading policy for {}..'.format(self.engine.name))
     start_time = time.time()
     while True:
         reply = Task(**element_by_href_as_json(follower))
         if reply.progress:
             logger.info('[{}]: policy progress -> {}%'.format(self.engine.name, 
                                                               reply.progress))
         if not reply.in_progress:
             logger.info('Upload policy task completed for {} in {} seconds'
                         .format(self.engine.name, time.time() - start_time))
             if not reply.success:
                 yield [reply.last_message]
             else:
                 yield []
         yield None
Esempio n. 17
0
    def export_elements(self, filename='export_elements.zip', typeof='all'):
        """
        Export elements from SMC.

        Valid types are:
        all (All Elements)|nw (Network Elements)|ips (IPS Elements)|
        sv (Services)|rb (Security Policies)|al (Alerts)|
        vpn (VPN Elements)

        :param type: type of element
        :param filename: Name of file for export
        :raises TaskRunFailed: failure during export with reason
        :rtype: DownloadTask
        """
        valid_types = ['all', 'nw', 'ips', 'sv', 'rb', 'al', 'vpn']
        if typeof not in valid_types:
            typeof = 'all'
        
        return Task.download(self, 'export_elements', filename,
            params={'recursive': True, 'type': typeof})
Esempio n. 18
0
    def upload(self, engine, wait_for_finish=True):
        """ 
        Upload policy to specific device. This is an asynchronous call
        that will return a 'follower' link that can be queried to determine 
        the status of the task. 
        
        If wait_for_finish is False, the progress
        href is returned when calling this method. If wait_for_finish is
        True, this generator function will return the new messages as they
        arrive.

        :param engine: name of device to upload policy to
        :param wait_for_finish: whether to wait in a loop until the upload completes
        :return: generator with updates, or follower href if wait_for_finish=False
        """
        element = prepared_request(TaskRunFailed,
                                   href=self._link('upload'),
                                   params={'filter': engine}).create()
        
        return task_handler(Task(**element.json), 
                            wait_for_finish=wait_for_finish)
Esempio n. 19
0
    def export(self, filename='element.zip', wait_for_finish=False):
        """
        Export this element
        
        :param str filename: filename to store exported element
        :param boolean wait_for_finish: wait for update msgs (default: False)
        :raises: ActionCommandFailed
        :return: generator yielding updates on progress, or [] if element cannot
                 be exported, like for system elements
        """
        from smc.administration.tasks import Task, task_handler
        try:
            element = prepared_request(ActionCommandFailed,
                                       href=self._link('export'),
                                       filename=filename).create()

            return task_handler(Task(**element.json),
                                wait_for_finish=wait_for_finish,
                                filename=filename)
        except ResourceNotFound:
            return []
Esempio n. 20
0
    def export(self, filename='element.zip'):
        """
        Export this element.

        Usage::

            engine = Engine('myfirewall')
            extask = engine.export(filename='fooexport.zip')
            while not extask.done():
                extask.wait(3)
            print("Finished download task: %s" % extask.message())
            print("File downloaded to: %s" % extask.filename)

        :param str filename: filename to store exported element
        :raises TaskRunFailed: invalid permissions, invalid directory, or this
            element is a system element and cannot be exported.
        :return: DownloadTask
        
        .. note:: It is not possible to export system elements
        """
        from smc.administration.tasks import Task
        return Task.download(self, 'export', filename)
Esempio n. 21
0
    def generate(self,
                 start_time=0,
                 end_time=0,
                 senders=None,
                 wait_for_finish=False,
                 timeout=5,
                 **kw):  # @ReservedAssignment
        """
        Generate the report and optionally wait for results.
        You can optionally add filters to the report by providing the senders
        argument as a list of type Element::

            report = ReportDesign('Firewall Weekly Summary')
            begin = datetime_to_ms(datetime.strptime("2018-02-03T00:00:00", "%Y-%m-%dT%H:%M:%S"))
            end = datetime_to_ms(datetime.strptime("2018-02-04T00:00:00", "%Y-%m-%dT%H:%M:%S"))
            report.generate(start_time=begin, end_time=end, senders=[Engine('vm')])

        :param int period_begin: milliseconds time defining start time for report
        :param int period_end: milliseconds time defining end time for report
        :param senders: filter targets to use when generating report
        :type senders: list(Element)
        :param bool wait_for_finish: enable polling for results
        :param int timeout: timeout between polling
        :raises TaskRunFailed: refresh failed, possibly locked policy
        :rtype: TaskOperationPoller
        """
        if start_time and end_time:
            kw.setdefault("params", {}).update({
                "start_time": start_time,
                "end_time": end_time
            })
        if senders:
            kw.setdefault("json",
                          {}).update({"senders": element_resolver(senders)})
        return Task.execute(self,
                            "generate",
                            timeout=timeout,
                            wait_for_finish=wait_for_finish,
                            **kw)
Esempio n. 22
0
    def upload(self, policy=None, timeout=5, wait_for_finish=False, **kw):
        """
        Upload policy to engine. This is used when a new policy is required
        for an engine, or this is the first time a policy is pushed to an
        engine.
        If an engine already has a policy and the intent is to re-push, then
        use :py:func:`refresh` instead.
        The policy argument can use a wildcard * to specify in the event a full
        name is not known::

            engine = Engine('myfw')
            task = engine.upload('Amazon*')
            for message in task.wait():
                print(message)

        :param str policy: name of policy to upload to engine; if None, current
            policy
        :param int timeout: timeout between queries
        :raises TaskRunFailed: upload failed with reason
        :rtype: TaskOperationPoller
        """
        return Task.execute(self, 'upload', params={'filter': policy},
            timeout=timeout, wait_for_finish=wait_for_finish, **kw)
Esempio n. 23
0
    def refresh(self, wait_for_finish=True, sleep=3):
        """ 
        Refresh existing policy on specified device. This is an asynchronous 
        call that will return a 'follower' link that can be queried to determine 
        the status of the task. 
        
        Last yield is result href; if wait_for_finish=False, the only yield is 
        the follower href::
        
            task = engine.refresh()
            for message in task:
                print message

        :param boolean wait_for_finish: whether to wait in a loop until the upload completes
        :param int sleep: number of seconds to sleep if wait_for_finish=True
        :raises: :py:class:`smc.api.exceptions.TaskRunFailed`
        :return: generator yielding updates on progress
        """
        element = prepared_request(TaskRunFailed,
                                   href=self._link('refresh')).create()

        return task_handler(Task(**element.json),
                            wait_for_finish=wait_for_finish,
                            sleep=sleep)