|
| 1 | +package shell |
| 2 | + |
| 3 | +import ( |
| 4 | + "errors" |
| 5 | + "sync" |
| 6 | + |
| 7 | + "golang.org/x/sync/semaphore" |
| 8 | +) |
| 9 | + |
| 10 | +// Keeps track of shell processes spawned by the daemon. |
| 11 | +type ShellRunner struct { |
| 12 | + shellCount *semaphore.Weighted // Current available shell count. |
| 13 | + sessions map[string]*ShellSession // Dict of all currently running shells. |
| 14 | + mut sync.Mutex // Protects sessions dict. |
| 15 | +} |
| 16 | + |
| 17 | +var ( |
| 18 | + ErrSessionNotFound = errors.New("session not found") |
| 19 | + ErrSessionLimitReached = errors.New("session limit reached") |
| 20 | +) |
| 21 | + |
| 22 | +// Create a new shell runner that is capable of spawning up to limit concurrent |
| 23 | +// shell processes. |
| 24 | +func NewShellRunner(limit int) (*ShellRunner, error) { |
| 25 | + sr := new(ShellRunner) |
| 26 | + sr.shellCount = semaphore.NewWeighted(int64(limit)) |
| 27 | + sr.sessions = make(map[string]*ShellSession) |
| 28 | + return sr, nil |
| 29 | +} |
| 30 | + |
| 31 | +// Spawn a new shell process and associate it with a given UUID. |
| 32 | +func (s *ShellRunner) Spawn(uuid string) (*ShellSession, error) { |
| 33 | + ok := s.shellCount.TryAcquire(1) |
| 34 | + if !ok { |
| 35 | + return nil, ErrSessionLimitReached |
| 36 | + } |
| 37 | + |
| 38 | + session, err := NewShellSession(uuid) |
| 39 | + if err != nil { |
| 40 | + return nil, err |
| 41 | + } |
| 42 | + |
| 43 | + s.mut.Lock() |
| 44 | + defer s.mut.Unlock() |
| 45 | + s.sessions[uuid] = session |
| 46 | + |
| 47 | + return session, nil |
| 48 | +} |
| 49 | + |
| 50 | +// Terminate a shell session that was previously spawned. The associated shell |
| 51 | +// process is terminated if it is still running. |
| 52 | +func (s *ShellRunner) Terminate(uuid string) error { |
| 53 | + s.mut.Lock() |
| 54 | + defer s.mut.Unlock() |
| 55 | + |
| 56 | + v, ok := s.sessions[uuid] |
| 57 | + if !ok { |
| 58 | + return ErrSessionNotFound |
| 59 | + } |
| 60 | + v.Close() |
| 61 | + delete(s.sessions, uuid) |
| 62 | + s.shellCount.Release(1) |
| 63 | + |
| 64 | + return nil |
| 65 | +} |
0 commit comments