Skip to content

Nornir Worker

Nornir Worker Inventory Reference¤

  • watchdog_interval - watchdog run interval in seconds, default is 30
  • connections_idle_timeout - watchdog connection idle timeout, default is None - no timeout, connection always kept alive, if set to 0, connections disconnected imminently after task completed, if positive number, connection disconnected after not being used for over connections_idle_timeout

WatchDog(worker) ¤

Bases: WorkerWatchDog

Class to monitor Nornir worker performance

Source code in norfab\workers\nornir_worker.py
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
def __init__(self, worker):
    super().__init__(worker)
    self.worker = worker
    self.connections_idle_timeout = worker.inventory.get(
        "connections_idle_timeout", None
    )
    self.connections_data = {}  # store connections use timestamps
    self.started_at = time.time()

    # stats attributes
    self.idle_connections_cleaned = 0
    self.dead_connections_cleaned = 0

    # list of tasks for watchdog to run in given order
    self.watchdog_tasks = [
        self.connections_clean,
        self.connections_keepalive,
    ]

connections_update(nr, plugin) ¤

Function to update connection use timestamps for each host

Parameters:

Name Type Description Default
nr

Nornir object

required
plugin str

connection plugin name

required
Source code in norfab\workers\nornir_worker.py
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
def connections_update(self, nr, plugin: str) -> None:
    """
    Function to update connection use timestamps for each host

    :param nr: Nornir object
    :param plugin: connection plugin name
    """
    conn_stats = {
        "last_use": None,
        "last_keepealive": None,
        "keepalive_count": 0,
    }
    for host_name in nr.inventory.hosts:
        self.connections_data.setdefault(host_name, {})
        self.connections_data[host_name].setdefault(plugin, conn_stats.copy())
        self.connections_data[host_name][plugin]["last_use"] = time.ctime()
    log.info(
        f"{self.worker.name} - updated connections use timestamps for '{plugin}'"
    )

connections_clean() ¤

Check if need to tear down connections that are idle - not being used over connections_idle_timeout

Source code in norfab\workers\nornir_worker.py
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
def connections_clean(self):
    """
    Check if need to tear down connections that are idle -
    not being used over connections_idle_timeout
    """
    # dictionary keyed by plugin name and value as a list of hosts
    disconnect = {}
    if not self.worker.connections_lock.acquire(blocking=False):
        return
    try:
        # if idle timeout not set, connections don't age out
        if self.connections_idle_timeout is None:
            disconnect = {}
        # disconnect all connections for all hosts
        elif self.connections_idle_timeout == 0:
            disconnect = {"all": list(self.connections_data.keys())}
        # only disconnect aged/idle connections
        elif self.connections_idle_timeout > 0:
            for host_name, plugins in self.connections_data.items():
                for plugin, conn_data in plugins.items():
                    last_use = time.mktime(time.strptime(conn_data["last_use"]))
                    age = time.time() - last_use
                    if age > self.connections_idle_timeout:
                        disconnect.setdefault(plugin, [])
                        disconnect[plugin].append(host_name)
        # run task to disconnect connections for aged hosts
        for plugin, hosts in disconnect.items():
            if not hosts:
                continue
            aged_hosts = FFun(self.worker.nr, FL=hosts)
            aged_hosts.run(task=nr_connections, call="close", conn_name=plugin)
            log.debug(
                f"{self.worker.name} watchdog, disconnected '{plugin}' "
                f"connections for '{', '.join(hosts)}'"
            )
            self.idle_connections_cleaned += len(hosts)
            # wipe out connections data if all connection closed
            if plugin == "all":
                self.connections_data = {}
                break
            # remove disconnected plugin from host's connections_data
            for host in hosts:
                self.connections_data[host].pop(plugin)
                if not self.connections_data[host]:
                    self.connections_data.pop(host)
    except Exception as e:
        msg = f"{self.worker.name} - watchdog failed to close idle connections, error: {e}"
        log.error(msg)
    finally:
        self.worker.connections_lock.release()

connections_keepalive() ¤

Keepalive connections and clean up dead connections if any

