Repository navigation
Expand file tree
/
Copy pathtutorial.html
More file actions
272 lines (231 loc) · 19.6 KB
/
Copy pathtutorial.html
File metadata and controls
272 lines (231 loc) · 19.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>チュートリアル — Pipeline Docs</title>
<meta name="description" content="Pipeline を初めて触る人向けのハンズオン。起動 → 最初のワークロード → 自作プラグイン → dispatcher→consumer パイプラインまでを手を動かして学びます。" />
<link rel="icon" type="image/x-icon" href="assets/favicon.ico" />
<link rel="icon" type="image/png" sizes="32x32" href="assets/icon-32.png" />
<link rel="stylesheet" href="assets/site.css" />
<link rel="stylesheet" href="assets/docs.css" />
<script>try{var t=localStorage.getItem('pipeline-docs-theme');if(t)document.documentElement.setAttribute('data-theme',t);}catch(e){}</script>
</head>
<body class="docs" data-page="tutorial">
<header class="docs-header">
<button class="icon-btn hamburger" aria-label="メニュー切替">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M3 6h18M3 12h18M3 18h18"/></svg>
</button>
<a class="brand" href="./"><img src="assets/icon-64.png" alt="" /><span class="brand-text">Pipeline</span><span class="brand-tag">Docs</span></a>
<div class="spacer"></div>
<div class="docs-search"><input type="text" id="docs-search-input" placeholder="ドキュメントを絞り込み ( / )" autocomplete="off" aria-label="検索" /></div>
<a class="hlink labelled" href="https://github.com/paps-jp/pipeline" target="_blank" rel="noopener" aria-label="GitHub">
<svg width="18" height="18" viewBox="0 0 16 16" fill="currentColor"><path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.76-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.01 8.01 0 0 0 16 8c0-4.42-3.58-8-8-8z"/></svg>
<span>GitHub</span>
</a>
<button class="icon-btn theme-toggle" aria-label="テーマ切替">
<svg class="sun" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"/></svg>
<svg class="moon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z"/></svg>
</button>
</header>
<div class="sb-backdrop"></div>
<div class="docs-layout">
<aside class="docs-sidebar" id="docs-sidebar"></aside>
<main class="docs-main">
<article class="docs-article">
<div class="docs-breadcrumb"><a href="manual.html">Docs</a> / はじめに / チュートリアル</div>
<h1>チュートリアル — 手を動かして理解する</h1>
<p class="lead">
このページは、Pipeline を初めて触るエンジニア向けのハンズオンです。制御プレーンの起動から、GUI と REST API での最初のジョブ実行、自作プラグインの作成、そして「dispatcher → consumer」という実運用の基本形までを、順に手を動かして体験します。所要 20〜30 分です。
</p>
<div class="callout">
<strong>前提:</strong> Python 3.12+ と、<a href="setup.html">セットアップ</a>で作った venv に <code>pip install -e .</code> 済みであること。まだなら先にセットアップを済ませてください。ここでは単一プロセス mode (SQLite 1ファイル) を使うので、GPU も外部 DB も不要です。
</div>
<h2>ステップ0: 全体像を掴む</h2>
<p>Pipeline の登場人物は3つだけです。まずこの関係を頭に入れると、以降の操作の意味が分かります。</p>
<ul>
<li><strong>制御プレーン</strong> — キューと Web UI/API を持つ司令塔。1プロセス。</li>
<li><strong>ワークロード</strong> — 「何をどう実行するか」の定義。専用のキュー (待ち行列) を1つ持ちます。</li>
<li><strong>ワーカー</strong> — キューからタスクを取り出して処理する実行役。制御プレーンに<em>取りに行く</em> pull 型です。</li>
</ul>
<pre><code>あなた / 外部システム / dispatcher
│ enqueue (タスク投入)
▼
┌───────────────┐ claim ┌──────────┐
│ ワークロード │ ───── タスク ─────▶ │ ワーカー │ → plugin.process()
│ のキュー │ ◀──── 結果 ──────── │ │
└───────────────┘ complete / fail └──────────┘</code></pre>
<p>「タスクをキューに入れる」→「ワーカーが取り出して処理する」→「結果が run として残る」。この1往復がすべての基本です。</p>
<h2>ステップ1: 起動して画面を見る</h2>
<pre><code>pipeline run --dev</code></pre>
<p>次のようなバナーが出て、ワンタイムの管理者パスワードが表示されます。</p>
<pre><code> Pipeline (dev) → http://localhost:8000
DB: sqlite:///./pipeline.db
admin password: xxxxxxxxxxxxxxxx (この起動限り)</code></pre>
<p>ブラウザで <code>http://localhost:8000</code> を開きます。<strong>ダッシュボード</strong>が表示され、「稼働ワーカー / 最近の失敗 / キュー深さ」の3パネルは空です (まだ何も無いので正常)。<code>--dev</code> は制御プレーンと同じプロセスの中にワーカーを1つ同居させるので、この後すぐタスクを処理できます。</p>
<h2>ステップ2: GUI で最初のワークロードを作る</h2>
<p>同梱の <code>echo-sample</code> プラグイン (受け取った pk と extra をそのまま返すだけ) を使います。</p>
<ol>
<li>左メニュー <strong>ワークロード</strong> → <strong>新規作成</strong>。</li>
<li><strong>slug</strong>: <code>echo-test</code> / <strong>表示名</strong>: <code>Echoテスト</code>。</li>
<li><strong>実行モード</strong>: <code>python_module</code>。</li>
<li><strong>プラグイン</strong>: <code>echo-sample</code> / <strong>モジュール</strong>: <code>main</code>。</li>
<li>フォームに <code>prefix</code> / <code>sleep_secs</code> / <code>fail_pk_substr</code> が出ます (これが plugin.yaml の <code>init_kwargs</code>)。既定のまま <strong>作成</strong>。</li>
<li>一覧に <code>echo-test</code> が出たら、enabled トグルが ON になっていることを確認します。</li>
</ol>
<p>次に <strong>📨 投入</strong> アイコンで、pk に <code>hello</code>、extra に <code>{"foo": "bar"}</code> を入れて投入します。数秒後、同じ行の <strong>履歴</strong> アイコンを開くと、run が緑 (success) で並び、展開すると <code>output_json</code> に <code>echoed</code> が入っているのが見えます。</p>
<div class="callout">
いま起きたこと: 投入で <code>echo_test_queue</code> テーブルに1行 (<code>pending</code>) が入り、同居ワーカーがそれを <code>claim</code> し、<code>echo_sample.process()</code> を呼び、戻り dict を <code>runs</code> に記録して行を消しました。これが<a href="concepts.html#タスクのライフサイクル">ライフサイクル</a>の一巡です。
</div>
<h2>ステップ3: 同じことを REST API で</h2>
<p>GUI でできることは全て HTTP API でもできます。CI やバッチ、外部システムからの投入はこちらを使います。</p>
<pre><code># タスクを1件投入
curl -X POST http://localhost:8000/api/v1/workloads/echo-test/tasks \
-H "Content-Type: application/json" \
-d '{"pk": "hello-2", "extra": {"foo": "bar"}}'
# 直近の run を確認
curl "http://localhost:8000/api/v1/workloads/echo-test/runs?limit=3"
# キューの深さ (pending / claimed / failed) を確認
curl http://localhost:8000/api/v1/workloads/echo-test/queue</code></pre>
<p>より詳しい request/response は <a href="rest-api.html">REST API リファレンス</a>にまとめてあります。ブラウザで <code>http://localhost:8000/docs</code> を開けば Swagger UI で全エンドポイントを対話的に叩けます。</p>
<h2>ステップ4: 自作プラグインを書く</h2>
<p>ここが本番です。「URL を受け取り、HTTP GET してステータスとサイズを返す」プラグインを、空のディレクトリから作ります。外部依存を避けるため標準ライブラリ (<code>urllib</code>) だけで書きます。</p>
<h3>4-1. ファイルを置く</h3>
<p>プラグインルート (dev では <code>./plugins/</code>、本番は <code>PIPELINE_PLUGIN_ROOT</code> = 既定 <code>/opt/pipeline/plugins</code>) に新しいディレクトリを作ります。</p>
<pre><code>plugins/
url_check/
plugin.yaml
main.py</code></pre>
<p><strong>plugins/url_check/plugin.yaml</strong></p>
<pre><code>name: url-check
description: |
extra.url (無ければ pk) を HTTP GET し、ステータスコードとバイト数を返す。
タイムアウトやDNSエラーは例外にして Pipeline のリトライに任せる。
init_kwargs:
- key: timeout_secs
type: float
default: 10
label: HTTP timeout
min: 1
max: 120
- key: user_agent
type: str
default: pipeline-url-check/1.0
label: User-Agent</code></pre>
<p><strong>plugins/url_check/main.py</strong></p>
<pre><code>from __future__ import annotations
import time
import urllib.request
from typing import Any
def setup(**kwargs: Any) -> dict[str, Any]:
# プロセス起動時に1回。ここで作った dict が以降 state として渡る。
return {
"timeout": float(kwargs.get("timeout_secs", 10)),
"ua": str(kwargs.get("user_agent", "pipeline-url-check/1.0")),
}
def process(task: Any, ctx: Any, state: Any) -> dict[str, Any]:
# 1タスク = 1 URL。url は extra 優先、無ければ pk を URL とみなす。
url = (task.extra or {}).get("url") or task.pk
req = urllib.request.Request(url, headers={"User-Agent": state["ua"]})
t0 = time.monotonic()
# 例外 (タイムアウト/DNS/接続拒否) は握らずに送出 → fail 扱いになり自動リトライ。
with urllib.request.urlopen(req, timeout=state["timeout"]) as resp:
body = resp.read()
elapsed_ms = round((time.monotonic() - t0) * 1000)
# 4xx/5xx を「失敗」にしたいなら、例外を投げず _error を返すのが定石。
if resp.status >= 400:
return {"_error": f"HTTP {resp.status} for {url}"}
# 成功: dict を返すと runs.output_json に保存される。
return {"url": url, "status": resp.status, "bytes": len(body), "elapsed_ms": elapsed_ms}
def cleanup(state: Any) -> None:
# 今回は解放するものが無い。接続プールやファイルを持つならここで閉じる。
pass</code></pre>
<h3>4-2. ワークロードとして登録する</h3>
<p>UI を再読み込みすると、プラグインドロップダウンに <code>url-check</code> が出ます (制御プレーンが <code>plugins/</code> を走査するため)。ステップ2と同じ手順で、slug <code>url-check</code> / 実行モード <code>python_module</code> / プラグイン <code>url-check</code> / モジュール <code>main</code> で作成します。</p>
<h3>4-3. 動かす</h3>
<pre><code>curl -X POST http://localhost:8000/api/v1/workloads/url-check/tasks \
-H "Content-Type: application/json" \
-d '{"pk": "https://example.com", "extra": {}}'
curl "http://localhost:8000/api/v1/workloads/url-check/runs?limit=1"
# → output_json: {"url":"https://example.com","status":200,"bytes":1256,"elapsed_ms":83}</code></pre>
<p>わざと失敗させて、リトライと dead-letter も見てみましょう。到達できない URL を投げると、<code>process()</code> が例外を送出 → <code>failed</code> になり、<code>max_attempts</code> (既定5) まで自動で再試行され、上限で dead-letter として残ります。RunsDrawer で traceback が、Dashboard のキュー深さで <code>failed</code> 件数が確認できます。</p>
<div class="callout warn">
<strong>開発ループの注意:</strong> <code>process()</code> の実体は<strong>ワーカープロセス内にキャッシュ</strong>されます (重い <code>setup()</code> を毎回走らせないため)。コードを直したら<strong>ワーカーを再起動</strong>してください。dev mode なら <code>pipeline run --dev</code> を Ctrl-C して起動し直すだけ。本番は該当ホストの worker を restart します (<a href="operations.html#アップデート">運用Tips</a>)。
</div>
<h2>ステップ5: プラグインをローカルで単体テストする</h2>
<p>fleet に載せる前に、<code>process()</code> は普通の Python 関数として単体で叩けます。素早い反復に便利です。</p>
<pre><code># plugins/url_check/ で
python3 - <<'PY'
from types import SimpleNamespace
import main
state = main.setup(timeout_secs=5)
task = SimpleNamespace(pk="https://example.com", extra={}, attempt=1, workload_slug="url-check")
ctx = SimpleNamespace(deadline=None, workdir="/tmp", env={}, workload_config={})
print(main.process(task, ctx, state))
main.cleanup(state)
PY</code></pre>
<p><code>task</code> / <code>ctx</code> は本番では専用オブジェクトですが、<code>process()</code> が参照する属性 (<code>pk</code> / <code>extra</code> / <code>attempt</code> と、必要なら <code>ctx.deadline</code> 等) を持つダミーで十分です。<a href="plugin-sdk.html#task-ctx-戻り値">属性一覧</a>を参照してください。</p>
<h2 id="step6-pipeline">ステップ6: 本物のパイプライン — dispatcher → consumer</h2>
<p>ここまではタスクを手 (curl/UI) で入れていました。実運用では、<strong>タスクを生成し続ける仕掛け</strong>が要ります。Pipeline の定石は次の2段構成です。</p>
<ul>
<li><strong>dispatcher</strong> — 上流 (フィード / DB / ディレクトリ / 外部 API) を定期的に見て、<em>新しく処理すべき対象</em>を下流ワークロードのキューへ <code>tasks/batch</code> で流し込む。ループし続けるので <code>self_loop</code> 型で作ります。</li>
<li><strong>consumer</strong> — 流れてきたタスクを1件ずつ <code>process()</code> する、ステップ4のような per-task プラグイン。</li>
</ul>
<pre><code>┌──────────┐ fetch ┌─────────────┐ tasks/batch ┌──────────────┐ process()
│ 上流ソース │ ─────────▶ │ dispatcher │ ─────────────▶ │ consumer │ ───────────▶ 結果
│ (feed/DB…) │ │ (self_loop) │ 下流キューへ │ (per-task) │
└──────────┘ └─────────────┘ enqueue └──────────────┘</code></pre>
<p>dispatcher の心臓部は、下流キューへの batch enqueue と、自分の次 tick の self-enqueue です。</p>
<pre><code>import json, urllib.request
def _post_json(url, payload):
req = urllib.request.Request(
url, data=json.dumps(payload).encode(),
headers={"Content-Type": "application/json"}, method="POST")
urllib.request.urlopen(req, timeout=15).read()
def process(task, ctx, state):
control = state["control_url"] # 例: http://localhost:8000
target = state["target_workload"] # 下流 consumer の slug
new_urls = discover_new_urls() # 上流を見て新規対象を集める (dedupは自前)
items = [{"pk": u, "extra": {}} for u in new_urls]
if items:
_post_json(f"{control}/api/v1/workloads/{target}/tasks/batch", {"items": items})
time.sleep(state["interval_s"]) # 次サイクルまで待つ
# 自分の次 tick を self-enqueue してループを継続 (これを忘れるとループが止まる)
_post_json(f"{control}/api/v1/workloads/{state['workload_slug']}/tasks",
{"pk": f"tick-{state['counter']+1}"})
return {"enqueued": len(items)}</code></pre>
<p>実際に動く完全な実装は同梱の <a href="https://github.com/paps-jp/pipeline/tree/main/examples/plugins/rss_news_dispatcher"><code>examples/plugins/rss_news_dispatcher/</code></a> (RSS を集めて <code>rss-news-summarize</code> に流す) が参考になります。self_loop の詳細・watchdog・singleton 化は <a href="plugin-sdk.html#self-loop">プラグインSDK</a>で解説しています。</p>
<div class="callout">
<strong>なぜ2段に分けるのか:</strong> 「対象の発見 (I/O・低頻度)」と「重い処理 (GPU・高並列)」を別ワークロードにすると、後者だけを worker 追加で水平スケールでき、優先度も別々に付けられます。dispatcher は1台に固定 (<code>max_concurrent_total: 1</code>)、consumer は GPU ホストに複数、という配置が典型です。
</div>
<h2>次のステップ</h2>
<div class="feature-grid">
<a class="feature-card" href="plugin-sdk.html" style="text-decoration:none">
<div class="icon">⚙</div><h3>プラグインSDK 詳解</h3>
<p>契約の全体・戻り値の意味・バッチ処理・self_loop・モジュール解決の内部。</p>
</a>
<a class="feature-card" href="concepts.html#タスクはどうやってキューに入るか" style="text-decoration:none">
<div class="icon">◆</div><h3>タスクの入り方</h3>
<p>手動 / 外部 POST / dispatcher の3経路と、pull 型の理由。</p>
</a>
<a class="feature-card" href="configuration.html#workload-のフィールド" style="text-decoration:none">
<div class="icon">⚑</div><h3>ワークロード設定</h3>
<p>priority / batch_size / lease / 同時実行上限 などの意味と既定。</p>
</a>
<a class="feature-card" href="operations.html#トラブルシューティング" style="text-decoration:none">
<div class="icon">✚</div><h3>トラブルシューティング</h3>
<p>claim されない / タスクが詰まる / import エラー等の対処。</p>
</a>
</div>
<nav class="docs-pager" id="docs-pager"></nav>
<div class="docs-foot">
<span>Pipeline — GUI-first batch fleet · <a href="https://paps-jp.github.io/" target="_blank" rel="noopener">ぱっぷすラボ</a></span>
<span><a href="https://github.com/paps-jp/pipeline">GitHub</a> · <a href="./">ホーム</a></span>
</div>
</article>
</main>
<aside class="docs-toc" id="docs-toc"></aside>
</div>
<script src="assets/docs.js" defer></script>
</body>
</html>