1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
|
//go:build !no_workceptor
// +build !no_workceptor
package workceptor
import (
"context"
"encoding/json"
"fmt"
"io"
"os"
"path"
"strconv"
"sync"
"time"
"github.com/fsnotify/fsnotify"
"github.com/rogpeppe/go-internal/lockedfile"
)
// Work sleep constants.
const (
SuccessWorkSleep = 1 * time.Second // Normal time to wait between checks
MaxWorkSleep = 1 * time.Minute // Max time to ever wait between checks
)
// Work state constants.
const (
WorkStatePending = 0
WorkStateRunning = 1
WorkStateSucceeded = 2
WorkStateFailed = 3
WorkStateCanceled = 4
)
// WatcherWrapper is wrapping the fsnofity Watcher struct and exposing the Event chan within.
type WatcherWrapper interface {
Add(name string) error
Remove(path string) error
Close() error
ErrorChannel() chan error
EventChannel() chan fsnotify.Event
}
type RealWatcher struct {
watcher *fsnotify.Watcher
}
func (rw *RealWatcher) Add(name string) error {
return rw.watcher.Add(name)
}
func (rw *RealWatcher) Remove(path string) error {
return rw.watcher.Remove(path)
}
func (rw *RealWatcher) Close() error {
return rw.watcher.Close()
}
func (rw *RealWatcher) ErrorChannel() chan error {
return rw.watcher.Errors
}
func (rw *RealWatcher) EventChannel() chan fsnotify.Event {
return rw.watcher.Events
}
// IsComplete returns true if a given WorkState indicates the job is finished.
func IsComplete(workState int) bool {
return workState == WorkStateSucceeded || workState == WorkStateFailed
}
// WorkStateToString returns a string representation of a WorkState.
func WorkStateToString(workState int) string {
switch workState {
case WorkStatePending:
return "Pending"
case WorkStateRunning:
return "Running"
case WorkStateSucceeded:
return "Succeeded"
case WorkStateFailed:
return "Failed"
case WorkStateCanceled:
return "Canceled"
default:
return "Unknown: " + strconv.Itoa(workState)
}
}
// ErrPending is returned when an operation hasn't succeeded or failed yet.
var ErrPending = fmt.Errorf("operation pending")
// IsPending returns true if the error is an ErrPending.
func IsPending(err error) bool {
return err == ErrPending
}
// BaseWorkUnit includes data common to all work units, and partially implements the WorkUnit interface.
type BaseWorkUnit struct {
w *Workceptor
status StatusFileData
unitID string
unitDir string
statusFileName string
stdoutFileName string
statusLock *sync.RWMutex
lastUpdateError error
lastUpdateErrorLock *sync.RWMutex
ctx context.Context
cancel context.CancelFunc
fs FileSystemer
watcher WatcherWrapper
}
// Init initializes the basic work unit data, in memory only.
func (bwu *BaseWorkUnit) Init(w *Workceptor, unitID string, workType string, fs FileSystemer, watcher WatcherWrapper) {
bwu.w = w
bwu.status.State = WorkStatePending
bwu.status.Detail = "Unit Created"
bwu.status.StdoutSize = 0
bwu.status.WorkType = workType
bwu.unitID = unitID
bwu.unitDir = path.Join(w.dataDir, unitID)
bwu.statusFileName = path.Join(bwu.unitDir, "status")
bwu.stdoutFileName = path.Join(bwu.unitDir, "stdout")
bwu.statusLock = &sync.RWMutex{}
bwu.lastUpdateErrorLock = &sync.RWMutex{}
bwu.ctx, bwu.cancel = context.WithCancel(w.ctx)
bwu.fs = fs
if watcher != nil {
bwu.watcher = watcher
} else {
watcher, err := fsnotify.NewWatcher()
if err == nil {
bwu.watcher = &RealWatcher{watcher: watcher}
} else {
bwu.w.nc.GetLogger().Info("fsnotify.NewWatcher returned %s", err)
bwu.watcher = nil
}
}
}
// Error logs message with unitID prepended.
func (bwu *BaseWorkUnit) Error(format string, v ...interface{}) {
format = fmt.Sprintf("[%s] %s", bwu.unitID, format)
bwu.w.nc.GetLogger().Error(format, v...)
}
// Warning logs message with unitID prepended.
func (bwu *BaseWorkUnit) Warning(format string, v ...interface{}) {
format = fmt.Sprintf("[%s] %s", bwu.unitID, format)
bwu.w.nc.GetLogger().Warning(format, v...)
}
// Info logs message with unitID prepended.
func (bwu *BaseWorkUnit) Info(format string, v ...interface{}) {
format = fmt.Sprintf("[%s] %s", bwu.unitID, format)
bwu.w.nc.GetLogger().Info(format, v...)
}
// Debug logs message with unitID prepended.
func (bwu *BaseWorkUnit) Debug(format string, v ...interface{}) {
format = fmt.Sprintf("[%s] %s", bwu.unitID, format)
bwu.w.nc.GetLogger().Debug(format, v...)
}
// SetFromParams sets the in-memory state from parameters.
func (bwu *BaseWorkUnit) SetFromParams(_ map[string]string) error {
return nil
}
// UnitDir returns the unit directory of this work unit.
func (bwu *BaseWorkUnit) UnitDir() string {
return bwu.unitDir
}
// ID returns the unique identifier of this work unit.
func (bwu *BaseWorkUnit) ID() string {
return bwu.unitID
}
// StatusFileName returns the full path to the status file in the unit dir.
func (bwu *BaseWorkUnit) StatusFileName() string {
return bwu.statusFileName
}
// StdoutFileName returns the full path to the stdout file in the unit dir.
func (bwu *BaseWorkUnit) StdoutFileName() string {
return bwu.stdoutFileName
}
// lockStatusFile gains a lock on the status file.
func (sfd *StatusFileData) lockStatusFile(filename string) (*lockedfile.File, error) {
lockFileName := filename + ".lock"
lockFile, err := lockedfile.OpenFile(lockFileName, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600)
if err != nil {
return nil, err
}
return lockFile, nil
}
// unlockStatusFile releases the lock on the status file.
func (sfd *StatusFileData) unlockStatusFile(filename string, lockFile *lockedfile.File) {
if err := lockFile.Close(); err != nil {
MainInstance.nc.GetLogger().Error("Error closing %s.lock: %s", filename, err)
}
}
// saveToFile saves status to an already-open file.
func (sfd *StatusFileData) saveToFile(file io.Writer) error {
jsonBytes, err := json.Marshal(sfd)
if err != nil {
return err
}
jsonBytes = append(jsonBytes, '\n')
_, err = file.Write(jsonBytes)
return err
}
// Save saves status to a file.
func (sfd *StatusFileData) Save(filename string) error {
lockFile, err := sfd.lockStatusFile(filename)
if err != nil {
return err
}
defer sfd.unlockStatusFile(filename, lockFile)
file, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600)
if err != nil {
return err
}
err = sfd.saveToFile(file)
if err != nil {
serr := file.Close()
if serr != nil {
MainInstance.nc.GetLogger().Error("Error closing %s: %s", filename, serr)
}
return err
}
return file.Close()
}
// Save saves status to a file.
func (bwu *BaseWorkUnit) Save() error {
bwu.statusLock.RLock()
defer bwu.statusLock.RUnlock()
return bwu.status.Save(bwu.statusFileName)
}
// loadFromFile loads status from an already open file.
func (sfd *StatusFileData) loadFromFile(file io.Reader) error {
jsonBytes, err := io.ReadAll(file)
if err != nil {
return err
}
return json.Unmarshal(jsonBytes, sfd)
}
// Load loads status from a file.
func (sfd *StatusFileData) Load(filename string) error {
lockFile, err := sfd.lockStatusFile(filename)
if err != nil {
return err
}
defer sfd.unlockStatusFile(filename, lockFile)
file, err := os.Open(filename)
if err != nil {
return err
}
err = sfd.loadFromFile(file)
if err != nil {
lerr := file.Close()
if lerr != nil {
MainInstance.nc.GetLogger().Error("Error closing %s: %s", filename, lerr)
}
return err
}
return file.Close()
}
// Load loads status from a file.
func (bwu *BaseWorkUnit) Load() error {
bwu.statusLock.Lock()
defer bwu.statusLock.Unlock()
return bwu.status.Load(bwu.statusFileName)
}
// UpdateFullStatus atomically updates the status metadata file. Changes should be made in the callback function.
// Errors are logged rather than returned.
func (sfd *StatusFileData) UpdateFullStatus(filename string, statusFunc func(*StatusFileData)) error {
lockFile, err := sfd.lockStatusFile(filename)
if err != nil {
return err
}
defer sfd.unlockStatusFile(filename, lockFile)
file, err := os.OpenFile(filename, os.O_CREATE|os.O_RDWR, 0o600)
if err != nil {
return err
}
defer func() {
err := file.Close()
if err != nil {
MainInstance.nc.GetLogger().Error("Error closing %s: %s", filename, err)
}
}()
size, err := file.Seek(0, 2)
if err != nil {
return err
}
_, err = file.Seek(0, 0)
if err != nil {
return err
}
if size > 0 {
err = sfd.loadFromFile(file)
if err != nil {
return err
}
}
statusFunc(sfd)
_, err = file.Seek(0, 0)
if err != nil {
return err
}
err = file.Truncate(0)
if err != nil {
return err
}
err = sfd.saveToFile(file)
if err != nil {
return err
}
return nil
}
// UpdateFullStatus atomically updates the whole status record. Changes should be made in the callback function.
// Errors are logged rather than returned.
func (bwu *BaseWorkUnit) UpdateFullStatus(statusFunc func(*StatusFileData)) {
bwu.statusLock.Lock()
defer bwu.statusLock.Unlock()
err := bwu.status.UpdateFullStatus(bwu.statusFileName, statusFunc)
bwu.lastUpdateErrorLock.Lock()
defer bwu.lastUpdateErrorLock.Unlock()
bwu.lastUpdateError = err
if err != nil {
bwu.w.nc.GetLogger().Error("Error updating status file %s: %s.", bwu.statusFileName, err)
}
}
// UpdateBasicStatus atomically updates key fields in the status metadata file. Errors are logged rather than returned.
// Passing -1 as stdoutSize leaves it unchanged.
func (sfd *StatusFileData) UpdateBasicStatus(filename string, state int, detail string, stdoutSize int64) error {
return sfd.UpdateFullStatus(filename, func(status *StatusFileData) {
status.State = state
status.Detail = detail
if stdoutSize >= 0 {
status.StdoutSize = stdoutSize
}
})
}
// UpdateBasicStatus atomically updates key fields in the status metadata file. Errors are logged rather than returned.
// Passing -1 as stdoutSize leaves it unchanged.
func (bwu *BaseWorkUnit) UpdateBasicStatus(state int, detail string, stdoutSize int64) {
bwu.statusLock.Lock()
defer bwu.statusLock.Unlock()
err := bwu.status.UpdateBasicStatus(bwu.statusFileName, state, detail, stdoutSize)
bwu.lastUpdateErrorLock.Lock()
defer bwu.lastUpdateErrorLock.Unlock()
bwu.lastUpdateError = err
if err != nil {
bwu.w.nc.GetLogger().Error("Error updating status file %s: %s.", bwu.statusFileName, err)
}
}
// LastUpdateError returns the last error (including nil) resulting from an UpdateBasicStatus or UpdateFullStatus.
func (bwu *BaseWorkUnit) LastUpdateError() error {
bwu.lastUpdateErrorLock.RLock()
defer bwu.lastUpdateErrorLock.RUnlock()
return bwu.lastUpdateError
}
// MonitorLocalStatus watches a unit dir and keeps the in-memory workUnit up to date with status changes.
func (bwu *BaseWorkUnit) MonitorLocalStatus() {
statusFile := path.Join(bwu.UnitDir(), "status")
var watcherEvents chan fsnotify.Event
watcherEvents = make(chan fsnotify.Event)
var watcherErrors chan error
watcherErrors = make(chan error)
if bwu.watcher != nil {
bwu.statusLock.Lock()
err := bwu.watcher.Add(statusFile)
bwu.statusLock.Unlock()
if err == nil {
defer func() {
bwu.watcher.Remove(statusFile)
err = bwu.watcher.Close()
if err != nil {
bwu.w.nc.GetLogger().Error("Error closing watcher: %v", err)
}
}()
watcherEvents = bwu.watcher.EventChannel()
watcherErrors = bwu.watcher.ErrorChannel()
} else {
werr := bwu.watcher.Close()
if werr != nil {
bwu.w.nc.GetLogger().Error("Error closing %s: %s", statusFile, err)
}
bwu.watcher = nil
}
}
fi, err := bwu.fs.Stat(statusFile)
if err != nil {
bwu.w.nc.GetLogger().Error("Error retrieving stat for %s: %s", statusFile, err)
fi = nil
}
loop:
for {
select {
case <-bwu.ctx.Done():
break loop
case event := <-watcherEvents:
switch {
case event.Has(fsnotify.Create):
bwu.w.nc.GetLogger().Debug("Watcher Event create of %s", statusFile)
case event.Op&fsnotify.Write == fsnotify.Write:
err = bwu.Load()
if err != nil {
bwu.w.nc.GetLogger().Error("Watcher Events Error reading %s: %s", statusFile, err)
}
case event.Op&fsnotify.Remove == fsnotify.Remove:
err = bwu.Load()
if err != nil {
bwu.w.nc.GetLogger().Debug("Watcher Events Remove reading %s: %s", statusFile, err)
}
case event.Op&fsnotify.Rename == fsnotify.Rename:
err = bwu.Load()
if err != nil {
bwu.w.nc.GetLogger().Debug("Watcher Events Rename reading %s: %s", statusFile, err)
}
}
case <-time.After(time.Second):
newFi, err := bwu.fs.Stat(statusFile)
if err == nil && (fi == nil || fi.ModTime() != newFi.ModTime()) {
fi = newFi
err = bwu.Load()
if err != nil {
bwu.w.nc.GetLogger().Error("Work unit load Error reading %s: %s", statusFile, err)
}
}
case err, ok := <-watcherErrors:
if !ok {
return
}
bwu.w.nc.GetLogger().Error("fsnotify Error reading %s: %s", statusFile, err)
}
complete := IsComplete(bwu.Status().State)
if complete {
break
}
}
}
// getStatus returns a copy of the base status (no ExtraData). The caller must already hold the statusLock.
func (bwu *BaseWorkUnit) getStatus() *StatusFileData {
status := bwu.status
status.ExtraData = nil
return &status
}
// Status returns a copy of the status currently loaded in memory (use Load to get it from disk).
func (bwu *BaseWorkUnit) Status() *StatusFileData {
return bwu.UnredactedStatus()
}
// UnredactedStatus returns a copy of the status currently loaded in memory, including secrets.
func (bwu *BaseWorkUnit) UnredactedStatus() *StatusFileData {
bwu.statusLock.RLock()
defer bwu.statusLock.RUnlock()
return bwu.getStatus()
}
// Release releases this unit of work, deleting its files.
func (bwu *BaseWorkUnit) Release(force bool) error {
bwu.statusLock.Lock()
defer bwu.statusLock.Unlock()
attemptsLeft := 3
for {
err := bwu.fs.RemoveAll(bwu.UnitDir())
if force {
break
} else if err != nil {
attemptsLeft--
if attemptsLeft > 0 {
bwu.w.nc.GetLogger().Warning("Error removing directory for %s. Retrying %d more times.", bwu.unitID, attemptsLeft)
time.Sleep(time.Second)
continue
}
bwu.w.nc.GetLogger().Error("Error removing directory for %s. No more retries left.", bwu.unitID)
return err
}
break
}
bwu.w.activeUnitsLock.Lock()
defer bwu.w.activeUnitsLock.Unlock()
delete(bwu.w.activeUnits, bwu.unitID)
return nil
}
func (bwu *BaseWorkUnit) CancelContext() {
bwu.cancel()
}
func (bwu *BaseWorkUnit) GetStatusCopy() StatusFileData {
return bwu.status
}
func (bwu *BaseWorkUnit) GetStatusWithoutExtraData() *StatusFileData {
return bwu.getStatus()
}
func (bwu *BaseWorkUnit) SetStatusExtraData(ed interface{}) {
bwu.status.ExtraData = ed
}
func (bwu *BaseWorkUnit) GetStatusLock() *sync.RWMutex {
return bwu.statusLock
}
func (bwu *BaseWorkUnit) GetWorkceptor() *Workceptor {
return bwu.w
}
func (bwu *BaseWorkUnit) SetWorkceptor(w *Workceptor) {
bwu.w = w
}
func (bwu *BaseWorkUnit) GetContext() context.Context {
return bwu.ctx
}
func (bwu *BaseWorkUnit) GetCancel() context.CancelFunc {
return bwu.cancel
}
// =============================================================================================== //
func newUnknownWorker(w *Workceptor, unitID string, workType string) WorkUnit {
uu := &unknownUnit{}
uu.BaseWorkUnit.Init(w, unitID, workType, FileSystem{}, nil)
return uu
}
// unknownUnit is used to represent units we find on disk, but don't recognize their WorkType.
type unknownUnit struct {
BaseWorkUnit
}
// Start starts the unit. Since we don't know what this unit is, we do nothing.
func (uu *unknownUnit) Start() error {
return nil
}
// Restart restarts the unit. Since we don't know what this unit is, we do nothing.
func (uu *unknownUnit) Restart() error {
return nil
}
// Cancel cancels a running unit. Since we don't know what this unit is, we do nothing.
func (uu *unknownUnit) Cancel() error {
return nil
}
func (uu *unknownUnit) Status() *StatusFileData {
status := uu.BaseWorkUnit.Status()
status.ExtraData = "Unknown WorkType"
return status
}
|