-
Notifications
You must be signed in to change notification settings - Fork 29
/
fabconnect.go
203 lines (178 loc) · 5.5 KB
/
fabconnect.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
// Copyright © 2023 Kaleido, Inc.
//
// SPDX-License-Identifier: Apache-2.0
//
// 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 cmd
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
yaml "gopkg.in/yaml.v2"
"github.com/hyperledger/firefly-fabconnect/internal/conf"
"github.com/hyperledger/firefly-fabconnect/internal/rest"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
prefixed "github.com/x-cray/logrus-prefixed-formatter"
)
func initLogging(debugLevel int) {
log.SetFormatter(&prefixed.TextFormatter{
TimestampFormat: "2006-01-02T15:04:05.000Z07:00",
DisableSorting: true,
ForceFormatting: true,
FullTimestamp: true,
})
switch debugLevel {
case 0:
log.SetLevel(log.ErrorLevel)
case 1:
log.SetLevel(log.InfoLevel)
case 2:
log.SetLevel(log.DebugLevel)
case 3:
log.SetLevel(log.TraceLevel)
default:
log.SetLevel(log.DebugLevel)
}
log.Debugf("Log level set to %d", debugLevel)
}
type cmdConfig struct {
DebugLevel int
DebugPort int
PrintYAML bool
Filename string
}
var rootConfig = &cmdConfig{}
func newRootCmd() (*cobra.Command, *conf.RESTGatewayConf) {
restGatewayConf := &conf.RESTGatewayConf{}
var restGateway *rest.Gateway
rootCmd := &cobra.Command{
Use: "fabconnect",
Short: "Connectivity Bridge for Hyperledger Fabric permissioned chains",
PreRunE: func(cmd *cobra.Command, args []string) error {
err := viper.Unmarshal(&restGatewayConf)
if err != nil {
return err
}
// allow tests to assign a mock
if restGateway == nil {
restGateway = rest.NewRESTGateway(restGatewayConf)
}
err = restGateway.ValidateConf()
if err != nil {
return err
}
err = restGateway.Init()
if err != nil {
return err
}
initLogging(rootConfig.DebugLevel)
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
if rootConfig.DebugPort > 0 {
router := NewDebugRouter()
router.addRoutes()
debugServer := &http.Server{Addr: fmt.Sprintf("127.0.0.1:%d", rootConfig.DebugPort), Handler: router.router, ReadHeaderTimeout: 30 * time.Second}
go func() {
_ = debugServer.ListenAndServe()
}()
log.Infof("Debug HTTP endpoint listening on 127.0.0.1:%d", rootConfig.DebugPort)
defer func() {
log.Infof("Shutting down the debug server")
_ = debugServer.Close()
}()
}
err := startServer(restGatewayConf, restGateway)
if err != nil {
return err
}
return nil
},
}
rootCmd.Flags().IntVarP(&rootConfig.DebugLevel, "debug", "d", 1, "0=error, 1=info, 2=debug")
rootCmd.Flags().IntVarP(&rootConfig.DebugPort, "debugPort", "Z", 0, "Port for pprof HTTP endpoints (localhost only)")
rootCmd.Flags().BoolVarP(&rootConfig.PrintYAML, "print-yaml-confg", "Y", false, "Print YAML config snippet and exit")
rootCmd.Flags().StringVarP(&rootConfig.Filename, "configfile", "f", "", "Configuration file, must be one of .yml, .yaml, or .json")
conf.CobraInit(rootCmd, restGatewayConf)
return rootCmd, restGatewayConf
}
func init() {
cobra.OnInitialize(initConfig)
// all environment variables for the "fabconnect" command will have the "FC" prefix
// e.g "FC_CONFIGFILE"
viper.SetEnvPrefix("FC")
viper.AutomaticEnv()
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
}
func initConfig() {
if rootConfig.Filename != "" {
viper.SetConfigFile(rootConfig.Filename)
if err := viper.ReadInConfig(); err != nil {
log.Infof("Can't read config: %s, will rely on environment variables and command line arguments for required configurations\n", err)
} else {
log.Infof("Using config file: %s\n", viper.ConfigFileUsed())
}
} else {
log.Info("No config file specified, will rely on environment variables and command line arguments for required configurations")
}
}
func startServer(restGatewayConf *conf.RESTGatewayConf, restGateway *rest.Gateway) error {
if rootConfig.PrintYAML {
a, err := marshalToYAML(rootConfig)
if err != nil {
return err
}
b, err := marshalToYAML(restGatewayConf)
if err != nil {
return err
}
print(fmt.Sprintf("# Full YAML configuration processed from supplied file\n%s\n%s\n", string(a), string(b)))
}
serverDone := make(chan bool)
go func(done chan bool) {
log.Info("Starting REST gateway")
if err := restGateway.Start(); err != nil {
log.Errorf("REST gateway failed: %s", err)
}
done <- true
}(serverDone)
// Terminate when ANY routine fails (do not wait for them all to complete)
<-serverDone
return nil
}
// MarshalToYAML marshals a JSON annotated structure into YAML, by first going to JSON
func marshalToYAML(conf interface{}) (yamlBytes []byte, err error) {
var jsonBytes []byte
if jsonBytes, err = json.Marshal(conf); err != nil {
return
}
jsonAsMap := make(map[string]interface{})
if err = json.Unmarshal(jsonBytes, &jsonAsMap); err != nil {
return
}
yamlBytes, err = yaml.Marshal(&jsonAsMap)
return
}
// Execute is called by the main method of the package
func Execute() int {
rootCmd, _ := newRootCmd()
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
return 1
}
return 0
}