Skip to content

Commit 8ca031c

Browse files
kgeiszliuxiaocs7
authored andcommitted
HBASE-29454 Update hbase-examples scripts to be compatible with Python 3
1 parent 758dc33 commit 8ca031c

File tree

20 files changed

+171
-71
lines changed

20 files changed

+171
-71
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,3 +24,4 @@ linklint/
2424
tmp
2525
**/.flattened-pom.xml
2626
.vscode/
27+
**/__pycache__

dev-support/blanks-eol-ignore.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,5 +20,5 @@
2020
.*/gen-cpp/.*
2121
.*/gen-perl/.*
2222
.*/gen-php/.*
23-
.*/gen-py/.*
23+
.*/gen_py/.*
2424
.*/gen-rb/.*

dev-support/blanks-tabs-ignore.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
.*/gen-cpp/.*
2121
.*/gen-perl/.*
2222
.*/gen-php/.*
23-
.*/gen-py/.*
23+
.*/gen_py/.*
2424
.*/gen-rb/.*
2525
# we have tabs in asciidoc, not sure whether it is OK to replace them with spaces
2626
src/main/asciidoc/.*

hbase-examples/README.txt

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,12 @@ Example code.
1717
${HBASE_ROOT}/hbase-thrift/src/main/resources/org/apache/hadoop/hbase/thrift/Hbase.thrift
1818
and re-placed at the corresponding paths. You should not have to do this generally.
1919

20+
For Python, modules with a dash cannot be imported. Instead, you must use an underscore or no
21+
dash at all. You can generate the code in a custom directory with the following:
22+
mkdir gen_py
23+
thrift --gen py --out gen_py \
24+
${HBASE_ROOT}/hbase-thrift/src/main/resources/org/apache/hadoop/hbase/thrift/Hbase.thrift
25+
2026
Before you run any Thrift examples, find a running HBase Thrift server (and a running
2127
hbase cluster for this server to talk to -- at a minimum start a standalone instance
2228
by doing ./bin/start-hbase.sh). If you start one locally (bin/hbase thrift start),
@@ -38,8 +44,8 @@ Example code.
3844
1. Modify the import path in the file to point to {$THRIFT_HOME}/lib/rb/lib.
3945
2. Execute {ruby DemoClient.rb} (or {ruby DemoClient.rb <host> <port>}).
4046

41-
* Python: hbase-examples/src/main/python/DemoClient.py
42-
1. Modify the added system path in the file to point to {$THRIFT_HOME}/lib/py/build/lib.[YOUR SYSTEM]
47+
* Python: hbase-examples/src/main/python/thrift1/DemoClient.py and hbase-examples/src/main/python/thrift2/DemoClient.py
48+
1. Install the thrift package to your local Python environment: pip3 install thrift
4349
2. Execute {python DemoClient.py <host> <port>}.
4450

4551
* PHP: hbase-examples/src/main/php/DemoClient.php

hbase-examples/src/main/python/thrift1/DemoClient.py

