Search in sources :

Example 16 with ActiveSpan

use of io.opentracing.ActiveSpan in project batfish by batfish.

the class WorkMgr method killWork.

private boolean killWork(QueuedWork work, String worker) {
    Client client = null;
    boolean killed = false;
    SpanContext queueWorkSpan = work.getWorkItem().getSourceSpan();
    try (ActiveSpan killTaskSpan = GlobalTracer.get().buildSpan("Checking Task Status").addReference(References.FOLLOWS_FROM, queueWorkSpan).startActive()) {
        // avoid unused warning
        assert killTaskSpan != null;
        client = CommonUtil.createHttpClientBuilder(_settings.getSslPoolDisable(), _settings.getSslPoolTrustAllCerts(), _settings.getSslPoolKeystoreFile(), _settings.getSslPoolKeystorePassword(), _settings.getSslPoolTruststoreFile(), _settings.getSslPoolTruststorePassword()).build();
        String protocol = _settings.getSslPoolDisable() ? "http" : "https";
        WebTarget webTarget = client.target(String.format("%s://%s%s/%s", protocol, worker, BfConsts.SVC_BASE_RSC, BfConsts.SVC_KILL_TASK_RSC)).queryParam(BfConsts.SVC_TASKID_KEY, UriComponent.encode(work.getId().toString(), UriComponent.Type.QUERY_PARAM_SPACE_ENCODED));
        Response response = webTarget.request(MediaType.APPLICATION_JSON).get();
        if (response.getStatus() != Response.Status.OK.getStatusCode()) {
            _logger.errorf("WM:KillTask: Got non-OK response %s\n", response.getStatus());
        } else {
            try {
                String sobj = response.readEntity(String.class);
                JSONArray array = new JSONArray(sobj);
                _logger.infof("response: %s [%s] [%s]\n", array, array.get(0), array.get(1));
                if (!array.get(0).equals(BfConsts.SVC_SUCCESS_KEY)) {
                    _logger.errorf("Got error while killing task: %s %s\n", array.get(0), array.get(1));
                } else {
                    Task task = BatfishObjectMapper.mapper().readValue(array.getString(1), Task.class);
                    _workQueueMgr.processTaskCheckResult(work, task);
                    killed = true;
                }
            } catch (IllegalStateException e) {
                // can happen if the worker dies before we could finish reading; let's assume success
                _logger.infof("worker appears dead before response completion\n");
                Task fakeTask = new Task(TaskStatus.TerminatedByUser, "worker appears dead before responding");
                _workQueueMgr.processTaskCheckResult(work, fakeTask);
                killed = true;
            }
        }
    } catch (ProcessingException e) {
        _logger.errorf("unable to connect to %s: %s\n", worker, ExceptionUtils.getStackTrace(e));
    } catch (Exception e) {
        _logger.errorf("exception: %s\n", ExceptionUtils.getStackTrace(e));
    } finally {
        if (client != null) {
            client.close();
        }
    }
    return killed;
}
Also used : Response(javax.ws.rs.core.Response) Task(org.batfish.common.Task) SpanContext(io.opentracing.SpanContext) ActiveSpan(io.opentracing.ActiveSpan) JSONArray(org.codehaus.jettison.json.JSONArray) WebTarget(javax.ws.rs.client.WebTarget) Client(javax.ws.rs.client.Client) ProcessingException(javax.ws.rs.ProcessingException) BatfishException(org.batfish.common.BatfishException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) JSONException(org.codehaus.jettison.json.JSONException) ProcessingException(javax.ws.rs.ProcessingException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 17 with ActiveSpan

use of io.opentracing.ActiveSpan in project batfish by batfish.

the class Batfish method serializeAwsConfigs.

private Answer serializeAwsConfigs(Path testRigPath, Path outputPath) {
    Answer answer = new Answer();
    Map<Path, String> configurationData = readConfigurationFiles(testRigPath, BfConsts.RELPATH_AWS_CONFIGS_DIR);
    AwsConfiguration config;
    try (ActiveSpan parseAwsConfigsSpan = GlobalTracer.get().buildSpan("Parse AWS configs").startActive()) {
        // avoid unused warning
        assert parseAwsConfigsSpan != null;
        config = parseAwsConfigurations(configurationData);
    }
    _logger.info("\n*** SERIALIZING AWS CONFIGURATION STRUCTURES ***\n");
    _logger.resetTimer();
    outputPath.toFile().mkdirs();
    Path currentOutputPath = outputPath.resolve(BfConsts.RELPATH_AWS_CONFIGS_FILE);
    _logger.debugf("Serializing AWS to \"%s\"...", currentOutputPath);
    serializeObject(config, currentOutputPath);
    _logger.debug("OK\n");
    _logger.printElapsedTime();
    return answer;
}
Also used : Path(java.nio.file.Path) Answer(org.batfish.datamodel.answers.Answer) AwsConfiguration(org.batfish.representation.aws.AwsConfiguration) ActiveSpan(io.opentracing.ActiveSpan)

Example 18 with ActiveSpan

use of io.opentracing.ActiveSpan in project batfish by batfish.

the class Batfish method saveDataPlane.

/* Write the dataplane to disk and cache, and write the answer element to disk.
   */
private void saveDataPlane(DataPlane dataPlane, DataPlaneAnswerElement answerElement, boolean compressed) {
    Path dataPlanePath = compressed ? _testrigSettings.getEnvironmentSettings().getCompressedDataPlanePath() : _testrigSettings.getEnvironmentSettings().getDataPlanePath();
    Path answerElementPath = compressed ? _testrigSettings.getEnvironmentSettings().getCompressedDataPlaneAnswerPath() : _testrigSettings.getEnvironmentSettings().getDataPlaneAnswerPath();
    Cache<TestrigSettings, DataPlane> cache = compressed ? _cachedCompressedDataPlanes : _cachedDataPlanes;
    cache.put(_testrigSettings, dataPlane);
    _logger.resetTimer();
    newBatch("Writing data plane to disk", 0);
    try (ActiveSpan writeDataplane = GlobalTracer.get().buildSpan("Writing data plane").startActive()) {
        // avoid unused warning
        assert writeDataplane != null;
        serializeObject(dataPlane, dataPlanePath);
        serializeObject(answerElement, answerElementPath);
    }
    _logger.printElapsedTime();
}
Also used : Path(java.nio.file.Path) DataPlane(org.batfish.datamodel.DataPlane) ActiveSpan(io.opentracing.ActiveSpan) TestrigSettings(org.batfish.config.Settings.TestrigSettings)

Example 19 with ActiveSpan

use of io.opentracing.ActiveSpan in project batfish by batfish.

the class Driver method runBatfishThroughService.

public static List<String> runBatfishThroughService(final String taskId, String[] args) {
    final Settings settings;
    try {
        settings = new Settings(_mainSettings);
        settings.setRunMode(RunMode.WORKER);
        settings.parseCommandLine(args);
        // assign taskId for status updates, termination requests
        settings.setTaskId(taskId);
    } catch (Exception e) {
        return Arrays.asList("failure", "Initialization failed: " + ExceptionUtils.getStackTrace(e));
    }
    try {
        Batfish.initTestrigSettings(settings);
    } catch (Exception e) {
        return Arrays.asList("failure", "Failed while applying auto basedir. (All arguments are supplied?): " + e.getMessage());
    }
    if (settings.canExecute()) {
        if (claimIdle()) {
            try {
                final BatfishLogger jobLogger = new BatfishLogger(settings.getLogLevel(), settings.getTimestamp(), settings.getLogFile(), settings.getLogTee(), false);
                settings.setLogger(jobLogger);
                final Task task = new Task(args);
                logTask(taskId, task);
                @Nullable SpanContext runTaskSpanContext = GlobalTracer.get().activeSpan() == null ? null : GlobalTracer.get().activeSpan().context();
                // run batfish on a new thread and set idle to true when done
                Thread thread = new Thread() {

                    @Override
                    public void run() {
                        try (ActiveSpan runBatfishSpan = GlobalTracer.get().buildSpan("Initialize Batfish in a new thread").addReference(References.FOLLOWS_FROM, runTaskSpanContext).startActive()) {
                            // avoid unused warning
                            assert runBatfishSpan != null;
                            task.setStatus(TaskStatus.InProgress);
                            String errMsg = runBatfish(settings);
                            if (errMsg == null) {
                                task.setStatus(TaskStatus.TerminatedNormally);
                            } else {
                                task.setStatus(TaskStatus.TerminatedAbnormally);
                                task.setErrMessage(errMsg);
                            }
                            task.setTerminated(new Date());
                            jobLogger.close();
                            makeIdle();
                        }
                    }
                };
                thread.start();
                return Arrays.asList(BfConsts.SVC_SUCCESS_KEY, "running now");
            } catch (Exception e) {
                _mainLogger.error("Exception while running task: " + e.getMessage());
                makeIdle();
                return Arrays.asList(BfConsts.SVC_FAILURE_KEY, e.getMessage());
            }
        } else {
            return Arrays.asList(BfConsts.SVC_FAILURE_KEY, "Not idle");
        }
    } else {
        return Arrays.asList(BfConsts.SVC_FAILURE_KEY, "Non-executable command");
    }
}
Also used : Task(org.batfish.common.Task) SpanContext(io.opentracing.SpanContext) BatfishLogger(org.batfish.common.BatfishLogger) ActiveSpan(io.opentracing.ActiveSpan) EnvironmentSettings(org.batfish.config.Settings.EnvironmentSettings) Settings(org.batfish.config.Settings) TestrigSettings(org.batfish.config.Settings.TestrigSettings) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) ProcessingException(javax.ws.rs.ProcessingException) QuestionException(org.batfish.common.QuestionException) BatfishException(org.batfish.common.BatfishException) IOException(java.io.IOException) CleanBatfishException(org.batfish.common.CleanBatfishException) Nullable(javax.annotation.Nullable) Date(java.util.Date)