Source code in norfab\workers\nornir_worker.py
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
def connections_keepalive(self):
    """Keepalive connections and clean up dead connections if any"""
    if self.connections_idle_timeout == 0:  # do not keepalive if idle is 0
        return
    if not self.worker.connections_lock.acquire(blocking=False):
        return
    try:
        log.debug(f"{self.worker.name} - watchdog running connections keepalive")
        stats = HostsKeepalive(self.worker.nr)
        self.dead_connections_cleaned += stats["dead_connections_cleaned"]
        # update connections statistics
        for plugins in self.connections_data.values():
            for plugin in plugins.values():
                plugin["last_keepealive"] = time.ctime()
                plugin["keepalive_count"] += 1
    except Exception as e:
        msg = f"{self.worker.name} - watchdog HostsKeepalive check error: {e}"
        log.error(msg)
    finally:
        self.worker.connections_lock.release()

NornirWorker(broker, service, worker_name, exit_event=None, init_done_event=None, log_level='WARNING') ¤

Bases: NFPWorker

Parameters:

Name Type Description Default
broker str

broker URL to connect to

required
service str

name of the service with worker belongs to

required
worker_name str

name of this worker

required
exit_event

if set, worker need to stop/exit

None
init_done_event

event to set when worker done initializing

None
log_level str

logging level of this worker

'WARNING'
Source code in norfab\workers\nornir_worker.py
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
def __init__(
    self,
    broker: str,
    service: str,
    worker_name: str,
    exit_event=None,
    init_done_event=None,
    log_level: str = "WARNING",
):
    super().__init__(broker, service, worker_name, exit_event, log_level)
    self.init_done_event = init_done_event
    self.tf_base_path = os.path.join(self.base_dir, "tf")

    # misc attributes
    self.connections_lock = Lock()

    # get inventory from broker
    self.inventory = self.load_inventory()

    # pull Nornir inventory from Netbox
    self._pull_netbox_inventory()

    # initiate Nornir
    self._init_nornir()

    # initiate watchdog
    self.watchdog = WatchDog(self)
    self.watchdog.start()

    self.init_done_event.set()
    log.info(f"{self.name} - Started")

render_jinja2_templates(templates, context, filters=None) ¤

helper function to render a list of Jinja2 templates

Parameters:

Name Type Description Default
templates list[str]

list of template strings to render

required
context dict

Jinja2 context dictionary

required
filter

custom Jinja2 filters

required

Returns:

Type Description
list[str]

list of rendered strings

Source code in norfab\workers\nornir_worker.py
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
def render_jinja2_templates(
    self, templates: list[str], context: dict, filters: dict = None
) -> list[str]:
    """
    helper function to render a list of Jinja2 templates

    :param templates: list of template strings to render
    :param context: Jinja2 context dictionary
    :param filter: custom Jinja2 filters
    :returns: list of rendered strings
    """
    rendered = []
    filters = filters or {}
    for template in templates:
        if template.startswith("nf://"):
            filepath = self.fetch_jinja2(template)
            searchpath, filename = os.path.split(filepath)
            j2env = Environment(loader=FileSystemLoader(searchpath))
            j2env.filters.update(filters)  # add custom filters
            renderer = j2env.get_template(filename)
        else:
            j2env = Environment(loader="BaseLoader")
            j2env.filters.update(filters)  # add custom filters
            renderer = j2env.from_string(template)
        rendered.append(renderer.render(**context))

    return rendered

load_job_data(job_data) ¤

Helper function to download job data and load it using YAML

Parameters:

Name Type Description Default
job_data str

URL to job data

required
Source code in norfab\workers\nornir_worker.py
455
456
457
458
459
460
461
462
463
464
465
466
467
468
def load_job_data(self, job_data: str):
    """
    Helper function to download job data and load it using YAML

    :param job_data: URL to job data
    """
    if self.is_url(job_data):
        job_data = self.fetch_file(job_data)
        if job_data is None:
            msg = f"{self.name} - '{job_data}' job data file download failed"
            raise FileNotFoundError(msg)
        job_data = yaml.safe_load(job_data)

    return job_data

get_nornir_hosts(details=False, **kwargs) ¤

Produce a list of hosts managed by this worker

Parameters:

Name Type Description Default
kwargs dict

dictionary of nornir-salt Fx filters

