-
Notifications
You must be signed in to change notification settings - Fork 10
/
create.go
507 lines (451 loc) · 12 KB
/
create.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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
package cmd
import (
"fmt"
"os"
"strconv"
"time"
"github.com/AlecAivazis/survey/v2"
"github.com/anyproto/any-sync/accountservice"
"github.com/anyproto/any-sync/util/crypto"
"github.com/spf13/cobra"
"gopkg.in/mgo.v2/bson"
"gopkg.in/yaml.v3"
)
type GeneralNodeConfig struct {
Account accountservice.Config `yaml:"account"`
Drpc struct {
Stream struct {
MaxMsgSizeMb int `yaml:"maxMsgSizeMb"`
} `yaml:"stream"`
} `yaml:"drpc"`
Yamux struct {
ListenAddrs []string `yaml:"listenAddrs"`
WriteTimeoutSec int `yaml:"writeTimeoutSec"`
DialTimeoutSec int `yaml:"dialTimeoutSec"`
} `yaml:"yamux"`
Network Network `yaml:"network"`
NetworkStorePath string `yaml:"networkStorePath"`
}
type CoordinatorNodeConfig struct {
GeneralNodeConfig `yaml:".,inline"`
Mongo struct {
Connect string `yaml:"connect"`
Database string `yaml:"database"`
} `yaml:"mongo"`
SpaceStatus struct {
RunSeconds int `yaml:"runSeconds"`
DeletionPeriodDays int `yaml:"deletionPeriodDays"`
} `yaml:"spaceStatus"`
}
type SyncNodeConfig struct {
GeneralNodeConfig `yaml:".,inline"`
NetworkUpdateIntervalSec int `yaml:"networkUpdateIntervalSec"`
Space struct {
GcTTL int `yaml:"gcTTL"`
SyncPeriod int `yaml:"syncPeriod"`
} `yaml:"space"`
Storage struct {
Path string `yaml:"path"`
} `yaml:"storage"`
NodeSync struct {
HotSync struct {
SimultaneousRequests int `yaml:"simultaneousRequests"`
} `yaml:"hotSync"`
SyncOnStart bool `yaml:"syncOnStart"`
PeriodicSyncHours int `yaml:"periodicSyncHours"`
} `yaml:"nodeSync"`
Log struct {
Production bool `yaml:"production"`
DefaultLevel string `yaml:"defaultLevel"`
NamedLevels struct {
} `yaml:"namedLevels"`
} `yaml:"log"`
}
type FileNodeConfig struct {
GeneralNodeConfig `yaml:".,inline"`
NetworkUpdateIntervalSec int `yaml:"networkUpdateIntervalSec"`
S3Store struct {
Endpoint string `yaml:"endpoint,omitempty"`
Region string `yaml:"region"`
Profile string `yaml:"profile"`
Bucket string `yaml:"bucket"`
MaxThreads int `yaml:"maxThreads"`
} `yaml:"s3Store"`
Redis struct {
IsCluster bool `yaml:"isCluster"`
URL string `yaml:"url"`
} `yaml:"redis"`
}
type Node struct {
PeerID string `yaml:"peerId"`
Addresses []string `yaml:"addresses"`
Types []string `yaml:"types"`
}
type HeartConfig struct {
NetworkID string `yaml:"networkId"`
Nodes []Node `yaml:"nodes"`
}
type Network struct {
ID string `yaml:"id"`
HeartConfig `yaml:".,inline"`
CreationTime time.Time `yaml:"creationTime"`
}
var create = &cobra.Command{
Use: "create",
Short: "Creates new network configuration",
Run: func(cmd *cobra.Command, args []string) {
// Create Network
fmt.Println("Creating network...")
netKey, _, _ := crypto.GenerateRandomEd25519KeyPair()
network = Network{
HeartConfig: HeartConfig{
Nodes: []Node{},
},
}
network.ID = bson.NewObjectId().Hex()
network.NetworkID = netKey.GetPublic().Network()
network.CreationTime = time.Now()
fmt.Println("\033[1m Network ID:\033[0m", network.NetworkID)
// Create coordinator node
fmt.Println("\nCreating coordinator node...")
var coordinatorQs = []*survey.Question{
{
Name: "address",
Prompt: &survey.Input{
Message: "Any-Sync Coordinator Node address",
Default: "127.0.0.1:4830",
},
Validate: survey.Required,
},
{
Name: "mongoConnect",
Prompt: &survey.Input{
Message: "Mongo connect URI",
Default: "mongodb://localhost:27017",
},
Validate: survey.Required,
},
{
Name: "mongoDB",
Prompt: &survey.Input{
Message: "Mongo database name",
Default: "coordinator",
},
Validate: survey.Required,
},
}
answers := struct {
Address string
MongoConnect string
MongoDB string
}{}
err := survey.Ask(coordinatorQs, &answers)
if err != nil {
fmt.Println(err.Error())
return
}
coordinatorNode := defaultCoordinatorNode()
coordinatorNode.Yamux.ListenAddrs = append(coordinatorNode.Yamux.ListenAddrs, answers.Address)
coordinatorNode.Mongo.Connect = answers.MongoConnect
coordinatorNode.Mongo.Database = answers.MongoDB
coordinatorNode.Account = generateAccount()
coordinatorNode.Account.SigningKey, _ = crypto.EncodeKeyToString(netKey)
addToNetwork(coordinatorNode.GeneralNodeConfig, "coordinator")
createSyncNode()
createFileNode()
lastStepOptions()
// Create configurations for all nodes
fmt.Println("\nCreating config file...")
coordinatorNode.Network = network
createConfigFile(coordinatorNode, "coordinator")
for i, syncNode := range syncNodes {
syncNode.Network = network
createConfigFile(syncNode, "sync_"+strconv.Itoa(i+1))
}
for i, fileNode := range fileNodes {
fileNode.Network = network
createConfigFile(fileNode, "file_"+strconv.Itoa(i+1))
}
createConfigFile(network.HeartConfig, "heart")
fmt.Println("Done!")
},
}
var network = Network{}
func addToNetwork(node GeneralNodeConfig, nodeType string) {
network.Nodes = append(network.Nodes, Node{
PeerID: node.Account.PeerId,
Addresses: node.Yamux.ListenAddrs,
Types: []string{nodeType},
})
}
var syncNodePort = "4430"
var syncNodes = []SyncNodeConfig{}
func createSyncNode() {
fmt.Println("\nCreating sync node...")
var syncQs = []*survey.Question{
{
Name: "address",
Prompt: &survey.Input{
Message: "Any-Sync Node address",
Default: "127.0.0.1:" + syncNodePort,
},
Validate: survey.Required,
},
}
answers := struct {
Address string
}{}
err := survey.Ask(syncQs, &answers)
if err != nil {
fmt.Println(err.Error())
return
}
syncNode := defaultSyncNode()
syncNode.Yamux.ListenAddrs = append(syncNode.Yamux.ListenAddrs, answers.Address)
syncNode.Account = generateAccount()
addToNetwork(syncNode.GeneralNodeConfig, "tree")
syncNodes = append(syncNodes, syncNode)
// Increase sync node port
port_num, _ := strconv.ParseInt(syncNodePort, 10, 0)
port_num += 1
syncNodePort = strconv.FormatInt(port_num, 10)
}
var fileNodePort = "4730"
var fileNodes = []FileNodeConfig{}
func createFileNode() {
fmt.Println("\nCreating file node...")
var fileQs = []*survey.Question{
{
Name: "address",
Prompt: &survey.Input{
Message: "Any-Sync File Node address",
Default: "127.0.0.1:" + fileNodePort,
},
Validate: survey.Required,
},
{
Name: "s3Endpoint",
Prompt: &survey.Input{
Message: "S3 Endpoint",
// Default: "",
Help: "Required only in the case you self-host S3-compatible object storage",
},
},
{
Name: "s3Region",
Prompt: &survey.Input{
Message: "S3 Region",
Default: "eu-central-1",
},
Validate: survey.Required,
},
{
Name: "s3Profile",
Prompt: &survey.Input{
Message: "S3 Profile",
Default: "default",
},
Validate: survey.Required,
},
{
Name: "s3Bucket",
Prompt: &survey.Input{
Message: "S3 Bucket",
Default: "any-sync-files",
},
Validate: survey.Required,
},
{
Name: "redisURL",
Prompt: &survey.Input{
Message: "Redis URL",
Default: "redis://127.0.0.1:6379/?dial_timeout=3&db=1&read_timeout=6s&max_retries=2",
},
Validate: survey.Required,
},
{
Name: "redisCluster",
Prompt: &survey.Select{
Message: "Is your redis installation a cluster?",
Options: []string{"true", "false"},
Default: "false",
},
Validate: survey.Required,
},
}
answers := struct {
Address string
S3Endpoint string
S3Region string
S3Profile string
S3Bucket string
RedisURL string
RedisCluster string
}{}
err := survey.Ask(fileQs, &answers)
if err != nil {
fmt.Println(err.Error())
return
}
fileNode := defaultFileNode()
fileNode.Yamux.ListenAddrs = append(fileNode.Yamux.ListenAddrs, answers.Address)
fileNode.S3Store.Endpoint = answers.S3Endpoint
fileNode.S3Store.Region = answers.S3Region
fileNode.S3Store.Profile = answers.S3Profile
fileNode.S3Store.Bucket = answers.S3Bucket
fileNode.Redis.URL = answers.RedisURL
fileNode.Redis.IsCluster, _ = strconv.ParseBool(answers.RedisCluster)
fileNode.Account = generateAccount()
addToNetwork(fileNode.GeneralNodeConfig, "file")
fileNodes = append(fileNodes, fileNode)
// Increase file node port
port_num, _ := strconv.ParseInt(fileNodePort, 10, 0)
port_num += 1
fileNodePort = strconv.FormatInt(port_num, 10)
}
func lastStepOptions() {
fmt.Println()
prompt := &survey.Select{
Message: "Do you want to add more nodes?",
Options: []string{"No, generate configs", "Add sync-node", "Add file-node"},
Default: "No, generate configs",
}
option := ""
survey.AskOne(prompt, &option, survey.WithValidator(survey.Required))
switch option {
case "Add sync-node":
createSyncNode()
lastStepOptions()
case "Add file-node":
createFileNode()
lastStepOptions()
default:
return
}
}
func generateAccount() accountservice.Config {
signKey, _, _ := crypto.GenerateRandomEd25519KeyPair()
encPeerSignKey, err := crypto.EncodeKeyToString(signKey)
if err != nil {
return accountservice.Config{}
}
peerID := signKey.GetPublic().PeerId()
return accountservice.Config{
PeerId: peerID,
PeerKey: encPeerSignKey,
SigningKey: encPeerSignKey,
}
}
func defaultGeneralNode() GeneralNodeConfig {
return GeneralNodeConfig{
Drpc: struct {
Stream struct {
MaxMsgSizeMb int "yaml:\"maxMsgSizeMb\""
} "yaml:\"stream\""
}{
Stream: struct {
MaxMsgSizeMb int "yaml:\"maxMsgSizeMb\""
}{
MaxMsgSizeMb: 256,
},
},
Yamux: struct {
ListenAddrs []string "yaml:\"listenAddrs\""
WriteTimeoutSec int "yaml:\"writeTimeoutSec\""
DialTimeoutSec int "yaml:\"dialTimeoutSec\""
}{
WriteTimeoutSec: 10,
DialTimeoutSec: 10,
},
NetworkStorePath: ".",
}
}
func defaultCoordinatorNode() CoordinatorNodeConfig {
return CoordinatorNodeConfig{
GeneralNodeConfig: defaultGeneralNode(),
Mongo: struct {
Connect string "yaml:\"connect\""
Database string "yaml:\"database\""
}{},
SpaceStatus: struct {
RunSeconds int "yaml:\"runSeconds\""
DeletionPeriodDays int "yaml:\"deletionPeriodDays\""
}{
RunSeconds: 20,
DeletionPeriodDays: 1,
},
}
}
func defaultSyncNode() SyncNodeConfig {
return SyncNodeConfig{
GeneralNodeConfig: defaultGeneralNode(),
NetworkUpdateIntervalSec: 600,
Space: struct {
GcTTL int "yaml:\"gcTTL\""
SyncPeriod int "yaml:\"syncPeriod\""
}{
GcTTL: 60,
SyncPeriod: 240,
},
Storage: struct {
Path string "yaml:\"path\""
}{
Path: "db",
},
NodeSync: struct {
HotSync struct {
SimultaneousRequests int "yaml:\"simultaneousRequests\""
} "yaml:\"hotSync\""
SyncOnStart bool "yaml:\"syncOnStart\""
PeriodicSyncHours int "yaml:\"periodicSyncHours\""
}{
HotSync: struct {
SimultaneousRequests int "yaml:\"simultaneousRequests\""
}{
SimultaneousRequests: 400,
},
SyncOnStart: true,
PeriodicSyncHours: 2,
},
Log: struct {
Production bool "yaml:\"production\""
DefaultLevel string "yaml:\"defaultLevel\""
NamedLevels struct{} "yaml:\"namedLevels\""
}{
Production: false,
DefaultLevel: "",
NamedLevels: struct{}{},
},
}
}
func defaultFileNode() FileNodeConfig {
return FileNodeConfig{
GeneralNodeConfig: defaultGeneralNode(),
NetworkUpdateIntervalSec: 600,
S3Store: struct {
Endpoint string "yaml:\"endpoint,omitempty\""
Region string "yaml:\"region\""
Profile string "yaml:\"profile\""
Bucket string "yaml:\"bucket\""
MaxThreads int "yaml:\"maxThreads\""
}{
MaxThreads: 16,
},
Redis: struct {
IsCluster bool "yaml:\"isCluster\""
URL string "yaml:\"url\""
}{},
}
}
func createConfigFile(in interface{}, ymlFilename string) {
bytes, err := yaml.Marshal(in)
if err != nil {
panic(fmt.Sprintf("Could not marshal the keys: %v", err))
}
err = os.WriteFile(ymlFilename+".yml", bytes, os.ModePerm)
if err != nil {
panic(fmt.Sprintf("Could not write the config to file: %v", err))
}
}
func init() {
}