Skip to content

Commit cafa88e

Browse files
committedJun 16, 2017
First commit
0 parents  commit cafa88e

33 files changed

+2625
-0
lines changed
 

‎.gitignore

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
*.pyc
2+
*.swp
3+
*.swo
4+
env

‎.travis.yml

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
sudo: true
2+
language: python
3+
python:
4+
- "2.7"
5+
install:
6+
- pip install --upgrade pip
7+
- pip install -r dev-requirements.txt
8+
script:
9+
- ./lint.sh
10+
- pip install .
11+
- pytest tests

‎LICENSE.txt

+194
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,194 @@
1+
Databricks CLI (the "Software")
2+
3+
The Software consists of a Work (as defined below) subject to the Apache License Version 2, but in order to use certain application programming interfaces (each, an "API") within the Software, the user of the Software ("Licensee")must obtain a license for the use of the API from Databricks, Inc. ("Databricks"), by creating an account at www.databricks.com and agreeing to either (a) the Community Edition Terms of Service, (b) the Databricks Terms of Service, or (c) another written agreement between Licensee and Databricks for the use of the Software.
4+
5+
Apache License
6+
Version 2.0, January 2004
7+
httpwww.apache.orglicenses
8+
9+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
10+
11+
1. Definitions.
12+
13+
License shall mean the terms and conditions for use, reproduction,
14+
and distribution as defined by Sections 1 through 9 of this document.
15+
16+
Licensor shall mean the copyright owner or entity authorized by
17+
the copyright owner that is granting the License.
18+
19+
Legal Entity shall mean the union of the acting entity and all
20+
other entities that control, are controlled by, or are under common
21+
control with that entity. For the purposes of this definition,
22+
control means (i) the power, direct or indirect, to cause the
23+
direction or management of such entity, whether by contract or
24+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
25+
outstanding shares, or (iii) beneficial ownership of such entity.
26+
27+
You (or Your) shall mean an individual or Legal Entity
28+
exercising permissions granted by this License.
29+
30+
Source form shall mean the preferred form for making modifications,
31+
including but not limited to software source code, documentation
32+
source, and configuration files.
33+
34+
Object form shall mean any form resulting from mechanical
35+
transformation or translation of a Source form, including but
36+
not limited to compiled object code, generated documentation,
37+
and conversions to other media types.
38+
39+
Work shall mean the work of authorship, whether in Source or
40+
Object form, made available under the License, as indicated by a
41+
copyright notice that is included in or attached to the work
42+
(an example is provided in the Appendix below).
43+
44+
Derivative Works shall mean any work, whether in Source or Object
45+
form, that is based on (or derived from) the Work and for which the
46+
editorial revisions, annotations, elaborations, or other modifications
47+
represent, as a whole, an original work of authorship. For the purposes
48+
of this License, Derivative Works shall not include works that remain
49+
separable from, or merely link (or bind by name) to the interfaces of,
50+
the Work and Derivative Works thereof.
51+
52+
Contribution shall mean any work of authorship, including
53+
the original version of the Work and any modifications or additions
54+
to that Work or Derivative Works thereof, that is intentionally
55+
submitted to Licensor for inclusion in the Work by the copyright owner
56+
or by an individual or Legal Entity authorized to submit on behalf of
57+
the copyright owner. For the purposes of this definition, submitted
58+
means any form of electronic, verbal, or written communication sent
59+
to the Licensor or its representatives, including but not limited to
60+
communication on electronic mailing lists, source code control systems,
61+
and issue tracking systems that are managed by, or on behalf of, the
62+
Licensor for the purpose of discussing and improving the Work, but
63+
excluding communication that is conspicuously marked or otherwise
64+
designated in writing by the copyright owner as Not a Contribution.
65+
66+
Contributor shall mean Licensor and any individual or Legal Entity
67+
on behalf of whom a Contribution has been received by Licensor and
68+
subsequently incorporated within the Work.
69+
70+
2. Grant of Copyright License. Subject to the terms and conditions of
71+
this License, each Contributor hereby grants to You a perpetual,
72+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
73+
copyright license to reproduce, prepare Derivative Works of,
74+
publicly display, publicly perform, sublicense, and distribute the
75+
Work and such Derivative Works in Source or Object form.
76+
77+
3. Grant of Patent License. Subject to the terms and conditions of
78+
this License, each Contributor hereby grants to You a perpetual,
79+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
80+
(except as stated in this section) patent license to make, have made,
81+
use, offer to sell, sell, import, and otherwise transfer the Work,
82+
where such license applies only to those patent claims licensable
83+
by such Contributor that are necessarily infringed by their
84+
Contribution(s) alone or by combination of their Contribution(s)
85+
with the Work to which such Contribution(s) was submitted. If You
86+
institute patent litigation against any entity (including a
87+
cross-claim or counterclaim in a lawsuit) alleging that the Work
88+
or a Contribution incorporated within the Work constitutes direct
89+
or contributory patent infringement, then any patent licenses
90+
granted to You under this License for that Work shall terminate
91+
as of the date such litigation is filed.
92+
93+
4. Redistribution. You may reproduce and distribute copies of the
94+
Work or Derivative Works thereof in any medium, with or without
95+
modifications, and in Source or Object form, provided that You
96+
meet the following conditions
97+
98+
(a) You must give any other recipients of the Work or
99+
Derivative Works a copy of this License; and
100+
101+
(b) You must cause any modified files to carry prominent notices
102+
stating that You changed the files; and
103+
104+
(c) You must retain, in the Source form of any Derivative Works
105+
that You distribute, all copyright, patent, trademark, and
106+
attribution notices from the Source form of the Work,
107+
excluding those notices that do not pertain to any part of
108+
the Derivative Works; and
109+
110+
(d) If the Work includes a NOTICE text file as part of its
111+
distribution, then any Derivative Works that You distribute must
112+
include a readable copy of the attribution notices contained
113+
within such NOTICE file, excluding those notices that do not
114+
pertain to any part of the Derivative Works, in at least one
115+
of the following places within a NOTICE text file distributed
116+
as part of the Derivative Works; within the Source form or
117+
documentation, if provided along with the Derivative Works; or,
118+
within a display generated by the Derivative Works, if and
119+
wherever such third-party notices normally appear. The contents
120+
of the NOTICE file are for informational purposes only and
121+
do not modify the License. You may add Your own attribution
122+
notices within Derivative Works that You distribute, alongside
123+
or as an addendum to the NOTICE text from the Work, provided
124+
that such additional attribution notices cannot be construed
125+
as modifying the License.
126+
127+
You may add Your own copyright statement to Your modifications and
128+
may provide additional or different license terms and conditions
129+
for use, reproduction, or distribution of Your modifications, or
130+
for any such Derivative Works as a whole, provided Your use,
131+
reproduction, and distribution of the Work otherwise complies with
132+
the conditions stated in this License.
133+
134+
5. Submission of Contributions. Unless You explicitly state otherwise,
135+
any Contribution intentionally submitted for inclusion in the Work
136+
by You to the Licensor shall be under the terms and conditions of
137+
this License, without any additional terms or conditions.
138+
Notwithstanding the above, nothing herein shall supersede or modify
139+
the terms of any separate license agreement you may have executed
140+
with Licensor regarding such Contributions.
141+
142+
6. Trademarks. This License does not grant permission to use the trade
143+
names, trademarks, service marks, or product names of the Licensor,
144+
except as required for reasonable and customary use in describing the
145+
origin of the Work and reproducing the content of the NOTICE file.
146+
147+
7. Disclaimer of Warranty. Unless required by applicable law or
148+
agreed to in writing, Licensor provides the Work (and each
149+
Contributor provides its Contributions) on an AS IS BASIS,
150+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
151+
implied, including, without limitation, any warranties or conditions
152+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
153+
PARTICULAR PURPOSE. You are solely responsible for determining the
154+
appropriateness of using or redistributing the Work and assume any
155+
risks associated with Your exercise of permissions under this License.
156+
157+
8. Limitation of Liability. In no event and under no legal theory,
158+
whether in tort (including negligence), contract, or otherwise,
159+
unless required by applicable law (such as deliberate and grossly
160+
negligent acts) or agreed to in writing, shall any Contributor be
161+
liable to You for damages, including any direct, indirect, special,
162+
incidental, or consequential damages of any character arising as a
163+
result of this License or out of the use or inability to use the
164+
Work (including but not limited to damages for loss of goodwill,
165+
work stoppage, computer failure or malfunction, or any and all
166+
other commercial damages or losses), even if such Contributor
167+
has been advised of the possibility of such damages.
168+
169+
9. Accepting Warranty or Additional Liability. While redistributing
170+
the Work or Derivative Works thereof, You may choose to offer,
171+
and charge a fee for, acceptance of support, warranty, indemnity,
172+
or other liability obligations andor rights consistent with this
173+
License. However, in accepting such obligations, You may act only
174+
on Your own behalf and on Your sole responsibility, not on behalf
175+
of any other Contributor, and only if You agree to indemnify,
176+
defend, and hold each Contributor harmless for any liability
177+
incurred by, or claims asserted against, such Contributor by reason
178+
of your accepting any such warranty or additional liability.
179+
180+
END OF TERMS AND CONDITIONS
181+
182+
Copyright 2017 Databricks, Inc.
183+
184+
Licensed under the Apache License, Version 2.0 (the License);
185+
you may not use this file except in compliance with the License.
186+
You may obtain a copy of the License at
187+
188+
http://www.apache.org/licenses/LICENSE-2.0
189+
190+
Unless required by applicable law or agreed to in writing, software
191+
distributed under the License is distributed on an AS IS BASIS,
192+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
193+
See the License for the specific language governing permissions and
194+
limitations under the License.

‎NOTICE.txt

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# Databricks CLI
2+
# Copyright 2017 Databricks, Inc.
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License”), except
5+
# that the use of services to which certain application programming
6+
# interfaces (each, an "API") connect requires that the user first obtain
7+
# a license for the use of the APIs from Databricks, Inc. ("Databricks"),
8+
# by creating an account at www.databricks.com and agreeing to either (a)
9+
# the Community Edition Terms of Service, (b) the Databricks Terms of
10+
# Service, or (c) another written agreement between Licensee and Databricks
11+
# for the use of the APIs.
12+
#
13+
# You may not use this file except in compliance with the License.
14+
# You may obtain a copy of the License at
15+
#
16+
# http://www.apache.org/licenses/LICENSE-2.0
17+
#
18+
# Unless required by applicable law or agreed to in writing, software
19+
# distributed under the License is distributed on an "AS IS" BASIS,
20+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21+
# See the License for the specific language governing permissions and
22+
# limitations under the License.
23+

