|
| 1 | +"""SonarQube Manager - Handles SonarQube container and scanning operations.""" |
| 2 | + |
| 3 | +import docker |
| 4 | +import time |
| 5 | +import requests |
| 6 | +import os |
| 7 | +from typing import Optional |
| 8 | +from rich.console import Console |
| 9 | +from secuscan.core.config import config |
| 10 | + |
| 11 | +console = Console() |
| 12 | + |
| 13 | + |
| 14 | +class SonarQubeManager: |
| 15 | + """Manages SonarQube container interactions and scanning.""" |
| 16 | + |
| 17 | + SONARQUBE_IMAGE = "sonarqube:community" |
| 18 | + SCANNER_IMAGE = "sonarsource/sonar-scanner-cli:latest" |
| 19 | + CONTAINER_NAME = "secuscan-sonarqube" |
| 20 | + |
| 21 | + def __init__(self): |
| 22 | + try: |
| 23 | + self.client = docker.from_env() |
| 24 | + self._available = True |
| 25 | + except docker.errors.DockerException: |
| 26 | + self.client = None |
| 27 | + self._available = False |
| 28 | + |
| 29 | + def is_available(self) -> bool: |
| 30 | + """Checks if Docker daemon is running and accessible.""" |
| 31 | + if not self._available: |
| 32 | + return False |
| 33 | + |
| 34 | + try: |
| 35 | + self.client.ping() |
| 36 | + return True |
| 37 | + except docker.errors.DockerException: |
| 38 | + return False |
| 39 | + |
| 40 | + def pull_image(self, image_name: str): |
| 41 | + """Pulls a Docker image if not present.""" |
| 42 | + if not self.is_available(): |
| 43 | + return |
| 44 | + |
| 45 | + try: |
| 46 | + self.client.images.get(image_name) |
| 47 | + console.print(f"[green]Image {image_name} found locally.[/green]") |
| 48 | + except docker.errors.ImageNotFound: |
| 49 | + console.print(f"[yellow]Pulling {image_name}...[/yellow]") |
| 50 | + with console.status(f"[bold green]Downloading {image_name}... This may take a while..."): |
| 51 | + self.client.images.pull(image_name) |
| 52 | + console.print("[green]Image pulled successfully.[/green]") |
| 53 | + |
| 54 | + def is_container_running(self) -> bool: |
| 55 | + """Checks if the SonarQube container is currently running.""" |
| 56 | + if not self.is_available(): |
| 57 | + return False |
| 58 | + |
| 59 | + try: |
| 60 | + container = self.client.containers.get(self.CONTAINER_NAME) |
| 61 | + return container.status == "running" |
| 62 | + except docker.errors.NotFound: |
| 63 | + return False |
| 64 | + |
| 65 | + def start_sonarqube(self): |
| 66 | + """Starts the SonarQube container.""" |
| 67 | + if not self.is_available(): |
| 68 | + raise RuntimeError("Docker is not available.") |
| 69 | + |
| 70 | + # Ensure image is pulled |
| 71 | + self.pull_image(self.SONARQUBE_IMAGE) |
| 72 | + |
| 73 | + if self.is_container_running(): |
| 74 | + console.print("[green]SonarQube container is already running.[/green]") |
| 75 | + return |
| 76 | + |
| 77 | + console.print("[yellow]Starting SonarQube container...[/yellow]") |
| 78 | + try: |
| 79 | + # Check if stopped container exists and remove it |
| 80 | + try: |
| 81 | + old_container = self.client.containers.get(self.CONTAINER_NAME) |
| 82 | + old_container.remove(force=True) |
| 83 | + except docker.errors.NotFound: |
| 84 | + pass |
| 85 | + |
| 86 | + self.client.containers.run( |
| 87 | + self.SONARQUBE_IMAGE, |
| 88 | + name=self.CONTAINER_NAME, |
| 89 | + ports={'9000/tcp': 9000}, |
| 90 | + environment={"SONAR_ES_BOOTSTRAP_CHECKS_DISABLE": "true"}, |
| 91 | + volumes={ |
| 92 | + 'sonarqube_data': {'bind': '/opt/sonarqube/data', 'mode': 'rw'}, |
| 93 | + 'sonarqube_extensions': {'bind': '/opt/sonarqube/extensions', 'mode': 'rw'}, |
| 94 | + 'sonarqube_logs': {'bind': '/opt/sonarqube/logs', 'mode': 'rw'} |
| 95 | + }, |
| 96 | + detach=True |
| 97 | + ) |
| 98 | + console.print("[green]SonarQube container started on port 9000.[/green]") |
| 99 | + self.wait_for_sonarqube() |
| 100 | + |
| 101 | + except Exception as e: |
| 102 | + console.print(f"[bold red]Failed to start SonarQube container: {e}[/bold red]") |
| 103 | + raise |
| 104 | + |
| 105 | + def wait_for_sonarqube(self, timeout: int = 180): |
| 106 | + """Waits for SonarQube API to become available.""" |
| 107 | + start_time = time.time() |
| 108 | + |
| 109 | + with console.status("[bold green]Waiting for SonarQube to initialize (this may take 1-2 minutes)...") as status: |
| 110 | + while time.time() - start_time < timeout: |
| 111 | + try: |
| 112 | + response = requests.get( |
| 113 | + f"{config.sonar_url}/api/system/status", |
| 114 | + timeout=5 |
| 115 | + ) |
| 116 | + if response.status_code == 200: |
| 117 | + data = response.json() |
| 118 | + if data.get("status") == "UP": |
| 119 | + console.print("[green]SonarQube is ready![/green]") |
| 120 | + return |
| 121 | + except requests.exceptions.RequestException: |
| 122 | + pass |
| 123 | + time.sleep(3) |
| 124 | + |
| 125 | + raise TimeoutError("SonarQube failed to start within the timeout period.") |
| 126 | + |
| 127 | + def ensure_sonarqube(self): |
| 128 | + """Ensures SonarQube is running and ready.""" |
| 129 | + if not self.is_available(): |
| 130 | + raise RuntimeError("Docker is not available.") |
| 131 | + |
| 132 | + self.start_sonarqube() |
| 133 | + |
| 134 | + def run_scan(self, target_dir: str): |
| 135 | + """Runs the SonarQube scanner on the target directory.""" |
| 136 | + if not self.is_available(): |
| 137 | + raise RuntimeError("Docker is not available.") |
| 138 | + |
| 139 | + target_dir = os.path.abspath(target_dir) |
| 140 | + self.pull_image(self.SCANNER_IMAGE) |
| 141 | + |
| 142 | + console.print(f"[yellow]Running SonarQube Scan on {target_dir}...[/yellow]") |
| 143 | + |
| 144 | + try: |
| 145 | + # Run sonar-scanner container linked to SonarQube |
| 146 | + self.client.containers.run( |
| 147 | + self.SCANNER_IMAGE, |
| 148 | + remove=True, |
| 149 | + volumes={target_dir: {'bind': '/usr/src', 'mode': 'rw'}}, |
| 150 | + environment={ |
| 151 | + 'SONAR_HOST_URL': f'http://{self.CONTAINER_NAME}:9000', |
| 152 | + 'SONAR_TOKEN': config.sonar_token, |
| 153 | + } if config.sonar_token else { |
| 154 | + 'SONAR_HOST_URL': f'http://{self.CONTAINER_NAME}:9000', |
| 155 | + 'SONAR_LOGIN': config.sonar_login, |
| 156 | + 'SONAR_PASSWORD': config.sonar_password |
| 157 | + }, |
| 158 | + links={self.CONTAINER_NAME: self.CONTAINER_NAME}, |
| 159 | + command=['-Dsonar.projectKey=secuscan_project', '-Dsonar.sources=.', '-Dsonar.java.binaries=.'] |
| 160 | + ) |
| 161 | + console.print("[green]SonarQube Scan completed successfully.[/green]") |
| 162 | + console.print(f"Results available at: {config.sonar_url}/dashboard?id=secuscan_project") |
| 163 | + |
| 164 | + except docker.errors.ContainerError as e: |
| 165 | + console.print(f"[bold red]SonarQube Scanner failed: {e}[/bold red]") |
| 166 | + except Exception as e: |
| 167 | + console.print(f"[bold red]Error running SonarQube scan: {e}[/bold red]") |
0 commit comments