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 | stores/sqlstore.go | getOrCreateAcksPending | func (ss *SQLSubStore) getOrCreateAcksPending(subid, seqno uint64) *sqlSubAcksPending {
if !ss.cache.needsFlush {
ss.cache.needsFlush = true
ss.sqlStore.scheduleSubStoreFlush(ss)
}
ap := ss.cache.subs[subid]
if ap == nil {
ap = &sqlSubAcksPending{
msgToRow: make(map[uint64]*sqlSubsPendingRow),
ackToRow: make(map[uint64]*sqlSubsPendingRow),
msgs: make(map[uint64]struct{}),
acks: make(map[uint64]struct{}),
}
ss.cache.subs[subid] = ap
}
if seqno > ap.lastSent {
ap.lastSent = seqno
}
return ap
} | go | func (ss *SQLSubStore) getOrCreateAcksPending(subid, seqno uint64) *sqlSubAcksPending {
if !ss.cache.needsFlush {
ss.cache.needsFlush = true
ss.sqlStore.scheduleSubStoreFlush(ss)
}
ap := ss.cache.subs[subid]
if ap == nil {
ap = &sqlSubAcksPending{
msgToRow: make(map[uint64]*sqlSubsPendingRow),
ackToRow: make(map[uint64]*sqlSubsPendingRow),
msgs: make(map[uint64]struct{}),
acks: make(map[uint64]struct{}),
}
ss.cache.subs[subid] = ap
}
if seqno > ap.lastSent {
ap.lastSent = seqno
}
return ap
} | [
"func",
"(",
"ss",
"*",
"SQLSubStore",
")",
"getOrCreateAcksPending",
"(",
"subid",
",",
"seqno",
"uint64",
")",
"*",
"sqlSubAcksPending",
"{",
"if",
"!",
"ss",
".",
"cache",
".",
"needsFlush",
"{",
"ss",
".",
"cache",
".",
"needsFlush",
"=",
"true",
"\n",
"ss",
".",
"sqlStore",
".",
"scheduleSubStoreFlush",
"(",
"ss",
")",
"\n",
"}",
"\n",
"ap",
":=",
"ss",
".",
"cache",
".",
"subs",
"[",
"subid",
"]",
"\n",
"if",
"ap",
"==",
"nil",
"{",
"ap",
"=",
"&",
"sqlSubAcksPending",
"{",
"msgToRow",
":",
"make",
"(",
"map",
"[",
"uint64",
"]",
"*",
"sqlSubsPendingRow",
")",
",",
"ackToRow",
":",
"make",
"(",
"map",
"[",
"uint64",
"]",
"*",
"sqlSubsPendingRow",
")",
",",
"msgs",
":",
"make",
"(",
"map",
"[",
"uint64",
"]",
"struct",
"{",
"}",
")",
",",
"acks",
":",
"make",
"(",
"map",
"[",
"uint64",
"]",
"struct",
"{",
"}",
")",
",",
"}",
"\n",
"ss",
".",
"cache",
".",
"subs",
"[",
"subid",
"]",
"=",
"ap",
"\n",
"}",
"\n",
"if",
"seqno",
">",
"ap",
".",
"lastSent",
"{",
"ap",
".",
"lastSent",
"=",
"seqno",
"\n",
"}",
"\n",
"return",
"ap",
"\n",
"}"
] | // This returns the structure responsible to keep track of
// pending messages and acks for a given subscription ID. | [
"This",
"returns",
"the",
"structure",
"responsible",
"to",
"keep",
"track",
"of",
"pending",
"messages",
"and",
"acks",
"for",
"a",
"given",
"subscription",
"ID",
"."
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/sqlstore.go#L1787-L1806 | train |
nats-io/nats-streaming-server | stores/sqlstore.go | addSeq | func (ss *SQLSubStore) addSeq(subid, seqno uint64) bool {
ap := ss.getOrCreateAcksPending(subid, seqno)
ap.msgs[seqno] = struct{}{}
return len(ap.msgs) >= sqlMaxPendingAcks
} | go | func (ss *SQLSubStore) addSeq(subid, seqno uint64) bool {
ap := ss.getOrCreateAcksPending(subid, seqno)
ap.msgs[seqno] = struct{}{}
return len(ap.msgs) >= sqlMaxPendingAcks
} | [
"func",
"(",
"ss",
"*",
"SQLSubStore",
")",
"addSeq",
"(",
"subid",
",",
"seqno",
"uint64",
")",
"bool",
"{",
"ap",
":=",
"ss",
".",
"getOrCreateAcksPending",
"(",
"subid",
",",
"seqno",
")",
"\n",
"ap",
".",
"msgs",
"[",
"seqno",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"return",
"len",
"(",
"ap",
".",
"msgs",
")",
">=",
"sqlMaxPendingAcks",
"\n",
"}"
] | // Adds the given sequence to the list of pending messages.
// Returns true if the number of pending messages has
// reached a certain threshold, indicating that the
// store should be flushed. | [
"Adds",
"the",
"given",
"sequence",
"to",
"the",
"list",
"of",
"pending",
"messages",
".",
"Returns",
"true",
"if",
"the",
"number",
"of",
"pending",
"messages",
"has",
"reached",
"a",
"certain",
"threshold",
"indicating",
"that",
"the",
"store",
"should",
"be",
"flushed",
"."
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/sqlstore.go#L1812-L1816 | train |
nats-io/nats-streaming-server | stores/sqlstore.go | ackSeq | func (ss *SQLSubStore) ackSeq(subid, seqno uint64) (bool, error) {
ap := ss.getOrCreateAcksPending(subid, seqno)
// If still in cache and not persisted into a row,
// then simply remove from map and do not persist the ack.
if _, exists := ap.msgs[seqno]; exists {
delete(ap.msgs, seqno)
} else if row := ap.msgToRow[seqno]; row != nil {
ap.acks[seqno] = struct{}{}
// This is an ack for a pending msg that was persisted
// in a row. Update the row's msgRef count.
delete(ap.msgToRow, seqno)
row.msgsRefs--
// If all pending messages in that row have been ack'ed
if row.msgsRefs == 0 {
// and if all acks on that row are no longer needed
// (or there was none)
if row.acksRefs == 0 {
// then this row can be deleted.
if err := ss.deleteSubPendingRow(subid, row.ID); err != nil {
return false, err
}
// If there is no error, we don't even need
// to persist this ack.
delete(ap.acks, seqno)
}
// Since there is no pending message left in this
// row, let's find all the corresponding acks' rows
// for these sequences and update their acksRefs
for seq := range row.msgs {
delete(row.msgs, seq)
ackRow := ap.ackToRow[seq]
if ackRow != nil {
// We found the row for the ack of this sequence,
// remove from map and update reference count.
// delete(ap.ackToRow, seq)
ackRow.acksRefs--
// If all acks for that row are no longer needed and
// that row has also no pending messages, then ok to
// delete.
if ackRow.acksRefs == 0 && ackRow.msgsRefs == 0 {
if err := ss.deleteSubPendingRow(subid, ackRow.ID); err != nil {
return false, err
}
}
} else {
// That means the ack is in current cache so we won't
// need to persist it.
delete(ap.acks, seq)
}
}
sqlSeqMapPool.Put(row.msgs)
row.msgs = nil
}
}
return len(ap.acks) >= sqlMaxPendingAcks, nil
} | go | func (ss *SQLSubStore) ackSeq(subid, seqno uint64) (bool, error) {
ap := ss.getOrCreateAcksPending(subid, seqno)
// If still in cache and not persisted into a row,
// then simply remove from map and do not persist the ack.
if _, exists := ap.msgs[seqno]; exists {
delete(ap.msgs, seqno)
} else if row := ap.msgToRow[seqno]; row != nil {
ap.acks[seqno] = struct{}{}
// This is an ack for a pending msg that was persisted
// in a row. Update the row's msgRef count.
delete(ap.msgToRow, seqno)
row.msgsRefs--
// If all pending messages in that row have been ack'ed
if row.msgsRefs == 0 {
// and if all acks on that row are no longer needed
// (or there was none)
if row.acksRefs == 0 {
// then this row can be deleted.
if err := ss.deleteSubPendingRow(subid, row.ID); err != nil {
return false, err
}
// If there is no error, we don't even need
// to persist this ack.
delete(ap.acks, seqno)
}
// Since there is no pending message left in this
// row, let's find all the corresponding acks' rows
// for these sequences and update their acksRefs
for seq := range row.msgs {
delete(row.msgs, seq)
ackRow := ap.ackToRow[seq]
if ackRow != nil {
// We found the row for the ack of this sequence,
// remove from map and update reference count.
// delete(ap.ackToRow, seq)
ackRow.acksRefs--
// If all acks for that row are no longer needed and
// that row has also no pending messages, then ok to
// delete.
if ackRow.acksRefs == 0 && ackRow.msgsRefs == 0 {
if err := ss.deleteSubPendingRow(subid, ackRow.ID); err != nil {
return false, err
}
}
} else {
// That means the ack is in current cache so we won't
// need to persist it.
delete(ap.acks, seq)
}
}
sqlSeqMapPool.Put(row.msgs)
row.msgs = nil
}
}
return len(ap.acks) >= sqlMaxPendingAcks, nil
} | [
"func",
"(",
"ss",
"*",
"SQLSubStore",
")",
"ackSeq",
"(",
"subid",
",",
"seqno",
"uint64",
")",
"(",
"bool",
",",
"error",
")",
"{",
"ap",
":=",
"ss",
".",
"getOrCreateAcksPending",
"(",
"subid",
",",
"seqno",
")",
"\n",
"if",
"_",
",",
"exists",
":=",
"ap",
".",
"msgs",
"[",
"seqno",
"]",
";",
"exists",
"{",
"delete",
"(",
"ap",
".",
"msgs",
",",
"seqno",
")",
"\n",
"}",
"else",
"if",
"row",
":=",
"ap",
".",
"msgToRow",
"[",
"seqno",
"]",
";",
"row",
"!=",
"nil",
"{",
"ap",
".",
"acks",
"[",
"seqno",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"delete",
"(",
"ap",
".",
"msgToRow",
",",
"seqno",
")",
"\n",
"row",
".",
"msgsRefs",
"--",
"\n",
"if",
"row",
".",
"msgsRefs",
"==",
"0",
"{",
"if",
"row",
".",
"acksRefs",
"==",
"0",
"{",
"if",
"err",
":=",
"ss",
".",
"deleteSubPendingRow",
"(",
"subid",
",",
"row",
".",
"ID",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"delete",
"(",
"ap",
".",
"acks",
",",
"seqno",
")",
"\n",
"}",
"\n",
"for",
"seq",
":=",
"range",
"row",
".",
"msgs",
"{",
"delete",
"(",
"row",
".",
"msgs",
",",
"seq",
")",
"\n",
"ackRow",
":=",
"ap",
".",
"ackToRow",
"[",
"seq",
"]",
"\n",
"if",
"ackRow",
"!=",
"nil",
"{",
"ackRow",
".",
"acksRefs",
"--",
"\n",
"if",
"ackRow",
".",
"acksRefs",
"==",
"0",
"&&",
"ackRow",
".",
"msgsRefs",
"==",
"0",
"{",
"if",
"err",
":=",
"ss",
".",
"deleteSubPendingRow",
"(",
"subid",
",",
"ackRow",
".",
"ID",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"else",
"{",
"delete",
"(",
"ap",
".",
"acks",
",",
"seq",
")",
"\n",
"}",
"\n",
"}",
"\n",
"sqlSeqMapPool",
".",
"Put",
"(",
"row",
".",
"msgs",
")",
"\n",
"row",
".",
"msgs",
"=",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"len",
"(",
"ap",
".",
"acks",
")",
">=",
"sqlMaxPendingAcks",
",",
"nil",
"\n",
"}"
] | // Adds the given sequence to the list of acks and possibly
// delete rows that have all their pending messages acknowledged.
// Returns true if the number of acks has reached a certain threshold,
// indicating that the store should be flushed. | [
"Adds",
"the",
"given",
"sequence",
"to",
"the",
"list",
"of",
"acks",
"and",
"possibly",
"delete",
"rows",
"that",
"have",
"all",
"their",
"pending",
"messages",
"acknowledged",
".",
"Returns",
"true",
"if",
"the",
"number",
"of",
"acks",
"has",
"reached",
"a",
"certain",
"threshold",
"indicating",
"that",
"the",
"store",
"should",
"be",
"flushed",
"."
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/sqlstore.go#L1822-L1877 | train |
nats-io/nats-streaming-server | stores/sqlstore.go | AddSeqPending | func (ss *SQLSubStore) AddSeqPending(subid, seqno uint64) error {
var err error
ss.Lock()
if !ss.closed {
if ss.cache != nil {
if isFull := ss.addSeq(subid, seqno); isFull {
err = ss.flush()
}
} else {
ls := ss.subLastSent[subid]
if seqno > ls {
ss.subLastSent[subid] = seqno
}
ss.curRow++
_, err = ss.sqlStore.preparedStmts[sqlSubAddPending].Exec(subid, ss.curRow, seqno)
if err != nil {
err = sqlStmtError(sqlSubAddPending, err)
}
}
}
ss.Unlock()
return err
} | go | func (ss *SQLSubStore) AddSeqPending(subid, seqno uint64) error {
var err error
ss.Lock()
if !ss.closed {
if ss.cache != nil {
if isFull := ss.addSeq(subid, seqno); isFull {
err = ss.flush()
}
} else {
ls := ss.subLastSent[subid]
if seqno > ls {
ss.subLastSent[subid] = seqno
}
ss.curRow++
_, err = ss.sqlStore.preparedStmts[sqlSubAddPending].Exec(subid, ss.curRow, seqno)
if err != nil {
err = sqlStmtError(sqlSubAddPending, err)
}
}
}
ss.Unlock()
return err
} | [
"func",
"(",
"ss",
"*",
"SQLSubStore",
")",
"AddSeqPending",
"(",
"subid",
",",
"seqno",
"uint64",
")",
"error",
"{",
"var",
"err",
"error",
"\n",
"ss",
".",
"Lock",
"(",
")",
"\n",
"if",
"!",
"ss",
".",
"closed",
"{",
"if",
"ss",
".",
"cache",
"!=",
"nil",
"{",
"if",
"isFull",
":=",
"ss",
".",
"addSeq",
"(",
"subid",
",",
"seqno",
")",
";",
"isFull",
"{",
"err",
"=",
"ss",
".",
"flush",
"(",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"ls",
":=",
"ss",
".",
"subLastSent",
"[",
"subid",
"]",
"\n",
"if",
"seqno",
">",
"ls",
"{",
"ss",
".",
"subLastSent",
"[",
"subid",
"]",
"=",
"seqno",
"\n",
"}",
"\n",
"ss",
".",
"curRow",
"++",
"\n",
"_",
",",
"err",
"=",
"ss",
".",
"sqlStore",
".",
"preparedStmts",
"[",
"sqlSubAddPending",
"]",
".",
"Exec",
"(",
"subid",
",",
"ss",
".",
"curRow",
",",
"seqno",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"err",
"=",
"sqlStmtError",
"(",
"sqlSubAddPending",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"ss",
".",
"Unlock",
"(",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // AddSeqPending implements the SubStore interface | [
"AddSeqPending",
"implements",
"the",
"SubStore",
"interface"
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/sqlstore.go#L1880-L1902 | train |
nats-io/nats-streaming-server | stores/sqlstore.go | AckSeqPending | func (ss *SQLSubStore) AckSeqPending(subid, seqno uint64) error {
var err error
ss.Lock()
if !ss.closed {
if ss.cache != nil {
var isFull bool
isFull, err = ss.ackSeq(subid, seqno)
if err == nil && isFull {
err = ss.flush()
}
} else {
updateLastSent := false
ls := ss.subLastSent[subid]
if seqno >= ls {
if seqno > ls {
ss.subLastSent[subid] = seqno
}
updateLastSent = true
}
if updateLastSent {
if _, err := ss.sqlStore.preparedStmts[sqlSubUpdateLastSent].Exec(seqno, ss.channelID, subid); err != nil {
ss.Unlock()
return sqlStmtError(sqlSubUpdateLastSent, err)
}
}
_, err = ss.sqlStore.preparedStmts[sqlSubDeletePending].Exec(subid, seqno)
if err != nil {
err = sqlStmtError(sqlSubDeletePending, err)
}
}
}
ss.Unlock()
return err
} | go | func (ss *SQLSubStore) AckSeqPending(subid, seqno uint64) error {
var err error
ss.Lock()
if !ss.closed {
if ss.cache != nil {
var isFull bool
isFull, err = ss.ackSeq(subid, seqno)
if err == nil && isFull {
err = ss.flush()
}
} else {
updateLastSent := false
ls := ss.subLastSent[subid]
if seqno >= ls {
if seqno > ls {
ss.subLastSent[subid] = seqno
}
updateLastSent = true
}
if updateLastSent {
if _, err := ss.sqlStore.preparedStmts[sqlSubUpdateLastSent].Exec(seqno, ss.channelID, subid); err != nil {
ss.Unlock()
return sqlStmtError(sqlSubUpdateLastSent, err)
}
}
_, err = ss.sqlStore.preparedStmts[sqlSubDeletePending].Exec(subid, seqno)
if err != nil {
err = sqlStmtError(sqlSubDeletePending, err)
}
}
}
ss.Unlock()
return err
} | [
"func",
"(",
"ss",
"*",
"SQLSubStore",
")",
"AckSeqPending",
"(",
"subid",
",",
"seqno",
"uint64",
")",
"error",
"{",
"var",
"err",
"error",
"\n",
"ss",
".",
"Lock",
"(",
")",
"\n",
"if",
"!",
"ss",
".",
"closed",
"{",
"if",
"ss",
".",
"cache",
"!=",
"nil",
"{",
"var",
"isFull",
"bool",
"\n",
"isFull",
",",
"err",
"=",
"ss",
".",
"ackSeq",
"(",
"subid",
",",
"seqno",
")",
"\n",
"if",
"err",
"==",
"nil",
"&&",
"isFull",
"{",
"err",
"=",
"ss",
".",
"flush",
"(",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"updateLastSent",
":=",
"false",
"\n",
"ls",
":=",
"ss",
".",
"subLastSent",
"[",
"subid",
"]",
"\n",
"if",
"seqno",
">=",
"ls",
"{",
"if",
"seqno",
">",
"ls",
"{",
"ss",
".",
"subLastSent",
"[",
"subid",
"]",
"=",
"seqno",
"\n",
"}",
"\n",
"updateLastSent",
"=",
"true",
"\n",
"}",
"\n",
"if",
"updateLastSent",
"{",
"if",
"_",
",",
"err",
":=",
"ss",
".",
"sqlStore",
".",
"preparedStmts",
"[",
"sqlSubUpdateLastSent",
"]",
".",
"Exec",
"(",
"seqno",
",",
"ss",
".",
"channelID",
",",
"subid",
")",
";",
"err",
"!=",
"nil",
"{",
"ss",
".",
"Unlock",
"(",
")",
"\n",
"return",
"sqlStmtError",
"(",
"sqlSubUpdateLastSent",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"ss",
".",
"sqlStore",
".",
"preparedStmts",
"[",
"sqlSubDeletePending",
"]",
".",
"Exec",
"(",
"subid",
",",
"seqno",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"err",
"=",
"sqlStmtError",
"(",
"sqlSubDeletePending",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"ss",
".",
"Unlock",
"(",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // AckSeqPending implements the SubStore interface | [
"AckSeqPending",
"implements",
"the",
"SubStore",
"interface"
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/sqlstore.go#L1905-L1938 | train |
nats-io/nats-streaming-server | stores/sqlstore.go | Flush | func (ss *SQLSubStore) Flush() error {
ss.Lock()
err := ss.flush()
ss.Unlock()
return err
} | go | func (ss *SQLSubStore) Flush() error {
ss.Lock()
err := ss.flush()
ss.Unlock()
return err
} | [
"func",
"(",
"ss",
"*",
"SQLSubStore",
")",
"Flush",
"(",
")",
"error",
"{",
"ss",
".",
"Lock",
"(",
")",
"\n",
"err",
":=",
"ss",
".",
"flush",
"(",
")",
"\n",
"ss",
".",
"Unlock",
"(",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // Flush implements the SubStore interface | [
"Flush",
"implements",
"the",
"SubStore",
"interface"
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/sqlstore.go#L2015-L2020 | train |
nats-io/nats-streaming-server | stores/sqlstore.go | Close | func (ss *SQLSubStore) Close() error {
ss.Lock()
if ss.closed {
ss.Unlock()
return nil
}
// Flush before switching the state to closed.
err := ss.flush()
ss.closed = true
ss.Unlock()
return err
} | go | func (ss *SQLSubStore) Close() error {
ss.Lock()
if ss.closed {
ss.Unlock()
return nil
}
// Flush before switching the state to closed.
err := ss.flush()
ss.closed = true
ss.Unlock()
return err
} | [
"func",
"(",
"ss",
"*",
"SQLSubStore",
")",
"Close",
"(",
")",
"error",
"{",
"ss",
".",
"Lock",
"(",
")",
"\n",
"if",
"ss",
".",
"closed",
"{",
"ss",
".",
"Unlock",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"err",
":=",
"ss",
".",
"flush",
"(",
")",
"\n",
"ss",
".",
"closed",
"=",
"true",
"\n",
"ss",
".",
"Unlock",
"(",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // Close implements the SubStore interface | [
"Close",
"implements",
"the",
"SubStore",
"interface"
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/sqlstore.go#L2136-L2147 | train |
nats-io/nats-streaming-server | util/channels.go | SendChannelsList | func SendChannelsList(channels []string, sendInbox, replyInbox string, nc *nats.Conn, serverID string) error {
// Since the NATS message payload is limited, we need to repeat
// requests if all channels can't fit in a request.
maxPayload := int(nc.MaxPayload())
// Reuse this request object to send the (possibly many) protocol message(s).
header := &spb.CtrlMsg{
ServerID: serverID,
MsgType: spb.CtrlMsg_Partitioning,
}
// The Data field (a byte array) will require 1+len(array)+(encoded size of array).
// To be conservative, let's just use a 8 bytes integer
headerSize := header.Size() + 1 + 8
var (
bytes []byte // Reused buffer in which the request is to marshal info
n int // Size of the serialized request in the above buffer
count int // Number of channels added to the request
)
for start := 0; start != len(channels); start += count {
bytes, n, count = encodeChannelsRequest(header, channels, bytes, headerSize, maxPayload, start)
if count == 0 {
return errors.New("message payload too small to send channels list")
}
if err := nc.PublishRequest(sendInbox, replyInbox, bytes[:n]); err != nil {
return err
}
}
return nc.Flush()
} | go | func SendChannelsList(channels []string, sendInbox, replyInbox string, nc *nats.Conn, serverID string) error {
// Since the NATS message payload is limited, we need to repeat
// requests if all channels can't fit in a request.
maxPayload := int(nc.MaxPayload())
// Reuse this request object to send the (possibly many) protocol message(s).
header := &spb.CtrlMsg{
ServerID: serverID,
MsgType: spb.CtrlMsg_Partitioning,
}
// The Data field (a byte array) will require 1+len(array)+(encoded size of array).
// To be conservative, let's just use a 8 bytes integer
headerSize := header.Size() + 1 + 8
var (
bytes []byte // Reused buffer in which the request is to marshal info
n int // Size of the serialized request in the above buffer
count int // Number of channels added to the request
)
for start := 0; start != len(channels); start += count {
bytes, n, count = encodeChannelsRequest(header, channels, bytes, headerSize, maxPayload, start)
if count == 0 {
return errors.New("message payload too small to send channels list")
}
if err := nc.PublishRequest(sendInbox, replyInbox, bytes[:n]); err != nil {
return err
}
}
return nc.Flush()
} | [
"func",
"SendChannelsList",
"(",
"channels",
"[",
"]",
"string",
",",
"sendInbox",
",",
"replyInbox",
"string",
",",
"nc",
"*",
"nats",
".",
"Conn",
",",
"serverID",
"string",
")",
"error",
"{",
"maxPayload",
":=",
"int",
"(",
"nc",
".",
"MaxPayload",
"(",
")",
")",
"\n",
"header",
":=",
"&",
"spb",
".",
"CtrlMsg",
"{",
"ServerID",
":",
"serverID",
",",
"MsgType",
":",
"spb",
".",
"CtrlMsg_Partitioning",
",",
"}",
"\n",
"headerSize",
":=",
"header",
".",
"Size",
"(",
")",
"+",
"1",
"+",
"8",
"\n",
"var",
"(",
"bytes",
"[",
"]",
"byte",
"\n",
"n",
"int",
"\n",
"count",
"int",
"\n",
")",
"\n",
"for",
"start",
":=",
"0",
";",
"start",
"!=",
"len",
"(",
"channels",
")",
";",
"start",
"+=",
"count",
"{",
"bytes",
",",
"n",
",",
"count",
"=",
"encodeChannelsRequest",
"(",
"header",
",",
"channels",
",",
"bytes",
",",
"headerSize",
",",
"maxPayload",
",",
"start",
")",
"\n",
"if",
"count",
"==",
"0",
"{",
"return",
"errors",
".",
"New",
"(",
"\"message payload too small to send channels list\"",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"nc",
".",
"PublishRequest",
"(",
"sendInbox",
",",
"replyInbox",
",",
"bytes",
"[",
":",
"n",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nc",
".",
"Flush",
"(",
")",
"\n",
"}"
] | // SendsChannelsList sends the list of channels to the given subject, possibly
// splitting the list in several requests if it cannot fit in a single message. | [
"SendsChannelsList",
"sends",
"the",
"list",
"of",
"channels",
"to",
"the",
"given",
"subject",
"possibly",
"splitting",
"the",
"list",
"in",
"several",
"requests",
"if",
"it",
"cannot",
"fit",
"in",
"a",
"single",
"message",
"."
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/util/channels.go#L30-L57 | train |
nats-io/nats-streaming-server | util/channels.go | DecodeChannels | func DecodeChannels(data []byte) ([]string, error) {
channels := []string{}
pos := 0
for pos < len(data) {
if pos+2 > len(data) {
return nil, fmt.Errorf("unable to decode size, pos=%v len=%v", pos, len(data))
}
cl := int(ByteOrder.Uint16(data[pos:]))
pos += encodedChannelLen
end := pos + cl
if end > len(data) {
return nil, fmt.Errorf("unable to decode channel, pos=%v len=%v max=%v (string=%v)",
pos, cl, len(data), string(data[pos:]))
}
c := string(data[pos:end])
channels = append(channels, c)
pos = end
}
return channels, nil
} | go | func DecodeChannels(data []byte) ([]string, error) {
channels := []string{}
pos := 0
for pos < len(data) {
if pos+2 > len(data) {
return nil, fmt.Errorf("unable to decode size, pos=%v len=%v", pos, len(data))
}
cl := int(ByteOrder.Uint16(data[pos:]))
pos += encodedChannelLen
end := pos + cl
if end > len(data) {
return nil, fmt.Errorf("unable to decode channel, pos=%v len=%v max=%v (string=%v)",
pos, cl, len(data), string(data[pos:]))
}
c := string(data[pos:end])
channels = append(channels, c)
pos = end
}
return channels, nil
} | [
"func",
"DecodeChannels",
"(",
"data",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"channels",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"pos",
":=",
"0",
"\n",
"for",
"pos",
"<",
"len",
"(",
"data",
")",
"{",
"if",
"pos",
"+",
"2",
">",
"len",
"(",
"data",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"unable to decode size, pos=%v len=%v\"",
",",
"pos",
",",
"len",
"(",
"data",
")",
")",
"\n",
"}",
"\n",
"cl",
":=",
"int",
"(",
"ByteOrder",
".",
"Uint16",
"(",
"data",
"[",
"pos",
":",
"]",
")",
")",
"\n",
"pos",
"+=",
"encodedChannelLen",
"\n",
"end",
":=",
"pos",
"+",
"cl",
"\n",
"if",
"end",
">",
"len",
"(",
"data",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"unable to decode channel, pos=%v len=%v max=%v (string=%v)\"",
",",
"pos",
",",
"cl",
",",
"len",
"(",
"data",
")",
",",
"string",
"(",
"data",
"[",
"pos",
":",
"]",
")",
")",
"\n",
"}",
"\n",
"c",
":=",
"string",
"(",
"data",
"[",
"pos",
":",
"end",
"]",
")",
"\n",
"channels",
"=",
"append",
"(",
"channels",
",",
"c",
")",
"\n",
"pos",
"=",
"end",
"\n",
"}",
"\n",
"return",
"channels",
",",
"nil",
"\n",
"}"
] | // DecodeChannels decodes from the given byte array the list of channel names
// and return them as an array of strings. | [
"DecodeChannels",
"decodes",
"from",
"the",
"given",
"byte",
"array",
"the",
"list",
"of",
"channel",
"names",
"and",
"return",
"them",
"as",
"an",
"array",
"of",
"strings",
"."
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/util/channels.go#L61-L80 | train |
nats-io/nats-streaming-server | server/ft.go | ftStart | func (s *StanServer) ftStart() (retErr error) {
s.log.Noticef("Starting in standby mode")
// For tests purposes
if ftPauseBeforeFirstAttempt {
<-ftPauseCh
}
print, _ := util.NewBackoffTimeCheck(time.Second, 2, time.Minute)
for {
select {
case <-s.ftQuit:
// we are done
return nil
case <-s.ftHBCh:
// go back to the beginning of the for loop
continue
case <-time.After(s.ftHBMissedInterval):
// try to lock the store
}
locked, err := s.ftGetStoreLock()
if err != nil {
// Log the error, but go back and wait for the next interval and
// try again. It is possible that the error resolves (for instance
// the connection to the database is restored - for SQL stores).
s.log.Errorf("ft: error attempting to get the store lock: %v", err)
continue
} else if locked {
break
}
// Here, we did not get the lock, print and go back to standby.
// Use some backoff for the printing to not fill up the log
if print.Ok() {
s.log.Noticef("ft: unable to get store lock at this time, going back to standby")
}
}
// Capture the time this server activated. It will be used in case several
// servers claim to be active. Not bulletproof since there could be clock
// differences, etc... but when more than one server has acquired the store
// lock it means we are already in trouble, so just trying to minimize the
// possible store corruption...
activationTime := time.Now()
s.log.Noticef("Server is active")
s.startGoRoutine(func() {
s.ftSendHBLoop(activationTime)
})
// Start the recovery process, etc..
return s.start(FTActive)
} | go | func (s *StanServer) ftStart() (retErr error) {
s.log.Noticef("Starting in standby mode")
// For tests purposes
if ftPauseBeforeFirstAttempt {
<-ftPauseCh
}
print, _ := util.NewBackoffTimeCheck(time.Second, 2, time.Minute)
for {
select {
case <-s.ftQuit:
// we are done
return nil
case <-s.ftHBCh:
// go back to the beginning of the for loop
continue
case <-time.After(s.ftHBMissedInterval):
// try to lock the store
}
locked, err := s.ftGetStoreLock()
if err != nil {
// Log the error, but go back and wait for the next interval and
// try again. It is possible that the error resolves (for instance
// the connection to the database is restored - for SQL stores).
s.log.Errorf("ft: error attempting to get the store lock: %v", err)
continue
} else if locked {
break
}
// Here, we did not get the lock, print and go back to standby.
// Use some backoff for the printing to not fill up the log
if print.Ok() {
s.log.Noticef("ft: unable to get store lock at this time, going back to standby")
}
}
// Capture the time this server activated. It will be used in case several
// servers claim to be active. Not bulletproof since there could be clock
// differences, etc... but when more than one server has acquired the store
// lock it means we are already in trouble, so just trying to minimize the
// possible store corruption...
activationTime := time.Now()
s.log.Noticef("Server is active")
s.startGoRoutine(func() {
s.ftSendHBLoop(activationTime)
})
// Start the recovery process, etc..
return s.start(FTActive)
} | [
"func",
"(",
"s",
"*",
"StanServer",
")",
"ftStart",
"(",
")",
"(",
"retErr",
"error",
")",
"{",
"s",
".",
"log",
".",
"Noticef",
"(",
"\"Starting in standby mode\"",
")",
"\n",
"if",
"ftPauseBeforeFirstAttempt",
"{",
"<-",
"ftPauseCh",
"\n",
"}",
"\n",
"print",
",",
"_",
":=",
"util",
".",
"NewBackoffTimeCheck",
"(",
"time",
".",
"Second",
",",
"2",
",",
"time",
".",
"Minute",
")",
"\n",
"for",
"{",
"select",
"{",
"case",
"<-",
"s",
".",
"ftQuit",
":",
"return",
"nil",
"\n",
"case",
"<-",
"s",
".",
"ftHBCh",
":",
"continue",
"\n",
"case",
"<-",
"time",
".",
"After",
"(",
"s",
".",
"ftHBMissedInterval",
")",
":",
"}",
"\n",
"locked",
",",
"err",
":=",
"s",
".",
"ftGetStoreLock",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"s",
".",
"log",
".",
"Errorf",
"(",
"\"ft: error attempting to get the store lock: %v\"",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"else",
"if",
"locked",
"{",
"break",
"\n",
"}",
"\n",
"if",
"print",
".",
"Ok",
"(",
")",
"{",
"s",
".",
"log",
".",
"Noticef",
"(",
"\"ft: unable to get store lock at this time, going back to standby\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"activationTime",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"s",
".",
"log",
".",
"Noticef",
"(",
"\"Server is active\"",
")",
"\n",
"s",
".",
"startGoRoutine",
"(",
"func",
"(",
")",
"{",
"s",
".",
"ftSendHBLoop",
"(",
"activationTime",
")",
"\n",
"}",
")",
"\n",
"return",
"s",
".",
"start",
"(",
"FTActive",
")",
"\n",
"}"
] | // ftStart will return only when this server has become active
// and was able to get the store's exclusive lock.
// This is running in a separate go-routine so if server state
// changes, take care of using the server's lock. | [
"ftStart",
"will",
"return",
"only",
"when",
"this",
"server",
"has",
"become",
"active",
"and",
"was",
"able",
"to",
"get",
"the",
"store",
"s",
"exclusive",
"lock",
".",
"This",
"is",
"running",
"in",
"a",
"separate",
"go",
"-",
"routine",
"so",
"if",
"server",
"state",
"changes",
"take",
"care",
"of",
"using",
"the",
"server",
"s",
"lock",
"."
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/server/ft.go#L56-L102 | train |
nats-io/nats-streaming-server | server/ft.go | ftGetStoreLock | func (s *StanServer) ftGetStoreLock() (bool, error) {
// Normally, the store would be set early and is immutable, but some
// FT tests do set a mock store after the server is created, so use
// locking here to avoid race reports.
s.mu.Lock()
store := s.store
s.mu.Unlock()
if ok, err := store.GetExclusiveLock(); !ok || err != nil {
// We got an error not related to locking (could be not supported,
// permissions error, file not reachable, etc..)
if err != nil {
return false, fmt.Errorf("ft: fatal error getting the store lock: %v", err)
}
// If ok is false, it means that we did not get the lock.
return false, nil
}
return true, nil
} | go | func (s *StanServer) ftGetStoreLock() (bool, error) {
// Normally, the store would be set early and is immutable, but some
// FT tests do set a mock store after the server is created, so use
// locking here to avoid race reports.
s.mu.Lock()
store := s.store
s.mu.Unlock()
if ok, err := store.GetExclusiveLock(); !ok || err != nil {
// We got an error not related to locking (could be not supported,
// permissions error, file not reachable, etc..)
if err != nil {
return false, fmt.Errorf("ft: fatal error getting the store lock: %v", err)
}
// If ok is false, it means that we did not get the lock.
return false, nil
}
return true, nil
} | [
"func",
"(",
"s",
"*",
"StanServer",
")",
"ftGetStoreLock",
"(",
")",
"(",
"bool",
",",
"error",
")",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"store",
":=",
"s",
".",
"store",
"\n",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"ok",
",",
"err",
":=",
"store",
".",
"GetExclusiveLock",
"(",
")",
";",
"!",
"ok",
"||",
"err",
"!=",
"nil",
"{",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"fmt",
".",
"Errorf",
"(",
"\"ft: fatal error getting the store lock: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"false",
",",
"nil",
"\n",
"}",
"\n",
"return",
"true",
",",
"nil",
"\n",
"}"
] | // ftGetStoreLock returns true if the server was able to get the
// exclusive store lock, false othewise, or if there was a fatal error doing so. | [
"ftGetStoreLock",
"returns",
"true",
"if",
"the",
"server",
"was",
"able",
"to",
"get",
"the",
"exclusive",
"store",
"lock",
"false",
"othewise",
"or",
"if",
"there",
"was",
"a",
"fatal",
"error",
"doing",
"so",
"."
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/server/ft.go#L106-L123 | train |
nats-io/nats-streaming-server | server/ft.go | ftSendHBLoop | func (s *StanServer) ftSendHBLoop(activationTime time.Time) {
// Release the wait group on exit
defer s.wg.Done()
timeAsBytes, _ := activationTime.MarshalBinary()
ftHB := &spb.CtrlMsg{
MsgType: spb.CtrlMsg_FTHeartbeat,
ServerID: s.serverID,
Data: timeAsBytes,
}
ftHBBytes, _ := ftHB.Marshal()
print, _ := util.NewBackoffTimeCheck(time.Second, 2, time.Minute)
for {
if err := s.ftnc.Publish(s.ftSubject, ftHBBytes); err != nil {
if print.Ok() {
s.log.Errorf("Unable to send FT heartbeat: %v", err)
}
}
startSelect:
select {
case m := <-s.ftHBCh:
hb := spb.CtrlMsg{}
if err := hb.Unmarshal(m.Data); err != nil {
goto startSelect
}
// Ignore our own message
if hb.MsgType != spb.CtrlMsg_FTHeartbeat || hb.ServerID == s.serverID {
goto startSelect
}
// Another server claims to be active
peerActivationTime := time.Time{}
if err := peerActivationTime.UnmarshalBinary(hb.Data); err != nil {
s.log.Errorf("Error decoding activation time: %v", err)
} else {
// Step down if the peer's activation time is earlier than ours.
err := fmt.Errorf("ft: serverID %q claims to be active", hb.ServerID)
if peerActivationTime.Before(activationTime) {
err = fmt.Errorf("%s, aborting", err)
if ftNoPanic {
s.setLastError(err)
return
}
panic(err)
} else {
s.log.Errorf(err.Error())
}
}
case <-time.After(s.ftHBInterval):
// We'll send the ping at the top of the for loop
case <-s.ftQuit:
return
}
}
} | go | func (s *StanServer) ftSendHBLoop(activationTime time.Time) {
// Release the wait group on exit
defer s.wg.Done()
timeAsBytes, _ := activationTime.MarshalBinary()
ftHB := &spb.CtrlMsg{
MsgType: spb.CtrlMsg_FTHeartbeat,
ServerID: s.serverID,
Data: timeAsBytes,
}
ftHBBytes, _ := ftHB.Marshal()
print, _ := util.NewBackoffTimeCheck(time.Second, 2, time.Minute)
for {
if err := s.ftnc.Publish(s.ftSubject, ftHBBytes); err != nil {
if print.Ok() {
s.log.Errorf("Unable to send FT heartbeat: %v", err)
}
}
startSelect:
select {
case m := <-s.ftHBCh:
hb := spb.CtrlMsg{}
if err := hb.Unmarshal(m.Data); err != nil {
goto startSelect
}
// Ignore our own message
if hb.MsgType != spb.CtrlMsg_FTHeartbeat || hb.ServerID == s.serverID {
goto startSelect
}
// Another server claims to be active
peerActivationTime := time.Time{}
if err := peerActivationTime.UnmarshalBinary(hb.Data); err != nil {
s.log.Errorf("Error decoding activation time: %v", err)
} else {
// Step down if the peer's activation time is earlier than ours.
err := fmt.Errorf("ft: serverID %q claims to be active", hb.ServerID)
if peerActivationTime.Before(activationTime) {
err = fmt.Errorf("%s, aborting", err)
if ftNoPanic {
s.setLastError(err)
return
}
panic(err)
} else {
s.log.Errorf(err.Error())
}
}
case <-time.After(s.ftHBInterval):
// We'll send the ping at the top of the for loop
case <-s.ftQuit:
return
}
}
} | [
"func",
"(",
"s",
"*",
"StanServer",
")",
"ftSendHBLoop",
"(",
"activationTime",
"time",
".",
"Time",
")",
"{",
"defer",
"s",
".",
"wg",
".",
"Done",
"(",
")",
"\n",
"timeAsBytes",
",",
"_",
":=",
"activationTime",
".",
"MarshalBinary",
"(",
")",
"\n",
"ftHB",
":=",
"&",
"spb",
".",
"CtrlMsg",
"{",
"MsgType",
":",
"spb",
".",
"CtrlMsg_FTHeartbeat",
",",
"ServerID",
":",
"s",
".",
"serverID",
",",
"Data",
":",
"timeAsBytes",
",",
"}",
"\n",
"ftHBBytes",
",",
"_",
":=",
"ftHB",
".",
"Marshal",
"(",
")",
"\n",
"print",
",",
"_",
":=",
"util",
".",
"NewBackoffTimeCheck",
"(",
"time",
".",
"Second",
",",
"2",
",",
"time",
".",
"Minute",
")",
"\n",
"for",
"{",
"if",
"err",
":=",
"s",
".",
"ftnc",
".",
"Publish",
"(",
"s",
".",
"ftSubject",
",",
"ftHBBytes",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"print",
".",
"Ok",
"(",
")",
"{",
"s",
".",
"log",
".",
"Errorf",
"(",
"\"Unable to send FT heartbeat: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"startSelect",
":",
"select",
"{",
"case",
"m",
":=",
"<-",
"s",
".",
"ftHBCh",
":",
"hb",
":=",
"spb",
".",
"CtrlMsg",
"{",
"}",
"\n",
"if",
"err",
":=",
"hb",
".",
"Unmarshal",
"(",
"m",
".",
"Data",
")",
";",
"err",
"!=",
"nil",
"{",
"goto",
"startSelect",
"\n",
"}",
"\n",
"if",
"hb",
".",
"MsgType",
"!=",
"spb",
".",
"CtrlMsg_FTHeartbeat",
"||",
"hb",
".",
"ServerID",
"==",
"s",
".",
"serverID",
"{",
"goto",
"startSelect",
"\n",
"}",
"\n",
"peerActivationTime",
":=",
"time",
".",
"Time",
"{",
"}",
"\n",
"if",
"err",
":=",
"peerActivationTime",
".",
"UnmarshalBinary",
"(",
"hb",
".",
"Data",
")",
";",
"err",
"!=",
"nil",
"{",
"s",
".",
"log",
".",
"Errorf",
"(",
"\"Error decoding activation time: %v\"",
",",
"err",
")",
"\n",
"}",
"else",
"{",
"err",
":=",
"fmt",
".",
"Errorf",
"(",
"\"ft: serverID %q claims to be active\"",
",",
"hb",
".",
"ServerID",
")",
"\n",
"if",
"peerActivationTime",
".",
"Before",
"(",
"activationTime",
")",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"%s, aborting\"",
",",
"err",
")",
"\n",
"if",
"ftNoPanic",
"{",
"s",
".",
"setLastError",
"(",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"panic",
"(",
"err",
")",
"\n",
"}",
"else",
"{",
"s",
".",
"log",
".",
"Errorf",
"(",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"case",
"<-",
"time",
".",
"After",
"(",
"s",
".",
"ftHBInterval",
")",
":",
"case",
"<-",
"s",
".",
"ftQuit",
":",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // ftSendHBLoop is used by an active server to send HB to the FT subject.
// Standby servers receiving those HBs do not attempt to lock the store.
// When they miss HBs, they will. | [
"ftSendHBLoop",
"is",
"used",
"by",
"an",
"active",
"server",
"to",
"send",
"HB",
"to",
"the",
"FT",
"subject",
".",
"Standby",
"servers",
"receiving",
"those",
"HBs",
"do",
"not",
"attempt",
"to",
"lock",
"the",
"store",
".",
"When",
"they",
"miss",
"HBs",
"they",
"will",
"."
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/server/ft.go#L128-L181 | train |
nats-io/nats-streaming-server | server/ft.go | ftSetup | func (s *StanServer) ftSetup() error {
// Check that store type is ok. So far only support for FileStore
if s.opts.StoreType != stores.TypeFile && s.opts.StoreType != stores.TypeSQL {
return fmt.Errorf("ft: only %v or %v stores supported in FT mode", stores.TypeFile, stores.TypeSQL)
}
// So far, those are not exposed to users, just used in tests.
// Still make sure that the missed HB interval is > than the HB
// interval.
if ftHBMissedInterval < time.Duration(float64(ftHBInterval)*1.1) {
return fmt.Errorf("ft: the missed heartbeat interval needs to be"+
" at least 10%% of the heartbeat interval (hb=%v missed hb=%v",
ftHBInterval, ftHBMissedInterval)
}
// Set the HB and MissedHB intervals, using a bit of randomness
rand.Seed(time.Now().UnixNano())
s.ftHBInterval = ftGetRandomInterval(ftHBInterval)
s.ftHBMissedInterval = ftGetRandomInterval(ftHBMissedInterval)
// Subscribe to FT subject
s.ftSubject = fmt.Sprintf("%s.%s.%s", ftHBPrefix, s.opts.ID, s.opts.FTGroupName)
s.ftHBCh = make(chan *nats.Msg)
sub, err := s.ftnc.Subscribe(s.ftSubject, func(m *nats.Msg) {
// Dropping incoming FT HBs is not crucial, we will then check for
// store lock.
select {
case s.ftHBCh <- m:
default:
}
})
if err != nil {
return fmt.Errorf("ft: unable to subscribe on ft subject: %v", err)
}
// We don't want to cause possible slow consumer error
sub.SetPendingLimits(-1, -1)
// Create channel to notify FT go routine to quit.
s.ftQuit = make(chan struct{}, 1)
// Set the state as standby initially
s.state = FTStandby
return nil
} | go | func (s *StanServer) ftSetup() error {
// Check that store type is ok. So far only support for FileStore
if s.opts.StoreType != stores.TypeFile && s.opts.StoreType != stores.TypeSQL {
return fmt.Errorf("ft: only %v or %v stores supported in FT mode", stores.TypeFile, stores.TypeSQL)
}
// So far, those are not exposed to users, just used in tests.
// Still make sure that the missed HB interval is > than the HB
// interval.
if ftHBMissedInterval < time.Duration(float64(ftHBInterval)*1.1) {
return fmt.Errorf("ft: the missed heartbeat interval needs to be"+
" at least 10%% of the heartbeat interval (hb=%v missed hb=%v",
ftHBInterval, ftHBMissedInterval)
}
// Set the HB and MissedHB intervals, using a bit of randomness
rand.Seed(time.Now().UnixNano())
s.ftHBInterval = ftGetRandomInterval(ftHBInterval)
s.ftHBMissedInterval = ftGetRandomInterval(ftHBMissedInterval)
// Subscribe to FT subject
s.ftSubject = fmt.Sprintf("%s.%s.%s", ftHBPrefix, s.opts.ID, s.opts.FTGroupName)
s.ftHBCh = make(chan *nats.Msg)
sub, err := s.ftnc.Subscribe(s.ftSubject, func(m *nats.Msg) {
// Dropping incoming FT HBs is not crucial, we will then check for
// store lock.
select {
case s.ftHBCh <- m:
default:
}
})
if err != nil {
return fmt.Errorf("ft: unable to subscribe on ft subject: %v", err)
}
// We don't want to cause possible slow consumer error
sub.SetPendingLimits(-1, -1)
// Create channel to notify FT go routine to quit.
s.ftQuit = make(chan struct{}, 1)
// Set the state as standby initially
s.state = FTStandby
return nil
} | [
"func",
"(",
"s",
"*",
"StanServer",
")",
"ftSetup",
"(",
")",
"error",
"{",
"if",
"s",
".",
"opts",
".",
"StoreType",
"!=",
"stores",
".",
"TypeFile",
"&&",
"s",
".",
"opts",
".",
"StoreType",
"!=",
"stores",
".",
"TypeSQL",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"ft: only %v or %v stores supported in FT mode\"",
",",
"stores",
".",
"TypeFile",
",",
"stores",
".",
"TypeSQL",
")",
"\n",
"}",
"\n",
"if",
"ftHBMissedInterval",
"<",
"time",
".",
"Duration",
"(",
"float64",
"(",
"ftHBInterval",
")",
"*",
"1.1",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"ft: the missed heartbeat interval needs to be\"",
"+",
"\" at least 10%% of the heartbeat interval (hb=%v missed hb=%v\"",
",",
"ftHBInterval",
",",
"ftHBMissedInterval",
")",
"\n",
"}",
"\n",
"rand",
".",
"Seed",
"(",
"time",
".",
"Now",
"(",
")",
".",
"UnixNano",
"(",
")",
")",
"\n",
"s",
".",
"ftHBInterval",
"=",
"ftGetRandomInterval",
"(",
"ftHBInterval",
")",
"\n",
"s",
".",
"ftHBMissedInterval",
"=",
"ftGetRandomInterval",
"(",
"ftHBMissedInterval",
")",
"\n",
"s",
".",
"ftSubject",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"%s.%s.%s\"",
",",
"ftHBPrefix",
",",
"s",
".",
"opts",
".",
"ID",
",",
"s",
".",
"opts",
".",
"FTGroupName",
")",
"\n",
"s",
".",
"ftHBCh",
"=",
"make",
"(",
"chan",
"*",
"nats",
".",
"Msg",
")",
"\n",
"sub",
",",
"err",
":=",
"s",
".",
"ftnc",
".",
"Subscribe",
"(",
"s",
".",
"ftSubject",
",",
"func",
"(",
"m",
"*",
"nats",
".",
"Msg",
")",
"{",
"select",
"{",
"case",
"s",
".",
"ftHBCh",
"<-",
"m",
":",
"default",
":",
"}",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"ft: unable to subscribe on ft subject: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"sub",
".",
"SetPendingLimits",
"(",
"-",
"1",
",",
"-",
"1",
")",
"\n",
"s",
".",
"ftQuit",
"=",
"make",
"(",
"chan",
"struct",
"{",
"}",
",",
"1",
")",
"\n",
"s",
".",
"state",
"=",
"FTStandby",
"\n",
"return",
"nil",
"\n",
"}"
] | // ftSetup checks that all required FT parameters have been specified and
// create the channel required for shutdown.
// Note that FTGroupName has to be set before server invokes this function,
// so this parameter is not checked here. | [
"ftSetup",
"checks",
"that",
"all",
"required",
"FT",
"parameters",
"have",
"been",
"specified",
"and",
"create",
"the",
"channel",
"required",
"for",
"shutdown",
".",
"Note",
"that",
"FTGroupName",
"has",
"to",
"be",
"set",
"before",
"server",
"invokes",
"this",
"function",
"so",
"this",
"parameter",
"is",
"not",
"checked",
"here",
"."
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/server/ft.go#L187-L225 | train |
nats-io/nats-streaming-server | server/client.go | newClientStore | func newClientStore(store stores.Store) *clientStore {
return &clientStore{
clients: make(map[string]*client),
connIDs: make(map[string]*client),
knownInvalid: make(map[string]struct{}),
store: store,
}
} | go | func newClientStore(store stores.Store) *clientStore {
return &clientStore{
clients: make(map[string]*client),
connIDs: make(map[string]*client),
knownInvalid: make(map[string]struct{}),
store: store,
}
} | [
"func",
"newClientStore",
"(",
"store",
"stores",
".",
"Store",
")",
"*",
"clientStore",
"{",
"return",
"&",
"clientStore",
"{",
"clients",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"client",
")",
",",
"connIDs",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"client",
")",
",",
"knownInvalid",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
")",
",",
"store",
":",
"store",
",",
"}",
"\n",
"}"
] | // newClientStore creates a new clientStore instance using `store` as the backing storage. | [
"newClientStore",
"creates",
"a",
"new",
"clientStore",
"instance",
"using",
"store",
"as",
"the",
"backing",
"storage",
"."
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/server/client.go#L51-L58 | train |
nats-io/nats-streaming-server | server/client.go | getSubsCopy | func (c *client) getSubsCopy() []*subState {
subs := make([]*subState, len(c.subs))
copy(subs, c.subs)
return subs
} | go | func (c *client) getSubsCopy() []*subState {
subs := make([]*subState, len(c.subs))
copy(subs, c.subs)
return subs
} | [
"func",
"(",
"c",
"*",
"client",
")",
"getSubsCopy",
"(",
")",
"[",
"]",
"*",
"subState",
"{",
"subs",
":=",
"make",
"(",
"[",
"]",
"*",
"subState",
",",
"len",
"(",
"c",
".",
"subs",
")",
")",
"\n",
"copy",
"(",
"subs",
",",
"c",
".",
"subs",
")",
"\n",
"return",
"subs",
"\n",
"}"
] | // getSubsCopy returns a copy of the client's subscribers array.
// At least Read-lock must be held by the caller. | [
"getSubsCopy",
"returns",
"a",
"copy",
"of",
"the",
"client",
"s",
"subscribers",
"array",
".",
"At",
"least",
"Read",
"-",
"lock",
"must",
"be",
"held",
"by",
"the",
"caller",
"."
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/server/client.go#L62-L66 | train |
nats-io/nats-streaming-server | server/client.go | register | func (cs *clientStore) register(info *spb.ClientInfo) (*client, error) {
cs.Lock()
defer cs.Unlock()
c := cs.clients[info.ID]
if c != nil {
return nil, ErrInvalidClient
}
sc, err := cs.store.AddClient(info)
if err != nil {
return nil, err
}
c = &client{info: sc, subs: make([]*subState, 0, 4)}
cs.clients[c.info.ID] = c
if len(c.info.ConnID) > 0 {
cs.connIDs[string(c.info.ConnID)] = c
}
delete(cs.knownInvalid, getKnownInvalidKey(info.ID, info.ConnID))
if cs.waitOnRegister != nil {
ch := cs.waitOnRegister[c.info.ID]
if ch != nil {
ch <- struct{}{}
delete(cs.waitOnRegister, c.info.ID)
}
}
return c, nil
} | go | func (cs *clientStore) register(info *spb.ClientInfo) (*client, error) {
cs.Lock()
defer cs.Unlock()
c := cs.clients[info.ID]
if c != nil {
return nil, ErrInvalidClient
}
sc, err := cs.store.AddClient(info)
if err != nil {
return nil, err
}
c = &client{info: sc, subs: make([]*subState, 0, 4)}
cs.clients[c.info.ID] = c
if len(c.info.ConnID) > 0 {
cs.connIDs[string(c.info.ConnID)] = c
}
delete(cs.knownInvalid, getKnownInvalidKey(info.ID, info.ConnID))
if cs.waitOnRegister != nil {
ch := cs.waitOnRegister[c.info.ID]
if ch != nil {
ch <- struct{}{}
delete(cs.waitOnRegister, c.info.ID)
}
}
return c, nil
} | [
"func",
"(",
"cs",
"*",
"clientStore",
")",
"register",
"(",
"info",
"*",
"spb",
".",
"ClientInfo",
")",
"(",
"*",
"client",
",",
"error",
")",
"{",
"cs",
".",
"Lock",
"(",
")",
"\n",
"defer",
"cs",
".",
"Unlock",
"(",
")",
"\n",
"c",
":=",
"cs",
".",
"clients",
"[",
"info",
".",
"ID",
"]",
"\n",
"if",
"c",
"!=",
"nil",
"{",
"return",
"nil",
",",
"ErrInvalidClient",
"\n",
"}",
"\n",
"sc",
",",
"err",
":=",
"cs",
".",
"store",
".",
"AddClient",
"(",
"info",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"c",
"=",
"&",
"client",
"{",
"info",
":",
"sc",
",",
"subs",
":",
"make",
"(",
"[",
"]",
"*",
"subState",
",",
"0",
",",
"4",
")",
"}",
"\n",
"cs",
".",
"clients",
"[",
"c",
".",
"info",
".",
"ID",
"]",
"=",
"c",
"\n",
"if",
"len",
"(",
"c",
".",
"info",
".",
"ConnID",
")",
">",
"0",
"{",
"cs",
".",
"connIDs",
"[",
"string",
"(",
"c",
".",
"info",
".",
"ConnID",
")",
"]",
"=",
"c",
"\n",
"}",
"\n",
"delete",
"(",
"cs",
".",
"knownInvalid",
",",
"getKnownInvalidKey",
"(",
"info",
".",
"ID",
",",
"info",
".",
"ConnID",
")",
")",
"\n",
"if",
"cs",
".",
"waitOnRegister",
"!=",
"nil",
"{",
"ch",
":=",
"cs",
".",
"waitOnRegister",
"[",
"c",
".",
"info",
".",
"ID",
"]",
"\n",
"if",
"ch",
"!=",
"nil",
"{",
"ch",
"<-",
"struct",
"{",
"}",
"{",
"}",
"\n",
"delete",
"(",
"cs",
".",
"waitOnRegister",
",",
"c",
".",
"info",
".",
"ID",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"c",
",",
"nil",
"\n",
"}"
] | // Register a new client. Returns ErrInvalidClient if client is already registered. | [
"Register",
"a",
"new",
"client",
".",
"Returns",
"ErrInvalidClient",
"if",
"client",
"is",
"already",
"registered",
"."
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/server/client.go#L76-L101 | train |
nats-io/nats-streaming-server | server/client.go | unregister | func (cs *clientStore) unregister(ID string) (*client, error) {
cs.Lock()
defer cs.Unlock()
c := cs.clients[ID]
if c == nil {
return nil, nil
}
c.Lock()
if c.hbt != nil {
c.hbt.Stop()
c.hbt = nil
}
connID := c.info.ConnID
c.Unlock()
delete(cs.clients, ID)
if len(connID) > 0 {
delete(cs.connIDs, string(connID))
}
if cs.waitOnRegister != nil {
delete(cs.waitOnRegister, ID)
}
err := cs.store.DeleteClient(ID)
return c, err
} | go | func (cs *clientStore) unregister(ID string) (*client, error) {
cs.Lock()
defer cs.Unlock()
c := cs.clients[ID]
if c == nil {
return nil, nil
}
c.Lock()
if c.hbt != nil {
c.hbt.Stop()
c.hbt = nil
}
connID := c.info.ConnID
c.Unlock()
delete(cs.clients, ID)
if len(connID) > 0 {
delete(cs.connIDs, string(connID))
}
if cs.waitOnRegister != nil {
delete(cs.waitOnRegister, ID)
}
err := cs.store.DeleteClient(ID)
return c, err
} | [
"func",
"(",
"cs",
"*",
"clientStore",
")",
"unregister",
"(",
"ID",
"string",
")",
"(",
"*",
"client",
",",
"error",
")",
"{",
"cs",
".",
"Lock",
"(",
")",
"\n",
"defer",
"cs",
".",
"Unlock",
"(",
")",
"\n",
"c",
":=",
"cs",
".",
"clients",
"[",
"ID",
"]",
"\n",
"if",
"c",
"==",
"nil",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"c",
".",
"Lock",
"(",
")",
"\n",
"if",
"c",
".",
"hbt",
"!=",
"nil",
"{",
"c",
".",
"hbt",
".",
"Stop",
"(",
")",
"\n",
"c",
".",
"hbt",
"=",
"nil",
"\n",
"}",
"\n",
"connID",
":=",
"c",
".",
"info",
".",
"ConnID",
"\n",
"c",
".",
"Unlock",
"(",
")",
"\n",
"delete",
"(",
"cs",
".",
"clients",
",",
"ID",
")",
"\n",
"if",
"len",
"(",
"connID",
")",
">",
"0",
"{",
"delete",
"(",
"cs",
".",
"connIDs",
",",
"string",
"(",
"connID",
")",
")",
"\n",
"}",
"\n",
"if",
"cs",
".",
"waitOnRegister",
"!=",
"nil",
"{",
"delete",
"(",
"cs",
".",
"waitOnRegister",
",",
"ID",
")",
"\n",
"}",
"\n",
"err",
":=",
"cs",
".",
"store",
".",
"DeleteClient",
"(",
"ID",
")",
"\n",
"return",
"c",
",",
"err",
"\n",
"}"
] | // Unregister a client. | [
"Unregister",
"a",
"client",
"."
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/server/client.go#L104-L127 | train |
nats-io/nats-streaming-server | server/client.go | isValid | func (cs *clientStore) isValid(ID string, connID []byte) bool {
cs.RLock()
valid := cs.lookupByConnIDOrID(ID, connID) != nil
cs.RUnlock()
return valid
} | go | func (cs *clientStore) isValid(ID string, connID []byte) bool {
cs.RLock()
valid := cs.lookupByConnIDOrID(ID, connID) != nil
cs.RUnlock()
return valid
} | [
"func",
"(",
"cs",
"*",
"clientStore",
")",
"isValid",
"(",
"ID",
"string",
",",
"connID",
"[",
"]",
"byte",
")",
"bool",
"{",
"cs",
".",
"RLock",
"(",
")",
"\n",
"valid",
":=",
"cs",
".",
"lookupByConnIDOrID",
"(",
"ID",
",",
"connID",
")",
"!=",
"nil",
"\n",
"cs",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"valid",
"\n",
"}"
] | // IsValid returns true if the client is registered, false otherwise. | [
"IsValid",
"returns",
"true",
"if",
"the",
"client",
"is",
"registered",
"false",
"otherwise",
"."
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/server/client.go#L130-L135 | train |
nats-io/nats-streaming-server | server/client.go | lookupByConnIDOrID | func (cs *clientStore) lookupByConnIDOrID(ID string, connID []byte) *client {
var c *client
if len(connID) > 0 {
c = cs.connIDs[string(connID)]
} else {
c = cs.clients[ID]
}
return c
} | go | func (cs *clientStore) lookupByConnIDOrID(ID string, connID []byte) *client {
var c *client
if len(connID) > 0 {
c = cs.connIDs[string(connID)]
} else {
c = cs.clients[ID]
}
return c
} | [
"func",
"(",
"cs",
"*",
"clientStore",
")",
"lookupByConnIDOrID",
"(",
"ID",
"string",
",",
"connID",
"[",
"]",
"byte",
")",
"*",
"client",
"{",
"var",
"c",
"*",
"client",
"\n",
"if",
"len",
"(",
"connID",
")",
">",
"0",
"{",
"c",
"=",
"cs",
".",
"connIDs",
"[",
"string",
"(",
"connID",
")",
"]",
"\n",
"}",
"else",
"{",
"c",
"=",
"cs",
".",
"clients",
"[",
"ID",
"]",
"\n",
"}",
"\n",
"return",
"c",
"\n",
"}"
] | // Lookup client by ConnID if not nil, otherwise by clientID.
// Assume at least clientStore RLock is held on entry. | [
"Lookup",
"client",
"by",
"ConnID",
"if",
"not",
"nil",
"otherwise",
"by",
"clientID",
".",
"Assume",
"at",
"least",
"clientStore",
"RLock",
"is",
"held",
"on",
"entry",
"."
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/server/client.go#L197-L205 | train |
nats-io/nats-streaming-server | server/client.go | lookup | func (cs *clientStore) lookup(ID string) *client {
cs.RLock()
c := cs.clients[ID]
cs.RUnlock()
return c
} | go | func (cs *clientStore) lookup(ID string) *client {
cs.RLock()
c := cs.clients[ID]
cs.RUnlock()
return c
} | [
"func",
"(",
"cs",
"*",
"clientStore",
")",
"lookup",
"(",
"ID",
"string",
")",
"*",
"client",
"{",
"cs",
".",
"RLock",
"(",
")",
"\n",
"c",
":=",
"cs",
".",
"clients",
"[",
"ID",
"]",
"\n",
"cs",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"c",
"\n",
"}"
] | // Lookup a client | [
"Lookup",
"a",
"client"
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/server/client.go#L208-L213 | train |
nats-io/nats-streaming-server | server/client.go | lookupByConnID | func (cs *clientStore) lookupByConnID(connID []byte) *client {
cs.RLock()
c := cs.connIDs[string(connID)]
cs.RUnlock()
return c
} | go | func (cs *clientStore) lookupByConnID(connID []byte) *client {
cs.RLock()
c := cs.connIDs[string(connID)]
cs.RUnlock()
return c
} | [
"func",
"(",
"cs",
"*",
"clientStore",
")",
"lookupByConnID",
"(",
"connID",
"[",
"]",
"byte",
")",
"*",
"client",
"{",
"cs",
".",
"RLock",
"(",
")",
"\n",
"c",
":=",
"cs",
".",
"connIDs",
"[",
"string",
"(",
"connID",
")",
"]",
"\n",
"cs",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"c",
"\n",
"}"
] | // Lookup a client by connection ID | [
"Lookup",
"a",
"client",
"by",
"connection",
"ID"
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/server/client.go#L216-L221 | train |
nats-io/nats-streaming-server | server/client.go | getSubs | func (cs *clientStore) getSubs(ID string) []*subState {
cs.RLock()
defer cs.RUnlock()
c := cs.clients[ID]
if c == nil {
return nil
}
c.RLock()
subs := c.getSubsCopy()
c.RUnlock()
return subs
} | go | func (cs *clientStore) getSubs(ID string) []*subState {
cs.RLock()
defer cs.RUnlock()
c := cs.clients[ID]
if c == nil {
return nil
}
c.RLock()
subs := c.getSubsCopy()
c.RUnlock()
return subs
} | [
"func",
"(",
"cs",
"*",
"clientStore",
")",
"getSubs",
"(",
"ID",
"string",
")",
"[",
"]",
"*",
"subState",
"{",
"cs",
".",
"RLock",
"(",
")",
"\n",
"defer",
"cs",
".",
"RUnlock",
"(",
")",
"\n",
"c",
":=",
"cs",
".",
"clients",
"[",
"ID",
"]",
"\n",
"if",
"c",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"c",
".",
"RLock",
"(",
")",
"\n",
"subs",
":=",
"c",
".",
"getSubsCopy",
"(",
")",
"\n",
"c",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"subs",
"\n",
"}"
] | // GetSubs returns the list of subscriptions for the client identified by ID,
// or nil if such client is not found. | [
"GetSubs",
"returns",
"the",
"list",
"of",
"subscriptions",
"for",
"the",
"client",
"identified",
"by",
"ID",
"or",
"nil",
"if",
"such",
"client",
"is",
"not",
"found",
"."
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/server/client.go#L225-L236 | train |
nats-io/nats-streaming-server | server/client.go | addSub | func (cs *clientStore) addSub(ID string, sub *subState) bool {
cs.RLock()
defer cs.RUnlock()
c := cs.clients[ID]
if c == nil {
return false
}
c.Lock()
c.subs = append(c.subs, sub)
c.Unlock()
return true
} | go | func (cs *clientStore) addSub(ID string, sub *subState) bool {
cs.RLock()
defer cs.RUnlock()
c := cs.clients[ID]
if c == nil {
return false
}
c.Lock()
c.subs = append(c.subs, sub)
c.Unlock()
return true
} | [
"func",
"(",
"cs",
"*",
"clientStore",
")",
"addSub",
"(",
"ID",
"string",
",",
"sub",
"*",
"subState",
")",
"bool",
"{",
"cs",
".",
"RLock",
"(",
")",
"\n",
"defer",
"cs",
".",
"RUnlock",
"(",
")",
"\n",
"c",
":=",
"cs",
".",
"clients",
"[",
"ID",
"]",
"\n",
"if",
"c",
"==",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"c",
".",
"Lock",
"(",
")",
"\n",
"c",
".",
"subs",
"=",
"append",
"(",
"c",
".",
"subs",
",",
"sub",
")",
"\n",
"c",
".",
"Unlock",
"(",
")",
"\n",
"return",
"true",
"\n",
"}"
] | // AddSub adds the subscription to the client identified by clientID
// and returns true only if the client has not been unregistered,
// otherwise returns false. | [
"AddSub",
"adds",
"the",
"subscription",
"to",
"the",
"client",
"identified",
"by",
"clientID",
"and",
"returns",
"true",
"only",
"if",
"the",
"client",
"has",
"not",
"been",
"unregistered",
"otherwise",
"returns",
"false",
"."
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/server/client.go#L241-L252 | train |
nats-io/nats-streaming-server | server/client.go | removeSub | func (cs *clientStore) removeSub(ID string, sub *subState) bool {
cs.RLock()
defer cs.RUnlock()
c := cs.clients[ID]
if c == nil {
return false
}
c.Lock()
removed := false
c.subs, removed = sub.deleteFromList(c.subs)
c.Unlock()
return removed
} | go | func (cs *clientStore) removeSub(ID string, sub *subState) bool {
cs.RLock()
defer cs.RUnlock()
c := cs.clients[ID]
if c == nil {
return false
}
c.Lock()
removed := false
c.subs, removed = sub.deleteFromList(c.subs)
c.Unlock()
return removed
} | [
"func",
"(",
"cs",
"*",
"clientStore",
")",
"removeSub",
"(",
"ID",
"string",
",",
"sub",
"*",
"subState",
")",
"bool",
"{",
"cs",
".",
"RLock",
"(",
")",
"\n",
"defer",
"cs",
".",
"RUnlock",
"(",
")",
"\n",
"c",
":=",
"cs",
".",
"clients",
"[",
"ID",
"]",
"\n",
"if",
"c",
"==",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"c",
".",
"Lock",
"(",
")",
"\n",
"removed",
":=",
"false",
"\n",
"c",
".",
"subs",
",",
"removed",
"=",
"sub",
".",
"deleteFromList",
"(",
"c",
".",
"subs",
")",
"\n",
"c",
".",
"Unlock",
"(",
")",
"\n",
"return",
"removed",
"\n",
"}"
] | // RemoveSub removes the subscription from the client identified by clientID
// and returns true only if the client has not been unregistered and that
// the subscription was found, otherwise returns false. | [
"RemoveSub",
"removes",
"the",
"subscription",
"from",
"the",
"client",
"identified",
"by",
"clientID",
"and",
"returns",
"true",
"only",
"if",
"the",
"client",
"has",
"not",
"been",
"unregistered",
"and",
"that",
"the",
"subscription",
"was",
"found",
"otherwise",
"returns",
"false",
"."
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/server/client.go#L257-L269 | train |
nats-io/nats-streaming-server | server/client.go | recoverClients | func (cs *clientStore) recoverClients(clients []*stores.Client) {
cs.Lock()
for _, sc := range clients {
client := &client{info: sc, subs: make([]*subState, 0, 4)}
cs.clients[client.info.ID] = client
if len(client.info.ConnID) > 0 {
cs.connIDs[string(client.info.ConnID)] = client
}
}
cs.Unlock()
} | go | func (cs *clientStore) recoverClients(clients []*stores.Client) {
cs.Lock()
for _, sc := range clients {
client := &client{info: sc, subs: make([]*subState, 0, 4)}
cs.clients[client.info.ID] = client
if len(client.info.ConnID) > 0 {
cs.connIDs[string(client.info.ConnID)] = client
}
}
cs.Unlock()
} | [
"func",
"(",
"cs",
"*",
"clientStore",
")",
"recoverClients",
"(",
"clients",
"[",
"]",
"*",
"stores",
".",
"Client",
")",
"{",
"cs",
".",
"Lock",
"(",
")",
"\n",
"for",
"_",
",",
"sc",
":=",
"range",
"clients",
"{",
"client",
":=",
"&",
"client",
"{",
"info",
":",
"sc",
",",
"subs",
":",
"make",
"(",
"[",
"]",
"*",
"subState",
",",
"0",
",",
"4",
")",
"}",
"\n",
"cs",
".",
"clients",
"[",
"client",
".",
"info",
".",
"ID",
"]",
"=",
"client",
"\n",
"if",
"len",
"(",
"client",
".",
"info",
".",
"ConnID",
")",
">",
"0",
"{",
"cs",
".",
"connIDs",
"[",
"string",
"(",
"client",
".",
"info",
".",
"ConnID",
")",
"]",
"=",
"client",
"\n",
"}",
"\n",
"}",
"\n",
"cs",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // recoverClients recreates the content of the client store based on clients
// information recovered from the Store. | [
"recoverClients",
"recreates",
"the",
"content",
"of",
"the",
"client",
"store",
"based",
"on",
"clients",
"information",
"recovered",
"from",
"the",
"Store",
"."
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/server/client.go#L273-L283 | train |
nats-io/nats-streaming-server | server/client.go | setClientHB | func (cs *clientStore) setClientHB(ID string, interval time.Duration, f func()) {
cs.RLock()
defer cs.RUnlock()
c := cs.clients[ID]
if c == nil {
return
}
c.Lock()
if c.hbt == nil {
c.hbt = time.AfterFunc(interval, f)
}
c.Unlock()
} | go | func (cs *clientStore) setClientHB(ID string, interval time.Duration, f func()) {
cs.RLock()
defer cs.RUnlock()
c := cs.clients[ID]
if c == nil {
return
}
c.Lock()
if c.hbt == nil {
c.hbt = time.AfterFunc(interval, f)
}
c.Unlock()
} | [
"func",
"(",
"cs",
"*",
"clientStore",
")",
"setClientHB",
"(",
"ID",
"string",
",",
"interval",
"time",
".",
"Duration",
",",
"f",
"func",
"(",
")",
")",
"{",
"cs",
".",
"RLock",
"(",
")",
"\n",
"defer",
"cs",
".",
"RUnlock",
"(",
")",
"\n",
"c",
":=",
"cs",
".",
"clients",
"[",
"ID",
"]",
"\n",
"if",
"c",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"c",
".",
"Lock",
"(",
")",
"\n",
"if",
"c",
".",
"hbt",
"==",
"nil",
"{",
"c",
".",
"hbt",
"=",
"time",
".",
"AfterFunc",
"(",
"interval",
",",
"f",
")",
"\n",
"}",
"\n",
"c",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // setClientHB will lookup the client `ID` and, if present, set the
// client's timer with the given interval and function. | [
"setClientHB",
"will",
"lookup",
"the",
"client",
"ID",
"and",
"if",
"present",
"set",
"the",
"client",
"s",
"timer",
"with",
"the",
"given",
"interval",
"and",
"function",
"."
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/server/client.go#L287-L299 | train |
nats-io/nats-streaming-server | server/client.go | removeClientHB | func (cs *clientStore) removeClientHB(c *client) {
if c == nil {
return
}
c.Lock()
if c.hbt != nil {
c.hbt.Stop()
c.hbt = nil
}
c.Unlock()
} | go | func (cs *clientStore) removeClientHB(c *client) {
if c == nil {
return
}
c.Lock()
if c.hbt != nil {
c.hbt.Stop()
c.hbt = nil
}
c.Unlock()
} | [
"func",
"(",
"cs",
"*",
"clientStore",
")",
"removeClientHB",
"(",
"c",
"*",
"client",
")",
"{",
"if",
"c",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"c",
".",
"Lock",
"(",
")",
"\n",
"if",
"c",
".",
"hbt",
"!=",
"nil",
"{",
"c",
".",
"hbt",
".",
"Stop",
"(",
")",
"\n",
"c",
".",
"hbt",
"=",
"nil",
"\n",
"}",
"\n",
"c",
".",
"Unlock",
"(",
")",
"\n",
"}"
] | // removeClientHB will stop and remove the client's heartbeat timer, if
// present. | [
"removeClientHB",
"will",
"stop",
"and",
"remove",
"the",
"client",
"s",
"heartbeat",
"timer",
"if",
"present",
"."
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/server/client.go#L303-L313 | train |
nats-io/nats-streaming-server | server/client.go | count | func (cs *clientStore) count() int {
cs.RLock()
total := len(cs.clients)
cs.RUnlock()
return total
} | go | func (cs *clientStore) count() int {
cs.RLock()
total := len(cs.clients)
cs.RUnlock()
return total
} | [
"func",
"(",
"cs",
"*",
"clientStore",
")",
"count",
"(",
")",
"int",
"{",
"cs",
".",
"RLock",
"(",
")",
"\n",
"total",
":=",
"len",
"(",
"cs",
".",
"clients",
")",
"\n",
"cs",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"total",
"\n",
"}"
] | // count returns the number of registered clients | [
"count",
"returns",
"the",
"number",
"of",
"registered",
"clients"
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/server/client.go#L329-L334 | train |
nats-io/nats-streaming-server | server/clustering.go | shutdown | func (r *raftNode) shutdown() error {
r.Lock()
if r.closed {
r.Unlock()
return nil
}
r.closed = true
r.Unlock()
if r.Raft != nil {
if err := r.Raft.Shutdown().Error(); err != nil {
return err
}
}
if r.transport != nil {
if err := r.transport.Close(); err != nil {
return err
}
}
if r.store != nil {
if err := r.store.Close(); err != nil {
return err
}
}
if r.joinSub != nil {
if err := r.joinSub.Unsubscribe(); err != nil {
return err
}
}
if r.logInput != nil {
if err := r.logInput.Close(); err != nil {
return err
}
}
return nil
} | go | func (r *raftNode) shutdown() error {
r.Lock()
if r.closed {
r.Unlock()
return nil
}
r.closed = true
r.Unlock()
if r.Raft != nil {
if err := r.Raft.Shutdown().Error(); err != nil {
return err
}
}
if r.transport != nil {
if err := r.transport.Close(); err != nil {
return err
}
}
if r.store != nil {
if err := r.store.Close(); err != nil {
return err
}
}
if r.joinSub != nil {
if err := r.joinSub.Unsubscribe(); err != nil {
return err
}
}
if r.logInput != nil {
if err := r.logInput.Close(); err != nil {
return err
}
}
return nil
} | [
"func",
"(",
"r",
"*",
"raftNode",
")",
"shutdown",
"(",
")",
"error",
"{",
"r",
".",
"Lock",
"(",
")",
"\n",
"if",
"r",
".",
"closed",
"{",
"r",
".",
"Unlock",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"r",
".",
"closed",
"=",
"true",
"\n",
"r",
".",
"Unlock",
"(",
")",
"\n",
"if",
"r",
".",
"Raft",
"!=",
"nil",
"{",
"if",
"err",
":=",
"r",
".",
"Raft",
".",
"Shutdown",
"(",
")",
".",
"Error",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"r",
".",
"transport",
"!=",
"nil",
"{",
"if",
"err",
":=",
"r",
".",
"transport",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"r",
".",
"store",
"!=",
"nil",
"{",
"if",
"err",
":=",
"r",
".",
"store",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"r",
".",
"joinSub",
"!=",
"nil",
"{",
"if",
"err",
":=",
"r",
".",
"joinSub",
".",
"Unsubscribe",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"r",
".",
"logInput",
"!=",
"nil",
"{",
"if",
"err",
":=",
"r",
".",
"logInput",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // shutdown attempts to stop the Raft node. | [
"shutdown",
"attempts",
"to",
"stop",
"the",
"Raft",
"node",
"."
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/server/clustering.go#L96-L130 | train |
nats-io/nats-streaming-server | server/clustering.go | createServerRaftNode | func (s *StanServer) createServerRaftNode(hasStreamingState bool) error {
var (
name = s.info.ClusterID
addr = s.getClusteringAddr(name)
existingState, err = s.createRaftNode(name)
)
if err != nil {
return err
}
if !existingState && hasStreamingState {
return fmt.Errorf("streaming state was recovered but cluster log path %q is empty", s.opts.Clustering.RaftLogPath)
}
node := s.raft
// Bootstrap if there is no previous state and we are starting this node as
// a seed or a cluster configuration is provided.
bootstrap := !existingState && (s.opts.Clustering.Bootstrap || len(s.opts.Clustering.Peers) > 0)
if bootstrap {
if err := s.bootstrapCluster(name, node.Raft); err != nil {
node.shutdown()
return err
}
} else if !existingState {
// Attempt to join the cluster if we're not bootstrapping.
req, err := (&spb.RaftJoinRequest{NodeID: s.opts.Clustering.NodeID, NodeAddr: addr}).Marshal()
if err != nil {
panic(err)
}
var (
joined = false
resp = &spb.RaftJoinResponse{}
)
s.log.Debugf("Joining Raft group %s", name)
// Attempt to join up to 5 times before giving up.
for i := 0; i < 5; i++ {
r, err := s.ncr.Request(fmt.Sprintf("%s.%s.join", defaultRaftPrefix, name), req, joinRaftGroupTimeout)
if err != nil {
time.Sleep(20 * time.Millisecond)
continue
}
if err := resp.Unmarshal(r.Data); err != nil {
time.Sleep(20 * time.Millisecond)
continue
}
if resp.Error != "" {
time.Sleep(20 * time.Millisecond)
continue
}
joined = true
break
}
if !joined {
node.shutdown()
return fmt.Errorf("failed to join Raft group %s", name)
}
}
if s.opts.Clustering.Bootstrap {
// If node is started with bootstrap, regardless if state exist or not, try to
// detect (and report) other nodes in same cluster started with bootstrap=true.
s.wg.Add(1)
go func() {
s.detectBootstrapMisconfig(name)
s.wg.Done()
}()
}
return nil
} | go | func (s *StanServer) createServerRaftNode(hasStreamingState bool) error {
var (
name = s.info.ClusterID
addr = s.getClusteringAddr(name)
existingState, err = s.createRaftNode(name)
)
if err != nil {
return err
}
if !existingState && hasStreamingState {
return fmt.Errorf("streaming state was recovered but cluster log path %q is empty", s.opts.Clustering.RaftLogPath)
}
node := s.raft
// Bootstrap if there is no previous state and we are starting this node as
// a seed or a cluster configuration is provided.
bootstrap := !existingState && (s.opts.Clustering.Bootstrap || len(s.opts.Clustering.Peers) > 0)
if bootstrap {
if err := s.bootstrapCluster(name, node.Raft); err != nil {
node.shutdown()
return err
}
} else if !existingState {
// Attempt to join the cluster if we're not bootstrapping.
req, err := (&spb.RaftJoinRequest{NodeID: s.opts.Clustering.NodeID, NodeAddr: addr}).Marshal()
if err != nil {
panic(err)
}
var (
joined = false
resp = &spb.RaftJoinResponse{}
)
s.log.Debugf("Joining Raft group %s", name)
// Attempt to join up to 5 times before giving up.
for i := 0; i < 5; i++ {
r, err := s.ncr.Request(fmt.Sprintf("%s.%s.join", defaultRaftPrefix, name), req, joinRaftGroupTimeout)
if err != nil {
time.Sleep(20 * time.Millisecond)
continue
}
if err := resp.Unmarshal(r.Data); err != nil {
time.Sleep(20 * time.Millisecond)
continue
}
if resp.Error != "" {
time.Sleep(20 * time.Millisecond)
continue
}
joined = true
break
}
if !joined {
node.shutdown()
return fmt.Errorf("failed to join Raft group %s", name)
}
}
if s.opts.Clustering.Bootstrap {
// If node is started with bootstrap, regardless if state exist or not, try to
// detect (and report) other nodes in same cluster started with bootstrap=true.
s.wg.Add(1)
go func() {
s.detectBootstrapMisconfig(name)
s.wg.Done()
}()
}
return nil
} | [
"func",
"(",
"s",
"*",
"StanServer",
")",
"createServerRaftNode",
"(",
"hasStreamingState",
"bool",
")",
"error",
"{",
"var",
"(",
"name",
"=",
"s",
".",
"info",
".",
"ClusterID",
"\n",
"addr",
"=",
"s",
".",
"getClusteringAddr",
"(",
"name",
")",
"\n",
"existingState",
",",
"err",
"=",
"s",
".",
"createRaftNode",
"(",
"name",
")",
"\n",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"!",
"existingState",
"&&",
"hasStreamingState",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"streaming state was recovered but cluster log path %q is empty\"",
",",
"s",
".",
"opts",
".",
"Clustering",
".",
"RaftLogPath",
")",
"\n",
"}",
"\n",
"node",
":=",
"s",
".",
"raft",
"\n",
"bootstrap",
":=",
"!",
"existingState",
"&&",
"(",
"s",
".",
"opts",
".",
"Clustering",
".",
"Bootstrap",
"||",
"len",
"(",
"s",
".",
"opts",
".",
"Clustering",
".",
"Peers",
")",
">",
"0",
")",
"\n",
"if",
"bootstrap",
"{",
"if",
"err",
":=",
"s",
".",
"bootstrapCluster",
"(",
"name",
",",
"node",
".",
"Raft",
")",
";",
"err",
"!=",
"nil",
"{",
"node",
".",
"shutdown",
"(",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"}",
"else",
"if",
"!",
"existingState",
"{",
"req",
",",
"err",
":=",
"(",
"&",
"spb",
".",
"RaftJoinRequest",
"{",
"NodeID",
":",
"s",
".",
"opts",
".",
"Clustering",
".",
"NodeID",
",",
"NodeAddr",
":",
"addr",
"}",
")",
".",
"Marshal",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"var",
"(",
"joined",
"=",
"false",
"\n",
"resp",
"=",
"&",
"spb",
".",
"RaftJoinResponse",
"{",
"}",
"\n",
")",
"\n",
"s",
".",
"log",
".",
"Debugf",
"(",
"\"Joining Raft group %s\"",
",",
"name",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"5",
";",
"i",
"++",
"{",
"r",
",",
"err",
":=",
"s",
".",
"ncr",
".",
"Request",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"%s.%s.join\"",
",",
"defaultRaftPrefix",
",",
"name",
")",
",",
"req",
",",
"joinRaftGroupTimeout",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"time",
".",
"Sleep",
"(",
"20",
"*",
"time",
".",
"Millisecond",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"if",
"err",
":=",
"resp",
".",
"Unmarshal",
"(",
"r",
".",
"Data",
")",
";",
"err",
"!=",
"nil",
"{",
"time",
".",
"Sleep",
"(",
"20",
"*",
"time",
".",
"Millisecond",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"if",
"resp",
".",
"Error",
"!=",
"\"\"",
"{",
"time",
".",
"Sleep",
"(",
"20",
"*",
"time",
".",
"Millisecond",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"joined",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"if",
"!",
"joined",
"{",
"node",
".",
"shutdown",
"(",
")",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"failed to join Raft group %s\"",
",",
"name",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"s",
".",
"opts",
".",
"Clustering",
".",
"Bootstrap",
"{",
"s",
".",
"wg",
".",
"Add",
"(",
"1",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"s",
".",
"detectBootstrapMisconfig",
"(",
"name",
")",
"\n",
"s",
".",
"wg",
".",
"Done",
"(",
")",
"\n",
"}",
"(",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // createRaftNode creates and starts a new Raft node. | [
"createRaftNode",
"creates",
"and",
"starts",
"a",
"new",
"Raft",
"node",
"."
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/server/clustering.go#L133-L199 | train |
nats-io/nats-streaming-server | server/clustering.go | bootstrapCluster | func (s *StanServer) bootstrapCluster(name string, node *raft.Raft) error {
var (
addr = s.getClusteringAddr(name)
// Include ourself in the cluster.
servers = []raft.Server{raft.Server{
ID: raft.ServerID(s.opts.Clustering.NodeID),
Address: raft.ServerAddress(addr),
}}
)
if len(s.opts.Clustering.Peers) > 0 {
// Bootstrap using provided cluster configuration.
s.log.Debugf("Bootstrapping Raft group %s using provided configuration", name)
for _, peer := range s.opts.Clustering.Peers {
servers = append(servers, raft.Server{
ID: raft.ServerID(peer),
Address: raft.ServerAddress(s.getClusteringPeerAddr(name, peer)),
})
}
} else {
// Bootstrap as a seed node.
s.log.Debugf("Bootstrapping Raft group %s as seed node", name)
}
config := raft.Configuration{Servers: servers}
return node.BootstrapCluster(config).Error()
} | go | func (s *StanServer) bootstrapCluster(name string, node *raft.Raft) error {
var (
addr = s.getClusteringAddr(name)
// Include ourself in the cluster.
servers = []raft.Server{raft.Server{
ID: raft.ServerID(s.opts.Clustering.NodeID),
Address: raft.ServerAddress(addr),
}}
)
if len(s.opts.Clustering.Peers) > 0 {
// Bootstrap using provided cluster configuration.
s.log.Debugf("Bootstrapping Raft group %s using provided configuration", name)
for _, peer := range s.opts.Clustering.Peers {
servers = append(servers, raft.Server{
ID: raft.ServerID(peer),
Address: raft.ServerAddress(s.getClusteringPeerAddr(name, peer)),
})
}
} else {
// Bootstrap as a seed node.
s.log.Debugf("Bootstrapping Raft group %s as seed node", name)
}
config := raft.Configuration{Servers: servers}
return node.BootstrapCluster(config).Error()
} | [
"func",
"(",
"s",
"*",
"StanServer",
")",
"bootstrapCluster",
"(",
"name",
"string",
",",
"node",
"*",
"raft",
".",
"Raft",
")",
"error",
"{",
"var",
"(",
"addr",
"=",
"s",
".",
"getClusteringAddr",
"(",
"name",
")",
"\n",
"servers",
"=",
"[",
"]",
"raft",
".",
"Server",
"{",
"raft",
".",
"Server",
"{",
"ID",
":",
"raft",
".",
"ServerID",
"(",
"s",
".",
"opts",
".",
"Clustering",
".",
"NodeID",
")",
",",
"Address",
":",
"raft",
".",
"ServerAddress",
"(",
"addr",
")",
",",
"}",
"}",
"\n",
")",
"\n",
"if",
"len",
"(",
"s",
".",
"opts",
".",
"Clustering",
".",
"Peers",
")",
">",
"0",
"{",
"s",
".",
"log",
".",
"Debugf",
"(",
"\"Bootstrapping Raft group %s using provided configuration\"",
",",
"name",
")",
"\n",
"for",
"_",
",",
"peer",
":=",
"range",
"s",
".",
"opts",
".",
"Clustering",
".",
"Peers",
"{",
"servers",
"=",
"append",
"(",
"servers",
",",
"raft",
".",
"Server",
"{",
"ID",
":",
"raft",
".",
"ServerID",
"(",
"peer",
")",
",",
"Address",
":",
"raft",
".",
"ServerAddress",
"(",
"s",
".",
"getClusteringPeerAddr",
"(",
"name",
",",
"peer",
")",
")",
",",
"}",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"s",
".",
"log",
".",
"Debugf",
"(",
"\"Bootstrapping Raft group %s as seed node\"",
",",
"name",
")",
"\n",
"}",
"\n",
"config",
":=",
"raft",
".",
"Configuration",
"{",
"Servers",
":",
"servers",
"}",
"\n",
"return",
"node",
".",
"BootstrapCluster",
"(",
"config",
")",
".",
"Error",
"(",
")",
"\n",
"}"
] | // bootstrapCluster bootstraps the node for the provided Raft group either as a
// seed node or with the given peer configuration, depending on configuration
// and with the latter taking precedence. | [
"bootstrapCluster",
"bootstraps",
"the",
"node",
"for",
"the",
"provided",
"Raft",
"group",
"either",
"as",
"a",
"seed",
"node",
"or",
"with",
"the",
"given",
"peer",
"configuration",
"depending",
"on",
"configuration",
"and",
"with",
"the",
"latter",
"taking",
"precedence",
"."
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/server/clustering.go#L420-L444 | train |
nats-io/nats-streaming-server | server/clustering.go | Apply | func (r *raftFSM) Apply(l *raft.Log) interface{} {
s := r.server
op := &spb.RaftOperation{}
if err := op.Unmarshal(l.Data); err != nil {
panic(err)
}
switch op.OpType {
case spb.RaftOperation_Publish:
// Message replication.
var (
c *channel
err error
lastSeq uint64
)
for _, msg := range op.PublishBatch.Messages {
// This is a batch for a given channel, so lookup channel once.
if c == nil {
c, err = s.lookupOrCreateChannel(msg.Subject)
// That should not be the case, but if it happens,
// just bail out.
if err == ErrChanDelInProgress {
return nil
}
lastSeq, err = c.store.Msgs.LastSequence()
}
if err == nil && lastSeq < msg.Sequence-1 {
err = s.raft.fsm.restoreMsgsFromSnapshot(c, lastSeq+1, msg.Sequence-1)
}
if err == nil {
_, err = c.store.Msgs.Store(msg)
}
if err != nil {
return fmt.Errorf("failed to store replicated message %d on channel %s: %v",
msg.Sequence, msg.Subject, err)
}
}
return nil
case spb.RaftOperation_Connect:
// Client connection create replication.
return s.processConnect(op.ClientConnect.Request, op.ClientConnect.Refresh)
case spb.RaftOperation_Disconnect:
// Client connection close replication.
return s.closeClient(op.ClientDisconnect.ClientID)
case spb.RaftOperation_Subscribe:
// Subscription replication.
sub, err := s.processSub(nil, op.Sub.Request, op.Sub.AckInbox, op.Sub.ID)
return &replicatedSub{sub: sub, err: err}
case spb.RaftOperation_RemoveSubscription:
fallthrough
case spb.RaftOperation_CloseSubscription:
// Close/Unsub subscription replication.
isSubClose := op.OpType == spb.RaftOperation_CloseSubscription
s.closeMu.Lock()
err := s.unsubscribe(op.Unsub, isSubClose)
s.closeMu.Unlock()
return err
case spb.RaftOperation_SendAndAck:
if !s.isLeader() {
s.processReplicatedSendAndAck(op.SubSentAck)
}
return nil
case spb.RaftOperation_DeleteChannel:
s.processDeleteChannel(op.Channel)
return nil
default:
panic(fmt.Sprintf("unknown op type %s", op.OpType))
}
} | go | func (r *raftFSM) Apply(l *raft.Log) interface{} {
s := r.server
op := &spb.RaftOperation{}
if err := op.Unmarshal(l.Data); err != nil {
panic(err)
}
switch op.OpType {
case spb.RaftOperation_Publish:
// Message replication.
var (
c *channel
err error
lastSeq uint64
)
for _, msg := range op.PublishBatch.Messages {
// This is a batch for a given channel, so lookup channel once.
if c == nil {
c, err = s.lookupOrCreateChannel(msg.Subject)
// That should not be the case, but if it happens,
// just bail out.
if err == ErrChanDelInProgress {
return nil
}
lastSeq, err = c.store.Msgs.LastSequence()
}
if err == nil && lastSeq < msg.Sequence-1 {
err = s.raft.fsm.restoreMsgsFromSnapshot(c, lastSeq+1, msg.Sequence-1)
}
if err == nil {
_, err = c.store.Msgs.Store(msg)
}
if err != nil {
return fmt.Errorf("failed to store replicated message %d on channel %s: %v",
msg.Sequence, msg.Subject, err)
}
}
return nil
case spb.RaftOperation_Connect:
// Client connection create replication.
return s.processConnect(op.ClientConnect.Request, op.ClientConnect.Refresh)
case spb.RaftOperation_Disconnect:
// Client connection close replication.
return s.closeClient(op.ClientDisconnect.ClientID)
case spb.RaftOperation_Subscribe:
// Subscription replication.
sub, err := s.processSub(nil, op.Sub.Request, op.Sub.AckInbox, op.Sub.ID)
return &replicatedSub{sub: sub, err: err}
case spb.RaftOperation_RemoveSubscription:
fallthrough
case spb.RaftOperation_CloseSubscription:
// Close/Unsub subscription replication.
isSubClose := op.OpType == spb.RaftOperation_CloseSubscription
s.closeMu.Lock()
err := s.unsubscribe(op.Unsub, isSubClose)
s.closeMu.Unlock()
return err
case spb.RaftOperation_SendAndAck:
if !s.isLeader() {
s.processReplicatedSendAndAck(op.SubSentAck)
}
return nil
case spb.RaftOperation_DeleteChannel:
s.processDeleteChannel(op.Channel)
return nil
default:
panic(fmt.Sprintf("unknown op type %s", op.OpType))
}
} | [
"func",
"(",
"r",
"*",
"raftFSM",
")",
"Apply",
"(",
"l",
"*",
"raft",
".",
"Log",
")",
"interface",
"{",
"}",
"{",
"s",
":=",
"r",
".",
"server",
"\n",
"op",
":=",
"&",
"spb",
".",
"RaftOperation",
"{",
"}",
"\n",
"if",
"err",
":=",
"op",
".",
"Unmarshal",
"(",
"l",
".",
"Data",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"switch",
"op",
".",
"OpType",
"{",
"case",
"spb",
".",
"RaftOperation_Publish",
":",
"var",
"(",
"c",
"*",
"channel",
"\n",
"err",
"error",
"\n",
"lastSeq",
"uint64",
"\n",
")",
"\n",
"for",
"_",
",",
"msg",
":=",
"range",
"op",
".",
"PublishBatch",
".",
"Messages",
"{",
"if",
"c",
"==",
"nil",
"{",
"c",
",",
"err",
"=",
"s",
".",
"lookupOrCreateChannel",
"(",
"msg",
".",
"Subject",
")",
"\n",
"if",
"err",
"==",
"ErrChanDelInProgress",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"lastSeq",
",",
"err",
"=",
"c",
".",
"store",
".",
"Msgs",
".",
"LastSequence",
"(",
")",
"\n",
"}",
"\n",
"if",
"err",
"==",
"nil",
"&&",
"lastSeq",
"<",
"msg",
".",
"Sequence",
"-",
"1",
"{",
"err",
"=",
"s",
".",
"raft",
".",
"fsm",
".",
"restoreMsgsFromSnapshot",
"(",
"c",
",",
"lastSeq",
"+",
"1",
",",
"msg",
".",
"Sequence",
"-",
"1",
")",
"\n",
"}",
"\n",
"if",
"err",
"==",
"nil",
"{",
"_",
",",
"err",
"=",
"c",
".",
"store",
".",
"Msgs",
".",
"Store",
"(",
"msg",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"failed to store replicated message %d on channel %s: %v\"",
",",
"msg",
".",
"Sequence",
",",
"msg",
".",
"Subject",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"case",
"spb",
".",
"RaftOperation_Connect",
":",
"return",
"s",
".",
"processConnect",
"(",
"op",
".",
"ClientConnect",
".",
"Request",
",",
"op",
".",
"ClientConnect",
".",
"Refresh",
")",
"\n",
"case",
"spb",
".",
"RaftOperation_Disconnect",
":",
"return",
"s",
".",
"closeClient",
"(",
"op",
".",
"ClientDisconnect",
".",
"ClientID",
")",
"\n",
"case",
"spb",
".",
"RaftOperation_Subscribe",
":",
"sub",
",",
"err",
":=",
"s",
".",
"processSub",
"(",
"nil",
",",
"op",
".",
"Sub",
".",
"Request",
",",
"op",
".",
"Sub",
".",
"AckInbox",
",",
"op",
".",
"Sub",
".",
"ID",
")",
"\n",
"return",
"&",
"replicatedSub",
"{",
"sub",
":",
"sub",
",",
"err",
":",
"err",
"}",
"\n",
"case",
"spb",
".",
"RaftOperation_RemoveSubscription",
":",
"fallthrough",
"\n",
"case",
"spb",
".",
"RaftOperation_CloseSubscription",
":",
"isSubClose",
":=",
"op",
".",
"OpType",
"==",
"spb",
".",
"RaftOperation_CloseSubscription",
"\n",
"s",
".",
"closeMu",
".",
"Lock",
"(",
")",
"\n",
"err",
":=",
"s",
".",
"unsubscribe",
"(",
"op",
".",
"Unsub",
",",
"isSubClose",
")",
"\n",
"s",
".",
"closeMu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"err",
"\n",
"case",
"spb",
".",
"RaftOperation_SendAndAck",
":",
"if",
"!",
"s",
".",
"isLeader",
"(",
")",
"{",
"s",
".",
"processReplicatedSendAndAck",
"(",
"op",
".",
"SubSentAck",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"case",
"spb",
".",
"RaftOperation_DeleteChannel",
":",
"s",
".",
"processDeleteChannel",
"(",
"op",
".",
"Channel",
")",
"\n",
"return",
"nil",
"\n",
"default",
":",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"unknown op type %s\"",
",",
"op",
".",
"OpType",
")",
")",
"\n",
"}",
"\n",
"}"
] | // Apply log is invoked once a log entry is committed.
// It returns a value which will be made available in the
// ApplyFuture returned by Raft.Apply method if that
// method was called on the same Raft node as the FSM. | [
"Apply",
"log",
"is",
"invoked",
"once",
"a",
"log",
"entry",
"is",
"committed",
".",
"It",
"returns",
"a",
"value",
"which",
"will",
"be",
"made",
"available",
"in",
"the",
"ApplyFuture",
"returned",
"by",
"Raft",
".",
"Apply",
"method",
"if",
"that",
"method",
"was",
"called",
"on",
"the",
"same",
"Raft",
"node",
"as",
"the",
"FSM",
"."
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/server/clustering.go#L458-L525 | train |
nats-io/nats-streaming-server | util/util.go | EnsureBufBigEnough | func EnsureBufBigEnough(buf []byte, needed int) []byte {
if buf == nil {
return make([]byte, needed)
} else if needed > len(buf) {
return make([]byte, int(float32(needed)*1.1))
}
return buf
} | go | func EnsureBufBigEnough(buf []byte, needed int) []byte {
if buf == nil {
return make([]byte, needed)
} else if needed > len(buf) {
return make([]byte, int(float32(needed)*1.1))
}
return buf
} | [
"func",
"EnsureBufBigEnough",
"(",
"buf",
"[",
"]",
"byte",
",",
"needed",
"int",
")",
"[",
"]",
"byte",
"{",
"if",
"buf",
"==",
"nil",
"{",
"return",
"make",
"(",
"[",
"]",
"byte",
",",
"needed",
")",
"\n",
"}",
"else",
"if",
"needed",
">",
"len",
"(",
"buf",
")",
"{",
"return",
"make",
"(",
"[",
"]",
"byte",
",",
"int",
"(",
"float32",
"(",
"needed",
")",
"*",
"1.1",
")",
")",
"\n",
"}",
"\n",
"return",
"buf",
"\n",
"}"
] | // EnsureBufBigEnough checks that given buffer is big enough to hold 'needed'
// bytes, otherwise returns a buffer of a size of at least 'needed' bytes. | [
"EnsureBufBigEnough",
"checks",
"that",
"given",
"buffer",
"is",
"big",
"enough",
"to",
"hold",
"needed",
"bytes",
"otherwise",
"returns",
"a",
"buffer",
"of",
"a",
"size",
"of",
"at",
"least",
"needed",
"bytes",
"."
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/util/util.go#L109-L116 | train |
nats-io/nats-streaming-server | util/util.go | CloseFile | func CloseFile(err error, f io.Closer) error {
if lerr := f.Close(); lerr != nil && err == nil {
err = lerr
}
return err
} | go | func CloseFile(err error, f io.Closer) error {
if lerr := f.Close(); lerr != nil && err == nil {
err = lerr
}
return err
} | [
"func",
"CloseFile",
"(",
"err",
"error",
",",
"f",
"io",
".",
"Closer",
")",
"error",
"{",
"if",
"lerr",
":=",
"f",
".",
"Close",
"(",
")",
";",
"lerr",
"!=",
"nil",
"&&",
"err",
"==",
"nil",
"{",
"err",
"=",
"lerr",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] | // CloseFile closes the given file and report the possible error only
// if the given error `err` is not already set. | [
"CloseFile",
"closes",
"the",
"given",
"file",
"and",
"report",
"the",
"possible",
"error",
"only",
"if",
"the",
"given",
"error",
"err",
"is",
"not",
"already",
"set",
"."
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/util/util.go#L144-L149 | train |
nats-io/nats-streaming-server | util/util.go | FriendlyBytes | func FriendlyBytes(bytes int64) string {
fbytes := float64(bytes)
base := 1024
pre := []string{"K", "M", "G", "T", "P", "E"}
if fbytes < float64(base) {
return fmt.Sprintf("%v B", fbytes)
}
exp := int(math.Log(fbytes) / math.Log(float64(base)))
index := exp - 1
return fmt.Sprintf("%.2f %sB", fbytes/math.Pow(float64(base), float64(exp)), pre[index])
} | go | func FriendlyBytes(bytes int64) string {
fbytes := float64(bytes)
base := 1024
pre := []string{"K", "M", "G", "T", "P", "E"}
if fbytes < float64(base) {
return fmt.Sprintf("%v B", fbytes)
}
exp := int(math.Log(fbytes) / math.Log(float64(base)))
index := exp - 1
return fmt.Sprintf("%.2f %sB", fbytes/math.Pow(float64(base), float64(exp)), pre[index])
} | [
"func",
"FriendlyBytes",
"(",
"bytes",
"int64",
")",
"string",
"{",
"fbytes",
":=",
"float64",
"(",
"bytes",
")",
"\n",
"base",
":=",
"1024",
"\n",
"pre",
":=",
"[",
"]",
"string",
"{",
"\"K\"",
",",
"\"M\"",
",",
"\"G\"",
",",
"\"T\"",
",",
"\"P\"",
",",
"\"E\"",
"}",
"\n",
"if",
"fbytes",
"<",
"float64",
"(",
"base",
")",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"%v B\"",
",",
"fbytes",
")",
"\n",
"}",
"\n",
"exp",
":=",
"int",
"(",
"math",
".",
"Log",
"(",
"fbytes",
")",
"/",
"math",
".",
"Log",
"(",
"float64",
"(",
"base",
")",
")",
")",
"\n",
"index",
":=",
"exp",
"-",
"1",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"%.2f %sB\"",
",",
"fbytes",
"/",
"math",
".",
"Pow",
"(",
"float64",
"(",
"base",
")",
",",
"float64",
"(",
"exp",
")",
")",
",",
"pre",
"[",
"index",
"]",
")",
"\n",
"}"
] | // FriendlyBytes returns a string with the given bytes int64
// represented as a size, such as 1KB, 10MB, etc... | [
"FriendlyBytes",
"returns",
"a",
"string",
"with",
"the",
"given",
"bytes",
"int64",
"represented",
"as",
"a",
"size",
"such",
"as",
"1KB",
"10MB",
"etc",
"..."
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/util/util.go#L207-L217 | train |
nats-io/nats-streaming-server | stores/cryptostore.go | Encrypt | func (s *EDStore) Encrypt(pbuf *[]byte, data []byte) ([]byte, error) {
var buf []byte
// If given a buffer, use that one
if pbuf != nil {
buf = *pbuf
}
// Make sure size is ok, expand if necessary
buf = util.EnsureBufBigEnough(buf, 1+s.nonceSize+s.cryptoOverhead+len(data))
// If buffer was passed, update the reference
if pbuf != nil {
*pbuf = buf
}
buf[0] = s.code
copy(buf[1:], s.nonce)
copy(buf[1+s.nonceSize:], data)
dst := buf[1+s.nonceSize : 1+s.nonceSize+len(data)]
ed := s.gcm.Seal(dst[:0], s.nonce, dst, nil)
for i := s.nonceSize - 1; i >= 0; i-- {
s.nonce[i]++
if s.nonce[i] != 0 {
break
}
}
return buf[:1+s.nonceSize+len(ed)], nil
} | go | func (s *EDStore) Encrypt(pbuf *[]byte, data []byte) ([]byte, error) {
var buf []byte
// If given a buffer, use that one
if pbuf != nil {
buf = *pbuf
}
// Make sure size is ok, expand if necessary
buf = util.EnsureBufBigEnough(buf, 1+s.nonceSize+s.cryptoOverhead+len(data))
// If buffer was passed, update the reference
if pbuf != nil {
*pbuf = buf
}
buf[0] = s.code
copy(buf[1:], s.nonce)
copy(buf[1+s.nonceSize:], data)
dst := buf[1+s.nonceSize : 1+s.nonceSize+len(data)]
ed := s.gcm.Seal(dst[:0], s.nonce, dst, nil)
for i := s.nonceSize - 1; i >= 0; i-- {
s.nonce[i]++
if s.nonce[i] != 0 {
break
}
}
return buf[:1+s.nonceSize+len(ed)], nil
} | [
"func",
"(",
"s",
"*",
"EDStore",
")",
"Encrypt",
"(",
"pbuf",
"*",
"[",
"]",
"byte",
",",
"data",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"var",
"buf",
"[",
"]",
"byte",
"\n",
"if",
"pbuf",
"!=",
"nil",
"{",
"buf",
"=",
"*",
"pbuf",
"\n",
"}",
"\n",
"buf",
"=",
"util",
".",
"EnsureBufBigEnough",
"(",
"buf",
",",
"1",
"+",
"s",
".",
"nonceSize",
"+",
"s",
".",
"cryptoOverhead",
"+",
"len",
"(",
"data",
")",
")",
"\n",
"if",
"pbuf",
"!=",
"nil",
"{",
"*",
"pbuf",
"=",
"buf",
"\n",
"}",
"\n",
"buf",
"[",
"0",
"]",
"=",
"s",
".",
"code",
"\n",
"copy",
"(",
"buf",
"[",
"1",
":",
"]",
",",
"s",
".",
"nonce",
")",
"\n",
"copy",
"(",
"buf",
"[",
"1",
"+",
"s",
".",
"nonceSize",
":",
"]",
",",
"data",
")",
"\n",
"dst",
":=",
"buf",
"[",
"1",
"+",
"s",
".",
"nonceSize",
":",
"1",
"+",
"s",
".",
"nonceSize",
"+",
"len",
"(",
"data",
")",
"]",
"\n",
"ed",
":=",
"s",
".",
"gcm",
".",
"Seal",
"(",
"dst",
"[",
":",
"0",
"]",
",",
"s",
".",
"nonce",
",",
"dst",
",",
"nil",
")",
"\n",
"for",
"i",
":=",
"s",
".",
"nonceSize",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
"{",
"s",
".",
"nonce",
"[",
"i",
"]",
"++",
"\n",
"if",
"s",
".",
"nonce",
"[",
"i",
"]",
"!=",
"0",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"buf",
"[",
":",
"1",
"+",
"s",
".",
"nonceSize",
"+",
"len",
"(",
"ed",
")",
"]",
",",
"nil",
"\n",
"}"
] | // Encrypt returns the encrypted data or an error | [
"Encrypt",
"returns",
"the",
"encrypted",
"data",
"or",
"an",
"error"
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/cryptostore.go#L201-L225 | train |
nats-io/nats-streaming-server | stores/cryptostore.go | Decrypt | func (s *EDStore) Decrypt(dst []byte, cipherText []byte) ([]byte, error) {
var gcm cipher.AEAD
if len(cipherText) > 0 {
switch cipherText[0] {
case CryptoCodeAES:
gcm = s.aesgcm
case CryptoCodeChaCha:
gcm = s.chachagcm
default:
// Anything else, assume no algo or something we don't know how to decrypt.
return cipherText, nil
}
}
if len(cipherText) <= 1+s.nonceSize {
return nil, fmt.Errorf("trying to decrypt data that is not (len=%v)", len(cipherText))
}
dd, err := gcm.Open(dst, cipherText[1:1+s.nonceSize], cipherText[1+s.nonceSize:], nil)
if err != nil {
return nil, err
}
return dd, nil
} | go | func (s *EDStore) Decrypt(dst []byte, cipherText []byte) ([]byte, error) {
var gcm cipher.AEAD
if len(cipherText) > 0 {
switch cipherText[0] {
case CryptoCodeAES:
gcm = s.aesgcm
case CryptoCodeChaCha:
gcm = s.chachagcm
default:
// Anything else, assume no algo or something we don't know how to decrypt.
return cipherText, nil
}
}
if len(cipherText) <= 1+s.nonceSize {
return nil, fmt.Errorf("trying to decrypt data that is not (len=%v)", len(cipherText))
}
dd, err := gcm.Open(dst, cipherText[1:1+s.nonceSize], cipherText[1+s.nonceSize:], nil)
if err != nil {
return nil, err
}
return dd, nil
} | [
"func",
"(",
"s",
"*",
"EDStore",
")",
"Decrypt",
"(",
"dst",
"[",
"]",
"byte",
",",
"cipherText",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"var",
"gcm",
"cipher",
".",
"AEAD",
"\n",
"if",
"len",
"(",
"cipherText",
")",
">",
"0",
"{",
"switch",
"cipherText",
"[",
"0",
"]",
"{",
"case",
"CryptoCodeAES",
":",
"gcm",
"=",
"s",
".",
"aesgcm",
"\n",
"case",
"CryptoCodeChaCha",
":",
"gcm",
"=",
"s",
".",
"chachagcm",
"\n",
"default",
":",
"return",
"cipherText",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"cipherText",
")",
"<=",
"1",
"+",
"s",
".",
"nonceSize",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"trying to decrypt data that is not (len=%v)\"",
",",
"len",
"(",
"cipherText",
")",
")",
"\n",
"}",
"\n",
"dd",
",",
"err",
":=",
"gcm",
".",
"Open",
"(",
"dst",
",",
"cipherText",
"[",
"1",
":",
"1",
"+",
"s",
".",
"nonceSize",
"]",
",",
"cipherText",
"[",
"1",
"+",
"s",
".",
"nonceSize",
":",
"]",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"dd",
",",
"nil",
"\n",
"}"
] | // Decrypt returns the decrypted data or an error | [
"Decrypt",
"returns",
"the",
"decrypted",
"data",
"or",
"an",
"error"
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/cryptostore.go#L228-L249 | train |
nats-io/nats-streaming-server | stores/cryptostore.go | NewCryptoStore | func NewCryptoStore(s Store, encryptionCipher string, encryptionKey []byte) (*CryptoStore, error) {
code, mkh, err := createMasterKeyHash(encryptionCipher, encryptionKey)
if err != nil {
return nil, err
}
cs := &CryptoStore{
Store: s,
code: code,
mkh: mkh,
}
// On success, erase the key
for i := 0; i < len(encryptionKey); i++ {
encryptionKey[i] = 'x'
}
return cs, nil
} | go | func NewCryptoStore(s Store, encryptionCipher string, encryptionKey []byte) (*CryptoStore, error) {
code, mkh, err := createMasterKeyHash(encryptionCipher, encryptionKey)
if err != nil {
return nil, err
}
cs := &CryptoStore{
Store: s,
code: code,
mkh: mkh,
}
// On success, erase the key
for i := 0; i < len(encryptionKey); i++ {
encryptionKey[i] = 'x'
}
return cs, nil
} | [
"func",
"NewCryptoStore",
"(",
"s",
"Store",
",",
"encryptionCipher",
"string",
",",
"encryptionKey",
"[",
"]",
"byte",
")",
"(",
"*",
"CryptoStore",
",",
"error",
")",
"{",
"code",
",",
"mkh",
",",
"err",
":=",
"createMasterKeyHash",
"(",
"encryptionCipher",
",",
"encryptionKey",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"cs",
":=",
"&",
"CryptoStore",
"{",
"Store",
":",
"s",
",",
"code",
":",
"code",
",",
"mkh",
":",
"mkh",
",",
"}",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"encryptionKey",
")",
";",
"i",
"++",
"{",
"encryptionKey",
"[",
"i",
"]",
"=",
"'x'",
"\n",
"}",
"\n",
"return",
"cs",
",",
"nil",
"\n",
"}"
] | // NewCryptoStore returns a CryptoStore instance with
// given underlying store. | [
"NewCryptoStore",
"returns",
"a",
"CryptoStore",
"instance",
"with",
"given",
"underlying",
"store",
"."
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/cryptostore.go#L253-L268 | train |
nats-io/nats-streaming-server | stores/limits.go | Clone | func (sl *StoreLimits) Clone() *StoreLimits {
cloned := *sl
cloned.PerChannel = sl.ClonePerChannelMap()
return &cloned
} | go | func (sl *StoreLimits) Clone() *StoreLimits {
cloned := *sl
cloned.PerChannel = sl.ClonePerChannelMap()
return &cloned
} | [
"func",
"(",
"sl",
"*",
"StoreLimits",
")",
"Clone",
"(",
")",
"*",
"StoreLimits",
"{",
"cloned",
":=",
"*",
"sl",
"\n",
"cloned",
".",
"PerChannel",
"=",
"sl",
".",
"ClonePerChannelMap",
"(",
")",
"\n",
"return",
"&",
"cloned",
"\n",
"}"
] | // Clone returns a copy of the store limits | [
"Clone",
"returns",
"a",
"copy",
"of",
"the",
"store",
"limits"
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/limits.go#L31-L35 | train |
nats-io/nats-streaming-server | stores/limits.go | ClonePerChannelMap | func (sl *StoreLimits) ClonePerChannelMap() map[string]*ChannelLimits {
if sl.PerChannel == nil {
return nil
}
clone := make(map[string]*ChannelLimits, len(sl.PerChannel))
for k, v := range sl.PerChannel {
copyVal := *v
clone[k] = ©Val
}
return clone
} | go | func (sl *StoreLimits) ClonePerChannelMap() map[string]*ChannelLimits {
if sl.PerChannel == nil {
return nil
}
clone := make(map[string]*ChannelLimits, len(sl.PerChannel))
for k, v := range sl.PerChannel {
copyVal := *v
clone[k] = ©Val
}
return clone
} | [
"func",
"(",
"sl",
"*",
"StoreLimits",
")",
"ClonePerChannelMap",
"(",
")",
"map",
"[",
"string",
"]",
"*",
"ChannelLimits",
"{",
"if",
"sl",
".",
"PerChannel",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"clone",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"ChannelLimits",
",",
"len",
"(",
"sl",
".",
"PerChannel",
")",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"sl",
".",
"PerChannel",
"{",
"copyVal",
":=",
"*",
"v",
"\n",
"clone",
"[",
"k",
"]",
"=",
"&",
"copyVal",
"\n",
"}",
"\n",
"return",
"clone",
"\n",
"}"
] | // ClonePerChannelMap returns a deep copy of the StoreLimits's PerChannel map | [
"ClonePerChannelMap",
"returns",
"a",
"deep",
"copy",
"of",
"the",
"StoreLimits",
"s",
"PerChannel",
"map"
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/limits.go#L38-L48 | train |
nats-io/nats-streaming-server | stores/limits.go | Print | func (sl *StoreLimits) Print() []string {
sublist := util.NewSublist()
for cn, cl := range sl.PerChannel {
sublist.Insert(cn, &channelLimitInfo{
name: cn,
limits: cl,
isLiteral: util.IsChannelNameLiteral(cn),
})
}
maxLevels := sublist.NumLevels()
txt := []string{}
title := "---------- Store Limits ----------"
txt = append(txt, title)
txt = append(txt, fmt.Sprintf("Channels: %s",
getLimitStr(true, int64(sl.MaxChannels),
int64(DefaultStoreLimits.MaxChannels),
limitCount)))
maxLen := len(title)
txt = append(txt, "--------- Channels Limits --------")
txt = append(txt, getGlobalLimitsPrintLines(&sl.ChannelLimits)...)
if len(sl.PerChannel) > 0 {
channels := sublist.Subjects()
channelLines := []string{}
for _, cn := range channels {
r := sublist.Match(cn)
var prev *channelLimitInfo
for i := 0; i < len(r); i++ {
channel := r[i].(*channelLimitInfo)
if channel.name == cn {
var parentLimits *ChannelLimits
if prev == nil {
parentLimits = &sl.ChannelLimits
} else {
parentLimits = prev.limits
}
channelLines = append(channelLines,
getChannelLimitsPrintLines(i, maxLevels, &maxLen, channel.name, channel.limits, parentLimits)...)
break
}
prev = channel
}
}
title := " List of Channels "
numberDashesLeft := (maxLen - len(title)) / 2
numberDashesRight := maxLen - len(title) - numberDashesLeft
title = fmt.Sprintf("%s%s%s",
repeatChar("-", numberDashesLeft),
title,
repeatChar("-", numberDashesRight))
txt = append(txt, title)
txt = append(txt, channelLines...)
}
txt = append(txt, repeatChar("-", maxLen))
return txt
} | go | func (sl *StoreLimits) Print() []string {
sublist := util.NewSublist()
for cn, cl := range sl.PerChannel {
sublist.Insert(cn, &channelLimitInfo{
name: cn,
limits: cl,
isLiteral: util.IsChannelNameLiteral(cn),
})
}
maxLevels := sublist.NumLevels()
txt := []string{}
title := "---------- Store Limits ----------"
txt = append(txt, title)
txt = append(txt, fmt.Sprintf("Channels: %s",
getLimitStr(true, int64(sl.MaxChannels),
int64(DefaultStoreLimits.MaxChannels),
limitCount)))
maxLen := len(title)
txt = append(txt, "--------- Channels Limits --------")
txt = append(txt, getGlobalLimitsPrintLines(&sl.ChannelLimits)...)
if len(sl.PerChannel) > 0 {
channels := sublist.Subjects()
channelLines := []string{}
for _, cn := range channels {
r := sublist.Match(cn)
var prev *channelLimitInfo
for i := 0; i < len(r); i++ {
channel := r[i].(*channelLimitInfo)
if channel.name == cn {
var parentLimits *ChannelLimits
if prev == nil {
parentLimits = &sl.ChannelLimits
} else {
parentLimits = prev.limits
}
channelLines = append(channelLines,
getChannelLimitsPrintLines(i, maxLevels, &maxLen, channel.name, channel.limits, parentLimits)...)
break
}
prev = channel
}
}
title := " List of Channels "
numberDashesLeft := (maxLen - len(title)) / 2
numberDashesRight := maxLen - len(title) - numberDashesLeft
title = fmt.Sprintf("%s%s%s",
repeatChar("-", numberDashesLeft),
title,
repeatChar("-", numberDashesRight))
txt = append(txt, title)
txt = append(txt, channelLines...)
}
txt = append(txt, repeatChar("-", maxLen))
return txt
} | [
"func",
"(",
"sl",
"*",
"StoreLimits",
")",
"Print",
"(",
")",
"[",
"]",
"string",
"{",
"sublist",
":=",
"util",
".",
"NewSublist",
"(",
")",
"\n",
"for",
"cn",
",",
"cl",
":=",
"range",
"sl",
".",
"PerChannel",
"{",
"sublist",
".",
"Insert",
"(",
"cn",
",",
"&",
"channelLimitInfo",
"{",
"name",
":",
"cn",
",",
"limits",
":",
"cl",
",",
"isLiteral",
":",
"util",
".",
"IsChannelNameLiteral",
"(",
"cn",
")",
",",
"}",
")",
"\n",
"}",
"\n",
"maxLevels",
":=",
"sublist",
".",
"NumLevels",
"(",
")",
"\n",
"txt",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"title",
":=",
"\"---------- Store Limits ----------\"",
"\n",
"txt",
"=",
"append",
"(",
"txt",
",",
"title",
")",
"\n",
"txt",
"=",
"append",
"(",
"txt",
",",
"fmt",
".",
"Sprintf",
"(",
"\"Channels: %s\"",
",",
"getLimitStr",
"(",
"true",
",",
"int64",
"(",
"sl",
".",
"MaxChannels",
")",
",",
"int64",
"(",
"DefaultStoreLimits",
".",
"MaxChannels",
")",
",",
"limitCount",
")",
")",
")",
"\n",
"maxLen",
":=",
"len",
"(",
"title",
")",
"\n",
"txt",
"=",
"append",
"(",
"txt",
",",
"\"--------- Channels Limits --------\"",
")",
"\n",
"txt",
"=",
"append",
"(",
"txt",
",",
"getGlobalLimitsPrintLines",
"(",
"&",
"sl",
".",
"ChannelLimits",
")",
"...",
")",
"\n",
"if",
"len",
"(",
"sl",
".",
"PerChannel",
")",
">",
"0",
"{",
"channels",
":=",
"sublist",
".",
"Subjects",
"(",
")",
"\n",
"channelLines",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"for",
"_",
",",
"cn",
":=",
"range",
"channels",
"{",
"r",
":=",
"sublist",
".",
"Match",
"(",
"cn",
")",
"\n",
"var",
"prev",
"*",
"channelLimitInfo",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"r",
")",
";",
"i",
"++",
"{",
"channel",
":=",
"r",
"[",
"i",
"]",
".",
"(",
"*",
"channelLimitInfo",
")",
"\n",
"if",
"channel",
".",
"name",
"==",
"cn",
"{",
"var",
"parentLimits",
"*",
"ChannelLimits",
"\n",
"if",
"prev",
"==",
"nil",
"{",
"parentLimits",
"=",
"&",
"sl",
".",
"ChannelLimits",
"\n",
"}",
"else",
"{",
"parentLimits",
"=",
"prev",
".",
"limits",
"\n",
"}",
"\n",
"channelLines",
"=",
"append",
"(",
"channelLines",
",",
"getChannelLimitsPrintLines",
"(",
"i",
",",
"maxLevels",
",",
"&",
"maxLen",
",",
"channel",
".",
"name",
",",
"channel",
".",
"limits",
",",
"parentLimits",
")",
"...",
")",
"\n",
"break",
"\n",
"}",
"\n",
"prev",
"=",
"channel",
"\n",
"}",
"\n",
"}",
"\n",
"title",
":=",
"\" List of Channels \"",
"\n",
"numberDashesLeft",
":=",
"(",
"maxLen",
"-",
"len",
"(",
"title",
")",
")",
"/",
"2",
"\n",
"numberDashesRight",
":=",
"maxLen",
"-",
"len",
"(",
"title",
")",
"-",
"numberDashesLeft",
"\n",
"title",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"%s%s%s\"",
",",
"repeatChar",
"(",
"\"-\"",
",",
"numberDashesLeft",
")",
",",
"title",
",",
"repeatChar",
"(",
"\"-\"",
",",
"numberDashesRight",
")",
")",
"\n",
"txt",
"=",
"append",
"(",
"txt",
",",
"title",
")",
"\n",
"txt",
"=",
"append",
"(",
"txt",
",",
"channelLines",
"...",
")",
"\n",
"}",
"\n",
"txt",
"=",
"append",
"(",
"txt",
",",
"repeatChar",
"(",
"\"-\"",
",",
"maxLen",
")",
")",
"\n",
"return",
"txt",
"\n",
"}"
] | // Print returns an array of strings suitable for printing the store limits. | [
"Print",
"returns",
"an",
"array",
"of",
"strings",
"suitable",
"for",
"printing",
"the",
"store",
"limits",
"."
] | 57c6c84265c0012a1efef365703c221329804d4c | https://github.com/nats-io/nats-streaming-server/blob/57c6c84265c0012a1efef365703c221329804d4c/stores/limits.go#L188-L242 | train |
jasonlvhit/gocron | gocron.go | NewJob | func NewJob(intervel uint64) *Job {
return &Job{
intervel,
"", "", "",
time.Unix(0, 0),
time.Unix(0, 0), 0,
time.Sunday,
make(map[string]interface{}),
make(map[string]([]interface{})),
}
} | go | func NewJob(intervel uint64) *Job {
return &Job{
intervel,
"", "", "",
time.Unix(0, 0),
time.Unix(0, 0), 0,
time.Sunday,
make(map[string]interface{}),
make(map[string]([]interface{})),
}
} | [
"func",
"NewJob",
"(",
"intervel",
"uint64",
")",
"*",
"Job",
"{",
"return",
"&",
"Job",
"{",
"intervel",
",",
"\"\"",
",",
"\"\"",
",",
"\"\"",
",",
"time",
".",
"Unix",
"(",
"0",
",",
"0",
")",
",",
"time",
".",
"Unix",
"(",
"0",
",",
"0",
")",
",",
"0",
",",
"time",
".",
"Sunday",
",",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
",",
"make",
"(",
"map",
"[",
"string",
"]",
"(",
"[",
"]",
"interface",
"{",
"}",
")",
")",
",",
"}",
"\n",
"}"
] | // Create a new job with the time interval. | [
"Create",
"a",
"new",
"job",
"with",
"the",
"time",
"interval",
"."
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L72-L82 | train |
jasonlvhit/gocron | gocron.go | run | func (j *Job) run() (result []reflect.Value, err error) {
f := reflect.ValueOf(j.funcs[j.jobFunc])
params := j.fparams[j.jobFunc]
if len(params) != f.Type().NumIn() {
err = errors.New("the number of param is not adapted")
return
}
in := make([]reflect.Value, len(params))
for k, param := range params {
in[k] = reflect.ValueOf(param)
}
result = f.Call(in)
j.lastRun = time.Now()
j.scheduleNextRun()
return
} | go | func (j *Job) run() (result []reflect.Value, err error) {
f := reflect.ValueOf(j.funcs[j.jobFunc])
params := j.fparams[j.jobFunc]
if len(params) != f.Type().NumIn() {
err = errors.New("the number of param is not adapted")
return
}
in := make([]reflect.Value, len(params))
for k, param := range params {
in[k] = reflect.ValueOf(param)
}
result = f.Call(in)
j.lastRun = time.Now()
j.scheduleNextRun()
return
} | [
"func",
"(",
"j",
"*",
"Job",
")",
"run",
"(",
")",
"(",
"result",
"[",
"]",
"reflect",
".",
"Value",
",",
"err",
"error",
")",
"{",
"f",
":=",
"reflect",
".",
"ValueOf",
"(",
"j",
".",
"funcs",
"[",
"j",
".",
"jobFunc",
"]",
")",
"\n",
"params",
":=",
"j",
".",
"fparams",
"[",
"j",
".",
"jobFunc",
"]",
"\n",
"if",
"len",
"(",
"params",
")",
"!=",
"f",
".",
"Type",
"(",
")",
".",
"NumIn",
"(",
")",
"{",
"err",
"=",
"errors",
".",
"New",
"(",
"\"the number of param is not adapted\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"in",
":=",
"make",
"(",
"[",
"]",
"reflect",
".",
"Value",
",",
"len",
"(",
"params",
")",
")",
"\n",
"for",
"k",
",",
"param",
":=",
"range",
"params",
"{",
"in",
"[",
"k",
"]",
"=",
"reflect",
".",
"ValueOf",
"(",
"param",
")",
"\n",
"}",
"\n",
"result",
"=",
"f",
".",
"Call",
"(",
"in",
")",
"\n",
"j",
".",
"lastRun",
"=",
"time",
".",
"Now",
"(",
")",
"\n",
"j",
".",
"scheduleNextRun",
"(",
")",
"\n",
"return",
"\n",
"}"
] | //Run the job and immediately reschedule it | [
"Run",
"the",
"job",
"and",
"immediately",
"reschedule",
"it"
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L90-L105 | train |
jasonlvhit/gocron | gocron.go | getFunctionName | func getFunctionName(fn interface{}) string {
return runtime.FuncForPC(reflect.ValueOf((fn)).Pointer()).Name()
} | go | func getFunctionName(fn interface{}) string {
return runtime.FuncForPC(reflect.ValueOf((fn)).Pointer()).Name()
} | [
"func",
"getFunctionName",
"(",
"fn",
"interface",
"{",
"}",
")",
"string",
"{",
"return",
"runtime",
".",
"FuncForPC",
"(",
"reflect",
".",
"ValueOf",
"(",
"(",
"fn",
")",
")",
".",
"Pointer",
"(",
")",
")",
".",
"Name",
"(",
")",
"\n",
"}"
] | // for given function fn, get the name of function. | [
"for",
"given",
"function",
"fn",
"get",
"the",
"name",
"of",
"function",
"."
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L108-L110 | train |
jasonlvhit/gocron | gocron.go | Do | func (j *Job) Do(jobFun interface{}, params ...interface{}) {
typ := reflect.TypeOf(jobFun)
if typ.Kind() != reflect.Func {
panic("only function can be schedule into the job queue.")
}
fname := getFunctionName(jobFun)
j.funcs[fname] = jobFun
j.fparams[fname] = params
j.jobFunc = fname
//schedule the next run
j.scheduleNextRun()
} | go | func (j *Job) Do(jobFun interface{}, params ...interface{}) {
typ := reflect.TypeOf(jobFun)
if typ.Kind() != reflect.Func {
panic("only function can be schedule into the job queue.")
}
fname := getFunctionName(jobFun)
j.funcs[fname] = jobFun
j.fparams[fname] = params
j.jobFunc = fname
//schedule the next run
j.scheduleNextRun()
} | [
"func",
"(",
"j",
"*",
"Job",
")",
"Do",
"(",
"jobFun",
"interface",
"{",
"}",
",",
"params",
"...",
"interface",
"{",
"}",
")",
"{",
"typ",
":=",
"reflect",
".",
"TypeOf",
"(",
"jobFun",
")",
"\n",
"if",
"typ",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"Func",
"{",
"panic",
"(",
"\"only function can be schedule into the job queue.\"",
")",
"\n",
"}",
"\n",
"fname",
":=",
"getFunctionName",
"(",
"jobFun",
")",
"\n",
"j",
".",
"funcs",
"[",
"fname",
"]",
"=",
"jobFun",
"\n",
"j",
".",
"fparams",
"[",
"fname",
"]",
"=",
"params",
"\n",
"j",
".",
"jobFunc",
"=",
"fname",
"\n",
"j",
".",
"scheduleNextRun",
"(",
")",
"\n",
"}"
] | // Specifies the jobFunc that should be called every time the job runs
// | [
"Specifies",
"the",
"jobFunc",
"that",
"should",
"be",
"called",
"every",
"time",
"the",
"job",
"runs"
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L114-L126 | train |
jasonlvhit/gocron | gocron.go | scheduleNextRun | func (j *Job) scheduleNextRun() {
if j.lastRun == time.Unix(0, 0) {
if j.unit == "weeks" {
i := time.Now().Weekday() - j.startDay
if i < 0 {
i = 7 + i
}
j.lastRun = time.Date(time.Now().Year(), time.Now().Month(), time.Now().Day()-int(i), 0, 0, 0, 0, loc)
} else {
j.lastRun = time.Now()
}
}
if j.period != 0 {
// translate all the units to the Seconds
j.nextRun = j.lastRun.Add(j.period * time.Second)
} else {
switch j.unit {
case "minutes":
j.period = time.Duration(j.interval * 60)
break
case "hours":
j.period = time.Duration(j.interval * 60 * 60)
break
case "days":
j.period = time.Duration(j.interval * 60 * 60 * 24)
break
case "weeks":
j.period = time.Duration(j.interval * 60 * 60 * 24 * 7)
break
case "seconds":
j.period = time.Duration(j.interval)
}
j.nextRun = j.lastRun.Add(j.period * time.Second)
}
} | go | func (j *Job) scheduleNextRun() {
if j.lastRun == time.Unix(0, 0) {
if j.unit == "weeks" {
i := time.Now().Weekday() - j.startDay
if i < 0 {
i = 7 + i
}
j.lastRun = time.Date(time.Now().Year(), time.Now().Month(), time.Now().Day()-int(i), 0, 0, 0, 0, loc)
} else {
j.lastRun = time.Now()
}
}
if j.period != 0 {
// translate all the units to the Seconds
j.nextRun = j.lastRun.Add(j.period * time.Second)
} else {
switch j.unit {
case "minutes":
j.period = time.Duration(j.interval * 60)
break
case "hours":
j.period = time.Duration(j.interval * 60 * 60)
break
case "days":
j.period = time.Duration(j.interval * 60 * 60 * 24)
break
case "weeks":
j.period = time.Duration(j.interval * 60 * 60 * 24 * 7)
break
case "seconds":
j.period = time.Duration(j.interval)
}
j.nextRun = j.lastRun.Add(j.period * time.Second)
}
} | [
"func",
"(",
"j",
"*",
"Job",
")",
"scheduleNextRun",
"(",
")",
"{",
"if",
"j",
".",
"lastRun",
"==",
"time",
".",
"Unix",
"(",
"0",
",",
"0",
")",
"{",
"if",
"j",
".",
"unit",
"==",
"\"weeks\"",
"{",
"i",
":=",
"time",
".",
"Now",
"(",
")",
".",
"Weekday",
"(",
")",
"-",
"j",
".",
"startDay",
"\n",
"if",
"i",
"<",
"0",
"{",
"i",
"=",
"7",
"+",
"i",
"\n",
"}",
"\n",
"j",
".",
"lastRun",
"=",
"time",
".",
"Date",
"(",
"time",
".",
"Now",
"(",
")",
".",
"Year",
"(",
")",
",",
"time",
".",
"Now",
"(",
")",
".",
"Month",
"(",
")",
",",
"time",
".",
"Now",
"(",
")",
".",
"Day",
"(",
")",
"-",
"int",
"(",
"i",
")",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"loc",
")",
"\n",
"}",
"else",
"{",
"j",
".",
"lastRun",
"=",
"time",
".",
"Now",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"j",
".",
"period",
"!=",
"0",
"{",
"j",
".",
"nextRun",
"=",
"j",
".",
"lastRun",
".",
"Add",
"(",
"j",
".",
"period",
"*",
"time",
".",
"Second",
")",
"\n",
"}",
"else",
"{",
"switch",
"j",
".",
"unit",
"{",
"case",
"\"minutes\"",
":",
"j",
".",
"period",
"=",
"time",
".",
"Duration",
"(",
"j",
".",
"interval",
"*",
"60",
")",
"\n",
"break",
"\n",
"case",
"\"hours\"",
":",
"j",
".",
"period",
"=",
"time",
".",
"Duration",
"(",
"j",
".",
"interval",
"*",
"60",
"*",
"60",
")",
"\n",
"break",
"\n",
"case",
"\"days\"",
":",
"j",
".",
"period",
"=",
"time",
".",
"Duration",
"(",
"j",
".",
"interval",
"*",
"60",
"*",
"60",
"*",
"24",
")",
"\n",
"break",
"\n",
"case",
"\"weeks\"",
":",
"j",
".",
"period",
"=",
"time",
".",
"Duration",
"(",
"j",
".",
"interval",
"*",
"60",
"*",
"60",
"*",
"24",
"*",
"7",
")",
"\n",
"break",
"\n",
"case",
"\"seconds\"",
":",
"j",
".",
"period",
"=",
"time",
".",
"Duration",
"(",
"j",
".",
"interval",
")",
"\n",
"}",
"\n",
"j",
".",
"nextRun",
"=",
"j",
".",
"lastRun",
".",
"Add",
"(",
"j",
".",
"period",
"*",
"time",
".",
"Second",
")",
"\n",
"}",
"\n",
"}"
] | //Compute the instant when this job should run next | [
"Compute",
"the",
"instant",
"when",
"this",
"job",
"should",
"run",
"next"
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L184-L220 | train |
jasonlvhit/gocron | gocron.go | Second | func (j *Job) Second() (job *Job) {
if j.interval != 1 {
panic("")
}
job = j.Seconds()
return
} | go | func (j *Job) Second() (job *Job) {
if j.interval != 1 {
panic("")
}
job = j.Seconds()
return
} | [
"func",
"(",
"j",
"*",
"Job",
")",
"Second",
"(",
")",
"(",
"job",
"*",
"Job",
")",
"{",
"if",
"j",
".",
"interval",
"!=",
"1",
"{",
"panic",
"(",
"\"\"",
")",
"\n",
"}",
"\n",
"job",
"=",
"j",
".",
"Seconds",
"(",
")",
"\n",
"return",
"\n",
"}"
] | // the follow functions set the job's unit with seconds,minutes,hours...
// Set the unit with second | [
"the",
"follow",
"functions",
"set",
"the",
"job",
"s",
"unit",
"with",
"seconds",
"minutes",
"hours",
"...",
"Set",
"the",
"unit",
"with",
"second"
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L230-L236 | train |
jasonlvhit/gocron | gocron.go | Minute | func (j *Job) Minute() (job *Job) {
if j.interval != 1 {
panic("")
}
job = j.Minutes()
return
} | go | func (j *Job) Minute() (job *Job) {
if j.interval != 1 {
panic("")
}
job = j.Minutes()
return
} | [
"func",
"(",
"j",
"*",
"Job",
")",
"Minute",
"(",
")",
"(",
"job",
"*",
"Job",
")",
"{",
"if",
"j",
".",
"interval",
"!=",
"1",
"{",
"panic",
"(",
"\"\"",
")",
"\n",
"}",
"\n",
"job",
"=",
"j",
".",
"Minutes",
"(",
")",
"\n",
"return",
"\n",
"}"
] | // Set the unit with minute, which interval is 1 | [
"Set",
"the",
"unit",
"with",
"minute",
"which",
"interval",
"is",
"1"
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L245-L251 | train |
jasonlvhit/gocron | gocron.go | Hour | func (j *Job) Hour() (job *Job) {
if j.interval != 1 {
panic("")
}
job = j.Hours()
return
} | go | func (j *Job) Hour() (job *Job) {
if j.interval != 1 {
panic("")
}
job = j.Hours()
return
} | [
"func",
"(",
"j",
"*",
"Job",
")",
"Hour",
"(",
")",
"(",
"job",
"*",
"Job",
")",
"{",
"if",
"j",
".",
"interval",
"!=",
"1",
"{",
"panic",
"(",
"\"\"",
")",
"\n",
"}",
"\n",
"job",
"=",
"j",
".",
"Hours",
"(",
")",
"\n",
"return",
"\n",
"}"
] | //set the unit with hour, which interval is 1 | [
"set",
"the",
"unit",
"with",
"hour",
"which",
"interval",
"is",
"1"
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L260-L266 | train |
jasonlvhit/gocron | gocron.go | Day | func (j *Job) Day() (job *Job) {
if j.interval != 1 {
panic("")
}
job = j.Days()
return
} | go | func (j *Job) Day() (job *Job) {
if j.interval != 1 {
panic("")
}
job = j.Days()
return
} | [
"func",
"(",
"j",
"*",
"Job",
")",
"Day",
"(",
")",
"(",
"job",
"*",
"Job",
")",
"{",
"if",
"j",
".",
"interval",
"!=",
"1",
"{",
"panic",
"(",
"\"\"",
")",
"\n",
"}",
"\n",
"job",
"=",
"j",
".",
"Days",
"(",
")",
"\n",
"return",
"\n",
"}"
] | // Set the job's unit with day, which interval is 1 | [
"Set",
"the",
"job",
"s",
"unit",
"with",
"day",
"which",
"interval",
"is",
"1"
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L275-L281 | train |
jasonlvhit/gocron | gocron.go | Tuesday | func (j *Job) Tuesday() (job *Job) {
if j.interval != 1 {
panic("")
}
j.startDay = 2
job = j.Weeks()
return
} | go | func (j *Job) Tuesday() (job *Job) {
if j.interval != 1 {
panic("")
}
j.startDay = 2
job = j.Weeks()
return
} | [
"func",
"(",
"j",
"*",
"Job",
")",
"Tuesday",
"(",
")",
"(",
"job",
"*",
"Job",
")",
"{",
"if",
"j",
".",
"interval",
"!=",
"1",
"{",
"panic",
"(",
"\"\"",
")",
"\n",
"}",
"\n",
"j",
".",
"startDay",
"=",
"2",
"\n",
"job",
"=",
"j",
".",
"Weeks",
"(",
")",
"\n",
"return",
"\n",
"}"
] | // Set the start day with Tuesday | [
"Set",
"the",
"start",
"day",
"with",
"Tuesday"
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L301-L308 | train |
jasonlvhit/gocron | gocron.go | Wednesday | func (j *Job) Wednesday() (job *Job) {
if j.interval != 1 {
panic("")
}
j.startDay = 3
job = j.Weeks()
return
} | go | func (j *Job) Wednesday() (job *Job) {
if j.interval != 1 {
panic("")
}
j.startDay = 3
job = j.Weeks()
return
} | [
"func",
"(",
"j",
"*",
"Job",
")",
"Wednesday",
"(",
")",
"(",
"job",
"*",
"Job",
")",
"{",
"if",
"j",
".",
"interval",
"!=",
"1",
"{",
"panic",
"(",
"\"\"",
")",
"\n",
"}",
"\n",
"j",
".",
"startDay",
"=",
"3",
"\n",
"job",
"=",
"j",
".",
"Weeks",
"(",
")",
"\n",
"return",
"\n",
"}"
] | // Set the start day woth Wednesday | [
"Set",
"the",
"start",
"day",
"woth",
"Wednesday"
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L311-L318 | train |
jasonlvhit/gocron | gocron.go | Thursday | func (j *Job) Thursday() (job *Job) {
if j.interval != 1 {
panic("")
}
j.startDay = 4
job = j.Weeks()
return
} | go | func (j *Job) Thursday() (job *Job) {
if j.interval != 1 {
panic("")
}
j.startDay = 4
job = j.Weeks()
return
} | [
"func",
"(",
"j",
"*",
"Job",
")",
"Thursday",
"(",
")",
"(",
"job",
"*",
"Job",
")",
"{",
"if",
"j",
".",
"interval",
"!=",
"1",
"{",
"panic",
"(",
"\"\"",
")",
"\n",
"}",
"\n",
"j",
".",
"startDay",
"=",
"4",
"\n",
"job",
"=",
"j",
".",
"Weeks",
"(",
")",
"\n",
"return",
"\n",
"}"
] | // Set the start day with thursday | [
"Set",
"the",
"start",
"day",
"with",
"thursday"
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L321-L328 | train |
jasonlvhit/gocron | gocron.go | Friday | func (j *Job) Friday() (job *Job) {
if j.interval != 1 {
panic("")
}
j.startDay = 5
job = j.Weeks()
return
} | go | func (j *Job) Friday() (job *Job) {
if j.interval != 1 {
panic("")
}
j.startDay = 5
job = j.Weeks()
return
} | [
"func",
"(",
"j",
"*",
"Job",
")",
"Friday",
"(",
")",
"(",
"job",
"*",
"Job",
")",
"{",
"if",
"j",
".",
"interval",
"!=",
"1",
"{",
"panic",
"(",
"\"\"",
")",
"\n",
"}",
"\n",
"j",
".",
"startDay",
"=",
"5",
"\n",
"job",
"=",
"j",
".",
"Weeks",
"(",
")",
"\n",
"return",
"\n",
"}"
] | // Set the start day with friday | [
"Set",
"the",
"start",
"day",
"with",
"friday"
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L331-L338 | train |
jasonlvhit/gocron | gocron.go | Saturday | func (j *Job) Saturday() (job *Job) {
if j.interval != 1 {
panic("")
}
j.startDay = 6
job = j.Weeks()
return
} | go | func (j *Job) Saturday() (job *Job) {
if j.interval != 1 {
panic("")
}
j.startDay = 6
job = j.Weeks()
return
} | [
"func",
"(",
"j",
"*",
"Job",
")",
"Saturday",
"(",
")",
"(",
"job",
"*",
"Job",
")",
"{",
"if",
"j",
".",
"interval",
"!=",
"1",
"{",
"panic",
"(",
"\"\"",
")",
"\n",
"}",
"\n",
"j",
".",
"startDay",
"=",
"6",
"\n",
"job",
"=",
"j",
".",
"Weeks",
"(",
")",
"\n",
"return",
"\n",
"}"
] | // Set the start day with saturday | [
"Set",
"the",
"start",
"day",
"with",
"saturday"
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L341-L348 | train |
jasonlvhit/gocron | gocron.go | Sunday | func (j *Job) Sunday() (job *Job) {
if j.interval != 1 {
panic("")
}
j.startDay = 0
job = j.Weeks()
return
} | go | func (j *Job) Sunday() (job *Job) {
if j.interval != 1 {
panic("")
}
j.startDay = 0
job = j.Weeks()
return
} | [
"func",
"(",
"j",
"*",
"Job",
")",
"Sunday",
"(",
")",
"(",
"job",
"*",
"Job",
")",
"{",
"if",
"j",
".",
"interval",
"!=",
"1",
"{",
"panic",
"(",
"\"\"",
")",
"\n",
"}",
"\n",
"j",
".",
"startDay",
"=",
"0",
"\n",
"job",
"=",
"j",
".",
"Weeks",
"(",
")",
"\n",
"return",
"\n",
"}"
] | // Set the start day with sunday | [
"Set",
"the",
"start",
"day",
"with",
"sunday"
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L351-L358 | train |
jasonlvhit/gocron | gocron.go | getRunnableJobs | func (s *Scheduler) getRunnableJobs() (running_jobs [MAXJOBNUM]*Job, n int) {
runnableJobs := [MAXJOBNUM]*Job{}
n = 0
sort.Sort(s)
for i := 0; i < s.size; i++ {
if s.jobs[i].shouldRun() {
runnableJobs[n] = s.jobs[i]
//fmt.Println(runnableJobs)
n++
} else {
break
}
}
return runnableJobs, n
} | go | func (s *Scheduler) getRunnableJobs() (running_jobs [MAXJOBNUM]*Job, n int) {
runnableJobs := [MAXJOBNUM]*Job{}
n = 0
sort.Sort(s)
for i := 0; i < s.size; i++ {
if s.jobs[i].shouldRun() {
runnableJobs[n] = s.jobs[i]
//fmt.Println(runnableJobs)
n++
} else {
break
}
}
return runnableJobs, n
} | [
"func",
"(",
"s",
"*",
"Scheduler",
")",
"getRunnableJobs",
"(",
")",
"(",
"running_jobs",
"[",
"MAXJOBNUM",
"]",
"*",
"Job",
",",
"n",
"int",
")",
"{",
"runnableJobs",
":=",
"[",
"MAXJOBNUM",
"]",
"*",
"Job",
"{",
"}",
"\n",
"n",
"=",
"0",
"\n",
"sort",
".",
"Sort",
"(",
"s",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"s",
".",
"size",
";",
"i",
"++",
"{",
"if",
"s",
".",
"jobs",
"[",
"i",
"]",
".",
"shouldRun",
"(",
")",
"{",
"runnableJobs",
"[",
"n",
"]",
"=",
"s",
".",
"jobs",
"[",
"i",
"]",
"\n",
"n",
"++",
"\n",
"}",
"else",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"runnableJobs",
",",
"n",
"\n",
"}"
] | // Get the current runnable jobs, which shouldRun is True | [
"Get",
"the",
"current",
"runnable",
"jobs",
"which",
"shouldRun",
"is",
"True"
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L395-L410 | train |
jasonlvhit/gocron | gocron.go | NextRun | func (s *Scheduler) NextRun() (*Job, time.Time) {
if s.size <= 0 {
return nil, time.Now()
}
sort.Sort(s)
return s.jobs[0], s.jobs[0].nextRun
} | go | func (s *Scheduler) NextRun() (*Job, time.Time) {
if s.size <= 0 {
return nil, time.Now()
}
sort.Sort(s)
return s.jobs[0], s.jobs[0].nextRun
} | [
"func",
"(",
"s",
"*",
"Scheduler",
")",
"NextRun",
"(",
")",
"(",
"*",
"Job",
",",
"time",
".",
"Time",
")",
"{",
"if",
"s",
".",
"size",
"<=",
"0",
"{",
"return",
"nil",
",",
"time",
".",
"Now",
"(",
")",
"\n",
"}",
"\n",
"sort",
".",
"Sort",
"(",
"s",
")",
"\n",
"return",
"s",
".",
"jobs",
"[",
"0",
"]",
",",
"s",
".",
"jobs",
"[",
"0",
"]",
".",
"nextRun",
"\n",
"}"
] | // Datetime when the next job should run. | [
"Datetime",
"when",
"the",
"next",
"job",
"should",
"run",
"."
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L413-L419 | train |
jasonlvhit/gocron | gocron.go | Every | func (s *Scheduler) Every(interval uint64) *Job {
job := NewJob(interval)
s.jobs[s.size] = job
s.size++
return job
} | go | func (s *Scheduler) Every(interval uint64) *Job {
job := NewJob(interval)
s.jobs[s.size] = job
s.size++
return job
} | [
"func",
"(",
"s",
"*",
"Scheduler",
")",
"Every",
"(",
"interval",
"uint64",
")",
"*",
"Job",
"{",
"job",
":=",
"NewJob",
"(",
"interval",
")",
"\n",
"s",
".",
"jobs",
"[",
"s",
".",
"size",
"]",
"=",
"job",
"\n",
"s",
".",
"size",
"++",
"\n",
"return",
"job",
"\n",
"}"
] | // Schedule a new periodic job | [
"Schedule",
"a",
"new",
"periodic",
"job"
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L422-L427 | train |
jasonlvhit/gocron | gocron.go | RunPending | func (s *Scheduler) RunPending() {
runnableJobs, n := s.getRunnableJobs()
if n != 0 {
for i := 0; i < n; i++ {
runnableJobs[i].run()
}
}
} | go | func (s *Scheduler) RunPending() {
runnableJobs, n := s.getRunnableJobs()
if n != 0 {
for i := 0; i < n; i++ {
runnableJobs[i].run()
}
}
} | [
"func",
"(",
"s",
"*",
"Scheduler",
")",
"RunPending",
"(",
")",
"{",
"runnableJobs",
",",
"n",
":=",
"s",
".",
"getRunnableJobs",
"(",
")",
"\n",
"if",
"n",
"!=",
"0",
"{",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"n",
";",
"i",
"++",
"{",
"runnableJobs",
"[",
"i",
"]",
".",
"run",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Run all the jobs that are scheduled to run. | [
"Run",
"all",
"the",
"jobs",
"that",
"are",
"scheduled",
"to",
"run",
"."
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L430-L438 | train |
jasonlvhit/gocron | gocron.go | RunAll | func (s *Scheduler) RunAll() {
for i := 0; i < s.size; i++ {
s.jobs[i].run()
}
} | go | func (s *Scheduler) RunAll() {
for i := 0; i < s.size; i++ {
s.jobs[i].run()
}
} | [
"func",
"(",
"s",
"*",
"Scheduler",
")",
"RunAll",
"(",
")",
"{",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"s",
".",
"size",
";",
"i",
"++",
"{",
"s",
".",
"jobs",
"[",
"i",
"]",
".",
"run",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // Run all jobs regardless if they are scheduled to run or not | [
"Run",
"all",
"jobs",
"regardless",
"if",
"they",
"are",
"scheduled",
"to",
"run",
"or",
"not"
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L441-L445 | train |
jasonlvhit/gocron | gocron.go | RunAllwithDelay | func (s *Scheduler) RunAllwithDelay(d int) {
for i := 0; i < s.size; i++ {
s.jobs[i].run()
time.Sleep(time.Duration(d))
}
} | go | func (s *Scheduler) RunAllwithDelay(d int) {
for i := 0; i < s.size; i++ {
s.jobs[i].run()
time.Sleep(time.Duration(d))
}
} | [
"func",
"(",
"s",
"*",
"Scheduler",
")",
"RunAllwithDelay",
"(",
"d",
"int",
")",
"{",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"s",
".",
"size",
";",
"i",
"++",
"{",
"s",
".",
"jobs",
"[",
"i",
"]",
".",
"run",
"(",
")",
"\n",
"time",
".",
"Sleep",
"(",
"time",
".",
"Duration",
"(",
"d",
")",
")",
"\n",
"}",
"\n",
"}"
] | // Run all jobs with delay seconds | [
"Run",
"all",
"jobs",
"with",
"delay",
"seconds"
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L448-L453 | train |
jasonlvhit/gocron | gocron.go | Remove | func (s *Scheduler) Remove(j interface{}) {
i := 0
found := false
for ; i < s.size; i++ {
if s.jobs[i].jobFunc == getFunctionName(j) {
found = true
break
}
}
if !found {
return
}
for j := (i + 1); j < s.size; j++ {
s.jobs[i] = s.jobs[j]
i++
}
s.size = s.size - 1
} | go | func (s *Scheduler) Remove(j interface{}) {
i := 0
found := false
for ; i < s.size; i++ {
if s.jobs[i].jobFunc == getFunctionName(j) {
found = true
break
}
}
if !found {
return
}
for j := (i + 1); j < s.size; j++ {
s.jobs[i] = s.jobs[j]
i++
}
s.size = s.size - 1
} | [
"func",
"(",
"s",
"*",
"Scheduler",
")",
"Remove",
"(",
"j",
"interface",
"{",
"}",
")",
"{",
"i",
":=",
"0",
"\n",
"found",
":=",
"false",
"\n",
"for",
";",
"i",
"<",
"s",
".",
"size",
";",
"i",
"++",
"{",
"if",
"s",
".",
"jobs",
"[",
"i",
"]",
".",
"jobFunc",
"==",
"getFunctionName",
"(",
"j",
")",
"{",
"found",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"found",
"{",
"return",
"\n",
"}",
"\n",
"for",
"j",
":=",
"(",
"i",
"+",
"1",
")",
";",
"j",
"<",
"s",
".",
"size",
";",
"j",
"++",
"{",
"s",
".",
"jobs",
"[",
"i",
"]",
"=",
"s",
".",
"jobs",
"[",
"j",
"]",
"\n",
"i",
"++",
"\n",
"}",
"\n",
"s",
".",
"size",
"=",
"s",
".",
"size",
"-",
"1",
"\n",
"}"
] | // Remove specific job j | [
"Remove",
"specific",
"job",
"j"
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L456-L476 | train |
jasonlvhit/gocron | gocron.go | Clear | func (s *Scheduler) Clear() {
for i := 0; i < s.size; i++ {
s.jobs[i] = nil
}
s.size = 0
} | go | func (s *Scheduler) Clear() {
for i := 0; i < s.size; i++ {
s.jobs[i] = nil
}
s.size = 0
} | [
"func",
"(",
"s",
"*",
"Scheduler",
")",
"Clear",
"(",
")",
"{",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"s",
".",
"size",
";",
"i",
"++",
"{",
"s",
".",
"jobs",
"[",
"i",
"]",
"=",
"nil",
"\n",
"}",
"\n",
"s",
".",
"size",
"=",
"0",
"\n",
"}"
] | // Delete all scheduled jobs | [
"Delete",
"all",
"scheduled",
"jobs"
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L479-L484 | train |
jasonlvhit/gocron | gocron.go | Start | func (s *Scheduler) Start() chan bool {
stopped := make(chan bool, 1)
ticker := time.NewTicker(1 * time.Second)
go func() {
for {
select {
case <-ticker.C:
s.RunPending()
case <-stopped:
return
}
}
}()
return stopped
} | go | func (s *Scheduler) Start() chan bool {
stopped := make(chan bool, 1)
ticker := time.NewTicker(1 * time.Second)
go func() {
for {
select {
case <-ticker.C:
s.RunPending()
case <-stopped:
return
}
}
}()
return stopped
} | [
"func",
"(",
"s",
"*",
"Scheduler",
")",
"Start",
"(",
")",
"chan",
"bool",
"{",
"stopped",
":=",
"make",
"(",
"chan",
"bool",
",",
"1",
")",
"\n",
"ticker",
":=",
"time",
".",
"NewTicker",
"(",
"1",
"*",
"time",
".",
"Second",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"for",
"{",
"select",
"{",
"case",
"<-",
"ticker",
".",
"C",
":",
"s",
".",
"RunPending",
"(",
")",
"\n",
"case",
"<-",
"stopped",
":",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"return",
"stopped",
"\n",
"}"
] | // Start all the pending jobs
// Add seconds ticker | [
"Start",
"all",
"the",
"pending",
"jobs",
"Add",
"seconds",
"ticker"
] | 5bcdd9fcfa9bf10574722841a11ccb2a57866dc8 | https://github.com/jasonlvhit/gocron/blob/5bcdd9fcfa9bf10574722841a11ccb2a57866dc8/gocron.go#L488-L504 | train |
hyperledger/burrow | acm/acmstate/state.go | GlobalAccountPermissions | func GlobalAccountPermissions(getter AccountGetter) permission.AccountPermissions {
if getter == nil {
return permission.AccountPermissions{
Roles: []string{},
}
}
return GlobalPermissionsAccount(getter).Permissions
} | go | func GlobalAccountPermissions(getter AccountGetter) permission.AccountPermissions {
if getter == nil {
return permission.AccountPermissions{
Roles: []string{},
}
}
return GlobalPermissionsAccount(getter).Permissions
} | [
"func",
"GlobalAccountPermissions",
"(",
"getter",
"AccountGetter",
")",
"permission",
".",
"AccountPermissions",
"{",
"if",
"getter",
"==",
"nil",
"{",
"return",
"permission",
".",
"AccountPermissions",
"{",
"Roles",
":",
"[",
"]",
"string",
"{",
"}",
",",
"}",
"\n",
"}",
"\n",
"return",
"GlobalPermissionsAccount",
"(",
"getter",
")",
".",
"Permissions",
"\n",
"}"
] | // Get global permissions from the account at GlobalPermissionsAddress | [
"Get",
"global",
"permissions",
"from",
"the",
"account",
"at",
"GlobalPermissionsAddress"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/acm/acmstate/state.go#L108-L115 | train |
hyperledger/burrow | execution/state/accounts.go | GetAccount | func (s *ReadState) GetAccount(address crypto.Address) (*acm.Account, error) {
tree, err := s.Forest.Reader(keys.Account.Prefix())
if err != nil {
return nil, err
}
accBytes := tree.Get(keys.Account.KeyNoPrefix(address))
if accBytes == nil {
return nil, nil
}
return acm.Decode(accBytes)
} | go | func (s *ReadState) GetAccount(address crypto.Address) (*acm.Account, error) {
tree, err := s.Forest.Reader(keys.Account.Prefix())
if err != nil {
return nil, err
}
accBytes := tree.Get(keys.Account.KeyNoPrefix(address))
if accBytes == nil {
return nil, nil
}
return acm.Decode(accBytes)
} | [
"func",
"(",
"s",
"*",
"ReadState",
")",
"GetAccount",
"(",
"address",
"crypto",
".",
"Address",
")",
"(",
"*",
"acm",
".",
"Account",
",",
"error",
")",
"{",
"tree",
",",
"err",
":=",
"s",
".",
"Forest",
".",
"Reader",
"(",
"keys",
".",
"Account",
".",
"Prefix",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"accBytes",
":=",
"tree",
".",
"Get",
"(",
"keys",
".",
"Account",
".",
"KeyNoPrefix",
"(",
"address",
")",
")",
"\n",
"if",
"accBytes",
"==",
"nil",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"return",
"acm",
".",
"Decode",
"(",
"accBytes",
")",
"\n",
"}"
] | // Returns nil if account does not exist with given address. | [
"Returns",
"nil",
"if",
"account",
"does",
"not",
"exist",
"with",
"given",
"address",
"."
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/execution/state/accounts.go#L13-L23 | train |
hyperledger/burrow | execution/state/validators.go | LoadValidatorRing | func LoadValidatorRing(version int64, ringSize int,
getImmutable func(version int64) (*storage.ImmutableForest, error)) (*validator.Ring, error) {
// In this method we have to page through previous version of the tree in order to reconstruct the in-memory
// ring structure. The corner cases are a little subtle but printing the buckets helps
// The basic idea is to load each version of the tree ringSize back, work out the difference that must have occurred
// between each bucket in the ring, and apply each diff to the ring. Once the ring is full it is symmetrical (up to
// a reindexing). If we are loading a chain whose height is less than the ring size we need to get the initial state
// correct
startVersion := version - int64(ringSize)
if startVersion < 1 {
// The ring will not be fully populated
startVersion = 1
}
var err error
// Read state to pull immutable forests from
rs := &ReadState{}
// Start with an empty ring - we want the initial bucket to have no cumulative power
ring := validator.NewRing(nil, ringSize)
// Load the IAVL state
rs.Forest, err = getImmutable(startVersion)
// Write the validator state at startVersion from IAVL tree into the ring's current bucket delta
err = validator.Write(ring, rs)
if err != nil {
return nil, err
}
// Rotate, now we have [ {bucket 0: cum: {}, delta: {start version changes} }, {bucket 1: cum: {start version changes}, delta {}, ... ]
// which is what we need (in particular we need this initial state if we are loading into a incompletely populated ring
_, _, err = ring.Rotate()
if err != nil {
return nil, err
}
// Rebuild validator Ring
for v := startVersion + 1; v <= version; v++ {
// Update IAVL read state to version of interest
rs.Forest, err = getImmutable(v)
if err != nil {
return nil, err
}
// Calculate the difference between the rings current cum and what is in state at this version
diff, err := validator.Diff(ring.CurrentSet(), rs)
if err != nil {
return nil, err
}
// Write that diff into the ring (just like it was when it was originally written to setPower)
err = validator.Write(ring, diff)
if err != nil {
return nil, err
}
// Rotate just like it was on the original commit
_, _, err = ring.Rotate()
if err != nil {
return nil, err
}
}
// Our ring should be the same up to symmetry in its index so we reindex to regain equality with the version we are loading
// This is the head index we would have had if we had started from version 1 like the chain did
ring.ReIndex(int(version % int64(ringSize)))
return ring, err
} | go | func LoadValidatorRing(version int64, ringSize int,
getImmutable func(version int64) (*storage.ImmutableForest, error)) (*validator.Ring, error) {
// In this method we have to page through previous version of the tree in order to reconstruct the in-memory
// ring structure. The corner cases are a little subtle but printing the buckets helps
// The basic idea is to load each version of the tree ringSize back, work out the difference that must have occurred
// between each bucket in the ring, and apply each diff to the ring. Once the ring is full it is symmetrical (up to
// a reindexing). If we are loading a chain whose height is less than the ring size we need to get the initial state
// correct
startVersion := version - int64(ringSize)
if startVersion < 1 {
// The ring will not be fully populated
startVersion = 1
}
var err error
// Read state to pull immutable forests from
rs := &ReadState{}
// Start with an empty ring - we want the initial bucket to have no cumulative power
ring := validator.NewRing(nil, ringSize)
// Load the IAVL state
rs.Forest, err = getImmutable(startVersion)
// Write the validator state at startVersion from IAVL tree into the ring's current bucket delta
err = validator.Write(ring, rs)
if err != nil {
return nil, err
}
// Rotate, now we have [ {bucket 0: cum: {}, delta: {start version changes} }, {bucket 1: cum: {start version changes}, delta {}, ... ]
// which is what we need (in particular we need this initial state if we are loading into a incompletely populated ring
_, _, err = ring.Rotate()
if err != nil {
return nil, err
}
// Rebuild validator Ring
for v := startVersion + 1; v <= version; v++ {
// Update IAVL read state to version of interest
rs.Forest, err = getImmutable(v)
if err != nil {
return nil, err
}
// Calculate the difference between the rings current cum and what is in state at this version
diff, err := validator.Diff(ring.CurrentSet(), rs)
if err != nil {
return nil, err
}
// Write that diff into the ring (just like it was when it was originally written to setPower)
err = validator.Write(ring, diff)
if err != nil {
return nil, err
}
// Rotate just like it was on the original commit
_, _, err = ring.Rotate()
if err != nil {
return nil, err
}
}
// Our ring should be the same up to symmetry in its index so we reindex to regain equality with the version we are loading
// This is the head index we would have had if we had started from version 1 like the chain did
ring.ReIndex(int(version % int64(ringSize)))
return ring, err
} | [
"func",
"LoadValidatorRing",
"(",
"version",
"int64",
",",
"ringSize",
"int",
",",
"getImmutable",
"func",
"(",
"version",
"int64",
")",
"(",
"*",
"storage",
".",
"ImmutableForest",
",",
"error",
")",
")",
"(",
"*",
"validator",
".",
"Ring",
",",
"error",
")",
"{",
"startVersion",
":=",
"version",
"-",
"int64",
"(",
"ringSize",
")",
"\n",
"if",
"startVersion",
"<",
"1",
"{",
"startVersion",
"=",
"1",
"\n",
"}",
"\n",
"var",
"err",
"error",
"\n",
"rs",
":=",
"&",
"ReadState",
"{",
"}",
"\n",
"ring",
":=",
"validator",
".",
"NewRing",
"(",
"nil",
",",
"ringSize",
")",
"\n",
"rs",
".",
"Forest",
",",
"err",
"=",
"getImmutable",
"(",
"startVersion",
")",
"\n",
"err",
"=",
"validator",
".",
"Write",
"(",
"ring",
",",
"rs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"_",
",",
"_",
",",
"err",
"=",
"ring",
".",
"Rotate",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"for",
"v",
":=",
"startVersion",
"+",
"1",
";",
"v",
"<=",
"version",
";",
"v",
"++",
"{",
"rs",
".",
"Forest",
",",
"err",
"=",
"getImmutable",
"(",
"v",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"diff",
",",
"err",
":=",
"validator",
".",
"Diff",
"(",
"ring",
".",
"CurrentSet",
"(",
")",
",",
"rs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"err",
"=",
"validator",
".",
"Write",
"(",
"ring",
",",
"diff",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"_",
",",
"_",
",",
"err",
"=",
"ring",
".",
"Rotate",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"ring",
".",
"ReIndex",
"(",
"int",
"(",
"version",
"%",
"int64",
"(",
"ringSize",
")",
")",
")",
"\n",
"return",
"ring",
",",
"err",
"\n",
"}"
] | // Initialises the validator Ring from the validator storage in forest | [
"Initialises",
"the",
"validator",
"Ring",
"from",
"the",
"validator",
"storage",
"in",
"forest"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/execution/state/validators.go#L15-L77 | train |
hyperledger/burrow | storage/key_format.go | ScanBytes | func (kf *KeyFormat) ScanBytes(key []byte) [][]byte {
segments := make([][]byte, len(kf.layout))
n := kf.prefix.Length()
for i, l := range kf.layout {
if l == 0 {
// Must be final variadic segment
segments[i] = key[n:]
return segments
}
n += l
if n > len(key) {
return segments[:i]
}
segments[i] = key[n-l : n]
}
return segments
} | go | func (kf *KeyFormat) ScanBytes(key []byte) [][]byte {
segments := make([][]byte, len(kf.layout))
n := kf.prefix.Length()
for i, l := range kf.layout {
if l == 0 {
// Must be final variadic segment
segments[i] = key[n:]
return segments
}
n += l
if n > len(key) {
return segments[:i]
}
segments[i] = key[n-l : n]
}
return segments
} | [
"func",
"(",
"kf",
"*",
"KeyFormat",
")",
"ScanBytes",
"(",
"key",
"[",
"]",
"byte",
")",
"[",
"]",
"[",
"]",
"byte",
"{",
"segments",
":=",
"make",
"(",
"[",
"]",
"[",
"]",
"byte",
",",
"len",
"(",
"kf",
".",
"layout",
")",
")",
"\n",
"n",
":=",
"kf",
".",
"prefix",
".",
"Length",
"(",
")",
"\n",
"for",
"i",
",",
"l",
":=",
"range",
"kf",
".",
"layout",
"{",
"if",
"l",
"==",
"0",
"{",
"segments",
"[",
"i",
"]",
"=",
"key",
"[",
"n",
":",
"]",
"\n",
"return",
"segments",
"\n",
"}",
"\n",
"n",
"+=",
"l",
"\n",
"if",
"n",
">",
"len",
"(",
"key",
")",
"{",
"return",
"segments",
"[",
":",
"i",
"]",
"\n",
"}",
"\n",
"segments",
"[",
"i",
"]",
"=",
"key",
"[",
"n",
"-",
"l",
":",
"n",
"]",
"\n",
"}",
"\n",
"return",
"segments",
"\n",
"}"
] | // Reads out the bytes associated with each segment of the key format from key. | [
"Reads",
"out",
"the",
"bytes",
"associated",
"with",
"each",
"segment",
"of",
"the",
"key",
"format",
"from",
"key",
"."
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/storage/key_format.go#L111-L127 | train |
hyperledger/burrow | storage/key_format.go | ScanNoPrefix | func (kf *KeyFormat) ScanNoPrefix(key []byte, args ...interface{}) error {
// Just pad by the length of the prefix
paddedKey := make([]byte, len(kf.prefix)+len(key))
copy(paddedKey[len(kf.prefix):], key)
return kf.Scan(paddedKey, args...)
} | go | func (kf *KeyFormat) ScanNoPrefix(key []byte, args ...interface{}) error {
// Just pad by the length of the prefix
paddedKey := make([]byte, len(kf.prefix)+len(key))
copy(paddedKey[len(kf.prefix):], key)
return kf.Scan(paddedKey, args...)
} | [
"func",
"(",
"kf",
"*",
"KeyFormat",
")",
"ScanNoPrefix",
"(",
"key",
"[",
"]",
"byte",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"paddedKey",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"len",
"(",
"kf",
".",
"prefix",
")",
"+",
"len",
"(",
"key",
")",
")",
"\n",
"copy",
"(",
"paddedKey",
"[",
"len",
"(",
"kf",
".",
"prefix",
")",
":",
"]",
",",
"key",
")",
"\n",
"return",
"kf",
".",
"Scan",
"(",
"paddedKey",
",",
"args",
"...",
")",
"\n",
"}"
] | // Like Scan but adds expects a key with the KeyFormat's prefix trimmed | [
"Like",
"Scan",
"but",
"adds",
"expects",
"a",
"key",
"with",
"the",
"KeyFormat",
"s",
"prefix",
"trimmed"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/storage/key_format.go#L149-L154 | train |
hyperledger/burrow | storage/key_format.go | KeyNoPrefix | func (kf *KeyFormat) KeyNoPrefix(args ...interface{}) (Prefix, error) {
key, err := kf.Key(args...)
if err != nil {
return nil, err
}
return key[len(kf.prefix):], nil
} | go | func (kf *KeyFormat) KeyNoPrefix(args ...interface{}) (Prefix, error) {
key, err := kf.Key(args...)
if err != nil {
return nil, err
}
return key[len(kf.prefix):], nil
} | [
"func",
"(",
"kf",
"*",
"KeyFormat",
")",
"KeyNoPrefix",
"(",
"args",
"...",
"interface",
"{",
"}",
")",
"(",
"Prefix",
",",
"error",
")",
"{",
"key",
",",
"err",
":=",
"kf",
".",
"Key",
"(",
"args",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"key",
"[",
"len",
"(",
"kf",
".",
"prefix",
")",
":",
"]",
",",
"nil",
"\n",
"}"
] | // Like Key but removes the prefix string | [
"Like",
"Key",
"but",
"removes",
"the",
"prefix",
"string"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/storage/key_format.go#L157-L163 | train |
hyperledger/burrow | storage/key_format.go | Fix | func (kf *KeyFormat) Fix(args ...interface{}) (*KeyFormat, error) {
key, err := kf.Key(args...)
if err != nil {
return nil, err
}
return NewKeyFormat(string(key), kf.layout[len(args):]...)
} | go | func (kf *KeyFormat) Fix(args ...interface{}) (*KeyFormat, error) {
key, err := kf.Key(args...)
if err != nil {
return nil, err
}
return NewKeyFormat(string(key), kf.layout[len(args):]...)
} | [
"func",
"(",
"kf",
"*",
"KeyFormat",
")",
"Fix",
"(",
"args",
"...",
"interface",
"{",
"}",
")",
"(",
"*",
"KeyFormat",
",",
"error",
")",
"{",
"key",
",",
"err",
":=",
"kf",
".",
"Key",
"(",
"args",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"NewKeyFormat",
"(",
"string",
"(",
"key",
")",
",",
"kf",
".",
"layout",
"[",
"len",
"(",
"args",
")",
":",
"]",
"...",
")",
"\n",
"}"
] | // Fixes the first args many segments as the prefix of a new KeyFormat by using the args to generate a key that becomes
// that prefix. Any remaining unassigned segments become the layout of the new KeyFormat. | [
"Fixes",
"the",
"first",
"args",
"many",
"segments",
"as",
"the",
"prefix",
"of",
"a",
"new",
"KeyFormat",
"by",
"using",
"the",
"args",
"to",
"generate",
"a",
"key",
"that",
"becomes",
"that",
"prefix",
".",
"Any",
"remaining",
"unassigned",
"segments",
"become",
"the",
"layout",
"of",
"the",
"new",
"KeyFormat",
"."
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/storage/key_format.go#L167-L173 | train |
hyperledger/burrow | storage/key_format.go | Iterator | func (kf *KeyFormat) Iterator(iterable KVIterable, start, end []byte, reverse ...bool) KVIterator {
if len(reverse) > 0 && reverse[0] {
return kf.prefix.Iterator(iterable.ReverseIterator, start, end)
}
return kf.prefix.Iterator(iterable.Iterator, start, end)
} | go | func (kf *KeyFormat) Iterator(iterable KVIterable, start, end []byte, reverse ...bool) KVIterator {
if len(reverse) > 0 && reverse[0] {
return kf.prefix.Iterator(iterable.ReverseIterator, start, end)
}
return kf.prefix.Iterator(iterable.Iterator, start, end)
} | [
"func",
"(",
"kf",
"*",
"KeyFormat",
")",
"Iterator",
"(",
"iterable",
"KVIterable",
",",
"start",
",",
"end",
"[",
"]",
"byte",
",",
"reverse",
"...",
"bool",
")",
"KVIterator",
"{",
"if",
"len",
"(",
"reverse",
")",
">",
"0",
"&&",
"reverse",
"[",
"0",
"]",
"{",
"return",
"kf",
".",
"prefix",
".",
"Iterator",
"(",
"iterable",
".",
"ReverseIterator",
",",
"start",
",",
"end",
")",
"\n",
"}",
"\n",
"return",
"kf",
".",
"prefix",
".",
"Iterator",
"(",
"iterable",
".",
"Iterator",
",",
"start",
",",
"end",
")",
"\n",
"}"
] | // Returns an iterator over the underlying iterable using this KeyFormat's prefix. This is to support proper iteration over the
// prefix in the presence of nil start or end which requests iteration to the inclusive edges of the domain. An optional
// argument for reverse can be passed to get reverse iteration. | [
"Returns",
"an",
"iterator",
"over",
"the",
"underlying",
"iterable",
"using",
"this",
"KeyFormat",
"s",
"prefix",
".",
"This",
"is",
"to",
"support",
"proper",
"iteration",
"over",
"the",
"prefix",
"in",
"the",
"presence",
"of",
"nil",
"start",
"or",
"end",
"which",
"requests",
"iteration",
"to",
"the",
"inclusive",
"edges",
"of",
"the",
"domain",
".",
"An",
"optional",
"argument",
"for",
"reverse",
"can",
"be",
"passed",
"to",
"get",
"reverse",
"iteration",
"."
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/storage/key_format.go#L178-L183 | train |
hyperledger/burrow | vent/service/server.go | NewServer | func NewServer(cfg *config.VentConfig, log *logger.Logger, consumer *Consumer) *Server {
// setup handlers
mux := http.NewServeMux()
mux.HandleFunc("/health", healthHandler(consumer))
return &Server{
Config: cfg,
Log: log,
Consumer: consumer,
mux: mux,
stopCh: make(chan bool, 1),
}
} | go | func NewServer(cfg *config.VentConfig, log *logger.Logger, consumer *Consumer) *Server {
// setup handlers
mux := http.NewServeMux()
mux.HandleFunc("/health", healthHandler(consumer))
return &Server{
Config: cfg,
Log: log,
Consumer: consumer,
mux: mux,
stopCh: make(chan bool, 1),
}
} | [
"func",
"NewServer",
"(",
"cfg",
"*",
"config",
".",
"VentConfig",
",",
"log",
"*",
"logger",
".",
"Logger",
",",
"consumer",
"*",
"Consumer",
")",
"*",
"Server",
"{",
"mux",
":=",
"http",
".",
"NewServeMux",
"(",
")",
"\n",
"mux",
".",
"HandleFunc",
"(",
"\"/health\"",
",",
"healthHandler",
"(",
"consumer",
")",
")",
"\n",
"return",
"&",
"Server",
"{",
"Config",
":",
"cfg",
",",
"Log",
":",
"log",
",",
"Consumer",
":",
"consumer",
",",
"mux",
":",
"mux",
",",
"stopCh",
":",
"make",
"(",
"chan",
"bool",
",",
"1",
")",
",",
"}",
"\n",
"}"
] | // NewServer returns a new HTTP server | [
"NewServer",
"returns",
"a",
"new",
"HTTP",
"server"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/vent/service/server.go#L21-L34 | train |
hyperledger/burrow | vent/service/server.go | Run | func (s *Server) Run() {
s.Log.Info("msg", "Starting HTTP Server")
// start http server
httpServer := &http.Server{Addr: s.Config.HTTPAddr, Handler: s}
go func() {
s.Log.Info("msg", "HTTP Server listening", "address", s.Config.HTTPAddr)
httpServer.ListenAndServe()
}()
// wait for stop signal
<-s.stopCh
s.Log.Info("msg", "Shutting down HTTP Server...")
httpServer.Shutdown(context.Background())
} | go | func (s *Server) Run() {
s.Log.Info("msg", "Starting HTTP Server")
// start http server
httpServer := &http.Server{Addr: s.Config.HTTPAddr, Handler: s}
go func() {
s.Log.Info("msg", "HTTP Server listening", "address", s.Config.HTTPAddr)
httpServer.ListenAndServe()
}()
// wait for stop signal
<-s.stopCh
s.Log.Info("msg", "Shutting down HTTP Server...")
httpServer.Shutdown(context.Background())
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"Run",
"(",
")",
"{",
"s",
".",
"Log",
".",
"Info",
"(",
"\"msg\"",
",",
"\"Starting HTTP Server\"",
")",
"\n",
"httpServer",
":=",
"&",
"http",
".",
"Server",
"{",
"Addr",
":",
"s",
".",
"Config",
".",
"HTTPAddr",
",",
"Handler",
":",
"s",
"}",
"\n",
"go",
"func",
"(",
")",
"{",
"s",
".",
"Log",
".",
"Info",
"(",
"\"msg\"",
",",
"\"HTTP Server listening\"",
",",
"\"address\"",
",",
"s",
".",
"Config",
".",
"HTTPAddr",
")",
"\n",
"httpServer",
".",
"ListenAndServe",
"(",
")",
"\n",
"}",
"(",
")",
"\n",
"<-",
"s",
".",
"stopCh",
"\n",
"s",
".",
"Log",
".",
"Info",
"(",
"\"msg\"",
",",
"\"Shutting down HTTP Server...\"",
")",
"\n",
"httpServer",
".",
"Shutdown",
"(",
"context",
".",
"Background",
"(",
")",
")",
"\n",
"}"
] | // Run starts the HTTP server | [
"Run",
"starts",
"the",
"HTTP",
"server"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/vent/service/server.go#L37-L54 | train |
hyperledger/burrow | vent/service/server.go | ServeHTTP | func (s *Server) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
s.mux.ServeHTTP(resp, req)
} | go | func (s *Server) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
s.mux.ServeHTTP(resp, req)
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"ServeHTTP",
"(",
"resp",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
")",
"{",
"s",
".",
"mux",
".",
"ServeHTTP",
"(",
"resp",
",",
"req",
")",
"\n",
"}"
] | // ServeHTTP dispatches the HTTP requests using the Server Mux | [
"ServeHTTP",
"dispatches",
"the",
"HTTP",
"requests",
"using",
"the",
"Server",
"Mux"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/vent/service/server.go#L57-L59 | train |
hyperledger/burrow | vent/service/rowbuilder.go | buildEventData | func buildEventData(projection *sqlsol.Projection, eventClass *types.EventClass, event *exec.Event, abiSpec *abi.AbiSpec,
l *logger.Logger) (types.EventDataRow, error) {
// a fresh new row to store column/value data
row := make(map[string]interface{})
// get header & log data for the given event
eventHeader := event.GetHeader()
eventLog := event.GetLog()
// decode event data using the provided abi specification
decodedData, err := decodeEvent(eventHeader, eventLog, abiSpec)
if err != nil {
return types.EventDataRow{}, errors.Wrapf(err, "Error decoding event (filter: %s)", eventClass.Filter)
}
l.Info("msg", fmt.Sprintf("Unpacked data: %v", decodedData), "eventName", decodedData[types.EventNameLabel])
rowAction := types.ActionUpsert
// for each data element, maps to SQL columnName and gets its value
// if there is no matching column for the item, it doesn't need to be stored in db
for fieldName, value := range decodedData {
// Can't think of case where we will get a key that is empty, but if we ever did we should not treat
// it as a delete marker when the delete marker field in unset
if eventClass.DeleteMarkerField != "" && eventClass.DeleteMarkerField == fieldName {
rowAction = types.ActionDelete
}
fieldMapping := eventClass.GetFieldMapping(fieldName)
if fieldMapping == nil {
continue
}
column, err := projection.GetColumn(eventClass.TableName, fieldMapping.ColumnName)
if err == nil {
if fieldMapping.BytesToString {
if bs, ok := value.(*[]byte); ok {
str := sanitiseBytesForString(*bs, l)
row[column.Name] = interface{}(str)
continue
}
}
row[column.Name] = value
} else {
l.Debug("msg", "could not get column", "err", err)
}
}
return types.EventDataRow{Action: rowAction, RowData: row, EventClass: eventClass}, nil
} | go | func buildEventData(projection *sqlsol.Projection, eventClass *types.EventClass, event *exec.Event, abiSpec *abi.AbiSpec,
l *logger.Logger) (types.EventDataRow, error) {
// a fresh new row to store column/value data
row := make(map[string]interface{})
// get header & log data for the given event
eventHeader := event.GetHeader()
eventLog := event.GetLog()
// decode event data using the provided abi specification
decodedData, err := decodeEvent(eventHeader, eventLog, abiSpec)
if err != nil {
return types.EventDataRow{}, errors.Wrapf(err, "Error decoding event (filter: %s)", eventClass.Filter)
}
l.Info("msg", fmt.Sprintf("Unpacked data: %v", decodedData), "eventName", decodedData[types.EventNameLabel])
rowAction := types.ActionUpsert
// for each data element, maps to SQL columnName and gets its value
// if there is no matching column for the item, it doesn't need to be stored in db
for fieldName, value := range decodedData {
// Can't think of case where we will get a key that is empty, but if we ever did we should not treat
// it as a delete marker when the delete marker field in unset
if eventClass.DeleteMarkerField != "" && eventClass.DeleteMarkerField == fieldName {
rowAction = types.ActionDelete
}
fieldMapping := eventClass.GetFieldMapping(fieldName)
if fieldMapping == nil {
continue
}
column, err := projection.GetColumn(eventClass.TableName, fieldMapping.ColumnName)
if err == nil {
if fieldMapping.BytesToString {
if bs, ok := value.(*[]byte); ok {
str := sanitiseBytesForString(*bs, l)
row[column.Name] = interface{}(str)
continue
}
}
row[column.Name] = value
} else {
l.Debug("msg", "could not get column", "err", err)
}
}
return types.EventDataRow{Action: rowAction, RowData: row, EventClass: eventClass}, nil
} | [
"func",
"buildEventData",
"(",
"projection",
"*",
"sqlsol",
".",
"Projection",
",",
"eventClass",
"*",
"types",
".",
"EventClass",
",",
"event",
"*",
"exec",
".",
"Event",
",",
"abiSpec",
"*",
"abi",
".",
"AbiSpec",
",",
"l",
"*",
"logger",
".",
"Logger",
")",
"(",
"types",
".",
"EventDataRow",
",",
"error",
")",
"{",
"row",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"eventHeader",
":=",
"event",
".",
"GetHeader",
"(",
")",
"\n",
"eventLog",
":=",
"event",
".",
"GetLog",
"(",
")",
"\n",
"decodedData",
",",
"err",
":=",
"decodeEvent",
"(",
"eventHeader",
",",
"eventLog",
",",
"abiSpec",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"types",
".",
"EventDataRow",
"{",
"}",
",",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"Error decoding event (filter: %s)\"",
",",
"eventClass",
".",
"Filter",
")",
"\n",
"}",
"\n",
"l",
".",
"Info",
"(",
"\"msg\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"Unpacked data: %v\"",
",",
"decodedData",
")",
",",
"\"eventName\"",
",",
"decodedData",
"[",
"types",
".",
"EventNameLabel",
"]",
")",
"\n",
"rowAction",
":=",
"types",
".",
"ActionUpsert",
"\n",
"for",
"fieldName",
",",
"value",
":=",
"range",
"decodedData",
"{",
"if",
"eventClass",
".",
"DeleteMarkerField",
"!=",
"\"\"",
"&&",
"eventClass",
".",
"DeleteMarkerField",
"==",
"fieldName",
"{",
"rowAction",
"=",
"types",
".",
"ActionDelete",
"\n",
"}",
"\n",
"fieldMapping",
":=",
"eventClass",
".",
"GetFieldMapping",
"(",
"fieldName",
")",
"\n",
"if",
"fieldMapping",
"==",
"nil",
"{",
"continue",
"\n",
"}",
"\n",
"column",
",",
"err",
":=",
"projection",
".",
"GetColumn",
"(",
"eventClass",
".",
"TableName",
",",
"fieldMapping",
".",
"ColumnName",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"if",
"fieldMapping",
".",
"BytesToString",
"{",
"if",
"bs",
",",
"ok",
":=",
"value",
".",
"(",
"*",
"[",
"]",
"byte",
")",
";",
"ok",
"{",
"str",
":=",
"sanitiseBytesForString",
"(",
"*",
"bs",
",",
"l",
")",
"\n",
"row",
"[",
"column",
".",
"Name",
"]",
"=",
"interface",
"{",
"}",
"(",
"str",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"}",
"\n",
"row",
"[",
"column",
".",
"Name",
"]",
"=",
"value",
"\n",
"}",
"else",
"{",
"l",
".",
"Debug",
"(",
"\"msg\"",
",",
"\"could not get column\"",
",",
"\"err\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"types",
".",
"EventDataRow",
"{",
"Action",
":",
"rowAction",
",",
"RowData",
":",
"row",
",",
"EventClass",
":",
"eventClass",
"}",
",",
"nil",
"\n",
"}"
] | // buildEventData builds event data from transactions | [
"buildEventData",
"builds",
"event",
"data",
"from",
"transactions"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/vent/service/rowbuilder.go#L19-L67 | train |
hyperledger/burrow | vent/service/rowbuilder.go | buildBlkData | func buildBlkData(tbls types.EventTables, block *exec.BlockExecution) (types.EventDataRow, error) {
// a fresh new row to store column/value data
row := make(map[string]interface{})
// block raw data
if _, ok := tbls[types.SQLBlockTableName]; ok {
blockHeader, err := json.Marshal(block.Header)
if err != nil {
return types.EventDataRow{}, fmt.Errorf("Couldn't marshal BlockHeader in block %v", block)
}
row[types.SQLColumnLabelHeight] = fmt.Sprintf("%v", block.Height)
row[types.SQLColumnLabelBlockHeader] = string(blockHeader)
} else {
return types.EventDataRow{}, fmt.Errorf("table: %s not found in table structure %v", types.SQLBlockTableName, tbls)
}
return types.EventDataRow{Action: types.ActionUpsert, RowData: row}, nil
} | go | func buildBlkData(tbls types.EventTables, block *exec.BlockExecution) (types.EventDataRow, error) {
// a fresh new row to store column/value data
row := make(map[string]interface{})
// block raw data
if _, ok := tbls[types.SQLBlockTableName]; ok {
blockHeader, err := json.Marshal(block.Header)
if err != nil {
return types.EventDataRow{}, fmt.Errorf("Couldn't marshal BlockHeader in block %v", block)
}
row[types.SQLColumnLabelHeight] = fmt.Sprintf("%v", block.Height)
row[types.SQLColumnLabelBlockHeader] = string(blockHeader)
} else {
return types.EventDataRow{}, fmt.Errorf("table: %s not found in table structure %v", types.SQLBlockTableName, tbls)
}
return types.EventDataRow{Action: types.ActionUpsert, RowData: row}, nil
} | [
"func",
"buildBlkData",
"(",
"tbls",
"types",
".",
"EventTables",
",",
"block",
"*",
"exec",
".",
"BlockExecution",
")",
"(",
"types",
".",
"EventDataRow",
",",
"error",
")",
"{",
"row",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"if",
"_",
",",
"ok",
":=",
"tbls",
"[",
"types",
".",
"SQLBlockTableName",
"]",
";",
"ok",
"{",
"blockHeader",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"block",
".",
"Header",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"types",
".",
"EventDataRow",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"Couldn't marshal BlockHeader in block %v\"",
",",
"block",
")",
"\n",
"}",
"\n",
"row",
"[",
"types",
".",
"SQLColumnLabelHeight",
"]",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"%v\"",
",",
"block",
".",
"Height",
")",
"\n",
"row",
"[",
"types",
".",
"SQLColumnLabelBlockHeader",
"]",
"=",
"string",
"(",
"blockHeader",
")",
"\n",
"}",
"else",
"{",
"return",
"types",
".",
"EventDataRow",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"table: %s not found in table structure %v\"",
",",
"types",
".",
"SQLBlockTableName",
",",
"tbls",
")",
"\n",
"}",
"\n",
"return",
"types",
".",
"EventDataRow",
"{",
"Action",
":",
"types",
".",
"ActionUpsert",
",",
"RowData",
":",
"row",
"}",
",",
"nil",
"\n",
"}"
] | // buildBlkData builds block data from block stream | [
"buildBlkData",
"builds",
"block",
"data",
"from",
"block",
"stream"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/vent/service/rowbuilder.go#L70-L88 | train |
hyperledger/burrow | vent/service/rowbuilder.go | buildTxData | func buildTxData(txe *exec.TxExecution) (types.EventDataRow, error) {
// transaction raw data
envelope, err := json.Marshal(txe.Envelope)
if err != nil {
return types.EventDataRow{}, fmt.Errorf("couldn't marshal envelope in tx %v", txe)
}
events, err := json.Marshal(txe.Events)
if err != nil {
return types.EventDataRow{}, fmt.Errorf("couldn't marshal events in tx %v", txe)
}
result, err := json.Marshal(txe.Result)
if err != nil {
return types.EventDataRow{}, fmt.Errorf("couldn't marshal result in tx %v", txe)
}
receipt, err := json.Marshal(txe.Receipt)
if err != nil {
return types.EventDataRow{}, fmt.Errorf("couldn't marshal receipt in tx %v", txe)
}
exception, err := json.Marshal(txe.Exception)
if err != nil {
return types.EventDataRow{}, fmt.Errorf("couldn't marshal exception in tx %v", txe)
}
return types.EventDataRow{
Action: types.ActionUpsert,
RowData: map[string]interface{}{
types.SQLColumnLabelHeight: txe.Height,
types.SQLColumnLabelTxHash: txe.TxHash.String(),
types.SQLColumnLabelIndex: txe.Index,
types.SQLColumnLabelTxType: txe.TxType.String(),
types.SQLColumnLabelEnvelope: string(envelope),
types.SQLColumnLabelEvents: string(events),
types.SQLColumnLabelResult: string(result),
types.SQLColumnLabelReceipt: string(receipt),
types.SQLColumnLabelException: string(exception),
},
}, nil
} | go | func buildTxData(txe *exec.TxExecution) (types.EventDataRow, error) {
// transaction raw data
envelope, err := json.Marshal(txe.Envelope)
if err != nil {
return types.EventDataRow{}, fmt.Errorf("couldn't marshal envelope in tx %v", txe)
}
events, err := json.Marshal(txe.Events)
if err != nil {
return types.EventDataRow{}, fmt.Errorf("couldn't marshal events in tx %v", txe)
}
result, err := json.Marshal(txe.Result)
if err != nil {
return types.EventDataRow{}, fmt.Errorf("couldn't marshal result in tx %v", txe)
}
receipt, err := json.Marshal(txe.Receipt)
if err != nil {
return types.EventDataRow{}, fmt.Errorf("couldn't marshal receipt in tx %v", txe)
}
exception, err := json.Marshal(txe.Exception)
if err != nil {
return types.EventDataRow{}, fmt.Errorf("couldn't marshal exception in tx %v", txe)
}
return types.EventDataRow{
Action: types.ActionUpsert,
RowData: map[string]interface{}{
types.SQLColumnLabelHeight: txe.Height,
types.SQLColumnLabelTxHash: txe.TxHash.String(),
types.SQLColumnLabelIndex: txe.Index,
types.SQLColumnLabelTxType: txe.TxType.String(),
types.SQLColumnLabelEnvelope: string(envelope),
types.SQLColumnLabelEvents: string(events),
types.SQLColumnLabelResult: string(result),
types.SQLColumnLabelReceipt: string(receipt),
types.SQLColumnLabelException: string(exception),
},
}, nil
} | [
"func",
"buildTxData",
"(",
"txe",
"*",
"exec",
".",
"TxExecution",
")",
"(",
"types",
".",
"EventDataRow",
",",
"error",
")",
"{",
"envelope",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"txe",
".",
"Envelope",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"types",
".",
"EventDataRow",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"couldn't marshal envelope in tx %v\"",
",",
"txe",
")",
"\n",
"}",
"\n",
"events",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"txe",
".",
"Events",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"types",
".",
"EventDataRow",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"couldn't marshal events in tx %v\"",
",",
"txe",
")",
"\n",
"}",
"\n",
"result",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"txe",
".",
"Result",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"types",
".",
"EventDataRow",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"couldn't marshal result in tx %v\"",
",",
"txe",
")",
"\n",
"}",
"\n",
"receipt",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"txe",
".",
"Receipt",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"types",
".",
"EventDataRow",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"couldn't marshal receipt in tx %v\"",
",",
"txe",
")",
"\n",
"}",
"\n",
"exception",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"txe",
".",
"Exception",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"types",
".",
"EventDataRow",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"couldn't marshal exception in tx %v\"",
",",
"txe",
")",
"\n",
"}",
"\n",
"return",
"types",
".",
"EventDataRow",
"{",
"Action",
":",
"types",
".",
"ActionUpsert",
",",
"RowData",
":",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"types",
".",
"SQLColumnLabelHeight",
":",
"txe",
".",
"Height",
",",
"types",
".",
"SQLColumnLabelTxHash",
":",
"txe",
".",
"TxHash",
".",
"String",
"(",
")",
",",
"types",
".",
"SQLColumnLabelIndex",
":",
"txe",
".",
"Index",
",",
"types",
".",
"SQLColumnLabelTxType",
":",
"txe",
".",
"TxType",
".",
"String",
"(",
")",
",",
"types",
".",
"SQLColumnLabelEnvelope",
":",
"string",
"(",
"envelope",
")",
",",
"types",
".",
"SQLColumnLabelEvents",
":",
"string",
"(",
"events",
")",
",",
"types",
".",
"SQLColumnLabelResult",
":",
"string",
"(",
"result",
")",
",",
"types",
".",
"SQLColumnLabelReceipt",
":",
"string",
"(",
"receipt",
")",
",",
"types",
".",
"SQLColumnLabelException",
":",
"string",
"(",
"exception",
")",
",",
"}",
",",
"}",
",",
"nil",
"\n",
"}"
] | // buildTxData builds transaction data from tx stream | [
"buildTxData",
"builds",
"transaction",
"data",
"from",
"tx",
"stream"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/vent/service/rowbuilder.go#L91-L131 | train |
hyperledger/burrow | event/pubsub/pubsub.go | NewServer | func NewServer(options ...Option) *Server {
s := &Server{
subscriptions: make(map[string]map[string]query.Query),
}
s.BaseService = *common.NewBaseService(nil, "PubSub", s)
for _, option := range options {
option(s)
}
// if BufferCapacity option was not set, the channel is unbuffered
s.cmds = make(chan cmd, s.cmdsCap)
return s
} | go | func NewServer(options ...Option) *Server {
s := &Server{
subscriptions: make(map[string]map[string]query.Query),
}
s.BaseService = *common.NewBaseService(nil, "PubSub", s)
for _, option := range options {
option(s)
}
// if BufferCapacity option was not set, the channel is unbuffered
s.cmds = make(chan cmd, s.cmdsCap)
return s
} | [
"func",
"NewServer",
"(",
"options",
"...",
"Option",
")",
"*",
"Server",
"{",
"s",
":=",
"&",
"Server",
"{",
"subscriptions",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"map",
"[",
"string",
"]",
"query",
".",
"Query",
")",
",",
"}",
"\n",
"s",
".",
"BaseService",
"=",
"*",
"common",
".",
"NewBaseService",
"(",
"nil",
",",
"\"PubSub\"",
",",
"s",
")",
"\n",
"for",
"_",
",",
"option",
":=",
"range",
"options",
"{",
"option",
"(",
"s",
")",
"\n",
"}",
"\n",
"s",
".",
"cmds",
"=",
"make",
"(",
"chan",
"cmd",
",",
"s",
".",
"cmdsCap",
")",
"\n",
"return",
"s",
"\n",
"}"
] | // NewServer returns a new server. See the commentary on the Option functions
// for a detailed description of how to configure buffering. If no options are
// provided, the resulting server's queue is unbuffered. | [
"NewServer",
"returns",
"a",
"new",
"server",
".",
"See",
"the",
"commentary",
"on",
"the",
"Option",
"functions",
"for",
"a",
"detailed",
"description",
"of",
"how",
"to",
"configure",
"buffering",
".",
"If",
"no",
"options",
"are",
"provided",
"the",
"resulting",
"server",
"s",
"queue",
"is",
"unbuffered",
"."
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/event/pubsub/pubsub.go#L71-L85 | train |
hyperledger/burrow | event/pubsub/pubsub.go | Subscribe | func (s *Server) Subscribe(ctx context.Context, clientID string, qry query.Query, outBuffer int) (<-chan interface{}, error) {
s.mtx.RLock()
clientSubscriptions, ok := s.subscriptions[clientID]
if ok {
_, ok = clientSubscriptions[qry.String()]
}
s.mtx.RUnlock()
if ok {
return nil, ErrAlreadySubscribed
}
// We are responsible for closing this channel so we create it
out := make(chan interface{}, outBuffer)
select {
case s.cmds <- cmd{op: sub, clientID: clientID, query: qry, ch: out}:
s.mtx.Lock()
if _, ok = s.subscriptions[clientID]; !ok {
s.subscriptions[clientID] = make(map[string]query.Query)
}
// preserve original query
// see Unsubscribe
s.subscriptions[clientID][qry.String()] = qry
s.mtx.Unlock()
return out, nil
case <-ctx.Done():
return nil, ctx.Err()
}
} | go | func (s *Server) Subscribe(ctx context.Context, clientID string, qry query.Query, outBuffer int) (<-chan interface{}, error) {
s.mtx.RLock()
clientSubscriptions, ok := s.subscriptions[clientID]
if ok {
_, ok = clientSubscriptions[qry.String()]
}
s.mtx.RUnlock()
if ok {
return nil, ErrAlreadySubscribed
}
// We are responsible for closing this channel so we create it
out := make(chan interface{}, outBuffer)
select {
case s.cmds <- cmd{op: sub, clientID: clientID, query: qry, ch: out}:
s.mtx.Lock()
if _, ok = s.subscriptions[clientID]; !ok {
s.subscriptions[clientID] = make(map[string]query.Query)
}
// preserve original query
// see Unsubscribe
s.subscriptions[clientID][qry.String()] = qry
s.mtx.Unlock()
return out, nil
case <-ctx.Done():
return nil, ctx.Err()
}
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"Subscribe",
"(",
"ctx",
"context",
".",
"Context",
",",
"clientID",
"string",
",",
"qry",
"query",
".",
"Query",
",",
"outBuffer",
"int",
")",
"(",
"<-",
"chan",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"s",
".",
"mtx",
".",
"RLock",
"(",
")",
"\n",
"clientSubscriptions",
",",
"ok",
":=",
"s",
".",
"subscriptions",
"[",
"clientID",
"]",
"\n",
"if",
"ok",
"{",
"_",
",",
"ok",
"=",
"clientSubscriptions",
"[",
"qry",
".",
"String",
"(",
")",
"]",
"\n",
"}",
"\n",
"s",
".",
"mtx",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"ok",
"{",
"return",
"nil",
",",
"ErrAlreadySubscribed",
"\n",
"}",
"\n",
"out",
":=",
"make",
"(",
"chan",
"interface",
"{",
"}",
",",
"outBuffer",
")",
"\n",
"select",
"{",
"case",
"s",
".",
"cmds",
"<-",
"cmd",
"{",
"op",
":",
"sub",
",",
"clientID",
":",
"clientID",
",",
"query",
":",
"qry",
",",
"ch",
":",
"out",
"}",
":",
"s",
".",
"mtx",
".",
"Lock",
"(",
")",
"\n",
"if",
"_",
",",
"ok",
"=",
"s",
".",
"subscriptions",
"[",
"clientID",
"]",
";",
"!",
"ok",
"{",
"s",
".",
"subscriptions",
"[",
"clientID",
"]",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"query",
".",
"Query",
")",
"\n",
"}",
"\n",
"s",
".",
"subscriptions",
"[",
"clientID",
"]",
"[",
"qry",
".",
"String",
"(",
")",
"]",
"=",
"qry",
"\n",
"s",
".",
"mtx",
".",
"Unlock",
"(",
")",
"\n",
"return",
"out",
",",
"nil",
"\n",
"case",
"<-",
"ctx",
".",
"Done",
"(",
")",
":",
"return",
"nil",
",",
"ctx",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // Subscribe creates a subscription for the given client. It accepts a channel
// on which messages matching the given query can be received. An error will be
// returned to the caller if the context is canceled or if subscription already
// exist for pair clientID and query. | [
"Subscribe",
"creates",
"a",
"subscription",
"for",
"the",
"given",
"client",
".",
"It",
"accepts",
"a",
"channel",
"on",
"which",
"messages",
"matching",
"the",
"given",
"query",
"can",
"be",
"received",
".",
"An",
"error",
"will",
"be",
"returned",
"to",
"the",
"caller",
"if",
"the",
"context",
"is",
"canceled",
"or",
"if",
"subscription",
"already",
"exist",
"for",
"pair",
"clientID",
"and",
"query",
"."
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/event/pubsub/pubsub.go#L108-L134 | train |
hyperledger/burrow | event/pubsub/pubsub.go | Publish | func (s *Server) Publish(ctx context.Context, msg interface{}) error {
return s.PublishWithTags(ctx, msg, query.TagMap(make(map[string]interface{})))
} | go | func (s *Server) Publish(ctx context.Context, msg interface{}) error {
return s.PublishWithTags(ctx, msg, query.TagMap(make(map[string]interface{})))
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"Publish",
"(",
"ctx",
"context",
".",
"Context",
",",
"msg",
"interface",
"{",
"}",
")",
"error",
"{",
"return",
"s",
".",
"PublishWithTags",
"(",
"ctx",
",",
"msg",
",",
"query",
".",
"TagMap",
"(",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
")",
")",
"\n",
"}"
] | // Publish publishes the given message. An error will be returned to the caller
// if the context is canceled. | [
"Publish",
"publishes",
"the",
"given",
"message",
".",
"An",
"error",
"will",
"be",
"returned",
"to",
"the",
"caller",
"if",
"the",
"context",
"is",
"canceled",
"."
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/event/pubsub/pubsub.go#L186-L188 | train |
hyperledger/burrow | event/pubsub/pubsub.go | PublishWithTags | func (s *Server) PublishWithTags(ctx context.Context, msg interface{}, tags query.Tagged) error {
select {
case s.cmds <- cmd{op: pub, msg: msg, tags: tags}:
return nil
case <-ctx.Done():
return ctx.Err()
}
} | go | func (s *Server) PublishWithTags(ctx context.Context, msg interface{}, tags query.Tagged) error {
select {
case s.cmds <- cmd{op: pub, msg: msg, tags: tags}:
return nil
case <-ctx.Done():
return ctx.Err()
}
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"PublishWithTags",
"(",
"ctx",
"context",
".",
"Context",
",",
"msg",
"interface",
"{",
"}",
",",
"tags",
"query",
".",
"Tagged",
")",
"error",
"{",
"select",
"{",
"case",
"s",
".",
"cmds",
"<-",
"cmd",
"{",
"op",
":",
"pub",
",",
"msg",
":",
"msg",
",",
"tags",
":",
"tags",
"}",
":",
"return",
"nil",
"\n",
"case",
"<-",
"ctx",
".",
"Done",
"(",
")",
":",
"return",
"ctx",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // PublishWithTags publishes the given message with the set of tags. The set is
// matched with clients queries. If there is a match, the message is sent to
// the client. | [
"PublishWithTags",
"publishes",
"the",
"given",
"message",
"with",
"the",
"set",
"of",
"tags",
".",
"The",
"set",
"is",
"matched",
"with",
"clients",
"queries",
".",
"If",
"there",
"is",
"a",
"match",
"the",
"message",
"is",
"sent",
"to",
"the",
"client",
"."
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/event/pubsub/pubsub.go#L193-L200 | train |
hyperledger/burrow | logging/loggers/sort_logger.go | SortLogger | func SortLogger(outputLogger log.Logger, keys ...string) log.Logger {
indices := make(map[string]int, len(keys))
for i, k := range keys {
indices[k] = i
}
return log.LoggerFunc(func(keyvals ...interface{}) error {
sortKeyvals(indices, keyvals)
return outputLogger.Log(keyvals...)
})
} | go | func SortLogger(outputLogger log.Logger, keys ...string) log.Logger {
indices := make(map[string]int, len(keys))
for i, k := range keys {
indices[k] = i
}
return log.LoggerFunc(func(keyvals ...interface{}) error {
sortKeyvals(indices, keyvals)
return outputLogger.Log(keyvals...)
})
} | [
"func",
"SortLogger",
"(",
"outputLogger",
"log",
".",
"Logger",
",",
"keys",
"...",
"string",
")",
"log",
".",
"Logger",
"{",
"indices",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"int",
",",
"len",
"(",
"keys",
")",
")",
"\n",
"for",
"i",
",",
"k",
":=",
"range",
"keys",
"{",
"indices",
"[",
"k",
"]",
"=",
"i",
"\n",
"}",
"\n",
"return",
"log",
".",
"LoggerFunc",
"(",
"func",
"(",
"keyvals",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"sortKeyvals",
"(",
"indices",
",",
"keyvals",
")",
"\n",
"return",
"outputLogger",
".",
"Log",
"(",
"keyvals",
"...",
")",
"\n",
"}",
")",
"\n",
"}"
] | // Provides a logger that sorts key-values with keys in keys before other key-values | [
"Provides",
"a",
"logger",
"that",
"sorts",
"key",
"-",
"values",
"with",
"keys",
"in",
"keys",
"before",
"other",
"key",
"-",
"values"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/logging/loggers/sort_logger.go#L63-L72 | train |
hyperledger/burrow | permission/account_permissions.go | HasRole | func (ap AccountPermissions) HasRole(role string) bool {
role = string(binary.RightPadBytes([]byte(role), 32))
for _, r := range ap.Roles {
if r == role {
return true
}
}
return false
} | go | func (ap AccountPermissions) HasRole(role string) bool {
role = string(binary.RightPadBytes([]byte(role), 32))
for _, r := range ap.Roles {
if r == role {
return true
}
}
return false
} | [
"func",
"(",
"ap",
"AccountPermissions",
")",
"HasRole",
"(",
"role",
"string",
")",
"bool",
"{",
"role",
"=",
"string",
"(",
"binary",
".",
"RightPadBytes",
"(",
"[",
"]",
"byte",
"(",
"role",
")",
",",
"32",
")",
")",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"ap",
".",
"Roles",
"{",
"if",
"r",
"==",
"role",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // Returns true if the role is found | [
"Returns",
"true",
"if",
"the",
"role",
"is",
"found"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/permission/account_permissions.go#L19-L27 | train |
hyperledger/burrow | permission/account_permissions.go | RemoveRole | func (ap *AccountPermissions) RemoveRole(role string) bool {
role = string(binary.RightPadBytes([]byte(role), 32))
for i, r := range ap.Roles {
if r == role {
post := []string{}
if len(ap.Roles) > i+1 {
post = ap.Roles[i+1:]
}
ap.Roles = append(ap.Roles[:i], post...)
return true
}
}
return false
} | go | func (ap *AccountPermissions) RemoveRole(role string) bool {
role = string(binary.RightPadBytes([]byte(role), 32))
for i, r := range ap.Roles {
if r == role {
post := []string{}
if len(ap.Roles) > i+1 {
post = ap.Roles[i+1:]
}
ap.Roles = append(ap.Roles[:i], post...)
return true
}
}
return false
} | [
"func",
"(",
"ap",
"*",
"AccountPermissions",
")",
"RemoveRole",
"(",
"role",
"string",
")",
"bool",
"{",
"role",
"=",
"string",
"(",
"binary",
".",
"RightPadBytes",
"(",
"[",
"]",
"byte",
"(",
"role",
")",
",",
"32",
")",
")",
"\n",
"for",
"i",
",",
"r",
":=",
"range",
"ap",
".",
"Roles",
"{",
"if",
"r",
"==",
"role",
"{",
"post",
":=",
"[",
"]",
"string",
"{",
"}",
"\n",
"if",
"len",
"(",
"ap",
".",
"Roles",
")",
">",
"i",
"+",
"1",
"{",
"post",
"=",
"ap",
".",
"Roles",
"[",
"i",
"+",
"1",
":",
"]",
"\n",
"}",
"\n",
"ap",
".",
"Roles",
"=",
"append",
"(",
"ap",
".",
"Roles",
"[",
":",
"i",
"]",
",",
"post",
"...",
")",
"\n",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // Returns true if the role is removed, and false if it is not found | [
"Returns",
"true",
"if",
"the",
"role",
"is",
"removed",
"and",
"false",
"if",
"it",
"is",
"not",
"found"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/permission/account_permissions.go#L42-L55 | train |
hyperledger/burrow | permission/account_permissions.go | Clone | func (ap *AccountPermissions) Clone() AccountPermissions {
// clone base permissions
basePermissionsClone := ap.Base
var rolesClone []string
// It helps if we normalise empty roles to []string(nil) rather than []string{}
if len(ap.Roles) > 0 {
// clone roles []string
rolesClone = make([]string, len(ap.Roles))
// strings are immutable so copy suffices
copy(rolesClone, ap.Roles)
}
return AccountPermissions{
Base: basePermissionsClone,
Roles: rolesClone,
}
} | go | func (ap *AccountPermissions) Clone() AccountPermissions {
// clone base permissions
basePermissionsClone := ap.Base
var rolesClone []string
// It helps if we normalise empty roles to []string(nil) rather than []string{}
if len(ap.Roles) > 0 {
// clone roles []string
rolesClone = make([]string, len(ap.Roles))
// strings are immutable so copy suffices
copy(rolesClone, ap.Roles)
}
return AccountPermissions{
Base: basePermissionsClone,
Roles: rolesClone,
}
} | [
"func",
"(",
"ap",
"*",
"AccountPermissions",
")",
"Clone",
"(",
")",
"AccountPermissions",
"{",
"basePermissionsClone",
":=",
"ap",
".",
"Base",
"\n",
"var",
"rolesClone",
"[",
"]",
"string",
"\n",
"if",
"len",
"(",
"ap",
".",
"Roles",
")",
">",
"0",
"{",
"rolesClone",
"=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"ap",
".",
"Roles",
")",
")",
"\n",
"copy",
"(",
"rolesClone",
",",
"ap",
".",
"Roles",
")",
"\n",
"}",
"\n",
"return",
"AccountPermissions",
"{",
"Base",
":",
"basePermissionsClone",
",",
"Roles",
":",
"rolesClone",
",",
"}",
"\n",
"}"
] | // Clone clones the account permissions | [
"Clone",
"clones",
"the",
"account",
"permissions"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/permission/account_permissions.go#L58-L74 | train |
hyperledger/burrow | txs/envelope.go | RealisePublicKey | func (s *Signatory) RealisePublicKey(getter acmstate.AccountGetter) error {
const errPrefix = "could not realise public key for signatory"
if s.PublicKey == nil {
if s.Address == nil {
return fmt.Errorf("%s: address not provided", errPrefix)
}
acc, err := getter.GetAccount(*s.Address)
if err != nil {
return fmt.Errorf("%s: could not get account %v: %v", errPrefix, *s.Address, err)
}
publicKey := acc.PublicKey
s.PublicKey = &publicKey
}
if !s.PublicKey.IsValid() {
return fmt.Errorf("%s: public key %v is invalid", errPrefix, *s.PublicKey)
}
address := s.PublicKey.GetAddress()
if s.Address == nil {
s.Address = &address
} else if address != *s.Address {
return fmt.Errorf("address %v provided with signatory does not match address generated from "+
"public key %v", *s.Address, address)
}
return nil
} | go | func (s *Signatory) RealisePublicKey(getter acmstate.AccountGetter) error {
const errPrefix = "could not realise public key for signatory"
if s.PublicKey == nil {
if s.Address == nil {
return fmt.Errorf("%s: address not provided", errPrefix)
}
acc, err := getter.GetAccount(*s.Address)
if err != nil {
return fmt.Errorf("%s: could not get account %v: %v", errPrefix, *s.Address, err)
}
publicKey := acc.PublicKey
s.PublicKey = &publicKey
}
if !s.PublicKey.IsValid() {
return fmt.Errorf("%s: public key %v is invalid", errPrefix, *s.PublicKey)
}
address := s.PublicKey.GetAddress()
if s.Address == nil {
s.Address = &address
} else if address != *s.Address {
return fmt.Errorf("address %v provided with signatory does not match address generated from "+
"public key %v", *s.Address, address)
}
return nil
} | [
"func",
"(",
"s",
"*",
"Signatory",
")",
"RealisePublicKey",
"(",
"getter",
"acmstate",
".",
"AccountGetter",
")",
"error",
"{",
"const",
"errPrefix",
"=",
"\"could not realise public key for signatory\"",
"\n",
"if",
"s",
".",
"PublicKey",
"==",
"nil",
"{",
"if",
"s",
".",
"Address",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"%s: address not provided\"",
",",
"errPrefix",
")",
"\n",
"}",
"\n",
"acc",
",",
"err",
":=",
"getter",
".",
"GetAccount",
"(",
"*",
"s",
".",
"Address",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"%s: could not get account %v: %v\"",
",",
"errPrefix",
",",
"*",
"s",
".",
"Address",
",",
"err",
")",
"\n",
"}",
"\n",
"publicKey",
":=",
"acc",
".",
"PublicKey",
"\n",
"s",
".",
"PublicKey",
"=",
"&",
"publicKey",
"\n",
"}",
"\n",
"if",
"!",
"s",
".",
"PublicKey",
".",
"IsValid",
"(",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"%s: public key %v is invalid\"",
",",
"errPrefix",
",",
"*",
"s",
".",
"PublicKey",
")",
"\n",
"}",
"\n",
"address",
":=",
"s",
".",
"PublicKey",
".",
"GetAddress",
"(",
")",
"\n",
"if",
"s",
".",
"Address",
"==",
"nil",
"{",
"s",
".",
"Address",
"=",
"&",
"address",
"\n",
"}",
"else",
"if",
"address",
"!=",
"*",
"s",
".",
"Address",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"address %v provided with signatory does not match address generated from \"",
"+",
"\"public key %v\"",
",",
"*",
"s",
".",
"Address",
",",
"address",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Attempts to 'realise' the PublicKey and Address of a Signatory possibly referring to state
// in the case where the Signatory contains an Address by no PublicKey. Checks consistency in other
// cases, possibly generating the Address from the PublicKey | [
"Attempts",
"to",
"realise",
"the",
"PublicKey",
"and",
"Address",
"of",
"a",
"Signatory",
"possibly",
"referring",
"to",
"state",
"in",
"the",
"case",
"where",
"the",
"Signatory",
"contains",
"an",
"Address",
"by",
"no",
"PublicKey",
".",
"Checks",
"consistency",
"in",
"other",
"cases",
"possibly",
"generating",
"the",
"Address",
"from",
"the",
"PublicKey"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/txs/envelope.go#L41-L65 | train |
hyperledger/burrow | vent/types/event_class.go | Validate | func (ec *EventClass) Validate() error {
return validation.ValidateStruct(ec,
validation.Field(&ec.TableName, validation.Required, validation.Length(1, 60)),
validation.Field(&ec.Filter, validation.Required),
validation.Field(&ec.FieldMappings, validation.Required, validation.Length(1, 0)),
)
} | go | func (ec *EventClass) Validate() error {
return validation.ValidateStruct(ec,
validation.Field(&ec.TableName, validation.Required, validation.Length(1, 60)),
validation.Field(&ec.Filter, validation.Required),
validation.Field(&ec.FieldMappings, validation.Required, validation.Length(1, 0)),
)
} | [
"func",
"(",
"ec",
"*",
"EventClass",
")",
"Validate",
"(",
")",
"error",
"{",
"return",
"validation",
".",
"ValidateStruct",
"(",
"ec",
",",
"validation",
".",
"Field",
"(",
"&",
"ec",
".",
"TableName",
",",
"validation",
".",
"Required",
",",
"validation",
".",
"Length",
"(",
"1",
",",
"60",
")",
")",
",",
"validation",
".",
"Field",
"(",
"&",
"ec",
".",
"Filter",
",",
"validation",
".",
"Required",
")",
",",
"validation",
".",
"Field",
"(",
"&",
"ec",
".",
"FieldMappings",
",",
"validation",
".",
"Required",
",",
"validation",
".",
"Length",
"(",
"1",
",",
"0",
")",
")",
",",
")",
"\n",
"}"
] | // Validate checks the structure of an EventClass | [
"Validate",
"checks",
"the",
"structure",
"of",
"an",
"EventClass"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/vent/types/event_class.go#L33-L39 | train |
hyperledger/burrow | vent/types/event_class.go | Validate | func (evColumn EventFieldMapping) Validate() error {
return validation.ValidateStruct(&evColumn,
validation.Field(&evColumn.ColumnName, validation.Required, validation.Length(1, 60)),
)
} | go | func (evColumn EventFieldMapping) Validate() error {
return validation.ValidateStruct(&evColumn,
validation.Field(&evColumn.ColumnName, validation.Required, validation.Length(1, 60)),
)
} | [
"func",
"(",
"evColumn",
"EventFieldMapping",
")",
"Validate",
"(",
")",
"error",
"{",
"return",
"validation",
".",
"ValidateStruct",
"(",
"&",
"evColumn",
",",
"validation",
".",
"Field",
"(",
"&",
"evColumn",
".",
"ColumnName",
",",
"validation",
".",
"Required",
",",
"validation",
".",
"Length",
"(",
"1",
",",
"60",
")",
")",
",",
")",
"\n",
"}"
] | // Validate checks the structure of an EventFieldMapping | [
"Validate",
"checks",
"the",
"structure",
"of",
"an",
"EventFieldMapping"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/vent/types/event_class.go#L88-L92 | train |
hyperledger/burrow | storage/mutable_forest.go | Load | func (muf *MutableForest) Load(version int64) error {
return muf.commitsTree.Load(version, true)
} | go | func (muf *MutableForest) Load(version int64) error {
return muf.commitsTree.Load(version, true)
} | [
"func",
"(",
"muf",
"*",
"MutableForest",
")",
"Load",
"(",
"version",
"int64",
")",
"error",
"{",
"return",
"muf",
".",
"commitsTree",
".",
"Load",
"(",
"version",
",",
"true",
")",
"\n",
"}"
] | // Load mutable forest from database, pass overwriting = true if you wish to make writes to version version + 1.
// this will | [
"Load",
"mutable",
"forest",
"from",
"database",
"pass",
"overwriting",
"=",
"true",
"if",
"you",
"wish",
"to",
"make",
"writes",
"to",
"version",
"version",
"+",
"1",
".",
"this",
"will"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/storage/mutable_forest.go#L84-L86 | train |
hyperledger/burrow | storage/mutable_forest.go | Writer | func (muf *MutableForest) Writer(prefix []byte) (*RWTree, error) {
// Try dirty cache first (if tree is new it may only be in this location)
prefixString := string(prefix)
if tree, ok := muf.dirty[prefixString]; ok {
return tree, nil
}
tree, err := muf.tree(prefix)
if err != nil {
return nil, err
}
// Mark tree as dirty
muf.dirty[prefixString] = tree
muf.dirtyPrefixes = append(muf.dirtyPrefixes, prefixString)
return tree, nil
} | go | func (muf *MutableForest) Writer(prefix []byte) (*RWTree, error) {
// Try dirty cache first (if tree is new it may only be in this location)
prefixString := string(prefix)
if tree, ok := muf.dirty[prefixString]; ok {
return tree, nil
}
tree, err := muf.tree(prefix)
if err != nil {
return nil, err
}
// Mark tree as dirty
muf.dirty[prefixString] = tree
muf.dirtyPrefixes = append(muf.dirtyPrefixes, prefixString)
return tree, nil
} | [
"func",
"(",
"muf",
"*",
"MutableForest",
")",
"Writer",
"(",
"prefix",
"[",
"]",
"byte",
")",
"(",
"*",
"RWTree",
",",
"error",
")",
"{",
"prefixString",
":=",
"string",
"(",
"prefix",
")",
"\n",
"if",
"tree",
",",
"ok",
":=",
"muf",
".",
"dirty",
"[",
"prefixString",
"]",
";",
"ok",
"{",
"return",
"tree",
",",
"nil",
"\n",
"}",
"\n",
"tree",
",",
"err",
":=",
"muf",
".",
"tree",
"(",
"prefix",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"muf",
".",
"dirty",
"[",
"prefixString",
"]",
"=",
"tree",
"\n",
"muf",
".",
"dirtyPrefixes",
"=",
"append",
"(",
"muf",
".",
"dirtyPrefixes",
",",
"prefixString",
")",
"\n",
"return",
"tree",
",",
"nil",
"\n",
"}"
] | // Calls to writer should be serialised as should writes to the tree | [
"Calls",
"to",
"writer",
"should",
"be",
"serialised",
"as",
"should",
"writes",
"to",
"the",
"tree"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/storage/mutable_forest.go#L115-L129 | train |
hyperledger/burrow | storage/mutable_forest.go | Delete | func (muf *MutableForest) Delete(prefix []byte) (*CommitID, error) {
bs, removed := muf.commitsTree.Delete(prefix)
if !removed {
return nil, nil
}
return UnmarshalCommitID(bs)
} | go | func (muf *MutableForest) Delete(prefix []byte) (*CommitID, error) {
bs, removed := muf.commitsTree.Delete(prefix)
if !removed {
return nil, nil
}
return UnmarshalCommitID(bs)
} | [
"func",
"(",
"muf",
"*",
"MutableForest",
")",
"Delete",
"(",
"prefix",
"[",
"]",
"byte",
")",
"(",
"*",
"CommitID",
",",
"error",
")",
"{",
"bs",
",",
"removed",
":=",
"muf",
".",
"commitsTree",
".",
"Delete",
"(",
"prefix",
")",
"\n",
"if",
"!",
"removed",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"return",
"UnmarshalCommitID",
"(",
"bs",
")",
"\n",
"}"
] | // Delete a tree - if the tree exists will return the CommitID of the latest saved version | [
"Delete",
"a",
"tree",
"-",
"if",
"the",
"tree",
"exists",
"will",
"return",
"the",
"CommitID",
"of",
"the",
"latest",
"saved",
"version"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/storage/mutable_forest.go#L132-L138 | train |
hyperledger/burrow | logging/loggers/multiple_output_logger.go | NewMultipleOutputLogger | func NewMultipleOutputLogger(outputLoggers ...log.Logger) log.Logger {
moLogger := make(MultipleOutputLogger, 0, len(outputLoggers))
// Flatten any MultipleOutputLoggers
for _, ol := range outputLoggers {
if ls, ok := ol.(MultipleOutputLogger); ok {
moLogger = append(moLogger, ls...)
} else {
moLogger = append(moLogger, ol)
}
}
return moLogger
} | go | func NewMultipleOutputLogger(outputLoggers ...log.Logger) log.Logger {
moLogger := make(MultipleOutputLogger, 0, len(outputLoggers))
// Flatten any MultipleOutputLoggers
for _, ol := range outputLoggers {
if ls, ok := ol.(MultipleOutputLogger); ok {
moLogger = append(moLogger, ls...)
} else {
moLogger = append(moLogger, ol)
}
}
return moLogger
} | [
"func",
"NewMultipleOutputLogger",
"(",
"outputLoggers",
"...",
"log",
".",
"Logger",
")",
"log",
".",
"Logger",
"{",
"moLogger",
":=",
"make",
"(",
"MultipleOutputLogger",
",",
"0",
",",
"len",
"(",
"outputLoggers",
")",
")",
"\n",
"for",
"_",
",",
"ol",
":=",
"range",
"outputLoggers",
"{",
"if",
"ls",
",",
"ok",
":=",
"ol",
".",
"(",
"MultipleOutputLogger",
")",
";",
"ok",
"{",
"moLogger",
"=",
"append",
"(",
"moLogger",
",",
"ls",
"...",
")",
"\n",
"}",
"else",
"{",
"moLogger",
"=",
"append",
"(",
"moLogger",
",",
"ol",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"moLogger",
"\n",
"}"
] | // Creates a logger that forks log messages to each of its outputLoggers | [
"Creates",
"a",
"logger",
"that",
"forks",
"log",
"messages",
"to",
"each",
"of",
"its",
"outputLoggers"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/logging/loggers/multiple_output_logger.go#L40-L51 | train |
hyperledger/burrow | deploy/util/readers.go | ReadTxSignAndBroadcast | func ReadTxSignAndBroadcast(txe *exec.TxExecution, err error, logger *logging.Logger) error {
// if there's an error just return.
if err != nil {
return err
}
// if there is nothing to unpack then just return.
if txe == nil {
return nil
}
// Unpack and display for the user.
height := fmt.Sprintf("%d", txe.Height)
if txe.Receipt.CreatesContract {
logger.InfoMsg("Tx Return",
"addr", txe.Receipt.ContractAddress.String(),
"Transaction Hash", hex.EncodeToString(txe.TxHash))
} else {
logger.InfoMsg("Tx Return",
"Transaction Hash", hex.EncodeToString(txe.TxHash),
"Block Height", height)
ret := txe.GetResult().GetReturn()
if len(ret) != 0 {
logger.InfoMsg("Return",
"Return Value", hex.EncodeUpperToString(ret),
"Exception", txe.Exception)
}
}
return nil
} | go | func ReadTxSignAndBroadcast(txe *exec.TxExecution, err error, logger *logging.Logger) error {
// if there's an error just return.
if err != nil {
return err
}
// if there is nothing to unpack then just return.
if txe == nil {
return nil
}
// Unpack and display for the user.
height := fmt.Sprintf("%d", txe.Height)
if txe.Receipt.CreatesContract {
logger.InfoMsg("Tx Return",
"addr", txe.Receipt.ContractAddress.String(),
"Transaction Hash", hex.EncodeToString(txe.TxHash))
} else {
logger.InfoMsg("Tx Return",
"Transaction Hash", hex.EncodeToString(txe.TxHash),
"Block Height", height)
ret := txe.GetResult().GetReturn()
if len(ret) != 0 {
logger.InfoMsg("Return",
"Return Value", hex.EncodeUpperToString(ret),
"Exception", txe.Exception)
}
}
return nil
} | [
"func",
"ReadTxSignAndBroadcast",
"(",
"txe",
"*",
"exec",
".",
"TxExecution",
",",
"err",
"error",
",",
"logger",
"*",
"logging",
".",
"Logger",
")",
"error",
"{",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"txe",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"height",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"%d\"",
",",
"txe",
".",
"Height",
")",
"\n",
"if",
"txe",
".",
"Receipt",
".",
"CreatesContract",
"{",
"logger",
".",
"InfoMsg",
"(",
"\"Tx Return\"",
",",
"\"addr\"",
",",
"txe",
".",
"Receipt",
".",
"ContractAddress",
".",
"String",
"(",
")",
",",
"\"Transaction Hash\"",
",",
"hex",
".",
"EncodeToString",
"(",
"txe",
".",
"TxHash",
")",
")",
"\n",
"}",
"else",
"{",
"logger",
".",
"InfoMsg",
"(",
"\"Tx Return\"",
",",
"\"Transaction Hash\"",
",",
"hex",
".",
"EncodeToString",
"(",
"txe",
".",
"TxHash",
")",
",",
"\"Block Height\"",
",",
"height",
")",
"\n",
"ret",
":=",
"txe",
".",
"GetResult",
"(",
")",
".",
"GetReturn",
"(",
")",
"\n",
"if",
"len",
"(",
"ret",
")",
"!=",
"0",
"{",
"logger",
".",
"InfoMsg",
"(",
"\"Return\"",
",",
"\"Return Value\"",
",",
"hex",
".",
"EncodeUpperToString",
"(",
"ret",
")",
",",
"\"Exception\"",
",",
"txe",
".",
"Exception",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // This is a closer function which is called by most of the tx_run functions | [
"This",
"is",
"a",
"closer",
"function",
"which",
"is",
"called",
"by",
"most",
"of",
"the",
"tx_run",
"functions"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/deploy/util/readers.go#L16-L48 | train |
hyperledger/burrow | deploy/util/readers.go | GetBoolResponse | func GetBoolResponse(question string, defaultAnswer bool, reader *os.File, logger *logging.Logger) (bool, error) {
var result bool
readr := bufio.NewReader(reader)
logger.InfoMsg(question)
text, _ := readr.ReadString('\n')
text = strings.Replace(text, "\n", "", 1)
if text == "" {
return defaultAnswer, nil
}
if text == "Yes" || text == "YES" || text == "Y" || text == "y" {
result = true
} else {
result = false
}
return result, nil
} | go | func GetBoolResponse(question string, defaultAnswer bool, reader *os.File, logger *logging.Logger) (bool, error) {
var result bool
readr := bufio.NewReader(reader)
logger.InfoMsg(question)
text, _ := readr.ReadString('\n')
text = strings.Replace(text, "\n", "", 1)
if text == "" {
return defaultAnswer, nil
}
if text == "Yes" || text == "YES" || text == "Y" || text == "y" {
result = true
} else {
result = false
}
return result, nil
} | [
"func",
"GetBoolResponse",
"(",
"question",
"string",
",",
"defaultAnswer",
"bool",
",",
"reader",
"*",
"os",
".",
"File",
",",
"logger",
"*",
"logging",
".",
"Logger",
")",
"(",
"bool",
",",
"error",
")",
"{",
"var",
"result",
"bool",
"\n",
"readr",
":=",
"bufio",
".",
"NewReader",
"(",
"reader",
")",
"\n",
"logger",
".",
"InfoMsg",
"(",
"question",
")",
"\n",
"text",
",",
"_",
":=",
"readr",
".",
"ReadString",
"(",
"'\\n'",
")",
"\n",
"text",
"=",
"strings",
".",
"Replace",
"(",
"text",
",",
"\"\\n\"",
",",
"\\n",
",",
"\"\"",
")",
"\n",
"1",
"\n",
"if",
"text",
"==",
"\"\"",
"{",
"return",
"defaultAnswer",
",",
"nil",
"\n",
"}",
"\n",
"if",
"text",
"==",
"\"Yes\"",
"||",
"text",
"==",
"\"YES\"",
"||",
"text",
"==",
"\"Y\"",
"||",
"text",
"==",
"\"y\"",
"{",
"result",
"=",
"true",
"\n",
"}",
"else",
"{",
"result",
"=",
"false",
"\n",
"}",
"\n",
"}"
] | // displays the question, scans for the response, if the response is an empty
// string will return default, otherwise will parseBool and return the result. | [
"displays",
"the",
"question",
"scans",
"for",
"the",
"response",
"if",
"the",
"response",
"is",
"an",
"empty",
"string",
"will",
"return",
"default",
"otherwise",
"will",
"parseBool",
"and",
"return",
"the",
"result",
"."
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/deploy/util/readers.go#L81-L99 | train |
hyperledger/burrow | execution/proposal/cache.go | Flush | func (cache *Cache) Flush(output Writer, backend Reader) error {
err := cache.Sync(output)
if err != nil {
return err
}
cache.Reset(backend)
return nil
} | go | func (cache *Cache) Flush(output Writer, backend Reader) error {
err := cache.Sync(output)
if err != nil {
return err
}
cache.Reset(backend)
return nil
} | [
"func",
"(",
"cache",
"*",
"Cache",
")",
"Flush",
"(",
"output",
"Writer",
",",
"backend",
"Reader",
")",
"error",
"{",
"err",
":=",
"cache",
".",
"Sync",
"(",
"output",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"cache",
".",
"Reset",
"(",
"backend",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Syncs the Cache and Resets it to use Writer as the backend Reader | [
"Syncs",
"the",
"Cache",
"and",
"Resets",
"it",
"to",
"use",
"Writer",
"as",
"the",
"backend",
"Reader"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/execution/proposal/cache.go#L163-L170 | train |
hyperledger/burrow | vent/config/config.go | DefaultVentConfig | func DefaultVentConfig() *VentConfig {
return &VentConfig{
DBAdapter: types.PostgresDB,
DBURL: DefaultPostgresDBURL,
DBSchema: "vent",
GRPCAddr: "localhost:10997",
HTTPAddr: "0.0.0.0:8080",
LogLevel: "debug",
DBBlockTx: false,
AnnounceEvery: time.Second * 5,
}
} | go | func DefaultVentConfig() *VentConfig {
return &VentConfig{
DBAdapter: types.PostgresDB,
DBURL: DefaultPostgresDBURL,
DBSchema: "vent",
GRPCAddr: "localhost:10997",
HTTPAddr: "0.0.0.0:8080",
LogLevel: "debug",
DBBlockTx: false,
AnnounceEvery: time.Second * 5,
}
} | [
"func",
"DefaultVentConfig",
"(",
")",
"*",
"VentConfig",
"{",
"return",
"&",
"VentConfig",
"{",
"DBAdapter",
":",
"types",
".",
"PostgresDB",
",",
"DBURL",
":",
"DefaultPostgresDBURL",
",",
"DBSchema",
":",
"\"vent\"",
",",
"GRPCAddr",
":",
"\"localhost:10997\"",
",",
"HTTPAddr",
":",
"\"0.0.0.0:8080\"",
",",
"LogLevel",
":",
"\"debug\"",
",",
"DBBlockTx",
":",
"false",
",",
"AnnounceEvery",
":",
"time",
".",
"Second",
"*",
"5",
",",
"}",
"\n",
"}"
] | // DefaultFlags returns a configuration with default values | [
"DefaultFlags",
"returns",
"a",
"configuration",
"with",
"default",
"values"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/vent/config/config.go#L27-L38 | train |
hyperledger/burrow | rpc/metrics/exporter.go | NewExporter | func NewExporter(service InfoService, blockSampleSize int, logger *logging.Logger) (*Exporter, error) {
chainStatus, err := service.Status()
if err != nil {
return nil, fmt.Errorf("NewExporter(): %v", err)
}
return &Exporter{
datum: &Datum{},
service: service,
chainID: chainStatus.NodeInfo.Network,
validatorMoniker: chainStatus.NodeInfo.Moniker,
blockSampleSize: uint64(blockSampleSize),
txPerBlockHistogramBuilder: makeHistogramBuilder(identity),
timePerBlockHistogramBuilder: makeHistogramBuilder(significantFiguresRounder(significantFiguresForSeconds)),
logger: logger.With(structure.ComponentKey, "Metrics_Exporter"),
}, nil
} | go | func NewExporter(service InfoService, blockSampleSize int, logger *logging.Logger) (*Exporter, error) {
chainStatus, err := service.Status()
if err != nil {
return nil, fmt.Errorf("NewExporter(): %v", err)
}
return &Exporter{
datum: &Datum{},
service: service,
chainID: chainStatus.NodeInfo.Network,
validatorMoniker: chainStatus.NodeInfo.Moniker,
blockSampleSize: uint64(blockSampleSize),
txPerBlockHistogramBuilder: makeHistogramBuilder(identity),
timePerBlockHistogramBuilder: makeHistogramBuilder(significantFiguresRounder(significantFiguresForSeconds)),
logger: logger.With(structure.ComponentKey, "Metrics_Exporter"),
}, nil
} | [
"func",
"NewExporter",
"(",
"service",
"InfoService",
",",
"blockSampleSize",
"int",
",",
"logger",
"*",
"logging",
".",
"Logger",
")",
"(",
"*",
"Exporter",
",",
"error",
")",
"{",
"chainStatus",
",",
"err",
":=",
"service",
".",
"Status",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"NewExporter(): %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"&",
"Exporter",
"{",
"datum",
":",
"&",
"Datum",
"{",
"}",
",",
"service",
":",
"service",
",",
"chainID",
":",
"chainStatus",
".",
"NodeInfo",
".",
"Network",
",",
"validatorMoniker",
":",
"chainStatus",
".",
"NodeInfo",
".",
"Moniker",
",",
"blockSampleSize",
":",
"uint64",
"(",
"blockSampleSize",
")",
",",
"txPerBlockHistogramBuilder",
":",
"makeHistogramBuilder",
"(",
"identity",
")",
",",
"timePerBlockHistogramBuilder",
":",
"makeHistogramBuilder",
"(",
"significantFiguresRounder",
"(",
"significantFiguresForSeconds",
")",
")",
",",
"logger",
":",
"logger",
".",
"With",
"(",
"structure",
".",
"ComponentKey",
",",
"\"Metrics_Exporter\"",
")",
",",
"}",
",",
"nil",
"\n",
"}"
] | // Exporter uses the InfoService to provide pre-aggregated metrics of various types that are then passed to prometheus
// as Const metrics rather than being accumulated by individual operations throughout the rest of the Burrow code. | [
"Exporter",
"uses",
"the",
"InfoService",
"to",
"provide",
"pre",
"-",
"aggregated",
"metrics",
"of",
"various",
"types",
"that",
"are",
"then",
"passed",
"to",
"prometheus",
"as",
"Const",
"metrics",
"rather",
"than",
"being",
"accumulated",
"by",
"individual",
"operations",
"throughout",
"the",
"rest",
"of",
"the",
"Burrow",
"code",
"."
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/rpc/metrics/exporter.go#L77-L92 | train |
hyperledger/burrow | rpc/metrics/exporter.go | Describe | func (e *Exporter) Describe(ch chan<- *prometheus.Desc) {
for _, m := range MetricDescriptions {
ch <- m
}
} | go | func (e *Exporter) Describe(ch chan<- *prometheus.Desc) {
for _, m := range MetricDescriptions {
ch <- m
}
} | [
"func",
"(",
"e",
"*",
"Exporter",
")",
"Describe",
"(",
"ch",
"chan",
"<-",
"*",
"prometheus",
".",
"Desc",
")",
"{",
"for",
"_",
",",
"m",
":=",
"range",
"MetricDescriptions",
"{",
"ch",
"<-",
"m",
"\n",
"}",
"\n",
"}"
] | // Describe - loops through the API metrics and passes them to prometheus.Describe | [
"Describe",
"-",
"loops",
"through",
"the",
"API",
"metrics",
"and",
"passes",
"them",
"to",
"prometheus",
".",
"Describe"
] | 59993f5aad71a8e16ab6ed4e57e138e2398eae4e | https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/rpc/metrics/exporter.go#L95-L99 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.