‎README.rst

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
databricks-cli
2+
==============
3+
.. image:: https://travis-ci.org/databricks/databricks-cli.svg?branch=master
4+
:target: https://travis-ci.org/databricks/databricks-cli
5+
:alt: Build Status
6+
7+
8+
This repository includes the code for the command line interface to
9+
Databricks APIs. Currently, the only APIs implemented are for DBFS.
10+
**PLEASE NOTE**, this CLI is under active development and is released as
11+
an experimental client. This
12+
means that interfaces are subject to being changed and that
13+
SLAs/engineering support are not provided.
14+
15+
If you're interested in contributing to the project please reach out.
16+
In addition, please leave bug reports as issues on our `Github project <https://github.com/databricks/databricks-cli>`_.
17+
18+
Requirements
19+
------------
20+
21+
- Python Version > 2.7.9
22+
- Python 3 is not supported
23+
24+
Installation
25+
---------------
26+
27+
To install simply run
28+
``pip install databricks-cli``
29+
30+
In order to upgrade your databricks-cli installation please run
31+
``pip install --upgrade databricks-cli``
32+
33+
Getting started
34+
----------------
35+
36+
After installing, ``dbfs`` will be installed into your PATH. Try it out
37+
by running ``dbfs --help``.
38+
39+
To configure your username/password/host try running ``dbfs configure``.
40+
You will be prompted for your username, password, and host.
41+
42+
Known Issues
43+
---------------
44+
``AttributeError: 'module' object has no attribute 'PROTOCOL_TLSv1_2'``
45+
46+
For compliance reasons, our webapp requires the client to speak TLSV1.2. The built in
47+
version of Python for MacOS does not have this version of TLS built in.
48+
49+
To use databricks-cli you should install a version of Python which has ``ssl.PROTOCOL_TLSv1_2``.
50+
For MacOS, the easiest way may be to install Python with `Homebrew <https://brew.sh/>`_.
51+
52+
53+
Don't have a password because of SSO?
54+
-------------------------------------
55+
56+
Your administrator can choose to set a password for you.

‎databricks_cli/__init__.py

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# Databricks CLI
2+
# Copyright 2017 Databricks, Inc.
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License"), except
5+
# that the use of services to which certain application programming
6+
# interfaces (each, an "API") connect requires that the user first obtain
7+
# a license for the use of the APIs from Databricks, Inc. ("Databricks"),
8+
# by creating an account at www.databricks.com and agreeing to either (a)
9+
# the Community Edition Terms of Service, (b) the Databricks Terms of
10+
# Service, or (c) another written agreement between Licensee and Databricks
11+
# for the use of the APIs.
12+
#
13+
# You may not use this file except in compliance with the License.
14+
# You may obtain a copy of the License at
15+
#
16+
# http://www.apache.org/licenses/LICENSE-2.0
17+
#
18+
# Unless required by applicable law or agreed to in writing, software
19+
# distributed under the License is distributed on an "AS IS" BASIS,
20+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21+
# See the License for the specific language governing permissions and
22+
# limitations under the License.

‎databricks_cli/cli.py

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# Databricks CLI
2+
# Copyright 2017 Databricks, Inc.
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License"), except
5+
# that the use of services to which certain application programming
6+
# interfaces (each, an "API") connect requires that the user first obtain
7+
# a license for the use of the APIs from Databricks, Inc. ("Databricks"),
8+
# by creating an account at www.databricks.com and agreeing to either (a)
9+
# the Community Edition Terms of Service, (b) the Databricks Terms of
10+
# Service, or (c) another written agreement between Licensee and Databricks
11+
# for the use of the APIs.
12+
#
13+
# You may not use this file except in compliance with the License.
14+
# You may obtain a copy of the License at
15+
#
16+
# http://www.apache.org/licenses/LICENSE-2.0
17+
#
18+
# Unless required by applicable law or agreed to in writing, software
19+
# distributed under the License is distributed on an "AS IS" BASIS,
20+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21+
# See the License for the specific language governing permissions and
22+
# limitations under the License.
23+
24+
import click
25+
26+
from databricks_cli.version import print_version_callback
27+
from databricks_cli.utils import CONTEXT_SETTINGS
28+
from databricks_cli.configure.cli import configure_cli
29+
from databricks_cli.dbfs.cli import dbfs_group
30+
31+
32+
@click.group(context_settings=CONTEXT_SETTINGS)
33+
@click.option('--version', '-v', is_flag=True, callback=print_version_callback,
34+
expose_value=False, is_eager=True)
35+
def cli():
36+
pass
37+
38+
39+
cli.add_command(configure_cli, name='configure')
40+
cli.add_command(dbfs_group, name='fs')

‎databricks_cli/configure/__init__.py

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# Databricks CLI
2+
# Copyright 2017 Databricks, Inc.
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License"), except
5+
# that the use of services to which certain application programming
6+
# interfaces (each, an "API") connect requires that the user first obtain
7+
# a license for the use of the APIs from Databricks, Inc. ("Databricks"),
8+
# by creating an account at www.databricks.com and agreeing to either (a)
9+
# the Community Edition Terms of Service, (b) the Databricks Terms of
10+
# Service, or (c) another written agreement between Licensee and Databricks
11+
# for the use of the APIs.
12+
#
13+
# You may not use this file except in compliance with the License.
14+
# You may obtain a copy of the License at
15+
#
16+
# http://www.apache.org/licenses/LICENSE-2.0
17+
#
18+
# Unless required by applicable law or agreed to in writing, software
19+
# distributed under the License is distributed on an "AS IS" BASIS,
20+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21+
# See the License for the specific language governing permissions and
22+
# limitations under the License.

‎databricks_cli/configure/cli.py

+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
# Databricks CLI
2+
# Copyright 2017 Databricks, Inc.
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License"), except
5+
# that the use of services to which certain application programming
6+
# interfaces (each, an "API") connect requires that the user first obtain
7+
# a license for the use of the APIs from Databricks, Inc. ("Databricks"),
8+
# by creating an account at www.databricks.com and agreeing to either (a)
9+
# the Community Edition Terms of Service, (b) the Databricks Terms of
10+
# Service, or (c) another written agreement between Licensee and Databricks
11+
# for the use of the APIs.
12+
#
13+
# You may not use this file except in compliance with the License.
14+
# You may obtain a copy of the License at
15+
#
16+
# http://www.apache.org/licenses/LICENSE-2.0
17+
#
18+
# Unless required by applicable law or agreed to in writing, software
19+
# distributed under the License is distributed on an "AS IS" BASIS,
20+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21+
# See the License for the specific language governing permissions and
22+
# limitations under the License.
23+
24+
import click
25+
26+
from click import ParamType
27+
28+
from databricks_cli.utils import CONTEXT_SETTINGS
29+
from databricks_cli.configure.config import DatabricksConfig
30+
31+
32+
PROMPT_HOST = 'Databricks Host (should begin with https://)'
33+
PROMPT_USERNAME = 'Username'
34+
PROMPT_PASSWORD = 'Password' # NOQA
35+
36+
37+
@click.command(context_settings=CONTEXT_SETTINGS)
38+
def configure_cli():
39+
conf = DatabricksConfig.fetch_from_fs()
40+
if conf.password:
41+
default_password = '*' * len(conf.password)
42+
else:
43+
default_password = None
44+
host = click.prompt(PROMPT_HOST, default=conf.host, type=_DbfsHost())
45+
username = click.prompt(PROMPT_USERNAME, default=conf.username)
46+
password = click.prompt(PROMPT_PASSWORD, default=default_password, hide_input=True,
47+
confirmation_prompt=True)
48+
if password == default_password:
49+
password = conf.password
50+
config = DatabricksConfig(host, username, password)
51+
config.overwrite()
52+
53+
54+
class _DbfsHost(ParamType):
55+
"""
56+
Used to validate the configured host
57+
"""
58+
def convert(self, value, param, ctx):
59+
if value.startswith('https://'):
60+
return value
61+
else:
62+
self.fail('The host does not start with https://')

‎databricks_cli/configure/config.py

+99
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
# Databricks CLI
2+
# Copyright 2017 Databricks, Inc.
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License"), except
5+
# that the use of services to which certain application programming
6+
# interfaces (each, an "API") connect requires that the user first obtain
7+
# a license for the use of the APIs from Databricks, Inc. ("Databricks"),
8+
# by creating an account at www.databricks.com and agreeing to either (a)
9+
# the Community Edition Terms of Service, (b) the Databricks Terms of
10+
# Service, or (c) another written agreement between Licensee and Databricks
11+
# for the use of the APIs.
12+
#
13+
# You may not use this file except in compliance with the License.
14+
# You may obtain a copy of the License at
15+
#
16+
# http://www.apache.org/licenses/LICENSE-2.0
17+
#
18+
# Unless required by applicable law or agreed to in writing, software
19+
# distributed under the License is distributed on an "AS IS" BASIS,
20+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21+
# See the License for the specific language governing permissions and
22+
# limitations under the License.
23+
24+
import ConfigParser
25+
import sys
26+
import os
27+
28+
from os.path import expanduser, join
29+
30+
from databricks_cli.utils import error_and_quit
31+
from databricks_cli.sdk import ApiClient, DbfsService
32+
33+
DEFAULT_SECTION = 'DEFAULT'
34+
HOST = 'host'
35+
USERNAME = 'username'
36+
PASSWORD = 'password' # NOQA
37+
38+
39+
def require_config(function):
40+
def decorator(*args, **kwargs):
41+
config = DatabricksConfig.fetch_from_fs()
42+
if not config.is_valid:
43+
error_and_quit(('You haven\'t configured the CLI yet! '
44+
'Please configure by entering `{} configure`').format(sys.argv[0]))
45+
return function(*args, **kwargs)
46+
decorator.__doc__ = function.__doc__
47+
return decorator
48+
49+
50+
def get_dbfs_client():
51+
conf = DatabricksConfig.fetch_from_fs()
52+
return DbfsService(ApiClient(conf.username, conf.password, host=conf.host))
53+
54+
55+
class DatabricksConfig(object):
56+
home = expanduser('~')
57+
58+
def __init__(self, host=None, username=None, password=None):
59+
self.config = ConfigParser.RawConfigParser()
60+
if host:
61+
self.config.set(DEFAULT_SECTION, HOST, host)
62+
if username:
63+
self.config.set(DEFAULT_SECTION, USERNAME, username)
64+
if password:
65+
self.config.set(DEFAULT_SECTION, PASSWORD, password)
66+
67+
def overwrite(self):
68+
config_path = join(self.home, '.databrickscfg')
69+
with open(config_path, 'wb') as cfg:
70+
self.config.write(cfg)
71+
os.chmod(config_path, 0o600)
72+
73+
@property
74+
def is_valid(self):
75+
return self.config.has_option(DEFAULT_SECTION, USERNAME) and \
76+
self.config.has_option(DEFAULT_SECTION, PASSWORD) and \
77+
self.config.has_option(DEFAULT_SECTION, HOST)
78+
79+
@property
80+
def host(self):
81+
return self.config.get(DEFAULT_SECTION, HOST) if self.is_valid else None
82+
83+
@property
84+
def username(self):
85+
return self.config.get(DEFAULT_SECTION, USERNAME) if self.is_valid else None
86+
87+
@property
88+
def password(self):
89+
return self.config.get(DEFAULT_SECTION, PASSWORD) if self.is_valid else None
90+
91+
@classmethod
92+
def fetch_from_fs(cls):
93+
databricks_config = cls()
94+
databricks_config.config.read(cls.get_path())
95+
return databricks_config
96+
97+
@classmethod
98+
def get_path(cls):
99+
return join(cls.home, '.databrickscfg')

