Go と MinIO による並行ファイル同期
Go のワーカーを五つ使い、MinIO バケットをローカルディレクトリにダウンロードします。このサンプルでは階層パスを保持し、既存のコピーを置き換える前に各ファイルを一時保存します。転送に失敗した場合や Ctrl+C を押した場合はエラーを返します。これは一方向のダウンローダーです。実行のたびにすべてのオブジェクトを再ダウンロードし、リモートで削除してもローカルファイルは削除しません。
MinIO サーバーのセットアップ
大文字と小文字を区別するローカルファイルシステムを備えた Linux 上で Bash を使用します。Go 1.26.8 を PATH に配置し、curl と diff をインストールしておきます。この手順は Go 1.26.8 と MinIO Go SDK v7.0.95 でテスト済みです。ポート 9000 と 9001 が空いている必要があります。
2026年10月3日現在、MinIO コミュニティリポジトリはアーカイブされており、メンテナンスは終了しています。コミュニティ版の配布はソースのみです。以下のバージョンを固定したサーバーは、分離されたローカルの学習用環境であり、新規の本番デプロイに推奨するものではありません。バージョン未固定のコンテナイメージではなく、そのリリース向けにMinIO が公開しているソースからのインストール手順を使用します。
新しい minio-sync ディレクトリを作成したい場所で、以下をシェルに貼り付けます。サブシェルを使うため、現在のディレクトリとシェルオプションは変更されません。作成先がすでに存在する場合は、インストール前にセットアップが停止します。サーバーのビルドには数分かかることがあります。
(
set -e
mkdir minio-sync
cd minio-sync
GOBIN="$PWD/bin" GOWORK=off GOTOOLCHAIN=local \
go install github.com/minio/minio@RELEASE.2025-10-15T17-29-55Z
)
そのターミナルでサーバーを起動し、実行したままにします。
(
cd minio-sync &&
MINIO_ROOT_USER=minioadmin MINIO_ROOT_PASSWORD=minioadmin \
./bin/minio server ./data --address 127.0.0.1:9000 --console-address 127.0.0.1:9001
)
両方のリスナーはループバックにバインドします。これらの周知の認証情報と平文 HTTP は、この非公開のサンドボックス内でのみ使用してください。終了時には、このターミナルで Ctrl+C を押します。サーバーは停止しますが、data ディレクトリは残り、次回の実行に利用できます。
プロジェクトの初期化
別のターミナルで、同じ親ディレクトリから作業を始めます。準備が整ったことを確認してから、モジュールを初期化し、バージョンを固定した SDK をインストールします。GOWORK=off により、上位の Go ワークスペースがサンプルのモジュール選択を変更するのを防ぎます。
(
set -e
curl -fsS http://127.0.0.1:9000/minio/health/ready
cd minio-sync
GOWORK=off GOTOOLCHAIN=local go mod init minio-sync
GOWORK=off GOTOOLCHAIN=local go get github.com/minio/minio-go/v7@v7.0.95
)
バケットへのデータ投入
minio-sync/_seed/ を作成し、以下を _seed/main.go として保存します。このコードは既知の入力ファイルを sample-input/ に書き込み、my-sync-bucket にアップロードします。内訳はテキストファイル 300 個、階層下のテキストファイル一つ、空ファイル一つ、バイナリファイル一つです。アンダースコア付きのディレクトリにより、この独立した実行プログラムをメインパッケージから分離します。
// _seed/main.go
package main
import (
"context"
"fmt"
"log"
"os"
"path/filepath"
"time"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
)
func main() {
if err := seed(); err != nil {
log.Fatal(err)
}
log.Println("Uploaded 303 sample objects")
}
func seed() error {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
client, err := minio.New("localhost:9000", &minio.Options{
Creds: credentials.NewStaticV4("minioadmin", "minioadmin", ""),
Secure: false,
})
if err != nil {
return err
}
const bucket = "my-sync-bucket"
exists, err := client.BucketExists(ctx, bucket)
if err != nil {
return err
}
if !exists {
if err := client.MakeBucket(ctx, bucket, minio.MakeBucketOptions{}); err != nil {
return err
}
}
files := map[string][]byte{
"notes/hello.txt": []byte("Hello from MinIO\n"),
"empty.bin": {},
"binary.bin": {0, 255, 128, 13, 10, 42, 0, 10},
}
for i := 0; i < 300; i++ {
files[fmt.Sprintf("logs/object-%03d.txt", i)] = []byte(fmt.Sprintf("object %d\n", i))
}
for key, body := range files {
filename := filepath.Join("sample-input", filepath.FromSlash(key))
if err := os.MkdirAll(filepath.Dir(filename), 0o700); err != nil {
return err
}
if err := os.WriteFile(filename, body, 0o600); err != nil {
return err
}
if _, err := client.FPutObject(ctx, bucket, key, filename, minio.PutObjectOptions{}); err != nil {
return fmt.Errorf("upload %q: %w", key, err)
}
}
return nil
}
親ディレクトリから初期データ投入プログラムを実行します。
(
cd minio-sync &&
GOWORK=off GOTOOLCHAIN=local go run ./_seed
)
Uploaded 303 sample objects と表示されます。再実行すると、これらのサンプルキーと入力ファイルを置き換えるため、この専用サーバーとディレクトリでのみ使用してください。ダウンロード中および結果の比較中は、サーバーのデータと
sample-input/ を変更しないでください。
MinIO クライアントのセットアップ
以下を minio-sync/client.go として保存します。ローカルサーバーは HTTP を使うため、useSSL は
false です。トランスポートの TLS 最小バージョン設定が有効になるのは、useSSL が true で、エンドポイントが HTTPS を提供する場合だけです。ダウンロードを開始するには、BucketExists が真の値を返し、かつエラーを返さない必要があります。
// client.go
package main
import (
"context"
"crypto/tls"
"fmt"
"net/http"
"time"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
)
// bucketName matches the bucket populated by _seed/main.go.
const bucketName = "my-sync-bucket"
func createMinioClient(ctx context.Context) (*minio.Client, error) {
endpoint := "localhost:9000"
accessKeyID := "minioadmin" // Use environment variables in production
secretAccessKey := "minioadmin" // Use environment variables in production
useSSL := false // true once your endpoint terminates TLS
// Only exercised when useSSL is true
transport := &http.Transport{
TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS12},
IdleConnTimeout: 90 * time.Second,
}
// Initialize minio client
opts := &minio.Options{
Creds: credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
Secure: useSSL,
Transport: transport,
}
client, err := minio.New(endpoint, opts)
if err != nil {
return nil, err
}
// BucketExists reports a bucket that is simply absent as (false, nil), so the boolean
// has to be checked too. Ignoring it turns a typo in the bucket name into a sync that
// quietly downloads nothing.
exists, err := client.BucketExists(ctx, bucketName)
if err != nil {
return nil, fmt.Errorf("failed to reach bucket %q: %w", bucketName, err)
}
if !exists {
return nil, fmt.Errorf("bucket %q does not exist", bucketName)
}
return client, nil
}
並行ファイルダウンロードの実装
以下を minio-sync/sync.go として保存します。五つのワーカーがタスクを読み込み、別の goroutine が結果を取り出し続けます。一覧取得が終わるまで結果の取り出しを待つと、チャネルバッファより大きいバケットではデッドロックが発生します。各オブジェクトには 10 分のタイムアウトを設定します。エラーを集計し、最終的な診断メッセージには最初にエラーになったオブジェクトのキーを含めます。
SDK の GetObject リファレンスには、エラーはストリームの読み取り時に発生することが多いと説明されています。そのため、io.Copy の確認は
GetObject の確認と同じくらい重要です。転送に失敗すると、その一時ファイルは削除され、以前に完了したコピーはそのまま残ります。
// sync.go
package main
import (
"context"
"fmt"
"io"
"os"
"path"
"path/filepath"
"strings"
"sync"
"time"
"github.com/minio/minio-go/v7"
)
type DownloadResult struct {
ObjectName string
Error error
}
func downloadFiles(ctx context.Context, client *minio.Client, bucketName string, outputDir string) error {
// 0700, because these are private copies. The process umask would otherwise usually
// leave them group- and world-readable.
if err := os.MkdirAll(outputDir, 0o700); err != nil {
return fmt.Errorf("failed to create output directory: %w", err)
}
// Resolve the directory once so the per-object checks below compare against a path
// that has no symlinks left in it.
root, err := filepath.EvalSymlinks(outputDir)
if err != nil {
return fmt.Errorf("failed to resolve output directory: %w", err)
}
// Cancelling here unblocks every worker if we bail out early
ctx, cancel := context.WithCancel(ctx)
defer cancel()
jobs := make(chan string, 100)
results := make(chan DownloadResult, 100)
var wg sync.WaitGroup
workerCount := 5
// Start workers
for i := 0; i < workerCount; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for objectName := range jobs {
err := downloadObject(ctx, client, bucketName, objectName, root)
select {
case results <- DownloadResult{ObjectName: objectName, Error: err}:
case <-ctx.Done():
return
}
}
}()
}
go func() {
wg.Wait()
close(results)
}()
// Collect results while the producer is still queueing. Draining only after
// close(jobs) deadlocks as soon as the buffers fill: workers block on
// `results <-`, stop reading `jobs`, and the producer blocks on `jobs <-`.
//
// Only a count and the first error are kept. A bucket can hold millions of objects,
// and appending every failure to a slice would grow without bound in exactly the run
// where things are going worst.
type failures struct {
count int
first error
}
collected := make(chan failures, 1)
go func() {
var seen failures
for result := range results {
if result.Error == nil {
continue
}
seen.count++
if seen.first == nil {
seen.first = fmt.Errorf("%s: %w", result.ObjectName, result.Error)
}
}
collected <- seen
}()
// List and queue objects. The deferred close lets the workers drain and exit
// on every path, including the early returns below.
listErr := func() error {
defer close(jobs)
opts := minio.ListObjectsOptions{Recursive: true}
for obj := range client.ListObjects(ctx, bucketName, opts) {
if obj.Err != nil {
// Cancel immediately so in-flight downloads stop now rather than running
// to completion behind a listing that has already failed.
cancel()
return fmt.Errorf("error listing objects: %w", obj.Err)
}
// Empty directory markers contain no file bytes to download.
if obj.Size == 0 && strings.HasSuffix(obj.Key, "/") {
continue
}
select {
case jobs <- obj.Key:
case <-ctx.Done():
return ctx.Err()
}
}
return nil
}()
// Always drain first, so every worker has finished before we report anything.
seen := <-collected
if listErr != nil {
return listErr
}
// A cancelled context ends the listing loop without an error of its own, and workers
// that were cut off never deliver a result. Without this check a cancelled sync would
// be indistinguishable from an empty bucket that synced cleanly.
if err := ctx.Err(); err != nil {
return fmt.Errorf("sync did not complete: %w", err)
}
if seen.count > 0 {
return fmt.Errorf("encountered %d download errors, first: %w", seen.count, seen.first)
}
return nil
}
// resolveOutputPath maps a server-supplied object key onto a path inside outputDir, which
// must already be symlink-free (see filepath.EvalSymlinks above).
//
// Keys are rejected rather than cleaned. `a/./b.txt` and `a/b/../b.txt` are different keys
// that both clean to `a/b.txt`, so cleaning them would let one object silently overwrite
// another, and lexical checks alone cannot see a symlink that is already on disk.
func resolveOutputPath(outputDir, objectName string) (string, error) {
if objectName == "" || objectName != path.Clean(objectName) || strings.Contains(objectName, `\`) {
return "", fmt.Errorf("refusing non-canonical object key: %q", objectName)
}
if !filepath.IsLocal(filepath.FromSlash(objectName)) {
return "", fmt.Errorf("refusing unsafe object key: %q", objectName)
}
current := outputDir
for _, element := range strings.Split(objectName, "/") {
current = filepath.Join(current, element)
info, err := os.Lstat(current)
if err != nil {
if os.IsNotExist(err) {
continue // Nothing here yet, so nothing can redirect the write
}
return "", fmt.Errorf("failed to inspect %q: %w", current, err)
}
if info.Mode()&os.ModeSymlink != 0 {
return "", fmt.Errorf("refusing object key through a symlink: %q", objectName)
}
}
return current, nil
}
func downloadObject(ctx context.Context, client *minio.Client, bucket, objectName, outputDir string) error {
outputPath, err := resolveOutputPath(outputDir, objectName)
if err != nil {
return err
}
// Create context with timeout
ctx, cancel := context.WithTimeout(ctx, 10*time.Minute)
defer cancel()
// Get object
obj, err := client.GetObject(ctx, bucket, objectName, minio.GetObjectOptions{})
if err != nil {
return fmt.Errorf("failed to get object: %w", err)
}
defer obj.Close()
if err := os.MkdirAll(filepath.Dir(outputPath), 0o700); err != nil {
return fmt.Errorf("failed to create directories: %w", err)
}
// Download to a sibling temp file so a failed sync never truncates the copy
// that a previous run completed, and never leaves a half-written file behind.
// os.CreateTemp already creates the file 0600.
temp, err := os.CreateTemp(filepath.Dir(outputPath), filepath.Base(outputPath)+".part-*")
if err != nil {
return fmt.Errorf("failed to create temporary file: %w", err)
}
tempPath := temp.Name()
defer func() {
temp.Close()
os.Remove(tempPath) // No-op once the rename below succeeded
}()
if _, err := io.Copy(temp, obj); err != nil {
return fmt.Errorf("failed to download file: %w", err)
}
if err := temp.Sync(); err != nil {
return fmt.Errorf("failed to flush file: %w", err)
}
if err := temp.Close(); err != nil {
return fmt.Errorf("failed to close file: %w", err)
}
// Rename is atomic within a filesystem, so readers see either the old file or
// the complete new one
if err := os.Rename(tempPath, outputPath); err != nil {
return fmt.Errorf("failed to publish file: %w", err)
}
return nil
}
エラー処理とトラブルシューティング
サイズが 0 バイトで、キーが / で終わる空ディレクトリマーカーはスキップします。通常の空ファイルはダウンロードします。ドットセグメント、バックスラッシュ、絶対パス、または保存先の既存のシンボリックリンクを含むキーは拒否します。reports のようなファイルキーも、reports/january.txt のような階層キーと競合します。バケット内でこれらのオブジェクトに異なる名前を付けてください。
起動に失敗する場合は、ポート 9000 または 9001 が使用中でないか確認します。クライアントがバケットに接続できない場合は、サーバーが引き続き動作していることと、初期データの投入が成功したことを確認します。一覧取得やオブジェクトへのアクセスで権限エラーが発生すると、ゼロ以外の終了ステータスを返します。保存先の権限エラーやファイルとディレクトリの競合でも実行は失敗しますが、他のワーカーがダウンロードを完了したファイルはディスク上に残ります。
実装のテスト
以下のエントリーポイントを minio-sync/main.go として、client.go および sync.go と同じ場所に保存します。シグナルに対応するコンテキストにより、Ctrl+C または SIGTERM で進行中のリクエストをキャンセルします。成功メッセージを出力するのは、一覧取得とすべてのワーカーがエラーなく完了した場合だけです。
// main.go
package main
import (
"context"
"log"
"os/signal"
"syscall"
)
func main() {
// Ctrl-C cancels the context, which stops the workers and makes downloadFiles
// report the interruption instead of exiting as if the sync had finished.
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
// Create MinIO client
client, err := createMinioClient(ctx)
if err != nil {
log.Fatalf("Failed to create MinIO client: %v", err)
}
// Start download. bucketName comes from client.go.
if err := downloadFiles(ctx, client, bucketName, "./downloads"); err != nil {
log.Fatalf("Download failed: %v", err)
}
log.Println("Download completed successfully")
}
親ディレクトリからダウンローダーを実行します。
(
cd minio-sync &&
GOWORK=off GOTOOLCHAIN=local go run .
)
Download completed successfully をログに出力し、minio-sync/downloads/ 配下にファイルを書き込みます。新しく作成したこのサンプルバケットについて、次のコマンドですべてのパスとバイトを検証します。
(
cd minio-sync &&
diff -r sample-input downloads
)
出力がなく終了ステータスがゼロなら、空ファイルとバイナリファイルを含め、ディレクトリが一致しています。バイトの違いやファイルの欠落があると、diff は失敗します。303 個のオブジェクトは、それぞれ 100 エントリーの両チャネルバッファを超えます。ダウンローダーを再実行すると、すべてのオブジェクトを再ダウンロードしてローカルのコピーを置き換えます。現在のバケットキーに関係のないファイルは
downloads/ に残ります。
セキュリティ上の注意点
downloads/ は、このプロセス専用にしてください。パスの検査では既存のシンボリックリンクを拒否しますが、検査から書き込みまでの間に別のプロセスがパスを変更することは防げません。ファイルシステムのサンドボックスではありません。新しいディレクトリにはモード 0700、一時保存するファイルには 0600 を使用します。既存のディレクトリの権限は厳格化しません。同じディレクトリに対して同時に実行するダウンローダーは一つだけにしてください。
リモートサービスでは、サンドボックスの認証情報を、必要なバケット操作だけに権限を限定したアカウントのものに置き換え、HTTPS を使用してください。このサンプルの固定されたローカル root 認証情報は、使い捨てサーバー専用です。サポート対象のストレージサービスとそのデプロイ要件は、このアーカイブ済みコミュニティサーバーを使う実習とは別のものです。
まとめ
ダウンロードが成功するたびに、同じローカルファイルシステム上の同一ディレクトリにある一時ファイルと名前変更を使って、ローカルファイルを一つ置き換えます。実行が失敗しても、ダウンロードに成功したファイルが含まれる場合があります。バケット単位のロールバックは行いません。このプログラムは、タイムスタンプの比較、変更されていないオブジェクトのスキップ、古いローカルファイルの削除、変更中のバケットのスナップショット作成は行いません。結果を一貫した一組のオブジェクトに対応させる必要がある場合は、実行中にバケットを変更しないでください。
