Search in sources :

Example 11 with ClientId

use of io.datarouter.storage.client.ClientId in project datarouter by hotpads.

the class S3WebInspector method buildBucketTable.

private ContainerTag<?> buildBucketTable(String contextPath, ClientId clientId) {
    DatarouterS3Client client = s3ClientManager.getClient(clientId);
    List<S3BucketDto> buckets = client.scanBuckets().parallel(new ParallelScannerContext(bucketRegionExecutor, bucketRegionExecutor.getMaximumPoolSize(), true)).map(bucket -> {
        // RPC
        Region region = client.getBucketRegion(bucket.name());
        return new S3BucketDto(clientId.getName(), bucket.name(), region, bucket.creationDate());
    }).sort(Comparator.comparing(bucket -> bucket.bucketName.toLowerCase())).list();
    var table = new J2HtmlTable<S3BucketDto>().withClasses("sortable table table-sm table-striped my-4 border").withHtmlColumn("Name", bucket -> {
        String href = new URIBuilder().setPath(contextPath + paths.datarouter.clients.awsS3.listObjects.toSlashedString()).addParameter(S3BucketHandler.P_client, bucket.clientName).addParameter(S3BucketHandler.P_bucket, bucket.bucketName).addParameter(S3BucketHandler.P_delimiter, "/").toString();
        return td(a(bucket.bucketName).withHref(href));
    }).withColumn("Region", bucket -> bucket.region).withColumn("Created", bucket -> bucket.creationDate).build(buckets);
    return div(h4("Buckets - " + buckets.size()), table).withClass("container-fluid my-4").withStyle("padding-left: 0px");
}
Also used : Scanner(io.datarouter.scanner.Scanner) DatarouterWebRequestParamsFactory(io.datarouter.web.browse.dto.DatarouterWebRequestParamsFactory) DatarouterS3Client(io.datarouter.aws.s3.DatarouterS3Client) S3BucketHandler(io.datarouter.aws.s3.web.S3BucketHandler) ParallelScannerContext(io.datarouter.scanner.ParallelScannerContext) ClientOptions(io.datarouter.storage.client.ClientOptions) TagCreator.h4(j2html.TagCreator.h4) Inject(javax.inject.Inject) HttpServletRequest(javax.servlet.http.HttpServletRequest) MessageMav(io.datarouter.web.handler.mav.imp.MessageMav) DatarouterWebRequireJsV2(io.datarouter.web.requirejs.DatarouterWebRequireJsV2) Map(java.util.Map) S3Node(io.datarouter.aws.s3.node.S3Node) ClientId(io.datarouter.storage.client.ClientId) DatarouterNodes(io.datarouter.storage.node.DatarouterNodes) Params(io.datarouter.web.handler.params.Params) Region(software.amazon.awssdk.regions.Region) J2HtmlTable(io.datarouter.web.html.j2html.J2HtmlTable) BucketRegionExecutor(io.datarouter.aws.s3.config.DatarouterAwsS3Executors.BucketRegionExecutor) NodeTool(io.datarouter.storage.node.NodeTool) DatarouterClientWebInspector(io.datarouter.web.browse.DatarouterClientWebInspector) URIBuilder(org.apache.http.client.utils.URIBuilder) DatarouterAwsS3Paths(io.datarouter.aws.s3.config.DatarouterAwsS3Paths) Mav(io.datarouter.web.handler.mav.Mav) Instant(java.time.Instant) TagCreator.a(j2html.TagCreator.a) ContainerTag(j2html.tags.ContainerTag) S3ClientType(io.datarouter.aws.s3.S3ClientType) List(java.util.List) TagCreator.td(j2html.TagCreator.td) Bootstrap4PageFactory(io.datarouter.web.html.j2html.bootstrap4.Bootstrap4PageFactory) Comparator(java.util.Comparator) TagCreator.div(j2html.TagCreator.div) DatarouterS3Client(io.datarouter.aws.s3.DatarouterS3Client) ParallelScannerContext(io.datarouter.scanner.ParallelScannerContext) Region(software.amazon.awssdk.regions.Region) URIBuilder(org.apache.http.client.utils.URIBuilder)

Example 12 with ClientId

