// Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package process
import (
"bytes"
"context"
"errors"
"fmt"
"os/exec"
"sync"
"time"
)
// TODO: This packages still uses a singleton for the Manager.
// Once there's a decent web framework and dependencies are passed around like they should,
// then we delete the singleton.
var (
// ErrExecTimeout represent a timeout error
ErrExecTimeout = errors.New("Process execution timeout")
manager *Manager
)
// Process represents a working process inherit from Gogs.
type Process struct {
PID int64 // Process ID, not system one.
Description string
Start time.Time
Cmd *exec.Cmd
}
// Manager knows about all processes and counts PIDs.
type Manager struct {
mutex sync.Mutex
counter int64
Processes map[int64]*Process
}
// GetManager returns a Manager and initializes one as singleton if there's none yet
func GetManager() *Manager {
if manager == nil {
manager = &Manager{
Processes: make(map[int64]*Process),
}
}
return manager
}
// Add a process to the ProcessManager and returns its PID.
func (pm *Manager) Add(description string, cmd *exec.Cmd) int64 {
pm.mutex.Lock()
pid := pm.counter + 1
pm.Processes[pid] = &Process{
PID: pid,
Description: description,
Start: time.Now(),
Cmd: cmd,
}
pm.counter = pid
pm.mutex.Unlock()
return pid
}
// Remove a process from the ProcessManager.
func (pm *Manager) Remove(pid int64) {
pm.mutex.Lock()
delete(pm.Processes, 4 | -2/+3 |