dremio-cli 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. dremio_cli/__init__.py +5 -0
  2. dremio_cli/__main__.py +6 -0
  3. dremio_cli/cli.py +191 -0
  4. dremio_cli/client/__init__.py +1 -0
  5. dremio_cli/client/auth.py +100 -0
  6. dremio_cli/client/base.py +190 -0
  7. dremio_cli/client/cloud.py +305 -0
  8. dremio_cli/client/factory.py +122 -0
  9. dremio_cli/client/software.py +561 -0
  10. dremio_cli/commands/__init__.py +1 -0
  11. dremio_cli/commands/catalog.py +143 -0
  12. dremio_cli/commands/favorite.py +162 -0
  13. dremio_cli/commands/folder.py +290 -0
  14. dremio_cli/commands/grant.py +202 -0
  15. dremio_cli/commands/history.py +122 -0
  16. dremio_cli/commands/job.py +321 -0
  17. dremio_cli/commands/lineage.py +9 -0
  18. dremio_cli/commands/profile.py +165 -0
  19. dremio_cli/commands/role.py +319 -0
  20. dremio_cli/commands/source.py +375 -0
  21. dremio_cli/commands/space.py +226 -0
  22. dremio_cli/commands/sql.py +280 -0
  23. dremio_cli/commands/table.py +155 -0
  24. dremio_cli/commands/tag.py +145 -0
  25. dremio_cli/commands/udf.py +9 -0
  26. dremio_cli/commands/user.py +250 -0
  27. dremio_cli/commands/view.py +369 -0
  28. dremio_cli/commands/wiki.py +163 -0
  29. dremio_cli/config.py +193 -0
  30. dremio_cli/env.py +175 -0
  31. dremio_cli/formatters/__init__.py +1 -0
  32. dremio_cli/formatters/json.py +19 -0
  33. dremio_cli/formatters/table.py +45 -0
  34. dremio_cli/formatters/yaml.py +17 -0
  35. dremio_cli/history.py +198 -0
  36. dremio_cli/utils/__init__.py +1 -0
  37. dremio_cli/utils/exceptions.py +35 -0
  38. dremio_cli/utils/helpers.py +73 -0
  39. dremio_cli/utils/validators.py +147 -0
  40. dremio_cli-1.0.0.dist-info/METADATA +261 -0
  41. dremio_cli-1.0.0.dist-info/RECORD +45 -0
  42. dremio_cli-1.0.0.dist-info/WHEEL +5 -0
  43. dremio_cli-1.0.0.dist-info/entry_points.txt +2 -0
  44. dremio_cli-1.0.0.dist-info/licenses/LICENSE +21 -0
  45. dremio_cli-1.0.0.dist-info/top_level.txt +1 -0
