-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
107 lines (85 loc) · 2.34 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package rfe
import (
"fmt"
"io"
"log"
"os"
"os/exec"
"strings"
"github.com/cskr/pubsub"
)
const firestoreEmulatorHost = "FIRESTORE_EMULATOR_HOST"
const loopbackIP = "127.0.0.1"
const firestoreStdoutTopic = "firetore-logs"
func getFirestoreEmulatorCmd(verbose bool, port uint16) *exec.Cmd {
var cmdArgs = []string{"beta", "emulators", "firestore", "start"}
if !verbose {
cmdArgs = append(cmdArgs, "--quiet")
}
if port == 0 {
port = getFreeHostPort()
}
hostPort := fmt.Sprintf("--host-port=%s:%d", loopbackIP, port)
cmdArgs = append(cmdArgs, hostPort)
return exec.Command("gcloud", cmdArgs...)
}
func setHostEnvIfIsConfigured(stdoutLine string) {
pos := strings.Index(stdoutLine, firestoreEmulatorHost+"=")
if pos > 0 {
host := stdoutLine[pos+len(firestoreEmulatorHost)+1:]
os.Setenv(firestoreEmulatorHost, host)
}
}
func publishFirestoreLogs(firestoreStdout io.ReadCloser, firestorePubSub *pubsub.PubSub) {
streamReadlinesIterator, err := getStreamReadlinesIterator(firestoreStdout)
if err != nil {
log.Fatal(err)
}
for line := range streamReadlinesIterator {
firestorePubSub.Pub(line, firestoreStdoutTopic)
}
}
func startFirestoreEmulator(verbose bool, port uint16) (cmd *exec.Cmd, stdout io.ReadCloser) {
cmd = getFirestoreEmulatorCmd(verbose, port)
stdout = getBothStdoutStderrCombined(cmd)
makeProcessKillable(cmd)
if err := cmd.Start(); err != nil {
log.Fatal(err)
}
return
}
func firestoreEmulatorIsReady(stdoutLine string) bool {
return strings.Contains(stdoutLine, "Dev App Server is now running")
}
func waitForFirestoreToBeReady(ps *pubsub.PubSub) {
channel := ps.Sub(firestoreStdoutTopic)
for {
if msg, ok := <-channel; ok {
if firestoreEmulatorIsReady(fmt.Sprintf("%s", msg)) {
go ps.Unsub(channel, firestoreStdoutTopic)
}
setHostEnvIfIsConfigured(fmt.Sprintf("%s", msg))
} else {
break
}
}
}
type FirestoreEmulator struct {
pubSub *pubsub.PubSub
stdout io.ReadCloser
cmd *exec.Cmd
Verbose bool
Port uint16
}
func (f *FirestoreEmulator) Start() {
f.pubSub = pubsub.New(0)
f.cmd, f.stdout = startFirestoreEmulator(f.Verbose, f.Port)
go publishFirestoreLogs(f.stdout, f.pubSub)
go logPubSubTopic(f.pubSub, firestoreStdoutTopic)
waitForFirestoreToBeReady(f.pubSub)
}
func (f *FirestoreEmulator) Shutdown() {
f.stdout.Close()
killProcessGroup(f.cmd)
f.pubSub.Shutdown()
}