repo
stringlengths
5
67
path
stringlengths
4
218
func_name
stringlengths
0
151
original_string
stringlengths
52
373k
language
stringclasses
6 values
code
stringlengths
52
373k
code_tokens
listlengths
10
512
docstring
stringlengths
3
47.2k
docstring_tokens
listlengths
3
234
sha
stringlengths
40
40
url
stringlengths
85
339
partition
stringclasses
3 values
nats-io/nats-streaming-server
server/server.go
sendAvailableMessagesToQueue
func (s *StanServer) sendAvailableMessagesToQueue(c *channel, qs *queueState) { if c == nil || qs == nil { return } qs.Lock() // Short circuit if no active members if len(qs.subs) == 0 { qs.Unlock() return } // If redelivery at startup in progress, don't attempt to deliver new messages if qs.newOnHold { qs.Unlock() return } for nextSeq := qs.lastSent + 1; qs.stalledSubCount < len(qs.subs); nextSeq++ { nextMsg := s.getNextMsg(c, &nextSeq, &qs.lastSent) if nextMsg == nil { break } if _, sent, sendMore := s.sendMsgToQueueGroup(qs, nextMsg, honorMaxInFlight); !sent || !sendMore { break } } qs.Unlock() }
go
func (s *StanServer) sendAvailableMessagesToQueue(c *channel, qs *queueState) { if c == nil || qs == nil { return } qs.Lock() // Short circuit if no active members if len(qs.subs) == 0 { qs.Unlock() return } // If redelivery at startup in progress, don't attempt to deliver new messages if qs.newOnHold { qs.Unlock() return } for nextSeq := qs.lastSent + 1; qs.stalledSubCount < len(qs.subs); nextSeq++ { nextMsg := s.getNextMsg(c, &nextSeq, &qs.lastSent) if nextMsg == nil { break } if _, sent, sendMore := s.sendMsgToQueueGroup(qs, nextMsg, honorMaxInFlight); !sent || !sendMore { break } } qs.Unlock() }
[ "func", "(", "s", "*", "StanServer", ")", "sendAvailableMessagesToQueue", "(", "c", "*", "channel", ",", "qs", "*", "queueState", ")", "{", "if", "c", "==", "nil", "||", "qs", "==", "nil", "{", "return", "\n", "}", "\n", "qs", ".", "Lock", "(", ")", "\n", "if", "len", "(", "qs", ".", "subs", ")", "==", "0", "{", "qs", ".", "Unlock", "(", ")", "\n", "return", "\n", "}", "\n", "if", "qs", ".", "newOnHold", "{", "qs", ".", "Unlock", "(", ")", "\n", "return", "\n", "}", "\n", "for", "nextSeq", ":=", "qs", ".", "lastSent", "+", "1", ";", "qs", ".", "stalledSubCount", "<", "len", "(", "qs", ".", "subs", ")", ";", "nextSeq", "++", "{", "nextMsg", ":=", "s", ".", "getNextMsg", "(", "c", ",", "&", "nextSeq", ",", "&", "qs", ".", "lastSent", ")", "\n", "if", "nextMsg", "==", "nil", "{", "break", "\n", "}", "\n", "if", "_", ",", "sent", ",", "sendMore", ":=", "s", ".", "sendMsgToQueueGroup", "(", "qs", ",", "nextMsg", ",", "honorMaxInFlight", ")", ";", "!", "sent", "||", "!", "sendMore", "{", "break", "\n", "}", "\n", "}", "\n", "qs", ".", "Unlock", "(", ")", "\n", "}" ]
// Send any messages that are ready to be sent that have been queued to the group.
[ "Send", "any", "messages", "that", "are", "ready", "to", "be", "sent", "that", "have", "been", "queued", "to", "the", "group", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/server/server.go#L4997-L5023
train
nats-io/nats-streaming-server
server/server.go
sendAvailableMessages
func (s *StanServer) sendAvailableMessages(c *channel, sub *subState) { sub.Lock() for nextSeq := sub.LastSent + 1; !sub.stalled; nextSeq++ { nextMsg := s.getNextMsg(c, &nextSeq, &sub.LastSent) if nextMsg == nil { break } if sent, sendMore := s.sendMsgToSub(sub, nextMsg, honorMaxInFlight); !sent || !sendMore { break } } sub.Unlock() }
go
func (s *StanServer) sendAvailableMessages(c *channel, sub *subState) { sub.Lock() for nextSeq := sub.LastSent + 1; !sub.stalled; nextSeq++ { nextMsg := s.getNextMsg(c, &nextSeq, &sub.LastSent) if nextMsg == nil { break } if sent, sendMore := s.sendMsgToSub(sub, nextMsg, honorMaxInFlight); !sent || !sendMore { break } } sub.Unlock() }
[ "func", "(", "s", "*", "StanServer", ")", "sendAvailableMessages", "(", "c", "*", "channel", ",", "sub", "*", "subState", ")", "{", "sub", ".", "Lock", "(", ")", "\n", "for", "nextSeq", ":=", "sub", ".", "LastSent", "+", "1", ";", "!", "sub", ".", "stalled", ";", "nextSeq", "++", "{", "nextMsg", ":=", "s", ".", "getNextMsg", "(", "c", ",", "&", "nextSeq", ",", "&", "sub", ".", "LastSent", ")", "\n", "if", "nextMsg", "==", "nil", "{", "break", "\n", "}", "\n", "if", "sent", ",", "sendMore", ":=", "s", ".", "sendMsgToSub", "(", "sub", ",", "nextMsg", ",", "honorMaxInFlight", ")", ";", "!", "sent", "||", "!", "sendMore", "{", "break", "\n", "}", "\n", "}", "\n", "sub", ".", "Unlock", "(", ")", "\n", "}" ]
// Send any messages that are ready to be sent that have been queued.
[ "Send", "any", "messages", "that", "are", "ready", "to", "be", "sent", "that", "have", "been", "queued", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/server/server.go#L5026-L5038
train
nats-io/nats-streaming-server
server/server.go
setSubStartSequence
func (s *StanServer) setSubStartSequence(c *channel, sr *pb.SubscriptionRequest) (string, uint64, error) { lastSent := uint64(0) debugTrace := "" // In all start position cases, if there is no message, ensure // lastSent stays at 0. switch sr.StartPosition { case pb.StartPosition_NewOnly: var err error lastSent, err = c.store.Msgs.LastSequence() if err != nil { return "", 0, err } if s.debug { debugTrace = fmt.Sprintf("new-only, seq=%d", lastSent+1) } case pb.StartPosition_LastReceived: lastSeq, err := c.store.Msgs.LastSequence() if err != nil { return "", 0, err } if lastSeq > 0 { lastSent = lastSeq - 1 } if s.debug { debugTrace = fmt.Sprintf("last message, seq=%d", lastSent+1) } case pb.StartPosition_TimeDeltaStart: startTime := time.Now().UnixNano() - sr.StartTimeDelta // If there is no message, seq will be 0. seq, err := c.store.Msgs.GetSequenceFromTimestamp(startTime) if err != nil { return "", 0, err } if seq > 0 { // If the time delta is in the future relative to the last // message in the log, 'seq' will be equal to last sequence + 1, // so this would translate to "new only" semantic. lastSent = seq - 1 } if s.debug { debugTrace = fmt.Sprintf("from time time='%v' seq=%d", time.Unix(0, startTime), lastSent+1) } case pb.StartPosition_SequenceStart: // If there is no message, firstSeq and lastSeq will be equal to 0. firstSeq, lastSeq, err := c.store.Msgs.FirstAndLastSequence() if err != nil { return "", 0, err } // StartSequence is an uint64, so can't be lower than 0. if sr.StartSequence < firstSeq { // That translates to sending the first message available. lastSent = firstSeq - 1 } else if sr.StartSequence > lastSeq { // That translates to "new only" lastSent = lastSeq } else if sr.StartSequence > 0 { // That translates to sending the message with StartSequence // sequence number. lastSent = sr.StartSequence - 1 } if s.debug { debugTrace = fmt.Sprintf("from sequence, asked_seq=%d actual_seq=%d", sr.StartSequence, lastSent+1) } case pb.StartPosition_First: firstSeq, err := c.store.Msgs.FirstSequence() if err != nil { return "", 0, err } if firstSeq > 0 { lastSent = firstSeq - 1 } if s.debug { debugTrace = fmt.Sprintf("from beginning, seq=%d", lastSent+1) } } return debugTrace, lastSent, nil }
go
func (s *StanServer) setSubStartSequence(c *channel, sr *pb.SubscriptionRequest) (string, uint64, error) { lastSent := uint64(0) debugTrace := "" // In all start position cases, if there is no message, ensure // lastSent stays at 0. switch sr.StartPosition { case pb.StartPosition_NewOnly: var err error lastSent, err = c.store.Msgs.LastSequence() if err != nil { return "", 0, err } if s.debug { debugTrace = fmt.Sprintf("new-only, seq=%d", lastSent+1) } case pb.StartPosition_LastReceived: lastSeq, err := c.store.Msgs.LastSequence() if err != nil { return "", 0, err } if lastSeq > 0 { lastSent = lastSeq - 1 } if s.debug { debugTrace = fmt.Sprintf("last message, seq=%d", lastSent+1) } case pb.StartPosition_TimeDeltaStart: startTime := time.Now().UnixNano() - sr.StartTimeDelta // If there is no message, seq will be 0. seq, err := c.store.Msgs.GetSequenceFromTimestamp(startTime) if err != nil { return "", 0, err } if seq > 0 { // If the time delta is in the future relative to the last // message in the log, 'seq' will be equal to last sequence + 1, // so this would translate to "new only" semantic. lastSent = seq - 1 } if s.debug { debugTrace = fmt.Sprintf("from time time='%v' seq=%d", time.Unix(0, startTime), lastSent+1) } case pb.StartPosition_SequenceStart: // If there is no message, firstSeq and lastSeq will be equal to 0. firstSeq, lastSeq, err := c.store.Msgs.FirstAndLastSequence() if err != nil { return "", 0, err } // StartSequence is an uint64, so can't be lower than 0. if sr.StartSequence < firstSeq { // That translates to sending the first message available. lastSent = firstSeq - 1 } else if sr.StartSequence > lastSeq { // That translates to "new only" lastSent = lastSeq } else if sr.StartSequence > 0 { // That translates to sending the message with StartSequence // sequence number. lastSent = sr.StartSequence - 1 } if s.debug { debugTrace = fmt.Sprintf("from sequence, asked_seq=%d actual_seq=%d", sr.StartSequence, lastSent+1) } case pb.StartPosition_First: firstSeq, err := c.store.Msgs.FirstSequence() if err != nil { return "", 0, err } if firstSeq > 0 { lastSent = firstSeq - 1 } if s.debug { debugTrace = fmt.Sprintf("from beginning, seq=%d", lastSent+1) } } return debugTrace, lastSent, nil }
[ "func", "(", "s", "*", "StanServer", ")", "setSubStartSequence", "(", "c", "*", "channel", ",", "sr", "*", "pb", ".", "SubscriptionRequest", ")", "(", "string", ",", "uint64", ",", "error", ")", "{", "lastSent", ":=", "uint64", "(", "0", ")", "\n", "debugTrace", ":=", "\"\"", "\n", "switch", "sr", ".", "StartPosition", "{", "case", "pb", ".", "StartPosition_NewOnly", ":", "var", "err", "error", "\n", "lastSent", ",", "err", "=", "c", ".", "store", ".", "Msgs", ".", "LastSequence", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "0", ",", "err", "\n", "}", "\n", "if", "s", ".", "debug", "{", "debugTrace", "=", "fmt", ".", "Sprintf", "(", "\"new-only, seq=%d\"", ",", "lastSent", "+", "1", ")", "\n", "}", "\n", "case", "pb", ".", "StartPosition_LastReceived", ":", "lastSeq", ",", "err", ":=", "c", ".", "store", ".", "Msgs", ".", "LastSequence", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "0", ",", "err", "\n", "}", "\n", "if", "lastSeq", ">", "0", "{", "lastSent", "=", "lastSeq", "-", "1", "\n", "}", "\n", "if", "s", ".", "debug", "{", "debugTrace", "=", "fmt", ".", "Sprintf", "(", "\"last message, seq=%d\"", ",", "lastSent", "+", "1", ")", "\n", "}", "\n", "case", "pb", ".", "StartPosition_TimeDeltaStart", ":", "startTime", ":=", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", "-", "sr", ".", "StartTimeDelta", "\n", "seq", ",", "err", ":=", "c", ".", "store", ".", "Msgs", ".", "GetSequenceFromTimestamp", "(", "startTime", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "0", ",", "err", "\n", "}", "\n", "if", "seq", ">", "0", "{", "lastSent", "=", "seq", "-", "1", "\n", "}", "\n", "if", "s", ".", "debug", "{", "debugTrace", "=", "fmt", ".", "Sprintf", "(", "\"from time time='%v' seq=%d\"", ",", "time", ".", "Unix", "(", "0", ",", "startTime", ")", ",", "lastSent", "+", "1", ")", "\n", "}", "\n", "case", "pb", ".", "StartPosition_SequenceStart", ":", "firstSeq", ",", "lastSeq", ",", "err", ":=", "c", ".", "store", ".", "Msgs", ".", "FirstAndLastSequence", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "0", ",", "err", "\n", "}", "\n", "if", "sr", ".", "StartSequence", "<", "firstSeq", "{", "lastSent", "=", "firstSeq", "-", "1", "\n", "}", "else", "if", "sr", ".", "StartSequence", ">", "lastSeq", "{", "lastSent", "=", "lastSeq", "\n", "}", "else", "if", "sr", ".", "StartSequence", ">", "0", "{", "lastSent", "=", "sr", ".", "StartSequence", "-", "1", "\n", "}", "\n", "if", "s", ".", "debug", "{", "debugTrace", "=", "fmt", ".", "Sprintf", "(", "\"from sequence, asked_seq=%d actual_seq=%d\"", ",", "sr", ".", "StartSequence", ",", "lastSent", "+", "1", ")", "\n", "}", "\n", "case", "pb", ".", "StartPosition_First", ":", "firstSeq", ",", "err", ":=", "c", ".", "store", ".", "Msgs", ".", "FirstSequence", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "0", ",", "err", "\n", "}", "\n", "if", "firstSeq", ">", "0", "{", "lastSent", "=", "firstSeq", "-", "1", "\n", "}", "\n", "if", "s", ".", "debug", "{", "debugTrace", "=", "fmt", ".", "Sprintf", "(", "\"from beginning, seq=%d\"", ",", "lastSent", "+", "1", ")", "\n", "}", "\n", "}", "\n", "return", "debugTrace", ",", "lastSent", ",", "nil", "\n", "}" ]
// Setup the start position for the subscriber.
[ "Setup", "the", "start", "position", "for", "the", "subscriber", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/server/server.go#L5070-L5148
train
nats-io/nats-streaming-server
server/server.go
startGoRoutine
func (s *StanServer) startGoRoutine(f func()) { s.mu.Lock() if !s.shutdown { s.wg.Add(1) go f() } s.mu.Unlock() }
go
func (s *StanServer) startGoRoutine(f func()) { s.mu.Lock() if !s.shutdown { s.wg.Add(1) go f() } s.mu.Unlock() }
[ "func", "(", "s", "*", "StanServer", ")", "startGoRoutine", "(", "f", "func", "(", ")", ")", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "if", "!", "s", ".", "shutdown", "{", "s", ".", "wg", ".", "Add", "(", "1", ")", "\n", "go", "f", "(", ")", "\n", "}", "\n", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "}" ]
// startGoRoutine starts the given function as a go routine if and only if // the server was not shutdown at that time. This is required because // we cannot increment the wait group after the shutdown process has started.
[ "startGoRoutine", "starts", "the", "given", "function", "as", "a", "go", "routine", "if", "and", "only", "if", "the", "server", "was", "not", "shutdown", "at", "that", "time", ".", "This", "is", "required", "because", "we", "cannot", "increment", "the", "wait", "group", "after", "the", "shutdown", "process", "has", "started", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/server/server.go#L5153-L5160
train
nats-io/nats-streaming-server
server/server.go
ClusterID
func (s *StanServer) ClusterID() string { s.mu.RLock() defer s.mu.RUnlock() return s.info.ClusterID }
go
func (s *StanServer) ClusterID() string { s.mu.RLock() defer s.mu.RUnlock() return s.info.ClusterID }
[ "func", "(", "s", "*", "StanServer", ")", "ClusterID", "(", ")", "string", "{", "s", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "RUnlock", "(", ")", "\n", "return", "s", ".", "info", ".", "ClusterID", "\n", "}" ]
// ClusterID returns the NATS Streaming Server's ID.
[ "ClusterID", "returns", "the", "NATS", "Streaming", "Server", "s", "ID", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/server/server.go#L5163-L5167
train
nats-io/nats-streaming-server
server/server.go
State
func (s *StanServer) State() State { s.mu.RLock() defer s.mu.RUnlock() return s.state }
go
func (s *StanServer) State() State { s.mu.RLock() defer s.mu.RUnlock() return s.state }
[ "func", "(", "s", "*", "StanServer", ")", "State", "(", ")", "State", "{", "s", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "RUnlock", "(", ")", "\n", "return", "s", ".", "state", "\n", "}" ]
// State returns the state of this server.
[ "State", "returns", "the", "state", "of", "this", "server", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/server/server.go#L5170-L5174
train
nats-io/nats-streaming-server
server/server.go
setLastError
func (s *StanServer) setLastError(err error) { s.mu.Lock() s.lastError = err s.state = Failed s.mu.Unlock() s.log.Fatalf("%v", err) }
go
func (s *StanServer) setLastError(err error) { s.mu.Lock() s.lastError = err s.state = Failed s.mu.Unlock() s.log.Fatalf("%v", err) }
[ "func", "(", "s", "*", "StanServer", ")", "setLastError", "(", "err", "error", ")", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "s", ".", "lastError", "=", "err", "\n", "s", ".", "state", "=", "Failed", "\n", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "s", ".", "log", ".", "Fatalf", "(", "\"%v\"", ",", "err", ")", "\n", "}" ]
// setLastError sets the last fatal error that occurred. This is // used in case of an async error that cannot directly be reported // to the user.
[ "setLastError", "sets", "the", "last", "fatal", "error", "that", "occurred", ".", "This", "is", "used", "in", "case", "of", "an", "async", "error", "that", "cannot", "directly", "be", "reported", "to", "the", "user", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/server/server.go#L5179-L5185
train
nats-io/nats-streaming-server
server/server.go
LastError
func (s *StanServer) LastError() error { s.mu.RLock() defer s.mu.RUnlock() return s.lastError }
go
func (s *StanServer) LastError() error { s.mu.RLock() defer s.mu.RUnlock() return s.lastError }
[ "func", "(", "s", "*", "StanServer", ")", "LastError", "(", ")", "error", "{", "s", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "RUnlock", "(", ")", "\n", "return", "s", ".", "lastError", "\n", "}" ]
// LastError returns the last fatal error the server experienced.
[ "LastError", "returns", "the", "last", "fatal", "error", "the", "server", "experienced", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/server/server.go#L5188-L5192
train
nats-io/nats-streaming-server
server/server.go
Shutdown
func (s *StanServer) Shutdown() { s.log.Noticef("Shutting down.") s.mu.Lock() if s.shutdown { s.mu.Unlock() return } close(s.shutdownCh) // Allows Shutdown() to be idempotent s.shutdown = true // Change the state too s.state = Shutdown // We need to make sure that the storeIOLoop returns before // closing the Store waitForIOStoreLoop := true // Capture under lock store := s.store ns := s.natsServer // Do not close and nil the connections here, they are used in many places // without locking. Once closed, s.nc.xxx() calls will simply fail, but // we won't panic. ncs := s.ncs ncr := s.ncr ncsr := s.ncsr nc := s.nc ftnc := s.ftnc nca := s.nca // Stop processing subscriptions start requests s.subStartQuit <- struct{}{} if s.ioChannel != nil { // Notify the IO channel that we are shutting down close(s.ioChannelQuit) } else { waitForIOStoreLoop = false } // In case we are running in FT mode. if s.ftQuit != nil { s.ftQuit <- struct{}{} } // In case we are running in Partitioning mode if s.partitions != nil { s.partitions.shutdown() } s.mu.Unlock() // Make sure the StoreIOLoop returns before closing the Store if waitForIOStoreLoop { s.ioChannelWG.Wait() } // Close Raft group before closing store. if s.raft != nil { if err := s.raft.shutdown(); err != nil { s.log.Errorf("Failed to stop Raft node: %v", err) } } // Close/Shutdown resources. Note that unless one instantiates StanServer // directly (instead of calling RunServer() and the like), these should // not be nil. if store != nil { store.Close() } if ncs != nil { ncs.Close() } if ncr != nil { ncr.Close() } if ncsr != nil { ncsr.Close() } if nc != nil { nc.Close() } if ftnc != nil { ftnc.Close() } if nca != nil { nca.Close() } if ns != nil { ns.Shutdown() } // Wait for go-routines to return s.wg.Wait() }
go
func (s *StanServer) Shutdown() { s.log.Noticef("Shutting down.") s.mu.Lock() if s.shutdown { s.mu.Unlock() return } close(s.shutdownCh) // Allows Shutdown() to be idempotent s.shutdown = true // Change the state too s.state = Shutdown // We need to make sure that the storeIOLoop returns before // closing the Store waitForIOStoreLoop := true // Capture under lock store := s.store ns := s.natsServer // Do not close and nil the connections here, they are used in many places // without locking. Once closed, s.nc.xxx() calls will simply fail, but // we won't panic. ncs := s.ncs ncr := s.ncr ncsr := s.ncsr nc := s.nc ftnc := s.ftnc nca := s.nca // Stop processing subscriptions start requests s.subStartQuit <- struct{}{} if s.ioChannel != nil { // Notify the IO channel that we are shutting down close(s.ioChannelQuit) } else { waitForIOStoreLoop = false } // In case we are running in FT mode. if s.ftQuit != nil { s.ftQuit <- struct{}{} } // In case we are running in Partitioning mode if s.partitions != nil { s.partitions.shutdown() } s.mu.Unlock() // Make sure the StoreIOLoop returns before closing the Store if waitForIOStoreLoop { s.ioChannelWG.Wait() } // Close Raft group before closing store. if s.raft != nil { if err := s.raft.shutdown(); err != nil { s.log.Errorf("Failed to stop Raft node: %v", err) } } // Close/Shutdown resources. Note that unless one instantiates StanServer // directly (instead of calling RunServer() and the like), these should // not be nil. if store != nil { store.Close() } if ncs != nil { ncs.Close() } if ncr != nil { ncr.Close() } if ncsr != nil { ncsr.Close() } if nc != nil { nc.Close() } if ftnc != nil { ftnc.Close() } if nca != nil { nca.Close() } if ns != nil { ns.Shutdown() } // Wait for go-routines to return s.wg.Wait() }
[ "func", "(", "s", "*", "StanServer", ")", "Shutdown", "(", ")", "{", "s", ".", "log", ".", "Noticef", "(", "\"Shutting down.\"", ")", "\n", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "if", "s", ".", "shutdown", "{", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "\n", "}", "\n", "close", "(", "s", ".", "shutdownCh", ")", "\n", "s", ".", "shutdown", "=", "true", "\n", "s", ".", "state", "=", "Shutdown", "\n", "waitForIOStoreLoop", ":=", "true", "\n", "store", ":=", "s", ".", "store", "\n", "ns", ":=", "s", ".", "natsServer", "\n", "ncs", ":=", "s", ".", "ncs", "\n", "ncr", ":=", "s", ".", "ncr", "\n", "ncsr", ":=", "s", ".", "ncsr", "\n", "nc", ":=", "s", ".", "nc", "\n", "ftnc", ":=", "s", ".", "ftnc", "\n", "nca", ":=", "s", ".", "nca", "\n", "s", ".", "subStartQuit", "<-", "struct", "{", "}", "{", "}", "\n", "if", "s", ".", "ioChannel", "!=", "nil", "{", "close", "(", "s", ".", "ioChannelQuit", ")", "\n", "}", "else", "{", "waitForIOStoreLoop", "=", "false", "\n", "}", "\n", "if", "s", ".", "ftQuit", "!=", "nil", "{", "s", ".", "ftQuit", "<-", "struct", "{", "}", "{", "}", "\n", "}", "\n", "if", "s", ".", "partitions", "!=", "nil", "{", "s", ".", "partitions", ".", "shutdown", "(", ")", "\n", "}", "\n", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "waitForIOStoreLoop", "{", "s", ".", "ioChannelWG", ".", "Wait", "(", ")", "\n", "}", "\n", "if", "s", ".", "raft", "!=", "nil", "{", "if", "err", ":=", "s", ".", "raft", ".", "shutdown", "(", ")", ";", "err", "!=", "nil", "{", "s", ".", "log", ".", "Errorf", "(", "\"Failed to stop Raft node: %v\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "if", "store", "!=", "nil", "{", "store", ".", "Close", "(", ")", "\n", "}", "\n", "if", "ncs", "!=", "nil", "{", "ncs", ".", "Close", "(", ")", "\n", "}", "\n", "if", "ncr", "!=", "nil", "{", "ncr", ".", "Close", "(", ")", "\n", "}", "\n", "if", "ncsr", "!=", "nil", "{", "ncsr", ".", "Close", "(", ")", "\n", "}", "\n", "if", "nc", "!=", "nil", "{", "nc", ".", "Close", "(", ")", "\n", "}", "\n", "if", "ftnc", "!=", "nil", "{", "ftnc", ".", "Close", "(", ")", "\n", "}", "\n", "if", "nca", "!=", "nil", "{", "nca", ".", "Close", "(", ")", "\n", "}", "\n", "if", "ns", "!=", "nil", "{", "ns", ".", "Shutdown", "(", ")", "\n", "}", "\n", "s", ".", "wg", ".", "Wait", "(", ")", "\n", "}" ]
// Shutdown will close our NATS connection and shutdown any embedded NATS server.
[ "Shutdown", "will", "close", "our", "NATS", "connection", "and", "shutdown", "any", "embedded", "NATS", "server", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/server/server.go#L5195-L5289
train
nats-io/nats-streaming-server
logger/logger.go
SetLogger
func (s *StanLogger) SetLogger(log Logger, logtime, debug, trace bool, logfile string) { s.mu.Lock() s.log = log s.ltime = logtime s.debug = debug s.trace = trace s.lfile = logfile s.mu.Unlock() }
go
func (s *StanLogger) SetLogger(log Logger, logtime, debug, trace bool, logfile string) { s.mu.Lock() s.log = log s.ltime = logtime s.debug = debug s.trace = trace s.lfile = logfile s.mu.Unlock() }
[ "func", "(", "s", "*", "StanLogger", ")", "SetLogger", "(", "log", "Logger", ",", "logtime", ",", "debug", ",", "trace", "bool", ",", "logfile", "string", ")", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "s", ".", "log", "=", "log", "\n", "s", ".", "ltime", "=", "logtime", "\n", "s", ".", "debug", "=", "debug", "\n", "s", ".", "trace", "=", "trace", "\n", "s", ".", "lfile", "=", "logfile", "\n", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "}" ]
// SetLogger sets the logger, debug and trace
[ "SetLogger", "sets", "the", "logger", "debug", "and", "trace" ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/logger/logger.go#L48-L56
train
nats-io/nats-streaming-server
logger/logger.go
GetLogger
func (s *StanLogger) GetLogger() Logger { s.mu.RLock() l := s.log s.mu.RUnlock() return l }
go
func (s *StanLogger) GetLogger() Logger { s.mu.RLock() l := s.log s.mu.RUnlock() return l }
[ "func", "(", "s", "*", "StanLogger", ")", "GetLogger", "(", ")", "Logger", "{", "s", ".", "mu", ".", "RLock", "(", ")", "\n", "l", ":=", "s", ".", "log", "\n", "s", ".", "mu", ".", "RUnlock", "(", ")", "\n", "return", "l", "\n", "}" ]
// GetLogger returns the logger
[ "GetLogger", "returns", "the", "logger" ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/logger/logger.go#L59-L64
train
nats-io/nats-streaming-server
logger/logger.go
ReopenLogFile
func (s *StanLogger) ReopenLogFile() { s.mu.Lock() if s.lfile == "" { s.mu.Unlock() s.Noticef("File log re-open ignored, not a file logger") return } if l, ok := s.log.(io.Closer); ok { if err := l.Close(); err != nil { s.mu.Unlock() s.Errorf("Unable to close logger: %v", err) return } } fileLog := natsdLogger.NewFileLogger(s.lfile, s.ltime, s.debug, s.trace, true) s.log = fileLog s.mu.Unlock() s.Noticef("File log re-opened") }
go
func (s *StanLogger) ReopenLogFile() { s.mu.Lock() if s.lfile == "" { s.mu.Unlock() s.Noticef("File log re-open ignored, not a file logger") return } if l, ok := s.log.(io.Closer); ok { if err := l.Close(); err != nil { s.mu.Unlock() s.Errorf("Unable to close logger: %v", err) return } } fileLog := natsdLogger.NewFileLogger(s.lfile, s.ltime, s.debug, s.trace, true) s.log = fileLog s.mu.Unlock() s.Noticef("File log re-opened") }
[ "func", "(", "s", "*", "StanLogger", ")", "ReopenLogFile", "(", ")", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "if", "s", ".", "lfile", "==", "\"\"", "{", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "s", ".", "Noticef", "(", "\"File log re-open ignored, not a file logger\"", ")", "\n", "return", "\n", "}", "\n", "if", "l", ",", "ok", ":=", "s", ".", "log", ".", "(", "io", ".", "Closer", ")", ";", "ok", "{", "if", "err", ":=", "l", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "s", ".", "Errorf", "(", "\"Unable to close logger: %v\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "fileLog", ":=", "natsdLogger", ".", "NewFileLogger", "(", "s", ".", "lfile", ",", "s", ".", "ltime", ",", "s", ".", "debug", ",", "s", ".", "trace", ",", "true", ")", "\n", "s", ".", "log", "=", "fileLog", "\n", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "s", ".", "Noticef", "(", "\"File log re-opened\"", ")", "\n", "}" ]
// ReopenLogFile closes and reopen the logfile. // Does nothing if the logger is not a file based.
[ "ReopenLogFile", "closes", "and", "reopen", "the", "logfile", ".", "Does", "nothing", "if", "the", "logger", "is", "not", "a", "file", "based", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/logger/logger.go#L68-L86
train
nats-io/nats-streaming-server
logger/logger.go
Close
func (s *StanLogger) Close() error { s.mu.Lock() defer s.mu.Unlock() if l, ok := s.log.(io.Closer); ok { return l.Close() } return nil }
go
func (s *StanLogger) Close() error { s.mu.Lock() defer s.mu.Unlock() if l, ok := s.log.(io.Closer); ok { return l.Close() } return nil }
[ "func", "(", "s", "*", "StanLogger", ")", "Close", "(", ")", "error", "{", "s", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "l", ",", "ok", ":=", "s", ".", "log", ".", "(", "io", ".", "Closer", ")", ";", "ok", "{", "return", "l", ".", "Close", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Close closes this logger, releasing possible held resources.
[ "Close", "closes", "this", "logger", "releasing", "possible", "held", "resources", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/logger/logger.go#L89-L96
train
nats-io/nats-streaming-server
logger/logger.go
Errorf
func (s *StanLogger) Errorf(format string, v ...interface{}) { s.executeLogCall(func(log Logger, format string, v ...interface{}) { log.Errorf(format, v...) }, format, v...) }
go
func (s *StanLogger) Errorf(format string, v ...interface{}) { s.executeLogCall(func(log Logger, format string, v ...interface{}) { log.Errorf(format, v...) }, format, v...) }
[ "func", "(", "s", "*", "StanLogger", ")", "Errorf", "(", "format", "string", ",", "v", "...", "interface", "{", "}", ")", "{", "s", ".", "executeLogCall", "(", "func", "(", "log", "Logger", ",", "format", "string", ",", "v", "...", "interface", "{", "}", ")", "{", "log", ".", "Errorf", "(", "format", ",", "v", "...", ")", "\n", "}", ",", "format", ",", "v", "...", ")", "\n", "}" ]
// Errorf logs an error
[ "Errorf", "logs", "an", "error" ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/logger/logger.go#L106-L110
train
nats-io/nats-streaming-server
logger/logger.go
Warnf
func (s *StanLogger) Warnf(format string, v ...interface{}) { s.executeLogCall(func(logger Logger, format string, v ...interface{}) { logger.Warnf(format, v...) }, format, v...) }
go
func (s *StanLogger) Warnf(format string, v ...interface{}) { s.executeLogCall(func(logger Logger, format string, v ...interface{}) { logger.Warnf(format, v...) }, format, v...) }
[ "func", "(", "s", "*", "StanLogger", ")", "Warnf", "(", "format", "string", ",", "v", "...", "interface", "{", "}", ")", "{", "s", ".", "executeLogCall", "(", "func", "(", "logger", "Logger", ",", "format", "string", ",", "v", "...", "interface", "{", "}", ")", "{", "logger", ".", "Warnf", "(", "format", ",", "v", "...", ")", "\n", "}", ",", "format", ",", "v", "...", ")", "\n", "}" ]
// Warnf logs a warning statement
[ "Warnf", "logs", "a", "warning", "statement" ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/logger/logger.go#L139-L143
train
nats-io/nats-streaming-server
stores/filestore.go
BufferSize
func BufferSize(size int) FileStoreOption { return func(o *FileStoreOptions) error { if size < 0 { return fmt.Errorf("buffer size value must be a positive number") } o.BufferSize = size return nil } }
go
func BufferSize(size int) FileStoreOption { return func(o *FileStoreOptions) error { if size < 0 { return fmt.Errorf("buffer size value must be a positive number") } o.BufferSize = size return nil } }
[ "func", "BufferSize", "(", "size", "int", ")", "FileStoreOption", "{", "return", "func", "(", "o", "*", "FileStoreOptions", ")", "error", "{", "if", "size", "<", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"buffer size value must be a positive number\"", ")", "\n", "}", "\n", "o", ".", "BufferSize", "=", "size", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// BufferSize is a FileStore option that sets the size of the buffer used // during store writes. This can help improve write performance.
[ "BufferSize", "is", "a", "FileStore", "option", "that", "sets", "the", "size", "of", "the", "buffer", "used", "during", "store", "writes", ".", "This", "can", "help", "improve", "write", "performance", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L210-L218
train
nats-io/nats-streaming-server
stores/filestore.go
CompactEnabled
func CompactEnabled(enabled bool) FileStoreOption { return func(o *FileStoreOptions) error { o.CompactEnabled = enabled return nil } }
go
func CompactEnabled(enabled bool) FileStoreOption { return func(o *FileStoreOptions) error { o.CompactEnabled = enabled return nil } }
[ "func", "CompactEnabled", "(", "enabled", "bool", ")", "FileStoreOption", "{", "return", "func", "(", "o", "*", "FileStoreOptions", ")", "error", "{", "o", ".", "CompactEnabled", "=", "enabled", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// CompactEnabled is a FileStore option that enables or disables file compaction. // The value false will disable compaction.
[ "CompactEnabled", "is", "a", "FileStore", "option", "that", "enables", "or", "disables", "file", "compaction", ".", "The", "value", "false", "will", "disable", "compaction", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L222-L227
train
nats-io/nats-streaming-server
stores/filestore.go
CompactInterval
func CompactInterval(seconds int) FileStoreOption { return func(o *FileStoreOptions) error { if seconds <= 0 { return fmt.Errorf("compact interval value must at least be 1 seconds") } o.CompactInterval = seconds return nil } }
go
func CompactInterval(seconds int) FileStoreOption { return func(o *FileStoreOptions) error { if seconds <= 0 { return fmt.Errorf("compact interval value must at least be 1 seconds") } o.CompactInterval = seconds return nil } }
[ "func", "CompactInterval", "(", "seconds", "int", ")", "FileStoreOption", "{", "return", "func", "(", "o", "*", "FileStoreOptions", ")", "error", "{", "if", "seconds", "<=", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"compact interval value must at least be 1 seconds\"", ")", "\n", "}", "\n", "o", ".", "CompactInterval", "=", "seconds", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// CompactInterval is a FileStore option that defines the minimum compaction interval. // Compaction is not timer based, but instead when things get "deleted". This value // prevents compaction to happen too often.
[ "CompactInterval", "is", "a", "FileStore", "option", "that", "defines", "the", "minimum", "compaction", "interval", ".", "Compaction", "is", "not", "timer", "based", "but", "instead", "when", "things", "get", "deleted", ".", "This", "value", "prevents", "compaction", "to", "happen", "too", "often", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L232-L240
train
nats-io/nats-streaming-server
stores/filestore.go
CompactFragmentation
func CompactFragmentation(fragmentation int) FileStoreOption { return func(o *FileStoreOptions) error { if fragmentation <= 0 { return fmt.Errorf("compact fragmentation value must at least be 1") } o.CompactFragmentation = fragmentation return nil } }
go
func CompactFragmentation(fragmentation int) FileStoreOption { return func(o *FileStoreOptions) error { if fragmentation <= 0 { return fmt.Errorf("compact fragmentation value must at least be 1") } o.CompactFragmentation = fragmentation return nil } }
[ "func", "CompactFragmentation", "(", "fragmentation", "int", ")", "FileStoreOption", "{", "return", "func", "(", "o", "*", "FileStoreOptions", ")", "error", "{", "if", "fragmentation", "<=", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"compact fragmentation value must at least be 1\"", ")", "\n", "}", "\n", "o", ".", "CompactFragmentation", "=", "fragmentation", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// CompactFragmentation is a FileStore option that defines the fragmentation ratio // below which compaction would not occur. For instance, specifying 50 means that // if other variables would allow for compaction, the compaction would occur only // after 50% of the file has data that is no longer valid.
[ "CompactFragmentation", "is", "a", "FileStore", "option", "that", "defines", "the", "fragmentation", "ratio", "below", "which", "compaction", "would", "not", "occur", ".", "For", "instance", "specifying", "50", "means", "that", "if", "other", "variables", "would", "allow", "for", "compaction", "the", "compaction", "would", "occur", "only", "after", "50%", "of", "the", "file", "has", "data", "that", "is", "no", "longer", "valid", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L246-L254
train
nats-io/nats-streaming-server
stores/filestore.go
CompactMinFileSize
func CompactMinFileSize(fileSize int64) FileStoreOption { return func(o *FileStoreOptions) error { if fileSize < 0 { return fmt.Errorf("compact minimum file size value must be a positive number") } o.CompactMinFileSize = fileSize return nil } }
go
func CompactMinFileSize(fileSize int64) FileStoreOption { return func(o *FileStoreOptions) error { if fileSize < 0 { return fmt.Errorf("compact minimum file size value must be a positive number") } o.CompactMinFileSize = fileSize return nil } }
[ "func", "CompactMinFileSize", "(", "fileSize", "int64", ")", "FileStoreOption", "{", "return", "func", "(", "o", "*", "FileStoreOptions", ")", "error", "{", "if", "fileSize", "<", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"compact minimum file size value must be a positive number\"", ")", "\n", "}", "\n", "o", ".", "CompactMinFileSize", "=", "fileSize", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// CompactMinFileSize is a FileStore option that defines the minimum file size below // which compaction would not occur. Specify `0` if you don't want any minimum.
[ "CompactMinFileSize", "is", "a", "FileStore", "option", "that", "defines", "the", "minimum", "file", "size", "below", "which", "compaction", "would", "not", "occur", ".", "Specify", "0", "if", "you", "don", "t", "want", "any", "minimum", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L258-L266
train
nats-io/nats-streaming-server
stores/filestore.go
DoCRC
func DoCRC(enableCRC bool) FileStoreOption { return func(o *FileStoreOptions) error { o.DoCRC = enableCRC return nil } }
go
func DoCRC(enableCRC bool) FileStoreOption { return func(o *FileStoreOptions) error { o.DoCRC = enableCRC return nil } }
[ "func", "DoCRC", "(", "enableCRC", "bool", ")", "FileStoreOption", "{", "return", "func", "(", "o", "*", "FileStoreOptions", ")", "error", "{", "o", ".", "DoCRC", "=", "enableCRC", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// DoCRC is a FileStore option that defines if a CRC checksum verification should // be performed when records are read from disk.
[ "DoCRC", "is", "a", "FileStore", "option", "that", "defines", "if", "a", "CRC", "checksum", "verification", "should", "be", "performed", "when", "records", "are", "read", "from", "disk", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L270-L275
train
nats-io/nats-streaming-server
stores/filestore.go
SliceConfig
func SliceConfig(maxMsgs int, maxBytes int64, maxAge time.Duration, script string) FileStoreOption { return func(o *FileStoreOptions) error { if maxMsgs < 0 || maxBytes < 0 || maxAge < 0 { return fmt.Errorf("slice max values must be positive numbers") } o.SliceMaxMsgs = maxMsgs o.SliceMaxBytes = maxBytes o.SliceMaxAge = maxAge o.SliceArchiveScript = script return nil } }
go
func SliceConfig(maxMsgs int, maxBytes int64, maxAge time.Duration, script string) FileStoreOption { return func(o *FileStoreOptions) error { if maxMsgs < 0 || maxBytes < 0 || maxAge < 0 { return fmt.Errorf("slice max values must be positive numbers") } o.SliceMaxMsgs = maxMsgs o.SliceMaxBytes = maxBytes o.SliceMaxAge = maxAge o.SliceArchiveScript = script return nil } }
[ "func", "SliceConfig", "(", "maxMsgs", "int", ",", "maxBytes", "int64", ",", "maxAge", "time", ".", "Duration", ",", "script", "string", ")", "FileStoreOption", "{", "return", "func", "(", "o", "*", "FileStoreOptions", ")", "error", "{", "if", "maxMsgs", "<", "0", "||", "maxBytes", "<", "0", "||", "maxAge", "<", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"slice max values must be positive numbers\"", ")", "\n", "}", "\n", "o", ".", "SliceMaxMsgs", "=", "maxMsgs", "\n", "o", ".", "SliceMaxBytes", "=", "maxBytes", "\n", "o", ".", "SliceMaxAge", "=", "maxAge", "\n", "o", ".", "SliceArchiveScript", "=", "script", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// SliceConfig is a FileStore option that allows the configuration of // file slice limits and optional archive script file name.
[ "SliceConfig", "is", "a", "FileStore", "option", "that", "allows", "the", "configuration", "of", "file", "slice", "limits", "and", "optional", "archive", "script", "file", "name", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L301-L312
train
nats-io/nats-streaming-server
stores/filestore.go
FileDescriptorsLimit
func FileDescriptorsLimit(limit int64) FileStoreOption { return func(o *FileStoreOptions) error { if limit < 0 { return fmt.Errorf("file descriptor limit must be a positive number") } o.FileDescriptorsLimit = limit return nil } }
go
func FileDescriptorsLimit(limit int64) FileStoreOption { return func(o *FileStoreOptions) error { if limit < 0 { return fmt.Errorf("file descriptor limit must be a positive number") } o.FileDescriptorsLimit = limit return nil } }
[ "func", "FileDescriptorsLimit", "(", "limit", "int64", ")", "FileStoreOption", "{", "return", "func", "(", "o", "*", "FileStoreOptions", ")", "error", "{", "if", "limit", "<", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"file descriptor limit must be a positive number\"", ")", "\n", "}", "\n", "o", ".", "FileDescriptorsLimit", "=", "limit", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// FileDescriptorsLimit is a soft limit hinting at FileStore to try to // limit the number of concurrent opened files to that limit.
[ "FileDescriptorsLimit", "is", "a", "soft", "limit", "hinting", "at", "FileStore", "to", "try", "to", "limit", "the", "number", "of", "concurrent", "opened", "files", "to", "that", "limit", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L316-L324
train
nats-io/nats-streaming-server
stores/filestore.go
ParallelRecovery
func ParallelRecovery(count int) FileStoreOption { return func(o *FileStoreOptions) error { if count <= 0 { return fmt.Errorf("parallel recovery value must be at least 1") } o.ParallelRecovery = count return nil } }
go
func ParallelRecovery(count int) FileStoreOption { return func(o *FileStoreOptions) error { if count <= 0 { return fmt.Errorf("parallel recovery value must be at least 1") } o.ParallelRecovery = count return nil } }
[ "func", "ParallelRecovery", "(", "count", "int", ")", "FileStoreOption", "{", "return", "func", "(", "o", "*", "FileStoreOptions", ")", "error", "{", "if", "count", "<=", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"parallel recovery value must be at least 1\"", ")", "\n", "}", "\n", "o", ".", "ParallelRecovery", "=", "count", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// ParallelRecovery is a FileStore option that allows the parallel // recovery of channels. When running with SSDs, try to use a higher // value than the default number of 1. When running with HDDs, // performance may be better if it stays at 1.
[ "ParallelRecovery", "is", "a", "FileStore", "option", "that", "allows", "the", "parallel", "recovery", "of", "channels", ".", "When", "running", "with", "SSDs", "try", "to", "use", "a", "higher", "value", "than", "the", "default", "number", "of", "1", ".", "When", "running", "with", "HDDs", "performance", "may", "be", "better", "if", "it", "stays", "at", "1", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L330-L338
train
nats-io/nats-streaming-server
stores/filestore.go
AllOptions
func AllOptions(opts *FileStoreOptions) FileStoreOption { return func(o *FileStoreOptions) error { if err := BufferSize(opts.BufferSize)(o); err != nil { return err } if err := CompactInterval(opts.CompactInterval)(o); err != nil { return err } if err := CompactFragmentation(opts.CompactFragmentation)(o); err != nil { return err } if err := CompactMinFileSize(opts.CompactMinFileSize)(o); err != nil { return err } if err := CRCPolynomial(opts.CRCPolynomial)(o); err != nil { return err } if err := SliceConfig(opts.SliceMaxMsgs, opts.SliceMaxBytes, opts.SliceMaxAge, opts.SliceArchiveScript)(o); err != nil { return err } if err := FileDescriptorsLimit(opts.FileDescriptorsLimit)(o); err != nil { return err } if err := ParallelRecovery(opts.ParallelRecovery)(o); err != nil { return err } o.CompactEnabled = opts.CompactEnabled o.DoCRC = opts.DoCRC o.DoSync = opts.DoSync o.TruncateUnexpectedEOF = opts.TruncateUnexpectedEOF return nil } }
go
func AllOptions(opts *FileStoreOptions) FileStoreOption { return func(o *FileStoreOptions) error { if err := BufferSize(opts.BufferSize)(o); err != nil { return err } if err := CompactInterval(opts.CompactInterval)(o); err != nil { return err } if err := CompactFragmentation(opts.CompactFragmentation)(o); err != nil { return err } if err := CompactMinFileSize(opts.CompactMinFileSize)(o); err != nil { return err } if err := CRCPolynomial(opts.CRCPolynomial)(o); err != nil { return err } if err := SliceConfig(opts.SliceMaxMsgs, opts.SliceMaxBytes, opts.SliceMaxAge, opts.SliceArchiveScript)(o); err != nil { return err } if err := FileDescriptorsLimit(opts.FileDescriptorsLimit)(o); err != nil { return err } if err := ParallelRecovery(opts.ParallelRecovery)(o); err != nil { return err } o.CompactEnabled = opts.CompactEnabled o.DoCRC = opts.DoCRC o.DoSync = opts.DoSync o.TruncateUnexpectedEOF = opts.TruncateUnexpectedEOF return nil } }
[ "func", "AllOptions", "(", "opts", "*", "FileStoreOptions", ")", "FileStoreOption", "{", "return", "func", "(", "o", "*", "FileStoreOptions", ")", "error", "{", "if", "err", ":=", "BufferSize", "(", "opts", ".", "BufferSize", ")", "(", "o", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "CompactInterval", "(", "opts", ".", "CompactInterval", ")", "(", "o", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "CompactFragmentation", "(", "opts", ".", "CompactFragmentation", ")", "(", "o", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "CompactMinFileSize", "(", "opts", ".", "CompactMinFileSize", ")", "(", "o", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "CRCPolynomial", "(", "opts", ".", "CRCPolynomial", ")", "(", "o", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "SliceConfig", "(", "opts", ".", "SliceMaxMsgs", ",", "opts", ".", "SliceMaxBytes", ",", "opts", ".", "SliceMaxAge", ",", "opts", ".", "SliceArchiveScript", ")", "(", "o", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "FileDescriptorsLimit", "(", "opts", ".", "FileDescriptorsLimit", ")", "(", "o", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "ParallelRecovery", "(", "opts", ".", "ParallelRecovery", ")", "(", "o", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "o", ".", "CompactEnabled", "=", "opts", ".", "CompactEnabled", "\n", "o", ".", "DoCRC", "=", "opts", ".", "DoCRC", "\n", "o", ".", "DoSync", "=", "opts", ".", "DoSync", "\n", "o", ".", "TruncateUnexpectedEOF", "=", "opts", ".", "TruncateUnexpectedEOF", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// AllOptions is a convenient option to pass all options from a FileStoreOptions // structure to the constructor.
[ "AllOptions", "is", "a", "convenient", "option", "to", "pass", "all", "options", "from", "a", "FileStoreOptions", "structure", "to", "the", "constructor", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L354-L386
train
nats-io/nats-streaming-server
stores/filestore.go
checkFileVersion
func checkFileVersion(r io.Reader) error { fv, err := util.ReadInt(r) if err != nil { return fmt.Errorf("unable to verify file version: %v", err) } if fv == 0 || fv > fileVersion { return fmt.Errorf("unsupported file version: %v (supports [1..%v])", fv, fileVersion) } return nil }
go
func checkFileVersion(r io.Reader) error { fv, err := util.ReadInt(r) if err != nil { return fmt.Errorf("unable to verify file version: %v", err) } if fv == 0 || fv > fileVersion { return fmt.Errorf("unsupported file version: %v (supports [1..%v])", fv, fileVersion) } return nil }
[ "func", "checkFileVersion", "(", "r", "io", ".", "Reader", ")", "error", "{", "fv", ",", "err", ":=", "util", ".", "ReadInt", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"unable to verify file version: %v\"", ",", "err", ")", "\n", "}", "\n", "if", "fv", "==", "0", "||", "fv", ">", "fileVersion", "{", "return", "fmt", ".", "Errorf", "(", "\"unsupported file version: %v (supports [1..%v])\"", ",", "fv", ",", "fileVersion", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// check that the version of the file is understood by this interface
[ "check", "that", "the", "version", "of", "the", "file", "is", "understood", "by", "this", "interface" ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L660-L669
train
nats-io/nats-streaming-server
stores/filestore.go
createNewWriter
func (w *bufferedWriter) createNewWriter(file *os.File) io.Writer { w.buf = bufio.NewWriterSize(file, w.bufSize) return w.buf }
go
func (w *bufferedWriter) createNewWriter(file *os.File) io.Writer { w.buf = bufio.NewWriterSize(file, w.bufSize) return w.buf }
[ "func", "(", "w", "*", "bufferedWriter", ")", "createNewWriter", "(", "file", "*", "os", ".", "File", ")", "io", ".", "Writer", "{", "w", ".", "buf", "=", "bufio", ".", "NewWriterSize", "(", "file", ",", "w", ".", "bufSize", ")", "\n", "return", "w", ".", "buf", "\n", "}" ]
// createNewWriter creates a new buffer writer for `file` with // the bufferedWriter's current buffer size.
[ "createNewWriter", "creates", "a", "new", "buffer", "writer", "for", "file", "with", "the", "bufferedWriter", "s", "current", "buffer", "size", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L781-L784
train
nats-io/nats-streaming-server
stores/filestore.go
tryShrinkBuffer
func (w *bufferedWriter) tryShrinkBuffer(file *os.File) (io.Writer, error) { // Nothing to do if we are already at the lowest // or file not set/opened. if w.bufSize == w.minShrinkSize || file == nil { return w.buf, nil } if !w.shrinkReq { percentFilled := w.buf.Buffered() * 100 / w.bufSize if percentFilled <= bufShrinkThreshold { w.shrinkReq = true } // Wait for next tick to see if we can shrink return w.buf, nil } if err := w.buf.Flush(); err != nil { return w.buf, err } // Reduce size, but ensure it does not go below the limit w.bufSize /= 2 if w.bufSize < w.minShrinkSize { w.bufSize = w.minShrinkSize } w.buf = bufio.NewWriterSize(file, w.bufSize) // Don't reset shrinkReq unless we are down to the limit if w.bufSize == w.minShrinkSize { w.shrinkReq = true } return w.buf, nil }
go
func (w *bufferedWriter) tryShrinkBuffer(file *os.File) (io.Writer, error) { // Nothing to do if we are already at the lowest // or file not set/opened. if w.bufSize == w.minShrinkSize || file == nil { return w.buf, nil } if !w.shrinkReq { percentFilled := w.buf.Buffered() * 100 / w.bufSize if percentFilled <= bufShrinkThreshold { w.shrinkReq = true } // Wait for next tick to see if we can shrink return w.buf, nil } if err := w.buf.Flush(); err != nil { return w.buf, err } // Reduce size, but ensure it does not go below the limit w.bufSize /= 2 if w.bufSize < w.minShrinkSize { w.bufSize = w.minShrinkSize } w.buf = bufio.NewWriterSize(file, w.bufSize) // Don't reset shrinkReq unless we are down to the limit if w.bufSize == w.minShrinkSize { w.shrinkReq = true } return w.buf, nil }
[ "func", "(", "w", "*", "bufferedWriter", ")", "tryShrinkBuffer", "(", "file", "*", "os", ".", "File", ")", "(", "io", ".", "Writer", ",", "error", ")", "{", "if", "w", ".", "bufSize", "==", "w", ".", "minShrinkSize", "||", "file", "==", "nil", "{", "return", "w", ".", "buf", ",", "nil", "\n", "}", "\n", "if", "!", "w", ".", "shrinkReq", "{", "percentFilled", ":=", "w", ".", "buf", ".", "Buffered", "(", ")", "*", "100", "/", "w", ".", "bufSize", "\n", "if", "percentFilled", "<=", "bufShrinkThreshold", "{", "w", ".", "shrinkReq", "=", "true", "\n", "}", "\n", "return", "w", ".", "buf", ",", "nil", "\n", "}", "\n", "if", "err", ":=", "w", ".", "buf", ".", "Flush", "(", ")", ";", "err", "!=", "nil", "{", "return", "w", ".", "buf", ",", "err", "\n", "}", "\n", "w", ".", "bufSize", "/=", "2", "\n", "if", "w", ".", "bufSize", "<", "w", ".", "minShrinkSize", "{", "w", ".", "bufSize", "=", "w", ".", "minShrinkSize", "\n", "}", "\n", "w", ".", "buf", "=", "bufio", ".", "NewWriterSize", "(", "file", ",", "w", ".", "bufSize", ")", "\n", "if", "w", ".", "bufSize", "==", "w", ".", "minShrinkSize", "{", "w", ".", "shrinkReq", "=", "true", "\n", "}", "\n", "return", "w", ".", "buf", ",", "nil", "\n", "}" ]
// tryShrinkBuffer checks and possibly shrinks the buffer
[ "tryShrinkBuffer", "checks", "and", "possibly", "shrinks", "the", "buffer" ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L811-L840
train
nats-io/nats-streaming-server
stores/filestore.go
checkShrinkRequest
func (w *bufferedWriter) checkShrinkRequest() { percentFilled := w.buf.Buffered() * 100 / w.bufSize // If above the threshold, cancel the request. if percentFilled > bufShrinkThreshold { w.shrinkReq = false } }
go
func (w *bufferedWriter) checkShrinkRequest() { percentFilled := w.buf.Buffered() * 100 / w.bufSize // If above the threshold, cancel the request. if percentFilled > bufShrinkThreshold { w.shrinkReq = false } }
[ "func", "(", "w", "*", "bufferedWriter", ")", "checkShrinkRequest", "(", ")", "{", "percentFilled", ":=", "w", ".", "buf", ".", "Buffered", "(", ")", "*", "100", "/", "w", ".", "bufSize", "\n", "if", "percentFilled", ">", "bufShrinkThreshold", "{", "w", ".", "shrinkReq", "=", "false", "\n", "}", "\n", "}" ]
// checkShrinkRequest checks how full the buffer is, and if is above a certain // threshold, cancels the shrink request
[ "checkShrinkRequest", "checks", "how", "full", "the", "buffer", "is", "and", "if", "is", "above", "a", "certain", "threshold", "cancels", "the", "shrink", "request" ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L844-L850
train
nats-io/nats-streaming-server
stores/filestore.go
openFile
func (fm *filesManager) openFile(file *file) error { fm.Lock() if fm.isClosed { fm.Unlock() return fmt.Errorf("unable to open file %q, store is being closed", file.name) } curState := atomic.LoadInt32(&file.state) if curState == fileRemoved { fm.Unlock() return fmt.Errorf("unable to open file %q, it has been removed", file.name) } if curState != fileClosed || file.handle != nil { fm.Unlock() panic(fmt.Errorf("request to open file %q but invalid state: handle=%v - state=%v", file.name, file.handle, file.state)) } var err error if fm.limit > 0 && fm.openedFDs >= fm.limit { fm.closeUnusedFiles(file.id) } file.handle, err = openFileWithFlags(file.name, file.flags) if err == nil { atomic.StoreInt32(&file.state, fileInUse) fm.openedFDs++ } fm.Unlock() return err }
go
func (fm *filesManager) openFile(file *file) error { fm.Lock() if fm.isClosed { fm.Unlock() return fmt.Errorf("unable to open file %q, store is being closed", file.name) } curState := atomic.LoadInt32(&file.state) if curState == fileRemoved { fm.Unlock() return fmt.Errorf("unable to open file %q, it has been removed", file.name) } if curState != fileClosed || file.handle != nil { fm.Unlock() panic(fmt.Errorf("request to open file %q but invalid state: handle=%v - state=%v", file.name, file.handle, file.state)) } var err error if fm.limit > 0 && fm.openedFDs >= fm.limit { fm.closeUnusedFiles(file.id) } file.handle, err = openFileWithFlags(file.name, file.flags) if err == nil { atomic.StoreInt32(&file.state, fileInUse) fm.openedFDs++ } fm.Unlock() return err }
[ "func", "(", "fm", "*", "filesManager", ")", "openFile", "(", "file", "*", "file", ")", "error", "{", "fm", ".", "Lock", "(", ")", "\n", "if", "fm", ".", "isClosed", "{", "fm", ".", "Unlock", "(", ")", "\n", "return", "fmt", ".", "Errorf", "(", "\"unable to open file %q, store is being closed\"", ",", "file", ".", "name", ")", "\n", "}", "\n", "curState", ":=", "atomic", ".", "LoadInt32", "(", "&", "file", ".", "state", ")", "\n", "if", "curState", "==", "fileRemoved", "{", "fm", ".", "Unlock", "(", ")", "\n", "return", "fmt", ".", "Errorf", "(", "\"unable to open file %q, it has been removed\"", ",", "file", ".", "name", ")", "\n", "}", "\n", "if", "curState", "!=", "fileClosed", "||", "file", ".", "handle", "!=", "nil", "{", "fm", ".", "Unlock", "(", ")", "\n", "panic", "(", "fmt", ".", "Errorf", "(", "\"request to open file %q but invalid state: handle=%v - state=%v\"", ",", "file", ".", "name", ",", "file", ".", "handle", ",", "file", ".", "state", ")", ")", "\n", "}", "\n", "var", "err", "error", "\n", "if", "fm", ".", "limit", ">", "0", "&&", "fm", ".", "openedFDs", ">=", "fm", ".", "limit", "{", "fm", ".", "closeUnusedFiles", "(", "file", ".", "id", ")", "\n", "}", "\n", "file", ".", "handle", ",", "err", "=", "openFileWithFlags", "(", "file", ".", "name", ",", "file", ".", "flags", ")", "\n", "if", "err", "==", "nil", "{", "atomic", ".", "StoreInt32", "(", "&", "file", ".", "state", ",", "fileInUse", ")", "\n", "fm", ".", "openedFDs", "++", "\n", "}", "\n", "fm", ".", "Unlock", "(", ")", "\n", "return", "err", "\n", "}" ]
// openFile opens the given file and sets its state to `fileInUse`. // If the file manager has been closed or the file removed, this call // returns an error. // Otherwise, if the file's state is not `fileClosed` this call will panic. // This call will possibly cause opened but unused files to be closed if the // number of open file requests is above the set limit.
[ "openFile", "opens", "the", "given", "file", "and", "sets", "its", "state", "to", "fileInUse", ".", "If", "the", "file", "manager", "has", "been", "closed", "or", "the", "file", "removed", "this", "call", "returns", "an", "error", ".", "Otherwise", "if", "the", "file", "s", "state", "is", "not", "fileClosed", "this", "call", "will", "panic", ".", "This", "call", "will", "possibly", "cause", "opened", "but", "unused", "files", "to", "be", "closed", "if", "the", "number", "of", "open", "file", "requests", "is", "above", "the", "set", "limit", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L926-L952
train
nats-io/nats-streaming-server
stores/filestore.go
closeLockedFile
func (fm *filesManager) closeLockedFile(file *file) error { if !atomic.CompareAndSwapInt32(&file.state, fileInUse, fileClosing) { panic(fmt.Errorf("file %q is requested to be closed but was not locked by caller", file.name)) } fm.Lock() err := fm.doClose(file) fm.Unlock() return err }
go
func (fm *filesManager) closeLockedFile(file *file) error { if !atomic.CompareAndSwapInt32(&file.state, fileInUse, fileClosing) { panic(fmt.Errorf("file %q is requested to be closed but was not locked by caller", file.name)) } fm.Lock() err := fm.doClose(file) fm.Unlock() return err }
[ "func", "(", "fm", "*", "filesManager", ")", "closeLockedFile", "(", "file", "*", "file", ")", "error", "{", "if", "!", "atomic", ".", "CompareAndSwapInt32", "(", "&", "file", ".", "state", ",", "fileInUse", ",", "fileClosing", ")", "{", "panic", "(", "fmt", ".", "Errorf", "(", "\"file %q is requested to be closed but was not locked by caller\"", ",", "file", ".", "name", ")", ")", "\n", "}", "\n", "fm", ".", "Lock", "(", ")", "\n", "err", ":=", "fm", ".", "doClose", "(", "file", ")", "\n", "fm", ".", "Unlock", "(", ")", "\n", "return", "err", "\n", "}" ]
// closeLockedFile closes the handle of the given file, but only if the caller // has locked the file. Will panic otherwise. // If the file's beforeClose callback is not nil, this callback is invoked // before the file handle is closed.
[ "closeLockedFile", "closes", "the", "handle", "of", "the", "given", "file", "but", "only", "if", "the", "caller", "has", "locked", "the", "file", ".", "Will", "panic", "otherwise", ".", "If", "the", "file", "s", "beforeClose", "callback", "is", "not", "nil", "this", "callback", "is", "invoked", "before", "the", "file", "handle", "is", "closed", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L958-L966
train
nats-io/nats-streaming-server
stores/filestore.go
closeFileIfOpened
func (fm *filesManager) closeFileIfOpened(file *file) error { if !atomic.CompareAndSwapInt32(&file.state, fileOpened, fileClosing) { return nil } fm.Lock() err := fm.doClose(file) fm.Unlock() return err }
go
func (fm *filesManager) closeFileIfOpened(file *file) error { if !atomic.CompareAndSwapInt32(&file.state, fileOpened, fileClosing) { return nil } fm.Lock() err := fm.doClose(file) fm.Unlock() return err }
[ "func", "(", "fm", "*", "filesManager", ")", "closeFileIfOpened", "(", "file", "*", "file", ")", "error", "{", "if", "!", "atomic", ".", "CompareAndSwapInt32", "(", "&", "file", ".", "state", ",", "fileOpened", ",", "fileClosing", ")", "{", "return", "nil", "\n", "}", "\n", "fm", ".", "Lock", "(", ")", "\n", "err", ":=", "fm", ".", "doClose", "(", "file", ")", "\n", "fm", ".", "Unlock", "(", ")", "\n", "return", "err", "\n", "}" ]
// closeFileIfOpened closes the handle of the given file, but only if the // file is opened and not currently locked. Does not return any error or panic // if file is in any other state. // If the file's beforeClose callback is not nil, this callback is invoked // before the file handle is closed.
[ "closeFileIfOpened", "closes", "the", "handle", "of", "the", "given", "file", "but", "only", "if", "the", "file", "is", "opened", "and", "not", "currently", "locked", ".", "Does", "not", "return", "any", "error", "or", "panic", "if", "file", "is", "in", "any", "other", "state", ".", "If", "the", "file", "s", "beforeClose", "callback", "is", "not", "nil", "this", "callback", "is", "invoked", "before", "the", "file", "handle", "is", "closed", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L973-L981
train
nats-io/nats-streaming-server
stores/filestore.go
doClose
func (fm *filesManager) doClose(file *file) error { var err error if file.beforeClose != nil { err = file.beforeClose() } util.CloseFile(err, file.handle) // Regardless of error, we need to change the state to closed. file.handle = nil atomic.StoreInt32(&file.state, fileClosed) fm.openedFDs-- return err }
go
func (fm *filesManager) doClose(file *file) error { var err error if file.beforeClose != nil { err = file.beforeClose() } util.CloseFile(err, file.handle) // Regardless of error, we need to change the state to closed. file.handle = nil atomic.StoreInt32(&file.state, fileClosed) fm.openedFDs-- return err }
[ "func", "(", "fm", "*", "filesManager", ")", "doClose", "(", "file", "*", "file", ")", "error", "{", "var", "err", "error", "\n", "if", "file", ".", "beforeClose", "!=", "nil", "{", "err", "=", "file", ".", "beforeClose", "(", ")", "\n", "}", "\n", "util", ".", "CloseFile", "(", "err", ",", "file", ".", "handle", ")", "\n", "file", ".", "handle", "=", "nil", "\n", "atomic", ".", "StoreInt32", "(", "&", "file", ".", "state", ",", "fileClosed", ")", "\n", "fm", ".", "openedFDs", "--", "\n", "return", "err", "\n", "}" ]
// doClose closes the file handle, setting it to nil and switching state to `fileClosed`. // If a `beforeClose` callback was registered on file creation, it is invoked // before the file handler is actually closed. // Lock is required on entry.
[ "doClose", "closes", "the", "file", "handle", "setting", "it", "to", "nil", "and", "switching", "state", "to", "fileClosed", ".", "If", "a", "beforeClose", "callback", "was", "registered", "on", "file", "creation", "it", "is", "invoked", "before", "the", "file", "handler", "is", "actually", "closed", ".", "Lock", "is", "required", "on", "entry", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L1006-L1017
train
nats-io/nats-streaming-server
stores/filestore.go
lockFile
func (fm *filesManager) lockFile(file *file) (bool, error) { if atomic.CompareAndSwapInt32(&file.state, fileOpened, fileInUse) { return true, nil } return false, fm.openFile(file) }
go
func (fm *filesManager) lockFile(file *file) (bool, error) { if atomic.CompareAndSwapInt32(&file.state, fileOpened, fileInUse) { return true, nil } return false, fm.openFile(file) }
[ "func", "(", "fm", "*", "filesManager", ")", "lockFile", "(", "file", "*", "file", ")", "(", "bool", ",", "error", ")", "{", "if", "atomic", ".", "CompareAndSwapInt32", "(", "&", "file", ".", "state", ",", "fileOpened", ",", "fileInUse", ")", "{", "return", "true", ",", "nil", "\n", "}", "\n", "return", "false", ",", "fm", ".", "openFile", "(", "file", ")", "\n", "}" ]
// lockFile locks the given file. // If the file was already opened, the boolean returned is true, // otherwise, the file is opened and the call returns false.
[ "lockFile", "locks", "the", "given", "file", ".", "If", "the", "file", "was", "already", "opened", "the", "boolean", "returned", "is", "true", "otherwise", "the", "file", "is", "opened", "and", "the", "call", "returns", "false", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L1022-L1027
train
nats-io/nats-streaming-server
stores/filestore.go
unlockFile
func (fm *filesManager) unlockFile(file *file) { if !atomic.CompareAndSwapInt32(&file.state, fileInUse, fileOpened) { panic(fmt.Errorf("failed to switch state from fileInUse to fileOpened for file %q, state=%v", file.name, file.state)) } }
go
func (fm *filesManager) unlockFile(file *file) { if !atomic.CompareAndSwapInt32(&file.state, fileInUse, fileOpened) { panic(fmt.Errorf("failed to switch state from fileInUse to fileOpened for file %q, state=%v", file.name, file.state)) } }
[ "func", "(", "fm", "*", "filesManager", ")", "unlockFile", "(", "file", "*", "file", ")", "{", "if", "!", "atomic", ".", "CompareAndSwapInt32", "(", "&", "file", ".", "state", ",", "fileInUse", ",", "fileOpened", ")", "{", "panic", "(", "fmt", ".", "Errorf", "(", "\"failed to switch state from fileInUse to fileOpened for file %q, state=%v\"", ",", "file", ".", "name", ",", "file", ".", "state", ")", ")", "\n", "}", "\n", "}" ]
// unlockFile unlocks the file if currently locked, otherwise panic.
[ "unlockFile", "unlocks", "the", "file", "if", "currently", "locked", "otherwise", "panic", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L1036-L1041
train
nats-io/nats-streaming-server
stores/filestore.go
trySwitchState
func (fm *filesManager) trySwitchState(file *file, newState int32) (bool, error) { wasOpened := false wasClosed := false for i := 0; i < 10000; i++ { if atomic.CompareAndSwapInt32(&file.state, fileOpened, newState) { wasOpened = true break } if atomic.CompareAndSwapInt32(&file.state, fileClosed, newState) { wasClosed = true break } if i%1000 == 1 { time.Sleep(time.Millisecond) } } if !wasOpened && !wasClosed { return false, fmt.Errorf("file %q is still probably locked", file.name) } return wasOpened, nil }
go
func (fm *filesManager) trySwitchState(file *file, newState int32) (bool, error) { wasOpened := false wasClosed := false for i := 0; i < 10000; i++ { if atomic.CompareAndSwapInt32(&file.state, fileOpened, newState) { wasOpened = true break } if atomic.CompareAndSwapInt32(&file.state, fileClosed, newState) { wasClosed = true break } if i%1000 == 1 { time.Sleep(time.Millisecond) } } if !wasOpened && !wasClosed { return false, fmt.Errorf("file %q is still probably locked", file.name) } return wasOpened, nil }
[ "func", "(", "fm", "*", "filesManager", ")", "trySwitchState", "(", "file", "*", "file", ",", "newState", "int32", ")", "(", "bool", ",", "error", ")", "{", "wasOpened", ":=", "false", "\n", "wasClosed", ":=", "false", "\n", "for", "i", ":=", "0", ";", "i", "<", "10000", ";", "i", "++", "{", "if", "atomic", ".", "CompareAndSwapInt32", "(", "&", "file", ".", "state", ",", "fileOpened", ",", "newState", ")", "{", "wasOpened", "=", "true", "\n", "break", "\n", "}", "\n", "if", "atomic", ".", "CompareAndSwapInt32", "(", "&", "file", ".", "state", ",", "fileClosed", ",", "newState", ")", "{", "wasClosed", "=", "true", "\n", "break", "\n", "}", "\n", "if", "i", "%", "1000", "==", "1", "{", "time", ".", "Sleep", "(", "time", ".", "Millisecond", ")", "\n", "}", "\n", "}", "\n", "if", "!", "wasOpened", "&&", "!", "wasClosed", "{", "return", "false", ",", "fmt", ".", "Errorf", "(", "\"file %q is still probably locked\"", ",", "file", ".", "name", ")", "\n", "}", "\n", "return", "wasOpened", ",", "nil", "\n", "}" ]
// trySwitchState attempts to switch an initial state of `fileOpened` // or `fileClosed` to the given newState. If it can't it will return an // error, otherwise, returned a boolean to indicate if the initial state // was `fileOpened`.
[ "trySwitchState", "attempts", "to", "switch", "an", "initial", "state", "of", "fileOpened", "or", "fileClosed", "to", "the", "given", "newState", ".", "If", "it", "can", "t", "it", "will", "return", "an", "error", "otherwise", "returned", "a", "boolean", "to", "indicate", "if", "the", "initial", "state", "was", "fileOpened", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L1047-L1067
train
nats-io/nats-streaming-server
stores/filestore.go
close
func (fm *filesManager) close() error { fm.Lock() if fm.isClosed { fm.Unlock() return nil } fm.isClosed = true files := make([]*file, 0, len(fm.files)) for _, file := range fm.files { files = append(files, file) } fm.files = nil fm.Unlock() var err error for _, file := range files { wasOpened, sserr := fm.trySwitchState(file, fmClosed) if sserr != nil { if err == nil { err = sserr } } else if wasOpened { fm.Lock() if cerr := fm.doClose(file); cerr != nil && err == nil { err = cerr } fm.Unlock() } } return err }
go
func (fm *filesManager) close() error { fm.Lock() if fm.isClosed { fm.Unlock() return nil } fm.isClosed = true files := make([]*file, 0, len(fm.files)) for _, file := range fm.files { files = append(files, file) } fm.files = nil fm.Unlock() var err error for _, file := range files { wasOpened, sserr := fm.trySwitchState(file, fmClosed) if sserr != nil { if err == nil { err = sserr } } else if wasOpened { fm.Lock() if cerr := fm.doClose(file); cerr != nil && err == nil { err = cerr } fm.Unlock() } } return err }
[ "func", "(", "fm", "*", "filesManager", ")", "close", "(", ")", "error", "{", "fm", ".", "Lock", "(", ")", "\n", "if", "fm", ".", "isClosed", "{", "fm", ".", "Unlock", "(", ")", "\n", "return", "nil", "\n", "}", "\n", "fm", ".", "isClosed", "=", "true", "\n", "files", ":=", "make", "(", "[", "]", "*", "file", ",", "0", ",", "len", "(", "fm", ".", "files", ")", ")", "\n", "for", "_", ",", "file", ":=", "range", "fm", ".", "files", "{", "files", "=", "append", "(", "files", ",", "file", ")", "\n", "}", "\n", "fm", ".", "files", "=", "nil", "\n", "fm", ".", "Unlock", "(", ")", "\n", "var", "err", "error", "\n", "for", "_", ",", "file", ":=", "range", "files", "{", "wasOpened", ",", "sserr", ":=", "fm", ".", "trySwitchState", "(", "file", ",", "fmClosed", ")", "\n", "if", "sserr", "!=", "nil", "{", "if", "err", "==", "nil", "{", "err", "=", "sserr", "\n", "}", "\n", "}", "else", "if", "wasOpened", "{", "fm", ".", "Lock", "(", ")", "\n", "if", "cerr", ":=", "fm", ".", "doClose", "(", "file", ")", ";", "cerr", "!=", "nil", "&&", "err", "==", "nil", "{", "err", "=", "cerr", "\n", "}", "\n", "fm", ".", "Unlock", "(", ")", "\n", "}", "\n", "}", "\n", "return", "err", "\n", "}" ]
// close the files manager, including all files currently opened. // Returns the first error encountered when closing the files.
[ "close", "the", "files", "manager", "including", "all", "files", "currently", "opened", ".", "Returns", "the", "first", "error", "encountered", "when", "closing", "the", "files", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L1147-L1178
train
nats-io/nats-streaming-server
stores/filestore.go
Init
func (fs *FileStore) Init(info *spb.ServerInfo) error { fs.Lock() defer fs.Unlock() if fs.serverFile == nil { var err error // Open/Create the server file (note that this file must not be opened, // in APPEND mode to allow truncate to work). fs.serverFile, err = fs.fm.createFile(serverFileName, os.O_RDWR|os.O_CREATE, nil) if err != nil { return err } } else { if _, err := fs.fm.lockFile(fs.serverFile); err != nil { return err } } f := fs.serverFile.handle // defer is ok for this function... defer fs.fm.unlockFile(fs.serverFile) // Truncate the file (4 is the size of the fileVersion record) if err := f.Truncate(4); err != nil { return err } // Move offset to 4 (truncate does not do that) if _, err := f.Seek(4, io.SeekStart); err != nil { return err } // ServerInfo record is not typed. We also don't pass a reusable buffer. if _, _, err := writeRecord(f, nil, recNoType, info, info.Size(), fs.crcTable); err != nil { return err } return nil }
go
func (fs *FileStore) Init(info *spb.ServerInfo) error { fs.Lock() defer fs.Unlock() if fs.serverFile == nil { var err error // Open/Create the server file (note that this file must not be opened, // in APPEND mode to allow truncate to work). fs.serverFile, err = fs.fm.createFile(serverFileName, os.O_RDWR|os.O_CREATE, nil) if err != nil { return err } } else { if _, err := fs.fm.lockFile(fs.serverFile); err != nil { return err } } f := fs.serverFile.handle // defer is ok for this function... defer fs.fm.unlockFile(fs.serverFile) // Truncate the file (4 is the size of the fileVersion record) if err := f.Truncate(4); err != nil { return err } // Move offset to 4 (truncate does not do that) if _, err := f.Seek(4, io.SeekStart); err != nil { return err } // ServerInfo record is not typed. We also don't pass a reusable buffer. if _, _, err := writeRecord(f, nil, recNoType, info, info.Size(), fs.crcTable); err != nil { return err } return nil }
[ "func", "(", "fs", "*", "FileStore", ")", "Init", "(", "info", "*", "spb", ".", "ServerInfo", ")", "error", "{", "fs", ".", "Lock", "(", ")", "\n", "defer", "fs", ".", "Unlock", "(", ")", "\n", "if", "fs", ".", "serverFile", "==", "nil", "{", "var", "err", "error", "\n", "fs", ".", "serverFile", ",", "err", "=", "fs", ".", "fm", ".", "createFile", "(", "serverFileName", ",", "os", ".", "O_RDWR", "|", "os", ".", "O_CREATE", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "else", "{", "if", "_", ",", "err", ":=", "fs", ".", "fm", ".", "lockFile", "(", "fs", ".", "serverFile", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "f", ":=", "fs", ".", "serverFile", ".", "handle", "\n", "defer", "fs", ".", "fm", ".", "unlockFile", "(", "fs", ".", "serverFile", ")", "\n", "if", "err", ":=", "f", ".", "Truncate", "(", "4", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "_", ",", "err", ":=", "f", ".", "Seek", "(", "4", ",", "io", ".", "SeekStart", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "_", ",", "_", ",", "err", ":=", "writeRecord", "(", "f", ",", "nil", ",", "recNoType", ",", "info", ",", "info", ".", "Size", "(", ")", ",", "fs", ".", "crcTable", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Init is used to persist server's information after the first start
[ "Init", "is", "used", "to", "persist", "server", "s", "information", "after", "the", "first", "start" ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L1461-L1495
train
nats-io/nats-streaming-server
stores/filestore.go
recoverClients
func (fs *FileStore) recoverClients() ([]*Client, error) { var err error var recType recordType var recSize int _buf := [256]byte{} buf := _buf[:] offset := int64(4) // Create a buffered reader to speed-up recovery br := bufio.NewReaderSize(fs.clientsFile.handle, defaultBufSize) for { buf, recSize, recType, err = readRecord(br, buf, true, fs.crcTable, fs.opts.DoCRC) if err != nil { switch err { case io.EOF: err = nil case errNeedRewind: err = fs.fm.truncateFile(fs.clientsFile, offset) default: err = fs.handleUnexpectedEOF(err, fs.clientsFile, offset, true) } if err == nil { break } return nil, err } readBytes := int64(recSize + recordHeaderSize) offset += readBytes fs.cliFileSize += readBytes switch recType { case addClient: c := &Client{} if err := c.ClientInfo.Unmarshal(buf[:recSize]); err != nil { return nil, err } // Add to the map. Note that if one already exists, which should // not, just replace with this most recent one. fs.clients[c.ID] = c case delClient: c := spb.ClientDelete{} if err := c.Unmarshal(buf[:recSize]); err != nil { return nil, err } delete(fs.clients, c.ID) fs.cliDeleteRecs++ default: return nil, fmt.Errorf("invalid client record type: %v", recType) } } clients := make([]*Client, len(fs.clients)) i := 0 // Convert the map into an array for _, c := range fs.clients { clients[i] = c i++ } return clients, nil }
go
func (fs *FileStore) recoverClients() ([]*Client, error) { var err error var recType recordType var recSize int _buf := [256]byte{} buf := _buf[:] offset := int64(4) // Create a buffered reader to speed-up recovery br := bufio.NewReaderSize(fs.clientsFile.handle, defaultBufSize) for { buf, recSize, recType, err = readRecord(br, buf, true, fs.crcTable, fs.opts.DoCRC) if err != nil { switch err { case io.EOF: err = nil case errNeedRewind: err = fs.fm.truncateFile(fs.clientsFile, offset) default: err = fs.handleUnexpectedEOF(err, fs.clientsFile, offset, true) } if err == nil { break } return nil, err } readBytes := int64(recSize + recordHeaderSize) offset += readBytes fs.cliFileSize += readBytes switch recType { case addClient: c := &Client{} if err := c.ClientInfo.Unmarshal(buf[:recSize]); err != nil { return nil, err } // Add to the map. Note that if one already exists, which should // not, just replace with this most recent one. fs.clients[c.ID] = c case delClient: c := spb.ClientDelete{} if err := c.Unmarshal(buf[:recSize]); err != nil { return nil, err } delete(fs.clients, c.ID) fs.cliDeleteRecs++ default: return nil, fmt.Errorf("invalid client record type: %v", recType) } } clients := make([]*Client, len(fs.clients)) i := 0 // Convert the map into an array for _, c := range fs.clients { clients[i] = c i++ } return clients, nil }
[ "func", "(", "fs", "*", "FileStore", ")", "recoverClients", "(", ")", "(", "[", "]", "*", "Client", ",", "error", ")", "{", "var", "err", "error", "\n", "var", "recType", "recordType", "\n", "var", "recSize", "int", "\n", "_buf", ":=", "[", "256", "]", "byte", "{", "}", "\n", "buf", ":=", "_buf", "[", ":", "]", "\n", "offset", ":=", "int64", "(", "4", ")", "\n", "br", ":=", "bufio", ".", "NewReaderSize", "(", "fs", ".", "clientsFile", ".", "handle", ",", "defaultBufSize", ")", "\n", "for", "{", "buf", ",", "recSize", ",", "recType", ",", "err", "=", "readRecord", "(", "br", ",", "buf", ",", "true", ",", "fs", ".", "crcTable", ",", "fs", ".", "opts", ".", "DoCRC", ")", "\n", "if", "err", "!=", "nil", "{", "switch", "err", "{", "case", "io", ".", "EOF", ":", "err", "=", "nil", "\n", "case", "errNeedRewind", ":", "err", "=", "fs", ".", "fm", ".", "truncateFile", "(", "fs", ".", "clientsFile", ",", "offset", ")", "\n", "default", ":", "err", "=", "fs", ".", "handleUnexpectedEOF", "(", "err", ",", "fs", ".", "clientsFile", ",", "offset", ",", "true", ")", "\n", "}", "\n", "if", "err", "==", "nil", "{", "break", "\n", "}", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "readBytes", ":=", "int64", "(", "recSize", "+", "recordHeaderSize", ")", "\n", "offset", "+=", "readBytes", "\n", "fs", ".", "cliFileSize", "+=", "readBytes", "\n", "switch", "recType", "{", "case", "addClient", ":", "c", ":=", "&", "Client", "{", "}", "\n", "if", "err", ":=", "c", ".", "ClientInfo", ".", "Unmarshal", "(", "buf", "[", ":", "recSize", "]", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "fs", ".", "clients", "[", "c", ".", "ID", "]", "=", "c", "\n", "case", "delClient", ":", "c", ":=", "spb", ".", "ClientDelete", "{", "}", "\n", "if", "err", ":=", "c", ".", "Unmarshal", "(", "buf", "[", ":", "recSize", "]", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "delete", "(", "fs", ".", "clients", ",", "c", ".", "ID", ")", "\n", "fs", ".", "cliDeleteRecs", "++", "\n", "default", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"invalid client record type: %v\"", ",", "recType", ")", "\n", "}", "\n", "}", "\n", "clients", ":=", "make", "(", "[", "]", "*", "Client", ",", "len", "(", "fs", ".", "clients", ")", ")", "\n", "i", ":=", "0", "\n", "for", "_", ",", "c", ":=", "range", "fs", ".", "clients", "{", "clients", "[", "i", "]", "=", "c", "\n", "i", "++", "\n", "}", "\n", "return", "clients", ",", "nil", "\n", "}" ]
// recoverClients reads the client files and returns an array of RecoveredClient
[ "recoverClients", "reads", "the", "client", "files", "and", "returns", "an", "array", "of", "RecoveredClient" ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L1498-L1557
train
nats-io/nats-streaming-server
stores/filestore.go
recoverServerInfo
func (fs *FileStore) recoverServerInfo() (*spb.ServerInfo, error) { info := &spb.ServerInfo{} buf, size, _, err := readRecord(fs.serverFile.handle, nil, false, fs.crcTable, fs.opts.DoCRC) if err != nil { if err == io.EOF { // We are done, no state recovered return nil, nil } fs.log.Errorf("Server file %q corrupted: %v", fs.serverFile.name, err) fs.log.Errorf("Follow instructions in documentation in order to recover from this") return nil, err } // Check that the size of the file is consistent with the size // of the record we are supposed to recover. Account for the // 12 bytes (4 + recordHeaderSize) corresponding to the fileVersion and // record header. fstat, err := fs.serverFile.handle.Stat() if err != nil { return nil, err } expectedSize := int64(size + 4 + recordHeaderSize) if fstat.Size() != expectedSize { return nil, fmt.Errorf("incorrect file size, expected %v bytes, got %v bytes", expectedSize, fstat.Size()) } // Reconstruct now if err := info.Unmarshal(buf[:size]); err != nil { return nil, err } return info, nil }
go
func (fs *FileStore) recoverServerInfo() (*spb.ServerInfo, error) { info := &spb.ServerInfo{} buf, size, _, err := readRecord(fs.serverFile.handle, nil, false, fs.crcTable, fs.opts.DoCRC) if err != nil { if err == io.EOF { // We are done, no state recovered return nil, nil } fs.log.Errorf("Server file %q corrupted: %v", fs.serverFile.name, err) fs.log.Errorf("Follow instructions in documentation in order to recover from this") return nil, err } // Check that the size of the file is consistent with the size // of the record we are supposed to recover. Account for the // 12 bytes (4 + recordHeaderSize) corresponding to the fileVersion and // record header. fstat, err := fs.serverFile.handle.Stat() if err != nil { return nil, err } expectedSize := int64(size + 4 + recordHeaderSize) if fstat.Size() != expectedSize { return nil, fmt.Errorf("incorrect file size, expected %v bytes, got %v bytes", expectedSize, fstat.Size()) } // Reconstruct now if err := info.Unmarshal(buf[:size]); err != nil { return nil, err } return info, nil }
[ "func", "(", "fs", "*", "FileStore", ")", "recoverServerInfo", "(", ")", "(", "*", "spb", ".", "ServerInfo", ",", "error", ")", "{", "info", ":=", "&", "spb", ".", "ServerInfo", "{", "}", "\n", "buf", ",", "size", ",", "_", ",", "err", ":=", "readRecord", "(", "fs", ".", "serverFile", ".", "handle", ",", "nil", ",", "false", ",", "fs", ".", "crcTable", ",", "fs", ".", "opts", ".", "DoCRC", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "io", ".", "EOF", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "fs", ".", "log", ".", "Errorf", "(", "\"Server file %q corrupted: %v\"", ",", "fs", ".", "serverFile", ".", "name", ",", "err", ")", "\n", "fs", ".", "log", ".", "Errorf", "(", "\"Follow instructions in documentation in order to recover from this\"", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "fstat", ",", "err", ":=", "fs", ".", "serverFile", ".", "handle", ".", "Stat", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "expectedSize", ":=", "int64", "(", "size", "+", "4", "+", "recordHeaderSize", ")", "\n", "if", "fstat", ".", "Size", "(", ")", "!=", "expectedSize", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"incorrect file size, expected %v bytes, got %v bytes\"", ",", "expectedSize", ",", "fstat", ".", "Size", "(", ")", ")", "\n", "}", "\n", "if", "err", ":=", "info", ".", "Unmarshal", "(", "buf", "[", ":", "size", "]", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "info", ",", "nil", "\n", "}" ]
// recoverServerInfo reads the server file and returns a ServerInfo structure
[ "recoverServerInfo", "reads", "the", "server", "file", "and", "returns", "a", "ServerInfo", "structure" ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L1560-L1590
train
nats-io/nats-streaming-server
stores/filestore.go
shouldCompactClientFile
func (fs *FileStore) shouldCompactClientFile() bool { // Global switch if !fs.opts.CompactEnabled { return false } // Check that if minimum file size is set, the client file // is at least at the minimum. if fs.opts.CompactMinFileSize > 0 && fs.cliFileSize < fs.opts.CompactMinFileSize { return false } // Check fragmentation frag := fs.cliDeleteRecs * 100 / (fs.cliDeleteRecs + len(fs.clients)) if frag < fs.opts.CompactFragmentation { return false } // Check that we don't do too often if time.Since(fs.cliCompactTS) < fs.compactItvl { return false } return true }
go
func (fs *FileStore) shouldCompactClientFile() bool { // Global switch if !fs.opts.CompactEnabled { return false } // Check that if minimum file size is set, the client file // is at least at the minimum. if fs.opts.CompactMinFileSize > 0 && fs.cliFileSize < fs.opts.CompactMinFileSize { return false } // Check fragmentation frag := fs.cliDeleteRecs * 100 / (fs.cliDeleteRecs + len(fs.clients)) if frag < fs.opts.CompactFragmentation { return false } // Check that we don't do too often if time.Since(fs.cliCompactTS) < fs.compactItvl { return false } return true }
[ "func", "(", "fs", "*", "FileStore", ")", "shouldCompactClientFile", "(", ")", "bool", "{", "if", "!", "fs", ".", "opts", ".", "CompactEnabled", "{", "return", "false", "\n", "}", "\n", "if", "fs", ".", "opts", ".", "CompactMinFileSize", ">", "0", "&&", "fs", ".", "cliFileSize", "<", "fs", ".", "opts", ".", "CompactMinFileSize", "{", "return", "false", "\n", "}", "\n", "frag", ":=", "fs", ".", "cliDeleteRecs", "*", "100", "/", "(", "fs", ".", "cliDeleteRecs", "+", "len", "(", "fs", ".", "clients", ")", ")", "\n", "if", "frag", "<", "fs", ".", "opts", ".", "CompactFragmentation", "{", "return", "false", "\n", "}", "\n", "if", "time", ".", "Since", "(", "fs", ".", "cliCompactTS", ")", "<", "fs", ".", "compactItvl", "{", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}" ]
// shouldCompactClientFile returns true if the client file should be compacted // Lock is held by caller
[ "shouldCompactClientFile", "returns", "true", "if", "the", "client", "file", "should", "be", "compacted", "Lock", "is", "held", "by", "caller" ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L1704-L1724
train
nats-io/nats-streaming-server
stores/filestore.go
compactClientFile
func (fs *FileStore) compactClientFile(orgFileName string) error { // Open a temporary file tmpFile, err := getTempFile(fs.fm.rootDir, clientsFileName) if err != nil { return err } defer func() { if tmpFile != nil { tmpFile.Close() os.Remove(tmpFile.Name()) } }() bw := bufio.NewWriterSize(tmpFile, defaultBufSize) fileSize := int64(0) size := 0 _buf := [256]byte{} buf := _buf[:] // Dump the content of active clients into the temporary file. for _, c := range fs.clients { buf, size, err = writeRecord(bw, buf, addClient, &c.ClientInfo, c.ClientInfo.Size(), fs.crcTable) if err != nil { return err } fileSize += int64(size) } // Flush the buffer on disk if err := bw.Flush(); err != nil { return err } // Start by closing the temporary file. if err := tmpFile.Close(); err != nil { return err } // Rename the tmp file to original file name if err := os.Rename(tmpFile.Name(), orgFileName); err != nil { return err } // Avoid unnecessary attempt to cleanup tmpFile = nil fs.cliDeleteRecs = 0 fs.cliFileSize = fileSize fs.cliCompactTS = time.Now() return nil }
go
func (fs *FileStore) compactClientFile(orgFileName string) error { // Open a temporary file tmpFile, err := getTempFile(fs.fm.rootDir, clientsFileName) if err != nil { return err } defer func() { if tmpFile != nil { tmpFile.Close() os.Remove(tmpFile.Name()) } }() bw := bufio.NewWriterSize(tmpFile, defaultBufSize) fileSize := int64(0) size := 0 _buf := [256]byte{} buf := _buf[:] // Dump the content of active clients into the temporary file. for _, c := range fs.clients { buf, size, err = writeRecord(bw, buf, addClient, &c.ClientInfo, c.ClientInfo.Size(), fs.crcTable) if err != nil { return err } fileSize += int64(size) } // Flush the buffer on disk if err := bw.Flush(); err != nil { return err } // Start by closing the temporary file. if err := tmpFile.Close(); err != nil { return err } // Rename the tmp file to original file name if err := os.Rename(tmpFile.Name(), orgFileName); err != nil { return err } // Avoid unnecessary attempt to cleanup tmpFile = nil fs.cliDeleteRecs = 0 fs.cliFileSize = fileSize fs.cliCompactTS = time.Now() return nil }
[ "func", "(", "fs", "*", "FileStore", ")", "compactClientFile", "(", "orgFileName", "string", ")", "error", "{", "tmpFile", ",", "err", ":=", "getTempFile", "(", "fs", ".", "fm", ".", "rootDir", ",", "clientsFileName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "func", "(", ")", "{", "if", "tmpFile", "!=", "nil", "{", "tmpFile", ".", "Close", "(", ")", "\n", "os", ".", "Remove", "(", "tmpFile", ".", "Name", "(", ")", ")", "\n", "}", "\n", "}", "(", ")", "\n", "bw", ":=", "bufio", ".", "NewWriterSize", "(", "tmpFile", ",", "defaultBufSize", ")", "\n", "fileSize", ":=", "int64", "(", "0", ")", "\n", "size", ":=", "0", "\n", "_buf", ":=", "[", "256", "]", "byte", "{", "}", "\n", "buf", ":=", "_buf", "[", ":", "]", "\n", "for", "_", ",", "c", ":=", "range", "fs", ".", "clients", "{", "buf", ",", "size", ",", "err", "=", "writeRecord", "(", "bw", ",", "buf", ",", "addClient", ",", "&", "c", ".", "ClientInfo", ",", "c", ".", "ClientInfo", ".", "Size", "(", ")", ",", "fs", ".", "crcTable", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "fileSize", "+=", "int64", "(", "size", ")", "\n", "}", "\n", "if", "err", ":=", "bw", ".", "Flush", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "tmpFile", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "os", ".", "Rename", "(", "tmpFile", ".", "Name", "(", ")", ",", "orgFileName", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "tmpFile", "=", "nil", "\n", "fs", ".", "cliDeleteRecs", "=", "0", "\n", "fs", ".", "cliFileSize", "=", "fileSize", "\n", "fs", ".", "cliCompactTS", "=", "time", ".", "Now", "(", ")", "\n", "return", "nil", "\n", "}" ]
// Rewrite the content of the clients map into a temporary file, // then swap back to active file. // Store lock held on entry
[ "Rewrite", "the", "content", "of", "the", "clients", "map", "into", "a", "temporary", "file", "then", "swap", "back", "to", "active", "file", ".", "Store", "lock", "held", "on", "entry" ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L1729-L1773
train
nats-io/nats-streaming-server
stores/filestore.go
Close
func (fs *FileStore) Close() error { fs.Lock() if fs.closed { fs.Unlock() return nil } fs.closed = true err := fs.genericStore.close() fm := fs.fm lockFile := fs.lockFile fs.Unlock() if fm != nil { if fmerr := fm.close(); fmerr != nil && err == nil { err = fmerr } } if lockFile != nil { err = util.CloseFile(err, lockFile) } return err }
go
func (fs *FileStore) Close() error { fs.Lock() if fs.closed { fs.Unlock() return nil } fs.closed = true err := fs.genericStore.close() fm := fs.fm lockFile := fs.lockFile fs.Unlock() if fm != nil { if fmerr := fm.close(); fmerr != nil && err == nil { err = fmerr } } if lockFile != nil { err = util.CloseFile(err, lockFile) } return err }
[ "func", "(", "fs", "*", "FileStore", ")", "Close", "(", ")", "error", "{", "fs", ".", "Lock", "(", ")", "\n", "if", "fs", ".", "closed", "{", "fs", ".", "Unlock", "(", ")", "\n", "return", "nil", "\n", "}", "\n", "fs", ".", "closed", "=", "true", "\n", "err", ":=", "fs", ".", "genericStore", ".", "close", "(", ")", "\n", "fm", ":=", "fs", ".", "fm", "\n", "lockFile", ":=", "fs", ".", "lockFile", "\n", "fs", ".", "Unlock", "(", ")", "\n", "if", "fm", "!=", "nil", "{", "if", "fmerr", ":=", "fm", ".", "close", "(", ")", ";", "fmerr", "!=", "nil", "&&", "err", "==", "nil", "{", "err", "=", "fmerr", "\n", "}", "\n", "}", "\n", "if", "lockFile", "!=", "nil", "{", "err", "=", "util", ".", "CloseFile", "(", "err", ",", "lockFile", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// Close closes all stores.
[ "Close", "closes", "all", "stores", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L1788-L1811
train
nats-io/nats-streaming-server
stores/filestore.go
beforeDataFileCloseCb
func (ms *FileMsgStore) beforeDataFileCloseCb(fslice *fileSlice) beforeFileClose { return func() error { if fslice != ms.writeSlice { return nil } if ms.bw != nil && ms.bw.buf != nil && ms.bw.buf.Buffered() > 0 { if err := ms.bw.buf.Flush(); err != nil { return err } } if ms.fstore.opts.DoSync { if err := fslice.file.handle.Sync(); err != nil { return err } } ms.writer = nil return nil } }
go
func (ms *FileMsgStore) beforeDataFileCloseCb(fslice *fileSlice) beforeFileClose { return func() error { if fslice != ms.writeSlice { return nil } if ms.bw != nil && ms.bw.buf != nil && ms.bw.buf.Buffered() > 0 { if err := ms.bw.buf.Flush(); err != nil { return err } } if ms.fstore.opts.DoSync { if err := fslice.file.handle.Sync(); err != nil { return err } } ms.writer = nil return nil } }
[ "func", "(", "ms", "*", "FileMsgStore", ")", "beforeDataFileCloseCb", "(", "fslice", "*", "fileSlice", ")", "beforeFileClose", "{", "return", "func", "(", ")", "error", "{", "if", "fslice", "!=", "ms", ".", "writeSlice", "{", "return", "nil", "\n", "}", "\n", "if", "ms", ".", "bw", "!=", "nil", "&&", "ms", ".", "bw", ".", "buf", "!=", "nil", "&&", "ms", ".", "bw", ".", "buf", ".", "Buffered", "(", ")", ">", "0", "{", "if", "err", ":=", "ms", ".", "bw", ".", "buf", ".", "Flush", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "if", "ms", ".", "fstore", ".", "opts", ".", "DoSync", "{", "if", "err", ":=", "fslice", ".", "file", ".", "handle", ".", "Sync", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "ms", ".", "writer", "=", "nil", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// beforeDataFileCloseCb returns a beforeFileClose callback to be used // by FileMsgStore's files when a data file for that slice is being closed. // This is invoked asynchronously and should not acquire the store's lock. // That being said, we have the guarantee that this will be not be invoked // concurrently for a given file and that the store will not be using this file.
[ "beforeDataFileCloseCb", "returns", "a", "beforeFileClose", "callback", "to", "be", "used", "by", "FileMsgStore", "s", "files", "when", "a", "data", "file", "for", "that", "slice", "is", "being", "closed", ".", "This", "is", "invoked", "asynchronously", "and", "should", "not", "acquire", "the", "store", "s", "lock", ".", "That", "being", "said", "we", "have", "the", "guarantee", "that", "this", "will", "be", "not", "be", "invoked", "concurrently", "for", "a", "given", "file", "and", "that", "the", "store", "will", "not", "be", "using", "this", "file", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L2069-L2087
train
nats-io/nats-streaming-server
stores/filestore.go
beforeIndexFileCloseCb
func (ms *FileMsgStore) beforeIndexFileCloseCb(fslice *fileSlice) beforeFileClose { return func() error { if fslice != ms.writeSlice { return nil } if len(ms.bufferedMsgs) > 0 { if err := ms.processBufferedMsgs(fslice); err != nil { return err } } if ms.fstore.opts.DoSync { if err := fslice.idxFile.handle.Sync(); err != nil { return err } } return nil } }
go
func (ms *FileMsgStore) beforeIndexFileCloseCb(fslice *fileSlice) beforeFileClose { return func() error { if fslice != ms.writeSlice { return nil } if len(ms.bufferedMsgs) > 0 { if err := ms.processBufferedMsgs(fslice); err != nil { return err } } if ms.fstore.opts.DoSync { if err := fslice.idxFile.handle.Sync(); err != nil { return err } } return nil } }
[ "func", "(", "ms", "*", "FileMsgStore", ")", "beforeIndexFileCloseCb", "(", "fslice", "*", "fileSlice", ")", "beforeFileClose", "{", "return", "func", "(", ")", "error", "{", "if", "fslice", "!=", "ms", ".", "writeSlice", "{", "return", "nil", "\n", "}", "\n", "if", "len", "(", "ms", ".", "bufferedMsgs", ")", ">", "0", "{", "if", "err", ":=", "ms", ".", "processBufferedMsgs", "(", "fslice", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "if", "ms", ".", "fstore", ".", "opts", ".", "DoSync", "{", "if", "err", ":=", "fslice", ".", "idxFile", ".", "handle", ".", "Sync", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// beforeIndexFileCloseCb returns a beforeFileClose callback to be used // by FileMsgStore's files when an index file for that slice is being closed. // This is invoked asynchronously and should not acquire the store's lock. // That being said, we have the guarantee that this will be not be invoked // concurrently for a given file and that the store will not be using this file.
[ "beforeIndexFileCloseCb", "returns", "a", "beforeFileClose", "callback", "to", "be", "used", "by", "FileMsgStore", "s", "files", "when", "an", "index", "file", "for", "that", "slice", "is", "being", "closed", ".", "This", "is", "invoked", "asynchronously", "and", "should", "not", "acquire", "the", "store", "s", "lock", ".", "That", "being", "said", "we", "have", "the", "guarantee", "that", "this", "will", "be", "not", "be", "invoked", "concurrently", "for", "a", "given", "file", "and", "that", "the", "store", "will", "not", "be", "using", "this", "file", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L2094-L2111
train
nats-io/nats-streaming-server
stores/filestore.go
setFile
func (ms *FileMsgStore) setFile(fslice *fileSlice, offset int64) error { var err error file := fslice.file.handle ms.writer = file if file != nil && ms.bw != nil { ms.writer = ms.bw.createNewWriter(file) } if offset == -1 { ms.wOffset, err = file.Seek(0, io.SeekEnd) } else { ms.wOffset = offset } return err }
go
func (ms *FileMsgStore) setFile(fslice *fileSlice, offset int64) error { var err error file := fslice.file.handle ms.writer = file if file != nil && ms.bw != nil { ms.writer = ms.bw.createNewWriter(file) } if offset == -1 { ms.wOffset, err = file.Seek(0, io.SeekEnd) } else { ms.wOffset = offset } return err }
[ "func", "(", "ms", "*", "FileMsgStore", ")", "setFile", "(", "fslice", "*", "fileSlice", ",", "offset", "int64", ")", "error", "{", "var", "err", "error", "\n", "file", ":=", "fslice", ".", "file", ".", "handle", "\n", "ms", ".", "writer", "=", "file", "\n", "if", "file", "!=", "nil", "&&", "ms", ".", "bw", "!=", "nil", "{", "ms", ".", "writer", "=", "ms", ".", "bw", ".", "createNewWriter", "(", "file", ")", "\n", "}", "\n", "if", "offset", "==", "-", "1", "{", "ms", ".", "wOffset", ",", "err", "=", "file", ".", "Seek", "(", "0", ",", "io", ".", "SeekEnd", ")", "\n", "}", "else", "{", "ms", ".", "wOffset", "=", "offset", "\n", "}", "\n", "return", "err", "\n", "}" ]
// setFile sets the current data and index file. // The buffered writer is recreated.
[ "setFile", "sets", "the", "current", "data", "and", "index", "file", ".", "The", "buffered", "writer", "is", "recreated", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L2115-L2128
train
nats-io/nats-streaming-server
stores/filestore.go
lockFiles
func (ms *FileMsgStore) lockFiles(fslice *fileSlice) error { return ms.doLockFiles(fslice, false) }
go
func (ms *FileMsgStore) lockFiles(fslice *fileSlice) error { return ms.doLockFiles(fslice, false) }
[ "func", "(", "ms", "*", "FileMsgStore", ")", "lockFiles", "(", "fslice", "*", "fileSlice", ")", "error", "{", "return", "ms", ".", "doLockFiles", "(", "fslice", ",", "false", ")", "\n", "}" ]
// lockFiles locks the data and index files of the given file slice. // If files were closed they are opened in this call, and if so, // and if this slice is the write slice, the writer and offset are reset.
[ "lockFiles", "locks", "the", "data", "and", "index", "files", "of", "the", "given", "file", "slice", ".", "If", "files", "were", "closed", "they", "are", "opened", "in", "this", "call", "and", "if", "so", "and", "if", "this", "slice", "is", "the", "write", "slice", "the", "writer", "and", "offset", "are", "reset", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L2174-L2176
train
nats-io/nats-streaming-server
stores/filestore.go
lockIndexFile
func (ms *FileMsgStore) lockIndexFile(fslice *fileSlice) error { return ms.doLockFiles(fslice, true) }
go
func (ms *FileMsgStore) lockIndexFile(fslice *fileSlice) error { return ms.doLockFiles(fslice, true) }
[ "func", "(", "ms", "*", "FileMsgStore", ")", "lockIndexFile", "(", "fslice", "*", "fileSlice", ")", "error", "{", "return", "ms", ".", "doLockFiles", "(", "fslice", ",", "true", ")", "\n", "}" ]
// lockIndexFile locks the index file of the given file slice. // If the file was closed it is opened in this call.
[ "lockIndexFile", "locks", "the", "index", "file", "of", "the", "given", "file", "slice", ".", "If", "the", "file", "was", "closed", "it", "is", "opened", "in", "this", "call", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L2180-L2182
train
nats-io/nats-streaming-server
stores/filestore.go
unlockIndexFile
func (ms *FileMsgStore) unlockIndexFile(fslice *fileSlice) { ms.fm.unlockFile(fslice.idxFile) }
go
func (ms *FileMsgStore) unlockIndexFile(fslice *fileSlice) { ms.fm.unlockFile(fslice.idxFile) }
[ "func", "(", "ms", "*", "FileMsgStore", ")", "unlockIndexFile", "(", "fslice", "*", "fileSlice", ")", "{", "ms", ".", "fm", ".", "unlockFile", "(", "fslice", ".", "idxFile", ")", "\n", "}" ]
// unlockIndexFile unlocks the already locked index file of the given file slice.
[ "unlockIndexFile", "unlocks", "the", "already", "locked", "index", "file", "of", "the", "given", "file", "slice", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L2185-L2187
train
nats-io/nats-streaming-server
stores/filestore.go
unlockFiles
func (ms *FileMsgStore) unlockFiles(fslice *fileSlice) { ms.fm.unlockFile(fslice.file) ms.fm.unlockFile(fslice.idxFile) }
go
func (ms *FileMsgStore) unlockFiles(fslice *fileSlice) { ms.fm.unlockFile(fslice.file) ms.fm.unlockFile(fslice.idxFile) }
[ "func", "(", "ms", "*", "FileMsgStore", ")", "unlockFiles", "(", "fslice", "*", "fileSlice", ")", "{", "ms", ".", "fm", ".", "unlockFile", "(", "fslice", ".", "file", ")", "\n", "ms", ".", "fm", ".", "unlockFile", "(", "fslice", ".", "idxFile", ")", "\n", "}" ]
// unlockFiles unlocks both data and index files of the given file slice.
[ "unlockFiles", "unlocks", "both", "data", "and", "index", "files", "of", "the", "given", "file", "slice", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L2190-L2193
train
nats-io/nats-streaming-server
stores/filestore.go
writeIndex
func (ms *FileMsgStore) writeIndex(w io.Writer, seq uint64, offset, timestamp int64, msgSize int) error { _buf := [msgIndexRecSize]byte{} buf := _buf[:] ms.addIndex(buf, seq, offset, timestamp, msgSize) _, err := w.Write(buf[:msgIndexRecSize]) return err }
go
func (ms *FileMsgStore) writeIndex(w io.Writer, seq uint64, offset, timestamp int64, msgSize int) error { _buf := [msgIndexRecSize]byte{} buf := _buf[:] ms.addIndex(buf, seq, offset, timestamp, msgSize) _, err := w.Write(buf[:msgIndexRecSize]) return err }
[ "func", "(", "ms", "*", "FileMsgStore", ")", "writeIndex", "(", "w", "io", ".", "Writer", ",", "seq", "uint64", ",", "offset", ",", "timestamp", "int64", ",", "msgSize", "int", ")", "error", "{", "_buf", ":=", "[", "msgIndexRecSize", "]", "byte", "{", "}", "\n", "buf", ":=", "_buf", "[", ":", "]", "\n", "ms", ".", "addIndex", "(", "buf", ",", "seq", ",", "offset", ",", "timestamp", ",", "msgSize", ")", "\n", "_", ",", "err", ":=", "w", ".", "Write", "(", "buf", "[", ":", "msgIndexRecSize", "]", ")", "\n", "return", "err", "\n", "}" ]
// writeIndex writes a message index record to the writer `w`
[ "writeIndex", "writes", "a", "message", "index", "record", "to", "the", "writer", "w" ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L2480-L2486
train
nats-io/nats-streaming-server
stores/filestore.go
addIndex
func (ms *FileMsgStore) addIndex(buf []byte, seq uint64, offset, timestamp int64, msgSize int) { util.ByteOrder.PutUint64(buf, seq) util.ByteOrder.PutUint64(buf[8:], uint64(offset)) util.ByteOrder.PutUint64(buf[16:], uint64(timestamp)) util.ByteOrder.PutUint32(buf[24:], uint32(msgSize)) crc := crc32.Checksum(buf[:msgIndexRecSize-crcSize], ms.fstore.crcTable) util.ByteOrder.PutUint32(buf[msgIndexRecSize-crcSize:], crc) }
go
func (ms *FileMsgStore) addIndex(buf []byte, seq uint64, offset, timestamp int64, msgSize int) { util.ByteOrder.PutUint64(buf, seq) util.ByteOrder.PutUint64(buf[8:], uint64(offset)) util.ByteOrder.PutUint64(buf[16:], uint64(timestamp)) util.ByteOrder.PutUint32(buf[24:], uint32(msgSize)) crc := crc32.Checksum(buf[:msgIndexRecSize-crcSize], ms.fstore.crcTable) util.ByteOrder.PutUint32(buf[msgIndexRecSize-crcSize:], crc) }
[ "func", "(", "ms", "*", "FileMsgStore", ")", "addIndex", "(", "buf", "[", "]", "byte", ",", "seq", "uint64", ",", "offset", ",", "timestamp", "int64", ",", "msgSize", "int", ")", "{", "util", ".", "ByteOrder", ".", "PutUint64", "(", "buf", ",", "seq", ")", "\n", "util", ".", "ByteOrder", ".", "PutUint64", "(", "buf", "[", "8", ":", "]", ",", "uint64", "(", "offset", ")", ")", "\n", "util", ".", "ByteOrder", ".", "PutUint64", "(", "buf", "[", "16", ":", "]", ",", "uint64", "(", "timestamp", ")", ")", "\n", "util", ".", "ByteOrder", ".", "PutUint32", "(", "buf", "[", "24", ":", "]", ",", "uint32", "(", "msgSize", ")", ")", "\n", "crc", ":=", "crc32", ".", "Checksum", "(", "buf", "[", ":", "msgIndexRecSize", "-", "crcSize", "]", ",", "ms", ".", "fstore", ".", "crcTable", ")", "\n", "util", ".", "ByteOrder", ".", "PutUint32", "(", "buf", "[", "msgIndexRecSize", "-", "crcSize", ":", "]", ",", "crc", ")", "\n", "}" ]
// addIndex adds a message index record in the given buffer
[ "addIndex", "adds", "a", "message", "index", "record", "in", "the", "given", "buffer" ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L2489-L2496
train
nats-io/nats-streaming-server
stores/filestore.go
readIndex
func (ms *FileMsgStore) readIndex(r io.Reader) (uint64, *msgIndex, error) { _buf := [msgIndexRecSize]byte{} buf := _buf[:] if _, err := io.ReadFull(r, buf); err != nil { return 0, nil, err } mindex := &msgIndex{} seq := util.ByteOrder.Uint64(buf) mindex.offset = int64(util.ByteOrder.Uint64(buf[8:])) mindex.timestamp = int64(util.ByteOrder.Uint64(buf[16:])) mindex.msgSize = util.ByteOrder.Uint32(buf[24:]) // If all zeros, return that caller should rewind (for recovery) if seq == 0 && mindex.offset == 0 && mindex.timestamp == 0 && mindex.msgSize == 0 { storedCRC := util.ByteOrder.Uint32(buf[msgIndexRecSize-crcSize:]) if storedCRC == 0 { return 0, nil, errNeedRewind } } if ms.fstore.opts.DoCRC { storedCRC := util.ByteOrder.Uint32(buf[msgIndexRecSize-crcSize:]) crc := crc32.Checksum(buf[:msgIndexRecSize-crcSize], ms.fstore.crcTable) if storedCRC != crc { return 0, nil, fmt.Errorf("corrupted data, expected crc to be 0x%08x, got 0x%08x", storedCRC, crc) } } return seq, mindex, nil }
go
func (ms *FileMsgStore) readIndex(r io.Reader) (uint64, *msgIndex, error) { _buf := [msgIndexRecSize]byte{} buf := _buf[:] if _, err := io.ReadFull(r, buf); err != nil { return 0, nil, err } mindex := &msgIndex{} seq := util.ByteOrder.Uint64(buf) mindex.offset = int64(util.ByteOrder.Uint64(buf[8:])) mindex.timestamp = int64(util.ByteOrder.Uint64(buf[16:])) mindex.msgSize = util.ByteOrder.Uint32(buf[24:]) // If all zeros, return that caller should rewind (for recovery) if seq == 0 && mindex.offset == 0 && mindex.timestamp == 0 && mindex.msgSize == 0 { storedCRC := util.ByteOrder.Uint32(buf[msgIndexRecSize-crcSize:]) if storedCRC == 0 { return 0, nil, errNeedRewind } } if ms.fstore.opts.DoCRC { storedCRC := util.ByteOrder.Uint32(buf[msgIndexRecSize-crcSize:]) crc := crc32.Checksum(buf[:msgIndexRecSize-crcSize], ms.fstore.crcTable) if storedCRC != crc { return 0, nil, fmt.Errorf("corrupted data, expected crc to be 0x%08x, got 0x%08x", storedCRC, crc) } } return seq, mindex, nil }
[ "func", "(", "ms", "*", "FileMsgStore", ")", "readIndex", "(", "r", "io", ".", "Reader", ")", "(", "uint64", ",", "*", "msgIndex", ",", "error", ")", "{", "_buf", ":=", "[", "msgIndexRecSize", "]", "byte", "{", "}", "\n", "buf", ":=", "_buf", "[", ":", "]", "\n", "if", "_", ",", "err", ":=", "io", ".", "ReadFull", "(", "r", ",", "buf", ")", ";", "err", "!=", "nil", "{", "return", "0", ",", "nil", ",", "err", "\n", "}", "\n", "mindex", ":=", "&", "msgIndex", "{", "}", "\n", "seq", ":=", "util", ".", "ByteOrder", ".", "Uint64", "(", "buf", ")", "\n", "mindex", ".", "offset", "=", "int64", "(", "util", ".", "ByteOrder", ".", "Uint64", "(", "buf", "[", "8", ":", "]", ")", ")", "\n", "mindex", ".", "timestamp", "=", "int64", "(", "util", ".", "ByteOrder", ".", "Uint64", "(", "buf", "[", "16", ":", "]", ")", ")", "\n", "mindex", ".", "msgSize", "=", "util", ".", "ByteOrder", ".", "Uint32", "(", "buf", "[", "24", ":", "]", ")", "\n", "if", "seq", "==", "0", "&&", "mindex", ".", "offset", "==", "0", "&&", "mindex", ".", "timestamp", "==", "0", "&&", "mindex", ".", "msgSize", "==", "0", "{", "storedCRC", ":=", "util", ".", "ByteOrder", ".", "Uint32", "(", "buf", "[", "msgIndexRecSize", "-", "crcSize", ":", "]", ")", "\n", "if", "storedCRC", "==", "0", "{", "return", "0", ",", "nil", ",", "errNeedRewind", "\n", "}", "\n", "}", "\n", "if", "ms", ".", "fstore", ".", "opts", ".", "DoCRC", "{", "storedCRC", ":=", "util", ".", "ByteOrder", ".", "Uint32", "(", "buf", "[", "msgIndexRecSize", "-", "crcSize", ":", "]", ")", "\n", "crc", ":=", "crc32", ".", "Checksum", "(", "buf", "[", ":", "msgIndexRecSize", "-", "crcSize", "]", ",", "ms", ".", "fstore", ".", "crcTable", ")", "\n", "if", "storedCRC", "!=", "crc", "{", "return", "0", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"corrupted data, expected crc to be 0x%08x, got 0x%08x\"", ",", "storedCRC", ",", "crc", ")", "\n", "}", "\n", "}", "\n", "return", "seq", ",", "mindex", ",", "nil", "\n", "}" ]
// readIndex reads a message index record from the given reader // and returns an allocated msgIndex object.
[ "readIndex", "reads", "a", "message", "index", "record", "from", "the", "given", "reader", "and", "returns", "an", "allocated", "msgIndex", "object", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L2500-L2526
train
nats-io/nats-streaming-server
stores/filestore.go
processBufferedMsgs
func (ms *FileMsgStore) processBufferedMsgs(fslice *fileSlice) error { idxBufferSize := len(ms.bufferedMsgs) * msgIndexRecSize ms.tmpMsgBuf = util.EnsureBufBigEnough(ms.tmpMsgBuf, idxBufferSize) bufOffset := 0 for _, pseq := range ms.bufferedSeqs { bm := ms.bufferedMsgs[pseq] if bm != nil { mindex := bm.index // We add the index info for this flushed message ms.addIndex(ms.tmpMsgBuf[bufOffset:], pseq, mindex.offset, mindex.timestamp, int(mindex.msgSize)) bufOffset += msgIndexRecSize delete(ms.bufferedMsgs, pseq) } } if bufOffset > 0 { if _, err := fslice.idxFile.handle.Write(ms.tmpMsgBuf[:bufOffset]); err != nil { return err } } ms.bufferedSeqs = ms.bufferedSeqs[:0] return nil }
go
func (ms *FileMsgStore) processBufferedMsgs(fslice *fileSlice) error { idxBufferSize := len(ms.bufferedMsgs) * msgIndexRecSize ms.tmpMsgBuf = util.EnsureBufBigEnough(ms.tmpMsgBuf, idxBufferSize) bufOffset := 0 for _, pseq := range ms.bufferedSeqs { bm := ms.bufferedMsgs[pseq] if bm != nil { mindex := bm.index // We add the index info for this flushed message ms.addIndex(ms.tmpMsgBuf[bufOffset:], pseq, mindex.offset, mindex.timestamp, int(mindex.msgSize)) bufOffset += msgIndexRecSize delete(ms.bufferedMsgs, pseq) } } if bufOffset > 0 { if _, err := fslice.idxFile.handle.Write(ms.tmpMsgBuf[:bufOffset]); err != nil { return err } } ms.bufferedSeqs = ms.bufferedSeqs[:0] return nil }
[ "func", "(", "ms", "*", "FileMsgStore", ")", "processBufferedMsgs", "(", "fslice", "*", "fileSlice", ")", "error", "{", "idxBufferSize", ":=", "len", "(", "ms", ".", "bufferedMsgs", ")", "*", "msgIndexRecSize", "\n", "ms", ".", "tmpMsgBuf", "=", "util", ".", "EnsureBufBigEnough", "(", "ms", ".", "tmpMsgBuf", ",", "idxBufferSize", ")", "\n", "bufOffset", ":=", "0", "\n", "for", "_", ",", "pseq", ":=", "range", "ms", ".", "bufferedSeqs", "{", "bm", ":=", "ms", ".", "bufferedMsgs", "[", "pseq", "]", "\n", "if", "bm", "!=", "nil", "{", "mindex", ":=", "bm", ".", "index", "\n", "ms", ".", "addIndex", "(", "ms", ".", "tmpMsgBuf", "[", "bufOffset", ":", "]", ",", "pseq", ",", "mindex", ".", "offset", ",", "mindex", ".", "timestamp", ",", "int", "(", "mindex", ".", "msgSize", ")", ")", "\n", "bufOffset", "+=", "msgIndexRecSize", "\n", "delete", "(", "ms", ".", "bufferedMsgs", ",", "pseq", ")", "\n", "}", "\n", "}", "\n", "if", "bufOffset", ">", "0", "{", "if", "_", ",", "err", ":=", "fslice", ".", "idxFile", ".", "handle", ".", "Write", "(", "ms", ".", "tmpMsgBuf", "[", ":", "bufOffset", "]", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "ms", ".", "bufferedSeqs", "=", "ms", ".", "bufferedSeqs", "[", ":", "0", "]", "\n", "return", "nil", "\n", "}" ]
// processBufferedMsgs adds message index records in the given buffer // for every pending buffered messages.
[ "processBufferedMsgs", "adds", "message", "index", "records", "in", "the", "given", "buffer", "for", "every", "pending", "buffered", "messages", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L2767-L2789
train
nats-io/nats-streaming-server
stores/filestore.go
readMsgIndex
func (ms *FileMsgStore) readMsgIndex(slice *fileSlice, seq uint64) (*msgIndex, error) { // Compute the offset in the index file itself. idxFileOffset := 4 + (int64(seq-slice.firstSeq)+int64(slice.rmCount))*msgIndexRecSize // Then position the file pointer of the index file. if _, err := slice.idxFile.handle.Seek(idxFileOffset, io.SeekStart); err != nil { return nil, err } // Read the index record and ensure we have what we expect seqInIndexFile, msgIndex, err := ms.readIndex(slice.idxFile.handle) if err != nil { return nil, err } if seqInIndexFile != seq { return nil, fmt.Errorf("wrong sequence, wanted %v got %v", seq, seqInIndexFile) } return msgIndex, nil }
go
func (ms *FileMsgStore) readMsgIndex(slice *fileSlice, seq uint64) (*msgIndex, error) { // Compute the offset in the index file itself. idxFileOffset := 4 + (int64(seq-slice.firstSeq)+int64(slice.rmCount))*msgIndexRecSize // Then position the file pointer of the index file. if _, err := slice.idxFile.handle.Seek(idxFileOffset, io.SeekStart); err != nil { return nil, err } // Read the index record and ensure we have what we expect seqInIndexFile, msgIndex, err := ms.readIndex(slice.idxFile.handle) if err != nil { return nil, err } if seqInIndexFile != seq { return nil, fmt.Errorf("wrong sequence, wanted %v got %v", seq, seqInIndexFile) } return msgIndex, nil }
[ "func", "(", "ms", "*", "FileMsgStore", ")", "readMsgIndex", "(", "slice", "*", "fileSlice", ",", "seq", "uint64", ")", "(", "*", "msgIndex", ",", "error", ")", "{", "idxFileOffset", ":=", "4", "+", "(", "int64", "(", "seq", "-", "slice", ".", "firstSeq", ")", "+", "int64", "(", "slice", ".", "rmCount", ")", ")", "*", "msgIndexRecSize", "\n", "if", "_", ",", "err", ":=", "slice", ".", "idxFile", ".", "handle", ".", "Seek", "(", "idxFileOffset", ",", "io", ".", "SeekStart", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "seqInIndexFile", ",", "msgIndex", ",", "err", ":=", "ms", ".", "readIndex", "(", "slice", ".", "idxFile", ".", "handle", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "seqInIndexFile", "!=", "seq", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"wrong sequence, wanted %v got %v\"", ",", "seq", ",", "seqInIndexFile", ")", "\n", "}", "\n", "return", "msgIndex", ",", "nil", "\n", "}" ]
// readMsgIndex reads a message index record from disk and returns a msgIndex // object. Same than getMsgIndex but without checking for message in // ms.bufferedMsgs first.
[ "readMsgIndex", "reads", "a", "message", "index", "record", "from", "disk", "and", "returns", "a", "msgIndex", "object", ".", "Same", "than", "getMsgIndex", "but", "without", "checking", "for", "message", "in", "ms", ".", "bufferedMsgs", "first", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L2912-L2928
train
nats-io/nats-streaming-server
stores/filestore.go
removeFirstMsg
func (ms *FileMsgStore) removeFirstMsg(mindex *msgIndex, lockFile bool) error { // Work with the first slice slice := ms.files[ms.firstFSlSeq] // Get the message index for the first valid message in this slice if mindex == nil { if lockFile || slice != ms.writeSlice { ms.lockIndexFile(slice) } var err error mindex, err = ms.getMsgIndex(slice, slice.firstSeq) if lockFile || slice != ms.writeSlice { ms.unlockIndexFile(slice) } if err != nil { return err } } // Size of the first message in this slice firstMsgSize := mindex.msgSize // For size, we count the size of serialized message + record header + // the corresponding index record size := uint64(firstMsgSize + msgRecordOverhead) // Keep track of number of "removed" messages in this slice slice.rmCount++ // Update total counts ms.totalCount-- ms.totalBytes -= size // Messages sequence is incremental with no gap on a given msgstore. ms.first++ // Invalidate ms.firstMsg, it will be looked-up on demand. ms.firstMsg = nil // Invalidate ms.lastMsg if it was the last message being removed. if ms.first > ms.last { ms.lastMsg = nil } // Is file slice is "empty" and not the last one if slice.msgsCount == slice.rmCount && len(ms.files) > 1 { ms.removeFirstSlice() } else { // This is the new first message in this slice. slice.firstSeq = ms.first } return nil }
go
func (ms *FileMsgStore) removeFirstMsg(mindex *msgIndex, lockFile bool) error { // Work with the first slice slice := ms.files[ms.firstFSlSeq] // Get the message index for the first valid message in this slice if mindex == nil { if lockFile || slice != ms.writeSlice { ms.lockIndexFile(slice) } var err error mindex, err = ms.getMsgIndex(slice, slice.firstSeq) if lockFile || slice != ms.writeSlice { ms.unlockIndexFile(slice) } if err != nil { return err } } // Size of the first message in this slice firstMsgSize := mindex.msgSize // For size, we count the size of serialized message + record header + // the corresponding index record size := uint64(firstMsgSize + msgRecordOverhead) // Keep track of number of "removed" messages in this slice slice.rmCount++ // Update total counts ms.totalCount-- ms.totalBytes -= size // Messages sequence is incremental with no gap on a given msgstore. ms.first++ // Invalidate ms.firstMsg, it will be looked-up on demand. ms.firstMsg = nil // Invalidate ms.lastMsg if it was the last message being removed. if ms.first > ms.last { ms.lastMsg = nil } // Is file slice is "empty" and not the last one if slice.msgsCount == slice.rmCount && len(ms.files) > 1 { ms.removeFirstSlice() } else { // This is the new first message in this slice. slice.firstSeq = ms.first } return nil }
[ "func", "(", "ms", "*", "FileMsgStore", ")", "removeFirstMsg", "(", "mindex", "*", "msgIndex", ",", "lockFile", "bool", ")", "error", "{", "slice", ":=", "ms", ".", "files", "[", "ms", ".", "firstFSlSeq", "]", "\n", "if", "mindex", "==", "nil", "{", "if", "lockFile", "||", "slice", "!=", "ms", ".", "writeSlice", "{", "ms", ".", "lockIndexFile", "(", "slice", ")", "\n", "}", "\n", "var", "err", "error", "\n", "mindex", ",", "err", "=", "ms", ".", "getMsgIndex", "(", "slice", ",", "slice", ".", "firstSeq", ")", "\n", "if", "lockFile", "||", "slice", "!=", "ms", ".", "writeSlice", "{", "ms", ".", "unlockIndexFile", "(", "slice", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "firstMsgSize", ":=", "mindex", ".", "msgSize", "\n", "size", ":=", "uint64", "(", "firstMsgSize", "+", "msgRecordOverhead", ")", "\n", "slice", ".", "rmCount", "++", "\n", "ms", ".", "totalCount", "--", "\n", "ms", ".", "totalBytes", "-=", "size", "\n", "ms", ".", "first", "++", "\n", "ms", ".", "firstMsg", "=", "nil", "\n", "if", "ms", ".", "first", ">", "ms", ".", "last", "{", "ms", ".", "lastMsg", "=", "nil", "\n", "}", "\n", "if", "slice", ".", "msgsCount", "==", "slice", ".", "rmCount", "&&", "len", "(", "ms", ".", "files", ")", ">", "1", "{", "ms", ".", "removeFirstSlice", "(", ")", "\n", "}", "else", "{", "slice", ".", "firstSeq", "=", "ms", ".", "first", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// removeFirstMsg "removes" the first message of the first slice. // If the slice is "empty" the file slice is removed.
[ "removeFirstMsg", "removes", "the", "first", "message", "of", "the", "first", "slice", ".", "If", "the", "slice", "is", "empty", "the", "file", "slice", "is", "removed", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L2932-L2975
train
nats-io/nats-streaming-server
stores/filestore.go
removeFirstSlice
func (ms *FileMsgStore) removeFirstSlice() { sl := ms.files[ms.firstFSlSeq] // We may or may not have the first slice locked, so need to close // the file knowing that files can be in either state. ms.fm.closeLockedOrOpenedFile(sl.file) ms.fm.remove(sl.file) // Close index file too. ms.fm.closeLockedOrOpenedFile(sl.idxFile) ms.fm.remove(sl.idxFile) // Assume we will remove the files remove := true // If there is an archive script invoke it first script := ms.fstore.opts.SliceArchiveScript if script != "" { datBak := sl.file.name + bakSuffix idxBak := sl.idxFile.name + bakSuffix var err error if err = os.Rename(sl.file.name, datBak); err == nil { if err = os.Rename(sl.idxFile.name, idxBak); err != nil { // Remove first backup file os.Remove(datBak) } } if err == nil { // Files have been successfully renamed, so don't attempt // to remove the original files. remove = false // We run the script in a go routine to not block the server. ms.allDone.Add(1) go func(subj, dat, idx string) { defer ms.allDone.Done() cmd := exec.Command(script, subj, dat, idx) output, err := cmd.CombinedOutput() if err != nil { ms.log.Noticef("Error invoking archive script %q: %v (output=%v)", script, err, string(output)) } else { ms.log.Noticef("Output of archive script for %s (%s and %s): %v", subj, dat, idx, string(output)) } }(ms.subject, datBak, idxBak) } } // Remove files if remove { os.Remove(sl.file.name) os.Remove(sl.idxFile.name) } // Remove slice from map delete(ms.files, ms.firstFSlSeq) // Normally, file slices have an incremental sequence number with // no gap. However, we want to support the fact that an user could // copy back some old file slice to be recovered, and so there // may be a gap. So find out what is the new first file sequence. for ms.firstFSlSeq < ms.lastFSlSeq { ms.firstFSlSeq++ if _, ok := ms.files[ms.firstFSlSeq]; ok { break } } // This should not happen! if ms.firstFSlSeq > ms.lastFSlSeq { panic("Removed last slice!") } }
go
func (ms *FileMsgStore) removeFirstSlice() { sl := ms.files[ms.firstFSlSeq] // We may or may not have the first slice locked, so need to close // the file knowing that files can be in either state. ms.fm.closeLockedOrOpenedFile(sl.file) ms.fm.remove(sl.file) // Close index file too. ms.fm.closeLockedOrOpenedFile(sl.idxFile) ms.fm.remove(sl.idxFile) // Assume we will remove the files remove := true // If there is an archive script invoke it first script := ms.fstore.opts.SliceArchiveScript if script != "" { datBak := sl.file.name + bakSuffix idxBak := sl.idxFile.name + bakSuffix var err error if err = os.Rename(sl.file.name, datBak); err == nil { if err = os.Rename(sl.idxFile.name, idxBak); err != nil { // Remove first backup file os.Remove(datBak) } } if err == nil { // Files have been successfully renamed, so don't attempt // to remove the original files. remove = false // We run the script in a go routine to not block the server. ms.allDone.Add(1) go func(subj, dat, idx string) { defer ms.allDone.Done() cmd := exec.Command(script, subj, dat, idx) output, err := cmd.CombinedOutput() if err != nil { ms.log.Noticef("Error invoking archive script %q: %v (output=%v)", script, err, string(output)) } else { ms.log.Noticef("Output of archive script for %s (%s and %s): %v", subj, dat, idx, string(output)) } }(ms.subject, datBak, idxBak) } } // Remove files if remove { os.Remove(sl.file.name) os.Remove(sl.idxFile.name) } // Remove slice from map delete(ms.files, ms.firstFSlSeq) // Normally, file slices have an incremental sequence number with // no gap. However, we want to support the fact that an user could // copy back some old file slice to be recovered, and so there // may be a gap. So find out what is the new first file sequence. for ms.firstFSlSeq < ms.lastFSlSeq { ms.firstFSlSeq++ if _, ok := ms.files[ms.firstFSlSeq]; ok { break } } // This should not happen! if ms.firstFSlSeq > ms.lastFSlSeq { panic("Removed last slice!") } }
[ "func", "(", "ms", "*", "FileMsgStore", ")", "removeFirstSlice", "(", ")", "{", "sl", ":=", "ms", ".", "files", "[", "ms", ".", "firstFSlSeq", "]", "\n", "ms", ".", "fm", ".", "closeLockedOrOpenedFile", "(", "sl", ".", "file", ")", "\n", "ms", ".", "fm", ".", "remove", "(", "sl", ".", "file", ")", "\n", "ms", ".", "fm", ".", "closeLockedOrOpenedFile", "(", "sl", ".", "idxFile", ")", "\n", "ms", ".", "fm", ".", "remove", "(", "sl", ".", "idxFile", ")", "\n", "remove", ":=", "true", "\n", "script", ":=", "ms", ".", "fstore", ".", "opts", ".", "SliceArchiveScript", "\n", "if", "script", "!=", "\"\"", "{", "datBak", ":=", "sl", ".", "file", ".", "name", "+", "bakSuffix", "\n", "idxBak", ":=", "sl", ".", "idxFile", ".", "name", "+", "bakSuffix", "\n", "var", "err", "error", "\n", "if", "err", "=", "os", ".", "Rename", "(", "sl", ".", "file", ".", "name", ",", "datBak", ")", ";", "err", "==", "nil", "{", "if", "err", "=", "os", ".", "Rename", "(", "sl", ".", "idxFile", ".", "name", ",", "idxBak", ")", ";", "err", "!=", "nil", "{", "os", ".", "Remove", "(", "datBak", ")", "\n", "}", "\n", "}", "\n", "if", "err", "==", "nil", "{", "remove", "=", "false", "\n", "ms", ".", "allDone", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", "subj", ",", "dat", ",", "idx", "string", ")", "{", "defer", "ms", ".", "allDone", ".", "Done", "(", ")", "\n", "cmd", ":=", "exec", ".", "Command", "(", "script", ",", "subj", ",", "dat", ",", "idx", ")", "\n", "output", ",", "err", ":=", "cmd", ".", "CombinedOutput", "(", ")", "\n", "if", "err", "!=", "nil", "{", "ms", ".", "log", ".", "Noticef", "(", "\"Error invoking archive script %q: %v (output=%v)\"", ",", "script", ",", "err", ",", "string", "(", "output", ")", ")", "\n", "}", "else", "{", "ms", ".", "log", ".", "Noticef", "(", "\"Output of archive script for %s (%s and %s): %v\"", ",", "subj", ",", "dat", ",", "idx", ",", "string", "(", "output", ")", ")", "\n", "}", "\n", "}", "(", "ms", ".", "subject", ",", "datBak", ",", "idxBak", ")", "\n", "}", "\n", "}", "\n", "if", "remove", "{", "os", ".", "Remove", "(", "sl", ".", "file", ".", "name", ")", "\n", "os", ".", "Remove", "(", "sl", ".", "idxFile", ".", "name", ")", "\n", "}", "\n", "delete", "(", "ms", ".", "files", ",", "ms", ".", "firstFSlSeq", ")", "\n", "for", "ms", ".", "firstFSlSeq", "<", "ms", ".", "lastFSlSeq", "{", "ms", ".", "firstFSlSeq", "++", "\n", "if", "_", ",", "ok", ":=", "ms", ".", "files", "[", "ms", ".", "firstFSlSeq", "]", ";", "ok", "{", "break", "\n", "}", "\n", "}", "\n", "if", "ms", ".", "firstFSlSeq", ">", "ms", ".", "lastFSlSeq", "{", "panic", "(", "\"Removed last slice!\"", ")", "\n", "}", "\n", "}" ]
// removeFirstSlice removes the first file slice. // Should not be called if first slice is also last!
[ "removeFirstSlice", "removes", "the", "first", "file", "slice", ".", "Should", "not", "be", "called", "if", "first", "slice", "is", "also", "last!" ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L2979-L3043
train
nats-io/nats-streaming-server
stores/filestore.go
getFileSliceForSeq
func (ms *FileMsgStore) getFileSliceForSeq(seq uint64) *fileSlice { if len(ms.files) == 0 { return nil } // Start with write slice slice := ms.writeSlice if (slice.firstSeq <= seq) && (seq <= slice.lastSeq) { return slice } // We want to support possible gaps in file slice sequence, so // no dichotomy, but simple iteration of the map, which in Go is // random. for _, slice := range ms.files { if (slice.firstSeq <= seq) && (seq <= slice.lastSeq) { return slice } } return nil }
go
func (ms *FileMsgStore) getFileSliceForSeq(seq uint64) *fileSlice { if len(ms.files) == 0 { return nil } // Start with write slice slice := ms.writeSlice if (slice.firstSeq <= seq) && (seq <= slice.lastSeq) { return slice } // We want to support possible gaps in file slice sequence, so // no dichotomy, but simple iteration of the map, which in Go is // random. for _, slice := range ms.files { if (slice.firstSeq <= seq) && (seq <= slice.lastSeq) { return slice } } return nil }
[ "func", "(", "ms", "*", "FileMsgStore", ")", "getFileSliceForSeq", "(", "seq", "uint64", ")", "*", "fileSlice", "{", "if", "len", "(", "ms", ".", "files", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "slice", ":=", "ms", ".", "writeSlice", "\n", "if", "(", "slice", ".", "firstSeq", "<=", "seq", ")", "&&", "(", "seq", "<=", "slice", ".", "lastSeq", ")", "{", "return", "slice", "\n", "}", "\n", "for", "_", ",", "slice", ":=", "range", "ms", ".", "files", "{", "if", "(", "slice", ".", "firstSeq", "<=", "seq", ")", "&&", "(", "seq", "<=", "slice", ".", "lastSeq", ")", "{", "return", "slice", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// getFileSliceForSeq returns the file slice where the message of the // given sequence is stored, or nil if the message is not found in any // of the file slices.
[ "getFileSliceForSeq", "returns", "the", "file", "slice", "where", "the", "message", "of", "the", "given", "sequence", "is", "stored", "or", "nil", "if", "the", "message", "is", "not", "found", "in", "any", "of", "the", "file", "slices", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L3048-L3066
train
nats-io/nats-streaming-server
stores/filestore.go
backgroundTasks
func (ms *FileMsgStore) backgroundTasks() { defer ms.allDone.Done() ms.RLock() hasBuffer := ms.bw != nil maxAge := int64(ms.limits.MaxAge) nextExpiration := ms.expiration lastCacheCheck := ms.timeTick lastBufShrink := ms.timeTick ms.RUnlock() for { // Update time timeTick := time.Now().UnixNano() atomic.StoreInt64(&ms.timeTick, timeTick) // Close unused file slices if atomic.LoadInt64(&ms.checkSlices) == 1 { ms.Lock() opened := 0 for _, slice := range ms.files { // If no FD limit and this is the write slice, skip. if !ms.hasFDsLimit && slice == ms.writeSlice { continue } opened++ if slice.lastUsed > 0 && time.Duration(timeTick-slice.lastUsed) >= sliceCloseInterval { slice.lastUsed = 0 ms.fm.closeFileIfOpened(slice.file) ms.fm.closeFileIfOpened(slice.idxFile) opened-- } } if opened == 0 { // We can update this without atomic since we are under store lock // and this go routine is the only place where we check the value. ms.checkSlices = 0 } ms.Unlock() } // Shrink the buffer if applicable if hasBuffer && time.Duration(timeTick-lastBufShrink) >= bufShrinkInterval { ms.Lock() if ms.writeSlice != nil { file := ms.writeSlice.file if ms.fm.lockFileIfOpened(file) { ms.writer, _ = ms.bw.tryShrinkBuffer(file.handle) ms.fm.unlockFile(file) } } ms.Unlock() lastBufShrink = timeTick } // Check for expiration if maxAge > 0 && nextExpiration > 0 && timeTick >= nextExpiration { ms.Lock() // Expire messages nextExpiration = ms.expireMsgs(timeTick, maxAge) ms.Unlock() } // Check for message caching if timeTick >= lastCacheCheck+cacheTTL { tryEvict := atomic.LoadInt32(&ms.cache.tryEvict) if tryEvict == 1 { ms.Lock() // Possibly remove some/all cached messages ms.cache.evict(timeTick) ms.Unlock() } lastCacheCheck = timeTick } select { case <-ms.bkgTasksDone: return case <-ms.bkgTasksWake: // wake up from a possible sleep to run the loop ms.RLock() nextExpiration = ms.expiration ms.RUnlock() case <-time.After(bkgTasksSleepDuration): // go back to top of for loop. } } }
go
func (ms *FileMsgStore) backgroundTasks() { defer ms.allDone.Done() ms.RLock() hasBuffer := ms.bw != nil maxAge := int64(ms.limits.MaxAge) nextExpiration := ms.expiration lastCacheCheck := ms.timeTick lastBufShrink := ms.timeTick ms.RUnlock() for { // Update time timeTick := time.Now().UnixNano() atomic.StoreInt64(&ms.timeTick, timeTick) // Close unused file slices if atomic.LoadInt64(&ms.checkSlices) == 1 { ms.Lock() opened := 0 for _, slice := range ms.files { // If no FD limit and this is the write slice, skip. if !ms.hasFDsLimit && slice == ms.writeSlice { continue } opened++ if slice.lastUsed > 0 && time.Duration(timeTick-slice.lastUsed) >= sliceCloseInterval { slice.lastUsed = 0 ms.fm.closeFileIfOpened(slice.file) ms.fm.closeFileIfOpened(slice.idxFile) opened-- } } if opened == 0 { // We can update this without atomic since we are under store lock // and this go routine is the only place where we check the value. ms.checkSlices = 0 } ms.Unlock() } // Shrink the buffer if applicable if hasBuffer && time.Duration(timeTick-lastBufShrink) >= bufShrinkInterval { ms.Lock() if ms.writeSlice != nil { file := ms.writeSlice.file if ms.fm.lockFileIfOpened(file) { ms.writer, _ = ms.bw.tryShrinkBuffer(file.handle) ms.fm.unlockFile(file) } } ms.Unlock() lastBufShrink = timeTick } // Check for expiration if maxAge > 0 && nextExpiration > 0 && timeTick >= nextExpiration { ms.Lock() // Expire messages nextExpiration = ms.expireMsgs(timeTick, maxAge) ms.Unlock() } // Check for message caching if timeTick >= lastCacheCheck+cacheTTL { tryEvict := atomic.LoadInt32(&ms.cache.tryEvict) if tryEvict == 1 { ms.Lock() // Possibly remove some/all cached messages ms.cache.evict(timeTick) ms.Unlock() } lastCacheCheck = timeTick } select { case <-ms.bkgTasksDone: return case <-ms.bkgTasksWake: // wake up from a possible sleep to run the loop ms.RLock() nextExpiration = ms.expiration ms.RUnlock() case <-time.After(bkgTasksSleepDuration): // go back to top of for loop. } } }
[ "func", "(", "ms", "*", "FileMsgStore", ")", "backgroundTasks", "(", ")", "{", "defer", "ms", ".", "allDone", ".", "Done", "(", ")", "\n", "ms", ".", "RLock", "(", ")", "\n", "hasBuffer", ":=", "ms", ".", "bw", "!=", "nil", "\n", "maxAge", ":=", "int64", "(", "ms", ".", "limits", ".", "MaxAge", ")", "\n", "nextExpiration", ":=", "ms", ".", "expiration", "\n", "lastCacheCheck", ":=", "ms", ".", "timeTick", "\n", "lastBufShrink", ":=", "ms", ".", "timeTick", "\n", "ms", ".", "RUnlock", "(", ")", "\n", "for", "{", "timeTick", ":=", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", "\n", "atomic", ".", "StoreInt64", "(", "&", "ms", ".", "timeTick", ",", "timeTick", ")", "\n", "if", "atomic", ".", "LoadInt64", "(", "&", "ms", ".", "checkSlices", ")", "==", "1", "{", "ms", ".", "Lock", "(", ")", "\n", "opened", ":=", "0", "\n", "for", "_", ",", "slice", ":=", "range", "ms", ".", "files", "{", "if", "!", "ms", ".", "hasFDsLimit", "&&", "slice", "==", "ms", ".", "writeSlice", "{", "continue", "\n", "}", "\n", "opened", "++", "\n", "if", "slice", ".", "lastUsed", ">", "0", "&&", "time", ".", "Duration", "(", "timeTick", "-", "slice", ".", "lastUsed", ")", ">=", "sliceCloseInterval", "{", "slice", ".", "lastUsed", "=", "0", "\n", "ms", ".", "fm", ".", "closeFileIfOpened", "(", "slice", ".", "file", ")", "\n", "ms", ".", "fm", ".", "closeFileIfOpened", "(", "slice", ".", "idxFile", ")", "\n", "opened", "--", "\n", "}", "\n", "}", "\n", "if", "opened", "==", "0", "{", "ms", ".", "checkSlices", "=", "0", "\n", "}", "\n", "ms", ".", "Unlock", "(", ")", "\n", "}", "\n", "if", "hasBuffer", "&&", "time", ".", "Duration", "(", "timeTick", "-", "lastBufShrink", ")", ">=", "bufShrinkInterval", "{", "ms", ".", "Lock", "(", ")", "\n", "if", "ms", ".", "writeSlice", "!=", "nil", "{", "file", ":=", "ms", ".", "writeSlice", ".", "file", "\n", "if", "ms", ".", "fm", ".", "lockFileIfOpened", "(", "file", ")", "{", "ms", ".", "writer", ",", "_", "=", "ms", ".", "bw", ".", "tryShrinkBuffer", "(", "file", ".", "handle", ")", "\n", "ms", ".", "fm", ".", "unlockFile", "(", "file", ")", "\n", "}", "\n", "}", "\n", "ms", ".", "Unlock", "(", ")", "\n", "lastBufShrink", "=", "timeTick", "\n", "}", "\n", "if", "maxAge", ">", "0", "&&", "nextExpiration", ">", "0", "&&", "timeTick", ">=", "nextExpiration", "{", "ms", ".", "Lock", "(", ")", "\n", "nextExpiration", "=", "ms", ".", "expireMsgs", "(", "timeTick", ",", "maxAge", ")", "\n", "ms", ".", "Unlock", "(", ")", "\n", "}", "\n", "if", "timeTick", ">=", "lastCacheCheck", "+", "cacheTTL", "{", "tryEvict", ":=", "atomic", ".", "LoadInt32", "(", "&", "ms", ".", "cache", ".", "tryEvict", ")", "\n", "if", "tryEvict", "==", "1", "{", "ms", ".", "Lock", "(", ")", "\n", "ms", ".", "cache", ".", "evict", "(", "timeTick", ")", "\n", "ms", ".", "Unlock", "(", ")", "\n", "}", "\n", "lastCacheCheck", "=", "timeTick", "\n", "}", "\n", "select", "{", "case", "<-", "ms", ".", "bkgTasksDone", ":", "return", "\n", "case", "<-", "ms", ".", "bkgTasksWake", ":", "ms", ".", "RLock", "(", ")", "\n", "nextExpiration", "=", "ms", ".", "expiration", "\n", "ms", ".", "RUnlock", "(", ")", "\n", "case", "<-", "time", ".", "After", "(", "bkgTasksSleepDuration", ")", ":", "}", "\n", "}", "\n", "}" ]
// backgroundTasks performs some background tasks related to this // messages store.
[ "backgroundTasks", "performs", "some", "background", "tasks", "related", "to", "this", "messages", "store", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L3070-L3157
train
nats-io/nats-streaming-server
stores/filestore.go
lookup
func (ms *FileMsgStore) lookup(seq uint64) (*pb.MsgProto, error) { // Reject message for sequence outside valid range if seq < ms.first || seq > ms.last { return nil, nil } // Check first if it's in the cache. msg := ms.cache.get(seq) if msg == nil && ms.bufferedMsgs != nil { // Possibly in bufferedMsgs bm := ms.bufferedMsgs[seq] if bm != nil { msg = bm.msg ms.cache.add(seq, msg, false) } } // If not, we need to read it from disk... if msg == nil { fslice := ms.getFileSliceForSeq(seq) if fslice == nil { return nil, nil } err := ms.lockFiles(fslice) if err != nil { return nil, err } msgIndex, err := ms.readMsgIndex(fslice, seq) if msgIndex != nil { file := fslice.file.handle // Position file to message's offset. 0 means from start. _, err = file.Seek(msgIndex.offset, io.SeekStart) if err == nil { ms.tmpMsgBuf, _, _, err = readRecord(file, ms.tmpMsgBuf, false, ms.fstore.crcTable, ms.fstore.opts.DoCRC) } } ms.unlockFiles(fslice) if err != nil || msgIndex == nil { return nil, err } // Recover this message msg = &pb.MsgProto{} err = msg.Unmarshal(ms.tmpMsgBuf[:msgIndex.msgSize]) if err != nil { return nil, err } ms.cache.add(seq, msg, false) } return msg, nil }
go
func (ms *FileMsgStore) lookup(seq uint64) (*pb.MsgProto, error) { // Reject message for sequence outside valid range if seq < ms.first || seq > ms.last { return nil, nil } // Check first if it's in the cache. msg := ms.cache.get(seq) if msg == nil && ms.bufferedMsgs != nil { // Possibly in bufferedMsgs bm := ms.bufferedMsgs[seq] if bm != nil { msg = bm.msg ms.cache.add(seq, msg, false) } } // If not, we need to read it from disk... if msg == nil { fslice := ms.getFileSliceForSeq(seq) if fslice == nil { return nil, nil } err := ms.lockFiles(fslice) if err != nil { return nil, err } msgIndex, err := ms.readMsgIndex(fslice, seq) if msgIndex != nil { file := fslice.file.handle // Position file to message's offset. 0 means from start. _, err = file.Seek(msgIndex.offset, io.SeekStart) if err == nil { ms.tmpMsgBuf, _, _, err = readRecord(file, ms.tmpMsgBuf, false, ms.fstore.crcTable, ms.fstore.opts.DoCRC) } } ms.unlockFiles(fslice) if err != nil || msgIndex == nil { return nil, err } // Recover this message msg = &pb.MsgProto{} err = msg.Unmarshal(ms.tmpMsgBuf[:msgIndex.msgSize]) if err != nil { return nil, err } ms.cache.add(seq, msg, false) } return msg, nil }
[ "func", "(", "ms", "*", "FileMsgStore", ")", "lookup", "(", "seq", "uint64", ")", "(", "*", "pb", ".", "MsgProto", ",", "error", ")", "{", "if", "seq", "<", "ms", ".", "first", "||", "seq", ">", "ms", ".", "last", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "msg", ":=", "ms", ".", "cache", ".", "get", "(", "seq", ")", "\n", "if", "msg", "==", "nil", "&&", "ms", ".", "bufferedMsgs", "!=", "nil", "{", "bm", ":=", "ms", ".", "bufferedMsgs", "[", "seq", "]", "\n", "if", "bm", "!=", "nil", "{", "msg", "=", "bm", ".", "msg", "\n", "ms", ".", "cache", ".", "add", "(", "seq", ",", "msg", ",", "false", ")", "\n", "}", "\n", "}", "\n", "if", "msg", "==", "nil", "{", "fslice", ":=", "ms", ".", "getFileSliceForSeq", "(", "seq", ")", "\n", "if", "fslice", "==", "nil", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "err", ":=", "ms", ".", "lockFiles", "(", "fslice", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "msgIndex", ",", "err", ":=", "ms", ".", "readMsgIndex", "(", "fslice", ",", "seq", ")", "\n", "if", "msgIndex", "!=", "nil", "{", "file", ":=", "fslice", ".", "file", ".", "handle", "\n", "_", ",", "err", "=", "file", ".", "Seek", "(", "msgIndex", ".", "offset", ",", "io", ".", "SeekStart", ")", "\n", "if", "err", "==", "nil", "{", "ms", ".", "tmpMsgBuf", ",", "_", ",", "_", ",", "err", "=", "readRecord", "(", "file", ",", "ms", ".", "tmpMsgBuf", ",", "false", ",", "ms", ".", "fstore", ".", "crcTable", ",", "ms", ".", "fstore", ".", "opts", ".", "DoCRC", ")", "\n", "}", "\n", "}", "\n", "ms", ".", "unlockFiles", "(", "fslice", ")", "\n", "if", "err", "!=", "nil", "||", "msgIndex", "==", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "msg", "=", "&", "pb", ".", "MsgProto", "{", "}", "\n", "err", "=", "msg", ".", "Unmarshal", "(", "ms", ".", "tmpMsgBuf", "[", ":", "msgIndex", ".", "msgSize", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "ms", ".", "cache", ".", "add", "(", "seq", ",", "msg", ",", "false", ")", "\n", "}", "\n", "return", "msg", ",", "nil", "\n", "}" ]
// lookup returns the message for the given sequence number, possibly // reading the message from disk. // Store write lock is assumed to be held on entry
[ "lookup", "returns", "the", "message", "for", "the", "given", "sequence", "number", "possibly", "reading", "the", "message", "from", "disk", ".", "Store", "write", "lock", "is", "assumed", "to", "be", "held", "on", "entry" ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L3162-L3209
train
nats-io/nats-streaming-server
stores/filestore.go
initCache
func (ms *FileMsgStore) initCache() { ms.cache = &msgsCache{ seqMaps: make(map[uint64]*cachedMsg), } }
go
func (ms *FileMsgStore) initCache() { ms.cache = &msgsCache{ seqMaps: make(map[uint64]*cachedMsg), } }
[ "func", "(", "ms", "*", "FileMsgStore", ")", "initCache", "(", ")", "{", "ms", ".", "cache", "=", "&", "msgsCache", "{", "seqMaps", ":", "make", "(", "map", "[", "uint64", "]", "*", "cachedMsg", ")", ",", "}", "\n", "}" ]
// initCache initializes the message cache
[ "initCache", "initializes", "the", "message", "cache" ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L3326-L3330
train
nats-io/nats-streaming-server
stores/filestore.go
add
func (c *msgsCache) add(seq uint64, msg *pb.MsgProto, isNew bool) { exp := cacheTTL if isNew { exp += msg.Timestamp } else { exp += time.Now().UnixNano() } cMsg := &cachedMsg{ expiration: exp, msg: msg, } if c.tail == nil { c.head = cMsg } else { c.tail.next = cMsg // Ensure last expiration is at least >= previous one. if cMsg.expiration < c.tail.expiration { cMsg.expiration = c.tail.expiration } } cMsg.prev = c.tail c.tail = cMsg c.seqMaps[seq] = cMsg if len(c.seqMaps) == 1 { atomic.StoreInt32(&c.tryEvict, 1) } }
go
func (c *msgsCache) add(seq uint64, msg *pb.MsgProto, isNew bool) { exp := cacheTTL if isNew { exp += msg.Timestamp } else { exp += time.Now().UnixNano() } cMsg := &cachedMsg{ expiration: exp, msg: msg, } if c.tail == nil { c.head = cMsg } else { c.tail.next = cMsg // Ensure last expiration is at least >= previous one. if cMsg.expiration < c.tail.expiration { cMsg.expiration = c.tail.expiration } } cMsg.prev = c.tail c.tail = cMsg c.seqMaps[seq] = cMsg if len(c.seqMaps) == 1 { atomic.StoreInt32(&c.tryEvict, 1) } }
[ "func", "(", "c", "*", "msgsCache", ")", "add", "(", "seq", "uint64", ",", "msg", "*", "pb", ".", "MsgProto", ",", "isNew", "bool", ")", "{", "exp", ":=", "cacheTTL", "\n", "if", "isNew", "{", "exp", "+=", "msg", ".", "Timestamp", "\n", "}", "else", "{", "exp", "+=", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", "\n", "}", "\n", "cMsg", ":=", "&", "cachedMsg", "{", "expiration", ":", "exp", ",", "msg", ":", "msg", ",", "}", "\n", "if", "c", ".", "tail", "==", "nil", "{", "c", ".", "head", "=", "cMsg", "\n", "}", "else", "{", "c", ".", "tail", ".", "next", "=", "cMsg", "\n", "if", "cMsg", ".", "expiration", "<", "c", ".", "tail", ".", "expiration", "{", "cMsg", ".", "expiration", "=", "c", ".", "tail", ".", "expiration", "\n", "}", "\n", "}", "\n", "cMsg", ".", "prev", "=", "c", ".", "tail", "\n", "c", ".", "tail", "=", "cMsg", "\n", "c", ".", "seqMaps", "[", "seq", "]", "=", "cMsg", "\n", "if", "len", "(", "c", ".", "seqMaps", ")", "==", "1", "{", "atomic", ".", "StoreInt32", "(", "&", "c", ".", "tryEvict", ",", "1", ")", "\n", "}", "\n", "}" ]
// add adds a message to the cache. // Store write lock is assumed held on entry
[ "add", "adds", "a", "message", "to", "the", "cache", ".", "Store", "write", "lock", "is", "assumed", "held", "on", "entry" ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L3334-L3360
train
nats-io/nats-streaming-server
stores/filestore.go
get
func (c *msgsCache) get(seq uint64) *pb.MsgProto { cMsg := c.seqMaps[seq] if cMsg == nil { return nil } // Bump the expiration cMsg.expiration = time.Now().UnixNano() + cacheTTL // If not already at the tail of the list, move it there if cMsg != c.tail { if cMsg.prev != nil { cMsg.prev.next = cMsg.next } if cMsg.next != nil { cMsg.next.prev = cMsg.prev } if cMsg == c.head { c.head = cMsg.next } cMsg.prev = c.tail c.tail.next = cMsg cMsg.next = nil // Ensure last expiration is at least >= previous one. if cMsg.expiration < c.tail.expiration { cMsg.expiration = c.tail.expiration } c.tail = cMsg } return cMsg.msg }
go
func (c *msgsCache) get(seq uint64) *pb.MsgProto { cMsg := c.seqMaps[seq] if cMsg == nil { return nil } // Bump the expiration cMsg.expiration = time.Now().UnixNano() + cacheTTL // If not already at the tail of the list, move it there if cMsg != c.tail { if cMsg.prev != nil { cMsg.prev.next = cMsg.next } if cMsg.next != nil { cMsg.next.prev = cMsg.prev } if cMsg == c.head { c.head = cMsg.next } cMsg.prev = c.tail c.tail.next = cMsg cMsg.next = nil // Ensure last expiration is at least >= previous one. if cMsg.expiration < c.tail.expiration { cMsg.expiration = c.tail.expiration } c.tail = cMsg } return cMsg.msg }
[ "func", "(", "c", "*", "msgsCache", ")", "get", "(", "seq", "uint64", ")", "*", "pb", ".", "MsgProto", "{", "cMsg", ":=", "c", ".", "seqMaps", "[", "seq", "]", "\n", "if", "cMsg", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "cMsg", ".", "expiration", "=", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", "+", "cacheTTL", "\n", "if", "cMsg", "!=", "c", ".", "tail", "{", "if", "cMsg", ".", "prev", "!=", "nil", "{", "cMsg", ".", "prev", ".", "next", "=", "cMsg", ".", "next", "\n", "}", "\n", "if", "cMsg", ".", "next", "!=", "nil", "{", "cMsg", ".", "next", ".", "prev", "=", "cMsg", ".", "prev", "\n", "}", "\n", "if", "cMsg", "==", "c", ".", "head", "{", "c", ".", "head", "=", "cMsg", ".", "next", "\n", "}", "\n", "cMsg", ".", "prev", "=", "c", ".", "tail", "\n", "c", ".", "tail", ".", "next", "=", "cMsg", "\n", "cMsg", ".", "next", "=", "nil", "\n", "if", "cMsg", ".", "expiration", "<", "c", ".", "tail", ".", "expiration", "{", "cMsg", ".", "expiration", "=", "c", ".", "tail", ".", "expiration", "\n", "}", "\n", "c", ".", "tail", "=", "cMsg", "\n", "}", "\n", "return", "cMsg", ".", "msg", "\n", "}" ]
// get returns a message if available in the cache. // Store write lock is assumed held on entry
[ "get", "returns", "a", "message", "if", "available", "in", "the", "cache", ".", "Store", "write", "lock", "is", "assumed", "held", "on", "entry" ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L3364-L3392
train
nats-io/nats-streaming-server
stores/filestore.go
evict
func (c *msgsCache) evict(now int64) { if c.head == nil { return } if now >= c.tail.expiration { // Bulk remove c.seqMaps = make(map[uint64]*cachedMsg) c.head, c.tail, c.tryEvict = nil, nil, 0 return } cMsg := c.head for cMsg != nil && cMsg.expiration <= now { delete(c.seqMaps, cMsg.msg.Sequence) cMsg = cMsg.next } if cMsg != c.head { // There should be at least one left, otherwise, they // would all have been bulk removed at top of this function. cMsg.prev = nil c.head = cMsg } }
go
func (c *msgsCache) evict(now int64) { if c.head == nil { return } if now >= c.tail.expiration { // Bulk remove c.seqMaps = make(map[uint64]*cachedMsg) c.head, c.tail, c.tryEvict = nil, nil, 0 return } cMsg := c.head for cMsg != nil && cMsg.expiration <= now { delete(c.seqMaps, cMsg.msg.Sequence) cMsg = cMsg.next } if cMsg != c.head { // There should be at least one left, otherwise, they // would all have been bulk removed at top of this function. cMsg.prev = nil c.head = cMsg } }
[ "func", "(", "c", "*", "msgsCache", ")", "evict", "(", "now", "int64", ")", "{", "if", "c", ".", "head", "==", "nil", "{", "return", "\n", "}", "\n", "if", "now", ">=", "c", ".", "tail", ".", "expiration", "{", "c", ".", "seqMaps", "=", "make", "(", "map", "[", "uint64", "]", "*", "cachedMsg", ")", "\n", "c", ".", "head", ",", "c", ".", "tail", ",", "c", ".", "tryEvict", "=", "nil", ",", "nil", ",", "0", "\n", "return", "\n", "}", "\n", "cMsg", ":=", "c", ".", "head", "\n", "for", "cMsg", "!=", "nil", "&&", "cMsg", ".", "expiration", "<=", "now", "{", "delete", "(", "c", ".", "seqMaps", ",", "cMsg", ".", "msg", ".", "Sequence", ")", "\n", "cMsg", "=", "cMsg", ".", "next", "\n", "}", "\n", "if", "cMsg", "!=", "c", ".", "head", "{", "cMsg", ".", "prev", "=", "nil", "\n", "c", ".", "head", "=", "cMsg", "\n", "}", "\n", "}" ]
// evict move down the cache maps, evicting the last one. // Store write lock is assumed held on entry
[ "evict", "move", "down", "the", "cache", "maps", "evicting", "the", "last", "one", ".", "Store", "write", "lock", "is", "assumed", "held", "on", "entry" ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L3396-L3417
train
nats-io/nats-streaming-server
stores/filestore.go
empty
func (c *msgsCache) empty() { atomic.StoreInt32(&c.tryEvict, 0) c.head, c.tail = nil, nil c.seqMaps = make(map[uint64]*cachedMsg) }
go
func (c *msgsCache) empty() { atomic.StoreInt32(&c.tryEvict, 0) c.head, c.tail = nil, nil c.seqMaps = make(map[uint64]*cachedMsg) }
[ "func", "(", "c", "*", "msgsCache", ")", "empty", "(", ")", "{", "atomic", ".", "StoreInt32", "(", "&", "c", ".", "tryEvict", ",", "0", ")", "\n", "c", ".", "head", ",", "c", ".", "tail", "=", "nil", ",", "nil", "\n", "c", ".", "seqMaps", "=", "make", "(", "map", "[", "uint64", "]", "*", "cachedMsg", ")", "\n", "}" ]
// empty empties the cache
[ "empty", "empties", "the", "cache" ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L3420-L3424
train
nats-io/nats-streaming-server
stores/filestore.go
Flush
func (ms *FileMsgStore) Flush() error { ms.Lock() var err error if ms.writeSlice != nil { err = ms.lockFiles(ms.writeSlice) if err == nil { err = ms.flush(ms.writeSlice) ms.unlockFiles(ms.writeSlice) } } ms.Unlock() return err }
go
func (ms *FileMsgStore) Flush() error { ms.Lock() var err error if ms.writeSlice != nil { err = ms.lockFiles(ms.writeSlice) if err == nil { err = ms.flush(ms.writeSlice) ms.unlockFiles(ms.writeSlice) } } ms.Unlock() return err }
[ "func", "(", "ms", "*", "FileMsgStore", ")", "Flush", "(", ")", "error", "{", "ms", ".", "Lock", "(", ")", "\n", "var", "err", "error", "\n", "if", "ms", ".", "writeSlice", "!=", "nil", "{", "err", "=", "ms", ".", "lockFiles", "(", "ms", ".", "writeSlice", ")", "\n", "if", "err", "==", "nil", "{", "err", "=", "ms", ".", "flush", "(", "ms", ".", "writeSlice", ")", "\n", "ms", ".", "unlockFiles", "(", "ms", ".", "writeSlice", ")", "\n", "}", "\n", "}", "\n", "ms", ".", "Unlock", "(", ")", "\n", "return", "err", "\n", "}" ]
// Flush flushes outstanding data into the store.
[ "Flush", "flushes", "outstanding", "data", "into", "the", "store", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L3495-L3507
train
nats-io/nats-streaming-server
stores/filestore.go
CreateSub
func (ss *FileSubStore) CreateSub(sub *spb.SubState) error { // Check if we can create the subscription (check limits and update // subscription count) ss.Lock() defer ss.Unlock() if err := ss.createSub(sub); err != nil { return err } if err := ss.writeRecord(nil, subRecNew, sub); err != nil { delete(ss.subs, sub.ID) return err } // We need to get a copy of the passed sub, we can't hold a reference // to it. csub := *sub s := &subscription{sub: &csub, seqnos: make(map[uint64]struct{})} ss.subs[sub.ID] = s return nil }
go
func (ss *FileSubStore) CreateSub(sub *spb.SubState) error { // Check if we can create the subscription (check limits and update // subscription count) ss.Lock() defer ss.Unlock() if err := ss.createSub(sub); err != nil { return err } if err := ss.writeRecord(nil, subRecNew, sub); err != nil { delete(ss.subs, sub.ID) return err } // We need to get a copy of the passed sub, we can't hold a reference // to it. csub := *sub s := &subscription{sub: &csub, seqnos: make(map[uint64]struct{})} ss.subs[sub.ID] = s return nil }
[ "func", "(", "ss", "*", "FileSubStore", ")", "CreateSub", "(", "sub", "*", "spb", ".", "SubState", ")", "error", "{", "ss", ".", "Lock", "(", ")", "\n", "defer", "ss", ".", "Unlock", "(", ")", "\n", "if", "err", ":=", "ss", ".", "createSub", "(", "sub", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "ss", ".", "writeRecord", "(", "nil", ",", "subRecNew", ",", "sub", ")", ";", "err", "!=", "nil", "{", "delete", "(", "ss", ".", "subs", ",", "sub", ".", "ID", ")", "\n", "return", "err", "\n", "}", "\n", "csub", ":=", "*", "sub", "\n", "s", ":=", "&", "subscription", "{", "sub", ":", "&", "csub", ",", "seqnos", ":", "make", "(", "map", "[", "uint64", "]", "struct", "{", "}", ")", "}", "\n", "ss", ".", "subs", "[", "sub", ".", "ID", "]", "=", "s", "\n", "return", "nil", "\n", "}" ]
// CreateSub records a new subscription represented by SubState. On success, // it returns an id that is used by the other methods.
[ "CreateSub", "records", "a", "new", "subscription", "represented", "by", "SubState", ".", "On", "success", "it", "returns", "an", "id", "that", "is", "used", "by", "the", "other", "methods", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L3787-L3805
train
nats-io/nats-streaming-server
stores/filestore.go
UpdateSub
func (ss *FileSubStore) UpdateSub(sub *spb.SubState) error { ss.Lock() defer ss.Unlock() if err := ss.writeRecord(nil, subRecUpdate, sub); err != nil { return err } // We need to get a copy of the passed sub, we can't hold a reference // to it. csub := *sub si := ss.subs[sub.ID] if si != nil { s := si.(*subscription) s.sub = &csub } else { s := &subscription{sub: &csub, seqnos: make(map[uint64]struct{})} ss.subs[sub.ID] = s } return nil }
go
func (ss *FileSubStore) UpdateSub(sub *spb.SubState) error { ss.Lock() defer ss.Unlock() if err := ss.writeRecord(nil, subRecUpdate, sub); err != nil { return err } // We need to get a copy of the passed sub, we can't hold a reference // to it. csub := *sub si := ss.subs[sub.ID] if si != nil { s := si.(*subscription) s.sub = &csub } else { s := &subscription{sub: &csub, seqnos: make(map[uint64]struct{})} ss.subs[sub.ID] = s } return nil }
[ "func", "(", "ss", "*", "FileSubStore", ")", "UpdateSub", "(", "sub", "*", "spb", ".", "SubState", ")", "error", "{", "ss", ".", "Lock", "(", ")", "\n", "defer", "ss", ".", "Unlock", "(", ")", "\n", "if", "err", ":=", "ss", ".", "writeRecord", "(", "nil", ",", "subRecUpdate", ",", "sub", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "csub", ":=", "*", "sub", "\n", "si", ":=", "ss", ".", "subs", "[", "sub", ".", "ID", "]", "\n", "if", "si", "!=", "nil", "{", "s", ":=", "si", ".", "(", "*", "subscription", ")", "\n", "s", ".", "sub", "=", "&", "csub", "\n", "}", "else", "{", "s", ":=", "&", "subscription", "{", "sub", ":", "&", "csub", ",", "seqnos", ":", "make", "(", "map", "[", "uint64", "]", "struct", "{", "}", ")", "}", "\n", "ss", ".", "subs", "[", "sub", ".", "ID", "]", "=", "s", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// UpdateSub updates a given subscription represented by SubState.
[ "UpdateSub", "updates", "a", "given", "subscription", "represented", "by", "SubState", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L3808-L3826
train
nats-io/nats-streaming-server
stores/filestore.go
shouldCompact
func (ss *FileSubStore) shouldCompact() bool { // Gobal switch if !ss.opts.CompactEnabled { return false } // Check that if minimum file size is set, the client file // is at least at the minimum. if ss.opts.CompactMinFileSize > 0 && ss.fileSize < ss.opts.CompactMinFileSize { return false } // Check fragmentation frag := 0 if ss.numRecs == 0 { frag = 100 } else { frag = ss.delRecs * 100 / ss.numRecs } if frag < ss.opts.CompactFragmentation { return false } // Check that we don't compact too often if time.Since(ss.compactTS) < ss.compactItvl { return false } return true }
go
func (ss *FileSubStore) shouldCompact() bool { // Gobal switch if !ss.opts.CompactEnabled { return false } // Check that if minimum file size is set, the client file // is at least at the minimum. if ss.opts.CompactMinFileSize > 0 && ss.fileSize < ss.opts.CompactMinFileSize { return false } // Check fragmentation frag := 0 if ss.numRecs == 0 { frag = 100 } else { frag = ss.delRecs * 100 / ss.numRecs } if frag < ss.opts.CompactFragmentation { return false } // Check that we don't compact too often if time.Since(ss.compactTS) < ss.compactItvl { return false } return true }
[ "func", "(", "ss", "*", "FileSubStore", ")", "shouldCompact", "(", ")", "bool", "{", "if", "!", "ss", ".", "opts", ".", "CompactEnabled", "{", "return", "false", "\n", "}", "\n", "if", "ss", ".", "opts", ".", "CompactMinFileSize", ">", "0", "&&", "ss", ".", "fileSize", "<", "ss", ".", "opts", ".", "CompactMinFileSize", "{", "return", "false", "\n", "}", "\n", "frag", ":=", "0", "\n", "if", "ss", ".", "numRecs", "==", "0", "{", "frag", "=", "100", "\n", "}", "else", "{", "frag", "=", "ss", ".", "delRecs", "*", "100", "/", "ss", ".", "numRecs", "\n", "}", "\n", "if", "frag", "<", "ss", ".", "opts", ".", "CompactFragmentation", "{", "return", "false", "\n", "}", "\n", "if", "time", ".", "Since", "(", "ss", ".", "compactTS", ")", "<", "ss", ".", "compactItvl", "{", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}" ]
// shouldCompact returns a boolean indicating if we should compact // Lock is held by caller
[ "shouldCompact", "returns", "a", "boolean", "indicating", "if", "we", "should", "compact", "Lock", "is", "held", "by", "caller" ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L3853-L3878
train
nats-io/nats-streaming-server
stores/filestore.go
AddSeqPending
func (ss *FileSubStore) AddSeqPending(subid, seqno uint64) error { ss.Lock() ss.updateSub.ID, ss.updateSub.Seqno = subid, seqno if err := ss.writeRecord(nil, subRecMsg, &ss.updateSub); err != nil { ss.Unlock() return err } si := ss.subs[subid] if si != nil { s := si.(*subscription) if seqno > s.sub.LastSent { s.sub.LastSent = seqno } s.seqnos[seqno] = struct{}{} } ss.Unlock() return nil }
go
func (ss *FileSubStore) AddSeqPending(subid, seqno uint64) error { ss.Lock() ss.updateSub.ID, ss.updateSub.Seqno = subid, seqno if err := ss.writeRecord(nil, subRecMsg, &ss.updateSub); err != nil { ss.Unlock() return err } si := ss.subs[subid] if si != nil { s := si.(*subscription) if seqno > s.sub.LastSent { s.sub.LastSent = seqno } s.seqnos[seqno] = struct{}{} } ss.Unlock() return nil }
[ "func", "(", "ss", "*", "FileSubStore", ")", "AddSeqPending", "(", "subid", ",", "seqno", "uint64", ")", "error", "{", "ss", ".", "Lock", "(", ")", "\n", "ss", ".", "updateSub", ".", "ID", ",", "ss", ".", "updateSub", ".", "Seqno", "=", "subid", ",", "seqno", "\n", "if", "err", ":=", "ss", ".", "writeRecord", "(", "nil", ",", "subRecMsg", ",", "&", "ss", ".", "updateSub", ")", ";", "err", "!=", "nil", "{", "ss", ".", "Unlock", "(", ")", "\n", "return", "err", "\n", "}", "\n", "si", ":=", "ss", ".", "subs", "[", "subid", "]", "\n", "if", "si", "!=", "nil", "{", "s", ":=", "si", ".", "(", "*", "subscription", ")", "\n", "if", "seqno", ">", "s", ".", "sub", ".", "LastSent", "{", "s", ".", "sub", ".", "LastSent", "=", "seqno", "\n", "}", "\n", "s", ".", "seqnos", "[", "seqno", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "ss", ".", "Unlock", "(", ")", "\n", "return", "nil", "\n", "}" ]
// AddSeqPending adds the given message seqno to the given subscription.
[ "AddSeqPending", "adds", "the", "given", "message", "seqno", "to", "the", "given", "subscription", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L3881-L3898
train
nats-io/nats-streaming-server
stores/filestore.go
AckSeqPending
func (ss *FileSubStore) AckSeqPending(subid, seqno uint64) error { ss.Lock() ss.updateSub.ID, ss.updateSub.Seqno = subid, seqno if err := ss.writeRecord(nil, subRecAck, &ss.updateSub); err != nil { ss.Unlock() return err } si := ss.subs[subid] if si != nil { s := si.(*subscription) delete(s.seqnos, seqno) // Test if we should compact if ss.shouldCompact() { ss.fm.closeFileIfOpened(ss.file) ss.compact(ss.file.name) } } ss.Unlock() return nil }
go
func (ss *FileSubStore) AckSeqPending(subid, seqno uint64) error { ss.Lock() ss.updateSub.ID, ss.updateSub.Seqno = subid, seqno if err := ss.writeRecord(nil, subRecAck, &ss.updateSub); err != nil { ss.Unlock() return err } si := ss.subs[subid] if si != nil { s := si.(*subscription) delete(s.seqnos, seqno) // Test if we should compact if ss.shouldCompact() { ss.fm.closeFileIfOpened(ss.file) ss.compact(ss.file.name) } } ss.Unlock() return nil }
[ "func", "(", "ss", "*", "FileSubStore", ")", "AckSeqPending", "(", "subid", ",", "seqno", "uint64", ")", "error", "{", "ss", ".", "Lock", "(", ")", "\n", "ss", ".", "updateSub", ".", "ID", ",", "ss", ".", "updateSub", ".", "Seqno", "=", "subid", ",", "seqno", "\n", "if", "err", ":=", "ss", ".", "writeRecord", "(", "nil", ",", "subRecAck", ",", "&", "ss", ".", "updateSub", ")", ";", "err", "!=", "nil", "{", "ss", ".", "Unlock", "(", ")", "\n", "return", "err", "\n", "}", "\n", "si", ":=", "ss", ".", "subs", "[", "subid", "]", "\n", "if", "si", "!=", "nil", "{", "s", ":=", "si", ".", "(", "*", "subscription", ")", "\n", "delete", "(", "s", ".", "seqnos", ",", "seqno", ")", "\n", "if", "ss", ".", "shouldCompact", "(", ")", "{", "ss", ".", "fm", ".", "closeFileIfOpened", "(", "ss", ".", "file", ")", "\n", "ss", ".", "compact", "(", "ss", ".", "file", ".", "name", ")", "\n", "}", "\n", "}", "\n", "ss", ".", "Unlock", "(", ")", "\n", "return", "nil", "\n", "}" ]
// AckSeqPending records that the given message seqno has been acknowledged // by the given subscription.
[ "AckSeqPending", "records", "that", "the", "given", "message", "seqno", "has", "been", "acknowledged", "by", "the", "given", "subscription", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L3902-L3921
train
nats-io/nats-streaming-server
stores/filestore.go
compact
func (ss *FileSubStore) compact(orgFileName string) error { tmpFile, err := getTempFile(ss.fm.rootDir, "subs") if err != nil { return err } tmpBW := bufio.NewWriterSize(tmpFile, defaultBufSize) // Save values in case of failed compaction savedNumRecs := ss.numRecs savedDelRecs := ss.delRecs savedFileSize := ss.fileSize // Cleanup in case of error during compact defer func() { if tmpFile != nil { tmpFile.Close() os.Remove(tmpFile.Name()) // Since we failed compaction, restore values ss.numRecs = savedNumRecs ss.delRecs = savedDelRecs ss.fileSize = savedFileSize } }() // Reset to 0 since writeRecord() is updating the values. ss.numRecs = 0 ss.delRecs = 0 ss.fileSize = 0 for _, subi := range ss.subs { sub := subi.(*subscription) err = ss.writeRecord(tmpBW, subRecNew, sub.sub) if err != nil { return err } ss.updateSub.ID = sub.sub.ID for seqno := range sub.seqnos { ss.updateSub.Seqno = seqno err = ss.writeRecord(tmpBW, subRecMsg, &ss.updateSub) if err != nil { return err } } } // Flush and sync the temporary file err = tmpBW.Flush() if err != nil { return err } err = tmpFile.Sync() if err != nil { return err } // Start by closing the temporary file. if err := tmpFile.Close(); err != nil { return err } // Rename the tmp file to original file name if err := os.Rename(tmpFile.Name(), orgFileName); err != nil { return err } // Prevent cleanup on success tmpFile = nil // Update the timestamp of this last successful compact ss.compactTS = time.Now() return nil }
go
func (ss *FileSubStore) compact(orgFileName string) error { tmpFile, err := getTempFile(ss.fm.rootDir, "subs") if err != nil { return err } tmpBW := bufio.NewWriterSize(tmpFile, defaultBufSize) // Save values in case of failed compaction savedNumRecs := ss.numRecs savedDelRecs := ss.delRecs savedFileSize := ss.fileSize // Cleanup in case of error during compact defer func() { if tmpFile != nil { tmpFile.Close() os.Remove(tmpFile.Name()) // Since we failed compaction, restore values ss.numRecs = savedNumRecs ss.delRecs = savedDelRecs ss.fileSize = savedFileSize } }() // Reset to 0 since writeRecord() is updating the values. ss.numRecs = 0 ss.delRecs = 0 ss.fileSize = 0 for _, subi := range ss.subs { sub := subi.(*subscription) err = ss.writeRecord(tmpBW, subRecNew, sub.sub) if err != nil { return err } ss.updateSub.ID = sub.sub.ID for seqno := range sub.seqnos { ss.updateSub.Seqno = seqno err = ss.writeRecord(tmpBW, subRecMsg, &ss.updateSub) if err != nil { return err } } } // Flush and sync the temporary file err = tmpBW.Flush() if err != nil { return err } err = tmpFile.Sync() if err != nil { return err } // Start by closing the temporary file. if err := tmpFile.Close(); err != nil { return err } // Rename the tmp file to original file name if err := os.Rename(tmpFile.Name(), orgFileName); err != nil { return err } // Prevent cleanup on success tmpFile = nil // Update the timestamp of this last successful compact ss.compactTS = time.Now() return nil }
[ "func", "(", "ss", "*", "FileSubStore", ")", "compact", "(", "orgFileName", "string", ")", "error", "{", "tmpFile", ",", "err", ":=", "getTempFile", "(", "ss", ".", "fm", ".", "rootDir", ",", "\"subs\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "tmpBW", ":=", "bufio", ".", "NewWriterSize", "(", "tmpFile", ",", "defaultBufSize", ")", "\n", "savedNumRecs", ":=", "ss", ".", "numRecs", "\n", "savedDelRecs", ":=", "ss", ".", "delRecs", "\n", "savedFileSize", ":=", "ss", ".", "fileSize", "\n", "defer", "func", "(", ")", "{", "if", "tmpFile", "!=", "nil", "{", "tmpFile", ".", "Close", "(", ")", "\n", "os", ".", "Remove", "(", "tmpFile", ".", "Name", "(", ")", ")", "\n", "ss", ".", "numRecs", "=", "savedNumRecs", "\n", "ss", ".", "delRecs", "=", "savedDelRecs", "\n", "ss", ".", "fileSize", "=", "savedFileSize", "\n", "}", "\n", "}", "(", ")", "\n", "ss", ".", "numRecs", "=", "0", "\n", "ss", ".", "delRecs", "=", "0", "\n", "ss", ".", "fileSize", "=", "0", "\n", "for", "_", ",", "subi", ":=", "range", "ss", ".", "subs", "{", "sub", ":=", "subi", ".", "(", "*", "subscription", ")", "\n", "err", "=", "ss", ".", "writeRecord", "(", "tmpBW", ",", "subRecNew", ",", "sub", ".", "sub", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "ss", ".", "updateSub", ".", "ID", "=", "sub", ".", "sub", ".", "ID", "\n", "for", "seqno", ":=", "range", "sub", ".", "seqnos", "{", "ss", ".", "updateSub", ".", "Seqno", "=", "seqno", "\n", "err", "=", "ss", ".", "writeRecord", "(", "tmpBW", ",", "subRecMsg", ",", "&", "ss", ".", "updateSub", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "err", "=", "tmpBW", ".", "Flush", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "err", "=", "tmpFile", ".", "Sync", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "tmpFile", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "os", ".", "Rename", "(", "tmpFile", ".", "Name", "(", ")", ",", "orgFileName", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "tmpFile", "=", "nil", "\n", "ss", ".", "compactTS", "=", "time", ".", "Now", "(", ")", "\n", "return", "nil", "\n", "}" ]
// compact rewrites all subscriptions on a temporary file, reducing the size // since we get rid of deleted subscriptions and message sequences that have // been acknowledged. On success, the subscriptions file is replaced by this // temporary file. // Lock is held by caller
[ "compact", "rewrites", "all", "subscriptions", "on", "a", "temporary", "file", "reducing", "the", "size", "since", "we", "get", "rid", "of", "deleted", "subscriptions", "and", "message", "sequences", "that", "have", "been", "acknowledged", ".", "On", "success", "the", "subscriptions", "file", "is", "replaced", "by", "this", "temporary", "file", ".", "Lock", "is", "held", "by", "caller" ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L3928-L3990
train
nats-io/nats-streaming-server
stores/filestore.go
writeRecord
func (ss *FileSubStore) writeRecord(w io.Writer, recType recordType, rec record) error { var err error totalSize := 0 recSize := rec.Size() var bwBuf *bufio.Writer needsUnlock := false if w == nil { if err := ss.lockFile(); err != nil { return err } needsUnlock = true if ss.bw != nil { bwBuf = ss.bw.buf // If we are using the buffer writer on this call, and the buffer is // not already at the max size... if bwBuf != nil && ss.bw.bufSize != ss.opts.BufferSize { // Check if record fits required := recSize + recordHeaderSize if required > bwBuf.Available() { ss.writer, err = ss.bw.expand(ss.file.handle, required) if err != nil { ss.fm.unlockFile(ss.file) return err } bwBuf = ss.bw.buf } } } w = ss.writer } ss.tmpSubBuf, totalSize, err = writeRecord(w, ss.tmpSubBuf, recType, rec, recSize, ss.crcTable) if err != nil { if needsUnlock { ss.fm.unlockFile(ss.file) } return err } if bwBuf != nil && ss.bw.shrinkReq { ss.bw.checkShrinkRequest() } // Indicate that we wrote something to the buffer/file ss.activity = true switch recType { case subRecNew: ss.numRecs++ case subRecMsg: ss.numRecs++ case subRecAck: // An ack makes the message record free space ss.delRecs++ case subRecUpdate: ss.numRecs++ // An update makes the old record free space ss.delRecs++ case subRecDel: ss.delRecs++ default: panic(fmt.Errorf("record type %v unknown", recType)) } ss.fileSize += int64(totalSize) if needsUnlock { ss.fm.unlockFile(ss.file) } return nil }
go
func (ss *FileSubStore) writeRecord(w io.Writer, recType recordType, rec record) error { var err error totalSize := 0 recSize := rec.Size() var bwBuf *bufio.Writer needsUnlock := false if w == nil { if err := ss.lockFile(); err != nil { return err } needsUnlock = true if ss.bw != nil { bwBuf = ss.bw.buf // If we are using the buffer writer on this call, and the buffer is // not already at the max size... if bwBuf != nil && ss.bw.bufSize != ss.opts.BufferSize { // Check if record fits required := recSize + recordHeaderSize if required > bwBuf.Available() { ss.writer, err = ss.bw.expand(ss.file.handle, required) if err != nil { ss.fm.unlockFile(ss.file) return err } bwBuf = ss.bw.buf } } } w = ss.writer } ss.tmpSubBuf, totalSize, err = writeRecord(w, ss.tmpSubBuf, recType, rec, recSize, ss.crcTable) if err != nil { if needsUnlock { ss.fm.unlockFile(ss.file) } return err } if bwBuf != nil && ss.bw.shrinkReq { ss.bw.checkShrinkRequest() } // Indicate that we wrote something to the buffer/file ss.activity = true switch recType { case subRecNew: ss.numRecs++ case subRecMsg: ss.numRecs++ case subRecAck: // An ack makes the message record free space ss.delRecs++ case subRecUpdate: ss.numRecs++ // An update makes the old record free space ss.delRecs++ case subRecDel: ss.delRecs++ default: panic(fmt.Errorf("record type %v unknown", recType)) } ss.fileSize += int64(totalSize) if needsUnlock { ss.fm.unlockFile(ss.file) } return nil }
[ "func", "(", "ss", "*", "FileSubStore", ")", "writeRecord", "(", "w", "io", ".", "Writer", ",", "recType", "recordType", ",", "rec", "record", ")", "error", "{", "var", "err", "error", "\n", "totalSize", ":=", "0", "\n", "recSize", ":=", "rec", ".", "Size", "(", ")", "\n", "var", "bwBuf", "*", "bufio", ".", "Writer", "\n", "needsUnlock", ":=", "false", "\n", "if", "w", "==", "nil", "{", "if", "err", ":=", "ss", ".", "lockFile", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "needsUnlock", "=", "true", "\n", "if", "ss", ".", "bw", "!=", "nil", "{", "bwBuf", "=", "ss", ".", "bw", ".", "buf", "\n", "if", "bwBuf", "!=", "nil", "&&", "ss", ".", "bw", ".", "bufSize", "!=", "ss", ".", "opts", ".", "BufferSize", "{", "required", ":=", "recSize", "+", "recordHeaderSize", "\n", "if", "required", ">", "bwBuf", ".", "Available", "(", ")", "{", "ss", ".", "writer", ",", "err", "=", "ss", ".", "bw", ".", "expand", "(", "ss", ".", "file", ".", "handle", ",", "required", ")", "\n", "if", "err", "!=", "nil", "{", "ss", ".", "fm", ".", "unlockFile", "(", "ss", ".", "file", ")", "\n", "return", "err", "\n", "}", "\n", "bwBuf", "=", "ss", ".", "bw", ".", "buf", "\n", "}", "\n", "}", "\n", "}", "\n", "w", "=", "ss", ".", "writer", "\n", "}", "\n", "ss", ".", "tmpSubBuf", ",", "totalSize", ",", "err", "=", "writeRecord", "(", "w", ",", "ss", ".", "tmpSubBuf", ",", "recType", ",", "rec", ",", "recSize", ",", "ss", ".", "crcTable", ")", "\n", "if", "err", "!=", "nil", "{", "if", "needsUnlock", "{", "ss", ".", "fm", ".", "unlockFile", "(", "ss", ".", "file", ")", "\n", "}", "\n", "return", "err", "\n", "}", "\n", "if", "bwBuf", "!=", "nil", "&&", "ss", ".", "bw", ".", "shrinkReq", "{", "ss", ".", "bw", ".", "checkShrinkRequest", "(", ")", "\n", "}", "\n", "ss", ".", "activity", "=", "true", "\n", "switch", "recType", "{", "case", "subRecNew", ":", "ss", ".", "numRecs", "++", "\n", "case", "subRecMsg", ":", "ss", ".", "numRecs", "++", "\n", "case", "subRecAck", ":", "ss", ".", "delRecs", "++", "\n", "case", "subRecUpdate", ":", "ss", ".", "numRecs", "++", "\n", "ss", ".", "delRecs", "++", "\n", "case", "subRecDel", ":", "ss", ".", "delRecs", "++", "\n", "default", ":", "panic", "(", "fmt", ".", "Errorf", "(", "\"record type %v unknown\"", ",", "recType", ")", ")", "\n", "}", "\n", "ss", ".", "fileSize", "+=", "int64", "(", "totalSize", ")", "\n", "if", "needsUnlock", "{", "ss", ".", "fm", ".", "unlockFile", "(", "ss", ".", "file", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// writes a record in the subscriptions file. // store's lock is held on entry.
[ "writes", "a", "record", "in", "the", "subscriptions", "file", ".", "store", "s", "lock", "is", "held", "on", "entry", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L3994-L4060
train
nats-io/nats-streaming-server
stores/filestore.go
Flush
func (ss *FileSubStore) Flush() error { ss.Lock() err := ss.lockFile() if err == nil { err = ss.flush() ss.fm.unlockFile(ss.file) } ss.Unlock() return err }
go
func (ss *FileSubStore) Flush() error { ss.Lock() err := ss.lockFile() if err == nil { err = ss.flush() ss.fm.unlockFile(ss.file) } ss.Unlock() return err }
[ "func", "(", "ss", "*", "FileSubStore", ")", "Flush", "(", ")", "error", "{", "ss", ".", "Lock", "(", ")", "\n", "err", ":=", "ss", ".", "lockFile", "(", ")", "\n", "if", "err", "==", "nil", "{", "err", "=", "ss", ".", "flush", "(", ")", "\n", "ss", ".", "fm", ".", "unlockFile", "(", "ss", ".", "file", ")", "\n", "}", "\n", "ss", ".", "Unlock", "(", ")", "\n", "return", "err", "\n", "}" ]
// Flush persists buffered operations to disk.
[ "Flush", "persists", "buffered", "operations", "to", "disk", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L4081-L4090
train
nats-io/nats-streaming-server
stores/filestore.go
Close
func (ss *FileSubStore) Close() error { ss.Lock() if ss.closed { ss.Unlock() return nil } ss.closed = true if ss.shrinkTimer != nil { if ss.shrinkTimer.Stop() { // If we can stop, timer callback won't fire, // so we need to decrement the wait group. ss.allDone.Done() } } ss.Unlock() // Wait on timers/callbacks ss.allDone.Wait() ss.Lock() var err error if ss.fm.remove(ss.file) { if ss.file.handle != nil { err = ss.flush() err = util.CloseFile(err, ss.file.handle) } } ss.Unlock() return err }
go
func (ss *FileSubStore) Close() error { ss.Lock() if ss.closed { ss.Unlock() return nil } ss.closed = true if ss.shrinkTimer != nil { if ss.shrinkTimer.Stop() { // If we can stop, timer callback won't fire, // so we need to decrement the wait group. ss.allDone.Done() } } ss.Unlock() // Wait on timers/callbacks ss.allDone.Wait() ss.Lock() var err error if ss.fm.remove(ss.file) { if ss.file.handle != nil { err = ss.flush() err = util.CloseFile(err, ss.file.handle) } } ss.Unlock() return err }
[ "func", "(", "ss", "*", "FileSubStore", ")", "Close", "(", ")", "error", "{", "ss", ".", "Lock", "(", ")", "\n", "if", "ss", ".", "closed", "{", "ss", ".", "Unlock", "(", ")", "\n", "return", "nil", "\n", "}", "\n", "ss", ".", "closed", "=", "true", "\n", "if", "ss", ".", "shrinkTimer", "!=", "nil", "{", "if", "ss", ".", "shrinkTimer", ".", "Stop", "(", ")", "{", "ss", ".", "allDone", ".", "Done", "(", ")", "\n", "}", "\n", "}", "\n", "ss", ".", "Unlock", "(", ")", "\n", "ss", ".", "allDone", ".", "Wait", "(", ")", "\n", "ss", ".", "Lock", "(", ")", "\n", "var", "err", "error", "\n", "if", "ss", ".", "fm", ".", "remove", "(", "ss", ".", "file", ")", "{", "if", "ss", ".", "file", ".", "handle", "!=", "nil", "{", "err", "=", "ss", ".", "flush", "(", ")", "\n", "err", "=", "util", ".", "CloseFile", "(", "err", ",", "ss", ".", "file", ".", "handle", ")", "\n", "}", "\n", "}", "\n", "ss", ".", "Unlock", "(", ")", "\n", "return", "err", "\n", "}" ]
// Close closes this store
[ "Close", "closes", "this", "store" ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/filestore.go#L4093-L4125
train
nats-io/nats-streaming-server
server/raft_transport.go
Dial
func (n *natsStreamLayer) Dial(address raft.ServerAddress, timeout time.Duration) (net.Conn, error) { if !n.conn.IsConnected() { return nil, errors.New("raft-nats: dial failed, not connected") } // QUESTION: The Raft NetTransport does connection pooling, which is useful // for TCP sockets. The NATS transport simulates a socket using a // subscription at each endpoint, but everything goes over the same NATS // socket. This means there is little advantage to pooling here currently. // Should we actually Dial a new NATS connection here and rely on pooling? connect := &connectRequestProto{ ID: n.localAddr.String(), Inbox: fmt.Sprintf(natsRequestInbox, n.localAddr.String(), nats.NewInbox()), } data, err := json.Marshal(connect) if err != nil { panic(err) } peerConn := n.newNATSConn(string(address)) // Setup inbox. sub, err := n.conn.Subscribe(connect.Inbox, peerConn.msgHandler) if err != nil { return nil, err } sub.SetPendingLimits(-1, -1) if err := n.conn.FlushTimeout(n.timeout); err != nil { sub.Unsubscribe() return nil, err } // Make connect request to peer. msg, err := n.conn.Request(fmt.Sprintf(natsConnectInbox, address), data, timeout) if err != nil { sub.Unsubscribe() return nil, err } var resp connectResponseProto if err := json.Unmarshal(msg.Data, &resp); err != nil { sub.Unsubscribe() return nil, err } peerConn.sub = sub peerConn.outbox = resp.Inbox n.mu.Lock() n.conns[peerConn] = struct{}{} n.mu.Unlock() return peerConn, nil }
go
func (n *natsStreamLayer) Dial(address raft.ServerAddress, timeout time.Duration) (net.Conn, error) { if !n.conn.IsConnected() { return nil, errors.New("raft-nats: dial failed, not connected") } // QUESTION: The Raft NetTransport does connection pooling, which is useful // for TCP sockets. The NATS transport simulates a socket using a // subscription at each endpoint, but everything goes over the same NATS // socket. This means there is little advantage to pooling here currently. // Should we actually Dial a new NATS connection here and rely on pooling? connect := &connectRequestProto{ ID: n.localAddr.String(), Inbox: fmt.Sprintf(natsRequestInbox, n.localAddr.String(), nats.NewInbox()), } data, err := json.Marshal(connect) if err != nil { panic(err) } peerConn := n.newNATSConn(string(address)) // Setup inbox. sub, err := n.conn.Subscribe(connect.Inbox, peerConn.msgHandler) if err != nil { return nil, err } sub.SetPendingLimits(-1, -1) if err := n.conn.FlushTimeout(n.timeout); err != nil { sub.Unsubscribe() return nil, err } // Make connect request to peer. msg, err := n.conn.Request(fmt.Sprintf(natsConnectInbox, address), data, timeout) if err != nil { sub.Unsubscribe() return nil, err } var resp connectResponseProto if err := json.Unmarshal(msg.Data, &resp); err != nil { sub.Unsubscribe() return nil, err } peerConn.sub = sub peerConn.outbox = resp.Inbox n.mu.Lock() n.conns[peerConn] = struct{}{} n.mu.Unlock() return peerConn, nil }
[ "func", "(", "n", "*", "natsStreamLayer", ")", "Dial", "(", "address", "raft", ".", "ServerAddress", ",", "timeout", "time", ".", "Duration", ")", "(", "net", ".", "Conn", ",", "error", ")", "{", "if", "!", "n", ".", "conn", ".", "IsConnected", "(", ")", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"raft-nats: dial failed, not connected\"", ")", "\n", "}", "\n", "connect", ":=", "&", "connectRequestProto", "{", "ID", ":", "n", ".", "localAddr", ".", "String", "(", ")", ",", "Inbox", ":", "fmt", ".", "Sprintf", "(", "natsRequestInbox", ",", "n", ".", "localAddr", ".", "String", "(", ")", ",", "nats", ".", "NewInbox", "(", ")", ")", ",", "}", "\n", "data", ",", "err", ":=", "json", ".", "Marshal", "(", "connect", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "peerConn", ":=", "n", ".", "newNATSConn", "(", "string", "(", "address", ")", ")", "\n", "sub", ",", "err", ":=", "n", ".", "conn", ".", "Subscribe", "(", "connect", ".", "Inbox", ",", "peerConn", ".", "msgHandler", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "sub", ".", "SetPendingLimits", "(", "-", "1", ",", "-", "1", ")", "\n", "if", "err", ":=", "n", ".", "conn", ".", "FlushTimeout", "(", "n", ".", "timeout", ")", ";", "err", "!=", "nil", "{", "sub", ".", "Unsubscribe", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "msg", ",", "err", ":=", "n", ".", "conn", ".", "Request", "(", "fmt", ".", "Sprintf", "(", "natsConnectInbox", ",", "address", ")", ",", "data", ",", "timeout", ")", "\n", "if", "err", "!=", "nil", "{", "sub", ".", "Unsubscribe", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "var", "resp", "connectResponseProto", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "msg", ".", "Data", ",", "&", "resp", ")", ";", "err", "!=", "nil", "{", "sub", ".", "Unsubscribe", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "peerConn", ".", "sub", "=", "sub", "\n", "peerConn", ".", "outbox", "=", "resp", ".", "Inbox", "\n", "n", ".", "mu", ".", "Lock", "(", ")", "\n", "n", ".", "conns", "[", "peerConn", "]", "=", "struct", "{", "}", "{", "}", "\n", "n", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "peerConn", ",", "nil", "\n", "}" ]
// Dial creates a new net.Conn with the remote address. This is implemented by // performing a handshake over NATS which establishes unique inboxes at each // endpoint for streaming data.
[ "Dial", "creates", "a", "new", "net", ".", "Conn", "with", "the", "remote", "address", ".", "This", "is", "implemented", "by", "performing", "a", "handshake", "over", "NATS", "which", "establishes", "unique", "inboxes", "at", "each", "endpoint", "for", "streaming", "data", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/server/raft_transport.go#L225-L276
train
nats-io/nats-streaming-server
server/raft_transport.go
newNATSTransport
func newNATSTransport(id string, conn *nats.Conn, timeout time.Duration, logOutput io.Writer) (*raft.NetworkTransport, error) { if logOutput == nil { logOutput = os.Stderr } return newNATSTransportWithLogger(id, conn, timeout, log.New(logOutput, "", log.LstdFlags)) }
go
func newNATSTransport(id string, conn *nats.Conn, timeout time.Duration, logOutput io.Writer) (*raft.NetworkTransport, error) { if logOutput == nil { logOutput = os.Stderr } return newNATSTransportWithLogger(id, conn, timeout, log.New(logOutput, "", log.LstdFlags)) }
[ "func", "newNATSTransport", "(", "id", "string", ",", "conn", "*", "nats", ".", "Conn", ",", "timeout", "time", ".", "Duration", ",", "logOutput", "io", ".", "Writer", ")", "(", "*", "raft", ".", "NetworkTransport", ",", "error", ")", "{", "if", "logOutput", "==", "nil", "{", "logOutput", "=", "os", ".", "Stderr", "\n", "}", "\n", "return", "newNATSTransportWithLogger", "(", "id", ",", "conn", ",", "timeout", ",", "log", ".", "New", "(", "logOutput", ",", "\"\"", ",", "log", ".", "LstdFlags", ")", ")", "\n", "}" ]
// newNATSTransport creates a new raft.NetworkTransport implemented with NATS // as the transport layer.
[ "newNATSTransport", "creates", "a", "new", "raft", ".", "NetworkTransport", "implemented", "with", "NATS", "as", "the", "transport", "layer", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/server/raft_transport.go#L350-L355
train
nats-io/nats-streaming-server
server/raft_transport.go
newNATSTransportWithLogger
func newNATSTransportWithLogger(id string, conn *nats.Conn, timeout time.Duration, logger *log.Logger) (*raft.NetworkTransport, error) { return createNATSTransport(id, conn, logger, timeout, func(stream raft.StreamLayer) *raft.NetworkTransport { return raft.NewNetworkTransportWithLogger(stream, 3, timeout, logger) }) }
go
func newNATSTransportWithLogger(id string, conn *nats.Conn, timeout time.Duration, logger *log.Logger) (*raft.NetworkTransport, error) { return createNATSTransport(id, conn, logger, timeout, func(stream raft.StreamLayer) *raft.NetworkTransport { return raft.NewNetworkTransportWithLogger(stream, 3, timeout, logger) }) }
[ "func", "newNATSTransportWithLogger", "(", "id", "string", ",", "conn", "*", "nats", ".", "Conn", ",", "timeout", "time", ".", "Duration", ",", "logger", "*", "log", ".", "Logger", ")", "(", "*", "raft", ".", "NetworkTransport", ",", "error", ")", "{", "return", "createNATSTransport", "(", "id", ",", "conn", ",", "logger", ",", "timeout", ",", "func", "(", "stream", "raft", ".", "StreamLayer", ")", "*", "raft", ".", "NetworkTransport", "{", "return", "raft", ".", "NewNetworkTransportWithLogger", "(", "stream", ",", "3", ",", "timeout", ",", "logger", ")", "\n", "}", ")", "\n", "}" ]
// newNATSTransportWithLogger creates a new raft.NetworkTransport implemented // with NATS as the transport layer using the provided Logger.
[ "newNATSTransportWithLogger", "creates", "a", "new", "raft", ".", "NetworkTransport", "implemented", "with", "NATS", "as", "the", "transport", "layer", "using", "the", "provided", "Logger", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/server/raft_transport.go#L359-L363
train
nats-io/nats-streaming-server
server/raft_transport.go
newNATSTransportWithConfig
func newNATSTransportWithConfig(id string, conn *nats.Conn, config *raft.NetworkTransportConfig) (*raft.NetworkTransport, error) { if config.Timeout == 0 { config.Timeout = 2 * time.Second } return createNATSTransport(id, conn, config.Logger, config.Timeout, func(stream raft.StreamLayer) *raft.NetworkTransport { config.Stream = stream return raft.NewNetworkTransportWithConfig(config) }) }
go
func newNATSTransportWithConfig(id string, conn *nats.Conn, config *raft.NetworkTransportConfig) (*raft.NetworkTransport, error) { if config.Timeout == 0 { config.Timeout = 2 * time.Second } return createNATSTransport(id, conn, config.Logger, config.Timeout, func(stream raft.StreamLayer) *raft.NetworkTransport { config.Stream = stream return raft.NewNetworkTransportWithConfig(config) }) }
[ "func", "newNATSTransportWithConfig", "(", "id", "string", ",", "conn", "*", "nats", ".", "Conn", ",", "config", "*", "raft", ".", "NetworkTransportConfig", ")", "(", "*", "raft", ".", "NetworkTransport", ",", "error", ")", "{", "if", "config", ".", "Timeout", "==", "0", "{", "config", ".", "Timeout", "=", "2", "*", "time", ".", "Second", "\n", "}", "\n", "return", "createNATSTransport", "(", "id", ",", "conn", ",", "config", ".", "Logger", ",", "config", ".", "Timeout", ",", "func", "(", "stream", "raft", ".", "StreamLayer", ")", "*", "raft", ".", "NetworkTransport", "{", "config", ".", "Stream", "=", "stream", "\n", "return", "raft", ".", "NewNetworkTransportWithConfig", "(", "config", ")", "\n", "}", ")", "\n", "}" ]
// newNATSTransportWithConfig returns a raft.NetworkTransport implemented // with NATS as the transport layer, using the given config struct.
[ "newNATSTransportWithConfig", "returns", "a", "raft", ".", "NetworkTransport", "implemented", "with", "NATS", "as", "the", "transport", "layer", "using", "the", "given", "config", "struct", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/server/raft_transport.go#L367-L375
train
nats-io/nats-streaming-server
stores/memstore.go
expireMsgs
func (ms *MemoryMsgStore) expireMsgs() { ms.Lock() defer ms.Unlock() if ms.closed { ms.wg.Done() return } now := time.Now().UnixNano() maxAge := int64(ms.limits.MaxAge) for { m, ok := ms.msgs[ms.first] if !ok { if ms.first < ms.last { ms.first++ continue } ms.ageTimer = nil ms.wg.Done() return } elapsed := now - m.Timestamp if elapsed >= maxAge { ms.removeFirstMsg() } else { if elapsed < 0 { ms.ageTimer.Reset(time.Duration(m.Timestamp - now + maxAge)) } else { ms.ageTimer.Reset(time.Duration(maxAge - elapsed)) } return } } }
go
func (ms *MemoryMsgStore) expireMsgs() { ms.Lock() defer ms.Unlock() if ms.closed { ms.wg.Done() return } now := time.Now().UnixNano() maxAge := int64(ms.limits.MaxAge) for { m, ok := ms.msgs[ms.first] if !ok { if ms.first < ms.last { ms.first++ continue } ms.ageTimer = nil ms.wg.Done() return } elapsed := now - m.Timestamp if elapsed >= maxAge { ms.removeFirstMsg() } else { if elapsed < 0 { ms.ageTimer.Reset(time.Duration(m.Timestamp - now + maxAge)) } else { ms.ageTimer.Reset(time.Duration(maxAge - elapsed)) } return } } }
[ "func", "(", "ms", "*", "MemoryMsgStore", ")", "expireMsgs", "(", ")", "{", "ms", ".", "Lock", "(", ")", "\n", "defer", "ms", ".", "Unlock", "(", ")", "\n", "if", "ms", ".", "closed", "{", "ms", ".", "wg", ".", "Done", "(", ")", "\n", "return", "\n", "}", "\n", "now", ":=", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", "\n", "maxAge", ":=", "int64", "(", "ms", ".", "limits", ".", "MaxAge", ")", "\n", "for", "{", "m", ",", "ok", ":=", "ms", ".", "msgs", "[", "ms", ".", "first", "]", "\n", "if", "!", "ok", "{", "if", "ms", ".", "first", "<", "ms", ".", "last", "{", "ms", ".", "first", "++", "\n", "continue", "\n", "}", "\n", "ms", ".", "ageTimer", "=", "nil", "\n", "ms", ".", "wg", ".", "Done", "(", ")", "\n", "return", "\n", "}", "\n", "elapsed", ":=", "now", "-", "m", ".", "Timestamp", "\n", "if", "elapsed", ">=", "maxAge", "{", "ms", ".", "removeFirstMsg", "(", ")", "\n", "}", "else", "{", "if", "elapsed", "<", "0", "{", "ms", ".", "ageTimer", ".", "Reset", "(", "time", ".", "Duration", "(", "m", ".", "Timestamp", "-", "now", "+", "maxAge", ")", ")", "\n", "}", "else", "{", "ms", ".", "ageTimer", ".", "Reset", "(", "time", ".", "Duration", "(", "maxAge", "-", "elapsed", ")", ")", "\n", "}", "\n", "return", "\n", "}", "\n", "}", "\n", "}" ]
// expireMsgs ensures that messages don't stay in the log longer than the // limit's MaxAge.
[ "expireMsgs", "ensures", "that", "messages", "don", "t", "stay", "in", "the", "log", "longer", "than", "the", "limit", "s", "MaxAge", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/memstore.go#L189-L222
train
nats-io/nats-streaming-server
stores/memstore.go
removeFirstMsg
func (ms *MemoryMsgStore) removeFirstMsg() { firstMsg := ms.msgs[ms.first] ms.totalBytes -= uint64(firstMsg.Size()) ms.totalCount-- delete(ms.msgs, ms.first) ms.first++ }
go
func (ms *MemoryMsgStore) removeFirstMsg() { firstMsg := ms.msgs[ms.first] ms.totalBytes -= uint64(firstMsg.Size()) ms.totalCount-- delete(ms.msgs, ms.first) ms.first++ }
[ "func", "(", "ms", "*", "MemoryMsgStore", ")", "removeFirstMsg", "(", ")", "{", "firstMsg", ":=", "ms", ".", "msgs", "[", "ms", ".", "first", "]", "\n", "ms", ".", "totalBytes", "-=", "uint64", "(", "firstMsg", ".", "Size", "(", ")", ")", "\n", "ms", ".", "totalCount", "--", "\n", "delete", "(", "ms", ".", "msgs", ",", "ms", ".", "first", ")", "\n", "ms", ".", "first", "++", "\n", "}" ]
// removeFirstMsg removes the first message and updates totals.
[ "removeFirstMsg", "removes", "the", "first", "message", "and", "updates", "totals", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/memstore.go#L225-L231
train
nats-io/nats-streaming-server
stores/sqlstore.go
SQLNoCaching
func SQLNoCaching(noCaching bool) SQLStoreOption { return func(o *SQLStoreOptions) error { o.NoCaching = noCaching return nil } }
go
func SQLNoCaching(noCaching bool) SQLStoreOption { return func(o *SQLStoreOptions) error { o.NoCaching = noCaching return nil } }
[ "func", "SQLNoCaching", "(", "noCaching", "bool", ")", "SQLStoreOption", "{", "return", "func", "(", "o", "*", "SQLStoreOptions", ")", "error", "{", "o", ".", "NoCaching", "=", "noCaching", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// SQLNoCaching sets the NoCaching option
[ "SQLNoCaching", "sets", "the", "NoCaching", "option" ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/sqlstore.go#L231-L236
train
nats-io/nats-streaming-server
stores/sqlstore.go
SQLMaxOpenConns
func SQLMaxOpenConns(max int) SQLStoreOption { return func(o *SQLStoreOptions) error { o.MaxOpenConns = max return nil } }
go
func SQLMaxOpenConns(max int) SQLStoreOption { return func(o *SQLStoreOptions) error { o.MaxOpenConns = max return nil } }
[ "func", "SQLMaxOpenConns", "(", "max", "int", ")", "SQLStoreOption", "{", "return", "func", "(", "o", "*", "SQLStoreOptions", ")", "error", "{", "o", ".", "MaxOpenConns", "=", "max", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// SQLMaxOpenConns sets the MaxOpenConns option
[ "SQLMaxOpenConns", "sets", "the", "MaxOpenConns", "option" ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/sqlstore.go#L239-L244
train
nats-io/nats-streaming-server
stores/sqlstore.go
SQLAllOptions
func SQLAllOptions(opts *SQLStoreOptions) SQLStoreOption { return func(o *SQLStoreOptions) error { o.NoCaching = opts.NoCaching o.MaxOpenConns = opts.MaxOpenConns return nil } }
go
func SQLAllOptions(opts *SQLStoreOptions) SQLStoreOption { return func(o *SQLStoreOptions) error { o.NoCaching = opts.NoCaching o.MaxOpenConns = opts.MaxOpenConns return nil } }
[ "func", "SQLAllOptions", "(", "opts", "*", "SQLStoreOptions", ")", "SQLStoreOption", "{", "return", "func", "(", "o", "*", "SQLStoreOptions", ")", "error", "{", "o", ".", "NoCaching", "=", "opts", ".", "NoCaching", "\n", "o", ".", "MaxOpenConns", "=", "opts", ".", "MaxOpenConns", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// SQLAllOptions is a convenient option to pass all options from a SQLStoreOptions // structure to the constructor.
[ "SQLAllOptions", "is", "a", "convenient", "option", "to", "pass", "all", "options", "from", "a", "SQLStoreOptions", "structure", "to", "the", "constructor", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/sqlstore.go#L248-L254
train
nats-io/nats-streaming-server
stores/sqlstore.go
sqlStmtError
func sqlStmtError(code int, err error) error { return fmt.Errorf("sql: error executing %q: %v", sqlStmts[code], err) }
go
func sqlStmtError(code int, err error) error { return fmt.Errorf("sql: error executing %q: %v", sqlStmts[code], err) }
[ "func", "sqlStmtError", "(", "code", "int", ",", "err", "error", ")", "error", "{", "return", "fmt", ".", "Errorf", "(", "\"sql: error executing %q: %v\"", ",", "sqlStmts", "[", "code", "]", ",", "err", ")", "\n", "}" ]
// sqlStmtError returns an error including the text of the offending SQL statement.
[ "sqlStmtError", "returns", "an", "error", "including", "the", "text", "of", "the", "offending", "SQL", "statement", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/sqlstore.go#L353-L355
train
nats-io/nats-streaming-server
stores/sqlstore.go
updateDBLock
func (s *SQLStore) updateDBLock() { defer s.wg.Done() var ( ticker = time.NewTicker(sqlLockUpdateInterval) hasLock = true err error failed int ) for { select { case <-ticker.C: hasLock, _, _, err = s.acquireDBLock(false) if !hasLock || err != nil { // If there is no error but we did not get the lock, // something is really wrong, abort right away. stopNow := !hasLock && err == nil if err != nil { failed++ s.log.Errorf("Unable to update store lock (failed=%v err=%v)", failed, err) } if stopNow || failed == sqlLockLostCount { if sqlNoPanic { s.log.Fatalf("Aborting") return } panic("lost store lock, aborting") } } else { failed = 0 } case <-s.doneCh: ticker.Stop() return } } }
go
func (s *SQLStore) updateDBLock() { defer s.wg.Done() var ( ticker = time.NewTicker(sqlLockUpdateInterval) hasLock = true err error failed int ) for { select { case <-ticker.C: hasLock, _, _, err = s.acquireDBLock(false) if !hasLock || err != nil { // If there is no error but we did not get the lock, // something is really wrong, abort right away. stopNow := !hasLock && err == nil if err != nil { failed++ s.log.Errorf("Unable to update store lock (failed=%v err=%v)", failed, err) } if stopNow || failed == sqlLockLostCount { if sqlNoPanic { s.log.Fatalf("Aborting") return } panic("lost store lock, aborting") } } else { failed = 0 } case <-s.doneCh: ticker.Stop() return } } }
[ "func", "(", "s", "*", "SQLStore", ")", "updateDBLock", "(", ")", "{", "defer", "s", ".", "wg", ".", "Done", "(", ")", "\n", "var", "(", "ticker", "=", "time", ".", "NewTicker", "(", "sqlLockUpdateInterval", ")", "\n", "hasLock", "=", "true", "\n", "err", "error", "\n", "failed", "int", "\n", ")", "\n", "for", "{", "select", "{", "case", "<-", "ticker", ".", "C", ":", "hasLock", ",", "_", ",", "_", ",", "err", "=", "s", ".", "acquireDBLock", "(", "false", ")", "\n", "if", "!", "hasLock", "||", "err", "!=", "nil", "{", "stopNow", ":=", "!", "hasLock", "&&", "err", "==", "nil", "\n", "if", "err", "!=", "nil", "{", "failed", "++", "\n", "s", ".", "log", ".", "Errorf", "(", "\"Unable to update store lock (failed=%v err=%v)\"", ",", "failed", ",", "err", ")", "\n", "}", "\n", "if", "stopNow", "||", "failed", "==", "sqlLockLostCount", "{", "if", "sqlNoPanic", "{", "s", ".", "log", ".", "Fatalf", "(", "\"Aborting\"", ")", "\n", "return", "\n", "}", "\n", "panic", "(", "\"lost store lock, aborting\"", ")", "\n", "}", "\n", "}", "else", "{", "failed", "=", "0", "\n", "}", "\n", "case", "<-", "s", ".", "doneCh", ":", "ticker", ".", "Stop", "(", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "}" ]
// This go-routine updates the DB store lock at regular intervals.
[ "This", "go", "-", "routine", "updates", "the", "DB", "store", "lock", "at", "regular", "intervals", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/sqlstore.go#L478-L514
train
nats-io/nats-streaming-server
stores/sqlstore.go
acquireDBLock
func (s *SQLStore) acquireDBLock(steal bool) (bool, string, uint64, error) { s.dbLock.Lock() defer s.dbLock.Unlock() var ( lockID string tick uint64 hasLock bool ) tx, err := s.dbLock.db.Begin() if err != nil { return false, "", 0, err } defer func() { if tx != nil { tx.Rollback() } }() r := tx.QueryRow(sqlStmts[sqlDBLockSelect]) err = r.Scan(&lockID, &tick) if err != nil && err != sql.ErrNoRows { return false, "", 0, sqlStmtError(sqlDBLockSelect, err) } if err == sql.ErrNoRows || steal || lockID == "" || lockID == s.dbLock.id { // If we are stealing, reset tick to 0 (so it will become 1 in update statement) if steal { tick = 0 } stmt := sqlStmts[sqlDBLockUpdate] if err == sql.ErrNoRows { stmt = sqlStmts[sqlDBLockInsert] } if _, err := tx.Exec(stmt, s.dbLock.id, tick+1); err != nil { return false, "", 0, sqlStmtError(sqlDBLockUpdate, err) } hasLock = true } if err := tx.Commit(); err != nil { return false, "", 0, err } tx = nil return hasLock, lockID, tick, nil }
go
func (s *SQLStore) acquireDBLock(steal bool) (bool, string, uint64, error) { s.dbLock.Lock() defer s.dbLock.Unlock() var ( lockID string tick uint64 hasLock bool ) tx, err := s.dbLock.db.Begin() if err != nil { return false, "", 0, err } defer func() { if tx != nil { tx.Rollback() } }() r := tx.QueryRow(sqlStmts[sqlDBLockSelect]) err = r.Scan(&lockID, &tick) if err != nil && err != sql.ErrNoRows { return false, "", 0, sqlStmtError(sqlDBLockSelect, err) } if err == sql.ErrNoRows || steal || lockID == "" || lockID == s.dbLock.id { // If we are stealing, reset tick to 0 (so it will become 1 in update statement) if steal { tick = 0 } stmt := sqlStmts[sqlDBLockUpdate] if err == sql.ErrNoRows { stmt = sqlStmts[sqlDBLockInsert] } if _, err := tx.Exec(stmt, s.dbLock.id, tick+1); err != nil { return false, "", 0, sqlStmtError(sqlDBLockUpdate, err) } hasLock = true } if err := tx.Commit(); err != nil { return false, "", 0, err } tx = nil return hasLock, lockID, tick, nil }
[ "func", "(", "s", "*", "SQLStore", ")", "acquireDBLock", "(", "steal", "bool", ")", "(", "bool", ",", "string", ",", "uint64", ",", "error", ")", "{", "s", ".", "dbLock", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "dbLock", ".", "Unlock", "(", ")", "\n", "var", "(", "lockID", "string", "\n", "tick", "uint64", "\n", "hasLock", "bool", "\n", ")", "\n", "tx", ",", "err", ":=", "s", ".", "dbLock", ".", "db", ".", "Begin", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "\"\"", ",", "0", ",", "err", "\n", "}", "\n", "defer", "func", "(", ")", "{", "if", "tx", "!=", "nil", "{", "tx", ".", "Rollback", "(", ")", "\n", "}", "\n", "}", "(", ")", "\n", "r", ":=", "tx", ".", "QueryRow", "(", "sqlStmts", "[", "sqlDBLockSelect", "]", ")", "\n", "err", "=", "r", ".", "Scan", "(", "&", "lockID", ",", "&", "tick", ")", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "sql", ".", "ErrNoRows", "{", "return", "false", ",", "\"\"", ",", "0", ",", "sqlStmtError", "(", "sqlDBLockSelect", ",", "err", ")", "\n", "}", "\n", "if", "err", "==", "sql", ".", "ErrNoRows", "||", "steal", "||", "lockID", "==", "\"\"", "||", "lockID", "==", "s", ".", "dbLock", ".", "id", "{", "if", "steal", "{", "tick", "=", "0", "\n", "}", "\n", "stmt", ":=", "sqlStmts", "[", "sqlDBLockUpdate", "]", "\n", "if", "err", "==", "sql", ".", "ErrNoRows", "{", "stmt", "=", "sqlStmts", "[", "sqlDBLockInsert", "]", "\n", "}", "\n", "if", "_", ",", "err", ":=", "tx", ".", "Exec", "(", "stmt", ",", "s", ".", "dbLock", ".", "id", ",", "tick", "+", "1", ")", ";", "err", "!=", "nil", "{", "return", "false", ",", "\"\"", ",", "0", ",", "sqlStmtError", "(", "sqlDBLockUpdate", ",", "err", ")", "\n", "}", "\n", "hasLock", "=", "true", "\n", "}", "\n", "if", "err", ":=", "tx", ".", "Commit", "(", ")", ";", "err", "!=", "nil", "{", "return", "false", ",", "\"\"", ",", "0", ",", "err", "\n", "}", "\n", "tx", "=", "nil", "\n", "return", "hasLock", ",", "lockID", ",", "tick", ",", "nil", "\n", "}" ]
// Returns if lock is acquired, the owner and tick value of the lock record.
[ "Returns", "if", "lock", "is", "acquired", "the", "owner", "and", "tick", "value", "of", "the", "lock", "record", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/sqlstore.go#L517-L558
train
nats-io/nats-streaming-server
stores/sqlstore.go
releaseDBLockIfOwner
func (s *SQLStore) releaseDBLockIfOwner() { s.dbLock.Lock() defer s.dbLock.Unlock() if s.dbLock.isOwner { s.dbLock.db.Exec(sqlStmts[sqlDBLockUpdate], "", 0) } }
go
func (s *SQLStore) releaseDBLockIfOwner() { s.dbLock.Lock() defer s.dbLock.Unlock() if s.dbLock.isOwner { s.dbLock.db.Exec(sqlStmts[sqlDBLockUpdate], "", 0) } }
[ "func", "(", "s", "*", "SQLStore", ")", "releaseDBLockIfOwner", "(", ")", "{", "s", ".", "dbLock", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "dbLock", ".", "Unlock", "(", ")", "\n", "if", "s", ".", "dbLock", ".", "isOwner", "{", "s", ".", "dbLock", ".", "db", ".", "Exec", "(", "sqlStmts", "[", "sqlDBLockUpdate", "]", ",", "\"\"", ",", "0", ")", "\n", "}", "\n", "}" ]
// Release the store lock if this store was the owner of the lock
[ "Release", "the", "store", "lock", "if", "this", "store", "was", "the", "owner", "of", "the", "lock" ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/sqlstore.go#L561-L567
train
nats-io/nats-streaming-server
stores/sqlstore.go
scheduleSubStoreFlush
func (s *SQLStore) scheduleSubStoreFlush(ss *SQLSubStore) { needSignal := false f := s.ssFlusher f.Lock() f.stores[ss] = struct{}{} if !f.signaled { f.signaled = true needSignal = true } f.Unlock() if needSignal { select { case f.signalCh <- struct{}{}: default: } } }
go
func (s *SQLStore) scheduleSubStoreFlush(ss *SQLSubStore) { needSignal := false f := s.ssFlusher f.Lock() f.stores[ss] = struct{}{} if !f.signaled { f.signaled = true needSignal = true } f.Unlock() if needSignal { select { case f.signalCh <- struct{}{}: default: } } }
[ "func", "(", "s", "*", "SQLStore", ")", "scheduleSubStoreFlush", "(", "ss", "*", "SQLSubStore", ")", "{", "needSignal", ":=", "false", "\n", "f", ":=", "s", ".", "ssFlusher", "\n", "f", ".", "Lock", "(", ")", "\n", "f", ".", "stores", "[", "ss", "]", "=", "struct", "{", "}", "{", "}", "\n", "if", "!", "f", ".", "signaled", "{", "f", ".", "signaled", "=", "true", "\n", "needSignal", "=", "true", "\n", "}", "\n", "f", ".", "Unlock", "(", ")", "\n", "if", "needSignal", "{", "select", "{", "case", "f", ".", "signalCh", "<-", "struct", "{", "}", "{", "}", ":", "default", ":", "}", "\n", "}", "\n", "}" ]
// Add this store to the list of SubStore needing flushing // and signal the go-routine responsible for flushing if // need be.
[ "Add", "this", "store", "to", "the", "list", "of", "SubStore", "needing", "flushing", "and", "signal", "the", "go", "-", "routine", "responsible", "for", "flushing", "if", "need", "be", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/sqlstore.go#L617-L633
train
nats-io/nats-streaming-server
stores/sqlstore.go
newSQLMsgStore
func (s *SQLStore) newSQLMsgStore(channel string, channelID int64, limits *MsgStoreLimits) *SQLMsgStore { msgStore := &SQLMsgStore{ sqlStore: s, channelID: channelID, } msgStore.init(channel, s.log, limits) if !s.opts.NoCaching { msgStore.writeCache = &sqlMsgsCache{msgs: make(map[uint64]*sqlCachedMsg)} } return msgStore }
go
func (s *SQLStore) newSQLMsgStore(channel string, channelID int64, limits *MsgStoreLimits) *SQLMsgStore { msgStore := &SQLMsgStore{ sqlStore: s, channelID: channelID, } msgStore.init(channel, s.log, limits) if !s.opts.NoCaching { msgStore.writeCache = &sqlMsgsCache{msgs: make(map[uint64]*sqlCachedMsg)} } return msgStore }
[ "func", "(", "s", "*", "SQLStore", ")", "newSQLMsgStore", "(", "channel", "string", ",", "channelID", "int64", ",", "limits", "*", "MsgStoreLimits", ")", "*", "SQLMsgStore", "{", "msgStore", ":=", "&", "SQLMsgStore", "{", "sqlStore", ":", "s", ",", "channelID", ":", "channelID", ",", "}", "\n", "msgStore", ".", "init", "(", "channel", ",", "s", ".", "log", ",", "limits", ")", "\n", "if", "!", "s", ".", "opts", ".", "NoCaching", "{", "msgStore", ".", "writeCache", "=", "&", "sqlMsgsCache", "{", "msgs", ":", "make", "(", "map", "[", "uint64", "]", "*", "sqlCachedMsg", ")", "}", "\n", "}", "\n", "return", "msgStore", "\n", "}" ]
// creates an instance of a SQLMsgStore
[ "creates", "an", "instance", "of", "a", "SQLMsgStore" ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/sqlstore.go#L636-L646
train
nats-io/nats-streaming-server
stores/sqlstore.go
newSQLSubStore
func (s *SQLStore) newSQLSubStore(channelID int64, limits *SubStoreLimits) *SQLSubStore { subStore := &SQLSubStore{ sqlStore: s, channelID: channelID, maxSubID: &s.maxSubID, limits: *limits, } subStore.log = s.log if s.opts.NoCaching { subStore.subLastSent = make(map[uint64]uint64) } else { subStore.cache = &sqlSubAcksPendingCache{ subs: make(map[uint64]*sqlSubAcksPending), } } return subStore }
go
func (s *SQLStore) newSQLSubStore(channelID int64, limits *SubStoreLimits) *SQLSubStore { subStore := &SQLSubStore{ sqlStore: s, channelID: channelID, maxSubID: &s.maxSubID, limits: *limits, } subStore.log = s.log if s.opts.NoCaching { subStore.subLastSent = make(map[uint64]uint64) } else { subStore.cache = &sqlSubAcksPendingCache{ subs: make(map[uint64]*sqlSubAcksPending), } } return subStore }
[ "func", "(", "s", "*", "SQLStore", ")", "newSQLSubStore", "(", "channelID", "int64", ",", "limits", "*", "SubStoreLimits", ")", "*", "SQLSubStore", "{", "subStore", ":=", "&", "SQLSubStore", "{", "sqlStore", ":", "s", ",", "channelID", ":", "channelID", ",", "maxSubID", ":", "&", "s", ".", "maxSubID", ",", "limits", ":", "*", "limits", ",", "}", "\n", "subStore", ".", "log", "=", "s", ".", "log", "\n", "if", "s", ".", "opts", ".", "NoCaching", "{", "subStore", ".", "subLastSent", "=", "make", "(", "map", "[", "uint64", "]", "uint64", ")", "\n", "}", "else", "{", "subStore", ".", "cache", "=", "&", "sqlSubAcksPendingCache", "{", "subs", ":", "make", "(", "map", "[", "uint64", "]", "*", "sqlSubAcksPending", ")", ",", "}", "\n", "}", "\n", "return", "subStore", "\n", "}" ]
// creates an instance of SQLSubStore
[ "creates", "an", "instance", "of", "SQLSubStore" ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/sqlstore.go#L649-L665
train
nats-io/nats-streaming-server
stores/sqlstore.go
initSQLStmtsTable
func initSQLStmtsTable(driver string) { // The sqlStmts table is initialized with MySQL statements. // Update the statements for the selected driver. switch driver { case driverPostgres: // Replace ? with $1, $2, etc... for i, stmt := range sqlStmts { n := 0 for strings.IndexByte(stmt, '?') != -1 { n++ param := "$" + strconv.Itoa(n) stmt = strings.Replace(stmt, "?", param, 1) } sqlStmts[i] = stmt } // Replace `row` with row for i, stmt := range sqlStmts { stmt := strings.Replace(stmt, "`row`", "row", -1) sqlStmts[i] = stmt } // OVER (PARTITION ...) is not supported in older MySQL servers. // So the default SQL statement is specific to MySQL and uses variables. // For Postgres, replace with this statement: sqlStmts[sqlRecoverGetSeqFloorForMaxBytes] = "SELECT COALESCE(MIN(seq), 0) FROM (SELECT seq, SUM(size) OVER (PARTITION BY id ORDER BY seq DESC) AS total FROM Messages WHERE id=$1)t WHERE t.total<=$2" } }
go
func initSQLStmtsTable(driver string) { // The sqlStmts table is initialized with MySQL statements. // Update the statements for the selected driver. switch driver { case driverPostgres: // Replace ? with $1, $2, etc... for i, stmt := range sqlStmts { n := 0 for strings.IndexByte(stmt, '?') != -1 { n++ param := "$" + strconv.Itoa(n) stmt = strings.Replace(stmt, "?", param, 1) } sqlStmts[i] = stmt } // Replace `row` with row for i, stmt := range sqlStmts { stmt := strings.Replace(stmt, "`row`", "row", -1) sqlStmts[i] = stmt } // OVER (PARTITION ...) is not supported in older MySQL servers. // So the default SQL statement is specific to MySQL and uses variables. // For Postgres, replace with this statement: sqlStmts[sqlRecoverGetSeqFloorForMaxBytes] = "SELECT COALESCE(MIN(seq), 0) FROM (SELECT seq, SUM(size) OVER (PARTITION BY id ORDER BY seq DESC) AS total FROM Messages WHERE id=$1)t WHERE t.total<=$2" } }
[ "func", "initSQLStmtsTable", "(", "driver", "string", ")", "{", "switch", "driver", "{", "case", "driverPostgres", ":", "for", "i", ",", "stmt", ":=", "range", "sqlStmts", "{", "n", ":=", "0", "\n", "for", "strings", ".", "IndexByte", "(", "stmt", ",", "'?'", ")", "!=", "-", "1", "{", "n", "++", "\n", "param", ":=", "\"$\"", "+", "strconv", ".", "Itoa", "(", "n", ")", "\n", "stmt", "=", "strings", ".", "Replace", "(", "stmt", ",", "\"?\"", ",", "param", ",", "1", ")", "\n", "}", "\n", "sqlStmts", "[", "i", "]", "=", "stmt", "\n", "}", "\n", "for", "i", ",", "stmt", ":=", "range", "sqlStmts", "{", "stmt", ":=", "strings", ".", "Replace", "(", "stmt", ",", "\"`row`\"", ",", "\"row\"", ",", "-", "1", ")", "\n", "sqlStmts", "[", "i", "]", "=", "stmt", "\n", "}", "\n", "sqlStmts", "[", "sqlRecoverGetSeqFloorForMaxBytes", "]", "=", "\"SELECT COALESCE(MIN(seq), 0) FROM (SELECT seq, SUM(size) OVER (PARTITION BY id ORDER BY seq DESC) AS total FROM Messages WHERE id=$1)t WHERE t.total<=$2\"", "\n", "}", "\n", "}" ]
// initialize the global sqlStmts table to driver's one.
[ "initialize", "the", "global", "sqlStmts", "table", "to", "driver", "s", "one", "." ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/sqlstore.go#L680-L705
train
nats-io/nats-streaming-server
stores/sqlstore.go
Init
func (s *SQLStore) Init(info *spb.ServerInfo) error { s.Lock() defer s.Unlock() count := 0 r := s.db.QueryRow(sqlStmts[sqlHasServerInfoRow]) if err := r.Scan(&count); err != nil && err != sql.ErrNoRows { return sqlStmtError(sqlHasServerInfoRow, err) } infoBytes, _ := info.Marshal() if count == 0 { if _, err := s.db.Exec(sqlStmts[sqlAddServerInfo], info.ClusterID, infoBytes, sqlVersion); err != nil { return sqlStmtError(sqlAddServerInfo, err) } } else { if _, err := s.db.Exec(sqlStmts[sqlUpdateServerInfo], info.ClusterID, infoBytes, sqlVersion); err != nil { return sqlStmtError(sqlUpdateServerInfo, err) } } return nil }
go
func (s *SQLStore) Init(info *spb.ServerInfo) error { s.Lock() defer s.Unlock() count := 0 r := s.db.QueryRow(sqlStmts[sqlHasServerInfoRow]) if err := r.Scan(&count); err != nil && err != sql.ErrNoRows { return sqlStmtError(sqlHasServerInfoRow, err) } infoBytes, _ := info.Marshal() if count == 0 { if _, err := s.db.Exec(sqlStmts[sqlAddServerInfo], info.ClusterID, infoBytes, sqlVersion); err != nil { return sqlStmtError(sqlAddServerInfo, err) } } else { if _, err := s.db.Exec(sqlStmts[sqlUpdateServerInfo], info.ClusterID, infoBytes, sqlVersion); err != nil { return sqlStmtError(sqlUpdateServerInfo, err) } } return nil }
[ "func", "(", "s", "*", "SQLStore", ")", "Init", "(", "info", "*", "spb", ".", "ServerInfo", ")", "error", "{", "s", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "Unlock", "(", ")", "\n", "count", ":=", "0", "\n", "r", ":=", "s", ".", "db", ".", "QueryRow", "(", "sqlStmts", "[", "sqlHasServerInfoRow", "]", ")", "\n", "if", "err", ":=", "r", ".", "Scan", "(", "&", "count", ")", ";", "err", "!=", "nil", "&&", "err", "!=", "sql", ".", "ErrNoRows", "{", "return", "sqlStmtError", "(", "sqlHasServerInfoRow", ",", "err", ")", "\n", "}", "\n", "infoBytes", ",", "_", ":=", "info", ".", "Marshal", "(", ")", "\n", "if", "count", "==", "0", "{", "if", "_", ",", "err", ":=", "s", ".", "db", ".", "Exec", "(", "sqlStmts", "[", "sqlAddServerInfo", "]", ",", "info", ".", "ClusterID", ",", "infoBytes", ",", "sqlVersion", ")", ";", "err", "!=", "nil", "{", "return", "sqlStmtError", "(", "sqlAddServerInfo", ",", "err", ")", "\n", "}", "\n", "}", "else", "{", "if", "_", ",", "err", ":=", "s", ".", "db", ".", "Exec", "(", "sqlStmts", "[", "sqlUpdateServerInfo", "]", ",", "info", ".", "ClusterID", ",", "infoBytes", ",", "sqlVersion", ")", ";", "err", "!=", "nil", "{", "return", "sqlStmtError", "(", "sqlUpdateServerInfo", ",", "err", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Init implements the Store interface
[ "Init", "implements", "the", "Store", "interface" ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/sqlstore.go#L708-L727
train
nats-io/nats-streaming-server
stores/sqlstore.go
Close
func (s *SQLStore) Close() error { s.Lock() if s.closed { s.Unlock() return nil } s.closed = true // This will cause MsgStore's and SubStore's to be closed. err := s.close() db := s.db wg := &s.wg // Signal background go-routines to quit if s.doneCh != nil { close(s.doneCh) } s.Unlock() // Wait for go routine(s) to finish wg.Wait() s.Lock() for _, ps := range s.preparedStmts { if lerr := ps.Close(); lerr != nil && err == nil { err = lerr } } if db != nil { if s.dbLock != nil { s.releaseDBLockIfOwner() } if lerr := db.Close(); lerr != nil && err == nil { err = lerr } } s.Unlock() return err }
go
func (s *SQLStore) Close() error { s.Lock() if s.closed { s.Unlock() return nil } s.closed = true // This will cause MsgStore's and SubStore's to be closed. err := s.close() db := s.db wg := &s.wg // Signal background go-routines to quit if s.doneCh != nil { close(s.doneCh) } s.Unlock() // Wait for go routine(s) to finish wg.Wait() s.Lock() for _, ps := range s.preparedStmts { if lerr := ps.Close(); lerr != nil && err == nil { err = lerr } } if db != nil { if s.dbLock != nil { s.releaseDBLockIfOwner() } if lerr := db.Close(); lerr != nil && err == nil { err = lerr } } s.Unlock() return err }
[ "func", "(", "s", "*", "SQLStore", ")", "Close", "(", ")", "error", "{", "s", ".", "Lock", "(", ")", "\n", "if", "s", ".", "closed", "{", "s", ".", "Unlock", "(", ")", "\n", "return", "nil", "\n", "}", "\n", "s", ".", "closed", "=", "true", "\n", "err", ":=", "s", ".", "close", "(", ")", "\n", "db", ":=", "s", ".", "db", "\n", "wg", ":=", "&", "s", ".", "wg", "\n", "if", "s", ".", "doneCh", "!=", "nil", "{", "close", "(", "s", ".", "doneCh", ")", "\n", "}", "\n", "s", ".", "Unlock", "(", ")", "\n", "wg", ".", "Wait", "(", ")", "\n", "s", ".", "Lock", "(", ")", "\n", "for", "_", ",", "ps", ":=", "range", "s", ".", "preparedStmts", "{", "if", "lerr", ":=", "ps", ".", "Close", "(", ")", ";", "lerr", "!=", "nil", "&&", "err", "==", "nil", "{", "err", "=", "lerr", "\n", "}", "\n", "}", "\n", "if", "db", "!=", "nil", "{", "if", "s", ".", "dbLock", "!=", "nil", "{", "s", ".", "releaseDBLockIfOwner", "(", ")", "\n", "}", "\n", "if", "lerr", ":=", "db", ".", "Close", "(", ")", ";", "lerr", "!=", "nil", "&&", "err", "==", "nil", "{", "err", "=", "lerr", "\n", "}", "\n", "}", "\n", "s", ".", "Unlock", "(", ")", "\n", "return", "err", "\n", "}" ]
// Close implements the Store interface
[ "Close", "implements", "the", "Store", "interface" ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/sqlstore.go#L1272-L1308
train
nats-io/nats-streaming-server
stores/sqlstore.go
GetSequenceFromTimestamp
func (ms *SQLMsgStore) GetSequenceFromTimestamp(timestamp int64) (uint64, error) { ms.Lock() defer ms.Unlock() // No message ever stored if ms.first == 0 { return 0, nil } // All messages have expired if ms.first > ms.last { return ms.last + 1, nil } r := ms.sqlStore.preparedStmts[sqlGetSequenceFromTimestamp].QueryRow(ms.channelID, timestamp) seq := uint64(0) err := r.Scan(&seq) if err == sql.ErrNoRows { return ms.last + 1, nil } if err != nil { return 0, sqlStmtError(sqlGetSequenceFromTimestamp, err) } return seq, nil }
go
func (ms *SQLMsgStore) GetSequenceFromTimestamp(timestamp int64) (uint64, error) { ms.Lock() defer ms.Unlock() // No message ever stored if ms.first == 0 { return 0, nil } // All messages have expired if ms.first > ms.last { return ms.last + 1, nil } r := ms.sqlStore.preparedStmts[sqlGetSequenceFromTimestamp].QueryRow(ms.channelID, timestamp) seq := uint64(0) err := r.Scan(&seq) if err == sql.ErrNoRows { return ms.last + 1, nil } if err != nil { return 0, sqlStmtError(sqlGetSequenceFromTimestamp, err) } return seq, nil }
[ "func", "(", "ms", "*", "SQLMsgStore", ")", "GetSequenceFromTimestamp", "(", "timestamp", "int64", ")", "(", "uint64", ",", "error", ")", "{", "ms", ".", "Lock", "(", ")", "\n", "defer", "ms", ".", "Unlock", "(", ")", "\n", "if", "ms", ".", "first", "==", "0", "{", "return", "0", ",", "nil", "\n", "}", "\n", "if", "ms", ".", "first", ">", "ms", ".", "last", "{", "return", "ms", ".", "last", "+", "1", ",", "nil", "\n", "}", "\n", "r", ":=", "ms", ".", "sqlStore", ".", "preparedStmts", "[", "sqlGetSequenceFromTimestamp", "]", ".", "QueryRow", "(", "ms", ".", "channelID", ",", "timestamp", ")", "\n", "seq", ":=", "uint64", "(", "0", ")", "\n", "err", ":=", "r", ".", "Scan", "(", "&", "seq", ")", "\n", "if", "err", "==", "sql", ".", "ErrNoRows", "{", "return", "ms", ".", "last", "+", "1", ",", "nil", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "sqlStmtError", "(", "sqlGetSequenceFromTimestamp", ",", "err", ")", "\n", "}", "\n", "return", "seq", ",", "nil", "\n", "}" ]
// GetSequenceFromTimestamp implements the MsgStore interface
[ "GetSequenceFromTimestamp", "implements", "the", "MsgStore", "interface" ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/sqlstore.go#L1481-L1502
train
nats-io/nats-streaming-server
stores/sqlstore.go
LastMsg
func (ms *SQLMsgStore) LastMsg() (*pb.MsgProto, error) { ms.Lock() msg, err := ms.lookup(ms.last) ms.Unlock() return msg, err }
go
func (ms *SQLMsgStore) LastMsg() (*pb.MsgProto, error) { ms.Lock() msg, err := ms.lookup(ms.last) ms.Unlock() return msg, err }
[ "func", "(", "ms", "*", "SQLMsgStore", ")", "LastMsg", "(", ")", "(", "*", "pb", ".", "MsgProto", ",", "error", ")", "{", "ms", ".", "Lock", "(", ")", "\n", "msg", ",", "err", ":=", "ms", ".", "lookup", "(", "ms", ".", "last", ")", "\n", "ms", ".", "Unlock", "(", ")", "\n", "return", "msg", ",", "err", "\n", "}" ]
// LastMsg implements the MsgStore interface
[ "LastMsg", "implements", "the", "MsgStore", "interface" ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/sqlstore.go#L1513-L1518
train
nats-io/nats-streaming-server
stores/sqlstore.go
expireMsgs
func (ms *SQLMsgStore) expireMsgs() { ms.Lock() defer ms.Unlock() if ms.closed { ms.wg.Done() return } var ( count int maxSeq uint64 totalSize uint64 timestamp int64 ) processErr := func(errCode int, err error) { ms.log.Errorf("Unable to perform expiration for channel %q: %v", ms.subject, sqlStmtError(errCode, err)) ms.expireTimer.Reset(sqlExpirationIntervalOnError) } for { expiredTimestamp := time.Now().UnixNano() - int64(ms.limits.MaxAge) r := ms.sqlStore.preparedStmts[sqlGetExpiredMessages].QueryRow(ms.channelID, expiredTimestamp) if err := r.Scan(&count, &maxSeq, &totalSize); err != nil { processErr(sqlGetExpiredMessages, err) return } // It could be that messages that should have expired have been // removed due to count/size limit. We still need to adjust the // expiration timer based on the first message that need to expire. if count > 0 { if maxSeq == ms.last { if _, err := ms.sqlStore.preparedStmts[sqlUpdateChannelMaxSeq].Exec(maxSeq, ms.channelID); err != nil { processErr(sqlUpdateChannelMaxSeq, err) return } } if _, err := ms.sqlStore.preparedStmts[sqlDeletedMsgsWithSeqLowerThan].Exec(ms.channelID, maxSeq); err != nil { processErr(sqlDeletedMsgsWithSeqLowerThan, err) return } ms.first = maxSeq + 1 ms.totalCount -= count ms.totalBytes -= totalSize } // Reset since we are in a loop timestamp = 0 // If there is any message left in the channel, find out what the expiration // timer needs to be set to. if ms.totalCount > 0 { r = ms.sqlStore.preparedStmts[sqlGetFirstMsgTimestamp].QueryRow(ms.channelID, ms.first) if err := r.Scan(&timestamp); err != nil { processErr(sqlGetFirstMsgTimestamp, err) return } } // No message left or no message to expire. The timer will be recreated when // a new message is added to the channel. if timestamp == 0 { ms.wg.Done() ms.expireTimer = nil return } elapsed := time.Duration(time.Now().UnixNano() - timestamp) if elapsed < ms.limits.MaxAge { ms.expireTimer.Reset(ms.limits.MaxAge - elapsed) // Done with the for loop return } } }
go
func (ms *SQLMsgStore) expireMsgs() { ms.Lock() defer ms.Unlock() if ms.closed { ms.wg.Done() return } var ( count int maxSeq uint64 totalSize uint64 timestamp int64 ) processErr := func(errCode int, err error) { ms.log.Errorf("Unable to perform expiration for channel %q: %v", ms.subject, sqlStmtError(errCode, err)) ms.expireTimer.Reset(sqlExpirationIntervalOnError) } for { expiredTimestamp := time.Now().UnixNano() - int64(ms.limits.MaxAge) r := ms.sqlStore.preparedStmts[sqlGetExpiredMessages].QueryRow(ms.channelID, expiredTimestamp) if err := r.Scan(&count, &maxSeq, &totalSize); err != nil { processErr(sqlGetExpiredMessages, err) return } // It could be that messages that should have expired have been // removed due to count/size limit. We still need to adjust the // expiration timer based on the first message that need to expire. if count > 0 { if maxSeq == ms.last { if _, err := ms.sqlStore.preparedStmts[sqlUpdateChannelMaxSeq].Exec(maxSeq, ms.channelID); err != nil { processErr(sqlUpdateChannelMaxSeq, err) return } } if _, err := ms.sqlStore.preparedStmts[sqlDeletedMsgsWithSeqLowerThan].Exec(ms.channelID, maxSeq); err != nil { processErr(sqlDeletedMsgsWithSeqLowerThan, err) return } ms.first = maxSeq + 1 ms.totalCount -= count ms.totalBytes -= totalSize } // Reset since we are in a loop timestamp = 0 // If there is any message left in the channel, find out what the expiration // timer needs to be set to. if ms.totalCount > 0 { r = ms.sqlStore.preparedStmts[sqlGetFirstMsgTimestamp].QueryRow(ms.channelID, ms.first) if err := r.Scan(&timestamp); err != nil { processErr(sqlGetFirstMsgTimestamp, err) return } } // No message left or no message to expire. The timer will be recreated when // a new message is added to the channel. if timestamp == 0 { ms.wg.Done() ms.expireTimer = nil return } elapsed := time.Duration(time.Now().UnixNano() - timestamp) if elapsed < ms.limits.MaxAge { ms.expireTimer.Reset(ms.limits.MaxAge - elapsed) // Done with the for loop return } } }
[ "func", "(", "ms", "*", "SQLMsgStore", ")", "expireMsgs", "(", ")", "{", "ms", ".", "Lock", "(", ")", "\n", "defer", "ms", ".", "Unlock", "(", ")", "\n", "if", "ms", ".", "closed", "{", "ms", ".", "wg", ".", "Done", "(", ")", "\n", "return", "\n", "}", "\n", "var", "(", "count", "int", "\n", "maxSeq", "uint64", "\n", "totalSize", "uint64", "\n", "timestamp", "int64", "\n", ")", "\n", "processErr", ":=", "func", "(", "errCode", "int", ",", "err", "error", ")", "{", "ms", ".", "log", ".", "Errorf", "(", "\"Unable to perform expiration for channel %q: %v\"", ",", "ms", ".", "subject", ",", "sqlStmtError", "(", "errCode", ",", "err", ")", ")", "\n", "ms", ".", "expireTimer", ".", "Reset", "(", "sqlExpirationIntervalOnError", ")", "\n", "}", "\n", "for", "{", "expiredTimestamp", ":=", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", "-", "int64", "(", "ms", ".", "limits", ".", "MaxAge", ")", "\n", "r", ":=", "ms", ".", "sqlStore", ".", "preparedStmts", "[", "sqlGetExpiredMessages", "]", ".", "QueryRow", "(", "ms", ".", "channelID", ",", "expiredTimestamp", ")", "\n", "if", "err", ":=", "r", ".", "Scan", "(", "&", "count", ",", "&", "maxSeq", ",", "&", "totalSize", ")", ";", "err", "!=", "nil", "{", "processErr", "(", "sqlGetExpiredMessages", ",", "err", ")", "\n", "return", "\n", "}", "\n", "if", "count", ">", "0", "{", "if", "maxSeq", "==", "ms", ".", "last", "{", "if", "_", ",", "err", ":=", "ms", ".", "sqlStore", ".", "preparedStmts", "[", "sqlUpdateChannelMaxSeq", "]", ".", "Exec", "(", "maxSeq", ",", "ms", ".", "channelID", ")", ";", "err", "!=", "nil", "{", "processErr", "(", "sqlUpdateChannelMaxSeq", ",", "err", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "if", "_", ",", "err", ":=", "ms", ".", "sqlStore", ".", "preparedStmts", "[", "sqlDeletedMsgsWithSeqLowerThan", "]", ".", "Exec", "(", "ms", ".", "channelID", ",", "maxSeq", ")", ";", "err", "!=", "nil", "{", "processErr", "(", "sqlDeletedMsgsWithSeqLowerThan", ",", "err", ")", "\n", "return", "\n", "}", "\n", "ms", ".", "first", "=", "maxSeq", "+", "1", "\n", "ms", ".", "totalCount", "-=", "count", "\n", "ms", ".", "totalBytes", "-=", "totalSize", "\n", "}", "\n", "timestamp", "=", "0", "\n", "if", "ms", ".", "totalCount", ">", "0", "{", "r", "=", "ms", ".", "sqlStore", ".", "preparedStmts", "[", "sqlGetFirstMsgTimestamp", "]", ".", "QueryRow", "(", "ms", ".", "channelID", ",", "ms", ".", "first", ")", "\n", "if", "err", ":=", "r", ".", "Scan", "(", "&", "timestamp", ")", ";", "err", "!=", "nil", "{", "processErr", "(", "sqlGetFirstMsgTimestamp", ",", "err", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "if", "timestamp", "==", "0", "{", "ms", ".", "wg", ".", "Done", "(", ")", "\n", "ms", ".", "expireTimer", "=", "nil", "\n", "return", "\n", "}", "\n", "elapsed", ":=", "time", ".", "Duration", "(", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", "-", "timestamp", ")", "\n", "if", "elapsed", "<", "ms", ".", "limits", ".", "MaxAge", "{", "ms", ".", "expireTimer", ".", "Reset", "(", "ms", ".", "limits", ".", "MaxAge", "-", "elapsed", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "}" ]
// expireMsgsLocked removes all messages that have expired in this channel. // Store lock is assumed held on entry
[ "expireMsgsLocked", "removes", "all", "messages", "that", "have", "expired", "in", "this", "channel", ".", "Store", "lock", "is", "assumed", "held", "on", "entry" ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/sqlstore.go#L1522-L1591
train
nats-io/nats-streaming-server
stores/sqlstore.go
Flush
func (ms *SQLMsgStore) Flush() error { ms.Lock() err := ms.flush() ms.Unlock() return err }
go
func (ms *SQLMsgStore) Flush() error { ms.Lock() err := ms.flush() ms.Unlock() return err }
[ "func", "(", "ms", "*", "SQLMsgStore", ")", "Flush", "(", ")", "error", "{", "ms", ".", "Lock", "(", ")", "\n", "err", ":=", "ms", ".", "flush", "(", ")", "\n", "ms", ".", "Unlock", "(", ")", "\n", "return", "err", "\n", "}" ]
// Flush implements the MsgStore interface
[ "Flush", "implements", "the", "MsgStore", "interface" ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/sqlstore.go#L1674-L1679
train
nats-io/nats-streaming-server
stores/sqlstore.go
UpdateSub
func (ss *SQLSubStore) UpdateSub(sub *spb.SubState) error { ss.Lock() defer ss.Unlock() subBytes, _ := sub.Marshal() r, err := ss.sqlStore.preparedStmts[sqlUpdateSub].Exec(subBytes, ss.channelID, sub.ID) if err != nil { return sqlStmtError(sqlUpdateSub, err) } // FileSubStoe supports updating a subscription for which there was no CreateSub. // Not sure if this is necessary, since I think server would never do that. // Stay consistent. c, err := r.RowsAffected() if err != nil { return err } if c == 0 { if _, err := ss.sqlStore.preparedStmts[sqlCreateSub].Exec(ss.channelID, sub.ID, subBytes); err != nil { return sqlStmtError(sqlCreateSub, err) } } return nil }
go
func (ss *SQLSubStore) UpdateSub(sub *spb.SubState) error { ss.Lock() defer ss.Unlock() subBytes, _ := sub.Marshal() r, err := ss.sqlStore.preparedStmts[sqlUpdateSub].Exec(subBytes, ss.channelID, sub.ID) if err != nil { return sqlStmtError(sqlUpdateSub, err) } // FileSubStoe supports updating a subscription for which there was no CreateSub. // Not sure if this is necessary, since I think server would never do that. // Stay consistent. c, err := r.RowsAffected() if err != nil { return err } if c == 0 { if _, err := ss.sqlStore.preparedStmts[sqlCreateSub].Exec(ss.channelID, sub.ID, subBytes); err != nil { return sqlStmtError(sqlCreateSub, err) } } return nil }
[ "func", "(", "ss", "*", "SQLSubStore", ")", "UpdateSub", "(", "sub", "*", "spb", ".", "SubState", ")", "error", "{", "ss", ".", "Lock", "(", ")", "\n", "defer", "ss", ".", "Unlock", "(", ")", "\n", "subBytes", ",", "_", ":=", "sub", ".", "Marshal", "(", ")", "\n", "r", ",", "err", ":=", "ss", ".", "sqlStore", ".", "preparedStmts", "[", "sqlUpdateSub", "]", ".", "Exec", "(", "subBytes", ",", "ss", ".", "channelID", ",", "sub", ".", "ID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "sqlStmtError", "(", "sqlUpdateSub", ",", "err", ")", "\n", "}", "\n", "c", ",", "err", ":=", "r", ".", "RowsAffected", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "c", "==", "0", "{", "if", "_", ",", "err", ":=", "ss", ".", "sqlStore", ".", "preparedStmts", "[", "sqlCreateSub", "]", ".", "Exec", "(", "ss", ".", "channelID", ",", "sub", ".", "ID", ",", "subBytes", ")", ";", "err", "!=", "nil", "{", "return", "sqlStmtError", "(", "sqlCreateSub", ",", "err", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// UpdateSub implements the SubStore interface
[ "UpdateSub", "implements", "the", "SubStore", "interface" ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/sqlstore.go#L1737-L1758
train
nats-io/nats-streaming-server
stores/sqlstore.go
DeleteSub
func (ss *SQLSubStore) DeleteSub(subid uint64) error { ss.Lock() defer ss.Unlock() if subid == atomic.LoadUint64(ss.maxSubID) { if _, err := ss.sqlStore.preparedStmts[sqlMarkSubscriptionAsDeleted].Exec(ss.channelID, subid); err != nil { return sqlStmtError(sqlMarkSubscriptionAsDeleted, err) } ss.hasMarkedAsDel = true } else { if _, err := ss.sqlStore.preparedStmts[sqlDeleteSubscription].Exec(ss.channelID, subid); err != nil { return sqlStmtError(sqlDeleteSubscription, err) } } if ss.cache != nil { delete(ss.cache.subs, subid) } else { delete(ss.subLastSent, subid) } // Ignore error on this since subscription would not be recovered // if above executed ok. ss.sqlStore.preparedStmts[sqlDeleteSubPendingMessages].Exec(subid) return nil }
go
func (ss *SQLSubStore) DeleteSub(subid uint64) error { ss.Lock() defer ss.Unlock() if subid == atomic.LoadUint64(ss.maxSubID) { if _, err := ss.sqlStore.preparedStmts[sqlMarkSubscriptionAsDeleted].Exec(ss.channelID, subid); err != nil { return sqlStmtError(sqlMarkSubscriptionAsDeleted, err) } ss.hasMarkedAsDel = true } else { if _, err := ss.sqlStore.preparedStmts[sqlDeleteSubscription].Exec(ss.channelID, subid); err != nil { return sqlStmtError(sqlDeleteSubscription, err) } } if ss.cache != nil { delete(ss.cache.subs, subid) } else { delete(ss.subLastSent, subid) } // Ignore error on this since subscription would not be recovered // if above executed ok. ss.sqlStore.preparedStmts[sqlDeleteSubPendingMessages].Exec(subid) return nil }
[ "func", "(", "ss", "*", "SQLSubStore", ")", "DeleteSub", "(", "subid", "uint64", ")", "error", "{", "ss", ".", "Lock", "(", ")", "\n", "defer", "ss", ".", "Unlock", "(", ")", "\n", "if", "subid", "==", "atomic", ".", "LoadUint64", "(", "ss", ".", "maxSubID", ")", "{", "if", "_", ",", "err", ":=", "ss", ".", "sqlStore", ".", "preparedStmts", "[", "sqlMarkSubscriptionAsDeleted", "]", ".", "Exec", "(", "ss", ".", "channelID", ",", "subid", ")", ";", "err", "!=", "nil", "{", "return", "sqlStmtError", "(", "sqlMarkSubscriptionAsDeleted", ",", "err", ")", "\n", "}", "\n", "ss", ".", "hasMarkedAsDel", "=", "true", "\n", "}", "else", "{", "if", "_", ",", "err", ":=", "ss", ".", "sqlStore", ".", "preparedStmts", "[", "sqlDeleteSubscription", "]", ".", "Exec", "(", "ss", ".", "channelID", ",", "subid", ")", ";", "err", "!=", "nil", "{", "return", "sqlStmtError", "(", "sqlDeleteSubscription", ",", "err", ")", "\n", "}", "\n", "}", "\n", "if", "ss", ".", "cache", "!=", "nil", "{", "delete", "(", "ss", ".", "cache", ".", "subs", ",", "subid", ")", "\n", "}", "else", "{", "delete", "(", "ss", ".", "subLastSent", ",", "subid", ")", "\n", "}", "\n", "ss", ".", "sqlStore", ".", "preparedStmts", "[", "sqlDeleteSubPendingMessages", "]", ".", "Exec", "(", "subid", ")", "\n", "return", "nil", "\n", "}" ]
// DeleteSub implements the SubStore interface
[ "DeleteSub", "implements", "the", "SubStore", "interface" ]
57c6c84265c0012a1efef365703c221329804d4c
https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/sqlstore.go#L1761-L1783
train