-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtrimetric.go
200 lines (179 loc) · 5.37 KB
/
trimetric.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
package trimetric
import (
"context"
"database/sql"
"log"
"net/http"
_ "net/http/pprof" // Import the pprof package to add the HTTP handlers
"strings"
"sync"
"time"
"github.com/bsdavidson/trimetric/api"
"github.com/bsdavidson/trimetric/logic"
"github.com/bsdavidson/trimetric/trimet"
"github.com/garyburd/redigo/redis"
"github.com/influxdata/influxdb/client/v2"
"github.com/pkg/errors"
"github.com/pressly/goose"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
// OpenDB connects to the database.
func OpenDB(url string) (*sql.DB, error) {
db, err := sql.Open("postgres", url)
if err != nil {
return nil, errors.WithStack(err)
}
if err := db.Ping(); err != nil {
return nil, errors.WithStack(err)
}
return db, nil
}
// OpenInfluxDB will open a connection and return an InfluxDB client
func OpenInfluxDB(host, username, password string) (client.Client, error) {
c, err := client.NewHTTPClient(client.HTTPConfig{
Addr: host,
Username: username,
Password: password,
Timeout: 100 * time.Millisecond,
})
if err != nil {
return nil, errors.WithStack(err)
}
return c, nil
}
// MigrateDB applies any updates needed to the database to bring it up to the
// latest version of the schema. If migrate is false, then it won't modify the DB
// but will instead return an error if the database is not up-to-date.
func MigrateDB(db *sql.DB, path string, migrate bool) error {
dbVer, err := goose.EnsureDBVersion(db)
if err != nil {
return errors.WithStack(err)
}
migrations, err := goose.CollectMigrations(path, 0, goose.MaxVersion)
if err != nil {
return errors.WithStack(err)
}
lm, err := migrations.Last()
if err != nil {
return errors.WithStack(err)
}
if !migrate {
if lm.Version > dbVer {
return errors.Errorf("database version update required, latest version: %d, current version:%d", lm.Version, dbVer)
}
return nil
}
if err := goose.Up(db, path); err != nil {
return errors.WithStack(err)
}
return nil
}
// Run starts all the processes for Trimetric.
func Run(ctx context.Context, cancel context.CancelFunc, debug bool, addr, apiKey string, db *sql.DB, influxClient client.Client, kafkaAddr, redisAddr, webPath string) error {
vds := &logic.VehicleSQLDataset{DB: db}
sds := &logic.StopSQLDataset{DB: db}
shds := &logic.ShapeSQLDataset{DB: db}
rds := &logic.RouteSQLDataset{DB: db}
lds := &logic.LoaderSQLDataset{DB: db}
tuds := &logic.TripUpdateSQLDataset{DB: db}
redisPool := &redis.Pool{
MaxIdle: 3,
IdleTimeout: 240 * time.Second,
Dial: func() (redis.Conn, error) { return redis.Dial("tcp", redisAddr) },
}
wg := &sync.WaitGroup{}
wg.Add(4)
defer func() {
cancel()
wg.Wait()
}()
go func() {
defer cancel()
defer wg.Done()
producer, err := logic.NewKafkaProducer(logic.VehiclePositionsTopic, []string{kafkaAddr})
if err != nil {
log.Println(err)
return
}
defer func() {
if err := producer.Close(); err != nil {
log.Println(err)
}
}()
if err := logic.ProduceVehiclePositions(ctx, producer, trimet.BaseTrimetURL, strings.TrimSpace(apiKey), time.Second); err != nil {
log.Println(err)
}
}()
go func() {
defer cancel()
defer wg.Done()
producer, err := logic.NewKafkaProducer(logic.TripUpdatesTopic, []string{kafkaAddr})
if err != nil {
log.Println(err)
return
}
defer func() {
if err := producer.Close(); err != nil {
log.Println(err)
}
}()
if err := logic.ProduceTripUpdates(ctx, trimet.BaseTrimetURL, strings.TrimSpace(apiKey), producer); err != nil {
log.Println(err)
}
}()
go func() {
defer cancel()
defer wg.Done()
if err := logic.ConsumeKafkaTopic(ctx, vds.UpsertVehiclePositionBytes, logic.VehiclePositionsTopic, []string{kafkaAddr}); err != nil {
log.Println(err)
}
}()
go func() {
defer cancel()
defer wg.Done()
if err := logic.ConsumeKafkaTopic(ctx, tuds.UpdateTripUpdateBytes, logic.TripUpdatesTopic, []string{kafkaAddr}); err != nil {
log.Println(err)
}
}()
go func() {
defer cancel()
defer wg.Done()
logic.PollGTFSData(ctx, lds, redisPool, 24*time.Hour)
}()
http.Handle("/metrics", promhttp.Handler())
log.Println("debug listening on :9876")
internalSrv := &http.Server{Addr: ":9876", Handler: http.DefaultServeMux}
go func() {
if err := internalSrv.ListenAndServe(); err != nil {
log.Println(err)
}
}()
mux := http.NewServeMux()
mux.HandleFunc("/api/v1/vehicles", api.HandleVehiclePositions(vds))
mux.HandleFunc("/api/v1/trimet/arrivals", api.HandleTrimetArrivals(apiKey))
mux.HandleFunc("/api/v1/arrivals", api.HandleArrivals(sds, shds))
mux.HandleFunc("/api/v1/routes", api.HandleRoutes(rds))
mux.HandleFunc("/api/v1/routes/lines", api.HandleRouteLines(shds))
mux.HandleFunc("/api/v1/shapes", api.HandleShapes(shds))
mux.HandleFunc("/api/v1/stops", api.HandleStops(sds))
mux.HandleFunc("/api/v1/trip", api.HandleTripUpdates(tuds))
mux.HandleFunc("/ws", api.HandleWS(vds, shds, sds, rds))
mux.Handle("/", http.FileServer(http.Dir(webPath)))
srv := &http.Server{Addr: addr, Handler: mux}
log.Printf("serving requests on %s", addr)
go func() {
<-ctx.Done()
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
log.Println(err)
}
if err := internalSrv.Shutdown(shutdownCtx); err != nil {
log.Println(err)
}
}()
if err := srv.ListenAndServe(); err != nil {
return errors.WithStack(err)
}
return nil
}