# `MaeBPF.Server`
[🔗](https://github.com/cocoa-xu/MaeBPF/blob/v0.1.0/maebpf/lib/maebpf/server.ex#L1)

OTP GenServer owning a live eBPF object, single or multi-hook `bpf_link`
attachments, optional `enif_select` ring buffer streaming, live zero-downtime
debug tracing, transactional map migration, and optional kernel runtime stats.

Provides:
  * Single-hook (`attach:`) and multi-hook (`hooks:`) lifecycle over one
    shared eBPF `Object` (e.g. `xdp :ingress` + `tcx :egress` sharing maps)
  * Automatic source-mapped verifier diagnostics (`MaeBPF.Diagnostics`)
    whenever a `source_map` or `use MaeBPF` module is present
  * Zero-polling kernel ring buffer event delivery via `enif_select` with
    bounded draining (`:list` or `:packed` mode), cooperative BEAM scheduler
    yielding under overload, and non-silent `ringbuf_drops` inspection
  * Transactional state-preserving atomic hot-swap (`MaeBPF.Map.reuse_fd/3` +
    `MaeBPF.Link.update_program/3`) with optional `MaeBPF.Migration` schema
    migration and automatic rollback on failure
  * Live zero-downtime `debug/2` and `undebug/1` switching to per-plug
    RingBuf tracing and back to zero-overhead production bytecode while
    reusing all live production maps
  * Optional `/sys/fs/bpf` pinning and zero-packet-drop crash/restart takeover
  * Dynamic runtime toggling of `BPF_STATS_RUN_TIME` (`enable_stats: false`
    by default)

# `child_spec`

Returns a specification to start this module under a supervisor.

See `Supervisor`.

# `debug`

Enables live zero-downtime per-plug RingBuf tracing on a running server
backed by a `use MaeBPF` module or `%MaeBPF.IR.Module{}`.

Recompiles the module with `debug_trace: true`, reuses all compatible live
production maps, opens `"__maebpf_debug_rb"` via `enif_select`, atomically
swaps active links via `BPF_LINK_UPDATE`, and delivers decoded per-plug trace
maps (`%{plug_id, plug, action, src_ip, dst_ip, sport, dport, ...}`) to
`:on_event`.

Options:
  * `:sample` - trace sampling interval `>= 1` (default `1`)
  * `:ringbuf_kb` - debug RingBuf size in KiB (default `256`)
  * `:on_event` - `fn(trace_map) -> any()` or `{pid, tag}` (sends `{tag, traces}`)
  * `:timeout` - GenServer call timeout in ms (default `15_000`)

# `get_global`

Reads and decodes a single BTF-described global variable from the active
object.

    {:ok, 1234} = MaeBPF.Server.get_global(srv, :target_pid)

# `get_globals`

Reads and decodes all BTF-described global variables from the active object.

    {:ok, %{"enabled" => true}} = MaeBPF.Server.get_globals(srv)

# `hot_swap`

Transactionally compiles, loads, reuses or migrates maps, and atomically swaps
the running program(s) on active `bpf_link` handles via `BPF_LINK_UPDATE`.

Supports `MaeBPF.Migration` when `migrate: true`, `map_specs:`,
`old_map_specs:`, `new_map_specs:`, `migrate_fns:`, `migrate_key_fns:`,
`defaults:`, or `reconcile_mode:` are supplied.

# `map_delete`

Deletes a map entry on the currently active object.

# `map_delete_domain`

Deletes an exact or wildcard domain entry from a reversed-FQDN `LPM_TRIE`
map on the active object.

# `map_delete_prog`

Deletes a program from a `BPF_MAP_TYPE_PROG_ARRAY` slot on the active object.

# `map_dump`

Dumps all entries from a map on the active object via `MaeBPF.Map.dump/3`.

# `map_lookup`

Looks up a map entry by binary key on the currently active object.

# `map_lookup_batch`

Batch-reads up to `max_entries` entries from a map on the active object.

# `map_lookup_percpu`

Looks up a per-CPU map entry on the currently active object.

# `map_lookup_percpu_sum_u64`

Sums a per-CPU `u64` map entry directly in C on the currently active object.

# `map_lookup_prog_id`

Reads the kernel program ID stored in a `BPF_MAP_TYPE_PROG_ARRAY` slot.

# `map_put_cidr`

Inserts or updates an IPv4 CIDR entry in a `BPF_MAP_TYPE_LPM_TRIE` map on the
currently active object.

# `map_put_domain`

Inserts or updates an exact or wildcard domain entry in a reversed-FQDN
`LPM_TRIE` map (`type: :lpm_domain`) on the active object.

    :ok = MaeBPF.Server.map_put_domain(srv, "blocked_domains", "*.blocked.org")

# `map_put_prog`

Inserts a program into a `BPF_MAP_TYPE_PROG_ARRAY` tail-call slot on the
active object.

    :ok = MaeBPF.Server.map_put_prog(srv, "jump_table", 0, "tail_v2")

# `map_update`

Updates a map entry on the currently active object.

# `map_update_percpu`

Updates a per-CPU map entry on the currently active object.

# `prog_dump`

Dumps kernel `xlated` and `jited` bytecode for the active program (or the
named hook/program on a multi-hook server).

# `prog_fd`

Returns the loaded kernel program file descriptor for `prog_or_hook`
(defaults to the server's primary program).

# `put_global`

Updates a mutable (`.data` or `.bss`) global variable on the active object.
Rejects `.rodata` writes with `{:error, {:readonly_global, name, hint}}`.

    :ok = MaeBPF.Server.put_global(srv, :enabled, false)

# `read_iter`

Reads an attached BPF iterator link (`iter/`) via `bpf_iter_create`.

    {:ok, bin} = MaeBPF.Server.read_iter(srv, max_bytes: 1_048_576)

# `resolve_swap_mode`

```elixir
@spec resolve_swap_mode(atom(), atom(), term()) ::
  {:ok, :atomic | :overlap | :replace} | {:error, term()}
```

Resolves the effective hot-swap mode (`:atomic`, `:overlap`, or `:replace`)
given `strategy`, kernel `link_type`, and `attach_spec`.

Fails closed on `:atomic` when `MaeBPF.Link.supports_atomic_update?/1` is
`false`.

# `set_stats`

Enables or disables kernel `BPF_STATS_RUN_TIME` dynamically on a live server
without reloading or detaching the running program.

# `start`

Starts an unlinked `MaeBPF.Server`.

# `start_link`

Starts a linked `MaeBPF.Server`.

Options:
  * `:module` | `:ir` | `:elf` | `:pure_spec` | `:c` | `:c_source` - program
    source (required; `:c` / `:c_source` requires the optional `:maebpf_c`
    package)
  * `:program` - program function name for single-hook attach (defaults to
    first program in object)
  * `:attach` - single-hook attach spec: `{:xdp, ifname_or_index}` |
    `{:xdp, ifname_or_index, opts}` | `{:tcx, ifname_or_index, :ingress | :egress}`
    | `{:tcx, ifname_or_index, :ingress | :egress, opts}` |
    `{:tracepoint, category, name}` | `:none`
  * `:hooks` - multi-hook keyword list or map of `hook_name => attach_spec`
    (for example `[ingress: {:xdp, "veth0"}, egress: {:tcx, "veth0", :egress}]`)
  * `:source_map` - optional instruction-to-source map for verifier diagnostics
  * `:map_specs` - optional list or map of `%MaeBPF.Schema.MapSpec{}` used
    when migrating maps during `hot_swap/3`
  * `:ringbuf_map` - optional ringbuf map name to stream via `enif_select`
  * `:ringbuf_mode` - `:list` (default) or `:packed`
  * `:ringbuf_max_events` - max samples drained per NIF call (default `512`)
  * `:ringbuf_max_bytes` - byte soft-cap per `:packed` drain (default `262_144`)
  * `:on_event` - callback for drained events:
    - in `:list` mode: `fn(event_bin) -> any()` or `{pid, tag}` (sends `{tag, events}`)
    - in `:packed` mode: `fn(packed_bin) -> any()`, `fn(count, packed_bin) -> any()`,
      or `{pid, tag}` (sends `{tag, count, packed_bin}`)
  * `:enable_stats` - enable kernel `BPF_STATS_RUN_TIME` on start (default `false`)
  * `:pin_dir` - optional `/sys/fs/bpf/...` directory for pinning link(s) + maps
    and zero-packet-drop crash/restart adoption
  * `:reuse_maps` - map of `%{map_name => fd_or_source}` before load
  * `:open_opts` - map passed to `object_open_mem/2`
  * `:compile_opts` - keyword opts forwarded to the compiler
  * `:name` - optional GenServer registered name

# `status`

Returns live program, link, multi-hook, map, ringbuf, `ringbuf_drops`,
debug tracing, stats, pinning, and hot-swap telemetry.

# `stop`

Stops the server and releases local handles.

For unpinned servers this immediately detaches all kernel links and frees maps.
For pinned servers (`:pin_dir`), pinned kernel links and maps remain active
for takeover until `unpin_and_stop/1..2` is called.

# `undebug`

Disables live debug tracing, closes `"__maebpf_debug_rb"`, and atomically
swaps back to the zero-overhead production ELF reusing all live maps.

# `unpin_and_stop`

Unpins any pinned link(s) and maps under `:pin_dir`, removes the pin directory
if empty, and stops the server so the kernel detaches the links immediately.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