dremio_cli/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Dremio CLI - A comprehensive command-line interface for Dremio."""
2
+
3
+ __version__ = "0.1.0"
4
+ __author__ = "Your Name"
5
+ __email__ = "your.email@example.com"
dremio_cli/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ """Main entry point for the Dremio CLI."""
2
+
3
+ from dremio_cli.cli import main
4
+
5
+ if __name__ == "__main__":
6
+ main()
dremio_cli/cli.py ADDED
@@ -0,0 +1,191 @@
1
+ """Main CLI module with command groups and REPL support."""
2
+
3
+ import sys
4
+ from typing import Optional
5
+
6
+ import click
7
+ from rich.console import Console
8
+
9
+ from dremio_cli.config import ProfileManager
10
+ from dremio_cli.commands import (
11
+ catalog,
12
+ profile,
13
+ source,
14
+ space,
15
+ folder,
16
+ table,
17
+ view,
18
+ sql,
19
+ job,
20
+ user,
21
+ role,
22
+ tag,
23
+ wiki,
24
+ grant,
25
+ history,
26
+ favorite,
27
+ )
28
+
29
+
30
+ console = Console()
31
+
32
+
33
+ class DremioContext:
34
+ """Context object for CLI commands."""
35
+
36
+ def __init__(self, profile_name: Optional[str] = None, output_format: str = "table"):
37
+ self.profile_manager = ProfileManager()
38
+ self.profile_name = profile_name or self.profile_manager.get_default_profile()
39
+ self.output_format = output_format
40
+ self.verbose = False
41
+
42
+
43
+ @click.group()
44
+ @click.option(
45
+ "--profile",
46
+ "-p",
47
+ help="Profile to use for this command",
48
+ type=str,
49
+ )
50
+ @click.option(
51
+ "--output",
52
+ "-o",
53
+ help="Output format",
54
+ type=click.Choice(["table", "json", "yaml"], case_sensitive=False),
55
+ default="table",
56
+ )
57
+ @click.option("--verbose", "-v", is_flag=True, help="Verbose output")
58
+ @click.option("--quiet", "-q", is_flag=True, help="Quiet mode")
59
+ @click.version_option()
60
+ @click.pass_context
61
+ def cli(
62
+ ctx: click.Context,
63
+ profile: Optional[str],
64
+ output: str,
65
+ verbose: bool,
66
+ quiet: bool,
67
+ ) -> None:
68
+ """Dremio CLI - Manage Dremio Cloud and Dremio Software from the command line."""
69
+ ctx.obj = DremioContext(profile_name=profile, output_format=output)
70
+ ctx.obj.verbose = verbose
71
+
72
+ if quiet:
73
+ console.quiet = True
74
+
75
+
76
+ # Register command groups
77
+ cli.add_command(profile.profile)
78
+ cli.add_command(catalog.catalog)
79
+ cli.add_command(source.source)
80
+ cli.add_command(space.space)
81
+ cli.add_command(folder.folder)
82
+ cli.add_command(table.table)
83
+ cli.add_command(view.view)
84
+ cli.add_command(sql.sql)
85
+ cli.add_command(job.job)
86
+ cli.add_command(user.user)
87
+ cli.add_command(role.role)
88
+ cli.add_command(tag.tag)
89
+ cli.add_command(wiki.wiki)
90
+ cli.add_command(grant.grant)
91
+ cli.add_command(history.history)
92
+ cli.add_command(favorite.favorite)
93
+
94
+
95
+
96
+ @cli.command()
97
+ @click.pass_context
98
+ def repl(ctx: click.Context) -> None:
99
+ """Start interactive REPL mode."""
100
+ from rich.table import Table
101
+
102
+ console.print("[bold green]Dremio CLI - Interactive Mode[/bold green]")
103
+ console.print("Type 'help' for available commands, 'exit' or 'quit' to exit.\n")
104
+
105
+ profile_name = ctx.obj.profile_name
106
+ console.print(f"[dim]Using profile: {profile_name}[/dim]\n")
107
+
108
+ # Help content
109
+ def show_help(command=None):
110
+ if command:
111
+ # Show help for specific command
112
+ try:
113
+ cli.main([command, '--help'], standalone_mode=False, obj=ctx.obj)
114
+ except SystemExit:
115
+ pass
116
+ else:
117
+ # Show general help
118
+ table = Table(title="Available Commands")
119
+ table.add_column("Command", style="cyan")
120
+ table.add_column("Description", style="green")
121
+
122
+ table.add_row("catalog", "Browse and navigate catalog")
123
+ table.add_row("sql", "Execute SQL queries")
124
+ table.add_row("job", "Manage jobs")
125
+ table.add_row("view", "Manage views")
126
+ table.add_row("source", "Manage sources")
127
+ table.add_row("space", "Manage spaces")
128
+ table.add_row("folder", "Manage folders")
129
+ table.add_row("grant", "Manage permissions")
130
+ table.add_row("history", "View command history")
131
+ table.add_row("favorite", "Manage favorite queries")
132
+ table.add_row("help [command]", "Show help for command")
133
+ table.add_row("exit/quit", "Exit REPL")
134
+
135
+ console.print(table)
136
+ console.print("\n[dim]Examples:[/dim]")
137
+ console.print(" catalog list")
138
+ console.print(" sql execute \"SELECT * FROM table LIMIT 10\"")
139
+ console.print(" help sql")
140
+
141
+ while True:
142
+ try:
143
+ command = console.input("[bold cyan]dremio>[/bold cyan] ")
144
+ command = command.strip()
145
+
146
+ if not command:
147
+ continue
148
+
149
+ # Handle help command
150
+ if command.lower() == "help":
151
+ show_help()
152
+ continue
153
+ elif command.lower().startswith("help "):
154
+ help_cmd = command[5:].strip()
155
+ show_help(help_cmd)
156
+ continue
157
+
158
+ if command.lower() in ("exit", "quit"):
159
+ console.print("[yellow]Goodbye![/yellow]")
160
+ break
161
+
162
+ # Parse and execute command
163
+ try:
164
+ # Remove 'dremio' prefix if present
165
+ if command.startswith("dremio "):
166
+ command = command[7:]
167
+
168
+ # Execute the command
169
+ cli.main(command.split(), standalone_mode=False, obj=ctx.obj)
170
+ except SystemExit:
171
+ # Click raises SystemExit, we want to continue in REPL
172
+ pass
173
+ except Exception as e:
174
+ console.print(f"[red]Error: {e}[/red]")
175
+
176
+ except (EOFError, KeyboardInterrupt):
177
+ console.print("\n[yellow]Goodbye![/yellow]")
178
+ break
179
+
180
+
181
+ def main() -> None:
182
+ """Main entry point."""
183
+ try:
184
+ cli()
185
+ except Exception as e:
186
+ console.print(f"[red]Error: {e}[/red]")
187
+ sys.exit(1)
188
+
189
+
190
+ if __name__ == "__main__":
191
+ main()
@@ -0,0 +1 @@
1
+ """HTTP client modules for Dremio API."""
@@ -0,0 +1,100 @@
1
+ """Authentication handlers for Dremio API."""
2
+
3
+ from typing import Dict, Any, Optional
4
+ import requests
5
+
6
+ from dremio_cli.utils.exceptions import AuthenticationError
7
+
8
+
9
+ def authenticate_with_username_password(
10
+ base_url: str,
11
+ username: str,
12
+ password: str,
13
+ ) -> str:
14
+ """Authenticate with username and password (Dremio Software only).
15
+
16
+ Args:
17
+ base_url: Base URL for Dremio
18
+ username: Username
19
+ password: Password
20
+
21
+ Returns:
22
+ Authentication token
23
+
24
+ Raises:
25
+ AuthenticationError: If authentication fails
26
+ """
27
+ # Use v2 API for login
28
+ login_url = base_url.replace("/api/v3", "/apiv2/login")
29
+
30
+ try:
31
+ response = requests.post(
32
+ login_url,
33
+ json={"userName": username, "password": password},
34
+ headers={"Content-Type": "application/json"},
35
+ timeout=30,
36
+ )
37
+
38
+ if not response.ok:
39
+ raise AuthenticationError(f"Authentication failed: {response.text}")
40
+
41
+ data = response.json()
42
+ token = data.get("token")
43
+
44
+ if not token:
45
+ raise AuthenticationError("No token in authentication response")
46
+
47
+ # Return self-contained token
48
+ return f"_dremio{token}"
49
+
50
+ except requests.RequestException as e:
51
+ raise AuthenticationError(f"Authentication request failed: {e}")
52
+
53
+
54
+ def refresh_oauth_token(
55
+ base_url: str,
56
+ refresh_token: str,
57
+ client_id: Optional[str] = None,
58
+ client_secret: Optional[str] = None,
59
+ ) -> Dict[str, Any]:
60
+ """Refresh OAuth token.
61
+
62
+ Args:
63
+ base_url: Base URL for Dremio
64
+ refresh_token: Refresh token
65
+ client_id: OAuth client ID
66
+ client_secret: OAuth client secret
67
+
68
+ Returns:
69
+ Dictionary with new access_token and refresh_token
70
+
71
+ Raises:
72
+ AuthenticationError: If refresh fails
73
+ """
74
+ oauth_url = f"{base_url}/oauth/token"
75
+
76
+ data = {
77
+ "grant_type": "refresh_token",
78
+ "refresh_token": refresh_token,
79
+ }
80
+
81
+ if client_id:
82
+ data["client_id"] = client_id
83
+ if client_secret:
84
+ data["client_secret"] = client_secret
85
+
86
+ try:
87
+ response = requests.post(
88
+ oauth_url,
89
+ json=data,
90
+ headers={"Content-Type": "application/json"},
91
+ timeout=30,
92
+ )
93
+
94
+ if not response.ok:
95
+ raise AuthenticationError(f"Token refresh failed: {response.text}")
96
+
97
+ return response.json()
98
+
99
+ except requests.RequestException as e:
100
+ raise AuthenticationError(f"Token refresh request failed: {e}")
@@ -0,0 +1,190 @@
1
+ """Base HTTP client for Dremio API."""
2
+
3
+ from typing import Any, Dict, Optional
4
+ from urllib.parse import urljoin
5
+
6
+ import requests
7
+ from requests.adapters import HTTPAdapter
8
+ from urllib3.util.retry import Retry
9
+
10
+ from dremio_cli.utils.exceptions import ApiError, AuthenticationError
11
+
12
+
13
+ class BaseClient:
14
+ """Base HTTP client for Dremio API."""
15
+
16
+ def __init__(
17
+ self,
18
+ base_url: str,
19
+ token: Optional[str] = None,
20
+ timeout: int = 30,
21
+ max_retries: int = 3,
22
+ ):
23
+ """Initialize base client.
24
+
25
+ Args:
26
+ base_url: Base URL for API
27
+ token: Authentication token
28
+ timeout: Request timeout in seconds
29
+ max_retries: Maximum number of retries
30
+ """
31
+ self.base_url = base_url.rstrip("/")
32
+ self.token = token
33
+ self.timeout = timeout
34
+
35
+ # Create session with retry logic
36
+ self.session = requests.Session()
37
+ retry_strategy = Retry(
38
+ total=max_retries,
39
+ backoff_factor=1,
40
+ status_forcelist=[429, 500, 502, 503, 504],
41
+ allowed_methods=["HEAD", "GET", "OPTIONS", "POST", "PUT", "DELETE"],
42
+ )
43
+ adapter = HTTPAdapter(max_retries=retry_strategy)
44
+ self.session.mount("http://", adapter)
45
+ self.session.mount("https://", adapter)
46
+
47
+ def _get_headers(self) -> Dict[str, str]:
48
+ """Get request headers with authentication.
49
+
50
+ Returns:
51
+ Dictionary of headers
52
+ """
53
+ headers = {
54
+ "Content-Type": "application/json",
55
+ "Accept": "application/json",
56
+ }
57
+
58
+ if self.token:
59
+ headers["Authorization"] = f"Bearer {self.token}"
60
+
61
+ return headers
62
+
63
+ def _build_url(self, endpoint: str) -> str:
64
+ """Build full URL from endpoint.
65
+
66
+ Args:
67
+ endpoint: API endpoint path
68
+
69
+ Returns:
70
+ Full URL
71
+ """
72
+ return urljoin(self.base_url + "/", endpoint.lstrip("/"))
73
+
74
+ def _handle_response(self, response: requests.Response) -> Any:
75
+ """Handle API response.
76
+
77
+ Args:
78
+ response: HTTP response
79
+
80
+ Returns:
81
+ Parsed JSON response
82
+
83
+ Raises:
84
+ AuthenticationError: If authentication fails
85
+ ApiError: If API request fails
86
+ """
87
+ if response.status_code == 401:
88
+ raise AuthenticationError("Authentication failed. Check your credentials.")
89
+
90
+ if response.status_code == 403:
91
+ raise ApiError("Access forbidden. Check your permissions.", status_code=403)
92
+
93
+ if response.status_code == 404:
94
+ raise ApiError("Resource not found.", status_code=404)
95
+
96
+ if not response.ok:
97
+ error_msg = f"API request failed with status {response.status_code}"
98
+ try:
99
+ error_data = response.json()
100
+ if "errorMessage" in error_data:
101
+ error_msg = error_data["errorMessage"]
102
+ if "moreInfo" in error_data:
103
+ error_msg += f": {error_data['moreInfo']}"
104
+ except Exception:
105
+ error_msg += f": {response.text}"
106
+
107
+ raise ApiError(error_msg, status_code=response.status_code, response_body=response.text)
108
+
109
+ # Return empty dict for 204 No Content
110
+ if response.status_code == 204:
111
+ return {}
112
+
113
+ try:
114
+ return response.json()
115
+ except Exception:
116
+ return response.text
117
+
118
+ def get(self, endpoint: str, params: Optional[Dict[str, Any]] = None) -> Any:
119
+ """Make GET request.
120
+
121
+ Args:
122
+ endpoint: API endpoint
123
+ params: Query parameters
124
+
125
+ Returns:
126
+ Response data
127
+ """
128
+ url = self._build_url(endpoint)
129
+ response = self.session.get(
130
+ url,
131
+ headers=self._get_headers(),
132
+ params=params,
133
+ timeout=self.timeout,
134
+ )
135
+ return self._handle_response(response)
136
+
137
+ def post(self, endpoint: str, data: Optional[Dict[str, Any]] = None) -> Any:
138
+ """Make POST request.
139
+
140
+ Args:
141
+ endpoint: API endpoint
142
+ data: Request body data
143
+
144
+ Returns:
145
+ Response data
146
+ """
147
+ url = self._build_url(endpoint)
148
+ response = self.session.post(
149
+ url,
150
+ headers=self._get_headers(),
151
+ json=data,
152
+ timeout=self.timeout,
153
+ )
154
+ return self._handle_response(response)
155
+
156
+ def put(self, endpoint: str, data: Optional[Dict[str, Any]] = None) -> Any:
157
+ """Make PUT request.
158
+
159
+ Args:
160
+ endpoint: API endpoint
161
+ data: Request body data
162
+
163
+ Returns:
164
+ Response data
165
+ """
166
+ url = self._build_url(endpoint)
167
+ response = self.session.put(
168
+ url,
169
+ headers=self._get_headers(),
170
+ json=data,
171
+ timeout=self.timeout,
172
+ )
173
+ return self._handle_response(response)
174
+
175
+ def delete(self, endpoint: str) -> Any:
176
+ """Make DELETE request.
177
+
178
+ Args:
179
+ endpoint: API endpoint
180
+
181
+ Returns:
182
+ Response data
183
+ """
184
+ url = self._build_url(endpoint)
185
+ response = self.session.delete(
186
+ url,
187
+ headers=self._get_headers(),
188
+ timeout=self.timeout,
189
+ )
190
+ return self._handle_response(response)