‎databricks_cli/dbfs/__init__.py

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# Databricks CLI
2+
# Copyright 2017 Databricks, Inc.
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License"), except
5+
# that the use of services to which certain application programming
6+
# interfaces (each, an "API") connect requires that the user first obtain
7+
# a license for the use of the APIs from Databricks, Inc. ("Databricks"),
8+
# by creating an account at www.databricks.com and agreeing to either (a)
9+
# the Community Edition Terms of Service, (b) the Databricks Terms of
10+
# Service, or (c) another written agreement between Licensee and Databricks
11+
# for the use of the APIs.
12+
#
13+
# You may not use this file except in compliance with the License.
14+
# You may obtain a copy of the License at
15+
#
16+
# http://www.apache.org/licenses/LICENSE-2.0
17+
#
18+
# Unless required by applicable law or agreed to in writing, software
19+
# distributed under the License is distributed on an "AS IS" BASIS,
20+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21+
# See the License for the specific language governing permissions and
22+
# limitations under the License.

‎databricks_cli/dbfs/api.py

+137
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
# Databricks CLI
2+
# Copyright 2017 Databricks, Inc.
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License"), except
5+
# that the use of services to which certain application programming
6+
# interfaces (each, an "API") connect requires that the user first obtain
7+
# a license for the use of the APIs from Databricks, Inc. ("Databricks"),
8+
# by creating an account at www.databricks.com and agreeing to either (a)
9+
# the Community Edition Terms of Service, (b) the Databricks Terms of
10+
# Service, or (c) another written agreement between Licensee and Databricks
11+
# for the use of the APIs.
12+
#
13+
# You may not use this file except in compliance with the License.
14+
# You may obtain a copy of the License at
15+
#
16+
# http://www.apache.org/licenses/LICENSE-2.0
17+
#
18+
# Unless required by applicable law or agreed to in writing, software
19+
# distributed under the License is distributed on an "AS IS" BASIS,
20+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21+
# See the License for the specific language governing permissions and
22+
# limitations under the License.
23+
24+
from base64 import b64encode, b64decode
25+
26+
import os
27+
import click
28+
29+
from requests.exceptions import HTTPError
30+
from databricks_cli.utils import error_and_quit
31+
from databricks_cli.configure.config import get_dbfs_client
32+
from databricks_cli.dbfs.dbfs_path import DbfsPath
33+
from databricks_cli.dbfs.exceptions import LocalFileExistsException
34+
35+
BUFFER_SIZE_BYTES = 2**20
36+
37+
38+
class FileInfo(object):
39+
def __init__(self, dbfs_path, is_dir, file_size):
40+
self.dbfs_path = dbfs_path
41+
self.is_dir = is_dir
42+
self.file_size = file_size
43+
44+
def to_row(self, is_long_form, is_absolute):
45+
path = self.dbfs_path.absolute_path if is_absolute else self.dbfs_path.basename
46+
stylized_path = click.style(path, 'cyan') if self.is_dir else path
47+
if is_long_form:
48+
filetype = 'dir' if self.is_dir else 'file'
49+
return [filetype, self.file_size, stylized_path]
50+
return [stylized_path]
51+
52+
@classmethod
53+
def from_json(cls, json):
54+
dbfs_path = DbfsPath.from_api_path(json['path'])
55+
return cls(dbfs_path, json['is_dir'], json['file_size'])
56+
57+
def __eq__(self, other):
58+
if isinstance(other, self.__class__):
59+
return self.dbfs_path == other.dbfs_path and \
60+
self.is_dir == other.is_dir and \
61+
self.file_size == other.file_size
62+
return False
63+
64+
65+
class DbfsErrorCodes(object):
66+
RESOURCE_DOES_NOT_EXIST = 'RESOURCE_DOES_NOT_EXIST'
67+
RESOURCE_ALREADY_EXISTS = 'RESOURCE_ALREADY_EXISTS'
68+
69+
70+
def list_files(dbfs_path):
71+
dbfs_api = get_dbfs_client()
72+
list_response = dbfs_api.list(dbfs_path.absolute_path)
73+
if 'files' in list_response:
74+
return [FileInfo.from_json(f) for f in list_response['files']]
75+
else:
76+
return []
77+
78+
79+
def file_exists(dbfs_path):
80+
try:
81+
get_status(dbfs_path)
82+
except HTTPError as e:
83+
if e.response.json()['error_code'] == DbfsErrorCodes.RESOURCE_DOES_NOT_EXIST:
84+
return False
85+
raise e
86+
return True
87+
88+
89+
def get_status(dbfs_path):
90+
dbfs_api = get_dbfs_client()
91+
json = dbfs_api.get_status(dbfs_path.absolute_path)
92+
return FileInfo.from_json(json)
93+
94+
95+
def put_file(src_path, dbfs_path, overwrite):
96+
dbfs_api = get_dbfs_client()
97+
handle = dbfs_api.create(dbfs_path.absolute_path, overwrite)['handle']
98+
with open(src_path, 'rb') as local_file:
99+
while True:
100+
contents = local_file.read(BUFFER_SIZE_BYTES)
101+
if len(contents) == 0:
102+
break
103+
dbfs_api.add_block(handle, b64encode(contents))
104+
dbfs_api.close(handle)
105+
106+
107+
def get_file(dbfs_path, dst_path, overwrite):
108+
if os.path.exists(dst_path) and not overwrite:
109+
raise LocalFileExistsException
110+
dbfs_api = get_dbfs_client()
111+
file_info = get_status(dbfs_path)
112+
if file_info.is_dir:
113+
error_and_quit(('The dbfs file {} is a directory.').format(repr(dbfs_path)))
114+
length = file_info.file_size
115+
offset = 0
116+
with open(dst_path, 'wb') as local_file:
117+
while offset < length:
118+
response = dbfs_api.read(dbfs_path.absolute_path, offset, BUFFER_SIZE_BYTES)
119+
bytes_read = response['bytes_read']
120+
data = response['data']
121+
offset += bytes_read
122+
local_file.write(b64decode(data))
123+
124+
125+
def delete(dbfs_path, recursive):
126+
dbfs_api = get_dbfs_client()
127+
dbfs_api.delete(dbfs_path.absolute_path, recursive=recursive)
128+
129+
130+
def mkdirs(dbfs_path):
131+
dbfs_api = get_dbfs_client()
132+
dbfs_api.mkdirs(dbfs_path.absolute_path)
133+
134+
135+
def move(dbfs_src, dbfs_dst):
136+
dbfs_api = get_dbfs_client()
137+
dbfs_api.move(dbfs_src.absolute_path, dbfs_dst.absolute_path)

‎databricks_cli/dbfs/cli.py