use of io.datarouter.storage.client.ClientId in project datarouter by hotpads.

the class BaseSchemaUpdateService method acquireSchemaUpdateLock.

private boolean acquireSchemaUpdateLock(Map<ClientId, List<String>> printedSchemaUpdates) {
    if (printedSchemaUpdates.isEmpty()) {
        return false;
    }
    String statement = printedSchemaUpdates.entrySet().stream().findFirst().map(entry -> String.join("\n\n", entry.getValue())).get();
    Instant now = Instant.now();
    Integer build = Optional.ofNullable(buildId).filter(buildId -> !"${env.BUILD_NUMBER}".equals(buildId)).or(() -> Optional.ofNullable(BUILD_NUMBER)).map(Integer::valueOf).orElseGet(() -> (int) now.getEpochSecond());
    ClusterSchemaUpdateLock lock = new ClusterSchemaUpdateLock(build, statement, serverName.get(), now);
    try {
        schemaUpdateLockDao.get().putAndAcquire(lock);
        logger.warn("Acquired schema update lock for hash={}", lock.getKey().getStatementHash());
        return true;
    } catch (Exception ex) {
        logger.warn("Didn't acquire schema update lock for hash={}", lock.getKey().getStatementHash());
        return false;
    }
}
Also used : Provider(javax.inject.Provider) LoggerFactory(org.slf4j.LoggerFactory) ClusterSchemaUpdateLock(io.datarouter.storage.config.storage.clusterschemaupdatelock.ClusterSchemaUpdateLock) PhysicalNode(io.datarouter.storage.node.type.physical.PhysicalNode) HashMap(java.util.HashMap) Callable(java.util.concurrent.Callable) DatarouterClusterSchemaUpdateLockDao(io.datarouter.storage.config.storage.clusterschemaupdatelock.DatarouterClusterSchemaUpdateLockDao) ServerName(io.datarouter.storage.config.properties.ServerName) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) ChangelogRecorder(io.datarouter.instrumentation.changelog.ChangelogRecorder) Future(java.util.concurrent.Future) MutableString(io.datarouter.util.mutable.MutableString) Map(java.util.Map) ClientId(io.datarouter.storage.client.ClientId) AdminEmail(io.datarouter.storage.config.properties.AdminEmail) DatarouterSchemaUpdateScheduler(io.datarouter.storage.config.executor.DatarouterStorageExecutors.DatarouterSchemaUpdateScheduler) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) DatarouterChangelogDtoBuilder(io.datarouter.instrumentation.changelog.ChangelogRecorder.DatarouterChangelogDtoBuilder) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Instant(java.time.Instant) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) EnvironmentName(io.datarouter.storage.config.properties.EnvironmentName) Optional(java.util.Optional) SingletonSupplier(io.datarouter.util.singletonsupplier.SingletonSupplier) Collections(java.util.Collections) ClusterSchemaUpdateLock(io.datarouter.storage.config.storage.clusterschemaupdatelock.ClusterSchemaUpdateLock) Instant(java.time.Instant) MutableString(io.datarouter.util.mutable.MutableString) ExecutionException(java.util.concurrent.ExecutionException)

Example 13 with ClientId

use of io.datarouter.storage.client.ClientId in project datarouter by hotpads.

the class BaseSchemaUpdateService method gatherSchemaUpdates.

