Advertisement
JimMcKeeth

Git_network_test

Mar 25th, 2025 (edited)
475
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 11.06 KB | Source Code | 0 0
  1. import speedtest
  2. import git
  3. from git.remote import RemoteProgress
  4. import os
  5. import datetime
  6. import time
  7. import shutil
  8. from pathlib import Path
  9. import traceback  
  10. import csv
  11.  
  12. def run_speed_test(max_retries=3, retry_delay=5):
  13.     last_error = None
  14.     for attempt in range(max_retries):
  15.         try:
  16.             st = speedtest.Speedtest(secure=True)  # Force HTTPS
  17.             st.get_servers()  # Get list of servers
  18.             st.get_best_server()  # Get best server
  19.            
  20.             # Run tests
  21.             download_speed = st.download() / 1_000_000  # Convert to Mbps
  22.             upload_speed = st.upload() / 1_000_000  # Convert to Mbps
  23.             ping = st.results.ping
  24.             return download_speed, upload_speed, ping
  25.            
  26.         except Exception as e:
  27.             last_error = str(e)
  28.             if "403" in str(e):
  29.                 print(f"Attempt {attempt + 1}/{max_retries}: Speedtest.net rate limit or authentication error")
  30.             else:
  31.                 print(f"Attempt {attempt + 1}/{max_retries}: Speed test failed - {str(e)}")
  32.            
  33.             if attempt < max_retries - 1:
  34.                 time.sleep(retry_delay * (attempt + 1))  # Exponential backoff
  35.    
  36.     raise Exception(f"Speed test failed after {max_retries} attempts. Last error: {last_error}")
  37.  
  38. def clone_repository(repo_url, target_dir, file_handle):
  39.     try:
  40.         log_message(f"Creating directory {target_dir}", file_handle)
  41.         os.makedirs(target_dir)
  42.        
  43.         # Create progress printer for Git operations
  44.         stage_times = {}
  45.         stage_start = None
  46.         current_stage = None
  47.         last_line_length = 0
  48.        
  49.         def progress_printer(op_code, cur_count, max_count=None, message=''):
  50.             nonlocal stage_start, current_stage, last_line_length
  51.            
  52.             # Determine the current stage
  53.             new_stage = []
  54.             if op_code & RemoteProgress.COUNTING:
  55.                 new_stage.append("Counting")
  56.             if op_code & RemoteProgress.COMPRESSING:
  57.                 new_stage.append("Compressing")
  58.             if op_code & RemoteProgress.WRITING:
  59.                 new_stage.append("Writing")
  60.             if op_code & RemoteProgress.RECEIVING:
  61.                 new_stage.append("Receiving")
  62.             if op_code & RemoteProgress.RESOLVING:
  63.                 new_stage.append("Resolving")
  64.             if op_code & RemoteProgress.FINDING_SOURCES:
  65.                 new_stage.append("Finding sources")
  66.            
  67.             new_stage = " & ".join(new_stage) if new_stage else f"Stage {op_code}"
  68.            
  69.             # If stage changed, record timing and log the new stage
  70.             if new_stage != current_stage:
  71.                 if stage_start and current_stage:
  72.                     duration = time.time() - stage_start
  73.                     if current_stage in stage_times:
  74.                         stage_times[current_stage] += duration
  75.                     else:
  76.                         stage_times[current_stage] = duration
  77.                     # Clear the last progress line and log the completed stage
  78.                     print(' ' * last_line_length + '\r', end='')
  79.                     log_message(f"Completed {current_stage}", file_handle)
  80.                 current_stage = new_stage
  81.                 stage_start = time.time()
  82.                 print(f"\nStarting {current_stage}...")
  83.            
  84.             # Update progress percentage on same line
  85.             if max_count:
  86.                 progress = f"{current_stage}: {cur_count}/{max_count} ({cur_count/max_count*100:.1f}%)\r"
  87.                 print(progress, end='')
  88.                 last_line_length = len(progress)
  89.        
  90.         # Clone with timing information
  91.         log_message("Starting Git clone operation...", file_handle)
  92.         clone_start = time.time()
  93.         repo = git.Repo.clone_from(repo_url, target_dir, progress=progress_printer)
  94.         print()  # Add newline after progress display
  95.        
  96.         # Record final stage timing
  97.         if stage_start and current_stage:
  98.             duration = time.time() - stage_start
  99.             if current_stage in stage_times:
  100.                 stage_times[current_stage] += duration
  101.             else:
  102.                 stage_times[current_stage] = duration
  103.        
  104.         # Log timing summary
  105.         total_time = time.time() - clone_start
  106.         log_message("\nGit clone timing summary:", file_handle)
  107.         for stage, duration in stage_times.items():
  108.             log_message(f"{stage}: {duration:.2f} seconds", file_handle)
  109.         log_message(f"Total clone time: {total_time:.2f} seconds", file_handle)
  110.        
  111.         return True, "Repository cloned successfully", repo
  112.     except Exception as e:
  113.         log_message(f"Clone error details:\n{traceback.format_exc()}", file_handle)
  114.         return False, str(e), None
  115.  
  116. def log_message(message, file_handle):
  117.     print(message)
  118.     file_handle.write(message + "\n")
  119.     file_handle.flush()
  120.  
  121. def do_speed_test(f):
  122.     # Speed test
  123.     log_message("Running speed test...", f)
  124.     try:
  125.         download, upload, ping = run_speed_test()
  126.         log_message(f"Download Speed: {download:.2f} Mbps", f)
  127.         log_message(f"Upload Speed: {upload:.2f} Mbps", f)
  128.         log_message(f"Ping: {ping:.2f} ms", f)
  129.     except Exception as e:
  130.         log_message(f"Speed test failed: {str(e)}", f)
  131.    
  132.     log_message("\n" + "-" * 50, f)
  133.     log_message("", f)
  134.  
  135. def cleanup_directory(directory, repo, file_handle):
  136.     max_attempts = 4
  137.     delay = 2
  138.  
  139.     for attempt in range(max_attempts):
  140.         try:
  141.             if os.path.exists(directory):
  142.                 # Clean up Git repository resources
  143.                 if repo is not None:
  144.                     try:
  145.                         for submodule in repo.submodules:
  146.                             submodule.remove()
  147.                         repo.git.clear_cache()
  148.                         repo.close()
  149.                     except Exception as git_error:
  150.                         log_message(f"Git cleanup warning: {str(git_error)}\n{traceback.format_exc()}", file_handle)
  151.                
  152.                 time.sleep(delay * attempt)
  153.                
  154.                 try:
  155.                     # Try removing files first
  156.                     for root, dirs, files in os.walk(directory, topdown=False):
  157.                         for name in files:
  158.                             file_path = os.path.join(root, name)
  159.                             try:
  160.                                 os.chmod(file_path, 0o777)  # Ensure we have permission
  161.                                 os.unlink(file_path)
  162.                             except Exception as e:
  163.                                 log_message(f"Failed to remove file {file_path}: {str(e)}", file_handle)
  164.                
  165.                     # Then try rmtree
  166.                     shutil.rmtree(directory, ignore_errors=False)  # Changed to False to get error details
  167.                    
  168.                     if not os.path.exists(directory):
  169.                         log_message(f"Successfully removed directory at {directory}", file_handle)
  170.                         return True
  171.                 except Exception as remove_error:
  172.                     log_message(f"Detailed removal error: {str(remove_error)}\n{traceback.format_exc()}", file_handle)
  173.             else:
  174.                 return True
  175.         except Exception as e:
  176.             log_message(f"Cleanup attempt {attempt + 1} failed: {str(e)}\n{traceback.format_exc()}", file_handle)
  177.             time.sleep(delay)
  178.    
  179.     return False
  180.  
  181. def write_metrics_to_csv(metrics):
  182.     csv_file = "network_tests.csv"
  183.     file_exists = os.path.exists(csv_file)
  184.    
  185.     with open(csv_file, 'a', newline='') as f:
  186.         writer = csv.writer(f)
  187.         if not file_exists:
  188.             writer.writerow([
  189.                 'Start Time', 'Log File',
  190.                 'Initial Ping (ms)', 'Initial Download (Mbps)', 'Initial Upload (Mbps)',
  191.                 'Git Clone Status', 'Git Execution Time (s)',
  192.                 'Final Ping (ms)', 'Final Download (Mbps)', 'Final Upload (Mbps)'
  193.             ])
  194.         writer.writerow(metrics)
  195.  
  196. def main(repo_url):
  197.     # Setup logging
  198.     start_time = datetime.datetime.now()
  199.     timestamp = start_time.strftime("%Y%m%d_%H%M%S")
  200.     log_file = f"network_test_{timestamp}.log"
  201.    
  202.     # Initialize metrics
  203.     initial_ping = initial_download = initial_upload = 0
  204.     final_ping = final_download = final_upload = 0
  205.     git_success = False
  206.     git_execution_time = 0
  207.    
  208.     with open(log_file, "w") as f:
  209.         log_message(f"Git Network Test - {start_time}", f)
  210.         log_message("-" * 50, f)
  211.         log_message("", f)
  212.        
  213.         # Initial speed test with retry
  214.         log_message("Running initial speed test...", f)
  215.         try:
  216.             initial_download, initial_upload, initial_ping = run_speed_test()
  217.             log_message(f"Download Speed: {initial_download:.2f} Mbps", f)
  218.             log_message(f"Upload Speed: {initial_upload:.2f} Mbps", f)
  219.             log_message(f"Ping: {initial_ping:.2f} ms", f)
  220.         except Exception as e:
  221.             log_message(f"Speed test failed: {str(e)}", f)
  222.        
  223.         log_message("\n" + "-" * 50 + "\n", f)
  224.  
  225.         # Git clone test
  226.         git_start_time = time.time()
  227.         target_dir = f"test_clone_{timestamp}"
  228.        
  229.         log_message(f"Attempting to clone repository: {repo_url}", f)
  230.         success, message, repo = clone_repository(repo_url, target_dir, f)
  231.         log_message(f"Clone result: {message}", f)
  232.         log_message(f"Clone success: {success}", f)
  233.        
  234.         git_success = success
  235.         git_execution_time = time.time() - git_start_time
  236.         log_message(f"\nTotal execution time: {git_execution_time:.2f} seconds", f)
  237.  
  238.         # Cleanup after successful clone
  239.         log_message(f"Attempting to remove cloned directory at {target_dir}", f)
  240.         if not cleanup_directory(target_dir, repo if success else None, f):
  241.             log_message(f"WARNING: Failed to remove directory {target_dir}", f)
  242.  
  243.         log_message("\n" + "-" * 50 + "\n", f)
  244.        
  245.         # Final speed test with retry
  246.         log_message("Running final speed test...", f)
  247.         try:
  248.             final_download, final_upload, final_ping = run_speed_test()
  249.             log_message(f"Download Speed: {final_download:.2f} Mbps", f)
  250.             log_message(f"Upload Speed: {final_upload:.2f} Mbps", f)
  251.             log_message(f"Ping: {final_ping:.2f} ms", f)
  252.         except Exception as e:
  253.             log_message(f"Speed test failed: {str(e)}", f)
  254.        
  255.         log_message("\n" + "-" * 50 + "\n", f)
  256.  
  257.     # Write metrics to CSV
  258.     metrics = [
  259.         start_time.isoformat(),
  260.         log_file,
  261.         f"{initial_ping:.2f}",
  262.         f"{initial_download:.2f}",
  263.         f"{initial_upload:.2f}",
  264.         "Success" if git_success else "Fail",
  265.         f"{git_execution_time:.2f}",
  266.         f"{final_ping:.2f}",
  267.         f"{final_download:.2f}",
  268.         f"{final_upload:.2f}"
  269.     ]
  270.     write_metrics_to_csv(metrics)
  271.  
  272. if __name__ == "__main__":
  273.     main("https://github.com/skia4delphi/skia4delphi.git")
  274.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement