You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@skywalking.apache.org by ha...@apache.org on 2025/02/07 13:12:34 UTC
(skywalking-banyandb) 01/01: Add taking the snapshot of data files
This is an automated email from the ASF dual-hosted git repository.
hanahmily pushed a commit to branch snapshot
in repository https://gitbox.apache.org/repos/asf/skywalking-banyandb.git
commit 4bc3abc6f6d74170216262508fbdf37409e297a8
Author: Gao Hongtao <ha...@gmail.com>
AuthorDate: Fri Feb 7 20:51:56 2025 +0800
Add taking the snapshot of data files
Signed-off-by: Gao Hongtao <ha...@gmail.com>
---
CHANGES.md | 1 +
api/data/snapshot.go | 32 ++++
api/proto/banyandb/database/v1/rpc.proto | 30 ++++
banyand/internal/storage/index.go | 4 +-
banyand/internal/storage/rotation_test.go | 4 +
banyand/internal/storage/storage.go | 2 +
banyand/internal/storage/tsdb.go | 40 +++++
banyand/internal/storage/tsdb_test.go | 53 +++++++
banyand/liaison/grpc/server.go | 2 +
banyand/liaison/grpc/snapshot.go | 54 +++++++
banyand/liaison/http/server.go | 1 +
banyand/measure/service.go | 5 +-
banyand/measure/snapshot.go | 115 +++++++++++++-
banyand/measure/snapshot_test.go | 97 ++++++++++++
banyand/property/listener.go | 70 +++++++++
banyand/property/service.go | 1 +
banyand/property/shard.go | 12 +-
banyand/queue/sub/health.go | 11 +-
banyand/queue/sub/helpers.go | 87 +++++++++++
banyand/queue/sub/server.go | 33 +++--
banyand/queue/sub/snapshot.go | 51 +++++++
banyand/queue/sub/sub.go | 76 +++-------
banyand/stream/index.go | 10 +-
banyand/stream/service.go | 3 +
banyand/stream/snapshot.go | 121 ++++++++++++++-
banyand/stream/snapshot_test.go | 111 ++++++++++++++
docs/api-reference.md | 78 ++++++++++
pkg/fs/file_system.go | 2 +
pkg/fs/fs_suite_test.go | 30 ++++
pkg/fs/local_file_system.go | 80 ++++++++++
pkg/fs/local_file_system_nix.go | 29 ++++
pkg/fs/local_file_system_test.go | 65 +++++++-
pkg/fs/local_file_system_windows.go | 4 +
pkg/index/index.go | 1 +
pkg/index/inverted/inverted.go | 9 ++
pkg/index/inverted/inverted_test.go | 41 +++++
pkg/schema/cache.go | 9 ++
pkg/schema/schema.go | 1 +
pkg/test/helpers/context.go | 6 +
pkg/test/setup/setup.go | 25 +++-
test/cases/snapshot/snapshot.go | 88 +++++++++++
.../distributed/snapshot/snapshot_suite_test.go | 165 +++++++++++++++++++++
.../standalone/snapshot/snapshot_suite_test.go | 130 ++++++++++++++++
43 files changed, 1699 insertions(+), 90 deletions(-)
diff --git a/CHANGES.md b/CHANGES.md
index 91511d09..220e5d65 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -25,6 +25,7 @@ Release Notes.
- Metadata: Introduce the periodic sync to sync the metadata from the etcd to the local cache in case of the loss of the events.
- Test: Add the e2e test for zipkin.
- Test: Limit the CPU and memory usage of the e2e test.
+- Add taking the snapshot of data files.
### Bug Fixes
diff --git a/api/data/snapshot.go b/api/data/snapshot.go
new file mode 100644
index 00000000..a15c0897
--- /dev/null
+++ b/api/data/snapshot.go
@@ -0,0 +1,32 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package data
+
+import (
+ "github.com/apache/skywalking-banyandb/api/common"
+ "github.com/apache/skywalking-banyandb/pkg/bus"
+)
+
+// SnapshotKindVersion is the version tag of snapshot kind.
+var SnapshotKindVersion = common.KindVersion{
+ Version: "v1",
+ Kind: "snapshot",
+}
+
+// TopicSnapshot is the snapshot topic.
+var TopicSnapshot = bus.BiTopic(SnapshotKindVersion.String())
diff --git a/api/proto/banyandb/database/v1/rpc.proto b/api/proto/banyandb/database/v1/rpc.proto
index a3429b7d..05202c8c 100644
--- a/api/proto/banyandb/database/v1/rpc.proto
+++ b/api/proto/banyandb/database/v1/rpc.proto
@@ -483,3 +483,33 @@ service TopNAggregationRegistryService {
// Exist doesn't expose an HTTP endpoint. Please use HEAD method to touch Get instead
rpc Exist(TopNAggregationRegistryServiceExistRequest) returns (TopNAggregationRegistryServiceExistResponse);
}
+
+message SnapshotRequest {
+ message Group {
+ common.v1.Catalog catalog = 1;
+ string group = 2;
+ }
+ repeated Group groups = 1;
+}
+
+message Snapshot {
+ common.v1.Catalog catalog = 1;
+ string name = 2;
+ string error = 3;
+}
+
+message SnapshotResponse {
+ repeated Snapshot snapshots = 1;
+}
+
+service SnapshotService {
+ rpc Snapshot(SnapshotRequest) returns (SnapshotResponse) {
+ option (google.api.http) = {
+ get: "/v1/snapshot"
+ additional_bindings: {
+ post: "/v1/snapshot"
+ body: "*"
+ }
+ };
+ }
+}
diff --git a/banyand/internal/storage/index.go b/banyand/internal/storage/index.go
index b1cfd383..5a62bf83 100644
--- a/banyand/internal/storage/index.go
+++ b/banyand/internal/storage/index.go
@@ -34,6 +34,8 @@ import (
"github.com/apache/skywalking-banyandb/pkg/timestamp"
)
+const seriesIndexDirName = "sidx"
+
func (s *segment[T, O]) IndexDB() IndexDB {
return s.index
}
@@ -58,7 +60,7 @@ func newSeriesIndex(ctx context.Context, root string, flushTimeoutSeconds int64,
p: common.GetPosition(ctx),
}
opts := inverted.StoreOpts{
- Path: path.Join(root, "sidx"),
+ Path: path.Join(root, seriesIndexDirName),
Logger: si.l,
BatchWaitSec: flushTimeoutSeconds,
CacheMaxBytes: cacheMaxBytes,
diff --git a/banyand/internal/storage/rotation_test.go b/banyand/internal/storage/rotation_test.go
index e9b1c9da..f25576b4 100644
--- a/banyand/internal/storage/rotation_test.go
+++ b/banyand/internal/storage/rotation_test.go
@@ -171,6 +171,10 @@ func (m *MockTSTable) Close() error {
func (m *MockTSTable) Collect(_ Metrics) {}
+func (m *MockTSTable) TakeFileSnapshot(_ string) error {
+ return nil
+}
+
var MockTSTableCreator = func(_ fs.FileSystem, _ string, _ common.Position,
_ *logger.Logger, _ timestamp.TimeRange, _, _ any,
) (*MockTSTable, error) {
diff --git a/banyand/internal/storage/storage.go b/banyand/internal/storage/storage.go
index 3db3f26c..469db5df 100644
--- a/banyand/internal/storage/storage.go
+++ b/banyand/internal/storage/storage.go
@@ -101,6 +101,7 @@ type TSDB[T TSTable, O any] interface {
SelectSegments(timeRange timestamp.TimeRange) []Segment[T, O]
Tick(ts int64)
UpdateOptions(opts *commonv1.ResourceOpts)
+ TakeFileSnapshot(dst string) error
}
// Segment is a time range of data.
@@ -117,6 +118,7 @@ type Segment[T TSTable, O any] interface {
type TSTable interface {
io.Closer
Collect(Metrics)
+ TakeFileSnapshot(dst string) error
}
// TSTableCreator creates a TSTable.
diff --git a/banyand/internal/storage/tsdb.go b/banyand/internal/storage/tsdb.go
index 167f0380..79579097 100644
--- a/banyand/internal/storage/tsdb.go
+++ b/banyand/internal/storage/tsdb.go
@@ -169,6 +169,46 @@ func (d *database[T, O]) UpdateOptions(resourceOpts *commonv1.ResourceOpts) {
d.segmentController.updateOptions(resourceOpts)
}
+func (d *database[T, O]) TakeFileSnapshot(dst string) error {
+ if d.closed.Load() {
+ return errors.New("database is closed")
+ }
+
+ segments := d.segmentController.segments()
+ defer func() {
+ for _, seg := range segments {
+ seg.DecRef()
+ }
+ }()
+
+ for _, seg := range segments {
+ segDir := filepath.Base(seg.location)
+ segPath := filepath.Join(dst, segDir)
+ lfs.MkdirIfNotExist(segPath, dirPerm)
+
+ indexPath := filepath.Join(segPath, seriesIndexDirName)
+ lfs.MkdirIfNotExist(indexPath, dirPerm)
+ if err := seg.index.store.TakeFileSnapshot(indexPath); err != nil {
+ return errors.Wrapf(err, "failed to snapshot index for segment %s", segDir)
+ }
+
+ sLst := seg.sLst.Load()
+ if sLst == nil {
+ continue
+ }
+ for _, shard := range *sLst {
+ shardDir := filepath.Base(shard.location)
+ shardPath := filepath.Join(segPath, shardDir)
+ lfs.MkdirIfNotExist(shardPath, dirPerm)
+ if err := shard.table.TakeFileSnapshot(shardPath); err != nil {
+ return errors.Wrapf(err, "failed to snapshot shard %s in segment %s", shardDir, segDir)
+ }
+ }
+ }
+
+ return nil
+}
+
func (d *database[T, O]) collect() {
if d.closed.Load() {
return
diff --git a/banyand/internal/storage/tsdb_test.go b/banyand/internal/storage/tsdb_test.go
index 2b33a4f9..dd96807d 100644
--- a/banyand/internal/storage/tsdb_test.go
+++ b/banyand/internal/storage/tsdb_test.go
@@ -19,6 +19,7 @@ package storage
import (
"context"
+ "path/filepath"
"testing"
"time"
@@ -162,3 +163,55 @@ func TestOpenTSDB(t *testing.T) {
tsdb.Close()
})
}
+
+func TestTakeFileSnapshot(t *testing.T) {
+ logger.Init(logger.Logging{
+ Env: "dev",
+ Level: flags.LogLevel,
+ })
+
+ t.Run("Take snapshot of existing TSDB", func(t *testing.T) {
+ dir, defFn := test.Space(require.New(t))
+ defer defFn()
+
+ snapshotDir := filepath.Join(dir, "snapshot")
+
+ opts := TSDBOpts[*MockTSTable, any]{
+ Location: dir,
+ SegmentInterval: IntervalRule{Unit: DAY, Num: 1},
+ TTL: IntervalRule{Unit: DAY, Num: 3},
+ ShardNum: 1,
+ TSTableCreator: MockTSTableCreator,
+ }
+
+ ctx := context.Background()
+ mc := timestamp.NewMockClock()
+
+ ts, err := time.ParseInLocation("2006-01-02 15:04:05", "2024-05-01 00:00:00", time.Local)
+ require.NoError(t, err)
+ mc.Set(ts)
+ ctx = timestamp.SetClock(ctx, mc)
+
+ tsdb, err := OpenTSDB(ctx, opts)
+ require.NoError(t, err)
+ require.NotNil(t, tsdb)
+
+ seg, err := tsdb.CreateSegmentIfNotExist(ts)
+ require.NoError(t, err)
+ require.NotNil(t, seg)
+ segLocation := seg.(*segment[*MockTSTable, any]).location // to verify snapshot files/dirs later
+ seg.DecRef()
+
+ err = tsdb.TakeFileSnapshot(snapshotDir)
+ require.NoError(t, err, "taking file snapshot should not produce an error")
+
+ segDir := filepath.Join(snapshotDir, filepath.Base(segLocation))
+ require.DirExists(t, segDir, "snapshot of the segment directory should exist")
+
+ indexDir := filepath.Join(segDir, seriesIndexDirName) // "seriesIndexDirName" comes from the TSDB code.
+ require.DirExists(t, indexDir,
+ "index directory must be present in the snapshot")
+
+ require.NoError(t, tsdb.Close())
+ })
+}
diff --git a/banyand/liaison/grpc/server.go b/banyand/liaison/grpc/server.go
index 1f540575..84515462 100644
--- a/banyand/liaison/grpc/server.go
+++ b/banyand/liaison/grpc/server.go
@@ -74,6 +74,7 @@ type NodeRegistries struct {
}
type server struct {
+ databasev1.UnimplementedSnapshotServiceServer
creds credentials.TransportCredentials
omr observability.MetricsRegistry
measureSVC *measureService
@@ -271,6 +272,7 @@ func (s *server) Serve() run.StopNotify {
databasev1.RegisterMeasureRegistryServiceServer(s.ser, s.measureRegistryServer)
propertyv1.RegisterPropertyServiceServer(s.ser, s.propertyServer)
databasev1.RegisterTopNAggregationRegistryServiceServer(s.ser, s.topNAggregationRegistryServer)
+ databasev1.RegisterSnapshotServiceServer(s.ser, s)
grpc_health_v1.RegisterHealthServer(s.ser, health.NewServer())
s.stopCh = make(chan struct{})
diff --git a/banyand/liaison/grpc/snapshot.go b/banyand/liaison/grpc/snapshot.go
new file mode 100644
index 00000000..3ec3b811
--- /dev/null
+++ b/banyand/liaison/grpc/snapshot.go
@@ -0,0 +1,54 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package grpc
+
+import (
+ "context"
+ "errors"
+ "fmt"
+
+ "github.com/apache/skywalking-banyandb/api/data"
+ databasev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/database/v1"
+ "github.com/apache/skywalking-banyandb/pkg/bus"
+ "github.com/apache/skywalking-banyandb/pkg/logger"
+)
+
+func (s *server) Snapshot(ctx context.Context, req *databasev1.SnapshotRequest) (*databasev1.SnapshotResponse, error) {
+ fs, err := s.pipeline.Publish(ctx, data.TopicSnapshot, bus.NewMessage(bus.MessageID(0), req.Groups))
+ if errors.Is(err, bus.ErrTopicNotExist) {
+ return nil, fmt.Errorf("this server does not support taking snapshot")
+ }
+ mm, err := fs.GetAll()
+ if err != nil {
+ return nil, err
+ }
+ var result []*databasev1.Snapshot
+ for _, m := range mm {
+ data := m.Data()
+ if data != nil {
+ snp, ok := data.(*databasev1.Snapshot)
+ if !ok {
+ logger.Panicf("invalid data type %T", data)
+ }
+ if snp != nil {
+ result = append(result, snp)
+ }
+ }
+ }
+ return &databasev1.SnapshotResponse{Snapshots: result}, nil
+}
diff --git a/banyand/liaison/http/server.go b/banyand/liaison/http/server.go
index 14b1d5d7..2dec2fd8 100644
--- a/banyand/liaison/http/server.go
+++ b/banyand/liaison/http/server.go
@@ -171,6 +171,7 @@ func (p *server) Serve() run.StopNotify {
databasev1.RegisterIndexRuleBindingRegistryServiceHandlerFromEndpoint(ctx, gwMux, p.grpcAddr, opts),
databasev1.RegisterGroupRegistryServiceHandlerFromEndpoint(ctx, gwMux, p.grpcAddr, opts),
databasev1.RegisterTopNAggregationRegistryServiceHandlerFromEndpoint(ctx, gwMux, p.grpcAddr, opts),
+ databasev1.RegisterSnapshotServiceHandlerFromEndpoint(ctx, gwMux, p.grpcAddr, opts),
streamv1.RegisterStreamServiceHandlerFromEndpoint(ctx, gwMux, p.grpcAddr, opts),
measurev1.RegisterMeasureServiceHandlerFromEndpoint(ctx, gwMux, p.grpcAddr, opts),
propertyv1.RegisterPropertyServiceHandlerFromEndpoint(ctx, gwMux, p.grpcAddr, opts),
diff --git a/banyand/measure/service.go b/banyand/measure/service.go
index 5bc9383f..1735e80b 100644
--- a/banyand/measure/service.go
+++ b/banyand/measure/service.go
@@ -123,12 +123,15 @@ func (s *service) PreRun(ctx context.Context) error {
return err
}
+ if err := s.pipeline.Subscribe(data.TopicSnapshot, &snapshotListener{s: s}); err != nil {
+ return err
+ }
+
s.writeListener = setUpWriteCallback(s.l, s.schemaRepo, s.maxDiskUsagePercent)
// only subscribe metricPipeline for data node
if s.metricPipeline != nil {
err := s.metricPipeline.Subscribe(data.TopicMeasureWrite, s.writeListener)
if err != nil {
- s.l.Err(err).Msgf("Fail to subscribe metricPipeline, %v", err)
return err
}
}
diff --git a/banyand/measure/snapshot.go b/banyand/measure/snapshot.go
index 041fbfff..c4c33876 100644
--- a/banyand/measure/snapshot.go
+++ b/banyand/measure/snapshot.go
@@ -18,12 +18,25 @@
package measure
import (
- "errors"
+ "context"
"fmt"
"path/filepath"
+ "sync"
"sync/atomic"
+ "time"
+
+ "github.com/pkg/errors"
+ "go.uber.org/multierr"
+
+ commonv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/common/v1"
+ databasev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/database/v1"
+ "github.com/apache/skywalking-banyandb/banyand/internal/storage"
+ "github.com/apache/skywalking-banyandb/pkg/bus"
+ "github.com/apache/skywalking-banyandb/pkg/schema"
)
+const snapshotsDir = "snapshots"
+
func (tst *tsTable) currentSnapshot() *snapshot {
tst.RLock()
defer tst.RUnlock()
@@ -134,3 +147,103 @@ func parseSnapshot(name string) (uint64, error) {
}
return parseEpoch(name[:16])
}
+
+func (tst *tsTable) TakeFileSnapshot(dst string) error {
+ snapshot := tst.currentSnapshot()
+ if snapshot == nil {
+ return fmt.Errorf("no current snapshot available")
+ }
+ defer snapshot.decRef()
+
+ for _, pw := range snapshot.parts {
+ if pw.mp != nil {
+ continue
+ }
+
+ part := pw.p
+ srcPath := part.path
+ destPartPath := filepath.Join(dst, filepath.Base(srcPath))
+
+ if err := tst.fileSystem.CreateHardLink(srcPath, destPartPath, nil); err != nil {
+ return fmt.Errorf("failed to create snapshot for part %d: %w", part.partMetadata.ID, err)
+ }
+ }
+ parent := filepath.Dir(dst)
+ tst.fileSystem.SyncPath(parent)
+ return nil
+}
+
+func (s *service) takeGroupSnapshot(dstDir string, groupName string) error {
+ group, ok := s.schemaRepo.LoadGroup(groupName)
+ if !ok {
+ return errors.Errorf("group %s not found", groupName)
+ }
+ db := group.SupplyTSDB()
+ if db == nil {
+ return errors.Errorf("group %s has no tsdb", group.GetSchema().Metadata.Name)
+ }
+ tsdb := db.(storage.TSDB[*tsTable, option])
+ if err := tsdb.TakeFileSnapshot(dstDir); err != nil {
+ return errors.WithMessagef(err, "snapshot %s fail to take file snapshot for group %s", dstDir, group.GetSchema().Metadata.Name)
+ }
+ return nil
+}
+
+type snapshotListener struct {
+ *bus.UnImplementedHealthyListener
+ s *service
+ snapshotSeq uint64
+ snapshotMux sync.Mutex
+}
+
+// Rev takes a snapshot of the database.
+func (s *snapshotListener) Rev(ctx context.Context, message bus.Message) bus.Message {
+ groups := message.Data().([]*databasev1.SnapshotRequest_Group)
+ var gg []schema.Group
+ if len(groups) == 0 {
+ gg = s.s.schemaRepo.LoadAllGroups()
+ } else {
+ for _, g := range groups {
+ if g.Catalog != commonv1.Catalog_CATALOG_MEASURE {
+ continue
+ }
+ group, ok := s.s.schemaRepo.LoadGroup(g.Group)
+ if !ok {
+ continue
+ }
+ gg = append(gg, group)
+ }
+ }
+ if len(gg) == 0 {
+ return bus.NewMessage(bus.MessageID(time.Now().UnixNano()), nil)
+ }
+ s.snapshotMux.Lock()
+ defer s.snapshotMux.Unlock()
+ sn := s.snapshotName()
+ var err error
+ for _, g := range gg {
+ select {
+ case <-ctx.Done():
+ return bus.NewMessage(bus.MessageID(time.Now().UnixNano()), nil)
+ default:
+ }
+ if errGroup := s.s.takeGroupSnapshot(filepath.Join(s.s.schemaRepo.path, snapshotsDir, sn), g.GetSchema().Metadata.Name); err != nil {
+ s.s.l.Error().Err(errGroup).Str("group", g.GetSchema().Metadata.Name).Msg("fail to take group snapshot")
+ err = multierr.Append(err, errGroup)
+ continue
+ }
+ }
+ snp := &databasev1.Snapshot{
+ Name: sn,
+ Catalog: commonv1.Catalog_CATALOG_MEASURE,
+ }
+ if err != nil {
+ snp.Error = err.Error()
+ }
+ return bus.NewMessage(bus.MessageID(time.Now().UnixNano()), snp)
+}
+
+func (s *snapshotListener) snapshotName() string {
+ s.snapshotSeq++
+ return fmt.Sprintf("%s-%08X", time.Now().UTC().Format("20060102150405"), s.snapshotSeq)
+}
diff --git a/banyand/measure/snapshot_test.go b/banyand/measure/snapshot_test.go
index 80cf41b1..b224f4f8 100644
--- a/banyand/measure/snapshot_test.go
+++ b/banyand/measure/snapshot_test.go
@@ -18,11 +18,21 @@
package measure
import (
+ "path/filepath"
+ "runtime"
"testing"
+ "time"
"github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+ "github.com/apache/skywalking-banyandb/api/common"
"github.com/apache/skywalking-banyandb/pkg/bytes"
+ "github.com/apache/skywalking-banyandb/pkg/fs"
+ "github.com/apache/skywalking-banyandb/pkg/logger"
+ "github.com/apache/skywalking-banyandb/pkg/test"
+ "github.com/apache/skywalking-banyandb/pkg/test/flags"
+ "github.com/apache/skywalking-banyandb/pkg/timestamp"
)
func TestSnapshotGetParts(t *testing.T) {
@@ -421,3 +431,90 @@ func TestSnapshotRemove(t *testing.T) {
})
}
}
+
+func TestSnapshotFunctionality(t *testing.T) {
+ fileSystem := fs.NewLocalFileSystem()
+
+ tmpPath, deferFn := test.Space(require.New(t))
+ defer deferFn()
+
+ tabDir := filepath.Join(tmpPath, "tab")
+ fileSystem.MkdirPanicIfExist(tabDir, 0o755)
+
+ tst, err := newTSTable(
+ fileSystem,
+ tabDir,
+ common.Position{},
+ logger.GetLogger("test"),
+ timestamp.TimeRange{},
+ option{
+ flushTimeout: 0,
+ mergePolicy: newDefaultMergePolicyForTesting(),
+ },
+ nil,
+ )
+ if err != nil {
+ t.Fatalf("failed to create newTSTable: %v", err)
+ }
+ defer tst.Close()
+
+ tst.mustAddDataPoints(dpsTS1)
+ tst.mustAddDataPoints(dpsTS2)
+ time.Sleep(100 * time.Millisecond) // allow time for flushing
+
+ require.Eventually(t, func() bool {
+ dd := fileSystem.ReadDir(tabDir)
+ partNum := 0
+ for _, d := range dd {
+ if d.IsDir() {
+ partNum++
+ }
+ }
+ return partNum >= 1
+ }, flags.EventuallyTimeout, time.Millisecond, "wait for file parts to be created")
+
+ snapshotPath := filepath.Join(tmpPath, "snapshot")
+ fileSystem.MkdirIfNotExist(snapshotPath, 0o755)
+
+ if err := tst.TakeFileSnapshot(snapshotPath); err != nil {
+ t.Fatalf("TakeFileSnapshot failed: %v", err)
+ }
+
+ entries := fileSystem.ReadDir(snapshotPath)
+
+ if len(entries) < 1 {
+ t.Fatalf("expected 1 directory for flushed part, got %d", len(entries))
+ }
+ partDir := entries[0].Name()
+
+ partFiles := fileSystem.ReadDir(filepath.Join(snapshotPath, partDir))
+
+ // Check "primary.bin" and "meta.bin" existence
+ hasPrimary := false
+ hasMeta := false
+ for _, pf := range partFiles {
+ switch pf.Name() {
+ case "primary.bin":
+ hasPrimary = true
+ case "meta.bin":
+ hasMeta = true
+ }
+ }
+ if !hasPrimary {
+ t.Error("expected primary.bin in snapshot, but none found")
+ }
+ if !hasMeta {
+ t.Error("expected meta.bin in snapshot, but none found")
+ }
+
+ // Verify hard links (Unix-only)
+ if runtime.GOOS != "windows" {
+ srcFile := filepath.Join(tabDir, partDir, "primary.bin")
+ destFile := filepath.Join(snapshotPath, partDir, "primary.bin")
+
+ err := fs.CompareINode(srcFile, destFile)
+ if err != nil {
+ t.Fatalf("expected hard linked files to share inode: %v", err)
+ }
+ }
+}
diff --git a/banyand/property/listener.go b/banyand/property/listener.go
index 0433b826..82f02791 100644
--- a/banyand/property/listener.go
+++ b/banyand/property/listener.go
@@ -19,12 +19,18 @@ package property
import (
"context"
+ "fmt"
+ "path"
+ "path/filepath"
"runtime/debug"
+ "sync"
"time"
"google.golang.org/protobuf/proto"
"github.com/apache/skywalking-banyandb/api/common"
+ commonv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/common/v1"
+ databasev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/database/v1"
modelv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/model/v1"
propertyv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/property/v1"
"github.com/apache/skywalking-banyandb/banyand/observability"
@@ -33,6 +39,8 @@ import (
"github.com/apache/skywalking-banyandb/pkg/query"
)
+const snapshotsDir = "snapshots"
+
var (
_ bus.MessageListener = (*updateListener)(nil)
_ bus.MessageListener = (*deleteListener)(nil)
@@ -194,3 +202,65 @@ func (h *queryListener) Rev(ctx context.Context, message bus.Message) (resp bus.
resp = bus.NewMessage(bus.MessageID(now), qResp)
return
}
+
+type snapshotListener struct {
+ *bus.UnImplementedHealthyListener
+ s *service
+ snapshotSeq uint64
+ snapshotMux sync.Mutex
+}
+
+// Rev takes a snapshot of the database.
+func (s *snapshotListener) Rev(ctx context.Context, message bus.Message) bus.Message {
+ groups := message.Data().([]*databasev1.SnapshotRequest_Group)
+ var toTake bool
+ if len(groups) == 0 {
+ toTake = true
+ } else {
+ for _, g := range groups {
+ if g.Catalog != commonv1.Catalog_CATALOG_PROPERTY {
+ toTake = true
+ break
+ }
+ }
+ }
+ if !toTake {
+ return bus.NewMessage(bus.MessageID(time.Now().UnixNano()), nil)
+ }
+ s.snapshotMux.Lock()
+ defer s.snapshotMux.Unlock()
+ sn := s.snapshotName()
+ shardsRef := s.s.db.sLst.Load()
+ if shardsRef == nil {
+ return bus.NewMessage(bus.MessageID(time.Now().UnixNano()), nil)
+ }
+ shards := *shardsRef
+ for _, shard := range shards {
+ select {
+ case <-ctx.Done():
+ return bus.NewMessage(bus.MessageID(time.Now().UnixNano()), nil)
+ default:
+ }
+ snpDir := path.Join(s.s.db.location, snapshotsDir, sn, filepath.Base(shard.location))
+ lfs.MkdirPanicIfExist(snpDir, dirPerm)
+ err := shard.store.TakeFileSnapshot(snpDir)
+ if err != nil {
+ s.s.l.Error().Err(err).Str("shard", filepath.Base(shard.location)).Msg("fail to take shard snapshot")
+ return bus.NewMessage(bus.MessageID(time.Now().UnixNano()), &databasev1.Snapshot{
+ Name: sn,
+ Catalog: commonv1.Catalog_CATALOG_PROPERTY,
+ Error: err.Error(),
+ })
+ }
+ }
+
+ return bus.NewMessage(bus.MessageID(time.Now().UnixNano()), &databasev1.Snapshot{
+ Name: sn,
+ Catalog: commonv1.Catalog_CATALOG_PROPERTY,
+ })
+}
+
+func (s *snapshotListener) snapshotName() string {
+ s.snapshotSeq++
+ return fmt.Sprintf("%s-%08X", time.Now().UTC().Format("20060102150405"), s.snapshotSeq)
+}
diff --git a/banyand/property/service.go b/banyand/property/service.go
index e3af4fe0..27fab914 100644
--- a/banyand/property/service.go
+++ b/banyand/property/service.go
@@ -104,6 +104,7 @@ func (s *service) PreRun(ctx context.Context) error {
s.pipeline.Subscribe(data.TopicPropertyUpdate, &updateListener{s: s, path: path, maxDiskUsagePercent: s.maxDiskUsagePercent}),
s.pipeline.Subscribe(data.TopicPropertyDelete, &deleteListener{s: s}),
s.pipeline.Subscribe(data.TopicPropertyQuery, &queryListener{s: s}),
+ s.pipeline.Subscribe(data.TopicSnapshot, &snapshotListener{s: s}),
)
}
diff --git a/banyand/property/shard.go b/banyand/property/shard.go
index 16a0fa55..feb8b78e 100644
--- a/banyand/property/shard.go
+++ b/banyand/property/shard.go
@@ -53,9 +53,10 @@ var (
)
type shard struct {
- store index.SeriesStore
- l *logger.Logger
- id common.ShardID
+ store index.SeriesStore
+ l *logger.Logger
+ location string
+ id common.ShardID
}
func (s *shard) close() error {
@@ -70,8 +71,9 @@ func (db *database) newShard(ctx context.Context, id common.ShardID, flushTimeou
location := path.Join(db.location, fmt.Sprintf(shardTemplate, int(id)))
sName := "shard" + strconv.Itoa(int(id))
si := &shard{
- id: id,
- l: logger.Fetch(ctx, sName),
+ id: id,
+ l: logger.Fetch(ctx, sName),
+ location: location,
}
opts := inverted.StoreOpts{
Path: location,
diff --git a/banyand/queue/sub/health.go b/banyand/queue/sub/health.go
index 599981d8..77e0743f 100644
--- a/banyand/queue/sub/health.go
+++ b/banyand/queue/sub/health.go
@@ -26,7 +26,8 @@ import (
func (s *server) HealthCheck(_ context.Context, req *clusterv1.HealthCheckRequest) (*clusterv1.HealthCheckResponse, error) {
if t, ok := s.topicMap[req.ServiceName]; ok {
- if l := s.listeners[t]; l != nil {
+ ll := s.listeners[t]
+ for _, l := range ll {
if err := l.CheckHealth(); err != nil {
return &clusterv1.HealthCheckResponse{
ServiceName: req.ServiceName,
@@ -34,11 +35,11 @@ func (s *server) HealthCheck(_ context.Context, req *clusterv1.HealthCheckReques
Error: err.Error(),
}, nil
}
- return &clusterv1.HealthCheckResponse{
- ServiceName: req.ServiceName,
- Status: modelv1.Status_STATUS_SUCCEED,
- }, nil
}
+ return &clusterv1.HealthCheckResponse{
+ ServiceName: req.ServiceName,
+ Status: modelv1.Status_STATUS_SUCCEED,
+ }, nil
}
return &clusterv1.HealthCheckResponse{
ServiceName: req.ServiceName,
diff --git a/banyand/queue/sub/helpers.go b/banyand/queue/sub/helpers.go
new file mode 100644
index 00000000..c4a387d7
--- /dev/null
+++ b/banyand/queue/sub/helpers.go
@@ -0,0 +1,87 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package sub
+
+import (
+ "time"
+
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/status"
+
+ "github.com/apache/skywalking-banyandb/api/common"
+ clusterv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/cluster/v1"
+ "github.com/apache/skywalking-banyandb/pkg/bus"
+ "github.com/apache/skywalking-banyandb/pkg/logger"
+)
+
+func (s *server) handleEOF(stream clusterv1.Service_SendServer, topic *bus.Topic, dataCollection []any, writeEntity *clusterv1.SendRequest) {
+ if len(dataCollection) < 1 {
+ return
+ }
+ listeners := s.getListeners(*topic)
+ if len(listeners) == 0 {
+ s.reply(stream, writeEntity, nil, "no listener found")
+ return
+ }
+ if len(listeners) > 1 {
+ logger.Panicf("multiple listeners found for topic %s", *topic)
+ }
+ listener := listeners[0]
+ if le := listener.CheckHealth(); le != nil {
+ s.reply(stream, writeEntity, le, "")
+ return
+ }
+ message := listener.Rev(stream.Context(), bus.NewMessage(bus.MessageID(0), dataCollection))
+ var resp *clusterv1.SendResponse
+ data := message.Data()
+ if data != nil {
+ switch d := data.(type) {
+ case *common.Error:
+ resp = &clusterv1.SendResponse{
+ MessageId: writeEntity.MessageId,
+ Error: d.Error(),
+ Status: d.Status(),
+ }
+ default:
+ resp = &clusterv1.SendResponse{
+ MessageId: writeEntity.MessageId,
+ }
+ }
+ }
+ if errSend := stream.Send(resp); errSend != nil {
+ s.log.Error().Stringer("written", writeEntity).Err(errSend).Msg("failed to send write response")
+ s.metrics.totalMsgSentErr.Inc(1, writeEntity.Topic)
+ }
+}
+
+func (s *server) handleRecvError(err error) error {
+ if status.Code(err) == codes.Canceled || status.Code(err) == codes.DeadlineExceeded {
+ return nil
+ }
+ s.log.Error().Err(err).Msg("failed to receive message")
+ return err
+}
+
+func (s *server) handleBatch(dataCollection *[]any, writeEntity *clusterv1.SendRequest, start *time.Time) {
+ if len(*dataCollection) == 0 {
+ s.metrics.totalStarted.Inc(1, writeEntity.Topic)
+ *start = time.Now()
+ }
+ *dataCollection = append(*dataCollection, writeEntity.Body)
+ s.metrics.totalMsgSent.Inc(1, writeEntity.Topic)
+}
diff --git a/banyand/queue/sub/server.go b/banyand/queue/sub/server.go
index 672389a7..c0dcc12c 100644
--- a/banyand/queue/sub/server.go
+++ b/banyand/queue/sub/server.go
@@ -64,32 +64,33 @@ var (
)
type server struct {
+ databasev1.UnimplementedSnapshotServiceServer
creds credentials.TransportCredentials
omr observability.MetricsRegistry
- healthSrv *http.Server
+ httpSrv *http.Server
log *logger.Logger
ser *grpclib.Server
- listeners map[bus.Topic]bus.MessageListener
+ listeners map[bus.Topic][]bus.MessageListener
topicMap map[string]bus.Topic
clusterv1.UnimplementedServiceServer
metrics *metrics
clientCloser context.CancelFunc
host string
addr string
- healthAddr string
+ httpAddr string
certFile string
keyFile string
maxRecvMsgSize run.Bytes
listenersLock sync.RWMutex
port uint32
- healthPort uint32
+ httpPort uint32
tls bool
}
// NewServer returns a new gRPC server.
func NewServer(omr observability.MetricsRegistry) queue.Server {
return &server{
- listeners: make(map[bus.Topic]bus.MessageListener),
+ listeners: make(map[bus.Topic][]bus.MessageListener),
topicMap: make(map[string]bus.Topic),
omr: omr,
}
@@ -122,7 +123,7 @@ func (s *server) FlagSet() *run.FlagSet {
fs.StringVar(&s.keyFile, "key-file", "", "the TLS key file")
fs.StringVar(&s.host, "grpc-host", "", "the host of banyand listens")
fs.Uint32Var(&s.port, "grpc-port", 17912, "the port of banyand listens")
- fs.Uint32Var(&s.healthPort, "health-port", 17913, "the port of banyand health check listens")
+ fs.Uint32Var(&s.httpPort, "http-port", 17913, "the port of banyand http api listens")
return fs
}
@@ -131,8 +132,8 @@ func (s *server) Validate() error {
if s.addr == ":" {
return errNoAddr
}
- s.healthAddr = net.JoinHostPort(s.host, strconv.FormatUint(uint64(s.healthPort), 10))
- if s.healthAddr == ":" {
+ s.httpAddr = net.JoinHostPort(s.host, strconv.FormatUint(uint64(s.httpPort), 10))
+ if s.httpAddr == ":" {
return errNoAddr
}
if !s.tls {
@@ -178,6 +179,7 @@ func (s *server) Serve() run.StopNotify {
s.ser = grpclib.NewServer(opts...)
clusterv1.RegisterServiceServer(s.ser, s)
grpc_health_v1.RegisterHealthServer(s.ser, health.NewServer())
+ databasev1.RegisterSnapshotServiceServer(s.ser, s)
var ctx context.Context
ctx, s.clientCloser = context.WithCancel(context.Background())
@@ -195,10 +197,15 @@ func (s *server) Serve() run.StopNotify {
return stopCh
}
gwMux := runtime.NewServeMux(runtime.WithHealthzEndpoint(client))
+ if err := databasev1.RegisterSnapshotServiceHandlerFromEndpoint(ctx, gwMux, s.addr, clientOpts); err != nil {
+ s.log.Error().Err(err).Msg("Failed to register snapshot service")
+ close(stopCh)
+ return stopCh
+ }
mux := chi.NewRouter()
mux.Mount("/api", http.StripPrefix("/api", gwMux))
- s.healthSrv = &http.Server{
- Addr: s.healthAddr,
+ s.httpSrv = &http.Server{
+ Addr: s.httpAddr,
Handler: mux,
ReadHeaderTimeout: 3 * time.Second,
}
@@ -219,8 +226,8 @@ func (s *server) Serve() run.StopNotify {
wg.Done()
}()
go func() {
- s.log.Info().Str("listenAddr", s.healthAddr).Msg("Start healthz http server")
- err := s.healthSrv.ListenAndServe()
+ s.log.Info().Str("listenAddr", s.httpAddr).Msg("Start healthz http server")
+ err := s.httpSrv.ListenAndServe()
if err != http.ErrServerClosed {
s.log.Error().Err(err)
}
@@ -240,7 +247,7 @@ func (s *server) GracefulStop() {
s.clientCloser()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
- _ = s.healthSrv.Shutdown(ctx)
+ _ = s.httpSrv.Shutdown(ctx)
go func() {
s.ser.GracefulStop()
close(stopped)
diff --git a/banyand/queue/sub/snapshot.go b/banyand/queue/sub/snapshot.go
new file mode 100644
index 00000000..7f7e833d
--- /dev/null
+++ b/banyand/queue/sub/snapshot.go
@@ -0,0 +1,51 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package sub
+
+import (
+ "context"
+
+ "github.com/apache/skywalking-banyandb/api/data"
+ databasev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/database/v1"
+ "github.com/apache/skywalking-banyandb/pkg/bus"
+ "github.com/apache/skywalking-banyandb/pkg/logger"
+)
+
+func (s *server) Snapshot(ctx context.Context, req *databasev1.SnapshotRequest) (*databasev1.SnapshotResponse, error) {
+ s.listenersLock.RLock()
+ defer s.listenersLock.RUnlock()
+ ll := s.getListeners(data.TopicSnapshot)
+ if len(ll) == 0 {
+ logger.Panicf("no listener found for topic %s", data.TopicSnapshot)
+ }
+ var result []*databasev1.Snapshot
+ for _, l := range ll {
+ message := l.Rev(ctx, bus.NewMessage(bus.MessageID(0), req.Groups))
+ data := message.Data()
+ if data != nil {
+ snp, ok := data.(*databasev1.Snapshot)
+ if !ok {
+ logger.Panicf("invalid data type %T", data)
+ }
+ if snp != nil {
+ result = append(result, snp)
+ }
+ }
+ }
+ return &databasev1.SnapshotResponse{Snapshots: result}, nil
+}
diff --git a/banyand/queue/sub/sub.go b/banyand/queue/sub/sub.go
index d30df552..7343b199 100644
--- a/banyand/queue/sub/sub.go
+++ b/banyand/queue/sub/sub.go
@@ -24,8 +24,6 @@ import (
"time"
"github.com/pkg/errors"
- "google.golang.org/grpc/codes"
- "google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/anypb"
@@ -33,6 +31,7 @@ import (
"github.com/apache/skywalking-banyandb/api/data"
clusterv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/cluster/v1"
"github.com/apache/skywalking-banyandb/pkg/bus"
+ "github.com/apache/skywalking-banyandb/pkg/logger"
)
func (s *server) Send(stream clusterv1.Service_SendServer) error {
@@ -55,50 +54,11 @@ func (s *server) Send(stream clusterv1.Service_SendServer) error {
}
writeEntity, err := stream.Recv()
if errors.Is(err, io.EOF) {
- if len(dataCollection) < 1 {
- return nil
- }
- listener := s.getListeners(*topic)
- if listener == nil {
- s.reply(stream, writeEntity, err, "no listener found")
- return nil
- }
- if le := listener.CheckHealth(); le != nil {
- s.reply(stream, writeEntity, le, "")
- return nil
- }
- message := listener.Rev(ctx, bus.NewMessage(bus.MessageID(0), dataCollection))
- var resp *clusterv1.SendResponse
- data := message.Data()
- if data != nil {
- switch d := data.(type) {
- case *common.Error:
- resp = &clusterv1.SendResponse{
- MessageId: writeEntity.MessageId,
- Error: d.Error(),
- Status: d.Status(),
- }
- default:
- resp = &clusterv1.SendResponse{
- MessageId: writeEntity.MessageId,
- }
- }
- }
- if errSend := stream.Send(resp); errSend != nil {
- s.log.Error().Stringer("written", writeEntity).Err(errSend).Msg("failed to send write response")
- s.metrics.totalMsgSentErr.Inc(1, writeEntity.Topic)
- }
+ s.handleEOF(stream, topic, dataCollection, writeEntity)
return nil
}
if err != nil {
- // If the context is canceled or the deadline is exceeded, the stream will be closed.
- // In this case, we should return nil to avoid logging the error.
- // Deadline exceeded will be raised when other data nodes are not available, and the client timeout context is triggered.
- if status.Code(err) == codes.Canceled || status.Code(err) == codes.DeadlineExceeded {
- return nil
- }
- s.log.Error().Err(err).Msg("failed to receive message")
- return err
+ return s.handleRecvError(err)
}
s.metrics.totalMsgReceived.Inc(1, writeEntity.Topic)
if writeEntity.Topic != "" && topic == nil {
@@ -126,20 +86,19 @@ func (s *server) Send(stream clusterv1.Service_SendServer) error {
continue
}
if writeEntity.BatchMod {
- if len(dataCollection) == 0 {
- s.metrics.totalStarted.Inc(1, writeEntity.Topic)
- start = time.Now()
- }
- dataCollection = append(dataCollection, writeEntity.Body)
- s.metrics.totalMsgSent.Inc(1, writeEntity.Topic)
+ s.handleBatch(&dataCollection, writeEntity, &start)
continue
}
s.metrics.totalStarted.Inc(1, writeEntity.Topic)
- listener := s.getListeners(*topic)
- if listener == nil {
+ listeners := s.getListeners(*topic)
+ if len(listeners) == 0 {
s.reply(stream, writeEntity, err, "no listener found")
continue
}
+ if len(listeners) > 1 {
+ logger.Panicf("multiple listeners found for topic %s", *topic)
+ }
+ listener := listeners[0]
m = listener.Rev(ctx, m)
if m.Data() == nil {
@@ -190,15 +149,20 @@ func (s *server) Send(stream clusterv1.Service_SendServer) error {
func (s *server) Subscribe(topic bus.Topic, listener bus.MessageListener) error {
s.listenersLock.Lock()
defer s.listenersLock.Unlock()
- if _, ok := s.listeners[topic]; !ok {
- s.listeners[topic] = listener
- s.topicMap[topic.String()] = topic
+ listeners, ok := s.listeners[topic]
+ if ok {
+ listeners = append(listeners, listener)
+ s.listeners[topic] = listeners
return nil
}
- return errors.New("topic already exists")
+ listeners = make([]bus.MessageListener, 0)
+ listeners = append(listeners, listener)
+ s.listeners[topic] = listeners
+ s.topicMap[topic.String()] = topic
+ return nil
}
-func (s *server) getListeners(topic bus.Topic) bus.MessageListener {
+func (s *server) getListeners(topic bus.Topic) []bus.MessageListener {
s.listenersLock.RLock()
defer s.listenersLock.RUnlock()
return s.listeners[topic]
diff --git a/banyand/stream/index.go b/banyand/stream/index.go
index a21f4b62..596608d1 100644
--- a/banyand/stream/index.go
+++ b/banyand/stream/index.go
@@ -34,17 +34,19 @@ import (
)
type elementIndex struct {
- store index.Store
- l *logger.Logger
+ store index.Store
+ l *logger.Logger
+ location string
}
func newElementIndex(ctx context.Context, root string, flushTimeoutSeconds int64, metrics *inverted.Metrics) (*elementIndex, error) {
ei := &elementIndex{
- l: logger.Fetch(ctx, "element_index"),
+ l: logger.Fetch(ctx, "element_index"),
+ location: path.Join(root, elementIndexFilename),
}
var err error
if ei.store, err = inverted.NewStore(inverted.StoreOpts{
- Path: path.Join(root, elementIndexFilename),
+ Path: ei.location,
Logger: ei.l,
BatchWaitSec: flushTimeoutSeconds,
Metrics: metrics,
diff --git a/banyand/stream/service.go b/banyand/stream/service.go
index a3be3826..3da45a69 100644
--- a/banyand/stream/service.go
+++ b/banyand/stream/service.go
@@ -120,6 +120,9 @@ func (s *service) PreRun(_ context.Context) error {
s.schemaRepo = newSchemaRepo(path, s)
// run a serial watcher
+ if err := s.pipeline.Subscribe(data.TopicSnapshot, &snapshotListener{s: s}); err != nil {
+ return err
+ }
s.writeListener = setUpWriteCallback(s.l, &s.schemaRepo, s.maxDiskUsagePercent)
err := s.pipeline.Subscribe(data.TopicStreamWrite, s.writeListener)
if err != nil {
diff --git a/banyand/stream/snapshot.go b/banyand/stream/snapshot.go
index 9aa274fb..d10999b6 100644
--- a/banyand/stream/snapshot.go
+++ b/banyand/stream/snapshot.go
@@ -18,12 +18,25 @@
package stream
import (
- "errors"
+ "context"
"fmt"
"path/filepath"
+ "sync"
"sync/atomic"
+ "time"
+
+ "github.com/pkg/errors"
+ "go.uber.org/multierr"
+
+ commonv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/common/v1"
+ databasev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/database/v1"
+ "github.com/apache/skywalking-banyandb/banyand/internal/storage"
+ "github.com/apache/skywalking-banyandb/pkg/bus"
+ "github.com/apache/skywalking-banyandb/pkg/schema"
)
+const snapshotsDir = "snapshots"
+
func (tst *tsTable) currentSnapshot() *snapshot {
tst.RLock()
defer tst.RUnlock()
@@ -134,3 +147,109 @@ func parseSnapshot(name string) (uint64, error) {
}
return parseEpoch(name[:16])
}
+
+func (tst *tsTable) TakeFileSnapshot(dst string) error {
+ indexDir := filepath.Join(dst, filepath.Base(tst.index.location))
+ tst.fileSystem.MkdirPanicIfExist(indexDir, dirPermission)
+ if err := tst.index.store.TakeFileSnapshot(indexDir); err != nil {
+ return fmt.Errorf("failed to take file snapshot for index: %w", err)
+ }
+
+ snapshot := tst.currentSnapshot()
+ if snapshot == nil {
+ return fmt.Errorf("no current snapshot available")
+ }
+ defer snapshot.decRef()
+
+ for _, pw := range snapshot.parts {
+ if pw.mp != nil {
+ continue
+ }
+
+ part := pw.p
+ srcPath := part.path
+ destPartPath := filepath.Join(dst, filepath.Base(srcPath))
+
+ if err := tst.fileSystem.CreateHardLink(srcPath, destPartPath, nil); err != nil {
+ return fmt.Errorf("failed to create snapshot for part %d: %w", part.partMetadata.ID, err)
+ }
+ }
+ parent := filepath.Dir(dst)
+ tst.fileSystem.SyncPath(parent)
+ return nil
+}
+
+func (s *service) takeGroupSnapshot(dstDir string, groupName string) error {
+ group, ok := s.schemaRepo.LoadGroup(groupName)
+ if !ok {
+ return errors.Errorf("group %s not found", groupName)
+ }
+ db := group.SupplyTSDB()
+ if db == nil {
+ return errors.Errorf("group %s has no tsdb", group.GetSchema().Metadata.Name)
+ }
+ tsdb := db.(storage.TSDB[*tsTable, option])
+ if err := tsdb.TakeFileSnapshot(dstDir); err != nil {
+ return errors.WithMessagef(err, "snapshot %s fail to take file snapshot for group %s", dstDir, group.GetSchema().Metadata.Name)
+ }
+ return nil
+}
+
+type snapshotListener struct {
+ *bus.UnImplementedHealthyListener
+ s *service
+ snapshotSeq uint64
+ snapshotMux sync.Mutex
+}
+
+// Rev takes a snapshot of the database.
+func (s *snapshotListener) Rev(ctx context.Context, message bus.Message) bus.Message {
+ groups := message.Data().([]*databasev1.SnapshotRequest_Group)
+ var gg []schema.Group
+ if len(groups) == 0 {
+ gg = s.s.schemaRepo.LoadAllGroups()
+ } else {
+ for _, g := range groups {
+ if g.Catalog != commonv1.Catalog_CATALOG_MEASURE {
+ continue
+ }
+ group, ok := s.s.schemaRepo.LoadGroup(g.Group)
+ if !ok {
+ continue
+ }
+ gg = append(gg, group)
+ }
+ }
+ if len(gg) == 0 {
+ return bus.NewMessage(bus.MessageID(time.Now().UnixNano()), nil)
+ }
+ s.snapshotMux.Lock()
+ defer s.snapshotMux.Unlock()
+ sn := s.snapshotName()
+ var err error
+ for _, g := range gg {
+ select {
+ case <-ctx.Done():
+ return bus.NewMessage(bus.MessageID(time.Now().UnixNano()), nil)
+ default:
+ }
+ if errGroup := s.s.takeGroupSnapshot(filepath.Join(s.s.schemaRepo.path, snapshotsDir, sn), g.GetSchema().Metadata.Name); err != nil {
+ s.s.l.Error().Err(errGroup).Str("group", g.GetSchema().Metadata.Name).Msg("fail to take group snapshot")
+ err = multierr.Append(err, errGroup)
+ continue
+ }
+ }
+ snp := &databasev1.Snapshot{
+ Name: sn,
+ Catalog: commonv1.Catalog_CATALOG_STREAM,
+ }
+ if err != nil {
+ snp.Error = err.Error()
+ }
+ return bus.NewMessage(bus.MessageID(time.Now().UnixNano()), snp)
+}
+
+func (s *snapshotListener) snapshotName() string {
+ s.snapshotSeq++
+ return fmt.Sprintf("%s-%08X", time.Now().UTC().Format("20060102150405"), s.snapshotSeq)
+}
diff --git a/banyand/stream/snapshot_test.go b/banyand/stream/snapshot_test.go
index fc2f3654..201cc8ad 100644
--- a/banyand/stream/snapshot_test.go
+++ b/banyand/stream/snapshot_test.go
@@ -18,11 +18,21 @@
package stream
import (
+ "path/filepath"
+ "runtime"
"testing"
+ "time"
"github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+ "github.com/apache/skywalking-banyandb/api/common"
"github.com/apache/skywalking-banyandb/pkg/bytes"
+ "github.com/apache/skywalking-banyandb/pkg/fs"
+ "github.com/apache/skywalking-banyandb/pkg/logger"
+ "github.com/apache/skywalking-banyandb/pkg/test"
+ "github.com/apache/skywalking-banyandb/pkg/test/flags"
+ "github.com/apache/skywalking-banyandb/pkg/timestamp"
)
func TestSnapshotGetParts(t *testing.T) {
@@ -420,3 +430,104 @@ func TestSnapshotRemove(t *testing.T) {
})
}
}
+
+func TestSnapshotFunctionality(t *testing.T) {
+ fileSystem := fs.NewLocalFileSystem()
+
+ tmpPath, deferFn := test.Space(require.New(t))
+ defer deferFn()
+
+ tabDir := filepath.Join(tmpPath, "tab")
+ fileSystem.MkdirPanicIfExist(tabDir, 0o755)
+
+ tst, err := newTSTable(
+ fileSystem,
+ tabDir,
+ common.Position{},
+ logger.GetLogger("test"),
+ timestamp.TimeRange{},
+ option{
+ flushTimeout: 0,
+ mergePolicy: newDefaultMergePolicy(),
+ },
+ nil,
+ )
+ if err != nil {
+ t.Fatalf("failed to create newTSTable: %v", err)
+ }
+ defer tst.Close()
+
+ tst.mustAddElements(esTS1)
+ tst.mustAddElements(esTS2)
+ time.Sleep(100 * time.Millisecond) // allow time for flushing
+
+ require.Eventually(t, func() bool {
+ dd := fileSystem.ReadDir(tabDir)
+ partNum := 0
+ for _, d := range dd {
+ if d.IsDir() {
+ partNum++
+ }
+ }
+ return partNum >= 1
+ }, flags.EventuallyTimeout, time.Millisecond, "wait for file parts to be created")
+
+ snapshotPath := filepath.Join(tmpPath, "snapshot")
+ fileSystem.MkdirIfNotExist(snapshotPath, 0o755)
+
+ if err := tst.TakeFileSnapshot(snapshotPath); err != nil {
+ t.Fatalf("TakeFileSnapshot failed: %v", err)
+ }
+
+ entries := fileSystem.ReadDir(snapshotPath)
+
+ if len(entries) < 1 {
+ t.Fatalf("expected 1 directory for flushed part, got %d", len(entries))
+ }
+ hasIndex := false
+ var partDir string
+ for _, entry := range entries {
+ if entry.Name() == elementIndexFilename {
+ hasIndex = true
+ } else {
+ partDir = entry.Name()
+ }
+ }
+ if !hasIndex {
+ t.Error("expected index file in snapshot, but none found")
+ }
+ if partDir == "" {
+ t.Error("expected part directory in snapshot, but none found")
+ }
+
+ partFiles := fileSystem.ReadDir(filepath.Join(snapshotPath, partDir))
+
+ // Check "primary.bin" and "meta.bin" existence
+ hasPrimary := false
+ hasMeta := false
+ for _, pf := range partFiles {
+ switch pf.Name() {
+ case "primary.bin":
+ hasPrimary = true
+ case "meta.bin":
+ hasMeta = true
+ }
+ }
+ if !hasPrimary {
+ t.Error("expected primary.bin in snapshot, but none found")
+ }
+ if !hasMeta {
+ t.Error("expected meta.bin in snapshot, but none found")
+ }
+
+ // Verify hard links (Unix-only)
+ if runtime.GOOS != "windows" {
+ srcFile := filepath.Join(tabDir, partDir, "primary.bin")
+ destFile := filepath.Join(snapshotPath, partDir, "primary.bin")
+
+ err := fs.CompareINode(srcFile, destFile)
+ if err != nil {
+ t.Fatalf("expected hard linked files to share inode: %v", err)
+ }
+ }
+}
diff --git a/docs/api-reference.md b/docs/api-reference.md
index 09cf839c..80554405 100644
--- a/docs/api-reference.md
+++ b/docs/api-reference.md
@@ -137,6 +137,10 @@
- [MeasureRegistryServiceListResponse](#banyandb-database-v1-MeasureRegistryServiceListResponse)
- [MeasureRegistryServiceUpdateRequest](#banyandb-database-v1-MeasureRegistryServiceUpdateRequest)
- [MeasureRegistryServiceUpdateResponse](#banyandb-database-v1-MeasureRegistryServiceUpdateResponse)
+ - [Snapshot](#banyandb-database-v1-Snapshot)
+ - [SnapshotRequest](#banyandb-database-v1-SnapshotRequest)
+ - [SnapshotRequest.Group](#banyandb-database-v1-SnapshotRequest-Group)
+ - [SnapshotResponse](#banyandb-database-v1-SnapshotResponse)
- [StreamRegistryServiceCreateRequest](#banyandb-database-v1-StreamRegistryServiceCreateRequest)
- [StreamRegistryServiceCreateResponse](#banyandb-database-v1-StreamRegistryServiceCreateResponse)
- [StreamRegistryServiceDeleteRequest](#banyandb-database-v1-StreamRegistryServiceDeleteRequest)
@@ -166,6 +170,7 @@
- [IndexRuleBindingRegistryService](#banyandb-database-v1-IndexRuleBindingRegistryService)
- [IndexRuleRegistryService](#banyandb-database-v1-IndexRuleRegistryService)
- [MeasureRegistryService](#banyandb-database-v1-MeasureRegistryService)
+ - [SnapshotService](#banyandb-database-v1-SnapshotService)
- [StreamRegistryService](#banyandb-database-v1-StreamRegistryService)
- [TopNAggregationRegistryService](#banyandb-database-v1-TopNAggregationRegistryService)
@@ -2061,6 +2066,69 @@ Type determine the index structure under the hood
+<a name="banyandb-database-v1-Snapshot"></a>
+
+### Snapshot
+
+
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| catalog | [banyandb.common.v1.Catalog](#banyandb-common-v1-Catalog) | | |
+| name | [string](#string) | | |
+| error | [string](#string) | | |
+
+
+
+
+
+
+<a name="banyandb-database-v1-SnapshotRequest"></a>
+
+### SnapshotRequest
+
+
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| groups | [SnapshotRequest.Group](#banyandb-database-v1-SnapshotRequest-Group) | repeated | |
+
+
+
+
+
+
+<a name="banyandb-database-v1-SnapshotRequest-Group"></a>
+
+### SnapshotRequest.Group
+
+
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| catalog | [banyandb.common.v1.Catalog](#banyandb-common-v1-Catalog) | | |
+| group | [string](#string) | | |
+
+
+
+
+
+
+<a name="banyandb-database-v1-SnapshotResponse"></a>
+
+### SnapshotResponse
+
+
+
+| Field | Type | Label | Description |
+| ----- | ---- | ----- | ----------- |
+| snapshots | [Snapshot](#banyandb-database-v1-Snapshot) | repeated | |
+
+
+
+
+
+
<a name="banyandb-database-v1-StreamRegistryServiceCreateRequest"></a>
### StreamRegistryServiceCreateRequest
@@ -2479,6 +2547,16 @@ Type determine the index structure under the hood
| Exist | [MeasureRegistryServiceExistRequest](#banyandb-database-v1-MeasureRegistryServiceExistRequest) | [MeasureRegistryServiceExistResponse](#banyandb-database-v1-MeasureRegistryServiceExistResponse) | Exist doesn't expose an HTTP endpoint. Please use HEAD method to touch Get instead |
+<a name="banyandb-database-v1-SnapshotService"></a>
+
+### SnapshotService
+
+
+| Method Name | Request Type | Response Type | Description |
+| ----------- | ------------ | ------------- | ------------|
+| Snapshot | [SnapshotRequest](#banyandb-database-v1-SnapshotRequest) | [SnapshotResponse](#banyandb-database-v1-SnapshotResponse) | |
+
+
<a name="banyandb-database-v1-StreamRegistryService"></a>
### StreamRegistryService
diff --git a/pkg/fs/file_system.go b/pkg/fs/file_system.go
index a2ed0950..755d3bc7 100644
--- a/pkg/fs/file_system.go
+++ b/pkg/fs/file_system.go
@@ -119,6 +119,8 @@ type FileSystem interface {
SyncPath(path string)
// MustGetFreeSpace returns the free space of the file system.
MustGetFreeSpace(path string) uint64
+ // CreateHardLink creates hard links in destPath for files in srcPath that pass the filter.
+ CreateHardLink(srcPath, destPath string, filter func(string) bool) error
}
// DirEntry is the interface that wraps the basic information about a file or directory.
diff --git a/pkg/fs/fs_suite_test.go b/pkg/fs/fs_suite_test.go
new file mode 100644
index 00000000..d073c111
--- /dev/null
+++ b/pkg/fs/fs_suite_test.go
@@ -0,0 +1,30 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package fs_test
+
+import (
+ "testing"
+
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+)
+
+func TestFs(t *testing.T) {
+ RegisterFailHandler(Fail)
+ RunSpecs(t, "Fs Suite")
+}
diff --git a/pkg/fs/local_file_system.go b/pkg/fs/local_file_system.go
index 39fcb22a..0d150203 100644
--- a/pkg/fs/local_file_system.go
+++ b/pkg/fs/local_file_system.go
@@ -280,6 +280,86 @@ func (fs *localFileSystem) MustGetFreeSpace(path string) uint64 {
return usage.Free
}
+func (fs *localFileSystem) CreateHardLink(srcPath, destPath string, filter func(string) bool) error {
+ _, err := os.Stat(srcPath)
+ if err != nil {
+ return &FileSystemError{
+ Code: IsNotExistError,
+ Message: fmt.Sprintf("Source path does not exist: %s, error: %v", srcPath, err),
+ }
+ }
+
+ err = filepath.Walk(srcPath, func(path string, info os.FileInfo, err error) error {
+ if err != nil {
+ return &FileSystemError{
+ Code: otherError,
+ Message: fmt.Sprintf("Error accessing path %s: %v", path, err),
+ }
+ }
+
+ if path == srcPath {
+ if info.IsDir() {
+ if err = os.MkdirAll(destPath, info.Mode()); err != nil {
+ return &FileSystemError{
+ Code: otherError,
+ Message: fmt.Sprintf("Failed to create destination root directory %s: %v", destPath, err),
+ }
+ }
+ }
+ return nil
+ }
+
+ relPath, err := filepath.Rel(srcPath, path)
+ if err != nil {
+ return &FileSystemError{
+ Code: otherError,
+ Message: fmt.Sprintf("Failed to get relative path for %s: %v", path, err),
+ }
+ }
+ destFullPath := filepath.Join(destPath, relPath)
+
+ if info.IsDir() {
+ if err := os.MkdirAll(destFullPath, info.Mode()); err != nil {
+ return &FileSystemError{
+ Code: otherError,
+ Message: fmt.Sprintf("Failed to create directory %s: %v", destFullPath, err),
+ }
+ }
+ return nil
+ }
+ if filter != nil && !filter(path) {
+ return nil
+ }
+
+ parentDir := filepath.Dir(destFullPath)
+ if err := os.MkdirAll(parentDir, 0o755); err != nil {
+ return &FileSystemError{
+ Code: otherError,
+ Message: fmt.Sprintf("Failed to create parent directory %s: %v", parentDir, err),
+ }
+ }
+
+ if err := os.Link(path, destFullPath); err != nil {
+ code := otherError
+ if os.IsExist(err) {
+ code = isExistError
+ } else if os.IsPermission(err) {
+ code = permissionError
+ }
+ return &FileSystemError{
+ Code: code,
+ Message: fmt.Sprintf("Failed to create hard link from %s to %s: %v", path, destFullPath, err),
+ }
+ }
+ return nil
+ })
+ if err != nil {
+ return err
+ }
+ fs.SyncPath(destPath)
+ return nil
+}
+
// Write adds new data to the end of a file.
func (file *LocalFile) Write(buffer []byte) (int, error) {
size, err := file.file.Write(buffer)
diff --git a/pkg/fs/local_file_system_nix.go b/pkg/fs/local_file_system_nix.go
index 4f2ebf0a..8d94f981 100644
--- a/pkg/fs/local_file_system_nix.go
+++ b/pkg/fs/local_file_system_nix.go
@@ -23,6 +23,7 @@ package fs
import (
"fmt"
"os"
+ "syscall"
"golang.org/x/sys/unix"
)
@@ -82,3 +83,31 @@ func syncFile(file *os.File) error {
}
return nil
}
+
+func mustGetFileStat(path string) (*syscall.Stat_t, error) {
+ fi, err := os.Stat(path)
+ if err != nil {
+ return nil, err
+ }
+ stat, ok := fi.Sys().(*syscall.Stat_t)
+ if !ok {
+ return nil, fmt.Errorf("failed to convert fileinfo.Sys() to *syscall.Stat_t for %s", path)
+ }
+ return stat, nil
+}
+
+// CompareINode compares the inode of two files.
+func CompareINode(srcPath, destPath string) error {
+ srcStat, err := mustGetFileStat(srcPath)
+ if err != nil {
+ return err
+ }
+ destStat, err := mustGetFileStat(destPath)
+ if err != nil {
+ return err
+ }
+ if srcStat.Ino != destStat.Ino {
+ return fmt.Errorf("src file inode: %d, dest file inode: %d", srcStat.Ino, destStat.Ino)
+ }
+ return nil
+}
diff --git a/pkg/fs/local_file_system_test.go b/pkg/fs/local_file_system_test.go
index eaf278a5..b5b58bf1 100644
--- a/pkg/fs/local_file_system_test.go
+++ b/pkg/fs/local_file_system_test.go
@@ -23,12 +23,13 @@ import (
"errors"
"io"
"os"
+ "path/filepath"
"github.com/onsi/ginkgo/v2"
"github.com/onsi/gomega"
)
-var _ = ginkgo.Describe("Loacl File System", func() {
+var _ = ginkgo.Describe("Local File System", func() {
const (
data string = "BanyanDB"
dirName string = "tmpDir"
@@ -146,4 +147,66 @@ var _ = ginkgo.Describe("Loacl File System", func() {
gomega.Expect(err).To(gomega.HaveOccurred())
})
})
+
+ ginkgo.Context("Hard Link Operations", func() {
+ const (
+ srcDir = "test_src"
+ destDir = "test_dest"
+ )
+
+ var fs FileSystem
+
+ ginkgo.BeforeEach(func() {
+ fs = NewLocalFileSystem()
+ // Create source directory structure
+ gomega.Expect(os.MkdirAll(srcDir, 0o755)).To(gomega.Succeed())
+ gomega.Expect(os.WriteFile(filepath.Join(srcDir, "file1.txt"), []byte("data1"), 0o600)).To(gomega.Succeed())
+ gomega.Expect(os.MkdirAll(filepath.Join(srcDir, "subdir"), 0o755)).To(gomega.Succeed())
+ gomega.Expect(os.WriteFile(filepath.Join(srcDir, "subdir", "file2.txt"), []byte("data2"), 0o600)).To(gomega.Succeed())
+ })
+
+ ginkgo.AfterEach(func() {
+ gomega.Expect(os.RemoveAll(srcDir)).To(gomega.Succeed())
+ gomega.Expect(os.RemoveAll(destDir)).To(gomega.Succeed())
+ })
+
+ ginkgo.It("should create hard links for files passing the filter", func() {
+ // Filter only "file1.txt"
+ filter := func(path string) bool {
+ return filepath.Base(path) == "file1.txt"
+ }
+
+ err := fs.CreateHardLink(srcDir, destDir, filter)
+ gomega.Expect(err).ToNot(gomega.HaveOccurred())
+
+ srcFile := filepath.Join(srcDir, "file1.txt")
+ destFile := filepath.Join(destDir, "file1.txt")
+ gomega.Expect(destFile).To(gomega.BeAnExistingFile())
+
+ gomega.Expect(CompareINode(srcFile, destFile)).To(gomega.Succeed())
+
+ _, err = os.Stat(filepath.Join(destDir, "subdir", "file2.txt"))
+ gomega.Expect(os.IsNotExist(err)).To(gomega.BeTrue())
+ })
+
+ ginkgo.It("should return error if source path does not exist", func() {
+ err := fs.CreateHardLink("non_existent_src", destDir, nil)
+ gomega.Expect(err).To(gomega.HaveOccurred())
+ var errFS *FileSystemError
+ gomega.Expect(errors.As(err, &errFS)).To(gomega.BeTrue())
+ gomega.Expect(errFS.Code).To(gomega.Equal(IsNotExistError))
+ })
+
+ ginkgo.It("should return error if destination file already exists", func() {
+ // Pre-create destination file
+ gomega.Expect(os.MkdirAll(destDir, 0o755)).To(gomega.Succeed())
+ gomega.Expect(os.WriteFile(filepath.Join(destDir, "file1.txt"), []byte("existing"), 0o600)).To(gomega.Succeed())
+
+ err := fs.CreateHardLink(srcDir, destDir, nil) // No filter
+ var errFS *FileSystemError
+ gomega.Expect(errors.As(err, &errFS)).To(gomega.BeTrue())
+ gomega.Expect(errFS.Code).To(gomega.Equal(isExistError))
+ gomega.Expect(errFS.Code).To(gomega.Equal(isExistError))
+ })
+ })
})
diff --git a/pkg/fs/local_file_system_windows.go b/pkg/fs/local_file_system_windows.go
index 969babc6..e0f33190 100644
--- a/pkg/fs/local_file_system_windows.go
+++ b/pkg/fs/local_file_system_windows.go
@@ -63,3 +63,7 @@ func (fs *localFileSystem) SyncPath(_ string) {}
func syncFile(_ *os.File) error {
return nil
}
+
+func CompareINode(srcPath, destPath string) error {
+ return nil
+}
\ No newline at end of file
diff --git a/pkg/index/index.go b/pkg/index/index.go
index b0a44194..b739f0b2 100644
--- a/pkg/index/index.go
+++ b/pkg/index/index.go
@@ -347,6 +347,7 @@ type Store interface {
Searcher
CollectMetrics(...string)
Reset()
+ TakeFileSnapshot(dst string) error
}
// Series represents a series in an index.
diff --git a/pkg/index/inverted/inverted.go b/pkg/index/inverted/inverted.go
index a54b4f19..01b06e17 100644
--- a/pkg/index/inverted/inverted.go
+++ b/pkg/index/inverted/inverted.go
@@ -360,6 +360,15 @@ func (s *store) Range(fieldKey index.FieldKey, opts index.RangeOpts) (list posti
return
}
+func (s *store) TakeFileSnapshot(dst string) error {
+ reader, err := s.writer.Reader()
+ if err != nil {
+ return err
+ }
+ defer reader.Close()
+ return reader.Backup(dst, nil)
+}
+
type blugeMatchIterator struct {
delegated search.DocumentMatchIterator
err error
diff --git a/pkg/index/inverted/inverted_test.go b/pkg/index/inverted/inverted_test.go
index b0a41aca..7fbbfda7 100644
--- a/pkg/index/inverted/inverted_test.go
+++ b/pkg/index/inverted/inverted_test.go
@@ -26,6 +26,7 @@ import (
"github.com/apache/skywalking-banyandb/api/common"
modelv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/model/v1"
+ "github.com/apache/skywalking-banyandb/pkg/fs"
"github.com/apache/skywalking-banyandb/pkg/index"
"github.com/apache/skywalking-banyandb/pkg/index/posting"
"github.com/apache/skywalking-banyandb/pkg/index/posting/roaring"
@@ -359,3 +360,43 @@ func setUp(t *require.Assertions) (tempDir string, deferFunc func()) {
tempDir, deferFunc = test.Space(t)
return tempDir, deferFunc
}
+
+func TestStore_TakeFileSnapshot(t *testing.T) {
+ tester := require.New(t)
+ path, fn := setUp(tester)
+ s, err := NewStore(StoreOpts{
+ Path: path,
+ Logger: logger.GetLogger("test"),
+ })
+ tester.NoError(err)
+ defer func() {
+ tester.NoError(s.Close())
+ fn()
+ }()
+
+ var batch index.Batch
+ sampleKey := index.FieldKey{
+ IndexRuleID: 10,
+ SeriesID: common.SeriesID(99),
+ }
+ batch.Documents = append(batch.Documents,
+ index.Document{
+ Fields: []index.Field{
+ index.NewStringField(sampleKey, "snapshot-test"),
+ },
+ DocID: 1,
+ },
+ )
+ tester.NoError(s.Batch(batch))
+
+ // Take snapshot
+ snapshotDir, cleanFn := test.Space(require.New(t))
+ defer cleanFn()
+
+ err = s.TakeFileSnapshot(snapshotDir)
+ tester.NoError(err)
+
+ fileSystem := fs.NewLocalFileSystem()
+ entries := fileSystem.ReadDir(snapshotDir)
+ tester.True(len(entries) > 0, "Expected snapshot to produce files")
+}
diff --git a/pkg/schema/cache.go b/pkg/schema/cache.go
index 0f8e9615..638c3147 100644
--- a/pkg/schema/cache.go
+++ b/pkg/schema/cache.go
@@ -310,6 +310,15 @@ func (sr *schemaRepo) LoadGroup(name string) (Group, bool) {
return g, g.isInit()
}
+func (sr *schemaRepo) LoadAllGroups() []Group {
+ var groups []Group
+ sr.groupMap.Range(func(_, value any) bool {
+ groups = append(groups, value.(*group))
+ return true
+ })
+ return groups
+}
+
func (sr *schemaRepo) LoadResource(metadata *commonv1.Metadata) (Resource, bool) {
k := getKey(metadata)
s, ok := sr.resourceMap.Load(k)
diff --git a/pkg/schema/schema.go b/pkg/schema/schema.go
index 50c455b9..e80a59a4 100644
--- a/pkg/schema/schema.go
+++ b/pkg/schema/schema.go
@@ -105,6 +105,7 @@ type Repository interface {
Init(schema.Kind) ([]string, []int64)
SendMetadataEvent(MetadataEvent)
LoadGroup(name string) (Group, bool)
+ LoadAllGroups() []Group
LoadResource(metadata *commonv1.Metadata) (Resource, bool)
Close()
StopCh() <-chan struct{}
diff --git a/pkg/test/helpers/context.go b/pkg/test/helpers/context.go
index e98ce51f..20d1d37a 100644
--- a/pkg/test/helpers/context.go
+++ b/pkg/test/helpers/context.go
@@ -70,3 +70,9 @@ func TimeRange(args Args, shardContext SharedContext) *modelv1.TimeRange {
End: timestamppb.New(b.Add(args.Duration)),
}
}
+
+// SnapshotSharedContext is the context shared between test cases in the snapshot testing.
+type SnapshotSharedContext struct {
+ Connection *grpclib.ClientConn
+ RootDir string
+}
diff --git a/pkg/test/setup/setup.go b/pkg/test/setup/setup.go
index 2057ddd9..9e26e60d 100644
--- a/pkg/test/setup/setup.go
+++ b/pkg/test/setup/setup.go
@@ -204,14 +204,16 @@ func CMD(flags ...string) func() {
}
}
-// DataNode runs a data node.
-func DataNode(etcdEndpoint string, flags ...string) func() {
+func startDataNode(etcdEndpoint string, flags ...string) (string, string, func(), func()) {
path, deferFn, err := test.NewSpace()
gomega.Expect(err).NotTo(gomega.HaveOccurred())
+
ports, err := test.AllocateFreePorts(1)
gomega.Expect(err).NotTo(gomega.HaveOccurred())
+
addr := fmt.Sprintf("%s:%d", host, ports[0])
nodeHost := "127.0.0.1"
+
flags = append(flags,
"data",
"--grpc-host="+host,
@@ -223,19 +225,38 @@ func DataNode(etcdEndpoint string, flags ...string) func() {
"--node-host-provider", "flag",
"--node-host", nodeHost,
)
+
closeFn := CMD(flags...)
+
gomega.Eventually(
helpers.HealthCheck(addr, 10*time.Second, 10*time.Second, grpclib.WithTransportCredentials(insecure.NewCredentials())),
testflags.EventuallyTimeout).Should(gomega.Succeed())
+
gomega.Eventually(func() (map[string]*databasev1.Node, error) {
return helpers.ListKeys(etcdEndpoint, fmt.Sprintf("/%s/nodes/%s:%d", metadata.DefaultNamespace, nodeHost, ports[0]))
}, testflags.EventuallyTimeout).Should(gomega.HaveLen(1))
+
+ return addr, path, closeFn, deferFn
+}
+
+// DataNode runs a data node.
+func DataNode(etcdEndpoint string, flags ...string) func() {
+ _, _, closeFn, deferFn := startDataNode(etcdEndpoint, flags...)
return func() {
closeFn()
deferFn()
}
}
+// DataNodeWithAddrAndDir runs a data node and returns the address and root path.
+func DataNodeWithAddrAndDir(etcdEndpoint string, flags ...string) (string, string, func()) {
+ addr, dir, closeFn, deferFn := startDataNode(etcdEndpoint, flags...)
+ return addr, dir, func() {
+ closeFn()
+ deferFn()
+ }
+}
+
// LiaisonNode runs a liaison node.
func LiaisonNode(etcdEndpoint string) (string, func()) {
ports, err := test.AllocateFreePorts(2)
diff --git a/test/cases/snapshot/snapshot.go b/test/cases/snapshot/snapshot.go
new file mode 100644
index 00000000..bdb0149e
--- /dev/null
+++ b/test/cases/snapshot/snapshot.go
@@ -0,0 +1,88 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+// Package snapshot_test contains integration test cases of the taking the snapshots.
+package snapshot_test
+
+import (
+ "context"
+ "path/filepath"
+
+ "github.com/onsi/ginkgo/v2"
+ "github.com/onsi/gomega"
+
+ commonv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/common/v1"
+ databasev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/database/v1"
+ "github.com/apache/skywalking-banyandb/pkg/fs"
+ "github.com/apache/skywalking-banyandb/pkg/test/helpers"
+)
+
+// SharedContext is the shared context for the snapshot test cases.
+var SharedContext helpers.SnapshotSharedContext
+
+var _ = ginkgo.Describe("Snapshot", func() {
+ lfs := fs.NewLocalFileSystem()
+
+ ginkgo.It("should take a snapshot", func() {
+ client := databasev1.NewSnapshotServiceClient(SharedContext.Connection)
+ resp, err := client.Snapshot(context.Background(), &databasev1.SnapshotRequest{})
+ gomega.Expect(err).NotTo(gomega.HaveOccurred())
+ gomega.Expect(resp).NotTo(gomega.BeNil())
+ gomega.Expect(resp.Snapshots).To(gomega.HaveLen(3))
+ for _, snp := range resp.Snapshots {
+ if snp.Catalog == commonv1.Catalog_CATALOG_MEASURE {
+ measureSnapshotDir := filepath.Join(SharedContext.RootDir, "measure", "snapshots")
+ entries := lfs.ReadDir(measureSnapshotDir)
+ gomega.Expect(entries).To(gomega.HaveLen(1))
+ gomega.Expect(entries[0].Name()).To(gomega.Equal(snp.Name))
+ } else if snp.Catalog == commonv1.Catalog_CATALOG_STREAM {
+ streamSnapshotDir := filepath.Join(SharedContext.RootDir, "stream", "snapshots")
+ entries := lfs.ReadDir(streamSnapshotDir)
+ gomega.Expect(entries).To(gomega.HaveLen(1))
+ gomega.Expect(entries[0].Name()).To(gomega.Equal(snp.Name))
+ } else if snp.Catalog == commonv1.Catalog_CATALOG_PROPERTY {
+ propertySnapshotDir := filepath.Join(SharedContext.RootDir, "property", "snapshots")
+ entries := lfs.ReadDir(propertySnapshotDir)
+ gomega.Expect(entries).To(gomega.HaveLen(1))
+ gomega.Expect(entries[0].Name()).To(gomega.Equal(snp.Name))
+ } else {
+ ginkgo.Fail("unexpected snapshot catalog")
+ }
+ }
+ resp, err = client.Snapshot(context.Background(), &databasev1.SnapshotRequest{})
+ gomega.Expect(err).NotTo(gomega.HaveOccurred())
+ gomega.Expect(resp).NotTo(gomega.BeNil())
+ gomega.Expect(resp.Snapshots).To(gomega.HaveLen(3))
+ for _, snp := range resp.Snapshots {
+ if snp.Catalog == commonv1.Catalog_CATALOG_MEASURE {
+ measureSnapshotDir := filepath.Join(SharedContext.RootDir, "measure", "snapshots")
+ entries := lfs.ReadDir(measureSnapshotDir)
+ gomega.Expect(entries).To(gomega.HaveLen(2))
+ } else if snp.Catalog == commonv1.Catalog_CATALOG_STREAM {
+ streamSnapshotDir := filepath.Join(SharedContext.RootDir, "stream", "snapshots")
+ entries := lfs.ReadDir(streamSnapshotDir)
+ gomega.Expect(entries).To(gomega.HaveLen(2))
+ } else if snp.Catalog == commonv1.Catalog_CATALOG_PROPERTY {
+ propertySnapshotDir := filepath.Join(SharedContext.RootDir, "property", "snapshots")
+ entries := lfs.ReadDir(propertySnapshotDir)
+ gomega.Expect(entries).To(gomega.HaveLen(2))
+ } else {
+ ginkgo.Fail("unexpected snapshot catalog")
+ }
+ }
+ })
+})
diff --git a/test/integration/distributed/snapshot/snapshot_suite_test.go b/test/integration/distributed/snapshot/snapshot_suite_test.go
new file mode 100644
index 00000000..bfd4c158
--- /dev/null
+++ b/test/integration/distributed/snapshot/snapshot_suite_test.go
@@ -0,0 +1,165 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package snapshot_test
+
+import (
+ "context"
+ "fmt"
+ "testing"
+ "time"
+
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+ "github.com/onsi/gomega/gleak"
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/credentials/insecure"
+
+ commonv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/common/v1"
+ databasev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/database/v1"
+ modelv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/model/v1"
+ propertyv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/property/v1"
+ "github.com/apache/skywalking-banyandb/banyand/metadata"
+ "github.com/apache/skywalking-banyandb/banyand/metadata/embeddedetcd"
+ "github.com/apache/skywalking-banyandb/banyand/metadata/schema"
+ "github.com/apache/skywalking-banyandb/pkg/grpchelper"
+ "github.com/apache/skywalking-banyandb/pkg/logger"
+ "github.com/apache/skywalking-banyandb/pkg/pool"
+ "github.com/apache/skywalking-banyandb/pkg/test"
+ "github.com/apache/skywalking-banyandb/pkg/test/flags"
+ "github.com/apache/skywalking-banyandb/pkg/test/gmatcher"
+ "github.com/apache/skywalking-banyandb/pkg/test/helpers"
+ test_measure "github.com/apache/skywalking-banyandb/pkg/test/measure"
+ "github.com/apache/skywalking-banyandb/pkg/test/setup"
+ test_stream "github.com/apache/skywalking-banyandb/pkg/test/stream"
+ "github.com/apache/skywalking-banyandb/pkg/timestamp"
+ test_cases "github.com/apache/skywalking-banyandb/test/cases"
+ casessnapshot "github.com/apache/skywalking-banyandb/test/cases/snapshot"
+)
+
+func TestSnapshot(t *testing.T) {
+ RegisterFailHandler(Fail)
+ RunSpecs(t, "Distributed Snapshot Suite")
+}
+
+var (
+ connection *grpc.ClientConn
+ dir string
+ deferFunc func()
+ goods []gleak.Goroutine
+)
+
+var _ = SynchronizedBeforeSuite(func() []byte {
+ Expect(logger.Init(logger.Logging{
+ Env: "dev",
+ Level: flags.LogLevel,
+ })).To(Succeed())
+ goods = gleak.Goroutines()
+ By("Starting etcd server")
+ ports, err := test.AllocateFreePorts(2)
+ Expect(err).NotTo(HaveOccurred())
+ var spaceDef func()
+ dir, spaceDef, err = test.NewSpace()
+ Expect(err).NotTo(HaveOccurred())
+ ep := fmt.Sprintf("http://127.0.0.1:%d", ports[0])
+ server, err := embeddedetcd.NewServer(
+ embeddedetcd.ConfigureListener([]string{ep}, []string{fmt.Sprintf("http://127.0.0.1:%d", ports[1])}),
+ embeddedetcd.RootDir(dir))
+ Expect(err).ShouldNot(HaveOccurred())
+ <-server.ReadyNotify()
+ By("Loading schema")
+ schemaRegistry, err := schema.NewEtcdSchemaRegistry(
+ schema.Namespace(metadata.DefaultNamespace),
+ schema.ConfigureServerEndpoints([]string{ep}),
+ )
+ Expect(err).NotTo(HaveOccurred())
+ defer schemaRegistry.Close()
+ ctx := context.Background()
+ test_stream.PreloadSchema(ctx, schemaRegistry)
+ test_measure.PreloadSchema(ctx, schemaRegistry)
+ By("Starting data node 0")
+ var dataAddr string
+ var closeDataNode0 func()
+ dataAddr, dir, closeDataNode0 = setup.DataNodeWithAddrAndDir(ep)
+ By("Starting liaison node")
+ liaisonAddr, closerLiaisonNode := setup.LiaisonNode(ep)
+ By("Initializing test cases")
+ ns := timestamp.NowMilli().UnixNano()
+ now := time.Unix(0, ns-ns%int64(time.Minute))
+ test_cases.Initialize(liaisonAddr, now)
+ conn, err := grpchelper.Conn(liaisonAddr, 10*time.Second, grpc.WithTransportCredentials(insecure.NewCredentials()))
+ Expect(err).NotTo(HaveOccurred())
+ defer conn.Close()
+ gClient := databasev1.NewGroupRegistryServiceClient(conn)
+ _, err = gClient.Create(context.Background(), &databasev1.GroupRegistryServiceCreateRequest{
+ Group: &commonv1.Group{
+ Metadata: &commonv1.Metadata{Name: "g"},
+ Catalog: commonv1.Catalog_CATALOG_PROPERTY,
+ ResourceOpts: &commonv1.ResourceOpts{
+ ShardNum: 2,
+ },
+ },
+ })
+ Expect(err).NotTo(HaveOccurred())
+ client := propertyv1.NewPropertyServiceClient(conn)
+ md := &propertyv1.Metadata{
+ Container: &commonv1.Metadata{
+ Name: "p",
+ Group: "g",
+ },
+ Id: "1",
+ }
+ resp, err := client.Apply(context.Background(), &propertyv1.ApplyRequest{Property: &propertyv1.Property{
+ Metadata: md,
+ Tags: []*modelv1.Tag{
+ {Key: "t1", Value: &modelv1.TagValue{Value: &modelv1.TagValue_Str{Str: &modelv1.Str{Value: "v1"}}}},
+ {Key: "t2", Value: &modelv1.TagValue{Value: &modelv1.TagValue_Str{Str: &modelv1.Str{Value: "v2"}}}},
+ },
+ }})
+ Expect(err).NotTo(HaveOccurred())
+ Expect(resp.Created).To(BeTrue())
+ Expect(resp.TagsNum).To(Equal(uint32(2)))
+ deferFunc = func() {
+ closerLiaisonNode()
+ closeDataNode0()
+ _ = server.Close()
+ <-server.StopNotify()
+ spaceDef()
+ }
+ return []byte(dataAddr)
+}, func(address []byte) {
+ var err error
+ connection, err = grpchelper.Conn(string(address), 10*time.Second,
+ grpc.WithTransportCredentials(insecure.NewCredentials()))
+ Expect(err).NotTo(HaveOccurred())
+ casessnapshot.SharedContext = helpers.SnapshotSharedContext{
+ Connection: connection,
+ RootDir: dir,
+ }
+})
+
+var _ = SynchronizedAfterSuite(func() {
+ if connection != nil {
+ Expect(connection.Close()).To(Succeed())
+ }
+}, func() {
+ if deferFunc != nil {
+ deferFunc()
+ }
+ Eventually(gleak.Goroutines, flags.EventuallyTimeout).ShouldNot(gleak.HaveLeaked(goods))
+ Eventually(pool.AllRefsCount, flags.EventuallyTimeout).Should(gmatcher.HaveZeroRef())
+})
diff --git a/test/integration/standalone/snapshot/snapshot_suite_test.go b/test/integration/standalone/snapshot/snapshot_suite_test.go
new file mode 100644
index 00000000..4d2eb310
--- /dev/null
+++ b/test/integration/standalone/snapshot/snapshot_suite_test.go
@@ -0,0 +1,130 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright
+// ownership. Apache Software Foundation (ASF) licenses this file to you under
+// the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package snapshot_test
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ . "github.com/onsi/ginkgo/v2"
+ . "github.com/onsi/gomega"
+ "github.com/onsi/gomega/gleak"
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/credentials/insecure"
+
+ commonv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/common/v1"
+ databasev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/database/v1"
+ modelv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/model/v1"
+ propertyv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/property/v1"
+ "github.com/apache/skywalking-banyandb/pkg/grpchelper"
+ "github.com/apache/skywalking-banyandb/pkg/logger"
+ "github.com/apache/skywalking-banyandb/pkg/pool"
+ "github.com/apache/skywalking-banyandb/pkg/test"
+ "github.com/apache/skywalking-banyandb/pkg/test/flags"
+ "github.com/apache/skywalking-banyandb/pkg/test/gmatcher"
+ "github.com/apache/skywalking-banyandb/pkg/test/helpers"
+ "github.com/apache/skywalking-banyandb/pkg/test/setup"
+ "github.com/apache/skywalking-banyandb/pkg/timestamp"
+ test_cases "github.com/apache/skywalking-banyandb/test/cases"
+ casessnapshot "github.com/apache/skywalking-banyandb/test/cases/snapshot"
+ integration_standalone "github.com/apache/skywalking-banyandb/test/integration/standalone"
+)
+
+func TestSnapshot(t *testing.T) {
+ RegisterFailHandler(Fail)
+ RunSpecs(t, "Snapshot Suite", Label(integration_standalone.Labels...))
+}
+
+var (
+ connection *grpc.ClientConn
+ dir string
+ deferFunc func()
+ goods []gleak.Goroutine
+)
+
+var _ = SynchronizedBeforeSuite(func() []byte {
+ goods = gleak.Goroutines()
+ Expect(logger.Init(logger.Logging{
+ Env: "dev",
+ Level: flags.LogLevel,
+ })).To(Succeed())
+ var err error
+ dir, _, err = test.NewSpace()
+ Expect(err).NotTo(HaveOccurred())
+ var ports []int
+ ports, err = test.AllocateFreePorts(4)
+ Expect(err).NotTo(HaveOccurred())
+ var addr string
+ addr, _, deferFunc = setup.ClosableStandalone(dir, ports)
+ ns := timestamp.NowMilli().UnixNano()
+ now := time.Unix(0, ns-ns%int64(time.Minute))
+ test_cases.Initialize(addr, now)
+
+ return []byte(addr)
+}, func(address []byte) {
+ var err error
+ connection, err = grpchelper.Conn(string(address), 10*time.Second,
+ grpc.WithTransportCredentials(insecure.NewCredentials()))
+ Expect(err).NotTo(HaveOccurred())
+ casessnapshot.SharedContext = helpers.SnapshotSharedContext{
+ Connection: connection,
+ RootDir: dir,
+ }
+ gClient := databasev1.NewGroupRegistryServiceClient(connection)
+ _, err = gClient.Create(context.Background(), &databasev1.GroupRegistryServiceCreateRequest{
+ Group: &commonv1.Group{
+ Metadata: &commonv1.Metadata{Name: "g"},
+ Catalog: commonv1.Catalog_CATALOG_PROPERTY,
+ ResourceOpts: &commonv1.ResourceOpts{
+ ShardNum: 2,
+ },
+ },
+ })
+ Expect(err).NotTo(HaveOccurred())
+ client := propertyv1.NewPropertyServiceClient(connection)
+ md := &propertyv1.Metadata{
+ Container: &commonv1.Metadata{
+ Name: "p",
+ Group: "g",
+ },
+ Id: "1",
+ }
+ resp, err := client.Apply(context.Background(), &propertyv1.ApplyRequest{Property: &propertyv1.Property{
+ Metadata: md,
+ Tags: []*modelv1.Tag{
+ {Key: "t1", Value: &modelv1.TagValue{Value: &modelv1.TagValue_Str{Str: &modelv1.Str{Value: "v1"}}}},
+ {Key: "t2", Value: &modelv1.TagValue{Value: &modelv1.TagValue_Str{Str: &modelv1.Str{Value: "v2"}}}},
+ },
+ }})
+ Expect(err).NotTo(HaveOccurred())
+ Expect(resp.Created).To(BeTrue())
+ Expect(resp.TagsNum).To(Equal(uint32(2)))
+})
+
+var _ = SynchronizedAfterSuite(func() {
+ if connection != nil {
+ Expect(connection.Close()).To(Succeed())
+ }
+}, func() {
+ if deferFunc != nil {
+ deferFunc()
+ }
+ Eventually(gleak.Goroutines, flags.EventuallyTimeout).ShouldNot(gleak.HaveLeaked(goods))
+ Eventually(pool.AllRefsCount, flags.EventuallyTimeout).Should(gmatcher.HaveZeroRef())
+})