{}
Source code in norfab\workers\nornir_worker.py
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
def get_nornir_hosts(self, details: bool = False, **kwargs: dict) -> list:
    """
    Produce a list of hosts managed by this worker

    :param kwargs: dictionary of nornir-salt Fx filters
    """
    filters = {k: kwargs.pop(k) for k in list(kwargs.keys()) if k in FFun_functions}
    filtered_nornir = FFun(self.nr, **filters)
    if details:
        return Result(
            result={
                host_name: {
                    "platform": str(host.platform),
                    "hostname": str(host.hostname),
                    "port": str(host.port),
                    "groups": [str(g) for g in host.groups],
                    "username": str(host.username),
                }
                for host_name, host in filtered_nornir.inventory.hosts.items()
            }
        )
    else:
        return Result(result=list(filtered_nornir.inventory.hosts))

get_nornir_inventory(**kwargs) ¤

Retrieve running Nornir inventory for requested hosts

Parameters:

Name Type Description Default
kwargs dict

dictionary of nornir-salt Fx filters

{}
Source code in norfab\workers\nornir_worker.py
517
518
519
520
521
522
523
524
525
526
527
def get_nornir_inventory(self, **kwargs: dict) -> dict:
    """
    Retrieve running Nornir inventory for requested hosts

    :param kwargs: dictionary of nornir-salt Fx filters
    """
    filters = {k: kwargs.pop(k) for k in list(kwargs.keys()) if k in FFun_functions}
    filtered_nornir = FFun(self.nr, **filters)
    return Result(
        result=filtered_nornir.inventory.dict(), task="get_nornir_inventory"
    )

get_nornir_version() ¤

Produce Python packages version report

Source code in norfab\workers\nornir_worker.py
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
def get_nornir_version(self):
    """
    Produce Python packages version report
    """
    libs = {
        "scrapli": "",
        "scrapli-netconf": "",
        "scrapli-community": "",
        "paramiko": "",
        "netmiko": "",
        "napalm": "",
        "nornir": "",
        "ncclient": "",
        "nornir-netmiko": "",
        "nornir-napalm": "",
        "nornir-scrapli": "",
        "nornir-utils": "",
        "tabulate": "",
        "xmltodict": "",
        "puresnmp": "",
        "pygnmi": "",
        "pyyaml": "",
        "jmespath": "",
        "jinja2": "",
        "ttp": "",
        "nornir-salt": "",
        "lxml": "",
        "ttp-templates": "",
        "ntc-templates": "",
        "cerberus": "",
        "pydantic": "",
        "requests": "",
        "textfsm": "",
        "N2G": "",
        "dnspython": "",
        "pythonping": "",
        "python": sys.version.split(" ")[0],
        "platform": sys.platform,
    }
    # get version of packages installed
    for pkg in libs.keys():
        try:
            libs[pkg] = importlib.metadata.version(pkg)
        except importlib.metadata.PackageNotFoundError:
            pass

    return Result(result=libs)

task(plugin, **kwargs) ¤

Function to invoke any of supported Nornir task plugins. This function performs dynamic import of requested plugin function and executes nr.run using supplied args and kwargs

plugin attribute can refer to a file to fetch from file service. File must contain function named task accepting Nornir task object as a first positional argument, for example:

# define connection name for RetryRunner to properly detect it
CONNECTION_NAME = "netmiko"

# create task function
def task(nornir_task_object, *args, **kwargs):
    pass

CONNECTION_NAME

CONNECTION_NAME must be defined within custom task function file if RetryRunner in use, otherwise connection retry logic skipped and connections to all hosts initiated simultaneously up to the number of num_workers.

Parameters:

Name Type Description Default
plugin str

(str) path.to.plugin.task_fun to import or nf://path/to/task.py to download custom task

required
kwargs

(dict) arguments to use with specified task plugin

