proc_sync.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. // Copyright 2017 Google Inc. All rights reserved.
  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 build
  15. import (
  16. "errors"
  17. "fmt"
  18. "math"
  19. "os"
  20. "path/filepath"
  21. "syscall"
  22. "time"
  23. "android/soong/ui/logger"
  24. )
  25. // This file provides cross-process synchronization methods
  26. // i.e. making sure only one Soong process is running for a given output directory
  27. func BecomeSingletonOrFail(ctx Context, config Config) (lock *fileLock) {
  28. lockingInfo, err := newLock(config.OutDir())
  29. if err != nil {
  30. ctx.Logger.Fatal(err)
  31. }
  32. lockfilePollDuration := time.Second
  33. lockfileTimeout := time.Second * 10
  34. if envTimeout := os.Getenv("SOONG_LOCK_TIMEOUT"); envTimeout != "" {
  35. lockfileTimeout, err = time.ParseDuration(envTimeout)
  36. if err != nil {
  37. ctx.Logger.Fatalf("failure parsing SOONG_LOCK_TIMEOUT %q: %s", envTimeout, err)
  38. }
  39. }
  40. err = lockSynchronous(*lockingInfo, newSleepWaiter(lockfilePollDuration, lockfileTimeout), ctx.Logger)
  41. if err != nil {
  42. ctx.Logger.Fatal(err)
  43. }
  44. return lockingInfo
  45. }
  46. type lockable interface {
  47. tryLock() error
  48. Unlock() error
  49. description() string
  50. }
  51. var _ lockable = (*fileLock)(nil)
  52. type fileLock struct {
  53. File *os.File
  54. }
  55. func (l fileLock) description() (path string) {
  56. return l.File.Name()
  57. }
  58. func (l fileLock) tryLock() (err error) {
  59. return syscall.Flock(int(l.File.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
  60. }
  61. func (l fileLock) Unlock() (err error) {
  62. return l.File.Close()
  63. }
  64. func lockSynchronous(lock lockable, waiter waiter, logger logger.Logger) (err error) {
  65. waited := false
  66. for {
  67. err = lock.tryLock()
  68. if err == nil {
  69. if waited {
  70. // If we had to wait at all, then when the wait is done, we inform the user
  71. logger.Printf("Acquired lock on %v; previous Soong process must have completed. Continuing...\n", lock.description())
  72. }
  73. return nil
  74. }
  75. done, description := waiter.checkDeadline()
  76. if !waited {
  77. logger.Printf("Waiting up to %s to lock %v to ensure no other Soong process is running in the same output directory\n", description, lock.description())
  78. }
  79. waited = true
  80. if done {
  81. return fmt.Errorf("Tried to lock %s, but timed out %s . Make sure no other Soong process is using it",
  82. lock.description(), waiter.summarize())
  83. } else {
  84. waiter.wait()
  85. }
  86. }
  87. }
  88. func newLock(basedir string) (lock *fileLock, err error) {
  89. lockPath := filepath.Join(basedir, ".lock")
  90. os.MkdirAll(basedir, 0777)
  91. lockfileDescriptor, err := os.OpenFile(lockPath, os.O_RDWR|os.O_CREATE, 0666)
  92. if err != nil {
  93. return nil, errors.New("failed to open " + lockPath)
  94. }
  95. lockingInfo := &fileLock{File: lockfileDescriptor}
  96. return lockingInfo, nil
  97. }
  98. type waiter interface {
  99. wait()
  100. checkDeadline() (done bool, remainder string)
  101. summarize() (summary string)
  102. }
  103. type sleepWaiter struct {
  104. sleepInterval time.Duration
  105. deadline time.Time
  106. totalWait time.Duration
  107. }
  108. var _ waiter = (*sleepWaiter)(nil)
  109. func newSleepWaiter(interval time.Duration, duration time.Duration) (waiter *sleepWaiter) {
  110. return &sleepWaiter{interval, time.Now().Add(duration), duration}
  111. }
  112. func (s sleepWaiter) wait() {
  113. time.Sleep(s.sleepInterval)
  114. }
  115. func (s *sleepWaiter) checkDeadline() (done bool, remainder string) {
  116. remainingSleep := s.deadline.Sub(time.Now())
  117. numSecondsRounded := math.Floor(remainingSleep.Seconds()*10+0.5) / 10
  118. if remainingSleep > 0 {
  119. return false, fmt.Sprintf("%vs", numSecondsRounded)
  120. } else {
  121. return true, ""
  122. }
  123. }
  124. func (s sleepWaiter) summarize() (summary string) {
  125. return fmt.Sprintf("polling every %v until %v", s.sleepInterval, s.totalWait)
  126. }