session.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package ansible
  15. import (
  16. "context"
  17. )
  18. type Runnable interface {
  19. Run(context.Context) error
  20. }
  21. // Session is a container for execution of playbook
  22. type Session struct {
  23. // Ctx is the context under which the playbook will run
  24. Ctx context.Context
  25. // Runnable is the task to be run
  26. Runnable Runnable
  27. // cancelFunc can be called to cancel the running playbook
  28. cancelFunc context.CancelFunc
  29. }
  30. // SessionManager manages a collection of keyed sessions
  31. type SessionManager map[string]*Session
  32. // Has returns true if a session with the specified id exists in the manager
  33. func (sm SessionManager) Has(id string) bool {
  34. _, ok := sm[id]
  35. return ok
  36. }
  37. // Add adds a Runnable to the manager keyed with the specified id
  38. func (sm SessionManager) Add(id string, runnable Runnable) *Session {
  39. ctx, cancelFunc := context.WithCancel(context.Background())
  40. session := &Session{
  41. Runnable: runnable,
  42. Ctx: ctx,
  43. cancelFunc: cancelFunc,
  44. }
  45. sm[id] = session
  46. return session
  47. }
  48. // Remove stops (if appliable) and removes the playbook keyed with the
  49. // specified id from the manager
  50. func (sm SessionManager) Remove(id string) {
  51. sm.Stop(id)
  52. delete(sm, id)
  53. }
  54. // Run runs the playbook keyed with specified id
  55. func (sm SessionManager) Run(id string) error {
  56. s, ok := sm[id]
  57. if !ok {
  58. return nil
  59. }
  60. return s.Runnable.Run(s.Ctx)
  61. }
  62. // Stop stops the playbook keyed with specified id
  63. func (sm SessionManager) Stop(id string) {
  64. s, ok := sm[id]
  65. if !ok {
  66. return
  67. }
  68. s.cancelFunc()
  69. }
  70. // Err returns possible error from sm.Ctx.Err()
  71. func (sm SessionManager) Err(id string) error {
  72. s, ok := sm[id]
  73. if !ok {
  74. return nil
  75. }
  76. return s.Ctx.Err()
  77. }