Resources#
A resource is one stream of raw items for one section in one scope. This page
builds resources step by step. Every snippet comes from one script,
resources.py, which reads hosts.csv and excel-hosts.csv. Put the three
files in one folder and run python resources.py to see the same output:
resources.py
"""A tour of resources: decorators, scopes, schemas, converters and problems.
Each numbered part is shown on the Resources page with its output. Run it with
`python resources.py`; it reads hosts.csv and excel-hosts.csv next to it.
"""
import functools
from pathlib import Path
from typing import Any
import click
from pydantic import BaseModel
from fireman import LoadError, Pipeline, Resource, Source, csv_file, resource
HERE = Path(__file__).parent
# 1. A resource from a generator
@resource("addresses")
def subnets(prefix: str, count: int):
for i in range(count):
yield {"name": f"{prefix}-{i}", "values": [f"10.{i}.0.0/16"]}
site = subnets("site", 2) # nothing is read yet
click.echo(f"{site.name} {site.scope}")
for index, item in site.extract().items:
click.echo(f"{index} {item}")
# 2. Scopes
@resource("services", firewall="edge")
def edge_services():
yield {"name": "syslog", "entries": [{"protocol": 17, "ports": [514, 514]}]}
@resource("rules", firewall="edge", policy="inbound")
def edge_rules():
yield {
"order_id": 10,
"action": "accept",
"sources": ["any"],
"destinations": ["10.0.0.5"],
"services": ["syslog"],
}
@resource("rules", firewall="edge")
def homeless_rules():
yield from ()
click.echo(f"{edge_services().scope} {edge_rules().scope}")
click.echo(edge_rules().scoped(firewall="core", policy="outbound").scope)
try:
Pipeline().load(Source((homeless_rules(),)))
except LoadError as exc:
click.echo(exc.problems[0])
# 3. A schema and converters
class HostRow(BaseModel):
host: str
ip: str
def to_address(row: HostRow) -> dict[str, Any]:
return {"name": row.host, "values": [row.ip]}
def tag(item: dict[str, Any]) -> dict[str, Any]:
return {**item, "name": f"lab-{item['name']}"}
ROWS = [
{"host": "nas", "ip": "10.0.0.5"},
{"host": "printer"},
{"host": "scanner", "ip": "10.0.0.7", "rack": "B2"},
]
@resource("addresses", schema=HostRow)
def hosts():
yield from ROWS
base = hosts()
converted = base.add_map(to_address).add_map(tag)
click.echo(f"{len(base.maps)} {len(converted.maps)}")
out = converted.extract()
for index, item in out.items:
click.echo(f"{index} {item}")
for problem in out.problems:
click.echo(problem)
# 4. Which exceptions become problems
def no_home_networks(item: dict[str, Any]) -> dict[str, Any]:
network = item["ip"] + "/32" # KeyError if missing, TypeError if not a string
if network.startswith("192.168."):
raise ValueError(f"{item['host']} uses a home network address")
return {"name": item["host"], "values": [network]}
@resource("addresses")
def raw_hosts():
yield {"host": "nas", "ip": "10.0.0.5"}
yield {"host": "printer"}
yield {"host": "laptop", "ip": "192.168.1.20"}
yield {"host": "phone", "ip": None}
for problem in raw_hosts().add_map(no_home_networks).extract().problems:
click.echo(problem)
def strip_ip(item: dict[str, Any]) -> dict[str, Any]:
return {"name": item["host"], "values": [item["ip"].strip()]} # None has no strip()
try:
raw_hosts().add_map(strip_ip).extract()
except AttributeError as exc:
click.echo(f"propagated: {exc}")
# 5. csv_file
rows = csv_file(HERE / "hosts.csv", "addresses")
for index, row in rows.extract().items[:2]:
click.echo(f"{index} {row}")
# 6. CSV options and missing files
# Excel writes a byte order mark and, in many locales, semicolons.
excel = csv_file(HERE / "excel-hosts.csv", "addresses", delimiter=";")
def from_excel(row: dict[str, str]) -> dict[str, Any]:
return {"name": row["Name"], "values": [row["Address"]]}
for index, item in excel.add_map(from_excel).extract().items:
click.echo(f"{index} {item}")
for problem in csv_file(Path("missing.csv"), "addresses").extract().problems:
click.echo(problem)
# 7. A Resource built directly
RULES = [
{"order_id": 10, "action": "deny", "sources": ["192.0.2.0/24"], "destinations": ["any"], "services": ["any"]},
]
direct = Resource("rules", functools.partial(iter, RULES), firewall="edge", policy="inbound")
click.echo(f"{direct.scope} {len(direct.extract().items)}")
# 8. Declaring the files a resource reads
click.echo([p.name for p in csv_file(HERE / "hosts.csv", "addresses").paths])
export = HERE / "excel-hosts.csv" # a file your own generator reads
watched = direct.reads(export)
click.echo([p.name for p in watched.paths])
hosts.csv
Name,Address,Owner
nas,10.0.0.5,storage
printer,10.0.0.6,office
excel-hosts.csv
Name;Address;Owner
build-01;10.60.0.11;ci
build-02;10.60.0.12;ci
The script starts with these imports:
import functools
from pathlib import Path
from typing import Any
import click
from pydantic import BaseModel
from fireman import LoadError, Pipeline, Resource, Source, csv_file, resource
HERE = Path(__file__).parent
A resource from a generator#
Decorate a generator function with @resource(name). The name is the section
the items belong to: addresses, fqdns, services, groups or rules.
The function can take any arguments:
@resource("addresses")
def subnets(prefix: str, count: int):
for i in range(count):
yield {"name": f"{prefix}-{i}", "values": [f"10.{i}.0.0/16"]}
site = subnets("site", 2) # nothing is read yet
click.echo(f"{site.name} {site.scope}")
for index, item in site.extract().items:
click.echo(f"{index} {item}")
addresses global
0 {'name': 'site-0', 'values': ['10.0.0.0/16']}
1 {'name': 'site-1', 'values': ['10.1.0.0/16']}
Calling subnets("site", 2) runs nothing. It returns a Resource that
remembers the call, and the generator runs each time the resource is
extracted. Pipeline.load extracts each resource once.
extract() returns an Extracted tuple: items, the items that came through
with their index, and problems, one Problem per thing that went wrong.
You rarely call it yourself, but it’s the quickest way to check a resource
while you write it.
These items are already in Fireman’s shape (see Input format), so
this resource needs no converter. Converters may also return model instances
such as AddressObject(...), or use the builders tcp(), udp() and icmp()
for service entries; Fireman accepts both. The difference shows when a value is
bad: a builder or model fails inside your converter, so the problem names only
the entry’s own field (services[0].ports), while a plain dict is checked by
Fireman with its full path (services[0].entries.0.port.ports). The examples
here return dicts for that reason.
Scopes#
Where the items belong is fixed when you declare the resource:
Declared with |
Scope |
Holds |
|---|---|---|
neither |
|
global objects |
|
|
objects of firewall |
|
|
rules of policy |
Rules need both a firewall and a policy, and objects never take a policy. The
scope property reads as in the table, and every problem starts with it.
@resource("services", firewall="edge")
def edge_services():
yield {"name": "syslog", "entries": [{"protocol": 17, "ports": [514, 514]}]}
@resource("rules", firewall="edge", policy="inbound")
def edge_rules():
yield {
"order_id": 10,
"action": "accept",
"sources": ["any"],
"destinations": ["10.0.0.5"],
"services": ["syslog"],
}
@resource("rules", firewall="edge")
def homeless_rules():
yield from ()
click.echo(f"{edge_services().scope} {edge_rules().scope}")
click.echo(edge_rules().scoped(firewall="core", policy="outbound").scope)
try:
Pipeline().load(Source((homeless_rules(),)))
except LoadError as exc:
click.echo(exc.problems[0])
edge edge/inbound
core/outbound
rules: need both a firewall and a policy
Nothing is checked when the resource is created, so homeless_rules() is
fine until it is loaded. Pipeline.load (and fireman load) then reports the
scope of every resource as a Problem in the LoadError, together with the
other problems and without reading that resource. The problem has no scope or
index, since it is about the resource, not an item. Firewall and policy names
follow the usual name rules; a bad name, or a
resource name other than the five above, is rejected when the resource is
created. The scope property still gives the best label it can, so an unscoped
rules resource reads global.
The decorator fixes the scope for every call. When the scopes come from the
data itself, say one policy per element of an XML file, leave the decorator’s
scope out and call scoped on the resource. It returns a new resource with that
firewall and policy (both default to none) and keeps the function, schema,
converters and paths:
@resource("rules")
def export_rules(export, device): ...
for device in devices(export):
yield export_rules(export, device).scoped(firewall=device.name, policy="in")
edge_rules().scoped(firewall="core", policy="outbound") above is
core/outbound. Calling export_rules(export, device) without scoped is a
load error.
A schema and converters#
Raw data rarely matches Fireman’s format. Two things bridge the gap:
- Schema
A pydantic model of your raw item, passed as
schema=. Each item goes throughmodel_validatefirst, so a bad row is reported with your own field names, and the converters get a typed object.- Converters
Functions added with
add_map, each taking the previous result. They run in the order you add them, after the schema.
add_map returns a new resource with the converter appended, so calls
daisy-chain: hosts().add_map(to_address).add_map(tag) runs to_address on
each item, then tag on its result. Chain as many as you need; each step
stays a small function you can test on its own. The original resource is left
alone, so you can also build variants from one base:
class HostRow(BaseModel):
host: str
ip: str
def to_address(row: HostRow) -> dict[str, Any]:
return {"name": row.host, "values": [row.ip]}
def tag(item: dict[str, Any]) -> dict[str, Any]:
return {**item, "name": f"lab-{item['name']}"}
ROWS = [
{"host": "nas", "ip": "10.0.0.5"},
{"host": "printer"},
{"host": "scanner", "ip": "10.0.0.7", "rack": "B2"},
]
@resource("addresses", schema=HostRow)
def hosts():
yield from ROWS
base = hosts()
converted = base.add_map(to_address).add_map(tag)
click.echo(f"{len(base.maps)} {len(converted.maps)}")
out = converted.extract()
for index, item in out.items:
click.echo(f"{index} {item}")
for problem in out.problems:
click.echo(problem)
0 2
0 {'name': 'lab-nas', 'values': ['10.0.0.5']}
2 {'name': 'lab-scanner', 'values': ['10.0.0.7']}
global/addresses[1].ip: Field required
The printer row has no ip, so the schema rejects it and the converters never
see it. The scanner keeps index 2: an item’s index is its position in what the
resource yielded, never renumbered when earlier items fail. Problems found
later by Fireman’s own models use the same index.
The schema is yours, so it can be as lax as your data needs. Pydantic’s
default mode turns the string "10" into the integer 10, for example, and
ignores extra fields such as rack. Fireman’s models stay strict either way.
Add model_config = ConfigDict(extra="forbid") to your schema if unknown
columns should be errors.
Which exceptions become problems#
A converter reports a bad item by raising. These become a Problem for that
item, and loading carries on with the next one:
- ValueError
The message is used as is. Raise it with a clear message for anything your converter rejects. Pydantic’s
ValidationErroris aValueErrortoo, and gives one problem per error, with its field path.- TypeError
Usually a value of the wrong type in your data.
- KeyError
A missing key. The problem reads
missing key 'ip'.
def no_home_networks(item: dict[str, Any]) -> dict[str, Any]:
network = item["ip"] + "/32" # KeyError if missing, TypeError if not a string
if network.startswith("192.168."):
raise ValueError(f"{item['host']} uses a home network address")
return {"name": item["host"], "values": [network]}
@resource("addresses")
def raw_hosts():
yield {"host": "nas", "ip": "10.0.0.5"}
yield {"host": "printer"}
yield {"host": "laptop", "ip": "192.168.1.20"}
yield {"host": "phone", "ip": None}
for problem in raw_hosts().add_map(no_home_networks).extract().problems:
click.echo(problem)
def strip_ip(item: dict[str, Any]) -> dict[str, Any]:
return {"name": item["host"], "values": [item["ip"].strip()]} # None has no strip()
try:
raw_hosts().add_map(strip_ip).extract()
except AttributeError as exc:
click.echo(f"propagated: {exc}")
global/addresses[1]: missing key 'ip'
global/addresses[2]: laptop uses a home network address
global/addresses[3]: unsupported operand type(s) for +: 'NoneType' and 'str'
propagated: 'NoneType' object has no attribute 'strip'
Any other exception, such as the AttributeError above, is a bug in the
converter, and it propagates.
An error from the generator itself is reported too, once for the whole
resource: OSError (a missing file), csv.Error, ValueError, TypeError and
KeyError become one problem with no index, such as
global/addresses: [Errno 2] No such file or directory: 'hosts.csv'. The items
yielded before the error are kept and that resource stops. Keep the reading in
the generator and every check that can fail per item in a converter or the
schema.
missing key 'ip' doesn’t say which record is meant. When a missing key is
likely, check for it and raise a ValueError that names the record.
csv_file#
csv_file(path, name, *, schema=None, firewall=None, policy=None, delimiter=",", encoding="utf-8-sig")
is a ready-made resource for CSV files with a header row. It lists path in
the resource’s paths (see below). The default encoding
reads plain UTF-8 and drops the byte order mark Excel adds. Each
item is the row as a dict[str, str], keyed by the header:
rows = csv_file(HERE / "hosts.csv", "addresses")
for index, row in rows.extract().items[:2]:
click.echo(f"{index} {row}")
0 {'Name': 'nas', 'Address': '10.0.0.5', 'Owner': 'storage'}
1 {'Name': 'printer', 'Address': '10.0.0.6', 'Owner': 'office'}
Every cell is a string, an empty cell is "", and index 0 is the first row
after the header, so the item at index n is on line n + 2 of the file. The
file is opened when the resource is extracted, not when you call csv_file, so
a missing file is a problem, not an exception.
Since cells are text, you’ll nearly always add a schema or a converter;
Example: CSV exports shows both.
Other dialects and formats#
Pass delimiter and encoding for other CSV flavours. Here is Excel’s
semicolon-separated export, with its byte order mark, and then a file that
doesn’t exist:
# Excel writes a byte order mark and, in many locales, semicolons.
excel = csv_file(HERE / "excel-hosts.csv", "addresses", delimiter=";")
def from_excel(row: dict[str, str]) -> dict[str, Any]:
return {"name": row["Name"], "values": [row["Address"]]}
for index, item in excel.add_map(from_excel).extract().items:
click.echo(f"{index} {item}")
for problem in csv_file(Path("missing.csv"), "addresses").extract().problems:
click.echo(problem)
0 {'name': 'build-01', 'values': ['10.60.0.11']}
1 {'name': 'build-02', 'values': ['10.60.0.12']}
global/addresses: [Errno 2] No such file or directory: 'missing.csv'
For any other format, write the generator yourself. A generator reads anything Python can: a database cursor, an HTTP API with pagination, a vendor SDK. Yield the raw records and leave the reshaping to converters, so a bad record becomes a problem instead of stopping the load.
A Resource built directly#
The decorator is a shortcut for the Resource class:
Resource(name, fn, schema=None, maps=(), firewall=None, policy=None, paths=())
fn takes no arguments and returns an iterable of raw items. To pass
arguments, wrap the function with functools.partial:
RULES = [
{"order_id": 10, "action": "deny", "sources": ["192.0.2.0/24"], "destinations": ["any"], "services": ["any"]},
]
direct = Resource("rules", functools.partial(iter, RULES), firewall="edge", policy="inbound")
click.echo(f"{direct.scope} {len(direct.extract().items)}")
# 8. Declaring the files a resource reads
click.echo([p.name for p in csv_file(HERE / "hosts.csv", "addresses").paths])
export = HERE / "excel-hosts.csv" # a file your own generator reads
watched = direct.reads(export)
click.echo([p.name for p in watched.paths])
edge/inbound 1
Build resources like this when you want every field in one place. When only
the scope comes from the data, Resource(...).scoped(...) does the same job.
Files a resource reads#
fireman load remembers the files it read, and later commands warn when one
changed. A resource tells Fireman which data files it reads in paths.
csv_file fills it in. For your own generator, call reads, which returns a
new resource with the files added (repeats are dropped):
click.echo([p.name for p in csv_file(HERE / "hosts.csv", "addresses").paths])
export = HERE / "excel-hosts.csv" # a file your own generator reads
watched = direct.reads(export)
click.echo([p.name for p in watched.paths])
['hosts.csv']
['excel-hosts.csv']
reads is a method, not a decorator argument, because the files are often
known only when the resource is built, like the path given to branch(path)
in Example: an XML export. A Source exposes the union of its resources’ files as
Source.paths.
Next, Sources puts resources together and loads them.