本文从Fabric-ca源码入手,以newRegisterCommand()函数为例,简单分析client启动时的过程。Fabric-ca源码可以从github.com下载,本文以v1.4.6为例进行简单分析。

与server相似,本文也是从main.go开始:

// fabric-ca/cmd/fabric-ca-client/main.go

package main

import (
...
) // The fabric-ca client main
func main() {
if err := command.RunMain(os.Args); err != nil {
os.Exit(1)
}
}

main()函数只是调用了package command中的RunMain()函数,所以接下来我们以RunMain()函数为起点来简析client端的启动过程,其中包括client端的初始化以及跟server端的初次交互:

// fabric-ca/cmd/fabric-ca-client/command/root.go  

package command

import "os"

// RunMain is the fabric-ca client main
func RunMain(args []string) error {
// Save the os.Args
saveOsArgs := os.Args
os.Args = args // Execute the command
cmdName := ""
if len(args) > 1 {
cmdName = args[1]
}
ccmd := NewCommand(cmdName)
err := ccmd.Execute() // Restore original os.Args
os.Args = saveOsArgs return err
}

不难看出,与server类似,都是先通过NewCommand()函数来添加命令,之后再通过Execute()来执行操作:

// fabric-ca/cmd/fabric-ca-client/command/clientcmd.go

// ClientCmd encapsulates cobra command that provides command line interface
// for the Fabric CA client and the configuration used by the Fabric CA client
type ClientCmd struct {
// name of the sub command
name string
// rootCmd is the base command for the Hyerledger Fabric CA client
rootCmd *cobra.Command
// My viper instance
myViper *viper.Viper
// cfgFileName is the name of the configuration file
cfgFileName string
// homeDirectory is the location of the client's home directory
homeDirectory string
// clientCfg is the client's configuration
clientCfg *lib.ClientConfig
// cfgAttrs are the attributes specified via flags or env variables
// and translated to Attributes field in registration
cfgAttrs []string
// cfgAttrReqs are the attribute requests specified via flags or env variables
// and translated to the AttrReqs field in enrollment
cfgAttrReqs []string
// cfgCsrNames are the certificate signing request names specified via flags
// or env variables
cfgCsrNames []string
// csrCommonName is the certificate signing request common name specified via the flag
csrCommonName string
// gencrl command argument values
crlParams crlArgs
// revoke command argument values
revokeParams revokeArgs
// profileMode is the profiling mode, cpu or mem or empty
profileMode string
// profileInst is the profiling instance object
profileInst interface {
Stop()
}
// Dynamically configuring identities
dynamicIdentity identityArgs
// Dynamically configuring affiliations
dynamicAffiliation affiliationArgs
// Set to log level
logLevel string
} // NewCommand returns new ClientCmd ready for running
func NewCommand(name string) *ClientCmd {
c := &ClientCmd{
myViper: viper.New(),
}
c.name = strings.ToLower(name)
c.init()
return c
} ... // init initializes the ClientCmd instance
// It intializes the cobra root and sub commands and
// registers command flgs with viper
func (c *ClientCmd) init() {
... c.rootCmd.AddCommand(c.newRegisterCommand(),
newEnrollCmd(c).getCommand(),
c.newReenrollCommand(),
c.newRevokeCommand(),
newGetCAInfoCmd(c).getCommand(),
c.newGenCsrCommand(),
c.newGenCRLCommand(),
c.newIdentityCommand(),
c.newAffiliationCommand(),
createCertificateCommand(c))
c.rootCmd.AddCommand(&cobra.Command{
Use: "version",
Short: "Prints Fabric CA Client version",
Run: func(cmd *cobra.Command, args []string) {
fmt.Print(metadata.GetVersionInfo(cmdName))
},
})
c.registerFlags()
...
}

在NewCommand()函数中,创建了一个*ClientCmd的对象,之后,调用该对象的init()方法。在init()方法中,首先实例化了*ClientCmd.rootCmd,其中会要执行checkAndEnableProfiling()来检查运行环境:

// checkAndEnableProfiling checks for the FABRIC_CA_CLIENT_PROFILE_MODE
// env variable, if it is set to "cpu", cpu profiling is enbled;
// if it is set to "heap", heap profiling is enabled
func (c *ClientCmd) checkAndEnableProfiling() error {
...
} // registerFlags registers command flags with viper
func (c *ClientCmd) registerFlags() {
...
}