+249
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,249 @@
1+
# Databricks CLI
2+
# Copyright 2017 Databricks, Inc.
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License"), except
5+
# that the use of services to which certain application programming
6+
# interfaces (each, an "API") connect requires that the user first obtain
7+
# a license for the use of the APIs from Databricks, Inc. ("Databricks"),
8+
# by creating an account at www.databricks.com and agreeing to either (a)
9+
# the Community Edition Terms of Service, (b) the Databricks Terms of
10+
# Service, or (c) another written agreement between Licensee and Databricks
11+
# for the use of the APIs.
12+
#
13+
# You may not use this file except in compliance with the License.
14+
# You may obtain a copy of the License at
15+
#
16+
# http://www.apache.org/licenses/LICENSE-2.0
17+
#
18+
# Unless required by applicable law or agreed to in writing, software
19+
# distributed under the License is distributed on an "AS IS" BASIS,
20+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21+
# See the License for the specific language governing permissions and
22+
# limitations under the License.
23+
24+
import os
25+
import click
26+
from tabulate import tabulate
27+
from requests.exceptions import HTTPError
28+
29+
from databricks_cli.utils import eat_exceptions, error_and_quit, CONTEXT_SETTINGS
30+
from databricks_cli.version import print_version_callback
31+
from databricks_cli.configure.cli import configure_cli
32+
from databricks_cli.configure.config import require_config
33+
from databricks_cli.dbfs.api import put_file, get_file, list_files, \
34+
delete, mkdirs, get_status, DbfsErrorCodes, move
35+
from databricks_cli.dbfs.dbfs_path import DbfsPath, DbfsPathClickType
36+
from databricks_cli.dbfs.exceptions import LocalFileExistsException
37+
38+
39+
@click.command(context_settings=CONTEXT_SETTINGS)
40+
@click.option('--absolute', is_flag=True, default=False,
41+
help='Displays absolute paths.')
42+
@click.option('-l', is_flag=True, default=False,
43+
help='Displays full information including size and file type.')
44+
@click.argument('dbfs_path', nargs=-1, type=DbfsPathClickType())
45+
@require_config
46+
@eat_exceptions
47+
def ls_cli(l, absolute, dbfs_path): # NOQA
48+
"""
49+
List files in DBFS.
50+
"""
51+
if len(dbfs_path) == 0:
52+
dbfs_path = DbfsPath('dbfs:/')
53+
elif len(dbfs_path) == 1:
54+
dbfs_path = dbfs_path[0]
55+
else:
56+
error_and_quit('ls can take a maximum of one path.')
57+
files = list_files(dbfs_path)
58+
table = tabulate([f.to_row(is_long_form=l, is_absolute=absolute) for f in files],
59+
tablefmt='plain')
60+
click.echo(table)
61+
62+
63+
@click.command(context_settings=CONTEXT_SETTINGS)
64+
@click.argument('dbfs_path', type=DbfsPathClickType())
65+
@require_config
66+
@eat_exceptions
67+
def mkdirs_cli(dbfs_path):
68+
"""
69+
Make directories in DBFS.
70+
71+
Note that this function is subtly different than mkdir. Mkdir requires
72+
the parent directory of the input to already exist. Mkdirs will create directories
73+
along the path to the argument directory.
74+
"""
75+
mkdirs(dbfs_path)
76+
77+
78+
@click.command(context_settings=CONTEXT_SETTINGS)
79+
@click.option('--recursive', '-r', is_flag=True, default=False)
80+
@click.argument('dbfs_path', type=DbfsPathClickType())
81+
@require_config
82+
@eat_exceptions
83+
def rm_cli(recursive, dbfs_path):
84+
"""
85+
Remove files from dbfs.
86+
87+
To remove a directory you must provide the --recursive flag.
88+
"""
89+
delete(dbfs_path, recursive)
90+
91+
92+
def copy_to_dbfs(src, dbfs_path_dst, overwrite):
93+
try:
94+
put_file(src, dbfs_path_dst, overwrite)
95+
except HTTPError as e:
96+
if e.response.json()['error_code'] == DbfsErrorCodes.RESOURCE_ALREADY_EXISTS:
97+
click.echo(e.response.json())
98+
else:
99+
raise e
100+
101+
102+
def copy_from_dbfs(dbfs_path_src, dst, overwrite):
103+
# Will truncate the local file if it exists.
104+
try:
105+
get_file(dbfs_path_src, dst, overwrite)
106+
except LocalFileExistsException:
107+
click.echo(('The host destination {} already exists. You should provide the '
108+
'--overwrite flag.')
109+
.format(dst))
110+
111+
112+
def copy_to_dbfs_non_recursive(src, dbfs_path_dst, overwrite):
113+
# Munge dst path in case dbfs_path_dst is a dir
114+
try:
115+
if get_status(dbfs_path_dst).is_dir:
116+
dbfs_path_dst = dbfs_path_dst.join(os.path.basename(src))
117+
except HTTPError as e:
118+
if e.response.json()['error_code'] == DbfsErrorCodes.RESOURCE_DOES_NOT_EXIST:
119+
pass
120+
else:
121+
raise e
122+
copy_to_dbfs(src, dbfs_path_dst, overwrite)
123+
124+
125+
def copy_from_dbfs_non_recursive(dbfs_path_src, dst, overwrite):
126+
# Munge dst path in case dst is a dir
127+
if os.path.isdir(dst):
128+
dst = os.path.join(dst, dbfs_path_src.basename)
129+
copy_from_dbfs(dbfs_path_src, dst, overwrite)
130+
131+
132+
def copy_to_dbfs_recursive(src, dbfs_path_dst, overwrite):
133+
try:
134+
mkdirs(dbfs_path_dst)
135+
except HTTPError as e:
136+
if e.response.json()['error_code'] == DbfsErrorCodes.RESOURCE_ALREADY_EXISTS:
137+
click.echo(e.response.json())
138+
return
139+
for filename in os.listdir(src):
140+
cur_src = os.path.join(src, filename)
141+
cur_dbfs_dst = dbfs_path_dst.join(filename)
142+
if os.path.isdir(cur_src):
143+
copy_to_dbfs_recursive(cur_src, cur_dbfs_dst, overwrite)
144+
elif os.path.isfile(cur_src):
145+
copy_to_dbfs(cur_src, cur_dbfs_dst, overwrite)
146+
147+
148+
def copy_from_dbfs_recursive(dbfs_path_src, dst, overwrite):
149+
if os.path.isfile(dst):
150+
click.echo('{} exists as a file. Skipping this subtree {}'.format(dst, repr(dbfs_path_src)))
151+
elif not os.path.isdir(dst):
152+
os.makedirs(dst)
153+
154+
for dbfs_src_file_info in list_files(dbfs_path_src):
155+
cur_dbfs_src = dbfs_src_file_info.dbfs_path
156+
cur_dst = os.path.join(dst, cur_dbfs_src.basename)
157+
if dbfs_src_file_info.is_dir:
158+
copy_from_dbfs_recursive(cur_dbfs_src, cur_dst, overwrite)
159+
else:
160+
copy_from_dbfs(cur_dbfs_src, cur_dst, overwrite)
161+
162+
163+
@click.command(context_settings=CONTEXT_SETTINGS)
164+
@click.option('--recursive', '-r', is_flag=True, default=False)
165+
@click.option('--overwrite', is_flag=True, default=False)
166+
@click.argument('src')
167+
@click.argument('dst')
168+
@require_config
169+
@eat_exceptions
170+
def cp_cli(recursive, overwrite, src, dst):
171+
"""
172+
Copy files to and from DBFS.
173+
174+
Note that this function will fail if the src and dst are both on the local filesystem
175+
or if they are both DBFS paths.
176+
177+
For non-recursive copies, if the dst is a directory, the file will be placed inside the
178+
directory. For example ``dbfs cp dbfs:/apple.txt .`` will create a file at `./apple.txt`.
179+
180+
For recursive copies, files inside of the src directory will be copied inside the dst directory
181+
with the same name. If the dst path does not exist, a directory will be created. For example
182+
``dbfs cp -r dbfs:/foo foo`` will create a directory foo and place the files ``dbfs:/foo/a`` at
183+
``foo/a``. If ``foo/a`` already exists, the file will not be overriden unless the --overwrite
184+
flag is provided -- however, dbfs cp --recursive will continue to try and copy other files.
185+
"""
186+
# Copy to DBFS in this case
187+
if not DbfsPath.is_valid(src) and DbfsPath.is_valid(dst):
188+
if not os.path.exists(src):
189+
error_and_quit('The local file {} does not exist.'.format(src))
190+
if not recursive:
191+
if os.path.isdir(src):
192+
error_and_quit(('The local file {} is a directory. You must provide --recursive')
193+
.format(src))
194+
copy_to_dbfs_non_recursive(src, DbfsPath(dst), overwrite)
195+
else:
196+
if not os.path.isdir(src):
197+
copy_to_dbfs_non_recursive(src, DbfsPath(dst), overwrite)
198+
return
199+
copy_to_dbfs_recursive(src, DbfsPath(dst), overwrite)
200+
# Copy from DBFS in this case
201+
elif DbfsPath.is_valid(src) and not DbfsPath.is_valid(dst):
202+
if not recursive:
203+
copy_from_dbfs_non_recursive(DbfsPath(src), dst, overwrite)
204+
else:
205+
dbfs_path_src = DbfsPath(src)
206+
if not get_status(dbfs_path_src).is_dir:
207+
copy_from_dbfs_non_recursive(dbfs_path_src, dst, overwrite)
208+
copy_from_dbfs_recursive(dbfs_path_src, dst, overwrite)
209+
elif not DbfsPath.is_valid(src) and not DbfsPath.is_valid(dst):
210+
error_and_quit('Both paths provided are from your local filesystem. '
211+
'To use this utility, one of the src or dst must be prefixed '
212+
'with dbfs:/')
213+
elif DbfsPath.is_valid(src) and DbfsPath.is_valid(dst):
214+
error_and_quit('Both paths provided are from the DBFS filesystem. '
215+
'To copy between the DBFS filesystem, you currently must copy the '
216+
'file from DBFS to your local filesystem and then back.')
217+
else:
218+
assert False, 'not reached'
219+
220+
221+
@click.command(context_settings=CONTEXT_SETTINGS)
222+
@click.argument('src', type=DbfsPathClickType())
223+
@click.argument('dst', type=DbfsPathClickType())
224+
@require_config
225+
@eat_exceptions
226+
def mv_cli(src, dst):
227+
"""
228+
Moves a file between two DBFS paths.
229+
"""
230+
move(src, dst)
231+
232+
233+
@click.group(context_settings=CONTEXT_SETTINGS)
234+
@click.option('--version', '-v', is_flag=True, callback=print_version_callback,
235+
expose_value=False, is_eager=True)
236+
def dbfs_group():
237+
"""
238+
Utility to interact with DBFS.
239+
DBFS paths are all prefixed with dbfs:/. Local paths can be absolute or local.
240+
"""
241+
pass
242+
243+
244+
dbfs_group.add_command(configure_cli, name='configure')
245+
dbfs_group.add_command(ls_cli, name='ls')
246+
dbfs_group.add_command(mkdirs_cli, name='mkdirs')
247+
dbfs_group.add_command(rm_cli, name='rm')
248+
dbfs_group.add_command(cp_cli, name='cp')
249+
dbfs_group.add_command(mv_cli, name='mv')

‎databricks_cli/dbfs/dbfs_path.py

+122
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
# Databricks CLI
2+
# Copyright 2017 Databricks, Inc.
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License"), except
5+
# that the use of services to which certain application programming
6+
# interfaces (each, an "API") connect requires that the user first obtain
7+
# a license for the use of the APIs from Databricks, Inc. ("Databricks"),
8+
# by creating an account at www.databricks.com and agreeing to either (a)
9+
# the Community Edition Terms of Service, (b) the Databricks Terms of
10+
# Service, or (c) another written agreement between Licensee and Databricks
11+
# for the use of the APIs.
12+
#
13+
# You may not use this file except in compliance with the License.
14+
# You may obtain a copy of the License at
15+
#
16+
# http://www.apache.org/licenses/LICENSE-2.0
17+
#
18+
# Unless required by applicable law or agreed to in writing, software
19+
# distributed under the License is distributed on an "AS IS" BASIS,
20+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21+
# See the License for the specific language governing permissions and
22+
# limitations under the License.
23+
24+
import os
25+
import click
26+
27+
from click import ParamType
28+
29+
from databricks_cli.utils import error_and_quit
30+
31+
32+
class DbfsPath(object):
33+
def __init__(self, absolute_path, validate=True):
34+
self.absolute_path = absolute_path
35+
if validate:
36+
self.validate()
37+
38+
@classmethod
39+
def from_api_path(cls, path):
40+
return cls('dbfs:' + path)
41+
42+
@classmethod
43+
def is_valid(cls, path):
44+
return cls(path, validate=False).is_absolute_path
45+
46+
def validate(self):
47+
"""
48+
Checks that the path is a proper DbfsPath. it must have a prefix of
49+
"dbfs:" and must be an absolute path.
50+
"""
51+
if self.absolute_path.startswith('dbfs://'):
52+
error_and_quit(('The path {} cannot start with dbfs://. '
53+
'It must start with dbfs:/').format(repr(self)))
54+
if not self.is_absolute_path:
55+
error_and_quit('The path {} must start with "{}"'.format(
56+
repr(self), repr(DbfsPath('dbfs:/'))))
57+
58+
def join(self, file_name):
59+
"""
60+
Returns a new extended DBFS path with a file_name.
61+
:param: file_name
62+
:type: str
63+
:rtype: DbfsPath
64+
"""
65+
stripped_dbfs_path = self._strip_trailing_slash()
66+
if stripped_dbfs_path.is_root:
67+
absolute_path = stripped_dbfs_path.absolute_path + file_name
68+
else:
69+
absolute_path = stripped_dbfs_path.absolute_path + '/' + file_name
70+
return DbfsPath(absolute_path)
71+
72+
def relpath(self, dbfs_path_prefix):
73+
"""
74+
Strips the prefix of this DbfsPath. Behaves very similar to os.path.relpath
75+
"""
76+
return os.path.relpath(self.absolute_path, dbfs_path_prefix.absolute_path)
77+
78+
@property
79+
def basename(self):
80+
"""
81+
This function is like the basename utility and is unlike os.path.basename.
82+
>>> assert DbfsPath('dbfs:/').basename == ''
83+
>>> assert DbfsPath('dbfs:/test').basename == 'test'
84+
>>> assert DbfsPath('dbfs:/test/').basename == 'test'
85+
"""
86+
if self.is_root:
87+
return ''
88+
elif self.absolute_path[-1] == '/':
89+
return self.absolute_path.split('/')[-2]
90+
else:
91+
return self.absolute_path.split('/')[-1]
92+
93+
@property
94+
def is_absolute_path(self):
95+
return self.absolute_path.startswith('dbfs:/')
96+
97+
@property
98+
def is_root(self):
99+
return self.absolute_path == 'dbfs:/'
100+
101+
def _strip_trailing_slash(self):
102+
if self.is_root:
103+
return DbfsPath('dbfs:/')
104+
elif self.absolute_path[-1] == '/':
105+
return DbfsPath(self.absolute_path[0:-1])
106+
else:
107+
return DbfsPath(self.absolute_path)
108+
109+
def __repr__(self):
110+
return click.style(self.absolute_path, underline=True)
111+
112+
def __eq__(self, other):
113+
if isinstance(other, self.__class__):
114+
return self.absolute_path == other.absolute_path
115+
return False
116+
117+
118+
class DbfsPathClickType(ParamType):
119+
name = 'Path'
120+
121+
def convert(self, value, param, ctx):
122+
return DbfsPath(value)