{}
Source code in norfab\workers\nornir_worker.py
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
def task(self, plugin: str, **kwargs) -> Result:
    """
    Function to invoke any of supported Nornir task plugins. This function
    performs dynamic import of requested plugin function and executes
    ``nr.run`` using supplied args and kwargs

    ``plugin`` attribute can refer to a file to fetch from file service. File must contain
    function named ``task`` accepting Nornir task object as a first positional
    argument, for example:

    ```python
    # define connection name for RetryRunner to properly detect it
    CONNECTION_NAME = "netmiko"

    # create task function
    def task(nornir_task_object, *args, **kwargs):
        pass
    ```

    !!! note "CONNECTION_NAME"

        ``CONNECTION_NAME`` must be defined within custom task function file if
        RetryRunner in use, otherwise connection retry logic skipped and connections
        to all hosts initiated simultaneously up to the number of ``num_workers``.

    :param plugin: (str) ``path.to.plugin.task_fun`` to import or ``nf://path/to/task.py``
        to download custom task
    :param kwargs: (dict) arguments to use with specified task plugin
    """
    # extract attributes
    add_details = kwargs.pop("add_details", False)  # ResultSerializer
    to_dict = kwargs.pop("to_dict", True)  # ResultSerializer
    filters = {k: kwargs.pop(k) for k in list(kwargs.keys()) if k in FFun_functions}
    ret = Result(task=f"{self.name}:task", result={} if to_dict else [])

    # download task from broker and load it
    if plugin.startswith("nf://"):
        function_text = self.fetch_file(plugin)
        if function_text is None:
            raise FileNotFoundError(
                f"{self.name} - '{plugin}' task plugin download failed"
            )

        # load task function running exec
        globals_dict = {}
        exec(function_text, globals_dict, globals_dict)
        task_function = globals_dict["task"]
    # import task function
    else:
        # below same as "from nornir.plugins.tasks import task_fun as task_function"
        task_fun = plugin.split(".")[-1]
        module = __import__(plugin, fromlist=[""])
        task_function = getattr(module, task_fun)

    self.nr.data.reset_failed_hosts()  # reset failed hosts
    filtered_nornir = FFun(self.nr, **filters)  # filter hosts

    # check if no hosts matched
    if not filtered_nornir.inventory.hosts:
        msg = (
            f"{self.name} - nothing to do, no hosts matched by filters '{filters}'"
        )
        log.debug(msg)
        ret.messages.append(msg)
        return ret

    nr = self._add_processors(filtered_nornir, kwargs)  # add processors

    # run task
    log.debug(f"{self.name} - running Nornir task '{plugin}', kwargs '{kwargs}'")
    with self.connections_lock:
        result = nr.run(task=task_function, **kwargs)
    ret.result = ResultSerializer(result, to_dict=to_dict, add_details=add_details)

    self.watchdog.connections_clean()

    return ret

cli(commands=None, plugin='netmiko', cli_dry_run=False, run_ttp=None, job_data=None, to_dict=True, add_details=False, **kwargs) ¤

Function to collect show commands output from devices using Command Line Interface (CLI)

Parameters:

Name Type Description Default
commands list

list of commands to send to devices

None
plugin str

plugin name to use - netmiko, scrapli, napalm

'netmiko'
cli_dry_run bool

do not send commands to devices just return them

False
job_data str

URL to YAML file with data or dictionary/list of data to pass on to Jinja2 rendering context

None
add_details bool

if True will add task execution details to the results

False
to_dict bool

default is True - produces dictionary results, if False will produce results list

True
run_ttp str

TTP Template to run