Lines changed: 32 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
#!/usr/bin/python
1+
#!/usr/bin/env python
22
'''
33
Licensed to the Apache Software Foundation (ASF) under one
44
or more contributor license agreements. See the NOTICE file
@@ -20,30 +20,22 @@
2020
import sys
2121
import time
2222
import os
23-
24-
# Modify this import path to point to the correct location to thrift.
25-
thrift_path = os.path.abspath('/Users/sergey/Downloads/thrift/lib/py/build/lib.macosx-10.8-intel-2.7')
26-
sys.path.append(thrift_path)
27-
gen_py_path = os.path.abspath('gen-py')
28-
sys.path.append(gen_py_path)
29-
30-
from thrift import Thrift
3123
from thrift.transport import TSocket, TTransport
3224
from thrift.protocol import TBinaryProtocol
33-
from hbase.ttypes import TThriftServerType
34-
from hbase.Hbase import Client, ColumnDescriptor, Mutation
25+
from gen_py.hbase import ttypes
26+
from gen_py.hbase.Hbase import Client, ColumnDescriptor, Mutation
3527

3628
def printVersions(row, versions):
37-
print "row: " + row + ", values: ",
29+
print("row: " + row + ", values: ", end=' ')
3830
for cell in versions:
39-
print cell.value + "; ",
40-
print
31+
print(cell.value + "; ", end=' ')
32+
print()
4133

4234
def printRow(entry):
43-
print "row: " + entry.row + ", cols:",
35+
print("row: " + entry.row + ", cols:", end=' ')
4436
for k in sorted(entry.columns):
45-
print k + " => " + entry.columns[k].value,
46-
print
37+
print(k + " => " + entry.columns[k].value, end=' ')
38+
print()
4739

4840

4941
def demo_client(host, port, is_framed_transport):
@@ -68,22 +60,22 @@ def demo_client(host, port, is_framed_transport):
6860

6961
# Check Thrift Server Type
7062
serverType = client.getThriftServerType()
71-
if serverType != TThriftServerType.ONE:
72-
raise Exception("Mismatch between client and server, server type is %s" % serverType)
63+
if serverType != ttypes.TThriftServerType.ONE:
64+
raise RuntimeError(f"Mismatch between client and server, server type is {serverType}")
7365

7466
t = "demo_table"
7567

7668
#
7769
# Scan all tables, look for the demo table and delete it.
7870
#
79-
print "scanning tables..."
71+
print("scanning tables...")
8072
for table in client.getTableNames():
81-
print " found: %s" %(table)
73+
print(f" found: {table}")
8274
if table == t:
8375
if client.isTableEnabled(table):
84-
print " disabling table: %s" %(t)
76+
print(f" disabling table: {t}")
8577
client.disableTable(table)
86-
print " deleting table: %s" %(t)
78+
print(f" deleting table: {t}")
8779
client.deleteTable(table)
8880

8981
columns = []
@@ -96,16 +88,16 @@ def demo_client(host, port, is_framed_transport):
9688
columns.append(col)
9789

9890
try:
99-
print "creating table: %s" %(t)
91+
print(f"creating table: {t}")
10092
client.createTable(t, columns)
101-
except AlreadyExists, ae:
102-
print "WARN: " + ae.message
93+
except ttypes.AlreadyExists as ae:
94+
print("WARN: " + ae.message)
10395

10496
cols = client.getColumnDescriptors(t)
105-
print "column families in %s" %(t)
97+
print(f"column families in {t}")
10698
for col_name in cols.keys():
10799
col = cols[col_name]
108-
print " column: %s, maxVer: %d" % (col.name, col.maxVersions)
100+
print(f" column: {col.name}, maxVer: {col.maxVersions}")
109101

110102
dummy_attributes = {}
111103
#
@@ -116,7 +108,7 @@ def demo_client(host, port, is_framed_transport):
116108

117109
# non-utf8 is fine for data
118110
mutations = [Mutation(column="entry:foo",value=invalid)]
119-
print str(mutations)
111+
print(str(mutations))
120112
client.mutateRow(t, "foo", mutations, dummy_attributes)
121113

122114
# try empty strings
@@ -131,25 +123,25 @@ def demo_client(host, port, is_framed_transport):
131123
try:
132124
mutations = [Mutation(column="entry:foo", value=invalid)]
133125
client.mutateRow(t, invalid, mutations, dummy_attributes)
134-
except ttypes.IOError, e:
135-
print 'expected exception: %s' %(e.message)
126+
except ttypes.IOError as e:
127+
print(f'expected exception: {e.message}')
136128

137129
# Run a scanner on the rows we just created
138-
print "Starting scanner..."
130+
print("Starting scanner...")
139131
scanner = client.scannerOpen(t, "", ["entry:"], dummy_attributes)
140132

141133
r = client.scannerGet(scanner)
142134
while r:
143135
printRow(r[0])
144136
r = client.scannerGet(scanner)
145-
print "Scanner finished"
137+
print("Scanner finished")
146138

147139
#
148140
# Run some operations on a bunch of rows.
149141
#
150142
for e in range(100, 0, -1):
151143
# format row keys as "00000" to "00100"
152-
row = "%0.5d" % (e)
144+
row = f"{row:05}"
153145

154146
mutations = [Mutation(column="unused:", value="DELETE_ME")]
155147
client.mutateRow(t, row, mutations, dummy_attributes)
@@ -187,15 +179,15 @@ def demo_client(host, port, is_framed_transport):
187179
r = client.get(t, row, "entry:foo", dummy_attributes)
188180
# just to be explicit, we get lists back, if it's empty there was no matching row.
189181
if len(r) > 0:
190-
raise "shouldn't get here!"
182+
raise RuntimeError("shouldn't get here!")
191183

192184
columnNames = []
193185
for (col, desc) in client.getColumnDescriptors(t).items():
194-
print "column with name: "+desc.name
195-
print desc
186+
print("column with name: "+desc.name)
187+
print(desc)
196188
columnNames.append(desc.name+":")
197189

198-
print "Starting scanner..."
190+
print("Starting scanner...")
199191
scanner = client.scannerOpenWithStop(t, "00020", "00040", columnNames, dummy_attributes)
200192

201193
r = client.scannerGet(scanner)
@@ -204,16 +196,14 @@ def demo_client(host, port, is_framed_transport):
204196
r = client.scannerGet(scanner)
205197

206198
client.scannerClose(scanner)
207-
print "Scanner finished"
199+
print("Scanner finished")
208200

209201
transport.close()
210202

211203

212204
if __name__ == '__main__':
213-
214-
import sys
215205
if len(sys.argv) < 3:
216-
print 'usage: %s <host> <port>' % __file__
206+
print(f'usage: {__file__} <host> <port>')
217207
sys.exit(1)
218208

219209
host = sys.argv[1]
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
#!/usr/bin/env python
2+
'''
3+
Licensed to the Apache Software Foundation (ASF) under one
4+
or more contributor license agreements. See the NOTICE file
5+
distributed with this work for additional information
6+
regarding copyright ownership. The ASF licenses this file
7+
to you under the Apache License, Version 2.0 (the
8+
"License"); you may not use this file except in compliance
9+
with the License. You may obtain a copy of the License at
10+
11+
http://www.apache.org/licenses/LICENSE-2.0
12+
13+
Unless required by applicable law or agreed to in writing, software
14+
distributed under the License is distributed on an "AS IS" BASIS,
15+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16+
See the License for the specific language governing permissions and
17+
limitations under the License.
18+
'''
19+
#
20+
# test thrift server over HTTP with SSL in place
21+
#
22+
# presumes thrift python lib is installed
23+
# presumes you have access to hbase thrift binding (i.e. you add gen_py to PYTHONPATH)
24+
# presumes thrift proxy is running on port 9090
25+
# presumes thrift proxy is running over https
26+
# presumes access to create and use tables in a namespace 'test'
27+
#
28+
# usage:
29+
# ./demo_hbase_thrift_over_http_tls.py host-running-thrift1.example.com
30+
import sys
31+
32+
from thrift.transport import THttpClient
33+
from thrift.protocol import TBinaryProtocol
34+
from gen_py.hbase import Hbase
35+
from gen_py.hbase.ttypes import ColumnDescriptor
36+
from gen_py.hbase.ttypes import Mutation
37+
38+
print("[INFO] setup connection")
39+
transport = THttpClient.THttpClient(f"https://{sys.argv[1]}:9090")
40+
client = Hbase.Client(TBinaryProtocol.TBinaryProtocol(transport))
41+
42+
table='test:thrift_proxy_demo'
43+
44+
print("[INFO] start client")
45+
transport.open()
46+
47+
print("[INFO] list the current tables")
48+
print(client.getTableNames())
49+
50+
print("[INFO] create a table, place some data")
51+
client.createTable(table, [ColumnDescriptor(name ='family1:')])
52+
client.mutateRow(table, 'row1',
53+
[Mutation(column = 'family1:cq1', value = 'foo'),
54+
Mutation(column = 'family1:cq2', value = 'foo')], {})
55+
client.mutateRow(table, 'row2',
56+
[Mutation(column = 'family1:cq1', value = 'bar'),
57+
Mutation(column = 'family1:cq2', value = 'bar')], {})
58+
client.mutateRow(table, 'row3',
59+
[Mutation(column = 'family1:cq1', value = 'foo'),
60+
Mutation(column = 'family1:cq2', value = 'foo')], {})
61+
client.mutateRow(table, 'row4',
62+
[Mutation(column = 'family1:cq1', value = 'bar'),
63+
Mutation(column = 'family1:cq2', value = 'bar')], {})
64+
65+
print("[INFO] scan")
66+
scan_id = client.scannerOpen(table, 'row1', [], {})
67+
for row in client.scannerGetList(scan_id, 25):
68+
print(row)
69+
client.scannerClose(scan_id)
70+
print("[INFO] get")
71+
for row in client.getRow(table, 'row3', {}):
72+
print(row)
73+
74+
print("[INFO] clean up")
75+
client.disableTable(table)
76+
client.deleteTable(table)

hbase-examples/src/main/python/thrift1/gen-py/hbase/__init__.py

Lines changed: 0 additions & 1 deletion
This file was deleted.

hbase-examples/src/main/python/thrift1/gen-py/hbase/Hbase-remote renamed to hbase-examples/src/main/python/thrift1/gen_py/hbase/Hbase-remote

File renamed without changes.

hbase-examples/src/main/python/thrift1/gen-py/hbase/Hbase.py renamed to hbase-examples/src/main/python/thrift1/gen_py/hbase/Hbase.py

File renamed without changes.
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
'''
2+
Licensed to the Apache Software Foundation (ASF) under one
3+
or more contributor license agreements. See the NOTICE file
4+
distributed with this work for additional information
5+
regarding copyright ownership. The ASF licenses this file
6+
to you under the Apache License, Version 2.0 (the
7+
"License"); you may not use this file except in compliance
8+
with the License. You may obtain a copy of the License at
9+
10+
http://www.apache.org/licenses/LICENSE-2.0
11+
12+
Unless required by applicable law or agreed to in writing, software
13+
distributed under the License is distributed on an "AS IS" BASIS,
14+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15+
See the License for the specific language governing permissions and
16+
limitations under the License.
17+
'''
18+
__all__ = ['ttypes', 'constants', 'Hbase']

0 commit comments

Comments
 (0)