11# oci-utils
22#
3- # Copyright (c) 2019, 2020 Oracle and/or its affiliates. All rights reserved.
3+ # Copyright (c) 2019, 2021 Oracle and/or its affiliates. All rights reserved.
44# Licensed under the Universal Permissive License v 1.0 as shown
55# at http://oss.oracle.com/licenses/upl.
66
1515import re
1616import sys
1717import time
18- import urllib .request
19- from datetime import datetime
18+ from urllib .request import urlopen , urlretrieve , Request
2019
21- import requests
2220import yaml
21+
2322from oci_utils .migrate import OciMigrateConfParam
2423from oci_utils .migrate import ProgressBar
25- from oci_utils .migrate import error_msg
2624from oci_utils .migrate import bytes_to_hex
2725from oci_utils .migrate import console_msg
26+ from oci_utils .migrate import error_msg
2827from oci_utils .migrate import migrate_data
2928from oci_utils .migrate import pause_msg
3029from oci_utils .migrate import read_yn
@@ -97,7 +96,7 @@ def exec_search(file_name, rootdir='/', dirnames=False):
9796 _logger .debug ('Found %s as directory.' , os .path .join (rootdir , path_name , file_name ))
9897 return os .path .join (rootdir , path_name , file_name )
9998 except Exception as e :
100- _logger .error (' Error while looking for %s: %s' , file_name , str (e ))
99+ _logger .error (' Error while looking for %s: %s' , file_name , str (e ))
101100 raise OciMigrateException ('Error while looking for %s:' % file_name ) from e
102101 return None
103102
@@ -169,39 +168,33 @@ def get_cloud_agent_if_relevant(root_part, os_type, major_release):
169168 bool: always True
170169 """
171170 _logger .debug ('__ Collecting the oracle_cloud_agent package if relevant.' )
172- _logger .debug ('root partition: %s' % root_part )
171+ _logger .debug ('root partition: %s' , root_part )
173172 _logger .debug ('os type: %s' % os_type )
174- _logger .debug ('major release: %s' % major_release )
173+ _logger .debug ('major release: %s' , major_release )
175174 pause_msg ('cloud agent' , pause_flag = '_OCI_AGENT' )
176175 try :
177176 if os_type in get_config_data ('ol_os_for_cloud_agent' ):
178177 _logger .debug ('OS is OL-type os.' )
179178 el_tag = get_config_data ('ol_version_id_dict' )[major_release ]
180- _logger .debug ('el tag: %s' % el_tag )
179+ _logger .debug ('el tag: %s' , el_tag )
181180 cloud_agent_url = get_url_data_from_base (el_tag )
182- _logger .debug ('cloud agent url: %s' % cloud_agent_url )
181+ _logger .debug ('cloud agent url: %s' , cloud_agent_url )
183182 if cloud_agent_url is None :
184183 _logger .debug ('URL with oracle cloud agent package not found.' )
185184 else :
186185 package_name = os .path .basename (cloud_agent_url )
187186 destination_dir = get_config_data ('ol_os_oracle_cloud_agent_store' )
188- destination = os .path .join (root_part ,
189- destination_dir .lstrip ('/' ),
190- package_name .lstrip ('/' ))
191- _logger .debug ('Destination for oracle cloud agent package: %s'
192- % destination )
193- _ = get_file_from_url (cloud_agent_url , destination )
194- migrate_data .oracle_cloud_agent_location = \
195- os .path .join ('/' ,
196- destination_dir .lstrip ('/' ),
197- package_name .lstrip ('/' ))
198- _logger .debug ('cloud agent location: %s'
199- % migrate_data .oracle_cloud_agent_location )
187+ destination = os .path .join (root_part , destination_dir .lstrip ('/' ), package_name .lstrip ('/' ))
188+ _logger .debug ('Destination for oracle cloud agent package: %s' , destination )
189+ get_file_from_url (cloud_agent_url , destination )
190+ migrate_data .oracle_cloud_agent_location \
191+ = os .path .join ('/' , destination_dir .lstrip ('/' ), package_name .lstrip ('/' ))
192+ _logger .debug ('cloud agent location: %s' , migrate_data .oracle_cloud_agent_location )
200193 else :
201194 _logger .debug ('This operation is not relevant here.' )
202195 return True
203196 except Exception as e :
204- _logger .debug ('Installation of the oracle cloud agent failed: %s' % str (e ))
197+ _logger .debug ('Installation of the oracle cloud agent failed: %s' , str (e ))
205198
206199 pause_msg ('cloud agent' , pause_flag = '_OCI_AGENT' )
207200 return True
@@ -225,7 +218,7 @@ def get_config_data(key):
225218 with OciMigrateConfParam (migrate_data .oci_migrate_conf_file , key ) as config :
226219 return config .get_values ()
227220 except FileNotFoundError as fnf :
228- _logger .debug ('File %s not found: %s, using data structure.' , migrate_data .oci_migrate_conf_file , str (fnf ))
221+ _logger .debug ('File %s not found: %s, using data structure.' , migrate_data .oci_migrate_conf_file , str (fnf ))
229222 if key in migrate_data .oci_image_migrate_config :
230223 return migrate_data .oci_image_migrate_config [key ]
231224
@@ -249,15 +242,15 @@ def get_file_from_url(url, dest):
249242 str: the full path of the destination on success, raises an exception
250243 otherwise.
251244 """
252- _logger .debug ('__ Get file from url %s.' % url )
245+ _logger .debug ('__ Get file from url %s.' , url )
253246 _ , nbcols = terminal_dimension ()
254247 packname = os .path .basename (url )
255248 try :
256249 downloadwait = ProgressBar (nbcols , 0.2 , progress_chars = ['pulling oracle-cloud-agent' ])
257250 downloadwait .start ()
258- _ = urllib . request . urlretrieve (url , dest )
251+ _ = urlretrieve (url , dest )
259252 except Exception as e :
260- _logger .warning ('Failed to retrieve %s int %s: %s' % ( url , dest , str (e ) ))
253+ _logger .warning ('Failed to retrieve %s int %s: %s' , url , dest , str (e ))
261254 raise ('Failed to retrieve %s int %s: %s' % (url , dest , str (e )))
262255 finally :
263256 if system_tools .is_thread_running (downloadwait ):
@@ -465,8 +458,7 @@ def mount_lvm2(devname):
465458 _logger .debug ('__ Running mount lvm2 %s' , devname )
466459 try :
467460 _ , nbcols = terminal_dimension ()
468- mountwait = ProgressBar (int (nbcols ), 0.2 ,
469- progress_chars = ['mounting lvm' ])
461+ mountwait = ProgressBar (int (nbcols ), 0.2 , progress_chars = ['mounting lvm' ])
470462 mountwait .start ()
471463 #
472464 # physical volumes
@@ -563,8 +555,7 @@ def mount_partition(devname, mountpoint=None):
563555 pause_msg (cmd , pause_flag = '_OCI_MOUNT' )
564556 _ , nbcols = terminal_dimension ()
565557 try :
566- mountpart = ProgressBar (nbcols , 0.2 ,
567- progress_chars = ['mount %s' % devname ])
558+ mountpart = ProgressBar (nbcols , 0.2 , progress_chars = ['mount %s' % devname ])
568559 mountpart .start ()
569560 _logger .debug ('command: %s' , cmd )
570561 cmdret = system_tools .run_call_cmd (cmd )
@@ -682,53 +673,15 @@ def read_from_url(url):
682673 # to keep the encodings import in place
683674 _ = dir (encodings .idna )
684675 try :
685- url_ref = requests .get (url )
686- if url_ref .status_code != 200 :
687- raise Exception ('url get status: %s while looking for %s'
688- % (str (url_ref .status_code ), url ))
689- url_contents = url_ref .content
690- url_ref .close ()
676+ url_request = Request (url = url , headers = {'Authorization' : 'Bearer Oracle' })
677+ with urlopen (url_request ) as url_ref :
678+ if url_ref .status != 200 :
679+ raise Exception ('url get status: %s while looking for %s' % (str (url_ref .status ), url ))
680+ url_contents = url_ref .read ()
691681 return url_contents
692682 except Exception as e :
693683 _logger .warning ('Failed to read from %s: %s' , url , str (e ))
694- raise OciMigrateException ('Failed to read from %s: %s' % (url , str (e )))
695-
696-
697- def result_msg (msg , flags = 'a' , result = False ):
698- """
699- Write information to the log file, the result file and the console if the
700- result flag is set.
701-
702- Parameters
703- ----------
704- msg: str
705- The message.
706- flags: str
707- The flags for the open file command.
708- result: bool
709- Flag, write to console if True.
710-
711- Returns
712- -------
713- No return value.
714- """
715- msg = ' Just mentioning I am here.' if msg is None else msg
716- _logger .debug ('%s' % msg )
717- try :
718- with open (migrate_data .result_filename , flags ) as f :
719- f .write (' %s: %s\n ' % (datetime .now ().strftime ('%H:%M:%S' ), msg ))
720- except IOError as e :
721- errornb , strerror = e .args
722- #
723- # trap permission denied errors if running as non root.
724- if errornb != 13 :
725- _logger .error (' Failed to write to %s: %s'
726- % (migrate_data .result_filename , strerror ))
727- except Exception as e :
728- _logger .error (' Failed to write to %s: %s'
729- % (migrate_data .result_filename , str (e )))
730- if result :
731- sys .stdout .write (' %s\n ' % msg )
684+ raise OciMigrateException ('Failed to read from %s' % url ) from e
732685
733686
734687def set_default_user (cfgfile , username ):
@@ -797,9 +750,7 @@ def show_fstab(fstabdata):
797750 No return value.
798751 """
799752 for line in fstabdata :
800- result_msg (msg = '%60s %20s %8s %20s %2s %2s'
801- % (line [0 ], line [1 ], line [2 ], line [3 ], line [4 ], line [5 ]),
802- result = True )
753+ result_msg (msg = '%60s %20s %8s %20s %2s %2s' % (line [0 ], line [1 ], line [2 ], line [3 ], line [4 ], line [5 ]), result = True )
803754
804755
805756def show_grub_data (grublist ):
@@ -1105,10 +1056,7 @@ def show_partition_table(table):
11051056 bootflag = 'YES'
11061057 else :
11071058 bootflag = ' NO'
1108- result_msg (msg = ' %02d %5s %16s %32s'
1109- % (i , bootflag , table [i ]['type' ],
1110- table [i ]['entry' ]),
1111- result = True )
1059+ result_msg (msg = ' %02d %5s %16s %32s' % (i , bootflag , table [i ]['type' ], table [i ]['entry' ]), result = True )
11121060
11131061
11141062@state_loop (3 )
@@ -1224,8 +1172,7 @@ def unmount_part(devname):
12241172 raise OciMigrateException ('Failed to remove mountpoint %s' % mntpoint )
12251173
12261174 _logger .critical (' Failed to unmount %s: %d' , devname , cmdret )
1227- console_msg ('Failed to unmount %s, error code %d.\n '
1228- 'Please verify before continuing.' % (devname , cmdret ))
1175+ console_msg ('Failed to unmount %s, error code %d.\n Please verify before continuing.' % (devname , cmdret ))
12291176 retry = read_yn ('Something prevented to complete %s, please verify and correct if possible. '
12301177 'Press Y to retry, N to ignore.' , waitenter = True )
12311178 if not retry :
@@ -1268,13 +1215,13 @@ def update_cloudconfig_runcmd(runcommand):
12681215 #
12691216 #
12701217 runcmd_definition = False
1271- if type (cloudcfg ) is dict :
1218+ if isinstance (cloudcfg , dict ) :
12721219 if 'runcmd' in list (cloudcfg .keys ()):
12731220 #
12741221 # runcmd present in cloud config file
12751222 run_cmd = cloudcfg ['runcmd' ]
12761223 for yaml_key in run_cmd :
1277- if type (yaml_key ) is list :
1224+ if isinstance (yaml_key , list ) :
12781225 for yamlval in yaml_key :
12791226 if runcommand in yamlval :
12801227 _logger .debug ('%s already in cloud_init' , runcommand )
@@ -1298,8 +1245,7 @@ def update_cloudconfig_runcmd(runcommand):
12981245
12991246 with open (cloudconfig , 'w' ) as f :
13001247 yaml .dump (cloudcfg , f , width = 50 )
1301- _logger .debug ('Cloud configuration file %s '
1302- 'successfully updated.' , cloudconfig )
1248+ _logger .debug ('Cloud configuration file %s successfully updated.' , cloudconfig )
13031249 return True
13041250 else :
13051251 _logger .error ('Invalid cloud config file.' )
0 commit comments