|
| 1 | +package com.redhat.podmortem.ai.service; |
| 2 | + |
| 3 | +import com.redhat.podmortem.common.model.analysis.AnalysisResult; |
| 4 | +import com.redhat.podmortem.common.model.provider.*; |
| 5 | +import io.smallrye.mutiny.Uni; |
| 6 | +import jakarta.enterprise.context.ApplicationScoped; |
| 7 | +import jakarta.inject.Inject; |
| 8 | +import java.time.Duration; |
| 9 | +import java.time.Instant; |
| 10 | +import java.time.temporal.ChronoUnit; |
| 11 | +import java.util.List; |
| 12 | +import java.util.stream.Collectors; |
| 13 | +import org.eclipse.microprofile.faulttolerance.CircuitBreaker; |
| 14 | +import org.eclipse.microprofile.faulttolerance.Fallback; |
| 15 | +import org.eclipse.microprofile.faulttolerance.Retry; |
| 16 | +import org.eclipse.microprofile.faulttolerance.Timeout; |
| 17 | +import org.jboss.logging.Logger; |
| 18 | + |
| 19 | +@ApplicationScoped |
| 20 | +public class AnalysisService { |
| 21 | + |
| 22 | + private static final Logger LOG = Logger.getLogger(AnalysisService.class); |
| 23 | + |
| 24 | + @Inject ProviderRegistry providerRegistry; |
| 25 | + |
| 26 | + @CircuitBreaker( |
| 27 | + requestVolumeThreshold = 10, |
| 28 | + failureRatio = 0.5, |
| 29 | + successThreshold = 3, |
| 30 | + delay = 5000) |
| 31 | + @Retry(maxRetries = 3, delay = 1000) |
| 32 | + @Timeout(value = 30, unit = ChronoUnit.SECONDS) |
| 33 | + public Uni<AIResponse> analyzeFailure( |
| 34 | + AnalysisResult analysisResult, AIProviderConfig providerConfig) { |
| 35 | + LOG.infof( |
| 36 | + "Starting AI analysis for analysis ID: %s using provider: %s", |
| 37 | + analysisResult.getAnalysisId(), providerConfig.getProviderId()); |
| 38 | + |
| 39 | + try { |
| 40 | + // get the AI provider implementation from ai-provider-lib |
| 41 | + AIProvider provider = providerRegistry.getProvider(providerConfig.getProviderId()); |
| 42 | + |
| 43 | + return provider.generateExplanation(analysisResult, providerConfig) |
| 44 | + .map(response -> enrichResponse(response, analysisResult)) |
| 45 | + .onFailure() |
| 46 | + .invoke( |
| 47 | + throwable -> |
| 48 | + LOG.errorf( |
| 49 | + throwable, |
| 50 | + "AI provider call failed for provider: %s", |
| 51 | + providerConfig.getProviderId())); |
| 52 | + |
| 53 | + } catch (Exception e) { |
| 54 | + LOG.errorf(e, "Failed to get AI provider: %s", providerConfig.getProviderId()); |
| 55 | + return Uni.createFrom().failure(e); |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + @Fallback(fallbackMethod = "generateFallbackExplanation") |
| 60 | + public Uni<AIResponse> protectedAnalyzeFailure( |
| 61 | + AnalysisResult analysisResult, AIProviderConfig providerConfig) { |
| 62 | + return analyzeFailure(analysisResult, providerConfig); |
| 63 | + } |
| 64 | + |
| 65 | + public Uni<AIResponse> generateFallbackExplanation( |
| 66 | + AnalysisResult analysisResult, AIProviderConfig providerConfig) { |
| 67 | + LOG.warnf("Using fallback explanation for analysis ID: %s", analysisResult.getAnalysisId()); |
| 68 | + |
| 69 | + // basic explanation based on analysis results when AI is unavailable |
| 70 | + String fallbackExplanation = buildBasicExplanation(analysisResult); |
| 71 | + |
| 72 | + AIResponse fallbackResponse = new AIResponse(); |
| 73 | + fallbackResponse.setExplanation(fallbackExplanation); |
| 74 | + fallbackResponse.setProviderId("fallback"); |
| 75 | + fallbackResponse.setModelId("pattern-based"); |
| 76 | + fallbackResponse.setGeneratedAt(Instant.now()); |
| 77 | + fallbackResponse.setProcessingTime(Duration.ofMillis(100)); |
| 78 | + fallbackResponse.setConfidence(0.6); // Lower confidence for fallback |
| 79 | + |
| 80 | + return Uni.createFrom().item(fallbackResponse); |
| 81 | + } |
| 82 | + |
| 83 | + public Uni<List<String>> getAvailableProviders() { |
| 84 | + return Uni.createFrom() |
| 85 | + .item( |
| 86 | + providerRegistry.getAllProviders().stream() |
| 87 | + .map(AIProvider::getProviderId) |
| 88 | + .collect(Collectors.toList())); |
| 89 | + } |
| 90 | + |
| 91 | + public Uni<ValidationResult> validateProvider(AIProviderConfig config) { |
| 92 | + try { |
| 93 | + AIProvider provider = providerRegistry.getProvider(config.getProviderId()); |
| 94 | + return provider.validateConfiguration(config); |
| 95 | + } catch (Exception e) { |
| 96 | + ValidationResult result = new ValidationResult(); |
| 97 | + result.setValid(false); |
| 98 | + result.setProviderId(config.getProviderId()); |
| 99 | + result.setMessage("Provider not found: " + e.getMessage()); |
| 100 | + return Uni.createFrom().item(result); |
| 101 | + } |
| 102 | + } |
| 103 | + |
| 104 | + private AIResponse enrichResponse(AIResponse response, AnalysisResult analysisResult) { |
| 105 | + // add any additional metadata or processing |
| 106 | + response.setGeneratedAt(Instant.now()); |
| 107 | + |
| 108 | + // add correlation with analysis metadata |
| 109 | + if (response.getMetadata() == null) { |
| 110 | + response.setMetadata( |
| 111 | + java.util.Map.of( |
| 112 | + "analysisId", |
| 113 | + analysisResult.getAnalysisId(), |
| 114 | + "eventCount", |
| 115 | + analysisResult.getEvents() != null |
| 116 | + ? analysisResult.getEvents().size() |
| 117 | + : 0)); |
| 118 | + } else { |
| 119 | + response.getMetadata().put("analysisId", analysisResult.getAnalysisId()); |
| 120 | + response.getMetadata() |
| 121 | + .put( |
| 122 | + "eventCount", |
| 123 | + analysisResult.getEvents() != null |
| 124 | + ? analysisResult.getEvents().size() |
| 125 | + : 0); |
| 126 | + } |
| 127 | + |
| 128 | + return response; |
| 129 | + } |
| 130 | + |
| 131 | + private String buildBasicExplanation(AnalysisResult analysisResult) { |
| 132 | + StringBuilder explanation = new StringBuilder(); |
| 133 | + |
| 134 | + explanation.append("Pod failure analysis (pattern-based fallback): "); |
| 135 | + |
| 136 | + if (analysisResult.getEvents() != null && !analysisResult.getEvents().isEmpty()) { |
| 137 | + // Get the first critical event |
| 138 | + var firstEvent = analysisResult.getEvents().get(0); |
| 139 | + |
| 140 | + // Access pattern ID and severity through the matched pattern |
| 141 | + if (firstEvent.getMatchedPattern() != null) { |
| 142 | + String patternId = firstEvent.getMatchedPattern().getId(); |
| 143 | + String severity = firstEvent.getMatchedPattern().getSeverity(); |
| 144 | + |
| 145 | + explanation |
| 146 | + .append("The pod appears to have failed due to pattern '") |
| 147 | + .append(patternId != null ? patternId : "unknown") |
| 148 | + .append("' with severity ") |
| 149 | + .append(severity != null ? severity : "unknown") |
| 150 | + .append(". "); |
| 151 | + } else { |
| 152 | + explanation |
| 153 | + .append("The pod appears to have failed with score ") |
| 154 | + .append(firstEvent.getScore()) |
| 155 | + .append(" at line ") |
| 156 | + .append(firstEvent.getLineNumber()) |
| 157 | + .append(". "); |
| 158 | + } |
| 159 | + |
| 160 | + if (analysisResult.getEvents().size() > 1) { |
| 161 | + explanation |
| 162 | + .append("Additional ") |
| 163 | + .append(analysisResult.getEvents().size() - 1) |
| 164 | + .append(" event(s) were also detected."); |
| 165 | + } |
| 166 | + } else { |
| 167 | + explanation.append("No specific failure patterns were detected in the log analysis."); |
| 168 | + } |
| 169 | + |
| 170 | + return explanation.toString(); |
| 171 | + } |
| 172 | +} |
0 commit comments