@Override public boolean isValidWorkApiKey(String apiKey) { Users allUsers = loadUsers(); boolean validUser = allUsers.users.stream().anyMatch(u -> apiKey.equals(u.apikey)); _logger.infof("Authorizer: %s is %s valid API key\n", apiKey, validUser ? "a" : "NOT a"); return validUser; }
<JobT> void handleProcessingError( List<JobT> jobs, List<BatfishException> failureCauses, boolean haltOnProcessingError) { int numJobs = jobs.size(); int numFailed = failureCauses.size(); int numSucceeded = numJobs - numFailed; _logger.infof("%d jobs succeeded; %d jobs failed\n", numSucceeded, numFailed); if (haltOnProcessingError) { BatfishException e = new BatfishException(JOB_FAILURE_MESSAGE); failureCauses.forEach(e::addSuppressed); throw e; } }
public ParserRuleContext parse(BatfishCombinedParser<?, ?> parser, String filename) { _logger.infof("Parsing: \"%s\"...", filename); return parse(parser); }
/** Returns information about the given {@link Container}, provided this user can access it. */ @GET public Response getContainer() { _logger.infof("WMS2: getNetwork '%s'\n", _name); Container container = Main.getWorkMgr().getContainer(_name); return Response.ok(container).build(); }
private static void checkParentProcess(int ppid) { try { if (!isProcessRunning(ppid)) { _mainLogger.infof("Committing suicide; ppid %d is dead.\n", ppid); System.exit(0); } } catch (Exception e) { _mainLogger.errorf("Exception while checking parent process with pid: %s", ppid); } }
private void storeConfigurations( Path outputDir, String batchName, Map<String, Configuration> configurations) { _logger.infof("\n*** %s***\n", batchName.toUpperCase()); AtomicInteger progressCount = _newBatch.apply(batchName, configurations.size()); // Delete any existing output, then recreate. CommonUtil.deleteDirectory(outputDir); mkdirs(outputDir); configurations .entrySet() .parallelStream() .forEach( e -> { Path currentOutputPath = outputDir.resolve(e.getKey()); serializeObject(e.getValue(), currentOutputPath); progressCount.incrementAndGet(); }); }
@Override public boolean isAccessibleNetwork(String apiKey, String containerName, boolean logError) { Permissions allPerms = loadPermissions(); boolean allowed = accessAllowed(apiKey, containerName, allPerms); if (!allowed && logError) { _logger.infof("Authorizer: %s is NOT allowed to access %s\n", apiKey, containerName); } return allowed; }
@GET @Path(BfConsts.SVC_KILL_TASK_RSC) @Produces(MediaType.APPLICATION_JSON) public JSONArray killTask(@QueryParam(BfConsts.SVC_TASKID_KEY) String taskId) { _logger.infof("BFS:killTask %s\n", taskId); try { if (Strings.isNullOrEmpty(taskId)) { return new JSONArray(Arrays.asList(BfConsts.SVC_FAILURE_KEY, "taskid not supplied")); } Task task = Driver.killTask(taskId); String taskStr = BatfishObjectMapper.writePrettyString(task); return new JSONArray(Arrays.asList(BfConsts.SVC_SUCCESS_KEY, taskStr)); } catch (Exception e) { return new JSONArray(Arrays.asList(BfConsts.SVC_FAILURE_KEY, e.getMessage())); } }
@Override public synchronized void authorizeContainer(String apiKey, String containerName) { _logger.infof("Authorizing %s for %s\n", apiKey, containerName); Permissions perms = loadPermissions(); if (accessAllowed(apiKey, containerName, perms)) { _logger.infof("Authorizer: %s is already allowed to access %s\n", apiKey, containerName); return; } // Add the new permissions to the list and save them back to disk. Permission newPermission = new Permission(); newPermission.apikey = apiKey; newPermission.container = containerName; perms.perms.add(newPermission); savePermissions(perms); }
@GET @Path(BfConsts.SVC_GET_TASKSTATUS_RSC) @Produces(MediaType.APPLICATION_JSON) public JSONArray getTaskStatus(@QueryParam(BfConsts.SVC_TASKID_KEY) String taskId) { _logger.infof("BFS:getTaskStatus %s\n", taskId); try { if (taskId == null || taskId.equals("")) { return new JSONArray(Arrays.asList(BfConsts.SVC_FAILURE_KEY, "taskid not supplied")); } Task task = Driver.getTaskFromLog(taskId); if (task == null) { task = new Task(TaskStatus.Unknown); } String taskStr = BatfishObjectMapper.writePrettyString(task); return new JSONArray(Arrays.asList(BfConsts.SVC_SUCCESS_KEY, taskStr)); } catch (Exception e) { return new JSONArray(Arrays.asList(BfConsts.SVC_FAILURE_KEY, e.getMessage())); } }
private SortedMap<Path, String> readConfigurationFiles(Path testRigPath, String configsType) { _logger.infof("\n*** READING %s FILES ***\n", configsType); _logger.resetTimer(); SortedMap<Path, String> configurationData = new TreeMap<>(); Path configsPath = testRigPath.resolve(configsType); List<Path> configFilePaths = listAllFiles(configsPath); AtomicInteger completed = newBatch("Reading network configuration files", configFilePaths.size()); for (Path file : configFilePaths) { _logger.debugf("Reading: \"%s\"\n", file); String fileTextRaw = CommonUtil.readFile(file.toAbsolutePath()); String fileText = fileTextRaw + ((fileTextRaw.length() != 0) ? "\n" : ""); configurationData.put(file, fileText); completed.incrementAndGet(); } _logger.printElapsedTime(); return configurationData; }
/** Returns information about reference library in the network */ @GET public ReferenceLibraryBean getReferenceLibrary() { _logger.infof("WMS2: getReferenceLibrary '%s'\n", _network); try { return new ReferenceLibraryBean(Main.getWorkMgr().getReferenceLibrary(_network)); } catch (IOException e) { throw new InternalServerErrorException("ReferenceLibrary resource is corrupted"); } } }
@Override public ComputeDataPlaneResult computeDataPlane( Map<String, Configuration> configurations, Topology topology) { Set<BgpAdvertisement> externalAdverts = _batfish.loadExternalBgpAnnouncements(configurations); ComputeDataPlaneResult answer = _engine.computeDataPlane(configurations, topology, externalAdverts); double averageRoutes = ((IncrementalDataPlane) answer._dataPlane) .getNodes().values().stream() .flatMap(n -> n.getVirtualRouters().values().stream()) .mapToInt(vr -> vr._mainRib.getRoutes().size()) .average() .orElse(0.00d); _logger.infof( "Generated data-plane for testrig:%s; iterations:%s, avg entries per node:%.2f\n", _batfish.getTestrigName(), ((IncrementalBdpAnswerElement) answer._answerElement).getDependentRoutesIterations(), averageRoutes); return answer; }
@DELETE public Response delReferenceBook() { _logger.infof("WMS2: delReferenceBook '%s' '%s'\n", _container, _bookName); try { ReferenceLibrary library = Main.getWorkMgr().getReferenceLibrary(_container); library.delAddressBook(_bookName); ReferenceLibrary.write(library, Main.getWorkMgr().getReferenceLibraryPath(_container)); return Response.ok().build(); } catch (IOException e) { throw new InternalServerErrorException("Reference library is corrupted"); } catch (NoSuchElementException e) { throw new NotFoundException("Book not found: " + _bookName); } }
static void initAuthorizer() { Settings settings = getSettings(); Authorizer.Type type = settings.getAuthorizationType(); switch (type) { case none: _authorizer = NoneAuthorizer.INSTANCE; break; case file: _authorizer = FileAuthorizer.createFromSettings(settings); break; case database: _authorizer = DbAuthorizer.createFromSettings(settings); break; default: System.err.print( "org.batfish.coordinator: Initialization failed. Unsupported authorizer type " + type); System.exit(1); } getLogger().infof("Using authorizer %s\n", _authorizer); }
@GET public ReferenceBookBean getReferenceBook() { _logger.infof("WMS2: getReferenceBook: '%s' '%s'\n", _container, _bookName); try { return new ReferenceBookBean( Main.getWorkMgr() .getReferenceLibrary(_container) .getReferenceBook(_bookName) .orElseThrow( () -> new NotFoundException( String.format( "Reference book '%s' not found in container '%s'", _bookName, _container)))); } catch (IOException e) { throw new InternalServerErrorException("Reference library data is corrupted"); } } }
@POST @Path(CoordConsts.SVC_RSC_GET_QUESTION_TEMPLATES) @Produces(MediaType.APPLICATION_JSON) @Deprecated public JSONArray getQuestionTemplates(@FormDataParam(CoordConsts.SVC_KEY_API_KEY) String apiKey) { try { _logger.infof("WMS:getQuestionTemplates %s\n", apiKey); checkStringParam(apiKey, "API key"); checkApiKeyValidity(apiKey); Map<String, String> questionTemplates = Main.getQuestionTemplates(); if (questionTemplates == null) { return failureResponse("Question templates dir is not configured"); } else { return successResponse( new JSONObject().put(CoordConsts.SVC_KEY_QUESTION_LIST, questionTemplates)); } } catch (Exception e) { String stackTrace = Throwables.getStackTraceAsString(e); _logger.errorf("WMS:getQuestionTemplates exception: %s\n", stackTrace); return failureResponse(e.getMessage()); } }
@Nonnull private SortedMap<String, Configuration> parseConfigurationsAndApplyEnvironment() { _logger.infof("Repairing configurations for testrig %s", _testrigSettings.getName()); repairConfigurations(); SortedMap<String, Configuration> configurations = _storage.loadConfigurations(_settings.getContainer(), _testrigSettings.getName()); verify( configurations != null, "Configurations should not be null when loaded immediately after repair."); postProcessSnapshot(configurations); return configurations; }
/** Adds or updates a new {@link MinorIssueConfig} to the network's issue settings */ @POST public Response addIssueConfig(IssueConfigBean bean) { _logger.infof("WMS2: addIssueConfig '%s'\n", _network); if (bean.major == null) { throw new BadRequestException("IssueConfigBean must have a major type"); } if (bean.minor == null) { throw new BadRequestException("IssueConfigBean must have a minor type"); } try { MajorIssueConfig issueConfig = Main.getWorkMgr().getMajorIssueConfig(_network, bean.major); MajorIssueConfig updatedConfig = issueConfig.put(bean.toMinorIssueConfig()); Main.getWorkMgr().putMajorIssueConfig(_network, bean.major, updatedConfig); return Response.ok().build(); } catch (IOException e) { throw new InternalServerErrorException("Could not add the issue config", e); } }
/** Adds a new {@link ReferenceBook} to the network's {@link ReferenceLibrary} */ @POST public Response addReferenceBook(ReferenceBookBean referenceBookBean) { _logger.infof("WMS2: addReferenceBook '%s'\n", _network); if (referenceBookBean.name == null) { throw new BadRequestException("ReferenceBook must have a name"); } try { ReferenceLibrary library = Main.getWorkMgr().getReferenceLibrary(_network); if (library.getReferenceBook(referenceBookBean.name).isPresent()) { throw new BadRequestException("Duplicate bookname: " + referenceBookBean.name); } ReferenceLibrary.mergeReferenceBooks( Main.getWorkMgr().getReferenceLibraryPath(_network), ImmutableSortedSet.of(referenceBookBean.toAddressBook())); return Response.ok().build(); } catch (IOException e) { throw new InternalServerErrorException("ReferenceLibrary resource is corrupted"); } }