Scott Baker | 14c8f18 | 2019-05-22 18:05:29 -0700 | [diff] [blame^] | 1 | /* |
| 2 | * Copyright 2019-present Open Networking Foundation |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | package testutils |
| 17 | |
| 18 | import ( |
| 19 | "fmt" |
| 20 | "os" |
| 21 | "os/exec" |
| 22 | "strings" |
| 23 | ) |
| 24 | |
| 25 | const ( |
| 26 | CONTAINER_NAME = "xos-mock-grpc-server" |
| 27 | //MOCK_DIR = "/home/smbaker/projects/gopath/src/github.com/opencord/cordctl/mock" |
| 28 | ) |
| 29 | |
| 30 | var MockDir = os.Getenv("CORDCTL_MOCK_DIR") |
| 31 | |
| 32 | func init() { |
| 33 | if MockDir == "" { |
| 34 | panic("CORDCTL_MOCK_DIR environment variable not set") |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | // Start the mock server and wait for it to be ready |
| 39 | // `data_name` is the name of the data.json to tell the mock server to use. |
| 40 | // If a mock server is already running with the same data_name, it is not restarted. |
| 41 | func StartMockServer(data_name string) error { |
| 42 | cmd_str := fmt.Sprintf("cd %s && DATA_JSON=%s docker-compose up -d", MockDir, data_name) |
| 43 | cmd := exec.Command("/bin/bash", "-c", cmd_str) |
| 44 | |
| 45 | err := cmd.Run() |
| 46 | if err != nil { |
| 47 | return err |
| 48 | } |
| 49 | |
| 50 | err = WaitForReady() |
| 51 | if err != nil { |
| 52 | return err |
| 53 | } |
| 54 | |
| 55 | return nil |
| 56 | } |
| 57 | |
| 58 | // Stop the mock server |
| 59 | func StopMockServer() error { |
| 60 | cmd_str := fmt.Sprintf("cd %s && docker-compose down", MockDir) |
| 61 | cmd := exec.Command("/bin/bash", "-c", cmd_str) |
| 62 | |
| 63 | err := cmd.Run() |
| 64 | if err != nil { |
| 65 | return err |
| 66 | } |
| 67 | |
| 68 | return nil |
| 69 | } |
| 70 | |
| 71 | // Wait for the mock server to be ready |
| 72 | func WaitForReady() error { |
| 73 | for { |
| 74 | ready, err := IsReady() |
| 75 | if err != nil { |
| 76 | return err |
| 77 | } |
| 78 | if ready { |
| 79 | return nil |
| 80 | } |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | // Return true if the mock server is ready |
| 85 | func IsReady() (bool, error) { |
| 86 | cmd := exec.Command("docker", "logs", CONTAINER_NAME) |
| 87 | out, err := cmd.Output() |
| 88 | if err != nil { |
| 89 | return false, err |
| 90 | } |
| 91 | |
| 92 | return strings.Contains(string(out), "Listening for requests"), nil |
| 93 | } |