forked from hyperledger/fabric
-
Notifications
You must be signed in to change notification settings - Fork 0
/
start.go
1369 lines (1204 loc) · 48 KB
/
start.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 IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package node
import (
"context"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"os"
"os/signal"
"path/filepath"
"sync"
"syscall"
"time"
docker "github.com/fsouza/go-dockerclient"
"github.com/golang/protobuf/proto"
"github.com/hyperledger/fabric-protos-go/common"
cb "github.com/hyperledger/fabric-protos-go/common"
discprotos "github.com/hyperledger/fabric-protos-go/discovery"
pb "github.com/hyperledger/fabric-protos-go/peer"
"github.com/hyperledger/fabric/bccsp/factory"
"github.com/hyperledger/fabric/common/cauthdsl"
ccdef "github.com/hyperledger/fabric/common/chaincode"
"github.com/hyperledger/fabric/common/crypto"
"github.com/hyperledger/fabric/common/crypto/tlsgen"
"github.com/hyperledger/fabric/common/deliver"
"github.com/hyperledger/fabric/common/flogging"
floggingmetrics "github.com/hyperledger/fabric/common/flogging/metrics"
"github.com/hyperledger/fabric/common/grpclogging"
"github.com/hyperledger/fabric/common/grpcmetrics"
"github.com/hyperledger/fabric/common/metadata"
"github.com/hyperledger/fabric/common/metrics"
"github.com/hyperledger/fabric/common/policies"
"github.com/hyperledger/fabric/common/policydsl"
"github.com/hyperledger/fabric/core/aclmgmt"
"github.com/hyperledger/fabric/core/cclifecycle"
"github.com/hyperledger/fabric/core/chaincode"
"github.com/hyperledger/fabric/core/chaincode/accesscontrol"
"github.com/hyperledger/fabric/core/chaincode/extcc"
"github.com/hyperledger/fabric/core/chaincode/lifecycle"
"github.com/hyperledger/fabric/core/chaincode/persistence"
"github.com/hyperledger/fabric/core/chaincode/platforms"
"github.com/hyperledger/fabric/core/committer/txvalidator/plugin"
"github.com/hyperledger/fabric/core/common/ccprovider"
"github.com/hyperledger/fabric/core/common/privdata"
coreconfig "github.com/hyperledger/fabric/core/config"
"github.com/hyperledger/fabric/core/container"
"github.com/hyperledger/fabric/core/container/dockercontroller"
"github.com/hyperledger/fabric/core/container/externalbuilder"
"github.com/hyperledger/fabric/core/deliverservice"
"github.com/hyperledger/fabric/core/dispatcher"
"github.com/hyperledger/fabric/core/endorser"
authHandler "github.com/hyperledger/fabric/core/handlers/auth"
endorsement2 "github.com/hyperledger/fabric/core/handlers/endorsement/api"
endorsement3 "github.com/hyperledger/fabric/core/handlers/endorsement/api/identities"
"github.com/hyperledger/fabric/core/handlers/library"
validation "github.com/hyperledger/fabric/core/handlers/validation/api"
"github.com/hyperledger/fabric/core/ledger"
"github.com/hyperledger/fabric/core/ledger/cceventmgmt"
"github.com/hyperledger/fabric/core/ledger/kvledger"
"github.com/hyperledger/fabric/core/ledger/ledgermgmt"
"github.com/hyperledger/fabric/core/operations"
"github.com/hyperledger/fabric/core/peer"
"github.com/hyperledger/fabric/core/policy"
"github.com/hyperledger/fabric/core/scc"
"github.com/hyperledger/fabric/core/scc/cscc"
"github.com/hyperledger/fabric/core/scc/lscc"
"github.com/hyperledger/fabric/core/scc/qscc"
"github.com/hyperledger/fabric/core/transientstore"
"github.com/hyperledger/fabric/discovery"
"github.com/hyperledger/fabric/discovery/endorsement"
discsupport "github.com/hyperledger/fabric/discovery/support"
discacl "github.com/hyperledger/fabric/discovery/support/acl"
ccsupport "github.com/hyperledger/fabric/discovery/support/chaincode"
"github.com/hyperledger/fabric/discovery/support/config"
"github.com/hyperledger/fabric/discovery/support/gossip"
gossipcommon "github.com/hyperledger/fabric/gossip/common"
gossipgossip "github.com/hyperledger/fabric/gossip/gossip"
gossipmetrics "github.com/hyperledger/fabric/gossip/metrics"
gossipprivdata "github.com/hyperledger/fabric/gossip/privdata"
"github.com/hyperledger/fabric/gossip/service"
gossipservice "github.com/hyperledger/fabric/gossip/service"
peergossip "github.com/hyperledger/fabric/internal/peer/gossip"
"github.com/hyperledger/fabric/internal/peer/version"
"github.com/hyperledger/fabric/internal/pkg/comm"
"github.com/hyperledger/fabric/msp"
"github.com/hyperledger/fabric/msp/mgmt"
"github.com/hyperledger/fabric/protoutil"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"google.golang.org/grpc"
)
const (
chaincodeAddrKey = "peer.chaincodeAddress"
chaincodeListenAddrKey = "peer.chaincodeListenAddress"
defaultChaincodePort = 7052
)
var chaincodeDevMode bool
func startCmd() *cobra.Command {
// Set the flags on the node start command.
flags := nodeStartCmd.Flags()
flags.BoolVarP(&chaincodeDevMode, "peer-chaincodedev", "", false, "start peer in chaincode development mode")
return nodeStartCmd
}
var nodeStartCmd = &cobra.Command{
Use: "start",
Short: "Starts the node.",
Long: `Starts a node that interacts with the network.`,
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) != 0 {
return fmt.Errorf("trailing args detected")
}
// Parsing of the command line is done so silence cmd usage
cmd.SilenceUsage = true
return serve(args)
},
}
// externalVMAdapter adapts coerces the result of Build to the
// container.Interface type expected by the VM interface.
type externalVMAdapter struct {
detector *externalbuilder.Detector
}
func (e externalVMAdapter) Build(
ccid string,
mdBytes []byte,
codePackage io.Reader,
) (container.Instance, error) {
i, err := e.detector.Build(ccid, mdBytes, codePackage)
if err != nil {
return nil, err
}
// ensure <nil> is returned instead of (*externalbuilder.Instance)(nil)
if i == nil {
return nil, nil
}
return i, err
}
type disabledDockerBuilder struct{}
func (disabledDockerBuilder) Build(string, *persistence.ChaincodePackageMetadata, io.Reader) (container.Instance, error) {
return nil, errors.New("docker build is disabled")
}
type endorserChannelAdapter struct {
peer *peer.Peer
}
func (e endorserChannelAdapter) Channel(channelID string) *endorser.Channel {
if peerChannel := e.peer.Channel(channelID); peerChannel != nil {
return &endorser.Channel{
IdentityDeserializer: peerChannel.MSPManager(),
}
}
return nil
}
type custodianLauncherAdapter struct {
launcher chaincode.Launcher
streamHandler extcc.StreamHandler
}
func (c custodianLauncherAdapter) Launch(ccid string) error {
return c.launcher.Launch(ccid, c.streamHandler)
}
func (c custodianLauncherAdapter) Stop(ccid string) error {
return c.launcher.Stop(ccid)
}
func serve(args []string) error {
// currently the peer only works with the standard MSP
// because in certain scenarios the MSP has to make sure
// that from a single credential you only have a single 'identity'.
// Idemix does not support this *YET* but it can be easily
// fixed to support it. For now, we just make sure that
// the peer only comes up with the standard MSP
mspType := mgmt.GetLocalMSP(factory.GetDefault()).GetType()
if mspType != msp.FABRIC {
panic("Unsupported msp type " + msp.ProviderTypeToString(mspType))
}
// Trace RPCs with the golang.org/x/net/trace package. This was moved out of
// the deliver service connection factory as it has process wide implications
// and was racy with respect to initialization of gRPC clients and servers.
grpc.EnableTracing = true
logger.Infof("Starting %s", version.GetInfo())
//obtain coreConfiguration
coreConfig, err := peer.GlobalConfig()
if err != nil {
return err
}
platformRegistry := platforms.NewRegistry(platforms.SupportedPlatforms...)
identityDeserializerFactory := func(chainID string) msp.IdentityDeserializer {
return mgmt.GetManagerForChain(chainID)
}
opsSystem := newOperationsSystem(coreConfig)
err = opsSystem.Start()
if err != nil {
return errors.WithMessage(err, "failed to initialize operations subsystem")
}
defer opsSystem.Stop()
metricsProvider := opsSystem.Provider
logObserver := floggingmetrics.NewObserver(metricsProvider)
flogging.SetObserver(logObserver)
mspID := coreConfig.LocalMSPID
membershipInfoProvider := privdata.NewMembershipInfoProvider(mspID, createSelfSignedData(), identityDeserializerFactory)
chaincodeInstallPath := filepath.Join(coreconfig.GetPath("peer.fileSystemPath"), "lifecycle", "chaincodes")
ccStore := persistence.NewStore(chaincodeInstallPath)
ccPackageParser := &persistence.ChaincodePackageParser{
MetadataProvider: ccprovider.PersistenceAdapter(ccprovider.MetadataAsTarEntries),
}
peerHost, _, err := net.SplitHostPort(coreConfig.PeerAddress)
if err != nil {
return fmt.Errorf("peer address is not in the format of host:port: %v", err)
}
listenAddr := coreConfig.ListenAddress
serverConfig, err := peer.GetServerConfig()
if err != nil {
logger.Fatalf("Error loading secure config for peer (%s)", err)
}
serverConfig.Logger = flogging.MustGetLogger("core.comm").With("server", "PeerServer")
serverConfig.ServerStatsHandler = comm.NewServerStatsHandler(metricsProvider)
serverConfig.UnaryInterceptors = append(
serverConfig.UnaryInterceptors,
grpcmetrics.UnaryServerInterceptor(grpcmetrics.NewUnaryMetrics(metricsProvider)),
grpclogging.UnaryServerInterceptor(flogging.MustGetLogger("comm.grpc.server").Zap()),
)
serverConfig.StreamInterceptors = append(
serverConfig.StreamInterceptors,
grpcmetrics.StreamServerInterceptor(grpcmetrics.NewStreamMetrics(metricsProvider)),
grpclogging.StreamServerInterceptor(flogging.MustGetLogger("comm.grpc.server").Zap()),
)
semaphores := initGrpcSemaphores(coreConfig)
if len(semaphores) != 0 {
serverConfig.UnaryInterceptors = append(serverConfig.UnaryInterceptors, unaryGrpcLimiter(semaphores))
serverConfig.StreamInterceptors = append(serverConfig.StreamInterceptors, streamGrpcLimiter(semaphores))
}
cs := comm.NewCredentialSupport()
if serverConfig.SecOpts.UseTLS {
logger.Info("Starting peer with TLS enabled")
cs = comm.NewCredentialSupport(serverConfig.SecOpts.ServerRootCAs...)
// set the cert to use if client auth is requested by remote endpoints
clientCert, err := peer.GetClientCertificate()
if err != nil {
logger.Fatalf("Failed to set TLS client certificate (%s)", err)
}
cs.SetClientCertificate(clientCert)
}
transientStoreProvider, err := transientstore.NewStoreProvider(
filepath.Join(coreconfig.GetPath("peer.fileSystemPath"), "transientstore"),
)
if err != nil {
return errors.WithMessage(err, "failed to open transient store")
}
deliverServiceConfig := deliverservice.GlobalConfig()
peerInstance := &peer.Peer{
ServerConfig: serverConfig,
CredentialSupport: cs,
StoreProvider: transientStoreProvider,
CryptoProvider: factory.GetDefault(),
OrdererEndpointOverrides: deliverServiceConfig.OrdererEndpointOverrides,
}
localMSP := mgmt.GetLocalMSP(factory.GetDefault())
signingIdentity, err := localMSP.GetDefaultSigningIdentity()
if err != nil {
logger.Panicf("Could not get the default signing identity from the local MSP: [%+v]", err)
}
signingIdentityBytes, err := signingIdentity.Serialize()
if err != nil {
logger.Panicf("Failed to serialize the signing identity: %v", err)
}
expirationLogger := flogging.MustGetLogger("certmonitor")
crypto.TrackExpiration(
serverConfig.SecOpts.UseTLS,
serverConfig.SecOpts.Certificate,
cs.GetClientCertificate().Certificate,
signingIdentityBytes,
expirationLogger.Warnf, // This can be used to piggyback a metric event in the future
time.Now(),
time.AfterFunc)
policyMgr := policies.PolicyManagerGetterFunc(peerInstance.GetPolicyManager)
deliverGRPCClient, err := comm.NewGRPCClient(comm.ClientConfig{
Timeout: deliverServiceConfig.ConnectionTimeout,
KaOpts: deliverServiceConfig.KeepaliveOptions,
SecOpts: deliverServiceConfig.SecOpts,
})
if err != nil {
logger.Panicf("Could not create the deliver grpc client: [%+v]", err)
}
policyChecker := policy.NewPolicyChecker(
policies.PolicyManagerGetterFunc(peerInstance.GetPolicyManager),
mgmt.GetLocalMSP(factory.GetDefault()),
mgmt.NewLocalMSPPrincipalGetter(factory.GetDefault()),
)
//startup aclmgmt with default ACL providers (resource based and default 1.0 policies based).
//Users can pass in their own ACLProvider to RegisterACLProvider (currently unit tests do this)
aclProvider := aclmgmt.NewACLProvider(
aclmgmt.ResourceGetter(peerInstance.GetStableChannelConfig),
policyChecker,
)
// TODO, unfortunately, the lifecycle initialization is very unclean at the
// moment. This is because ccprovider.SetChaincodePath only works after
// ledgermgmt.Initialize, but ledgermgmt.Initialize requires a reference to
// lifecycle. Finally, lscc requires a reference to the system chaincode
// provider in order to be created, which requires chaincode support to be
// up, which also requires, you guessed it, lifecycle. Once we remove the
// v1.0 lifecycle, we should be good to collapse all of the init of lifecycle
// to this point.
lifecycleResources := &lifecycle.Resources{
Serializer: &lifecycle.Serializer{},
ChannelConfigSource: peerInstance,
ChaincodeStore: ccStore,
PackageParser: ccPackageParser,
}
privdataConfig := gossipprivdata.GlobalConfig()
lifecycleValidatorCommitter := &lifecycle.ValidatorCommitter{
CoreConfig: coreConfig,
PrivdataConfig: privdataConfig,
Resources: lifecycleResources,
LegacyDeployedCCInfoProvider: &lscc.DeployedCCInfoProvider{},
}
ccInfoFSImpl := &ccprovider.CCInfoFSImpl{GetHasher: factory.GetDefault()}
// legacyMetadataManager collects metadata information from the legacy
// lifecycle (lscc). This is expected to disappear with FAB-15061.
legacyMetadataManager, err := cclifecycle.NewMetadataManager(
cclifecycle.EnumerateFunc(
func() ([]ccdef.InstalledChaincode, error) {
return ccInfoFSImpl.ListInstalledChaincodes(ccInfoFSImpl.GetChaincodeInstallPath(), ioutil.ReadDir, ccprovider.LoadPackage)
},
),
)
if err != nil {
logger.Panicf("Failed creating LegacyMetadataManager: +%v", err)
}
// metadataManager aggregates metadata information from _lifecycle and
// the legacy lifecycle (lscc).
metadataManager := lifecycle.NewMetadataManager()
// the purpose of these two managers is to feed per-channel chaincode data
// into gossip owing to the fact that we are transitioning from lscc to
// _lifecycle, we still have two providers of such information until v2.1,
// in which we will remove the legacy.
//
// the flow of information is the following
//
// gossip <-- metadataManager <-- lifecycleCache (for _lifecycle)
// \
// - legacyMetadataManager (for lscc)
//
// FAB-15061 tracks the work necessary to remove LSCC, at which point we
// will be able to simplify the flow to simply be
//
// gossip <-- lifecycleCache
chaincodeCustodian := lifecycle.NewChaincodeCustodian()
externalBuilderOutput := filepath.Join(coreconfig.GetPath("peer.fileSystemPath"), "externalbuilder", "builds")
if err := os.MkdirAll(externalBuilderOutput, 0700); err != nil {
logger.Panicf("could not create externalbuilder build output dir: %s", err)
}
ebMetadataProvider := &externalbuilder.MetadataProvider{
DurablePath: externalBuilderOutput,
}
lifecycleCache := lifecycle.NewCache(lifecycleResources, mspID, metadataManager, chaincodeCustodian, ebMetadataProvider)
txProcessors := map[common.HeaderType]ledger.CustomTxProcessor{
common.HeaderType_CONFIG: &peer.ConfigTxProcessor{},
}
peerInstance.LedgerMgr = ledgermgmt.NewLedgerMgr(
&ledgermgmt.Initializer{
CustomTxProcessors: txProcessors,
DeployedChaincodeInfoProvider: lifecycleValidatorCommitter,
MembershipInfoProvider: membershipInfoProvider,
ChaincodeLifecycleEventProvider: lifecycleCache,
MetricsProvider: metricsProvider,
HealthCheckRegistry: opsSystem,
StateListeners: []ledger.StateListener{lifecycleCache},
Config: ledgerConfig(),
Hasher: factory.GetDefault(),
EbMetadataProvider: ebMetadataProvider,
},
)
peerServer, err := comm.NewGRPCServer(listenAddr, serverConfig)
if err != nil {
logger.Fatalf("Failed to create peer server (%s)", err)
}
// FIXME: Creating the gossip service has the side effect of starting a bunch
// of go routines and registration with the grpc server.
gossipService, err := initGossipService(
policyMgr,
metricsProvider,
peerServer,
signingIdentity,
cs,
coreConfig.PeerAddress,
deliverGRPCClient,
deliverServiceConfig,
privdataConfig,
)
if err != nil {
return errors.WithMessage(err, "failed to initialize gossip service")
}
defer gossipService.Stop()
peerInstance.GossipService = gossipService
// Configure CC package storage
lsccInstallPath := filepath.Join(coreconfig.GetPath("peer.fileSystemPath"), "chaincodes")
ccprovider.SetChaincodesPath(lsccInstallPath)
if err := lifecycleCache.InitializeLocalChaincodes(); err != nil {
return errors.WithMessage(err, "could not initialize local chaincodes")
}
// Parameter overrides must be processed before any parameters are
// cached. Failures to cache cause the server to terminate immediately.
if chaincodeDevMode {
logger.Info("Running in chaincode development mode")
logger.Info("Disable loading validity system chaincode")
viper.Set("chaincode.mode", chaincode.DevModeUserRunsChaincode)
}
mutualTLS := serverConfig.SecOpts.UseTLS && serverConfig.SecOpts.RequireClientCert
policyCheckerProvider := func(resourceName string) deliver.PolicyCheckerFunc {
return func(env *cb.Envelope, channelID string) error {
return aclProvider.CheckACL(resourceName, channelID, env)
}
}
metrics := deliver.NewMetrics(metricsProvider)
abServer := &peer.DeliverServer{
DeliverHandler: deliver.NewHandler(
&peer.DeliverChainManager{Peer: peerInstance},
coreConfig.AuthenticationTimeWindow,
mutualTLS,
metrics,
false,
),
PolicyCheckerProvider: policyCheckerProvider,
}
pb.RegisterDeliverServer(peerServer.Server(), abServer)
// Create a self-signed CA for chaincode service
ca, err := tlsgen.NewCA()
if err != nil {
logger.Panic("Failed creating authentication layer:", err)
}
ccSrv, ccEndpoint, err := createChaincodeServer(coreConfig, ca, peerHost)
if err != nil {
logger.Panicf("Failed to create chaincode server: %s", err)
}
//get user mode
userRunsCC := chaincode.IsDevMode()
tlsEnabled := coreConfig.PeerTLSEnabled
// create chaincode specific tls CA
authenticator := accesscontrol.NewAuthenticator(ca)
chaincodeHandlerRegistry := chaincode.NewHandlerRegistry(userRunsCC)
lifecycleTxQueryExecutorGetter := &chaincode.TxQueryExecutorGetter{
CCID: scc.ChaincodeID(lifecycle.LifecycleNamespace),
HandlerRegistry: chaincodeHandlerRegistry,
}
if coreConfig.VMEndpoint == "" && len(coreConfig.ExternalBuilders) == 0 {
logger.Panic("VMEndpoint not set and no ExternalBuilders defined")
}
chaincodeConfig := chaincode.GlobalConfig()
var dockerBuilder container.DockerBuilder
if coreConfig.VMEndpoint != "" {
client, err := createDockerClient(coreConfig)
if err != nil {
logger.Panicf("cannot create docker client: %s", err)
}
dockerVM := &dockercontroller.DockerVM{
PeerID: coreConfig.PeerID,
NetworkID: coreConfig.NetworkID,
BuildMetrics: dockercontroller.NewBuildMetrics(opsSystem.Provider),
Client: client,
AttachStdOut: coreConfig.VMDockerAttachStdout,
HostConfig: getDockerHostConfig(),
ChaincodePull: coreConfig.ChaincodePull,
NetworkMode: coreConfig.VMNetworkMode,
PlatformBuilder: &platforms.Builder{
Registry: platformRegistry,
Client: client,
},
// This field is superfluous for chaincodes built with v2.0+ binaries
// however, to prevent users from being forced to rebuild leaving for now
// but it should be removed in the future.
LoggingEnv: []string{
"CORE_CHAINCODE_LOGGING_LEVEL=" + chaincodeConfig.LogLevel,
"CORE_CHAINCODE_LOGGING_SHIM=" + chaincodeConfig.ShimLogLevel,
"CORE_CHAINCODE_LOGGING_FORMAT=" + chaincodeConfig.LogFormat,
},
MSPID: mspID,
}
if err := opsSystem.RegisterChecker("docker", dockerVM); err != nil {
logger.Panicf("failed to register docker health check: %s", err)
}
dockerBuilder = dockerVM
}
// docker is disabled when we're missing the docker config
if dockerBuilder == nil {
dockerBuilder = &disabledDockerBuilder{}
}
externalVM := &externalbuilder.Detector{
Builders: externalbuilder.CreateBuilders(coreConfig.ExternalBuilders, mspID),
DurablePath: externalBuilderOutput,
}
buildRegistry := &container.BuildRegistry{}
containerRouter := &container.Router{
DockerBuilder: dockerBuilder,
ExternalBuilder: externalVMAdapter{externalVM},
PackageProvider: &persistence.FallbackPackageLocator{
ChaincodePackageLocator: &persistence.ChaincodePackageLocator{
ChaincodeDir: chaincodeInstallPath,
},
LegacyCCPackageLocator: &ccprovider.CCInfoFSImpl{GetHasher: factory.GetDefault()},
},
}
builtinSCCs := map[string]struct{}{
"lscc": {},
"qscc": {},
"cscc": {},
"_lifecycle": {},
}
lsccInst := &lscc.SCC{
BuiltinSCCs: builtinSCCs,
Support: &lscc.SupportImpl{
GetMSPIDs: peerInstance.GetMSPIDs,
},
SCCProvider: &lscc.PeerShim{Peer: peerInstance},
ACLProvider: aclProvider,
GetMSPIDs: peerInstance.GetMSPIDs,
PolicyChecker: policyChecker,
BCCSP: factory.GetDefault(),
BuildRegistry: buildRegistry,
ChaincodeBuilder: containerRouter,
EbMetadataProvider: ebMetadataProvider,
}
chaincodeEndorsementInfo := &lifecycle.ChaincodeEndorsementInfoSource{
LegacyImpl: lsccInst,
Resources: lifecycleResources,
Cache: lifecycleCache,
BuiltinSCCs: builtinSCCs,
}
containerRuntime := &chaincode.ContainerRuntime{
BuildRegistry: buildRegistry,
ContainerRouter: containerRouter,
}
lifecycleFunctions := &lifecycle.ExternalFunctions{
Resources: lifecycleResources,
InstallListener: lifecycleCache,
InstalledChaincodesLister: lifecycleCache,
ChaincodeBuilder: containerRouter,
BuildRegistry: buildRegistry,
}
lifecycleSCC := &lifecycle.SCC{
Dispatcher: &dispatcher.Dispatcher{
Protobuf: &dispatcher.ProtobufImpl{},
},
DeployedCCInfoProvider: lifecycleValidatorCommitter,
QueryExecutorProvider: lifecycleTxQueryExecutorGetter,
Functions: lifecycleFunctions,
OrgMSPID: mspID,
ChannelConfigSource: peerInstance,
ACLProvider: aclProvider,
}
chaincodeLauncher := &chaincode.RuntimeLauncher{
Metrics: chaincode.NewLaunchMetrics(opsSystem.Provider),
Registry: chaincodeHandlerRegistry,
Runtime: containerRuntime,
StartupTimeout: chaincodeConfig.StartupTimeout,
CertGenerator: authenticator,
CACert: ca.CertBytes(),
PeerAddress: ccEndpoint,
ConnectionHandler: &extcc.ExternalChaincodeRuntime{},
}
// Keep TestQueries working
if !chaincodeConfig.TLSEnabled {
chaincodeLauncher.CertGenerator = nil
}
chaincodeSupport := &chaincode.ChaincodeSupport{
ACLProvider: aclProvider,
AppConfig: peerInstance,
DeployedCCInfoProvider: lifecycleValidatorCommitter,
ExecuteTimeout: chaincodeConfig.ExecuteTimeout,
InstallTimeout: chaincodeConfig.InstallTimeout,
HandlerRegistry: chaincodeHandlerRegistry,
HandlerMetrics: chaincode.NewHandlerMetrics(opsSystem.Provider),
Keepalive: chaincodeConfig.Keepalive,
Launcher: chaincodeLauncher,
Lifecycle: chaincodeEndorsementInfo,
Peer: peerInstance,
Runtime: containerRuntime,
BuiltinSCCs: builtinSCCs,
TotalQueryLimit: chaincodeConfig.TotalQueryLimit,
UserRunsCC: userRunsCC,
}
custodianLauncher := custodianLauncherAdapter{
launcher: chaincodeLauncher,
streamHandler: chaincodeSupport,
}
go chaincodeCustodian.Work(buildRegistry, containerRouter, custodianLauncher)
ccSupSrv := pb.ChaincodeSupportServer(chaincodeSupport)
if tlsEnabled {
ccSupSrv = authenticator.Wrap(ccSupSrv)
}
csccInst := cscc.New(
aclProvider,
lifecycleValidatorCommitter,
lsccInst,
lifecycleValidatorCommitter,
policyChecker,
peerInstance,
factory.GetDefault(),
)
qsccInst := scc.SelfDescribingSysCC(qscc.New(aclProvider, peerInstance))
pb.RegisterChaincodeSupportServer(ccSrv.Server(), ccSupSrv)
// start the chaincode specific gRPC listening service
go ccSrv.Start()
logger.Debugf("Running peer")
libConf, err := library.LoadConfig()
if err != nil {
return errors.WithMessage(err, "could not decode peer handlers configuration")
}
reg := library.InitRegistry(libConf)
authFilters := reg.Lookup(library.Auth).([]authHandler.Filter)
endorserSupport := &endorser.SupportImpl{
SignerSerializer: signingIdentity,
Peer: peerInstance,
ChaincodeSupport: chaincodeSupport,
ACLProvider: aclProvider,
BuiltinSCCs: builtinSCCs,
}
endorsementPluginsByName := reg.Lookup(library.Endorsement).(map[string]endorsement2.PluginFactory)
validationPluginsByName := reg.Lookup(library.Validation).(map[string]validation.PluginFactory)
signingIdentityFetcher := (endorsement3.SigningIdentityFetcher)(endorserSupport)
channelStateRetriever := endorser.ChannelStateRetriever(endorserSupport)
pluginMapper := endorser.MapBasedPluginMapper(endorsementPluginsByName)
pluginEndorser := endorser.NewPluginEndorser(&endorser.PluginSupport{
ChannelStateRetriever: channelStateRetriever,
TransientStoreRetriever: peerInstance,
PluginMapper: pluginMapper,
SigningIdentityFetcher: signingIdentityFetcher,
})
endorserSupport.PluginEndorser = pluginEndorser
channelFetcher := endorserChannelAdapter{
peer: peerInstance,
}
serverEndorser := &endorser.Endorser{
PrivateDataDistributor: gossipService,
ChannelFetcher: channelFetcher,
LocalMSP: localMSP,
Support: endorserSupport,
Metrics: endorser.NewMetrics(metricsProvider),
}
// deploy system chaincodes
for _, cc := range []scc.SelfDescribingSysCC{lsccInst, csccInst, qsccInst, lifecycleSCC} {
if enabled, ok := chaincodeConfig.SCCWhitelist[cc.Name()]; !ok || !enabled {
logger.Infof("not deploying chaincode %s as it is not enabled", cc.Name())
continue
}
scc.DeploySysCC(cc, chaincodeSupport)
}
logger.Infof("Deployed system chaincodes")
// register the lifecycleMetadataManager to get updates from the legacy
// chaincode; lifecycleMetadataManager will aggregate these updates with
// the ones from the new lifecycle and deliver both
// this is expected to disappear with FAB-15061
legacyMetadataManager.AddListener(metadataManager)
// register gossip as a listener for updates from lifecycleMetadataManager
metadataManager.AddListener(lifecycle.HandleMetadataUpdateFunc(func(channel string, chaincodes ccdef.MetadataSet) {
gossipService.UpdateChaincodes(chaincodes.AsChaincodes(), gossipcommon.ChannelID(channel))
}))
// this brings up all the channels
peerInstance.Initialize(
func(cid string) {
// initialize the metadata for this channel.
// This call will pre-populate chaincode information for this
// channel but it won't fire any updates to its listeners
lifecycleCache.InitializeMetadata(cid)
// initialize the legacyMetadataManager for this channel.
// This call will pre-populate chaincode information from
// the legacy lifecycle for this channel; it will also fire
// the listener, which will cascade to metadataManager
// and eventually to gossip to pre-populate data structures.
// this is expected to disappear with FAB-15061
sub, err := legacyMetadataManager.NewChannelSubscription(cid, cclifecycle.QueryCreatorFunc(func() (cclifecycle.Query, error) {
return peerInstance.GetLedger(cid).NewQueryExecutor()
}))
if err != nil {
logger.Panicf("Failed subscribing to chaincode lifecycle updates")
}
// register this channel's legacyMetadataManager (sub) to get ledger updates
// this is expected to disappear with FAB-15061
cceventmgmt.GetMgr().Register(cid, sub)
},
peerServer,
plugin.MapBasedMapper(validationPluginsByName),
lifecycleValidatorCommitter,
lsccInst,
lifecycleValidatorCommitter,
coreConfig.ValidatorPoolSize,
)
if coreConfig.DiscoveryEnabled {
registerDiscoveryService(
coreConfig,
peerInstance,
peerServer,
policyMgr,
lifecycle.NewMetadataProvider(
lifecycleCache,
legacyMetadataManager,
peerInstance,
),
gossipService,
)
}
logger.Infof("Starting peer with ID=[%s], network ID=[%s], address=[%s]", coreConfig.PeerID, coreConfig.NetworkID, coreConfig.PeerAddress)
// Get configuration before starting go routines to avoid
// racing in tests
profileEnabled := coreConfig.ProfileEnabled
profileListenAddress := coreConfig.ProfileListenAddress
// Start the grpc server. Done in a goroutine so we can deploy the
// genesis block if needed.
serve := make(chan error)
// Start profiling http endpoint if enabled
if profileEnabled {
go func() {
logger.Infof("Starting profiling server with listenAddress = %s", profileListenAddress)
if profileErr := http.ListenAndServe(profileListenAddress, nil); profileErr != nil {
logger.Errorf("Error starting profiler: %s", profileErr)
}
}()
}
handleSignals(addPlatformSignals(map[os.Signal]func(){
syscall.SIGINT: func() { serve <- nil },
syscall.SIGTERM: func() { serve <- nil },
}))
logger.Infof("Started peer with ID=[%s], network ID=[%s], address=[%s]", coreConfig.PeerID, coreConfig.NetworkID, coreConfig.PeerAddress)
// get a list of ledger IDs and load preResetHeight files for these ledger IDs
ledgerIDs, err := peerInstance.LedgerMgr.GetLedgerIDs()
if err != nil {
return errors.WithMessage(err, "failed to get ledger IDs")
}
// check to see if the peer ledgers have been reset
rootFSPath := filepath.Join(coreconfig.GetPath("peer.fileSystemPath"), "ledgersData")
preResetHeights, err := kvledger.LoadPreResetHeight(rootFSPath, ledgerIDs)
if err != nil {
return fmt.Errorf("error loading prereset height: %s", err)
}
for cid, height := range preResetHeights {
logger.Infof("Ledger rebuild: channel [%s]: preresetHeight: [%d]", cid, height)
}
if len(preResetHeights) > 0 {
logger.Info("Ledger rebuild: Entering loop to check if current ledger heights surpass prereset ledger heights. Endorsement request processing will be disabled.")
resetFilter := &reset{
reject: true,
}
authFilters = append(authFilters, resetFilter)
go resetLoop(resetFilter, preResetHeights, ledgerIDs, peerInstance.GetLedger, 10*time.Second)
}
// start the peer server
auth := authHandler.ChainFilters(serverEndorser, authFilters...)
// Register the Endorser server
pb.RegisterEndorserServer(peerServer.Server(), auth)
go func() {
var grpcErr error
if grpcErr = peerServer.Start(); grpcErr != nil {
grpcErr = fmt.Errorf("grpc server exited with error: %s", grpcErr)
}
serve <- grpcErr
}()
// Block until grpc server exits
return <-serve
}
func handleSignals(handlers map[os.Signal]func()) {
var signals []os.Signal
for sig := range handlers {
signals = append(signals, sig)
}
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, signals...)
go func() {
for sig := range signalChan {
logger.Infof("Received signal: %d (%s)", sig, sig)
handlers[sig]()
}
}()
}
func localPolicy(policyObject proto.Message) policies.Policy {
localMSP := mgmt.GetLocalMSP(factory.GetDefault())
pp := cauthdsl.NewPolicyProvider(localMSP)
policy, _, err := pp.NewPolicy(protoutil.MarshalOrPanic(policyObject))
if err != nil {
logger.Panicf("Failed creating local policy: +%v", err)
}
return policy
}
func createSelfSignedData() protoutil.SignedData {
sID := mgmt.GetLocalSigningIdentityOrPanic(factory.GetDefault())
msg := make([]byte, 32)
sig, err := sID.Sign(msg)
if err != nil {
logger.Panicf("Failed creating self signed data because message signing failed: %v", err)
}
peerIdentity, err := sID.Serialize()
if err != nil {
logger.Panicf("Failed creating self signed data because peer identity couldn't be serialized: %v", err)
}
return protoutil.SignedData{
Data: msg,
Signature: sig,
Identity: peerIdentity,
}
}
func registerDiscoveryService(
coreConfig *peer.Config,
peerInstance *peer.Peer,
peerServer *comm.GRPCServer,
polMgr policies.ChannelPolicyManagerGetter,
metadataProvider *lifecycle.MetadataProvider,
gossipService *gossipservice.GossipService,
) {
mspID := coreConfig.LocalMSPID
localAccessPolicy := localPolicy(policydsl.SignedByAnyAdmin([]string{mspID}))
if coreConfig.DiscoveryOrgMembersAllowed {
localAccessPolicy = localPolicy(policydsl.SignedByAnyMember([]string{mspID}))
}
channelVerifier := discacl.NewChannelVerifier(policies.ChannelApplicationWriters, polMgr)
acl := discacl.NewDiscoverySupport(channelVerifier, localAccessPolicy, discacl.ChannelConfigGetterFunc(peerInstance.GetStableChannelConfig))
gSup := gossip.NewDiscoverySupport(gossipService)
ccSup := ccsupport.NewDiscoverySupport(metadataProvider)
ea := endorsement.NewEndorsementAnalyzer(gSup, ccSup, acl, metadataProvider)
confSup := config.NewDiscoverySupport(config.CurrentConfigBlockGetterFunc(func(channelID string) *common.Block {
channel := peerInstance.Channel(channelID)
if channel == nil {
return nil
}
block, err := peer.ConfigBlockFromLedger(channel.Ledger())
if err != nil {
logger.Error("failed to get config block", err)
return nil
}
return block
}))
support := discsupport.NewDiscoverySupport(acl, gSup, ea, confSup, acl)
svc := discovery.NewService(discovery.Config{
TLS: peerServer.TLSEnabled(),
AuthCacheEnabled: coreConfig.DiscoveryAuthCacheEnabled,
AuthCacheMaxSize: coreConfig.DiscoveryAuthCacheMaxSize,
AuthCachePurgeRetentionRatio: coreConfig.DiscoveryAuthCachePurgeRetentionRatio,
}, support)
logger.Info("Discovery service activated")
discprotos.RegisterDiscoveryServer(peerServer.Server(), svc)
}
// create a CC listener using peer.chaincodeListenAddress (and if that's not set use peer.peerAddress)
func createChaincodeServer(coreConfig *peer.Config, ca tlsgen.CA, peerHostname string) (srv *comm.GRPCServer, ccEndpoint string, err error) {
// before potentially setting chaincodeListenAddress, compute chaincode endpoint at first
ccEndpoint, err = computeChaincodeEndpoint(coreConfig.ChaincodeAddress, coreConfig.ChaincodeListenAddress, peerHostname)
if err != nil {
if chaincode.IsDevMode() {
// if any error for dev mode, we use 0.0.0.0:7052
ccEndpoint = fmt.Sprintf("%s:%d", "0.0.0.0", defaultChaincodePort)
logger.Warningf("use %s as chaincode endpoint because of error in computeChaincodeEndpoint: %s", ccEndpoint, err)
} else {
// for non-dev mode, we have to return error
logger.Errorf("Error computing chaincode endpoint: %s", err)
return nil, "", err
}
}
host, _, err := net.SplitHostPort(ccEndpoint)
if err != nil {
logger.Panic("Chaincode service host", ccEndpoint, "isn't a valid hostname:", err)
}
cclistenAddress := coreConfig.ChaincodeListenAddress
if cclistenAddress == "" {
cclistenAddress = fmt.Sprintf("%s:%d", peerHostname, defaultChaincodePort)
logger.Warningf("%s is not set, using %s", chaincodeListenAddrKey, cclistenAddress)
coreConfig.ChaincodeListenAddress = cclistenAddress
}
config, err := peer.GetServerConfig()
if err != nil {
logger.Errorf("Error getting server config: %s", err)
return nil, "", err
}