public synchronized void gatherSchemaUpdates(boolean wait) {
    boolean shouldNotify = true;
    Map<ClientId, List<String>> printedSchemaUpdates = new HashMap<>();
    Iterator<Future<Optional<SchemaUpdateResult>>> futureIterator = futures.iterator();
    MutableString oneStartupBlockReason = new MutableString("");
    while (futureIterator.hasNext()) {
        Future<Optional<SchemaUpdateResult>> future = futureIterator.next();
        if (wait || future.isDone()) {
            try {
                Optional<SchemaUpdateResult> optional = future.get();
                if (optional.isEmpty()) {
                    continue;
                }
                printedSchemaUpdates.computeIfAbsent(optional.get().clientId, $ -> new ArrayList<>()).add(optional.get().ddl);
                optional.get().startupBlockReason.ifPresent(oneStartupBlockReason::set);
            } catch (InterruptedException | ExecutionException e) {
                logger.error("", e);
                throw new RuntimeException(e);
            }
            futureIterator.remove();
        } else {
            shouldNotify = false;
        }
    }
    if (shouldNotify && acquireSchemaUpdateLock(printedSchemaUpdates)) {
        sendEmail(printedSchemaUpdates, !oneStartupBlockReason.getString().isEmpty());
        recordChangelog(printedSchemaUpdates);
    }
    if (!oneStartupBlockReason.getString().isEmpty()) {
        logger.error(oneStartupBlockReason.getString());
        throw new RuntimeException(oneStartupBlockReason.getString());
    }
}
Also used : Provider(javax.inject.Provider) LoggerFactory(org.slf4j.LoggerFactory) ClusterSchemaUpdateLock(io.datarouter.storage.config.storage.clusterschemaupdatelock.ClusterSchemaUpdateLock) PhysicalNode(io.datarouter.storage.node.type.physical.PhysicalNode) HashMap(java.util.HashMap) Callable(java.util.concurrent.Callable) DatarouterClusterSchemaUpdateLockDao(io.datarouter.storage.config.storage.clusterschemaupdatelock.DatarouterClusterSchemaUpdateLockDao) ServerName(io.datarouter.storage.config.properties.ServerName) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) ChangelogRecorder(io.datarouter.instrumentation.changelog.ChangelogRecorder) Future(java.util.concurrent.Future) MutableString(io.datarouter.util.mutable.MutableString) Map(java.util.Map) ClientId(io.datarouter.storage.client.ClientId) AdminEmail(io.datarouter.storage.config.properties.AdminEmail) DatarouterSchemaUpdateScheduler(io.datarouter.storage.config.executor.DatarouterStorageExecutors.DatarouterSchemaUpdateScheduler) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) DatarouterChangelogDtoBuilder(io.datarouter.instrumentation.changelog.ChangelogRecorder.DatarouterChangelogDtoBuilder) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Instant(java.time.Instant) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) EnvironmentName(io.datarouter.storage.config.properties.EnvironmentName) Optional(java.util.Optional) SingletonSupplier(io.datarouter.util.singletonsupplier.SingletonSupplier) Collections(java.util.Collections) Optional(java.util.Optional) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ArrayList(java.util.ArrayList) MutableString(io.datarouter.util.mutable.MutableString) ClientId(io.datarouter.storage.client.ClientId) Future(java.util.concurrent.Future) ArrayList(java.util.ArrayList) List(java.util.List) ExecutionException(java.util.concurrent.ExecutionException)

Example 14 with ClientId

use of io.datarouter.storage.client.ClientId in project datarouter by hotpads.

the class SqsQueueRegistryService method getSqsQueuesForClient.

public Pair<List<Twin<String>>, List<String>> getSqsQueuesForClient(ClientId clientId) {
    Set<String> knownQueuesUrls = new HashSet<>();
    AmazonSQS sqs = sqsClientManager.getAmazonSqs(clientId);
    List<? extends BaseSqsNode<?, ?, ?>> sqsNodes = Scanner.of(nodes.getPhysicalNodesForClient(clientId.getName())).map(NodeTool::extractSinglePhysicalNode).map(physicalNode -> (BaseSqsNode<?, ?, ?>) physicalNode).list();
    List<Twin<String>> knownQueueUrlByName = Scanner.of(sqsNodes).map(BaseSqsNode::getQueueUrlAndName).map(Supplier::get).each(twin -> knownQueuesUrls.add(twin.getLeft())).list();
    List<String> unreferencedQueues = Scanner.of(sqsNodes).map(BaseSqsNode::buildNamespace).distinct().map(sqs::listQueues).concatIter(ListQueuesResult::getQueueUrls).exclude(knownQueuesUrls::contains).map(queueUrl -> StringTool.getStringAfterLastOccurrence("/", queueUrl)).include(queueName -> sqsQueueExists(sqs, queueName)).list();
    return new Pair<>(knownQueueUrlByName, unreferencedQueues);
}
Also used : Twin(io.datarouter.util.tuple.Twin) Scanner(io.datarouter.scanner.Scanner) NodeTool(io.datarouter.storage.node.NodeTool) Set(java.util.Set) ListQueuesResult(com.amazonaws.services.sqs.model.ListQueuesResult) Singleton(javax.inject.Singleton) StringTool(io.datarouter.util.string.StringTool) Supplier(java.util.function.Supplier) HashSet(java.util.HashSet) Inject(javax.inject.Inject) SqsClientManager(io.datarouter.aws.sqs.SqsClientManager) List(java.util.List) QueueDoesNotExistException(com.amazonaws.services.sqs.model.QueueDoesNotExistException) ClientId(io.datarouter.storage.client.ClientId) AmazonSQS(com.amazonaws.services.sqs.AmazonSQS) BaseSqsNode(io.datarouter.aws.sqs.BaseSqsNode) DatarouterNodes(io.datarouter.storage.node.DatarouterNodes) Pair(io.datarouter.util.tuple.Pair) ListQueuesResult(com.amazonaws.services.sqs.model.ListQueuesResult) AmazonSQS(com.amazonaws.services.sqs.AmazonSQS) Twin(io.datarouter.util.tuple.Twin) NodeTool(io.datarouter.storage.node.NodeTool) BaseSqsNode(io.datarouter.aws.sqs.BaseSqsNode) Supplier(java.util.function.Supplier) HashSet(java.util.HashSet) Pair(io.datarouter.util.tuple.Pair)

