The program
The greeter answers one question, greeter.hello, with a greeting for the name it is sent. It is one
file in each language, and it does what every Plugin does in the same order: it declares itself, starts,
says how it is, answers what it is sent, and closes its Session when it is asked to stop. It replaces
the program the template wrote in plugin/; in Python, the file is the one you made by hand.
- Go
- Rust
- Python
- C
- C++
// Command greeter is a Plugin that answers one question: who it is greeting.
package main
import (
"context"
"fmt"
"os"
"os/signal"
"syscall"
"github.com/yoke-project/yoke-sdk-go/plugin"
)
func declaration() plugin.Declaration {
return plugin.Declaration{
ID: "com.example.greeter",
Queries: []string{"greeter.hello"},
Capabilities: []plugin.Capability{
{Name: "query.hello.answer", Governs: plugin.Object{Query: "greeter.hello"}},
},
}
}
func main() {
// The Manifest is generated from the declaration, so the two cannot disagree.
if len(os.Args) == 2 && os.Args[1] == "--manifest" {
os.Stdout.Write(declaration().Manifest())
return
}
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)
defer stop()
u, err := plugin.Start(ctx, declaration())
if err != nil {
fmt.Fprintln(os.Stderr, "greeter:", err)
os.Exit(1)
}
u.Health(0, "ready to greet")
for {
select {
case event, open := <-u.Events():
if !open {
return
}
if q, ok := event.(plugin.Question); ok && q.Type == "greeter.hello" {
u.Answer(q, []byte("hello, "+string(q.Payload)))
}
case <-ctx.Done():
// Asked to stop: close the Session in order, and leave once it has ended.
u.Close()
<-u.Done()
return
}
}
}
//! greeter: a Plugin that answers one question, who it is greeting.
use tokio::signal::unix::{SignalKind, signal};
use yoke_sdk::plugin::{Capability, Declaration, Event, Object, start};
fn declaration() -> Declaration {
Declaration {
id: "com.example.greeter".into(),
queries: vec!["greeter.hello".into()],
capabilities: vec![Capability {
name: "query.hello.answer".into(),
governs: Object::Query("greeter.hello".into()),
}],
..Default::default()
}
}
#[tokio::main]
async fn main() {
// The Manifest is generated from the declaration, so the two cannot disagree.
if std::env::args().nth(1).as_deref() == Some("--manifest") {
print!("{}", declaration().manifest());
return;
}
let unit = match start(&declaration()).await {
Ok(unit) => unit,
Err(err) => {
eprintln!("greeter: {err}");
std::process::exit(1);
}
};
let _ = unit.health(0, "ready to greet").await;
let mut term = signal(SignalKind::terminate()).expect("greeter listens for SIGTERM");
loop {
tokio::select! {
event = unit.next() => match event {
None | Some(Event::Ended(_)) => return,
Some(Event::Question(q)) if q.r#type == "greeter.hello" => {
let mut answer = b"hello, ".to_vec();
answer.extend_from_slice(&q.payload);
let _ = unit.answer(&q, answer).await;
}
Some(_) => {}
},
_ = term.recv() => {
// Asked to stop: close the Session in order, and leave once it has ended.
let _ = unit.close().await;
while let Some(event) = unit.next().await {
if matches!(event, Event::Ended(_)) {
break;
}
}
return;
}
}
}
}
"""greeter: a Plugin that answers one question, who it is greeting."""
import asyncio
import signal
import sys
from yoke_sdk import base, plugin
def declaration():
return plugin.Declaration(
id="com.example.greeter",
queries=["greeter.hello"],
capabilities=[
plugin.Capability("query.hello.answer", plugin.Object(query="greeter.hello")),
],
)
async def run():
unit = await plugin.start(declaration())
await unit.health(0, "ready to greet")
stopping = asyncio.Event()
asyncio.get_running_loop().add_signal_handler(signal.SIGTERM, stopping.set)
asked = asyncio.create_task(stopping.wait())
while True:
following = asyncio.create_task(unit.next())
done, _ = await asyncio.wait({following, asked}, return_when=asyncio.FIRST_COMPLETED)
if following in done:
event = following.result()
if event is None or isinstance(event, plugin.Ended):
return
if isinstance(event, plugin.Question) and event.type == "greeter.hello":
await unit.answer(event, b"hello, " + event.payload)
continue
# Asked to stop: close the Session in order, and leave once it has ended.
following.cancel()
await unit.close()
while (event := await unit.next()) is not None and not isinstance(event, plugin.Ended):
pass
return
def main():
# The Manifest is generated from the declaration, so the two cannot disagree.
if sys.argv[1:] == ["--manifest"]:
sys.stdout.write(declaration().manifest())
return
try:
asyncio.run(run())
except base.Error as err:
print("greeter:", err, file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()
/* greeter: a Plugin that answers one question, who it is greeting. */
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <yoke/plugin.h>
static const char *const queries[] = {"greeter.hello", NULL};
static const yoke_capability capabilities[] = {
{.name = "query.hello.answer", .governs = {YOKE_GOVERNS_QUERY, "greeter.hello"}},
{0},
};
static const yoke_declaration declaration = {
.id = "com.example.greeter",
.queries = queries,
.capabilities = capabilities,
};
static volatile sig_atomic_t stopping;
static void on_term(int sig) { (void)sig; stopping = 1; }
static void answer(yoke_unit *unit, const yoke_event *q) {
static const char hello[] = "hello, ";
size_t len = sizeof hello - 1 + q->payload_len;
char *text = malloc(len);
memcpy(text, hello, sizeof hello - 1);
memcpy(text + sizeof hello - 1, q->payload, q->payload_len);
yoke_error err = {0};
if (yoke_answer(unit, q, text, len, &err) != 0) {
fprintf(stderr, "greeter: %s\n", err.message);
yoke_error_clear(&err);
}
free(text);
}
int main(int argc, char **argv) {
/* The Manifest is generated from the declaration, so the two cannot disagree. */
if (argc == 2 && strcmp(argv[1], "--manifest") == 0) {
char *manifest = yoke_manifest(&declaration);
fputs(manifest, stdout);
free(manifest);
return 0;
}
signal(SIGTERM, on_term);
yoke_error err = {0};
yoke_unit *unit = yoke_start(&declaration, &err);
if (unit == NULL) {
fprintf(stderr, "greeter: %s\n", err.message);
yoke_error_clear(&err);
return 1;
}
yoke_health(unit, 0, "ready to greet", &err);
yoke_event event = {0};
while (!stopping) {
int got = yoke_next_within(unit, &event, 200);
if (got == 0)
break; /* the Session has ended */
if (got == 1 && event.kind == YOKE_QUESTION && strcmp(event.type, "greeter.hello") == 0)
answer(unit, &event);
if (got == 1)
yoke_event_clear(&event);
}
if (stopping) {
/* Asked to stop: close the Session in order, and leave once it has ended. */
yoke_close(unit, &err);
while (yoke_next(unit, &event) == 1)
yoke_event_clear(&event);
}
yoke_free(unit);
return 0;
}
// greeter: a Plugin that answers one question, who it is greeting.
#include <atomic>
#include <chrono>
#include <csignal>
#include <iostream>
#include <string_view>
#include <variant>
#include <yoke/base.hpp>
#include <yoke/plugin.hpp>
using namespace yoke::plugin;
Declaration declaration() {
return {
.id = "com.example.greeter",
.queries = {"greeter.hello"},
.capabilities = {{"query.hello.answer", {Governs::query, "greeter.hello"}}},
};
}
static std::atomic<bool> stopping;
int main(int argc, char **argv) {
// The Manifest is generated from the declaration, so the two cannot disagree.
if (argc == 2 && std::string_view(argv[1]) == "--manifest") {
std::cout << declaration().manifest();
return 0;
}
std::signal(SIGTERM, [](int) { stopping = true; });
try {
auto unit = Unit::start(declaration());
unit->health(0, "ready to greet");
while (!stopping && !unit->done()) {
auto event = unit->next(std::chrono::milliseconds(200));
if (!event)
continue;
if (auto *q = std::get_if<Question>(&*event); q && q->type == "greeter.hello")
unit->answer(*q, "hello, " + q->payload);
}
if (stopping) {
// Asked to stop: close the Session in order, and leave once it has ended.
unit->close();
while (unit->next()) {
}
}
} catch (const std::exception &err) {
std::cerr << "greeter: " << err.what() << '\n';
return 1;
}
}
What each part does
The five programs are made of the same parts, named the way each language names things:
| Part | What it does |
|---|---|
| the declaration | the identity, the question the Plugin answers, and the capability that governs it. Everything a Plugin may be asked or may send is declared, and each object is governed by exactly one capability (the Manifest, capabilities) |
--manifest | prints the Manifest the declaration generates. The program is the only source of it, so the file shipped beside the program cannot disagree with what the program registers |
| the start | reads what the Core handed the process at launch, binds the unit's own socket, registers, and opens the Session. A refusal is returned or thrown, and nothing is tried again (what a unit arrives with, admission) |
| the first health report | a grade on the scale an event's severity uses, 0 to 99 and higher more serious, and a line for a person. The library repeats the last report at every beat and sends none before the first, so a Plugin that never reports loses its liveness and is ended (the families) |
| the events | what the Core sends, in the order it sent it: a question to answer, a command to acknowledge, a stream to start or stop, a refusal, and the end of the Session |
| the answer | correlated to its question by the library. The payload is the Plugin's own bytes: the Core carries it and never reads it |
| the close | on SIGTERM, the Core's way of asking a unit to stop: the Plugin closes the Session, waits for its end, and exits. A unit still running when the deployment's stop window has passed is killed (the Session) |
What a Plugin does not do is as deliberate. It does not choose its socket, retry a refused start, reconnect, or grant itself anything. The library does the order the contract requires — binding before registering, the heartbeat, the end of the Session — so the program holds only the declaration and what to do with each event.
A Plugin started by hand is not admitted. It has no token, because the Core did not launch it, and the start fails. It runs under a Core, as the next page shows.
Build it, and keep its Manifest
From greeter/, the composer runs the build yoke-plugin.yaml states, for this machine's
architecture unless --arch names another, and leaves the executable in build/<arch>/:
- Go
- Rust
- Python
- C
- C++
yoke-compose build
build/x86_64/greeter --manifest > plugin/com.example.greeter.yaml
build/x86_64/greeter
The executable depends on nothing on the host: the template builds it with CGO_ENABLED=0, linked
statically.
yoke-compose build
build/x86_64/greeter --manifest > plugin/com.example.greeter.yaml
The executable links the host's C library dynamically, as Rust does by default.
By hand, from the Plugin's directory. The Core launches a file, not an interpreter with arguments, so a Python Plugin needs a small launcher: one executable file that starts the program under its environment's interpreter.
printf '#!/bin/sh\nexec %s -I %s "$@"\n' "$PWD/.venv/bin/python" "$PWD/greeter.py" > greeter
chmod +x greeter
./greeter --manifest > com.example.greeter.yaml
The executable is the launcher, greeter. It names the environment by its absolute path, so it runs
on this machine only; handing it on says what that means.
yoke-compose build
build/x86_64/greeter --manifest > plugin/com.example.greeter.yaml
The library is linked statically, and gRPC, protobuf-c and OpenSSL dynamically: the host that runs it needs their runtime libraries.
yoke-compose build
build/x86_64/greeter --manifest > plugin/com.example.greeter.yaml
The library is linked statically, and gRPC, protobuf and OpenSSL dynamically: the host that runs it needs their runtime libraries.
The build runs where build.in says, with what yoke-plugin.yaml states and nothing else of the
composer's: the architecture, the language's own name for it, and $YOKE_OUT, where the program is
written. Building for another architecture than this machine's is the language's own business — Go and
Rust cross-compile; C and C++ need a CMake toolchain file — and a build that cannot refuses rather than
write the wrong program.
The Manifest is kept in the source, beside the program. It is what the program prints, written
again whenever the declaration changes. Kept there, it can be read before anything is built — by you,
by whoever takes the Plugin, by the operator who grants it — and the template's continuous integration,
.github/workflows/manifest.yml, builds the program at every change, has it print its Manifest and
fails where it differs from the one kept.
Every family writes the same Manifest. The YAML is spelled slightly differently — how far a list is indented, whether a string is quoted — and it says the same thing:
manifest: 1
id: com.example.greeter
protocol: 1
queries:
- id: greeter.hello
capabilities:
- name: query.hello.answer
governs:
query: greeter.hello
The executable and the Manifest are the Plugin. Every way of running it, or of handing it to somebody, starts from these two files.
The same, by hand
Without the composer, the program is built in its own directory, with the language's own tools,
and its Manifest written beside it. The files are where the end of starting it put
them: main.go, src/main.rs, greeter.c and greeter.cpp at the directory's root rather than under
plugin/.
- Go
- Rust
- Python
- C
- C++
go mod tidy
CGO_ENABLED=0 go build -o greeter .
./greeter --manifest > com.example.greeter.yaml
The executable is greeter, and it depends on nothing on the host: with CGO_ENABLED=0 it is linked
statically.
cargo build --release
./target/release/greeter --manifest > com.example.greeter.yaml
The executable is target/release/greeter. It links the host's C library dynamically, as Rust does by
default.
The Core launches a file, not an interpreter with arguments, so a Python Plugin needs a small launcher: one executable file that starts the program under its environment's interpreter.
printf '#!/bin/sh\nexec %s -I %s "$@"\n' "$PWD/.venv/bin/python" "$PWD/greeter.py" > greeter
chmod +x greeter
./greeter --manifest > com.example.greeter.yaml
The executable is the launcher, greeter. It names the environment by its absolute path, so it runs
on this machine only; handing it on says what that means.
cmake -S . -B build -DCMAKE_PREFIX_PATH="$HOME/.local"
cmake --build build
./build/greeter --manifest > com.example.greeter.yaml
The executable is build/greeter. The library is linked statically, and gRPC, protobuf-c and OpenSSL
dynamically: the host that runs it needs their runtime libraries.
cmake -S . -B build -DCMAKE_PREFIX_PATH="$HOME/.local"
cmake --build build
./build/greeter --manifest > com.example.greeter.yaml
The executable is build/greeter. The library is linked statically, and gRPC, protobuf and OpenSSL
dynamically: the host that runs it needs their runtime libraries.