‎databricks_cli/dbfs/exceptions.py

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# Databricks CLI
2+
# Copyright 2017 Databricks, Inc.
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License"), except
5+
# that the use of services to which certain application programming
6+
# interfaces (each, an "API") connect requires that the user first obtain
7+
# a license for the use of the APIs from Databricks, Inc. ("Databricks"),
8+
# by creating an account at www.databricks.com and agreeing to either (a)
9+
# the Community Edition Terms of Service, (b) the Databricks Terms of
10+
# Service, or (c) another written agreement between Licensee and Databricks
11+
# for the use of the APIs.
12+
#
13+
# You may not use this file except in compliance with the License.
14+
# You may obtain a copy of the License at
15+
#
16+
# http://www.apache.org/licenses/LICENSE-2.0
17+
#
18+
# Unless required by applicable law or agreed to in writing, software
19+
# distributed under the License is distributed on an "AS IS" BASIS,
20+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21+
# See the License for the specific language governing permissions and
22+
# limitations under the License.
23+
24+
25+
class LocalFileExistsException(Exception):
26+
pass

‎databricks_cli/sdk/__init__.py

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
# Databricks CLI
2+
# Copyright 2017 Databricks, Inc.
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License"), except
5+
# that the use of services to which certain application programming
6+
# interfaces (each, an "API") connect requires that the user first obtain
7+
# a license for the use of the APIs from Databricks, Inc. ("Databricks"),
8+
# by creating an account at www.databricks.com and agreeing to either (a)
9+
# the Community Edition Terms of Service, (b) the Databricks Terms of
10+
# Service, or (c) another written agreement between Licensee and Databricks
11+
# for the use of the APIs.
12+
#
13+
# You may not use this file except in compliance with the License.
14+
# You may obtain a copy of the License at
15+
#
16+
# http://www.apache.org/licenses/LICENSE-2.0
17+
#
18+
# Unless required by applicable law or agreed to in writing, software
19+
# distributed under the License is distributed on an "AS IS" BASIS,
20+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21+
# See the License for the specific language governing permissions and
22+
# limitations under the License.
23+
24+
"""
25+
Databricks Python REST Client 2.0 for interacting with various services.
26+
27+
Currently supports services including clusters and jobs.
28+
29+
Requires Python 2.7.9 or above.
30+
31+
To get started, below is an example usage of the Python API client.
32+
33+
# Import databricks package:
34+
from databricks import *
35+
36+
# Create a client:
37+
userName = "user@company.com"
38+
password = "MySecretPassword"
39+
client = ApiClient(userName, password, host = "https://dbc-12345678-9101.cloud.databricks.com")
40+
41+
# List jobs:
42+
jobs = JobsService(client)
43+
print jobs.list_jobs()
44+
45+
# For help:
46+
help(databricks)
47+
48+
# To examine available services:
49+
help(databricks.service)
50+
51+
# To examine the jobs API:
52+
help(JobsService)
53+
"""
54+
from .service import *
55+
from .objects import *
56+
from .api_client import ApiClient

‎databricks_cli/sdk/api_client.py

+109
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
#!/usr/bin/env python
2+
3+
# Databricks CLI
4+
# Copyright 2017 Databricks, Inc.
5+
#
6+
# Licensed under the Apache License, Version 2.0 (the "License"), except
7+
# that the use of services to which certain application programming
8+
# interfaces (each, an "API") connect requires that the user first obtain
9+
# a license for the use of the APIs from Databricks, Inc. ("Databricks"),
10+
# by creating an account at www.databricks.com and agreeing to either (a)
11+
# the Community Edition Terms of Service, (b) the Databricks Terms of
12+
# Service, or (c) another written agreement between Licensee and Databricks
13+
# for the use of the APIs.
14+
#
15+
# You may not use this file except in compliance with the License.
16+
# You may obtain a copy of the License at
17+
#
18+
# http://www.apache.org/licenses/LICENSE-2.0
19+
#
20+
# Unless required by applicable law or agreed to in writing, software
21+
# distributed under the License is distributed on an "AS IS" BASIS,
22+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
23+
# See the License for the specific language governing permissions and
24+
# limitations under the License.
25+
26+
27+
"""
28+
A common class to be used by client of different APIs
29+
"""
30+
31+
import base64
32+
import json
33+
import warnings
34+
import requests
35+
import ssl
36+
37+
import version
38+
39+
from requests.adapters import HTTPAdapter
40+
41+
try:
42+
from requests.packages.urllib3.poolmanager import PoolManager
43+
from requests.packages.urllib3 import exceptions
44+
requests.packages.urllib3.disable_warnings()
45+
except ImportError:
46+
from urllib3.poolmanager import PoolManager
47+
from urllib3 import exceptions
48+
49+
class TlsV1HttpAdapter(HTTPAdapter):
50+
"""
51+
A HTTP adapter implementation that specifies the ssl version to be TLS1.
52+
This avoids problems with openssl versions that
53+
use SSL3 as a default (which is not supported by the server side).
54+
"""
55+
56+
def init_poolmanager(self, connections, maxsize, block=False):
57+
self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize, block=block, ssl_version=ssl.PROTOCOL_TLSv1_2)
58+
59+
class ApiClient(object):
60+
"""
61+
A partial Python implementation of dbc rest api
62+
to be used by different versions of the client.
63+
"""
64+
def __init__(self, user = None, password = None, host = None, configUrl = None,
65+
apiVersion = version.API_VERSION, default_headers = {}):
66+
if configUrl:
67+
self.url = configUrl
68+
params = self.performQuery("/", headers = {})[1]
69+
params = credential.json
70+
user = str(params["user"])
71+
password = str(params["password"])
72+
host = str(params["apiUrl"].split("/api")[0])
73+
74+
if host[-1] == "/":
75+
host = host[:-1]
76+
77+
self.session = requests.Session()
78+
self.session.mount('https://', TlsV1HttpAdapter())
79+
80+
self.url = "%s/api/%s" % (host, apiVersion)
81+
if user is not None and password is not None:
82+
userHeaderData = "Basic " + base64.standard_b64encode(user + ":" + password)
83+
auth = {'Authorization': userHeaderData, 'Content-Type': 'text/json'}
84+
else:
85+
auth = {}
86+
self.default_headers = dict(auth.items() + default_headers.items())
87+
88+
def close(self):
89+
"""Close the client"""
90+
pass
91+
92+
# helper functions starting here
93+
94+
def perform_query(self, method, path, data = {}, headers = None):
95+
"""set up connection and perform query"""
96+
if headers is None:
97+
headers = self.default_headers
98+
99+
with warnings.catch_warnings():
100+
warnings.simplefilter("ignore", exceptions.InsecureRequestWarning)
101+
resp = self.session.request(method, self.url + path, data = json.dumps(data),
102+
verify = False, headers = headers)
103+
104+
try:
105+
resp.raise_for_status()
106+
except requests.exceptions.HTTPError, e:
107+
raise e
108+
return resp.json()
109+

‎databricks_cli/sdk/objects.py