Example 15 with ClientId

use of io.datarouter.storage.client.ClientId in project datarouter by hotpads.

the class SqsUpdateQueueHandler method deleteAllUnreferencedQueues.

@Handler
private Mav deleteAllUnreferencedQueues(@Param(PARAM_clientName) String clientName, @Param(PARAM_referer) String referer) {
    ClientId clientId = datarouterClients.getClientId(clientName);
    List<String> unreferencedQueueNames = queueRegistryService.getSqsQueuesForClient(clientId).getRight();
    AmazonSQS sqs = sqsClientManager.getAmazonSqs(clientId);
    Scanner.of(unreferencedQueueNames).map(sqs::getQueueUrl).map(GetQueueUrlResult::getQueueUrl).forEach(sqs::deleteQueue);
    String message = "Deleted all unreferenced SQS queues";
    Scanner.of(unreferencedQueueNames).map(queueName -> new DatarouterChangelogDtoBuilder("Sqs", queueName, "delete unreferenced queue", getSessionInfo().getRequiredSession().getUsername())).map(DatarouterChangelogDtoBuilder::build).forEach(changelogRecorder::record);
    return buildPage(referer, message);
}
Also used : ClientId(io.datarouter.storage.client.ClientId) AmazonSQS(com.amazonaws.services.sqs.AmazonSQS) DatarouterChangelogDtoBuilder(io.datarouter.instrumentation.changelog.ChangelogRecorder.DatarouterChangelogDtoBuilder) BaseHandler(io.datarouter.web.handler.BaseHandler)

Aggregations

ClientId (io.datarouter.storage.client.ClientId)21 List (java.util.List)10 Inject (javax.inject.Inject)9 Scanner (io.datarouter.scanner.Scanner)7 BaseHandler (io.datarouter.web.handler.BaseHandler)7 TagCreator.div (j2html.TagCreator.div)6 ContainerTag (j2html.tags.ContainerTag)6 ArrayList (java.util.ArrayList)6 Optional (java.util.Optional)6 DatarouterChangelogDtoBuilder (io.datarouter.instrumentation.changelog.ChangelogRecorder.DatarouterChangelogDtoBuilder)4 DatarouterClients (io.datarouter.storage.client.DatarouterClients)4 PhysicalNode (io.datarouter.storage.node.type.physical.PhysicalNode)4 Mav (io.datarouter.web.handler.mav.Mav)4 J2HtmlTable (io.datarouter.web.html.j2html.J2HtmlTable)4 Bootstrap4PageFactory (io.datarouter.web.html.j2html.bootstrap4.Bootstrap4PageFactory)4 DatarouterWebRequireJsV2 (io.datarouter.web.requirejs.DatarouterWebRequireJsV2)4 Collections (java.util.Collections)4 Map (java.util.Map)4 Logger (org.slf4j.Logger)4 LoggerFactory (org.slf4j.LoggerFactory)4