Example 20 with ActiveSpan

use of io.opentracing.ActiveSpan in project batfish by batfish.

the class WorkItemTest method testInjectExtract.

@Test
public void testInjectExtract() {
    MockContext sourceContext;
    try (ActiveSpan activeSpan = _mockTracer.buildSpan("test span").startActive()) {
        SpanContext sourceContextTmp = activeSpan.context();
        assertThat(sourceContextTmp, instanceOf(MockContext.class));
        sourceContext = (MockContext) sourceContextTmp;
        _workItem.setSourceSpan(activeSpan, _mockTracer);
    }
    SpanContext extractedContextTmp = _workItem.getSourceSpan(_mockTracer);
    assertThat(extractedContextTmp, notNullValue());
    assertThat(extractedContextTmp, instanceOf(MockContext.class));
    MockContext extractedContext = (MockContext) extractedContextTmp;
    // test that injected and extracted spans have same span context data
    assertThat(extractedContext.traceId(), equalTo(sourceContext.traceId()));
    assertThat(extractedContext.spanId(), equalTo(sourceContext.spanId()));
}
Also used : MockContext(io.opentracing.mock.MockSpan.MockContext) SpanContext(io.opentracing.SpanContext) ThreadLocalActiveSpan(io.opentracing.util.ThreadLocalActiveSpan) ActiveSpan(io.opentracing.ActiveSpan) NoopActiveSpan(io.opentracing.NoopActiveSpanSource.NoopActiveSpan) Test(org.junit.Test)

Aggregations

ActiveSpan (io.opentracing.ActiveSpan)24 BatfishException (org.batfish.common.BatfishException)12 SpanContext (io.opentracing.SpanContext)10 IOException (java.io.IOException)8 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)7 NoopActiveSpan (io.opentracing.NoopActiveSpanSource.NoopActiveSpan)6 ThreadLocalActiveSpan (io.opentracing.util.ThreadLocalActiveSpan)6 Path (java.nio.file.Path)6 CleanBatfishException (org.batfish.common.CleanBatfishException)6 JSONException (org.codehaus.jettison.json.JSONException)6 Test (org.junit.Test)6 ProcessingException (javax.ws.rs.ProcessingException)5 Answer (org.batfish.datamodel.answers.Answer)5 TreeMap (java.util.TreeMap)4 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)4 Nullable (javax.annotation.Nullable)4 BatfishLogger (org.batfish.common.BatfishLogger)4 JSONArray (org.codehaus.jettison.json.JSONArray)4 ImmutableSortedSet (com.google.common.collect.ImmutableSortedSet)3 LinkedHashSet (java.util.LinkedHashSet)3