pipen-gcs 0.0.1__tar.gz

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.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright {yyyy} {name of copyright owner}
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,82 @@
1
+ Metadata-Version: 2.1
2
+ Name: pipen-gcs
3
+ Version: 0.0.1
4
+ Summary: A plugin for pipen to handle file metadata in Google Cloud Storage
5
+ License: MIT
6
+ Author: pwwang
7
+ Author-email: 1188067+pwwang@users.noreply.github.com
8
+ Requires-Python: >=3.9,<4.0
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.9
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Requires-Dist: google-cloud-storage (>=2.17.0,<3.0.0)
16
+ Requires-Dist: pipen (>=0.15.0,<0.16.0)
17
+ Description-Content-Type: text/markdown
18
+
19
+ # pipen-gcs
20
+
21
+ A plugin for [pipen][1] to handle files in Google Cloud Storage
22
+
23
+ ## Installation
24
+
25
+ ```bash
26
+ pip install -U pipen-gcs
27
+
28
+ # uninstall to disable
29
+ pip uninstall pipen-gcs
30
+ ```
31
+
32
+ ## Usage
33
+
34
+ ```python
35
+ from pipen import Proc, Pipen
36
+
37
+ class MyProc(Proc):
38
+ input = "infile:file"
39
+ input_data = ["gs://bucket/path/to/file"]
40
+ output = "outfile:file:gs://bucket/path/to/output"
41
+ script = "cat {{infile}} > {{outfile}}"
42
+
43
+ class MyPipen(Pipen):
44
+ starts = MyProc
45
+ # input files/directories will be downloaded to /tmp
46
+ # output files/directories will be generated in /tmp and then uploaded
47
+ # to the cloud storage
48
+ plugin_opts = {"gcs_localize": "/tmp"}
49
+
50
+ if __name__ == "__main__":
51
+ MyPipen().run()
52
+ ```
53
+
54
+ You can also disable localization, then you will have to handle the
55
+ cloud storage files yourself.
56
+
57
+ ```python
58
+ from pipen import Proc, Pipen
59
+
60
+ class MyProc(Proc):
61
+ input = "infile:file"
62
+ input_data = ["gs://bucket/path/to/file"]
63
+ output = "outfile:file:gs://bucket/path/to/output"
64
+ script = "gsutil cp {{infile}} {{outfile}}"
65
+
66
+ class MyPipen(Pipen):
67
+ starts = MyProc
68
+ plugin_opts = {"gcs_localize": False}
69
+
70
+ if __name__ == "__main__":
71
+ MyPipen().run()
72
+ ```
73
+
74
+ ## Configuration
75
+
76
+ - `gcs_localize`: The directory to localize the cloud storage files. If
77
+ set to `False`, the files will not be localized. Default is `False`.
78
+ - `gcs_credentials`: The path to the Google Cloud Service Account
79
+ credentials file.
80
+
81
+ [1]: https://github.com/pwwang/pipen
82
+
@@ -0,0 +1,63 @@
1
+ # pipen-gcs
2
+
3
+ A plugin for [pipen][1] to handle files in Google Cloud Storage
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pip install -U pipen-gcs
9
+
10
+ # uninstall to disable
11
+ pip uninstall pipen-gcs
12
+ ```
13
+
14
+ ## Usage
15
+
16
+ ```python
17
+ from pipen import Proc, Pipen
18
+
19
+ class MyProc(Proc):
20
+ input = "infile:file"
21
+ input_data = ["gs://bucket/path/to/file"]
22
+ output = "outfile:file:gs://bucket/path/to/output"
23
+ script = "cat {{infile}} > {{outfile}}"
24
+
25
+ class MyPipen(Pipen):
26
+ starts = MyProc
27
+ # input files/directories will be downloaded to /tmp
28
+ # output files/directories will be generated in /tmp and then uploaded
29
+ # to the cloud storage
30
+ plugin_opts = {"gcs_localize": "/tmp"}
31
+
32
+ if __name__ == "__main__":
33
+ MyPipen().run()
34
+ ```
35
+
36
+ You can also disable localization, then you will have to handle the
37
+ cloud storage files yourself.
38
+
39
+ ```python
40
+ from pipen import Proc, Pipen
41
+
42
+ class MyProc(Proc):
43
+ input = "infile:file"
44
+ input_data = ["gs://bucket/path/to/file"]
45
+ output = "outfile:file:gs://bucket/path/to/output"
46
+ script = "gsutil cp {{infile}} {{outfile}}"
47
+
48
+ class MyPipen(Pipen):
49
+ starts = MyProc
50
+ plugin_opts = {"gcs_localize": False}
51
+
52
+ if __name__ == "__main__":
53
+ MyPipen().run()
54
+ ```
55
+
56
+ ## Configuration
57
+
58
+ - `gcs_localize`: The directory to localize the cloud storage files. If
59
+ set to `False`, the files will not be localized. Default is `False`.
60
+ - `gcs_credentials`: The path to the Google Cloud Service Account
61
+ credentials file.
62
+
63
+ [1]: https://github.com/pwwang/pipen
@@ -0,0 +1,191 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+
5
+ from typing import TYPE_CHECKING
6
+ from pathlib import Path
7
+
8
+ from pipen import plugin
9
+ from pipen.defaults import ProcOutputType
10
+ from pipen.utils import get_logger
11
+ from google.cloud import storage
12
+
13
+ from .utils import (
14
+ parse_gcs_uri,
15
+ get_gs_type,
16
+ update_plugin_data,
17
+ get_plugin_data,
18
+ get_gs_mtime,
19
+ download_gs_file,
20
+ download_gs_dir,
21
+ clear_gs_file,
22
+ clear_gs_dir,
23
+ gs_dir_exists,
24
+ gs_file_exists,
25
+ upload_gs_file,
26
+ upload_gs_dir,
27
+ create_gs_dir,
28
+ InvalidGoogleStorageURIError,
29
+ )
30
+
31
+ if TYPE_CHECKING:
32
+ from pipen import Pipen
33
+
34
+ __version__ = "0.0.1"
35
+ logger = get_logger("gcs")
36
+
37
+
38
+ class PipenGcsPlugin:
39
+ """A plugin for pipen to handle file metadata in Google Cloud Storage
40
+
41
+ Configurations:
42
+ gs_localize: False or a directory to download files to and upload back
43
+ the output files. If False, the plugin will not download or upload
44
+ files. The job script should handle the files in the cloud.
45
+ gs_credentials: The path to the Google Cloud Storage credentials file.
46
+ """
47
+
48
+ version = __version__
49
+ name = "gcs"
50
+
51
+ def __init__(self):
52
+ self.gclient = None # pragma: no cover
53
+
54
+ @plugin.impl
55
+ async def on_init(self, pipen: Pipen) -> None:
56
+ """Initialize the plugin"""
57
+ # Whether to download files to local and upload the output files back
58
+ pipen.config.plugin_opts.setdefault("gcs_localize", False)
59
+ # Google Cloud Storage credentials, otherwise you need to login manually
60
+ pipen.config.plugin_opts.setdefault("gcs_credentials", None)
61
+
62
+ @plugin.impl
63
+ async def on_start(self, pipen: Pipen) -> None:
64
+ """Login to Google Cloud Storage using the credentials if provided"""
65
+ logger.setLevel("INFO")
66
+ plugin_opts = pipen.config.plugin_opts or {}
67
+ if plugin_opts.get("gcs_credentials"):
68
+ os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = plugin_opts[
69
+ "gcs_credentials"
70
+ ]
71
+ self.gclient = storage.Client()
72
+
73
+ @plugin.impl
74
+ def norm_inpath(self, job, inpath, is_dir):
75
+ if not isinstance(inpath, str) or not inpath.startswith(
76
+ "gs://"
77
+ ): # pragma: no cover
78
+ # let next plugin handle it
79
+ return None
80
+
81
+ plugin_opts = job.proc.plugin_opts or {}
82
+ gs_localize = plugin_opts.get("gs_localize", False)
83
+
84
+ gstype = get_gs_type(self.gclient, inpath)
85
+ if gstype == "none":
86
+ raise InvalidGoogleStorageURIError(
87
+ f"[{job.proc.name}] Input path not exists: {inpath}"
88
+ )
89
+ if gstype == "bucket":
90
+ raise InvalidGoogleStorageURIError(
91
+ f"[{job.proc.name}] Input path expected instead of a bare bucket: "
92
+ f"{inpath}"
93
+ )
94
+
95
+ if not gs_localize:
96
+ return inpath
97
+
98
+ gs_localize = Path(gs_localize)
99
+ # Download the file to local
100
+ bucket, path = parse_gcs_uri(inpath)
101
+ localpath = gs_localize.joinpath(bucket, path)
102
+ job.log("info", f"Localizing {inpath} ...", logger=logger)
103
+ if is_dir:
104
+ download_gs_dir(self.gclient, inpath, localpath)
105
+ else:
106
+ download_gs_file(self.gclient, inpath, localpath)
107
+
108
+ return localpath
109
+
110
+ @plugin.impl
111
+ def norm_outpath(self, job, outpath, is_dir):
112
+ if not isinstance(outpath, str) or not outpath.startswith(
113
+ "gs://"
114
+ ): # pragma: no cover
115
+ # let next plugin handle it
116
+ return None
117
+
118
+ plugin_opts = job.proc.plugin_opts or {}
119
+ gs_localize = plugin_opts.get("gs_localize", False)
120
+
121
+ gstype = get_gs_type(self.gclient, outpath)
122
+ if gstype == "bucket":
123
+ raise InvalidGoogleStorageURIError(
124
+ f"[{job.proc.name}] Output path expected instead of a bare bucket: "
125
+ f"{outpath}"
126
+ )
127
+
128
+ if not gs_localize:
129
+ return outpath
130
+
131
+ gs_localize = Path(gs_localize)
132
+ bucket, path = parse_gcs_uri(outpath)
133
+ localpath = gs_localize.joinpath(bucket, path)
134
+ if is_dir:
135
+ outpath = outpath.rstrip("/") + "/"
136
+ create_gs_dir(self.gclient, outpath)
137
+ localpath.mkdir(parents=True, exist_ok=True)
138
+ else:
139
+ localpath.parent.mkdir(parents=True, exist_ok=True)
140
+
141
+ # save the original output with gs://
142
+ ret = str(localpath)
143
+ update_plugin_data(job, ret, outpath)
144
+
145
+ return ret
146
+
147
+ @plugin.impl
148
+ def get_mtime(self, job, path, dirsig):
149
+ if not isinstance(path, str) or not path.startswith(
150
+ "gs://"
151
+ ): # pragma: no cover
152
+ return None
153
+
154
+ return get_gs_mtime(self.gclient, path, dirsig)
155
+
156
+ @plugin.impl
157
+ async def clear_path(self, job, path, is_dir):
158
+ if not isinstance(path, str) or not path.startswith(
159
+ "gs://"
160
+ ): # pragma: no cover
161
+ return None
162
+
163
+ if is_dir:
164
+ return clear_gs_dir(self.gclient, path)
165
+
166
+ return clear_gs_file(self.gclient, path)
167
+
168
+ @plugin.impl
169
+ async def output_exists(self, job, path, is_dir):
170
+ if not isinstance(path, str) or not path.startswith(
171
+ "gs://"
172
+ ): # pragma: no cover
173
+ return None
174
+
175
+ if is_dir:
176
+ return gs_dir_exists(self.gclient, path)
177
+
178
+ return gs_file_exists(self.gclient, path)
179
+
180
+ @plugin.impl
181
+ async def on_job_succeeded(self, job):
182
+ for key, value in job.output.items():
183
+ gspath = get_plugin_data(job, value)
184
+ if gspath is None:
185
+ continue
186
+
187
+ job.log("info", f"Uploading output '{key}' to {gspath} ...", logger=logger)
188
+ if job._output_types[key] == ProcOutputType.FILE:
189
+ upload_gs_file(self.gclient, value, gspath)
190
+ else:
191
+ upload_gs_dir(self.gclient, value, gspath)
@@ -0,0 +1,313 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from pathlib import Path
5
+ from typing import Any, TYPE_CHECKING
6
+
7
+ from pipen.utils import mark, get_marked
8
+ from google.cloud import storage
9
+
10
+ if TYPE_CHECKING:
11
+ from pipen import Job
12
+
13
+
14
+ class InvalidGoogleStorageURIError(Exception):
15
+ """Invalid Google Cloud Storage URI"""
16
+
17
+
18
+ def _mtime(blob: storage.Blob) -> float:
19
+ """Get the modification time of a blob
20
+
21
+ Args:
22
+ blob (storage.Blob): The blob to get the modification time
23
+
24
+ Returns:
25
+ float: The modification time
26
+ """
27
+ if blob.metadata and "mtime" in blob.metadata:
28
+ return float(blob.metadata["mtime"])
29
+ return blob.updated.timestamp() if blob.updated else 0.0
30
+
31
+
32
+ def parse_gcs_uri(uri: str) -> tuple[str, str]:
33
+ """Parse a Google Cloud Storage URI
34
+
35
+ Example:
36
+ >>> parse_gcs_uri("gs://bucket/path/to/file")
37
+ ("bucket", "path/to/file")
38
+ >>> parse_gcs_uri("gs://bucket/path/to/dir/")
39
+ ("bucket", "path/to/dir/")
40
+ >>> parse_gcs_uri("gs://bucket/")
41
+ ("bucket", "")
42
+
43
+ Args:
44
+ uri (str): The URI to parse
45
+
46
+ Returns:
47
+ tuple[str, str]: The bucket and the path
48
+ """
49
+ if uri.startswith("gs://"):
50
+ uri = uri[5:]
51
+ bucket, *path = uri.split("/")
52
+ return bucket, "/".join(path)
53
+
54
+
55
+ def get_gs_type(client: storage.Client, gs_uri: str) -> str:
56
+ """Get the type of a file/dir in Google Cloud Storage
57
+
58
+ Example:
59
+ >>> get_gs_type(client, "gs://bucket/")
60
+ "bucket"
61
+ >>> get_gs_type(client, "gs://bucket/path/to/dir/")
62
+ "dir"
63
+ >>> get_gs_type(client, "gs://bucket/path/to/file")
64
+ "file"
65
+ >>> get_gs_type(client, "gs://bucket/not/exist")
66
+ "none"
67
+
68
+ Args:
69
+ client (storage.Client): The Google Cloud Storage client
70
+ gs_uri (str): The URI of the file in Google Cloud Storage
71
+
72
+ Returns:
73
+ str: The type, either bucket, dir, file or none (not exists)
74
+ """
75
+ bucket, path = parse_gcs_uri(gs_uri)
76
+ if not path:
77
+ return "bucket"
78
+
79
+ bucket = client.get_bucket(bucket)
80
+ blob = bucket.get_blob(path)
81
+ if blob:
82
+ return "dir" if blob.name.endswith("/") else "file"
83
+
84
+ path = path.rstrip("/") + "/"
85
+ blobs = list(bucket.list_blobs(prefix=path, max_results=1))
86
+ if blobs:
87
+ return "dir"
88
+
89
+ return "none"
90
+
91
+
92
+ def update_plugin_data(job: Job, key: str, value: Any) -> None:
93
+ """Update the plugin data for a job
94
+
95
+ Args:
96
+ job (Job): The job to update
97
+ key (str): The key to update
98
+ value (Any): The value to update
99
+ """
100
+ plugin_data = get_marked(job.proc.__class__, "plugin_data", {})
101
+ plugin_data.setdefault("gcs", {})
102
+ plugin_data["gcs"][key] = value
103
+ mark(plugin_data=plugin_data)(job.proc.__class__)
104
+
105
+
106
+ def get_plugin_data(job: Job, key: str, default: Any = None) -> Any:
107
+ """Get the plugin data for a job
108
+
109
+ Args:
110
+ job (Job): The job to get the data from
111
+ key (str): The key to get
112
+ default (Any, optional): The default value to return. Defaults to None.
113
+
114
+ Returns:
115
+ Any: The value of the key
116
+ """
117
+ plugin_data = get_marked(job.proc.__class__, "plugin_data", {})
118
+ return plugin_data.get("gcs", {}).get(key, default)
119
+
120
+
121
+ def download_gs_file(
122
+ client: storage.Client,
123
+ gs_uri: str,
124
+ localpath: str | Path,
125
+ ) -> None:
126
+ """Download a file from Google Cloud Storage
127
+
128
+ Args:
129
+ client (storage.Client): The Google Cloud Storage client
130
+ gs_uri (str): The URI of the file in Google Cloud Storage
131
+ localpath (str | Path): The local path to download
132
+ """
133
+ bucket, path = parse_gcs_uri(gs_uri)
134
+ blob = client.get_bucket(bucket).get_blob(path)
135
+ Path(localpath).parent.mkdir(parents=True, exist_ok=True)
136
+ blob.download_to_filename(str(localpath))
137
+ mtime = _mtime(blob)
138
+ os.utime(localpath, (mtime, mtime))
139
+
140
+
141
+ def download_gs_dir(
142
+ client: storage.Client,
143
+ gs_uri: str,
144
+ localpath: str | Path,
145
+ ) -> None:
146
+ """Download a file from Google Cloud Storage
147
+
148
+ Args:
149
+ client (storage.Client): The Google Cloud Storage client
150
+ gs_uri (str): The URI of the file in Google Cloud Storage
151
+ localpath (str | Path): The local path to download
152
+ """
153
+ bucket, path = parse_gcs_uri(gs_uri)
154
+ path = path.rstrip("/") + "/"
155
+ bucket = client.get_bucket(bucket)
156
+ blobs = bucket.list_blobs(prefix=path)
157
+
158
+ for blob in reversed(list(blobs)):
159
+ localfile = Path(localpath).joinpath(blob.name[len(path):])
160
+ if blob.name.endswith("/"):
161
+ localfile.mkdir(parents=True, exist_ok=True)
162
+ else:
163
+ localfile.parent.mkdir(parents=True, exist_ok=True)
164
+ blob.download_to_filename(localfile)
165
+
166
+ mtime = _mtime(blob)
167
+ os.utime(localfile, (mtime, mtime))
168
+
169
+
170
+ def get_gs_mtime(client: storage.Client, gs_uri: str, dir_depth: int) -> float:
171
+ """Get the modification time of a file/dir in Google Cloud Storage
172
+
173
+ Args:
174
+ client (storage.Client): The Google Cloud Storage client
175
+ gs_uri (str): The URI of the file in Google Cloud Storage
176
+ dir_depth (int): The depth of the directory to check
177
+
178
+ Returns:
179
+ float: The modification time
180
+ """
181
+ gstype = get_gs_type(client, gs_uri) # file or dir, check when pipeline starts
182
+ bucket, path = parse_gcs_uri(gs_uri)
183
+ bucket = client.get_bucket(bucket)
184
+ blob = bucket.get_blob(path)
185
+ if gstype == "file" or dir_depth == 0:
186
+ return _mtime(blob)
187
+
188
+ path = path.rstrip("/") + "/"
189
+ blobs = bucket.list_blobs(prefix=path)
190
+ return max(
191
+ (
192
+ _mtime(blob)
193
+ for blob in blobs
194
+ if blob.name.rstrip("/")[len(path):].count("/") < dir_depth
195
+ ),
196
+ default=0.0,
197
+ )
198
+
199
+
200
+ def clear_gs_file(client: storage.Client, gs_uri: str) -> bool:
201
+ """Clear a file from Google Cloud Storage
202
+
203
+ Args:
204
+ client (storage.Client): The Google Cloud Storage client
205
+ gs_uri (str): The URI of the file in Google Cloud Storage
206
+ """
207
+ bucket, path = parse_gcs_uri(gs_uri)
208
+ blob = client.get_bucket(bucket).get_blob(path)
209
+ if blob:
210
+ blob.delete()
211
+ return True
212
+
213
+
214
+ def clear_gs_dir(client: storage.Client, gs_uri: str) -> bool:
215
+ """Clear a directory from Google Cloud Storage
216
+
217
+ Args:
218
+ client (storage.Client): The Google Cloud Storage client
219
+ gs_uri (str): The URI of the directory in Google Cloud Storage
220
+ """
221
+ bucket, path = parse_gcs_uri(gs_uri)
222
+ path = path.rstrip("/") + "/"
223
+ bucket = client.get_bucket(bucket)
224
+ blobs = bucket.list_blobs(prefix=path)
225
+ # reversed to delete files first
226
+ for blob in reversed(list(blobs)):
227
+ blob.delete()
228
+ return True
229
+
230
+
231
+ def gs_dir_exists(client: storage.Client, gs_uri: str) -> bool:
232
+ """Check if a directory exists in Google Cloud Storage
233
+
234
+ Args:
235
+ client (storage.Client): The Google Cloud Storage client
236
+ gs_uri (str): The URI of the directory in Google Cloud Storage
237
+
238
+ Returns:
239
+ bool: True if the directory exists
240
+ """
241
+ gstype = get_gs_type(client, gs_uri)
242
+ return gstype == "dir"
243
+
244
+
245
+ def gs_file_exists(client: storage.Client, gs_uri: str) -> bool:
246
+ """Check if a file exists in Google Cloud Storage
247
+
248
+ Args:
249
+ client (storage.Client): The Google Cloud Storage client
250
+ gs_uri (str): The URI of the file in Google Cloud Storage
251
+
252
+ Returns:
253
+ bool: True if the file exists
254
+ """
255
+ gstype = get_gs_type(client, gs_uri)
256
+ return gstype == "file"
257
+
258
+
259
+ def upload_gs_file(
260
+ client: storage.Client,
261
+ localpath: str | Path,
262
+ gs_uri: str,
263
+ ) -> None:
264
+ """Upload a file to Google Cloud Storage
265
+
266
+ Args:
267
+ client (storage.Client): The Google Cloud Storage client
268
+ localpath (str | Path): The local path to upload
269
+ gs_uri (str): The URI of the file in Google Cloud Storage
270
+ """
271
+ bucket, path = parse_gcs_uri(gs_uri)
272
+ blob = client.get_bucket(bucket).blob(path)
273
+ blob.metadata = {"mtime": Path(localpath).stat().st_mtime}
274
+ blob.upload_from_filename(str(localpath))
275
+
276
+
277
+ def upload_gs_dir(
278
+ client: storage.Client,
279
+ localpath: str | Path,
280
+ gs_uri: str,
281
+ ) -> None:
282
+ """Upload a directory to Google Cloud Storage
283
+
284
+ Args:
285
+ client (storage.Client): The Google Cloud Storage client
286
+ localpath (str | Path): The local path to upload
287
+ gs_uri (str): The URI of the directory in Google Cloud Storage
288
+ """
289
+ bucket, path = parse_gcs_uri(gs_uri)
290
+ path = path.rstrip("/") + "/"
291
+ bucket = client.get_bucket(bucket)
292
+ for localfile in Path(localpath).rglob("*"):
293
+ if localfile.is_dir():
294
+ continue
295
+ blob = bucket.blob(path + str(localfile.relative_to(localpath)))
296
+ blob.metadata = {"mtime": localfile.stat().st_mtime}
297
+ blob.upload_from_filename(str(localfile))
298
+
299
+
300
+ def create_gs_dir(client: storage.Client, gs_uri: str) -> None:
301
+ """Create a directory in Google Cloud Storage
302
+
303
+ Args:
304
+ client (storage.Client): The Google Cloud Storage client
305
+ gs_uri (str): The URI of the directory in Google Cloud Storage
306
+ """
307
+ gstype = get_gs_type(client, gs_uri)
308
+ if gstype == "dir":
309
+ return
310
+ bucket, path = parse_gcs_uri(gs_uri)
311
+ path = path.rstrip("/") + "/"
312
+ blob = client.get_bucket(bucket).blob(path)
313
+ blob.upload_from_string("", content_type="application/x-directory")
@@ -0,0 +1,38 @@
1
+ [tool.poetry]
2
+ name = "pipen-gcs"
3
+ version = "0.0.1"
4
+ description = "A plugin for pipen to handle file metadata in Google Cloud Storage"
5
+ authors = ["pwwang <1188067+pwwang@users.noreply.github.com>"]
6
+ license = "MIT"
7
+ readme = "README.md"
8
+
9
+ [tool.poetry.build]
10
+ generate-setup-file = true
11
+
12
+ [tool.poetry.dependencies]
13
+ python = "^3.9"
14
+ pipen = "^0.15.0"
15
+ google-cloud-storage = "^2.17.0"
16
+
17
+ [tool.poetry.plugins.pipen]
18
+ gcs = "pipen_gcs:PipenGcsPlugin"
19
+
20
+ [tool.poetry.group.dev.dependencies]
21
+ python-dotenv = "^1.0.1"
22
+ pytest = "^8"
23
+ pytest-cov = "^5.0.0"
24
+ pytest-forked = "^1.6.0"
25
+ pytest-xdist = "^3"
26
+
27
+ [tool.poetry.group.extra.dependencies]
28
+ ipykernel = "^6.29.5"
29
+
30
+ [build-system]
31
+ requires = ["poetry-core"]
32
+ build-backend = "poetry.core.masonry.api"
33
+
34
+ [tool.pytest.ini_options]
35
+ addopts = "-vv -n 1 --cov-config=.coveragerc --cov=pipen_gcs --cov-report xml:.coverage.xml --cov-report term-missing"
36
+ console_output_style = "progress"
37
+ junit_family = "xunit1"
38
+ filterwarnings = []
@@ -0,0 +1,34 @@
1
+ # -*- coding: utf-8 -*-
2
+ from setuptools import setup
3
+
4
+ packages = \
5
+ ['pipen_gcs']
6
+
7
+ package_data = \
8
+ {'': ['*']}
9
+
10
+ install_requires = \
11
+ ['google-cloud-storage>=2.17.0,<3.0.0', 'pipen>=0.15.0,<0.16.0']
12
+
13
+ entry_points = \
14
+ {'pipen': ['gcs = pipen_gcs:PipenGcsPlugin']}
15
+
16
+ setup_kwargs = {
17
+ 'name': 'pipen-gcs',
18
+ 'version': '0.0.1',
19
+ 'description': 'A plugin for pipen to handle file metadata in Google Cloud Storage',
20
+ 'long_description': '# pipen-gcs\n\nA plugin for [pipen][1] to handle files in Google Cloud Storage\n\n## Installation\n\n```bash\npip install -U pipen-gcs\n\n# uninstall to disable\npip uninstall pipen-gcs\n```\n\n## Usage\n\n```python\nfrom pipen import Proc, Pipen\n\nclass MyProc(Proc):\n input = "infile:file"\n input_data = ["gs://bucket/path/to/file"]\n output = "outfile:file:gs://bucket/path/to/output"\n script = "cat {{infile}} > {{outfile}}"\n\nclass MyPipen(Pipen):\n starts = MyProc\n # input files/directories will be downloaded to /tmp\n # output files/directories will be generated in /tmp and then uploaded\n # to the cloud storage\n plugin_opts = {"gcs_localize": "/tmp"}\n\nif __name__ == "__main__":\n MyPipen().run()\n```\n\nYou can also disable localization, then you will have to handle the\ncloud storage files yourself.\n\n```python\nfrom pipen import Proc, Pipen\n\nclass MyProc(Proc):\n input = "infile:file"\n input_data = ["gs://bucket/path/to/file"]\n output = "outfile:file:gs://bucket/path/to/output"\n script = "gsutil cp {{infile}} {{outfile}}"\n\nclass MyPipen(Pipen):\n starts = MyProc\n plugin_opts = {"gcs_localize": False}\n\nif __name__ == "__main__":\n MyPipen().run()\n```\n\n## Configuration\n\n- `gcs_localize`: The directory to localize the cloud storage files. If\n set to `False`, the files will not be localized. Default is `False`.\n- `gcs_credentials`: The path to the Google Cloud Service Account\n credentials file.\n\n[1]: https://github.com/pwwang/pipen\n',
21
+ 'author': 'pwwang',
22
+ 'author_email': '1188067+pwwang@users.noreply.github.com',
23
+ 'maintainer': 'None',
24
+ 'maintainer_email': 'None',
25
+ 'url': 'None',
26
+ 'packages': packages,
27
+ 'package_data': package_data,
28
+ 'install_requires': install_requires,
29
+ 'entry_points': entry_points,
30
+ 'python_requires': '>=3.9,<4.0',
31
+ }
32
+
33
+
34
+ setup(**setup_kwargs)