+301
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,301 @@
1+
# Databricks CLI
2+
# Copyright 2017 Databricks, Inc.
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License"), except
5+
# that the use of services to which certain application programming
6+
# interfaces (each, an "API") connect requires that the user first obtain
7+
# a license for the use of the APIs from Databricks, Inc. ("Databricks"),
8+
# by creating an account at www.databricks.com and agreeing to either (a)
9+
# the Community Edition Terms of Service, (b) the Databricks Terms of
10+
# Service, or (c) another written agreement between Licensee and Databricks
11+
# for the use of the APIs.
12+
#
13+
# You may not use this file except in compliance with the License.
14+
# You may obtain a copy of the License at
15+
#
16+
# http://www.apache.org/licenses/LICENSE-2.0
17+
#
18+
# Unless required by applicable law or agreed to in writing, software
19+
# distributed under the License is distributed on an "AS IS" BASIS,
20+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21+
# See the License for the specific language governing permissions and
22+
# limitations under the License.
23+
24+
class AutoScale(dict):
25+
def __init__(self, min_workers=None, max_workers=None):
26+
super(AutoScale, self).__init__()
27+
if min_workers is not None:
28+
self['min_workers'] = min_workers
29+
if max_workers is not None:
30+
self['max_workers'] = max_workers
31+
32+
class AwsAttributes(dict):
33+
def __init__(self, first_on_demand=None, availability=None, zone_id=None,
34+
instance_profile_arn=None, spot_bid_price_percent=None, ebs_volume_type=None,
35+
ebs_volume_count=None, ebs_volume_size=None):
36+
super(AwsAttributes, self).__init__()
37+
if first_on_demand is not None:
38+
self['first_on_demand'] = first_on_demand
39+
if availability is not None:
40+
self['availability'] = availability
41+
if zone_id is not None:
42+
self['zone_id'] = zone_id
43+
if instance_profile_arn is not None:
44+
self['instance_profile_arn'] = instance_profile_arn
45+
if spot_bid_price_percent is not None:
46+
self['spot_bid_price_percent'] = spot_bid_price_percent
47+
if ebs_volume_type is not None:
48+
self['ebs_volume_type'] = ebs_volume_type
49+
if ebs_volume_count is not None:
50+
self['ebs_volume_count'] = ebs_volume_count
51+
if ebs_volume_size is not None:
52+
self['ebs_volume_size'] = ebs_volume_size
53+
54+
class ClusterLogConf(dict):
55+
def __init__(self, dbfs=None, s3=None):
56+
super(ClusterLogConf, self).__init__()
57+
if dbfs is not None:
58+
self['dbfs'] = dbfs
59+
if not isinstance(dbfs, dict):
60+
raise TypeError('Expected databricks.DbfsStorageInfo() or dict for field dbfs')
61+
if s3 is not None:
62+
self['s3'] = s3
63+
if not isinstance(s3, dict):
64+
raise TypeError('Expected databricks.S3StorageInfo() or dict for field s3')
65+
66+
class DbfsStorageInfo(dict):
67+
def __init__(self, destination=None):
68+
super(DbfsStorageInfo, self).__init__()
69+
if destination is not None:
70+
self['destination'] = destination
71+
72+
class S3StorageInfo(dict):
73+
def __init__(self, destination=None, region=None, endpoint=None, enable_encryption=None,
74+
encryption_type=None, kms_key=None, canned_acl=None):
75+
super(S3StorageInfo, self).__init__()
76+
if destination is not None:
77+
self['destination'] = destination
78+
if region is not None:
79+
self['region'] = region
80+
if endpoint is not None:
81+
self['endpoint'] = endpoint
82+
if enable_encryption is not None:
83+
self['enable_encryption'] = enable_encryption
84+
if encryption_type is not None:
85+
self['encryption_type'] = encryption_type
86+
if kms_key is not None:
87+
self['kms_key'] = kms_key
88+
if canned_acl is not None:
89+
self['canned_acl'] = canned_acl
90+
91+
class ClusterTag(dict):
92+
def __init__(self, key=None, value=None):
93+
super(ClusterTag, self).__init__()
94+
if key is not None:
95+
self['key'] = key
96+
if value is not None:
97+
self['value'] = value
98+
99+
class SparkConfPair(dict):
100+
def __init__(self, key=None, value=None):
101+
super(SparkConfPair, self).__init__()
102+
if key is not None:
103+
self['key'] = key
104+
if value is not None:
105+
self['value'] = value
106+
107+
class SparkEnvPair(dict):
108+
def __init__(self, key=None, value=None):
109+
super(SparkEnvPair, self).__init__()
110+
if key is not None:
111+
self['key'] = key
112+
if value is not None:
113+
self['value'] = value
114+
115+
class NewCluster(dict):
116+
def __init__(self, cluster_name=None, spark_version=None, spark_conf=None,
117+
aws_attributes=None, node_type_id=None, driver_node_type_id=None,
118+
ssh_public_keys=None, custom_tags=None, cluster_log_conf=None,
119+
spark_env_vars=None, autotermination_minutes=None, enable_elastic_disk=None,
120+
num_workers=None, autoscale=None):
121+
super(NewCluster, self).__init__()
122+
if cluster_name is not None:
123+
self['cluster_name'] = cluster_name
124+
if spark_version is not None:
125+
self['spark_version'] = spark_version
126+
if spark_conf is not None:
127+
self['spark_conf'] = spark_conf
128+
if aws_attributes is not None:
129+
self['aws_attributes'] = aws_attributes
130+
if not isinstance(aws_attributes, dict):
131+
raise TypeError('Expected databricks.AwsAttributes() or dict for field aws_attributes')
132+
if node_type_id is not None:
133+
self['node_type_id'] = node_type_id
134+
if driver_node_type_id is not None:
135+
self['driver_node_type_id'] = driver_node_type_id
136+
if ssh_public_keys is not None:
137+
self['ssh_public_keys'] = ssh_public_keys
138+
if custom_tags is not None:
139+
self['custom_tags'] = custom_tags
140+
if cluster_log_conf is not None:
141+
self['cluster_log_conf'] = cluster_log_conf
142+
if not isinstance(cluster_log_conf, dict):
143+
raise TypeError('Expected databricks.ClusterLogConf() or dict for field cluster_log_conf')
144+
if spark_env_vars is not None:
145+
self['spark_env_vars'] = spark_env_vars
146+
if autotermination_minutes is not None:
147+
self['autotermination_minutes'] = autotermination_minutes
148+
if enable_elastic_disk is not None:
149+
self['enable_elastic_disk'] = enable_elastic_disk
150+
if num_workers is not None:
151+
self['num_workers'] = num_workers
152+
if autoscale is not None:
153+
self['autoscale'] = autoscale
154+
if not isinstance(autoscale, dict):
155+
raise TypeError('Expected databricks.AutoScale() or dict for field autoscale')
156+
157+
class CronSchedule(dict):
158+
def __init__(self, quartz_cron_expression, timezone_id):
159+
super(CronSchedule, self).__init__()
160+
if quartz_cron_expression is not None:
161+
self['quartz_cron_expression'] = quartz_cron_expression
162+
if timezone_id is not None:
163+
self['timezone_id'] = timezone_id
164+
165+
class JobSettings(dict):
166+
def __init__(self, name=None, existing_cluster_id=None, new_cluster=None, libraries=None,
167+
email_notifications=None, timeout_seconds=None, max_retries=None,
168+
min_retry_interval_millis=None, retry_on_timeout=None, schedule=None,
169+
notebook_task=None, spark_jar_task=None, max_concurrent_runs=None):
170+
super(JobSettings, self).__init__()
171+
if name is not None:
172+
self['name'] = name
173+
if existing_cluster_id is not None:
174+
self['existing_cluster_id'] = existing_cluster_id
175+
if new_cluster is not None:
176+
self['new_cluster'] = new_cluster
177+
if not isinstance(new_cluster, dict):
178+
raise TypeError('Expected databricks.NewCluster() or dict for field new_cluster')
179+
if libraries is not None:
180+
self['libraries'] = libraries
181+
if email_notifications is not None:
182+
self['email_notifications'] = email_notifications
183+
if not isinstance(email_notifications, dict):
184+
raise TypeError('Expected databricks.JobEmailNotifications() or dict for field email_notifications')
185+
if timeout_seconds is not None:
186+
self['timeout_seconds'] = timeout_seconds
187+
if max_retries is not None:
188+
self['max_retries'] = max_retries
189+
if min_retry_interval_millis is not None:
190+
self['min_retry_interval_millis'] = min_retry_interval_millis
191+
if retry_on_timeout is not None:
192+
self['retry_on_timeout'] = retry_on_timeout
193+
if schedule is not None:
194+
self['schedule'] = schedule
195+
if not isinstance(schedule, dict):
196+
raise TypeError('Expected databricks.CronSchedule() or dict for field schedule')
197+
if notebook_task is not None:
198+
self['notebook_task'] = notebook_task
199+
if not isinstance(notebook_task, dict):
200+
raise TypeError('Expected databricks.NotebookTask() or dict for field notebook_task')
201+
if spark_jar_task is not None:
202+
self['spark_jar_task'] = spark_jar_task
203+
if not isinstance(spark_jar_task, dict):
204+
raise TypeError('Expected databricks.SparkJarTask() or dict for field spark_jar_task')
205+
if max_concurrent_runs is not None:
206+
self['max_concurrent_runs'] = max_concurrent_runs
207+
208+
class JobEmailNotifications(dict):
209+
def __init__(self, on_start=None, on_success=None, on_failure=None):
210+
super(JobEmailNotifications, self).__init__()
211+
if on_start is not None:
212+
self['on_start'] = on_start
213+
if on_success is not None:
214+
self['on_success'] = on_success
215+
if on_failure is not None:
216+
self['on_failure'] = on_failure
217+
218+
class NotebookTask(dict):
219+
def __init__(self, notebook_path, base_parameters=None):
220+
super(NotebookTask, self).__init__()
221+
if notebook_path is not None:
222+
self['notebook_path'] = notebook_path
223+
if base_parameters is not None:
224+
self['base_parameters'] = base_parameters
225+
226+
class ParamPair(dict):
227+
def __init__(self, key=None, value=None):
228+
super(ParamPair, self).__init__()
229+
if key is not None:
230+
self['key'] = key
231+
if value is not None:
232+
self['value'] = value
233+
234+
class SparkJarTask(dict):
235+
def __init__(self, jar_uri=None, main_class_name=None, parameters=None):
236+
super(SparkJarTask, self).__init__()
237+
if jar_uri is not None:
238+
self['jar_uri'] = jar_uri
239+
if main_class_name is not None:
240+
self['main_class_name'] = main_class_name
241+
if parameters is not None:
242+
self['parameters'] = parameters
243+
244+
class EggSpecification(dict):
245+
def __init__(self, uri=None):
246+
super(EggSpecification, self).__init__()
247+
if uri is not None:
248+
self['uri'] = uri
249+
250+
class JarSpecification(dict):
251+
def __init__(self, uri=None):
252+
super(JarSpecification, self).__init__()
253+
if uri is not None:
254+
self['uri'] = uri
255+
256+
class MavenSpecification(dict):
257+
def __init__(self):
258+
super(MavenSpecification, self).__init__()
259+
pass
260+
261+
class PipSpecification(dict):
262+
def __init__(self, package_name=None, version_specifier=None):
263+
super(PipSpecification, self).__init__()
264+
if package_name is not None:
265+
self['package_name'] = package_name
266+
if version_specifier is not None:
267+
self['version_specifier'] = version_specifier
268+
269+
class Library(dict):
270+
def __init__(self, jar=None, egg=None, pypi=None, maven=None):
271+
super(Library, self).__init__()
272+
if jar is not None:
273+
self['jar'] = jar
274+
if egg is not None:
275+
self['egg'] = egg
276+
if pypi is not None:
277+
self['pypi'] = pypi
278+
if not isinstance(pypi, dict):
279+
raise TypeError('Expected databricks.PythonPyPiLibrary() or dict for field pypi')
280+
if maven is not None:
281+
self['maven'] = maven
282+
if not isinstance(maven, dict):
283+
raise TypeError('Expected databricks.MavenLibrary() or dict for field maven')
284+
285+
class MavenLibrary(dict):
286+
def __init__(self, coordinates, repo=None, exclusions=None):
287+
super(MavenLibrary, self).__init__()
288+
if coordinates is not None:
289+
self['coordinates'] = coordinates
290+
if repo is not None:
291+
self['repo'] = repo
292+
if exclusions is not None:
293+
self['exclusions'] = exclusions
294+
295+
class PythonPyPiLibrary(dict):
296+
def __init__(self, package, repo=None):
297+
super(PythonPyPiLibrary, self).__init__()
298+
if package is not None:
299+
self['package'] = package
300+
if repo is not None:
301+
self['repo'] = repo

‎databricks_cli/sdk/service.py

+459
Large diffs are not rendered by default.

‎databricks_cli/sdk/version.py

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Databricks CLI
2+
# Copyright 2017 Databricks, Inc.
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License"), except
5+
# that the use of services to which certain application programming
6+
# interfaces (each, an "API") connect requires that the user first obtain
7+
# a license for the use of the APIs from Databricks, Inc. ("Databricks"),
8+
# by creating an account at www.databricks.com and agreeing to either (a)
9+
# the Community Edition Terms of Service, (b) the Databricks Terms of
10+
# Service, or (c) another written agreement between Licensee and Databricks
11+
# for the use of the APIs.
12+
#
13+
# You may not use this file except in compliance with the License.
14+
# You may obtain a copy of the License at
15+
#
16+
# http://www.apache.org/licenses/LICENSE-2.0
17+
#
18+
# Unless required by applicable law or agreed to in writing, software
19+
# distributed under the License is distributed on an "AS IS" BASIS,
20+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21+
# See the License for the specific language governing permissions and
22+
# limitations under the License.
23+
24+
API_VERSION=2.0

‎databricks_cli/utils.py

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
# Databricks CLI
2+
# Copyright 2017 Databricks, Inc.
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License"), except
5+
# that the use of services to which certain application programming
6+
# interfaces (each, an "API") connect requires that the user first obtain
7+
# a license for the use of the APIs from Databricks, Inc. ("Databricks"),
8+
# by creating an account at www.databricks.com and agreeing to either (a)
9+
# the Community Edition Terms of Service, (b) the Databricks Terms of
10+
# Service, or (c) another written agreement between Licensee and Databricks
11+
# for the use of the APIs.
12+
#
13+
# You may not use this file except in compliance with the License.
14+
# You may obtain a copy of the License at
15+
#
16+
# http://www.apache.org/licenses/LICENSE-2.0
17+
#
18+
# Unless required by applicable law or agreed to in writing, software
19+
# distributed under the License is distributed on an "AS IS" BASIS,
20+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21+
# See the License for the specific language governing permissions and
22+
# limitations under the License.
23+
24+
import sys
25+
import click
26+
27+
from requests.exceptions import HTTPError
28+
29+
30+
CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
31+
32+
33+
def eat_exceptions(function):
34+
def decorator(*args, **kwargs):
35+
try:
36+
return function(*args, **kwargs)
37+
except HTTPError as exception:
38+
if exception.response.status_code == 401:
39+
error_and_quit('Your authentication information may be incorrect. Please '
40+
'reconfigure with ``dbfs configure``')
41+
else:
42+
error_and_quit(exception.response.content)
43+
decorator.__doc__ = function.__doc__
44+
return decorator
45+
46+
47+
def error_and_quit(message):
48+
click.echo('Error: {}'.format(message))
49+
sys.exit(1)

‎databricks_cli/version.py

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# Databricks CLI
2+
# Copyright 2017 Databricks, Inc.
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License"), except
5+
# that the use of services to which certain application programming
6+
# interfaces (each, an "API") connect requires that the user first obtain
7+
# a license for the use of the APIs from Databricks, Inc. ("Databricks"),
8+
# by creating an account at www.databricks.com and agreeing to either (a)
9+
# the Community Edition Terms of Service, (b) the Databricks Terms of
10+
# Service, or (c) another written agreement between Licensee and Databricks
11+
# for the use of the APIs.
12+
#
13+
# You may not use this file except in compliance with the License.
14+
# You may obtain a copy of the License at
15+
#
16+
# http://www.apache.org/licenses/LICENSE-2.0
17+
#
18+
# Unless required by applicable law or agreed to in writing, software
19+
# distributed under the License is distributed on an "AS IS" BASIS,
20+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21+
# See the License for the specific language governing permissions and
22+
# limitations under the License.
23+
24+
version = '0.1' # NOQA
25+
26+
27+
def print_version_callback(ctx, param, value): # NOQA
28+
import click
29+
if not value or ctx.resilient_parsing:
30+
return
31+
click.echo('Version {}'.format(version))
32+
ctx.exit()

‎dev-requirements.txt

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
# Test reqs
2+
prospector[with_pyroma]
3+
pytest
4+
mock
5+
# Real reqs
6+
click>=6.7
7+
requests>=2.17.3
8+
tabulate>=0.7.7

‎lint.sh

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
#!/usr/bin/env bash
2+
3+
FWDIR="$(cd "`dirname $0`"; pwd)"
4+
cd "$FWDIR"
5+
6+
prospector --profile "$FWDIR/prospector.yaml"

‎prospector.yaml

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
strictness: high
2+
test-warnings: True
3+
doc-warnings: false
4+
5+
ignore-paths:
6+
- sdk
7+
8+
max-line-length: 100
9+
10+
pylint:
11+
disable:
12+
- too-many-instance-attributes
13+
- cyclic-import
14+
- len-as-condition
15+
- invalid-name
16+
- no-else-return
17+
- no-self-use
18+
19+
mccabe:
20+
disable:
21+
- MC0001
22+
23+
pyroma:
24+
run: true

‎setup.py

+58
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
# Databricks CLI
2+
# Copyright 2017 Databricks, Inc.
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License"), except
5+
# that the use of services to which certain application programming
6+
# interfaces (each, an "API") connect requires that the user first obtain
7+
# a license for the use of the APIs from Databricks, Inc. ("Databricks"),
8+
# by creating an account at www.databricks.com and agreeing to either (a)
9+
# the Community Edition Terms of Service, (b) the Databricks Terms of
10+
# Service, or (c) another written agreement between Licensee and Databricks
11+
# for the use of the APIs.
12+
#
13+
# You may not use this file except in compliance with the License.
14+
# You may obtain a copy of the License at
15+
#
16+
# http://www.apache.org/licenses/LICENSE-2.0
17+
#
18+
# Unless required by applicable law or agreed to in writing, software
19+
# distributed under the License is distributed on an "AS IS" BASIS,
20+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21+
# See the License for the specific language governing permissions and
22+
# limitations under the License.
23+
24+
import imp
25+
import os
26+
from setuptools import setup, find_packages
27+
28+
version = imp.load_source(
29+
'databricks_cli.version', os.path.join('databricks_cli', 'version.py')).version
30+
31+
setup(
32+
name='databricks-cli',
33+
version=version,
34+
packages=find_packages(exclude=['tests', 'tests.*']),
35+
install_requires=[
36+
'click>=6.7',
37+
'requests>=2.17.3',
38+
'tabulate>=0.7.7',
39+
],
40+
entry_points='''
41+
[console_scripts]
42+
databricks=databricks_cli.cli:cli
43+
dbfs=databricks_cli.dbfs.cli:dbfs_group
44+
''',
45+
zip_safe=False,
46+
author='Andrew Chen',
47+
author_email='andrewchen@databricks.com',
48+
description='A command line interface for Databricks',
49+
long_description=open('README.rst').read(),
50+
license='Apache License 2.0',
51+
classifiers=[
52+
'Intended Audience :: Developers',
53+
'Intended Audience :: System Administrators',
54+
'Programming Language :: Python :: 2.7',
55+
],
56+
keywords='databricks cli',
57+
url='https://github.com/databricks/databricks-cli'
58+
)

‎tests/__init__.py

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# Databricks CLI
2+
# Copyright 2017 Databricks, Inc.
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License"), except
5+
# that the use of services to which certain application programming
6+
# interfaces (each, an "API") connect requires that the user first obtain
7+
# a license for the use of the APIs from Databricks, Inc. ("Databricks"),
8+
# by creating an account at www.databricks.com and agreeing to either (a)
9+
# the Community Edition Terms of Service, (b) the Databricks Terms of
10+
# Service, or (c) another written agreement between Licensee and Databricks
11+
# for the use of the APIs.
12+
#
13+
# You may not use this file except in compliance with the License.
14+
# You may obtain a copy of the License at
15+
#
16+
# http://www.apache.org/licenses/LICENSE-2.0
17+
#
18+
# Unless required by applicable law or agreed to in writing, software
19+
# distributed under the License is distributed on an "AS IS" BASIS,
20+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21+
# See the License for the specific language governing permissions and
22+
# limitations under the License.

‎tests/configure/__init__.py

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# Databricks CLI
2+
# Copyright 2017 Databricks, Inc.
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License"), except
5+
# that the use of services to which certain application programming
6+
# interfaces (each, an "API") connect requires that the user first obtain
7+
# a license for the use of the APIs from Databricks, Inc. ("Databricks"),
8+
# by creating an account at www.databricks.com and agreeing to either (a)
9+
# the Community Edition Terms of Service, (b) the Databricks Terms of
10+
# Service, or (c) another written agreement between Licensee and Databricks
11+
# for the use of the APIs.
12+
#
13+
# You may not use this file except in compliance with the License.
14+
# You may obtain a copy of the License at
15+
#
16+
# http://www.apache.org/licenses/LICENSE-2.0
17+
#
18+
# Unless required by applicable law or agreed to in writing, software
19+
# distributed under the License is distributed on an "AS IS" BASIS,
20+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21+
# See the License for the specific language governing permissions and
22+
# limitations under the License.

‎tests/configure/test_config.py

+64
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
# Databricks CLI
2+
# Copyright 2017 Databricks, Inc.
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License"), except
5+
# that the use of services to which certain application programming
6+
# interfaces (each, an "API") connect requires that the user first obtain
7+
# a license for the use of the APIs from Databricks, Inc. ("Databricks"),
8+
# by creating an account at www.databricks.com and agreeing to either (a)
9+
# the Community Edition Terms of Service, (b) the Databricks Terms of
10+
# Service, or (c) another written agreement between Licensee and Databricks
11+
# for the use of the APIs.
12+
#
13+
# You may not use this file except in compliance with the License.
14+
# You may obtain a copy of the License at
15+
#
16+
# http://www.apache.org/licenses/LICENSE-2.0
17+
#
18+
# Unless required by applicable law or agreed to in writing, software
19+
# distributed under the License is distributed on an "AS IS" BASIS,
20+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21+
# See the License for the specific language governing permissions and
22+
# limitations under the License.
23+
24+
import mock
25+
26+
import databricks_cli.configure.config as config
27+
28+
29+
def test_require_config_valid():
30+
with mock.patch('databricks_cli.configure.config.DatabricksConfig') as DatabricksConfigMock:
31+
config_mock = DatabricksConfigMock.fetch_from_fs.return_value
32+
config_mock.is_valid = True
33+
34+
@config.require_config
35+
def test_function(x):
36+
return x
37+
38+
assert test_function(1) == 1
39+
40+
41+
def test_require_config_invalid():
42+
with mock.patch('databricks_cli.configure.config.DatabricksConfig') as DatabricksConfigMock:
43+
with mock.patch('databricks_cli.configure.config.error_and_quit') as error_and_quit_mock:
44+
config_mock = DatabricksConfigMock.fetch_from_fs.return_value
45+
config_mock.is_valid = False
46+
47+
@config.require_config
48+
def test_function(x):
49+
return x
50+
51+
test_function(1)
52+
53+
assert error_and_quit_mock.call_count == 1
54+
assert 'You haven\'t configured the CLI' in error_and_quit_mock.call_args[0][0]
55+
56+
57+
class TestDatabricksConfig(object):
58+
def test_is_valid_true(self):
59+
databricks_config = config.DatabricksConfig('host', 'username', 'password')
60+
assert databricks_config.is_valid
61+
62+
def test_is_valid_false(self):
63+
databricks_config = config.DatabricksConfig('host', 'username')
64+
assert not databricks_config.is_valid

‎tests/dbfs/__init__.py

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# Databricks CLI
2+
# Copyright 2017 Databricks, Inc.
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License"), except
5+
# that the use of services to which certain application programming
6+
# interfaces (each, an "API") connect requires that the user first obtain
7+
# a license for the use of the APIs from Databricks, Inc. ("Databricks"),
8+
# by creating an account at www.databricks.com and agreeing to either (a)
9+
# the Community Edition Terms of Service, (b) the Databricks Terms of
10+
# Service, or (c) another written agreement between Licensee and Databricks
11+
# for the use of the APIs.
12+
#
13+
# You may not use this file except in compliance with the License.
14+
# You may obtain a copy of the License at
15+
#
16+
# http://www.apache.org/licenses/LICENSE-2.0
17+
#
18+
# Unless required by applicable law or agreed to in writing, software
19+
# distributed under the License is distributed on an "AS IS" BASIS,
20+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21+
# See the License for the specific language governing permissions and
22+
# limitations under the License.

‎tests/dbfs/test_api.py

