diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..b85972e --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +*.sh linguist-language=JAVA +*.py linguist-language=JAVA diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..e69de29 diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..ce76036 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,52 @@ +language: python +sudo: enabled +services: + - mysql +matrix: + include: + - name: "Python 2.7 on Xenial Linux" + python: 2.7 + dist: xenial + before_install: + - pip install MySQL-python + - name: "Python 3.4 on Xenial Linux" + python: 3.4 + dist: xenial + before_install: + - pip install PyMySQL + - name: "Python 3.5 on Xenial Linux" + python: 3.5 + dist: xenial + before_install: + - pip install PyMySQL + - name: "Python 3.6 on Xenial Linux" + python: 3.6 + dist: xenial + before_install: + - pip install PyMySQL + - name: "Python 3.7 on Xenial Linux" + python: 3.7 + dist: xenial + before_install: + - pip install PyMySQL +addons: + apt: + packages: + - git + - openssl + - curl + - nginx + homebrew: + packages: + - git + - openssl + - curl + - nginx +install: + - pip install -r requirements.txt +script: + - java -version + - cd deploy + - sed -i "s%dbUsername%root%g" common.properties + - sed -i "s%dbPassword%%g" common.properties + - python deploy.py installAll travis && python telnet.py diff --git a/README-en.md b/README-en.md new file mode 100644 index 0000000..9d1f39a --- /dev/null +++ b/README-en.md @@ -0,0 +1,43 @@ +[中文](README.md)|English + +![image](https://webasedoc.readthedocs.io/zh_CN/latest/_images/logo.jpg) + +# What's WeBASE? + +**WeBASE** (WeBank Blockchain Application Software Extension) is a set of general components building between blockchain application and FISCO-BCOS Nodes. Each module is designed around blockchain transaction, contract, key management, data and visual management. Developers can choose subsystems for deployment according to business needs. + +**WeBASE** shields the complexity of the bottom layer of the blockchain, reduces the threshold of developers, and greatly improves the development efficiency of the blockchain application. It includes subsystems such as node front, node management, web management platform, sign service, data export etc.. + +**WeBASE** standardizes the application and development of blockchain. After building the FISCO BCOS nodes, only five steps needed to develop and build the application of blockchain. For details of developing process, please refer to [Using WeBASE to develop blockchain application](https://github.com/WeBankFinTech/WeBASE-Doc/blob/master/docs/WeBASE/quick-start.md) + + **WeBASE One Click Installation** (including FISCO BCOS nodes + WeBASE-Front + WeBASE-Node-Manager + WeBASE-Web) refers to [WeBASE One-Click-Installation Documentation](https://webasedoc.readthedocs.io/zh_CN/latest/docs/WeBASE/install.html),**WeBASE**'s overall structure design and the detailed introduction of the functions and installation of each subsystem, please refer to [WeBASE Online Documentation](https://webasedoc.readthedocs.io/zh_CN/latest/index.html) + +## Subsystem introduction +* **Node Front service [WeBASE-Front](https://github.com/WeBankFinTech/WeBASE-Front)** +It integrates web3sdk and provides restful interface. The client can interact with the node in the form of HTTP. The built-in memory database collects the health data of the node. Built in Web console to realize the visual operation of nodes and solidity IDE etc.. + +* **Node management service [WeBASE-Node-Manager](https://github.com/WeBankFinTech/WeBASE-Node-Manager)** +Based on WeBASE-Front, handle all web requests from WeBASE-Web pages, manage the status of each node, manage all smart contracts on the chain, make statistics and Analysis on the data of the blockchain, audit abnormal transactions, private key management, etc. + +* **WeBASE management platform [WeBASE-Web](https://github.com/WeBankFinTech/WeBASE-Web)** +Visual operation platform, based on which node information can be viewed and smart contracts can be developed. + +* **Transcation service [WeBASE-Transcation](https://github.com/WeBankFinTech/WeBASE-Transcation)** +Receive transaction request, cache transaction to database and asynchronously chain up, which can greatly improve throughput and solve the TPS bottleneck problem of blockchain. + +* **Private key Hosting and cloud signature service [WeBASE-Sign](https://github.com/WeBankFinTech/WeBASE-Sign)** +Hosting user private key, providing cloud signature. + +* **Data export code generation tool [WeBASE-Codegen-Monkey](https://github.com/WeBankFinTech/WeBASE-Codegen-Monkey)** +The code generation tool can generate the core code of data export through configuration. + +* **Data export service [WeBASE-Collect-Bee](https://github.com/WeBankFinTech/WeBASE-Collect-Bee)** +Export the basic data on the blockchain, such as the current block height, total transaction volume, etc. export the business data of the contract on the blockchain, including the event, constructor, contract address, execution function information, etc. through the configuration of the smart contract. + +## Contribution +Please read our [contribution document](https://webasedoc.readthedocs.io/zh_CN/latest/docs/WeBASE/CONTRIBUTING.html) to learn how to contribute your code and submit your contribution. + +I hope that with your participation, WeBASE will get better and better! + +## Community +Contact us: webase@webank.com diff --git a/README.md b/README.md new file mode 100644 index 0000000..54ce59c --- /dev/null +++ b/README.md @@ -0,0 +1,54 @@ +中文|[English](README-en.md) + +![image](https://webasedoc.readthedocs.io/zh_CN/latest/_images/logo.jpg) + +# 什么是WeBASE + +**WeBASE**(WeBank Blockchain Application Software Extension) 是在区块链应用和FISCO BCOS节点之间搭建的一套通用组件,围绕交易、合约、密钥管理,数据,可视化管理来设计各个模块;开发者可以根据业务所需,选择子系统进行部署。 + +**WeBASE**屏蔽了区块链底层的复杂度,降低开发者的门槛,大幅提高区块链应用的开发效率,包含**节点前置**、**节点管理**、**Web管理平台**、**签名服务**、**数据导出**等子系统。 + +**WeBASE**将区块链应用开发标准化,搭建完FISCO BCOS节点后,只需按照五步标准流程进行区块链应用开发,开发流程请参阅 [使用WeBASE开发区块链应用](https://github.com/WeBankFinTech/WeBASE-Doc/blob/master/docs/WeBASE/quick-start.md) + +**WeBASE一键部署**(FISCO BCOS + WeBASE-Front + WeBASE-Node-Manager + WeBASE-Sign + WeBASE-Web)可以参考[WeBASE一键部署文档](https://webasedoc.readthedocs.io/zh_CN/latest/docs/WeBASE/install.html),**WeBASE**整体结构设计与各子系统功能与安装部署的详细介绍,请参考[WeBASE在线文档](https://webasedoc.readthedocs.io/zh_CN/latest/index.html) + +## 各子系统简介 +* **节点前置服务 [WeBASE-Front](https://github.com/WeBankFinTech/WeBASE-Front)** +集成web3sdk,提供restful风格的接口,客户端可以使用http的形式和节点进行交互,内置内存数据库,采集节点健康度数据。内置web控制台,实现节点的可视化、合约部署IDE等功能。 + +* **节点管理服务 [WeBASE-Node-Manager](https://github.com/WeBankFinTech/WeBASE-Node-Manager)** +处理WeBASE-Web前端页面所有web请求,基于前置服务,管理各个节点的状态,管理链上所有智能合约,对区块链的数据进行统计、分析,对异常交易的审计,私钥管理等。 + +* **WeBASE管理平台 [WeBASE-Web](https://github.com/WeBankFinTech/WeBASE-Web)** +基于节点管理服务的可视化操作平台,可基于此平台查看节点信息,开发智能合约等。 + +* **交易服务 [WeBASE-Transcation](https://github.com/WeBankFinTech/WeBASE-Transcation)** +接收交易请求,缓存交易到数据库中,异步上链,可大幅提升吞吐量,解决区块链的tps瓶颈问题。 + +* **私钥托管和签名服务 [WeBASE-Sign](https://github.com/WeBankFinTech/WeBASE-Sign)** +托管用户私钥,提供云端签名。 + +* **数据导出代码生成工具 [WeBASE-Codegen-Monkey](https://github.com/WeBankFinTech/WeBASE-Codegen-Monkey)** +代码生成工具,通过配置可以生成数据导出的核心代码。 + +* **数据导出服务 [WeBASE-Collect-Bee](https://github.com/WeBankFinTech/WeBASE-Collect-Bee)** +导出区块链上的基础数据,如当前块高、交易总量等,通过智能合约的配置,导出区块链上合约的业务数据,包括event、构造函数、合约地址、执行函数的信息等。 + +* **链管理服务 [WeBASE-Chain-Manager](https://github.com/WeBankFinTech/WeBASE-Chain-Manager)** +链管理服务支持管理多条链,支持国密链、非国密链。对外提供群组的增删查改接口,让用户可以便捷地建立自己应用的群组。 + +* **合约安全检测服务 [WeBASE-Solidity-Security](https://github.com/WeBankFinTech/WeBASE-Solidity-Security)** +合约安全检测服务继承了solidity合约检测工具slither,对外提供检测接口。 + +* **数据统计服务 [WeBASE-Stat](https://github.com/WeBankFinTech/WeBASE-Stat)** +统计数据服务以前置为基础,拉取CPU、内存、IO、群组大小、群组gas、群组网络流量的数据,记录数据库。 + + +## 贡献说明 +请阅读我们的[贡献文档](https://webasedoc.readthedocs.io/zh_CN/latest/docs/WeBASE/CONTRIBUTING.html),了解如何贡献代码,并提交你的贡献。 + +希望在您的参与下,WeBASE会越来越好! + +## 社区 +联系我们:webase@webank.com + diff --git a/deploy/README-en.md b/deploy/README-en.md new file mode 100644 index 0000000..d1fcee3 --- /dev/null +++ b/deploy/README-en.md @@ -0,0 +1,12 @@ +# Quick build +## Introduction + +One-click deployment quickly builds A WeBASE management desk environment. Includes node (FISCO-BCOS 2.0), node front subsystem (WeBASE-Front), private key and sign managerment subsystem (WeBASE-Sign), node management subsystem (WeBASE-Node-Manager), management platform (WeBASE-Web). Among them, the configuration of the node is optional, you can choose to use the existing chain or build a new chain. For more information, check out the online documentation for one-click deployment (https://webasedoc.readthedocs.io/zh_CN/latest/docs/WeBASE/install.html). + +## A description of the contribution +Read our contribution documentation to learn how to contribute code and submit your contribution. + +Hopefully with your participation, WeBASE will get better and better! + +## The community +Contact us: webase@webank.com diff --git a/deploy/comm/__init__.py b/deploy/comm/__init__.py new file mode 100644 index 0000000..fc51ec7 --- /dev/null +++ b/deploy/comm/__init__.py @@ -0,0 +1,6 @@ +#!/usr/bin/env python3 + +import sys +if sys.version_info.major == 3: + import pymysql + pymysql.install_as_MySQLdb() \ No newline at end of file diff --git a/deploy/comm/build.py b/deploy/comm/build.py new file mode 100644 index 0000000..1a7402d --- /dev/null +++ b/deploy/comm/build.py @@ -0,0 +1,558 @@ +#!/usr/bin/python3 +# encoding: utf-8 + +import sys +import os +from .utils import * +from .mysql import * + +baseDir = getBaseDir() +currentDir = getCurrentBaseDir() + +def do(): + print ("===================== deploy start... =====================") + installNode() + installWeb() + installManager() + installSign() + installFront() + print ("===================== deploy end... =====================") + os.chdir(currentDir) + web_version = getCommProperties("webase.web.version") + mgr_version = getCommProperties("webase.mgr.version") + sign_version = getCommProperties("webase.sign.version") + front_version = getCommProperties("webase.front.version") + + print ("===================== webase-web version {} =====================".format(web_version)) + print ("===================== webase-node-mgr version {} =====================".format(mgr_version)) + print ("===================== webase-sign version {} =====================".format(sign_version)) + print ("===================== webase-front version {} =====================".format(front_version)) + print ("================================================================") + return + +def start(): + startNode() + startWeb() + startManager() + startSign() + startFront() + return + +def end(): + stopNode() + stopWeb() + stopManager() + stopSign() + stopFront() + return + +def installNode(): + if_exist_fisco = getCommProperties("if.exist.fisco") + node_p2pPort = int(getCommProperties("node.p2pPort")) + node_channelPort = int(getCommProperties("node.channelPort")) + node_rpcPort = int(getCommProperties("node.rpcPort")) + fisco_version = getCommProperties("fisco.version") + node_counts = getCommProperties("node.counts") + encrypt_type = int(getCommProperties("encrypt.type")) + + if if_exist_fisco == "no": + print ("================================================================") + print ("============== FISCO-BCOS install... ==============") + # init configure file + if not os.path.exists(currentDir + "/nodetemp"): + doCmd('cp -f nodeconf nodetemp') + else: + doCmd('cp -f nodetemp nodeconf') + + node_nums = 2 + if node_counts != "nodeCounts": + node_nums = int(node_counts) + doCmd('sed -i "s/nodeCounts/{}/g" nodeconf'.format(node_nums)) + doCmdIgnoreException("dos2unix nodeconf") + + gitComm = "wget https://github.com/FISCO-BCOS/FISCO-BCOS/releases/download/v{}/build_chain.sh && chmod u+x build_chain.sh".format(fisco_version) + if not os.path.exists("{}/nodes".format(currentDir)): + print (gitComm) + os.system(gitComm) + if encrypt_type == 1: + os.system("bash build_chain.sh -f nodeconf -p {},{},{} -v {} -i -g".format(node_p2pPort, node_channelPort, node_rpcPort, fisco_version)) + else: + os.system("bash build_chain.sh -f nodeconf -p {},{},{} -v {} -i".format(node_p2pPort, node_channelPort, node_rpcPort, fisco_version)) + else: + info = "n" + if sys.version_info.major == 2: + info = raw_input("FISCO-BCOS node directory “nodes” already exists. Reinstall or not?[y/n]:") + else: + info = input("FISCO-BCOS node directory “nodes” already exists. Reinstall or not?[y/n]:") + if info == "y" or info == "Y": + doCmdIgnoreException("bash nodes/127.0.0.1/stop_all.sh") + doCmd("rm -rf nodes") + print (gitComm) + os.system(gitComm) + if encrypt_type == 1: + os.system("bash build_chain.sh -f nodeconf -p {},{},{} -v {} -i -g".format(node_p2pPort, node_channelPort, node_rpcPort, fisco_version)) + else: + os.system("bash build_chain.sh -f nodeconf -p {},{},{} -v {} -i".format(node_p2pPort, node_channelPort, node_rpcPort, fisco_version)) + startNode() + +def startNode(): + print ("============== FISCO-BCOS start... ==============") + if_exist_fisco = getCommProperties("if.exist.fisco") + fisco_dir = getCommProperties("fisco.dir") + if if_exist_fisco == "no": + fisco_dir = currentDir + "/nodes/127.0.0.1" + + if not os.path.exists(fisco_dir + "/start_all.sh"): + print ("======= FISCO-BCOS dir:{} is not correct. please check! =======".format(fisco_dir)) + sys.exit(0) + os.chdir(fisco_dir) + doCmdIgnoreException("chmod u+x *.sh") + doCmdIgnoreException("dos2unix *.sh") + os.system("bash start_all.sh") + print ("============== FISCO-BCOS end... ==============") + return + +def stopNode(): + if_exist_fisco = getCommProperties("if.exist.fisco") + fisco_dir = getCommProperties("fisco.dir") + if if_exist_fisco == "no": + fisco_dir = currentDir + "/nodes/127.0.0.1" + + if not os.path.exists(fisco_dir + "/stop_all.sh"): + print ("======= FISCO-BCOS dir:{} is not correct. please check! =======".format(fisco_dir)) + sys.exit(0) + os.chdir(fisco_dir) + doCmdIgnoreException("chmod u+x *.sh") + doCmdIgnoreException("dos2unix *.sh") + os.system("bash stop_all.sh") + return + +def changeWebConfig(): + # get properties + deploy_ip = "127.0.0.1" + web_port = getCommProperties("web.port") + mgr_port = getCommProperties("mgr.port") + + # init configure file + web_conf_dir = currentDir + "/comm" + if not os.path.exists(web_conf_dir + "/temp.conf"): + doCmd('cp -f {}/nginx.conf {}/temp.conf'.format(web_conf_dir, web_conf_dir)) + else: + doCmd('cp -f {}/temp.conf {}/nginx.conf'.format(web_conf_dir, web_conf_dir)) + + # change web config + web_dir = currentDir + "/webase-web" + web_log_dir = web_dir + "/log" + doCmd('mkdir -p {}'.format(web_log_dir)) + doCmd('sed -i "s/127.0.0.1/{}/g" {}/comm/nginx.conf'.format(deploy_ip, currentDir)) + doCmd('sed -i "s/5000/{}/g" {}/comm/nginx.conf'.format(web_port, currentDir)) + doCmd('sed -i "s/server 127.0.0.1:5001/server {}:{}/g" {}/comm/nginx.conf'.format(deploy_ip, mgr_port, currentDir)) + doCmd('sed -i "s:log_path:{}:g" {}/comm/nginx.conf'.format(web_log_dir, currentDir)) + doCmd('sed -i "s:web_page_url:{}:g" {}/comm/nginx.conf'.format(web_dir, currentDir)) + + return + +def installWeb(): + print ("================================================================") + print ("============== WeBASE-Web install... ==============") + os.chdir(currentDir) + web_version = getCommProperties("webase.web.version") + gitComm = "wget https://www.fisco.com.cn/cdn/webase/releases/download/{}/webase-web.zip".format(web_version) + pullSourceExtract(gitComm,"webase-web") + changeWebConfig() + startWeb() + +def startWeb(): + print ("============== WeBASE-Web start... ==============") + if os.path.exists("/run/nginx-webase-web.pid"): + info = "n" + if sys.version_info.major == 2: + info = raw_input("WeBASE-Web Process already exists. Kill process to force restart?[y/n]:") + else: + info = input("WeBASE-Web Process already exists. Kill process to force restart?[y/n]:") + if info == "y" or info == "Y": + fin = open('/run/nginx-webase-web.pid', 'r') + pid = fin.read() + cmd = "sudo kill -QUIT {}".format(pid) + os.system(cmd) + doCmdIgnoreException("sudo rm -rf /run/nginx-webase-web.pid") + else: + sys.exit(0) + web_log_dir = currentDir + "/webase-web/log" + doCmd('mkdir -p {}'.format(web_log_dir)) + nginx_config_dir = currentDir + "/comm/nginx.conf" + res = doCmd("which nginx") + if res["status"] == 0: + res2 = doCmd("sudo " + res["output"] + " -c " + nginx_config_dir) + if res2["status"] == 0: + print ("======= WeBASE-Web start success! =======") + else: + print ("======= WeBASE-Web start fail. Please view log file (default path:./webase-web/log/). =======") + sys.exit(0) + else: + print ("======= WeBASE-Web start fail. Please view log file (default path:./log/). =======") + sys.exit(0) + print ("============== WeBASE-Web end... ==============") + return + +def stopWeb(): + if os.path.exists("/run/nginx-webase-web.pid"): + fin = open('/run/nginx-webase-web.pid', 'r') + pid = fin.read() + cmd = "sudo kill -QUIT {}".format(pid) + os.system(cmd) + doCmdIgnoreException("sudo rm -rf /run/nginx-webase-web.pid") + print ("======= WeBASE-Web stop success! =======") + else: + print ("======= WeBASE-Web is not running! =======") + return + +def changeManagerConfig(): + # get properties + mgr_port = getCommProperties("mgr.port") + mysql_ip = getCommProperties("mysql.ip") + mysql_port = getCommProperties("mysql.port") + mysql_user = getCommProperties("mysql.user") + mysql_password = getCommProperties("mysql.password") + mysql_database = getCommProperties("mysql.database") + encrypt_type = int(getCommProperties("encrypt.type")) + + # init file + server_dir = currentDir + "/webase-node-mgr" + script_dir = server_dir + "/script" + script_dir_gm = script_dir + "/gm" + conf_dir = server_dir + "/conf" + if encrypt_type == 1: + if not os.path.exists(script_dir_gm + "/temp-gm.sh"): + doCmd('cp -f {}/webase-gm.sh {}/temp-gm.sh'.format(script_dir_gm, script_dir_gm)) + else: + doCmd('cp -f {}/temp-gm.sh {}/webase-gm.sh'.format(script_dir_gm, script_dir_gm)) + else: + if not os.path.exists(script_dir + "/temp.sh"): + doCmd('cp -f {}/webase.sh {}/temp.sh'.format(script_dir, script_dir)) + else: + doCmd('cp -f {}/temp.sh {}/webase.sh'.format(script_dir, script_dir)) + if not os.path.exists(conf_dir + "/temp.yml"): + doCmd('cp -f {}/application.yml {}/temp.yml'.format(conf_dir, conf_dir)) + else: + doCmd('cp -f {}/temp.yml {}/application.yml'.format(conf_dir, conf_dir)) + + # change script config + if encrypt_type == 1: + doCmd('sed -i "s/defaultAccount/{}/g" {}/webase-gm.sh'.format(mysql_user, script_dir_gm)) + doCmd('sed -i "s/defaultPassword/{}/g" {}/webase-gm.sh'.format(mysql_password, script_dir_gm)) + doCmd('sed -i "s/webasenodemanager/{}/g" {}/webase-gm.sh'.format(mysql_database, script_dir_gm)) + else: + doCmd('sed -i "s/defaultAccount/{}/g" {}/webase.sh'.format(mysql_user, script_dir)) + doCmd('sed -i "s/defaultPassword/{}/g" {}/webase.sh'.format(mysql_password, script_dir)) + doCmd('sed -i "s/webasenodemanager/{}/g" {}/webase.sh'.format(mysql_database, script_dir)) + + # change server config + doCmd('sed -i "s/5001/{}/g" {}/application.yml'.format(mgr_port, conf_dir)) + doCmd('sed -i "s/127.0.0.1/{}/g" {}/application.yml'.format(mysql_ip, conf_dir)) + doCmd('sed -i "s/3306/{}/g" {}/application.yml'.format(mysql_port, conf_dir)) + doCmd('sed -i "s/defaultAccount/{}/g" {}/application.yml'.format(mysql_user, conf_dir)) + doCmd('sed -i "s/defaultPassword/{}/g" {}/application.yml'.format(mysql_password, conf_dir)) + doCmd('sed -i "s/webasenodemanager/{}/g" {}/application.yml'.format(mysql_database, conf_dir)) + doCmd('sed -i "s%encryptType: 0%encryptType: {}%g" {}/application.yml'.format(encrypt_type, conf_dir)) + + return + +def installManager(): + print ("================================================================") + print ("============== WeBASE-Node-Manager install... ==============") + os.chdir(currentDir) + mgr_version = getCommProperties("webase.mgr.version") + encrypt_type = int(getCommProperties("encrypt.type")) + gitComm = "wget https://www.fisco.com.cn/cdn/webase/releases/download/{}/webase-node-mgr.zip".format(mgr_version) + pullSourceExtract(gitComm,"webase-node-mgr") + changeManagerConfig() + dbConnect() + + mysql_ip = getCommProperties("mysql.ip") + mysql_port = getCommProperties("mysql.port") + server_dir = currentDir + "/webase-node-mgr" + script_dir = server_dir + "/script" + script_cmd = 'bash webase.sh {} {}'.format(mysql_ip, mysql_port) + if encrypt_type == 1: + script_dir = script_dir + "/gm" + script_cmd = 'bash webase-gm.sh {} {}'.format(mysql_ip, mysql_port) + + if len(sys.argv) == 3 and sys.argv[2] == "travis": + print ("Travis CI do not initialize database") + else: + info = "n" + if sys.version_info.major == 2: + info = raw_input("Whether to initialize the data (the first deployment or rebuilding of the library needs to be performed)?[y/n]:") + else: + info = input("Whether to initialize the data (the first deployment or rebuilding of the library needs to be performed)?[y/n]:") + if info == "y" or info == "Y": + os.chdir(script_dir) + doCmdIgnoreException("chmod u+x *.sh") + doCmdIgnoreException("dos2unix *.sh") + dbResult = doCmd(script_cmd) + if dbResult["status"] == 0: + if_success = 'success' in dbResult["output"] + if if_success: + print ("======= script init success! =======") + else: + print ("======= script init fail! =======") + print (dbResult["output"]) + sys.exit(0) + else: + print ("======= script init fail. Please view log file (default path:./log/). =======") + sys.exit(0) + startManager() + return + +def startManager(): + print ("============== WeBASE-Node-Manager start... ==============") + os.chdir(currentDir) + managerPort = getCommProperties("mgr.port") + server_dir = currentDir + "/webase-node-mgr" + os.chdir(server_dir) + doCmdIgnoreException("source /etc/profile") + doCmdIgnoreException("chmod u+x *.sh") + doCmdIgnoreException("dos2unix *.sh") + result = doCmd("bash start.sh") + if result["status"] == 0: + if_started = 'is running' in result["output"] + if if_started: + pid = get_str_btw(result["output"], "(", ")") + print ("WeBASE-Node-Manager Port {} is running PID({})".format(managerPort,pid)) + sys.exit(0) + if_success = 'Starting' in result["output"] + if if_success: + print ("======= WeBASE-Node-Manager starting . Please check through the log file (default path:./webase-node-mgr/log/). =======") + else: + print ("======= WeBASE-Node-Manager start fail. Please check through the log file (default path:./webase-node-mgr/log/). =======") + sys.exit(0) + else: + print ("======= WeBASE-Node-Manager start fail. Please view log file (default path:./log/). =======") + sys.exit(0) + print ("============== WeBASE-Node-Manager end... ==============") + return + +def stopManager(): + server_dir = currentDir + "/webase-node-mgr" + os.chdir(server_dir) + doCmdIgnoreException("source /etc/profile") + doCmdIgnoreException("chmod u+x *.sh") + doCmdIgnoreException("dos2unix *.sh") + result = doCmd("bash stop.sh") + if result["status"] == 0: + if_success = 'Success' in result["output"] + if if_success: + print ("======= WeBASE-Node-Manager stop success! =======") + else: + print ("======= WeBASE-Node-Manager is not running! =======") + else: + print ("======= WeBASE-Node-Manager stop fail. Please view log file (default path:./log/). =======") + return + +def changeFrontConfig(): + # get properties + deploy_ip = "127.0.0.1" + sign_port = getCommProperties("sign.port") + frontPort = getCommProperties("front.port") + nodeListenIp = getCommProperties("node.listenIp") + nodeChannelPort = getCommProperties("node.channelPort") + frontDb = getCommProperties("front.h2.name") + encrypt_type = int(getCommProperties("encrypt.type")) + + if_exist_fisco = getCommProperties("if.exist.fisco") + fisco_dir = getCommProperties("fisco.dir") + node_dir = getCommProperties("node.dir") + if if_exist_fisco == "no": + fisco_dir = currentDir + "/nodes/127.0.0.1" + node_dir = currentDir + "/nodes/127.0.0.1/node0" + + # init file + server_dir = currentDir + "/webase-front/conf" + if not os.path.exists(server_dir + "/temp.yml"): + doCmd('cp -f {}/application.yml {}/temp.yml'.format(server_dir, server_dir)) + else: + doCmd('cp -f {}/temp.yml {}/application.yml'.format(server_dir, server_dir)) + + # change server config + doCmd('sed -i "s/5002/{}/g" {}/application.yml'.format(frontPort, server_dir)) + doCmd('sed -i "s/ip: 127.0.0.1/ip: {}/g" {}/application.yml'.format(nodeListenIp, server_dir)) + doCmd('sed -i "s/20200/{}/g" {}/application.yml'.format(nodeChannelPort, server_dir)) + doCmd('sed -i "s%encryptType: 0%encryptType: {}%g" {}/application.yml'.format(encrypt_type, server_dir)) + doCmd('sed -i "s/keyServer: 127.0.0.1:5004/keyServer: {}:{}/g" {}/application.yml'.format(deploy_ip, sign_port, server_dir)) + doCmd('sed -i "s%/webasefront%/{}%g" {}/application.yml'.format(frontDb, server_dir)) + doCmd('sed -i "s%monitorDisk: /%monitorDisk: {}%g" {}/application.yml'.format(fisco_dir, server_dir)) + doCmd('sed -i "s%nodePath: /fisco/nodes/127.0.0.1/node0%nodePath: {}%g" {}/application.yml'.format(node_dir, server_dir)) + + return + +def installFront(): + print ("================================================================") + print ("============== WeBASE-Front install... ==============") + os.chdir(currentDir) + front_version = getCommProperties("webase.front.version") + gitComm = "wget https://www.fisco.com.cn/cdn/webase/releases/download/{}/webase-front.zip".format(front_version) + frontPackage = "webase-front" + server_dir = currentDir + "/" + frontPackage + pullSourceExtract(gitComm,frontPackage) + changeFrontConfig() + + # check front db + frontDb = getCommProperties("front.h2.name") + db_dir = currentDir+"/h2" + doCmdIgnoreException("mkdir -p {}".format(db_dir)) + res_file = checkFileName(db_dir,frontDb) + if res_file: + info = "n" + if sys.version_info.major == 2: + info = raw_input("WeBASE-Front database {} already exists, delete rebuild or not?[y/n]:".format(frontDb)) + else: + info = input("WeBASE-Front database {} already exists, delete rebuild or not?[y/n]:".format(frontDb)) + if info == "y" or info == "Y": + doCmdIgnoreException("rm -rf {}/{}.*".format(db_dir,frontDb)) + + # copy node crt + if_exist_fisco = getCommProperties("if.exist.fisco") + fisco_dir = getCommProperties("fisco.dir") + if if_exist_fisco == "no": + fisco_dir = currentDir + "/nodes/127.0.0.1" + sdk_dir = fisco_dir + "/sdk" + if not os.path.exists(sdk_dir): + print ("======= FISCO-BCOS sdk dir:{} is not exist. please check! =======".format(sdk_dir)) + sys.exit(0) + os.chdir(server_dir) + copyFiles(fisco_dir + "/sdk", server_dir + "/conf") + + startFront() + return + +def startFront(): + print ("============== WeBASE-Front start... ==============") + os.chdir(currentDir) + frontPort = getCommProperties("front.port") + frontPackage = "webase-front" + os.chdir(currentDir + "/" + frontPackage) + doCmdIgnoreException("source /etc/profile") + doCmdIgnoreException("chmod u+x *.sh") + doCmdIgnoreException("dos2unix *.sh") + result = doCmd("bash start.sh") + if result["status"] == 0: + if_started = 'is running' in result["output"] + if if_started: + pid = get_str_btw(result["output"], "(", ")") + print ("WeBASE-Front Port {} is running PID({})".format(frontPort,pid)) + sys.exit(0) + if_success = 'Starting' in result["output"] + if if_success: + print ("======= WeBASE-Front starting . Please check through the log file (default path:./{}/log/). =======".format(frontPackage)) + else: + print ("======= WeBASE-Front start fail. Please check through the log file (default path:./{}/log/). =======".format(frontPackage)) + sys.exit(0) + else: + print ("======= WeBASE-Front start fail. Please view log file (default path:./log/). =======") + sys.exit(0) + print ("============== WeBASE-Front end... ==============") + print ("================================================================") + return + +def stopFront(): + os.chdir(currentDir) + server_dir = currentDir + "/webase-front" + os.chdir(server_dir) + doCmdIgnoreException("source /etc/profile") + doCmdIgnoreException("chmod u+x *.sh") + doCmdIgnoreException("dos2unix *.sh") + result = doCmd("bash stop.sh") + if result["status"] == 0: + if_success = 'Success' in result["output"] + if if_success: + print ("======= WeBASE-Front stop success! =======") + else: + print ("======= WeBASE-Front is not running! =======") + else: + print ("======= WeBASE-Front stop fail. Please view log file (default path:./log/). =======") + return + +def changeSignConfig(): + # get properties + sign_port = getCommProperties("sign.port") + mysql_ip = getCommProperties("sign.mysql.ip") + mysql_port = getCommProperties("sign.mysql.port") + mysql_user = getCommProperties("sign.mysql.user") + mysql_password = getCommProperties("sign.mysql.password") + mysql_database = getCommProperties("sign.mysql.database") + + # init file + server_dir = currentDir + "/webase-sign" + conf_dir = server_dir + "/conf" + if not os.path.exists(conf_dir + "/temp.yml"): + doCmd('cp -f {}/application.yml {}/temp.yml'.format(conf_dir, conf_dir)) + else: + doCmd('cp -f {}/temp.yml {}/application.yml'.format(conf_dir, conf_dir)) + + # change server config + doCmd('sed -i "s/5004/{}/g" {}/application.yml'.format(sign_port, conf_dir)) + doCmd('sed -i "s/127.0.0.1/{}/g" {}/application.yml'.format(mysql_ip, conf_dir)) + doCmd('sed -i "s/3306/{}/g" {}/application.yml'.format(mysql_port, conf_dir)) + doCmd('sed -i "s/dbUsername/{}/g" {}/application.yml'.format(mysql_user, conf_dir)) + doCmd('sed -i "s/dbPassword/{}/g" {}/application.yml'.format(mysql_password, conf_dir)) + doCmd('sed -i "s/webasesign/{}/g" {}/application.yml'.format(mysql_database, conf_dir)) + + return + +def installSign(): + print ("================================================================") + print ("============== WeBASE-Sign install... ==============") + os.chdir(currentDir) + sign_version = getCommProperties("webase.sign.version") + gitComm = "wget https://www.fisco.com.cn/cdn/webase/releases/download/{}/webase-sign.zip".format(sign_version) + pullSourceExtract(gitComm,"webase-sign") + changeSignConfig() + signDbConnect() + startSign() + return + +def startSign(): + print ("============== WeBASE-Sign start... ==============") + os.chdir(currentDir) + signPort = getCommProperties("sign.port") + server_dir = currentDir + "/webase-sign" + os.chdir(server_dir) + doCmdIgnoreException("source /etc/profile") + doCmdIgnoreException("chmod u+x *.sh") + doCmdIgnoreException("dos2unix *.sh") + result = doCmd("bash start.sh") + if result["status"] == 0: + if_started = 'is running' in result["output"] + if if_started: + pid = get_str_btw(result["output"], "(", ")") + print ("WeBASE-Sign Port {} is running PID({})".format(signPort,pid)) + sys.exit(0) + if_success = 'Starting' in result["output"] + if if_success: + print ("======= WeBASE-Sign starting. Please check through the log file (default path:./webase-sign/log/). =======") + else: + print ("======= WeBASE-Sign start fail. Please check through the log file (default path:./webase-sign/log/). =======") + sys.exit(0) + else: + print ("======= WeBASE-Sign start fail. Please view log file (default path:./log/). =======") + sys.exit(0) + print ("============== WeBASE-Sign end... ==============") + return + +def stopSign(): + server_dir = currentDir + "/webase-sign" + os.chdir(server_dir) + doCmdIgnoreException("source /etc/profile") + doCmdIgnoreException("chmod u+x *.sh") + doCmdIgnoreException("dos2unix *.sh") + result = doCmd("bash stop.sh") + if result["status"] == 0: + if_success = 'Success' in result["output"] + if if_success: + print ("======= WeBASE-Sign stop success! =======") + else: + print ("======= WeBASE-Sign is not running! =======") + else: + print ("======= WeBASE-Sign stop fail. Please view log file (default path:./log/). =======") + return diff --git a/deploy/comm/check.py b/deploy/comm/check.py new file mode 100644 index 0000000..ea7ec41 --- /dev/null +++ b/deploy/comm/check.py @@ -0,0 +1,212 @@ +#!/usr/bin/env python3 +# encoding: utf-8 + +from . import log as deployLog +import sys +from .utils import * + +log = deployLog.getLocalLogger() +checkDependent = ["git","openssl","curl"] + +def do(): + print ("================================================================"), + webaseMsg = ''' + _ _ ______ ___ _____ _____ + | | | | | ___ \/ _ \/ ___| ___| + | | | | ___| |_/ / /_\ \ `--.| |__ + | |/\| |/ _ | ___ | _ |`--. | __| + \ /\ | __| |_/ | | | /\__/ | |___ + \/ \/ \___\____/\_| |_\____/\____/ + ''' + print (webaseMsg) + print ("================================================================") + print ("===================== envrionment check... =====================") + installRequirements() + checkNginx() + checkJava() + checkNodePort() + checkWebPort() + checkMgrPort() + checkSignPort() + checkFrontPort() + checkSignDbConnect() + checkMgrDbConnect() + print ("===================== envrionment ready... =====================") + print ("================================================================") + +def checkPort(): + checkWebPort() + checkMgrPort() + checkSignPort() + checkFrontPort() + +def installRequirements(): + for require in checkDependent: + print ("check {}...".format(require)) + hasInstall = hasInstallServer(require) + if not hasInstall: + installByYum(require) + print ("check finished sucessfully.") + return + +def checkNginx(): + print ("check nginx...") + require = "nginx" + hasInstall = hasInstallServer(require) + if not hasInstall: + installByYum(require) + print ("check finished sucessfully.") + +def checkJava(): + print ("check java...") + res_check = doCmdIgnoreException("java -version") + if res_check["status"] != 0: + print (" error! java has not been installed or configured!") + sys.exit(0) + res_home = doCmd("echo $JAVA_HOME") + if res_home["output"].strip() == "": + print (" error! JAVA_HOME has not been configured!") + sys.exit(0) + print ("check finished sucessfully.") + return + +def checkNodePort(): + if_exist_fisco = getCommProperties("if.exist.fisco") + if if_exist_fisco == "yes": + # checkExistedNodePort() + return + elif if_exist_fisco == "no": + print ("check FISCO-BCOS node port...") + checkNewNodePort() + print ("check finished sucessfully.") + else: + print (" error! param if.exist.fisco must be yes or no, current is {}. please check.".format(if_exist_fisco)) + sys.exit(0) + +def checkExistedNodePort(): + listen_ip = getCommProperties("node.listenIp") + node_rpcPort = int(getCommProperties("node.rpcPort")) + node_p2pPort = int(getCommProperties("node.p2pPort")) + node_channelPort = int(getCommProperties("node.channelPort")) + res_rpcPort = net_if_used_no_msg(listen_ip,node_rpcPort) + if not res_rpcPort: + print (" error! rpc port {} is not alive. please check.".format(node_rpcPort)) + sys.exit(0) + res_p2pPort = net_if_used_no_msg(listen_ip,node_p2pPort) + if not res_p2pPort: + print (" error! p2p port {} is not alive. please check.".format(node_p2pPort)) + sys.exit(0) + res_channelPort = net_if_used_no_msg(listen_ip,node_channelPort) + if not res_channelPort: + print (" error! channel port {} is not alive. please check.".format(node_channelPort)) + sys.exit(0) + return + +def checkNewNodePort(): + listen_ip = getCommProperties("node.listenIp") + nodes = getCommProperties("node.counts") + node_counts = 2 + if nodes != "nodeCounts": + node_counts = int(nodes) + node_rpcPort = int(getCommProperties("node.rpcPort")) + node_p2pPort = int(getCommProperties("node.p2pPort")) + node_channelPort = int(getCommProperties("node.channelPort")) + for i in range(node_counts): + res_rpcPort = net_if_used(listen_ip,node_rpcPort+i) + if res_rpcPort: + sys.exit(0) + res_p2pPort = net_if_used(listen_ip,node_p2pPort+i) + if res_p2pPort: + sys.exit(0) + res_channelPort = net_if_used(listen_ip,node_channelPort+i) + if res_channelPort: + sys.exit(0) + return + +def checkWebPort(): + print ("check WeBASE-Web port...") + deploy_ip = "127.0.0.1" + web_port = getCommProperties("web.port") + res_web = net_if_used(deploy_ip,web_port) + if res_web: + sys.exit(0) + print ("check finished sucessfully.") + return + +def checkMgrPort(): + print ("check WeBASE-Node-Manager port...") + deploy_ip = "127.0.0.1" + mgr_port = getCommProperties("mgr.port") + res_mgr = net_if_used(deploy_ip,mgr_port) + if res_mgr: + sys.exit(0) + print ("check finished sucessfully.") + return + +def checkFrontPort(): + print ("check WeBASE-Front port...") + deploy_ip = "127.0.0.1" + front_port = getCommProperties("front.port") + res_front = net_if_used(deploy_ip,front_port) + if res_front: + sys.exit(0) + print ("check finished sucessfully.") + return + +def checkSignPort(): + print ("check WeBASE-Sign port...") + deploy_ip = "127.0.0.1" + sign_port = getCommProperties("sign.port") + res_sign = net_if_used(deploy_ip,sign_port) + if res_sign: + sys.exit(0) + print ("check finished sucessfully.") + return + +def checkMgrDbConnect(): + print ("check database connection...") + mysql_ip = getCommProperties("mysql.ip") + mysql_port = getCommProperties("mysql.port") + ifLink = do_telnet(mysql_ip,mysql_port) + if not ifLink: + print ('Mgr database ip:{} port:{} is disconnected, please confirm.'.format(mysql_ip, mysql_port)) + sys.exit(0) + print ("check finished sucessfully.") + return + +def checkSignDbConnect(): + print ("check database connection...") + mysql_ip = getCommProperties("sign.mysql.ip") + mysql_port = getCommProperties("sign.mysql.port") + ifLink = do_telnet(mysql_ip,mysql_port) + if not ifLink: + print ('Sign database ip:{} port:{} is disconnected, please confirm.'.format(mysql_ip, mysql_port)) + sys.exit(0) + print ("check finished sucessfully.") + return + +def hasInstallServer(server): + result = doCmdIgnoreException("which {}".format(server)) + if result["status"] == 0: + return True + else: + return False + +def installByYum(server): + if isCentos(): + result = doCmdIgnoreException("sudo yum -y install {}".format(server)) + if result["status"] != 0: + os.system("sudo yum -y install epel-release") + os.system("sudo yum -y install python-pip") + os.system("pip install requests") + result = doCmd("sudo yum -y install {}".format(server)) + elif isSuse(): + os.system("sudo zypper install -y {}".format(server)) + elif isUbuntu(): + os.system("sudo apt-get install -y {}".format(server)) + else: + raise Exception("error,not support this platform,only support centos,suse,ubuntu.") + return + +if __name__ == '__main__': + pass diff --git a/deploy/comm/log.py b/deploy/comm/log.py new file mode 100644 index 0000000..6de1390 --- /dev/null +++ b/deploy/comm/log.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python3 +# encoding: utf-8 + +import logging, os + +class Logger: + def __init__(self, path, clever=logging.DEBUG, Flevel=logging.DEBUG): + self.logger = logging.getLogger(path) + self.logger.setLevel(logging.DEBUG) + log_format = logging.Formatter('[%(asctime)s] [%(levelname)s] %(message)s', '%Y-%m-%d %H:%M:%S') + fh = logging.FileHandler(path) + fh.setFormatter(log_format) + fh.setLevel(Flevel) + self.logger.addHandler(fh) + + def debug(self, message): + self.logger.debug(message) + + def info(self, message): + self.logger.info(message) + + def infoPrint(self, mesage): + print (mesage) + self.logger.info(mesage) + + def war(self, message): + self.logger.warn(message) + + def error(self, message): + self.logger.error(message) + + def cri(self, message): + self.logger.critical(message) + + +loggermap = {} +def getLocalLogger(): + logPath ="./log/" + logName="info.log" + isExists=os.path.exists(logPath) + if not isExists: + os.makedirs(logPath) + if logPath+logName in loggermap: + return loggermap[logPath+logName] + else: + logger = Logger(logPath+logName, logging.INFO, logging.INFO) + loggermap[logPath+logName] = logger + return logger + +if __name__ == '__main__': + log = getLocalLogger() + log.info("vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv") \ No newline at end of file diff --git a/deploy/comm/mysql.py b/deploy/comm/mysql.py new file mode 100644 index 0000000..1ffbfbd --- /dev/null +++ b/deploy/comm/mysql.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python3 +# encoding: utf-8 + +from . import log as deployLog +import sys +import MySQLdb as mdb +from .utils import * + +log = deployLog.getLocalLogger() + +def dbConnect(): + # get properties + mysql_ip = getCommProperties("mysql.ip") + mysql_port = int(getCommProperties("mysql.port")) + mysql_user = getCommProperties("mysql.user") + mysql_password = getCommProperties("mysql.password") + mysql_database = getCommProperties("mysql.database") + + try: + # connect + conn = mdb.connect(host=mysql_ip, port=mysql_port, user=mysql_user, passwd=mysql_password, charset='utf8') + conn.autocommit(1) + cursor = conn.cursor() + + # check db + result = cursor.execute('show databases like "%s"' %mysql_database) + drop_db = 'DROP DATABASE IF EXISTS {}'.format(mysql_database) + create_db = 'CREATE DATABASE IF NOT EXISTS {}'.format(mysql_database) + if result == 1: + info = "n" + if sys.version_info.major == 2: + info = raw_input("WeBASE-Node-Manager database {} already exists, delete rebuild or not?[y/n]:".format(mysql_database)) + else: + info = input("WeBASE-Node-Manager database {} already exists, delete rebuild or not?[y/n]:".format(mysql_database)) + if info == "y" or info == "Y": + log.info(drop_db) + cursor.execute(drop_db) + log.info(create_db) + cursor.execute(create_db) + else: + log.info(create_db) + cursor.execute(create_db) + cursor.close() + conn.close() + except: + import traceback + log.info(" mysql except {}".format(traceback.format_exc())) + traceback.print_exc() + sys.exit(0) + +def signDbConnect(): + # get properties + mysql_ip = getCommProperties("sign.mysql.ip") + mysql_port = int(getCommProperties("sign.mysql.port")) + mysql_user = getCommProperties("sign.mysql.user") + mysql_password = getCommProperties("sign.mysql.password") + mysql_database = getCommProperties("sign.mysql.database") + + try: + # connect + conn = mdb.connect(host=mysql_ip, port=mysql_port, user=mysql_user, passwd=mysql_password, charset='utf8') + conn.autocommit(1) + cursor = conn.cursor() + + # check db + result = cursor.execute('show databases like "%s"' %mysql_database) + drop_db = 'DROP DATABASE IF EXISTS {}'.format(mysql_database) + create_db = 'CREATE DATABASE IF NOT EXISTS {}'.format(mysql_database) + if result == 1: + info = "n" + if sys.version_info.major == 2: + info = raw_input("WeBASE-Sign database {} already exists, delete rebuild or not?[y/n]:".format(mysql_database)) + else: + info = input("WeBASE-Sign database {} already exists, delete rebuild or not?[y/n]:".format(mysql_database)) + if info == "y" or info == "Y": + log.info(drop_db) + cursor.execute(drop_db) + log.info(create_db) + cursor.execute(create_db) + else: + log.info(create_db) + cursor.execute(create_db) + cursor.close() + conn.close() + except: + import traceback + log.info(" mysql except {}".format(traceback.format_exc())) + traceback.print_exc() + sys.exit(0) + +if __name__ == '__main__': + pass diff --git a/deploy/comm/nginx.conf b/deploy/comm/nginx.conf new file mode 100644 index 0000000..41a25e5 --- /dev/null +++ b/deploy/comm/nginx.conf @@ -0,0 +1,60 @@ +user root; +worker_processes 1; + +error_log log_path/error.log; + +pid /run/nginx-webase-web.pid; + +events { + worker_connections 1024; +} + +http { + include /etc/nginx/mime.types; + default_type application/octet-stream; + + #log_format main '$remote_addr - $remote_user [$time_local] "$request" ' + # '$status $body_bytes_sent "$http_referer" ' + # '"$http_user_agent" "$http_x_forwarded_for"'; + + access_log log_path/access.log ; + + sendfile on; + #tcp_nopush on; + + #keepalive_timeout 0; + keepalive_timeout 65; + + #gzip on; + add_header X-Frame-Options SAMEORIGIN; + upstream node_mgr_server{ + server 127.0.0.1:5001; + } + server { + listen 5000 default_server; + server_name 127.0.0.1; + location / { + root web_page_url; + index index.html index.htm; + try_files $uri $uri/ /index.html =404; + } + + include /etc/nginx/default.d/*.conf; + + location /mgr { + proxy_pass http://node_mgr_server/; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + } + + error_page 404 /404.html; + location = /40x.html { + } + + error_page 500 502 503 504 /50x.html; + location = /50x.html { + } + } + +} diff --git a/deploy/comm/utils.py b/deploy/comm/utils.py new file mode 100644 index 0000000..960c232 --- /dev/null +++ b/deploy/comm/utils.py @@ -0,0 +1,221 @@ +#!/usr/bin/env python3 +# encoding: utf-8 + +import os +import sys +try: + import ConfigParser +except: + try: + import configparser as ConfigParser + except: + from six.moves import configparser as ConfigParser +if sys.version_info.major == 2: + import commands +else: + import subprocess +from . import log as deployLog +import socket +import fcntl +import struct +import telnetlib +import platform +import shutil +from distutils.dir_util import copy_tree + +log = deployLog.getLocalLogger() +platformStr = platform.platform() + +def getIpAddress(ifname): + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + return socket.inet_ntoa(fcntl.ioctl( + s.fileno(), + 0x8915, # SIOCGIFADDR + struct.pack('256s', ifname[:15]) + )[20:24]) + +def getLocalIp(): + return getIpAddress("eth0") + +def net_if_used(ip,port): + s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) + s.settimeout(0.5) + try: + result=s.connect_ex((ip, int(port))) + if result==0: + print (" error! port {} has been used. please check.".format(port)) + return True + else: + return False + finally: + s.close() + +def net_if_used_no_msg(ip,port): + s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) + s.settimeout(0.5) + try: + result=s.connect_ex((ip, int(port))) + if result==0: + return True + else: + return False + finally: + s.close() + +def isUbuntu(): + return platformStr.lower().find("ubuntu") > -1 + +def isCentos(): + return platformStr.lower().find("centos") > -1 + +def isSuse(): + return platformStr.lower().find("suse") > -1 + +def getBaseDir(): + cwd = os.getcwd() + log.info(" os.getcwd() is {}".format(cwd)) + path = os.path.abspath(os.path.join(os.getcwd(), "..")) + return path + +def getCurrentBaseDir(): + cwd = os.getcwd() + log.info(" os.getcwd() is {}".format(cwd)) + path = os.path.abspath(os.path.join(os.getcwd(), ".")) + return path + +def copytree(src, dst): + copy_tree(src,dst) + return + +def doCmd(cmd): + log.info(" execute cmd start ,cmd : {}".format(cmd)) + result = dict() + if sys.version_info.major == 2: + (status, output) = commands.getstatusoutput(cmd) + else: + (status, output) = subprocess.getstatusoutput(cmd) + result["status"] = status + result["output"] = output + log.info(" execute cmd end ,cmd : {},status :{} , output: {}".format(cmd,status,output)) + if (0 != status): + raise Exception("execute cmd error ,cmd : {}, status is {} ,output is {}".format(cmd,status, output)) + return result + +def doCmdIgnoreException(cmd): + log.info(" execute cmd start ,cmd : {}".format(cmd)) + result = dict() + if sys.version_info.major == 2: + (status, output) = commands.getstatusoutput(cmd) + else: + (status, output) = subprocess.getstatusoutput(cmd) + result["status"] = status + result["output"] = output + log.info(" execute cmd end ,cmd : {},status :{} , output: {}".format(cmd, status, output)) + return result + +def getCommProperties(paramsKey): + current_dir = getCurrentBaseDir() + cf = ConfigParser.ConfigParser() + propertiesDir =current_dir+"/common.properties" + cf.read(propertiesDir) + log.info(" commProperties is {} ".format(propertiesDir)) + cf.sections() + value = cf.get('common', paramsKey) + return value + +def replaceConf(fileName,oldStr,newStr): + if not os.path.isfile(fileName): + print ("{} is not a file ".format(fileName)) + return + oldData ="" + with open(fileName, "r") as f: + for line in f: + if oldStr in line: + line = line.replace(oldStr, newStr) + oldData += line + with open(fileName, "w") as f: + f.write(oldData) + return + +def replaceConfDir(filePath,oldStr,newStr): + if not os.path.isdir(filePath): + print ("{} is not a dir ".format(filePath)) + return + for root, dirs, files in os.walk(filePath): + for file in files: + replaceConf(os.path.join(root,file),oldStr,newStr) + return + +def copyFiles(sourceDir, targetDir): + log.info(" copyFiles sourceDir: {} ".format(sourceDir)) + for f in os.listdir(sourceDir): + sourceF = os.path.join(sourceDir, f) + targetF = os.path.join(targetDir, f) + if os.path.isfile(sourceF): + # check dir + if not os.path.exists(targetDir): + os.makedirs(targetDir) + # copy file + shutil.copy(sourceF,targetF) + # check sub folder + if os.path.isdir(sourceF): + copyFiles(sourceF, targetF) + +def do_telnet(host,port): + try: + tn = telnetlib.Telnet(host, port, timeout=5) + tn.close() + except: + return False + return True + +def pullSourceExtract(gitComm,fileName): + if not os.path.exists("{}/{}.zip".format(getCurrentBaseDir(),fileName)): + print (gitComm) + os.system(gitComm) + else: + info = "n" + if sys.version_info.major == 2: + info = raw_input("{}.zip already exists. Download again or not?[y/n]:".format(fileName)) + else: + info = input("{}.zip already exists. Download again or not?[y/n]:".format(fileName)) + if info == "y" or info == "Y": + doCmd("rm -rf {}.zip".format(fileName)) + doCmd("rm -rf {}".format(fileName)) + print (gitComm) + os.system(gitComm) + if not os.path.exists("{}/{}".format(getCurrentBaseDir(),fileName)): + doCmd("unzip -o {}.zip".format(fileName)) + if not os.path.exists("{}/{}".format(getCurrentBaseDir(),fileName)): + print ("{}.zip extract failed!".format(fileName)) + sys.exit(0) + else: + info1 = "n" + if sys.version_info.major == 2: + info1 = raw_input("{}.zip has been unzipped. Whether to re-unzip?[y/n]:".format(fileName)) + else: + info1 = input("{}.zip has been unzipped. Whether to re-unzip?[y/n]:".format(fileName)) + if info1 == "y" or info1 == "Y": + doCmd("rm -rf {}".format(fileName)) + doCmd("unzip -o {}.zip".format(fileName)) + if not os.path.exists("{}/{}".format(getCurrentBaseDir(),fileName)): + print ("{}.zip extract failed!".format(fileName)) + sys.exit(0) + +def checkFileName(dir,fileName): + Files=os.listdir(dir) + for k in range(len(Files)): + Files[k]=os.path.splitext(Files[k])[0] + fileName = fileName + ".mv" + if fileName in Files: + return True + else: + return False + +def get_str_btw(s, f, b): + par = s.partition(f) + return (par[2].partition(b))[0][:] + +if __name__ == '__main__': + print(getIpAddress("eth0")) + pass \ No newline at end of file diff --git a/deploy/common.properties b/deploy/common.properties new file mode 100644 index 0000000..8372f73 --- /dev/null +++ b/deploy/common.properties @@ -0,0 +1,62 @@ +[common] + +# Webase Subsystem Version (v1.1.0 or above) +webase.web.version=v1.3.2 +webase.mgr.version=v1.3.2 +webase.sign.version=v1.3.2 +webase.front.version=v1.3.2 + +# Mysql database configuration of WeBASE-Node-Manager +mysql.ip=localhost +mysql.port=3306 +mysql.user=dbUsername +mysql.password=dbPassword +mysql.database=webasenodemanager + +# Mysql database configuration of WeBASE-Sign +sign.mysql.ip=localhost +sign.mysql.port=3306 +sign.mysql.user=dbUsername +sign.mysql.password=dbPassword +sign.mysql.database=webasesign + +# H2 database name of WeBASE-Front +front.h2.name=webasefront + +# WeBASE-Web service port +web.port=5000 +# WeBASE-Node-Manager service port +mgr.port=5001 +# WeBASE-Front service port +front.port=5002 +# WeBASE-Sign service port +sign.port=5004 + +# Node listening IP +node.listenIp=127.0.0.1 +# Node p2p service port +node.p2pPort=30300 +# Node channel service port +node.channelPort=20200 +# Node rpc service port +node.rpcPort=8545 + +# Encrypt type (0: standard, 1: guomi) +encrypt.type=0 + +# Use existing chain or not (yes/no) +if.exist.fisco=no + +# Configuration is required when using the existing chain +# The path of the existing chain, the path of the start_all.sh script +# Under the path, there should be a SDK directory where the SDK certificates (ca.crt, node.crt and node. Key) are stored +fisco.dir=/data/app/nodes/127.0.0.1 +# Absolute path of the connected node in WeBASE-Front +# Under the path, there is a conf directory where node certificates (ca.crt, node.crt and node. Key) are stored +node.dir=/data/app/nodes/127.0.0.1/node0 + +# Configuration required when building a new chain +# Fisco-bcos version +fisco.version=2.4.1 +# Number of building nodes (two by default) +node.counts=nodeCounts diff --git a/deploy/deploy.py b/deploy/deploy.py new file mode 100644 index 0000000..960b22d --- /dev/null +++ b/deploy/deploy.py @@ -0,0 +1,84 @@ +#!/usr/bin/python3 +# encoding: utf-8 + +import sys +import comm.check as commCheck +import comm.build as commBuild +def do(): + if len(sys.argv)==1: + help() + return + param = sys.argv[1] + if "installAll" == param: + commCheck.do() + commBuild.do() + elif "startAll" == param: + commCheck.checkPort() + commBuild.start() + elif "stopAll" == param: + commBuild.end() + elif "startNode" == param: + commBuild.startNode() + elif "stopNode" == param: + commBuild.stopNode() + elif "startWeb" == param: + commBuild.startWeb() + elif "stopWeb" == param: + commBuild.stopWeb() + elif "startManager" == param: + commBuild.startManager() + elif "stopManager" == param: + commBuild.stopManager() + elif "startFront" == param: + commBuild.startFront() + elif "stopFront" == param: + commBuild.stopFront() + elif "startSign" == param: + commBuild.startSign() + elif "stopSign" == param: + commBuild.stopSign() + elif "check"== param: + commCheck.do() + elif "help"== param: + help() + else: + paramError() + return + +def help(): + helpMsg = ''' +Usage: python deploy [Parameter] + +Parameter: + check: check the environment + installAll: check the environment, deploy all server + startAll: check server port, start all server + stopAll: stop all server + startNode: start FISCO-BCOS nodes + stopNode: stop FISCO-BCOS nodes + startWeb: start WeBASE-Web server + stopWeb: stop WeBASE-Web server + startManager: start WeBASE-Node-Manager server + stopManager: stop WeBASE-Node-Manager server + startFront: start WeBASE-Front server + stopFront: stop WeBASE-Front server + startSign: start WeBASE-Sign server + stopSign: stop WeBASE-Sign server + +Attention: + 1. Need to install python, jdk, mysql, MySQL-python or PyMySQL first + 2. Need to ensure a smooth network + 3. You need to install git, wget, nginx; if it is not installed, the installation script will automatically install these components, but this may fail. + ''' + print (helpMsg) + return + +def paramError(): + print ("") + print ("Param error! Please check.") + help() + return + +if __name__ == '__main__': + do() + pass \ No newline at end of file diff --git a/deploy/install.md b/deploy/install.md new file mode 100644 index 0000000..9dcd8eb --- /dev/null +++ b/deploy/install.md @@ -0,0 +1,12 @@ +# 快速搭建 +## 简介 + +一键部署可以快速搭建WeBASE管理台环境。包括节点(FISCO-BCOS 2.0+)、节点前置子系统(WeBASE-Front)、签名服务子系统(WeBASE-Sign)、节点管理子系统(WeBASE-Node-Manager)、管理平台(WeBASE-Web)。其中,节点的搭建是可选的,可以通过配置来选择使用已有链或者搭建新链。详细介绍请查看[一键部署在线文档](https://webasedoc.readthedocs.io/zh_CN/latest/docs/WeBASE/install.html)。 + +## 贡献说明 +请阅读我们的贡献文档,了解如何贡献代码,并提交你的贡献。 + +希望在您的参与下,WeBASE会越来越好! + +## 社区 +联系我们:webase@webank.com diff --git a/deploy/nodeconf b/deploy/nodeconf new file mode 100644 index 0000000..33faad1 --- /dev/null +++ b/deploy/nodeconf @@ -0,0 +1 @@ +127.0.0.1:nodeCounts agencyA 1,2 diff --git a/deploy/telnet.py b/deploy/telnet.py new file mode 100644 index 0000000..3dfe53e --- /dev/null +++ b/deploy/telnet.py @@ -0,0 +1,50 @@ +#!/usr/bin/python3 +# encoding: utf-8 + +import sys +from comm.utils import * + +def do(): + deploy_ip = "127.0.0.1" + web_port = int(getCommProperties("web.port")) + mgr_port = int(getCommProperties("mgr.port")) + front_port = int(getCommProperties("front.port")) + + telnet_web = net_if_used_no_msg(deploy_ip,web_port) + telnet_mgr = net_if_used_no_msg(deploy_ip,mgr_port) + telnet_front = net_if_used_no_msg(deploy_ip,front_port) + print ("telnet_web:{} telnet_mgr:{} telnet_front:{}".format(telnet_web, telnet_mgr, telnet_front)) + + if telnet_web and telnet_mgr and telnet_front: + print ("deploy success.") + else: + print ("============= deploy log =============") + deploy_log = doCmdIgnoreException("cat ./log/info.log") + print (deploy_log["output"]) + if not telnet_web: + print ("============================ WeBASE-Web fail... ============================") + context = doCmdIgnoreException("cat ./webase-web/log/access.log") + print (context["output"]) + if not telnet_mgr: + print ("============================ WeBASE-Node-Manager fail... ============================") + print ("============= node-manager.out =============") + context1 = doCmdIgnoreException("cat ./webase-node-mgr/log/node-manager.out") + print (context1["output"]) + print ("============= WeBASE-Node-Manager.log =============") + context2 = doCmdIgnoreException("cat ./webase-node-mgr/log/WeBASE-Node-Manager.log") + print (context2["output"]) + if not telnet_front: + print ("============================ WeBASE-Front fail... ============================") + print ("============= front.out =============") + context1 = doCmdIgnoreException("cat ./webase-front/log/front.out") + print (context1["output"]) + print ("============= WeBASE-Front.log =============") + context2 = doCmdIgnoreException("cat ./webase-front/log/WeBASE-Front.log") + print (context2["output"]) + print ("============= web3sdk.log =============") + context3 = doCmdIgnoreException("cat ./webase-front/log/web3sdk.log") + print (context3["output"]) + raise Exception("deploy fail.") +if __name__ == '__main__': + do() + pass \ No newline at end of file diff --git a/images/architecture.png b/images/architecture.png new file mode 100644 index 0000000..7cf1f7e Binary files /dev/null and b/images/architecture.png differ diff --git a/images/contract.png b/images/contract.png new file mode 100644 index 0000000..cc4c96e Binary files /dev/null and b/images/contract.png differ diff --git a/images/frontInfo.png b/images/frontInfo.png new file mode 100644 index 0000000..3009a9c Binary files /dev/null and b/images/frontInfo.png differ diff --git a/images/keyUser.png b/images/keyUser.png new file mode 100644 index 0000000..5f71931 Binary files /dev/null and b/images/keyUser.png differ diff --git a/images/monitor.png b/images/monitor.png new file mode 100644 index 0000000..87dd014 Binary files /dev/null and b/images/monitor.png differ diff --git a/images/transHash.png b/images/transHash.png new file mode 100644 index 0000000..774f982 Binary files /dev/null and b/images/transHash.png differ diff --git a/quick-start.md b/quick-start.md new file mode 100644 index 0000000..7fc42f4 --- /dev/null +++ b/quick-start.md @@ -0,0 +1,123 @@ +# 使用WeBASE开发区块链应用 + +## 1 部署WeBASE +搭建WeBASE, 请参考[快速部署](https://webasedoc.readthedocs.io/zh_CN/latest/docs/WeBASE/install.html) + +## 2 登录WeBASE管理平台进行配置 +安装WeBASE完成后,需要将节点信息添加到WeBASE平台中,这样WeBASE才可和节点进行通信。需要添加的信息包含节点信息,生成用户的私钥等。如下图所示: + +* 节点信息: +![[节点]](./images/frontInfo.png) + +* 私钥用户: +![[私钥用户]](./images/keyUser.png) + +## 3 开发智能合约 +以HelloWorld.sol为例 +``` +pragma solidity ^0.4.2; + +contract HelloWorld{ + string name; + + function HelloWorld(){ + name = "Hello, World!"; + } + + function get()constant returns(string){ + return name; + } + + function set(string n){ + name = n; + } +} +``` + +* 通过智能合约IDE部署合约,并获取合约地址等信息, +![[合约]](./images/contract.png) + + + +## 4 应用层开发 + +### 4.1 根据所写合约和交易api的格式,发送交易。 +请参考[交易接口](https://webasedoc.readthedocs.io/zh_CN/latest/docs/WeBASE-Front/interface.html#id235) + +从IDE中的输出信息,拷贝合约地址,合约名,方法名等信息,同时获取用户的公钥信息,调用交易接口。 +具体代码请参考 [HelloWorld范例](https://github.com/WeBankFinTech/WeBASE/tree/master/quick-start) + +### 4.2 接口调用的主要代码: +* application.yml +``` +transactionUrl: http://127.0.0.1:5002/WeBASE-Front/trans/handle +groupId: 1 +userAddress: "0x4f08eac5af5e77b7006d11bee94adba2f721def8" +useAes: true +contract.name: HelloWorld +contract.address: "0xca597170829f4ad5054b618425a56e0be23cbc55" +contract.funcName: set +contract.funcParam: "[\"abc\"]" +``` +* TransactionService.java +``` +@Slf4j +@Data +@Service +public class TransactionService { + @Autowired + private RestTemplate rest; + @Value("${transactionUrl}") + private String url; + @Value("${userAddress}") + private String user; + @Value("${groupId}") + private int groupId; + @Value("${useAes}") + private Boolean useAes; + @Value("${contract.name}") + private String contractName; + @Value("${contract.address}") + private String contractAddress; + @Value("${contract.funcName}") + private String funcName; + @Value("${contract.funcParam}") + private String funcParam; + + public void sendTransaction() { + + try { + TransactionParam transParam = new TransactionParam(); + transParam.setGroupId(groupId); + transParam.setContractAddress(contractAddress); + transParam.setUseAes(useAes); + transParam.setUser(user); + transParam.setContractName(contractName); + transParam.setFuncName(funcName); + transParam.setFuncParam(JSONArray.parseArray(funcParam)); + + log.info("transaction param:{}", JSON.toJSONString(transParam)); + Object rsp = rest.postForObject(url, transParam, Object.class); + String rspStr = "null"; + if (Objects.nonNull(rsp)) { + rspStr = JSON.toJSONString(rsp); + } + log.info("transaction result:{}", rspStr); + } catch (Exception ex) { + log.error("fail sendTransaction", ex); + } + System.exit(1); + } +} +``` + +## 5 运维管理 +应用层发布后,持续发送交易,可在WeBASE管理平台查看数据概览,节点监控,查看交易解析,交易审计等管理功能。 +* 查看交易解析 +![[交易解析]](./images/transHash.png) + + + + + + diff --git a/quick-start/.gitignore b/quick-start/.gitignore new file mode 100644 index 0000000..6c01878 --- /dev/null +++ b/quick-start/.gitignore @@ -0,0 +1,32 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ diff --git a/quick-start/build.gradle b/quick-start/build.gradle new file mode 100644 index 0000000..d0f69f7 --- /dev/null +++ b/quick-start/build.gradle @@ -0,0 +1,101 @@ +group = 'com.webank.webase' +version = '0.0.1-SNAPSHOT' + +apply plugin: 'maven' +apply plugin: 'java' +apply plugin: 'idea' +apply plugin: 'eclipse' + + +sourceCompatibility = 1.8 +targetCompatibility = 1.8 + +[compileJava, compileTestJava, javadoc]*.options*.encoding = 'UTF-8' + +// In this section you declare where to find the dependencies of your project +repositories { + maven {url "http://maven.aliyun.com/nexus/content/groups/public/"} + + mavenLocal() + mavenCentral() +} + +def springboot_version="2.1.2.RELEASE" +List springboot = [ + "org.springframework.boot:spring-boot-starter-web:$springboot_version", + "org.springframework.boot:spring-boot-starter-log4j2:$springboot_version" +] + + +List lombok = [ + "org.projectlombok:lombok:1.18.2" +] + +List test = [ + "org.springframework.boot:spring-boot-starter-test:$springboot_version" +] + + +dependencies { + compile springboot + // compile "org.apache.commons:commons-lang3:3.8.1" + compile "com.alibaba:fastjson:1.2.60" + + compileOnly lombok + + testCompile test +} + +configurations { + all*.exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging' + all*.exclude group: 'org.slf4j', module: 'slf4j-log4j12' + all*.exclude group: 'log4j', module: 'log4j' + all*.exclude group: 'org.ow2.asm', module: 'asm' + all*.exclude group: 'jline', module: 'jline' + all*.exclude group: 'com.google.protobuf', module: 'protobuf-java' + all*.exclude group: 'javax.annotation', module: 'javax.annotation-api' +} + +sourceSets { + main { + java { + srcDir 'src/main/java' + } + resources { + srcDir 'src/main/resources' + } + } +} + +clean { + delete 'dist' + delete 'build' +} + + +jar { + destinationDir file('dist/apps') + archiveName project.name + '.jar' + exclude '**/*.xml' + exclude '**/*.yml' + exclude '**/*.properties' + + doLast { + copy { + from file('src/main/resources/') + into 'dist/conf' + } + copy { + from file('script/') + into 'dist/script' + } + copy { + from configurations.runtime + into 'dist/lib' + } + copy { + from file('.').listFiles().findAll{File f -> (f.name.endsWith('.bat') || f.name.endsWith('.sh') || f.name.endsWith('.env'))} + into 'dist' + } + } +} diff --git a/quick-start/src/main/java/com/webank/webase/Application.java b/quick-start/src/main/java/com/webank/webase/Application.java new file mode 100644 index 0000000..ef32311 --- /dev/null +++ b/quick-start/src/main/java/com/webank/webase/Application.java @@ -0,0 +1,27 @@ +package com.webank.webase; + +import com.webank.webase.transaction.TransactionService; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.http.client.SimpleClientHttpRequestFactory; +import org.springframework.web.client.RestTemplate; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + ConfigurableApplicationContext applicationContext = SpringApplication.run(Application.class, args); + TransactionService tranService = applicationContext.getBean(TransactionService.class); + tranService.sendTransaction(); + } + + @Bean + public RestTemplate getRestTemplate() { + SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); + factory.setReadTimeout(10000);// ms + factory.setConnectTimeout(10000);// ms + return new RestTemplate(factory); + } +} diff --git a/quick-start/src/main/java/com/webank/webase/transaction/TransactionParam.java b/quick-start/src/main/java/com/webank/webase/transaction/TransactionParam.java new file mode 100644 index 0000000..d41d88e --- /dev/null +++ b/quick-start/src/main/java/com/webank/webase/transaction/TransactionParam.java @@ -0,0 +1,35 @@ +/** + * Copyright 2014-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ +package com.webank.webase.transaction; + +import java.util.List; + +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * param of send transaction. + */ +@Data +@NoArgsConstructor +public class TransactionParam { + + private Integer groupId; + private String user; + private String contractName; + private String funcName; + private String contractAddress; + private Boolean useAes; + private List funcParam; +} \ No newline at end of file diff --git a/quick-start/src/main/java/com/webank/webase/transaction/TransactionService.java b/quick-start/src/main/java/com/webank/webase/transaction/TransactionService.java new file mode 100644 index 0000000..20326fa --- /dev/null +++ b/quick-start/src/main/java/com/webank/webase/transaction/TransactionService.java @@ -0,0 +1,62 @@ +package com.webank.webase.transaction; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import lombok.Data; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.web.client.RestTemplate; + +import java.util.Objects; + + +@Slf4j +@Data +@Service +public class TransactionService { + @Autowired + private RestTemplate rest; + @Value("${transactionUrl}") + private String url; + @Value("${userAddress}") + private String user; + @Value("${groupId}") + private int groupId; + @Value("${useAes}") + private Boolean useAes; + @Value("${contract.name}") + private String contractName; + @Value("${contract.address}") + private String contractAddress; + @Value("${contract.funcName}") + private String funcName; + @Value("${contract.funcParam}") + private String funcParam; + + public void sendTransaction() { + + try { + TransactionParam transParam = new TransactionParam(); + transParam.setGroupId(groupId); + transParam.setContractAddress(contractAddress); + transParam.setUseAes(useAes); + transParam.setUser(user); + transParam.setContractName(contractName); + transParam.setFuncName(funcName); + transParam.setFuncParam(JSONArray.parseArray(funcParam)); + + log.info("transaction param:{}", JSON.toJSONString(transParam)); + Object rsp = rest.postForObject(url, transParam, Object.class); + String rspStr = "null"; + if (Objects.nonNull(rsp)) { + rspStr = JSON.toJSONString(rsp); + } + log.info("transaction result:{}", rspStr); + } catch (Exception ex) { + log.error("fail sendTransaction", ex); + } + System.exit(1); + } +} diff --git a/quick-start/src/main/resources/application.yml b/quick-start/src/main/resources/application.yml new file mode 100644 index 0000000..10f80c1 --- /dev/null +++ b/quick-start/src/main/resources/application.yml @@ -0,0 +1,9 @@ +transactionUrl: http://127.0.0.1:5002/WeBASE-Front/trans/handle +groupId: 1 +userAddress: "0x4f08eac5af5e77b7006d11bee94adba2f721def8" +useAes: true +contract: + name: HelloWorld + address: "0xca597170829f4ad5054b618425a56e0be23cbc55" + funcName: set + funcParam: "[\"abc\"]" \ No newline at end of file diff --git a/quick-start/src/main/resources/log4j2.xml b/quick-start/src/main/resources/log4j2.xml new file mode 100644 index 0000000..3c85f57 --- /dev/null +++ b/quick-start/src/main/resources/log4j2.xml @@ -0,0 +1,58 @@ + + + + + + ./logs + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/quick-start/src/test/java/com/webank/webase/helloworld/WebaseHelloworldApplicationTests.java b/quick-start/src/test/java/com/webank/webase/helloworld/WebaseHelloworldApplicationTests.java new file mode 100644 index 0000000..fb30646 --- /dev/null +++ b/quick-start/src/test/java/com/webank/webase/helloworld/WebaseHelloworldApplicationTests.java @@ -0,0 +1,16 @@ +package com.webank.webase.helloworld; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class WebaseHelloworldApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..663bd1f --- /dev/null +++ b/requirements.txt @@ -0,0 +1 @@ +requests \ No newline at end of file