mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 18:47:20 +01:00
* mq: seal a partition's fence when a repartition drains it Draining a partition shut it down and answered at once: its last window was still being flushed, and its fence was left unsealed. A publisher still holding the old assignment could then load the range again on its leader at the same epoch and append to a range the topic no longer lists, so nothing could treat a removed range as complete. The drain now waits for the last flush, waiting out a retirement already pending too, and seals the fence before it answers; a drained range its leader does not have loaded has its stored fence sealed as found. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: serve a sealed range a repartition removed from its files A repartition drops the old ranges from the topic, and a fetch for one was answered partition not found, so whatever a consumer had not read from it was out of reach. A fetch naming a generation and range the topic no longer assigns, whose fence is sealed, is now served read-only by any broker: a stopped log buffer over the range's files, with its log start and high-water mark read from them, answers through the same stateless read as a live partition, out-of-range included. A reader is reused for 30 seconds, so a purge elsewhere shows soon. An unassigned range whose fence is not sealed may still take writes and keeps the old answer. The test filer can now keep what is uploaded to it, so flushed windows read back. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: list a topic's retired ranges in the partition lookup LookupTopicBrokers takes include_retired and then also answers retired_partitions: each sealed range of an earlier generation the topic no longer assigns that still holds data, with its log start and high-water mark, read from the range's files. A consumer can find what a repartition left behind and fetch it. Unsealed ranges are left out, since they may still take writes. The test filer lists the directories an entry's path implies, as the filer does. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: purge retired ranges past retention The retention pass hands each partition with expired files to its leader, but it walked only the topic's current assignments, so a range a repartition retired kept its files forever. The balancer now purges each sealed retired range itself, deleting its expired files under the sealed fence as read. As for a live partition the newest file stays, so the range keeps its high-water mark and a read below the raised log start is out of range. The purging broker drops its cached reader of the range. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: the offset scan of a partition's files stops with its caller Retired fetches and listings, the retention pass and a follower take-over now pass their context to the filer scan, so a cancelled lookup or a broker shutting down does not wait on a filer that stops sending entries. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: drain a repartition's old ranges only after saving the new topic.conf A repartition drained the old ranges before saving the topic.conf that replaces them, and a drain now seals them. When that save failed, the ranges topic.conf still assigned were sealed: their leader could not take their fence again, and with every broker healthy nothing moved the epoch on, so the topic took no more writes. The old ranges are now drained after the save, so a failed save leaves them assigned, unsealed and writable. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: leave a drained range's fence to a holder still renewing it A drained range its leader had not loaded had its stored fence sealed as found. If a follower had taken that fence over and was still storing the records it acked, the seal replaced its token, so its remaining writes failed the fence check and those records never reached the range. The drain now seals a found fence only once nobody has renewed it for fenceSealWait, the same test a new leader applies; a holder still renewing it seals it itself when done, and the drain waits for that. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: seal a range drained while its broker shuts down Once a broker shutdown has started it retires every partition itself, so removing one for a drain reports false, and the drain answered success without sealing the range. It now waits for the shutdown's last flush of the partition and seals the fence like any other drain. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: read retired ranges without a log buffer, dropping old readers on access Each retired range's reader was a stopped log buffer, which still allocated the buffers and windows a writer needs, and cached readers past their time were dropped only when another was created. A retired range is now read through ReadFlushedMessagesAtOffset, the stateless disk read with its chunk cache and nothing else, answering out-of-range and end of partition as a live buffer does; the disk read helpers take the read function and cache instead of a buffer. Readers past retiredReaderTTL are dropped on every lookup. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: bound the retention pass over retired ranges The pass over a topic's retired ranges ran under the broker's own context, so a filer that stopped answering its listing or offset scan held the balancer's retention loop for good. Each topic's pass over its retired ranges now has generationPassTimeout, as handing expired partitions to their leaders does. The test also covers a fetch of a retired range returning with its caller. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: a drain seals a stale fence only as it read it A drained range its leader had not loaded is sealed once its fence has gone fenceSealWait without a renewal. The seal required only the fence's token, which a renewal keeps, so a holder that renewed between the drain's read and its seal still had the fence sealed under it, and its remaining writes failed the fence check. The seal now requires the entry as read, as a new leader's take does, and a drain that loses that race looks again. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: finish the drains a stopped balancer left behind A repartition saves the new topic.conf and then drains the old ranges. A balancer that stopped in between left them unsealed, and nothing came back to them: repair looks only at topic.conf, and retired reads, listing and retention skip unsealed ranges, so their records were out of reach. The balancer's periodic pass now also looks for range directories that topic.conf no longer names and whose fence is unsealed, and asks the broker holding the fence to drain the range, which flushes what it holds and seals it. A holder that does not answer is drained by the balancer itself, which seals the fence only once nobody has renewed it for fenceSealWait. Each topic's pass is bounded by generationPassTimeout. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: finish a predecessor's drains on taking the balancer lock The pass that finishes drains a stopped balancer left behind ran only with the retention loop, so after a balancer restart its old ranges could stay unsealed, and unreadable, for up to five minutes. A broker that finds itself the balancer now runs the pass once right away in the background, bounded per topic as the periodic one is, so the wait is down to the fenceSealWait rule. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: report a drain's error on the test goroutine Two drain tests ran the drain, which fails the test on error, in a goroutine of their own, where failing only ends that goroutine and leaves the test waiting or passing on what it saw. The drain's error now comes back over the channel the test already waits on, and the test fails there. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: drain a repartition's replaced ranges outside the topic.conf lock A repartition drained the replaced ranges while it still held topicConfLock, under the lock's 30-second deadline, and the drain now waits for each range's last flush and seal. A slow flush held every cache-miss read of topic.conf behind the lock, could run the shared deadline out and leave a range unsealed, and left the new ranges' assignment to a context that had already expired. The new ranges are now assigned under the lock, and the replaced ones drained after it is released, with a deadline of their own sized for a flush and a seal that may wait out fenceSealWait. A range the drain does not get to is finished by the balancer's pass over orphaned ranges. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * mq: move a retired read past offsets no stored entry holds A read of a retired range at an offset no stored entry holds, below the high-water mark, answered no records with the same next offset and no end of partition, so a consumer asked for that offset again forever. Such a stretch is a gap in the offsets or entries the log could not place. The read now looks for the lowest stored offset after it and reads from there, and when none is held up to the high-water mark it answers the end of the partition at the high-water mark. Below the log start the read is still out of range. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: serve a client only the partition generation it names A partition is found by its range alone, so a fetch naming an older generation of a range the topic still assigns, not sealed and so not read as retired, was answered from the live partition of the newer generation: the client read records of a generation it never asked for, at offsets that mean something else there. A client that names a generation now gets only that one: one that is not the assigned generation, or not the one loaded, is refused with the partition not found a removed unsealed range gets. A client that names none still matches by range. A publisher refused this way looks the topic up again, as it does when the balancer is ahead of the cached topic.conf, and the unflushed-message query and the flush notification check the generation too. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: decide orphaned ranges under the topic.conf lock from the stored conf The pass that finishes unfinished drains took topic.conf from the cache and listed the stored ranges without the topic.conf lock. A balancer just elected with a stale cache, or a repartition saving its new generation between the read and the listing, made current ranges look orphaned, and they were drained and sealed. The pass now takes topicConfLock, reads topic.conf from the filer, lists the stored ranges and decides under it, then drains what it found once the lock is released; a repartition cannot assign a generation that is already gone, so the decision holds. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: drain only the partition generation a drain names A drain found the loaded partition by its boundaries alone. A topic repartitioned 1 -> 2 -> 1 has its first range and its current one on the same boundaries, so finishing the first one's unfinished drain removed and sealed the current range instead. A drain naming a generation now takes a loaded partition only of that generation; otherwise it seals the named generation's stored fence, as for a range its leader has not loaded. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: leave an orphaned range's own drain time when its holder stalls Finishing an orphaned range's drain asks the broker holding its fence first and drains the range itself when that fails. The holder's call had the whole per-topic deadline, so a holder that took the call and never answered used it up, and the drain here then ran on an expired context and did nothing. The holder now gets half the time that is left, keeping the rest for the drain here. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: end an unflushed query a broker would redirect to itself A broker still holding an older generation of a range it now leads under a newer one refuses a query for the newer generation, looks the range up, finds itself as the leader, and redirected the query to itself, which did the same again until the caller gave up. When the lookup names this broker the query now ends with an error saying the generation is assigned here but not loaded; a lookup naming another broker is still followed. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: refuse a loaded generation the topic no longer assigns After a split the old range stays loaded on its broker until the drain unloads and seals it. A fetch naming that generation passed the generation check, since no assignment shares its range any more, and was served from a buffer that is neither assigned nor sealed. A loaded partition is now served by generation only while topic.conf assigns it; the cache is reread once before refusing, so a broker whose cache predates the assignment that loaded the partition still serves it. Once the drain unloads and seals it, the retired reader serves it from its files. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq logstore: retry a parquet reader whose topic.conf read failed The parquet reader reads topic.conf once, when it is built, and a failed read left it a reader that finds nothing, for good. A merged offset read then skipped the compacted offsets to the first log file, and a sealed partition's reader, finding nothing stored, ended the partition at its high water mark. The reader is now set up on its first read and again on each read while topic.conf cannot be read, failing those reads; a topic.conf that does not exist still means no compacted rows. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: keep a drained range from reloading until its seal lands A drain unlisted the range once its last flush landed, before sealing its fence. A publisher whose topic.conf cache still assigned the range to this broker could load it again in between, take the fence at the same epoch, and make the seal fail, leaving the range unsealed after the repartition. The drain now holds the range as retiring until its seal returns, so a loader waits and then finds the fence sealed. A failed seal releases it, unsealed and unassigned, for the orphan pass. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 * mq: seal a drained range only once all it accepted is stored A drain sealed the fence after the partition's last flush returned, without asking whether that flush stored anything. A flush abandoned when a broker stop ran out its flush budget drops the window and breaks the follow stream so the follower stores its copy, but the seal could land first, and the follower, finding the fence sealed, gave up records the leader had acknowledged. The drain now seals only when the flushed watermark reaches the last accepted offset; otherwise it leaves the fence to the follower and fails, and a later drain or the orphan pass finds it sealed by the follower or seals it once it is stale. Claude-Session: https://claude.ai/code/session_011Upvai5AjLiNE5B1HCAn34 --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
386 lines
12 KiB
Go
386 lines
12 KiB
Go
package topic
|
|
|
|
import (
|
|
"context"
|
|
"sync"
|
|
"time"
|
|
|
|
cmap "github.com/orcaman/concurrent-map/v2"
|
|
"github.com/seaweedfs/seaweedfs/weed/glog"
|
|
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
|
|
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
|
|
"github.com/shirou/gopsutil/v4/cpu"
|
|
)
|
|
|
|
// LocalTopicManager manages topics on local broker
|
|
type LocalTopicManager struct {
|
|
topics cmap.ConcurrentMap[string, *LocalTopic]
|
|
cleanupDone chan struct{} // Signal cleanup goroutine to stop
|
|
cleanupTimer *time.Ticker
|
|
|
|
// stopMu orders partition adds and cleanup passes against Shutdown
|
|
stopMu sync.RWMutex
|
|
stopped bool
|
|
// partitions shut down whose last flush is still pending
|
|
retiringMu sync.Mutex
|
|
retiring map[*LocalPartition]*retirement
|
|
}
|
|
|
|
type retirement struct {
|
|
topic Topic
|
|
flushed chan struct{}
|
|
// holds keep it listed past its last flush
|
|
holds int
|
|
done bool
|
|
}
|
|
|
|
// NewLocalTopicManager creates a new LocalTopicManager
|
|
func NewLocalTopicManager() *LocalTopicManager {
|
|
return &LocalTopicManager{
|
|
topics: cmap.New[*LocalTopic](),
|
|
cleanupDone: make(chan struct{}),
|
|
retiring: make(map[*LocalPartition]*retirement),
|
|
}
|
|
}
|
|
|
|
// StartIdlePartitionCleanup starts a background goroutine that periodically
|
|
// cleans up idle partitions (partitions with no publishers and no subscribers)
|
|
func (manager *LocalTopicManager) StartIdlePartitionCleanup(ctx context.Context, checkInterval, idleTimeout time.Duration) {
|
|
manager.cleanupTimer = time.NewTicker(checkInterval)
|
|
|
|
go func() {
|
|
defer close(manager.cleanupDone)
|
|
defer manager.cleanupTimer.Stop()
|
|
|
|
glog.V(1).Infof("Idle partition cleanup started: check every %v, cleanup after %v idle", checkInterval, idleTimeout)
|
|
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
glog.V(1).Info("Idle partition cleanup stopped")
|
|
return
|
|
case <-manager.cleanupTimer.C:
|
|
manager.cleanupIdlePartitions(idleTimeout)
|
|
}
|
|
}
|
|
}()
|
|
}
|
|
|
|
// cleanupIdlePartitions removes idle partitions from memory
|
|
func (manager *LocalTopicManager) cleanupIdlePartitions(idleTimeout time.Duration) {
|
|
manager.stopMu.RLock()
|
|
defer manager.stopMu.RUnlock()
|
|
if manager.stopped {
|
|
return
|
|
}
|
|
cleanedCount := 0
|
|
var emptyTopics []string
|
|
|
|
// Iterate through all topics
|
|
manager.topics.IterCb(func(topicKey string, localTopic *LocalTopic) {
|
|
localTopic.partitionLock.Lock()
|
|
defer localTopic.partitionLock.Unlock()
|
|
|
|
// Check each partition
|
|
for i := len(localTopic.Partitions) - 1; i >= 0; i-- {
|
|
partition := localTopic.Partitions[i]
|
|
|
|
if partition.ShouldCleanup(idleTimeout) {
|
|
glog.V(1).Infof("Cleaning up idle partition %s (idle for %v, publishers=%d, subscribers=%d)",
|
|
partition.Partition.String(),
|
|
partition.GetIdleDuration(),
|
|
partition.Publishers.Size(),
|
|
partition.Subscribers.Size())
|
|
|
|
manager.retire(localTopic.Topic, partition)
|
|
|
|
// Remove from slice
|
|
localTopic.Partitions = append(localTopic.Partitions[:i], localTopic.Partitions[i+1:]...)
|
|
cleanedCount++
|
|
}
|
|
}
|
|
|
|
if len(localTopic.Partitions) == 0 {
|
|
emptyTopics = append(emptyTopics, topicKey)
|
|
}
|
|
})
|
|
|
|
// Remove emptied topics only after the iteration: IterCb holds the shard's
|
|
// read lock while running the callback, so calling Remove (which takes the
|
|
// same shard's write lock) inside it self-deadlocks and permanently wedges
|
|
// the shard — every later reader of that shard blocks behind the stuck
|
|
// writer, hanging ListTopicsInMemory/TopicExistsInMemory forever.
|
|
for _, topicKey := range emptyTopics {
|
|
manager.topics.RemoveCb(topicKey, func(key string, localTopic *LocalTopic, exists bool) bool {
|
|
if !exists || localTopic == nil {
|
|
return false
|
|
}
|
|
// Re-check emptiness under the shard's write lock: a publisher or
|
|
// subscriber may have added a partition since the scan above.
|
|
localTopic.partitionLock.RLock()
|
|
defer localTopic.partitionLock.RUnlock()
|
|
if len(localTopic.Partitions) > 0 {
|
|
return false
|
|
}
|
|
glog.V(1).Infof("Removing empty topic %s", key)
|
|
return true
|
|
})
|
|
}
|
|
|
|
if cleanedCount > 0 {
|
|
glog.V(0).Infof("Cleaned up %d idle partition(s)", cleanedCount)
|
|
}
|
|
}
|
|
|
|
// WaitForCleanupShutdown waits for the cleanup goroutine to finish
|
|
func (manager *LocalTopicManager) WaitForCleanupShutdown() {
|
|
<-manager.cleanupDone
|
|
glog.V(1).Info("Idle partition cleanup shutdown complete")
|
|
}
|
|
|
|
// retire shuts a partition down and makes Shutdown wait for its last flush.
|
|
func (manager *LocalTopicManager) retire(t Topic, p *LocalPartition) {
|
|
manager.markRetiring(t, p, false)
|
|
p.Shutdown()
|
|
}
|
|
|
|
// HoldRetired keeps p listed as retiring, past its last flush, until release is
|
|
// called, so its range is not loaded again meanwhile, as before it is sealed.
|
|
func (manager *LocalTopicManager) HoldRetired(t Topic, p *LocalPartition) (release func()) {
|
|
r := manager.markRetiring(t, p, true)
|
|
var once sync.Once
|
|
return func() {
|
|
once.Do(func() {
|
|
manager.retiringMu.Lock()
|
|
defer manager.retiringMu.Unlock()
|
|
r.holds--
|
|
manager.endRetirementLocked(p, r)
|
|
})
|
|
}
|
|
}
|
|
|
|
func (manager *LocalTopicManager) markRetiring(t Topic, p *LocalPartition, hold bool) *retirement {
|
|
manager.retiringMu.Lock()
|
|
defer manager.retiringMu.Unlock()
|
|
r, ok := manager.retiring[p]
|
|
if !ok {
|
|
r = &retirement{topic: t, flushed: make(chan struct{})}
|
|
manager.retiring[p] = r
|
|
go func() {
|
|
p.LogBuffer.WaitForShutdown()
|
|
p.closeReplica()
|
|
manager.retiringMu.Lock()
|
|
defer manager.retiringMu.Unlock()
|
|
r.done = true
|
|
manager.endRetirementLocked(p, r)
|
|
}()
|
|
}
|
|
if hold {
|
|
r.holds++
|
|
}
|
|
return r
|
|
}
|
|
|
|
func (manager *LocalTopicManager) endRetirementLocked(p *LocalPartition, r *retirement) {
|
|
if r.done && r.holds == 0 && manager.retiring[p] == r {
|
|
delete(manager.retiring, p)
|
|
close(r.flushed)
|
|
}
|
|
}
|
|
|
|
// Shutdown closes every partition and waits until each has flushed what it holds.
|
|
// Partitions cannot be added once it starts.
|
|
func (manager *LocalTopicManager) Shutdown() {
|
|
manager.stopMu.Lock()
|
|
manager.stopped = true
|
|
manager.stopMu.Unlock()
|
|
|
|
var topics []*LocalTopic
|
|
manager.topics.IterCb(func(_ string, localTopic *LocalTopic) {
|
|
topics = append(topics, localTopic)
|
|
})
|
|
for _, localTopic := range topics {
|
|
localTopic.partitionLock.RLock()
|
|
held := append([]*LocalPartition(nil), localTopic.Partitions...)
|
|
localTopic.partitionLock.RUnlock()
|
|
for _, p := range held {
|
|
manager.retire(localTopic.Topic, p)
|
|
}
|
|
}
|
|
// Anything removed before the snapshot was retired before it, so it is here too.
|
|
manager.retiringMu.Lock()
|
|
var partitions []*LocalPartition
|
|
for p := range manager.retiring {
|
|
partitions = append(partitions, p)
|
|
}
|
|
manager.retiringMu.Unlock()
|
|
for _, p := range partitions {
|
|
p.LogBuffer.WaitForShutdown()
|
|
}
|
|
}
|
|
|
|
// IsStopping reports whether Shutdown has started.
|
|
func (manager *LocalTopicManager) IsStopping() bool {
|
|
manager.stopMu.RLock()
|
|
defer manager.stopMu.RUnlock()
|
|
return manager.stopped
|
|
}
|
|
|
|
// AddLocalPartition adds a partition, or reports false once Shutdown has started.
|
|
func (manager *LocalTopicManager) AddLocalPartition(topic Topic, localPartition *LocalPartition) bool {
|
|
manager.stopMu.RLock()
|
|
defer manager.stopMu.RUnlock()
|
|
if manager.stopped {
|
|
return false
|
|
}
|
|
localTopic, ok := manager.topics.Get(topic.String())
|
|
if !ok {
|
|
localTopic = NewLocalTopic(topic)
|
|
}
|
|
if !manager.topics.SetIfAbsent(topic.String(), localTopic) {
|
|
localTopic, _ = manager.topics.Get(topic.String())
|
|
}
|
|
localTopic.addPartition(localPartition)
|
|
return true
|
|
}
|
|
|
|
// GetLocalPartition gets a topic from the local topic manager
|
|
func (manager *LocalTopicManager) GetLocalPartition(topic Topic, partition Partition) *LocalPartition {
|
|
localTopic, ok := manager.topics.Get(topic.String())
|
|
if !ok {
|
|
return nil
|
|
}
|
|
result := localTopic.findPartition(partition)
|
|
return result
|
|
}
|
|
|
|
// RemoveTopic removes a topic from the local topic manager
|
|
func (manager *LocalTopicManager) RemoveTopic(topic Topic) {
|
|
manager.topics.Remove(topic.String())
|
|
}
|
|
|
|
// RemoveLocalPartition retires p if it is still listed, leaving a copy that has
|
|
// replaced it. It reports false once Shutdown has started, which then retires p
|
|
// from its own snapshot.
|
|
func (manager *LocalTopicManager) RemoveLocalPartition(topic Topic, p *LocalPartition) (removed bool) {
|
|
manager.stopMu.RLock()
|
|
defer manager.stopMu.RUnlock()
|
|
if manager.stopped || p == nil {
|
|
return false
|
|
}
|
|
localTopic, ok := manager.topics.Get(topic.String())
|
|
if !ok || !localTopic.removePartition(p, func() { manager.markRetiring(topic, p, false) }) {
|
|
return false
|
|
}
|
|
manager.retire(topic, p)
|
|
return true
|
|
}
|
|
|
|
// RetiringPartition is a retired partition of this range whose last flush, or a
|
|
// hold on it, is still pending; a replacement must not read the stored offsets
|
|
// before it lands.
|
|
func (manager *LocalTopicManager) RetiringPartition(topic Topic, partition Partition) *LocalPartition {
|
|
p, _ := manager.findRetiring(topic, partition)
|
|
return p
|
|
}
|
|
|
|
func (manager *LocalTopicManager) findRetiring(topic Topic, partition Partition) (*LocalPartition, *retirement) {
|
|
manager.retiringMu.Lock()
|
|
defer manager.retiringMu.Unlock()
|
|
for p, r := range manager.retiring {
|
|
if r.topic.String() == topic.String() && p.Partition.LogicalEquals(partition) {
|
|
return p, r
|
|
}
|
|
}
|
|
return nil, nil
|
|
}
|
|
|
|
// WaitRetired returns once no retired partition of this range has a flush
|
|
// pending, or with ctx's error once ctx is done.
|
|
func (manager *LocalTopicManager) WaitRetired(ctx context.Context, topic Topic, partition Partition) error {
|
|
for _, r := manager.findRetiring(topic, partition); r != nil; _, r = manager.findRetiring(topic, partition) {
|
|
select {
|
|
case <-r.flushed:
|
|
case <-ctx.Done():
|
|
return ctx.Err()
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (manager *LocalTopicManager) ClosePublishers(topic Topic, unixTsNs int64) (removed bool) {
|
|
localTopic, ok := manager.topics.Get(topic.String())
|
|
if !ok {
|
|
return false
|
|
}
|
|
return localTopic.closePartitionPublishers(unixTsNs)
|
|
}
|
|
|
|
func (manager *LocalTopicManager) CloseSubscribers(topic Topic, unixTsNs int64) (removed bool) {
|
|
localTopic, ok := manager.topics.Get(topic.String())
|
|
if !ok {
|
|
return false
|
|
}
|
|
return localTopic.closePartitionSubscribers(unixTsNs)
|
|
}
|
|
|
|
// ListTopicsInMemory returns all topics currently tracked in memory
|
|
func (manager *LocalTopicManager) ListTopicsInMemory() []Topic {
|
|
var topics []Topic
|
|
for item := range manager.topics.IterBuffered() {
|
|
topics = append(topics, item.Val.Topic)
|
|
}
|
|
return topics
|
|
}
|
|
|
|
// TopicExistsInMemory checks if a topic exists in memory (not flushed data)
|
|
func (manager *LocalTopicManager) TopicExistsInMemory(topic Topic) bool {
|
|
_, exists := manager.topics.Get(topic.String())
|
|
return exists
|
|
}
|
|
|
|
func (manager *LocalTopicManager) CollectStats(duration time.Duration) *mq_pb.BrokerStats {
|
|
stats := &mq_pb.BrokerStats{
|
|
Stats: make(map[string]*mq_pb.TopicPartitionStats),
|
|
}
|
|
|
|
// collect current broker's cpu usage
|
|
// this needs to be in front, so the following stats can be more accurate
|
|
usages, err := cpu.Percent(duration, false)
|
|
if err == nil && len(usages) > 0 {
|
|
stats.CpuUsagePercent = int32(usages[0])
|
|
}
|
|
|
|
// collect current broker's topics and partitions
|
|
manager.topics.IterCb(func(topic string, localTopic *LocalTopic) {
|
|
for _, localPartition := range localTopic.Partitions {
|
|
topicPartition := &TopicPartition{
|
|
Topic: Topic{Namespace: localTopic.Namespace, Name: localTopic.Name},
|
|
Partition: localPartition.Partition,
|
|
}
|
|
stats.Stats[topicPartition.TopicPartitionId()] = &mq_pb.TopicPartitionStats{
|
|
Topic: &schema_pb.Topic{
|
|
Namespace: string(localTopic.Namespace),
|
|
Name: localTopic.Name,
|
|
},
|
|
Partition: localPartition.Partition.ToPbPartition(),
|
|
PublisherCount: int32(localPartition.Publishers.Size()),
|
|
SubscriberCount: int32(localPartition.Subscribers.Size()),
|
|
Follower: localPartition.Follower,
|
|
}
|
|
// fmt.Printf("collect topic %+v partition %+v\n", topicPartition, localPartition.Partition)
|
|
}
|
|
})
|
|
|
|
return stats
|
|
|
|
}
|
|
|
|
func (manager *LocalTopicManager) WaitUntilNoPublishers(topic Topic) {
|
|
localTopic, ok := manager.topics.Get(topic.String())
|
|
if !ok {
|
|
return
|
|
}
|
|
localTopic.WaitUntilNoPublishers()
|
|
}
|