proc_sync_test.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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. "fmt"
  17. "io/ioutil"
  18. "os"
  19. "os/exec"
  20. "path/filepath"
  21. "syscall"
  22. "testing"
  23. "android/soong/ui/logger"
  24. )
  25. // some util methods and data structures that aren't directly part of a test
  26. func makeLockDir() (path string, err error) {
  27. return ioutil.TempDir("", "soong_lock_test")
  28. }
  29. func lockOrFail(t *testing.T) (lock fileLock) {
  30. lockDir, err := makeLockDir()
  31. var lockPointer *fileLock
  32. if err == nil {
  33. lockPointer, err = newLock(lockDir)
  34. }
  35. if err != nil {
  36. os.RemoveAll(lockDir)
  37. t.Fatalf("Failed to create lock: %v", err)
  38. }
  39. return *lockPointer
  40. }
  41. func removeTestLock(fileLock fileLock) {
  42. lockdir := filepath.Dir(fileLock.File.Name())
  43. os.RemoveAll(lockdir)
  44. }
  45. // countWaiter only exists for the purposes of testing lockSynchronous
  46. type countWaiter struct {
  47. numWaitsElapsed int
  48. maxNumWaits int
  49. }
  50. func newCountWaiter(count int) (waiter *countWaiter) {
  51. return &countWaiter{0, count}
  52. }
  53. func (c *countWaiter) wait() {
  54. c.numWaitsElapsed++
  55. }
  56. func (c *countWaiter) checkDeadline() (done bool, remainder string) {
  57. numWaitsRemaining := c.maxNumWaits - c.numWaitsElapsed
  58. if numWaitsRemaining < 1 {
  59. return true, ""
  60. }
  61. return false, fmt.Sprintf("%v waits remain", numWaitsRemaining)
  62. }
  63. func (c countWaiter) summarize() (summary string) {
  64. return fmt.Sprintf("waiting %v times", c.maxNumWaits)
  65. }
  66. // countLock only exists for the purposes of testing lockSynchronous
  67. type countLock struct {
  68. nextIndex int
  69. successIndex int
  70. }
  71. var _ lockable = (*countLock)(nil)
  72. // returns a countLock that succeeds on iteration <index>
  73. func testLockCountingTo(index int) (lock *countLock) {
  74. return &countLock{nextIndex: 0, successIndex: index}
  75. }
  76. func (c *countLock) description() (message string) {
  77. return fmt.Sprintf("counter that counts from %v to %v", c.nextIndex, c.successIndex)
  78. }
  79. func (c *countLock) tryLock() (err error) {
  80. currentIndex := c.nextIndex
  81. c.nextIndex++
  82. if currentIndex == c.successIndex {
  83. return nil
  84. }
  85. return fmt.Errorf("Lock busy: %s", c.description())
  86. }
  87. func (c *countLock) Unlock() (err error) {
  88. if c.nextIndex == c.successIndex {
  89. return nil
  90. }
  91. return fmt.Errorf("Not locked: %s", c.description())
  92. }
  93. // end of util methods
  94. // start of tests
  95. // simple test
  96. func TestGetLock(t *testing.T) {
  97. lockfile := lockOrFail(t)
  98. defer removeTestLock(lockfile)
  99. }
  100. // a more complicated test that spans multiple processes
  101. var lockPathVariable = "LOCK_PATH"
  102. var successStatus = 0
  103. var unexpectedError = 1
  104. var busyStatus = 2
  105. func TestTrylock(t *testing.T) {
  106. lockpath := os.Getenv(lockPathVariable)
  107. if len(lockpath) < 1 {
  108. checkTrylockMainProcess(t)
  109. } else {
  110. getLockAndExit(lockpath)
  111. }
  112. }
  113. // the portion of TestTrylock that runs in the main process
  114. func checkTrylockMainProcess(t *testing.T) {
  115. var err error
  116. lockfile := lockOrFail(t)
  117. defer removeTestLock(lockfile)
  118. lockdir := filepath.Dir(lockfile.File.Name())
  119. otherAcquired, message, err := forkAndGetLock(lockdir)
  120. if err != nil {
  121. t.Fatalf("Unexpected error in subprocess trying to lock uncontested fileLock: %v. Subprocess output: %q", err, message)
  122. }
  123. if !otherAcquired {
  124. t.Fatalf("Subprocess failed to lock uncontested fileLock. Subprocess output: %q", message)
  125. }
  126. err = lockfile.tryLock()
  127. if err != nil {
  128. t.Fatalf("Failed to lock fileLock: %v", err)
  129. }
  130. reacquired, message, err := forkAndGetLock(filepath.Dir(lockfile.File.Name()))
  131. if err != nil {
  132. t.Fatal(err)
  133. }
  134. if reacquired {
  135. t.Fatalf("Permitted locking fileLock twice. Subprocess output: %q", message)
  136. }
  137. err = lockfile.Unlock()
  138. if err != nil {
  139. t.Fatalf("Error unlocking fileLock: %v", err)
  140. }
  141. reacquired, message, err = forkAndGetLock(filepath.Dir(lockfile.File.Name()))
  142. if err != nil {
  143. t.Fatal(err)
  144. }
  145. if !reacquired {
  146. t.Fatalf("Subprocess failed to acquire lock after it was released by the main process. Subprocess output: %q", message)
  147. }
  148. }
  149. func forkAndGetLock(lockDir string) (acquired bool, subprocessOutput []byte, err error) {
  150. cmd := exec.Command(os.Args[0], "-test.run=TestTrylock")
  151. cmd.Env = append(os.Environ(), fmt.Sprintf("%s=%s", lockPathVariable, lockDir))
  152. subprocessOutput, err = cmd.CombinedOutput()
  153. exitStatus := successStatus
  154. if exitError, ok := err.(*exec.ExitError); ok {
  155. if waitStatus, ok := exitError.Sys().(syscall.WaitStatus); ok {
  156. exitStatus = waitStatus.ExitStatus()
  157. }
  158. }
  159. if exitStatus == successStatus {
  160. return true, subprocessOutput, nil
  161. } else if exitStatus == busyStatus {
  162. return false, subprocessOutput, nil
  163. } else {
  164. return false, subprocessOutput, fmt.Errorf("Unexpected status %v", exitStatus)
  165. }
  166. }
  167. // This function runs in a different process. See TestTrylock
  168. func getLockAndExit(lockpath string) {
  169. fmt.Printf("Will lock path %q\n", lockpath)
  170. lockfile, err := newLock(lockpath)
  171. exitStatus := unexpectedError
  172. if err == nil {
  173. err = lockfile.tryLock()
  174. if err == nil {
  175. exitStatus = successStatus
  176. } else {
  177. exitStatus = busyStatus
  178. }
  179. }
  180. fmt.Printf("Tried to lock path %s. Received error %v. Exiting with status %v\n", lockpath, err, exitStatus)
  181. os.Exit(exitStatus)
  182. }
  183. func TestLockFirstTrySucceeds(t *testing.T) {
  184. noopLogger := logger.New(ioutil.Discard)
  185. lock := testLockCountingTo(0)
  186. waiter := newCountWaiter(0)
  187. err := lockSynchronous(lock, waiter, noopLogger)
  188. if err != nil {
  189. t.Fatal(err)
  190. }
  191. if waiter.numWaitsElapsed != 0 {
  192. t.Fatalf("Incorrect number of waits elapsed; expected 0, got %v", waiter.numWaitsElapsed)
  193. }
  194. }
  195. func TestLockThirdTrySucceeds(t *testing.T) {
  196. noopLogger := logger.New(ioutil.Discard)
  197. lock := testLockCountingTo(2)
  198. waiter := newCountWaiter(2)
  199. err := lockSynchronous(lock, waiter, noopLogger)
  200. if err != nil {
  201. t.Fatal(err)
  202. }
  203. if waiter.numWaitsElapsed != 2 {
  204. t.Fatalf("Incorrect number of waits elapsed; expected 2, got %v", waiter.numWaitsElapsed)
  205. }
  206. }
  207. func TestLockTimedOut(t *testing.T) {
  208. noopLogger := logger.New(ioutil.Discard)
  209. lock := testLockCountingTo(3)
  210. waiter := newCountWaiter(2)
  211. err := lockSynchronous(lock, waiter, noopLogger)
  212. if err == nil {
  213. t.Fatalf("Appeared to have acquired lock on iteration %v which should not be available until iteration %v", waiter.numWaitsElapsed, lock.successIndex)
  214. }
  215. if waiter.numWaitsElapsed != waiter.maxNumWaits {
  216. t.Fatalf("Waited an incorrect number of times; expected %v, got %v", waiter.maxNumWaits, waiter.numWaitsElapsed)
  217. }
  218. }