之后会调用AddCommand()函数来添加newRegisterCommand()、newEnrollCmd(c).getCommand()、newReenrollCommand()、newRevokeCommand()、newGetCAInfoCmd(c).getCommand()、newGenCsrCommand()、newGenCRLCommand()、newIdentityCommand()、newAffiliationCommand()、createCertificateCommand()和获取client版本的命令。随后执行c.registerFlags()操作。registerFlags()函数中主要是注册一些命令行参数,这里就不细究了。

newRegisterCommand()

// fabric-ca/cmd/fabric-ca-client/command/register.go

func (c *ClientCmd) newRegisterCommand() *cobra.Command {
...
} // The client register main logic
func (c *ClientCmd) runRegister() error {
...
}

在newRegisterCommand()函数中,实例化了一个*cobra.Command命令对象,该对象中包含两个命令:ConfigInit()和runRegister()。ConfigInit()命令是为fabric-ca-client命令初始化一些配置,这里不做说明,而runRegister()中包含客户端注册的主要逻辑:首先实例化一个lib.Client结构体,之后导入client端的身份凭证client.LoadMyIdentity(),随后发起注册*Identity.Register()。

// fabric-ca/lib/client.go

// Client is the fabric-ca client object
type Client struct {
// The client's home directory
HomeDir string `json:"homeDir,omitempty"`
// The client's configuration
Config *ClientConfig
// Denotes if the client object is already initialized
initialized bool
// File and directory paths
keyFile, certFile, idemixCredFile, idemixCredsDir, ipkFile, caCertsDir string
// The crypto service provider (BCCSP)
csp bccsp.BCCSP
// HTTP client associated with this Fabric CA client
httpClient *http.Client
// Public key of Idemix issuer
issuerPublicKey *idemix.IssuerPublicKey
} // LoadMyIdentity loads the client's identity from disk
func (c *Client) LoadMyIdentity() (*Identity, error) {
...
return c.LoadIdentity(c.keyFile, c.certFile, c.idemixCredFile)
} // LoadIdentity loads an identity from disk
func (c *Client) LoadIdentity(keyFile, certFile, idemixCredFile string) (*Identity, error) {
...
return c.NewIdentity(creds)
} // NewIdentity creates a new identity
func (c *Client) NewIdentity(creds []credential.Credential) (*Identity, error) {
...
return NewIdentity(c, name, creds), nil
}

如上,在LoadMyIdentity()中会先调用Init()来初始化client,然后再调用LoadIdentity()函数,从硬盘中导入身份凭证。在LoadIdentity()中同样会调用Init()来初始化client,之后会调用NewCredential()接口来导入x509和idemin格式的证书。证书读取完成后,调用NewIdentity()来创建新的身份认证。至此,身份导入过程就完成了,接下来就是注册了。

//fabric-ca/lib/identity.go

// Register registers a new identity
// @param req The registration request
func (i *Identity) Register(req *api.RegistrationRequest) (rr *api.RegistrationResponse, err error) {
...
}

在Register(),会将认证请求序列后,通过Post请求发送给服务端,并将服务端的应答返回给调用者。

// Post sends arbitrary request body (reqBody) to an endpoint.
// This adds an authorization header which contains the signature
// of this identity over the body and non-signature part of the authorization header.
// The return value is the body of the response.
func (i *Identity) Post(endpoint string, reqBody []byte, result interface{}, queryParam map[string]string) error {
...
}

至此,注册命令就结束了。

