SeaweedFS is a distributed storage system for object storage (S3), file systems, Iceberg table buckets, and Lance vector buckets, designed to handle billions of files with O(1) disk access and effortless horizontal scaling.
Go blob-storagecloud-drivedistributed-file-systemdistributed-storageerasure-codingfusehadoop-hdfshdfskuberneteslancelancedbobject-storageposixs3s3-storageseaweedfstiered-file-systemvector-search
Fix Maintenance Task Sorting and Refactor Log Persistence (#8199)
Chris Lu72a8f598f2e9
diff --git a/weed/admin/dash/admin_server.go b/weed/admin/dash/admin_server.goindex 5e4179c2a8..4c0cfd2615 100644--- a/weed/admin/dash/admin_server.go+++ b/weed/admin/dash/admin_server.go@@ -5,7 +5,6 @@ import ("fmt""net/http""sort"- "strconv""strings""time"@@ -33,6 +32,17 @@ import (_ "github.com/seaweedfs/seaweedfs/weed/credential/grpc" // Register gRPC credential store)+const (+ maxAssignmentHistoryDisplay = 50+ maxLogMessageLength = 2000+ maxLogFields = 20+ maxRelatedTasksDisplay = 50+ maxRecentTasksDisplay = 10+ defaultCacheTimeout = 10 * time.Second+ defaultFilerCacheTimeout = 30 * time.Second+ defaultStatsCacheTimeout = 30 * time.Second+)+// FilerConfig holds filer configuration needed for bucket operationstype FilerConfig struct {BucketsPath string@@ -132,10 +142,10 @@ func NewAdminServer(masters string, templateFS http.FileSystem, dataDir string,templateFS: templateFS,dataDir: dataDir,grpcDialOption: grpcDialOption,- cacheExpiration: 10 * time.Second,- filerCacheExpiration: 30 * time.Second, // Cache filers for 30 seconds+ cacheExpiration: defaultCacheTimeout,+ filerCacheExpiration: defaultFilerCacheTimeout,configPersistence: NewConfigPersistence(dataDir),- collectionStatsCacheThreshold: 30 * time.Second,+ collectionStatsCacheThreshold: defaultStatsCacheTimeout,s3TablesManager: newS3TablesManager(),icebergPort: icebergPort,}@@ -779,7 +789,7 @@ func (s *AdminServer) GetClusterBrokers() (*ClusterBrokersData, error) {// ShowMaintenanceQueue displays the maintenance queue pagefunc (as *AdminServer) ShowMaintenanceQueue(c *gin.Context) {- data, err := as.getMaintenanceQueueData()+ data, err := as.GetMaintenanceQueueData()if err != nil {c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})return@@ -868,7 +878,7 @@ func (as *AdminServer) TriggerMaintenanceScan(c *gin.Context) {// GetMaintenanceTasks returns all maintenance tasksfunc (as *AdminServer) GetMaintenanceTasks(c *gin.Context) {- tasks, err := as.getMaintenanceTasks()+ tasks, err := as.GetAllMaintenanceTasks()if err != nil {c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})return@@ -1032,9 +1042,9 @@ func (as *AdminServer) UpdateMaintenanceConfigData(config *maintenance.Maintenan// Helper methods for maintenance operations-// getMaintenanceQueueData returns data for the maintenance queue UI-func (as *AdminServer) getMaintenanceQueueData() (*maintenance.MaintenanceQueueData, error) {- tasks, err := as.getMaintenanceTasks()+// GetMaintenanceQueueData returns data for the maintenance queue UI+func (as *AdminServer) GetMaintenanceQueueData() (*maintenance.MaintenanceQueueData, error) {+ tasks, err := as.GetAllMaintenanceTasks()if err != nil {return nil, err}@@ -1089,14 +1099,16 @@ func (as *AdminServer) getMaintenanceQueueStats() (*maintenance.QueueStats, erroreturn queueStats, nil}-// getMaintenanceTasks returns all maintenance tasks-func (as *AdminServer) getMaintenanceTasks() ([]*maintenance.MaintenanceTask, error) {+// GetAllMaintenanceTasks returns all maintenance tasks+func (as *AdminServer) GetAllMaintenanceTasks() ([]*maintenance.MaintenanceTask, error) {if as.maintenanceManager == nil {return []*maintenance.MaintenanceTask{}, nil}- // Collect all tasks from memory across all statuses- allTasks := []*maintenance.MaintenanceTask{}+ // 1. Collect all tasks from memory+ tasksMap := make(map[string]*maintenance.MaintenanceTask)++ // Collect from memory via GetTasks loop to ensure we catch everythingstatuses := []maintenance.MaintenanceTaskStatus{maintenance.TaskStatusPending,maintenance.TaskStatusAssigned,@@ -1108,29 +1120,92 @@ func (as *AdminServer) getMaintenanceTasks() ([]*maintenance.MaintenanceTask, erfor _, status := range statuses {tasks := as.maintenanceManager.GetTasks(status, "", 0)- allTasks = append(allTasks, tasks...)+ for _, t := range tasks {+ tasksMap[t.ID] = t+ }}- // Also load any persisted tasks that might not be in memory+ // 2. Merge persisted tasksif as.configPersistence != nil {persistedTasks, err := as.configPersistence.LoadAllTaskStates()if err == nil {- // Add any persisted tasks not already in memory- for _, persistedTask := range persistedTasks {- found := false- for _, memoryTask := range allTasks {- if memoryTask.ID == persistedTask.ID {- found = true- break- }- }- if !found {- allTasks = append(allTasks, persistedTask)+ for _, t := range persistedTasks {+ if _, exists := tasksMap[t.ID]; !exists {+ tasksMap[t.ID] = t}}}}+ // 3. Bucketize buckets+ var pendingTasks, activeTasks, finishedTasks []*maintenance.MaintenanceTask++ for _, t := range tasksMap {+ switch t.Status {+ case maintenance.TaskStatusPending:+ pendingTasks = append(pendingTasks, t)+ case maintenance.TaskStatusAssigned, maintenance.TaskStatusInProgress:+ activeTasks = append(activeTasks, t)+ case maintenance.TaskStatusCompleted, maintenance.TaskStatusFailed, maintenance.TaskStatusCancelled:+ finishedTasks = append(finishedTasks, t)+ default:+ // Treat unknown as finished/archived? Or pending?+ // Safest to add to finished so they appear somewhere+ finishedTasks = append(finishedTasks, t)+ }+ }++ // 4. Sort buckets+ // Pending: Newest Created First+ sort.Slice(pendingTasks, func(i, j int) bool {+ return pendingTasks[i].CreatedAt.After(pendingTasks[j].CreatedAt)+ })++ // Active: Newest Created First (or StartedAt?)+ sort.Slice(activeTasks, func(i, j int) bool {+ return activeTasks[i].CreatedAt.After(activeTasks[j].CreatedAt)+ })++ // Finished: Newest Completed First+ sort.Slice(finishedTasks, func(i, j int) bool {+ t1 := finishedTasks[i].CompletedAt+ t2 := finishedTasks[j].CompletedAt++ // Handle nil completion times+ if t1 == nil && t2 == nil {+ // Both nil, fallback to CreatedAt+ if !finishedTasks[i].CreatedAt.Equal(finishedTasks[j].CreatedAt) {+ return finishedTasks[i].CreatedAt.After(finishedTasks[j].CreatedAt)+ }+ return finishedTasks[i].ID > finishedTasks[j].ID+ }+ if t1 == nil {+ return false // t1 (nil) goes to bottom+ }+ if t2 == nil {+ return true // t2 (nil) goes to bottom+ }++ // Compare completion times+ if !t1.Equal(*t2) {+ return t1.After(*t2)+ }++ // Fallback to CreatedAt if completion times are identical+ if !finishedTasks[i].CreatedAt.Equal(finishedTasks[j].CreatedAt) {+ return finishedTasks[i].CreatedAt.After(finishedTasks[j].CreatedAt)+ }++ // Final tie-breaker: ID+ return finishedTasks[i].ID > finishedTasks[j].ID+ })++ // 5. Recombine+ allTasks := make([]*maintenance.MaintenanceTask, 0, len(tasksMap))+ allTasks = append(allTasks, pendingTasks...)+ allTasks = append(allTasks, activeTasks...)+ allTasks = append(allTasks, finishedTasks...)+return allTasks, nil}@@ -1181,15 +1256,25 @@ func (as *AdminServer) GetMaintenanceTaskDetail(taskID string) (*maintenance.Tasreturn nil, err}+ // Copy task and truncate assignment history for display+ displayTask := *task+ displayTask.AssignmentHistory = nil // History is provided separately in taskDetail+// Create task detail structure from the loaded tasktaskDetail := &maintenance.TaskDetailData{- Task: task,+ Task: &displayTask,AssignmentHistory: task.AssignmentHistory, // Use assignment history from persisted taskExecutionLogs: []*maintenance.TaskExecutionLog{},RelatedTasks: []*maintenance.MaintenanceTask{},LastUpdated: time.Now(),}+ // Truncate assignment history if it's too long (display last N only)+ if len(taskDetail.AssignmentHistory) > maxAssignmentHistoryDisplay {+ startIdx := len(taskDetail.AssignmentHistory) - maxAssignmentHistoryDisplay+ taskDetail.AssignmentHistory = taskDetail.AssignmentHistory[startIdx:]+ }+if taskDetail.AssignmentHistory == nil {taskDetail.AssignmentHistory = []*maintenance.TaskAssignmentRecord{}}@@ -1205,72 +1290,19 @@ func (as *AdminServer) GetMaintenanceTaskDetail(taskID string) (*maintenance.Tas}}- // Get execution logs from worker if task is active/completed and worker is connected- if task.Status == maintenance.TaskStatusInProgress || task.Status == maintenance.TaskStatusCompleted {- if as.workerGrpcServer != nil && task.WorkerID != "" {- workerLogs, err := as.workerGrpcServer.RequestTaskLogs(task.WorkerID, taskID, 100, "")- if err == nil && len(workerLogs) > 0 {- // Convert worker logs to maintenance logs- for _, workerLog := range workerLogs {- maintenanceLog := &maintenance.TaskExecutionLog{- Timestamp: time.Unix(workerLog.Timestamp, 0),- Level: workerLog.Level,- Message: workerLog.Message,- Source: "worker",- TaskID: taskID,- WorkerID: task.WorkerID,- }- // carry structured fields if present- if len(workerLog.Fields) > 0 {- maintenanceLog.Fields = make(map[string]string, len(workerLog.Fields))- for k, v := range workerLog.Fields {- maintenanceLog.Fields[k] = v- }- }- // carry optional progress/status- if workerLog.Progress != 0 {- p := float64(workerLog.Progress)- maintenanceLog.Progress = &p- }- if workerLog.Status != "" {- maintenanceLog.Status = workerLog.Status- }- taskDetail.ExecutionLogs = append(taskDetail.ExecutionLogs, maintenanceLog)- }- } else if err != nil {- // Add a diagnostic log entry when worker logs cannot be retrieved- diagnosticLog := &maintenance.TaskExecutionLog{- Timestamp: time.Now(),- Level: "WARNING",- Message: fmt.Sprintf("Failed to retrieve worker logs: %v", err),- Source: "admin",- TaskID: taskID,- WorkerID: task.WorkerID,- }- taskDetail.ExecutionLogs = append(taskDetail.ExecutionLogs, diagnosticLog)- glog.V(1).Infof("Failed to get worker logs for task %s from worker %s: %v", taskID, task.WorkerID, err)- }+ // Load execution logs from disk+ if as.configPersistence != nil {+ logs, err := as.configPersistence.LoadTaskExecutionLogs(taskID)+ if err == nil {+ taskDetail.ExecutionLogs = logs} else {- // Add diagnostic information when worker is not available- reason := "worker gRPC server not available"- if task.WorkerID == "" {- reason = "no worker assigned to task"- }- diagnosticLog := &maintenance.TaskExecutionLog{- Timestamp: time.Now(),- Level: "INFO",- Message: fmt.Sprintf("Worker logs not available: %s", reason),- Source: "admin",- TaskID: taskID,- WorkerID: task.WorkerID,- }- taskDetail.ExecutionLogs = append(taskDetail.ExecutionLogs, diagnosticLog)+ glog.V(2).Infof("No execution logs found on disk for task %s", taskID)}}// Get related tasks (other tasks on same volume/server)if task.VolumeID != 0 || task.Server != "" {- allTasks := as.maintenanceManager.GetTasks("", "", 50) // Get recent tasks+ allTasks := as.maintenanceManager.GetTasks("", "", maxRelatedTasksDisplay) // Get recent tasksfor _, relatedTask := range allTasks {if relatedTask.ID != taskID &&(relatedTask.VolumeID == task.VolumeID || relatedTask.Server == task.Server) {@@ -1324,7 +1356,7 @@ func (as *AdminServer) getMaintenanceWorkerDetails(workerID string) (*WorkerDeta}// Get recent tasks for this worker- recentTasks := as.maintenanceManager.GetTasks(TaskStatusCompleted, "", 10)+ recentTasks := as.maintenanceManager.GetTasks(TaskStatusCompleted, "", maxRecentTasksDisplay)var workerRecentTasks []*MaintenanceTaskfor _, task := range recentTasks {if task.WorkerID == workerID {@@ -1336,12 +1368,13 @@ func (as *AdminServer) getMaintenanceWorkerDetails(workerID string) (*WorkerDetavar totalDuration time.Durationvar completedTasks, failedTasks intfor _, task := range workerRecentTasks {- if task.Status == TaskStatusCompleted {+ switch task.Status {+ case TaskStatusCompleted:completedTasks++if task.StartedAt != nil && task.CompletedAt != nil {totalDuration += task.CompletedAt.Sub(*task.StartedAt)}- } else if task.Status == TaskStatusFailed {+ case TaskStatusFailed:failedTasks++}}@@ -1370,31 +1403,29 @@ func (as *AdminServer) getMaintenanceWorkerDetails(workerID string) (*WorkerDeta}, nil}-// GetWorkerLogs fetches logs from a specific worker for a task+// GetWorkerLogs fetches logs from a specific worker for a task (now reads from disk)func (as *AdminServer) GetWorkerLogs(c *gin.Context) {workerID := c.Param("id")taskID := c.Query("taskId")- maxEntriesStr := c.DefaultQuery("maxEntries", "100")- logLevel := c.DefaultQuery("logLevel", "")-- maxEntries := int32(100)- if maxEntriesStr != "" {- if parsed, err := strconv.ParseInt(maxEntriesStr, 10, 32); err == nil {- maxEntries = int32(parsed)- }- }- if as.workerGrpcServer == nil {- c.JSON(http.StatusServiceUnavailable, gin.H{"error": "Worker gRPC server not available"})+ // Check config persistence first+ if as.configPersistence == nil {+ c.JSON(http.StatusInternalServerError, gin.H{"error": "Config persistence not available"})return}- logs, err := as.workerGrpcServer.RequestTaskLogs(workerID, taskID, maxEntries, logLevel)+ // Load logs strictly from disk to avoid timeouts and network dependency+ // This matches the behavior of the Task Detail page+ logs, err := as.configPersistence.LoadTaskExecutionLogs(taskID)if err != nil {- c.JSON(http.StatusBadGateway, gin.H{"error": fmt.Sprintf("Failed to get logs from worker: %v", err)})- return+ glog.V(2).Infof("No execution logs found on disk for task %s: %v", taskID, err)+ logs = []*maintenance.TaskExecutionLog{}}+ // Filter logs by workerID if strictly needed, but usually task logs are what we want+ // The persistent logs struct (TaskExecutionLog) matches what the frontend expects for the detail view+ // ensuring consistent display.+c.JSON(http.StatusOK, gin.H{"worker_id": workerID, "task_id": taskID, "logs": logs, "count": len(logs)})}diff --git a/weed/admin/dash/config_persistence.go b/weed/admin/dash/config_persistence.goindex 6578ee8904..061abc7c9f 100644--- a/weed/admin/dash/config_persistence.go+++ b/weed/admin/dash/config_persistence.go@@ -962,7 +962,36 @@ func (cp *ConfigPersistence) CleanupCompletedTasks() error {// Sort by completion time (most recent first)sort.Slice(completedTasks, func(i, j int) bool {- return completedTasks[i].CompletedAt.After(*completedTasks[j].CompletedAt)+ t1 := completedTasks[i].CompletedAt+ t2 := completedTasks[j].CompletedAt++ // Handle nil completion times+ if t1 == nil && t2 == nil {+ // Both nil, fallback to CreatedAt+ if !completedTasks[i].CreatedAt.Equal(completedTasks[j].CreatedAt) {+ return completedTasks[i].CreatedAt.After(completedTasks[j].CreatedAt)+ }+ return completedTasks[i].ID > completedTasks[j].ID+ }+ if t1 == nil {+ return false // t1 (nil) goes to bottom+ }+ if t2 == nil {+ return true // t2 (nil) goes to bottom+ }++ // Compare completion times+ if !t1.Equal(*t2) {+ return t1.After(*t2)+ }++ // Fallback to CreatedAt if completion times are identical+ if !completedTasks[i].CreatedAt.Equal(completedTasks[j].CreatedAt) {+ return completedTasks[i].CreatedAt.After(completedTasks[j].CreatedAt)+ }++ // Final tie-breaker: ID+ return completedTasks[i].ID > completedTasks[j].ID})// Keep only the most recent MaxCompletedTasks, delete the restdiff --git a/weed/admin/dash/worker_grpc_server.go b/weed/admin/dash/worker_grpc_server.goindex 34e9a92840..b5841f82af 100644--- a/weed/admin/dash/worker_grpc_server.go+++ b/weed/admin/dash/worker_grpc_server.go@@ -8,6 +8,7 @@ import ("sync""time"+ "github.com/seaweedfs/seaweedfs/weed/admin/maintenance""github.com/seaweedfs/seaweedfs/weed/glog""github.com/seaweedfs/seaweedfs/weed/pb""github.com/seaweedfs/seaweedfs/weed/pb/worker_pb"@@ -17,6 +18,15 @@ import ("google.golang.org/grpc/peer")+const (+ maxLogFetchLimit = 1000+ maxLogMessageSize = 2000+ maxLogFieldsCount = 20+ logRequestTimeout = 10 * time.Second+ logResponseTimeout = 30 * time.Second+ logSendTimeout = 10 * time.Second+)+// WorkerGrpcServer implements the WorkerService gRPC interfacetype WorkerGrpcServer struct {worker_pb.UnimplementedWorkerServiceServer@@ -42,7 +52,6 @@ type LogRequestContext struct {TaskID stringWorkerID stringResponseCh chan *worker_pb.TaskLogResponse- Timeout time.Time}// WorkerConnection represents an active worker connection@@ -89,8 +98,9 @@ func (s *WorkerGrpcServer) StartWithTLS(port int) error {s.listener = listeners.running = true- // Start cleanup routine+ // Start background routinesgo s.cleanupRoutine()+ go s.activeLogFetchLoop()// Start serving in a goroutinego func() {@@ -437,9 +447,90 @@ func (s *WorkerGrpcServer) handleTaskCompletion(conn *WorkerConnection, completi} else {glog.Errorf("Worker %s failed task %s: %s", conn.workerID, completion.TaskId, completion.ErrorMessage)}++ // Fetch and persist logs+ go s.FetchAndSaveLogs(conn.workerID, completion.TaskId)}}+// FetchAndSaveLogs retrieves logs from a worker and saves them to disk+func (s *WorkerGrpcServer) FetchAndSaveLogs(workerID, taskID string) error {+ // Add a small initial delay to allow worker to finalize and sync logs+ // especially when this is called immediately after TaskComplete+ time.Sleep(300 * time.Millisecond)++ var workerLogs []*worker_pb.TaskLogEntry+ var err error++ // Retry a few times if fetch fails, as logs might be in the middle of a terminal sync+ for attempt := 1; attempt <= 3; attempt++ {+ workerLogs, err = s.RequestTaskLogs(workerID, taskID, maxLogFetchLimit, "")+ if err == nil {+ break+ }+ if attempt < 3 {+ glog.V(1).Infof("Fetch logs attempt %d failed for task %s: %v. Retrying in 1s...", attempt, taskID, err)+ time.Sleep(1 * time.Second)+ }+ }++ if err != nil {+ glog.Warningf("Failed to fetch logs for task %s after 3 attempts: %v", taskID, err)+ return err+ }++ // Convert logs+ var maintenanceLogs []*maintenance.TaskExecutionLog+ for _, workerLog := range workerLogs {+ maintenanceLog := &maintenance.TaskExecutionLog{+ Timestamp: time.Unix(workerLog.Timestamp, 0),+ Level: workerLog.Level,+ Message: workerLog.Message,+ Source: "worker",+ TaskID: taskID,+ WorkerID: workerID,+ }++ // Truncate very long messages to prevent rendering issues and disk bloat+ if len(maintenanceLog.Message) > maxLogMessageSize {+ maintenanceLog.Message = maintenanceLog.Message[:maxLogMessageSize] + "... (truncated)"+ }++ // carry structured fields if present+ if len(workerLog.Fields) > 0 {+ maintenanceLog.Fields = make(map[string]string)+ fieldCount := 0+ for k, v := range workerLog.Fields {+ if fieldCount >= maxLogFieldsCount {+ maintenanceLog.Fields["..."] = fmt.Sprintf("(%d more fields truncated)", len(workerLog.Fields)-maxLogFieldsCount)+ break+ }+ maintenanceLog.Fields[k] = v+ fieldCount+++ }+ }++ // carry optional progress/status+ if workerLog.Progress != 0 {+ p := float64(workerLog.Progress)+ maintenanceLog.Progress = &p+ }+ if workerLog.Status != "" {+ maintenanceLog.Status = workerLog.Status+ }+ maintenanceLogs = append(maintenanceLogs, maintenanceLog)+ }++ // Persist logs+ if s.adminServer.configPersistence != nil {+ if err := s.adminServer.configPersistence.SaveTaskExecutionLogs(taskID, maintenanceLogs); err != nil {+ glog.Errorf("Failed to persist logs for task %s: %v", taskID, err)+ return err+ }+ }+ return nil+}+// handleTaskLogResponse processes task log responses from workersfunc (s *WorkerGrpcServer) handleTaskLogResponse(conn *WorkerConnection, response *worker_pb.TaskLogResponse) {requestKey := fmt.Sprintf("%s:%s", response.WorkerId, response.TaskId)@@ -575,10 +666,13 @@ func (s *WorkerGrpcServer) RequestTaskLogs(workerID, taskID string, maxEntries iTaskID: taskID,WorkerID: workerID,ResponseCh: responseCh,- Timeout: time.Now().Add(10 * time.Second),}s.logRequestsMutex.Lock()+ if _, exists := s.pendingLogRequests[requestKey]; exists {+ s.logRequestsMutex.Unlock()+ return nil, fmt.Errorf("a log request for task %s is already in progress", taskID)+ }s.pendingLogRequests[requestKey] = requestContexts.logRequestsMutex.Unlock()@@ -601,10 +695,12 @@ func (s *WorkerGrpcServer) RequestTaskLogs(workerID, taskID string, maxEntries iselect {case conn.outgoing <- logRequest:glog.V(1).Infof("Log request sent to worker %s for task %s", workerID, taskID)- case <-time.After(5 * time.Second):+ case <-time.After(logSendTimeout):// Clean up pending request on timeouts.logRequestsMutex.Lock()- delete(s.pendingLogRequests, requestKey)+ if s.pendingLogRequests[requestKey] == requestContext {+ delete(s.pendingLogRequests, requestKey)+ }s.logRequestsMutex.Unlock()return nil, fmt.Errorf("timeout sending log request to worker %s", workerID)}@@ -617,10 +713,12 @@ func (s *WorkerGrpcServer) RequestTaskLogs(workerID, taskID string, maxEntries i}glog.V(1).Infof("Received %d log entries for task %s from worker %s", len(response.LogEntries), taskID, workerID)return response.LogEntries, nil- case <-time.After(10 * time.Second):+ case <-time.After(logResponseTimeout):// Clean up pending request on timeouts.logRequestsMutex.Lock()- delete(s.pendingLogRequests, requestKey)+ if s.pendingLogRequests[requestKey] == requestContext {+ delete(s.pendingLogRequests, requestKey)+ }s.logRequestsMutex.Unlock()return nil, fmt.Errorf("timeout waiting for log response from worker %s", workerID)}@@ -684,3 +782,38 @@ func findClientAddress(ctx context.Context) string {}return pr.Addr.String()}++// activeLogFetchLoop periodically fetches logs for all in-progress tasks+func (s *WorkerGrpcServer) activeLogFetchLoop() {+ ticker := time.NewTicker(30 * time.Second)+ defer ticker.Stop()++ for {+ select {+ case <-s.stopChan:+ return+ case <-ticker.C:+ if !s.running || s.adminServer == nil || s.adminServer.maintenanceManager == nil {+ continue+ }++ // Get all in-progress tasks+ tasks := s.adminServer.maintenanceManager.GetTasks(maintenance.TaskStatusInProgress, "", 0)+ if len(tasks) == 0 {+ continue+ }++ glog.V(2).Infof("Background log fetcher: found %d in-progress tasks", len(tasks))+ for _, task := range tasks {+ if task.WorkerID != "" {+ // Use a goroutine to avoid blocking the loop+ go func(wID, tID string) {+ if err := s.FetchAndSaveLogs(wID, tID); err != nil {+ glog.V(2).Infof("Background log fetch failed for task %s on worker %s: %v", tID, wID, err)+ }+ }(task.WorkerID, task.ID)+ }+ }+ }+ }+}diff --git a/weed/admin/handlers/maintenance_handlers.go b/weed/admin/handlers/maintenance_handlers.goindex 3c1b5e410c..005f60277b 100644--- a/weed/admin/handlers/maintenance_handlers.go+++ b/weed/admin/handlers/maintenance_handlers.go@@ -39,6 +39,11 @@ func NewMaintenanceHandlers(adminServer *dash.AdminServer) *MaintenanceHandlersfunc (h *MaintenanceHandlers) ShowTaskDetail(c *gin.Context) {taskID := c.Param("id")+ if h.adminServer == nil {+ c.String(http.StatusInternalServerError, "Admin server not initialized")+ return+ }+taskDetail, err := h.adminServer.GetMaintenanceTaskDetail(taskID)if err != nil {glog.Errorf("DEBUG ShowTaskDetail: error getting task detail for %s: %v", taskID, err)@@ -111,6 +116,10 @@ func (h *MaintenanceHandlers) ShowMaintenanceQueue(c *gin.Context) {// ShowMaintenanceWorkers displays the maintenance workers pagefunc (h *MaintenanceHandlers) ShowMaintenanceWorkers(c *gin.Context) {+ if h.adminServer == nil {+ c.JSON(http.StatusInternalServerError, gin.H{"error": "Admin server not initialized"})+ return+ }workersData, err := h.adminServer.GetMaintenanceWorkersData()if err != nil {c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})@@ -339,6 +348,8 @@ func (h *MaintenanceHandlers) UpdateTaskConfig(c *gin.Context) {glog.Warningf("Failed to save task config to protobuf file: %v", err)// Don't fail the request, just log the warning}+ } else if h.adminServer == nil {+ glog.Warningf("Failed to save task config: admin server not initialized")}// Trigger a configuration reload in the maintenance manager@@ -492,74 +503,25 @@ func (h *MaintenanceHandlers) UpdateMaintenanceConfig(c *gin.Context) {// Helper methods that delegate to AdminServerfunc (h *MaintenanceHandlers) getMaintenanceQueueData() (*maintenance.MaintenanceQueueData, error) {- tasks, err := h.getMaintenanceTasks()- if err != nil {- return nil, err- }-- workers, err := h.getMaintenanceWorkers()- if err != nil {- return nil, err- }-- stats, err := h.getMaintenanceQueueStats()- if err != nil {- return nil, err- }-- data := &maintenance.MaintenanceQueueData{- Tasks: tasks,- Workers: workers,- Stats: stats,- LastUpdated: time.Now(),- }-- return data, nil-}--func (h *MaintenanceHandlers) getMaintenanceQueueStats() (*maintenance.QueueStats, error) {- // Use the exported method from AdminServer- return h.adminServer.GetMaintenanceQueueStats()-}--func (h *MaintenanceHandlers) getMaintenanceTasks() ([]*maintenance.MaintenanceTask, error) {- // Call the maintenance manager directly to get recent tasks (limit for performance)if h.adminServer == nil {- return []*maintenance.MaintenanceTask{}, nil+ return nil, fmt.Errorf("admin server not initialized")}-- manager := h.adminServer.GetMaintenanceManager()- if manager == nil {- return []*maintenance.MaintenanceTask{}, nil- }-- // Get recent tasks only (last 100) to prevent slow page loads- // Users can view more tasks via pagination if needed- allTasks := manager.GetTasks("", "", 100)- return allTasks, nil+ // Use the exported method from AdminServer used by the JSON API+ return h.adminServer.GetMaintenanceQueueData()}-func (h *MaintenanceHandlers) getMaintenanceWorkers() ([]*maintenance.MaintenanceWorker, error) {- // Get workers from the admin server's maintenance manager+func (h *MaintenanceHandlers) getMaintenanceConfig() (*maintenance.MaintenanceConfigData, error) {if h.adminServer == nil {- return []*maintenance.MaintenanceWorker{}, nil+ return nil, fmt.Errorf("admin server not initialized")}-- if h.adminServer.GetMaintenanceManager() == nil {- return []*maintenance.MaintenanceWorker{}, nil- }-- // Get workers from the maintenance manager- workers := h.adminServer.GetMaintenanceManager().GetWorkers()- return workers, nil-}--func (h *MaintenanceHandlers) getMaintenanceConfig() (*maintenance.MaintenanceConfigData, error) {// Delegate to AdminServer's real persistence methodreturn h.adminServer.GetMaintenanceConfigData()}func (h *MaintenanceHandlers) updateMaintenanceConfig(config *maintenance.MaintenanceConfig) error {+ if h.adminServer == nil {+ return fmt.Errorf("admin server not initialized")+ }// Delegate to AdminServer's real persistence methodreturn h.adminServer.UpdateMaintenanceConfigData(config)}diff --git a/weed/admin/maintenance/maintenance_queue.go b/weed/admin/maintenance/maintenance_queue.goindex d39c96a303..8c863fcf48 100644--- a/weed/admin/maintenance/maintenance_queue.go+++ b/weed/admin/maintenance/maintenance_queue.go@@ -587,15 +587,35 @@ func (mq *MaintenanceQueue) GetTasks(status MaintenanceTaskStatus, taskType Maincontinue}tasks = append(tasks, task)- if limit > 0 && len(tasks) >= limit {- break- }}- // Sort by creation time (newest first)- sort.Slice(tasks, func(i, j int) bool {- return tasks[i].CreatedAt.After(tasks[j].CreatedAt)- })+ // Sort based on status+ if status == TaskStatusCompleted || status == TaskStatusFailed || status == TaskStatusCancelled {+ sort.Slice(tasks, func(i, j int) bool {+ t1 := tasks[i].CompletedAt+ t2 := tasks[j].CompletedAt+ if t1 == nil && t2 == nil {+ return tasks[i].CreatedAt.After(tasks[j].CreatedAt)+ }+ if t1 == nil {+ return false+ }+ if t2 == nil {+ return true+ }+ return t1.After(*t2)+ })+ } else {+ // Default to creation time (newest first)+ sort.Slice(tasks, func(i, j int) bool {+ return tasks[i].CreatedAt.After(tasks[j].CreatedAt)+ })+ }++ // Apply limit after sorting+ if limit > 0 && len(tasks) > limit {+ tasks = tasks[:limit]+ }return tasks}diff --git a/weed/admin/view/app/admin_templ.go b/weed/admin/view/app/admin_templ.goindex cbff92c5df..c32024b951 100644--- a/weed/admin/view/app/admin_templ.go+++ b/weed/admin/view/app/admin_templ.go@@ -1,6 +1,6 @@// Code generated by templ - DO NOT EDIT.-// templ: version: v0.3.960+// templ: version: v0.3.977package app//lint:file-ignore SA4006 This context is only used if a nested component is present.diff --git a/weed/admin/view/app/cluster_brokers_templ.go b/weed/admin/view/app/cluster_brokers_templ.goindex 18b5b0c34e..f176dc0d63 100644--- a/weed/admin/view/app/cluster_brokers_templ.go+++ b/weed/admin/view/app/cluster_brokers_templ.go@@ -1,6 +1,6 @@// Code generated by templ - DO NOT EDIT.-// templ: version: v0.3.960+// templ: version: v0.3.977package app//lint:file-ignore SA4006 This context is only used if a nested component is present.diff --git a/weed/admin/view/app/cluster_collections_templ.go b/weed/admin/view/app/cluster_collections_templ.goindex 1e0234cbd8..a800f63eaa 100644--- a/weed/admin/view/app/cluster_collections_templ.go+++ b/weed/admin/view/app/cluster_collections_templ.go@@ -1,6 +1,6 @@// Code generated by templ - DO NOT EDIT.-// templ: version: v0.3.960+// templ: version: v0.3.977package app//lint:file-ignore SA4006 This context is only used if a nested component is present.diff --git a/weed/admin/view/app/cluster_ec_shards_templ.go b/weed/admin/view/app/cluster_ec_shards_templ.goindex 05a557c4f0..b46111da7f 100644--- a/weed/admin/view/app/cluster_ec_shards_templ.go+++ b/weed/admin/view/app/cluster_ec_shards_templ.go@@ -1,6 +1,6 @@// Code generated by templ - DO NOT EDIT.-// templ: version: v0.3.960+// templ: version: v0.3.977package app//lint:file-ignore SA4006 This context is only used if a nested component is present.diff --git a/weed/admin/view/app/cluster_ec_volumes_templ.go b/weed/admin/view/app/cluster_ec_volumes_templ.goindex d3420d3203..42996be48c 100644--- a/weed/admin/view/app/cluster_ec_volumes_templ.go+++ b/weed/admin/view/app/cluster_ec_volumes_templ.go@@ -1,6 +1,6 @@// Code generated by templ - DO NOT EDIT.-// templ: version: v0.3.960+// templ: version: v0.3.977package app//lint:file-ignore SA4006 This context is only used if a nested component is present.diff --git a/weed/admin/view/app/cluster_filers_templ.go b/weed/admin/view/app/cluster_filers_templ.goindex c61c218fcd..8aad3730e2 100644--- a/weed/admin/view/app/cluster_filers_templ.go+++ b/weed/admin/view/app/cluster_filers_templ.go@@ -1,6 +1,6 @@// Code generated by templ - DO NOT EDIT.-// templ: version: v0.3.960+// templ: version: v0.3.977package app//lint:file-ignore SA4006 This context is only used if a nested component is present.diff --git a/weed/admin/view/app/cluster_masters_templ.go b/weed/admin/view/app/cluster_masters_templ.goindex b10881bc0c..e68949291f 100644--- a/weed/admin/view/app/cluster_masters_templ.go+++ b/weed/admin/view/app/cluster_masters_templ.go@@ -1,6 +1,6 @@// Code generated by templ - DO NOT EDIT.-// templ: version: v0.3.960+// templ: version: v0.3.977package app//lint:file-ignore SA4006 This context is only used if a nested component is present.diff --git a/weed/admin/view/app/cluster_volume_servers_templ.go b/weed/admin/view/app/cluster_volume_servers_templ.goindex 3a47df7d96..f27f088a50 100644--- a/weed/admin/view/app/cluster_volume_servers_templ.go+++ b/weed/admin/view/app/cluster_volume_servers_templ.go@@ -1,6 +1,6 @@// Code generated by templ - DO NOT EDIT.-// templ: version: v0.3.960+// templ: version: v0.3.977package app//lint:file-ignore SA4006 This context is only used if a nested component is present.diff --git a/weed/admin/view/app/cluster_volumes_templ.go b/weed/admin/view/app/cluster_volumes_templ.goindex 117ae8585f..66817e49f7 100644--- a/weed/admin/view/app/cluster_volumes_templ.go+++ b/weed/admin/view/app/cluster_volumes_templ.go@@ -1,6 +1,6 @@// Code generated by templ - DO NOT EDIT.-// templ: version: v0.3.960+// templ: version: v0.3.977package app//lint:file-ignore SA4006 This context is only used if a nested component is present.diff --git a/weed/admin/view/app/collection_details_templ.go b/weed/admin/view/app/collection_details_templ.goindex 16e025ed2c..313b535a9d 100644--- a/weed/admin/view/app/collection_details_templ.go+++ b/weed/admin/view/app/collection_details_templ.go@@ -1,6 +1,6 @@// Code generated by templ - DO NOT EDIT.-// templ: version: v0.3.960+// templ: version: v0.3.977package app//lint:file-ignore SA4006 This context is only used if a nested component is present.diff --git a/weed/admin/view/app/ec_volume_details_templ.go b/weed/admin/view/app/ec_volume_details_templ.goindex 1092f1b865..d09665c8fe 100644--- a/weed/admin/view/app/ec_volume_details_templ.go+++ b/weed/admin/view/app/ec_volume_details_templ.go@@ -1,6 +1,6 @@// Code generated by templ - DO NOT EDIT.-// templ: version: v0.3.960+// templ: version: v0.3.977package app//lint:file-ignore SA4006 This context is only used if a nested component is present.diff --git a/weed/admin/view/app/file_browser_templ.go b/weed/admin/view/app/file_browser_templ.goindex 6da7ad22dc..8e8793e990 100644--- a/weed/admin/view/app/file_browser_templ.go+++ b/weed/admin/view/app/file_browser_templ.go@@ -1,6 +1,6 @@// Code generated by templ - DO NOT EDIT.-// templ: version: v0.3.960+// templ: version: v0.3.977package app//lint:file-ignore SA4006 This context is only used if a nested component is present.diff --git a/weed/admin/view/app/iceberg_catalog_templ.go b/weed/admin/view/app/iceberg_catalog_templ.goindex 2a74583cb1..dc5d766914 100644--- a/weed/admin/view/app/iceberg_catalog_templ.go+++ b/weed/admin/view/app/iceberg_catalog_templ.go@@ -1,6 +1,6 @@// Code generated by templ - DO NOT EDIT.-// templ: version: v0.3.960+// templ: version: v0.3.977package app//lint:file-ignore SA4006 This context is only used if a nested component is present.diff --git a/weed/admin/view/app/iceberg_namespaces_templ.go b/weed/admin/view/app/iceberg_namespaces_templ.goindex 8df314ef41..4d6d973e57 100644--- a/weed/admin/view/app/iceberg_namespaces_templ.go+++ b/weed/admin/view/app/iceberg_namespaces_templ.go@@ -1,6 +1,6 @@// Code generated by templ - DO NOT EDIT.-// templ: version: v0.3.960+// templ: version: v0.3.977package app//lint:file-ignore SA4006 This context is only used if a nested component is present.diff --git a/weed/admin/view/app/iceberg_tables_templ.go b/weed/admin/view/app/iceberg_tables_templ.goindex 87084f0b8a..06e82b8cab 100644--- a/weed/admin/view/app/iceberg_tables_templ.go+++ b/weed/admin/view/app/iceberg_tables_templ.go@@ -1,6 +1,6 @@// Code generated by templ - DO NOT EDIT.-// templ: version: v0.3.960+// templ: version: v0.3.977package app//lint:file-ignore SA4006 This context is only used if a nested component is present.diff --git a/weed/admin/view/app/maintenance_config_schema_templ.go b/weed/admin/view/app/maintenance_config_schema_templ.goindex 289590fd69..c44e37ad44 100644--- a/weed/admin/view/app/maintenance_config_schema_templ.go+++ b/weed/admin/view/app/maintenance_config_schema_templ.go@@ -1,6 +1,6 @@// Code generated by templ - DO NOT EDIT.-// templ: version: v0.3.960+// templ: version: v0.3.977package app//lint:file-ignore SA4006 This context is only used if a nested component is present.diff --git a/weed/admin/view/app/maintenance_config_templ.go b/weed/admin/view/app/maintenance_config_templ.goindex 75017b31da..685f51b07b 100644--- a/weed/admin/view/app/maintenance_config_templ.go+++ b/weed/admin/view/app/maintenance_config_templ.go@@ -1,6 +1,6 @@// Code generated by templ - DO NOT EDIT.-// templ: version: v0.3.960+// templ: version: v0.3.977package app//lint:file-ignore SA4006 This context is only used if a nested component is present.diff --git a/weed/admin/view/app/maintenance_queue.templ b/weed/admin/view/app/maintenance_queue.templindex fa56cdb3fd..d67ab56c2e 100644--- a/weed/admin/view/app/maintenance_queue.templ+++ b/weed/admin/view/app/maintenance_queue.templ@@ -302,12 +302,7 @@ templ MaintenanceQueue(data *maintenance.MaintenanceQueueData) {// Debug output to browser consoleconsole.log("DEBUG: Maintenance Queue Template loaded");- // Auto-refresh every 10 seconds- setInterval(function() {- if (!document.hidden) {- window.location.reload();- }- }, 10000);+window.triggerScan = function() {console.log("triggerScan called");diff --git a/weed/admin/view/app/maintenance_queue_templ.go b/weed/admin/view/app/maintenance_queue_templ.goindex bd2f845e55..6c06e7f805 100644--- a/weed/admin/view/app/maintenance_queue_templ.go+++ b/weed/admin/view/app/maintenance_queue_templ.go@@ -1,6 +1,6 @@// Code generated by templ - DO NOT EDIT.-// templ: version: v0.3.960+// templ: version: v0.3.977package app//lint:file-ignore SA4006 This context is only used if a nested component is present.@@ -610,7 +610,7 @@ func MaintenanceQueue(data *maintenance.MaintenanceQueueData) templ.Component {return templ_7745c5c3_Err}}- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 63, "</div></div></div></div></div><script>\n // Debug output to browser console\n console.log(\"DEBUG: Maintenance Queue Template loaded\");\n \n // Auto-refresh every 10 seconds\n setInterval(function() {\n if (!document.hidden) {\n window.location.reload();\n }\n }, 10000);\n\n window.triggerScan = function() {\n console.log(\"triggerScan called\");\n fetch('/api/maintenance/scan', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n }\n })\n .then(response => response.json())\n .then(data => {\n if (data.success) {\n showToast('Success', 'Maintenance scan triggered successfully', 'success');\n setTimeout(() => window.location.reload(), 2000);\n } else {\n showToast('Error', 'Failed to trigger scan: ' + (data.error || 'Unknown error'), 'danger');\n }\n })\n .catch(error => {\n showToast('Error', 'Error: ' + error.message, 'danger');\n });\n };\n\n window.refreshPage = function() {\n console.log(\"refreshPage called\");\n window.location.reload();\n };\n\n window.navigateToTask = function(element) {\n const taskId = element.getAttribute('data-task-id');\n if (taskId) {\n window.location.href = '/maintenance/tasks/' + taskId;\n }\n };\n </script>")+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 63, "</div></div></div></div></div><script>\n // Debug output to browser console\n console.log(\"DEBUG: Maintenance Queue Template loaded\");\n \n\n\n window.triggerScan = function() {\n console.log(\"triggerScan called\");\n fetch('/api/maintenance/scan', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n }\n })\n .then(response => response.json())\n .then(data => {\n if (data.success) {\n showToast('Success', 'Maintenance scan triggered successfully', 'success');\n setTimeout(() => window.location.reload(), 2000);\n } else {\n showToast('Error', 'Failed to trigger scan: ' + (data.error || 'Unknown error'), 'danger');\n }\n })\n .catch(error => {\n showToast('Error', 'Error: ' + error.message, 'danger');\n });\n };\n\n window.refreshPage = function() {\n console.log(\"refreshPage called\");\n window.location.reload();\n };\n\n window.navigateToTask = function(element) {\n const taskId = element.getAttribute('data-task-id');\n if (taskId) {\n window.location.href = '/maintenance/tasks/' + taskId;\n }\n };\n </script>")if templ_7745c5c3_Err != nil {return templ_7745c5c3_Err}@@ -809,7 +809,7 @@ func ProgressBar(progress float64, status maintenance.MaintenanceTaskStatus) temvar templ_7745c5c3_Var35 stringtempl_7745c5c3_Var35, templ_7745c5c3_Err = templruntime.SanitizeStyleAttributeValues(fmt.Sprintf("width: %.1f%%", progress))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/maintenance_queue.templ`, Line: 390, Col: 102}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/maintenance_queue.templ`, Line: 385, Col: 102}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var35))if templ_7745c5c3_Err != nil {@@ -822,7 +822,7 @@ func ProgressBar(progress float64, status maintenance.MaintenanceTaskStatus) temvar templ_7745c5c3_Var36 stringtempl_7745c5c3_Var36, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%.1f%%", progress))if templ_7745c5c3_Err != nil {- return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/maintenance_queue.templ`, Line: 393, Col: 66}+ return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/maintenance_queue.templ`, Line: 388, Col: 66}}_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var36))if templ_7745c5c3_Err != nil {diff --git a/weed/admin/view/app/maintenance_workers_templ.go b/weed/admin/view/app/maintenance_workers_templ.goindex a1de325b80..8c84361a9b 100644--- a/weed/admin/view/app/maintenance_workers_templ.go+++ b/weed/admin/view/app/maintenance_workers_templ.go@@ -1,6 +1,6 @@// Code generated by templ - DO NOT EDIT.-// templ: version: v0.3.960+// templ: version: v0.3.977package app//lint:file-ignore SA4006 This context is only used if a nested component is present.diff --git a/weed/admin/view/app/object_store_users_templ.go b/weed/admin/view/app/object_store_users_templ.goindex 2c11fe0e2f..34b8cf5173 100644--- a/weed/admin/view/app/object_store_users_templ.go+++ b/weed/admin/view/app/object_store_users_templ.go@@ -1,6 +1,6 @@// Code generated by templ - DO NOT EDIT.-// templ: version: v0.3.960+// templ: version: v0.3.977package app//lint:file-ignore SA4006 This context is only used if a nested component is present.diff --git a/weed/admin/view/app/policies_templ.go b/weed/admin/view/app/policies_templ.goindex da911247cc..8e1de7c239 100644--- a/weed/admin/view/app/policies_templ.go+++ b/weed/admin/view/app/policies_templ.go@@ -1,6 +1,6 @@// Code generated by templ - DO NOT EDIT.-// templ: version: v0.3.960+// templ: version: v0.3.977package app//lint:file-ignore SA4006 This context is only used if a nested component is present.diff --git a/weed/admin/view/app/s3_buckets_templ.go b/weed/admin/view/app/s3_buckets_templ.goindex 6b58b55807..7644bd750d 100644--- a/weed/admin/view/app/s3_buckets_templ.go+++ b/weed/admin/view/app/s3_buckets_templ.go@@ -1,6 +1,6 @@// Code generated by templ - DO NOT EDIT.-// templ: version: v0.3.960+// templ: version: v0.3.977package app//lint:file-ignore SA4006 This context is only used if a nested component is present.diff --git a/weed/admin/view/app/s3tables_buckets_templ.go b/weed/admin/view/app/s3tables_buckets_templ.goindex 0312c44f27..56478162ce 100644--- a/weed/admin/view/app/s3tables_buckets_templ.go+++ b/weed/admin/view/app/s3tables_buckets_templ.go@@ -1,6 +1,6 @@// Code generated by templ - DO NOT EDIT.-// templ: version: v0.3.960+// templ: version: v0.3.977package app//lint:file-ignore SA4006 This context is only used if a nested component is present.diff --git a/weed/admin/view/app/s3tables_namespaces_templ.go b/weed/admin/view/app/s3tables_namespaces_templ.goindex e18605cb93..6cf818eafd 100644--- a/weed/admin/view/app/s3tables_namespaces_templ.go+++ b/weed/admin/view/app/s3tables_namespaces_templ.go@@ -1,6 +1,6 @@// Code generated by templ - DO NOT EDIT.-// templ: version: v0.3.960+// templ: version: v0.3.977package app//lint:file-ignore SA4006 This context is only used if a nested component is present.diff --git a/weed/admin/view/app/s3tables_tables_templ.go b/weed/admin/view/app/s3tables_tables_templ.goindex 22c6e7ca1e..25c03f2696 100644--- a/weed/admin/view/app/s3tables_tables_templ.go+++ b/weed/admin/view/app/s3tables_tables_templ.go@@ -1,6 +1,6 @@// Code generated by templ - DO NOT EDIT.-// templ: version: v0.3.960+// templ: version: v0.3.977package app//lint:file-ignore SA4006 This context is only used if a nested component is present.diff --git a/weed/admin/view/app/service_accounts_templ.go b/weed/admin/view/app/service_accounts_templ.goindex 64805f5b62..6905f9ac32 100644--- a/weed/admin/view/app/service_accounts_templ.go+++ b/weed/admin/view/app/service_accounts_templ.go@@ -1,6 +1,6 @@// Code generated by templ - DO NOT EDIT.-// templ: version: v0.3.960+// templ: version: v0.3.977package app//lint:file-ignore SA4006 This context is only used if a nested component is present.diff --git a/weed/admin/view/app/subscribers_templ.go b/weed/admin/view/app/subscribers_templ.goindex 32b743da66..103963fe15 100644--- a/weed/admin/view/app/subscribers_templ.go+++ b/weed/admin/view/app/subscribers_templ.go@@ -1,6 +1,6 @@// Code generated by templ - DO NOT EDIT.-// templ: version: v0.3.960+// templ: version: v0.3.977package app//lint:file-ignore SA4006 This context is only used if a nested component is present.diff --git a/weed/admin/view/app/task_config_schema.templ b/weed/admin/view/app/task_config_schema.templindex 91d46190f9..1c33938540 100644--- a/weed/admin/view/app/task_config_schema.templ+++ b/weed/admin/view/app/task_config_schema.templ@@ -430,7 +430,7 @@ func getTaskConfigStringField(config interface{}, fieldName string) string {func getTaskNumberStep(field *config.Field) string {if field.Type == config.FieldTypeFloat {- return "0.01"+ return "any"}return "1"}diff --git a/weed/admin/view/app/task_config_schema_templ.go b/weed/admin/view/app/task_config_schema_templ.goindex ebe65a5715..80f0c2871a 100644--- a/weed/admin/view/app/task_config_schema_templ.go+++ b/weed/admin/view/app/task_config_schema_templ.go@@ -1,6 +1,6 @@// Code generated by templ - DO NOT EDIT.-// templ: version: v0.3.960+// templ: version: v0.3.977package app//lint:file-ignore SA4006 This context is only used if a nested component is present.@@ -891,7 +891,7 @@ func getTaskConfigStringField(config interface{}, fieldName string) string {func getTaskNumberStep(field *config.Field) string {if field.Type == config.FieldTypeFloat {- return "0.01"+ return "any"}return "1"}diff --git a/weed/admin/view/app/task_config_templ.go b/weed/admin/view/app/task_config_templ.goindex 243b5816e8..d6edc5c643 100644--- a/weed/admin/view/app/task_config_templ.go+++ b/weed/admin/view/app/task_config_templ.go@@ -1,6 +1,6 @@// Code generated by templ - DO NOT EDIT.-// templ: version: v0.3.960+// templ: version: v0.3.977package app//lint:file-ignore SA4006 This context is only used if a nested component is present.diff --git a/weed/admin/view/app/task_config_templ_templ.go b/weed/admin/view/app/task_config_templ_templ.goindex 5b5d261b0a..3e2f60aeea 100644--- a/weed/admin/view/app/task_config_templ_templ.go+++ b/weed/admin/view/app/task_config_templ_templ.go@@ -1,6 +1,6 @@// Code generated by templ - DO NOT EDIT.-// templ: version: v0.3.960+// templ: version: v0.3.977package app//lint:file-ignore SA4006 This context is only used if a nested component is present.diff --git a/weed/admin/view/app/task_detail.templ b/weed/admin/view/app/task_detail.templindex aa1a452600..0e46c713d4 100644--- a/weed/admin/view/app/task_detail.templ+++ b/weed/admin/view/app/task_detail.templ@@ -942,10 +942,48 @@ templ TaskDetail(data *maintenance.TaskDetailData) {return;}+// Format and display logs with structured fieldslet logText = '';++ // Helper function to format timestamps robustly+ function formatTimestamp(timestamp) {+ if (!timestamp) {+ return 'N/A';+ }++ let date;++ // Check if timestamp is a numeric string (e.g., "1738652668")+ if (typeof timestamp === 'string' && /^\d+$/.test(timestamp)) {+ const numericTimestamp = parseInt(timestamp, 10);+ // Treat values > 10^10 as milliseconds, otherwise as seconds+ date = numericTimestamp > 10000000000+ ? new Date(numericTimestamp)+ : new Date(numericTimestamp * 1000);+ } else if (typeof timestamp === 'string') {+ // ISO date string+ date = new Date(timestamp);+ } else if (typeof timestamp === 'number') {+ // Numeric timestamp (seconds or milliseconds)+ date = timestamp > 10000000000+ ? new Date(timestamp)+ : new Date(timestamp * 1000);+ } else {+ return 'N/A';+ }++ // Validate the date+ if (isNaN(date.getTime())) {+ return 'N/A';+ }++ return date.toISOString();+ }+logs.forEach(entry => {- const timestamp = entry.timestamp ? new Date(entry.timestamp * 1000).toISOString() : 'N/A';+ const timestamp = formatTimestamp(entry.timestamp);+const level = entry.level || 'INFO';const message = entry.message || '';@@ -1011,7 +1049,12 @@ templ TaskDetail(data *maintenance.TaskDetailData) {let logContent = '';if (data.logs && data.logs.length > 0) {data.logs.forEach(entry => {- const timestamp = entry.timestamp ? new Date(entry.timestamp * 1000).toISOString() : 'N/A';+ let timestamp;+ if (typeof entry.timestamp === 'string') {+ timestamp = new Date(entry.timestamp).toISOString();+ } else {+ timestamp = entry.timestamp ? new Date(entry.timestamp * 1000).toISOString() : 'N/A';+ }const level = entry.level || 'INFO';const message = entry.message || '';diff --git a/weed/admin/view/app/task_detail_templ.go b/weed/admin/view/app/task_detail_templ.goindex 7e0657b5e5..e1211c7b68 100644--- a/weed/admin/view/app/task_detail_templ.go+++ b/weed/admin/view/app/task_detail_templ.go@@ -1,6 +1,6 @@// Code generated by templ - DO NOT EDIT.-// templ: version: v0.3.960+// templ: version: v0.3.977package app//lint:file-ignore SA4006 This context is only used if a nested component is present.@@ -1617,7 +1617,7 @@ func TaskDetail(data *maintenance.TaskDetailData) templ.Component {if templ_7745c5c3_Err != nil {return templ_7745c5c3_Err}- templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 201, "\" onclick=\"exportTaskDetail(this.getAttribute('data-task-id'))\"><i class=\"fas fa-download me-1\"></i> Export Details</button></div></div></div></div></div><!-- Task Logs Modal --><div class=\"modal fade\" id=\"taskLogsModal\" tabindex=\"-1\" aria-labelledby=\"taskLogsModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-xl\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"taskLogsModalLabel\"><i class=\"fas fa-file-text me-2\"></i>Task Logs</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><div id=\"logsLoadingSpinner\" class=\"text-center py-4\" style=\"display: none;\"><div class=\"spinner-border text-primary\" role=\"status\"><span class=\"visually-hidden\">Loading logs...</span></div><p class=\"mt-2\">Fetching logs from worker...</p></div><div id=\"logsError\" class=\"alert alert-danger\" style=\"display: none;\"><i class=\"fas fa-exclamation-triangle me-2\"></i> <span id=\"logsErrorMessage\"></span></div><div id=\"logsContent\" style=\"display: none;\"><div class=\"d-flex justify-content-between align-items-center mb-3\"><div><strong>Task:</strong> <span id=\"logsTaskId\"></span> | <strong>Worker:</strong> <span id=\"logsWorkerId\"></span> | <strong>Entries:</strong> <span id=\"logsCount\"></span></div><div class=\"btn-group\"><button type=\"button\" class=\"btn btn-sm btn-outline-primary\" onclick=\"refreshModalLogs()\"><i class=\"fas fa-sync-alt me-1\"></i>Refresh</button> <button type=\"button\" class=\"btn btn-sm btn-outline-success\" onclick=\"downloadTaskLogs()\"><i class=\"fas fa-download me-1\"></i>Download</button></div></div><div class=\"card\"><div class=\"card-header\"><div class=\"d-flex justify-content-between align-items-center\"><span>Log Entries (Last 100)</span> <small class=\"text-muted\">Newest entries first</small></div></div><div class=\"card-body p-0\"><pre id=\"logsDisplay\" class=\"bg-dark text-light p-3 mb-0\" style=\"max-height: 400px; overflow-y: auto; font-size: 0.85rem; line-height: 1.4;\"></pre></div></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Close</button></div></div></div></div><style>\n .timeline-container {\n position: relative;\n padding: 20px 0;\n }\n \n .timeline-progress {\n display: flex;\n justify-content: space-between;\n align-items: flex-start;\n position: relative;\n max-width: 100%;\n }\n \n .timeline-step {\n display: flex;\n flex-direction: column;\n align-items: center;\n flex: 1;\n position: relative;\n }\n \n .timeline-circle {\n width: 40px;\n height: 40px;\n border-radius: 50%;\n display: flex;\n align-items: center;\n justify-content: center;\n color: white;\n font-weight: bold;\n box-shadow: 0 2px 4px rgba(0,0,0,0.1);\n z-index: 2;\n position: relative;\n }\n \n .timeline-circle.completed {\n background-color: #28a745;\n border: 3px solid #1e7e34;\n }\n \n .timeline-circle.pending {\n background-color: #6c757d;\n border: 3px solid #495057;\n }\n \n .timeline-connector {\n position: absolute;\n top: 20px;\n left: 50%;\n right: -50%;\n height: 4px;\n z-index: 1;\n margin-left: 20px;\n margin-right: 20px;\n }\n \n .timeline-connector.completed {\n background-color: #28a745;\n }\n \n .timeline-connector:not(.completed) {\n background-color: #dee2e6;\n }\n \n .timeline-step:last-child .timeline-connector {\n display: none;\n }\n \n .timeline-label {\n margin-top: 15px;\n text-align: center;\n min-height: 60px;\n }\n \n .timeline-label strong {\n display: block;\n font-size: 0.9rem;\n margin-bottom: 4px;\n }\n \n .timeline-label small {\n font-size: 0.75rem;\n line-height: 1.2;\n }\n \n @media (max-width: 768px) {\n .timeline-progress {\n flex-direction: column;\n align-items: stretch;\n }\n \n .timeline-step {\n flex-direction: row;\n align-items: center;\n margin-bottom: 20px;\n }\n \n .timeline-circle {\n margin-right: 15px;\n flex-shrink: 0;\n }\n \n .timeline-connector {\n display: none;\n }\n \n .timeline-label {\n text-align: left;\n margin-top: 0;\n min-height: auto;\n }\n }\n </style><script>\n // Global variables for current logs modal\n let currentTaskId = '';\n let currentWorkerId = '';\n\n function refreshPage() {\n location.reload();\n }\n\n function showTaskLogs(taskId, workerId) {\n currentTaskId = taskId;\n currentWorkerId = workerId;\n \n // Show the modal\n const modal = new bootstrap.Modal(document.getElementById('taskLogsModal'));\n modal.show();\n \n // Load logs\n loadTaskLogs(taskId, workerId);\n }\n\n function loadTaskLogs(taskId, workerId) {\n // Show loading spinner\n document.getElementById('logsLoadingSpinner').style.display = 'block';\n document.getElementById('logsError').style.display = 'none';\n document.getElementById('logsContent').style.display = 'none';\n \n // Update modal info\n document.getElementById('logsTaskId').textContent = taskId;\n document.getElementById('logsWorkerId').textContent = workerId;\n \n // Fetch logs from the API\n fetch(`/api/maintenance/workers/${workerId}/logs?taskId=${taskId}&maxEntries=100`)\n .then(response => response.json())\n .then(data => {\n document.getElementById('logsLoadingSpinner').style.display = 'none';\n \n if (data.error) {\n showLogsError(data.error);\n return;\n }\n \n // Display logs\n displayLogs(data.logs, data.count || 0);\n })\n .catch(error => {\n document.getElementById('logsLoadingSpinner').style.display = 'none';\n showLogsError('Failed to fetch logs: ' + error.message);\n });\n }\n\n function displayLogs(logs, count) {\n document.getElementById('logsError').style.display = 'none';\n document.getElementById('logsContent').style.display = 'block';\n document.getElementById('logsCount').textContent = count;\n \n const logsDisplay = document.getElementById('logsDisplay');\n \n if (!logs || logs.length === 0) {\n logsDisplay.textContent = 'No logs found for this task.';\n return;\n }\n \n // Format and display logs with structured fields\n let logText = '';\n logs.forEach(entry => {\n const timestamp = entry.timestamp ? new Date(entry.timestamp * 1000).toISOString() : 'N/A';\n const level = entry.level || 'INFO';\n const message = entry.message || '';\n \n logText += `[${timestamp}] ${level}: ${message}`;\n \n // Add structured fields if they exist\n if (entry.fields && Object.keys(entry.fields).length > 0) {\n const fieldsStr = Object.entries(entry.fields)\n .map(([key, value]) => `${key}=${value}`)\n .join(', ');\n logText += ` | ${fieldsStr}`;\n }\n \n // Add progress if available\n if (entry.progress !== undefined && entry.progress !== null) {\n logText += ` | progress=${entry.progress}%`;\n }\n \n // Add status if available\n if (entry.status) {\n logText += ` | status=${entry.status}`;\n }\n \n logText += '\\n';\n });\n \n logsDisplay.textContent = logText;\n \n // Scroll to top\n logsDisplay.scrollTop = 0;\n }\n\n function showLogsError(errorMessage) {\n document.getElementById('logsError').style.display = 'block';\n document.getElementById('logsContent').style.display = 'none';\n document.getElementById('logsErrorMessage').textContent = errorMessage;\n }\n\n function refreshModalLogs() {\n if (currentTaskId && currentWorkerId) {\n loadTaskLogs(currentTaskId, currentWorkerId);\n }\n }\n\n function downloadTaskLogs() {\n if (!currentTaskId || !currentWorkerId) {\n showAlert('No task logs to download', 'info');\n return;\n }\n \n // Download all logs (without maxEntries limit)\n const downloadUrl = `/api/maintenance/workers/${currentWorkerId}/logs?taskId=${currentTaskId}&maxEntries=0`;\n \n fetch(downloadUrl)\n .then(response => response.json())\n .then(data => {\n if (data.error) {\n showAlert('Error downloading logs: ' + data.error, 'error');\n return;\n }\n \n // Convert logs to text format with structured fields\n let logContent = '';\n if (data.logs && data.logs.length > 0) {\n data.logs.forEach(entry => {\n const timestamp = entry.timestamp ? new Date(entry.timestamp * 1000).toISOString() : 'N/A';\n const level = entry.level || 'INFO';\n const message = entry.message || '';\n \n logContent += `[${timestamp}] ${level}: ${message}`;\n \n // Add structured fields if they exist\n if (entry.fields && Object.keys(entry.fields).length > 0) {\n const fieldsStr = Object.entries(entry.fields)\n .map(([key, value]) => `${key}=${value}`)\n .join(', ');\n logContent += ` | ${fieldsStr}`;\n }\n \n // Add progress if available\n if (entry.progress !== undefined && entry.progress !== null) {\n logContent += ` | progress=${entry.progress}%`;\n }\n \n // Add status if available\n if (entry.status) {\n logContent += ` | status=${entry.status}`;\n }\n \n logContent += '\\n';\n });\n } else {\n logContent = 'No logs found for this task.';\n }\n \n // Create and download file\n const blob = new Blob([logContent], { type: 'text/plain' });\n const url = URL.createObjectURL(blob);\n const link = document.createElement('a');\n link.href = url;\n link.download = `task-${currentTaskId}-logs.txt`;\n link.click();\n URL.revokeObjectURL(url);\n })\n .catch(error => {\n showAlert('Error downloading logs: ' + error.message, 'error');\n });\n }\n\n function cancelTask(taskId) {\n showConfirm('Are you sure you want to cancel this task?', function() {\n fetch(`/api/maintenance/tasks/${taskId}/cancel`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n })\n .then(response => response.json())\n .then(data => {\n if (data.success) {\n showAlert('Task cancelled successfully', 'success');\n location.reload();\n } else {\n showAlert('Error cancelling task: ' + data.error, 'error');\n }\n })\n .catch(error => {\n console.error('Error:', error);\n showAlert('Error cancelling task', 'error');\n });\n });\n }\n\n function refreshTaskLogs(taskId) {\n fetch(`/api/maintenance/tasks/${taskId}/detail`)\n .then(response => response.json())\n .then(data => {\n location.reload();\n })\n .catch(error => {\n console.error('Error:', error);\n showAlert('Error refreshing logs', 'error');\n });\n }\n\n function exportTaskDetail(taskId) {\n fetch(`/api/maintenance/tasks/${taskId}/detail`)\n .then(response => response.json())\n .then(data => {\n const dataStr = JSON.stringify(data, null, 2);\n const dataBlob = new Blob([dataStr], {type: 'application/json'});\n const url = URL.createObjectURL(dataBlob);\n const link = document.createElement('a');\n link.href = url;\n link.download = `task-${taskId}-detail.json`;\n link.click();\n URL.revokeObjectURL(url);\n })\n .catch(error => {\n console.error('Error:', error);\n showAlert('Error exporting task detail', 'error');\n });\n }\n\n // Auto-refresh every 30 seconds for active tasks\n if ('{string(data.Task.Status)}' === 'in_progress') {\n setInterval(refreshPage, 30000);\n }\n </script>")+ templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 201, "\" onclick=\"exportTaskDetail(this.getAttribute('data-task-id'))\"><i class=\"fas fa-download me-1\"></i> Export Details</button></div></div></div></div></div><!-- Task Logs Modal --><div class=\"modal fade\" id=\"taskLogsModal\" tabindex=\"-1\" aria-labelledby=\"taskLogsModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-xl\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"taskLogsModalLabel\"><i class=\"fas fa-file-text me-2\"></i>Task Logs</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><div id=\"logsLoadingSpinner\" class=\"text-center py-4\" style=\"display: none;\"><div class=\"spinner-border text-primary\" role=\"status\"><span class=\"visually-hidden\">Loading logs...</span></div><p class=\"mt-2\">Fetching logs from worker...</p></div><div id=\"logsError\" class=\"alert alert-danger\" style=\"display: none;\"><i class=\"fas fa-exclamation-triangle me-2\"></i> <span id=\"logsErrorMessage\"></span></div><div id=\"logsContent\" style=\"display: none;\"><div class=\"d-flex justify-content-between align-items-center mb-3\"><div><strong>Task:</strong> <span id=\"logsTaskId\"></span> | <strong>Worker:</strong> <span id=\"logsWorkerId\"></span> | <strong>Entries:</strong> <span id=\"logsCount\"></span></div><div class=\"btn-group\"><button type=\"button\" class=\"btn btn-sm btn-outline-primary\" onclick=\"refreshModalLogs()\"><i class=\"fas fa-sync-alt me-1\"></i>Refresh</button> <button type=\"button\" class=\"btn btn-sm btn-outline-success\" onclick=\"downloadTaskLogs()\"><i class=\"fas fa-download me-1\"></i>Download</button></div></div><div class=\"card\"><div class=\"card-header\"><div class=\"d-flex justify-content-between align-items-center\"><span>Log Entries (Last 100)</span> <small class=\"text-muted\">Newest entries first</small></div></div><div class=\"card-body p-0\"><pre id=\"logsDisplay\" class=\"bg-dark text-light p-3 mb-0\" style=\"max-height: 400px; overflow-y: auto; font-size: 0.85rem; line-height: 1.4;\"></pre></div></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Close</button></div></div></div></div><style>\n .timeline-container {\n position: relative;\n padding: 20px 0;\n }\n \n .timeline-progress {\n display: flex;\n justify-content: space-between;\n align-items: flex-start;\n position: relative;\n max-width: 100%;\n }\n \n .timeline-step {\n display: flex;\n flex-direction: column;\n align-items: center;\n flex: 1;\n position: relative;\n }\n \n .timeline-circle {\n width: 40px;\n height: 40px;\n border-radius: 50%;\n display: flex;\n align-items: center;\n justify-content: center;\n color: white;\n font-weight: bold;\n box-shadow: 0 2px 4px rgba(0,0,0,0.1);\n z-index: 2;\n position: relative;\n }\n \n .timeline-circle.completed {\n background-color: #28a745;\n border: 3px solid #1e7e34;\n }\n \n .timeline-circle.pending {\n background-color: #6c757d;\n border: 3px solid #495057;\n }\n \n .timeline-connector {\n position: absolute;\n top: 20px;\n left: 50%;\n right: -50%;\n height: 4px;\n z-index: 1;\n margin-left: 20px;\n margin-right: 20px;\n }\n \n .timeline-connector.completed {\n background-color: #28a745;\n }\n \n .timeline-connector:not(.completed) {\n background-color: #dee2e6;\n }\n \n .timeline-step:last-child .timeline-connector {\n display: none;\n }\n \n .timeline-label {\n margin-top: 15px;\n text-align: center;\n min-height: 60px;\n }\n \n .timeline-label strong {\n display: block;\n font-size: 0.9rem;\n margin-bottom: 4px;\n }\n \n .timeline-label small {\n font-size: 0.75rem;\n line-height: 1.2;\n }\n \n @media (max-width: 768px) {\n .timeline-progress {\n flex-direction: column;\n align-items: stretch;\n }\n \n .timeline-step {\n flex-direction: row;\n align-items: center;\n margin-bottom: 20px;\n }\n \n .timeline-circle {\n margin-right: 15px;\n flex-shrink: 0;\n }\n \n .timeline-connector {\n display: none;\n }\n \n .timeline-label {\n text-align: left;\n margin-top: 0;\n min-height: auto;\n }\n }\n </style><script>\n // Global variables for current logs modal\n let currentTaskId = '';\n let currentWorkerId = '';\n\n function refreshPage() {\n location.reload();\n }\n\n function showTaskLogs(taskId, workerId) {\n currentTaskId = taskId;\n currentWorkerId = workerId;\n \n // Show the modal\n const modal = new bootstrap.Modal(document.getElementById('taskLogsModal'));\n modal.show();\n \n // Load logs\n loadTaskLogs(taskId, workerId);\n }\n\n function loadTaskLogs(taskId, workerId) {\n // Show loading spinner\n document.getElementById('logsLoadingSpinner').style.display = 'block';\n document.getElementById('logsError').style.display = 'none';\n document.getElementById('logsContent').style.display = 'none';\n \n // Update modal info\n document.getElementById('logsTaskId').textContent = taskId;\n document.getElementById('logsWorkerId').textContent = workerId;\n \n // Fetch logs from the API\n fetch(`/api/maintenance/workers/${workerId}/logs?taskId=${taskId}&maxEntries=100`)\n .then(response => response.json())\n .then(data => {\n document.getElementById('logsLoadingSpinner').style.display = 'none';\n \n if (data.error) {\n showLogsError(data.error);\n return;\n }\n \n // Display logs\n displayLogs(data.logs, data.count || 0);\n })\n .catch(error => {\n document.getElementById('logsLoadingSpinner').style.display = 'none';\n showLogsError('Failed to fetch logs: ' + error.message);\n });\n }\n\n function displayLogs(logs, count) {\n document.getElementById('logsError').style.display = 'none';\n document.getElementById('logsContent').style.display = 'block';\n document.getElementById('logsCount').textContent = count;\n \n const logsDisplay = document.getElementById('logsDisplay');\n \n if (!logs || logs.length === 0) {\n logsDisplay.textContent = 'No logs found for this task.';\n return;\n }\n \n \n // Format and display logs with structured fields\n let logText = '';\n \n // Helper function to format timestamps robustly\n function formatTimestamp(timestamp) {\n if (!timestamp) {\n return 'N/A';\n }\n \n let date;\n \n // Check if timestamp is a numeric string (e.g., \"1738652668\")\n if (typeof timestamp === 'string' && /^\\d+$/.test(timestamp)) {\n const numericTimestamp = parseInt(timestamp, 10);\n // Treat values > 10^10 as milliseconds, otherwise as seconds\n date = numericTimestamp > 10000000000 \n ? new Date(numericTimestamp) \n : new Date(numericTimestamp * 1000);\n } else if (typeof timestamp === 'string') {\n // ISO date string\n date = new Date(timestamp);\n } else if (typeof timestamp === 'number') {\n // Numeric timestamp (seconds or milliseconds)\n date = timestamp > 10000000000 \n ? new Date(timestamp) \n : new Date(timestamp * 1000);\n } else {\n return 'N/A';\n }\n \n // Validate the date\n if (isNaN(date.getTime())) {\n return 'N/A';\n }\n \n return date.toISOString();\n }\n \n logs.forEach(entry => {\n const timestamp = formatTimestamp(entry.timestamp);\n\n const level = entry.level || 'INFO';\n const message = entry.message || '';\n \n logText += `[${timestamp}] ${level}: ${message}`;\n \n // Add structured fields if they exist\n if (entry.fields && Object.keys(entry.fields).length > 0) {\n const fieldsStr = Object.entries(entry.fields)\n .map(([key, value]) => `${key}=${value}`)\n .join(', ');\n logText += ` | ${fieldsStr}`;\n }\n \n // Add progress if available\n if (entry.progress !== undefined && entry.progress !== null) {\n logText += ` | progress=${entry.progress}%`;\n }\n \n // Add status if available\n if (entry.status) {\n logText += ` | status=${entry.status}`;\n }\n \n logText += '\\n';\n });\n \n logsDisplay.textContent = logText;\n \n // Scroll to top\n logsDisplay.scrollTop = 0;\n }\n\n function showLogsError(errorMessage) {\n document.getElementById('logsError').style.display = 'block';\n document.getElementById('logsContent').style.display = 'none';\n document.getElementById('logsErrorMessage').textContent = errorMessage;\n }\n\n function refreshModalLogs() {\n if (currentTaskId && currentWorkerId) {\n loadTaskLogs(currentTaskId, currentWorkerId);\n }\n }\n\n function downloadTaskLogs() {\n if (!currentTaskId || !currentWorkerId) {\n showAlert('No task logs to download', 'info');\n return;\n }\n \n // Download all logs (without maxEntries limit)\n const downloadUrl = `/api/maintenance/workers/${currentWorkerId}/logs?taskId=${currentTaskId}&maxEntries=0`;\n \n fetch(downloadUrl)\n .then(response => response.json())\n .then(data => {\n if (data.error) {\n showAlert('Error downloading logs: ' + data.error, 'error');\n return;\n }\n \n // Convert logs to text format with structured fields\n let logContent = '';\n if (data.logs && data.logs.length > 0) {\n data.logs.forEach(entry => {\n let timestamp;\n if (typeof entry.timestamp === 'string') {\n timestamp = new Date(entry.timestamp).toISOString();\n } else {\n timestamp = entry.timestamp ? new Date(entry.timestamp * 1000).toISOString() : 'N/A';\n }\n const level = entry.level || 'INFO';\n const message = entry.message || '';\n \n logContent += `[${timestamp}] ${level}: ${message}`;\n \n // Add structured fields if they exist\n if (entry.fields && Object.keys(entry.fields).length > 0) {\n const fieldsStr = Object.entries(entry.fields)\n .map(([key, value]) => `${key}=${value}`)\n .join(', ');\n logContent += ` | ${fieldsStr}`;\n }\n \n // Add progress if available\n if (entry.progress !== undefined && entry.progress !== null) {\n logContent += ` | progress=${entry.progress}%`;\n }\n \n // Add status if available\n if (entry.status) {\n logContent += ` | status=${entry.status}`;\n }\n \n logContent += '\\n';\n });\n } else {\n logContent = 'No logs found for this task.';\n }\n \n // Create and download file\n const blob = new Blob([logContent], { type: 'text/plain' });\n const url = URL.createObjectURL(blob);\n const link = document.createElement('a');\n link.href = url;\n link.download = `task-${currentTaskId}-logs.txt`;\n link.click();\n URL.revokeObjectURL(url);\n })\n .catch(error => {\n showAlert('Error downloading logs: ' + error.message, 'error');\n });\n }\n\n function cancelTask(taskId) {\n showConfirm('Are you sure you want to cancel this task?', function() {\n fetch(`/api/maintenance/tasks/${taskId}/cancel`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n })\n .then(response => response.json())\n .then(data => {\n if (data.success) {\n showAlert('Task cancelled successfully', 'success');\n location.reload();\n } else {\n showAlert('Error cancelling task: ' + data.error, 'error');\n }\n })\n .catch(error => {\n console.error('Error:', error);\n showAlert('Error cancelling task', 'error');\n });\n });\n }\n\n function refreshTaskLogs(taskId) {\n fetch(`/api/maintenance/tasks/${taskId}/detail`)\n .then(response => response.json())\n .then(data => {\n location.reload();\n })\n .catch(error => {\n console.error('Error:', error);\n showAlert('Error refreshing logs', 'error');\n });\n }\n\n function exportTaskDetail(taskId) {\n fetch(`/api/maintenance/tasks/${taskId}/detail`)\n .then(response => response.json())\n .then(data => {\n const dataStr = JSON.stringify(data, null, 2);\n const dataBlob = new Blob([dataStr], {type: 'application/json'});\n const url = URL.createObjectURL(dataBlob);\n const link = document.createElement('a');\n link.href = url;\n link.download = `task-${taskId}-detail.json`;\n link.click();\n URL.revokeObjectURL(url);\n })\n .catch(error => {\n console.error('Error:', error);\n showAlert('Error exporting task detail', 'error');\n });\n }\n\n // Auto-refresh every 30 seconds for active tasks\n if ('{string(data.Task.Status)}' === 'in_progress') {\n setInterval(refreshPage, 30000);\n }\n </script>")if templ_7745c5c3_Err != nil {return templ_7745c5c3_Err}diff --git a/weed/admin/view/app/topic_details_templ.go b/weed/admin/view/app/topic_details_templ.goindex a3e48f581a..f7f3501af4 100644--- a/weed/admin/view/app/topic_details_templ.go+++ b/weed/admin/view/app/topic_details_templ.go@@ -1,6 +1,6 @@// Code generated by templ - DO NOT EDIT.-// templ: version: v0.3.960+// templ: version: v0.3.977package app//lint:file-ignore SA4006 This context is only used if a nested component is present.diff --git a/weed/admin/view/app/topics_templ.go b/weed/admin/view/app/topics_templ.goindex 6920a2e539..4ada9b3d30 100644--- a/weed/admin/view/app/topics_templ.go+++ b/weed/admin/view/app/topics_templ.go@@ -1,6 +1,6 @@// Code generated by templ - DO NOT EDIT.-// templ: version: v0.3.960+// templ: version: v0.3.977package app//lint:file-ignore SA4006 This context is only used if a nested component is present.diff --git a/weed/admin/view/app/volume_details_templ.go b/weed/admin/view/app/volume_details_templ.goindex 8091fad7bb..732fcdea5c 100644--- a/weed/admin/view/app/volume_details_templ.go+++ b/weed/admin/view/app/volume_details_templ.go@@ -1,6 +1,6 @@// Code generated by templ - DO NOT EDIT.-// templ: version: v0.3.960+// templ: version: v0.3.977package app//lint:file-ignore SA4006 This context is only used if a nested component is present.diff --git a/weed/admin/view/components/config_sections_templ.go b/weed/admin/view/components/config_sections_templ.goindex ca428dccdc..638542e2c3 100644--- a/weed/admin/view/components/config_sections_templ.go+++ b/weed/admin/view/components/config_sections_templ.go@@ -1,6 +1,6 @@// Code generated by templ - DO NOT EDIT.-// templ: version: v0.3.960+// templ: version: v0.3.977package components//lint:file-ignore SA4006 This context is only used if a nested component is present.diff --git a/weed/admin/view/components/form_fields_templ.go b/weed/admin/view/components/form_fields_templ.goindex a78cf8e95d..26e146f72b 100644--- a/weed/admin/view/components/form_fields_templ.go+++ b/weed/admin/view/components/form_fields_templ.go@@ -1,6 +1,6 @@// Code generated by templ - DO NOT EDIT.-// templ: version: v0.3.960+// templ: version: v0.3.977package components//lint:file-ignore SA4006 This context is only used if a nested component is present.diff --git a/weed/admin/view/layout/layout_templ.go b/weed/admin/view/layout/layout_templ.goindex a9d66bf47c..30767a979c 100644--- a/weed/admin/view/layout/layout_templ.go+++ b/weed/admin/view/layout/layout_templ.go@@ -1,6 +1,6 @@// Code generated by templ - DO NOT EDIT.-// templ: version: v0.3.960+// templ: version: v0.3.977package layout//lint:file-ignore SA4006 This context is only used if a nested component is present.diff --git a/weed/command/admin.go b/weed/command/admin.goindex 67ed4e4ab8..4aa8e35b3e 100644--- a/weed/command/admin.go+++ b/weed/command/admin.go@@ -230,7 +230,20 @@ func startAdminServer(ctx context.Context, options AdminOptions, enableUI bool,// Create routerr := gin.New()- r.Use(gin.Logger(), gin.Recovery())+ r.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {+ if param.StatusCode == 200 {+ return ""+ }+ return fmt.Sprintf("[GIN] %v | %3d | %13v | %15s | %-7s %s\n%s",+ param.TimeStamp.Format("2006/01/02 - 15:04:05"),+ param.StatusCode,+ param.Latency,+ param.ClientIP,+ param.Method,+ param.Path,+ param.ErrorMessage,+ )+ }), gin.Recovery())// Create data directory first if specified (needed for session key storage)var dataDir stringdiff --git a/weed/server/master_grpc_server_assign.go b/weed/server/master_grpc_server_assign.goindex c05a2cb7d7..081d79cc19 100644--- a/weed/server/master_grpc_server_assign.go+++ b/weed/server/master_grpc_server_assign.go@@ -79,6 +79,16 @@ func (ms *MasterServer) Assign(ctx context.Context, req *master_pb.AssignRequest}vl := ms.Topo.GetVolumeLayout(option.Collection, option.ReplicaPlacement, option.Ttl, option.DiskType)+ if req.DiskType == "" {+ if writable, _ := vl.GetWritableVolumeCount(); writable == 0 {+ if hddVl := ms.Topo.GetVolumeLayout(option.Collection, option.ReplicaPlacement, option.Ttl, types.ToDiskType(types.HddType)); hddVl != nil {+ if writable, _ := hddVl.GetWritableVolumeCount(); writable > 0 {+ option.DiskType = types.ToDiskType(types.HddType)+ vl = hddVl+ }+ }+ }+ }vl.SetLastGrowCount(req.WritableVolumeCount)var (diff --git a/weed/worker/tasks/erasure_coding/detection.go b/weed/worker/tasks/erasure_coding/detection.goindex 88f8a017a4..2bc61469cf 100644--- a/weed/worker/tasks/erasure_coding/detection.go+++ b/weed/worker/tasks/erasure_coding/detection.go@@ -241,13 +241,15 @@ func Detection(metrics []*types.VolumeHealthMetrics, clusterInfo *types.ClusterIresults = append(results, result)} else {// Count debug reasons+ if metric.Age < quietThreshold {+ skippedQuietTime+++ }+ if metric.FullnessRatio < ecConfig.FullnessRatio {+ skippedFullness+++ }+if debugCount < 5 { // Limit to avoid spam- if metric.Age < quietThreshold {- skippedQuietTime++- }- if metric.FullnessRatio < ecConfig.FullnessRatio {- skippedFullness++- }+ // Logic moved outside}debugCount++}@@ -256,7 +258,7 @@ func Detection(metrics []*types.VolumeHealthMetrics, clusterInfo *types.ClusterI// Log debug summary if no tasks were createdif len(results) == 0 && len(metrics) > 0 {totalVolumes := len(metrics)- glog.V(1).Infof("EC detection: No tasks created for %d volumes (skipped: %d already EC, %d too small, %d filtered, %d not quiet, %d not full)",+ glog.Infof("EC detection: No tasks created for %d volumes (skipped: %d already EC, %d too small, %d filtered, %d not quiet, %d not full)",totalVolumes, skippedAlreadyEC, skippedTooSmall, skippedCollectionFilter, skippedQuietTime, skippedFullness)// Show details for first few volumesdiff --git a/weed/worker/tasks/task_logger.go b/weed/worker/tasks/task_logger.goindex cc65c6d7b5..96f1846377 100644--- a/weed/worker/tasks/task_logger.go+++ b/weed/worker/tasks/task_logger.go@@ -30,6 +30,7 @@ type TaskLogger interface {LogWithFields(level string, message string, fields map[string]interface{})// Lifecycle+ Sync() errorClose() errorGetLogDir() string}@@ -230,6 +231,17 @@ func (l *FileTaskLogger) LogWithFields(level string, message string, fields map[l.writeLogEntry(entry)}+// Sync flushes buffered data to disk+func (l *FileTaskLogger) Sync() error {+ l.mutex.Lock()+ defer l.mutex.Unlock()++ if l.logFile != nil {+ return l.logFile.Sync()+ }+ return nil+}+// Close closes the logger and finalizes metadatafunc (l *FileTaskLogger) Close() error {l.Info("Task logger closed for %s", l.taskID)@@ -423,7 +435,10 @@ func ReadTaskLogs(logDir string) ([]TaskLogEntry, error) {if err == io.EOF {break}- return nil, fmt.Errorf("failed to decode log entry: %w", err)+ // If we fail to decode an entry, it might be a partial write at the end of the file+ // Return what we have so far instead of failing the entire request+ glog.V(1).Infof("Failed to decode log entry in %s: %v (returning %d partial logs)", logPath, err, len(entries))+ break}entries = append(entries, entry)}diff --git a/weed/worker/types/typed_task_interface.go b/weed/worker/types/typed_task_interface.goindex d04cea3d3d..39eaa22863 100644--- a/weed/worker/types/typed_task_interface.go+++ b/weed/worker/types/typed_task_interface.go@@ -19,6 +19,7 @@ type TaskLogger interface {Error(message string, args ...interface{})Debug(message string, args ...interface{})LogWithFields(level string, message string, fields map[string]interface{})+ Sync() errorClose() error}diff --git a/weed/worker/worker.go b/weed/worker/worker.goindex e44234f33a..0f45d9dc7b 100644--- a/weed/worker/worker.go+++ b/weed/worker/worker.go@@ -707,6 +707,9 @@ func (w *Worker) executeTask(task *types.TaskInput) {err = taskInstance.Execute(ctx, task.TypedParams)// Report completion+ if fileLogger != nil {+ fileLogger.Sync()+ }if err != nil {w.completeTask(task.ID, false, err.Error())w.cmds <- workerCommand{@@ -718,14 +721,15 @@ func (w *Worker) executeTask(task *types.TaskInput) {fileLogger.Error("Task %s failed: %v", task.ID, err)}} else {+ if fileLogger != nil {+ fileLogger.Info("Task %s completed successfully", task.ID)+ fileLogger.Sync()+ }w.completeTask(task.ID, true, "")w.cmds <- workerCommand{action: ActionIncTaskComplete,}glog.Infof("Worker %s completed task %s successfully", w.id, task.ID)- if fileLogger != nil {- fileLogger.Info("Task %s completed successfully", task.ID)- }}}