Skip to content

Commit 713ae31

Browse files
committed
Kuiper 2.0.0
1 parent 39a60e8 commit 713ae31

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

44 files changed

+3850
-37
lines changed

Kuiper-update.py

Lines changed: 368 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,368 @@
1+
2+
3+
4+
import zipfile
5+
import sys
6+
import os
7+
import yaml
8+
import urllib
9+
import json
10+
import subprocess
11+
import time
12+
from datetime import datetime
13+
import argparse
14+
import signal
15+
16+
class Kuiper_Update:
17+
18+
def __init__(self, args):
19+
self.args = args
20+
# =================== get configuration
21+
self.y = yaml.load( open( 'configuration.yaml' , 'r' ) , Loader=yaml.FullLoader )
22+
self.kuiper_update_log_file = self.y['Logs']['log_folder'] + self.y['Logs']['update_log']
23+
self.release_url = self.y['Git']['git_url_release']
24+
self.current_version = self.y['Git']['k_version']
25+
self.kuiper_backup = 'kuiper-backup.zip'
26+
self.kuiper_package = "Kuiper-update.zip"
27+
28+
if not os.path.exists(self.y['Logs']['log_folder']):
29+
os.makedirs(self.y['Logs']['log_folder'])
30+
31+
self.kuiper_update_log = open(self.kuiper_update_log_file , 'w')
32+
33+
34+
# exclude dirs: such as raw and files folders
35+
self.backup_dirs_exclude = [
36+
os.path.join( self.y['Directories']['artifacts_upload'][0] ,self.y['Directories']['artifacts_upload'][1] ) ,
37+
os.path.join( self.y['Directories']['artifacts_upload_raw'][0] ,self.y['Directories']['artifacts_upload_raw'][1] ),
38+
self.y['Logs']['log_folder']
39+
]
40+
41+
# exclude files: such as the backup, package file, and update log file
42+
self.backup_files_exclude = [
43+
self.kuiper_backup,
44+
self.kuiper_package,
45+
self.kuiper_update_log_file
46+
]
47+
48+
49+
50+
# print the kuiper update logs
51+
def write_log(self, msg):
52+
msg = str(datetime.now()) + ": " + msg
53+
# be quiet and dont print the messages if -q enabled
54+
if not self.args.quiet:
55+
print msg
56+
self.kuiper_update_log.write( msg + "\n")
57+
58+
59+
60+
# print the download progress
61+
def DownloadProgress(self, count, block_size, total_size):
62+
global start_time
63+
if count == 0:
64+
start_time = time.time()
65+
return
66+
duration = time.time() - start_time
67+
progress_size = int(count * block_size)
68+
speed = int(progress_size / (1024 * duration))
69+
percent = int((float(progress_size) / total_size) * 100 )
70+
sys.stdout.write("\r...%d%%, %d MB, %d KB/s, %d seconds passed" %
71+
(percent, progress_size / (1024 * 1024), speed, duration))
72+
73+
74+
75+
# backup current Kuiper files
76+
def backup_files(self):
77+
try:
78+
self.write_log( "Start backup for Kuiper")
79+
# backup the current Kuiper files before updating it
80+
backup = zipfile.ZipFile(self.kuiper_backup , 'w')
81+
82+
backup_files = []
83+
for root, dirs, files in os.walk(self.y['Directories']['platform_folder']):
84+
85+
for file in files:
86+
87+
# exclude files in backup_files_exclude
88+
if file in self.backup_files_exclude:
89+
continue
90+
91+
file_path = os.path.join(root.lstrip("."), file)
92+
# if file in folders backup_dirs_exclude skip it
93+
if not file_path.startswith(tuple(self.backup_dirs_exclude)):
94+
self.write_log( "Backup file: " + file_path )
95+
backup_files.append( file_path )
96+
backup.write(os.path.join(root, file))
97+
98+
backup.close()
99+
self.write_log("Current Kuiper backup done")
100+
return [True, "Current Kuiper backup done"]
101+
102+
except Exception as e:
103+
self.write_log("Failed to backup current Kuiper: " + str(e))
104+
return [False, "Failed to backup Kuiper"]
105+
106+
107+
# ============================ Remove old files
108+
# remove all files from the current Kuiper version
109+
110+
def Remove_Old_Files(self):
111+
count = 0
112+
all_files = []
113+
for root, dirs, files in os.walk('./'):
114+
# if the directory is in the excluded list then skip it
115+
if root in self.backup_dirs_exclude:
116+
continue
117+
118+
for name in files:
119+
all_files.append( os.path.join(root, name) )
120+
121+
for f in all_files:
122+
# if the file in the excluded list then skip it
123+
if f in self.backup_files_exclude:
124+
continue
125+
126+
try:
127+
# delete the old file
128+
self.write_log("Delete file: " + f)
129+
count += 1
130+
except Exception as e:
131+
self.write_log("Failed to delete file: " + f )
132+
self.write_log("Error: " + str(e) )
133+
return False
134+
135+
self.write_log("Successfuly removed all old files: " + str(count) + " files")
136+
return True
137+
138+
# ============================ Update kuiper files
139+
def Decompress_Files(self):
140+
141+
# ============== Update Kuiper
142+
zip_update = zipfile.ZipFile(self.kuiper_package)
143+
144+
bUpdateSuccess = [True , "done"]
145+
for file in zip_update.namelist():
146+
# skip folders
147+
if file.endswith("/"):
148+
continue
149+
150+
# read the file
151+
fileobj = zip_update.open(file)
152+
153+
dst_path = "/".join(file.split("/")[1:])
154+
self.write_log("update file: " + dst_path)
155+
156+
try:
157+
# if the folder not exists, then create folder
158+
if os.path.dirname(dst_path) != "" and os.path.exists(os.path.dirname(dst_path)) == False:
159+
os.makedirs(os.path.dirname(dst_path))
160+
except Exception as e:
161+
self.write_log( "Failed to create folder ["+dst_path+"]" )
162+
bUpdateSuccess = [False , "Failed to create folder ["+dst_path+"] - " + str(e)]
163+
break
164+
165+
166+
try:
167+
# read and write the new files
168+
with open(dst_path , 'wb') as df:
169+
df.write(fileobj.read())
170+
df.close()
171+
except Exception as e:
172+
self.write_log( "Couldn't update file ["+dst_path+"]")
173+
bUpdateSuccess = [False , "[-] Couldn't update file ["+dst_path+"]" + str(e)]
174+
break
175+
176+
return bUpdateSuccess
177+
178+
179+
180+
# ========================== check update
181+
# check if update avaliable
182+
def check_update(self):
183+
self.write_log("Check latest update version")
184+
link = self.release_url
185+
current_version = self.current_version
186+
try:
187+
request = urllib.urlopen(link)
188+
response = request.read()
189+
data = json.loads(response)
190+
191+
self.write_log("Kuiper current version \t["+str(current_version)+"]")
192+
if current_version < data['tag_name']:
193+
self.write_log("Kuiper new release version \t["+str(data['tag_name'])+"]")
194+
195+
new_release_link = data['zipball_url'] # get the link to download the package
196+
self.write_log("Kuiper New release link \t["+new_release_link+"]")
197+
198+
return {
199+
'status' : True,
200+
"up-to-date": False,
201+
"link" : new_release_link ,
202+
"version" : data['tag_name']
203+
}
204+
else:
205+
self.write_log("Kuiper is up-to-date")
206+
return {
207+
'status' : True,
208+
"up-to-date": True
209+
}
210+
211+
except Exception as e:
212+
self.write_log("Failed to check latest update: " + str(e))
213+
return {
214+
'status': False,
215+
'error' : "Failed to check latest update: " + str(e)
216+
}
217+
218+
219+
220+
221+
222+
223+
# ========================== update function
224+
def update(self):
225+
226+
kuiper_package = self.kuiper_package if self.args.package is None else self.args.package
227+
use_package = False if self.args.package is None else True
228+
229+
230+
231+
self.write_log("Start updating Kuiper")
232+
# =========================== if package provided
233+
# if package provided check the version from the package
234+
if use_package:
235+
try:
236+
zip_package = zipfile.ZipFile(kuiper_package)
237+
zip_config = zip_package.read('configuration.yaml')
238+
zip_config_yaml = yaml.safe_load(zip_config)
239+
240+
zip_package.close()
241+
242+
package_version = zip_config_yaml['Git']['k_version']
243+
self.write_log("Package verson: " + zip_config_yaml['Git']['k_version'] )
244+
245+
246+
# check if the current version newer than the provided package
247+
if self.current_version >= package_version:
248+
self.write_log("The installed version is newer than the provided package version")
249+
self.write_log("current version: " + str(self.current_version ) + " , package version: " + package_version)
250+
return False
251+
252+
except Exception as e:
253+
self.write_log("Failed opening the package file: " + str(e))
254+
return False
255+
256+
# =========================== download package if not provided
257+
# if there is not package provided check from github
258+
else:
259+
update_version = self.check_update()
260+
if update_version['status'] and not update_version['up-to-date']:
261+
262+
self.write_log( "Start Downloading Kuiper " + update_version['version'] )
263+
self.write_log( "GitHub URL zip file: " + update_version['link'] )
264+
265+
# downloaded zip file from github (link, target, print_download_progress)
266+
download_success = True #
267+
try:
268+
urllib.urlretrieve(update_version['link'], kuiper_package , self.DownloadProgress )
269+
print "done"
270+
self.write_log("Download success: " +update_version['link'] + " >>> " + kuiper_package)
271+
272+
except Exception as e:
273+
self.write_log("Failed to download the Kuiper package from Github: " + update_version['link'] )
274+
self.write_log("Error message: " + str(e))
275+
return False
276+
277+
else:
278+
return False
279+
280+
# ====================== backup
281+
# if package is exists/downloaded, then start backup the old files
282+
backup = self.backup_files()
283+
284+
# if failed to backup
285+
if not backup[0]:
286+
return False
287+
288+
# ====================== Remove files
289+
# if failed to remove old files
290+
bRemoveOldFiles = self.Remove_Old_Files()
291+
if not bRemoveOldFiles:
292+
return False
293+
294+
# ====================== Decompress the package
295+
bDecompressFiles = self.Decompress_Files()
296+
if not bDecompressFiles[0]:
297+
return False
298+
299+
# ====================== Install new dependencies
300+
# install new dependinces
301+
302+
303+
# the user wasn't authenticated as a sudoer, exit?
304+
self.write_log("Start install dependencies")
305+
proc_install_dep = subprocess.call(['sudo','./kuiper_install.sh' , '-install'])
306+
307+
308+
# ====================== Remove
309+
# remove backup and new update release
310+
self.write_log("Remove file: " + self.kuiper_backup)
311+
os.remove(self.kuiper_backup)
312+
313+
# if the package is not provided by client (means it has been downloaded) then remove the downloaded package file
314+
if self.args.package is None:
315+
self.write_log("Remove file: " + kuiper_package)
316+
os.remove(kuiper_package)
317+
318+
319+
# ====================== Close logging file
320+
self.write_log("Update successfuly done")
321+
322+
323+
# close the logging
324+
self.kuiper_update_log.close()
325+
326+
327+
328+
329+
def main():
330+
331+
# ================== arguments
332+
a_parser = argparse.ArgumentParser('Python script tool to update Kuiper')
333+
334+
requiredargs = a_parser.add_argument_group('Required [choose one]')
335+
requiredargs.add_argument('-c', dest='check_update', help='Check if update avaliable from Github', action="store_true")
336+
requiredargs.add_argument('-u' , dest='update' , help='Update Kuiper', action="store_true")
337+
338+
a_parser.add_argument('-p' , dest='package' , help='The path of update package, if not specified it will download it from Github')
339+
a_parser.add_argument('-q' , dest='quiet', action="store_true" , help="Don't print the update log messages")
340+
341+
args = a_parser.parse_args()
342+
343+
344+
345+
# if command check_update nor update has been provided
346+
if args.check_update==False and args.update==False:
347+
print "Specifiy the options -c (check_update) or -u (update)"
348+
a_parser.print_help()
349+
350+
351+
# if check update used
352+
elif args.check_update:
353+
obj_checkupdate = Kuiper_Update(args)
354+
obj_checkupdate.check_update()
355+
356+
# if update request
357+
elif args.update:
358+
obj_checkupdate = Kuiper_Update(args)
359+
obj_checkupdate.update()
360+
361+
362+
# if nothing requested
363+
else:
364+
a_parser.print_help()
365+
366+
367+
368+
main()

0 commit comments

Comments
 (0)