-
Notifications
You must be signed in to change notification settings - Fork 0
/
endpointconfig.go
1854 lines (1528 loc) · 56.3 KB
/
endpointconfig.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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright SecureKey Technologies Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package fab
import (
// "crypto/tls"
// "crypto/x509"
"reflect"
"regexp"
"strconv"
"strings"
"time"
"github.com/jxu86/fabric-sdk-go-gm/pkg/common/errors/multi"
"github.com/jxu86/fabric-sdk-go-gm/pkg/common/errors/retry"
"github.com/jxu86/fabric-sdk-go-gm/pkg/common/errors/status"
"github.com/jxu86/fabric-sdk-go-gm/pkg/common/logging"
"github.com/jxu86/fabric-sdk-go-gm/pkg/common/providers/core"
"github.com/jxu86/fabric-sdk-go-gm/pkg/common/providers/fab"
commtls "github.com/jxu86/fabric-sdk-go-gm/pkg/core/config/comm/tls"
"github.com/jxu86/fabric-sdk-go-gm/pkg/core/config/cryptoutil"
"github.com/jxu86/fabric-sdk-go-gm/pkg/core/config/endpoint"
"github.com/jxu86/fabric-sdk-go-gm/pkg/core/config/lookup"
"github.com/jxu86/fabric-sdk-go-gm/pkg/core/cryptosuite"
"github.com/jxu86/fabric-sdk-go-gm/pkg/util/pathvar"
"github.com/mitchellh/mapstructure"
"github.com/pkg/errors"
grpcCodes "google.golang.org/grpc/codes"
"github.com/jxu86/fabric-sdk-go-gm/third_party/github.com/tjfoc/gmsm/sm2"
tls "github.com/jxu86/fabric-sdk-go-gm/third_party/github.com/tjfoc/gmtls"
)
var logger = logging.NewLogger("fabsdk/fab")
var defaultOrdererListenPort = 7050
var defaultPeerListenPort = 7051
const (
defaultPeerConnectionTimeout = time.Second * 10
defaultPeerResponseTimeout = time.Minute * 3
defaultDiscoveryGreylistExpiryTimeout = time.Second * 10
defaultEventRegTimeout = time.Second * 15
defaultOrdererConnectionTimeout = time.Second * 15
defaultOrdererResponseTimeout = time.Minute * 2
defaultQueryTimeout = time.Minute * 3
defaultExecuteTimeout = time.Minute * 3
defaultResMgmtTimeout = time.Minute * 3
defaultDiscoveryConnectionTimeout = time.Second * 15
defaultDiscoveryResponseTimeout = time.Second * 15
defaultConnIdleInterval = time.Second * 30
defaultEventServiceIdleInterval = time.Minute * 2
defaultChannelConfigRefreshInterval = time.Second * 90
defaultChannelMemshpRefreshInterval = time.Second * 60
defaultDiscoveryRefreshInterval = time.Second * 5
defaultSelectionRefreshInterval = time.Second * 5
defaultCacheSweepInterval = time.Second * 15
defaultResolverStrategy = fab.PreferOrgStrategy
defaultMinBlockHeightResolverMode = fab.ResolveByThreshold
defaultBalancer = fab.Random
defaultBlockHeightLagThreshold = 5
defaultReconnectBlockHeightLagThreshold = 10
defaultPeerMonitor = "" // The peer monitor will be enabled if necessary
defaultPeerMonitorPeriod = 5 * time.Second
//default grpc opts
defaultKeepAliveTime = 0
defaultKeepAliveTimeout = time.Second * 20
defaultKeepAlivePermit = false
defaultFailFast = false
defaultAllowInsecure = false
defaultMaxTargets = 2
defaultMinResponses = 1
defaultEntity = "_default"
)
var (
defaultDiscoveryRetryableCodes = map[status.Group][]status.Code{
status.GRPCTransportStatus: {
status.Code(grpcCodes.Unavailable),
},
status.DiscoveryServerStatus: {
status.QueryEndorsers,
},
}
defaultDiscoveryRetryOpts = retry.Opts{
Attempts: 6,
InitialBackoff: 500 * time.Millisecond,
MaxBackoff: 5 * time.Second,
BackoffFactor: 1.75,
RetryableCodes: defaultDiscoveryRetryableCodes,
}
defaultChannelPolicies = &ChannelPolicies{
QueryChannelConfig: QueryChannelConfigPolicy{
MaxTargets: defaultMaxTargets,
MinResponses: defaultMinResponses,
RetryOpts: retry.Opts{},
},
Discovery: DiscoveryPolicy{
MaxTargets: defaultMaxTargets,
MinResponses: defaultMinResponses,
RetryOpts: defaultDiscoveryRetryOpts,
},
Selection: SelectionPolicy{
SortingStrategy: BlockHeightPriority,
Balancer: Random,
BlockHeightLagThreshold: defaultBlockHeightLagThreshold,
},
EventService: EventServicePolicy{
ResolverStrategy: string(fab.PreferOrgStrategy),
MinBlockHeightResolverMode: string(defaultMinBlockHeightResolverMode),
Balancer: Random,
PeerMonitor: defaultPeerMonitor,
PeerMonitorPeriod: defaultPeerMonitorPeriod,
BlockHeightLagThreshold: defaultBlockHeightLagThreshold,
ReconnectBlockHeightLagThreshold: defaultReconnectBlockHeightLagThreshold,
},
}
)
//ConfigFromBackend returns endpoint config implementation for given backend
func ConfigFromBackend(coreBackend ...core.ConfigBackend) (fab.EndpointConfig, error) {
config := &EndpointConfig{
backend: lookup.New(coreBackend...),
}
if err := config.loadEndpointConfiguration(); err != nil {
return nil, errors.WithMessage(err, "network configuration load failed")
}
//print deprecated warning
detectDeprecatedNetworkConfig(config)
return config, nil
}
// EndpointConfig represents the endpoint configuration for the client
type EndpointConfig struct {
backend *lookup.ConfigLookup
networkConfig *fab.NetworkConfig
tlsCertPool commtls.CertPool
entityMatchers *entityMatchers
peerConfigsByOrg map[string][]fab.PeerConfig
networkPeers []fab.NetworkPeer
ordererConfigs []fab.OrdererConfig
channelPeersByChannel map[string][]fab.ChannelPeer
channelOrderersByChannel map[string][]fab.OrdererConfig
tlsClientCerts []tls.Certificate
peerMatchers []matcherEntry
ordererMatchers []matcherEntry
channelMatchers []matcherEntry
defaultPeerConfig fab.PeerConfig
defaultOrdererConfig fab.OrdererConfig
defaultChannelPolicies fab.ChannelPolicies
defaultChannel *fab.ChannelEndpointConfig
}
//endpointConfigEntity contains endpoint config elements needed by endpointconfig
type endpointConfigEntity struct {
Client ClientConfig
Channels map[string]ChannelEndpointConfig
Organizations map[string]OrganizationConfig
Orderers map[string]OrdererConfig
Peers map[string]PeerConfig
}
//entityMatchers for endpoint configuration
type entityMatchers struct {
matchers map[string][]MatchConfig
}
//matcher entry mapping regex to match config
type matcherEntry struct {
regex *regexp.Regexp
matchConfig MatchConfig
}
// Timeout reads timeouts for the given timeout type, if type is not found in the config
// then default is set as per the const value above for the corresponding type
func (c *EndpointConfig) Timeout(tType fab.TimeoutType) time.Duration {
return c.getTimeout(tType)
}
// OrderersConfig returns a list of defined orderers
func (c *EndpointConfig) OrderersConfig() []fab.OrdererConfig {
return c.ordererConfigs
}
// OrdererConfig returns the requested orderer
func (c *EndpointConfig) OrdererConfig(nameOrURL string) (*fab.OrdererConfig, bool, bool) {
return c.tryMatchingOrdererConfig(nameOrURL, true)
}
// PeersConfig Retrieves the fabric peers for the specified org from the
// config file provided
func (c *EndpointConfig) PeersConfig(org string) ([]fab.PeerConfig, bool) {
peerConfigs, ok := c.peerConfigsByOrg[strings.ToLower(org)]
return peerConfigs, ok
}
// PeerConfig Retrieves a specific peer from the configuration by name or url
func (c *EndpointConfig) PeerConfig(nameOrURL string) (*fab.PeerConfig, bool) {
return c.tryMatchingPeerConfig(nameOrURL, true)
}
// NetworkConfig returns the network configuration defined in the config file
func (c *EndpointConfig) NetworkConfig() *fab.NetworkConfig {
return c.networkConfig
}
// NetworkPeers returns the network peers configuration, all the peers from all the orgs in config.
func (c *EndpointConfig) NetworkPeers() []fab.NetworkPeer {
return c.networkPeers
}
// MappedChannelName will return channelName if it is an original channel name in the config
// if it is not, then it will try to find a channelMatcher and return its MappedName.
// If more than one matcher is found, then the first matcher in the list will be used.
func (c *EndpointConfig) mappedChannelName(networkConfig *fab.NetworkConfig, channelName string) string {
// if channelName is the original key found in the Channels map config, then return it as is
_, ok := networkConfig.Channels[strings.ToLower(channelName)]
if ok {
return channelName
}
// if !ok, then find a channelMatcher for channelName
//Return if no channelMatchers are configured
if len(c.channelMatchers) == 0 {
return defaultEntity
}
//loop over channelMatchers to find the matching channel name
for _, matcher := range c.channelMatchers {
if matcher.regex.MatchString(channelName) {
// get the matching matchConfig from the index number
return matcher.matchConfig.MappedName
}
}
return defaultEntity
}
// ChannelConfig returns the channel configuration
func (c *EndpointConfig) ChannelConfig(name string) *fab.ChannelEndpointConfig {
// get the mapped channel Name
mappedChannelName := c.mappedChannelName(c.networkConfig, name)
if mappedChannelName == defaultEntity {
return c.defaultChannel
}
//look up in network config by channelName
ch, ok := c.networkConfig.Channels[strings.ToLower(mappedChannelName)]
if !ok {
return c.defaultChannel
}
return &ch
}
// ChannelPeers returns the channel peers configuration
func (c *EndpointConfig) ChannelPeers(name string) []fab.ChannelPeer {
//get mapped channel name
mappedChannelName := c.mappedChannelName(c.networkConfig, name)
//look up in dictionary
return c.channelPeersByChannel[strings.ToLower(mappedChannelName)]
}
// ChannelOrderers returns a list of channel orderers
func (c *EndpointConfig) ChannelOrderers(name string) []fab.OrdererConfig {
//get mapped channel name
mappedChannelName := c.mappedChannelName(c.networkConfig, name)
//look up in dictionary
return c.channelOrderersByChannel[strings.ToLower(mappedChannelName)]
}
// TLSCACertPool returns the configured cert pool. If a certConfig
// is provided, the certificate is added to the pool
func (c *EndpointConfig) TLSCACertPool() commtls.CertPool {
return c.tlsCertPool
}
// TLSClientCerts loads the client's certs for mutual TLS
func (c *EndpointConfig) TLSClientCerts() []tls.Certificate {
return c.tlsClientCerts
}
func (c *EndpointConfig) loadPrivateKeyFromConfig(clientConfig *ClientConfig, clientCerts tls.Certificate, cb []byte) ([]tls.Certificate, error) {
kb := clientConfig.TLSCerts.Client.Key.Bytes()
// load the key/cert pair from []byte
clientCerts, err := tls.X509KeyPair(cb, kb)
if err != nil {
return nil, errors.Errorf("Error loading cert/key pair as TLS client credentials: %s", err)
}
logger.Debug("pk read from config successfully")
return []tls.Certificate{clientCerts}, nil
}
// CryptoConfigPath ...
func (c *EndpointConfig) CryptoConfigPath() string {
return pathvar.Subst(c.backend.GetString("client.cryptoconfig.path"))
}
func (c *EndpointConfig) getTimeout(tType fab.TimeoutType) time.Duration { //nolint
var timeout time.Duration
switch tType {
case fab.PeerConnection:
timeout = c.backend.GetDuration("client.peer.timeout.connection")
if timeout == 0 {
timeout = defaultPeerConnectionTimeout
}
case fab.PeerResponse:
timeout = c.backend.GetDuration("client.peer.timeout.response")
if timeout == 0 {
timeout = defaultPeerResponseTimeout
}
case fab.DiscoveryGreylistExpiry:
timeout = c.backend.GetDuration("client.peer.timeout.discovery.greylistExpiry")
if timeout == 0 {
timeout = defaultDiscoveryGreylistExpiryTimeout
}
case fab.EventReg:
timeout = c.backend.GetDuration("client.eventService.timeout.registrationResponse")
if timeout == 0 {
timeout = defaultEventRegTimeout
}
case fab.OrdererConnection:
timeout = c.backend.GetDuration("client.orderer.timeout.connection")
if timeout == 0 {
timeout = defaultOrdererConnectionTimeout
}
case fab.OrdererResponse:
timeout = c.backend.GetDuration("client.orderer.timeout.response")
if timeout == 0 {
timeout = defaultOrdererResponseTimeout
}
case fab.DiscoveryConnection:
timeout = c.backend.GetDuration("client.discovery.timeout.connection")
if timeout == 0 {
timeout = defaultDiscoveryConnectionTimeout
}
case fab.DiscoveryResponse:
timeout = c.backend.GetDuration("client.discovery.timeout.response")
if timeout == 0 {
timeout = defaultDiscoveryResponseTimeout
}
case fab.Query:
timeout = c.backend.GetDuration("client.global.timeout.query")
if timeout == 0 {
timeout = defaultQueryTimeout
}
case fab.Execute:
timeout = c.backend.GetDuration("client.global.timeout.execute")
if timeout == 0 {
timeout = defaultExecuteTimeout
}
case fab.ResMgmt:
timeout = c.backend.GetDuration("client.global.timeout.resmgmt")
if timeout == 0 {
timeout = defaultResMgmtTimeout
}
case fab.ConnectionIdle:
timeout = c.backend.GetDuration("client.global.cache.connectionIdle")
if timeout == 0 {
timeout = defaultConnIdleInterval
}
case fab.EventServiceIdle:
timeout = c.backend.GetDuration("client.global.cache.eventServiceIdle")
if timeout == 0 {
timeout = defaultEventServiceIdleInterval
}
case fab.ChannelConfigRefresh:
timeout = c.backend.GetDuration("client.global.cache.channelConfig")
if timeout == 0 {
timeout = defaultChannelConfigRefreshInterval
}
case fab.ChannelMembershipRefresh:
timeout = c.backend.GetDuration("client.global.cache.channelMembership")
if timeout == 0 {
timeout = defaultChannelMemshpRefreshInterval
}
case fab.DiscoveryServiceRefresh:
timeout = c.backend.GetDuration("client.global.cache.discovery")
if timeout == 0 {
timeout = defaultDiscoveryRefreshInterval
}
case fab.SelectionServiceRefresh:
timeout = c.backend.GetDuration("client.global.cache.selection")
if timeout == 0 {
timeout = defaultSelectionRefreshInterval
}
case fab.CacheSweepInterval: // EXPERIMENTAL - do we need this to be configurable?
timeout = c.backend.GetDuration("client.cache.interval.sweep")
if timeout == 0 {
timeout = defaultCacheSweepInterval
}
}
return timeout
}
func (c *EndpointConfig) loadEndpointConfiguration() error {
endpointConfigurationEntity := endpointConfigEntity{}
err := c.backend.UnmarshalKey("client", &endpointConfigurationEntity.Client)
logger.Debugf("Client is: %+v", endpointConfigurationEntity.Client)
if err != nil {
return errors.WithMessage(err, "failed to parse 'client' config item to endpointConfigurationEntity.Client type")
}
err = c.backend.UnmarshalKey(
"channels", &endpointConfigurationEntity.Channels,
lookup.WithUnmarshalHookFunction(peerChannelConfigHookFunc()),
)
logger.Debugf("channels are: %+v", endpointConfigurationEntity.Channels)
if err != nil {
return errors.WithMessage(err, "failed to parse 'channels' config item to endpointConfigurationEntity.Channels type")
}
err = c.backend.UnmarshalKey("organizations", &endpointConfigurationEntity.Organizations)
logger.Debugf("organizations are: %+v", endpointConfigurationEntity.Organizations)
if err != nil {
return errors.WithMessage(err, "failed to parse 'organizations' config item to endpointConfigurationEntity.Organizations type")
}
err = c.backend.UnmarshalKey("orderers", &endpointConfigurationEntity.Orderers)
logger.Debugf("orderers are: %+v", endpointConfigurationEntity.Orderers)
if err != nil {
return errors.WithMessage(err, "failed to parse 'orderers' config item to endpointConfigurationEntity.Orderers type")
}
err = c.backend.UnmarshalKey("peers", &endpointConfigurationEntity.Peers)
logger.Debugf("peers are: %+v", endpointConfigurationEntity.Peers)
if err != nil {
return errors.WithMessage(err, "failed to parse 'peers' config item to endpointConfigurationEntity.Peers type")
}
//load all endpointconfig entities
err = c.loadEndpointConfigEntities(&endpointConfigurationEntity)
if err != nil {
return errors.WithMessage(err, "failed to load channel configs")
}
return nil
}
func (c *EndpointConfig) loadEndpointConfigEntities(configEntity *endpointConfigEntity) error {
//Compile the entityMatchers
matchError := c.compileMatchers()
if matchError != nil {
return matchError
}
//load all TLS configs, before building any network config
err := c.loadAllTLSConfig(configEntity)
if err != nil {
return errors.WithMessage(err, "failed to load network TLSConfig")
}
//load default configs
err = c.loadDefaultConfigItems(configEntity)
if err != nil {
return errors.WithMessage(err, "failed to network config")
}
//load network config
err = c.loadNetworkConfig(configEntity)
if err != nil {
return errors.WithMessage(err, "failed to network config")
}
//load peer configs by org dictionary
c.loadPeerConfigsByOrg()
//load network peers
c.loadNetworkPeers()
//load orderer configs
err = c.loadOrdererConfigs()
if err != nil {
return errors.WithMessage(err, "failed to load orderer configs")
}
//load channel peers
err = c.loadChannelPeers()
if err != nil {
return errors.WithMessage(err, "failed to load channel peers")
}
//load channel orderers
err = c.loadChannelOrderers()
if err != nil {
return errors.WithMessage(err, "failed to load channel orderers")
}
//load tls cert pool
err = c.loadTLSCertPool()
if err != nil {
return errors.WithMessage(err, "failed to load TLS cert pool")
}
c.loadDefaultChannel()
return nil
}
func (c *EndpointConfig) loadDefaultChannel() {
defChCfg, ok := c.networkConfig.Channels[defaultEntity]
if ok {
c.defaultChannel = &fab.ChannelEndpointConfig{Peers: defChCfg.Peers, Orderers: defChCfg.Orderers, Policies: defChCfg.Policies}
delete(c.networkConfig.Channels, defaultEntity)
} else {
logger.Debugf("No default config. Returning hard-coded defaults.")
c.defaultChannel = &fab.ChannelEndpointConfig{Policies: c.getChannelPolicies(defaultChannelPolicies)}
}
}
func (c *EndpointConfig) loadDefaultConfigItems(configEntity *endpointConfigEntity) error {
//default orderer config
err := c.loadDefaultOrderer(configEntity)
if err != nil {
return errors.WithMessage(err, "failed to load default orderer")
}
//default peer config
err = c.loadDefaultPeer(configEntity)
if err != nil {
return errors.WithMessage(err, "failed to load default peer")
}
//default channel policies
c.loadDefaultChannelPolicies(configEntity)
return nil
}
func (c *EndpointConfig) loadNetworkConfig(configEntity *endpointConfigEntity) error {
networkConfig := fab.NetworkConfig{}
//Channels
networkConfig.Channels = make(map[string]fab.ChannelEndpointConfig)
// Load default channel config first since it will be used for defaulting other channels peers and orderers
defChNwCfg, ok := configEntity.Channels[defaultEntity]
if ok {
networkConfig.Channels[defaultEntity] = c.loadChannelEndpointConfig(defChNwCfg, ChannelEndpointConfig{})
} else {
networkConfig.Channels[defaultEntity] = fab.ChannelEndpointConfig{Policies: c.getChannelPolicies(defaultChannelPolicies)}
}
for chID, chNwCfg := range configEntity.Channels {
if chID == defaultEntity {
// default entity has been loaded already
continue
}
networkConfig.Channels[chID] = c.loadChannelEndpointConfig(chNwCfg, defChNwCfg)
}
//Organizations
networkConfig.Organizations = make(map[string]fab.OrganizationConfig)
for orgName, orgConfig := range configEntity.Organizations {
tlsKeyCertPairs := make(map[string]fab.CertKeyPair)
for user, tlsKeyPair := range orgConfig.Users {
tlsKeyCertPairs[user] = fab.CertKeyPair{
Cert: tlsKeyPair.Cert.Bytes(),
Key: tlsKeyPair.Key.Bytes(),
}
}
networkConfig.Organizations[orgName] = fab.OrganizationConfig{
MSPID: orgConfig.MSPID,
CryptoPath: orgConfig.CryptoPath,
Peers: orgConfig.Peers,
CertificateAuthorities: orgConfig.CertificateAuthorities,
Users: tlsKeyCertPairs,
}
}
//Orderers
err := c.loadAllOrdererConfigs(&networkConfig, configEntity.Orderers)
if err != nil {
return err
}
//Peers
err = c.loadAllPeerConfigs(&networkConfig, configEntity.Peers)
if err != nil {
return err
}
c.networkConfig = &networkConfig
return nil
}
func (c *EndpointConfig) loadChannelEndpointConfig(chNwCfg ChannelEndpointConfig, defChNwCfg ChannelEndpointConfig) fab.ChannelEndpointConfig {
chPeers := make(map[string]fab.PeerChannelConfig)
chNwCfgPeers := chNwCfg.Peers
if len(chNwCfgPeers) == 0 {
//fill peers in with default channel peers
chNwCfgPeers = defChNwCfg.Peers
}
for chPeer, chPeerCfg := range chNwCfgPeers {
if c.isPeerToBeIgnored(chPeer) {
//filter peer to be ignored
continue
}
chPeers[chPeer] = fab.PeerChannelConfig{
EndorsingPeer: chPeerCfg.EndorsingPeer,
ChaincodeQuery: chPeerCfg.ChaincodeQuery,
LedgerQuery: chPeerCfg.LedgerQuery,
EventSource: chPeerCfg.EventSource,
}
}
chOrderers := []string{}
chNwCfgOrderers := chNwCfg.Orderers
if len(chNwCfgOrderers) == 0 {
//fill orderers in with default channel orderers
chNwCfgOrderers = defChNwCfg.Orderers
}
for _, name := range chNwCfgOrderers {
if !c.isOrdererToBeIgnored(name) {
//filter orderer to be ignored
chOrderers = append(chOrderers, name)
}
}
// Policies use default channel policies if info is missing
return fab.ChannelEndpointConfig{
Peers: chPeers,
Orderers: chOrderers,
Policies: c.addMissingChannelPoliciesItems(chNwCfg),
}
}
func (c *EndpointConfig) getChannelPolicies(policies *ChannelPolicies) fab.ChannelPolicies {
discoveryPolicy := fab.DiscoveryPolicy{
MaxTargets: policies.Discovery.MaxTargets,
MinResponses: policies.Discovery.MinResponses,
RetryOpts: policies.Discovery.RetryOpts,
}
selectionPolicy := fab.SelectionPolicy{
SortingStrategy: fab.SelectionSortingStrategy(policies.Selection.SortingStrategy),
Balancer: fab.BalancerType(policies.Selection.Balancer),
BlockHeightLagThreshold: policies.Selection.BlockHeightLagThreshold,
}
channelCfgPolicy := fab.QueryChannelConfigPolicy{
MaxTargets: policies.QueryChannelConfig.MaxTargets,
MinResponses: policies.QueryChannelConfig.MinResponses,
RetryOpts: policies.QueryChannelConfig.RetryOpts,
}
eventServicePolicy := fab.EventServicePolicy{
ResolverStrategy: fab.ResolverStrategy(policies.EventService.ResolverStrategy),
MinBlockHeightResolverMode: fab.MinBlockHeightResolverMode(policies.EventService.MinBlockHeightResolverMode),
Balancer: fab.BalancerType(policies.EventService.Balancer),
BlockHeightLagThreshold: policies.EventService.BlockHeightLagThreshold,
PeerMonitor: fab.EnabledDisabled(policies.EventService.PeerMonitor),
ReconnectBlockHeightLagThreshold: policies.EventService.ReconnectBlockHeightLagThreshold,
PeerMonitorPeriod: policies.EventService.PeerMonitorPeriod,
}
return fab.ChannelPolicies{
Discovery: discoveryPolicy,
Selection: selectionPolicy,
QueryChannelConfig: channelCfgPolicy,
EventService: eventServicePolicy,
}
}
func (c *EndpointConfig) addMissingChannelPoliciesItems(chNwCfg ChannelEndpointConfig) fab.ChannelPolicies {
policies := c.getChannelPolicies(&chNwCfg.Policies)
policies.Discovery = c.addMissingDiscoveryPolicyInfo(policies.Discovery)
policies.Selection = c.addMissingSelectionPolicyInfo(policies.Selection)
policies.QueryChannelConfig = c.addMissingQueryChannelConfigPolicyInfo(policies.QueryChannelConfig)
policies.EventService = c.addMissingEventServicePolicyInfo(policies.EventService)
return policies
}
func (c *EndpointConfig) addMissingDiscoveryPolicyInfo(policy fab.DiscoveryPolicy) fab.DiscoveryPolicy {
if policy.MaxTargets == 0 {
policy.MaxTargets = c.defaultChannelPolicies.Discovery.MaxTargets
}
if policy.MinResponses == 0 {
policy.MinResponses = c.defaultChannelPolicies.Discovery.MinResponses
}
if isEmpty(policy.RetryOpts) {
policy.RetryOpts = c.defaultChannelPolicies.Discovery.RetryOpts
} else {
policy.RetryOpts = addMissingRetryOpts(policy.RetryOpts, c.defaultChannelPolicies.Discovery.RetryOpts)
}
return policy
}
func (c *EndpointConfig) addMissingSelectionPolicyInfo(policy fab.SelectionPolicy) fab.SelectionPolicy {
if policy.SortingStrategy == "" {
policy.SortingStrategy = c.defaultChannelPolicies.Selection.SortingStrategy
}
if policy.Balancer == "" {
policy.Balancer = c.defaultChannelPolicies.Selection.Balancer
}
if policy.BlockHeightLagThreshold == 0 {
policy.BlockHeightLagThreshold = defaultBlockHeightLagThreshold
}
return policy
}
func (c *EndpointConfig) addMissingQueryChannelConfigPolicyInfo(policy fab.QueryChannelConfigPolicy) fab.QueryChannelConfigPolicy {
if policy.MaxTargets == 0 {
policy.MaxTargets = c.defaultChannelPolicies.QueryChannelConfig.MaxTargets
}
if policy.MinResponses == 0 {
policy.MinResponses = c.defaultChannelPolicies.QueryChannelConfig.MinResponses
}
if isEmpty(policy.RetryOpts) {
policy.RetryOpts = c.defaultChannelPolicies.QueryChannelConfig.RetryOpts
} else {
policy.RetryOpts = addMissingRetryOpts(policy.RetryOpts, c.defaultChannelPolicies.QueryChannelConfig.RetryOpts)
}
return policy
}
func (c *EndpointConfig) addMissingEventServicePolicyInfo(policy fab.EventServicePolicy) fab.EventServicePolicy {
if policy.Balancer == "" {
policy.Balancer = c.defaultChannelPolicies.EventService.Balancer
}
if policy.BlockHeightLagThreshold == 0 {
policy.BlockHeightLagThreshold = c.defaultChannelPolicies.EventService.BlockHeightLagThreshold
}
if policy.ResolverStrategy == "" {
policy.ResolverStrategy = c.defaultChannelPolicies.EventService.ResolverStrategy
}
if policy.MinBlockHeightResolverMode == "" {
policy.MinBlockHeightResolverMode = c.defaultChannelPolicies.EventService.MinBlockHeightResolverMode
}
if policy.PeerMonitor == "" {
policy.PeerMonitor = c.defaultChannelPolicies.EventService.PeerMonitor
}
if policy.ReconnectBlockHeightLagThreshold == 0 {
policy.ReconnectBlockHeightLagThreshold = c.defaultChannelPolicies.EventService.ReconnectBlockHeightLagThreshold
}
if policy.PeerMonitorPeriod == 0 {
policy.PeerMonitorPeriod = c.defaultChannelPolicies.EventService.PeerMonitorPeriod
}
return policy
}
func addMissingRetryOpts(opts retry.Opts, defaultOpts retry.Opts) retry.Opts {
// If retry opts are defined then Attempts must be defined, otherwise
// we cannot distinguish between default 0 and intentional 0 to disable retries for that channel
empty := retry.Opts{}
if opts.InitialBackoff == empty.InitialBackoff {
opts.InitialBackoff = defaultOpts.InitialBackoff
}
if opts.BackoffFactor == empty.BackoffFactor {
opts.BackoffFactor = defaultOpts.BackoffFactor
}
if opts.MaxBackoff == empty.MaxBackoff {
opts.MaxBackoff = defaultOpts.MaxBackoff
}
if len(opts.RetryableCodes) == len(empty.RetryableCodes) {
opts.RetryableCodes = defaultOpts.RetryableCodes
}
return opts
}
func isEmpty(opts retry.Opts) bool {
empty := retry.Opts{}
if opts.Attempts == empty.Attempts &&
opts.InitialBackoff == empty.InitialBackoff &&
opts.BackoffFactor == empty.BackoffFactor &&
opts.MaxBackoff == empty.MaxBackoff &&
len(opts.RetryableCodes) == len(empty.RetryableCodes) {
return true
}
return false
}
func (c *EndpointConfig) loadAllPeerConfigs(networkConfig *fab.NetworkConfig, entityPeers map[string]PeerConfig) error {
networkConfig.Peers = make(map[string]fab.PeerConfig)
for name, peerConfig := range entityPeers {
if name == defaultEntity || c.isPeerToBeIgnored(name) {
//filter default and ignored peers
continue
}
tlsCert, _, err := peerConfig.TLSCACerts.TLSCert()
if err != nil {
return errors.WithMessage(err, "failed to load peer network config")
}
networkConfig.Peers[name] = c.addMissingPeerConfigItems(name, fab.PeerConfig{
URL: peerConfig.URL,
GRPCOptions: peerConfig.GRPCOptions,
TLSCACert: tlsCert,
})
}
return nil
}
func (c *EndpointConfig) loadAllOrdererConfigs(networkConfig *fab.NetworkConfig, entityOrderers map[string]OrdererConfig) error {
networkConfig.Orderers = make(map[string]fab.OrdererConfig)
for name, ordererConfig := range entityOrderers {
if name == defaultEntity || c.isOrdererToBeIgnored(name) {
//filter default and ignored orderers
continue
}
tlsCert, _, err := ordererConfig.TLSCACerts.TLSCert()
if err != nil {
return errors.WithMessage(err, "failed to load orderer network config")
}
networkConfig.Orderers[name] = c.addMissingOrdererConfigItems(name, fab.OrdererConfig{
URL: ordererConfig.URL,
GRPCOptions: ordererConfig.GRPCOptions,
TLSCACert: tlsCert,
})
}
return nil
}
func (c *EndpointConfig) addMissingPeerConfigItems(name string, config fab.PeerConfig) fab.PeerConfig {
// peer URL
if config.URL == "" {
if c.defaultPeerConfig.URL == "" {
config.URL = name + ":" + strconv.Itoa(defaultPeerListenPort)
} else {
config.URL = c.defaultPeerConfig.URL
}
}
//tls ca certs
if config.TLSCACert == nil {
config.TLSCACert = c.defaultPeerConfig.TLSCACert
}
//if no grpc opts found
if len(config.GRPCOptions) == 0 {
config.GRPCOptions = c.defaultPeerConfig.GRPCOptions
return config
}
//missing grpc opts
for name, val := range c.defaultPeerConfig.GRPCOptions {
_, ok := config.GRPCOptions[name]
if !ok {
config.GRPCOptions[name] = val
}
}
return config
}
func (c *EndpointConfig) addMissingOrdererConfigItems(name string, config fab.OrdererConfig) fab.OrdererConfig {
// orderer URL
if config.URL == "" {
if c.defaultOrdererConfig.URL == "" {
config.URL = name + ":" + strconv.Itoa(defaultOrdererListenPort)
} else {
config.URL = c.defaultOrdererConfig.URL
}
}
//tls ca certs
if config.TLSCACert == nil {
config.TLSCACert = c.defaultOrdererConfig.TLSCACert
}
//if no grpc opts found
if len(config.GRPCOptions) == 0 {
config.GRPCOptions = c.defaultOrdererConfig.GRPCOptions
return config
}
//missing grpc opts
for name, val := range c.defaultOrdererConfig.GRPCOptions {
_, ok := config.GRPCOptions[name]
if !ok {
config.GRPCOptions[name] = val
}
}
return config
}
func (c *EndpointConfig) loadDefaultOrderer(configEntity *endpointConfigEntity) error {
defaultEntityOrderer, ok := configEntity.Orderers[defaultEntity]
if !ok {
defaultEntityOrderer = OrdererConfig{
GRPCOptions: make(map[string]interface{}),
}
}
c.defaultOrdererConfig = fab.OrdererConfig{
GRPCOptions: defaultEntityOrderer.GRPCOptions,
}
//set defaults for missing grpc opts
//keep-alive-time
_, ok = c.defaultOrdererConfig.GRPCOptions["keep-alive-time"]
if !ok {
c.defaultOrdererConfig.GRPCOptions["keep-alive-time"] = defaultKeepAliveTime
}
//keep-alive-timeout
_, ok = c.defaultOrdererConfig.GRPCOptions["keep-alive-timeout"]
if !ok {
c.defaultOrdererConfig.GRPCOptions["keep-alive-timeout"] = defaultKeepAliveTimeout
}
//keep-alive-permit
_, ok = c.defaultOrdererConfig.GRPCOptions["keep-alive-permit"]
if !ok {
c.defaultOrdererConfig.GRPCOptions["keep-alive-permit"] = defaultKeepAlivePermit
}
//fail-fast
_, ok = c.defaultOrdererConfig.GRPCOptions["fail-fast"]
if !ok {
c.defaultOrdererConfig.GRPCOptions["fail-fast"] = defaultFailFast
}
//allow-insecure
_, ok = c.defaultOrdererConfig.GRPCOptions["allow-insecure"]
if !ok {
c.defaultOrdererConfig.GRPCOptions["allow-insecure"] = defaultAllowInsecure
}
var err error
c.defaultOrdererConfig.TLSCACert, _, err = defaultEntityOrderer.TLSCACerts.TLSCert()
if err != nil {
return errors.WithMessage(err, "failed to load default orderer network config")
}
return nil
}
func (c *EndpointConfig) loadDefaultChannelPolicies(configEntity *endpointConfigEntity) {
var defaultChPolicies fab.ChannelPolicies
defaultChannel, ok := configEntity.Channels[defaultEntity]
if !ok {
defaultChPolicies = c.getChannelPolicies(defaultChannelPolicies)
} else {