mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-02 09:07:17 +01:00
Compare commits
17
Commits
fix-pr-7909
...
4.05
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
87b71029f7 | ||
|
|
ade2e58cf4 | ||
|
|
4e2af080df | ||
|
|
6f28cb7f87 | ||
|
|
c405ff1374 | ||
|
|
998bcf2b3f | ||
|
|
f7f133166a | ||
|
|
60707f99d8 | ||
|
|
31a4f57cd9 | ||
|
|
5a135f8c5a | ||
|
|
099da9332b | ||
|
|
b107c45176 | ||
|
|
9072e1d38a | ||
|
|
1424fe6ed5 | ||
|
|
8f182e68e8 | ||
|
|
568f1fe5b1 | ||
|
|
91fcc60898 |
No files matched your search
@@ -54,9 +54,9 @@ Table of Contents
|
||||
=================
|
||||
|
||||
* [Quick Start](#quick-start)
|
||||
* [Quick Start with weed mini](#quick-start-with-weed-mini)
|
||||
* [Quick Start for S3 API on Docker](#quick-start-for-s3-api-on-docker)
|
||||
* [Quick Start with Single Binary](#quick-start-with-single-binary)
|
||||
* [Quick Start SeaweedFS S3 on AWS](#quick-start-seaweedfs-s3-on-aws)
|
||||
* [Introduction](#introduction)
|
||||
* [Features](#features)
|
||||
* [Additional Features](#additional-features)
|
||||
@@ -78,6 +78,32 @@ Table of Contents
|
||||
|
||||
# Quick Start #
|
||||
|
||||
|
||||
## Quick Start with weed mini ##
|
||||
The easiest way to get started with SeaweedFS for development and testing:
|
||||
|
||||
* Download the latest binary from https://github.com/seaweedfs/seaweedfs/releases and unzip a single binary file `weed` or `weed.exe`.
|
||||
|
||||
Example:
|
||||
|
||||
```bash
|
||||
# remove quarantine on macOS
|
||||
# xattr -d com.apple.quarantine ./weed
|
||||
export AWS_ACCESS_KEY_ID=admin
|
||||
export AWS_SECRET_ACCESS_KEY=key
|
||||
./weed mini -dir=/data
|
||||
```
|
||||
|
||||
This single command starts a complete SeaweedFS setup with:
|
||||
- **Master UI**: http://localhost:9333
|
||||
- **Volume Server**: http://localhost:9340
|
||||
- **Filer UI**: http://localhost:8888
|
||||
- **S3 Endpoint**: http://localhost:8333
|
||||
- **WebDAV**: http://localhost:7333
|
||||
- **Admin UI**: http://localhost:23646
|
||||
|
||||
Perfect for development, testing, learning SeaweedFS, and single node deployments!
|
||||
|
||||
## Quick Start for S3 API on Docker ##
|
||||
|
||||
`docker run -p 8333:8333 chrislusf/seaweedfs server -s3`
|
||||
@@ -85,13 +111,10 @@ Table of Contents
|
||||
## Quick Start with Single Binary ##
|
||||
* Download the latest binary from https://github.com/seaweedfs/seaweedfs/releases and unzip a single binary file `weed` or `weed.exe`. Or run `go install github.com/seaweedfs/seaweedfs/weed@latest`.
|
||||
* `export AWS_ACCESS_KEY_ID=admin ; export AWS_SECRET_ACCESS_KEY=key` as the admin credentials to access the object store.
|
||||
* Run `weed server -dir=/some/data/dir -s3` to start one master, one volume server, one filer, and one S3 gateway.
|
||||
* Run `weed server -dir=/some/data/dir -s3` to start one master, one volume server, one filer, and one S3 gateway. The difference with `weed mini` is that `weed mini` can auto configure based on the single host environment, while `weed server` requires manual configuration and are designed for production use.
|
||||
|
||||
Also, to increase capacity, just add more volume servers by running `weed volume -dir="/some/data/dir2" -master="<master_host>:9333" -port=8081` locally, or on a different machine, or on thousands of machines. That is it!
|
||||
|
||||
## Quick Start SeaweedFS S3 on AWS ##
|
||||
* Setup fast production-ready [SeaweedFS S3 on AWS with cloudformation](https://aws.amazon.com/marketplace/pp/prodview-nzelz5gprlrjc)
|
||||
|
||||
# Introduction #
|
||||
|
||||
SeaweedFS is a simple and highly scalable distributed file system. There are two objectives:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
apiVersion: v1
|
||||
description: SeaweedFS
|
||||
name: seaweedfs
|
||||
appVersion: "4.04"
|
||||
appVersion: "4.05"
|
||||
# Dev note: Trigger a helm chart release by `git tag -a helm-<version>`
|
||||
version: 4.0.404
|
||||
version: 4.0.405
|
||||
@@ -4,6 +4,13 @@
|
||||
{{- /* Determine service name based on deployment mode */}}
|
||||
{{- $serviceName := ternary (printf "%s-all-in-one" (include "seaweedfs.name" .)) (printf "%s-s3" (include "seaweedfs.name" .)) .Values.allInOne.enabled }}
|
||||
{{- $s3Port := .Values.allInOne.s3.port | default .Values.s3.port }}
|
||||
{{- /* Build hosts list - support both legacy .host (string) and new .hosts (array) for backwards compatibility */}}
|
||||
{{- $hosts := list }}
|
||||
{{- if kindIs "slice" .Values.s3.ingress.host }}
|
||||
{{- $hosts = .Values.s3.ingress.host }}
|
||||
{{- else if .Values.s3.ingress.host }}
|
||||
{{- $hosts = list .Values.s3.ingress.host }}
|
||||
{{- end }}
|
||||
{{- if semverCompare ">=1.19-0" .Capabilities.KubeVersion.GitVersion }}
|
||||
apiVersion: networking.k8s.io/v1
|
||||
{{- else if semverCompare ">=1.14-0" .Capabilities.KubeVersion.GitVersion }}
|
||||
@@ -30,6 +37,25 @@ spec:
|
||||
tls:
|
||||
{{ .Values.s3.ingress.tls | default list | toYaml | nindent 6}}
|
||||
rules:
|
||||
{{- if $hosts }}
|
||||
{{- range $hosts }}
|
||||
- host: {{ . | quote }}
|
||||
http:
|
||||
paths:
|
||||
- path: {{ $.Values.s3.ingress.path | quote }}
|
||||
pathType: {{ $.Values.s3.ingress.pathType | quote }}
|
||||
backend:
|
||||
{{- if semverCompare ">=1.19-0" $.Capabilities.KubeVersion.GitVersion }}
|
||||
service:
|
||||
name: {{ $serviceName }}
|
||||
port:
|
||||
number: {{ $s3Port }}
|
||||
{{- else }}
|
||||
serviceName: {{ $serviceName }}
|
||||
servicePort: {{ $s3Port }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- else }}
|
||||
- http:
|
||||
paths:
|
||||
- path: {{ .Values.s3.ingress.path | quote }}
|
||||
@@ -44,7 +70,5 @@ spec:
|
||||
serviceName: {{ $serviceName }}
|
||||
servicePort: {{ $s3Port }}
|
||||
{{- end }}
|
||||
{{- if .Values.s3.ingress.host }}
|
||||
host: {{ .Values.s3.ingress.host | quote }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
@@ -134,7 +134,7 @@ spec:
|
||||
{{- if .Values.worker.adminServer }}
|
||||
-admin={{ .Values.worker.adminServer }} \
|
||||
{{- else }}
|
||||
-admin={{ template "seaweedfs.name" . }}-admin.{{ .Release.Namespace }}:{{ .Values.admin.port }} \
|
||||
-admin={{ template "seaweedfs.name" . }}-admin.{{ .Release.Namespace }}:{{ .Values.admin.port }}{{ if .Values.admin.grpcPort }}.{{ .Values.admin.grpcPort }}{{ end }} \
|
||||
{{- end }}
|
||||
-capabilities={{ .Values.worker.capabilities }} \
|
||||
-maxConcurrent={{ .Values.worker.maxConcurrent }} \
|
||||
|
||||
@@ -1012,7 +1012,7 @@ s3:
|
||||
ingress:
|
||||
enabled: false
|
||||
className: ""
|
||||
# host: false for "*" hostname
|
||||
# host: false for "*" hostname, or an array for multiple hostnames
|
||||
host: "seaweedfs.cluster.local"
|
||||
path: "/"
|
||||
pathType: Prefix
|
||||
@@ -1231,9 +1231,9 @@ worker:
|
||||
metricsPort: 9327
|
||||
|
||||
# Admin server to connect to
|
||||
# Format: "host:port" or auto-discover from admin service
|
||||
adminServer: ""
|
||||
|
||||
|
||||
# Worker capabilities - comma-separated list
|
||||
# Available: vacuum, balance, erasure_coding
|
||||
# Default: "vacuum,balance,erasure_coding" (all capabilities)
|
||||
|
||||
@@ -225,11 +225,11 @@ func (s *WorkerGrpcServer) WorkerStream(stream worker_pb.WorkerService_WorkerStr
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
glog.Infof("Worker %s connection closed: %v", workerID, ctx.Err())
|
||||
s.unregisterWorker(workerID)
|
||||
s.unregisterWorker(conn)
|
||||
return nil
|
||||
case <-connCtx.Done():
|
||||
glog.Infof("Worker %s connection cancelled", workerID)
|
||||
s.unregisterWorker(workerID)
|
||||
s.unregisterWorker(conn)
|
||||
return nil
|
||||
default:
|
||||
}
|
||||
@@ -241,7 +241,7 @@ func (s *WorkerGrpcServer) WorkerStream(stream worker_pb.WorkerService_WorkerStr
|
||||
} else {
|
||||
glog.Errorf("Error receiving from worker %s: %v", workerID, err)
|
||||
}
|
||||
s.unregisterWorker(workerID)
|
||||
s.unregisterWorker(conn)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -294,7 +294,7 @@ func (s *WorkerGrpcServer) handleWorkerMessage(conn *WorkerConnection, msg *work
|
||||
|
||||
case *worker_pb.WorkerMessage_Shutdown:
|
||||
glog.Infof("Worker %s shutting down: %s", workerID, m.Shutdown.Reason)
|
||||
s.unregisterWorker(workerID)
|
||||
s.unregisterWorker(conn)
|
||||
|
||||
default:
|
||||
glog.Warningf("Unknown message type from worker %s", workerID)
|
||||
@@ -463,17 +463,24 @@ func (s *WorkerGrpcServer) safeCloseOutgoingChannel(conn *WorkerConnection, sour
|
||||
}
|
||||
|
||||
// unregisterWorker removes a worker connection
|
||||
func (s *WorkerGrpcServer) unregisterWorker(workerID string) {
|
||||
func (s *WorkerGrpcServer) unregisterWorker(conn *WorkerConnection) {
|
||||
s.connMutex.Lock()
|
||||
conn, exists := s.connections[workerID]
|
||||
existingConn, exists := s.connections[conn.workerID]
|
||||
if !exists {
|
||||
s.connMutex.Unlock()
|
||||
glog.V(2).Infof("unregisterWorker: worker %s not found in connections map (already unregistered)", workerID)
|
||||
glog.V(2).Infof("unregisterWorker: worker %s not found in connections map (already unregistered)", conn.workerID)
|
||||
return
|
||||
}
|
||||
|
||||
// Only remove if it matches the specific connection instance
|
||||
if existingConn != conn {
|
||||
s.connMutex.Unlock()
|
||||
glog.V(1).Infof("unregisterWorker: worker %s connection replaced, skipping unregister for old connection", conn.workerID)
|
||||
return
|
||||
}
|
||||
|
||||
// Remove from map first to prevent duplicate cleanup attempts
|
||||
delete(s.connections, workerID)
|
||||
delete(s.connections, conn.workerID)
|
||||
s.connMutex.Unlock()
|
||||
|
||||
// Cancel context to signal goroutines to stop
|
||||
@@ -482,7 +489,7 @@ func (s *WorkerGrpcServer) unregisterWorker(workerID string) {
|
||||
// Safely close the outgoing channel with recover to handle potential double-close
|
||||
s.safeCloseOutgoingChannel(conn, "unregisterWorker")
|
||||
|
||||
glog.V(1).Infof("Unregistered worker %s", workerID)
|
||||
glog.V(1).Infof("Unregistered worker %s", conn.workerID)
|
||||
}
|
||||
|
||||
// cleanupRoutine periodically cleans up stale connections
|
||||
@@ -505,16 +512,19 @@ func (s *WorkerGrpcServer) cleanupStaleConnections() {
|
||||
cutoff := time.Now().Add(-2 * time.Minute)
|
||||
|
||||
s.connMutex.Lock()
|
||||
defer s.connMutex.Unlock()
|
||||
|
||||
for workerID, conn := range s.connections {
|
||||
// collect connections to remove first to avoid deadlock if unregisterWorker locks
|
||||
var toRemove []*WorkerConnection
|
||||
for _, conn := range s.connections {
|
||||
if conn.lastSeen.Before(cutoff) {
|
||||
glog.Warningf("Cleaning up stale worker connection: %s", workerID)
|
||||
conn.cancel()
|
||||
s.safeCloseOutgoingChannel(conn, "cleanupStaleConnections")
|
||||
delete(s.connections, workerID)
|
||||
toRemove = append(toRemove, conn)
|
||||
}
|
||||
}
|
||||
s.connMutex.Unlock()
|
||||
|
||||
for _, conn := range toRemove {
|
||||
glog.Warningf("Cleaning up stale worker connection: %s", conn.workerID)
|
||||
s.unregisterWorker(conn)
|
||||
}
|
||||
}
|
||||
|
||||
// GetConnectedWorkers returns a list of currently connected workers
|
||||
|
||||
@@ -224,6 +224,36 @@ func runFuse(cmd *Command, args []string) bool {
|
||||
fusermountPath = parameter.value
|
||||
case "config_dir":
|
||||
util.ConfigurationFileDirectory.Set(parameter.value)
|
||||
// FUSE performance options
|
||||
case "writebackCache":
|
||||
if parsed, err := strconv.ParseBool(parameter.value); err == nil {
|
||||
mountOptions.writebackCache = &parsed
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "failed to parse 'writebackCache' value %q: %v\n", parameter.value, err)
|
||||
return false
|
||||
}
|
||||
case "asyncDio":
|
||||
if parsed, err := strconv.ParseBool(parameter.value); err == nil {
|
||||
mountOptions.asyncDio = &parsed
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "failed to parse 'asyncDio' value %q: %v\n", parameter.value, err)
|
||||
return false
|
||||
}
|
||||
case "cacheSymlink":
|
||||
if parsed, err := strconv.ParseBool(parameter.value); err == nil {
|
||||
mountOptions.cacheSymlink = &parsed
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "failed to parse 'cacheSymlink' value %q: %v\n", parameter.value, err)
|
||||
return false
|
||||
}
|
||||
// macOS-specific FUSE options
|
||||
case "sys.novncache":
|
||||
if parsed, err := strconv.ParseBool(parameter.value); err == nil {
|
||||
mountOptions.novncache = &parsed
|
||||
} else {
|
||||
fmt.Fprintf(os.Stderr, "failed to parse 'sys.novncache' value %q: %v\n", parameter.value, err)
|
||||
return false
|
||||
}
|
||||
default:
|
||||
t := parameter.name
|
||||
if parameter.value != "true" {
|
||||
|
||||
@@ -47,6 +47,14 @@ type MountOptions struct {
|
||||
rdmaReadOnly *bool
|
||||
rdmaMaxConcurrent *int
|
||||
rdmaTimeoutMs *int
|
||||
|
||||
// FUSE performance options
|
||||
writebackCache *bool
|
||||
asyncDio *bool
|
||||
cacheSymlink *bool
|
||||
|
||||
// macOS-specific FUSE options
|
||||
novncache *bool
|
||||
}
|
||||
|
||||
var (
|
||||
@@ -102,6 +110,14 @@ func init() {
|
||||
mountCpuProfile = cmdMount.Flag.String("cpuprofile", "", "cpu profile output file")
|
||||
mountMemProfile = cmdMount.Flag.String("memprofile", "", "memory profile output file")
|
||||
mountReadRetryTime = cmdMount.Flag.Duration("readRetryTime", 6*time.Second, "maximum read retry wait time")
|
||||
|
||||
// FUSE performance options
|
||||
mountOptions.writebackCache = cmdMount.Flag.Bool("writebackCache", false, "enable FUSE writeback cache for improved write performance (at risk of data loss on crash)")
|
||||
mountOptions.asyncDio = cmdMount.Flag.Bool("asyncDio", false, "enable async direct I/O for better concurrency")
|
||||
mountOptions.cacheSymlink = cmdMount.Flag.Bool("cacheSymlink", false, "enable symlink caching to reduce metadata lookups")
|
||||
|
||||
// macOS-specific FUSE options
|
||||
mountOptions.novncache = cmdMount.Flag.Bool("sys.novncache", false, "(macOS only) disable vnode name caching to avoid stale data")
|
||||
}
|
||||
|
||||
var cmdMount = &Command{
|
||||
|
||||
+41
-29
@@ -208,12 +208,24 @@ func RunMount(option *MountOptions, umask os.FileMode) bool {
|
||||
if runtime.GOARCH == "amd64" {
|
||||
fuseMountOptions.Options = append(fuseMountOptions.Options, "noapplexattr")
|
||||
}
|
||||
// fuseMountOptions.Options = append(fuseMountOptions.Options, "novncache") // need to test effectiveness
|
||||
if option.novncache != nil && *option.novncache {
|
||||
fuseMountOptions.Options = append(fuseMountOptions.Options, "novncache")
|
||||
}
|
||||
fuseMountOptions.Options = append(fuseMountOptions.Options, "slow_statfs")
|
||||
fuseMountOptions.Options = append(fuseMountOptions.Options, "volname="+serverFriendlyName)
|
||||
fuseMountOptions.Options = append(fuseMountOptions.Options, fmt.Sprintf("iosize=%d", ioSizeMB*1024*1024))
|
||||
}
|
||||
|
||||
if option.writebackCache != nil && *option.writebackCache {
|
||||
fuseMountOptions.Options = append(fuseMountOptions.Options, "writeback_cache")
|
||||
}
|
||||
if option.asyncDio != nil && *option.asyncDio {
|
||||
fuseMountOptions.Options = append(fuseMountOptions.Options, "async_dio")
|
||||
}
|
||||
if option.cacheSymlink != nil && *option.cacheSymlink {
|
||||
fuseMountOptions.EnableSymlinkCaching = true
|
||||
}
|
||||
|
||||
// find mount point
|
||||
mountRoot := filerMountRootPath
|
||||
if mountRoot != "/" && strings.HasSuffix(mountRoot, "/") {
|
||||
@@ -226,34 +238,34 @@ func RunMount(option *MountOptions, umask os.FileMode) bool {
|
||||
}
|
||||
|
||||
seaweedFileSystem := mount.NewSeaweedFileSystem(&mount.Option{
|
||||
MountDirectory: dir,
|
||||
FilerAddresses: filerAddresses,
|
||||
GrpcDialOption: grpcDialOption,
|
||||
FilerMountRootPath: mountRoot,
|
||||
Collection: *option.collection,
|
||||
Replication: *option.replication,
|
||||
TtlSec: int32(*option.ttlSec),
|
||||
DiskType: types.ToDiskType(*option.diskType),
|
||||
ChunkSizeLimit: int64(chunkSizeLimitMB) * 1024 * 1024,
|
||||
ConcurrentWriters: *option.concurrentWriters,
|
||||
ConcurrentReaders: *option.concurrentReaders,
|
||||
CacheDirForRead: *option.cacheDirForRead,
|
||||
CacheSizeMBForRead: *option.cacheSizeMBForRead,
|
||||
CacheDirForWrite: cacheDirForWrite,
|
||||
CacheMetaTTlSec: *option.cacheMetaTtlSec,
|
||||
DataCenter: *option.dataCenter,
|
||||
Quota: int64(*option.collectionQuota) * 1024 * 1024,
|
||||
MountUid: uid,
|
||||
MountGid: gid,
|
||||
MountMode: mountMode,
|
||||
MountCtime: fileInfo.ModTime(),
|
||||
MountMtime: time.Now(),
|
||||
Umask: umask,
|
||||
VolumeServerAccess: *mountOptions.volumeServerAccess,
|
||||
Cipher: cipher,
|
||||
UidGidMapper: uidGidMapper,
|
||||
DisableXAttr: *option.disableXAttr,
|
||||
IsMacOs: runtime.GOOS == "darwin",
|
||||
MountDirectory: dir,
|
||||
FilerAddresses: filerAddresses,
|
||||
GrpcDialOption: grpcDialOption,
|
||||
FilerMountRootPath: mountRoot,
|
||||
Collection: *option.collection,
|
||||
Replication: *option.replication,
|
||||
TtlSec: int32(*option.ttlSec),
|
||||
DiskType: types.ToDiskType(*option.diskType),
|
||||
ChunkSizeLimit: int64(chunkSizeLimitMB) * 1024 * 1024,
|
||||
ConcurrentWriters: *option.concurrentWriters,
|
||||
ConcurrentReaders: *option.concurrentReaders,
|
||||
CacheDirForRead: *option.cacheDirForRead,
|
||||
CacheSizeMBForRead: *option.cacheSizeMBForRead,
|
||||
CacheDirForWrite: cacheDirForWrite,
|
||||
CacheMetaTTlSec: *option.cacheMetaTtlSec,
|
||||
DataCenter: *option.dataCenter,
|
||||
Quota: int64(*option.collectionQuota) * 1024 * 1024,
|
||||
MountUid: uid,
|
||||
MountGid: gid,
|
||||
MountMode: mountMode,
|
||||
MountCtime: fileInfo.ModTime(),
|
||||
MountMtime: time.Now(),
|
||||
Umask: umask,
|
||||
VolumeServerAccess: *mountOptions.volumeServerAccess,
|
||||
Cipher: cipher,
|
||||
UidGidMapper: uidGidMapper,
|
||||
DisableXAttr: *option.disableXAttr,
|
||||
IsMacOs: runtime.GOOS == "darwin",
|
||||
MetadataFlushSeconds: *option.metadataFlushSeconds,
|
||||
// RDMA acceleration options
|
||||
RdmaEnabled: *option.rdmaEnabled,
|
||||
|
||||
@@ -23,6 +23,7 @@ import (
|
||||
_ "github.com/seaweedfs/seaweedfs/weed/worker/tasks/balance"
|
||||
_ "github.com/seaweedfs/seaweedfs/weed/worker/tasks/erasure_coding"
|
||||
_ "github.com/seaweedfs/seaweedfs/weed/worker/tasks/vacuum"
|
||||
|
||||
// TODO: Implement additional task packages (add to default capabilities when ready):
|
||||
// _ "github.com/seaweedfs/seaweedfs/weed/worker/tasks/remote" - for uploading volumes to remote/cloud storage
|
||||
// _ "github.com/seaweedfs/seaweedfs/weed/worker/tasks/replication" - for fixing replication issues and maintaining data consistency
|
||||
|
||||
@@ -55,6 +55,7 @@ func (f *Filer) assignAndUpload(targetFile string, data []byte) (*operation.Assi
|
||||
Count: 1,
|
||||
Collection: util.Nvl(f.metaLogCollection, rule.Collection),
|
||||
Replication: util.Nvl(f.metaLogReplication, rule.Replication),
|
||||
DiskType: rule.DiskType,
|
||||
WritableVolumeCount: rule.VolumeGrowthCount,
|
||||
}
|
||||
|
||||
|
||||
@@ -5,12 +5,16 @@ import (
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/rsa"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -58,6 +62,13 @@ type OIDCConfig struct {
|
||||
|
||||
// JWKSCacheTTLSeconds sets how long to cache JWKS before refresh (default 3600 seconds)
|
||||
JWKSCacheTTLSeconds int `json:"jwksCacheTTLSeconds,omitempty"`
|
||||
|
||||
// TLSCACert is the path to the CA certificate file for custom/self-signed certificates
|
||||
TLSCACert string `json:"tlsCaCert,omitempty"`
|
||||
|
||||
// TLSInsecureSkipVerify controls whether to skip TLS verification.
|
||||
// WARNING: Should only be used in development/testing environments. Never use in production.
|
||||
TLSInsecureSkipVerify bool `json:"tlsInsecureSkipVerify,omitempty"`
|
||||
}
|
||||
|
||||
// JWKS represents JSON Web Key Set
|
||||
@@ -124,6 +135,45 @@ func (p *OIDCProvider) Initialize(config interface{}) error {
|
||||
p.jwksTTL = time.Hour
|
||||
}
|
||||
|
||||
// Configure HTTP client with TLS settings
|
||||
tlsConfig := &tls.Config{
|
||||
InsecureSkipVerify: oidcConfig.TLSInsecureSkipVerify,
|
||||
MinVersion: tls.VersionTLS12, // Prevent TLS downgrade attacks
|
||||
}
|
||||
|
||||
if oidcConfig.TLSInsecureSkipVerify {
|
||||
glog.Warningf("OIDC provider %q is configured to skip TLS verification. This is insecure and should not be used in production.", p.name)
|
||||
}
|
||||
|
||||
if oidcConfig.TLSCACert != "" {
|
||||
// Validate that the CA cert path is absolute to prevent reading unintended files
|
||||
if !filepath.IsAbs(oidcConfig.TLSCACert) {
|
||||
return fmt.Errorf("TLSCACert must be an absolute path, got: %s", oidcConfig.TLSCACert)
|
||||
}
|
||||
|
||||
caCert, err := os.ReadFile(oidcConfig.TLSCACert)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read CA cert file: %w", err)
|
||||
}
|
||||
// Start with the system cert pool to trust public CAs, then add the custom one.
|
||||
rootCAs, _ := x509.SystemCertPool()
|
||||
if rootCAs == nil {
|
||||
rootCAs = x509.NewCertPool()
|
||||
}
|
||||
if !rootCAs.AppendCertsFromPEM(caCert) {
|
||||
return fmt.Errorf("failed to append CA cert from file: %s", oidcConfig.TLSCACert)
|
||||
}
|
||||
tlsConfig.RootCAs = rootCAs
|
||||
}
|
||||
|
||||
transport := &http.Transport{
|
||||
TLSClientConfig: tlsConfig,
|
||||
}
|
||||
p.httpClient = &http.Client{
|
||||
Timeout: 30 * time.Second,
|
||||
Transport: transport,
|
||||
}
|
||||
|
||||
// For testing, we'll skip the actual OIDC client initialization
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -49,8 +49,10 @@ const (
|
||||
ConfigFieldClientSecret = "clientSecret"
|
||||
ConfigFieldJWKSUri = "jwksUri"
|
||||
ConfigFieldScopes = "scopes"
|
||||
ConfigFieldUserInfoUri = "userInfoUri"
|
||||
ConfigFieldRedirectUri = "redirectUri"
|
||||
ConfigFieldUserInfoUri = "userInfoUri"
|
||||
ConfigFieldRedirectUri = "redirectUri"
|
||||
ConfigFieldTLSCACert = "tlsCaCert"
|
||||
ConfigFieldTLSInsecureSkipVerify = "tlsInsecureSkipVerify"
|
||||
)
|
||||
|
||||
// Error Messages
|
||||
|
||||
@@ -115,6 +115,14 @@ func (f *ProviderFactory) convertToOIDCConfig(configMap map[string]interface{})
|
||||
config.Scopes = scopes
|
||||
}
|
||||
|
||||
if tlsCaCert, ok := configMap[ConfigFieldTLSCACert].(string); ok {
|
||||
config.TLSCACert = tlsCaCert
|
||||
}
|
||||
|
||||
if tlsInsecureSkipVerify, ok := configMap[ConfigFieldTLSInsecureSkipVerify].(bool); ok {
|
||||
config.TLSInsecureSkipVerify = tlsInsecureSkipVerify
|
||||
}
|
||||
|
||||
// Convert claims mapping
|
||||
if claimsMapInterface, ok := configMap["claimsMapping"]; ok {
|
||||
claimsMap, err := f.convertToStringMap(claimsMapInterface)
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package mount
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"syscall"
|
||||
|
||||
"github.com/hanwen/go-fuse/v2/fuse"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
func grpcErrorToFuseStatus(err error) fuse.Status {
|
||||
if err == nil {
|
||||
return fuse.OK
|
||||
}
|
||||
|
||||
// Unpack error for inspection
|
||||
if s, ok := status.FromError(err); ok {
|
||||
switch s.Code() {
|
||||
case codes.OK:
|
||||
return fuse.OK
|
||||
case codes.Canceled, codes.DeadlineExceeded:
|
||||
return fuse.Status(syscall.ETIMEDOUT)
|
||||
case codes.Unavailable:
|
||||
return fuse.Status(syscall.EAGAIN)
|
||||
case codes.ResourceExhausted:
|
||||
return fuse.Status(syscall.EAGAIN) // Or syscall.ENOSPC
|
||||
case codes.PermissionDenied:
|
||||
return fuse.Status(syscall.EACCES)
|
||||
case codes.Unauthenticated:
|
||||
return fuse.Status(syscall.EPERM)
|
||||
case codes.NotFound:
|
||||
return fuse.ENOENT
|
||||
case codes.AlreadyExists:
|
||||
return fuse.Status(syscall.EEXIST)
|
||||
case codes.InvalidArgument:
|
||||
return fuse.EINVAL
|
||||
}
|
||||
}
|
||||
|
||||
// String matching for errors that don't have proper gRPC codes but are known
|
||||
errStr := err.Error()
|
||||
if strings.Contains(errStr, "transport") {
|
||||
return fuse.Status(syscall.EAGAIN)
|
||||
}
|
||||
// Add other string matches if necessary
|
||||
|
||||
return fuse.EIO
|
||||
}
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
|
||||
"google.golang.org/grpc"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
@@ -28,7 +27,7 @@ func (wfs *WFS) WithFilerClient(streamingMode bool, fn func(filer_pb.SeaweedFile
|
||||
}, filerGrpcAddress, false, wfs.option.GrpcDialOption)
|
||||
|
||||
if err != nil {
|
||||
glog.V(0).Infof("WithFilerClient %d %v: %v", x, filerGrpcAddress, err)
|
||||
// glog.V(0).Infof("WithFilerClient %d %v: %v", x, filerGrpcAddress, err)
|
||||
} else {
|
||||
atomic.StoreInt32(&wfs.option.filerIndex, i)
|
||||
return nil
|
||||
|
||||
+11
-4
@@ -3,12 +3,13 @@ package mount
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"syscall"
|
||||
|
||||
"github.com/hanwen/go-fuse/v2/fuse"
|
||||
"github.com/seaweedfs/seaweedfs/weed/filer"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
func (wfs *WFS) saveEntry(path util.FullPath, entry *filer_pb.Entry) (code fuse.Status) {
|
||||
@@ -33,14 +34,20 @@ func (wfs *WFS) saveEntry(path util.FullPath, entry *filer_pb.Entry) (code fuse.
|
||||
}
|
||||
|
||||
if err := wfs.metaCache.UpdateEntry(context.Background(), filer.FromPbEntry(request.Directory, request.Entry)); err != nil {
|
||||
return fmt.Errorf("UpdateEntry dir %s: %v", path, err)
|
||||
return fmt.Errorf("metaCache.UpdateEntry dir %s: %w", path, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
glog.Errorf("saveEntry %s: %v", path, err)
|
||||
return fuse.EIO
|
||||
// glog.V(0).Infof("saveEntry %s: %v", path, err)
|
||||
fuseStatus := grpcErrorToFuseStatus(err)
|
||||
if fuseStatus == fuse.EIO {
|
||||
glog.Errorf("saveEntry failed for %s: %v (returning EIO)", path, err)
|
||||
} else {
|
||||
glog.V(1).Infof("saveEntry failed for %s: %v (returning %v)", path, err, fuseStatus)
|
||||
}
|
||||
return fuseStatus
|
||||
}
|
||||
|
||||
return fuse.OK
|
||||
|
||||
@@ -257,6 +257,15 @@ func hostAndPort(address string) (host string, port uint64, err error) {
|
||||
if colonIndex < 0 {
|
||||
return "", 0, fmt.Errorf("server should have hostname:port format: %v", address)
|
||||
}
|
||||
dotIndex := strings.LastIndex(address, ".")
|
||||
if dotIndex > colonIndex {
|
||||
// port format is "port.grpcPort"
|
||||
port, err = strconv.ParseUint(address[colonIndex+1:dotIndex], 10, 64)
|
||||
if err != nil {
|
||||
return "", 0, fmt.Errorf("server port parse error: %w", err)
|
||||
}
|
||||
return address[:colonIndex], port, err
|
||||
}
|
||||
port, err = strconv.ParseUint(address[colonIndex+1:], 10, 64)
|
||||
if err != nil {
|
||||
return "", 0, fmt.Errorf("server port parse error: %w", err)
|
||||
@@ -267,6 +276,19 @@ func hostAndPort(address string) (host string, port uint64, err error) {
|
||||
|
||||
func ServerToGrpcAddress(server string) (serverGrpcAddress string) {
|
||||
|
||||
colonIndex := strings.LastIndex(server, ":")
|
||||
if colonIndex >= 0 {
|
||||
if dotIndex := strings.LastIndex(server, "."); dotIndex > colonIndex {
|
||||
// port format is "port.grpcPort"
|
||||
// return the host:grpcPort
|
||||
host := server[:colonIndex]
|
||||
grpcPort := server[dotIndex+1:]
|
||||
if _, err := strconv.ParseUint(grpcPort, 10, 64); err == nil {
|
||||
return util.JoinHostPort(host, int(0+util.ParseInt(grpcPort, 0)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
host, port, parseErr := hostAndPort(server)
|
||||
if parseErr != nil {
|
||||
glog.Fatalf("server address %s parse error: %v", server, parseErr)
|
||||
|
||||
@@ -118,17 +118,17 @@ func diskInfoToString(diskInfo *master_pb.DiskInfo) string {
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
func (c *commandVolumeList) writeTopologyInfo(writer io.Writer, t *master_pb.TopologyInfo, volumeSizeLimitMb uint64, verbosityLevel int) statistics {
|
||||
func (c *commandVolumeList) writeTopologyInfo(writer io.Writer, t *master_pb.TopologyInfo, volumeSizeLimitMb uint64, verbosityLevel int) *statistics {
|
||||
output(verbosityLevel >= 0, writer, "Topology volumeSizeLimit:%d MB%s\n", volumeSizeLimitMb, diskInfosToString(t.DiskInfos))
|
||||
slices.SortFunc(t.DataCenterInfos, func(a, b *master_pb.DataCenterInfo) int {
|
||||
return strings.Compare(a.Id, b.Id)
|
||||
})
|
||||
var s statistics
|
||||
s := newStatistics()
|
||||
for _, dc := range t.DataCenterInfos {
|
||||
if *c.dataCenter != "" && *c.dataCenter != dc.Id {
|
||||
continue
|
||||
}
|
||||
s = s.plus(c.writeDataCenterInfo(writer, dc, verbosityLevel))
|
||||
s.add(c.writeDataCenterInfo(writer, dc, verbosityLevel))
|
||||
}
|
||||
output(verbosityLevel >= 0, writer, "%+v \n", s)
|
||||
return s
|
||||
@@ -144,7 +144,7 @@ func (c *commandVolumeList) writeDataCenterInfo(writer io.Writer, t *master_pb.D
|
||||
if *c.rack != "" && *c.rack != r.Id {
|
||||
continue
|
||||
}
|
||||
s = s.plus(c.writeRackInfo(writer, r, verbosityLevel, func() {
|
||||
s.add(c.writeRackInfo(writer, r, verbosityLevel, func() {
|
||||
output(verbosityLevel >= 1, writer, " DataCenter %s%s\n", t.Id, diskInfosToString(t.DiskInfos))
|
||||
}))
|
||||
if !dataCenterInfoFound && !s.isEmpty() {
|
||||
@@ -165,7 +165,7 @@ func (c *commandVolumeList) writeRackInfo(writer io.Writer, t *master_pb.RackInf
|
||||
if *c.dataNode != "" && *c.dataNode != dn.Id {
|
||||
continue
|
||||
}
|
||||
s = s.plus(c.writeDataNodeInfo(writer, dn, verbosityLevel, func() {
|
||||
s.add(c.writeDataNodeInfo(writer, dn, verbosityLevel, func() {
|
||||
outCenterInfo()
|
||||
output(verbosityLevel >= 2, writer, " Rack %s%s\n", t.Id, diskInfosToString(t.DiskInfos))
|
||||
}))
|
||||
@@ -182,7 +182,7 @@ func (c *commandVolumeList) writeDataNodeInfo(writer io.Writer, t *master_pb.Dat
|
||||
diskInfoFound := false
|
||||
for _, diskType := range sortMapKey(t.DiskInfos) {
|
||||
diskInfo := t.DiskInfos[diskType]
|
||||
s = s.plus(c.writeDiskInfo(writer, diskInfo, verbosityLevel, func() {
|
||||
s.add(c.writeDiskInfo(writer, diskInfo, verbosityLevel, func() {
|
||||
outRackInfo()
|
||||
output(verbosityLevel >= 3, writer, " DataNode %s%s\n", t.Id, diskInfosToString(t.DiskInfos))
|
||||
}))
|
||||
@@ -232,7 +232,7 @@ func (c *commandVolumeList) writeDiskInfo(writer io.Writer, t *master_pb.DiskInf
|
||||
output(verbosityLevel >= 4, writer, " Disk %s(%s) id:%d\n", diskType, diskInfoToString(t), t.DiskId)
|
||||
volumeInfosFound = true
|
||||
}
|
||||
s = s.plus(writeVolumeInformationMessage(writer, vi, verbosityLevel))
|
||||
s.add(writeVolumeInformationMessage(writer, vi, verbosityLevel))
|
||||
}
|
||||
ecShardInfoFound := false
|
||||
for _, ecShardInfo := range t.EcShardInfos {
|
||||
@@ -244,29 +244,7 @@ func (c *commandVolumeList) writeDiskInfo(writer io.Writer, t *master_pb.DiskInf
|
||||
output(verbosityLevel >= 4, writer, " Disk %s(%s) id:%d\n", diskType, diskInfoToString(t), t.DiskId)
|
||||
ecShardInfoFound = true
|
||||
}
|
||||
var expireAtString string
|
||||
destroyTime := ecShardInfo.ExpireAtSec
|
||||
if destroyTime > 0 {
|
||||
expireAtString = fmt.Sprintf("expireAt:%s", time.Unix(int64(destroyTime), 0).Format("2006-01-02 15:04:05"))
|
||||
}
|
||||
|
||||
// Build shard size information
|
||||
si := erasure_coding.ShardsInfoFromVolumeEcShardInformationMessage(ecShardInfo)
|
||||
var totalSize int64
|
||||
var shardSizeInfo string
|
||||
|
||||
if len(ecShardInfo.ShardSizes) > 0 {
|
||||
var shardDetails []string
|
||||
for _, shardId := range si.Ids() {
|
||||
size := int64(si.Size(shardId))
|
||||
shardDetails = append(shardDetails, fmt.Sprintf("%d:%s", shardId, util.BytesToHumanReadable(uint64(size))))
|
||||
totalSize += size
|
||||
}
|
||||
shardSizeInfo = fmt.Sprintf(" sizes:[%s] total:%s", strings.Join(shardDetails, " "), util.BytesToHumanReadable(uint64(totalSize)))
|
||||
}
|
||||
|
||||
output(verbosityLevel >= 5, writer, " ec volume id:%v collection:%v shards:%v%s %s\n",
|
||||
ecShardInfo.Id, ecShardInfo.Collection, si.Ids(), shardSizeInfo, expireAtString)
|
||||
s.add(writeECShardInformationMessage(writer, ecShardInfo, verbosityLevel))
|
||||
}
|
||||
output((volumeInfosFound || ecShardInfoFound) && verbosityLevel >= 4, writer, " Disk %s %+v \n", diskType, s)
|
||||
return s
|
||||
@@ -274,7 +252,42 @@ func (c *commandVolumeList) writeDiskInfo(writer io.Writer, t *master_pb.DiskInf
|
||||
|
||||
func writeVolumeInformationMessage(writer io.Writer, t *master_pb.VolumeInformationMessage, verbosityLevel int) statistics {
|
||||
output(verbosityLevel >= 5, writer, " volume %+v \n", t)
|
||||
return newStatistics(t)
|
||||
return statistics{
|
||||
Size: t.Size,
|
||||
FileCount: t.FileCount,
|
||||
DeletedFileCount: t.DeleteCount,
|
||||
DeletedBytes: t.DeletedByteCount,
|
||||
}
|
||||
}
|
||||
|
||||
func writeECShardInformationMessage(writer io.Writer, t *master_pb.VolumeEcShardInformationMessage, verbosityLevel int) statistics {
|
||||
var expireAtString string
|
||||
if t.ExpireAtSec > 0 {
|
||||
expireAtString = fmt.Sprintf("expireAt:%s", time.Unix(int64(t.ExpireAtSec), 0).Format("2006-01-02 15:04:05"))
|
||||
}
|
||||
|
||||
// Build shard size information
|
||||
si := erasure_coding.ShardsInfoFromVolumeEcShardInformationMessage(t)
|
||||
var totalSize uint64
|
||||
var shardSizeInfo string
|
||||
|
||||
if len(t.ShardSizes) > 0 {
|
||||
var shardDetails []string
|
||||
for _, shardId := range si.Ids() {
|
||||
size := uint64(si.Size(shardId))
|
||||
shardDetails = append(shardDetails, fmt.Sprintf("%d:%s", shardId, util.BytesToHumanReadable(uint64(size))))
|
||||
totalSize += size
|
||||
}
|
||||
shardSizeInfo = fmt.Sprintf(" sizes:[%s] total:%s", strings.Join(shardDetails, " "), util.BytesToHumanReadable(uint64(totalSize)))
|
||||
}
|
||||
|
||||
output(verbosityLevel >= 5, writer, " ec volume id:%v collection:%v shards:%v%s %s\n",
|
||||
t.Id, t.Collection, si.Ids(), shardSizeInfo, expireAtString)
|
||||
|
||||
// TODO: add file counts once available in VolumeInformationMessage.
|
||||
return statistics{
|
||||
Size: totalSize,
|
||||
}
|
||||
}
|
||||
|
||||
func output(condition bool, w io.Writer, format string, a ...interface{}) {
|
||||
@@ -290,29 +303,27 @@ type statistics struct {
|
||||
DeletedBytes uint64
|
||||
}
|
||||
|
||||
func newStatistics(t *master_pb.VolumeInformationMessage) statistics {
|
||||
return statistics{
|
||||
Size: t.Size,
|
||||
FileCount: t.FileCount,
|
||||
DeletedFileCount: t.DeleteCount,
|
||||
DeletedBytes: t.DeletedByteCount,
|
||||
func newStatistics() *statistics {
|
||||
return &statistics{
|
||||
Size: 0,
|
||||
FileCount: 0,
|
||||
DeletedFileCount: 0,
|
||||
DeletedBytes: 0,
|
||||
}
|
||||
}
|
||||
|
||||
func (s statistics) plus(t statistics) statistics {
|
||||
return statistics{
|
||||
Size: s.Size + t.Size,
|
||||
FileCount: s.FileCount + t.FileCount,
|
||||
DeletedFileCount: s.DeletedFileCount + t.DeletedFileCount,
|
||||
DeletedBytes: s.DeletedBytes + t.DeletedBytes,
|
||||
}
|
||||
func (s *statistics) add(t statistics) {
|
||||
s.Size += t.Size
|
||||
s.FileCount += t.FileCount
|
||||
s.DeletedFileCount += t.DeletedFileCount
|
||||
s.DeletedBytes += t.DeletedBytes
|
||||
}
|
||||
|
||||
func (s statistics) isEmpty() bool {
|
||||
func (s *statistics) isEmpty() bool {
|
||||
return s.Size == 0 && s.FileCount == 0 && s.DeletedFileCount == 0 && s.DeletedBytes == 0
|
||||
}
|
||||
|
||||
func (s statistics) String() string {
|
||||
func (s *statistics) String() string {
|
||||
if s.DeletedFileCount > 0 {
|
||||
return fmt.Sprintf("total size:%d file_count:%d deleted_file:%d deleted_bytes:%d", s.Size, s.FileCount, s.DeletedFileCount, s.DeletedBytes)
|
||||
}
|
||||
|
||||
@@ -34,6 +34,8 @@ type DiskLocation struct {
|
||||
ecVolumes map[needle.VolumeId]*erasure_coding.EcVolume
|
||||
ecVolumesLock sync.RWMutex
|
||||
|
||||
ecShardNotifyHandler func(collection string, vid needle.VolumeId, shardId erasure_coding.ShardId, ecVolume *erasure_coding.EcVolume)
|
||||
|
||||
isDiskSpaceLow bool
|
||||
closeCh chan struct{}
|
||||
}
|
||||
@@ -259,7 +261,7 @@ func (l *DiskLocation) loadExistingVolumesWithId(needleMapKind NeedleMapKind, ld
|
||||
l.concurrentLoadingVolumes(needleMapKind, workerNum, ldbTimeout, diskId)
|
||||
glog.V(2).Infof("Store started on dir: %s with %d volumes max %d (disk ID: %d)", l.Directory, len(l.volumes), l.MaxVolumeCount, diskId)
|
||||
|
||||
l.loadAllEcShards()
|
||||
l.loadAllEcShards(l.ecShardNotifyHandler)
|
||||
glog.V(2).Infof("Store started on dir: %s with %d ec shards (disk ID: %d)", l.Directory, len(l.ecVolumes), diskId)
|
||||
|
||||
}
|
||||
|
||||
@@ -136,7 +136,7 @@ func (l *DiskLocation) UnloadEcShard(vid needle.VolumeId, shardId erasure_coding
|
||||
return true
|
||||
}
|
||||
|
||||
func (l *DiskLocation) loadEcShards(shards []string, collection string, vid needle.VolumeId) (err error) {
|
||||
func (l *DiskLocation) loadEcShards(shards []string, collection string, vid needle.VolumeId, onShardLoad func(collection string, vid needle.VolumeId, shardId erasure_coding.ShardId, ecVolume *erasure_coding.EcVolume)) (err error) {
|
||||
|
||||
for _, shard := range shards {
|
||||
shardId, err := strconv.ParseInt(path.Ext(shard)[3:], 10, 64)
|
||||
@@ -149,16 +149,19 @@ func (l *DiskLocation) loadEcShards(shards []string, collection string, vid need
|
||||
return fmt.Errorf("shard ID out of range: %d", shardId)
|
||||
}
|
||||
|
||||
_, err = l.LoadEcShard(collection, vid, erasure_coding.ShardId(shardId))
|
||||
ecVolume, err := l.LoadEcShard(collection, vid, erasure_coding.ShardId(shardId))
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to load ec shard %v: %w", shard, err)
|
||||
}
|
||||
if onShardLoad != nil {
|
||||
onShardLoad(collection, vid, erasure_coding.ShardId(shardId), ecVolume)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (l *DiskLocation) loadAllEcShards() (err error) {
|
||||
func (l *DiskLocation) loadAllEcShards(onShardLoad func(collection string, vid needle.VolumeId, shardId erasure_coding.ShardId, ecVolume *erasure_coding.EcVolume)) (err error) {
|
||||
|
||||
dirEntries, err := os.ReadDir(l.Directory)
|
||||
if err != nil {
|
||||
@@ -222,7 +225,7 @@ func (l *DiskLocation) loadAllEcShards() (err error) {
|
||||
}
|
||||
|
||||
if ext == ".ecx" && volumeId == prevVolumeId && collection == prevCollection {
|
||||
l.handleFoundEcxFile(sameVolumeShards, collection, volumeId)
|
||||
l.handleFoundEcxFile(sameVolumeShards, collection, volumeId, onShardLoad)
|
||||
reset()
|
||||
continue
|
||||
}
|
||||
@@ -277,7 +280,7 @@ func (l *DiskLocation) EcShardCount() int {
|
||||
|
||||
// handleFoundEcxFile processes a complete group of EC shards when their .ecx file is found.
|
||||
// This includes validation, loading, and cleanup of incomplete/invalid EC volumes.
|
||||
func (l *DiskLocation) handleFoundEcxFile(shards []string, collection string, volumeId needle.VolumeId) {
|
||||
func (l *DiskLocation) handleFoundEcxFile(shards []string, collection string, volumeId needle.VolumeId, onShardLoad func(collection string, vid needle.VolumeId, shardId erasure_coding.ShardId, ecVolume *erasure_coding.EcVolume)) {
|
||||
// Check if this is an incomplete EC encoding (not a distributed EC volume)
|
||||
// Key distinction: if .dat file still exists, EC encoding may have failed
|
||||
// If .dat file is gone, this is likely a distributed EC volume with shards on multiple servers
|
||||
@@ -297,7 +300,7 @@ func (l *DiskLocation) handleFoundEcxFile(shards []string, collection string, vo
|
||||
}
|
||||
|
||||
// Attempt to load the EC shards
|
||||
if err := l.loadEcShards(shards, collection, volumeId); err != nil {
|
||||
if err := l.loadEcShards(shards, collection, volumeId, onShardLoad); err != nil {
|
||||
// If EC shards failed to load and .dat still exists, clean up EC files to allow .dat file to be used
|
||||
// If .dat is gone, log error but don't clean up (may be waiting for shards from other servers)
|
||||
if datExists {
|
||||
|
||||
@@ -177,13 +177,13 @@ func TestIncompleteEcEncodingCleanup(t *testing.T) {
|
||||
}
|
||||
|
||||
// Run loadAllEcShards
|
||||
loadErr := diskLocation.loadAllEcShards()
|
||||
loadErr := diskLocation.loadAllEcShards(nil)
|
||||
if loadErr != nil {
|
||||
t.Logf("loadAllEcShards returned error (expected in some cases): %v", loadErr)
|
||||
}
|
||||
|
||||
// Test idempotency - running again should not cause issues
|
||||
loadErr2 := diskLocation.loadAllEcShards()
|
||||
loadErr2 := diskLocation.loadAllEcShards(nil)
|
||||
if loadErr2 != nil {
|
||||
t.Logf("Second loadAllEcShards returned error: %v", loadErr2)
|
||||
}
|
||||
@@ -550,7 +550,7 @@ func TestEcCleanupWithSeparateIdxDirectory(t *testing.T) {
|
||||
// Do not create .ecx: trigger orphaned-shards cleanup when .dat exists
|
||||
|
||||
// Run loadAllEcShards
|
||||
loadErr := diskLocation.loadAllEcShards()
|
||||
loadErr := diskLocation.loadAllEcShards(nil)
|
||||
if loadErr != nil {
|
||||
t.Logf("loadAllEcShards error: %v", loadErr)
|
||||
}
|
||||
@@ -621,7 +621,7 @@ func TestDistributedEcVolumeNoFileDeletion(t *testing.T) {
|
||||
// NO .dat file - this is a distributed EC volume
|
||||
|
||||
// Run loadAllEcShards - this should fail but NOT delete shard files
|
||||
loadErr := diskLocation.loadAllEcShards()
|
||||
loadErr := diskLocation.loadAllEcShards(nil)
|
||||
if loadErr != nil {
|
||||
t.Logf("loadAllEcShards returned error (expected): %v", loadErr)
|
||||
}
|
||||
|
||||
+33
-6
@@ -86,6 +86,12 @@ func NewStore(grpcDialOption grpc.DialOption, ip string, port int, grpcPort int,
|
||||
s = &Store{grpcDialOption: grpcDialOption, Port: port, Ip: ip, GrpcPort: grpcPort, PublicUrl: publicUrl, Id: id, NeedleMapKind: needleMapKind}
|
||||
s.Locations = make([]*DiskLocation, 0)
|
||||
|
||||
s.NewVolumesChan = make(chan master_pb.VolumeShortInformationMessage, 1024)
|
||||
s.DeletedVolumesChan = make(chan master_pb.VolumeShortInformationMessage, 1024)
|
||||
|
||||
s.NewEcShardsChan = make(chan master_pb.VolumeEcShardInformationMessage, 1024)
|
||||
s.DeletedEcShardsChan = make(chan master_pb.VolumeEcShardInformationMessage, 1024)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < len(dirnames); i++ {
|
||||
location := NewDiskLocation(dirnames[i], int32(maxVolumeCounts[i]), minFreeSpaces[i], idxFolder, diskTypes[i])
|
||||
@@ -93,6 +99,33 @@ func NewStore(grpcDialOption grpc.DialOption, ip string, port int, grpcPort int,
|
||||
stats.VolumeServerMaxVolumeCounter.Add(float64(maxVolumeCounts[i]))
|
||||
|
||||
diskId := uint32(i) // Track disk ID
|
||||
|
||||
location.ecShardNotifyHandler = func(collection string, vid needle.VolumeId, shardId erasure_coding.ShardId, ecVolume *erasure_coding.EcVolume) {
|
||||
var shardSize int64
|
||||
if shard, found := ecVolume.FindEcVolumeShard(shardId); found {
|
||||
shardSize = shard.Size()
|
||||
}
|
||||
si := erasure_coding.NewShardsInfo()
|
||||
si.Set(shardId, erasure_coding.ShardSize(shardSize))
|
||||
|
||||
// Use non-blocking send during startup to avoid deadlock
|
||||
// The channel reader only starts after connecting to master, but we're loading during startup
|
||||
select {
|
||||
case s.NewEcShardsChan <- master_pb.VolumeEcShardInformationMessage{
|
||||
Id: uint32(vid),
|
||||
Collection: collection,
|
||||
EcIndexBits: si.Bitmap(),
|
||||
ShardSizes: si.SizesInt64(),
|
||||
DiskType: string(location.DiskType),
|
||||
ExpireAtSec: ecVolume.ExpireAtSec,
|
||||
DiskId: diskId,
|
||||
}:
|
||||
default:
|
||||
// Channel full during startup - this is OK, heartbeat will report EC shards later
|
||||
glog.V(2).Infof("NewEcShardsChan full during startup for shard %d.%d, will be reported in heartbeat", vid, shardId)
|
||||
}
|
||||
}
|
||||
|
||||
wg.Add(1)
|
||||
go func(id uint32, diskLoc *DiskLocation) {
|
||||
defer wg.Done()
|
||||
@@ -101,12 +134,6 @@ func NewStore(grpcDialOption grpc.DialOption, ip string, port int, grpcPort int,
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
s.NewVolumesChan = make(chan master_pb.VolumeShortInformationMessage, 3)
|
||||
s.DeletedVolumesChan = make(chan master_pb.VolumeShortInformationMessage, 3)
|
||||
|
||||
s.NewEcShardsChan = make(chan master_pb.VolumeEcShardInformationMessage, 3)
|
||||
s.DeletedEcShardsChan = make(chan master_pb.VolumeEcShardInformationMessage, 3)
|
||||
|
||||
return
|
||||
}
|
||||
func (s *Store) AddVolume(volumeId needle.VolumeId, collection string, needleMapKind NeedleMapKind, replicaPlacement string, ttlString string, preallocate int64, ver needle.Version, MemoryMapMaxSizeMb uint32, diskType DiskType, ldbTimeout int64) error {
|
||||
|
||||
+1
-1
@@ -67,7 +67,7 @@ func RetryUntil(name string, job func() error, onErrFn func(err error) (shouldCo
|
||||
break
|
||||
}
|
||||
if onErrFn(err) {
|
||||
if strings.Contains(err.Error(), "transport") {
|
||||
if strings.Contains(err.Error(), "transport") || strings.Contains(err.Error(), "ResourceExhausted") || strings.Contains(err.Error(), "Unavailable") {
|
||||
glog.V(0).Infof("retry %s: err: %v", name, err)
|
||||
}
|
||||
time.Sleep(waitTime)
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
|
||||
var (
|
||||
MAJOR_VERSION = int32(4)
|
||||
MINOR_VERSION = int32(04)
|
||||
MINOR_VERSION = int32(05)
|
||||
VERSION_NUMBER = fmt.Sprintf("%d.%02d", MAJOR_VERSION, MINOR_VERSION)
|
||||
VERSION = util.SizeLimit + " " + VERSION_NUMBER
|
||||
COMMIT = ""
|
||||
|
||||
+93
-46
@@ -7,6 +7,8 @@ import (
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"crypto/rand"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/worker_pb"
|
||||
@@ -26,6 +28,9 @@ type GrpcAdminClient struct {
|
||||
|
||||
cmds chan grpcCommand
|
||||
|
||||
// Session identification for logging
|
||||
sessionID string
|
||||
|
||||
// Reconnection parameters
|
||||
maxReconnectAttempts int
|
||||
reconnectBackoff time.Duration
|
||||
@@ -49,6 +54,7 @@ const (
|
||||
ActionQueryReconnecting grpcAction = "query_reconnecting"
|
||||
ActionQueryConnected grpcAction = "query_connected"
|
||||
ActionQueryShouldReconnect grpcAction = "query_shouldreconnect"
|
||||
ActionResetReconnectStop grpcAction = "reset_reconnect_stop"
|
||||
)
|
||||
|
||||
type registrationRequest struct {
|
||||
@@ -83,9 +89,15 @@ func NewGrpcAdminClient(adminAddress string, workerID string, dialOption grpc.Di
|
||||
// Admin uses HTTP port + 10000 as gRPC port
|
||||
grpcAddress := pb.ServerToGrpcAddress(adminAddress)
|
||||
|
||||
// Generate a unique session ID for logging
|
||||
sessionBytes := make([]byte, 2)
|
||||
rand.Read(sessionBytes)
|
||||
sessionID := fmt.Sprintf("%x", sessionBytes)
|
||||
|
||||
c := &GrpcAdminClient{
|
||||
adminAddress: grpcAddress,
|
||||
workerID: workerID,
|
||||
sessionID: sessionID,
|
||||
dialOption: dialOption,
|
||||
maxReconnectAttempts: 0, // 0 means infinite attempts
|
||||
reconnectBackoff: 1 * time.Second,
|
||||
@@ -133,8 +145,11 @@ func (c *GrpcAdminClient) safeCloseChannel(chPtr *chan struct{}) {
|
||||
func (c *GrpcAdminClient) managerLoop() {
|
||||
state := &grpcState{shouldReconnect: true}
|
||||
|
||||
glog.V(1).Infof("[session %s] Manager loop started for worker %s", c.sessionID, c.workerID)
|
||||
|
||||
out:
|
||||
for cmd := range c.cmds {
|
||||
glog.V(4).Infof("[session %s] Manager received command: %s", c.sessionID, cmd.action)
|
||||
switch cmd.action {
|
||||
case ActionConnect:
|
||||
c.handleConnect(cmd, state)
|
||||
@@ -152,11 +167,20 @@ out:
|
||||
cmd.resp <- err
|
||||
case ActionStreamError:
|
||||
state.connected = false
|
||||
// Restart reconnection loop if needed
|
||||
if state.shouldReconnect && state.reconnectStop == nil {
|
||||
glog.V(1).Infof("[session %s] Stream error, starting reconnection loop", c.sessionID)
|
||||
stop := make(chan struct{})
|
||||
state.reconnectStop = stop
|
||||
go c.reconnectionLoop(stop, func() {
|
||||
c.cmds <- grpcCommand{action: ActionResetReconnectStop, data: state}
|
||||
})
|
||||
}
|
||||
case ActionRegisterWorker:
|
||||
req := cmd.data.(registrationRequest)
|
||||
state.lastWorkerInfo = req.Worker
|
||||
if !state.connected {
|
||||
glog.V(1).Infof("Not connected yet, worker info stored for registration upon connection")
|
||||
glog.V(1).Infof("[session %s] Not connected yet, worker info stored for registration upon connection", c.sessionID)
|
||||
// Respond immediately with success (registration will happen later)
|
||||
req.Resp <- nil
|
||||
continue
|
||||
@@ -179,13 +203,17 @@ out:
|
||||
case ActionQueryShouldReconnect:
|
||||
respCh := cmd.data.(chan bool)
|
||||
respCh <- state.shouldReconnect
|
||||
case ActionResetReconnectStop:
|
||||
// This is an internal action to reset the stop channel when reconnectionLoop exits
|
||||
s := cmd.data.(*grpcState)
|
||||
s.reconnectStop = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Connect establishes gRPC connection to admin server with TLS detection
|
||||
func (c *GrpcAdminClient) Connect() error {
|
||||
resp := make(chan error)
|
||||
resp := make(chan error, 1)
|
||||
c.cmds <- grpcCommand{
|
||||
action: ActionConnect,
|
||||
resp: resp,
|
||||
@@ -199,15 +227,24 @@ func (c *GrpcAdminClient) handleConnect(cmd grpcCommand, s *grpcState) {
|
||||
return
|
||||
}
|
||||
|
||||
// Start reconnection loop immediately (async)
|
||||
stop := make(chan struct{})
|
||||
s.reconnectStop = stop
|
||||
go c.reconnectionLoop(stop)
|
||||
// Start reconnection loop immediately if not already running (async)
|
||||
if s.reconnectStop == nil {
|
||||
glog.V(1).Infof("[session %s] Starting reconnection loop", c.sessionID)
|
||||
stop := make(chan struct{})
|
||||
s.reconnectStop = stop
|
||||
go c.reconnectionLoop(stop, func() {
|
||||
// This callback is executed when the reconnectionLoop exits.
|
||||
// It ensures that s.reconnectStop is reset to nil, allowing a new loop to be started later.
|
||||
c.cmds <- grpcCommand{action: ActionResetReconnectStop, data: s}
|
||||
})
|
||||
} else {
|
||||
glog.V(1).Infof("[session %s] Reconnection loop already running", c.sessionID)
|
||||
}
|
||||
|
||||
// Attempt the initial connection
|
||||
err := c.attemptConnection(s)
|
||||
if err != nil {
|
||||
glog.V(1).Infof("Initial connection failed, reconnection loop will retry: %v", err)
|
||||
glog.Warningf("[session %s] Initial connection failed, reconnection loop will retry: %v", c.sessionID, err)
|
||||
cmd.resp <- err
|
||||
return
|
||||
}
|
||||
@@ -221,10 +258,10 @@ func (c *GrpcAdminClient) createConnection() (*grpc.ClientConn, error) {
|
||||
|
||||
conn, err := pb.GrpcDial(ctx, c.adminAddress, false, c.dialOption)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to connect to admin server: %w", err)
|
||||
return nil, fmt.Errorf("failed to connect to admin server %s: %w", c.adminAddress, err)
|
||||
}
|
||||
|
||||
glog.Infof("Connected to admin server at %s", c.adminAddress)
|
||||
glog.Infof("[session %s] Connected to admin server at %s", c.sessionID, c.adminAddress)
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
@@ -242,7 +279,7 @@ func (c *GrpcAdminClient) attemptConnection(s *grpcState) error {
|
||||
// Create bidirectional stream
|
||||
s.streamCtx, s.streamCancel = context.WithCancel(context.Background())
|
||||
stream, err := s.client.WorkerStream(s.streamCtx)
|
||||
glog.Infof("Worker stream created")
|
||||
glog.Infof("[session %s] Worker stream created", c.sessionID)
|
||||
if err != nil {
|
||||
s.conn.Close()
|
||||
return fmt.Errorf("failed to create worker stream: %w", err)
|
||||
@@ -255,8 +292,8 @@ func (c *GrpcAdminClient) attemptConnection(s *grpcState) error {
|
||||
s.streamExit = make(chan struct{})
|
||||
s.streamFailed = make(chan struct{})
|
||||
s.regWait = make(chan *worker_pb.RegistrationResponse, 1)
|
||||
go handleOutgoing(s.stream, s.streamExit, c.outgoing, c.cmds)
|
||||
go handleIncoming(c.workerID, s.stream, s.streamExit, c.incoming, c.cmds, s.streamFailed, s.regWait)
|
||||
go handleOutgoing(c.sessionID, s.stream, s.streamExit, c.outgoing, c.cmds)
|
||||
go handleIncoming(c.sessionID, c.workerID, s.stream, s.streamExit, c.incoming, c.cmds, s.streamFailed, s.regWait)
|
||||
|
||||
// Always check for worker info and send registration immediately as the very first message
|
||||
if s.lastWorkerInfo != nil {
|
||||
@@ -270,18 +307,19 @@ func (c *GrpcAdminClient) attemptConnection(s *grpcState) error {
|
||||
s.connected = false
|
||||
return fmt.Errorf("failed to register worker: %w", err)
|
||||
}
|
||||
glog.Infof("Worker registered successfully with admin server")
|
||||
glog.Infof("[session %s] Worker %s registered successfully with admin server", c.sessionID, c.workerID)
|
||||
} else {
|
||||
// No worker info yet - stream will wait for registration
|
||||
glog.V(1).Infof("Connected to admin server, waiting for worker registration info")
|
||||
glog.V(1).Infof("[session %s] Connected to admin server, waiting for worker registration info", c.sessionID)
|
||||
}
|
||||
|
||||
glog.Infof("Connected to admin server at %s", c.adminAddress)
|
||||
glog.V(1).Infof("[session %s] attemptConnection successful", c.sessionID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// reconnect attempts to re-establish the connection
|
||||
func (c *GrpcAdminClient) reconnect(s *grpcState) error {
|
||||
glog.V(1).Infof("[session %s] Reconnection attempt starting", c.sessionID)
|
||||
// Clean up existing connection completely
|
||||
c.safeCloseChannel(&s.streamExit)
|
||||
c.safeCloseChannel(&s.streamFailed)
|
||||
@@ -299,25 +337,31 @@ func (c *GrpcAdminClient) reconnect(s *grpcState) error {
|
||||
return fmt.Errorf("failed to reconnect: %w", err)
|
||||
}
|
||||
|
||||
glog.Infof("[session %s] Successfully reconnected to admin server", c.sessionID)
|
||||
// Registration is now handled in attemptConnection if worker info is available
|
||||
return nil
|
||||
}
|
||||
|
||||
// reconnectionLoop handles automatic reconnection with exponential backoff
|
||||
func (c *GrpcAdminClient) reconnectionLoop(reconnectStop chan struct{}) {
|
||||
func (c *GrpcAdminClient) reconnectionLoop(reconnectStop chan struct{}, onExit func()) {
|
||||
defer onExit() // Ensure the cleanup callback is called when the loop exits
|
||||
backoff := c.reconnectBackoff
|
||||
attempts := 0
|
||||
|
||||
for {
|
||||
attempts++ // Count this attempt (starts at 1)
|
||||
waitDuration := backoff
|
||||
if attempts == 0 {
|
||||
waitDuration = time.Second
|
||||
if attempts == 1 {
|
||||
waitDuration = 100 * time.Millisecond // Quick retry for the very first failure
|
||||
}
|
||||
glog.V(2).Infof("[session %s] Reconnection loop sleeping for %v before attempt %d", c.sessionID, waitDuration, attempts)
|
||||
select {
|
||||
case <-reconnectStop:
|
||||
glog.V(1).Infof("[session %s] Reconnection loop stopping (received signal)", c.sessionID)
|
||||
return
|
||||
case <-time.After(waitDuration):
|
||||
}
|
||||
|
||||
resp := make(chan error, 1)
|
||||
c.cmds <- grpcCommand{
|
||||
action: ActionReconnect,
|
||||
@@ -326,19 +370,17 @@ func (c *GrpcAdminClient) reconnectionLoop(reconnectStop chan struct{}) {
|
||||
err := <-resp
|
||||
if err == nil {
|
||||
// Successful reconnection
|
||||
attempts = 0
|
||||
backoff = c.reconnectBackoff
|
||||
glog.Infof("Successfully reconnected to admin server")
|
||||
glog.Infof("[session %s] Successfully reconnected to admin server, stopping reconnection loop", c.sessionID)
|
||||
return // EXIT ON SUCCESS
|
||||
} else if errors.Is(err, ErrAlreadyConnected) {
|
||||
attempts = 0
|
||||
backoff = c.reconnectBackoff
|
||||
glog.V(1).Infof("[session %s] Already connected, stopping reconnection loop", c.sessionID)
|
||||
return // EXIT ON SUCCESS (already connected)
|
||||
} else {
|
||||
attempts++
|
||||
glog.Errorf("Reconnection attempt %d failed: %v", attempts, err)
|
||||
glog.Warningf("[session %s] Reconnection attempt %d failed: %v", c.sessionID, attempts, err)
|
||||
|
||||
// Check if we should give up
|
||||
if c.maxReconnectAttempts > 0 && attempts >= c.maxReconnectAttempts {
|
||||
glog.Errorf("Max reconnection attempts (%d) reached, giving up", c.maxReconnectAttempts)
|
||||
glog.Errorf("[session %s] Max reconnection attempts (%d) reached, giving up", c.sessionID, c.maxReconnectAttempts)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -347,17 +389,21 @@ func (c *GrpcAdminClient) reconnectionLoop(reconnectStop chan struct{}) {
|
||||
if backoff > c.maxReconnectBackoff {
|
||||
backoff = c.maxReconnectBackoff
|
||||
}
|
||||
glog.Infof("Waiting %v before next reconnection attempt", backoff)
|
||||
glog.V(1).Infof("[session %s] Waiting %v before next reconnection attempt", c.sessionID, backoff)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// handleOutgoing processes outgoing messages to admin
|
||||
func handleOutgoing(
|
||||
sessionID string,
|
||||
stream worker_pb.WorkerService_WorkerStreamClient,
|
||||
streamExit <-chan struct{},
|
||||
outgoing <-chan *worker_pb.WorkerMessage,
|
||||
cmds chan<- grpcCommand) {
|
||||
|
||||
glog.V(1).Infof("[session %s] Outgoing message handler started", sessionID)
|
||||
defer glog.V(1).Infof("[session %s] Outgoing message handler stopping", sessionID)
|
||||
msgCh := make(chan *worker_pb.WorkerMessage, 1)
|
||||
errCh := make(chan error, 1) // Buffered to prevent blocking if the manager is busy
|
||||
|
||||
@@ -375,18 +421,18 @@ func handleOutgoing(
|
||||
// Helper function to handle stream errors and cleanup
|
||||
handleStreamError := func(err error) {
|
||||
if err != nil {
|
||||
glog.Errorf("Failed to send message to admin: %v", err)
|
||||
glog.Warningf("[session %s] Stream send error: %v", sessionID, err)
|
||||
select {
|
||||
case cmds <- grpcCommand{action: ActionStreamError, data: err}:
|
||||
// Successfully queued
|
||||
default:
|
||||
// Manager busy, queue asynchronously to avoid blocking
|
||||
glog.V(2).Infof("Manager busy, queuing stream error asynchronously from outgoing handler: %v", err)
|
||||
glog.V(2).Infof("[session %s] Manager busy, queuing stream error asynchronously from outgoing handler: %v", sessionID, err)
|
||||
go func(e error) {
|
||||
select {
|
||||
case cmds <- grpcCommand{action: ActionStreamError, data: e}:
|
||||
case <-time.After(2 * time.Second):
|
||||
glog.Warningf("Failed to send stream error to manager from outgoing handler, channel blocked: %v", e)
|
||||
glog.Warningf("[session %s] Failed to send stream error to manager from outgoing handler, channel blocked: %v", sessionID, e)
|
||||
}
|
||||
}(err)
|
||||
}
|
||||
@@ -428,14 +474,17 @@ func handleOutgoing(
|
||||
|
||||
// handleIncoming processes incoming messages from admin
|
||||
func handleIncoming(
|
||||
sessionID string,
|
||||
workerID string,
|
||||
stream worker_pb.WorkerService_WorkerStreamClient,
|
||||
streamExit <-chan struct{},
|
||||
incoming chan<- *worker_pb.AdminMessage,
|
||||
cmds chan<- grpcCommand,
|
||||
streamFailed chan<- struct{},
|
||||
regWait chan<- *worker_pb.RegistrationResponse) {
|
||||
glog.V(1).Infof("INCOMING HANDLER STARTED: Worker %s incoming message handler started", workerID)
|
||||
streamFailed chan struct{},
|
||||
regWait chan *worker_pb.RegistrationResponse) {
|
||||
|
||||
glog.V(1).Infof("[session %s] Incoming message handler started", sessionID)
|
||||
defer glog.V(1).Infof("[session %s] Incoming message handler stopping", sessionID)
|
||||
msgCh := make(chan *worker_pb.AdminMessage)
|
||||
errCh := make(chan error, 1) // Buffered to prevent blocking if the manager is busy
|
||||
// regWait is buffered with size 1 so that the registration response can be sent
|
||||
@@ -455,12 +504,10 @@ func handleIncoming(
|
||||
}()
|
||||
|
||||
for {
|
||||
glog.V(4).Infof("LISTENING: Worker %s waiting for message from admin server", workerID)
|
||||
|
||||
select {
|
||||
case msg := <-msgCh:
|
||||
// Message successfully received from the stream
|
||||
glog.V(4).Infof("MESSAGE RECEIVED: Worker %s received message from admin server: %T", workerID, msg.Message)
|
||||
glog.V(4).Infof("[session %s] Received message from admin server: %T", sessionID, msg.Message)
|
||||
|
||||
// If this is a registration response, also publish to the registration waiter.
|
||||
// regWait is buffered (size 1) so that the response can be sent even if sendRegistration
|
||||
@@ -468,26 +515,26 @@ func handleIncoming(
|
||||
if rr := msg.GetRegistrationResponse(); rr != nil {
|
||||
select {
|
||||
case regWait <- rr:
|
||||
glog.V(3).Infof("REGISTRATION RESPONSE: Worker %s routed registration response to waiter", workerID)
|
||||
glog.V(3).Infof("[session %s] Registration response routed to waiter", sessionID)
|
||||
default:
|
||||
glog.V(2).Infof("REGISTRATION RESPONSE DROPPED: Worker %s registration response dropped (no waiter)", workerID)
|
||||
glog.V(2).Infof("[session %s] Registration response dropped (no waiter)", sessionID)
|
||||
}
|
||||
}
|
||||
|
||||
// Route message to general handler.
|
||||
select {
|
||||
case incoming <- msg:
|
||||
glog.V(3).Infof("MESSAGE ROUTED: Worker %s successfully routed message to handler", workerID)
|
||||
glog.V(3).Infof("[session %s] Message routed to incoming channel", sessionID)
|
||||
case <-time.After(time.Second):
|
||||
glog.Warningf("MESSAGE DROPPED: Worker %s incoming message buffer full, dropping message: %T", workerID, msg.Message)
|
||||
glog.Warningf("[session %s] Incoming message buffer full, dropping message: %T", sessionID, msg.Message)
|
||||
}
|
||||
|
||||
case err := <-errCh:
|
||||
// Stream Receiver goroutine reported an error (EOF or network error)
|
||||
if err == io.EOF {
|
||||
glog.Infof("STREAM CLOSED: Worker %s admin server closed the stream", workerID)
|
||||
glog.Infof("[session %s] Admin server closed the stream", sessionID)
|
||||
} else {
|
||||
glog.Errorf("RECEIVE ERROR: Worker %s failed to receive message from admin: %v", workerID, err)
|
||||
glog.Warningf("[session %s] Stream receive error: %v", sessionID, err)
|
||||
}
|
||||
|
||||
// Signal that stream has failed (non-blocking)
|
||||
@@ -502,23 +549,23 @@ func handleIncoming(
|
||||
select {
|
||||
case cmds <- grpcCommand{action: ActionStreamError, data: err}:
|
||||
default:
|
||||
glog.V(2).Infof("Manager busy, queuing stream error asynchronously: %v", err)
|
||||
glog.V(2).Infof("[session %s] Manager busy, queuing stream error asynchronously from incoming handler: %v", sessionID, err)
|
||||
go func(e error) {
|
||||
select {
|
||||
case cmds <- grpcCommand{action: ActionStreamError, data: e}:
|
||||
case <-time.After(2 * time.Second):
|
||||
glog.Warningf("Failed to send stream error to manager, channel blocked: %v", e)
|
||||
glog.Warningf("[session %s] Failed to send stream error to manager from incoming handler, channel blocked: %v", sessionID, e)
|
||||
}
|
||||
}(err)
|
||||
}
|
||||
|
||||
// Exit the main handler loop
|
||||
glog.V(1).Infof("INCOMING HANDLER STOPPED: Worker %s stopping incoming handler due to stream error", workerID)
|
||||
glog.V(1).Infof("[session %s] Incoming message handler stopping due to stream error", sessionID)
|
||||
return
|
||||
|
||||
case <-streamExit:
|
||||
// Manager closed this channel, signaling a controlled disconnection.
|
||||
glog.V(1).Infof("INCOMING HANDLER STOPPED: Worker %s stopping incoming handler - received exit signal", workerID)
|
||||
glog.V(1).Infof("[session %s] Incoming message handler stopping - received exit signal", sessionID)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -195,7 +195,7 @@ func NewWorker(config *types.WorkerConfig) (*Worker, error) {
|
||||
|
||||
func (w *Worker) managerLoop() {
|
||||
w.state = &workerState{
|
||||
startTime: time.Now(),
|
||||
running: false,
|
||||
stopChan: make(chan struct{}),
|
||||
currentTasks: make(map[string]*types.TaskInput),
|
||||
}
|
||||
@@ -428,6 +428,7 @@ func (w *Worker) Start() error {
|
||||
|
||||
// Start starts the worker
|
||||
func (w *Worker) handleStart(cmd workerCommand) {
|
||||
glog.Infof("Worker %s handleStart called", w.id)
|
||||
if w.state.running {
|
||||
cmd.resp <- fmt.Errorf("worker is already running")
|
||||
return
|
||||
|
||||
Reference in new issue
Block a user