This repository has been archived by the owner on Nov 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
main.go
207 lines (181 loc) · 6.17 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
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
201
202
203
204
205
206
207
// Copyright (c) 2019 IoTeX
// This is an alpha (internal) release and is not suitable for production. This source code is provided 'as is' and no
// warranties are given as to title or non-infringement, merchantability or fitness for purpose and, to the extent
// permitted by law, all liability for your use of the code is disclaimed. This source code is governed by Apache
// License 2.0 that can be found in the LICENSE file.
// usage: go build -o ./bin/server -v .
// ./bin/server
package main
import (
"bytes"
"context"
"io/ioutil"
"net/http"
"os"
"strconv"
"time"
"github.com/99designs/gqlgen/handler"
"github.com/iotexproject/iotex-core/pkg/log"
"github.com/iotexproject/iotex-election/pb/api"
"github.com/iotexproject/iotex-proto/golang/iotexapi"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"google.golang.org/grpc"
"gopkg.in/yaml.v2"
"github.com/iotexproject/iotex-analytics/graphql"
"github.com/iotexproject/iotex-analytics/indexcontext"
"github.com/iotexproject/iotex-analytics/indexservice"
"github.com/iotexproject/iotex-analytics/queryprotocol/actions"
"github.com/iotexproject/iotex-analytics/queryprotocol/chainmeta"
"github.com/iotexproject/iotex-analytics/queryprotocol/hermes2"
"github.com/iotexproject/iotex-analytics/queryprotocol/productivity"
"github.com/iotexproject/iotex-analytics/queryprotocol/rewards"
"github.com/iotexproject/iotex-analytics/queryprotocol/votings"
"github.com/iotexproject/iotex-analytics/sql"
)
const defaultPort = "8089"
func main() {
port := os.Getenv("PORT")
if port == "" {
port = defaultPort
}
configPath := os.Getenv("CONFIG")
if configPath == "" {
configPath = "config.yaml"
}
chainEndpoint := os.Getenv("CHAIN_ENDPOINT")
if chainEndpoint == "" {
chainEndpoint = "127.0.0.1:14014"
}
electionEndpoint := os.Getenv("ELECTION_ENDPOINT")
if electionEndpoint == "" {
electionEndpoint = "127.0.0.1:8090"
}
connectionStr := os.Getenv("CONNECTION_STRING")
if connectionStr == "" {
connectionStr = "root:rootuser@tcp(127.0.0.1:3306)/"
}
dbName := os.Getenv("DB_NAME")
if dbName == "" {
dbName = "analytics"
}
data, err := ioutil.ReadFile(configPath)
if err != nil {
log.L().Fatal("Failed to load config file", zap.Error(err))
}
var cfg indexservice.Config
if err := yaml.Unmarshal(data, &cfg); err != nil {
log.L().Fatal("failed to unmarshal config", zap.Error(err))
}
if cfg.Zap == nil {
zapCfg := zap.NewProductionConfig()
cfg.Zap = &zapCfg
} else {
if cfg.Zap.Development {
cfg.Zap.EncoderConfig = zap.NewDevelopmentEncoderConfig()
} else {
cfg.Zap.EncoderConfig = zap.NewProductionEncoderConfig()
}
}
cfg.Zap.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
cfg.Zap.EncoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
logger, err := cfg.Zap.Build()
if err == nil {
zap.ReplaceGlobals(logger)
}
readOnly := os.Getenv("READ_ONLY")
if readOnly != "" {
cfg.ReadOnly = readOnly == "true"
}
store := sql.NewMySQL(connectionStr, dbName, cfg.ReadOnly)
maxOpenConnsStr := os.Getenv("MAX_OPEN_CONNECTIONS")
if maxOpenConnsStr != "" {
maxOpenConns, err := strconv.Atoi(maxOpenConnsStr)
if err != nil {
log.L().Info("failed to parse parameter", zap.String("MAX_OPEN_CONNECTIONS", maxOpenConnsStr), zap.Error(err))
}
store.SetMaxOpenConns(maxOpenConns)
}
idx := indexservice.NewIndexer(store, cfg)
if err := idx.RegisterDefaultProtocols(); err != nil {
log.L().Fatal("Failed to register default protocols", zap.Error(err))
}
http.Handle("/", graphqlHandler(handler.Playground("GraphQL playground", "/query")))
http.Handle("/query", graphqlHandler(handler.GraphQL(graphql.NewExecutableSchema(graphql.Config{Resolvers: &graphql.Resolver{
PP: productivity.NewProtocol(idx),
RP: rewards.NewProtocol(idx),
VP: votings.NewProtocol(idx),
AP: actions.NewProtocol(idx),
CP: chainmeta.NewProtocol(idx),
HP: hermes2.NewProtocol(idx, cfg.HermesConfig),
}}))))
//http.Handle("/metrics", promhttp.Handler())
//log.S().Infof("connect to http://localhost:%s/ for GraphQL playground", port)
// Start GraphQL query service
go func() {
if err := http.ListenAndServe(":"+port, nil); err != nil {
log.L().Fatal("Failed to serve index query service", zap.Error(err))
}
}()
grpcCtx1, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
conn1, err := grpc.DialContext(grpcCtx1, chainEndpoint, grpc.WithBlock(), grpc.WithInsecure())
if err != nil {
log.L().Error("Failed to connect to chain's API server.")
}
chainClient := iotexapi.NewAPIServiceClient(conn1)
grpcCtx2, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
conn2, err := grpc.DialContext(grpcCtx2, electionEndpoint, grpc.WithBlock(), grpc.WithInsecure())
if err != nil {
log.L().Error("Failed to connect to election's API server.")
}
electionClient := api.NewAPIServiceClient(conn2)
ctx := indexcontext.WithIndexCtx(context.Background(), indexcontext.IndexCtx{
ChainClient: chainClient,
ElectionClient: electionClient,
ConsensusScheme: idx.Config.ConsensusScheme,
})
if err := idx.Start(ctx); err != nil {
log.L().Fatal("Failed to start the indexer", zap.Error(err))
}
defer func() {
if err := idx.Stop(ctx); err != nil {
log.L().Fatal("Failed to stop the indexer", zap.Error(err))
}
}()
select {}
}
func graphqlHandler(playgroundHandler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "*")
if r.Method == "POST" {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
log.L().Error("Failed to read request body", zap.Error(err))
w.WriteHeader(http.StatusInternalServerError)
return
}
// clone body
r.Body = ioutil.NopCloser(bytes.NewReader(body))
clientIP, clientID := getIPID(r)
log.L().Info("request stat",
zap.String("clientIP", clientIP),
zap.String("clientID", clientID),
zap.ByteString("body", body))
}
playgroundHandler.ServeHTTP(w, r)
})
}
func getIPID(r *http.Request) (ip, id string) {
ip = r.Header.Get("X-Forwarded-For")
if ip == "" {
ip = r.RemoteAddr
}
id = r.Header.Get("x-iotex-client-id")
if id == "" {
id = "unknown"
}
return
}