github.com/anjalikarhana/fabric@v2.1.1+incompatible/orderer/common/server/main.go (about) 1 /* 2 Copyright IBM Corp. All Rights Reserved. 3 4 SPDX-License-Identifier: Apache-2.0 5 */ 6 7 package server 8 9 import ( 10 "bytes" 11 "context" 12 "fmt" 13 "io/ioutil" 14 "net" 15 "net/http" 16 _ "net/http/pprof" // This is essentially the main package for the orderer 17 "os" 18 "os/signal" 19 "sync" 20 "syscall" 21 "time" 22 23 "github.com/golang/protobuf/proto" 24 "github.com/hyperledger/fabric-lib-go/healthz" 25 cb "github.com/hyperledger/fabric-protos-go/common" 26 ab "github.com/hyperledger/fabric-protos-go/orderer" 27 "github.com/hyperledger/fabric/bccsp" 28 "github.com/hyperledger/fabric/bccsp/factory" 29 "github.com/hyperledger/fabric/common/channelconfig" 30 "github.com/hyperledger/fabric/common/crypto" 31 "github.com/hyperledger/fabric/common/flogging" 32 floggingmetrics "github.com/hyperledger/fabric/common/flogging/metrics" 33 "github.com/hyperledger/fabric/common/grpclogging" 34 "github.com/hyperledger/fabric/common/grpcmetrics" 35 "github.com/hyperledger/fabric/common/ledger/blockledger" 36 "github.com/hyperledger/fabric/common/metrics" 37 "github.com/hyperledger/fabric/common/metrics/disabled" 38 "github.com/hyperledger/fabric/common/tools/protolator" 39 "github.com/hyperledger/fabric/core/operations" 40 "github.com/hyperledger/fabric/internal/pkg/comm" 41 "github.com/hyperledger/fabric/internal/pkg/identity" 42 "github.com/hyperledger/fabric/msp" 43 "github.com/hyperledger/fabric/orderer/common/bootstrap/file" 44 "github.com/hyperledger/fabric/orderer/common/cluster" 45 "github.com/hyperledger/fabric/orderer/common/localconfig" 46 "github.com/hyperledger/fabric/orderer/common/metadata" 47 "github.com/hyperledger/fabric/orderer/common/multichannel" 48 "github.com/hyperledger/fabric/orderer/consensus" 49 "github.com/hyperledger/fabric/orderer/consensus/etcdraft" 50 "github.com/hyperledger/fabric/orderer/consensus/kafka" 51 "github.com/hyperledger/fabric/orderer/consensus/solo" 52 "github.com/hyperledger/fabric/protoutil" 53 "go.uber.org/zap/zapcore" 54 "google.golang.org/grpc" 55 "gopkg.in/alecthomas/kingpin.v2" 56 ) 57 58 var logger = flogging.MustGetLogger("orderer.common.server") 59 60 //command line flags 61 var ( 62 app = kingpin.New("orderer", "Hyperledger Fabric orderer node") 63 64 _ = app.Command("start", "Start the orderer node").Default() // preserved for cli compatibility 65 version = app.Command("version", "Show version information") 66 67 clusterTypes = map[string]struct{}{"etcdraft": {}} 68 ) 69 70 // Main is the entry point of orderer process 71 func Main() { 72 fullCmd := kingpin.MustParse(app.Parse(os.Args[1:])) 73 74 // "version" command 75 if fullCmd == version.FullCommand() { 76 fmt.Println(metadata.GetVersionInfo()) 77 return 78 } 79 80 conf, err := localconfig.Load() 81 if err != nil { 82 logger.Error("failed to parse config: ", err) 83 os.Exit(1) 84 } 85 initializeLogging() 86 87 prettyPrintStruct(conf) 88 89 cryptoProvider := factory.GetDefault() 90 91 signer, signErr := loadLocalMSP(conf).GetDefaultSigningIdentity() 92 if signErr != nil { 93 logger.Panicf("Failed to get local MSP identity: %s", signErr) 94 } 95 96 opsSystem := newOperationsSystem(conf.Operations, conf.Metrics) 97 if err = opsSystem.Start(); err != nil { 98 logger.Panicf("failed to initialize operations subsystem: %s", err) 99 } 100 defer opsSystem.Stop() 101 metricsProvider := opsSystem.Provider 102 logObserver := floggingmetrics.NewObserver(metricsProvider) 103 flogging.SetObserver(logObserver) 104 105 serverConfig := initializeServerConfig(conf, metricsProvider) 106 grpcServer := initializeGrpcServer(conf, serverConfig) 107 caMgr := &caManager{ 108 appRootCAsByChain: make(map[string][][]byte), 109 ordererRootCAsByChain: make(map[string][][]byte), 110 clientRootCAs: serverConfig.SecOpts.ClientRootCAs, 111 } 112 113 lf, _, err := createLedgerFactory(conf, metricsProvider) 114 if err != nil { 115 logger.Panicf("Failed to create ledger factory: %v", err) 116 } 117 118 var clusterBootBlock *cb.Block 119 // configure following artifacts properly if orderer is of cluster type 120 var r *replicationInitiator 121 clusterServerConfig := serverConfig 122 clusterGRPCServer := grpcServer // by default, cluster shares the same grpc server 123 var clusterClientConfig comm.ClientConfig 124 var clusterDialer *cluster.PredicateDialer 125 var clusterType, reuseGrpcListener bool 126 var serversToUpdate []*comm.GRPCServer 127 if conf.General.BootstrapMethod == "file" { 128 bootstrapBlock := extractBootstrapBlock(conf) 129 if err := ValidateBootstrapBlock(bootstrapBlock, cryptoProvider); err != nil { 130 logger.Panicf("Failed validating bootstrap block: %v", err) 131 } 132 sysChanLastConfigBlock := extractSysChanLastConfig(lf, bootstrapBlock) 133 clusterBootBlock = selectClusterBootBlock(bootstrapBlock, sysChanLastConfigBlock) 134 135 typ := consensusType(bootstrapBlock, cryptoProvider) 136 clusterType = isClusterType(clusterBootBlock, cryptoProvider) 137 if clusterType { 138 logger.Infof("Setting up cluster for orderer type %s", typ) 139 clusterClientConfig = initializeClusterClientConfig(conf) 140 clusterDialer = &cluster.PredicateDialer{ 141 Config: clusterClientConfig, 142 } 143 144 r = createReplicator(lf, bootstrapBlock, conf, clusterClientConfig.SecOpts, signer, cryptoProvider) 145 // Only clusters that are equipped with a recent config block can replicate. 146 if conf.General.BootstrapMethod == "file" { 147 r.replicateIfNeeded(bootstrapBlock) 148 } 149 150 if reuseGrpcListener = reuseListener(conf, typ); !reuseGrpcListener { 151 clusterServerConfig, clusterGRPCServer = configureClusterListener(conf, serverConfig, ioutil.ReadFile) 152 } 153 154 // If we have a separate gRPC server for the cluster, 155 // we need to update its TLS CA certificate pool. 156 serversToUpdate = append(serversToUpdate, clusterGRPCServer) 157 } 158 // Are we bootstrapping? 159 if len(lf.ChannelIDs()) == 0 { 160 initializeBootstrapChannel(clusterBootBlock, lf) 161 } else { 162 logger.Info("Not bootstrapping because of existing channels") 163 } 164 165 } 166 167 identityBytes, err := signer.Serialize() 168 if err != nil { 169 logger.Panicf("Failed serializing signing identity: %v", err) 170 } 171 172 expirationLogger := flogging.MustGetLogger("certmonitor") 173 crypto.TrackExpiration( 174 serverConfig.SecOpts.UseTLS, 175 serverConfig.SecOpts.Certificate, 176 [][]byte{clusterClientConfig.SecOpts.Certificate}, 177 identityBytes, 178 expirationLogger.Warnf, // This can be used to piggyback a metric event in the future 179 time.Now(), 180 time.AfterFunc) 181 182 // if cluster is reusing client-facing server, then it is already 183 // appended to serversToUpdate at this point. 184 if grpcServer.MutualTLSRequired() && !reuseGrpcListener { 185 serversToUpdate = append(serversToUpdate, grpcServer) 186 } 187 188 tlsCallback := func(bundle *channelconfig.Bundle) { 189 logger.Debug("Executing callback to update root CAs") 190 caMgr.updateTrustedRoots(bundle, serversToUpdate...) 191 if clusterType { 192 caMgr.updateClusterDialer( 193 clusterDialer, 194 clusterClientConfig.SecOpts.ServerRootCAs, 195 ) 196 } 197 } 198 199 manager := initializeMultichannelRegistrar( 200 clusterBootBlock, 201 r, 202 clusterDialer, 203 clusterServerConfig, 204 clusterGRPCServer, 205 conf, 206 signer, 207 metricsProvider, 208 opsSystem, 209 lf, 210 cryptoProvider, 211 tlsCallback, 212 ) 213 214 mutualTLS := serverConfig.SecOpts.UseTLS && serverConfig.SecOpts.RequireClientCert 215 server := NewServer( 216 manager, 217 metricsProvider, 218 &conf.Debug, 219 conf.General.Authentication.TimeWindow, 220 mutualTLS, 221 conf.General.Authentication.NoExpirationChecks, 222 ) 223 224 logger.Infof("Starting %s", metadata.GetVersionInfo()) 225 handleSignals(addPlatformSignals(map[os.Signal]func(){ 226 syscall.SIGTERM: func() { 227 grpcServer.Stop() 228 if clusterGRPCServer != grpcServer { 229 clusterGRPCServer.Stop() 230 } 231 }, 232 })) 233 234 if !reuseGrpcListener && clusterType { 235 logger.Info("Starting cluster listener on", clusterGRPCServer.Address()) 236 go clusterGRPCServer.Start() 237 } 238 239 if conf.General.Profile.Enabled { 240 go initializeProfilingService(conf) 241 } 242 ab.RegisterAtomicBroadcastServer(grpcServer.Server(), server) 243 logger.Info("Beginning to serve requests") 244 grpcServer.Start() 245 } 246 247 func reuseListener(conf *localconfig.TopLevel, typ string) bool { 248 clusterConf := conf.General.Cluster 249 // If listen address is not configured, and the TLS certificate isn't configured, 250 // it means we use the general listener of the node. 251 if clusterConf.ListenPort == 0 && clusterConf.ServerCertificate == "" && clusterConf.ListenAddress == "" && clusterConf.ServerPrivateKey == "" { 252 logger.Info("Cluster listener is not configured, defaulting to use the general listener on port", conf.General.ListenPort) 253 254 if !conf.General.TLS.Enabled { 255 logger.Panicf("TLS is required for running ordering nodes of type %s.", typ) 256 } 257 258 return true 259 } 260 261 // Else, one of the above is defined, so all 4 properties should be defined. 262 if clusterConf.ListenPort == 0 || clusterConf.ServerCertificate == "" || clusterConf.ListenAddress == "" || clusterConf.ServerPrivateKey == "" { 263 logger.Panic("Options: General.Cluster.ListenPort, General.Cluster.ListenAddress, General.Cluster.ServerCertificate," + 264 " General.Cluster.ServerPrivateKey, should be defined altogether.") 265 } 266 267 return false 268 } 269 270 // Extract system channel last config block 271 func extractSysChanLastConfig(lf blockledger.Factory, bootstrapBlock *cb.Block) *cb.Block { 272 // Are we bootstrapping? 273 channelCount := len(lf.ChannelIDs()) 274 if channelCount == 0 { 275 logger.Info("Bootstrapping because no existing channels") 276 return nil 277 } 278 logger.Infof("Not bootstrapping because of %d existing channels", channelCount) 279 280 systemChannelName, err := protoutil.GetChainIDFromBlock(bootstrapBlock) 281 if err != nil { 282 logger.Panicf("Failed extracting system channel name from bootstrap block: %v", err) 283 } 284 systemChannelLedger, err := lf.GetOrCreate(systemChannelName) 285 if err != nil { 286 logger.Panicf("Failed getting system channel ledger: %v", err) 287 } 288 height := systemChannelLedger.Height() 289 lastConfigBlock := multichannel.ConfigBlock(systemChannelLedger) 290 logger.Infof("System channel: name=%s, height=%d, last config block number=%d", 291 systemChannelName, height, lastConfigBlock.Header.Number) 292 return lastConfigBlock 293 } 294 295 // Select cluster boot block 296 func selectClusterBootBlock(bootstrapBlock, sysChanLastConfig *cb.Block) *cb.Block { 297 if sysChanLastConfig == nil { 298 logger.Debug("Selected bootstrap block, because system channel last config block is nil") 299 return bootstrapBlock 300 } 301 302 if sysChanLastConfig.Header.Number > bootstrapBlock.Header.Number { 303 logger.Infof("Cluster boot block is system channel last config block; Blocks Header.Number system-channel=%d, bootstrap=%d", 304 sysChanLastConfig.Header.Number, bootstrapBlock.Header.Number) 305 return sysChanLastConfig 306 } 307 308 logger.Infof("Cluster boot block is bootstrap (genesis) block; Blocks Header.Number system-channel=%d, bootstrap=%d", 309 sysChanLastConfig.Header.Number, bootstrapBlock.Header.Number) 310 return bootstrapBlock 311 } 312 313 func createReplicator( 314 lf blockledger.Factory, 315 bootstrapBlock *cb.Block, 316 conf *localconfig.TopLevel, 317 secOpts comm.SecureOptions, 318 signer identity.SignerSerializer, 319 bccsp bccsp.BCCSP, 320 ) *replicationInitiator { 321 logger := flogging.MustGetLogger("orderer.common.cluster") 322 323 vl := &verifierLoader{ 324 verifierFactory: &cluster.BlockVerifierAssembler{Logger: logger, BCCSP: bccsp}, 325 onFailure: func(block *cb.Block) { 326 protolator.DeepMarshalJSON(os.Stdout, block) 327 }, 328 ledgerFactory: lf, 329 logger: logger, 330 } 331 332 systemChannelName, err := protoutil.GetChainIDFromBlock(bootstrapBlock) 333 if err != nil { 334 logger.Panicf("Failed extracting system channel name from bootstrap block: %v", err) 335 } 336 337 // System channel is not verified because we trust the bootstrap block 338 // and use backward hash chain verification. 339 verifiersByChannel := vl.loadVerifiers() 340 verifiersByChannel[systemChannelName] = &cluster.NoopBlockVerifier{} 341 342 vr := &cluster.VerificationRegistry{ 343 LoadVerifier: vl.loadVerifier, 344 Logger: logger, 345 VerifiersByChannel: verifiersByChannel, 346 VerifierFactory: &cluster.BlockVerifierAssembler{Logger: logger, BCCSP: bccsp}, 347 } 348 349 ledgerFactory := &ledgerFactory{ 350 Factory: lf, 351 onBlockCommit: vr.BlockCommitted, 352 } 353 return &replicationInitiator{ 354 registerChain: vr.RegisterVerifier, 355 verifierRetriever: vr, 356 logger: logger, 357 secOpts: secOpts, 358 conf: conf, 359 lf: ledgerFactory, 360 signer: signer, 361 cryptoProvider: bccsp, 362 } 363 } 364 365 func initializeLogging() { 366 loggingSpec := os.Getenv("FABRIC_LOGGING_SPEC") 367 loggingFormat := os.Getenv("FABRIC_LOGGING_FORMAT") 368 flogging.Init(flogging.Config{ 369 Format: loggingFormat, 370 Writer: os.Stderr, 371 LogSpec: loggingSpec, 372 }) 373 } 374 375 // Start the profiling service if enabled. 376 func initializeProfilingService(conf *localconfig.TopLevel) { 377 logger.Info("Starting Go pprof profiling service on:", conf.General.Profile.Address) 378 // The ListenAndServe() call does not return unless an error occurs. 379 logger.Panic("Go pprof service failed:", http.ListenAndServe(conf.General.Profile.Address, nil)) 380 } 381 382 func handleSignals(handlers map[os.Signal]func()) { 383 var signals []os.Signal 384 for sig := range handlers { 385 signals = append(signals, sig) 386 } 387 388 signalChan := make(chan os.Signal, 1) 389 signal.Notify(signalChan, signals...) 390 391 go func() { 392 for sig := range signalChan { 393 logger.Infof("Received signal: %d (%s)", sig, sig) 394 handlers[sig]() 395 } 396 }() 397 } 398 399 type loadPEMFunc func(string) ([]byte, error) 400 401 // configureClusterListener returns a new ServerConfig and a new gRPC server (with its own TLS listener). 402 func configureClusterListener(conf *localconfig.TopLevel, generalConf comm.ServerConfig, loadPEM loadPEMFunc) (comm.ServerConfig, *comm.GRPCServer) { 403 clusterConf := conf.General.Cluster 404 405 cert, err := loadPEM(clusterConf.ServerCertificate) 406 if err != nil { 407 logger.Panicf("Failed to load cluster server certificate from '%s' (%s)", clusterConf.ServerCertificate, err) 408 } 409 410 key, err := loadPEM(clusterConf.ServerPrivateKey) 411 if err != nil { 412 logger.Panicf("Failed to load cluster server key from '%s' (%s)", clusterConf.ServerPrivateKey, err) 413 } 414 415 port := fmt.Sprintf("%d", clusterConf.ListenPort) 416 bindAddr := net.JoinHostPort(clusterConf.ListenAddress, port) 417 418 var clientRootCAs [][]byte 419 for _, serverRoot := range conf.General.Cluster.RootCAs { 420 rootCACert, err := loadPEM(serverRoot) 421 if err != nil { 422 logger.Panicf("Failed to load CA cert file '%s' (%s)", serverRoot, err) 423 } 424 clientRootCAs = append(clientRootCAs, rootCACert) 425 } 426 427 serverConf := comm.ServerConfig{ 428 StreamInterceptors: generalConf.StreamInterceptors, 429 UnaryInterceptors: generalConf.UnaryInterceptors, 430 ConnectionTimeout: generalConf.ConnectionTimeout, 431 ServerStatsHandler: generalConf.ServerStatsHandler, 432 Logger: generalConf.Logger, 433 KaOpts: generalConf.KaOpts, 434 SecOpts: comm.SecureOptions{ 435 TimeShift: conf.General.Cluster.TLSHandshakeTimeShift, 436 CipherSuites: comm.DefaultTLSCipherSuites, 437 ClientRootCAs: clientRootCAs, 438 RequireClientCert: true, 439 Certificate: cert, 440 UseTLS: true, 441 Key: key, 442 }, 443 } 444 445 srv, err := comm.NewGRPCServer(bindAddr, serverConf) 446 if err != nil { 447 logger.Panicf("Failed creating gRPC server on %s:%d due to %v", clusterConf.ListenAddress, clusterConf.ListenPort, err) 448 } 449 450 return serverConf, srv 451 } 452 453 func initializeClusterClientConfig(conf *localconfig.TopLevel) comm.ClientConfig { 454 cc := comm.ClientConfig{ 455 AsyncConnect: true, 456 KaOpts: comm.DefaultKeepaliveOptions, 457 Timeout: conf.General.Cluster.DialTimeout, 458 SecOpts: comm.SecureOptions{}, 459 } 460 461 if conf.General.Cluster.ClientCertificate == "" { 462 return cc 463 } 464 465 certFile := conf.General.Cluster.ClientCertificate 466 certBytes, err := ioutil.ReadFile(certFile) 467 if err != nil { 468 logger.Fatalf("Failed to load client TLS certificate file '%s' (%s)", certFile, err) 469 } 470 471 keyFile := conf.General.Cluster.ClientPrivateKey 472 keyBytes, err := ioutil.ReadFile(keyFile) 473 if err != nil { 474 logger.Fatalf("Failed to load client TLS key file '%s' (%s)", keyFile, err) 475 } 476 477 var serverRootCAs [][]byte 478 for _, serverRoot := range conf.General.Cluster.RootCAs { 479 rootCACert, err := ioutil.ReadFile(serverRoot) 480 if err != nil { 481 logger.Fatalf("Failed to load ServerRootCAs file '%s' (%s)", serverRoot, err) 482 } 483 serverRootCAs = append(serverRootCAs, rootCACert) 484 } 485 486 cc.SecOpts = comm.SecureOptions{ 487 TimeShift: conf.General.Cluster.TLSHandshakeTimeShift, 488 RequireClientCert: true, 489 CipherSuites: comm.DefaultTLSCipherSuites, 490 ServerRootCAs: serverRootCAs, 491 Certificate: certBytes, 492 Key: keyBytes, 493 UseTLS: true, 494 } 495 496 return cc 497 } 498 499 func initializeServerConfig(conf *localconfig.TopLevel, metricsProvider metrics.Provider) comm.ServerConfig { 500 // secure server config 501 secureOpts := comm.SecureOptions{ 502 UseTLS: conf.General.TLS.Enabled, 503 RequireClientCert: conf.General.TLS.ClientAuthRequired, 504 } 505 // check to see if TLS is enabled 506 if secureOpts.UseTLS { 507 msg := "TLS" 508 // load crypto material from files 509 serverCertificate, err := ioutil.ReadFile(conf.General.TLS.Certificate) 510 if err != nil { 511 logger.Fatalf("Failed to load server Certificate file '%s' (%s)", 512 conf.General.TLS.Certificate, err) 513 } 514 serverKey, err := ioutil.ReadFile(conf.General.TLS.PrivateKey) 515 if err != nil { 516 logger.Fatalf("Failed to load PrivateKey file '%s' (%s)", 517 conf.General.TLS.PrivateKey, err) 518 } 519 var serverRootCAs, clientRootCAs [][]byte 520 for _, serverRoot := range conf.General.TLS.RootCAs { 521 root, err := ioutil.ReadFile(serverRoot) 522 if err != nil { 523 logger.Fatalf("Failed to load ServerRootCAs file '%s' (%s)", 524 err, serverRoot) 525 } 526 serverRootCAs = append(serverRootCAs, root) 527 } 528 if secureOpts.RequireClientCert { 529 for _, clientRoot := range conf.General.TLS.ClientRootCAs { 530 root, err := ioutil.ReadFile(clientRoot) 531 if err != nil { 532 logger.Fatalf("Failed to load ClientRootCAs file '%s' (%s)", 533 err, clientRoot) 534 } 535 clientRootCAs = append(clientRootCAs, root) 536 } 537 msg = "mutual TLS" 538 } 539 secureOpts.Key = serverKey 540 secureOpts.Certificate = serverCertificate 541 secureOpts.ServerRootCAs = serverRootCAs 542 secureOpts.ClientRootCAs = clientRootCAs 543 logger.Infof("Starting orderer with %s enabled", msg) 544 } 545 kaOpts := comm.DefaultKeepaliveOptions 546 // keepalive settings 547 // ServerMinInterval must be greater than 0 548 if conf.General.Keepalive.ServerMinInterval > time.Duration(0) { 549 kaOpts.ServerMinInterval = conf.General.Keepalive.ServerMinInterval 550 } 551 kaOpts.ServerInterval = conf.General.Keepalive.ServerInterval 552 kaOpts.ServerTimeout = conf.General.Keepalive.ServerTimeout 553 554 commLogger := flogging.MustGetLogger("core.comm").With("server", "Orderer") 555 556 if metricsProvider == nil { 557 metricsProvider = &disabled.Provider{} 558 } 559 560 return comm.ServerConfig{ 561 SecOpts: secureOpts, 562 KaOpts: kaOpts, 563 Logger: commLogger, 564 ServerStatsHandler: comm.NewServerStatsHandler(metricsProvider), 565 ConnectionTimeout: conf.General.ConnectionTimeout, 566 StreamInterceptors: []grpc.StreamServerInterceptor{ 567 grpcmetrics.StreamServerInterceptor(grpcmetrics.NewStreamMetrics(metricsProvider)), 568 grpclogging.StreamServerInterceptor(flogging.MustGetLogger("comm.grpc.server").Zap()), 569 }, 570 UnaryInterceptors: []grpc.UnaryServerInterceptor{ 571 grpcmetrics.UnaryServerInterceptor(grpcmetrics.NewUnaryMetrics(metricsProvider)), 572 grpclogging.UnaryServerInterceptor( 573 flogging.MustGetLogger("comm.grpc.server").Zap(), 574 grpclogging.WithLeveler(grpclogging.LevelerFunc(grpcLeveler)), 575 ), 576 }, 577 } 578 } 579 580 func grpcLeveler(ctx context.Context, fullMethod string) zapcore.Level { 581 switch fullMethod { 582 case "/orderer.Cluster/Step": 583 return flogging.DisabledLevel 584 default: 585 return zapcore.InfoLevel 586 } 587 } 588 589 func extractBootstrapBlock(conf *localconfig.TopLevel) *cb.Block { 590 var bootstrapBlock *cb.Block 591 592 // Select the bootstrapping mechanism 593 switch conf.General.BootstrapMethod { 594 case "file": // For now, "file" is the only supported genesis method 595 bootstrapBlock = file.New(conf.General.BootstrapFile).GenesisBlock() 596 case "none": // simply honor the configuration value 597 return nil 598 default: 599 logger.Panic("Unknown genesis method:", conf.General.BootstrapMethod) 600 } 601 602 return bootstrapBlock 603 } 604 605 func initializeBootstrapChannel(genesisBlock *cb.Block, lf blockledger.Factory) { 606 chainID, err := protoutil.GetChainIDFromBlock(genesisBlock) 607 if err != nil { 608 logger.Fatal("Failed to parse channel ID from genesis block:", err) 609 } 610 gl, err := lf.GetOrCreate(chainID) 611 if err != nil { 612 logger.Fatal("Failed to create the system channel:", err) 613 } 614 615 if err := gl.Append(genesisBlock); err != nil { 616 logger.Fatal("Could not write genesis block to ledger:", err) 617 } 618 } 619 620 func isClusterType(genesisBlock *cb.Block, bccsp bccsp.BCCSP) bool { 621 _, exists := clusterTypes[consensusType(genesisBlock, bccsp)] 622 return exists 623 } 624 625 func consensusType(genesisBlock *cb.Block, bccsp bccsp.BCCSP) string { 626 if genesisBlock == nil || genesisBlock.Data == nil || len(genesisBlock.Data.Data) == 0 { 627 logger.Fatalf("Empty genesis block") 628 } 629 env := &cb.Envelope{} 630 if err := proto.Unmarshal(genesisBlock.Data.Data[0], env); err != nil { 631 logger.Fatalf("Failed to unmarshal the genesis block's envelope: %v", err) 632 } 633 bundle, err := channelconfig.NewBundleFromEnvelope(env, bccsp) 634 if err != nil { 635 logger.Fatalf("Failed creating bundle from the genesis block: %v", err) 636 } 637 ordConf, exists := bundle.OrdererConfig() 638 if !exists { 639 logger.Fatalf("Orderer config doesn't exist in bundle derived from genesis block") 640 } 641 return ordConf.ConsensusType() 642 } 643 644 func initializeGrpcServer(conf *localconfig.TopLevel, serverConfig comm.ServerConfig) *comm.GRPCServer { 645 lis, err := net.Listen("tcp", fmt.Sprintf("%s:%d", conf.General.ListenAddress, conf.General.ListenPort)) 646 if err != nil { 647 logger.Fatal("Failed to listen:", err) 648 } 649 650 // Create GRPC server - return if an error occurs 651 grpcServer, err := comm.NewGRPCServerFromListener(lis, serverConfig) 652 if err != nil { 653 logger.Fatal("Failed to return new GRPC server:", err) 654 } 655 656 return grpcServer 657 } 658 659 func loadLocalMSP(conf *localconfig.TopLevel) msp.MSP { 660 // MUST call GetLocalMspConfig first, so that default BCCSP is properly 661 // initialized prior to LoadByType. 662 mspConfig, err := msp.GetLocalMspConfig(conf.General.LocalMSPDir, conf.General.BCCSP, conf.General.LocalMSPID) 663 if err != nil { 664 logger.Panicf("Failed to get local msp config: %v", err) 665 } 666 667 typ := msp.ProviderTypeToString(msp.FABRIC) 668 opts, found := msp.Options[typ] 669 if !found { 670 logger.Panicf("MSP option for type %s is not found", typ) 671 } 672 673 localmsp, err := msp.New(opts, factory.GetDefault()) 674 if err != nil { 675 logger.Panicf("Failed to load local MSP: %v", err) 676 } 677 678 if err = localmsp.Setup(mspConfig); err != nil { 679 logger.Panicf("Failed to setup local msp with config: %v", err) 680 } 681 682 return localmsp 683 } 684 685 //go:generate counterfeiter -o mocks/health_checker.go -fake-name HealthChecker . healthChecker 686 687 // HealthChecker defines the contract for health checker 688 type healthChecker interface { 689 RegisterChecker(component string, checker healthz.HealthChecker) error 690 } 691 692 func initializeMultichannelRegistrar( 693 bootstrapBlock *cb.Block, 694 ri *replicationInitiator, 695 clusterDialer *cluster.PredicateDialer, 696 srvConf comm.ServerConfig, 697 srv *comm.GRPCServer, 698 conf *localconfig.TopLevel, 699 signer identity.SignerSerializer, 700 metricsProvider metrics.Provider, 701 healthChecker healthChecker, 702 lf blockledger.Factory, 703 bccsp bccsp.BCCSP, 704 callbacks ...channelconfig.BundleActor, 705 ) *multichannel.Registrar { 706 707 registrar := multichannel.NewRegistrar(*conf, lf, signer, metricsProvider, bccsp, callbacks...) 708 709 consenters := map[string]consensus.Consenter{} 710 711 var icr etcdraft.InactiveChainRegistry 712 if conf.General.BootstrapMethod == "file" && isClusterType(bootstrapBlock, bccsp) { 713 etcdConsenter := initializeEtcdraftConsenter(consenters, conf, lf, clusterDialer, bootstrapBlock, ri, srvConf, srv, registrar, metricsProvider, bccsp) 714 icr = etcdConsenter.InactiveChainRegistry 715 } 716 717 consenters["solo"] = solo.New() 718 var kafkaMetrics *kafka.Metrics 719 consenters["kafka"], kafkaMetrics = kafka.New(conf.Kafka, metricsProvider, healthChecker, icr, registrar.CreateChain) 720 // Note, we pass a 'nil' channel here, we could pass a channel that 721 // closes if we wished to cleanup this routine on exit. 722 go kafkaMetrics.PollGoMetricsUntilStop(time.Minute, nil) 723 registrar.Initialize(consenters) 724 return registrar 725 } 726 727 func initializeEtcdraftConsenter( 728 consenters map[string]consensus.Consenter, 729 conf *localconfig.TopLevel, 730 lf blockledger.Factory, 731 clusterDialer *cluster.PredicateDialer, 732 bootstrapBlock *cb.Block, 733 ri *replicationInitiator, 734 srvConf comm.ServerConfig, 735 srv *comm.GRPCServer, 736 registrar *multichannel.Registrar, 737 metricsProvider metrics.Provider, 738 bccsp bccsp.BCCSP, 739 ) *etcdraft.Consenter { 740 replicationRefreshInterval := conf.General.Cluster.ReplicationBackgroundRefreshInterval 741 if replicationRefreshInterval == 0 { 742 replicationRefreshInterval = defaultReplicationBackgroundRefreshInterval 743 } 744 745 systemChannelName, err := protoutil.GetChainIDFromBlock(bootstrapBlock) 746 if err != nil { 747 ri.logger.Panicf("Failed extracting system channel name from bootstrap block: %v", err) 748 } 749 systemLedger, err := lf.GetOrCreate(systemChannelName) 750 if err != nil { 751 ri.logger.Panicf("Failed obtaining system channel (%s) ledger: %v", systemChannelName, err) 752 } 753 getConfigBlock := func() *cb.Block { 754 return multichannel.ConfigBlock(systemLedger) 755 } 756 757 exponentialSleep := exponentialDurationSeries(replicationBackgroundInitialRefreshInterval, replicationRefreshInterval) 758 ticker := newTicker(exponentialSleep) 759 760 icr := &inactiveChainReplicator{ 761 logger: logger, 762 scheduleChan: ticker.C, 763 quitChan: make(chan struct{}), 764 replicator: ri, 765 chains2CreationCallbacks: make(map[string]chainCreation), 766 retrieveLastSysChannelConfigBlock: getConfigBlock, 767 registerChain: ri.registerChain, 768 } 769 770 // Use the inactiveChainReplicator as a channel lister, since it has knowledge 771 // of all inactive chains. 772 // This is to prevent us pulling the entire system chain when attempting to enumerate 773 // the channels in the system. 774 ri.channelLister = icr 775 776 go icr.run() 777 raftConsenter := etcdraft.New(clusterDialer, conf, srvConf, srv, registrar, icr, metricsProvider, bccsp) 778 consenters["etcdraft"] = raftConsenter 779 return raftConsenter 780 } 781 782 func newOperationsSystem(ops localconfig.Operations, metrics localconfig.Metrics) *operations.System { 783 return operations.NewSystem(operations.Options{ 784 Logger: flogging.MustGetLogger("orderer.operations"), 785 ListenAddress: ops.ListenAddress, 786 Metrics: operations.MetricsOptions{ 787 Provider: metrics.Provider, 788 Statsd: &operations.Statsd{ 789 Network: metrics.Statsd.Network, 790 Address: metrics.Statsd.Address, 791 WriteInterval: metrics.Statsd.WriteInterval, 792 Prefix: metrics.Statsd.Prefix, 793 }, 794 }, 795 TLS: operations.TLS{ 796 Enabled: ops.TLS.Enabled, 797 CertFile: ops.TLS.Certificate, 798 KeyFile: ops.TLS.PrivateKey, 799 ClientCertRequired: ops.TLS.ClientAuthRequired, 800 ClientCACertFiles: ops.TLS.ClientRootCAs, 801 }, 802 Version: metadata.Version, 803 }) 804 } 805 806 // caMgr manages certificate authorities scoped by channel 807 type caManager struct { 808 sync.Mutex 809 appRootCAsByChain map[string][][]byte 810 ordererRootCAsByChain map[string][][]byte 811 clientRootCAs [][]byte 812 } 813 814 func (mgr *caManager) updateTrustedRoots( 815 cm channelconfig.Resources, 816 servers ...*comm.GRPCServer, 817 ) { 818 mgr.Lock() 819 defer mgr.Unlock() 820 821 appRootCAs := [][]byte{} 822 ordererRootCAs := [][]byte{} 823 appOrgMSPs := make(map[string]struct{}) 824 ordOrgMSPs := make(map[string]struct{}) 825 826 if ac, ok := cm.ApplicationConfig(); ok { 827 //loop through app orgs and build map of MSPIDs 828 for _, appOrg := range ac.Organizations() { 829 appOrgMSPs[appOrg.MSPID()] = struct{}{} 830 } 831 } 832 833 if ac, ok := cm.OrdererConfig(); ok { 834 //loop through orderer orgs and build map of MSPIDs 835 for _, ordOrg := range ac.Organizations() { 836 ordOrgMSPs[ordOrg.MSPID()] = struct{}{} 837 } 838 } 839 840 if cc, ok := cm.ConsortiumsConfig(); ok { 841 for _, consortium := range cc.Consortiums() { 842 //loop through consortium orgs and build map of MSPIDs 843 for _, consortiumOrg := range consortium.Organizations() { 844 appOrgMSPs[consortiumOrg.MSPID()] = struct{}{} 845 } 846 } 847 } 848 849 cid := cm.ConfigtxValidator().ChannelID() 850 logger.Debugf("updating root CAs for channel [%s]", cid) 851 msps, err := cm.MSPManager().GetMSPs() 852 if err != nil { 853 logger.Errorf("Error getting root CAs for channel %s (%s)", cid, err) 854 return 855 } 856 for k, v := range msps { 857 // check to see if this is a FABRIC MSP 858 if v.GetType() == msp.FABRIC { 859 for _, root := range v.GetTLSRootCerts() { 860 // check to see of this is an app org MSP 861 if _, ok := appOrgMSPs[k]; ok { 862 logger.Debugf("adding app root CAs for MSP [%s]", k) 863 appRootCAs = append(appRootCAs, root) 864 } 865 // check to see of this is an orderer org MSP 866 if _, ok := ordOrgMSPs[k]; ok { 867 logger.Debugf("adding orderer root CAs for MSP [%s]", k) 868 ordererRootCAs = append(ordererRootCAs, root) 869 } 870 } 871 for _, intermediate := range v.GetTLSIntermediateCerts() { 872 // check to see of this is an app org MSP 873 if _, ok := appOrgMSPs[k]; ok { 874 logger.Debugf("adding app root CAs for MSP [%s]", k) 875 appRootCAs = append(appRootCAs, intermediate) 876 } 877 // check to see of this is an orderer org MSP 878 if _, ok := ordOrgMSPs[k]; ok { 879 logger.Debugf("adding orderer root CAs for MSP [%s]", k) 880 ordererRootCAs = append(ordererRootCAs, intermediate) 881 } 882 } 883 } 884 } 885 mgr.appRootCAsByChain[cid] = appRootCAs 886 mgr.ordererRootCAsByChain[cid] = ordererRootCAs 887 888 // now iterate over all roots for all app and orderer chains 889 trustedRoots := [][]byte{} 890 for _, roots := range mgr.appRootCAsByChain { 891 trustedRoots = append(trustedRoots, roots...) 892 } 893 for _, roots := range mgr.ordererRootCAsByChain { 894 trustedRoots = append(trustedRoots, roots...) 895 } 896 // also need to append statically configured root certs 897 if len(mgr.clientRootCAs) > 0 { 898 trustedRoots = append(trustedRoots, mgr.clientRootCAs...) 899 } 900 901 // now update the client roots for the gRPC server 902 for _, srv := range servers { 903 err = srv.SetClientRootCAs(trustedRoots) 904 if err != nil { 905 msg := "Failed to update trusted roots for orderer from latest config " + 906 "block. This orderer may not be able to communicate " + 907 "with members of channel %s (%s)" 908 logger.Warningf(msg, cm.ConfigtxValidator().ChannelID(), err) 909 } 910 } 911 } 912 913 func (mgr *caManager) updateClusterDialer( 914 clusterDialer *cluster.PredicateDialer, 915 localClusterRootCAs [][]byte, 916 ) { 917 mgr.Lock() 918 defer mgr.Unlock() 919 920 // Iterate over all orderer root CAs for all chains and add them 921 // to the root CAs 922 var clusterRootCAs [][]byte 923 for _, roots := range mgr.ordererRootCAsByChain { 924 clusterRootCAs = append(clusterRootCAs, roots...) 925 } 926 927 // Add the local root CAs too 928 clusterRootCAs = append(clusterRootCAs, localClusterRootCAs...) 929 // Update the cluster config with the new root CAs 930 clusterDialer.UpdateRootCAs(clusterRootCAs) 931 } 932 933 func prettyPrintStruct(i interface{}) { 934 params := localconfig.Flatten(i) 935 var buffer bytes.Buffer 936 for i := range params { 937 buffer.WriteString("\n\t") 938 buffer.WriteString(params[i]) 939 } 940 logger.Infof("Orderer config values:%s\n", buffer.String()) 941 }