addftool 0.0.1__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.
addftool/__init__.py ADDED
File without changes
addftool/blob.py ADDED
@@ -0,0 +1,192 @@
1
+ import argparse
2
+ import requests
3
+ import subprocess
4
+ import os
5
+ import json
6
+ import yaml
7
+ from cryptography.fernet import Fernet
8
+
9
+
10
+ def add_api(parser):
11
+ parser.add_argument("-k", "--key", help="f key", required=True)
12
+ parser.add_argument("-a", "--api", help="api url")
13
+ parser.add_argument("-n", "--name", help="name")
14
+ parser.add_argument("-c", "--container", help="container")
15
+
16
+
17
+ def get_ubuntu_version():
18
+ with open("/etc/os-release") as f:
19
+ for line in f:
20
+ if line.startswith("VERSION_ID="):
21
+ version = line.split("=")[1].strip().strip('"')
22
+ return version
23
+ return "22.04"
24
+
25
+
26
+ def execute_command(command, to_file=None):
27
+ if to_file is not None:
28
+ to_file.write(command + "\n")
29
+ return None
30
+ else:
31
+ print("Execute command: ", command)
32
+ result = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE).stdout.read().decode()
33
+ print("Result: ", result)
34
+ return result
35
+
36
+
37
+ def create_dir_for_current_user(dir_path, sudo=False):
38
+ command = f"mkdir -p {dir_path}"
39
+ if sudo:
40
+ command = "sudo " + command
41
+ execute_command(command)
42
+ command = f"chown $USER {dir_path}"
43
+ if sudo:
44
+ command = "sudo " + command
45
+ execute_command(command)
46
+
47
+
48
+ def install_main(args):
49
+ # generate install script
50
+ if args.output_script is not None:
51
+ script_writer = open(args.output_script, "w")
52
+ else:
53
+ script_writer = None
54
+
55
+ # get ubuntu version
56
+ ubuntu_version = get_ubuntu_version()
57
+
58
+ # check if has root permission
59
+ # if has root permission, run install script
60
+ # else, print install script
61
+
62
+ print("Get ubuntu version: ", ubuntu_version)
63
+ command = f"wget https://packages.microsoft.com/config/ubuntu/{ubuntu_version}/packages-microsoft-prod.deb -O /tmp/packages-microsoft-prod.deb"
64
+ print("Install packages-microsoft-prod.deb")
65
+ execute_command(command, script_writer)
66
+ command = "dpkg -i /tmp/packages-microsoft-prod.deb"
67
+ if args.sudo:
68
+ command = "sudo " + command
69
+ execute_command(command, script_writer)
70
+
71
+ command = "apt-get update"
72
+ if args.sudo:
73
+ command = "sudo " + command
74
+ execute_command(command, script_writer)
75
+
76
+ command = "apt-get install fuse3 blobfuse2 -y"
77
+ if args.sudo:
78
+ command = "sudo " + command
79
+ execute_command(command, script_writer)
80
+
81
+
82
+ def mount_main(args):
83
+ sas_token = get_token(args, info=True)
84
+
85
+ template = {
86
+ 'logging': {'type': 'syslog', 'level': 'log_debug'},
87
+ 'components': ['libfuse', 'file_cache', 'attr_cache', 'azstorage'],
88
+ 'libfuse': {'attribute-expiration-sec': 120, 'entry-expiration-sec': 120, 'negative-entry-expiration-sec': 240},
89
+ 'file_cache': {'path': '', 'timeout-sec': 120, 'max-size-mb': 40960},
90
+ 'attr_cache': {'timeout-sec': 7200},
91
+ 'azstorage': {
92
+ 'type': 'block',
93
+ 'endpoint': '',
94
+ 'account-name': '',
95
+ 'mode': 'sas',
96
+ 'sas': '',
97
+ 'container': ''},
98
+ }
99
+
100
+ if args.template is not None:
101
+ with open(args.template, 'r') as stream:
102
+ try:
103
+ template = yaml.safe_load(stream)
104
+ except yaml.YAMLError as exc:
105
+ print(exc)
106
+
107
+ template['file_cache']['path'] = args.buffer
108
+
109
+ template['azstorage']['sas'] = sas_token
110
+ template['azstorage']['endpoint'] = "https://%s.blob.core.windows.net" % args.name
111
+ template['azstorage']['account-name'] = args.name
112
+ template['azstorage']['container'] = args.container
113
+
114
+ create_dir_for_current_user(args.buffer, sudo=args.sudo)
115
+ create_dir_for_current_user(args.mount, sudo=args.sudo)
116
+
117
+ # write config file into /tmp/config.yaml
118
+
119
+ temp_config = "/tmp/config.yaml"
120
+ with open(temp_config, 'w') as stream:
121
+ yaml.dump(template, stream)
122
+
123
+ command = f"blobfuse2 mount {args.mount} --config-file={temp_config}"
124
+ execute_command(command)
125
+
126
+
127
+ def get_token(args, info=False):
128
+ api_url = args.api
129
+
130
+ f = Fernet(args.key.encode())
131
+
132
+ an = f.encrypt(args.name.encode()).decode()
133
+ cn = f.encrypt(args.container.encode()).decode()
134
+
135
+ if info:
136
+ print("Get token from: ", api_url)
137
+ print("Name: ", an)
138
+ print("Container: ", cn)
139
+
140
+ params = {
141
+ "an": an,
142
+ "cn": cn,
143
+ }
144
+ response = requests.get(api_url, params=params)
145
+ if response.status_code == 200:
146
+ data = json.loads(response.text)
147
+ token = f.decrypt(data["sas"].encode()).decode()
148
+ if token.startswith('"'):
149
+ token = token[1:]
150
+ if token.endswith('"'):
151
+ token = token[:-1]
152
+ if token.startswith("?"):
153
+ return token
154
+ else:
155
+ return "?" + token
156
+ else:
157
+ return f"Error: {response.status_code}"
158
+
159
+
160
+ def main():
161
+ # exmaple usage: addfblob install
162
+ # exmaple usage: addfblob mount -k <key> -a <api> -b <buffer> -m <mount_dir>
163
+ # exmaple usage: addfblob token -k <key> -a <api>
164
+ parser = argparse.ArgumentParser(description="Addf's tool")
165
+
166
+ subparsers = parser.add_subparsers(dest='command', help='Sub-command help')
167
+ install_parser = subparsers.add_parser('install', help='Install help')
168
+ install_parser.add_argument("-o", "--output_script", help="output script", default=None)
169
+ install_parser.add_argument("--sudo", help="sudo", action="store_true")
170
+
171
+ mount_parser = subparsers.add_parser('mount', help='Mount help')
172
+ add_api(mount_parser)
173
+ mount_parser.add_argument("-b", "--buffer", help="buffer dir", required=True)
174
+ mount_parser.add_argument("-m", "--mount", help="mount dir", required=True)
175
+ mount_parser.add_argument("-t", "--template", help="yaml template file", default=None)
176
+ mount_parser.add_argument("--sudo", help="sudo", action="store_true")
177
+
178
+ token_parser = subparsers.add_parser('token', help='Token help')
179
+ add_api(token_parser)
180
+
181
+ args = parser.parse_args()
182
+
183
+ if args.command == 'install':
184
+ install_main(args)
185
+ elif args.command == 'mount':
186
+ mount_main(args)
187
+ elif args.command == 'token':
188
+ print(get_token(args, info=False))
189
+
190
+
191
+ if __name__ == "__main__":
192
+ main()
addftool/util.py ADDED
@@ -0,0 +1,32 @@
1
+ def rangeexpand(txt):
2
+ lst = []
3
+ for r in txt.split(','):
4
+ if '-' in r[1:]:
5
+ r0, r1 = r[1:].split('-', 1)
6
+ r1 = r1.strip()
7
+ lst += range(int(r[0] + r0), int(r1) + 1)
8
+ elif not r.strip():
9
+ continue
10
+ else:
11
+ lst.append(int(r.strip()))
12
+ return lst
13
+
14
+
15
+ def test_rangeexpand():
16
+ import pytest
17
+
18
+ assert rangeexpand('1, 3-5, 7') == [1, 3, 4, 5, 7]
19
+ assert rangeexpand('1, 3-5, 7, 10-12') == [1, 3, 4, 5, 7, 10, 11, 12]
20
+ assert rangeexpand('1-5') == [1, 2, 3, 4, 5]
21
+ assert rangeexpand('1-5, 7-10') == [1, 2, 3, 4, 5, 7, 8, 9, 10]
22
+ assert rangeexpand('') == []
23
+ assert rangeexpand('1') == [1]
24
+ assert rangeexpand('1-1') == [1]
25
+ assert rangeexpand('1-1, 3-3, 5-5') == [1, 3, 5]
26
+ assert rangeexpand('1-1, 3-3, 5-5, 7-7') == [1, 3, 5, 7]
27
+
28
+ with pytest.raises(ValueError):
29
+ rangeexpand('1-2-3')
30
+
31
+ with pytest.raises(ValueError):
32
+ rangeexpand('1 7-9')
@@ -0,0 +1,19 @@
1
+ Copyright (c) 2018 The Python Packaging Authority
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all
11
+ copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ SOFTWARE.
@@ -0,0 +1,8 @@
1
+ Metadata-Version: 2.1
2
+ Name: addftool
3
+ Version: 0.0.1
4
+ License-File: LICENSE
5
+ Requires-Dist: cryptography
6
+ Requires-Dist: requests
7
+ Requires-Dist: PyYAML
8
+
@@ -0,0 +1,9 @@
1
+ addftool/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ addftool/blob.py,sha256=d36wu7acIyfF6mcm2iQqVDZ-kg1cvDr3rSFCyPQpdpA,6175
3
+ addftool/util.py,sha256=gx-pqNJk31tmWtRJvZrIkI15ER7QZg9FtaM_OyP0JqU,975
4
+ addftool-0.0.1.dist-info/LICENSE,sha256=7EI8xVBu6h_7_JlVw-yPhhOZlpY9hP8wal7kHtqKT_E,1074
5
+ addftool-0.0.1.dist-info/METADATA,sha256=RoIRgv0J85qVBp0-OXQC1lRsnBDZE4ecgnyXUJsJ93A,149
6
+ addftool-0.0.1.dist-info/WHEEL,sha256=cVxcB9AmuTcXqmwrtPhNK88dr7IR_b6qagTj0UvIEbY,91
7
+ addftool-0.0.1.dist-info/entry_points.txt,sha256=H3Z3iWsLB1CFdckedIA652_3tWaNS5Rl7fFWgFaFRIc,48
8
+ addftool-0.0.1.dist-info/top_level.txt,sha256=jqj56-plrBbyzY0tIxB6wPzjAA8kte4hUlajyyQygN4,9
9
+ addftool-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (74.1.2)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ addfblob = addftool.blob:main
@@ -0,0 +1 @@
1
+ addftool