None
Source code in norfab\workers\nornir_worker.py
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
def cli(
    self,
    commands: list = None,
    plugin: str = "netmiko",
    cli_dry_run: bool = False,
    run_ttp: str = None,
    job_data: str = None,
    to_dict: bool = True,
    add_details: bool = False,
    **kwargs,
) -> dict:
    """
    Function to collect show commands output from devices using
    Command Line Interface (CLI)

    :param commands: list of commands to send to devices
    :param plugin: plugin name to use - ``netmiko``, ``scrapli``, ``napalm``
    :param cli_dry_run: do not send commands to devices just return them
    :param job_data: URL to YAML file with data or dictionary/list of data
        to pass on to Jinja2 rendering context
    :param add_details: if True will add task execution details to the results
    :param to_dict: default is True - produces dictionary results, if False
        will produce results list
    :param run_ttp: TTP Template to run
    """
    job_data = job_data or {}
    filters = {k: kwargs.pop(k) for k in list(kwargs.keys()) if k in FFun_functions}
    downloaded_cmds = []
    timeout = self.current_job["timeout"] * 0.9
    ret = Result(task=f"{self.name}:cli", result={} if to_dict else [])

    # decide on what send commands task plugin to use
    if plugin == "netmiko":
        task_plugin = netmiko_send_commands
        if kwargs.get("use_ps"):
            kwargs.setdefault("timeout", timeout)
        else:
            kwargs.setdefault("read_timeout", timeout)
    elif plugin == "scrapli":
        task_plugin = scrapli_send_commands
        kwargs.setdefault("timeout_ops", timeout)
    elif plugin == "napalm":
        task_plugin = napalm_send_commands
    else:
        raise UnsupportedPluginError(f"Plugin '{plugin}' not supported")

    self.nr.data.reset_failed_hosts()  # reset failed hosts
    filtered_nornir = FFun(self.nr, **filters)  # filter hosts

    # check if no hosts matched
    if not filtered_nornir.inventory.hosts:
        msg = (
            f"{self.name} - nothing to do, no hosts matched by filters '{filters}'"
        )
        log.debug(msg)
        ret.messages.append(msg)
        return ret

    # download TTP template
    if self.is_url(run_ttp):
        downloaded = self.fetch_file(run_ttp)
        kwargs["run_ttp"] = downloaded
        if downloaded is None:
            msg = f"{self.name} - TTP template download failed '{run_ttp}'"
            raise FileNotFoundError(msg)
    # use TTP template as is - inline template or ttp://xyz path
    elif run_ttp:
        kwargs["run_ttp"] = run_ttp

    # download job data
    job_data = self.load_job_data(job_data)

    nr = self._add_processors(filtered_nornir, kwargs)  # add processors

    # render commands using Jinja2 on a per-host basis
    if commands:
        commands = commands if isinstance(commands, list) else [commands]
        for host in nr.inventory.hosts.values():
            rendered = self.render_jinja2_templates(
                templates=commands,
                context={
                    "host": host,
                    "norfab": self.client,
                    "nornir": self,
                    "job_data": job_data,
                },
                filters=self.add_jinja2_filters(),
            )
            host.data["__task__"] = {"commands": rendered}

    # run task
    log.debug(
        f"{self.name} - running cli commands '{commands}', kwargs '{kwargs}', is cli dry run - '{cli_dry_run}'"
    )
    if cli_dry_run is True:
        result = nr.run(
            task=nr_test, use_task_data="commands", name="cli_dry_run", **kwargs
        )
    else:
        with self.connections_lock:
            result = nr.run(task=task_plugin, **kwargs)

    ret.result = ResultSerializer(result, to_dict=to_dict, add_details=add_details)

    # remove __task__ data
    for host_name, host_object in nr.inventory.hosts.items():
        _ = host_object.data.pop("__task__", None)

    self.watchdog.connections_update(nr, plugin)
    self.watchdog.connections_clean()

    return ret

nb_get_next_ip(*args, **kwargs) ¤

Method to query next available IP address from Netbox service

Source code in norfab\workers\nornir_worker.py
777
778
779
780
781
782
783
784
785
786
787
788
789
790
def nb_get_next_ip(self, *args, **kwargs):
    """Method to query next available IP address from Netbox service"""
    reply = self.client.run_job(
        "netbox",
        "get_next_ip",
        args=args,
        kwargs=kwargs,
        workers="any",
        timeout=30,
    )
    # reply is a dict of {worker_name: results_dict}
    result = list(reply.values())[0]

    return result["result"]

cfg(config, plugin='netmiko', cfg_dry_run=False, to_dict=True, add_details=False, job_data=None, **kwargs) ¤

Function to send configuration commands to devices using Command Line Interface (CLI)

Parameters:

Name Type Description Default
config list

list of commands to send to devices

required
plugin str

plugin name to use - netmiko, scrapli, napalm

'netmiko'
cfg_dry_run bool

do not send commands to devices just return them

False
job_data str

URL to YAML file with data or dictionary/list of data to pass on to Jinja2 rendering context

None
add_details bool

if True will add task execution details to the results

False
to_dict bool

default is True - produces dictionary results, if False will produce results list

