Skip to content

Commit 7a20976

Browse files
authored
Merge pull request #659 from YoungHypo/issue-fix_channel_fetch
Fix issue#650 of channel fetch error
2 parents 52c4a97 + 297b495 commit 7a20976

File tree

6 files changed

+203
-105
lines changed

6 files changed

+203
-105
lines changed

src/api-engine/api/lib/configtxgen/configtx.py

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -51,13 +51,13 @@ def create(self, name, consensus, orderers, peers, orderer_cfg=None, application
5151
Consenters = []
5252

5353
for orderer in orderers:
54-
OrdererMSP = orderer["name"].capitalize() + "Orderer"
55-
OrdererOrg = dict(Name=orderer["name"].split(".")[0].capitalize() + "Orderer",
56-
ID='{}MSP'.format(OrdererMSP),
54+
OrdererMSP = "OrdererMSP"
55+
OrdererOrg = dict(Name="Orderer",
56+
ID= OrdererMSP,
5757
MSPDir='{}/{}/crypto-config/ordererOrganizations/{}/msp'.format(self.filepath, orderer["name"], orderer['name'].split(".", 1)[1]),
58-
Policies=dict(Readers=dict(Type="Signature", Rule="OR('{}MSP.member')".format(OrdererMSP)),
59-
Writers=dict(Type="Signature", Rule="OR('{}MSP.member')".format(OrdererMSP)),
60-
Admins=dict(Type="Signature", Rule="OR('{}MSP.admin')".format(OrdererMSP)))
58+
Policies=dict(Readers=dict(Type="Signature", Rule="OR('{}.member')".format(OrdererMSP)),
59+
Writers=dict(Type="Signature", Rule="OR('{}.member')".format(OrdererMSP)),
60+
Admins=dict(Type="Signature", Rule="OR('{}.admin')".format(OrdererMSP)))
6161
)
6262
for host in orderer['hosts']:
6363
OrdererAddress.append('{}.{}:{}'.format(host['name'], orderer['name'].split(".", 1)[1], 7050))
@@ -74,15 +74,14 @@ def create(self, name, consensus, orderers, peers, orderer_cfg=None, application
7474
PeerOrganizations = []
7575

7676
for peer in peers:
77-
PeerMSP = peer["name"].capitalize()
78-
PeerOrganizations.append(dict(Name=peer["name"].split(".")[0].capitalize(),
79-
ID='{}MSP'.format(PeerMSP),
77+
PeerMSP = peer['name'].split(".", 1)[0].capitalize() + "MSP"
78+
PeerOrganizations.append(dict(Name=peer['name'].split(".", 1)[0].capitalize(),
79+
ID=PeerMSP,
8080
MSPDir='{}/{}/crypto-config/peerOrganizations/{}/msp'.format(self.filepath, peer['name'], peer['name']),
81-
# AnchorPeers=[{'Port': peer["hosts"][0]["port"], 'Host': '{}.{}'.format(peer["hosts"][0]["name"],peer["name"])}],
82-
Policies=dict(Readers=dict(Type="Signature", Rule="OR('{}MSP.member')".format(PeerMSP)),
83-
Writers=dict(Type="Signature", Rule="OR('{}MSP.member')".format(PeerMSP)),
84-
Admins=dict(Type="Signature", Rule="OR('{}MSP.admin')".format(PeerMSP)),
85-
Endorsement=dict(Type="Signature", Rule="OR('{}MSP.member')".format(PeerMSP)))
81+
Policies=dict(Readers=dict(Type="Signature", Rule="OR('{}.admin', '{}.peer', '{}.client')".format(PeerMSP, PeerMSP, PeerMSP)),
82+
Writers=dict(Type="Signature", Rule="OR('{}.admin', '{}.client')".format(PeerMSP, PeerMSP)),
83+
Admins=dict(Type="Signature", Rule="OR('{}.admin')".format(PeerMSP)),
84+
Endorsement=dict(Type="Signature", Rule="OR('{}.peer')".format(PeerMSP)))
8685
))
8786
Organizations = OrdererOrganizations + PeerOrganizations
8887
Capabilities = dict(

src/api-engine/api/lib/configtxgen/configtxgen.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
#
22
# SPDX-License-Identifier: Apache-2.0
33
#
4-
from subprocess import call
54
from api.config import CELLO_HOME, FABRIC_TOOL, FABRIC_VERSION
65

6+
import subprocess
77
import logging
88
LOG = logging.getLogger(__name__)
99

@@ -42,9 +42,13 @@ def genesis(self, profile="", channelid="", outputblock="genesis.block"):
4242
"-channelID", "{}".format(channelid)
4343
]
4444

45-
LOG.info("Running command: " + " ".join(command))
45+
LOG.info(" ".join(command))
4646

47-
call(command)
47+
subprocess.run(command, check=True)
48+
49+
except subprocess.CalledProcessError as e:
50+
err_msg = "configtxgen genesis fail! "
51+
raise Exception(err_msg+str(e))
4852

4953
except Exception as e:
5054
err_msg = "configtxgen genesis fail! "

src/api-engine/api/lib/peer/channel.py

Lines changed: 73 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import os
55
import json
66
import subprocess
7+
import time
78
from api.lib.peer.command import Command
89
from api.config import FABRIC_TOOL, FABRIC_VERSION
910
import logging
@@ -20,23 +21,39 @@ def __init__(self, version=FABRIC_VERSION, peer=FABRIC_TOOL, **kwargs):
2021

2122
def create(self, channel, orderer_admin_url, block_path, time_out="90s"):
2223
try:
23-
res = 0x100
24-
command = ""
24+
command = []
2525

2626
if os.getenv("CORE_PEER_TLS_ENABLED") == "false" or os.getenv("CORE_PEER_TLS_ENABLED") is None:
27-
command = "{} channel join --channelID {} --config-block {} -o {}".format(self.osnadmin, channel, block_path, orderer_admin_url)
27+
command = [
28+
self.osnadmin,
29+
"channel", "join",
30+
"--channelID", channel,
31+
"--config-block", block_path,
32+
"-o", orderer_admin_url,
33+
]
2834
else:
2935
ORDERER_CA = os.getenv("ORDERER_CA")
3036
ORDERER_ADMIN_TLS_SIGN_CERT = os.getenv("ORDERER_ADMIN_TLS_SIGN_CERT")
3137
ORDERER_ADMIN_TLS_PRIVATE_KEY = os.getenv("ORDERER_ADMIN_TLS_PRIVATE_KEY")
32-
command = "{} channel join --channelID {} --config-block {} -o {} --ca-file {} --client-cert {} --client-key {}".format(self.osnadmin, channel, block_path, orderer_admin_url, ORDERER_CA, ORDERER_ADMIN_TLS_SIGN_CERT, ORDERER_ADMIN_TLS_PRIVATE_KEY)
33-
34-
LOG.info(f"{command}")
35-
res = os.system(command)
36-
37-
# The return value of os.system is not the result of executing the program. It is a 16 bit number,
38-
# and its high bit is the return code
39-
res = res >> 8
38+
command = [
39+
self.osnadmin,
40+
"channel", "join",
41+
"--channelID", channel,
42+
"--config-block", block_path,
43+
"-o", orderer_admin_url,
44+
"--ca-file", ORDERER_CA,
45+
"--client-cert", ORDERER_ADMIN_TLS_SIGN_CERT,
46+
"--client-key", ORDERER_ADMIN_TLS_PRIVATE_KEY
47+
]
48+
49+
LOG.info(" ".join(command))
50+
51+
res = subprocess.run(command, check=True)
52+
53+
except subprocess.CalledProcessError as e:
54+
err_msg = "create channel failed for {}!".format(e)
55+
raise Exception(err_msg+str(e))
56+
4057
except Exception as e:
4158
err_msg = "create channel failed for {}!".format(e)
4259
raise Exception(err_msg)
@@ -78,30 +95,58 @@ def update(self, channel, channel_tx, orderer_url):
7895
res = res >> 8
7996
return res
8097

81-
def fetch(self, block_path, channel, orderer_general_url):
98+
def fetch(self, block_path, channel, orderer_general_url, max_retries=5, retry_interval=1):
8299
"""
83100
Fetch a specified block, writing it to a file e.g. <channelID>.block.
84101
params:
85102
option: block option newest|oldest|config|(block number).
86103
channel: channel id.
87104
"""
88-
try:
89-
res = 0x100
90-
command = ""
91-
if os.getenv("CORE_PEER_TLS_ENABLED") == "false" or os.getenv("CORE_PEER_TLS_ENABLED") is None:
92-
command = "{} channel fetch config {} -o {} -c {}".format(self.peer, block_path, orderer_general_url, channel)
93-
else:
94-
ORDERER_CA = os.getenv("ORDERER_CA")
95-
orderer_address = orderer_general_url.split(":")[0]
96-
command = "{} channel fetch config {} -o {} --ordererTLSHostnameOverride {} -c {} --tls --cafile {}".format(self.peer, block_path, orderer_general_url, orderer_address, channel, ORDERER_CA)
105+
res = 0
106+
command = []
107+
if os.getenv("CORE_PEER_TLS_ENABLED") == "false" or os.getenv("CORE_PEER_TLS_ENABLED") is None:
108+
command = [
109+
self.peer,
110+
"channel", "fetch",
111+
"config", block_path,
112+
"-o", orderer_general_url,
113+
"-c", channel
114+
]
115+
else:
116+
ORDERER_CA = os.getenv("ORDERER_CA")
117+
orderer_address = orderer_general_url.split(":")[0]
118+
command = [
119+
self.peer,
120+
"channel", "fetch",
121+
"config", block_path,
122+
"-o", orderer_general_url,
123+
"--ordererTLSHostnameOverride", orderer_address,
124+
"-c", channel,
125+
"--tls",
126+
"--cafile", ORDERER_CA
127+
]
128+
129+
LOG.info(" ".join(command))
130+
131+
# Retry fetching the block up to max_retries times
132+
for attempt in range(1, max_retries+1):
133+
try:
134+
LOG.debug("Attempt %d/%d to fetch block", attempt, max_retries)
135+
136+
res = subprocess.run(command, check=True)
137+
138+
LOG.info("Successfully fetched block")
139+
break
140+
141+
except subprocess.CalledProcessError as e:
142+
LOG.debug(f"Attempt {attempt}/{max_retries} failed")
143+
144+
if attempt <= max_retries:
145+
time.sleep(retry_interval)
146+
else:
147+
LOG.error(f"Failed to fetch block after {max_retries} attempts")
148+
raise e
97149

98-
LOG.info(f"{command}")
99-
res = os.system(command)
100-
101-
res = res >> 8
102-
except Exception as e:
103-
err_msg = "fetch a specified block failed {}!".format(e)
104-
raise Exception(err_msg)
105150
return res
106151

107152
def signconfigtx(self, channel_tx):

src/api-engine/api/lib/pki/cryptogen/cryptocfg.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ def create(self, peernum, orderernum) -> None:
5959
else:
6060
template = dict(Count=orderernum)
6161
org.append(dict(Domain=self.name.split(".", 1)[1],
62-
Name=self.name.split(".")[0].capitalize() + item,
62+
Name=item,
6363
CA=ca,
6464
Specs=specs,
6565
EnableNodeOUs=self.enablenodeous,
@@ -89,6 +89,7 @@ def update(self, org_info: any) -> None:
8989
orgs = network['OrdererOrgs']
9090

9191
for org in orgs:
92+
# org["Template"]["Count"] += 1
9293
specs = org["Specs"]
9394
for host in org_info["Specs"]:
9495
specs.append(dict(Hostname=host))

src/api-engine/api/lib/pki/cryptogen/cryptogen.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ def generate(self, output="crypto-config", config="crypto-config.yaml"):
4040
"--config={}/{}/{}".format(self.filepath, self.name, config)
4141
]
4242

43-
LOG.info("Running command: " + " ".join(command))
43+
LOG.info(" ".join(command))
4444

4545
call(command)
4646

@@ -63,7 +63,7 @@ def extend(self, input="crypto-config", config="crypto-config.yaml"):
6363
"--config={}/{}/{}".format(self.filepath, self.name, config)
6464
]
6565

66-
LOG.info("Running command: " + " ".join(command))
66+
LOG.info(" ".join(command))
6767

6868
call(command)
6969

0 commit comments

Comments
 (0)