-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
220 lines (182 loc) · 7.42 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
210
211
212
213
214
215
216
217
218
219
220
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package main
import (
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
"reflect"
"github.com/golang/protobuf/proto"
_ "github.com/hyperledger/fabric-protos-go/common"
cb "github.com/hyperledger/fabric-protos-go/common" // Import these to register the proto types
_ "github.com/hyperledger/fabric-protos-go/msp"
_ "github.com/hyperledger/fabric-protos-go/orderer"
_ "github.com/hyperledger/fabric-protos-go/orderer/etcdraft"
_ "github.com/hyperledger/fabric-protos-go/peer"
"github.com/hyperledger/fabric/common/flogging"
"github.com/hyperledger/fabric/common/tools/protolator"
"github.com/hyperledger/fabric/internal/configtxlator/metadata"
"github.com/hyperledger/fabric/internal/configtxlator/rest"
"github.com/hyperledger/fabric/internal/configtxlator/update"
"github.com/gorilla/handlers"
"github.com/pkg/errors"
"gopkg.in/alecthomas/kingpin.v2"
)
// command line flags
var (
app = kingpin.New("configtxlator", "Utility for generating Hyperledger Fabric channel configurations")
start = app.Command("start", "Start the configtxlator REST server")
hostname = start.Flag("hostname", "The hostname or IP on which the REST server will listen").Default("0.0.0.0").String()
port = start.Flag("port", "The port on which the REST server will listen").Default("7059").Int()
cors = start.Flag("CORS", "Allowable CORS domains, e.g. '*' or 'www.example.com' (may be repeated).").Strings()
protoEncode = app.Command("proto_encode", "Converts a JSON document to protobuf.")
protoEncodeType = protoEncode.Flag("type", "The type of protobuf structure to encode to. For example, 'common.Config'.").Required().String()
protoEncodeSource = protoEncode.Flag("input", "A file containing the JSON document.").Default(os.Stdin.Name()).File()
protoEncodeDest = protoEncode.Flag("output", "A file to write the output to.").Default(os.Stdout.Name()).OpenFile(os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
protoDecode = app.Command("proto_decode", "Converts a proto message to JSON.")
protoDecodeType = protoDecode.Flag("type", "The type of protobuf structure to decode from. For example, 'common.Config'.").Required().String()
protoDecodeSource = protoDecode.Flag("input", "A file containing the proto message.").Default(os.Stdin.Name()).File()
protoDecodeDest = protoDecode.Flag("output", "A file to write the JSON document to.").Default(os.Stdout.Name()).OpenFile(os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
computeUpdate = app.Command("compute_update", "Takes two marshaled common.Config messages and computes the config update which transitions between the two.")
computeUpdateOriginal = computeUpdate.Flag("original", "The original config message.").File()
computeUpdateUpdated = computeUpdate.Flag("updated", "The updated config message.").File()
computeUpdateChannelID = computeUpdate.Flag("channel_id", "The name of the channel for this update.").Required().String()
computeUpdateDest = computeUpdate.Flag("output", "A file to write the JSON document to.").Default(os.Stdout.Name()).OpenFile(os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
version = app.Command("version", "Show version information")
)
var logger = flogging.MustGetLogger("configtxlator")
func main() {
kingpin.Version("0.0.1")
switch kingpin.MustParse(app.Parse(os.Args[1:])) {
// "start" command
case start.FullCommand():
startServer(fmt.Sprintf("%s:%d", *hostname, *port), *cors)
// "proto_encode" command
case protoEncode.FullCommand():
defer (*protoEncodeSource).Close()
defer (*protoEncodeDest).Close()
err := encodeProto(*protoEncodeType, *protoEncodeSource, *protoEncodeDest)
if err != nil {
app.Fatalf("Error decoding: %s", err)
}
case protoDecode.FullCommand():
defer (*protoDecodeSource).Close()
defer (*protoDecodeDest).Close()
err := decodeProto(*protoDecodeType, *protoDecodeSource, *protoDecodeDest)
if err != nil {
app.Fatalf("Error decoding: %s", err)
}
case computeUpdate.FullCommand():
defer (*computeUpdateOriginal).Close()
defer (*computeUpdateUpdated).Close()
defer (*computeUpdateDest).Close()
err := computeUpdt(*computeUpdateOriginal, *computeUpdateUpdated, *computeUpdateDest, *computeUpdateChannelID)
if err != nil {
app.Fatalf("Error computing update: %s", err)
}
// "version" command
case version.FullCommand():
printVersion()
}
}
func startServer(address string, cors []string) {
var err error
listener, err := net.Listen("tcp", address)
if err != nil {
app.Fatalf("Could not bind to address '%s': %s", address, err)
}
if len(cors) > 0 {
origins := handlers.AllowedOrigins(cors)
// Note, configtxlator only exposes POST APIs for the time being, this
// list will need to be expanded if new non-POST APIs are added
methods := handlers.AllowedMethods([]string{http.MethodPost})
headers := handlers.AllowedHeaders([]string{"Content-Type"})
logger.Infof("Serving HTTP requests on %s with CORS %v", listener.Addr(), cors)
err = http.Serve(listener, handlers.CORS(origins, methods, headers)(rest.NewRouter()))
} else {
logger.Infof("Serving HTTP requests on %s", listener.Addr())
err = http.Serve(listener, rest.NewRouter())
}
app.Fatalf("Error starting server:[%s]\n", err)
}
func printVersion() {
fmt.Println(metadata.GetVersionInfo())
}
func encodeProto(msgName string, input, output *os.File) error {
msgType := proto.MessageType(msgName)
if msgType == nil {
return errors.Errorf("message of type %s unknown", msgType)
}
msg := reflect.New(msgType.Elem()).Interface().(proto.Message)
err := protolator.DeepUnmarshalJSON(input, msg)
if err != nil {
return errors.Wrapf(err, "error decoding input")
}
out, err := proto.Marshal(msg)
if err != nil {
return errors.Wrapf(err, "error marshaling")
}
_, err = output.Write(out)
if err != nil {
return errors.Wrapf(err, "error writing output")
}
return nil
}
func decodeProto(msgName string, input, output *os.File) error {
msgType := proto.MessageType(msgName)
if msgType == nil {
return errors.Errorf("message of type %s unknown", msgType)
}
msg := reflect.New(msgType.Elem()).Interface().(proto.Message)
in, err := ioutil.ReadAll(input)
if err != nil {
return errors.Wrapf(err, "error reading input")
}
err = proto.Unmarshal(in, msg)
if err != nil {
return errors.Wrapf(err, "error unmarshaling")
}
err = protolator.DeepMarshalJSON(output, msg)
if err != nil {
return errors.Wrapf(err, "error encoding output")
}
return nil
}
func computeUpdt(original, updated, output *os.File, channelID string) error {
origIn, err := ioutil.ReadAll(original)
if err != nil {
return errors.Wrapf(err, "error reading original config")
}
origConf := &cb.Config{}
err = proto.Unmarshal(origIn, origConf)
if err != nil {
return errors.Wrapf(err, "error unmarshaling original config")
}
updtIn, err := ioutil.ReadAll(updated)
if err != nil {
return errors.Wrapf(err, "error reading updated config")
}
updtConf := &cb.Config{}
err = proto.Unmarshal(updtIn, updtConf)
if err != nil {
return errors.Wrapf(err, "error unmarshaling updated config")
}
cu, err := update.Compute(origConf, updtConf)
if err != nil {
return errors.Wrapf(err, "error computing config update")
}
cu.ChannelId = channelID
outBytes, err := proto.Marshal(cu)
if err != nil {
return errors.Wrapf(err, "error marshaling computed config update")
}
_, err = output.Write(outBytes)
if err != nil {
return errors.Wrapf(err, "error writing config update to output")
}
return nil
}