True
Source code in norfab\workers\nornir_worker.py
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
def cfg(
    self,
    config: list,
    plugin: str = "netmiko",
    cfg_dry_run: bool = False,
    to_dict: bool = True,
    add_details: bool = False,
    job_data: str = None,
    **kwargs,
) -> dict:
    """
    Function to send configuration commands to devices using
    Command Line Interface (CLI)

    :param config: list of commands to send to devices
    :param plugin: plugin name to use - ``netmiko``, ``scrapli``, ``napalm``
    :param cfg_dry_run: do not send commands to devices just return them
    :param job_data: URL to YAML file with data or dictionary/list of data
        to pass on to Jinja2 rendering context
    :param add_details: if True will add task execution details to the results
    :param to_dict: default is True - produces dictionary results, if False
        will produce results list
    """
    downloaded_cfg = []
    config = config if isinstance(config, list) else [config]
    filters = {k: kwargs.pop(k) for k in list(kwargs.keys()) if k in FFun_functions}
    ret = Result(task=f"{self.name}:cfg", result={} if to_dict else [])
    timeout = self.current_job["timeout"]

    # decide on what send commands task plugin to use
    if plugin == "netmiko":
        task_plugin = netmiko_send_config
    elif plugin == "scrapli":
        task_plugin = scrapli_send_config
    elif plugin == "napalm":
        task_plugin = napalm_configure
    else:
        raise UnsupportedPluginError(f"Plugin '{plugin}' not supported")

    self.nr.data.reset_failed_hosts()  # reset failed hosts
    filtered_nornir = FFun(self.nr, **filters)  # filter hosts

    # check if no hosts matched
    if not filtered_nornir.inventory.hosts:
        msg = (
            f"{self.name} - nothing to do, no hosts matched by filters '{filters}'"
        )
        ret.messages.append(msg)
        log.debug(msg)
        return ret

    job_data = self.load_job_data(job_data)

    nr = self._add_processors(filtered_nornir, kwargs)  # add processors

    # render config using Jinja2 on a per-host basis
    for host in nr.inventory.hosts.values():
        rendered = self.render_jinja2_templates(
            templates=config,
            context={
                "host": host,
                "norfab": self.client,
                "nornir": self,
                "job_data": job_data,
            },
            filters=self.add_jinja2_filters(),
        )
        host.data["__task__"] = {"config": rendered}

    # run task
    log.debug(
        f"{self.name} - sending config commands '{config}', kwargs '{kwargs}', is cfg_dry_run - '{cfg_dry_run}'"
    )
    if cfg_dry_run is True:
        result = nr.run(
            task=nr_test, use_task_data="config", name="cfg_dry_run", **kwargs
        )
    else:
        with self.connections_lock:
            result = nr.run(task=task_plugin, **kwargs)
        ret.changed = True

    ret.result = ResultSerializer(result, to_dict=to_dict, add_details=add_details)

    # remove __task__ data
    for host_name, host_object in nr.inventory.hosts.items():
        _ = host_object.data.pop("__task__", None)

    self.watchdog.connections_update(nr, plugin)
    self.watchdog.connections_clean()

    return ret

test(suite, subset=None, dry_run=False, remove_tasks=True, failed_only=False, return_tests_suite=False, job_data=None, **kwargs) ¤

Function to tests data obtained from devices.

Parameters:

Name Type Description Default
suite Union[list, str]

path to YAML file with tests

required
dry_run bool

if True, returns produced per-host tests suite content only

False
subset str

list or string with comma separated non case sensitive glob patterns to filter tests' by name, subset argument ignored by dry run

None
failed_only bool

if True returns test results for failed tests only

False
remove_tasks bool

if False results will include other tasks output

True
return_tests_suite bool

if True returns rendered per-host tests suite content in addition to test results using dictionary with results and suite keys

False
job_data str

URL to YAML file with data or dictionary/list of data to pass on to Jinja2 rendering context

None
kwargs

any additional arguments to pass on to Nornir service task

