-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmain.go
384 lines (304 loc) · 9.96 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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
/*
Copyright IBM Corp. 2017 All Rights Reserved.
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 main
import (
"flag"
"fmt"
"log"
"os"
"os/exec"
"path"
"path/filepath"
"strings"
"text/template"
"github.com/ibm-silvergate/netcomposer/netModel"
"github.com/ibm-silvergate/netcomposer/netSpec"
)
//Flags
var (
specFile string
templatesPath string
outputPath string
)
//Paths
var (
networkPath string
volumesPath string
cryptoConfigPath string
chaincodesPath string
genesisPath string
channelsPath string
networkConfigPath string
)
func readFlags() {
flag.StringVar(&specFile, "spec", "", "spec file e.g. samplenet.yaml")
flag.StringVar(&templatesPath, "templates", "templates", "templates path e.g. ./templates")
flag.StringVar(&outputPath, "output", "out", "tools path e.g. $HOME/HF-networks")
flag.Parse()
if specFile == "" {
fmt.Fprintln(os.Stderr, "spec file must be specified")
os.Exit(1)
}
}
func main() {
readFlags()
netSpec, err := netSpec.LoadFromFile(specFile)
if err != nil {
log.Fatalf("Error loading network spec file: %v", err)
os.Exit(1)
}
netSpec.SetDefaults()
err = netSpec.Validate()
if err != nil {
log.Fatalf("Network spec is NOT valid: %v", err)
}
netModel := netModel.BuildNetModelFrom(netSpec)
err = netModel.Validate()
if err != nil {
log.Fatalf("Network spec is NOT valid: %v", err)
}
createPaths(netModel)
copyChaincodes(netSpec)
genCryptoConfigFile(netSpec)
genCryptoMaterial(netModel, "crypto-config.yaml")
genConfigTXFile(netModel)
genDockerComposeFile(netModel)
genNetworkConfigFile(netModel)
genNetworkConfigForOrgs(netModel)
genGenesisBlock(netModel, genesisPath, "genesis.block")
genChannelConfig(netModel, channelsPath)
genPullImagesScriptFile(netModel)
genProvisionScript(netModel)
}
func createPaths(netModel *netModel.NetModel) {
networkPath = filepath.Join(outputPath, netModel.Name)
volumesPath = filepath.Join(networkPath, "volumes")
cryptoConfigPath = filepath.Join(volumesPath, "crypto-config")
chaincodesPath = filepath.Join(volumesPath, "chaincodes")
genesisPath = filepath.Join(cryptoConfigPath, "genesis")
channelsPath = filepath.Join(cryptoConfigPath, "channel-artifacts")
networkConfigPath = filepath.Join(volumesPath, "network")
os.MkdirAll(networkPath, 0777)
os.MkdirAll(volumesPath, 0777)
os.MkdirAll(cryptoConfigPath, 0777)
os.MkdirAll(volumesPath, 0777)
os.MkdirAll(chaincodesPath, 0777)
os.MkdirAll(genesisPath, 0777)
os.MkdirAll(channelsPath, 0777)
os.MkdirAll(networkConfigPath, 0777)
}
func genCryptoConfigFile(spec *netSpec.NetSpec) {
fmt.Print("Generating crypto config file: ")
cryptoConfigTemplate := loadTemplate("crypto-config-template.yaml")
panicOnError(execTemplate(cryptoConfigTemplate, spec, networkPath, "crypto-config.yaml"))
fmt.Println("SUCCEED")
}
func genConfigTXFile(netModel *netModel.NetModel) {
fmt.Print("Generating configTX file: ")
configTXTemplate := loadTemplate("configtx-template.yaml")
panicOnError(execTemplate(configTXTemplate, netModel, networkPath, "configtx.yaml"))
fmt.Println("SUCCEED")
}
func genDockerComposeFile(netModel *netModel.NetModel) {
fmt.Print("Generating docker compose file: ")
dockerComposeTemplate := loadTemplate("docker-compose-template.yaml")
panicOnError(execTemplate(dockerComposeTemplate, netModel, networkPath, "docker-compose.yaml"))
fmt.Println("SUCCEED")
}
func genNetworkConfigFile(netModel *netModel.NetModel) {
fmt.Print("Generating network config file: ")
networkConfigTemplate := loadTemplate("network-config-template.yaml")
panicOnError(execTemplate(networkConfigTemplate, netModel, networkConfigPath, "network-config.yaml"))
fmt.Println("SUCCEED")
}
func genNetworkConfigForOrgs(netModel *netModel.NetModel) {
networkConfigTemplate := loadTemplate("network-config-org-template.yaml")
for _, org := range netModel.PeerOrganizations {
fmt.Printf("Generating network config for organization %s: ", org.Name)
netClientDef := struct {
Network string
Description string
Organization string
}{
Network: netModel.Name,
Description: netModel.Description,
Organization: org.Name,
}
panicOnError(
execTemplate(
networkConfigTemplate,
netClientDef,
networkConfigPath,
fmt.Sprintf("network-config-%s.yaml", org.Name)))
fmt.Println("SUCCEED")
}
}
func genPullImagesScriptFile(netModel *netModel.NetModel) {
fmt.Print("Generating script to pull fabric docker images: ")
pullImagesTemplate := loadTemplate("pull-docker-images-template.sh")
panicOnError(execTemplate(pullImagesTemplate, netModel, networkPath, "pull-docker-images.sh"))
args := []string{"+x", filepath.Join(filepath.Clean(networkPath), "pull-docker-images.sh")}
cmd := exec.Command("chmod", args...)
if combinedOutput, err := cmd.CombinedOutput(); err != nil {
fmt.Printf("Err: %s\n", err)
fmt.Printf("\tCombined Output: %s\n", combinedOutput)
os.Exit(1)
}
fmt.Println("SUCCEED")
}
func genProvisionScript(netModel *netModel.NetModel) {
fmt.Print("Generating provisioning script: ")
provisionTemplate := loadTemplate("provision-template.sh")
panicOnError(execTemplate(provisionTemplate, netModel, networkPath, "provision.sh"))
args := []string{"+x", filepath.Join(filepath.Clean(networkPath), "provision.sh")}
cmd := exec.Command("chmod", args...)
if combinedOutput, err := cmd.CombinedOutput(); err != nil {
fmt.Printf("Err: %s\n", err)
fmt.Printf("\tCombined Output: %s\n", combinedOutput)
os.Exit(1)
}
fmt.Println("SUCCEED")
}
func fixSKFilename(path string, f os.FileInfo, err error) (e error) {
if strings.HasSuffix(f.Name(), "_sk") {
dir := filepath.Dir(path)
newname := filepath.Join(dir, "secret.key")
os.Rename(path, newname)
}
return
}
func genCryptoMaterial(netModel *netModel.NetModel, cryptoConfigFile string) {
fmt.Print("Generating crypto material: ")
cryptoConfigFilePath := filepath.Join(filepath.Join(outputPath, netModel.Name), cryptoConfigFile)
args := []string{
"generate",
"--config", cryptoConfigFilePath,
"--output", cryptoConfigPath,
}
if err := exec.Command(fmt.Sprintf("cryptogen"), args...).Run(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
/* Fix naming from cryptogen tool
* Rename private key files ending in "_sk" to "secret.key" for easier configuration in templates
*/
filepath.Walk(filepath.Join(volumesPath, "crypto-config"), fixSKFilename)
fmt.Println("SUCCEED")
}
func genGenesisBlock(netModel *netModel.NetModel, genesisPath, genesisFile string) {
fmt.Print("Generating genesis block: ")
args := []string{
"-profile", netModel.Name + "Genesis", //netmodel.Name is the "network" in yaml
"-outputBlock", filepath.Join(genesisPath, genesisFile),
}
cmd := exec.Command(fmt.Sprintf("configtxgen"), args...)
netPath, _ := filepath.Abs(networkPath)
cmd.Env = append(cmd.Env, fmt.Sprintf("FABRIC_CFG_PATH=%s", netPath))
if combinedOutput, err := cmd.CombinedOutput(); err != nil {
fmt.Printf("Err: %s\n", err)
fmt.Printf("\tCombined Output: %s\n", combinedOutput)
os.Exit(1)
}
fmt.Println("SUCCEED")
}
func genChannelConfig(netModel *netModel.NetModel, channelsPath string) {
for _, ch := range netModel.Channels {
fmt.Printf("Generating config for channel %s: ", ch.Name)
args := []string{
"-profile", ch.Name,
"-outputCreateChannelTx", filepath.Join(channelsPath, fmt.Sprintf("%s.tx", ch.Name)),
"-channelID", ch.Name,
}
cmd := exec.Command(fmt.Sprintf("configtxgen"), args...)
netPath, _ := filepath.Abs(networkPath)
cmd.Env = append(cmd.Env, fmt.Sprintf("FABRIC_CFG_PATH=%s", netPath))
if combinedOutput, err := cmd.CombinedOutput(); err != nil {
fmt.Printf("Err: %s\n", err)
fmt.Printf("\tCombined Output: %s\n", combinedOutput)
os.Exit(1)
}
fmt.Println("SUCCEED")
}
}
func copyChaincodes(spec *netSpec.NetSpec) {
if spec.ChaincodesPath != "" {
fmt.Printf("Copying chaincodes to %s: ", chaincodesPath)
copyFolder(spec.ChaincodesPath, chaincodesPath)
fmt.Println("SUCCEED")
} else {
fmt.Println("Chaincodes path was not specified, no chaincode will be included into peer containers")
}
}
func copyFolder(sPath, dPath string) {
sourcePath := os.ExpandEnv(sPath)
_, err := os.Stat(sourcePath)
if err != nil {
os.Exit(1)
}
destinationPath, err := filepath.Abs(dPath)
if err != nil {
os.Exit(1)
}
cpArgs := []string{"-r", sourcePath, destinationPath}
cmd := exec.Command("cp", cpArgs...)
if combinedOutput, err := cmd.CombinedOutput(); err != nil {
fmt.Printf("Err: %s\n", err)
fmt.Printf("\tCombined Output: %s\n", combinedOutput)
os.Exit(1)
}
}
func loadTemplate(templateFile string) *template.Template {
templateFilePath := path.Join(templatesPath, templateFile)
fm := template.FuncMap{
"Sequence": sequence,
"ToLower": strings.ToLower,
"Inc": inc,
}
t, err := template.New(templateFile).Funcs(fm).ParseFiles(templateFilePath)
if err != nil {
log.Fatalln(err)
}
return t
}
func sequence(start, end int) (stream chan int) {
stream = make(chan int)
go func() {
for i := start; i <= end; i++ {
stream <- i
}
close(stream)
}()
return
}
func inc(val int) int {
return val + 1
}
func execTemplate(t *template.Template, model interface{}, targetPath string, targetFile string) error {
path := filepath.Join(targetPath, targetFile)
f, err := os.Create(filepath.Clean(path))
if err != nil {
log.Println("Error creating file: ", err)
return err
}
err = t.Execute(f, model)
if err != nil {
log.Println("Error executing template: ", err)
return err
}
return nil
}
func panicOnError(err error) {
if err != nil {
panic(err)
}
}