-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
209 lines (180 loc) · 6.16 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
208
209
/*
* Copyright 2019 Insolar Technologies
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package api
import (
"context"
"crypto"
"fmt"
"net"
"net/http"
"sync"
"time"
"github.com/gorilla/rpc/v2"
jsonrpc "github.com/gorilla/rpc/v2/json2"
"github.com/insolar/insolar/application/extractor"
"github.com/pkg/errors"
"github.com/insolar/insolar/api/seedmanager"
"github.com/insolar/insolar/configuration"
"github.com/insolar/insolar/core"
"github.com/insolar/insolar/core/reply"
"github.com/insolar/insolar/instrumentation/inslogger"
"github.com/insolar/insolar/platformpolicy"
)
// Runner implements Component for API
type Runner struct {
CertificateManager core.CertificateManager `inject:""`
StorageExporter core.StorageExporter `inject:""`
ContractRequester core.ContractRequester `inject:""`
NetworkCoordinator core.NetworkCoordinator `inject:""`
GenesisDataProvider core.GenesisDataProvider `inject:""`
NetworkSwitcher core.NetworkSwitcher `inject:""`
NodeNetwork core.NodeNetwork `inject:""`
PulseStorage core.PulseStorage `inject:""`
server *http.Server
rpcServer *rpc.Server
cfg *configuration.APIRunner
keyCache map[string]crypto.PublicKey
cacheLock *sync.RWMutex
SeedManager *seedmanager.SeedManager
SeedGenerator seedmanager.SeedGenerator
}
func checkConfig(cfg *configuration.APIRunner) error {
if cfg == nil {
return errors.New("[ checkConfig ] config is nil")
}
if cfg.Address == "" {
return errors.New("[ checkConfig ] Address must not be empty")
}
if len(cfg.Call) == 0 {
return errors.New("[ checkConfig ] Call must exist")
}
if len(cfg.RPC) == 0 {
return errors.New("[ checkConfig ] RPC must exist")
}
if cfg.Timeout == 0 {
return errors.New("[ checkConfig ] Timeout must not be null")
}
return nil
}
func (ar *Runner) registerServices(rpcServer *rpc.Server) error {
err := rpcServer.RegisterService(NewStorageExporterService(ar), "exporter")
if err != nil {
return errors.New("[ registerServices ] Can't RegisterService: exporter")
}
err = rpcServer.RegisterService(NewSeedService(ar), "seed")
if err != nil {
return errors.New("[ registerServices ] Can't RegisterService: seed")
}
err = rpcServer.RegisterService(NewInfoService(ar), "info")
if err != nil {
return errors.New("[ registerServices ] Can't RegisterService: info")
}
err = rpcServer.RegisterService(NewStatusService(ar), "status")
if err != nil {
return errors.New("[ registerServices ] Can't RegisterService: status")
}
err = rpcServer.RegisterService(NewNodeCertService(ar), "cert")
if err != nil {
return errors.New("[ registerServices ] Can't RegisterService: cert")
}
return nil
}
// NewRunner is C-tor for API Runner
func NewRunner(cfg *configuration.APIRunner) (*Runner, error) {
if err := checkConfig(cfg); err != nil {
return nil, errors.Wrap(err, "[ NewAPIRunner ] Bad config")
}
addrStr := fmt.Sprint(cfg.Address)
rpcServer := rpc.NewServer()
ar := Runner{
server: &http.Server{Addr: addrStr},
rpcServer: rpcServer,
cfg: cfg,
keyCache: make(map[string]crypto.PublicKey),
cacheLock: &sync.RWMutex{},
}
rpcServer.RegisterCodec(jsonrpc.NewCodec(), "application/json")
if err := ar.registerServices(rpcServer); err != nil {
return nil, errors.Wrap(err, "[ NewAPIRunner ] Can't register services:")
}
return &ar, nil
}
// IsAPIRunner is implementation of APIRunner interface for component manager
func (ar *Runner) IsAPIRunner() bool {
return true
}
// Start runs api server
func (ar *Runner) Start(ctx context.Context) error {
hc := NewHealthChecker(ar.CertificateManager, ar.NodeNetwork)
http.HandleFunc("/healthcheck", hc.CheckHandler)
ar.SeedManager = seedmanager.New()
http.HandleFunc(ar.cfg.Call, ar.callHandler())
http.Handle(ar.cfg.RPC, ar.rpcServer)
inslog := inslogger.FromContext(ctx)
inslog.Info("Starting ApiRunner ...")
inslog.Info("Config: ", ar.cfg)
listener, err := net.Listen("tcp", ar.server.Addr)
if err != nil {
return errors.Wrap(err, "Can't start listening")
}
go func() {
if err := ar.server.Serve(listener); err != nil {
inslog.Error("Httpserver: ListenAndServe() error: ", err)
}
}()
return nil
}
// Stop stops api server
func (ar *Runner) Stop(ctx context.Context) error {
const timeOut = 5
inslogger.FromContext(ctx).Infof("Shutting down server gracefully ...(waiting for %d seconds)", timeOut)
ctxWithTimeout, cancel := context.WithTimeout(ctx, time.Duration(timeOut)*time.Second)
defer cancel()
err := ar.server.Shutdown(ctxWithTimeout)
if err != nil {
return errors.Wrap(err, "Can't gracefully stop API server")
}
return nil
}
func (ar *Runner) getMemberPubKey(ctx context.Context, ref string) (crypto.PublicKey, error) { //nolint
ar.cacheLock.RLock()
publicKey, ok := ar.keyCache[ref]
ar.cacheLock.RUnlock()
if ok {
return publicKey, nil
}
reference, err := core.NewRefFromBase58(ref)
if err != nil {
return nil, errors.Wrap(err, "[ getMemberPubKey ] Can't parse ref")
}
res, err := ar.ContractRequester.SendRequest(ctx, reference, "GetPublicKey", []interface{}{})
if err != nil {
return nil, errors.Wrap(err, "[ getMemberPubKey ] Can't get public key")
}
publicKeyString, err := extractor.PublicKeyResponse(res.(*reply.CallMethod).Result)
if err != nil {
return nil, errors.Wrap(err, "[ getMemberPubKey ] Can't extract response")
}
kp := platformpolicy.NewKeyProcessor()
publicKey, err = kp.ImportPublicKeyPEM([]byte(publicKeyString))
if err != nil {
return nil, errors.Wrap(err, "Failed to convert public key")
}
ar.cacheLock.Lock()
ar.keyCache[ref] = publicKey
ar.cacheLock.Unlock()
return publicKey, nil
}