{}
Source code in norfab\workers\nornir_worker.py
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
def test(
    self,
    suite: Union[list, str],
    subset: str = None,
    dry_run: bool = False,
    remove_tasks: bool = True,
    failed_only: bool = False,
    return_tests_suite: bool = False,
    job_data: str = None,
    **kwargs,
) -> dict:
    """
    Function to tests data obtained from devices.

    :param suite: path to YAML file with tests
    :param dry_run: if True, returns produced per-host tests suite content only
    :param subset: list or string with comma separated non case sensitive glob
        patterns to filter tests' by name, subset argument ignored by dry run
    :param failed_only: if True returns test results for failed tests only
    :param remove_tasks: if False results will include other tasks output
    :param return_tests_suite: if True returns rendered per-host tests suite
        content in addition to test results using dictionary with ``results``
        and ``suite`` keys
    :param job_data: URL to YAML file with data or dictionary/list of data
        to pass on to Jinja2 rendering context
    :param kwargs: any additional arguments to pass on to Nornir service task
    """
    tests = {}  # dictionary to hold per-host test suites
    add_details = kwargs.get("add_details", False)  # ResultSerializer
    to_dict = kwargs.get("to_dict", True)  # ResultSerializer
    filters = {k: kwargs.pop(k) for k in list(kwargs.keys()) if k in FFun_functions}
    ret = Result(task=f"{self.name}:test", result={} if to_dict else [])
    suites = {}  # dictionary to hold combined test suites

    self.nr.data.reset_failed_hosts()  # reset failed hosts
    filtered_nornir = FFun(self.nr, **filters)  # filter hosts

    # check if no hosts matched
    if not filtered_nornir.inventory.hosts:
        msg = (
            f"{self.name} - nothing to do, no hosts matched by filters '{filters}'"
        )
        log.debug(msg)
        ret.messages.append(msg)
        if return_tests_suite is True:
            ret.result = {"test_results": [], "suite": {}}
        return ret

    # download job data
    job_data = self.load_job_data(job_data)

    # generate per-host test suites
    for host_name, host in filtered_nornir.inventory.hosts.items():
        # render suite using Jinja2
        try:
            rendered_suite = self.render_jinja2_templates(
                templates=[suite],
                context={
                    "host": host,
                    "norfab": self.client,
                    "nornir": self,
                    "job_data": job_data,
                },
                filters=self.add_jinja2_filters(),
            )
            rendered_suite = rendered_suite[0]
        except Exception as e:
            msg = f"{self.name} - '{suite}' Jinja2 rendering failed: '{e}'"
            raise RuntimeError(msg)
        # load suit using YAML
        try:
            tests[host_name] = yaml.safe_load(rendered_suite)
        except Exception as e:
            msg = f"{self.name} - '{suite}' YAML load failed: '{e}'"
            raise RuntimeError(msg)

    # validate tests suite
    try:
        _ = modelTestsProcessorSuite(tests=tests)
    except Exception as e:
        msg = f"{self.name} - '{suite}' suite validation failed: '{e}'"
        raise RuntimeError(msg)

    # download pattern, schema and custom function files
    for host_name in tests.keys():
        for index, item in enumerate(tests[host_name]):
            for k in ["pattern", "schema", "function_file"]:
                if self.is_url(item.get(k)):
                    item[k] = self.fetch_file(
                        item[k], raise_on_fail=True, read=True
                    )
                    if k == "function_file":
                        item["function_text"] = item.pop(k)
            tests[host_name][index] = item

    # save per-host tests suite content before mutating it
    if return_tests_suite is True:
        return_suite = copy.deepcopy(tests)

    log.debug(f"{self.name} - running test '{suite}', is dry run - '{dry_run}'")
    # run dry run task
    if dry_run is True:
        result = filtered_nornir.run(
            task=nr_test, name="tests_dry_run", ret_data_per_host=tests
        )
        ret.result = ResultSerializer(
            result, to_dict=to_dict, add_details=add_details
        )
    # combine per-host tests in suites based on task and arguments
    # Why - to run tests using any nornir service tasks with various arguments
    else:
        for host_name, host_tests in tests.items():
            for test in host_tests:
                dhash = hashlib.md5()
                test_args = test.pop("norfab", {})
                nrtask = test_args.get("nrtask", "cli")
                assert nrtask in [
                    "cli",
                    "network",
                    "cfg",
                    "task",
                ], f"{self.name} - unsupported NorFab Nornir Service task '{nrtask}'"
                test_json = json.dumps(test_args, sort_keys=True).encode()
                dhash.update(test_json)
                test_hash = dhash.hexdigest()
                suites.setdefault(test_hash, {"params": test_args, "tests": {}})
                suites[test_hash]["tests"].setdefault(host_name, [])
                suites[test_hash]["tests"][host_name].append(test)
        log.debug(
            f"{self.name} - combined per-host tests suites based on NorFab Nornir Service task and arguments:\n{suites}"
        )
        # run test suites collecting output from devices
        for tests_suite in suites.values():
            nrtask = tests_suite["params"].pop("nrtask", "cli")
            function_kwargs = {
                **tests_suite["params"],
                **kwargs,
                **filters,
                "tests": tests_suite["tests"],
                "remove_tasks": remove_tasks,
                "failed_only": failed_only,
                "subset": subset,
            }
            result = getattr(self, nrtask)(
                **function_kwargs
            )  # returns Result object
            # save test results into overall results
            if to_dict == True:
                for host_name, host_res in result.result.items():
                    ret.result.setdefault(host_name, {})
                    ret.result[host_name].update(host_res)
            else:
                ret.result.extend(result.result)

    # check if need to return tests suite content
    if return_tests_suite is True:
        ret.result = {"test_results": ret.result, "suite": return_suite}

    return ret

