run.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. /*
  2. Copyright 2018 The Kubernetes Authors.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package sidecar
  14. import (
  15. "bytes"
  16. "encoding/json"
  17. "fmt"
  18. "io/ioutil"
  19. "os"
  20. "os/signal"
  21. "path/filepath"
  22. "strconv"
  23. "strings"
  24. "sync"
  25. "syscall"
  26. "time"
  27. "github.com/fsnotify/fsnotify"
  28. "github.com/sirupsen/logrus"
  29. "k8s.io/test-infra/prow/pod-utils/downwardapi"
  30. "k8s.io/test-infra/prow/pod-utils/gcs"
  31. )
  32. // Run will watch for the process being wrapped to exit
  33. // and then post the status of that process and any artifacts
  34. // to cloud storage.
  35. func (o Options) Run() error {
  36. spec, err := downwardapi.ResolveSpecFromEnv()
  37. if err != nil {
  38. return fmt.Errorf("could not resolve job spec: %v", err)
  39. }
  40. // If we are being asked to terminate by the kubelet but we have
  41. // NOT seen the test process exit cleanly, we need a to start
  42. // uploading artifacts to GCS immediately. If we notice the process
  43. // exit while doing this best-effort upload, we can race with the
  44. // second upload but we can tolerate this as we'd rather get SOME
  45. // data into GCS than attempt to cancel these uploads and get none.
  46. interrupt := make(chan os.Signal)
  47. signal.Notify(interrupt, os.Interrupt, syscall.SIGTERM)
  48. go func() {
  49. select {
  50. case s := <-interrupt:
  51. logrus.Errorf("Received an interrupt: %s", s)
  52. o.doUpload(spec, false, true)
  53. }
  54. }()
  55. // Only start watching file events if the file doesn't exist
  56. // If the file exists, it means the main process already completed.
  57. if _, err := os.Stat(o.WrapperOptions.MarkerFile); os.IsNotExist(err) {
  58. watcher, err := fsnotify.NewWatcher()
  59. if err != nil {
  60. return fmt.Errorf("could not begin fsnotify watch: %v", err)
  61. }
  62. defer watcher.Close()
  63. ticker := time.NewTicker(30 * time.Second)
  64. group := sync.WaitGroup{}
  65. group.Add(1)
  66. go func() {
  67. defer group.Done()
  68. for {
  69. select {
  70. case event := <-watcher.Events:
  71. if event.Name == o.WrapperOptions.MarkerFile && event.Op&fsnotify.Create == fsnotify.Create {
  72. return
  73. }
  74. case err := <-watcher.Errors:
  75. logrus.WithError(err).Info("Encountered an error during fsnotify watch")
  76. case <-ticker.C:
  77. if _, err := os.Stat(o.WrapperOptions.MarkerFile); err == nil {
  78. return
  79. }
  80. }
  81. }
  82. }()
  83. dir := filepath.Dir(o.WrapperOptions.MarkerFile)
  84. if err := watcher.Add(dir); err != nil {
  85. return fmt.Errorf("could not add to fsnotify watch: %v", err)
  86. }
  87. group.Wait()
  88. ticker.Stop()
  89. }
  90. // If we are being asked to terminate by the kubelet but we have
  91. // seen the test process exit cleanly, we need a chance to upload
  92. // artifacts to GCS. The only valid way for this program to exit
  93. // after a SIGINT or SIGTERM in this situation is to finish]
  94. // uploading, so we ignore the signals.
  95. signal.Ignore(os.Interrupt, syscall.SIGTERM)
  96. passed := false
  97. aborted := false
  98. returnCodeData, err := ioutil.ReadFile(o.WrapperOptions.MarkerFile)
  99. if err != nil {
  100. logrus.WithError(err).Warn("Could not read return code from marker file")
  101. } else {
  102. returnCode, err := strconv.Atoi(strings.TrimSpace(string(returnCodeData)))
  103. if err != nil {
  104. logrus.WithError(err).Warn("Failed to parse process return code")
  105. }
  106. passed = returnCode == 0 && err == nil
  107. aborted = returnCode == 130
  108. }
  109. return o.doUpload(spec, passed, aborted)
  110. }
  111. func (o Options) doUpload(spec *downwardapi.JobSpec, passed, aborted bool) error {
  112. uploadTargets := map[string]gcs.UploadFunc{
  113. "build-log.txt": gcs.FileUpload(o.WrapperOptions.ProcessLog),
  114. }
  115. var result string
  116. switch {
  117. case passed:
  118. result = "SUCCESS"
  119. case aborted:
  120. result = "ABORTED"
  121. default:
  122. result = "FAILURE"
  123. }
  124. finished := struct {
  125. Timestamp int64 `json:"timestamp"`
  126. Passed bool `json:"passed"`
  127. Result string `json:"result"`
  128. }{
  129. Timestamp: time.Now().Unix(),
  130. Passed: passed,
  131. Result: result,
  132. }
  133. finishedData, err := json.Marshal(&finished)
  134. if err != nil {
  135. logrus.WithError(err).Warn("Could not marshal finishing data")
  136. } else {
  137. uploadTargets["finished.json"] = gcs.DataUpload(bytes.NewBuffer(finishedData))
  138. }
  139. if err := o.GcsOptions.Run(spec, uploadTargets); err != nil {
  140. return fmt.Errorf("failed to upload to GCS: %v", err)
  141. }
  142. return nil
  143. }