feat: build wahrwelt A/D toolkit
This commit is contained in:
1 parent
303438d206
commit
653924d8c6
564 files changed
+36310
-49998
No files matched your search
@@ -0,0 +1,167 @@
|
||||
package archive
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"compress/gzip"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
const (
|
||||
maxArchiveEntries = 10000
|
||||
maxArchiveExpanded = 512 << 20
|
||||
)
|
||||
|
||||
func Untar(dst string, r io.Reader) error {
|
||||
abs, err := filepath.Abs(dst)
|
||||
if err != nil {
|
||||
return fmt.Errorf("определение пути назначения: %w", err)
|
||||
}
|
||||
if err := os.MkdirAll(abs, 0700); err != nil {
|
||||
return fmt.Errorf("создание каталога %s: %w", dst, err)
|
||||
}
|
||||
root, err := os.OpenRoot(abs)
|
||||
if err != nil {
|
||||
return fmt.Errorf("открытие каталога назначения %s: %w", dst, err)
|
||||
}
|
||||
defer root.Close()
|
||||
|
||||
gzr, err := gzip.NewReader(r)
|
||||
if err != nil {
|
||||
return fmt.Errorf("создание gzip-читателя: %w", err)
|
||||
}
|
||||
defer func() {
|
||||
if err := gzr.Close(); err != nil {
|
||||
logrus.Errorf("Ошибка закрытия gzip-потока: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
tr := tar.NewReader(gzr)
|
||||
entries := 0
|
||||
var expanded int64
|
||||
for {
|
||||
header, err := tr.Next()
|
||||
if errors.Is(err, io.EOF) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("чтение заголовка архива: %w", err)
|
||||
}
|
||||
if header == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
entries++
|
||||
if entries > maxArchiveEntries {
|
||||
return fmt.Errorf("в архиве больше %d записей", maxArchiveEntries)
|
||||
}
|
||||
if strings.Contains(header.Name, `\`) || !filepath.IsLocal(header.Name) {
|
||||
return fmt.Errorf("небезопасный путь в архиве: %q", header.Name)
|
||||
}
|
||||
name := filepath.Clean(header.Name)
|
||||
if name == "." && header.Typeflag != tar.TypeDir {
|
||||
return fmt.Errorf("у файла в архиве пустой путь")
|
||||
}
|
||||
|
||||
switch header.Typeflag {
|
||||
case tar.TypeDir:
|
||||
if name != "." {
|
||||
if err := root.MkdirAll(name, 0700); err != nil {
|
||||
return fmt.Errorf("создание каталога %s: %w", name, err)
|
||||
}
|
||||
}
|
||||
case tar.TypeReg, tar.TypeRegA:
|
||||
if header.Size < 0 || header.Size > maxArchiveExpanded-expanded {
|
||||
return fmt.Errorf("распакованный архив превышает %d байт", maxArchiveExpanded)
|
||||
}
|
||||
parent := filepath.Dir(name)
|
||||
if parent != "." {
|
||||
if err := root.MkdirAll(parent, 0700); err != nil {
|
||||
return fmt.Errorf("создание каталога %s: %w", parent, err)
|
||||
}
|
||||
}
|
||||
mode := os.FileMode(0600) | (os.FileMode(header.Mode) & 0100)
|
||||
f, err := root.OpenFile(name, os.O_CREATE|os.O_EXCL|os.O_WRONLY, mode)
|
||||
if err != nil {
|
||||
return fmt.Errorf("создание файла %s: %w", name, err)
|
||||
}
|
||||
if _, err := io.CopyN(f, tr, header.Size); err != nil {
|
||||
_ = f.Close()
|
||||
_ = root.Remove(name)
|
||||
return fmt.Errorf("копирование файла %s: %w", name, err)
|
||||
}
|
||||
if err := f.Close(); err != nil {
|
||||
_ = root.Remove(name)
|
||||
return fmt.Errorf("закрытие файла %s: %w", name, err)
|
||||
}
|
||||
expanded += header.Size
|
||||
default:
|
||||
return fmt.Errorf("неподдерживаемый тип записи архива %q", header.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func Tar(src string, w io.Writer) error {
|
||||
root, err := filepath.Abs(src)
|
||||
if err != nil {
|
||||
return fmt.Errorf("определение исходного каталога: %w", err)
|
||||
}
|
||||
if _, err := os.Stat(root); err != nil {
|
||||
return fmt.Errorf("исходные данные недоступны: %w", err)
|
||||
}
|
||||
|
||||
gzw := gzip.NewWriter(w)
|
||||
tw := tar.NewWriter(gzw)
|
||||
walkErr := filepath.Walk(root, func(file string, fi os.FileInfo, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if fi.Mode()&os.ModeSymlink != 0 || !fi.Mode().IsRegular() && !fi.IsDir() {
|
||||
return fmt.Errorf("неподдерживаемый тип исходного файла: %s", file)
|
||||
}
|
||||
name, err := filepath.Rel(root, file)
|
||||
if err != nil {
|
||||
return fmt.Errorf("определение пути архива: %w", err)
|
||||
}
|
||||
header, err := tar.FileInfoHeader(fi, fi.Name())
|
||||
if err != nil {
|
||||
return fmt.Errorf("создание заголовка архива: %w", err)
|
||||
}
|
||||
header.Name = name
|
||||
if err := tw.WriteHeader(header); err != nil {
|
||||
return fmt.Errorf("запись заголовка архива: %w", err)
|
||||
}
|
||||
if fi.IsDir() {
|
||||
return nil
|
||||
}
|
||||
f, err := os.Open(file)
|
||||
if err != nil {
|
||||
return fmt.Errorf("открытие файла %s: %w", file, err)
|
||||
}
|
||||
_, copyErr := io.Copy(tw, f)
|
||||
closeErr := f.Close()
|
||||
if copyErr != nil {
|
||||
return fmt.Errorf("копирование файла %s: %w", file, copyErr)
|
||||
}
|
||||
if closeErr != nil {
|
||||
return fmt.Errorf("закрытие файла %s: %w", file, closeErr)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if closeErr := tw.Close(); walkErr == nil {
|
||||
walkErr = closeErr
|
||||
}
|
||||
if closeErr := gzw.Close(); walkErr == nil {
|
||||
walkErr = closeErr
|
||||
}
|
||||
if walkErr != nil {
|
||||
return fmt.Errorf("упаковка каталога %s: %w", src, walkErr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package archive
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func testTarGz(t *testing.T, headers []tar.Header, bodies [][]byte) *bytes.Buffer {
|
||||
t.Helper()
|
||||
var buf bytes.Buffer
|
||||
gz := gzip.NewWriter(&buf)
|
||||
tw := tar.NewWriter(gz)
|
||||
for i := range headers {
|
||||
require.NoError(t, tw.WriteHeader(&headers[i]))
|
||||
if headers[i].Typeflag == tar.TypeReg || headers[i].Typeflag == tar.TypeRegA {
|
||||
if len(bodies[i]) > 0 {
|
||||
_, err := tw.Write(bodies[i])
|
||||
require.NoError(t, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
require.NoError(t, tw.Close())
|
||||
require.NoError(t, gz.Close())
|
||||
return &buf
|
||||
}
|
||||
|
||||
func TestUntarRejectsEscapingPathsAndLinks(t *testing.T) {
|
||||
for _, header := range []tar.Header{
|
||||
{Name: "../outside", Typeflag: tar.TypeReg, Mode: 0600, Size: 1},
|
||||
{Name: "/tmp/outside", Typeflag: tar.TypeReg, Mode: 0600, Size: 1},
|
||||
{Name: "link", Typeflag: tar.TypeSymlink, Linkname: "../outside", Mode: 0777},
|
||||
{Name: "hardlink", Typeflag: tar.TypeLink, Linkname: "../outside", Mode: 0600},
|
||||
} {
|
||||
t.Run(header.Name, func(t *testing.T) {
|
||||
dst := t.TempDir()
|
||||
archive := testTarGz(t, []tar.Header{header}, [][]byte{{'x'}})
|
||||
require.Error(t, Untar(dst, archive))
|
||||
require.NoError(t, filepath.WalkDir(dst, func(_ string, d os.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if d.Type()&os.ModeSymlink != 0 {
|
||||
t.Errorf("archive created a symlink: %s", d.Name())
|
||||
}
|
||||
return nil
|
||||
}))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestUntarRejectsExpandedSizeLimit(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
gz := gzip.NewWriter(&buf)
|
||||
tw := tar.NewWriter(gz)
|
||||
require.NoError(t, tw.WriteHeader(&tar.Header{
|
||||
Name: "large", Typeflag: tar.TypeReg, Mode: 0600, Size: maxArchiveExpanded + 1,
|
||||
}))
|
||||
require.NoError(t, gz.Close())
|
||||
require.ErrorContains(t, Untar(t.TempDir(), &buf), "превышает")
|
||||
}
|
||||
|
||||
func TestUntarPreservesOnlyOwnerExecute(t *testing.T) {
|
||||
dst := t.TempDir()
|
||||
archive := testTarGz(t, []tar.Header{
|
||||
{Name: "main", Typeflag: tar.TypeReg, Mode: 0755, Size: 1},
|
||||
{Name: "helper", Typeflag: tar.TypeReg, Mode: 0755, Size: 1},
|
||||
}, [][]byte{{'m'}, {'h'}})
|
||||
require.NoError(t, Untar(dst, archive))
|
||||
for _, name := range []string{"main", "helper"} {
|
||||
info, err := os.Stat(filepath.Join(dst, name))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, os.FileMode(0700), info.Mode().Perm())
|
||||
}
|
||||
}
|
||||
|
||||
func TestUntarRejectsTooManyEntries(t *testing.T) {
|
||||
headers := make([]tar.Header, maxArchiveEntries+1)
|
||||
bodies := make([][]byte, len(headers))
|
||||
for i := range headers {
|
||||
headers[i] = tar.Header{Name: fmt.Sprintf("entry/%d", i), Typeflag: tar.TypeDir, Mode: 0700}
|
||||
}
|
||||
archive := testTarGz(t, headers, bodies)
|
||||
require.ErrorContains(t, Untar(t.TempDir(), archive), "больше")
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package filestream
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
fspb "github.com/c4t-but-s4d/neo/v2/proto/go/fileserver"
|
||||
)
|
||||
|
||||
const (
|
||||
chunkSize = 2 * 1024 * 1024 // 2MB
|
||||
// MaxFileSize ограничивает размер файлов, передаваемых по gRPC.
|
||||
MaxFileSize int64 = 128 << 20
|
||||
)
|
||||
|
||||
type DownloadStream interface {
|
||||
Recv() (*fspb.FileStream, error)
|
||||
}
|
||||
|
||||
type UploadStream interface {
|
||||
Send(*fspb.FileStream) error
|
||||
}
|
||||
|
||||
func Save(stream DownloadStream, out io.Writer) error {
|
||||
return SaveLimit(stream, out, 0)
|
||||
}
|
||||
|
||||
// SaveLimit копирует поток с ограничением размера. Нулевой лимит означает,
|
||||
// что размер не ограничен; так сохраняется совместимость с вызывающим кодом,
|
||||
// который устанавливает собственный предел.
|
||||
func SaveLimit(stream DownloadStream, out io.Writer, limit int64) error {
|
||||
var total int64
|
||||
for {
|
||||
in, err := stream.Recv()
|
||||
if errors.Is(err, io.EOF) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("чтение из потока: %w", err)
|
||||
}
|
||||
if limit > 0 && (int64(len(in.Chunk)) > limit-total) {
|
||||
return fmt.Errorf("размер файла превышает лимит %d байт", limit)
|
||||
}
|
||||
n, err := out.Write(in.Chunk)
|
||||
if err != nil {
|
||||
return fmt.Errorf("запись части потока: %w", err)
|
||||
}
|
||||
if n != len(in.Chunk) {
|
||||
return io.ErrShortWrite
|
||||
}
|
||||
total += int64(n)
|
||||
}
|
||||
}
|
||||
|
||||
func Load(in io.Reader, stream UploadStream) error {
|
||||
b := make([]byte, chunkSize)
|
||||
for {
|
||||
n, err := in.Read(b)
|
||||
if errors.Is(err, io.EOF) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("чтение содержимого: %w", err)
|
||||
}
|
||||
if err := stream.Send(&fspb.FileStream{Chunk: b[:n]}); err != nil {
|
||||
return fmt.Errorf("отправка части в поток: %w", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package filestream
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
fspb "github.com/c4t-but-s4d/neo/v2/proto/go/fileserver"
|
||||
)
|
||||
|
||||
type failedReadWriter struct {
|
||||
}
|
||||
|
||||
var errTestWrite = errors.New("test read write error")
|
||||
|
||||
func (rw *failedReadWriter) Write(_ []byte) (n int, err error) {
|
||||
return 0, errTestWrite
|
||||
}
|
||||
|
||||
func (rw *failedReadWriter) Read(_ []byte) (n int, err error) {
|
||||
return 0, errTestWrite
|
||||
}
|
||||
|
||||
type mockUploadStream struct {
|
||||
withError bool
|
||||
buf bytes.Buffer
|
||||
}
|
||||
|
||||
func (ms *mockUploadStream) Send(s *fspb.FileStream) error {
|
||||
ms.buf.Write(s.Chunk)
|
||||
if ms.withError {
|
||||
return errTestWrite
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type mockDownloadStream struct {
|
||||
withError bool
|
||||
data *strings.Reader
|
||||
chunkSize int
|
||||
}
|
||||
|
||||
func (ms *mockDownloadStream) Recv() (*fspb.FileStream, error) {
|
||||
if ms.chunkSize == 0 {
|
||||
ms.chunkSize = chunkSize
|
||||
}
|
||||
if ms.withError {
|
||||
return nil, errTestWrite
|
||||
}
|
||||
b := make([]byte, ms.chunkSize)
|
||||
n, err := ms.data.Read(b)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("reading stream content: %w", err)
|
||||
}
|
||||
return &fspb.FileStream{Chunk: b[:n]}, nil
|
||||
}
|
||||
|
||||
func TestLoad(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
reader io.Reader
|
||||
stream *mockUploadStream
|
||||
want string
|
||||
err error
|
||||
}{
|
||||
{
|
||||
reader: strings.NewReader("somedata"),
|
||||
stream: &mockUploadStream{withError: false},
|
||||
want: "somedata",
|
||||
err: nil,
|
||||
},
|
||||
{
|
||||
reader: &failedReadWriter{},
|
||||
stream: &mockUploadStream{withError: false},
|
||||
want: "",
|
||||
err: errTestWrite,
|
||||
},
|
||||
{
|
||||
reader: strings.NewReader("somedata"),
|
||||
stream: &mockUploadStream{withError: true},
|
||||
want: "somedata",
|
||||
err: errTestWrite,
|
||||
},
|
||||
} {
|
||||
require.ErrorIs(t, Load(tc.reader, tc.stream), tc.err)
|
||||
if diff := cmp.Diff(tc.want, tc.stream.buf.String()); diff != "" {
|
||||
t.Errorf("Load() result mismatch (-want +got):\n%s", diff)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSave(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
writer *strings.Builder
|
||||
stream *mockDownloadStream
|
||||
want string
|
||||
err error
|
||||
}{
|
||||
{
|
||||
writer: &strings.Builder{},
|
||||
stream: &mockDownloadStream{data: strings.NewReader("abacaba")},
|
||||
want: "abacaba",
|
||||
err: nil,
|
||||
},
|
||||
{
|
||||
writer: &strings.Builder{},
|
||||
stream: &mockDownloadStream{data: strings.NewReader("abacaba"), chunkSize: 1},
|
||||
want: "abacaba",
|
||||
err: nil,
|
||||
},
|
||||
{
|
||||
writer: &strings.Builder{},
|
||||
stream: &mockDownloadStream{data: strings.NewReader("abacaba"), withError: true},
|
||||
want: "",
|
||||
err: errTestWrite,
|
||||
},
|
||||
} {
|
||||
require.ErrorIs(t, Save(tc.stream, tc.writer), tc.err)
|
||||
if diff := cmp.Diff(tc.want, tc.writer.String()); diff != "" {
|
||||
t.Errorf("Save() result mismatch (-want +got):\n%s", diff)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveLimitRejectsOversizedStream(t *testing.T) {
|
||||
writer := &strings.Builder{}
|
||||
stream := &mockDownloadStream{data: strings.NewReader("123456"), chunkSize: 3}
|
||||
|
||||
err := SaveLimit(stream, writer, 5)
|
||||
require.ErrorContains(t, err, "превышает лимит")
|
||||
require.Equal(t, "123", writer.String())
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package grpcauth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"fmt"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
const authKey = "authorization"
|
||||
|
||||
var workerMethods = map[string]struct{}{
|
||||
"/exploits.Service/Ping": {},
|
||||
"/exploits.Service/Exploit": {},
|
||||
"/exploits.Service/BroadcastSubscribe": {},
|
||||
"/exploits.Service/SingleRunSubscribe": {},
|
||||
"/fileserver.Service/DownloadFile": {},
|
||||
"/logs.Service/AddLogLines": {},
|
||||
}
|
||||
|
||||
const MinKeyLength = 32
|
||||
|
||||
func ValidateKey(key string) error {
|
||||
if len(key) < MinKeyLength {
|
||||
return fmt.Errorf("ключ gRPC должен содержать не менее %d байт", MinKeyLength)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func ValidateKeyPair(adminKey, workerKey string) error {
|
||||
if err := ValidateKey(adminKey); err != nil {
|
||||
return fmt.Errorf("админский ключ: %w", err)
|
||||
}
|
||||
if err := ValidateKey(workerKey); err != nil {
|
||||
return fmt.Errorf("ключ worker: %w", err)
|
||||
}
|
||||
if keyMatches(adminKey, workerKey) {
|
||||
return fmt.Errorf("админский ключ и ключ worker должны различаться")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func keyMatches(expected, provided string) bool {
|
||||
expectedHash := sha256.Sum256([]byte(expected))
|
||||
providedHash := sha256.Sum256([]byte(provided))
|
||||
return subtle.ConstantTimeCompare(expectedHash[:], providedHash[:]) == 1
|
||||
}
|
||||
|
||||
func NewServerInterceptor(key string) *ServerTokenInterceptor {
|
||||
return &ServerTokenInterceptor{
|
||||
adminKey: key,
|
||||
}
|
||||
}
|
||||
|
||||
func NewServerInterceptorWithWorkerKey(adminKey, workerKey string) *ServerTokenInterceptor {
|
||||
return &ServerTokenInterceptor{adminKey: adminKey, workerKey: workerKey}
|
||||
}
|
||||
|
||||
type ServerTokenInterceptor struct {
|
||||
adminKey string
|
||||
workerKey string
|
||||
}
|
||||
|
||||
func (ti *ServerTokenInterceptor) authorize(ctx context.Context, method string) error {
|
||||
md, ok := metadata.FromIncomingContext(ctx)
|
||||
if !ok {
|
||||
return status.Errorf(codes.Unauthenticated, "метаданные не переданы")
|
||||
}
|
||||
values := md[authKey]
|
||||
if len(values) != 1 {
|
||||
return status.Errorf(codes.Unauthenticated, "токен авторизации не передан")
|
||||
}
|
||||
adminMatch := keyMatches(ti.adminKey, values[0])
|
||||
workerMatch := keyMatches(ti.workerKey, values[0])
|
||||
if adminMatch {
|
||||
return nil
|
||||
}
|
||||
if !workerMatch {
|
||||
return status.Errorf(codes.Unauthenticated, "передан неверный токен")
|
||||
}
|
||||
if _, allowed := workerMethods[method]; !allowed {
|
||||
return status.Errorf(codes.PermissionDenied, "токен worker не разрешает этот вызов")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ti *ServerTokenInterceptor) Unary() grpc.UnaryServerInterceptor {
|
||||
return func(
|
||||
ctx context.Context,
|
||||
req interface{},
|
||||
info *grpc.UnaryServerInfo,
|
||||
handler grpc.UnaryHandler,
|
||||
) (interface{}, error) {
|
||||
if err := ti.authorize(ctx, info.FullMethod); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return handler(ctx, req)
|
||||
}
|
||||
}
|
||||
|
||||
func (ti *ServerTokenInterceptor) Stream() grpc.StreamServerInterceptor {
|
||||
return func(
|
||||
srv interface{},
|
||||
stream grpc.ServerStream,
|
||||
info *grpc.StreamServerInfo,
|
||||
handler grpc.StreamHandler,
|
||||
) error {
|
||||
if err := ti.authorize(stream.Context(), info.FullMethod); err != nil {
|
||||
return err
|
||||
}
|
||||
return handler(srv, stream)
|
||||
}
|
||||
}
|
||||
|
||||
func NewClientInterceptor(key string) *ClientTokenInterceptor {
|
||||
return &ClientTokenInterceptor{token: key}
|
||||
}
|
||||
|
||||
type ClientTokenInterceptor struct {
|
||||
token string
|
||||
}
|
||||
|
||||
func (interceptor *ClientTokenInterceptor) attachToken(ctx context.Context) context.Context {
|
||||
return metadata.AppendToOutgoingContext(ctx, authKey, interceptor.token)
|
||||
}
|
||||
|
||||
func (interceptor *ClientTokenInterceptor) Unary() grpc.UnaryClientInterceptor {
|
||||
return func(
|
||||
ctx context.Context,
|
||||
method string,
|
||||
req, reply interface{},
|
||||
cc *grpc.ClientConn,
|
||||
invoker grpc.UnaryInvoker,
|
||||
opts ...grpc.CallOption,
|
||||
) error {
|
||||
return invoker(interceptor.attachToken(ctx), method, req, reply, cc, opts...)
|
||||
}
|
||||
}
|
||||
|
||||
func (interceptor *ClientTokenInterceptor) Stream() grpc.StreamClientInterceptor {
|
||||
return func(
|
||||
ctx context.Context,
|
||||
desc *grpc.StreamDesc,
|
||||
cc *grpc.ClientConn,
|
||||
method string,
|
||||
streamer grpc.Streamer,
|
||||
opts ...grpc.CallOption,
|
||||
) (grpc.ClientStream, error) {
|
||||
return streamer(interceptor.attachToken(ctx), desc, cc, method, opts...)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package grpcauth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
epb "github.com/c4t-but-s4d/neo/v2/proto/go/exploits"
|
||||
fspb "github.com/c4t-but-s4d/neo/v2/proto/go/fileserver"
|
||||
lpb "github.com/c4t-but-s4d/neo/v2/proto/go/logs"
|
||||
"github.com/stretchr/testify/require"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
const (
|
||||
testAdminKey = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
|
||||
testWorkerKey = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
|
||||
)
|
||||
|
||||
func authContext(key string) context.Context {
|
||||
return metadata.NewIncomingContext(context.Background(), metadata.Pairs(authKey, key))
|
||||
}
|
||||
|
||||
func TestWorkerTokenMethodAccess(t *testing.T) {
|
||||
interceptor := NewServerInterceptorWithWorkerKey(testAdminKey, testWorkerKey)
|
||||
for method := range workerMethods {
|
||||
require.NoError(t, interceptor.authorize(authContext(testWorkerKey), method), method)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkerTokenCannotCallAdministrativeOrUnknownMethods(t *testing.T) {
|
||||
interceptor := NewServerInterceptorWithWorkerKey(testAdminKey, testWorkerKey)
|
||||
services := []struct {
|
||||
name string
|
||||
methods []string
|
||||
streams []string
|
||||
}{
|
||||
{epb.Service_ServiceDesc.ServiceName, methodNames(epb.Service_ServiceDesc.Methods), streamNames(epb.Service_ServiceDesc.Streams)},
|
||||
{fspb.Service_ServiceDesc.ServiceName, methodNames(fspb.Service_ServiceDesc.Methods), streamNames(fspb.Service_ServiceDesc.Streams)},
|
||||
{lpb.Service_ServiceDesc.ServiceName, methodNames(lpb.Service_ServiceDesc.Methods), streamNames(lpb.Service_ServiceDesc.Streams)},
|
||||
}
|
||||
for _, service := range services {
|
||||
for _, method := range append(service.methods, service.streams...) {
|
||||
fullMethod := "/" + service.name + "/" + method
|
||||
_, workerAllowed := workerMethods[fullMethod]
|
||||
err := interceptor.authorize(authContext(testWorkerKey), fullMethod)
|
||||
if workerAllowed {
|
||||
require.NoError(t, err, fullMethod)
|
||||
} else {
|
||||
require.Equal(t, codes.PermissionDenied, status.Code(err), fullMethod)
|
||||
}
|
||||
}
|
||||
}
|
||||
err := interceptor.authorize(authContext(testWorkerKey), "/unknown.Service/Method")
|
||||
require.Equal(t, codes.PermissionDenied, status.Code(err))
|
||||
}
|
||||
|
||||
func methodNames(methods []grpc.MethodDesc) []string {
|
||||
result := make([]string, 0, len(methods))
|
||||
for _, method := range methods {
|
||||
result = append(result, method.MethodName)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func streamNames(streams []grpc.StreamDesc) []string {
|
||||
result := make([]string, 0, len(streams))
|
||||
for _, stream := range streams {
|
||||
result = append(result, stream.StreamName)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func TestAdminTokenCanCallAllMethods(t *testing.T) {
|
||||
interceptor := NewServerInterceptorWithWorkerKey(testAdminKey, testWorkerKey)
|
||||
require.NoError(t, interceptor.authorize(authContext(testAdminKey), "/unknown.Service/Method"))
|
||||
}
|
||||
|
||||
func TestAuthorizationComparisonRejectsMismatchesAtEveryPosition(t *testing.T) {
|
||||
interceptor := NewServerInterceptorWithWorkerKey(testAdminKey, testWorkerKey)
|
||||
for i := range testAdminKey {
|
||||
wrong := []byte(testAdminKey)
|
||||
wrong[i] ^= 1
|
||||
err := interceptor.authorize(authContext(string(wrong)), "/exploits.Service/Ping")
|
||||
require.Equal(t, codes.Unauthenticated, status.Code(err))
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateKeyPair(t *testing.T) {
|
||||
require.NoError(t, ValidateKeyPair(testAdminKey, testWorkerKey))
|
||||
require.Error(t, ValidateKeyPair(testAdminKey, testAdminKey))
|
||||
require.Error(t, ValidateKeyPair("short", testWorkerKey))
|
||||
require.Error(t, ValidateKeyPair(testAdminKey, "short"))
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package gstream
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type Sizable interface {
|
||||
EstimateSize() int
|
||||
}
|
||||
|
||||
type BatcherFunc[S, D any] func(t []S) (D, error)
|
||||
|
||||
func NewDynamicSizeCache[T Sizable, M any](s WStream[M], maxSize int, bf BatcherFunc[T, *M]) *DynamicSizeCache[T, M] {
|
||||
return &DynamicSizeCache[T, M]{
|
||||
stream: s,
|
||||
batcher: bf,
|
||||
maxSize: maxSize,
|
||||
}
|
||||
}
|
||||
|
||||
type DynamicSizeCache[T Sizable, M any] struct {
|
||||
stream WStream[M]
|
||||
batcher BatcherFunc[T, *M]
|
||||
maxSize int
|
||||
curSize int
|
||||
queue []T
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func (d *DynamicSizeCache[T, M]) Queue(ts ...T) error {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
|
||||
for _, t := range ts {
|
||||
d.curSize += t.EstimateSize()
|
||||
d.queue = append(d.queue, t)
|
||||
if d.curSize >= d.maxSize {
|
||||
if err := d.flushUnlocked(); err != nil {
|
||||
return fmt.Errorf("отправка накопленных данных: %w", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *DynamicSizeCache[T, M]) Flush() error {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
return d.flushUnlocked()
|
||||
}
|
||||
|
||||
func (d *DynamicSizeCache[T, M]) Context() context.Context {
|
||||
return d.stream.Context()
|
||||
}
|
||||
|
||||
// flushUnlocked вызывается при удерживаемой блокировке.
|
||||
func (d *DynamicSizeCache[T, M]) flushUnlocked() error {
|
||||
if len(d.queue) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
m, err := d.batcher(d.queue)
|
||||
if err != nil {
|
||||
return fmt.Errorf("преобразование накопленных данных: %w", err)
|
||||
}
|
||||
if err := d.stream.Send(m); err != nil {
|
||||
return fmt.Errorf("отправка накопленных данных в поток: %w", err)
|
||||
}
|
||||
d.curSize = 0
|
||||
d.queue = d.queue[:0]
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package gstream
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestDynamicSizeCacheSimple(t *testing.T) {
|
||||
s := &mockWStream{}
|
||||
cache := NewDynamicSizeCache[*mockSizable, []*mockSizable](
|
||||
s,
|
||||
10,
|
||||
func(a []*mockSizable) (*[]*mockSizable, error) {
|
||||
return &a, nil
|
||||
},
|
||||
)
|
||||
gen := func(a int) *mockSizable {
|
||||
return &mockSizable{size: a}
|
||||
}
|
||||
require.NoError(t, cache.Queue(gen(5), gen(3)))
|
||||
require.Empty(t, s.sent)
|
||||
|
||||
require.NoError(t, cache.Flush())
|
||||
require.Equal(t, [][]*mockSizable{{gen(5), gen(3)}}, s.sent)
|
||||
s.sent = nil
|
||||
|
||||
require.NoError(t, cache.Queue(gen(5), gen(3)))
|
||||
require.NoError(t, cache.Queue(gen(2), gen(3)))
|
||||
require.Equal(t, [][]*mockSizable{{gen(5), gen(3), gen(2)}}, s.sent)
|
||||
require.NoError(t, cache.Flush())
|
||||
require.Equal(t, [][]*mockSizable{{gen(5), gen(3), gen(2)}, {gen(3)}}, s.sent)
|
||||
}
|
||||
|
||||
func TestDynamicSizeCache_ErrorPropagation(t *testing.T) {
|
||||
mockErr := errors.New("mock error")
|
||||
s := &mockWStream{returnErr: mockErr}
|
||||
cache := NewDynamicSizeCache[*mockSizable, []*mockSizable](
|
||||
s,
|
||||
5,
|
||||
func(a []*mockSizable) (*[]*mockSizable, error) {
|
||||
return &a, nil
|
||||
},
|
||||
)
|
||||
err := cache.Queue(&mockSizable{size: 5})
|
||||
require.ErrorIs(t, err, mockErr)
|
||||
require.NotEqual(t, mockErr, err)
|
||||
require.Equal(t, [][]*mockSizable{{&mockSizable{size: 5}}}, s.sent)
|
||||
}
|
||||
|
||||
type mockSizable struct {
|
||||
size int
|
||||
}
|
||||
|
||||
func (s *mockSizable) EstimateSize() int {
|
||||
return s.size
|
||||
}
|
||||
|
||||
type mockWStream struct {
|
||||
sent [][]*mockSizable
|
||||
returnErr error
|
||||
}
|
||||
|
||||
func (m *mockWStream) Send(t *[]*mockSizable) error {
|
||||
tmp := make([]*mockSizable, len(*t))
|
||||
copy(tmp, *t)
|
||||
m.sent = append(m.sent, tmp)
|
||||
return m.returnErr
|
||||
}
|
||||
|
||||
func (m *mockWStream) Context() context.Context {
|
||||
return context.Background()
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package gstream
|
||||
|
||||
import "context"
|
||||
|
||||
type RStream[T any] interface {
|
||||
Recv() (*T, error)
|
||||
Context() context.Context
|
||||
}
|
||||
|
||||
type WStream[T any] interface {
|
||||
Send(*T) error
|
||||
Context() context.Context
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package gstream
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type wrappedWStream[In, Out any] struct {
|
||||
original WStream[Out]
|
||||
mapper func(*In) *Out
|
||||
}
|
||||
|
||||
func Wrap[In, Out any](original WStream[Out], mapper func(*In) *Out) WStream[In] {
|
||||
return &wrappedWStream[In, Out]{
|
||||
original: original,
|
||||
mapper: mapper,
|
||||
}
|
||||
}
|
||||
|
||||
func (w *wrappedWStream[In, Out]) Send(t *In) error {
|
||||
if err := w.original.Send(w.mapper(t)); err != nil {
|
||||
return fmt.Errorf("отправка в исходный поток: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *wrappedWStream[In, Out]) Context() context.Context {
|
||||
return w.original.Context()
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package hostbucket
|
||||
|
||||
import (
|
||||
"sync"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/google/go-cmp/cmp/cmpopts"
|
||||
|
||||
"github.com/c4t-but-s4d/neo/v2/pkg/rendezvous"
|
||||
epb "github.com/c4t-but-s4d/neo/v2/proto/go/exploits"
|
||||
)
|
||||
|
||||
func New(teams map[string]string) *HostBucket {
|
||||
return &HostBucket{
|
||||
buck: make(map[string]*epb.TeamBucket),
|
||||
nodes: nil,
|
||||
teams: teams,
|
||||
r: rendezvous.New(),
|
||||
}
|
||||
}
|
||||
|
||||
type HostBucket struct {
|
||||
m sync.RWMutex
|
||||
buck map[string]*epb.TeamBucket
|
||||
nodes []*node
|
||||
teams map[string]string
|
||||
r *rendezvous.Rendezvous
|
||||
}
|
||||
|
||||
// TODO: ускорить добавление и удаление IP-адресов
|
||||
func (hb *HostBucket) UpdateTeams(teams map[string]string) {
|
||||
lessFunc := func(s1, s2 string) bool {
|
||||
return s1 < s2
|
||||
}
|
||||
if !cmp.Equal(teams, hb.teams, cmpopts.SortSlices(lessFunc)) {
|
||||
hb.m.Lock()
|
||||
defer hb.m.Unlock()
|
||||
hb.teams = teams
|
||||
hb.rehash()
|
||||
}
|
||||
}
|
||||
|
||||
func (hb *HostBucket) Buckets() map[string]*epb.TeamBucket {
|
||||
hb.m.RLock()
|
||||
defer hb.m.RUnlock()
|
||||
|
||||
clone := make(map[string]*epb.TeamBucket, len(hb.buck))
|
||||
for k, v := range hb.buck {
|
||||
clone[k] = v
|
||||
}
|
||||
return clone
|
||||
}
|
||||
|
||||
func (hb *HostBucket) Exists(id string) (exists bool) {
|
||||
hb.m.RLock()
|
||||
defer hb.m.RUnlock()
|
||||
_, exists = hb.buck[id]
|
||||
return
|
||||
}
|
||||
|
||||
func (hb *HostBucket) AddNode(id string, weight int) {
|
||||
hb.m.Lock()
|
||||
defer hb.m.Unlock()
|
||||
|
||||
if _, ok := hb.buck[id]; ok {
|
||||
return
|
||||
}
|
||||
|
||||
hb.buck[id] = &epb.TeamBucket{}
|
||||
n := &node{
|
||||
id: id,
|
||||
weight: weight,
|
||||
}
|
||||
hb.nodes = append(hb.nodes, n)
|
||||
// TODO: ускорить добавление узлов
|
||||
hb.rehash()
|
||||
}
|
||||
|
||||
func (hb *HostBucket) DeleteNode(id string) bool {
|
||||
hb.m.Lock()
|
||||
defer hb.m.Unlock()
|
||||
if _, ok := hb.buck[id]; !ok {
|
||||
return false
|
||||
}
|
||||
for i, n := range hb.nodes {
|
||||
if n.id == id {
|
||||
last := len(hb.nodes) - 1
|
||||
hb.nodes[i] = hb.nodes[last]
|
||||
hb.nodes[last] = nil
|
||||
hb.nodes = hb.nodes[:last]
|
||||
delete(hb.buck, id)
|
||||
|
||||
// TODO: ускорить удаление узлов
|
||||
hb.rehash()
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (hb *HostBucket) rehash() {
|
||||
for _, v := range hb.buck {
|
||||
v.Reset()
|
||||
}
|
||||
if len(hb.nodes) == 0 {
|
||||
return
|
||||
}
|
||||
for id, ip := range hb.teams {
|
||||
bestHash := 0.0
|
||||
bestNode := ""
|
||||
|
||||
for _, n := range hb.nodes {
|
||||
hash := hb.r.Calculate(n.id, n.weight, id)
|
||||
if bestNode == "" || hash > bestHash {
|
||||
bestNode = n.id
|
||||
bestHash = hash
|
||||
}
|
||||
}
|
||||
|
||||
if hb.buck[bestNode].Teams == nil {
|
||||
hb.buck[bestNode].Teams = make(map[string]string)
|
||||
}
|
||||
hb.buck[bestNode].Teams[id] = ip
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
package hostbucket
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"testing"
|
||||
|
||||
"github.com/denisbrodbeck/machineid"
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/google/go-cmp/cmp/cmpopts"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/c4t-but-s4d/neo/v2/pkg/testutils"
|
||||
)
|
||||
|
||||
func TestHostBucket_Add(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
b *HostBucket
|
||||
users []string
|
||||
want map[string]int
|
||||
}{
|
||||
{
|
||||
b: New(map[string]string{"id1": "ip1"}),
|
||||
users: []string{"u1"},
|
||||
want: map[string]int{"u1": 1},
|
||||
},
|
||||
{
|
||||
b: New(map[string]string{"id1": "ip1", "id2": "ip2", "id3": "ip3"}),
|
||||
users: []string{},
|
||||
want: map[string]int{},
|
||||
},
|
||||
} {
|
||||
for _, u := range tc.users {
|
||||
tc.b.AddNode(u, 1)
|
||||
}
|
||||
b := tc.b.Buckets()
|
||||
gotTeams := make(map[string]string)
|
||||
for cid, wantn := range tc.want {
|
||||
ipb := b[cid]
|
||||
require.Len(t, ipb.Teams, wantn)
|
||||
for k, v := range ipb.Teams {
|
||||
gotTeams[k] = v
|
||||
}
|
||||
}
|
||||
if diff := cmp.Diff(tc.b.teams, gotTeams, cmpopts.SortSlices(testutils.LessString)); diff != "" && len(tc.want) > 0 {
|
||||
t.Errorf("HostBucket.AddNode() summary ips mismatch (-want +got):\n%s", diff)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHostBucket_Add_Distribution(t *testing.T) {
|
||||
populate := func(idCount, ipCount, weightMax int) *HostBucket {
|
||||
teams := make(map[string]string)
|
||||
for i := 0; i < ipCount; i++ {
|
||||
id := fmt.Sprintf("team-%d", i)
|
||||
teams[id] = testutils.RandomIP()
|
||||
}
|
||||
hb := New(teams)
|
||||
|
||||
mid, err := machineid.ID()
|
||||
require.NoError(t, err)
|
||||
for i := 0; i < idCount; i++ {
|
||||
id := testutils.RandomString(len(mid))
|
||||
w := testutils.RandomInt(1, weightMax+1)
|
||||
hb.AddNode(id, w)
|
||||
}
|
||||
return hb
|
||||
}
|
||||
|
||||
for _, tc := range []struct {
|
||||
ipCount int
|
||||
idCount int
|
||||
maxDeviation float64
|
||||
weightMax int
|
||||
runs int
|
||||
}{
|
||||
{
|
||||
100,
|
||||
5,
|
||||
1.5,
|
||||
32,
|
||||
100,
|
||||
},
|
||||
{
|
||||
1000,
|
||||
10,
|
||||
1,
|
||||
32,
|
||||
100,
|
||||
},
|
||||
} {
|
||||
for i := 0; i < tc.runs; i++ {
|
||||
b := populate(tc.idCount, tc.ipCount, tc.weightMax)
|
||||
sizes := make([]float64, tc.idCount)
|
||||
meanSize := 0.0
|
||||
for i := range sizes {
|
||||
id := b.nodes[i].id
|
||||
sizes[i] = float64(len(b.buck[id].Teams)) / float64(b.nodes[i].weight)
|
||||
meanSize += sizes[i]
|
||||
}
|
||||
meanSize /= float64(len(sizes))
|
||||
|
||||
for i := range sizes {
|
||||
deviation := math.Abs((sizes[i] - meanSize) / meanSize)
|
||||
require.Truef(
|
||||
t,
|
||||
deviation <= tc.maxDeviation,
|
||||
"Deviation for bucket %s too large: %f > %f, target size: %f, weight %d, got size: %f",
|
||||
b.nodes[i].id,
|
||||
deviation,
|
||||
tc.maxDeviation,
|
||||
meanSize,
|
||||
b.nodes[i].weight,
|
||||
sizes[i],
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHostBucket_Balancing(t *testing.T) {
|
||||
populate := func(ipCount, idCount int) *HostBucket {
|
||||
teams := make(map[string]string)
|
||||
for i := 0; i < ipCount; i++ {
|
||||
id := fmt.Sprintf("team-%d", i)
|
||||
teams[id] = testutils.RandomIP()
|
||||
}
|
||||
hb := New(teams)
|
||||
|
||||
mid, err := machineid.ID()
|
||||
require.NoError(t, err)
|
||||
for i := 0; i < idCount; i++ {
|
||||
id := testutils.RandomString(len(mid))
|
||||
hb.AddNode(id, 1)
|
||||
}
|
||||
return hb
|
||||
}
|
||||
|
||||
for _, tc := range []struct {
|
||||
ipCount int
|
||||
idCount int
|
||||
maxMoved float64
|
||||
cntAdd int
|
||||
cntDelete int
|
||||
}{
|
||||
{
|
||||
100,
|
||||
5,
|
||||
0.3,
|
||||
0,
|
||||
1,
|
||||
},
|
||||
{
|
||||
1000,
|
||||
10,
|
||||
0.2,
|
||||
1,
|
||||
0,
|
||||
},
|
||||
} {
|
||||
b := populate(tc.ipCount, tc.idCount)
|
||||
|
||||
beforeByIP := make(map[string]string)
|
||||
for _, n := range b.nodes {
|
||||
for _, ip := range b.buck[n.id].Teams {
|
||||
beforeByIP[ip] = n.id
|
||||
}
|
||||
}
|
||||
|
||||
getCntMoved := func() int {
|
||||
cntMoved := 0
|
||||
for _, n := range b.nodes {
|
||||
for _, ip := range b.buck[n.id].Teams {
|
||||
if n.id != beforeByIP[ip] {
|
||||
cntMoved++
|
||||
}
|
||||
beforeByIP[ip] = n.id
|
||||
}
|
||||
}
|
||||
return cntMoved
|
||||
}
|
||||
|
||||
for i := 0; i < tc.cntDelete; i++ {
|
||||
toDelete := testutils.RandomInt(0, tc.idCount)
|
||||
b.DeleteNode(b.nodes[toDelete].id)
|
||||
}
|
||||
cntMoved := getCntMoved()
|
||||
movedFraction := float64(cntMoved) / float64(tc.ipCount)
|
||||
require.Truef(
|
||||
t,
|
||||
movedFraction <= tc.maxMoved,
|
||||
"Too many ips moved after delete: %f%%, %d of %d",
|
||||
movedFraction*100,
|
||||
cntMoved,
|
||||
tc.ipCount,
|
||||
)
|
||||
|
||||
mid, err := machineid.ID()
|
||||
require.NoError(t, err)
|
||||
for i := 0; i < tc.cntAdd; i++ {
|
||||
id := testutils.RandomString(len(mid))
|
||||
b.AddNode(id, 1)
|
||||
}
|
||||
cntMoved = getCntMoved()
|
||||
movedFraction = float64(cntMoved) / float64(tc.ipCount)
|
||||
require.Truef(
|
||||
t,
|
||||
movedFraction <= tc.maxMoved,
|
||||
"Too many ips moved after delete: %f%%, %d of %d",
|
||||
movedFraction*100,
|
||||
cntMoved,
|
||||
tc.ipCount,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHostBucket_Delete(t *testing.T) {
|
||||
populate := func(teams map[string]string, ids []string) *HostBucket {
|
||||
hb := New(teams)
|
||||
for _, id := range ids {
|
||||
hb.AddNode(id, 1)
|
||||
}
|
||||
return hb
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
b *HostBucket
|
||||
delete []string
|
||||
want map[string]int
|
||||
}{
|
||||
{
|
||||
b: populate(map[string]string{"team1": "ip1", "team2": "ip2"}, []string{"id1", "id2"}),
|
||||
delete: []string{"id1"},
|
||||
want: map[string]int{"id2": 2},
|
||||
},
|
||||
{
|
||||
b: populate(map[string]string{"team1": "ip1", "team2": "ip2"}, []string{"id1"}),
|
||||
delete: []string{"id1"},
|
||||
want: map[string]int{},
|
||||
},
|
||||
} {
|
||||
for _, tid := range tc.delete {
|
||||
tc.b.DeleteNode(tid)
|
||||
}
|
||||
gotTeams := make(map[string]string)
|
||||
for cid, wantn := range tc.want {
|
||||
ipb := tc.b.buck[cid]
|
||||
require.Len(t, ipb.Teams, wantn)
|
||||
for k, v := range ipb.Teams {
|
||||
gotTeams[k] = v
|
||||
}
|
||||
}
|
||||
if diff := cmp.Diff(tc.b.teams, gotTeams, cmpopts.SortSlices(testutils.LessString)); diff != "" && len(tc.want) > 0 {
|
||||
t.Errorf("HostBucket.DeleteNode() summary ips mismatch (-want +got):\n%s", diff)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package hostbucket
|
||||
|
||||
type node struct {
|
||||
id string
|
||||
weight int
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package joblogger
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"runtime"
|
||||
"strings"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/c4t-but-s4d/neo/v2/internal/logger"
|
||||
logspb "github.com/c4t-but-s4d/neo/v2/proto/go/logs"
|
||||
)
|
||||
|
||||
// Ограничение длины сообщения журнала - 1 МиБ.
|
||||
const maxMessageLength = 1024 * 1024
|
||||
|
||||
func New(exploit string, version int64, team string, sender Sender) *JobLogger {
|
||||
return &JobLogger{
|
||||
exploit: exploit,
|
||||
version: version,
|
||||
team: team,
|
||||
sender: sender,
|
||||
}
|
||||
}
|
||||
|
||||
type JobLogger struct {
|
||||
exploit string
|
||||
version int64
|
||||
team string
|
||||
sender Sender
|
||||
}
|
||||
|
||||
func (l *JobLogger) Debugf(format string, args ...interface{}) {
|
||||
l.logProxy(logrus.DebugLevel, format, args...)
|
||||
msg := fmt.Sprintf(format, args...)
|
||||
l.sender.Add(l.newLine(msg, "debug"))
|
||||
}
|
||||
|
||||
func (l *JobLogger) Infof(format string, args ...interface{}) {
|
||||
l.logProxy(logrus.InfoLevel, format, args...)
|
||||
msg := fmt.Sprintf(format, args...)
|
||||
l.sender.Add(l.newLine(msg, "info"))
|
||||
}
|
||||
|
||||
func (l *JobLogger) Warningf(format string, args ...interface{}) {
|
||||
l.logProxy(logrus.WarnLevel, format, args...)
|
||||
msg := fmt.Sprintf(format, args...)
|
||||
l.sender.Add(l.newLine(msg, "warning"))
|
||||
}
|
||||
|
||||
func (l *JobLogger) Errorf(format string, args ...interface{}) {
|
||||
l.logProxy(logrus.ErrorLevel, format, args...)
|
||||
msg := fmt.Sprintf(format, args...)
|
||||
l.sender.Add(l.newLine(msg, "error"))
|
||||
}
|
||||
|
||||
func (l *JobLogger) newLine(msg, level string) *logspb.LogLine {
|
||||
return &logspb.LogLine{
|
||||
Exploit: l.exploit,
|
||||
Version: l.version,
|
||||
Message: sanitizeMessage(msg),
|
||||
Level: level,
|
||||
Team: l.team,
|
||||
}
|
||||
}
|
||||
|
||||
func (l *JobLogger) getLogger() *logrus.Entry {
|
||||
return logrus.WithFields(logrus.Fields{
|
||||
"exploit": l.exploit,
|
||||
"version": l.version,
|
||||
"team": l.team,
|
||||
})
|
||||
}
|
||||
|
||||
func (l *JobLogger) logProxy(level logrus.Level, format string, args ...interface{}) {
|
||||
if logrus.IsLevelEnabled(level) {
|
||||
l.
|
||||
getLogger().
|
||||
WithField(logger.CustomKeyFile, fileInfo(3)).
|
||||
Logf(level, format, args...)
|
||||
}
|
||||
}
|
||||
|
||||
func sanitizeMessage(msg string) string {
|
||||
if len(msg) > maxMessageLength {
|
||||
msg = msg[:maxMessageLength]
|
||||
}
|
||||
return msg
|
||||
}
|
||||
|
||||
func fileInfo(skip int) string {
|
||||
_, file, line, ok := runtime.Caller(skip)
|
||||
if !ok {
|
||||
file = "<???>"
|
||||
line = 1
|
||||
} else {
|
||||
slash := strings.LastIndex(file, "/")
|
||||
if slash >= 0 {
|
||||
file = file[slash+1:]
|
||||
}
|
||||
}
|
||||
return fmt.Sprintf("%s:%d", file, line)
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package joblogger
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/c4t-but-s4d/neo/v2/internal/client"
|
||||
logspb "github.com/c4t-but-s4d/neo/v2/proto/go/logs"
|
||||
)
|
||||
|
||||
const (
|
||||
sendInterval = time.Second
|
||||
)
|
||||
|
||||
type Sender interface {
|
||||
Add(lines ...*logspb.LogLine)
|
||||
}
|
||||
|
||||
func NewDummySender() *DummySender {
|
||||
return &DummySender{}
|
||||
}
|
||||
|
||||
type DummySender struct{}
|
||||
|
||||
func (s *DummySender) Add(...*logspb.LogLine) {
|
||||
}
|
||||
|
||||
func NewRemoteSender(client *client.Client) *RemoteSender {
|
||||
return &RemoteSender{
|
||||
client: client,
|
||||
queue: make([]*logspb.LogLine, 0, 1000),
|
||||
}
|
||||
}
|
||||
|
||||
type RemoteSender struct {
|
||||
client *client.Client
|
||||
queue []*logspb.LogLine
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func (s *RemoteSender) Add(lines ...*logspb.LogLine) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.queue = append(s.queue, lines...)
|
||||
}
|
||||
|
||||
func (s *RemoteSender) Start(ctx context.Context) {
|
||||
ticker := time.NewTicker(sendInterval)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
if err := s.send(ctx); err != nil {
|
||||
logrus.Errorf("Не удалось отправить журналы: %v", err)
|
||||
}
|
||||
case <-ctx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *RemoteSender) send(ctx context.Context) error {
|
||||
s.mu.Lock()
|
||||
batch := make([]*logspb.LogLine, len(s.queue))
|
||||
copy(batch, s.queue)
|
||||
s.queue = s.queue[:0]
|
||||
s.mu.Unlock()
|
||||
|
||||
if len(batch) == 0 {
|
||||
logrus.Debugf("Отправка записей журнала: %d", len(batch))
|
||||
} else {
|
||||
logrus.Infof("Отправка записей журнала: %d", len(batch))
|
||||
}
|
||||
if err := s.client.AddLogLines(ctx, batch...); err != nil {
|
||||
return fmt.Errorf("отправка пакета на сервер: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package neosync
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
func Sleep(ctx context.Context, d time.Duration) {
|
||||
t := time.NewTimer(d)
|
||||
defer t.Stop()
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-t.C:
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package neosync
|
||||
|
||||
import "sync"
|
||||
|
||||
func AwaitWG(wg *sync.WaitGroup) <-chan struct{} {
|
||||
c := make(chan struct{})
|
||||
go func() {
|
||||
wg.Wait()
|
||||
close(c)
|
||||
}()
|
||||
return c
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package pubsub
|
||||
|
||||
import "sync"
|
||||
|
||||
type PubSub[T any] struct {
|
||||
subs map[string]*Subscription[T]
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
func NewPubSub[T any]() *PubSub[T] {
|
||||
return &PubSub[T]{
|
||||
subs: make(map[string]*Subscription[T]),
|
||||
}
|
||||
}
|
||||
|
||||
func (ps *PubSub[T]) Publish(msg T) {
|
||||
ps.mu.RLock()
|
||||
defer ps.mu.RUnlock()
|
||||
for _, sub := range ps.subs {
|
||||
sub.Push(msg)
|
||||
}
|
||||
}
|
||||
|
||||
func (ps *PubSub[T]) Subscribe(onMsg MessageHandler[T]) *Subscription[T] {
|
||||
ps.mu.Lock()
|
||||
defer ps.mu.Unlock()
|
||||
|
||||
sub := NewSubscription(onMsg)
|
||||
ps.subs[sub.GetID()] = sub
|
||||
return sub
|
||||
}
|
||||
|
||||
func (ps *PubSub[T]) Unsubscribe(sub *Subscription[T]) {
|
||||
ps.mu.Lock()
|
||||
defer ps.mu.Unlock()
|
||||
delete(ps.subs, sub.GetID())
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
package pubsub
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"go.uber.org/goleak"
|
||||
|
||||
"github.com/c4t-but-s4d/neo/v2/pkg/neosync"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
goleak.VerifyTestMain(m)
|
||||
}
|
||||
|
||||
func TestPubSub_single(t *testing.T) {
|
||||
p := NewPubSub[string]()
|
||||
|
||||
wg := sync.WaitGroup{}
|
||||
wg.Add(1)
|
||||
|
||||
sub := p.Subscribe(func(msg string) error {
|
||||
require.Equal(t, "blah-blah", msg)
|
||||
wg.Done()
|
||||
return nil
|
||||
})
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go sub.Run(ctx)
|
||||
|
||||
p.Publish("blah-blah")
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func TestPubSub_nonBlockPublish(t *testing.T) {
|
||||
p := NewPubSub[string]()
|
||||
|
||||
wg := sync.WaitGroup{}
|
||||
wg.Add(11)
|
||||
|
||||
sub := p.Subscribe(func(msg string) error {
|
||||
require.Equal(t, "pew-pew", msg)
|
||||
wg.Done()
|
||||
return nil
|
||||
})
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go sub.Run(ctx)
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
for i := 0; i < 11; i++ {
|
||||
p.Publish("pew-pew")
|
||||
}
|
||||
close(done)
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-time.After(1 * time.Second):
|
||||
t.Fatal("publish method must not be blocked")
|
||||
case <-done:
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func TestPubSub_multipleSubscribers(t *testing.T) {
|
||||
p := NewPubSub[string]()
|
||||
|
||||
wgFirst := sync.WaitGroup{}
|
||||
wgFirst.Add(1)
|
||||
wgSecond := sync.WaitGroup{}
|
||||
wgSecond.Add(1)
|
||||
|
||||
sub1 := p.Subscribe(func(msg string) error {
|
||||
require.Equal(t, "blah", msg)
|
||||
wgFirst.Done()
|
||||
return nil
|
||||
})
|
||||
ctx1, cancel1 := context.WithCancel(context.Background())
|
||||
defer cancel1()
|
||||
go sub1.Run(ctx1)
|
||||
|
||||
sub2 := p.Subscribe(func(msg string) error {
|
||||
require.Equal(t, "blah", msg)
|
||||
wgSecond.Done()
|
||||
return nil
|
||||
})
|
||||
ctx2, cancel2 := context.WithCancel(context.Background())
|
||||
defer cancel2()
|
||||
go sub2.Run(ctx2)
|
||||
|
||||
p.Publish("blah")
|
||||
|
||||
wgFirst.Wait()
|
||||
wgSecond.Wait()
|
||||
}
|
||||
|
||||
func TestPubSub_slowpoke(t *testing.T) {
|
||||
p := NewPubSub[string]()
|
||||
|
||||
const samples = 100
|
||||
|
||||
wgSlow := sync.WaitGroup{}
|
||||
wgSlow.Add(samples)
|
||||
slowCtx, slowCancel := context.WithCancel(context.Background())
|
||||
defer func() {
|
||||
slowCancel()
|
||||
wgSlow.Wait()
|
||||
}()
|
||||
|
||||
slowSub := p.Subscribe(func(msg string) error {
|
||||
defer wgSlow.Done()
|
||||
|
||||
select {
|
||||
case <-slowCtx.Done():
|
||||
return nil
|
||||
default:
|
||||
time.Sleep(1 * time.Second)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
go slowSub.Run(slowCtx)
|
||||
|
||||
fastWg := sync.WaitGroup{}
|
||||
fastWg.Add(samples)
|
||||
|
||||
fastSub := p.Subscribe(func(msg string) error {
|
||||
require.Equal(t, "pew-pew", msg)
|
||||
fastWg.Done()
|
||||
return nil
|
||||
})
|
||||
fastCtx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go fastSub.Run(fastCtx)
|
||||
|
||||
for i := 0; i < samples; i++ {
|
||||
p.Publish("pew-pew")
|
||||
}
|
||||
|
||||
select {
|
||||
case <-time.After(1 * time.Second):
|
||||
t.Fatal("publish blocks on slowpoke?")
|
||||
case <-neosync.AwaitWG(&fastWg):
|
||||
// ok
|
||||
}
|
||||
}
|
||||
|
||||
func TestPubSub_unsubscribe(t *testing.T) {
|
||||
p := NewPubSub[string]()
|
||||
|
||||
sub1 := p.Subscribe(func(msg string) error {
|
||||
t.Error("first subscriber must not be called")
|
||||
return nil
|
||||
})
|
||||
ctx1, cancel1 := context.WithCancel(context.Background())
|
||||
defer cancel1()
|
||||
go sub1.Run(ctx1)
|
||||
|
||||
p.Unsubscribe(sub1)
|
||||
|
||||
wg := sync.WaitGroup{}
|
||||
wg.Add(1)
|
||||
|
||||
sub2 := p.Subscribe(func(msg string) error {
|
||||
require.Equal(t, "pew-pew", msg)
|
||||
wg.Done()
|
||||
return nil
|
||||
})
|
||||
ctx2, cancel2 := context.WithCancel(context.Background())
|
||||
defer cancel2()
|
||||
go sub2.Run(ctx2)
|
||||
|
||||
p.Publish("pew-pew")
|
||||
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func TestPubSub_sequencePublishers(t *testing.T) {
|
||||
p := NewPubSub[string]()
|
||||
|
||||
wg := sync.WaitGroup{}
|
||||
wg.Add(10)
|
||||
|
||||
sub := p.Subscribe(func(msg string) error {
|
||||
require.Equal(t, "pew-pew", msg)
|
||||
wg.Done()
|
||||
return nil
|
||||
})
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go sub.Run(ctx)
|
||||
|
||||
for i := 0; i < 10; i++ {
|
||||
p.Publish("pew-pew")
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func TestPubSub_concurrentPublishers(t *testing.T) {
|
||||
p := NewPubSub[string]()
|
||||
|
||||
wg := sync.WaitGroup{}
|
||||
wg.Add(10)
|
||||
|
||||
sub := p.Subscribe(func(msg string) error {
|
||||
require.Equal(t, "pew-pew", msg)
|
||||
wg.Done()
|
||||
return nil
|
||||
})
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go sub.Run(ctx)
|
||||
|
||||
for i := 0; i < 10; i++ {
|
||||
go p.Publish("pew-pew")
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func TestPubSub_msgOrder(t *testing.T) {
|
||||
p := NewPubSub[uint64]()
|
||||
|
||||
wg := sync.WaitGroup{}
|
||||
wg.Add(15)
|
||||
|
||||
c := uint64(0)
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
sub := p.Subscribe(func(msg uint64) error {
|
||||
expected := atomic.AddUint64(&c, 1)
|
||||
require.Equal(t, expected, msg)
|
||||
wg.Done()
|
||||
return nil
|
||||
})
|
||||
go sub.Run(ctx)
|
||||
|
||||
for i := uint64(1); i < 11; i++ {
|
||||
if i == 6 {
|
||||
c := uint64(5)
|
||||
sub := p.Subscribe(func(msg uint64) error {
|
||||
expected := atomic.AddUint64(&c, 1)
|
||||
require.Equal(t, expected, msg)
|
||||
wg.Done()
|
||||
return nil
|
||||
})
|
||||
go sub.Run(ctx)
|
||||
}
|
||||
|
||||
p.Publish(i)
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package pubsub
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type MessageHandler[T any] func(T) error
|
||||
|
||||
type Subscription[T any] struct {
|
||||
id string
|
||||
queue []T
|
||||
mu sync.Mutex
|
||||
notify chan struct{}
|
||||
h MessageHandler[T]
|
||||
}
|
||||
|
||||
func NewSubscription[T any](onMsg MessageHandler[T]) *Subscription[T] {
|
||||
id := uuid.NewString()
|
||||
return &Subscription[T]{
|
||||
id: id,
|
||||
queue: nil,
|
||||
notify: make(chan struct{}, 1),
|
||||
h: onMsg,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Subscription[T]) Run(ctx context.Context) {
|
||||
for {
|
||||
select {
|
||||
case _, ok := <-s.notify:
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
for {
|
||||
s.mu.Lock()
|
||||
if len(s.queue) == 0 {
|
||||
s.mu.Unlock()
|
||||
break
|
||||
}
|
||||
cmd := s.queue[0]
|
||||
s.queue = s.queue[1:]
|
||||
s.mu.Unlock()
|
||||
|
||||
logrus.Debugf("Обработка сообщения типа %T в подписке %s", cmd, s.id)
|
||||
if err := s.h(cmd); err != nil {
|
||||
logrus.Errorf("Ошибка обработчика сообщения подписки: %v", err)
|
||||
continue
|
||||
}
|
||||
}
|
||||
case <-ctx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Subscription[T]) Push(msg T) {
|
||||
s.mu.Lock()
|
||||
s.queue = append(s.queue, msg)
|
||||
s.mu.Unlock()
|
||||
|
||||
select {
|
||||
case s.notify <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Subscription[T]) GetID() string {
|
||||
return s.id
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package pubsub
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestNewSubscription(t *testing.T) {
|
||||
sub := NewSubscription[int](nil)
|
||||
newSub := NewSubscription[int](nil)
|
||||
require.NotEqual(t, sub.GetID(), newSub.GetID(), "id is not random")
|
||||
}
|
||||
|
||||
func Test_subscription_Push(t *testing.T) {
|
||||
sub := &Subscription[string]{
|
||||
id: "test",
|
||||
queue: nil,
|
||||
notify: make(chan struct{}),
|
||||
h: nil,
|
||||
}
|
||||
sub.Push("test")
|
||||
require.Equal(t, []string{"test"}, sub.queue)
|
||||
}
|
||||
|
||||
func Test_subscription_Run(t *testing.T) {
|
||||
var received string
|
||||
signal := make(chan struct{})
|
||||
handler := func(msg string) error {
|
||||
received = msg
|
||||
close(signal)
|
||||
return nil
|
||||
}
|
||||
sub := &Subscription[string]{
|
||||
id: "test",
|
||||
queue: nil,
|
||||
notify: make(chan struct{}, 1),
|
||||
h: handler,
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go sub.Run(ctx)
|
||||
|
||||
const msg = "message"
|
||||
sub.Push(msg)
|
||||
|
||||
select {
|
||||
case <-signal:
|
||||
break
|
||||
case <-time.After(time.Millisecond * 100):
|
||||
t.Errorf("Handler was not called in time")
|
||||
}
|
||||
|
||||
require.Equal(t, msg, received)
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package rendezvous
|
||||
|
||||
import (
|
||||
"hash"
|
||||
"sync"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
"github.com/spaolacci/murmur3"
|
||||
)
|
||||
|
||||
type Rendezvous struct {
|
||||
hcache map[string]uint64
|
||||
mu sync.RWMutex
|
||||
h hash.Hash64
|
||||
}
|
||||
|
||||
func New() *Rendezvous {
|
||||
return &Rendezvous{
|
||||
hcache: make(map[string]uint64),
|
||||
h: murmur3.New64WithSeed(1337),
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Rendezvous) checkCache(key string) (uint64, bool) {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
raw, ok := r.hcache[key]
|
||||
return raw, ok
|
||||
}
|
||||
|
||||
func (r *Rendezvous) calcHash(key string) uint64 {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
|
||||
r.h.Reset()
|
||||
if _, err := r.h.Write([]byte(key)); err != nil {
|
||||
logrus.Fatalf("Не удалось вычислить хэш: %v", err)
|
||||
}
|
||||
rawVal := r.h.Sum64()
|
||||
r.hcache[key] = rawVal
|
||||
return rawVal
|
||||
}
|
||||
|
||||
func (r *Rendezvous) Calculate(node string, weight int, value string) float64 {
|
||||
key := combineKey(node, value)
|
||||
if raw, ok := r.checkCache(key); ok {
|
||||
return weightHash(raw, weight)
|
||||
}
|
||||
raw := r.calcHash(key)
|
||||
return weightHash(raw, weight)
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package rendezvous
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestRendezvous_Calculate(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
nodeID string
|
||||
nodeWeight int
|
||||
value string
|
||||
}{
|
||||
{
|
||||
"simple_test",
|
||||
"kek",
|
||||
1,
|
||||
"lol",
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
r := New()
|
||||
hash := r.Calculate(tt.nodeID, tt.nodeWeight, tt.value)
|
||||
if hash == 0 {
|
||||
t.Error("Zero hash returned")
|
||||
}
|
||||
|
||||
k := combineKey(tt.nodeID, tt.value)
|
||||
rhash, ok := r.checkCache(k)
|
||||
require.True(t, ok)
|
||||
needHash := weightHash(rhash, tt.nodeWeight)
|
||||
require.Equal(t, needHash, hash)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package rendezvous
|
||||
|
||||
import "math"
|
||||
|
||||
const maxUInt64 = float64(^uint64(0))
|
||||
|
||||
func combineKey(nodeID, value string) string {
|
||||
return nodeID + ":" + value
|
||||
}
|
||||
|
||||
func weightHash(hash uint64, weight int) float64 {
|
||||
scale := 1.0 / -math.Log(float64(hash)/maxUInt64)
|
||||
return scale * float64(weight)
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package testutils
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/c4t-but-s4d/neo/v2/pkg/joblogger"
|
||||
)
|
||||
|
||||
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
||||
|
||||
var seededRand = rand.New(rand.NewSource(1337))
|
||||
|
||||
func LessString(v1, v2 string) bool {
|
||||
return v1 < v2
|
||||
}
|
||||
|
||||
func CanceledContext() context.Context {
|
||||
ctx, c := context.WithCancel(context.Background())
|
||||
defer c()
|
||||
return ctx
|
||||
}
|
||||
|
||||
func TimedOutContext() context.Context {
|
||||
ctx, c := context.WithTimeout(context.Background(), time.Second*0)
|
||||
defer c()
|
||||
return ctx
|
||||
}
|
||||
|
||||
func RandomStringWithCharset(length int, charset string) string {
|
||||
b := make([]byte, length)
|
||||
for i := range b {
|
||||
b[i] = charset[seededRand.Intn(len(charset))]
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func RandomString(length int) string {
|
||||
return RandomStringWithCharset(length, charset)
|
||||
}
|
||||
|
||||
func RandomInt(min, max int) int {
|
||||
n := seededRand.Intn(max - min)
|
||||
return min + n
|
||||
}
|
||||
|
||||
func RandomIP() string {
|
||||
gen := func() int {
|
||||
return RandomInt(0, 256)
|
||||
}
|
||||
return fmt.Sprintf("%d.%d.%d.%d", gen(), gen(), gen(), gen())
|
||||
}
|
||||
|
||||
func MetricsNamespace() string {
|
||||
return fmt.Sprintf("test_%s", uuid.NewString()[:8])
|
||||
}
|
||||
|
||||
type HTTPRequestChecker func(*testing.T, *http.Request)
|
||||
|
||||
func NewCheckedTestServer(t *testing.T, checker HTTPRequestChecker) *httptest.Server {
|
||||
t.Helper()
|
||||
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
checker(t, r)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
return s
|
||||
}
|
||||
|
||||
func DummyJobLogger(name, team string) *joblogger.JobLogger {
|
||||
return joblogger.New(name, 1, team, joblogger.NewDummySender())
|
||||
}
|
||||
Reference in new issue
Block a user