| 
 | 1 | +package com.walmartlabs.concord.plugins.codecoverage;  | 
 | 2 | + | 
 | 3 | +/*-  | 
 | 4 | + * *****  | 
 | 5 | + * Concord  | 
 | 6 | + * -----  | 
 | 7 | + * Copyright (C) 2017 - 2024 Walmart Inc.  | 
 | 8 | + * -----  | 
 | 9 | + * Licensed under the Apache License, Version 2.0 (the "License");  | 
 | 10 | + * you may not use this file except in compliance with the License.  | 
 | 11 | + * You may obtain a copy of the License at  | 
 | 12 | + *  | 
 | 13 | + *      http://www.apache.org/licenses/LICENSE-2.0  | 
 | 14 | + *  | 
 | 15 | + * Unless required by applicable law or agreed to in writing, software  | 
 | 16 | + * distributed under the License is distributed on an "AS IS" BASIS,  | 
 | 17 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  | 
 | 18 | + * See the License for the specific language governing permissions and  | 
 | 19 | + * limitations under the License.  | 
 | 20 | + * =====  | 
 | 21 | + */  | 
 | 22 | + | 
 | 23 | +import com.walmartlabs.concord.common.IOUtils;  | 
 | 24 | +import com.walmartlabs.concord.runtime.v2.ProcessDefinitionUtils;  | 
 | 25 | +import com.walmartlabs.concord.runtime.v2.model.FlowCall;  | 
 | 26 | +import com.walmartlabs.concord.runtime.v2.model.ProcessDefinition;  | 
 | 27 | +import com.walmartlabs.concord.runtime.v2.model.Step;  | 
 | 28 | +import com.walmartlabs.concord.runtime.v2.runner.PersistenceService;  | 
 | 29 | +import com.walmartlabs.concord.runtime.v2.runner.vm.ElementEventProducer;  | 
 | 30 | +import com.walmartlabs.concord.runtime.v2.runner.vm.FlowCallCommand;  | 
 | 31 | +import com.walmartlabs.concord.runtime.v2.runner.vm.TaskCallCommand;  | 
 | 32 | +import com.walmartlabs.concord.runtime.v2.sdk.WorkingDirectory;  | 
 | 33 | +import com.walmartlabs.concord.svm.*;  | 
 | 34 | +import com.walmartlabs.concord.svm.Runtime;  | 
 | 35 | +import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;  | 
 | 36 | +import org.slf4j.Logger;  | 
 | 37 | +import org.slf4j.LoggerFactory;  | 
 | 38 | + | 
 | 39 | +import javax.inject.Inject;  | 
 | 40 | +import java.io.IOException;  | 
 | 41 | +import java.nio.file.Files;  | 
 | 42 | +import java.nio.file.Path;  | 
 | 43 | +import java.nio.file.StandardOpenOption;  | 
 | 44 | +import java.util.Objects;  | 
 | 45 | +import java.util.stream.Collectors;  | 
 | 46 | + | 
 | 47 | +public class CodeCoverage implements ExecutionListener {  | 
 | 48 | + | 
 | 49 | +    public static final Logger log = LoggerFactory.getLogger(CodeCoverage.class);  | 
 | 50 | + | 
 | 51 | +    private static final String COVERAGE_INFO_FILENAME = "coverage.info";  | 
 | 52 | +    private static final String FLOWS_FILENAME = "flows.zip";  | 
 | 53 | + | 
 | 54 | +    private final StepsRecorder steps;  | 
 | 55 | +    private final PersistenceService persistenceService;  | 
 | 56 | +    private final Path workDir;  | 
 | 57 | + | 
 | 58 | +    @Inject  | 
 | 59 | +    public CodeCoverage(StepsRecorder steps, PersistenceService persistenceService, WorkingDirectory workingDirectory) {  | 
 | 60 | +        this.steps = steps;  | 
 | 61 | +        this.persistenceService = persistenceService;  | 
 | 62 | +        this.workDir = workingDirectory.getValue();  | 
 | 63 | +    }  | 
 | 64 | + | 
 | 65 | +    @Override  | 
 | 66 | +    public void beforeProcessStart(Runtime runtime, State state) {  | 
 | 67 | +        saveFlows(runtime.getService(ProcessDefinition.class));  | 
 | 68 | +    }  | 
 | 69 | + | 
 | 70 | +    @Override  | 
 | 71 | +    public Result beforeCommand(Runtime runtime, VM vm, State state, ThreadId threadId, Command cmd) {  | 
 | 72 | +        // we need the name of the flow, so we can handle the call step only in `afterCommand`  | 
 | 73 | +        if (cmd instanceof FlowCallCommand) {  | 
 | 74 | +            return Result.CONTINUE;  | 
 | 75 | +        }  | 
 | 76 | + | 
 | 77 | +        if (cmd instanceof ElementEventProducer eep) {  | 
 | 78 | +            processStep(eep.getStep(), runtime, state, threadId);  | 
 | 79 | +        } else if (cmd instanceof TaskCallCommand tcc) {  | 
 | 80 | +            processStep(tcc.getStep(), runtime, state, threadId);  | 
 | 81 | +        }  | 
 | 82 | + | 
 | 83 | +        return Result.CONTINUE;  | 
 | 84 | +    }  | 
 | 85 | + | 
 | 86 | +    @Override  | 
 | 87 | +    public Result afterCommand(Runtime runtime, VM vm, State state, ThreadId threadId, Command cmd) {  | 
 | 88 | +        if (cmd instanceof FlowCallCommand fcc) {  | 
 | 89 | +            processStep(fcc.getStep(), runtime, state, threadId);  | 
 | 90 | +        }  | 
 | 91 | +        return Result.CONTINUE;  | 
 | 92 | +    }  | 
 | 93 | + | 
 | 94 | +    private void processStep(Step step, Runtime runtime, State state, ThreadId threadId) {  | 
 | 95 | +        var loc = step.getLocation();  | 
 | 96 | +        if (loc == null || loc.lineNum() < 0 || loc.fileName() == null) {  | 
 | 97 | +            return;  | 
 | 98 | +        }  | 
 | 99 | + | 
 | 100 | +        var pd = runtime.getService(ProcessDefinition.class);  | 
 | 101 | + | 
 | 102 | +        steps.record(StepInfo.builder()  | 
 | 103 | +                .fileName(Objects.requireNonNull(loc.fileName()))  | 
 | 104 | +                .line(loc.lineNum())  | 
 | 105 | +                .processDefinitionId(ProcessDefinitionUtils.getCurrentFlowName(pd, step))  | 
 | 106 | +                .flowCallName(flowCallName(step, state, threadId))  | 
 | 107 | +                .build());  | 
 | 108 | +    }  | 
 | 109 | + | 
 | 110 | +    @Override  | 
 | 111 | +    public void onProcessError(Runtime runtime, State state, Exception e) {  | 
 | 112 | +        generateReport(runtime);  | 
 | 113 | +    }  | 
 | 114 | + | 
 | 115 | +    @Override  | 
 | 116 | +    public void afterProcessEnds(Runtime runtime, State state, Frame lastFrame) {  | 
 | 117 | +        if (isSuspended(state)) {  | 
 | 118 | +            return;  | 
 | 119 | +        }  | 
 | 120 | + | 
 | 121 | +        generateReport(runtime);  | 
 | 122 | +    }  | 
 | 123 | + | 
 | 124 | +    private void generateReport(Runtime runtime) {  | 
 | 125 | +        log.info("Generating code coverage info...");  | 
 | 126 | + | 
 | 127 | +        try {  | 
 | 128 | +            var reportProducer = new LcovReportProducer(runtime.getService(ProcessDefinition.class));  | 
 | 129 | +            reportProducer.onSteps(steps.list());  | 
 | 130 | + | 
 | 131 | +            steps.cleanup();  | 
 | 132 | + | 
 | 133 | +            persistenceService.persistFile(COVERAGE_INFO_FILENAME, reportProducer::produce, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);  | 
 | 134 | +        } catch (Exception e) {  | 
 | 135 | +            throw new RuntimeException("Can't generate code coverage report", e);  | 
 | 136 | +        }  | 
 | 137 | + | 
 | 138 | +        log.info("Coverage info saved as attachment with name '{}'", COVERAGE_INFO_FILENAME);  | 
 | 139 | +    }  | 
 | 140 | + | 
 | 141 | +    private static boolean isSuspended(State state) {  | 
 | 142 | +        return state.threadStatus().entrySet().stream()  | 
 | 143 | +                .anyMatch(e -> e.getValue() == ThreadStatus.SUSPENDED);  | 
 | 144 | +    }  | 
 | 145 | + | 
 | 146 | +    private static String flowCallName(Step step, State state, ThreadId threadId) {  | 
 | 147 | +        if (step instanceof FlowCall) {  | 
 | 148 | +            return FlowCallCommand.getFlowName(state, threadId);  | 
 | 149 | +        }  | 
 | 150 | +        return null;  | 
 | 151 | +    }  | 
 | 152 | + | 
 | 153 | +    private void saveFlows(ProcessDefinition processDefinition) {  | 
 | 154 | +        var fileNames = processDefinition.flows().values().stream()  | 
 | 155 | +                .map(v -> v.location().fileName())  | 
 | 156 | +                .filter(Objects::nonNull)  | 
 | 157 | +                .collect(Collectors.toSet());  | 
 | 158 | + | 
 | 159 | +        persistenceService.persistFile(FLOWS_FILENAME, out -> {  | 
 | 160 | +            try (ZipArchiveOutputStream zip = new ZipArchiveOutputStream(out)) {  | 
 | 161 | + | 
 | 162 | +                for (var fileName : fileNames) {  | 
 | 163 | +                    var file = workDir.resolve(fileName);  | 
 | 164 | +                    if (Files.notExists(file)) {  | 
 | 165 | +                        log.warn("CodeCoverage: can't save flow '{}' -> file not exists. This is most likely a bug", fileName);  | 
 | 166 | +                        continue;  | 
 | 167 | +                    }  | 
 | 168 | + | 
 | 169 | +                    try {  | 
 | 170 | +                        IOUtils.zipFile(zip, file, fileName);  | 
 | 171 | +                    } catch (IOException ex) {  | 
 | 172 | +                        log.error("CodeCoverage: failed to add file '{}'. Error: {}", fileName, ex.getMessage());  | 
 | 173 | +                        throw ex;  | 
 | 174 | +                    }  | 
 | 175 | +                }  | 
 | 176 | +            }  | 
 | 177 | +        });  | 
 | 178 | +        log.debug("CodeCoverage: flows saved as '{}' process attachment", FLOWS_FILENAME);  | 
 | 179 | +    }  | 
 | 180 | +}  | 
0 commit comments