Fabric-ca client端初始化过程源码分析的更多相关文章

  1. Bootstrap初始化过程源码分析--netty客户端的启动

    Bootstrap初始化过程 netty的客户端引导类是Bootstrap,我们看一下spark的rpc中客户端部分对Bootstrap的初始化过程 TransportClientFactory.cr ...

  2. A2dp初始化流程源码分析

    蓝牙启动的时候,会涉及到各个profile 的启动.这篇文章分析一下,蓝牙中a2dp profile的初始化流程. 我们从AdapterState.java中对于USER_TURN_ON 消息的处理说 ...

  3. A2dp sink 初始化流程源码分析

    A2dp sink的初始化流程和A2dp 的初始化流程,基本一样,这里做简单分析.这里分析的android的版本是Android O. 我们先从service的启动说起吧. 下面 是启动的时候的log ...

  4. Netty入门一:服务端应用搭建 & 启动过程源码分析

    最近周末也没啥事就学学Netty,同时打算写一些博客记录一下(写的过程理解更加深刻了) 本文主要从三个方法来呈现:Netty核心组件简介.Netty服务端创建.Netty启动过程源码分析 如果你对Ne ...

  5. SpringSecurity 初始化流程源码

    SpringSecurity 初始化流程源码 本篇主要讲解 SpringSecurity初始化流程的源码部分,包括核心的 springSecurityFilterChain 是如何创建的,以及在介绍哪 ...

  6. Spark(五十一):Spark On YARN(Yarn-Cluster模式)启动流程源码分析(二)

    上篇<Spark(四十九):Spark On YARN启动流程源码分析(一)>我们讲到启动SparkContext初始化,ApplicationMaster启动资源中,讲解的内容明显不完整 ...

  7. Dubbo消费方服务调用过程源码分析

    参考:dubbo消费方服务调用过程源码分析dubbo基于spring的构建分析Dubbo概述--调用过程dubbo 请求调用过程分析dubbo集群容错机制代码分析1dubbo集群容错策略的代码分析2d ...

  8. [Android]从Launcher开始启动App流程源码分析

    以下内容为原创,欢迎转载,转载请注明 来自天天博客:http://www.cnblogs.com/tiantianbyconan/p/5017056.html 从Launcher开始启动App流程源码 ...

  9. spark源码阅读--shuffle读过程源码分析

    shuffle读过程源码分析 上一篇中,我们分析了shuffle在map阶段的写过程.简单回顾一下,主要是将ShuffleMapTask计算的结果数据在内存中按照分区和key进行排序,过程中由于内存限 ...

  10. Spark(四十九):Spark On YARN启动流程源码分析(一)

    引导: 该篇章主要讲解执行spark-submit.sh提交到将任务提交给Yarn阶段代码分析. spark-submit的入口函数 一般提交一个spark作业的方式采用spark-submit来提交 ...

随机推荐

  1. Intellij IDEA 显示 access.log 日志

    先配置  SpringBoot 记录 access.log 日志,先让accesslog 显示出来

  2. dmesg 时间误差现象

    案例现象 这天收到监控平台发来的告警,说有台机器程序崩溃了 因为以前也有过相关的错误,根据经验,用 dmesg命令看下内核信息 发现有点不对劲,报错信息的时间跟告警时间不一致,正常来讲报错时间应该跟告 ...

  3. 2015年第六届 蓝桥杯B组 C/C++决赛题解

    1.积分之迷 小明开了个网上商店,卖风铃.共有3个品牌:A,B,C. 为了促销,每件商品都会返固定的积分. 小明开业第一天收到了三笔订单: 第一笔:3个A + 7个B + 1个C,共返积分:315 第 ...

  4. 针对Python基本数据类型的操作

    在学习Python语法前,请大家务必注意,Python是通过缩进来定义代码层次的,即同一层次的代码都是左对齐,而下个层次的代码块与当前代码块相比,会有4个空格的缩进. 这里缩进的空格数是约定俗成的,当 ...

  5. svg组件封装

    svg图标优点 文件体积小,能够被大量的压缩 图片可无限放大而不失真(矢量图的基本特征) 在视网膜显示屏上效果极佳 能够实现互动和滤镜效果 svg图标使用 1.安装相应的npm包: yarn add ...

  6. C# 排序算法5:归并排序

    归并排序,是将两个(或两个以上)有序表合并成一个新的有序表,即把待排序序列分为若干个有序的子序列,再把有序的子序列合并为整体有序序列.该算法是采用分治法. 原理: 1.申请空间,使其大小为两个已经排序 ...

  7. java进阶(25)--泛型

    一.泛型基本概念 JDK5.0后新特性:Generic 1.不使用泛型举例

  8. java使用递归及迭代方式实现前序遍历 中序遍历 后序遍历 以及实现层序遍历

    本文为博主原创,转载请注明出处: 目录: 一.快速理解前序,中序,后序遍历的区别 二.使用递归的方式实现前序,中序,后序遍历 三. 使用迭代的方式实现前序 中序 后序遍历 四.层序遍历 一.快速理解前 ...

  9. redis 持久化机制及配置

    本文为博主原创,未经允许不得转载: 目录: 1. RDB 2. AOF(append-only file) 3. RDB 和 AOF 特性比对 4. 混合持久化 redis 数据持久化共有两种方式:一 ...

  10. 【SHELL】获取脚本输入参数

    参数获取 EXEC_PARAMS=(${@:index}) 示例 ./do.sh test a b c d e f EXEC_PARAMS=(${@:0}) ./do.sh test a b c d ...