+157
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,157 @@
1+
# Databricks CLI
2+
# Copyright 2017 Databricks, Inc.
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License"), except
5+
# that the use of services to which certain application programming
6+
# interfaces (each, an "API") connect requires that the user first obtain
7+
# a license for the use of the APIs from Databricks, Inc. ("Databricks"),
8+
# by creating an account at www.databricks.com and agreeing to either (a)
9+
# the Community Edition Terms of Service, (b) the Databricks Terms of
10+
# Service, or (c) another written agreement between Licensee and Databricks
11+
# for the use of the APIs.
12+
#
13+
# You may not use this file except in compliance with the License.
14+
# You may obtain a copy of the License at
15+
#
16+
# http://www.apache.org/licenses/LICENSE-2.0
17+
#
18+
# Unless required by applicable law or agreed to in writing, software
19+
# distributed under the License is distributed on an "AS IS" BASIS,
20+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21+
# See the License for the specific language governing permissions and
22+
# limitations under the License.
23+
24+
from base64 import b64encode
25+
26+
import os
27+
import requests
28+
import mock
29+
import pytest
30+
31+
import databricks_cli.dbfs.api as api
32+
from databricks_cli.dbfs.dbfs_path import DbfsPath
33+
from databricks_cli.dbfs.exceptions import LocalFileExistsException
34+
35+
TEST_DBFS_PATH = DbfsPath('dbfs:/test')
36+
TEST_FILE_JSON = {
37+
'path': '/test',
38+
'is_dir': False,
39+
'file_size': 1
40+
}
41+
TEST_FILE_INFO = api.FileInfo(TEST_DBFS_PATH, False, 1)
42+
43+
44+
def get_resource_does_not_exist_exception():
45+
response = requests.Response()
46+
response._content = '{"error_code": "' + api.DbfsErrorCodes.RESOURCE_DOES_NOT_EXIST + '"}' # NOQA
47+
return requests.exceptions.HTTPError(response=response)
48+
49+
50+
class TestFileInfo(object):
51+
def test_to_row_not_long_form_not_absolute(self):
52+
file_info = api.FileInfo(TEST_DBFS_PATH, False, 1)
53+
row = file_info.to_row(is_long_form=False, is_absolute=False)
54+
assert len(row) == 1
55+
assert TEST_DBFS_PATH.basename == row[0]
56+
57+
def test_to_row_long_form_not_absolute(self):
58+
file_info = api.FileInfo(TEST_DBFS_PATH, False, 1)
59+
row = file_info.to_row(is_long_form=True, is_absolute=False)
60+
assert len(row) == 3
61+
assert row[0] == 'file'
62+
assert row[1] == 1
63+
assert TEST_DBFS_PATH.basename == row[2]
64+
65+
def test_from_json(self):
66+
file_info = api.FileInfo.from_json(TEST_FILE_JSON)
67+
assert file_info.dbfs_path == TEST_DBFS_PATH
68+
assert not file_info.is_dir
69+
assert file_info.file_size == 1
70+
71+
72+
def test_list_files_exists():
73+
with mock.patch('databricks_cli.dbfs.api.get_dbfs_client') as get_dbfs_client:
74+
json = {
75+
'files': [TEST_FILE_JSON]
76+
}
77+
get_dbfs_client.return_value.list.return_value = json
78+
files = api.list_files(TEST_DBFS_PATH)
79+
80+
assert len(files) == 1
81+
assert TEST_FILE_INFO == files[0]
82+
83+
84+
def test_list_files_does_not_exist():
85+
with mock.patch('databricks_cli.dbfs.api.get_dbfs_client') as get_dbfs_client:
86+
json = {}
87+
get_dbfs_client.return_value.list.return_value = json
88+
files = api.list_files(TEST_DBFS_PATH)
89+
90+
assert len(files) == 0
91+
92+
93+
def test_file_exists_true():
94+
with mock.patch('databricks_cli.dbfs.api.get_dbfs_client') as get_dbfs_client:
95+
get_dbfs_client.return_value.get_status.return_value = TEST_FILE_JSON
96+
assert api.file_exists(TEST_DBFS_PATH)
97+
98+
99+
def test_file_exists_false():
100+
with mock.patch('databricks_cli.dbfs.api.get_dbfs_client') as get_dbfs_client:
101+
exception = get_resource_does_not_exist_exception()
102+
get_dbfs_client.return_value.get_status = mock.Mock(side_effect=exception)
103+
assert not api.file_exists(TEST_DBFS_PATH)
104+
105+
106+
def test_get_status():
107+
with mock.patch('databricks_cli.dbfs.api.get_dbfs_client') as get_dbfs_client:
108+
get_dbfs_client.return_value.get_status.return_value = TEST_FILE_JSON
109+
assert api.get_status(TEST_DBFS_PATH) == TEST_FILE_INFO
110+
111+
112+
def test_get_status_fail():
113+
with mock.patch('databricks_cli.dbfs.api.get_dbfs_client') as get_dbfs_client:
114+
exception = get_resource_does_not_exist_exception()
115+
get_dbfs_client.return_value.get_status = mock.Mock(side_effect=exception)
116+
with pytest.raises(exception.__class__):
117+
api.get_status(TEST_DBFS_PATH)
118+
119+
120+
def test_put_file(tmpdir):
121+
test_file_path = os.path.join(tmpdir.strpath, 'test')
122+
with open(test_file_path, 'w') as f:
123+
f.write('test')
124+
125+
with mock.patch('databricks_cli.dbfs.api.get_dbfs_client') as get_dbfs_client:
126+
api_mock = get_dbfs_client.return_value
127+
test_handle = 0
128+
api_mock.create.return_value = {'handle': test_handle}
129+
api.put_file(test_file_path, TEST_DBFS_PATH, True)
130+
131+
assert api_mock.add_block.call_count == 1
132+
assert test_handle == api_mock.add_block.call_args[0][0]
133+
assert b64encode('test') == api_mock.add_block.call_args[0][1]
134+
135+
136+
def test_get_file_check_overwrite(tmpdir):
137+
test_file_path = os.path.join(tmpdir.strpath, 'test')
138+
with open(test_file_path, 'w') as f:
139+
f.write('test')
140+
with pytest.raises(LocalFileExistsException):
141+
api.get_file(TEST_DBFS_PATH, test_file_path, False)
142+
143+
144+
def test_get_file(tmpdir):
145+
with mock.patch('databricks_cli.dbfs.api.get_dbfs_client') as get_dbfs_client:
146+
api_mock = get_dbfs_client.return_value
147+
api_mock.get_status.return_value = TEST_FILE_JSON
148+
api_mock.read.return_value = {
149+
'bytes_read': 1,
150+
'data': b64encode('x'),
151+
}
152+
153+
test_file_path = os.path.join(tmpdir.strpath, 'test')
154+
api.get_file(TEST_DBFS_PATH, test_file_path, True)
155+
156+
with open(test_file_path, 'r') as f:
157+
assert f.read() == 'x'

‎tests/dbfs/test_dbfs_path.py

+69
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
# Databricks CLI
2+
# Copyright 2017 Databricks, Inc.
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License"), except
5+
# that the use of services to which certain application programming
6+
# interfaces (each, an "API") connect requires that the user first obtain
7+
# a license for the use of the APIs from Databricks, Inc. ("Databricks"),
8+
# by creating an account at www.databricks.com and agreeing to either (a)
9+
# the Community Edition Terms of Service, (b) the Databricks Terms of
10+
# Service, or (c) another written agreement between Licensee and Databricks
11+
# for the use of the APIs.
12+
#
13+
# You may not use this file except in compliance with the License.
14+
# You may obtain a copy of the License at
15+
#
16+
# http://www.apache.org/licenses/LICENSE-2.0
17+
#
18+
# Unless required by applicable law or agreed to in writing, software
19+
# distributed under the License is distributed on an "AS IS" BASIS,
20+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21+
# See the License for the specific language governing permissions and
22+
# limitations under the License.
23+
24+
import mock
25+
from databricks_cli.dbfs.dbfs_path import DbfsPath
26+
27+
TEST_DBFS_PATH = DbfsPath('dbfs:/test')
28+
29+
30+
class TestDbfsPath(object):
31+
def test_from_api_path_valid(self):
32+
dbfs_path = DbfsPath.from_api_path('/test')
33+
assert dbfs_path == TEST_DBFS_PATH
34+
35+
def test_from_api_path_invalid(self):
36+
with mock.patch('databricks_cli.dbfs.dbfs_path.error_and_quit') as error_and_quit_mock:
37+
DbfsPath.from_api_path('dbfs:/test')
38+
assert error_and_quit_mock.call_count == 1
39+
assert 'must start with' in error_and_quit_mock.call_args[0][0]
40+
41+
def test_is_valid_true(self):
42+
assert DbfsPath.is_valid('dbfs:/test')
43+
44+
def test_is_valid_false(self):
45+
assert not DbfsPath.is_valid('/test')
46+
assert not DbfsPath.is_valid('test')
47+
48+
def test_join(self):
49+
assert DbfsPath('dbfs:/test/a') == TEST_DBFS_PATH.join('a')
50+
51+
def test_relpath(self):
52+
assert DbfsPath('dbfs:/test/a').relpath(TEST_DBFS_PATH) == 'a'
53+
54+
def test_basename(self):
55+
assert DbfsPath('dbfs:/').basename == ''
56+
assert DbfsPath('dbfs:/test').basename == 'test'
57+
assert DbfsPath('dbfs:/test/').basename == 'test'
58+
59+
def test_is_absolute_path(self):
60+
assert DbfsPath('dbfs:/').is_absolute_path
61+
assert not DbfsPath('test', validate=False).is_absolute_path
62+
63+
def test_is_root(self):
64+
assert DbfsPath('dbfs:/').is_root
65+
assert not DbfsPath('test', validate=False).is_root
66+
67+
def test_eq(self):
68+
assert DbfsPath('dbfs:/') == DbfsPath('dbfs:/')
69+
assert DbfsPath('dbfs:/') != 'bad type'

‎tests/test_utils.py

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# Databricks CLI
2+
# Copyright 2017 Databricks, Inc.
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License"), except
5+
# that the use of services to which certain application programming
6+
# interfaces (each, an "API") connect requires that the user first obtain
7+
# a license for the use of the APIs from Databricks, Inc. ("Databricks"),
8+
# by creating an account at www.databricks.com and agreeing to either (a)
9+
# the Community Edition Terms of Service, (b) the Databricks Terms of
10+
# Service, or (c) another written agreement between Licensee and Databricks
11+
# for the use of the APIs.
12+
#
13+
# You may not use this file except in compliance with the License.
14+
# You may obtain a copy of the License at
15+
#
16+
# http://www.apache.org/licenses/LICENSE-2.0
17+
#
18+
# Unless required by applicable law or agreed to in writing, software
19+
# distributed under the License is distributed on an "AS IS" BASIS,
20+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21+
# See the License for the specific language governing permissions and
22+
# limitations under the License.
23+
24+
import mock
25+
from requests import Response
26+
from requests.exceptions import HTTPError
27+
28+
import databricks_cli.utils as utils
29+
30+
31+
def test_eat_exceptions_normal_case():
32+
"""
33+
If no exceptions, this wrapper should do nothing.
34+
"""
35+
@utils.eat_exceptions
36+
def test_function(x):
37+
return x
38+
39+
assert test_function(1) == 1
40+
41+
42+
def test_eat_exceptions_401():
43+
"""
44+
If wrapped function returns 401 HTTPError, then print special error message.
45+
"""
46+
with mock.patch('databricks_cli.utils.error_and_quit') as error_and_quit_mock:
47+
@utils.eat_exceptions
48+
def test_function():
49+
resp = Response()
50+
resp.status_code = 401
51+
raise HTTPError(response=resp)
52+
test_function()
53+
assert error_and_quit_mock.call_count == 1
54+
assert 'Your authentication information' in error_and_quit_mock.call_args[0][0]

0 commit comments

Comments
 (0)
Please sign in to comment.