network(fun, **kwargs) ¤

Function to call various network related utility functions.

Parameters:

Name Type Description Default
fun

(str) utility function name to call

required
kwargs

(dict) function arguments Available utility functions. resolve_dns function resolves hosts' hostname DNS returning IP addresses using nornir_salt.plugins.tasks.network.resolve_dns Nornir-Salt function. ping function Function to execute ICMP ping to host using nornir_salt.plugins.tasks.network.ping Nornir-Salt function.

{}
Source code in norfab\workers\nornir_worker.py
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
def network(self, fun, **kwargs) -> dict:
    """
    Function to call various network related utility functions.

    :param fun: (str) utility function name to call
    :param kwargs: (dict) function arguments

    Available utility functions.

    **resolve_dns** function

    resolves hosts' hostname DNS returning IP addresses using
    ``nornir_salt.plugins.tasks.network.resolve_dns`` Nornir-Salt
    function.

    **ping** function

    Function to execute ICMP ping to host using
    ``nornir_salt.plugins.tasks.network.ping`` Nornir-Salt
    function.
    """
    kwargs["call"] = fun
    return self.task(
        plugin="nornir_salt.plugins.tasks.network",
        **kwargs,
    )

parse(plugin='napalm', getters='get_facts', template=None, commands=None, to_dict=True, add_details=False, **kwargs) ¤

Function to parse network devices show commands output

Parameters:

Name Type Description Default
plugin str

plugin name to use - napalm, textfsm, ttp

'napalm'
getters str

NAPALM getters to use

'get_facts'
commands list

commands to send to devices for TextFSM or TTP template

None
template str

TextFSM or TTP parsing template string or path to file For NAPALM plugin method can refer to a list of getters names.

None
Source code in norfab\workers\nornir_worker.py
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
def parse(
    self,
    plugin: str = "napalm",
    getters: str = "get_facts",
    template: str = None,
    commands: list = None,
    to_dict: bool = True,
    add_details: bool = False,
    **kwargs,
):
    """
    Function to parse network devices show commands output

    :param plugin: plugin name to use - ``napalm``, ``textfsm``, ``ttp``
    :param getters: NAPALM getters to use
    :param commands: commands to send to devices for TextFSM or TTP template
    :param template: TextFSM or TTP parsing template string or path to file

    For NAPALM plugin ``method`` can refer to a list of getters names.
    """
    filters = {k: kwargs.pop(k) for k in list(kwargs.keys()) if k in FFun_functions}
    ret = Result(task=f"{self.name}:parse", result={} if to_dict else [])

    self.nr.data.reset_failed_hosts()  # reset failed hosts
    filtered_nornir = FFun(self.nr, **filters)  # filter hosts

    # check if no hosts matched
    if not filtered_nornir.inventory.hosts:
        msg = (
            f"{self.name} - nothing to do, no hosts matched by filters '{filters}'"
        )
        ret.messages.append(msg)
        log.debug(msg)
        return ret

    if plugin == "napalm":
        nr = self._add_processors(filtered_nornir, kwargs)  # add processors
        result = nr.run(task=napalm_get, getters=getters, **kwargs)
        ret.result = ResultSerializer(
            result, to_dict=to_dict, add_details=add_details
        )
    elif plugin == "ttp":
        result = self.cli(
            commands=commands or [],
            run_ttp=template,
            **filters,
            **kwargs,
            to_dict=to_dict,
            add_details=add_details,
            plugin="netmiko",
        )
        ret.result = result.result
    elif plugin == "textfsm":
        result = self.cli(
            commands=commands,
            **filters,
            **kwargs,
            to_dict=to_dict,
            add_details=add_details,
            use_textfsm=True,
            textfsm_template=template,
            plugin="netmiko",
        )
        ret.result = result.result
    else:
        raise UnsupportedPluginError(f"Plugin '{plugin}' not supported")

    return ret