id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequencelengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
sequencelengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
151,500
tecbot/gorocksdb
memory_usage.go
GetApproximateMemoryUsageByType
func GetApproximateMemoryUsageByType(dbs []*DB, caches []*Cache) (*MemoryUsage, error) { // register memory consumers consumers := C.rocksdb_memory_consumers_create() defer C.rocksdb_memory_consumers_destroy(consumers) for _, db := range dbs { if db != nil { C.rocksdb_memory_consumers_add_db(consumers, db.c) } } for _, cache := range caches { if cache != nil { C.rocksdb_memory_consumers_add_cache(consumers, cache.c) } } // obtain memory usage stats var cErr *C.char memoryUsage := C.rocksdb_approximate_memory_usage_create(consumers, &cErr) if cErr != nil { defer C.free(unsafe.Pointer(cErr)) return nil, errors.New(C.GoString(cErr)) } defer C.rocksdb_approximate_memory_usage_destroy(memoryUsage) result := &MemoryUsage{ MemTableTotal: uint64(C.rocksdb_approximate_memory_usage_get_mem_table_total(memoryUsage)), MemTableUnflushed: uint64(C.rocksdb_approximate_memory_usage_get_mem_table_unflushed(memoryUsage)), MemTableReadersTotal: uint64(C.rocksdb_approximate_memory_usage_get_mem_table_readers_total(memoryUsage)), CacheTotal: uint64(C.rocksdb_approximate_memory_usage_get_cache_total(memoryUsage)), } return result, nil }
go
func GetApproximateMemoryUsageByType(dbs []*DB, caches []*Cache) (*MemoryUsage, error) { // register memory consumers consumers := C.rocksdb_memory_consumers_create() defer C.rocksdb_memory_consumers_destroy(consumers) for _, db := range dbs { if db != nil { C.rocksdb_memory_consumers_add_db(consumers, db.c) } } for _, cache := range caches { if cache != nil { C.rocksdb_memory_consumers_add_cache(consumers, cache.c) } } // obtain memory usage stats var cErr *C.char memoryUsage := C.rocksdb_approximate_memory_usage_create(consumers, &cErr) if cErr != nil { defer C.free(unsafe.Pointer(cErr)) return nil, errors.New(C.GoString(cErr)) } defer C.rocksdb_approximate_memory_usage_destroy(memoryUsage) result := &MemoryUsage{ MemTableTotal: uint64(C.rocksdb_approximate_memory_usage_get_mem_table_total(memoryUsage)), MemTableUnflushed: uint64(C.rocksdb_approximate_memory_usage_get_mem_table_unflushed(memoryUsage)), MemTableReadersTotal: uint64(C.rocksdb_approximate_memory_usage_get_mem_table_readers_total(memoryUsage)), CacheTotal: uint64(C.rocksdb_approximate_memory_usage_get_cache_total(memoryUsage)), } return result, nil }
[ "func", "GetApproximateMemoryUsageByType", "(", "dbs", "[", "]", "*", "DB", ",", "caches", "[", "]", "*", "Cache", ")", "(", "*", "MemoryUsage", ",", "error", ")", "{", "// register memory consumers", "consumers", ":=", "C", ".", "rocksdb_memory_consumers_create", "(", ")", "\n", "defer", "C", ".", "rocksdb_memory_consumers_destroy", "(", "consumers", ")", "\n\n", "for", "_", ",", "db", ":=", "range", "dbs", "{", "if", "db", "!=", "nil", "{", "C", ".", "rocksdb_memory_consumers_add_db", "(", "consumers", ",", "db", ".", "c", ")", "\n", "}", "\n", "}", "\n", "for", "_", ",", "cache", ":=", "range", "caches", "{", "if", "cache", "!=", "nil", "{", "C", ".", "rocksdb_memory_consumers_add_cache", "(", "consumers", ",", "cache", ".", "c", ")", "\n", "}", "\n", "}", "\n\n", "// obtain memory usage stats", "var", "cErr", "*", "C", ".", "char", "\n", "memoryUsage", ":=", "C", ".", "rocksdb_approximate_memory_usage_create", "(", "consumers", ",", "&", "cErr", ")", "\n", "if", "cErr", "!=", "nil", "{", "defer", "C", ".", "free", "(", "unsafe", ".", "Pointer", "(", "cErr", ")", ")", "\n", "return", "nil", ",", "errors", ".", "New", "(", "C", ".", "GoString", "(", "cErr", ")", ")", "\n", "}", "\n\n", "defer", "C", ".", "rocksdb_approximate_memory_usage_destroy", "(", "memoryUsage", ")", "\n\n", "result", ":=", "&", "MemoryUsage", "{", "MemTableTotal", ":", "uint64", "(", "C", ".", "rocksdb_approximate_memory_usage_get_mem_table_total", "(", "memoryUsage", ")", ")", ",", "MemTableUnflushed", ":", "uint64", "(", "C", ".", "rocksdb_approximate_memory_usage_get_mem_table_unflushed", "(", "memoryUsage", ")", ")", ",", "MemTableReadersTotal", ":", "uint64", "(", "C", ".", "rocksdb_approximate_memory_usage_get_mem_table_readers_total", "(", "memoryUsage", ")", ")", ",", "CacheTotal", ":", "uint64", "(", "C", ".", "rocksdb_approximate_memory_usage_get_cache_total", "(", "memoryUsage", ")", ")", ",", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// GetApproximateMemoryUsageByType returns summary // memory usage stats for given databases and caches.
[ "GetApproximateMemoryUsageByType", "returns", "summary", "memory", "usage", "stats", "for", "given", "databases", "and", "caches", "." ]
8752a943348155073ae407010e2b75c40480271a
https://github.com/tecbot/gorocksdb/blob/8752a943348155073ae407010e2b75c40480271a/memory_usage.go#L25-L58
151,501
tecbot/gorocksdb
transactiondb.go
OpenTransactionDb
func OpenTransactionDb( opts *Options, transactionDBOpts *TransactionDBOptions, name string, ) (*TransactionDB, error) { var ( cErr *C.char cName = C.CString(name) ) defer C.free(unsafe.Pointer(cName)) db := C.rocksdb_transactiondb_open( opts.c, transactionDBOpts.c, cName, &cErr) if cErr != nil { defer C.free(unsafe.Pointer(cErr)) return nil, errors.New(C.GoString(cErr)) } return &TransactionDB{ name: name, c: db, opts: opts, transactionDBOpts: transactionDBOpts, }, nil }
go
func OpenTransactionDb( opts *Options, transactionDBOpts *TransactionDBOptions, name string, ) (*TransactionDB, error) { var ( cErr *C.char cName = C.CString(name) ) defer C.free(unsafe.Pointer(cName)) db := C.rocksdb_transactiondb_open( opts.c, transactionDBOpts.c, cName, &cErr) if cErr != nil { defer C.free(unsafe.Pointer(cErr)) return nil, errors.New(C.GoString(cErr)) } return &TransactionDB{ name: name, c: db, opts: opts, transactionDBOpts: transactionDBOpts, }, nil }
[ "func", "OpenTransactionDb", "(", "opts", "*", "Options", ",", "transactionDBOpts", "*", "TransactionDBOptions", ",", "name", "string", ",", ")", "(", "*", "TransactionDB", ",", "error", ")", "{", "var", "(", "cErr", "*", "C", ".", "char", "\n", "cName", "=", "C", ".", "CString", "(", "name", ")", "\n", ")", "\n", "defer", "C", ".", "free", "(", "unsafe", ".", "Pointer", "(", "cName", ")", ")", "\n", "db", ":=", "C", ".", "rocksdb_transactiondb_open", "(", "opts", ".", "c", ",", "transactionDBOpts", ".", "c", ",", "cName", ",", "&", "cErr", ")", "\n", "if", "cErr", "!=", "nil", "{", "defer", "C", ".", "free", "(", "unsafe", ".", "Pointer", "(", "cErr", ")", ")", "\n", "return", "nil", ",", "errors", ".", "New", "(", "C", ".", "GoString", "(", "cErr", ")", ")", "\n", "}", "\n", "return", "&", "TransactionDB", "{", "name", ":", "name", ",", "c", ":", "db", ",", "opts", ":", "opts", ",", "transactionDBOpts", ":", "transactionDBOpts", ",", "}", ",", "nil", "\n", "}" ]
// OpenTransactionDb opens a database with the specified options.
[ "OpenTransactionDb", "opens", "a", "database", "with", "the", "specified", "options", "." ]
8752a943348155073ae407010e2b75c40480271a
https://github.com/tecbot/gorocksdb/blob/8752a943348155073ae407010e2b75c40480271a/transactiondb.go#L20-L42
151,502
tecbot/gorocksdb
transactiondb.go
TransactionBegin
func (db *TransactionDB) TransactionBegin( opts *WriteOptions, transactionOpts *TransactionOptions, oldTransaction *Transaction, ) *Transaction { if oldTransaction != nil { return NewNativeTransaction(C.rocksdb_transaction_begin( db.c, opts.c, transactionOpts.c, oldTransaction.c, )) } return NewNativeTransaction(C.rocksdb_transaction_begin( db.c, opts.c, transactionOpts.c, nil)) }
go
func (db *TransactionDB) TransactionBegin( opts *WriteOptions, transactionOpts *TransactionOptions, oldTransaction *Transaction, ) *Transaction { if oldTransaction != nil { return NewNativeTransaction(C.rocksdb_transaction_begin( db.c, opts.c, transactionOpts.c, oldTransaction.c, )) } return NewNativeTransaction(C.rocksdb_transaction_begin( db.c, opts.c, transactionOpts.c, nil)) }
[ "func", "(", "db", "*", "TransactionDB", ")", "TransactionBegin", "(", "opts", "*", "WriteOptions", ",", "transactionOpts", "*", "TransactionOptions", ",", "oldTransaction", "*", "Transaction", ",", ")", "*", "Transaction", "{", "if", "oldTransaction", "!=", "nil", "{", "return", "NewNativeTransaction", "(", "C", ".", "rocksdb_transaction_begin", "(", "db", ".", "c", ",", "opts", ".", "c", ",", "transactionOpts", ".", "c", ",", "oldTransaction", ".", "c", ",", ")", ")", "\n", "}", "\n\n", "return", "NewNativeTransaction", "(", "C", ".", "rocksdb_transaction_begin", "(", "db", ".", "c", ",", "opts", ".", "c", ",", "transactionOpts", ".", "c", ",", "nil", ")", ")", "\n", "}" ]
// TransactionBegin begins a new transaction // with the WriteOptions and TransactionOptions given.
[ "TransactionBegin", "begins", "a", "new", "transaction", "with", "the", "WriteOptions", "and", "TransactionOptions", "given", "." ]
8752a943348155073ae407010e2b75c40480271a
https://github.com/tecbot/gorocksdb/blob/8752a943348155073ae407010e2b75c40480271a/transactiondb.go#L57-L73
151,503
tecbot/gorocksdb
transactiondb.go
NewCheckpoint
func (db *TransactionDB) NewCheckpoint() (*Checkpoint, error) { var ( cErr *C.char ) cCheckpoint := C.rocksdb_transactiondb_checkpoint_object_create( db.c, &cErr, ) if cErr != nil { defer C.free(unsafe.Pointer(cErr)) return nil, errors.New(C.GoString(cErr)) } return NewNativeCheckpoint(cCheckpoint), nil }
go
func (db *TransactionDB) NewCheckpoint() (*Checkpoint, error) { var ( cErr *C.char ) cCheckpoint := C.rocksdb_transactiondb_checkpoint_object_create( db.c, &cErr, ) if cErr != nil { defer C.free(unsafe.Pointer(cErr)) return nil, errors.New(C.GoString(cErr)) } return NewNativeCheckpoint(cCheckpoint), nil }
[ "func", "(", "db", "*", "TransactionDB", ")", "NewCheckpoint", "(", ")", "(", "*", "Checkpoint", ",", "error", ")", "{", "var", "(", "cErr", "*", "C", ".", "char", "\n", ")", "\n", "cCheckpoint", ":=", "C", ".", "rocksdb_transactiondb_checkpoint_object_create", "(", "db", ".", "c", ",", "&", "cErr", ",", ")", "\n", "if", "cErr", "!=", "nil", "{", "defer", "C", ".", "free", "(", "unsafe", ".", "Pointer", "(", "cErr", ")", ")", "\n", "return", "nil", ",", "errors", ".", "New", "(", "C", ".", "GoString", "(", "cErr", ")", ")", "\n", "}", "\n\n", "return", "NewNativeCheckpoint", "(", "cCheckpoint", ")", ",", "nil", "\n", "}" ]
// NewCheckpoint creates a new Checkpoint for this db.
[ "NewCheckpoint", "creates", "a", "new", "Checkpoint", "for", "this", "db", "." ]
8752a943348155073ae407010e2b75c40480271a
https://github.com/tecbot/gorocksdb/blob/8752a943348155073ae407010e2b75c40480271a/transactiondb.go#L124-L137
151,504
tecbot/gorocksdb
transactiondb.go
Close
func (transactionDB *TransactionDB) Close() { C.rocksdb_transactiondb_close(transactionDB.c) transactionDB.c = nil }
go
func (transactionDB *TransactionDB) Close() { C.rocksdb_transactiondb_close(transactionDB.c) transactionDB.c = nil }
[ "func", "(", "transactionDB", "*", "TransactionDB", ")", "Close", "(", ")", "{", "C", ".", "rocksdb_transactiondb_close", "(", "transactionDB", ".", "c", ")", "\n", "transactionDB", ".", "c", "=", "nil", "\n", "}" ]
// Close closes the database.
[ "Close", "closes", "the", "database", "." ]
8752a943348155073ae407010e2b75c40480271a
https://github.com/tecbot/gorocksdb/blob/8752a943348155073ae407010e2b75c40480271a/transactiondb.go#L140-L143
151,505
tecbot/gorocksdb
options_transaction.go
SetExpiration
func (opts *TransactionOptions) SetExpiration(expiration int64) { C.rocksdb_transaction_options_set_expiration(opts.c, C.int64_t(expiration)) }
go
func (opts *TransactionOptions) SetExpiration(expiration int64) { C.rocksdb_transaction_options_set_expiration(opts.c, C.int64_t(expiration)) }
[ "func", "(", "opts", "*", "TransactionOptions", ")", "SetExpiration", "(", "expiration", "int64", ")", "{", "C", ".", "rocksdb_transaction_options_set_expiration", "(", "opts", ".", "c", ",", "C", ".", "int64_t", "(", "expiration", ")", ")", "\n", "}" ]
// SetExpiration sets the Expiration duration in milliseconds. // If non-negative, transactions that last longer than this many milliseconds will fail to commit. // If not set, a forgotten transaction that is never committed, rolled back, or deleted // will never relinquish any locks it holds. This could prevent keys from // being written by other writers.
[ "SetExpiration", "sets", "the", "Expiration", "duration", "in", "milliseconds", ".", "If", "non", "-", "negative", "transactions", "that", "last", "longer", "than", "this", "many", "milliseconds", "will", "fail", "to", "commit", ".", "If", "not", "set", "a", "forgotten", "transaction", "that", "is", "never", "committed", "rolled", "back", "or", "deleted", "will", "never", "relinquish", "any", "locks", "it", "holds", ".", "This", "could", "prevent", "keys", "from", "being", "written", "by", "other", "writers", "." ]
8752a943348155073ae407010e2b75c40480271a
https://github.com/tecbot/gorocksdb/blob/8752a943348155073ae407010e2b75c40480271a/options_transaction.go#L48-L50
151,506
tecbot/gorocksdb
options_transaction.go
SetDeadlockDetectDepth
func (opts *TransactionOptions) SetDeadlockDetectDepth(depth int64) { C.rocksdb_transaction_options_set_deadlock_detect_depth(opts.c, C.int64_t(depth)) }
go
func (opts *TransactionOptions) SetDeadlockDetectDepth(depth int64) { C.rocksdb_transaction_options_set_deadlock_detect_depth(opts.c, C.int64_t(depth)) }
[ "func", "(", "opts", "*", "TransactionOptions", ")", "SetDeadlockDetectDepth", "(", "depth", "int64", ")", "{", "C", ".", "rocksdb_transaction_options_set_deadlock_detect_depth", "(", "opts", ".", "c", ",", "C", ".", "int64_t", "(", "depth", ")", ")", "\n", "}" ]
// SetDeadlockDetectDepth sets the number of traversals to make during deadlock detection.
[ "SetDeadlockDetectDepth", "sets", "the", "number", "of", "traversals", "to", "make", "during", "deadlock", "detection", "." ]
8752a943348155073ae407010e2b75c40480271a
https://github.com/tecbot/gorocksdb/blob/8752a943348155073ae407010e2b75c40480271a/options_transaction.go#L53-L55
151,507
tecbot/gorocksdb
options_transaction.go
SetMaxWriteBatchSize
func (opts *TransactionOptions) SetMaxWriteBatchSize(size uint64) { C.rocksdb_transaction_options_set_max_write_batch_size(opts.c, C.size_t(size)) }
go
func (opts *TransactionOptions) SetMaxWriteBatchSize(size uint64) { C.rocksdb_transaction_options_set_max_write_batch_size(opts.c, C.size_t(size)) }
[ "func", "(", "opts", "*", "TransactionOptions", ")", "SetMaxWriteBatchSize", "(", "size", "uint64", ")", "{", "C", ".", "rocksdb_transaction_options_set_max_write_batch_size", "(", "opts", ".", "c", ",", "C", ".", "size_t", "(", "size", ")", ")", "\n", "}" ]
// SetMaxWriteBatchSize sets the maximum number of bytes used for the write batch. 0 means no limit.
[ "SetMaxWriteBatchSize", "sets", "the", "maximum", "number", "of", "bytes", "used", "for", "the", "write", "batch", ".", "0", "means", "no", "limit", "." ]
8752a943348155073ae407010e2b75c40480271a
https://github.com/tecbot/gorocksdb/blob/8752a943348155073ae407010e2b75c40480271a/options_transaction.go#L58-L60
151,508
tecbot/gorocksdb
options_transaction.go
Destroy
func (opts *TransactionOptions) Destroy() { C.rocksdb_transaction_options_destroy(opts.c) opts.c = nil }
go
func (opts *TransactionOptions) Destroy() { C.rocksdb_transaction_options_destroy(opts.c) opts.c = nil }
[ "func", "(", "opts", "*", "TransactionOptions", ")", "Destroy", "(", ")", "{", "C", ".", "rocksdb_transaction_options_destroy", "(", "opts", ".", "c", ")", "\n", "opts", ".", "c", "=", "nil", "\n", "}" ]
// Destroy deallocates the TransactionOptions object.
[ "Destroy", "deallocates", "the", "TransactionOptions", "object", "." ]
8752a943348155073ae407010e2b75c40480271a
https://github.com/tecbot/gorocksdb/blob/8752a943348155073ae407010e2b75c40480271a/options_transaction.go#L63-L66
151,509
prometheus/procfs
proc.go
Self
func (fs FS) Self() (Proc, error) { p, err := os.Readlink(fs.Path("self")) if err != nil { return Proc{}, err } pid, err := strconv.Atoi(strings.Replace(p, string(fs), "", -1)) if err != nil { return Proc{}, err } return fs.NewProc(pid) }
go
func (fs FS) Self() (Proc, error) { p, err := os.Readlink(fs.Path("self")) if err != nil { return Proc{}, err } pid, err := strconv.Atoi(strings.Replace(p, string(fs), "", -1)) if err != nil { return Proc{}, err } return fs.NewProc(pid) }
[ "func", "(", "fs", "FS", ")", "Self", "(", ")", "(", "Proc", ",", "error", ")", "{", "p", ",", "err", ":=", "os", ".", "Readlink", "(", "fs", ".", "Path", "(", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Proc", "{", "}", ",", "err", "\n", "}", "\n", "pid", ",", "err", ":=", "strconv", ".", "Atoi", "(", "strings", ".", "Replace", "(", "p", ",", "string", "(", "fs", ")", ",", "\"", "\"", ",", "-", "1", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Proc", "{", "}", ",", "err", "\n", "}", "\n", "return", "fs", ".", "NewProc", "(", "pid", ")", "\n", "}" ]
// Self returns a process for the current process.
[ "Self", "returns", "a", "process", "for", "the", "current", "process", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/proc.go#L68-L78
151,510
prometheus/procfs
proc.go
NewProc
func (fs FS) NewProc(pid int) (Proc, error) { if _, err := os.Stat(fs.Path(strconv.Itoa(pid))); err != nil { return Proc{}, err } return Proc{PID: pid, fs: fs}, nil }
go
func (fs FS) NewProc(pid int) (Proc, error) { if _, err := os.Stat(fs.Path(strconv.Itoa(pid))); err != nil { return Proc{}, err } return Proc{PID: pid, fs: fs}, nil }
[ "func", "(", "fs", "FS", ")", "NewProc", "(", "pid", "int", ")", "(", "Proc", ",", "error", ")", "{", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "fs", ".", "Path", "(", "strconv", ".", "Itoa", "(", "pid", ")", ")", ")", ";", "err", "!=", "nil", "{", "return", "Proc", "{", "}", ",", "err", "\n", "}", "\n", "return", "Proc", "{", "PID", ":", "pid", ",", "fs", ":", "fs", "}", ",", "nil", "\n", "}" ]
// NewProc returns a process for the given pid.
[ "NewProc", "returns", "a", "process", "for", "the", "given", "pid", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/proc.go#L81-L86
151,511
prometheus/procfs
proc.go
AllProcs
func (fs FS) AllProcs() (Procs, error) { d, err := os.Open(fs.Path()) if err != nil { return Procs{}, err } defer d.Close() names, err := d.Readdirnames(-1) if err != nil { return Procs{}, fmt.Errorf("could not read %s: %s", d.Name(), err) } p := Procs{} for _, n := range names { pid, err := strconv.ParseInt(n, 10, 64) if err != nil { continue } p = append(p, Proc{PID: int(pid), fs: fs}) } return p, nil }
go
func (fs FS) AllProcs() (Procs, error) { d, err := os.Open(fs.Path()) if err != nil { return Procs{}, err } defer d.Close() names, err := d.Readdirnames(-1) if err != nil { return Procs{}, fmt.Errorf("could not read %s: %s", d.Name(), err) } p := Procs{} for _, n := range names { pid, err := strconv.ParseInt(n, 10, 64) if err != nil { continue } p = append(p, Proc{PID: int(pid), fs: fs}) } return p, nil }
[ "func", "(", "fs", "FS", ")", "AllProcs", "(", ")", "(", "Procs", ",", "error", ")", "{", "d", ",", "err", ":=", "os", ".", "Open", "(", "fs", ".", "Path", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Procs", "{", "}", ",", "err", "\n", "}", "\n", "defer", "d", ".", "Close", "(", ")", "\n\n", "names", ",", "err", ":=", "d", ".", "Readdirnames", "(", "-", "1", ")", "\n", "if", "err", "!=", "nil", "{", "return", "Procs", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "d", ".", "Name", "(", ")", ",", "err", ")", "\n", "}", "\n\n", "p", ":=", "Procs", "{", "}", "\n", "for", "_", ",", "n", ":=", "range", "names", "{", "pid", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "n", ",", "10", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "continue", "\n", "}", "\n", "p", "=", "append", "(", "p", ",", "Proc", "{", "PID", ":", "int", "(", "pid", ")", ",", "fs", ":", "fs", "}", ")", "\n", "}", "\n\n", "return", "p", ",", "nil", "\n", "}" ]
// AllProcs returns a list of all currently available processes.
[ "AllProcs", "returns", "a", "list", "of", "all", "currently", "available", "processes", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/proc.go#L89-L111
151,512
prometheus/procfs
proc.go
CmdLine
func (p Proc) CmdLine() ([]string, error) { f, err := os.Open(p.path("cmdline")) if err != nil { return nil, err } defer f.Close() data, err := ioutil.ReadAll(f) if err != nil { return nil, err } if len(data) < 1 { return []string{}, nil } return strings.Split(string(bytes.TrimRight(data, string("\x00"))), string(byte(0))), nil }
go
func (p Proc) CmdLine() ([]string, error) { f, err := os.Open(p.path("cmdline")) if err != nil { return nil, err } defer f.Close() data, err := ioutil.ReadAll(f) if err != nil { return nil, err } if len(data) < 1 { return []string{}, nil } return strings.Split(string(bytes.TrimRight(data, string("\x00"))), string(byte(0))), nil }
[ "func", "(", "p", "Proc", ")", "CmdLine", "(", ")", "(", "[", "]", "string", ",", "error", ")", "{", "f", ",", "err", ":=", "os", ".", "Open", "(", "p", ".", "path", "(", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n\n", "data", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "f", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "len", "(", "data", ")", "<", "1", "{", "return", "[", "]", "string", "{", "}", ",", "nil", "\n", "}", "\n\n", "return", "strings", ".", "Split", "(", "string", "(", "bytes", ".", "TrimRight", "(", "data", ",", "string", "(", "\"", "\\x00", "\"", ")", ")", ")", ",", "string", "(", "byte", "(", "0", ")", ")", ")", ",", "nil", "\n", "}" ]
// CmdLine returns the command line of a process.
[ "CmdLine", "returns", "the", "command", "line", "of", "a", "process", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/proc.go#L114-L131
151,513
prometheus/procfs
proc.go
Comm
func (p Proc) Comm() (string, error) { f, err := os.Open(p.path("comm")) if err != nil { return "", err } defer f.Close() data, err := ioutil.ReadAll(f) if err != nil { return "", err } return strings.TrimSpace(string(data)), nil }
go
func (p Proc) Comm() (string, error) { f, err := os.Open(p.path("comm")) if err != nil { return "", err } defer f.Close() data, err := ioutil.ReadAll(f) if err != nil { return "", err } return strings.TrimSpace(string(data)), nil }
[ "func", "(", "p", "Proc", ")", "Comm", "(", ")", "(", "string", ",", "error", ")", "{", "f", ",", "err", ":=", "os", ".", "Open", "(", "p", ".", "path", "(", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n\n", "data", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "f", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "return", "strings", ".", "TrimSpace", "(", "string", "(", "data", ")", ")", ",", "nil", "\n", "}" ]
// Comm returns the command name of a process.
[ "Comm", "returns", "the", "command", "name", "of", "a", "process", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/proc.go#L134-L147
151,514
prometheus/procfs
proc.go
Executable
func (p Proc) Executable() (string, error) { exe, err := os.Readlink(p.path("exe")) if os.IsNotExist(err) { return "", nil } return exe, err }
go
func (p Proc) Executable() (string, error) { exe, err := os.Readlink(p.path("exe")) if os.IsNotExist(err) { return "", nil } return exe, err }
[ "func", "(", "p", "Proc", ")", "Executable", "(", ")", "(", "string", ",", "error", ")", "{", "exe", ",", "err", ":=", "os", ".", "Readlink", "(", "p", ".", "path", "(", "\"", "\"", ")", ")", "\n", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "\"", "\"", ",", "nil", "\n", "}", "\n\n", "return", "exe", ",", "err", "\n", "}" ]
// Executable returns the absolute path of the executable command of a process.
[ "Executable", "returns", "the", "absolute", "path", "of", "the", "executable", "command", "of", "a", "process", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/proc.go#L150-L157
151,515
prometheus/procfs
proc.go
Cwd
func (p Proc) Cwd() (string, error) { wd, err := os.Readlink(p.path("cwd")) if os.IsNotExist(err) { return "", nil } return wd, err }
go
func (p Proc) Cwd() (string, error) { wd, err := os.Readlink(p.path("cwd")) if os.IsNotExist(err) { return "", nil } return wd, err }
[ "func", "(", "p", "Proc", ")", "Cwd", "(", ")", "(", "string", ",", "error", ")", "{", "wd", ",", "err", ":=", "os", ".", "Readlink", "(", "p", ".", "path", "(", "\"", "\"", ")", ")", "\n", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "\"", "\"", ",", "nil", "\n", "}", "\n\n", "return", "wd", ",", "err", "\n", "}" ]
// Cwd returns the absolute path to the current working directory of the process.
[ "Cwd", "returns", "the", "absolute", "path", "to", "the", "current", "working", "directory", "of", "the", "process", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/proc.go#L160-L167
151,516
prometheus/procfs
proc.go
FileDescriptors
func (p Proc) FileDescriptors() ([]uintptr, error) { names, err := p.fileDescriptors() if err != nil { return nil, err } fds := make([]uintptr, len(names)) for i, n := range names { fd, err := strconv.ParseInt(n, 10, 32) if err != nil { return nil, fmt.Errorf("could not parse fd %s: %s", n, err) } fds[i] = uintptr(fd) } return fds, nil }
go
func (p Proc) FileDescriptors() ([]uintptr, error) { names, err := p.fileDescriptors() if err != nil { return nil, err } fds := make([]uintptr, len(names)) for i, n := range names { fd, err := strconv.ParseInt(n, 10, 32) if err != nil { return nil, fmt.Errorf("could not parse fd %s: %s", n, err) } fds[i] = uintptr(fd) } return fds, nil }
[ "func", "(", "p", "Proc", ")", "FileDescriptors", "(", ")", "(", "[", "]", "uintptr", ",", "error", ")", "{", "names", ",", "err", ":=", "p", ".", "fileDescriptors", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "fds", ":=", "make", "(", "[", "]", "uintptr", ",", "len", "(", "names", ")", ")", "\n", "for", "i", ",", "n", ":=", "range", "names", "{", "fd", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "n", ",", "10", ",", "32", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "n", ",", "err", ")", "\n", "}", "\n", "fds", "[", "i", "]", "=", "uintptr", "(", "fd", ")", "\n", "}", "\n\n", "return", "fds", ",", "nil", "\n", "}" ]
// FileDescriptors returns the currently open file descriptors of a process.
[ "FileDescriptors", "returns", "the", "currently", "open", "file", "descriptors", "of", "a", "process", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/proc.go#L180-L196
151,517
prometheus/procfs
proc.go
FileDescriptorsLen
func (p Proc) FileDescriptorsLen() (int, error) { fds, err := p.fileDescriptors() if err != nil { return 0, err } return len(fds), nil }
go
func (p Proc) FileDescriptorsLen() (int, error) { fds, err := p.fileDescriptors() if err != nil { return 0, err } return len(fds), nil }
[ "func", "(", "p", "Proc", ")", "FileDescriptorsLen", "(", ")", "(", "int", ",", "error", ")", "{", "fds", ",", "err", ":=", "p", ".", "fileDescriptors", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "return", "len", "(", "fds", ")", ",", "nil", "\n", "}" ]
// FileDescriptorsLen returns the number of currently open file descriptors of // a process.
[ "FileDescriptorsLen", "returns", "the", "number", "of", "currently", "open", "file", "descriptors", "of", "a", "process", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/proc.go#L220-L227
151,518
prometheus/procfs
proc.go
MountStats
func (p Proc) MountStats() ([]*Mount, error) { f, err := os.Open(p.path("mountstats")) if err != nil { return nil, err } defer f.Close() return parseMountStats(f) }
go
func (p Proc) MountStats() ([]*Mount, error) { f, err := os.Open(p.path("mountstats")) if err != nil { return nil, err } defer f.Close() return parseMountStats(f) }
[ "func", "(", "p", "Proc", ")", "MountStats", "(", ")", "(", "[", "]", "*", "Mount", ",", "error", ")", "{", "f", ",", "err", ":=", "os", ".", "Open", "(", "p", ".", "path", "(", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n\n", "return", "parseMountStats", "(", "f", ")", "\n", "}" ]
// MountStats retrieves statistics and configuration for mount points in a // process's namespace.
[ "MountStats", "retrieves", "statistics", "and", "configuration", "for", "mount", "points", "in", "a", "process", "s", "namespace", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/proc.go#L231-L239
151,519
prometheus/procfs
proc_limits.go
NewLimits
func (p Proc) NewLimits() (ProcLimits, error) { f, err := os.Open(p.path("limits")) if err != nil { return ProcLimits{}, err } defer f.Close() var ( l = ProcLimits{} s = bufio.NewScanner(f) ) for s.Scan() { fields := limitsDelimiter.Split(s.Text(), limitsFields) if len(fields) != limitsFields { return ProcLimits{}, fmt.Errorf( "couldn't parse %s line %s", f.Name(), s.Text()) } switch fields[0] { case "Max cpu time": l.CPUTime, err = parseInt(fields[1]) case "Max file size": l.FileSize, err = parseInt(fields[1]) case "Max data size": l.DataSize, err = parseInt(fields[1]) case "Max stack size": l.StackSize, err = parseInt(fields[1]) case "Max core file size": l.CoreFileSize, err = parseInt(fields[1]) case "Max resident set": l.ResidentSet, err = parseInt(fields[1]) case "Max processes": l.Processes, err = parseInt(fields[1]) case "Max open files": l.OpenFiles, err = parseInt(fields[1]) case "Max locked memory": l.LockedMemory, err = parseInt(fields[1]) case "Max address space": l.AddressSpace, err = parseInt(fields[1]) case "Max file locks": l.FileLocks, err = parseInt(fields[1]) case "Max pending signals": l.PendingSignals, err = parseInt(fields[1]) case "Max msgqueue size": l.MsqqueueSize, err = parseInt(fields[1]) case "Max nice priority": l.NicePriority, err = parseInt(fields[1]) case "Max realtime priority": l.RealtimePriority, err = parseInt(fields[1]) case "Max realtime timeout": l.RealtimeTimeout, err = parseInt(fields[1]) } if err != nil { return ProcLimits{}, err } } return l, s.Err() }
go
func (p Proc) NewLimits() (ProcLimits, error) { f, err := os.Open(p.path("limits")) if err != nil { return ProcLimits{}, err } defer f.Close() var ( l = ProcLimits{} s = bufio.NewScanner(f) ) for s.Scan() { fields := limitsDelimiter.Split(s.Text(), limitsFields) if len(fields) != limitsFields { return ProcLimits{}, fmt.Errorf( "couldn't parse %s line %s", f.Name(), s.Text()) } switch fields[0] { case "Max cpu time": l.CPUTime, err = parseInt(fields[1]) case "Max file size": l.FileSize, err = parseInt(fields[1]) case "Max data size": l.DataSize, err = parseInt(fields[1]) case "Max stack size": l.StackSize, err = parseInt(fields[1]) case "Max core file size": l.CoreFileSize, err = parseInt(fields[1]) case "Max resident set": l.ResidentSet, err = parseInt(fields[1]) case "Max processes": l.Processes, err = parseInt(fields[1]) case "Max open files": l.OpenFiles, err = parseInt(fields[1]) case "Max locked memory": l.LockedMemory, err = parseInt(fields[1]) case "Max address space": l.AddressSpace, err = parseInt(fields[1]) case "Max file locks": l.FileLocks, err = parseInt(fields[1]) case "Max pending signals": l.PendingSignals, err = parseInt(fields[1]) case "Max msgqueue size": l.MsqqueueSize, err = parseInt(fields[1]) case "Max nice priority": l.NicePriority, err = parseInt(fields[1]) case "Max realtime priority": l.RealtimePriority, err = parseInt(fields[1]) case "Max realtime timeout": l.RealtimeTimeout, err = parseInt(fields[1]) } if err != nil { return ProcLimits{}, err } } return l, s.Err() }
[ "func", "(", "p", "Proc", ")", "NewLimits", "(", ")", "(", "ProcLimits", ",", "error", ")", "{", "f", ",", "err", ":=", "os", ".", "Open", "(", "p", ".", "path", "(", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "ProcLimits", "{", "}", ",", "err", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n\n", "var", "(", "l", "=", "ProcLimits", "{", "}", "\n", "s", "=", "bufio", ".", "NewScanner", "(", "f", ")", "\n", ")", "\n", "for", "s", ".", "Scan", "(", ")", "{", "fields", ":=", "limitsDelimiter", ".", "Split", "(", "s", ".", "Text", "(", ")", ",", "limitsFields", ")", "\n", "if", "len", "(", "fields", ")", "!=", "limitsFields", "{", "return", "ProcLimits", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "f", ".", "Name", "(", ")", ",", "s", ".", "Text", "(", ")", ")", "\n", "}", "\n\n", "switch", "fields", "[", "0", "]", "{", "case", "\"", "\"", ":", "l", ".", "CPUTime", ",", "err", "=", "parseInt", "(", "fields", "[", "1", "]", ")", "\n", "case", "\"", "\"", ":", "l", ".", "FileSize", ",", "err", "=", "parseInt", "(", "fields", "[", "1", "]", ")", "\n", "case", "\"", "\"", ":", "l", ".", "DataSize", ",", "err", "=", "parseInt", "(", "fields", "[", "1", "]", ")", "\n", "case", "\"", "\"", ":", "l", ".", "StackSize", ",", "err", "=", "parseInt", "(", "fields", "[", "1", "]", ")", "\n", "case", "\"", "\"", ":", "l", ".", "CoreFileSize", ",", "err", "=", "parseInt", "(", "fields", "[", "1", "]", ")", "\n", "case", "\"", "\"", ":", "l", ".", "ResidentSet", ",", "err", "=", "parseInt", "(", "fields", "[", "1", "]", ")", "\n", "case", "\"", "\"", ":", "l", ".", "Processes", ",", "err", "=", "parseInt", "(", "fields", "[", "1", "]", ")", "\n", "case", "\"", "\"", ":", "l", ".", "OpenFiles", ",", "err", "=", "parseInt", "(", "fields", "[", "1", "]", ")", "\n", "case", "\"", "\"", ":", "l", ".", "LockedMemory", ",", "err", "=", "parseInt", "(", "fields", "[", "1", "]", ")", "\n", "case", "\"", "\"", ":", "l", ".", "AddressSpace", ",", "err", "=", "parseInt", "(", "fields", "[", "1", "]", ")", "\n", "case", "\"", "\"", ":", "l", ".", "FileLocks", ",", "err", "=", "parseInt", "(", "fields", "[", "1", "]", ")", "\n", "case", "\"", "\"", ":", "l", ".", "PendingSignals", ",", "err", "=", "parseInt", "(", "fields", "[", "1", "]", ")", "\n", "case", "\"", "\"", ":", "l", ".", "MsqqueueSize", ",", "err", "=", "parseInt", "(", "fields", "[", "1", "]", ")", "\n", "case", "\"", "\"", ":", "l", ".", "NicePriority", ",", "err", "=", "parseInt", "(", "fields", "[", "1", "]", ")", "\n", "case", "\"", "\"", ":", "l", ".", "RealtimePriority", ",", "err", "=", "parseInt", "(", "fields", "[", "1", "]", ")", "\n", "case", "\"", "\"", ":", "l", ".", "RealtimeTimeout", ",", "err", "=", "parseInt", "(", "fields", "[", "1", "]", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "ProcLimits", "{", "}", ",", "err", "\n", "}", "\n", "}", "\n\n", "return", "l", ",", "s", ".", "Err", "(", ")", "\n", "}" ]
// NewLimits returns the current soft limits of the process.
[ "NewLimits", "returns", "the", "current", "soft", "limits", "of", "the", "process", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/proc_limits.go#L81-L139
151,520
prometheus/procfs
mountstats.go
parseMountStatsNFS
func parseMountStatsNFS(s *bufio.Scanner, statVersion string) (*MountStatsNFS, error) { // Field indicators for parsing specific types of data const ( fieldOpts = "opts:" fieldAge = "age:" fieldBytes = "bytes:" fieldEvents = "events:" fieldPerOpStats = "per-op" fieldTransport = "xprt:" ) stats := &MountStatsNFS{ StatVersion: statVersion, } for s.Scan() { ss := strings.Fields(string(s.Bytes())) if len(ss) == 0 { break } if len(ss) < 2 { return nil, fmt.Errorf("not enough information for NFS stats: %v", ss) } switch ss[0] { case fieldOpts: for _, opt := range strings.Split(ss[1], ",") { split := strings.Split(opt, "=") if len(split) == 2 && split[0] == "mountaddr" { stats.MountAddress = split[1] } } case fieldAge: // Age integer is in seconds d, err := time.ParseDuration(ss[1] + "s") if err != nil { return nil, err } stats.Age = d case fieldBytes: bstats, err := parseNFSBytesStats(ss[1:]) if err != nil { return nil, err } stats.Bytes = *bstats case fieldEvents: estats, err := parseNFSEventsStats(ss[1:]) if err != nil { return nil, err } stats.Events = *estats case fieldTransport: if len(ss) < 3 { return nil, fmt.Errorf("not enough information for NFS transport stats: %v", ss) } tstats, err := parseNFSTransportStats(ss[1:], statVersion) if err != nil { return nil, err } stats.Transport = *tstats } // When encountering "per-operation statistics", we must break this // loop and parse them separately to ensure we can terminate parsing // before reaching another device entry; hence why this 'if' statement // is not just another switch case if ss[0] == fieldPerOpStats { break } } if err := s.Err(); err != nil { return nil, err } // NFS per-operation stats appear last before the next device entry perOpStats, err := parseNFSOperationStats(s) if err != nil { return nil, err } stats.Operations = perOpStats return stats, nil }
go
func parseMountStatsNFS(s *bufio.Scanner, statVersion string) (*MountStatsNFS, error) { // Field indicators for parsing specific types of data const ( fieldOpts = "opts:" fieldAge = "age:" fieldBytes = "bytes:" fieldEvents = "events:" fieldPerOpStats = "per-op" fieldTransport = "xprt:" ) stats := &MountStatsNFS{ StatVersion: statVersion, } for s.Scan() { ss := strings.Fields(string(s.Bytes())) if len(ss) == 0 { break } if len(ss) < 2 { return nil, fmt.Errorf("not enough information for NFS stats: %v", ss) } switch ss[0] { case fieldOpts: for _, opt := range strings.Split(ss[1], ",") { split := strings.Split(opt, "=") if len(split) == 2 && split[0] == "mountaddr" { stats.MountAddress = split[1] } } case fieldAge: // Age integer is in seconds d, err := time.ParseDuration(ss[1] + "s") if err != nil { return nil, err } stats.Age = d case fieldBytes: bstats, err := parseNFSBytesStats(ss[1:]) if err != nil { return nil, err } stats.Bytes = *bstats case fieldEvents: estats, err := parseNFSEventsStats(ss[1:]) if err != nil { return nil, err } stats.Events = *estats case fieldTransport: if len(ss) < 3 { return nil, fmt.Errorf("not enough information for NFS transport stats: %v", ss) } tstats, err := parseNFSTransportStats(ss[1:], statVersion) if err != nil { return nil, err } stats.Transport = *tstats } // When encountering "per-operation statistics", we must break this // loop and parse them separately to ensure we can terminate parsing // before reaching another device entry; hence why this 'if' statement // is not just another switch case if ss[0] == fieldPerOpStats { break } } if err := s.Err(); err != nil { return nil, err } // NFS per-operation stats appear last before the next device entry perOpStats, err := parseNFSOperationStats(s) if err != nil { return nil, err } stats.Operations = perOpStats return stats, nil }
[ "func", "parseMountStatsNFS", "(", "s", "*", "bufio", ".", "Scanner", ",", "statVersion", "string", ")", "(", "*", "MountStatsNFS", ",", "error", ")", "{", "// Field indicators for parsing specific types of data", "const", "(", "fieldOpts", "=", "\"", "\"", "\n", "fieldAge", "=", "\"", "\"", "\n", "fieldBytes", "=", "\"", "\"", "\n", "fieldEvents", "=", "\"", "\"", "\n", "fieldPerOpStats", "=", "\"", "\"", "\n", "fieldTransport", "=", "\"", "\"", "\n", ")", "\n\n", "stats", ":=", "&", "MountStatsNFS", "{", "StatVersion", ":", "statVersion", ",", "}", "\n\n", "for", "s", ".", "Scan", "(", ")", "{", "ss", ":=", "strings", ".", "Fields", "(", "string", "(", "s", ".", "Bytes", "(", ")", ")", ")", "\n", "if", "len", "(", "ss", ")", "==", "0", "{", "break", "\n", "}", "\n", "if", "len", "(", "ss", ")", "<", "2", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ss", ")", "\n", "}", "\n\n", "switch", "ss", "[", "0", "]", "{", "case", "fieldOpts", ":", "for", "_", ",", "opt", ":=", "range", "strings", ".", "Split", "(", "ss", "[", "1", "]", ",", "\"", "\"", ")", "{", "split", ":=", "strings", ".", "Split", "(", "opt", ",", "\"", "\"", ")", "\n", "if", "len", "(", "split", ")", "==", "2", "&&", "split", "[", "0", "]", "==", "\"", "\"", "{", "stats", ".", "MountAddress", "=", "split", "[", "1", "]", "\n", "}", "\n", "}", "\n", "case", "fieldAge", ":", "// Age integer is in seconds", "d", ",", "err", ":=", "time", ".", "ParseDuration", "(", "ss", "[", "1", "]", "+", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "stats", ".", "Age", "=", "d", "\n", "case", "fieldBytes", ":", "bstats", ",", "err", ":=", "parseNFSBytesStats", "(", "ss", "[", "1", ":", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "stats", ".", "Bytes", "=", "*", "bstats", "\n", "case", "fieldEvents", ":", "estats", ",", "err", ":=", "parseNFSEventsStats", "(", "ss", "[", "1", ":", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "stats", ".", "Events", "=", "*", "estats", "\n", "case", "fieldTransport", ":", "if", "len", "(", "ss", ")", "<", "3", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ss", ")", "\n", "}", "\n\n", "tstats", ",", "err", ":=", "parseNFSTransportStats", "(", "ss", "[", "1", ":", "]", ",", "statVersion", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "stats", ".", "Transport", "=", "*", "tstats", "\n", "}", "\n\n", "// When encountering \"per-operation statistics\", we must break this", "// loop and parse them separately to ensure we can terminate parsing", "// before reaching another device entry; hence why this 'if' statement", "// is not just another switch case", "if", "ss", "[", "0", "]", "==", "fieldPerOpStats", "{", "break", "\n", "}", "\n", "}", "\n\n", "if", "err", ":=", "s", ".", "Err", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// NFS per-operation stats appear last before the next device entry", "perOpStats", ",", "err", ":=", "parseNFSOperationStats", "(", "s", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "stats", ".", "Operations", "=", "perOpStats", "\n\n", "return", "stats", ",", "nil", "\n", "}" ]
// parseMountStatsNFS parses a MountStatsNFS by scanning additional information // related to NFS statistics.
[ "parseMountStatsNFS", "parses", "a", "MountStatsNFS", "by", "scanning", "additional", "information", "related", "to", "NFS", "statistics", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/mountstats.go#L319-L408
151,521
prometheus/procfs
mountstats.go
parseNFSBytesStats
func parseNFSBytesStats(ss []string) (*NFSBytesStats, error) { if len(ss) != fieldBytesLen { return nil, fmt.Errorf("invalid NFS bytes stats: %v", ss) } ns := make([]uint64, 0, fieldBytesLen) for _, s := range ss { n, err := strconv.ParseUint(s, 10, 64) if err != nil { return nil, err } ns = append(ns, n) } return &NFSBytesStats{ Read: ns[0], Write: ns[1], DirectRead: ns[2], DirectWrite: ns[3], ReadTotal: ns[4], WriteTotal: ns[5], ReadPages: ns[6], WritePages: ns[7], }, nil }
go
func parseNFSBytesStats(ss []string) (*NFSBytesStats, error) { if len(ss) != fieldBytesLen { return nil, fmt.Errorf("invalid NFS bytes stats: %v", ss) } ns := make([]uint64, 0, fieldBytesLen) for _, s := range ss { n, err := strconv.ParseUint(s, 10, 64) if err != nil { return nil, err } ns = append(ns, n) } return &NFSBytesStats{ Read: ns[0], Write: ns[1], DirectRead: ns[2], DirectWrite: ns[3], ReadTotal: ns[4], WriteTotal: ns[5], ReadPages: ns[6], WritePages: ns[7], }, nil }
[ "func", "parseNFSBytesStats", "(", "ss", "[", "]", "string", ")", "(", "*", "NFSBytesStats", ",", "error", ")", "{", "if", "len", "(", "ss", ")", "!=", "fieldBytesLen", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ss", ")", "\n", "}", "\n\n", "ns", ":=", "make", "(", "[", "]", "uint64", ",", "0", ",", "fieldBytesLen", ")", "\n", "for", "_", ",", "s", ":=", "range", "ss", "{", "n", ",", "err", ":=", "strconv", ".", "ParseUint", "(", "s", ",", "10", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "ns", "=", "append", "(", "ns", ",", "n", ")", "\n", "}", "\n\n", "return", "&", "NFSBytesStats", "{", "Read", ":", "ns", "[", "0", "]", ",", "Write", ":", "ns", "[", "1", "]", ",", "DirectRead", ":", "ns", "[", "2", "]", ",", "DirectWrite", ":", "ns", "[", "3", "]", ",", "ReadTotal", ":", "ns", "[", "4", "]", ",", "WriteTotal", ":", "ns", "[", "5", "]", ",", "ReadPages", ":", "ns", "[", "6", "]", ",", "WritePages", ":", "ns", "[", "7", "]", ",", "}", ",", "nil", "\n", "}" ]
// parseNFSBytesStats parses a NFSBytesStats line using an input set of // integer fields.
[ "parseNFSBytesStats", "parses", "a", "NFSBytesStats", "line", "using", "an", "input", "set", "of", "integer", "fields", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/mountstats.go#L412-L437
151,522
prometheus/procfs
mountstats.go
parseNFSEventsStats
func parseNFSEventsStats(ss []string) (*NFSEventsStats, error) { if len(ss) != fieldEventsLen { return nil, fmt.Errorf("invalid NFS events stats: %v", ss) } ns := make([]uint64, 0, fieldEventsLen) for _, s := range ss { n, err := strconv.ParseUint(s, 10, 64) if err != nil { return nil, err } ns = append(ns, n) } return &NFSEventsStats{ InodeRevalidate: ns[0], DnodeRevalidate: ns[1], DataInvalidate: ns[2], AttributeInvalidate: ns[3], VFSOpen: ns[4], VFSLookup: ns[5], VFSAccess: ns[6], VFSUpdatePage: ns[7], VFSReadPage: ns[8], VFSReadPages: ns[9], VFSWritePage: ns[10], VFSWritePages: ns[11], VFSGetdents: ns[12], VFSSetattr: ns[13], VFSFlush: ns[14], VFSFsync: ns[15], VFSLock: ns[16], VFSFileRelease: ns[17], CongestionWait: ns[18], Truncation: ns[19], WriteExtension: ns[20], SillyRename: ns[21], ShortRead: ns[22], ShortWrite: ns[23], JukeboxDelay: ns[24], PNFSRead: ns[25], PNFSWrite: ns[26], }, nil }
go
func parseNFSEventsStats(ss []string) (*NFSEventsStats, error) { if len(ss) != fieldEventsLen { return nil, fmt.Errorf("invalid NFS events stats: %v", ss) } ns := make([]uint64, 0, fieldEventsLen) for _, s := range ss { n, err := strconv.ParseUint(s, 10, 64) if err != nil { return nil, err } ns = append(ns, n) } return &NFSEventsStats{ InodeRevalidate: ns[0], DnodeRevalidate: ns[1], DataInvalidate: ns[2], AttributeInvalidate: ns[3], VFSOpen: ns[4], VFSLookup: ns[5], VFSAccess: ns[6], VFSUpdatePage: ns[7], VFSReadPage: ns[8], VFSReadPages: ns[9], VFSWritePage: ns[10], VFSWritePages: ns[11], VFSGetdents: ns[12], VFSSetattr: ns[13], VFSFlush: ns[14], VFSFsync: ns[15], VFSLock: ns[16], VFSFileRelease: ns[17], CongestionWait: ns[18], Truncation: ns[19], WriteExtension: ns[20], SillyRename: ns[21], ShortRead: ns[22], ShortWrite: ns[23], JukeboxDelay: ns[24], PNFSRead: ns[25], PNFSWrite: ns[26], }, nil }
[ "func", "parseNFSEventsStats", "(", "ss", "[", "]", "string", ")", "(", "*", "NFSEventsStats", ",", "error", ")", "{", "if", "len", "(", "ss", ")", "!=", "fieldEventsLen", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ss", ")", "\n", "}", "\n\n", "ns", ":=", "make", "(", "[", "]", "uint64", ",", "0", ",", "fieldEventsLen", ")", "\n", "for", "_", ",", "s", ":=", "range", "ss", "{", "n", ",", "err", ":=", "strconv", ".", "ParseUint", "(", "s", ",", "10", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "ns", "=", "append", "(", "ns", ",", "n", ")", "\n", "}", "\n\n", "return", "&", "NFSEventsStats", "{", "InodeRevalidate", ":", "ns", "[", "0", "]", ",", "DnodeRevalidate", ":", "ns", "[", "1", "]", ",", "DataInvalidate", ":", "ns", "[", "2", "]", ",", "AttributeInvalidate", ":", "ns", "[", "3", "]", ",", "VFSOpen", ":", "ns", "[", "4", "]", ",", "VFSLookup", ":", "ns", "[", "5", "]", ",", "VFSAccess", ":", "ns", "[", "6", "]", ",", "VFSUpdatePage", ":", "ns", "[", "7", "]", ",", "VFSReadPage", ":", "ns", "[", "8", "]", ",", "VFSReadPages", ":", "ns", "[", "9", "]", ",", "VFSWritePage", ":", "ns", "[", "10", "]", ",", "VFSWritePages", ":", "ns", "[", "11", "]", ",", "VFSGetdents", ":", "ns", "[", "12", "]", ",", "VFSSetattr", ":", "ns", "[", "13", "]", ",", "VFSFlush", ":", "ns", "[", "14", "]", ",", "VFSFsync", ":", "ns", "[", "15", "]", ",", "VFSLock", ":", "ns", "[", "16", "]", ",", "VFSFileRelease", ":", "ns", "[", "17", "]", ",", "CongestionWait", ":", "ns", "[", "18", "]", ",", "Truncation", ":", "ns", "[", "19", "]", ",", "WriteExtension", ":", "ns", "[", "20", "]", ",", "SillyRename", ":", "ns", "[", "21", "]", ",", "ShortRead", ":", "ns", "[", "22", "]", ",", "ShortWrite", ":", "ns", "[", "23", "]", ",", "JukeboxDelay", ":", "ns", "[", "24", "]", ",", "PNFSRead", ":", "ns", "[", "25", "]", ",", "PNFSWrite", ":", "ns", "[", "26", "]", ",", "}", ",", "nil", "\n", "}" ]
// parseNFSEventsStats parses a NFSEventsStats line using an input set of // integer fields.
[ "parseNFSEventsStats", "parses", "a", "NFSEventsStats", "line", "using", "an", "input", "set", "of", "integer", "fields", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/mountstats.go#L441-L485
151,523
prometheus/procfs
mountstats.go
parseNFSOperationStats
func parseNFSOperationStats(s *bufio.Scanner) ([]NFSOperationStats, error) { const ( // Number of expected fields in each per-operation statistics set numFields = 9 ) var ops []NFSOperationStats for s.Scan() { ss := strings.Fields(string(s.Bytes())) if len(ss) == 0 { // Must break when reading a blank line after per-operation stats to // enable top-level function to parse the next device entry break } if len(ss) != numFields { return nil, fmt.Errorf("invalid NFS per-operations stats: %v", ss) } // Skip string operation name for integers ns := make([]uint64, 0, numFields-1) for _, st := range ss[1:] { n, err := strconv.ParseUint(st, 10, 64) if err != nil { return nil, err } ns = append(ns, n) } ops = append(ops, NFSOperationStats{ Operation: strings.TrimSuffix(ss[0], ":"), Requests: ns[0], Transmissions: ns[1], MajorTimeouts: ns[2], BytesSent: ns[3], BytesReceived: ns[4], CumulativeQueueTime: time.Duration(ns[5]) * time.Millisecond, CumulativeTotalResponseTime: time.Duration(ns[6]) * time.Millisecond, CumulativeTotalRequestTime: time.Duration(ns[7]) * time.Millisecond, }) } return ops, s.Err() }
go
func parseNFSOperationStats(s *bufio.Scanner) ([]NFSOperationStats, error) { const ( // Number of expected fields in each per-operation statistics set numFields = 9 ) var ops []NFSOperationStats for s.Scan() { ss := strings.Fields(string(s.Bytes())) if len(ss) == 0 { // Must break when reading a blank line after per-operation stats to // enable top-level function to parse the next device entry break } if len(ss) != numFields { return nil, fmt.Errorf("invalid NFS per-operations stats: %v", ss) } // Skip string operation name for integers ns := make([]uint64, 0, numFields-1) for _, st := range ss[1:] { n, err := strconv.ParseUint(st, 10, 64) if err != nil { return nil, err } ns = append(ns, n) } ops = append(ops, NFSOperationStats{ Operation: strings.TrimSuffix(ss[0], ":"), Requests: ns[0], Transmissions: ns[1], MajorTimeouts: ns[2], BytesSent: ns[3], BytesReceived: ns[4], CumulativeQueueTime: time.Duration(ns[5]) * time.Millisecond, CumulativeTotalResponseTime: time.Duration(ns[6]) * time.Millisecond, CumulativeTotalRequestTime: time.Duration(ns[7]) * time.Millisecond, }) } return ops, s.Err() }
[ "func", "parseNFSOperationStats", "(", "s", "*", "bufio", ".", "Scanner", ")", "(", "[", "]", "NFSOperationStats", ",", "error", ")", "{", "const", "(", "// Number of expected fields in each per-operation statistics set", "numFields", "=", "9", "\n", ")", "\n\n", "var", "ops", "[", "]", "NFSOperationStats", "\n\n", "for", "s", ".", "Scan", "(", ")", "{", "ss", ":=", "strings", ".", "Fields", "(", "string", "(", "s", ".", "Bytes", "(", ")", ")", ")", "\n", "if", "len", "(", "ss", ")", "==", "0", "{", "// Must break when reading a blank line after per-operation stats to", "// enable top-level function to parse the next device entry", "break", "\n", "}", "\n\n", "if", "len", "(", "ss", ")", "!=", "numFields", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ss", ")", "\n", "}", "\n\n", "// Skip string operation name for integers", "ns", ":=", "make", "(", "[", "]", "uint64", ",", "0", ",", "numFields", "-", "1", ")", "\n", "for", "_", ",", "st", ":=", "range", "ss", "[", "1", ":", "]", "{", "n", ",", "err", ":=", "strconv", ".", "ParseUint", "(", "st", ",", "10", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "ns", "=", "append", "(", "ns", ",", "n", ")", "\n", "}", "\n\n", "ops", "=", "append", "(", "ops", ",", "NFSOperationStats", "{", "Operation", ":", "strings", ".", "TrimSuffix", "(", "ss", "[", "0", "]", ",", "\"", "\"", ")", ",", "Requests", ":", "ns", "[", "0", "]", ",", "Transmissions", ":", "ns", "[", "1", "]", ",", "MajorTimeouts", ":", "ns", "[", "2", "]", ",", "BytesSent", ":", "ns", "[", "3", "]", ",", "BytesReceived", ":", "ns", "[", "4", "]", ",", "CumulativeQueueTime", ":", "time", ".", "Duration", "(", "ns", "[", "5", "]", ")", "*", "time", ".", "Millisecond", ",", "CumulativeTotalResponseTime", ":", "time", ".", "Duration", "(", "ns", "[", "6", "]", ")", "*", "time", ".", "Millisecond", ",", "CumulativeTotalRequestTime", ":", "time", ".", "Duration", "(", "ns", "[", "7", "]", ")", "*", "time", ".", "Millisecond", ",", "}", ")", "\n", "}", "\n\n", "return", "ops", ",", "s", ".", "Err", "(", ")", "\n", "}" ]
// parseNFSOperationStats parses a slice of NFSOperationStats by scanning // additional information about per-operation statistics until an empty // line is reached.
[ "parseNFSOperationStats", "parses", "a", "slice", "of", "NFSOperationStats", "by", "scanning", "additional", "information", "about", "per", "-", "operation", "statistics", "until", "an", "empty", "line", "is", "reached", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/mountstats.go#L490-L535
151,524
prometheus/procfs
mountstats.go
parseNFSTransportStats
func parseNFSTransportStats(ss []string, statVersion string) (*NFSTransportStats, error) { // Extract the protocol field. It is the only string value in the line protocol := ss[0] ss = ss[1:] switch statVersion { case statVersion10: var expectedLength int if protocol == "tcp" { expectedLength = fieldTransport10TCPLen } else if protocol == "udp" { expectedLength = fieldTransport10UDPLen } else { return nil, fmt.Errorf("invalid NFS protocol \"%s\" in stats 1.0 statement: %v", protocol, ss) } if len(ss) != expectedLength { return nil, fmt.Errorf("invalid NFS transport stats 1.0 statement: %v", ss) } case statVersion11: var expectedLength int if protocol == "tcp" { expectedLength = fieldTransport11TCPLen } else if protocol == "udp" { expectedLength = fieldTransport11UDPLen } else { return nil, fmt.Errorf("invalid NFS protocol \"%s\" in stats 1.1 statement: %v", protocol, ss) } if len(ss) != expectedLength { return nil, fmt.Errorf("invalid NFS transport stats 1.1 statement: %v", ss) } default: return nil, fmt.Errorf("unrecognized NFS transport stats version: %q", statVersion) } // Allocate enough for v1.1 stats since zero value for v1.1 stats will be okay // in a v1.0 response. Since the stat length is bigger for TCP stats, we use // the TCP length here. // // Note: slice length must be set to length of v1.1 stats to avoid a panic when // only v1.0 stats are present. // See: https://github.com/prometheus/node_exporter/issues/571. ns := make([]uint64, fieldTransport11TCPLen) for i, s := range ss { n, err := strconv.ParseUint(s, 10, 64) if err != nil { return nil, err } ns[i] = n } // The fields differ depending on the transport protocol (TCP or UDP) // From https://utcc.utoronto.ca/%7Ecks/space/blog/linux/NFSMountstatsXprt // // For the udp RPC transport there is no connection count, connect idle time, // or idle time (fields #3, #4, and #5); all other fields are the same. So // we set them to 0 here. if protocol == "udp" { ns = append(ns[:2], append(make([]uint64, 3), ns[2:]...)...) } return &NFSTransportStats{ Protocol: protocol, Port: ns[0], Bind: ns[1], Connect: ns[2], ConnectIdleTime: ns[3], IdleTime: time.Duration(ns[4]) * time.Second, Sends: ns[5], Receives: ns[6], BadTransactionIDs: ns[7], CumulativeActiveRequests: ns[8], CumulativeBacklog: ns[9], MaximumRPCSlotsUsed: ns[10], CumulativeSendingQueue: ns[11], CumulativePendingQueue: ns[12], }, nil }
go
func parseNFSTransportStats(ss []string, statVersion string) (*NFSTransportStats, error) { // Extract the protocol field. It is the only string value in the line protocol := ss[0] ss = ss[1:] switch statVersion { case statVersion10: var expectedLength int if protocol == "tcp" { expectedLength = fieldTransport10TCPLen } else if protocol == "udp" { expectedLength = fieldTransport10UDPLen } else { return nil, fmt.Errorf("invalid NFS protocol \"%s\" in stats 1.0 statement: %v", protocol, ss) } if len(ss) != expectedLength { return nil, fmt.Errorf("invalid NFS transport stats 1.0 statement: %v", ss) } case statVersion11: var expectedLength int if protocol == "tcp" { expectedLength = fieldTransport11TCPLen } else if protocol == "udp" { expectedLength = fieldTransport11UDPLen } else { return nil, fmt.Errorf("invalid NFS protocol \"%s\" in stats 1.1 statement: %v", protocol, ss) } if len(ss) != expectedLength { return nil, fmt.Errorf("invalid NFS transport stats 1.1 statement: %v", ss) } default: return nil, fmt.Errorf("unrecognized NFS transport stats version: %q", statVersion) } // Allocate enough for v1.1 stats since zero value for v1.1 stats will be okay // in a v1.0 response. Since the stat length is bigger for TCP stats, we use // the TCP length here. // // Note: slice length must be set to length of v1.1 stats to avoid a panic when // only v1.0 stats are present. // See: https://github.com/prometheus/node_exporter/issues/571. ns := make([]uint64, fieldTransport11TCPLen) for i, s := range ss { n, err := strconv.ParseUint(s, 10, 64) if err != nil { return nil, err } ns[i] = n } // The fields differ depending on the transport protocol (TCP or UDP) // From https://utcc.utoronto.ca/%7Ecks/space/blog/linux/NFSMountstatsXprt // // For the udp RPC transport there is no connection count, connect idle time, // or idle time (fields #3, #4, and #5); all other fields are the same. So // we set them to 0 here. if protocol == "udp" { ns = append(ns[:2], append(make([]uint64, 3), ns[2:]...)...) } return &NFSTransportStats{ Protocol: protocol, Port: ns[0], Bind: ns[1], Connect: ns[2], ConnectIdleTime: ns[3], IdleTime: time.Duration(ns[4]) * time.Second, Sends: ns[5], Receives: ns[6], BadTransactionIDs: ns[7], CumulativeActiveRequests: ns[8], CumulativeBacklog: ns[9], MaximumRPCSlotsUsed: ns[10], CumulativeSendingQueue: ns[11], CumulativePendingQueue: ns[12], }, nil }
[ "func", "parseNFSTransportStats", "(", "ss", "[", "]", "string", ",", "statVersion", "string", ")", "(", "*", "NFSTransportStats", ",", "error", ")", "{", "// Extract the protocol field. It is the only string value in the line", "protocol", ":=", "ss", "[", "0", "]", "\n", "ss", "=", "ss", "[", "1", ":", "]", "\n\n", "switch", "statVersion", "{", "case", "statVersion10", ":", "var", "expectedLength", "int", "\n", "if", "protocol", "==", "\"", "\"", "{", "expectedLength", "=", "fieldTransport10TCPLen", "\n", "}", "else", "if", "protocol", "==", "\"", "\"", "{", "expectedLength", "=", "fieldTransport10UDPLen", "\n", "}", "else", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\\\"", "\\\"", "\"", ",", "protocol", ",", "ss", ")", "\n", "}", "\n", "if", "len", "(", "ss", ")", "!=", "expectedLength", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ss", ")", "\n", "}", "\n", "case", "statVersion11", ":", "var", "expectedLength", "int", "\n", "if", "protocol", "==", "\"", "\"", "{", "expectedLength", "=", "fieldTransport11TCPLen", "\n", "}", "else", "if", "protocol", "==", "\"", "\"", "{", "expectedLength", "=", "fieldTransport11UDPLen", "\n", "}", "else", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\\\"", "\\\"", "\"", ",", "protocol", ",", "ss", ")", "\n", "}", "\n", "if", "len", "(", "ss", ")", "!=", "expectedLength", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ss", ")", "\n", "}", "\n", "default", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "statVersion", ")", "\n", "}", "\n\n", "// Allocate enough for v1.1 stats since zero value for v1.1 stats will be okay", "// in a v1.0 response. Since the stat length is bigger for TCP stats, we use", "// the TCP length here.", "//", "// Note: slice length must be set to length of v1.1 stats to avoid a panic when", "// only v1.0 stats are present.", "// See: https://github.com/prometheus/node_exporter/issues/571.", "ns", ":=", "make", "(", "[", "]", "uint64", ",", "fieldTransport11TCPLen", ")", "\n", "for", "i", ",", "s", ":=", "range", "ss", "{", "n", ",", "err", ":=", "strconv", ".", "ParseUint", "(", "s", ",", "10", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "ns", "[", "i", "]", "=", "n", "\n", "}", "\n\n", "// The fields differ depending on the transport protocol (TCP or UDP)", "// From https://utcc.utoronto.ca/%7Ecks/space/blog/linux/NFSMountstatsXprt", "//", "// For the udp RPC transport there is no connection count, connect idle time,", "// or idle time (fields #3, #4, and #5); all other fields are the same. So", "// we set them to 0 here.", "if", "protocol", "==", "\"", "\"", "{", "ns", "=", "append", "(", "ns", "[", ":", "2", "]", ",", "append", "(", "make", "(", "[", "]", "uint64", ",", "3", ")", ",", "ns", "[", "2", ":", "]", "...", ")", "...", ")", "\n", "}", "\n\n", "return", "&", "NFSTransportStats", "{", "Protocol", ":", "protocol", ",", "Port", ":", "ns", "[", "0", "]", ",", "Bind", ":", "ns", "[", "1", "]", ",", "Connect", ":", "ns", "[", "2", "]", ",", "ConnectIdleTime", ":", "ns", "[", "3", "]", ",", "IdleTime", ":", "time", ".", "Duration", "(", "ns", "[", "4", "]", ")", "*", "time", ".", "Second", ",", "Sends", ":", "ns", "[", "5", "]", ",", "Receives", ":", "ns", "[", "6", "]", ",", "BadTransactionIDs", ":", "ns", "[", "7", "]", ",", "CumulativeActiveRequests", ":", "ns", "[", "8", "]", ",", "CumulativeBacklog", ":", "ns", "[", "9", "]", ",", "MaximumRPCSlotsUsed", ":", "ns", "[", "10", "]", ",", "CumulativeSendingQueue", ":", "ns", "[", "11", "]", ",", "CumulativePendingQueue", ":", "ns", "[", "12", "]", ",", "}", ",", "nil", "\n", "}" ]
// parseNFSTransportStats parses a NFSTransportStats line using an input set of // integer fields matched to a specific stats version.
[ "parseNFSTransportStats", "parses", "a", "NFSTransportStats", "line", "using", "an", "input", "set", "of", "integer", "fields", "matched", "to", "a", "specific", "stats", "version", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/mountstats.go#L539-L616
151,525
prometheus/procfs
xfrm.go
NewXfrmStat
func NewXfrmStat() (XfrmStat, error) { fs, err := NewFS(DefaultMountPoint) if err != nil { return XfrmStat{}, err } return fs.NewXfrmStat() }
go
func NewXfrmStat() (XfrmStat, error) { fs, err := NewFS(DefaultMountPoint) if err != nil { return XfrmStat{}, err } return fs.NewXfrmStat() }
[ "func", "NewXfrmStat", "(", ")", "(", "XfrmStat", ",", "error", ")", "{", "fs", ",", "err", ":=", "NewFS", "(", "DefaultMountPoint", ")", "\n", "if", "err", "!=", "nil", "{", "return", "XfrmStat", "{", "}", ",", "err", "\n", "}", "\n\n", "return", "fs", ".", "NewXfrmStat", "(", ")", "\n", "}" ]
// NewXfrmStat reads the xfrm_stat statistics.
[ "NewXfrmStat", "reads", "the", "xfrm_stat", "statistics", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/xfrm.go#L89-L96
151,526
prometheus/procfs
xfrm.go
NewXfrmStat
func (fs FS) NewXfrmStat() (XfrmStat, error) { file, err := os.Open(fs.Path("net/xfrm_stat")) if err != nil { return XfrmStat{}, err } defer file.Close() var ( x = XfrmStat{} s = bufio.NewScanner(file) ) for s.Scan() { fields := strings.Fields(s.Text()) if len(fields) != 2 { return XfrmStat{}, fmt.Errorf( "couldn't parse %s line %s", file.Name(), s.Text()) } name := fields[0] value, err := strconv.Atoi(fields[1]) if err != nil { return XfrmStat{}, err } switch name { case "XfrmInError": x.XfrmInError = value case "XfrmInBufferError": x.XfrmInBufferError = value case "XfrmInHdrError": x.XfrmInHdrError = value case "XfrmInNoStates": x.XfrmInNoStates = value case "XfrmInStateProtoError": x.XfrmInStateProtoError = value case "XfrmInStateModeError": x.XfrmInStateModeError = value case "XfrmInStateSeqError": x.XfrmInStateSeqError = value case "XfrmInStateExpired": x.XfrmInStateExpired = value case "XfrmInStateInvalid": x.XfrmInStateInvalid = value case "XfrmInTmplMismatch": x.XfrmInTmplMismatch = value case "XfrmInNoPols": x.XfrmInNoPols = value case "XfrmInPolBlock": x.XfrmInPolBlock = value case "XfrmInPolError": x.XfrmInPolError = value case "XfrmOutError": x.XfrmOutError = value case "XfrmInStateMismatch": x.XfrmInStateMismatch = value case "XfrmOutBundleGenError": x.XfrmOutBundleGenError = value case "XfrmOutBundleCheckError": x.XfrmOutBundleCheckError = value case "XfrmOutNoStates": x.XfrmOutNoStates = value case "XfrmOutStateProtoError": x.XfrmOutStateProtoError = value case "XfrmOutStateModeError": x.XfrmOutStateModeError = value case "XfrmOutStateSeqError": x.XfrmOutStateSeqError = value case "XfrmOutStateExpired": x.XfrmOutStateExpired = value case "XfrmOutPolBlock": x.XfrmOutPolBlock = value case "XfrmOutPolDead": x.XfrmOutPolDead = value case "XfrmOutPolError": x.XfrmOutPolError = value case "XfrmFwdHdrError": x.XfrmFwdHdrError = value case "XfrmOutStateInvalid": x.XfrmOutStateInvalid = value case "XfrmAcquireError": x.XfrmAcquireError = value } } return x, s.Err() }
go
func (fs FS) NewXfrmStat() (XfrmStat, error) { file, err := os.Open(fs.Path("net/xfrm_stat")) if err != nil { return XfrmStat{}, err } defer file.Close() var ( x = XfrmStat{} s = bufio.NewScanner(file) ) for s.Scan() { fields := strings.Fields(s.Text()) if len(fields) != 2 { return XfrmStat{}, fmt.Errorf( "couldn't parse %s line %s", file.Name(), s.Text()) } name := fields[0] value, err := strconv.Atoi(fields[1]) if err != nil { return XfrmStat{}, err } switch name { case "XfrmInError": x.XfrmInError = value case "XfrmInBufferError": x.XfrmInBufferError = value case "XfrmInHdrError": x.XfrmInHdrError = value case "XfrmInNoStates": x.XfrmInNoStates = value case "XfrmInStateProtoError": x.XfrmInStateProtoError = value case "XfrmInStateModeError": x.XfrmInStateModeError = value case "XfrmInStateSeqError": x.XfrmInStateSeqError = value case "XfrmInStateExpired": x.XfrmInStateExpired = value case "XfrmInStateInvalid": x.XfrmInStateInvalid = value case "XfrmInTmplMismatch": x.XfrmInTmplMismatch = value case "XfrmInNoPols": x.XfrmInNoPols = value case "XfrmInPolBlock": x.XfrmInPolBlock = value case "XfrmInPolError": x.XfrmInPolError = value case "XfrmOutError": x.XfrmOutError = value case "XfrmInStateMismatch": x.XfrmInStateMismatch = value case "XfrmOutBundleGenError": x.XfrmOutBundleGenError = value case "XfrmOutBundleCheckError": x.XfrmOutBundleCheckError = value case "XfrmOutNoStates": x.XfrmOutNoStates = value case "XfrmOutStateProtoError": x.XfrmOutStateProtoError = value case "XfrmOutStateModeError": x.XfrmOutStateModeError = value case "XfrmOutStateSeqError": x.XfrmOutStateSeqError = value case "XfrmOutStateExpired": x.XfrmOutStateExpired = value case "XfrmOutPolBlock": x.XfrmOutPolBlock = value case "XfrmOutPolDead": x.XfrmOutPolDead = value case "XfrmOutPolError": x.XfrmOutPolError = value case "XfrmFwdHdrError": x.XfrmFwdHdrError = value case "XfrmOutStateInvalid": x.XfrmOutStateInvalid = value case "XfrmAcquireError": x.XfrmAcquireError = value } } return x, s.Err() }
[ "func", "(", "fs", "FS", ")", "NewXfrmStat", "(", ")", "(", "XfrmStat", ",", "error", ")", "{", "file", ",", "err", ":=", "os", ".", "Open", "(", "fs", ".", "Path", "(", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "XfrmStat", "{", "}", ",", "err", "\n", "}", "\n", "defer", "file", ".", "Close", "(", ")", "\n\n", "var", "(", "x", "=", "XfrmStat", "{", "}", "\n", "s", "=", "bufio", ".", "NewScanner", "(", "file", ")", "\n", ")", "\n\n", "for", "s", ".", "Scan", "(", ")", "{", "fields", ":=", "strings", ".", "Fields", "(", "s", ".", "Text", "(", ")", ")", "\n\n", "if", "len", "(", "fields", ")", "!=", "2", "{", "return", "XfrmStat", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "file", ".", "Name", "(", ")", ",", "s", ".", "Text", "(", ")", ")", "\n", "}", "\n\n", "name", ":=", "fields", "[", "0", "]", "\n", "value", ",", "err", ":=", "strconv", ".", "Atoi", "(", "fields", "[", "1", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "XfrmStat", "{", "}", ",", "err", "\n", "}", "\n\n", "switch", "name", "{", "case", "\"", "\"", ":", "x", ".", "XfrmInError", "=", "value", "\n", "case", "\"", "\"", ":", "x", ".", "XfrmInBufferError", "=", "value", "\n", "case", "\"", "\"", ":", "x", ".", "XfrmInHdrError", "=", "value", "\n", "case", "\"", "\"", ":", "x", ".", "XfrmInNoStates", "=", "value", "\n", "case", "\"", "\"", ":", "x", ".", "XfrmInStateProtoError", "=", "value", "\n", "case", "\"", "\"", ":", "x", ".", "XfrmInStateModeError", "=", "value", "\n", "case", "\"", "\"", ":", "x", ".", "XfrmInStateSeqError", "=", "value", "\n", "case", "\"", "\"", ":", "x", ".", "XfrmInStateExpired", "=", "value", "\n", "case", "\"", "\"", ":", "x", ".", "XfrmInStateInvalid", "=", "value", "\n", "case", "\"", "\"", ":", "x", ".", "XfrmInTmplMismatch", "=", "value", "\n", "case", "\"", "\"", ":", "x", ".", "XfrmInNoPols", "=", "value", "\n", "case", "\"", "\"", ":", "x", ".", "XfrmInPolBlock", "=", "value", "\n", "case", "\"", "\"", ":", "x", ".", "XfrmInPolError", "=", "value", "\n", "case", "\"", "\"", ":", "x", ".", "XfrmOutError", "=", "value", "\n", "case", "\"", "\"", ":", "x", ".", "XfrmInStateMismatch", "=", "value", "\n", "case", "\"", "\"", ":", "x", ".", "XfrmOutBundleGenError", "=", "value", "\n", "case", "\"", "\"", ":", "x", ".", "XfrmOutBundleCheckError", "=", "value", "\n", "case", "\"", "\"", ":", "x", ".", "XfrmOutNoStates", "=", "value", "\n", "case", "\"", "\"", ":", "x", ".", "XfrmOutStateProtoError", "=", "value", "\n", "case", "\"", "\"", ":", "x", ".", "XfrmOutStateModeError", "=", "value", "\n", "case", "\"", "\"", ":", "x", ".", "XfrmOutStateSeqError", "=", "value", "\n", "case", "\"", "\"", ":", "x", ".", "XfrmOutStateExpired", "=", "value", "\n", "case", "\"", "\"", ":", "x", ".", "XfrmOutPolBlock", "=", "value", "\n", "case", "\"", "\"", ":", "x", ".", "XfrmOutPolDead", "=", "value", "\n", "case", "\"", "\"", ":", "x", ".", "XfrmOutPolError", "=", "value", "\n", "case", "\"", "\"", ":", "x", ".", "XfrmFwdHdrError", "=", "value", "\n", "case", "\"", "\"", ":", "x", ".", "XfrmOutStateInvalid", "=", "value", "\n", "case", "\"", "\"", ":", "x", ".", "XfrmAcquireError", "=", "value", "\n", "}", "\n\n", "}", "\n\n", "return", "x", ",", "s", ".", "Err", "(", ")", "\n", "}" ]
// NewXfrmStat reads the xfrm_stat statistics from the 'proc' filesystem.
[ "NewXfrmStat", "reads", "the", "xfrm_stat", "statistics", "from", "the", "proc", "filesystem", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/xfrm.go#L99-L187
151,527
prometheus/procfs
internal/util/parse.go
ParseUint32s
func ParseUint32s(ss []string) ([]uint32, error) { us := make([]uint32, 0, len(ss)) for _, s := range ss { u, err := strconv.ParseUint(s, 10, 32) if err != nil { return nil, err } us = append(us, uint32(u)) } return us, nil }
go
func ParseUint32s(ss []string) ([]uint32, error) { us := make([]uint32, 0, len(ss)) for _, s := range ss { u, err := strconv.ParseUint(s, 10, 32) if err != nil { return nil, err } us = append(us, uint32(u)) } return us, nil }
[ "func", "ParseUint32s", "(", "ss", "[", "]", "string", ")", "(", "[", "]", "uint32", ",", "error", ")", "{", "us", ":=", "make", "(", "[", "]", "uint32", ",", "0", ",", "len", "(", "ss", ")", ")", "\n", "for", "_", ",", "s", ":=", "range", "ss", "{", "u", ",", "err", ":=", "strconv", ".", "ParseUint", "(", "s", ",", "10", ",", "32", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "us", "=", "append", "(", "us", ",", "uint32", "(", "u", ")", ")", "\n", "}", "\n\n", "return", "us", ",", "nil", "\n", "}" ]
// ParseUint32s parses a slice of strings into a slice of uint32s.
[ "ParseUint32s", "parses", "a", "slice", "of", "strings", "into", "a", "slice", "of", "uint32s", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/internal/util/parse.go#L23-L35
151,528
prometheus/procfs
internal/util/parse.go
ParseUint64s
func ParseUint64s(ss []string) ([]uint64, error) { us := make([]uint64, 0, len(ss)) for _, s := range ss { u, err := strconv.ParseUint(s, 10, 64) if err != nil { return nil, err } us = append(us, u) } return us, nil }
go
func ParseUint64s(ss []string) ([]uint64, error) { us := make([]uint64, 0, len(ss)) for _, s := range ss { u, err := strconv.ParseUint(s, 10, 64) if err != nil { return nil, err } us = append(us, u) } return us, nil }
[ "func", "ParseUint64s", "(", "ss", "[", "]", "string", ")", "(", "[", "]", "uint64", ",", "error", ")", "{", "us", ":=", "make", "(", "[", "]", "uint64", ",", "0", ",", "len", "(", "ss", ")", ")", "\n", "for", "_", ",", "s", ":=", "range", "ss", "{", "u", ",", "err", ":=", "strconv", ".", "ParseUint", "(", "s", ",", "10", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "us", "=", "append", "(", "us", ",", "u", ")", "\n", "}", "\n\n", "return", "us", ",", "nil", "\n", "}" ]
// ParseUint64s parses a slice of strings into a slice of uint64s.
[ "ParseUint64s", "parses", "a", "slice", "of", "strings", "into", "a", "slice", "of", "uint64s", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/internal/util/parse.go#L38-L50
151,529
prometheus/procfs
internal/util/parse.go
ReadUintFromFile
func ReadUintFromFile(path string) (uint64, error) { data, err := ioutil.ReadFile(path) if err != nil { return 0, err } return strconv.ParseUint(strings.TrimSpace(string(data)), 10, 64) }
go
func ReadUintFromFile(path string) (uint64, error) { data, err := ioutil.ReadFile(path) if err != nil { return 0, err } return strconv.ParseUint(strings.TrimSpace(string(data)), 10, 64) }
[ "func", "ReadUintFromFile", "(", "path", "string", ")", "(", "uint64", ",", "error", ")", "{", "data", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "return", "strconv", ".", "ParseUint", "(", "strings", ".", "TrimSpace", "(", "string", "(", "data", ")", ")", ",", "10", ",", "64", ")", "\n", "}" ]
// ReadUintFromFile reads a file and attempts to parse a uint64 from it.
[ "ReadUintFromFile", "reads", "a", "file", "and", "attempts", "to", "parse", "a", "uint64", "from", "it", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/internal/util/parse.go#L53-L59
151,530
prometheus/procfs
internal/util/parse.go
ParseBool
func ParseBool(b string) *bool { var truth bool switch b { case "enabled": truth = true case "disabled": truth = false default: return nil } return &truth }
go
func ParseBool(b string) *bool { var truth bool switch b { case "enabled": truth = true case "disabled": truth = false default: return nil } return &truth }
[ "func", "ParseBool", "(", "b", "string", ")", "*", "bool", "{", "var", "truth", "bool", "\n", "switch", "b", "{", "case", "\"", "\"", ":", "truth", "=", "true", "\n", "case", "\"", "\"", ":", "truth", "=", "false", "\n", "default", ":", "return", "nil", "\n", "}", "\n", "return", "&", "truth", "\n", "}" ]
// ParseBool parses a string into a boolean pointer.
[ "ParseBool", "parses", "a", "string", "into", "a", "boolean", "pointer", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/internal/util/parse.go#L62-L73
151,531
prometheus/procfs
sysfs/fs.go
Path
func (fs FS) Path(p ...string) string { return filepath.Join(append([]string{string(fs)}, p...)...) }
go
func (fs FS) Path(p ...string) string { return filepath.Join(append([]string{string(fs)}, p...)...) }
[ "func", "(", "fs", "FS", ")", "Path", "(", "p", "...", "string", ")", "string", "{", "return", "filepath", ".", "Join", "(", "append", "(", "[", "]", "string", "{", "string", "(", "fs", ")", "}", ",", "p", "...", ")", "...", ")", "\n", "}" ]
// Path returns the path of the given subsystem relative to the sys root.
[ "Path", "returns", "the", "path", "of", "the", "given", "subsystem", "relative", "to", "the", "sys", "root", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/sysfs/fs.go#L44-L46
151,532
prometheus/procfs
bcache/get.go
ReadStats
func ReadStats(sysfs string) ([]*Stats, error) { matches, err := filepath.Glob(path.Join(sysfs, "fs/bcache/*-*")) if err != nil { return nil, err } stats := make([]*Stats, 0, len(matches)) for _, uuidPath := range matches { // "*-*" in glob above indicates the name of the bcache. name := filepath.Base(uuidPath) // stats s, err := GetStats(uuidPath) if err != nil { return nil, err } s.Name = name stats = append(stats, s) } return stats, nil }
go
func ReadStats(sysfs string) ([]*Stats, error) { matches, err := filepath.Glob(path.Join(sysfs, "fs/bcache/*-*")) if err != nil { return nil, err } stats := make([]*Stats, 0, len(matches)) for _, uuidPath := range matches { // "*-*" in glob above indicates the name of the bcache. name := filepath.Base(uuidPath) // stats s, err := GetStats(uuidPath) if err != nil { return nil, err } s.Name = name stats = append(stats, s) } return stats, nil }
[ "func", "ReadStats", "(", "sysfs", "string", ")", "(", "[", "]", "*", "Stats", ",", "error", ")", "{", "matches", ",", "err", ":=", "filepath", ".", "Glob", "(", "path", ".", "Join", "(", "sysfs", ",", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "stats", ":=", "make", "(", "[", "]", "*", "Stats", ",", "0", ",", "len", "(", "matches", ")", ")", "\n", "for", "_", ",", "uuidPath", ":=", "range", "matches", "{", "// \"*-*\" in glob above indicates the name of the bcache.", "name", ":=", "filepath", ".", "Base", "(", "uuidPath", ")", "\n\n", "// stats", "s", ",", "err", ":=", "GetStats", "(", "uuidPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "s", ".", "Name", "=", "name", "\n", "stats", "=", "append", "(", "stats", ",", "s", ")", "\n", "}", "\n\n", "return", "stats", ",", "nil", "\n", "}" ]
// ReadStats retrieves bcache runtime statistics for each bcache.
[ "ReadStats", "retrieves", "bcache", "runtime", "statistics", "for", "each", "bcache", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/bcache/get.go#L28-L50
151,533
prometheus/procfs
bcache/get.go
parsePseudoFloat
func parsePseudoFloat(str string) (float64, error) { ss := strings.Split(str, ".") intPart, err := strconv.ParseFloat(ss[0], 64) if err != nil { return 0, err } if len(ss) == 1 { // Pure integers are fine. return intPart, nil } fracPart, err := strconv.ParseFloat(ss[1], 64) if err != nil { return 0, err } // fracPart is a number between 0 and 1023 divided by 100; it is off // by a small amount. Unexpected bumps in time lines may occur because // for bch_hprint .1 != .10 and .10 > .9 (at least up to Linux // v4.12-rc3). // Restore the proper order: fracPart = fracPart / 10.24 return intPart + fracPart, nil }
go
func parsePseudoFloat(str string) (float64, error) { ss := strings.Split(str, ".") intPart, err := strconv.ParseFloat(ss[0], 64) if err != nil { return 0, err } if len(ss) == 1 { // Pure integers are fine. return intPart, nil } fracPart, err := strconv.ParseFloat(ss[1], 64) if err != nil { return 0, err } // fracPart is a number between 0 and 1023 divided by 100; it is off // by a small amount. Unexpected bumps in time lines may occur because // for bch_hprint .1 != .10 and .10 > .9 (at least up to Linux // v4.12-rc3). // Restore the proper order: fracPart = fracPart / 10.24 return intPart + fracPart, nil }
[ "func", "parsePseudoFloat", "(", "str", "string", ")", "(", "float64", ",", "error", ")", "{", "ss", ":=", "strings", ".", "Split", "(", "str", ",", "\"", "\"", ")", "\n\n", "intPart", ",", "err", ":=", "strconv", ".", "ParseFloat", "(", "ss", "[", "0", "]", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "if", "len", "(", "ss", ")", "==", "1", "{", "// Pure integers are fine.", "return", "intPart", ",", "nil", "\n", "}", "\n", "fracPart", ",", "err", ":=", "strconv", ".", "ParseFloat", "(", "ss", "[", "1", "]", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "// fracPart is a number between 0 and 1023 divided by 100; it is off", "// by a small amount. Unexpected bumps in time lines may occur because", "// for bch_hprint .1 != .10 and .10 > .9 (at least up to Linux", "// v4.12-rc3).", "// Restore the proper order:", "fracPart", "=", "fracPart", "/", "10.24", "\n", "return", "intPart", "+", "fracPart", ",", "nil", "\n", "}" ]
// ParsePseudoFloat parses the peculiar format produced by bcache's bch_hprint.
[ "ParsePseudoFloat", "parses", "the", "peculiar", "format", "produced", "by", "bcache", "s", "bch_hprint", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/bcache/get.go#L53-L77
151,534
prometheus/procfs
bcache/get.go
dehumanize
func dehumanize(hbytes []byte) (uint64, error) { ll := len(hbytes) if ll == 0 { return 0, fmt.Errorf("zero-length reply") } lastByte := hbytes[ll-1] mul := float64(1) var ( mant float64 err error ) // If lastByte is beyond the range of ASCII digits, it must be a // multiplier. if lastByte > 57 { // Remove multiplier from slice. hbytes = hbytes[:len(hbytes)-1] const ( _ = 1 << (10 * iota) KiB MiB GiB TiB PiB EiB ZiB YiB ) multipliers := map[rune]float64{ // Source for conversion rules: // linux-kernel/drivers/md/bcache/util.c:bch_hprint() 'k': KiB, 'M': MiB, 'G': GiB, 'T': TiB, 'P': PiB, 'E': EiB, 'Z': ZiB, 'Y': YiB, } mul = multipliers[rune(lastByte)] mant, err = parsePseudoFloat(string(hbytes)) if err != nil { return 0, err } } else { // Not humanized by bch_hprint mant, err = strconv.ParseFloat(string(hbytes), 64) if err != nil { return 0, err } } res := uint64(mant * mul) return res, nil }
go
func dehumanize(hbytes []byte) (uint64, error) { ll := len(hbytes) if ll == 0 { return 0, fmt.Errorf("zero-length reply") } lastByte := hbytes[ll-1] mul := float64(1) var ( mant float64 err error ) // If lastByte is beyond the range of ASCII digits, it must be a // multiplier. if lastByte > 57 { // Remove multiplier from slice. hbytes = hbytes[:len(hbytes)-1] const ( _ = 1 << (10 * iota) KiB MiB GiB TiB PiB EiB ZiB YiB ) multipliers := map[rune]float64{ // Source for conversion rules: // linux-kernel/drivers/md/bcache/util.c:bch_hprint() 'k': KiB, 'M': MiB, 'G': GiB, 'T': TiB, 'P': PiB, 'E': EiB, 'Z': ZiB, 'Y': YiB, } mul = multipliers[rune(lastByte)] mant, err = parsePseudoFloat(string(hbytes)) if err != nil { return 0, err } } else { // Not humanized by bch_hprint mant, err = strconv.ParseFloat(string(hbytes), 64) if err != nil { return 0, err } } res := uint64(mant * mul) return res, nil }
[ "func", "dehumanize", "(", "hbytes", "[", "]", "byte", ")", "(", "uint64", ",", "error", ")", "{", "ll", ":=", "len", "(", "hbytes", ")", "\n", "if", "ll", "==", "0", "{", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "lastByte", ":=", "hbytes", "[", "ll", "-", "1", "]", "\n", "mul", ":=", "float64", "(", "1", ")", "\n", "var", "(", "mant", "float64", "\n", "err", "error", "\n", ")", "\n", "// If lastByte is beyond the range of ASCII digits, it must be a", "// multiplier.", "if", "lastByte", ">", "57", "{", "// Remove multiplier from slice.", "hbytes", "=", "hbytes", "[", ":", "len", "(", "hbytes", ")", "-", "1", "]", "\n\n", "const", "(", "_", "=", "1", "<<", "(", "10", "*", "iota", ")", "\n", "KiB", "\n", "MiB", "\n", "GiB", "\n", "TiB", "\n", "PiB", "\n", "EiB", "\n", "ZiB", "\n", "YiB", "\n", ")", "\n\n", "multipliers", ":=", "map", "[", "rune", "]", "float64", "{", "// Source for conversion rules:", "// linux-kernel/drivers/md/bcache/util.c:bch_hprint()", "'k'", ":", "KiB", ",", "'M'", ":", "MiB", ",", "'G'", ":", "GiB", ",", "'T'", ":", "TiB", ",", "'P'", ":", "PiB", ",", "'E'", ":", "EiB", ",", "'Z'", ":", "ZiB", ",", "'Y'", ":", "YiB", ",", "}", "\n", "mul", "=", "multipliers", "[", "rune", "(", "lastByte", ")", "]", "\n", "mant", ",", "err", "=", "parsePseudoFloat", "(", "string", "(", "hbytes", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "}", "else", "{", "// Not humanized by bch_hprint", "mant", ",", "err", "=", "strconv", ".", "ParseFloat", "(", "string", "(", "hbytes", ")", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "}", "\n", "res", ":=", "uint64", "(", "mant", "*", "mul", ")", "\n", "return", "res", ",", "nil", "\n", "}" ]
// Dehumanize converts a human-readable byte slice into a uint64.
[ "Dehumanize", "converts", "a", "human", "-", "readable", "byte", "slice", "into", "a", "uint64", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/bcache/get.go#L80-L135
151,535
prometheus/procfs
bcache/get.go
parsePriorityStats
func parsePriorityStats(line string, ps *PriorityStats) error { var ( value uint64 err error ) switch { case strings.HasPrefix(line, "Unused:"): fields := strings.Fields(line) rawValue := fields[len(fields)-1] valueStr := strings.TrimSuffix(rawValue, "%") value, err = strconv.ParseUint(valueStr, 10, 64) if err != nil { return err } ps.UnusedPercent = value case strings.HasPrefix(line, "Metadata:"): fields := strings.Fields(line) rawValue := fields[len(fields)-1] valueStr := strings.TrimSuffix(rawValue, "%") value, err = strconv.ParseUint(valueStr, 10, 64) if err != nil { return err } ps.MetadataPercent = value } return nil }
go
func parsePriorityStats(line string, ps *PriorityStats) error { var ( value uint64 err error ) switch { case strings.HasPrefix(line, "Unused:"): fields := strings.Fields(line) rawValue := fields[len(fields)-1] valueStr := strings.TrimSuffix(rawValue, "%") value, err = strconv.ParseUint(valueStr, 10, 64) if err != nil { return err } ps.UnusedPercent = value case strings.HasPrefix(line, "Metadata:"): fields := strings.Fields(line) rawValue := fields[len(fields)-1] valueStr := strings.TrimSuffix(rawValue, "%") value, err = strconv.ParseUint(valueStr, 10, 64) if err != nil { return err } ps.MetadataPercent = value } return nil }
[ "func", "parsePriorityStats", "(", "line", "string", ",", "ps", "*", "PriorityStats", ")", "error", "{", "var", "(", "value", "uint64", "\n", "err", "error", "\n", ")", "\n", "switch", "{", "case", "strings", ".", "HasPrefix", "(", "line", ",", "\"", "\"", ")", ":", "fields", ":=", "strings", ".", "Fields", "(", "line", ")", "\n", "rawValue", ":=", "fields", "[", "len", "(", "fields", ")", "-", "1", "]", "\n", "valueStr", ":=", "strings", ".", "TrimSuffix", "(", "rawValue", ",", "\"", "\"", ")", "\n", "value", ",", "err", "=", "strconv", ".", "ParseUint", "(", "valueStr", ",", "10", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "ps", ".", "UnusedPercent", "=", "value", "\n", "case", "strings", ".", "HasPrefix", "(", "line", ",", "\"", "\"", ")", ":", "fields", ":=", "strings", ".", "Fields", "(", "line", ")", "\n", "rawValue", ":=", "fields", "[", "len", "(", "fields", ")", "-", "1", "]", "\n", "valueStr", ":=", "strings", ".", "TrimSuffix", "(", "rawValue", ",", "\"", "\"", ")", "\n", "value", ",", "err", "=", "strconv", ".", "ParseUint", "(", "valueStr", ",", "10", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "ps", ".", "MetadataPercent", "=", "value", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ParsePriorityStats parses lines from the priority_stats file.
[ "ParsePriorityStats", "parses", "lines", "from", "the", "priority_stats", "file", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/bcache/get.go#L167-L193
151,536
prometheus/procfs
sysfs/system_cpu.go
NewSystemCpufreq
func (fs FS) NewSystemCpufreq() ([]SystemCPUCpufreqStats, error) { var g errgroup.Group cpus, err := filepath.Glob(fs.Path("devices/system/cpu/cpu[0-9]*")) if err != nil { return nil, err } systemCpufreq := make([]SystemCPUCpufreqStats, len(cpus)) for i, cpu := range cpus { cpuName := strings.TrimPrefix(filepath.Base(cpu), "cpu") cpuCpufreqPath := filepath.Join(cpu, "cpufreq") _, err = os.Stat(cpuCpufreqPath) if os.IsNotExist(err) { continue } else if err != nil { return nil, err } // Execute the parsing of each CPU in parallel. // This is done because the kernel intentionally delays access to each CPU by // 50 milliseconds to avoid DDoSing possibly expensive functions. i := i // https://golang.org/doc/faq#closures_and_goroutines g.Go(func() error { cpufreq, err := parseCpufreqCpuinfo(cpuCpufreqPath) if err == nil { cpufreq.Name = cpuName systemCpufreq[i] = *cpufreq } return err }) } if err = g.Wait(); err != nil { return nil, err } return systemCpufreq, nil }
go
func (fs FS) NewSystemCpufreq() ([]SystemCPUCpufreqStats, error) { var g errgroup.Group cpus, err := filepath.Glob(fs.Path("devices/system/cpu/cpu[0-9]*")) if err != nil { return nil, err } systemCpufreq := make([]SystemCPUCpufreqStats, len(cpus)) for i, cpu := range cpus { cpuName := strings.TrimPrefix(filepath.Base(cpu), "cpu") cpuCpufreqPath := filepath.Join(cpu, "cpufreq") _, err = os.Stat(cpuCpufreqPath) if os.IsNotExist(err) { continue } else if err != nil { return nil, err } // Execute the parsing of each CPU in parallel. // This is done because the kernel intentionally delays access to each CPU by // 50 milliseconds to avoid DDoSing possibly expensive functions. i := i // https://golang.org/doc/faq#closures_and_goroutines g.Go(func() error { cpufreq, err := parseCpufreqCpuinfo(cpuCpufreqPath) if err == nil { cpufreq.Name = cpuName systemCpufreq[i] = *cpufreq } return err }) } if err = g.Wait(); err != nil { return nil, err } return systemCpufreq, nil }
[ "func", "(", "fs", "FS", ")", "NewSystemCpufreq", "(", ")", "(", "[", "]", "SystemCPUCpufreqStats", ",", "error", ")", "{", "var", "g", "errgroup", ".", "Group", "\n\n", "cpus", ",", "err", ":=", "filepath", ".", "Glob", "(", "fs", ".", "Path", "(", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "systemCpufreq", ":=", "make", "(", "[", "]", "SystemCPUCpufreqStats", ",", "len", "(", "cpus", ")", ")", "\n", "for", "i", ",", "cpu", ":=", "range", "cpus", "{", "cpuName", ":=", "strings", ".", "TrimPrefix", "(", "filepath", ".", "Base", "(", "cpu", ")", ",", "\"", "\"", ")", "\n\n", "cpuCpufreqPath", ":=", "filepath", ".", "Join", "(", "cpu", ",", "\"", "\"", ")", "\n", "_", ",", "err", "=", "os", ".", "Stat", "(", "cpuCpufreqPath", ")", "\n", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "continue", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Execute the parsing of each CPU in parallel.", "// This is done because the kernel intentionally delays access to each CPU by", "// 50 milliseconds to avoid DDoSing possibly expensive functions.", "i", ":=", "i", "// https://golang.org/doc/faq#closures_and_goroutines", "\n", "g", ".", "Go", "(", "func", "(", ")", "error", "{", "cpufreq", ",", "err", ":=", "parseCpufreqCpuinfo", "(", "cpuCpufreqPath", ")", "\n", "if", "err", "==", "nil", "{", "cpufreq", ".", "Name", "=", "cpuName", "\n", "systemCpufreq", "[", "i", "]", "=", "*", "cpufreq", "\n", "}", "\n", "return", "err", "\n", "}", ")", "\n", "}", "\n\n", "if", "err", "=", "g", ".", "Wait", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "systemCpufreq", ",", "nil", "\n", "}" ]
// NewSystemCpufreq returns CPU frequency metrics for all CPUs.
[ "NewSystemCpufreq", "returns", "CPU", "frequency", "metrics", "for", "all", "CPUs", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/sysfs/system_cpu.go#L60-L99
151,537
prometheus/procfs
xfs/parse.go
extentAllocationStats
func extentAllocationStats(us []uint32) (ExtentAllocationStats, error) { if l := len(us); l != 4 { return ExtentAllocationStats{}, fmt.Errorf("incorrect number of values for XFS extent allocation stats: %d", l) } return ExtentAllocationStats{ ExtentsAllocated: us[0], BlocksAllocated: us[1], ExtentsFreed: us[2], BlocksFreed: us[3], }, nil }
go
func extentAllocationStats(us []uint32) (ExtentAllocationStats, error) { if l := len(us); l != 4 { return ExtentAllocationStats{}, fmt.Errorf("incorrect number of values for XFS extent allocation stats: %d", l) } return ExtentAllocationStats{ ExtentsAllocated: us[0], BlocksAllocated: us[1], ExtentsFreed: us[2], BlocksFreed: us[3], }, nil }
[ "func", "extentAllocationStats", "(", "us", "[", "]", "uint32", ")", "(", "ExtentAllocationStats", ",", "error", ")", "{", "if", "l", ":=", "len", "(", "us", ")", ";", "l", "!=", "4", "{", "return", "ExtentAllocationStats", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "l", ")", "\n", "}", "\n\n", "return", "ExtentAllocationStats", "{", "ExtentsAllocated", ":", "us", "[", "0", "]", ",", "BlocksAllocated", ":", "us", "[", "1", "]", ",", "ExtentsFreed", ":", "us", "[", "2", "]", ",", "BlocksFreed", ":", "us", "[", "3", "]", ",", "}", ",", "nil", "\n", "}" ]
// extentAllocationStats builds an ExtentAllocationStats from a slice of uint32s.
[ "extentAllocationStats", "builds", "an", "ExtentAllocationStats", "from", "a", "slice", "of", "uint32s", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/xfs/parse.go#L128-L139
151,538
prometheus/procfs
xfs/parse.go
btreeStats
func btreeStats(us []uint32) (BTreeStats, error) { if l := len(us); l != 4 { return BTreeStats{}, fmt.Errorf("incorrect number of values for XFS btree stats: %d", l) } return BTreeStats{ Lookups: us[0], Compares: us[1], RecordsInserted: us[2], RecordsDeleted: us[3], }, nil }
go
func btreeStats(us []uint32) (BTreeStats, error) { if l := len(us); l != 4 { return BTreeStats{}, fmt.Errorf("incorrect number of values for XFS btree stats: %d", l) } return BTreeStats{ Lookups: us[0], Compares: us[1], RecordsInserted: us[2], RecordsDeleted: us[3], }, nil }
[ "func", "btreeStats", "(", "us", "[", "]", "uint32", ")", "(", "BTreeStats", ",", "error", ")", "{", "if", "l", ":=", "len", "(", "us", ")", ";", "l", "!=", "4", "{", "return", "BTreeStats", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "l", ")", "\n", "}", "\n\n", "return", "BTreeStats", "{", "Lookups", ":", "us", "[", "0", "]", ",", "Compares", ":", "us", "[", "1", "]", ",", "RecordsInserted", ":", "us", "[", "2", "]", ",", "RecordsDeleted", ":", "us", "[", "3", "]", ",", "}", ",", "nil", "\n", "}" ]
// btreeStats builds a BTreeStats from a slice of uint32s.
[ "btreeStats", "builds", "a", "BTreeStats", "from", "a", "slice", "of", "uint32s", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/xfs/parse.go#L142-L153
151,539
prometheus/procfs
xfs/parse.go
blockMappingStats
func blockMappingStats(us []uint32) (BlockMappingStats, error) { if l := len(us); l != 7 { return BlockMappingStats{}, fmt.Errorf("incorrect number of values for XFS block mapping stats: %d", l) } return BlockMappingStats{ Reads: us[0], Writes: us[1], Unmaps: us[2], ExtentListInsertions: us[3], ExtentListDeletions: us[4], ExtentListLookups: us[5], ExtentListCompares: us[6], }, nil }
go
func blockMappingStats(us []uint32) (BlockMappingStats, error) { if l := len(us); l != 7 { return BlockMappingStats{}, fmt.Errorf("incorrect number of values for XFS block mapping stats: %d", l) } return BlockMappingStats{ Reads: us[0], Writes: us[1], Unmaps: us[2], ExtentListInsertions: us[3], ExtentListDeletions: us[4], ExtentListLookups: us[5], ExtentListCompares: us[6], }, nil }
[ "func", "blockMappingStats", "(", "us", "[", "]", "uint32", ")", "(", "BlockMappingStats", ",", "error", ")", "{", "if", "l", ":=", "len", "(", "us", ")", ";", "l", "!=", "7", "{", "return", "BlockMappingStats", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "l", ")", "\n", "}", "\n\n", "return", "BlockMappingStats", "{", "Reads", ":", "us", "[", "0", "]", ",", "Writes", ":", "us", "[", "1", "]", ",", "Unmaps", ":", "us", "[", "2", "]", ",", "ExtentListInsertions", ":", "us", "[", "3", "]", ",", "ExtentListDeletions", ":", "us", "[", "4", "]", ",", "ExtentListLookups", ":", "us", "[", "5", "]", ",", "ExtentListCompares", ":", "us", "[", "6", "]", ",", "}", ",", "nil", "\n", "}" ]
// BlockMappingStat builds a BlockMappingStats from a slice of uint32s.
[ "BlockMappingStat", "builds", "a", "BlockMappingStats", "from", "a", "slice", "of", "uint32s", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/xfs/parse.go#L156-L170
151,540
prometheus/procfs
xfs/parse.go
directoryOperationStats
func directoryOperationStats(us []uint32) (DirectoryOperationStats, error) { if l := len(us); l != 4 { return DirectoryOperationStats{}, fmt.Errorf("incorrect number of values for XFS directory operation stats: %d", l) } return DirectoryOperationStats{ Lookups: us[0], Creates: us[1], Removes: us[2], Getdents: us[3], }, nil }
go
func directoryOperationStats(us []uint32) (DirectoryOperationStats, error) { if l := len(us); l != 4 { return DirectoryOperationStats{}, fmt.Errorf("incorrect number of values for XFS directory operation stats: %d", l) } return DirectoryOperationStats{ Lookups: us[0], Creates: us[1], Removes: us[2], Getdents: us[3], }, nil }
[ "func", "directoryOperationStats", "(", "us", "[", "]", "uint32", ")", "(", "DirectoryOperationStats", ",", "error", ")", "{", "if", "l", ":=", "len", "(", "us", ")", ";", "l", "!=", "4", "{", "return", "DirectoryOperationStats", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "l", ")", "\n", "}", "\n\n", "return", "DirectoryOperationStats", "{", "Lookups", ":", "us", "[", "0", "]", ",", "Creates", ":", "us", "[", "1", "]", ",", "Removes", ":", "us", "[", "2", "]", ",", "Getdents", ":", "us", "[", "3", "]", ",", "}", ",", "nil", "\n", "}" ]
// DirectoryOperationStats builds a DirectoryOperationStats from a slice of uint32s.
[ "DirectoryOperationStats", "builds", "a", "DirectoryOperationStats", "from", "a", "slice", "of", "uint32s", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/xfs/parse.go#L173-L184
151,541
prometheus/procfs
xfs/parse.go
transactionStats
func transactionStats(us []uint32) (TransactionStats, error) { if l := len(us); l != 3 { return TransactionStats{}, fmt.Errorf("incorrect number of values for XFS transaction stats: %d", l) } return TransactionStats{ Sync: us[0], Async: us[1], Empty: us[2], }, nil }
go
func transactionStats(us []uint32) (TransactionStats, error) { if l := len(us); l != 3 { return TransactionStats{}, fmt.Errorf("incorrect number of values for XFS transaction stats: %d", l) } return TransactionStats{ Sync: us[0], Async: us[1], Empty: us[2], }, nil }
[ "func", "transactionStats", "(", "us", "[", "]", "uint32", ")", "(", "TransactionStats", ",", "error", ")", "{", "if", "l", ":=", "len", "(", "us", ")", ";", "l", "!=", "3", "{", "return", "TransactionStats", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "l", ")", "\n", "}", "\n\n", "return", "TransactionStats", "{", "Sync", ":", "us", "[", "0", "]", ",", "Async", ":", "us", "[", "1", "]", ",", "Empty", ":", "us", "[", "2", "]", ",", "}", ",", "nil", "\n", "}" ]
// TransactionStats builds a TransactionStats from a slice of uint32s.
[ "TransactionStats", "builds", "a", "TransactionStats", "from", "a", "slice", "of", "uint32s", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/xfs/parse.go#L187-L197
151,542
prometheus/procfs
xfs/parse.go
inodeOperationStats
func inodeOperationStats(us []uint32) (InodeOperationStats, error) { if l := len(us); l != 7 { return InodeOperationStats{}, fmt.Errorf("incorrect number of values for XFS inode operation stats: %d", l) } return InodeOperationStats{ Attempts: us[0], Found: us[1], Recycle: us[2], Missed: us[3], Duplicate: us[4], Reclaims: us[5], AttributeChange: us[6], }, nil }
go
func inodeOperationStats(us []uint32) (InodeOperationStats, error) { if l := len(us); l != 7 { return InodeOperationStats{}, fmt.Errorf("incorrect number of values for XFS inode operation stats: %d", l) } return InodeOperationStats{ Attempts: us[0], Found: us[1], Recycle: us[2], Missed: us[3], Duplicate: us[4], Reclaims: us[5], AttributeChange: us[6], }, nil }
[ "func", "inodeOperationStats", "(", "us", "[", "]", "uint32", ")", "(", "InodeOperationStats", ",", "error", ")", "{", "if", "l", ":=", "len", "(", "us", ")", ";", "l", "!=", "7", "{", "return", "InodeOperationStats", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "l", ")", "\n", "}", "\n\n", "return", "InodeOperationStats", "{", "Attempts", ":", "us", "[", "0", "]", ",", "Found", ":", "us", "[", "1", "]", ",", "Recycle", ":", "us", "[", "2", "]", ",", "Missed", ":", "us", "[", "3", "]", ",", "Duplicate", ":", "us", "[", "4", "]", ",", "Reclaims", ":", "us", "[", "5", "]", ",", "AttributeChange", ":", "us", "[", "6", "]", ",", "}", ",", "nil", "\n", "}" ]
// InodeOperationStats builds an InodeOperationStats from a slice of uint32s.
[ "InodeOperationStats", "builds", "an", "InodeOperationStats", "from", "a", "slice", "of", "uint32s", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/xfs/parse.go#L200-L214
151,543
prometheus/procfs
xfs/parse.go
logOperationStats
func logOperationStats(us []uint32) (LogOperationStats, error) { if l := len(us); l != 5 { return LogOperationStats{}, fmt.Errorf("incorrect number of values for XFS log operation stats: %d", l) } return LogOperationStats{ Writes: us[0], Blocks: us[1], NoInternalBuffers: us[2], Force: us[3], ForceSleep: us[4], }, nil }
go
func logOperationStats(us []uint32) (LogOperationStats, error) { if l := len(us); l != 5 { return LogOperationStats{}, fmt.Errorf("incorrect number of values for XFS log operation stats: %d", l) } return LogOperationStats{ Writes: us[0], Blocks: us[1], NoInternalBuffers: us[2], Force: us[3], ForceSleep: us[4], }, nil }
[ "func", "logOperationStats", "(", "us", "[", "]", "uint32", ")", "(", "LogOperationStats", ",", "error", ")", "{", "if", "l", ":=", "len", "(", "us", ")", ";", "l", "!=", "5", "{", "return", "LogOperationStats", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "l", ")", "\n", "}", "\n\n", "return", "LogOperationStats", "{", "Writes", ":", "us", "[", "0", "]", ",", "Blocks", ":", "us", "[", "1", "]", ",", "NoInternalBuffers", ":", "us", "[", "2", "]", ",", "Force", ":", "us", "[", "3", "]", ",", "ForceSleep", ":", "us", "[", "4", "]", ",", "}", ",", "nil", "\n", "}" ]
// LogOperationStats builds a LogOperationStats from a slice of uint32s.
[ "LogOperationStats", "builds", "a", "LogOperationStats", "from", "a", "slice", "of", "uint32s", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/xfs/parse.go#L217-L229
151,544
prometheus/procfs
xfs/parse.go
readWriteStats
func readWriteStats(us []uint32) (ReadWriteStats, error) { if l := len(us); l != 2 { return ReadWriteStats{}, fmt.Errorf("incorrect number of values for XFS read write stats: %d", l) } return ReadWriteStats{ Read: us[0], Write: us[1], }, nil }
go
func readWriteStats(us []uint32) (ReadWriteStats, error) { if l := len(us); l != 2 { return ReadWriteStats{}, fmt.Errorf("incorrect number of values for XFS read write stats: %d", l) } return ReadWriteStats{ Read: us[0], Write: us[1], }, nil }
[ "func", "readWriteStats", "(", "us", "[", "]", "uint32", ")", "(", "ReadWriteStats", ",", "error", ")", "{", "if", "l", ":=", "len", "(", "us", ")", ";", "l", "!=", "2", "{", "return", "ReadWriteStats", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "l", ")", "\n", "}", "\n\n", "return", "ReadWriteStats", "{", "Read", ":", "us", "[", "0", "]", ",", "Write", ":", "us", "[", "1", "]", ",", "}", ",", "nil", "\n", "}" ]
// ReadWriteStats builds a ReadWriteStats from a slice of uint32s.
[ "ReadWriteStats", "builds", "a", "ReadWriteStats", "from", "a", "slice", "of", "uint32s", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/xfs/parse.go#L232-L241
151,545
prometheus/procfs
xfs/parse.go
attributeOperationStats
func attributeOperationStats(us []uint32) (AttributeOperationStats, error) { if l := len(us); l != 4 { return AttributeOperationStats{}, fmt.Errorf("incorrect number of values for XFS attribute operation stats: %d", l) } return AttributeOperationStats{ Get: us[0], Set: us[1], Remove: us[2], List: us[3], }, nil }
go
func attributeOperationStats(us []uint32) (AttributeOperationStats, error) { if l := len(us); l != 4 { return AttributeOperationStats{}, fmt.Errorf("incorrect number of values for XFS attribute operation stats: %d", l) } return AttributeOperationStats{ Get: us[0], Set: us[1], Remove: us[2], List: us[3], }, nil }
[ "func", "attributeOperationStats", "(", "us", "[", "]", "uint32", ")", "(", "AttributeOperationStats", ",", "error", ")", "{", "if", "l", ":=", "len", "(", "us", ")", ";", "l", "!=", "4", "{", "return", "AttributeOperationStats", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "l", ")", "\n", "}", "\n\n", "return", "AttributeOperationStats", "{", "Get", ":", "us", "[", "0", "]", ",", "Set", ":", "us", "[", "1", "]", ",", "Remove", ":", "us", "[", "2", "]", ",", "List", ":", "us", "[", "3", "]", ",", "}", ",", "nil", "\n", "}" ]
// AttributeOperationStats builds an AttributeOperationStats from a slice of uint32s.
[ "AttributeOperationStats", "builds", "an", "AttributeOperationStats", "from", "a", "slice", "of", "uint32s", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/xfs/parse.go#L244-L255
151,546
prometheus/procfs
xfs/parse.go
inodeClusteringStats
func inodeClusteringStats(us []uint32) (InodeClusteringStats, error) { if l := len(us); l != 3 { return InodeClusteringStats{}, fmt.Errorf("incorrect number of values for XFS inode clustering stats: %d", l) } return InodeClusteringStats{ Iflush: us[0], Flush: us[1], FlushInode: us[2], }, nil }
go
func inodeClusteringStats(us []uint32) (InodeClusteringStats, error) { if l := len(us); l != 3 { return InodeClusteringStats{}, fmt.Errorf("incorrect number of values for XFS inode clustering stats: %d", l) } return InodeClusteringStats{ Iflush: us[0], Flush: us[1], FlushInode: us[2], }, nil }
[ "func", "inodeClusteringStats", "(", "us", "[", "]", "uint32", ")", "(", "InodeClusteringStats", ",", "error", ")", "{", "if", "l", ":=", "len", "(", "us", ")", ";", "l", "!=", "3", "{", "return", "InodeClusteringStats", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "l", ")", "\n", "}", "\n\n", "return", "InodeClusteringStats", "{", "Iflush", ":", "us", "[", "0", "]", ",", "Flush", ":", "us", "[", "1", "]", ",", "FlushInode", ":", "us", "[", "2", "]", ",", "}", ",", "nil", "\n", "}" ]
// InodeClusteringStats builds an InodeClusteringStats from a slice of uint32s.
[ "InodeClusteringStats", "builds", "an", "InodeClusteringStats", "from", "a", "slice", "of", "uint32s", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/xfs/parse.go#L258-L268
151,547
prometheus/procfs
xfs/parse.go
vnodeStats
func vnodeStats(us []uint32) (VnodeStats, error) { // The attribute "Free" appears to not be available on older XFS // stats versions. Therefore, 7 or 8 elements may appear in // this slice. l := len(us) if l != 7 && l != 8 { return VnodeStats{}, fmt.Errorf("incorrect number of values for XFS vnode stats: %d", l) } s := VnodeStats{ Active: us[0], Allocate: us[1], Get: us[2], Hold: us[3], Release: us[4], Reclaim: us[5], Remove: us[6], } // Skip adding free, unless it is present. The zero value will // be used in place of an actual count. if l == 7 { return s, nil } s.Free = us[7] return s, nil }
go
func vnodeStats(us []uint32) (VnodeStats, error) { // The attribute "Free" appears to not be available on older XFS // stats versions. Therefore, 7 or 8 elements may appear in // this slice. l := len(us) if l != 7 && l != 8 { return VnodeStats{}, fmt.Errorf("incorrect number of values for XFS vnode stats: %d", l) } s := VnodeStats{ Active: us[0], Allocate: us[1], Get: us[2], Hold: us[3], Release: us[4], Reclaim: us[5], Remove: us[6], } // Skip adding free, unless it is present. The zero value will // be used in place of an actual count. if l == 7 { return s, nil } s.Free = us[7] return s, nil }
[ "func", "vnodeStats", "(", "us", "[", "]", "uint32", ")", "(", "VnodeStats", ",", "error", ")", "{", "// The attribute \"Free\" appears to not be available on older XFS", "// stats versions. Therefore, 7 or 8 elements may appear in", "// this slice.", "l", ":=", "len", "(", "us", ")", "\n", "if", "l", "!=", "7", "&&", "l", "!=", "8", "{", "return", "VnodeStats", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "l", ")", "\n", "}", "\n\n", "s", ":=", "VnodeStats", "{", "Active", ":", "us", "[", "0", "]", ",", "Allocate", ":", "us", "[", "1", "]", ",", "Get", ":", "us", "[", "2", "]", ",", "Hold", ":", "us", "[", "3", "]", ",", "Release", ":", "us", "[", "4", "]", ",", "Reclaim", ":", "us", "[", "5", "]", ",", "Remove", ":", "us", "[", "6", "]", ",", "}", "\n\n", "// Skip adding free, unless it is present. The zero value will", "// be used in place of an actual count.", "if", "l", "==", "7", "{", "return", "s", ",", "nil", "\n", "}", "\n\n", "s", ".", "Free", "=", "us", "[", "7", "]", "\n", "return", "s", ",", "nil", "\n", "}" ]
// VnodeStats builds a VnodeStats from a slice of uint32s.
[ "VnodeStats", "builds", "a", "VnodeStats", "from", "a", "slice", "of", "uint32s", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/xfs/parse.go#L271-L298
151,548
prometheus/procfs
xfs/parse.go
bufferStats
func bufferStats(us []uint32) (BufferStats, error) { if l := len(us); l != 9 { return BufferStats{}, fmt.Errorf("incorrect number of values for XFS buffer stats: %d", l) } return BufferStats{ Get: us[0], Create: us[1], GetLocked: us[2], GetLockedWaited: us[3], BusyLocked: us[4], MissLocked: us[5], PageRetries: us[6], PageFound: us[7], GetRead: us[8], }, nil }
go
func bufferStats(us []uint32) (BufferStats, error) { if l := len(us); l != 9 { return BufferStats{}, fmt.Errorf("incorrect number of values for XFS buffer stats: %d", l) } return BufferStats{ Get: us[0], Create: us[1], GetLocked: us[2], GetLockedWaited: us[3], BusyLocked: us[4], MissLocked: us[5], PageRetries: us[6], PageFound: us[7], GetRead: us[8], }, nil }
[ "func", "bufferStats", "(", "us", "[", "]", "uint32", ")", "(", "BufferStats", ",", "error", ")", "{", "if", "l", ":=", "len", "(", "us", ")", ";", "l", "!=", "9", "{", "return", "BufferStats", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "l", ")", "\n", "}", "\n\n", "return", "BufferStats", "{", "Get", ":", "us", "[", "0", "]", ",", "Create", ":", "us", "[", "1", "]", ",", "GetLocked", ":", "us", "[", "2", "]", ",", "GetLockedWaited", ":", "us", "[", "3", "]", ",", "BusyLocked", ":", "us", "[", "4", "]", ",", "MissLocked", ":", "us", "[", "5", "]", ",", "PageRetries", ":", "us", "[", "6", "]", ",", "PageFound", ":", "us", "[", "7", "]", ",", "GetRead", ":", "us", "[", "8", "]", ",", "}", ",", "nil", "\n", "}" ]
// BufferStats builds a BufferStats from a slice of uint32s.
[ "BufferStats", "builds", "a", "BufferStats", "from", "a", "slice", "of", "uint32s", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/xfs/parse.go#L301-L317
151,549
prometheus/procfs
xfs/parse.go
extendedPrecisionStats
func extendedPrecisionStats(us []uint64) (ExtendedPrecisionStats, error) { if l := len(us); l != 3 { return ExtendedPrecisionStats{}, fmt.Errorf("incorrect number of values for XFS extended precision stats: %d", l) } return ExtendedPrecisionStats{ FlushBytes: us[0], WriteBytes: us[1], ReadBytes: us[2], }, nil }
go
func extendedPrecisionStats(us []uint64) (ExtendedPrecisionStats, error) { if l := len(us); l != 3 { return ExtendedPrecisionStats{}, fmt.Errorf("incorrect number of values for XFS extended precision stats: %d", l) } return ExtendedPrecisionStats{ FlushBytes: us[0], WriteBytes: us[1], ReadBytes: us[2], }, nil }
[ "func", "extendedPrecisionStats", "(", "us", "[", "]", "uint64", ")", "(", "ExtendedPrecisionStats", ",", "error", ")", "{", "if", "l", ":=", "len", "(", "us", ")", ";", "l", "!=", "3", "{", "return", "ExtendedPrecisionStats", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "l", ")", "\n", "}", "\n\n", "return", "ExtendedPrecisionStats", "{", "FlushBytes", ":", "us", "[", "0", "]", ",", "WriteBytes", ":", "us", "[", "1", "]", ",", "ReadBytes", ":", "us", "[", "2", "]", ",", "}", ",", "nil", "\n", "}" ]
// ExtendedPrecisionStats builds an ExtendedPrecisionStats from a slice of uint32s.
[ "ExtendedPrecisionStats", "builds", "an", "ExtendedPrecisionStats", "from", "a", "slice", "of", "uint32s", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/xfs/parse.go#L320-L330
151,550
prometheus/procfs
fs.go
Path
func (fs FS) Path(p ...string) string { return path.Join(append([]string{string(fs)}, p...)...) }
go
func (fs FS) Path(p ...string) string { return path.Join(append([]string{string(fs)}, p...)...) }
[ "func", "(", "fs", "FS", ")", "Path", "(", "p", "...", "string", ")", "string", "{", "return", "path", ".", "Join", "(", "append", "(", "[", "]", "string", "{", "string", "(", "fs", ")", "}", ",", "p", "...", ")", "...", ")", "\n", "}" ]
// Path returns the path of the given subsystem relative to the procfs root.
[ "Path", "returns", "the", "path", "of", "the", "given", "subsystem", "relative", "to", "the", "procfs", "root", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/fs.go#L44-L46
151,551
prometheus/procfs
sysfs/class_thermal.go
NewClassThermalZoneStats
func (fs FS) NewClassThermalZoneStats() ([]ClassThermalZoneStats, error) { zones, err := filepath.Glob(fs.Path("class/thermal/thermal_zone[0-9]*")) if err != nil { return []ClassThermalZoneStats{}, err } var zoneStats = ClassThermalZoneStats{} stats := make([]ClassThermalZoneStats, len(zones)) for i, zone := range zones { zoneName := strings.TrimPrefix(filepath.Base(zone), "thermal_zone") zoneStats, err = parseClassThermalZone(zone) if err != nil { return []ClassThermalZoneStats{}, err } zoneStats.Name = zoneName stats[i] = zoneStats } return stats, nil }
go
func (fs FS) NewClassThermalZoneStats() ([]ClassThermalZoneStats, error) { zones, err := filepath.Glob(fs.Path("class/thermal/thermal_zone[0-9]*")) if err != nil { return []ClassThermalZoneStats{}, err } var zoneStats = ClassThermalZoneStats{} stats := make([]ClassThermalZoneStats, len(zones)) for i, zone := range zones { zoneName := strings.TrimPrefix(filepath.Base(zone), "thermal_zone") zoneStats, err = parseClassThermalZone(zone) if err != nil { return []ClassThermalZoneStats{}, err } zoneStats.Name = zoneName stats[i] = zoneStats } return stats, nil }
[ "func", "(", "fs", "FS", ")", "NewClassThermalZoneStats", "(", ")", "(", "[", "]", "ClassThermalZoneStats", ",", "error", ")", "{", "zones", ",", "err", ":=", "filepath", ".", "Glob", "(", "fs", ".", "Path", "(", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "[", "]", "ClassThermalZoneStats", "{", "}", ",", "err", "\n", "}", "\n\n", "var", "zoneStats", "=", "ClassThermalZoneStats", "{", "}", "\n", "stats", ":=", "make", "(", "[", "]", "ClassThermalZoneStats", ",", "len", "(", "zones", ")", ")", "\n", "for", "i", ",", "zone", ":=", "range", "zones", "{", "zoneName", ":=", "strings", ".", "TrimPrefix", "(", "filepath", ".", "Base", "(", "zone", ")", ",", "\"", "\"", ")", "\n\n", "zoneStats", ",", "err", "=", "parseClassThermalZone", "(", "zone", ")", "\n", "if", "err", "!=", "nil", "{", "return", "[", "]", "ClassThermalZoneStats", "{", "}", ",", "err", "\n", "}", "\n", "zoneStats", ".", "Name", "=", "zoneName", "\n", "stats", "[", "i", "]", "=", "zoneStats", "\n", "}", "\n", "return", "stats", ",", "nil", "\n", "}" ]
// NewClassThermalZoneStats returns Thermal Zone metrics for all zones.
[ "NewClassThermalZoneStats", "returns", "Thermal", "Zone", "metrics", "for", "all", "zones", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/sysfs/class_thermal.go#L39-L58
151,552
prometheus/procfs
mdstat.go
ParseMDStat
func (fs FS) ParseMDStat() (mdstates []MDStat, err error) { mdStatusFilePath := fs.Path("mdstat") content, err := ioutil.ReadFile(mdStatusFilePath) if err != nil { return []MDStat{}, fmt.Errorf("error parsing %s: %s", mdStatusFilePath, err) } mdStates := []MDStat{} lines := strings.Split(string(content), "\n") for i, l := range lines { if l == "" { continue } if l[0] == ' ' { continue } if strings.HasPrefix(l, "Personalities") || strings.HasPrefix(l, "unused") { continue } mainLine := strings.Split(l, " ") if len(mainLine) < 3 { return mdStates, fmt.Errorf("error parsing mdline: %s", l) } mdName := mainLine[0] activityState := mainLine[2] if len(lines) <= i+3 { return mdStates, fmt.Errorf( "error parsing %s: too few lines for md device %s", mdStatusFilePath, mdName, ) } active, total, size, err := evalStatusline(lines[i+1]) if err != nil { return mdStates, fmt.Errorf("error parsing %s: %s", mdStatusFilePath, err) } // j is the line number of the syncing-line. j := i + 2 if strings.Contains(lines[i+2], "bitmap") { // skip bitmap line j = i + 3 } // If device is syncing at the moment, get the number of currently // synced bytes, otherwise that number equals the size of the device. syncedBlocks := size if strings.Contains(lines[j], "recovery") || strings.Contains(lines[j], "resync") { syncedBlocks, err = evalBuildline(lines[j]) if err != nil { return mdStates, fmt.Errorf("error parsing %s: %s", mdStatusFilePath, err) } } mdStates = append(mdStates, MDStat{ Name: mdName, ActivityState: activityState, DisksActive: active, DisksTotal: total, BlocksTotal: size, BlocksSynced: syncedBlocks, }) } return mdStates, nil }
go
func (fs FS) ParseMDStat() (mdstates []MDStat, err error) { mdStatusFilePath := fs.Path("mdstat") content, err := ioutil.ReadFile(mdStatusFilePath) if err != nil { return []MDStat{}, fmt.Errorf("error parsing %s: %s", mdStatusFilePath, err) } mdStates := []MDStat{} lines := strings.Split(string(content), "\n") for i, l := range lines { if l == "" { continue } if l[0] == ' ' { continue } if strings.HasPrefix(l, "Personalities") || strings.HasPrefix(l, "unused") { continue } mainLine := strings.Split(l, " ") if len(mainLine) < 3 { return mdStates, fmt.Errorf("error parsing mdline: %s", l) } mdName := mainLine[0] activityState := mainLine[2] if len(lines) <= i+3 { return mdStates, fmt.Errorf( "error parsing %s: too few lines for md device %s", mdStatusFilePath, mdName, ) } active, total, size, err := evalStatusline(lines[i+1]) if err != nil { return mdStates, fmt.Errorf("error parsing %s: %s", mdStatusFilePath, err) } // j is the line number of the syncing-line. j := i + 2 if strings.Contains(lines[i+2], "bitmap") { // skip bitmap line j = i + 3 } // If device is syncing at the moment, get the number of currently // synced bytes, otherwise that number equals the size of the device. syncedBlocks := size if strings.Contains(lines[j], "recovery") || strings.Contains(lines[j], "resync") { syncedBlocks, err = evalBuildline(lines[j]) if err != nil { return mdStates, fmt.Errorf("error parsing %s: %s", mdStatusFilePath, err) } } mdStates = append(mdStates, MDStat{ Name: mdName, ActivityState: activityState, DisksActive: active, DisksTotal: total, BlocksTotal: size, BlocksSynced: syncedBlocks, }) } return mdStates, nil }
[ "func", "(", "fs", "FS", ")", "ParseMDStat", "(", ")", "(", "mdstates", "[", "]", "MDStat", ",", "err", "error", ")", "{", "mdStatusFilePath", ":=", "fs", ".", "Path", "(", "\"", "\"", ")", "\n", "content", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "mdStatusFilePath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "[", "]", "MDStat", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "mdStatusFilePath", ",", "err", ")", "\n", "}", "\n\n", "mdStates", ":=", "[", "]", "MDStat", "{", "}", "\n", "lines", ":=", "strings", ".", "Split", "(", "string", "(", "content", ")", ",", "\"", "\\n", "\"", ")", "\n", "for", "i", ",", "l", ":=", "range", "lines", "{", "if", "l", "==", "\"", "\"", "{", "continue", "\n", "}", "\n", "if", "l", "[", "0", "]", "==", "' '", "{", "continue", "\n", "}", "\n", "if", "strings", ".", "HasPrefix", "(", "l", ",", "\"", "\"", ")", "||", "strings", ".", "HasPrefix", "(", "l", ",", "\"", "\"", ")", "{", "continue", "\n", "}", "\n\n", "mainLine", ":=", "strings", ".", "Split", "(", "l", ",", "\"", "\"", ")", "\n", "if", "len", "(", "mainLine", ")", "<", "3", "{", "return", "mdStates", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "l", ")", "\n", "}", "\n", "mdName", ":=", "mainLine", "[", "0", "]", "\n", "activityState", ":=", "mainLine", "[", "2", "]", "\n\n", "if", "len", "(", "lines", ")", "<=", "i", "+", "3", "{", "return", "mdStates", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "mdStatusFilePath", ",", "mdName", ",", ")", "\n", "}", "\n\n", "active", ",", "total", ",", "size", ",", "err", ":=", "evalStatusline", "(", "lines", "[", "i", "+", "1", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "mdStates", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "mdStatusFilePath", ",", "err", ")", "\n", "}", "\n\n", "// j is the line number of the syncing-line.", "j", ":=", "i", "+", "2", "\n", "if", "strings", ".", "Contains", "(", "lines", "[", "i", "+", "2", "]", ",", "\"", "\"", ")", "{", "// skip bitmap line", "j", "=", "i", "+", "3", "\n", "}", "\n\n", "// If device is syncing at the moment, get the number of currently", "// synced bytes, otherwise that number equals the size of the device.", "syncedBlocks", ":=", "size", "\n", "if", "strings", ".", "Contains", "(", "lines", "[", "j", "]", ",", "\"", "\"", ")", "||", "strings", ".", "Contains", "(", "lines", "[", "j", "]", ",", "\"", "\"", ")", "{", "syncedBlocks", ",", "err", "=", "evalBuildline", "(", "lines", "[", "j", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "mdStates", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "mdStatusFilePath", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "mdStates", "=", "append", "(", "mdStates", ",", "MDStat", "{", "Name", ":", "mdName", ",", "ActivityState", ":", "activityState", ",", "DisksActive", ":", "active", ",", "DisksTotal", ":", "total", ",", "BlocksTotal", ":", "size", ",", "BlocksSynced", ":", "syncedBlocks", ",", "}", ")", "\n", "}", "\n\n", "return", "mdStates", ",", "nil", "\n", "}" ]
// ParseMDStat parses an mdstat-file and returns a struct with the relevant infos.
[ "ParseMDStat", "parses", "an", "mdstat", "-", "file", "and", "returns", "a", "struct", "with", "the", "relevant", "infos", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/mdstat.go#L46-L113
151,553
prometheus/procfs
stat.go
parseSoftIRQStat
func parseSoftIRQStat(line string) (SoftIRQStat, uint64, error) { softIRQStat := SoftIRQStat{} var total uint64 var prefix string _, err := fmt.Sscanf(line, "%s %d %d %d %d %d %d %d %d %d %d %d", &prefix, &total, &softIRQStat.Hi, &softIRQStat.Timer, &softIRQStat.NetTx, &softIRQStat.NetRx, &softIRQStat.Block, &softIRQStat.BlockIoPoll, &softIRQStat.Tasklet, &softIRQStat.Sched, &softIRQStat.Hrtimer, &softIRQStat.Rcu) if err != nil { return SoftIRQStat{}, 0, fmt.Errorf("couldn't parse %s (softirq): %s", line, err) } return softIRQStat, total, nil }
go
func parseSoftIRQStat(line string) (SoftIRQStat, uint64, error) { softIRQStat := SoftIRQStat{} var total uint64 var prefix string _, err := fmt.Sscanf(line, "%s %d %d %d %d %d %d %d %d %d %d %d", &prefix, &total, &softIRQStat.Hi, &softIRQStat.Timer, &softIRQStat.NetTx, &softIRQStat.NetRx, &softIRQStat.Block, &softIRQStat.BlockIoPoll, &softIRQStat.Tasklet, &softIRQStat.Sched, &softIRQStat.Hrtimer, &softIRQStat.Rcu) if err != nil { return SoftIRQStat{}, 0, fmt.Errorf("couldn't parse %s (softirq): %s", line, err) } return softIRQStat, total, nil }
[ "func", "parseSoftIRQStat", "(", "line", "string", ")", "(", "SoftIRQStat", ",", "uint64", ",", "error", ")", "{", "softIRQStat", ":=", "SoftIRQStat", "{", "}", "\n", "var", "total", "uint64", "\n", "var", "prefix", "string", "\n\n", "_", ",", "err", ":=", "fmt", ".", "Sscanf", "(", "line", ",", "\"", "\"", ",", "&", "prefix", ",", "&", "total", ",", "&", "softIRQStat", ".", "Hi", ",", "&", "softIRQStat", ".", "Timer", ",", "&", "softIRQStat", ".", "NetTx", ",", "&", "softIRQStat", ".", "NetRx", ",", "&", "softIRQStat", ".", "Block", ",", "&", "softIRQStat", ".", "BlockIoPoll", ",", "&", "softIRQStat", ".", "Tasklet", ",", "&", "softIRQStat", ".", "Sched", ",", "&", "softIRQStat", ".", "Hrtimer", ",", "&", "softIRQStat", ".", "Rcu", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "SoftIRQStat", "{", "}", ",", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "line", ",", "err", ")", "\n", "}", "\n\n", "return", "softIRQStat", ",", "total", ",", "nil", "\n", "}" ]
// Parse a softirq line.
[ "Parse", "a", "softirq", "line", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/stat.go#L133-L150
151,554
prometheus/procfs
ipvs.go
NewIPVSStats
func NewIPVSStats() (IPVSStats, error) { fs, err := NewFS(DefaultMountPoint) if err != nil { return IPVSStats{}, err } return fs.NewIPVSStats() }
go
func NewIPVSStats() (IPVSStats, error) { fs, err := NewFS(DefaultMountPoint) if err != nil { return IPVSStats{}, err } return fs.NewIPVSStats() }
[ "func", "NewIPVSStats", "(", ")", "(", "IPVSStats", ",", "error", ")", "{", "fs", ",", "err", ":=", "NewFS", "(", "DefaultMountPoint", ")", "\n", "if", "err", "!=", "nil", "{", "return", "IPVSStats", "{", "}", ",", "err", "\n", "}", "\n\n", "return", "fs", ".", "NewIPVSStats", "(", ")", "\n", "}" ]
// NewIPVSStats reads the IPVS statistics.
[ "NewIPVSStats", "reads", "the", "IPVS", "statistics", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/ipvs.go#L66-L73
151,555
prometheus/procfs
ipvs.go
NewIPVSStats
func (fs FS) NewIPVSStats() (IPVSStats, error) { file, err := os.Open(fs.Path("net/ip_vs_stats")) if err != nil { return IPVSStats{}, err } defer file.Close() return parseIPVSStats(file) }
go
func (fs FS) NewIPVSStats() (IPVSStats, error) { file, err := os.Open(fs.Path("net/ip_vs_stats")) if err != nil { return IPVSStats{}, err } defer file.Close() return parseIPVSStats(file) }
[ "func", "(", "fs", "FS", ")", "NewIPVSStats", "(", ")", "(", "IPVSStats", ",", "error", ")", "{", "file", ",", "err", ":=", "os", ".", "Open", "(", "fs", ".", "Path", "(", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "IPVSStats", "{", "}", ",", "err", "\n", "}", "\n", "defer", "file", ".", "Close", "(", ")", "\n\n", "return", "parseIPVSStats", "(", "file", ")", "\n", "}" ]
// NewIPVSStats reads the IPVS statistics from the specified `proc` filesystem.
[ "NewIPVSStats", "reads", "the", "IPVS", "statistics", "from", "the", "specified", "proc", "filesystem", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/ipvs.go#L76-L84
151,556
prometheus/procfs
ipvs.go
parseIPVSStats
func parseIPVSStats(file io.Reader) (IPVSStats, error) { var ( statContent []byte statLines []string statFields []string stats IPVSStats ) statContent, err := ioutil.ReadAll(file) if err != nil { return IPVSStats{}, err } statLines = strings.SplitN(string(statContent), "\n", 4) if len(statLines) != 4 { return IPVSStats{}, errors.New("ip_vs_stats corrupt: too short") } statFields = strings.Fields(statLines[2]) if len(statFields) != 5 { return IPVSStats{}, errors.New("ip_vs_stats corrupt: unexpected number of fields") } stats.Connections, err = strconv.ParseUint(statFields[0], 16, 64) if err != nil { return IPVSStats{}, err } stats.IncomingPackets, err = strconv.ParseUint(statFields[1], 16, 64) if err != nil { return IPVSStats{}, err } stats.OutgoingPackets, err = strconv.ParseUint(statFields[2], 16, 64) if err != nil { return IPVSStats{}, err } stats.IncomingBytes, err = strconv.ParseUint(statFields[3], 16, 64) if err != nil { return IPVSStats{}, err } stats.OutgoingBytes, err = strconv.ParseUint(statFields[4], 16, 64) if err != nil { return IPVSStats{}, err } return stats, nil }
go
func parseIPVSStats(file io.Reader) (IPVSStats, error) { var ( statContent []byte statLines []string statFields []string stats IPVSStats ) statContent, err := ioutil.ReadAll(file) if err != nil { return IPVSStats{}, err } statLines = strings.SplitN(string(statContent), "\n", 4) if len(statLines) != 4 { return IPVSStats{}, errors.New("ip_vs_stats corrupt: too short") } statFields = strings.Fields(statLines[2]) if len(statFields) != 5 { return IPVSStats{}, errors.New("ip_vs_stats corrupt: unexpected number of fields") } stats.Connections, err = strconv.ParseUint(statFields[0], 16, 64) if err != nil { return IPVSStats{}, err } stats.IncomingPackets, err = strconv.ParseUint(statFields[1], 16, 64) if err != nil { return IPVSStats{}, err } stats.OutgoingPackets, err = strconv.ParseUint(statFields[2], 16, 64) if err != nil { return IPVSStats{}, err } stats.IncomingBytes, err = strconv.ParseUint(statFields[3], 16, 64) if err != nil { return IPVSStats{}, err } stats.OutgoingBytes, err = strconv.ParseUint(statFields[4], 16, 64) if err != nil { return IPVSStats{}, err } return stats, nil }
[ "func", "parseIPVSStats", "(", "file", "io", ".", "Reader", ")", "(", "IPVSStats", ",", "error", ")", "{", "var", "(", "statContent", "[", "]", "byte", "\n", "statLines", "[", "]", "string", "\n", "statFields", "[", "]", "string", "\n", "stats", "IPVSStats", "\n", ")", "\n\n", "statContent", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "file", ")", "\n", "if", "err", "!=", "nil", "{", "return", "IPVSStats", "{", "}", ",", "err", "\n", "}", "\n\n", "statLines", "=", "strings", ".", "SplitN", "(", "string", "(", "statContent", ")", ",", "\"", "\\n", "\"", ",", "4", ")", "\n", "if", "len", "(", "statLines", ")", "!=", "4", "{", "return", "IPVSStats", "{", "}", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "statFields", "=", "strings", ".", "Fields", "(", "statLines", "[", "2", "]", ")", "\n", "if", "len", "(", "statFields", ")", "!=", "5", "{", "return", "IPVSStats", "{", "}", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "stats", ".", "Connections", ",", "err", "=", "strconv", ".", "ParseUint", "(", "statFields", "[", "0", "]", ",", "16", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "IPVSStats", "{", "}", ",", "err", "\n", "}", "\n", "stats", ".", "IncomingPackets", ",", "err", "=", "strconv", ".", "ParseUint", "(", "statFields", "[", "1", "]", ",", "16", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "IPVSStats", "{", "}", ",", "err", "\n", "}", "\n", "stats", ".", "OutgoingPackets", ",", "err", "=", "strconv", ".", "ParseUint", "(", "statFields", "[", "2", "]", ",", "16", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "IPVSStats", "{", "}", ",", "err", "\n", "}", "\n", "stats", ".", "IncomingBytes", ",", "err", "=", "strconv", ".", "ParseUint", "(", "statFields", "[", "3", "]", ",", "16", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "IPVSStats", "{", "}", ",", "err", "\n", "}", "\n", "stats", ".", "OutgoingBytes", ",", "err", "=", "strconv", ".", "ParseUint", "(", "statFields", "[", "4", "]", ",", "16", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "IPVSStats", "{", "}", ",", "err", "\n", "}", "\n\n", "return", "stats", ",", "nil", "\n", "}" ]
// parseIPVSStats performs the actual parsing of `ip_vs_stats`.
[ "parseIPVSStats", "performs", "the", "actual", "parsing", "of", "ip_vs_stats", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/ipvs.go#L87-L132
151,557
prometheus/procfs
net_dev.go
newNetDev
func newNetDev(file string) (NetDev, error) { f, err := os.Open(file) if err != nil { return NetDev{}, err } defer f.Close() nd := NetDev{} s := bufio.NewScanner(f) for n := 0; s.Scan(); n++ { // Skip the 2 header lines. if n < 2 { continue } line, err := nd.parseLine(s.Text()) if err != nil { return nd, err } nd[line.Name] = *line } return nd, s.Err() }
go
func newNetDev(file string) (NetDev, error) { f, err := os.Open(file) if err != nil { return NetDev{}, err } defer f.Close() nd := NetDev{} s := bufio.NewScanner(f) for n := 0; s.Scan(); n++ { // Skip the 2 header lines. if n < 2 { continue } line, err := nd.parseLine(s.Text()) if err != nil { return nd, err } nd[line.Name] = *line } return nd, s.Err() }
[ "func", "newNetDev", "(", "file", "string", ")", "(", "NetDev", ",", "error", ")", "{", "f", ",", "err", ":=", "os", ".", "Open", "(", "file", ")", "\n", "if", "err", "!=", "nil", "{", "return", "NetDev", "{", "}", ",", "err", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n\n", "nd", ":=", "NetDev", "{", "}", "\n", "s", ":=", "bufio", ".", "NewScanner", "(", "f", ")", "\n", "for", "n", ":=", "0", ";", "s", ".", "Scan", "(", ")", ";", "n", "++", "{", "// Skip the 2 header lines.", "if", "n", "<", "2", "{", "continue", "\n", "}", "\n\n", "line", ",", "err", ":=", "nd", ".", "parseLine", "(", "s", ".", "Text", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nd", ",", "err", "\n", "}", "\n\n", "nd", "[", "line", ".", "Name", "]", "=", "*", "line", "\n", "}", "\n\n", "return", "nd", ",", "s", ".", "Err", "(", ")", "\n", "}" ]
// newNetDev creates a new NetDev from the contents of the given file.
[ "newNetDev", "creates", "a", "new", "NetDev", "from", "the", "contents", "of", "the", "given", "file", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/net_dev.go#L71-L95
151,558
prometheus/procfs
net_dev.go
Total
func (nd NetDev) Total() NetDevLine { total := NetDevLine{} names := make([]string, 0, len(nd)) for _, ifc := range nd { names = append(names, ifc.Name) total.RxBytes += ifc.RxBytes total.RxPackets += ifc.RxPackets total.RxPackets += ifc.RxPackets total.RxErrors += ifc.RxErrors total.RxDropped += ifc.RxDropped total.RxFIFO += ifc.RxFIFO total.RxFrame += ifc.RxFrame total.RxCompressed += ifc.RxCompressed total.RxMulticast += ifc.RxMulticast total.TxBytes += ifc.TxBytes total.TxPackets += ifc.TxPackets total.TxErrors += ifc.TxErrors total.TxDropped += ifc.TxDropped total.TxFIFO += ifc.TxFIFO total.TxCollisions += ifc.TxCollisions total.TxCarrier += ifc.TxCarrier total.TxCompressed += ifc.TxCompressed } sort.Strings(names) total.Name = strings.Join(names, ", ") return total }
go
func (nd NetDev) Total() NetDevLine { total := NetDevLine{} names := make([]string, 0, len(nd)) for _, ifc := range nd { names = append(names, ifc.Name) total.RxBytes += ifc.RxBytes total.RxPackets += ifc.RxPackets total.RxPackets += ifc.RxPackets total.RxErrors += ifc.RxErrors total.RxDropped += ifc.RxDropped total.RxFIFO += ifc.RxFIFO total.RxFrame += ifc.RxFrame total.RxCompressed += ifc.RxCompressed total.RxMulticast += ifc.RxMulticast total.TxBytes += ifc.TxBytes total.TxPackets += ifc.TxPackets total.TxErrors += ifc.TxErrors total.TxDropped += ifc.TxDropped total.TxFIFO += ifc.TxFIFO total.TxCollisions += ifc.TxCollisions total.TxCarrier += ifc.TxCarrier total.TxCompressed += ifc.TxCompressed } sort.Strings(names) total.Name = strings.Join(names, ", ") return total }
[ "func", "(", "nd", "NetDev", ")", "Total", "(", ")", "NetDevLine", "{", "total", ":=", "NetDevLine", "{", "}", "\n\n", "names", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "nd", ")", ")", "\n", "for", "_", ",", "ifc", ":=", "range", "nd", "{", "names", "=", "append", "(", "names", ",", "ifc", ".", "Name", ")", "\n", "total", ".", "RxBytes", "+=", "ifc", ".", "RxBytes", "\n", "total", ".", "RxPackets", "+=", "ifc", ".", "RxPackets", "\n", "total", ".", "RxPackets", "+=", "ifc", ".", "RxPackets", "\n", "total", ".", "RxErrors", "+=", "ifc", ".", "RxErrors", "\n", "total", ".", "RxDropped", "+=", "ifc", ".", "RxDropped", "\n", "total", ".", "RxFIFO", "+=", "ifc", ".", "RxFIFO", "\n", "total", ".", "RxFrame", "+=", "ifc", ".", "RxFrame", "\n", "total", ".", "RxCompressed", "+=", "ifc", ".", "RxCompressed", "\n", "total", ".", "RxMulticast", "+=", "ifc", ".", "RxMulticast", "\n", "total", ".", "TxBytes", "+=", "ifc", ".", "TxBytes", "\n", "total", ".", "TxPackets", "+=", "ifc", ".", "TxPackets", "\n", "total", ".", "TxErrors", "+=", "ifc", ".", "TxErrors", "\n", "total", ".", "TxDropped", "+=", "ifc", ".", "TxDropped", "\n", "total", ".", "TxFIFO", "+=", "ifc", ".", "TxFIFO", "\n", "total", ".", "TxCollisions", "+=", "ifc", ".", "TxCollisions", "\n", "total", ".", "TxCarrier", "+=", "ifc", ".", "TxCarrier", "\n", "total", ".", "TxCompressed", "+=", "ifc", ".", "TxCompressed", "\n", "}", "\n", "sort", ".", "Strings", "(", "names", ")", "\n", "total", ".", "Name", "=", "strings", ".", "Join", "(", "names", ",", "\"", "\"", ")", "\n\n", "return", "total", "\n", "}" ]
// Total aggregates the values across interfaces and returns a new NetDevLine. // The Name field will be a sorted comma separated list of interface names.
[ "Total", "aggregates", "the", "values", "across", "interfaces", "and", "returns", "a", "new", "NetDevLine", ".", "The", "Name", "field", "will", "be", "a", "sorted", "comma", "separated", "list", "of", "interface", "names", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/net_dev.go#L188-L216
151,559
prometheus/procfs
proc_psi.go
NewPSIStatsForResource
func NewPSIStatsForResource(resource string) (PSIStats, error) { fs, err := NewFS(DefaultMountPoint) if err != nil { return PSIStats{}, err } return fs.NewPSIStatsForResource(resource) }
go
func NewPSIStatsForResource(resource string) (PSIStats, error) { fs, err := NewFS(DefaultMountPoint) if err != nil { return PSIStats{}, err } return fs.NewPSIStatsForResource(resource) }
[ "func", "NewPSIStatsForResource", "(", "resource", "string", ")", "(", "PSIStats", ",", "error", ")", "{", "fs", ",", "err", ":=", "NewFS", "(", "DefaultMountPoint", ")", "\n", "if", "err", "!=", "nil", "{", "return", "PSIStats", "{", "}", ",", "err", "\n", "}", "\n\n", "return", "fs", ".", "NewPSIStatsForResource", "(", "resource", ")", "\n", "}" ]
// NewPSIStatsForResource reads pressure stall information for the specified // resource. At time of writing this can be either "cpu", "memory" or "io".
[ "NewPSIStatsForResource", "reads", "pressure", "stall", "information", "for", "the", "specified", "resource", ".", "At", "time", "of", "writing", "this", "can", "be", "either", "cpu", "memory", "or", "io", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/proc_psi.go#L56-L63
151,560
prometheus/procfs
proc_psi.go
parsePSIStats
func parsePSIStats(resource string, file io.Reader) (PSIStats, error) { psiStats := PSIStats{} stats, err := ioutil.ReadAll(file) if err != nil { return psiStats, fmt.Errorf("psi_stats: unable to read data for %s", resource) } for _, l := range strings.Split(string(stats), "\n") { prefix := strings.Split(l, " ")[0] switch prefix { case "some": psi := PSILine{} _, err := fmt.Sscanf(l, fmt.Sprintf("some %s", lineFormat), &psi.Avg10, &psi.Avg60, &psi.Avg300, &psi.Total) if err != nil { return PSIStats{}, err } psiStats.Some = &psi case "full": psi := PSILine{} _, err := fmt.Sscanf(l, fmt.Sprintf("full %s", lineFormat), &psi.Avg10, &psi.Avg60, &psi.Avg300, &psi.Total) if err != nil { return PSIStats{}, err } psiStats.Full = &psi default: // If we encounter a line with an unknown prefix, ignore it and move on // Should new measurement types be added in the future we'll simply ignore them instead // of erroring on retrieval continue } } return psiStats, nil }
go
func parsePSIStats(resource string, file io.Reader) (PSIStats, error) { psiStats := PSIStats{} stats, err := ioutil.ReadAll(file) if err != nil { return psiStats, fmt.Errorf("psi_stats: unable to read data for %s", resource) } for _, l := range strings.Split(string(stats), "\n") { prefix := strings.Split(l, " ")[0] switch prefix { case "some": psi := PSILine{} _, err := fmt.Sscanf(l, fmt.Sprintf("some %s", lineFormat), &psi.Avg10, &psi.Avg60, &psi.Avg300, &psi.Total) if err != nil { return PSIStats{}, err } psiStats.Some = &psi case "full": psi := PSILine{} _, err := fmt.Sscanf(l, fmt.Sprintf("full %s", lineFormat), &psi.Avg10, &psi.Avg60, &psi.Avg300, &psi.Total) if err != nil { return PSIStats{}, err } psiStats.Full = &psi default: // If we encounter a line with an unknown prefix, ignore it and move on // Should new measurement types be added in the future we'll simply ignore them instead // of erroring on retrieval continue } } return psiStats, nil }
[ "func", "parsePSIStats", "(", "resource", "string", ",", "file", "io", ".", "Reader", ")", "(", "PSIStats", ",", "error", ")", "{", "psiStats", ":=", "PSIStats", "{", "}", "\n", "stats", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "file", ")", "\n", "if", "err", "!=", "nil", "{", "return", "psiStats", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "resource", ")", "\n", "}", "\n\n", "for", "_", ",", "l", ":=", "range", "strings", ".", "Split", "(", "string", "(", "stats", ")", ",", "\"", "\\n", "\"", ")", "{", "prefix", ":=", "strings", ".", "Split", "(", "l", ",", "\"", "\"", ")", "[", "0", "]", "\n", "switch", "prefix", "{", "case", "\"", "\"", ":", "psi", ":=", "PSILine", "{", "}", "\n", "_", ",", "err", ":=", "fmt", ".", "Sscanf", "(", "l", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "lineFormat", ")", ",", "&", "psi", ".", "Avg10", ",", "&", "psi", ".", "Avg60", ",", "&", "psi", ".", "Avg300", ",", "&", "psi", ".", "Total", ")", "\n", "if", "err", "!=", "nil", "{", "return", "PSIStats", "{", "}", ",", "err", "\n", "}", "\n", "psiStats", ".", "Some", "=", "&", "psi", "\n", "case", "\"", "\"", ":", "psi", ":=", "PSILine", "{", "}", "\n", "_", ",", "err", ":=", "fmt", ".", "Sscanf", "(", "l", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "lineFormat", ")", ",", "&", "psi", ".", "Avg10", ",", "&", "psi", ".", "Avg60", ",", "&", "psi", ".", "Avg300", ",", "&", "psi", ".", "Total", ")", "\n", "if", "err", "!=", "nil", "{", "return", "PSIStats", "{", "}", ",", "err", "\n", "}", "\n", "psiStats", ".", "Full", "=", "&", "psi", "\n", "default", ":", "// If we encounter a line with an unknown prefix, ignore it and move on", "// Should new measurement types be added in the future we'll simply ignore them instead", "// of erroring on retrieval", "continue", "\n", "}", "\n", "}", "\n\n", "return", "psiStats", ",", "nil", "\n", "}" ]
// parsePSIStats parses the specified file for pressure stall information
[ "parsePSIStats", "parses", "the", "specified", "file", "for", "pressure", "stall", "information" ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/proc_psi.go#L77-L110
151,561
prometheus/procfs
buddyinfo.go
NewBuddyInfo
func NewBuddyInfo() ([]BuddyInfo, error) { fs, err := NewFS(DefaultMountPoint) if err != nil { return nil, err } return fs.NewBuddyInfo() }
go
func NewBuddyInfo() ([]BuddyInfo, error) { fs, err := NewFS(DefaultMountPoint) if err != nil { return nil, err } return fs.NewBuddyInfo() }
[ "func", "NewBuddyInfo", "(", ")", "(", "[", "]", "BuddyInfo", ",", "error", ")", "{", "fs", ",", "err", ":=", "NewFS", "(", "DefaultMountPoint", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "fs", ".", "NewBuddyInfo", "(", ")", "\n", "}" ]
// NewBuddyInfo reads the buddyinfo statistics.
[ "NewBuddyInfo", "reads", "the", "buddyinfo", "statistics", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/buddyinfo.go#L35-L42
151,562
prometheus/procfs
buddyinfo.go
NewBuddyInfo
func (fs FS) NewBuddyInfo() ([]BuddyInfo, error) { file, err := os.Open(fs.Path("buddyinfo")) if err != nil { return nil, err } defer file.Close() return parseBuddyInfo(file) }
go
func (fs FS) NewBuddyInfo() ([]BuddyInfo, error) { file, err := os.Open(fs.Path("buddyinfo")) if err != nil { return nil, err } defer file.Close() return parseBuddyInfo(file) }
[ "func", "(", "fs", "FS", ")", "NewBuddyInfo", "(", ")", "(", "[", "]", "BuddyInfo", ",", "error", ")", "{", "file", ",", "err", ":=", "os", ".", "Open", "(", "fs", ".", "Path", "(", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "file", ".", "Close", "(", ")", "\n\n", "return", "parseBuddyInfo", "(", "file", ")", "\n", "}" ]
// NewBuddyInfo reads the buddyinfo statistics from the specified `proc` filesystem.
[ "NewBuddyInfo", "reads", "the", "buddyinfo", "statistics", "from", "the", "specified", "proc", "filesystem", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/buddyinfo.go#L45-L53
151,563
prometheus/procfs
proc_stat.go
NewStat
func (p Proc) NewStat() (ProcStat, error) { f, err := os.Open(p.path("stat")) if err != nil { return ProcStat{}, err } defer f.Close() data, err := ioutil.ReadAll(f) if err != nil { return ProcStat{}, err } var ( ignore int s = ProcStat{PID: p.PID, fs: p.fs} l = bytes.Index(data, []byte("(")) r = bytes.LastIndex(data, []byte(")")) ) if l < 0 || r < 0 { return ProcStat{}, fmt.Errorf( "unexpected format, couldn't extract comm: %s", data, ) } s.Comm = string(data[l+1 : r]) _, err = fmt.Fscan( bytes.NewBuffer(data[r+2:]), &s.State, &s.PPID, &s.PGRP, &s.Session, &s.TTY, &s.TPGID, &s.Flags, &s.MinFlt, &s.CMinFlt, &s.MajFlt, &s.CMajFlt, &s.UTime, &s.STime, &s.CUTime, &s.CSTime, &s.Priority, &s.Nice, &s.NumThreads, &ignore, &s.Starttime, &s.VSize, &s.RSS, ) if err != nil { return ProcStat{}, err } return s, nil }
go
func (p Proc) NewStat() (ProcStat, error) { f, err := os.Open(p.path("stat")) if err != nil { return ProcStat{}, err } defer f.Close() data, err := ioutil.ReadAll(f) if err != nil { return ProcStat{}, err } var ( ignore int s = ProcStat{PID: p.PID, fs: p.fs} l = bytes.Index(data, []byte("(")) r = bytes.LastIndex(data, []byte(")")) ) if l < 0 || r < 0 { return ProcStat{}, fmt.Errorf( "unexpected format, couldn't extract comm: %s", data, ) } s.Comm = string(data[l+1 : r]) _, err = fmt.Fscan( bytes.NewBuffer(data[r+2:]), &s.State, &s.PPID, &s.PGRP, &s.Session, &s.TTY, &s.TPGID, &s.Flags, &s.MinFlt, &s.CMinFlt, &s.MajFlt, &s.CMajFlt, &s.UTime, &s.STime, &s.CUTime, &s.CSTime, &s.Priority, &s.Nice, &s.NumThreads, &ignore, &s.Starttime, &s.VSize, &s.RSS, ) if err != nil { return ProcStat{}, err } return s, nil }
[ "func", "(", "p", "Proc", ")", "NewStat", "(", ")", "(", "ProcStat", ",", "error", ")", "{", "f", ",", "err", ":=", "os", ".", "Open", "(", "p", ".", "path", "(", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "ProcStat", "{", "}", ",", "err", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n\n", "data", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "f", ")", "\n", "if", "err", "!=", "nil", "{", "return", "ProcStat", "{", "}", ",", "err", "\n", "}", "\n\n", "var", "(", "ignore", "int", "\n\n", "s", "=", "ProcStat", "{", "PID", ":", "p", ".", "PID", ",", "fs", ":", "p", ".", "fs", "}", "\n", "l", "=", "bytes", ".", "Index", "(", "data", ",", "[", "]", "byte", "(", "\"", "\"", ")", ")", "\n", "r", "=", "bytes", ".", "LastIndex", "(", "data", ",", "[", "]", "byte", "(", "\"", "\"", ")", ")", "\n", ")", "\n\n", "if", "l", "<", "0", "||", "r", "<", "0", "{", "return", "ProcStat", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "data", ",", ")", "\n", "}", "\n\n", "s", ".", "Comm", "=", "string", "(", "data", "[", "l", "+", "1", ":", "r", "]", ")", "\n", "_", ",", "err", "=", "fmt", ".", "Fscan", "(", "bytes", ".", "NewBuffer", "(", "data", "[", "r", "+", "2", ":", "]", ")", ",", "&", "s", ".", "State", ",", "&", "s", ".", "PPID", ",", "&", "s", ".", "PGRP", ",", "&", "s", ".", "Session", ",", "&", "s", ".", "TTY", ",", "&", "s", ".", "TPGID", ",", "&", "s", ".", "Flags", ",", "&", "s", ".", "MinFlt", ",", "&", "s", ".", "CMinFlt", ",", "&", "s", ".", "MajFlt", ",", "&", "s", ".", "CMajFlt", ",", "&", "s", ".", "UTime", ",", "&", "s", ".", "STime", ",", "&", "s", ".", "CUTime", ",", "&", "s", ".", "CSTime", ",", "&", "s", ".", "Priority", ",", "&", "s", ".", "Nice", ",", "&", "s", ".", "NumThreads", ",", "&", "ignore", ",", "&", "s", ".", "Starttime", ",", "&", "s", ".", "VSize", ",", "&", "s", ".", "RSS", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "ProcStat", "{", "}", ",", "err", "\n", "}", "\n\n", "return", "s", ",", "nil", "\n", "}" ]
// NewStat returns the current status information of the process.
[ "NewStat", "returns", "the", "current", "status", "information", "of", "the", "process", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/proc_stat.go#L106-L164
151,564
prometheus/procfs
proc_stat.go
StartTime
func (s ProcStat) StartTime() (float64, error) { stat, err := s.fs.NewStat() if err != nil { return 0, err } return float64(stat.BootTime) + (float64(s.Starttime) / userHZ), nil }
go
func (s ProcStat) StartTime() (float64, error) { stat, err := s.fs.NewStat() if err != nil { return 0, err } return float64(stat.BootTime) + (float64(s.Starttime) / userHZ), nil }
[ "func", "(", "s", "ProcStat", ")", "StartTime", "(", ")", "(", "float64", ",", "error", ")", "{", "stat", ",", "err", ":=", "s", ".", "fs", ".", "NewStat", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "return", "float64", "(", "stat", ".", "BootTime", ")", "+", "(", "float64", "(", "s", ".", "Starttime", ")", "/", "userHZ", ")", ",", "nil", "\n", "}" ]
// StartTime returns the unix timestamp of the process in seconds.
[ "StartTime", "returns", "the", "unix", "timestamp", "of", "the", "process", "in", "seconds", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/proc_stat.go#L177-L183
151,565
prometheus/procfs
proc_stat.go
CPUTime
func (s ProcStat) CPUTime() float64 { return float64(s.UTime+s.STime) / userHZ }
go
func (s ProcStat) CPUTime() float64 { return float64(s.UTime+s.STime) / userHZ }
[ "func", "(", "s", "ProcStat", ")", "CPUTime", "(", ")", "float64", "{", "return", "float64", "(", "s", ".", "UTime", "+", "s", ".", "STime", ")", "/", "userHZ", "\n", "}" ]
// CPUTime returns the total CPU user and system time in seconds.
[ "CPUTime", "returns", "the", "total", "CPU", "user", "and", "system", "time", "in", "seconds", "." ]
87a4384529e0652f5035fb5cc8095faf73ea9b0b
https://github.com/prometheus/procfs/blob/87a4384529e0652f5035fb5cc8095faf73ea9b0b/proc_stat.go#L186-L188
151,566
nats-io/go-nats-streaming
stan.go
ConnectWait
func ConnectWait(t time.Duration) Option { return func(o *Options) error { o.ConnectTimeout = t return nil } }
go
func ConnectWait(t time.Duration) Option { return func(o *Options) error { o.ConnectTimeout = t return nil } }
[ "func", "ConnectWait", "(", "t", "time", ".", "Duration", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "error", "{", "o", ".", "ConnectTimeout", "=", "t", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// ConnectWait is an Option to set the timeout for establishing a connection.
[ "ConnectWait", "is", "an", "Option", "to", "set", "the", "timeout", "for", "establishing", "a", "connection", "." ]
3e2ff0719c7a6219b4e791e19c782de98c701f4a
https://github.com/nats-io/go-nats-streaming/blob/3e2ff0719c7a6219b4e791e19c782de98c701f4a/stan.go#L198-L203
151,567
nats-io/go-nats-streaming
stan.go
PubAckWait
func PubAckWait(t time.Duration) Option { return func(o *Options) error { o.AckTimeout = t return nil } }
go
func PubAckWait(t time.Duration) Option { return func(o *Options) error { o.AckTimeout = t return nil } }
[ "func", "PubAckWait", "(", "t", "time", ".", "Duration", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "error", "{", "o", ".", "AckTimeout", "=", "t", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// PubAckWait is an Option to set the timeout for waiting for an ACK for a // published message.
[ "PubAckWait", "is", "an", "Option", "to", "set", "the", "timeout", "for", "waiting", "for", "an", "ACK", "for", "a", "published", "message", "." ]
3e2ff0719c7a6219b4e791e19c782de98c701f4a
https://github.com/nats-io/go-nats-streaming/blob/3e2ff0719c7a6219b4e791e19c782de98c701f4a/stan.go#L207-L212
151,568
nats-io/go-nats-streaming
stan.go
MaxPubAcksInflight
func MaxPubAcksInflight(max int) Option { return func(o *Options) error { o.MaxPubAcksInflight = max return nil } }
go
func MaxPubAcksInflight(max int) Option { return func(o *Options) error { o.MaxPubAcksInflight = max return nil } }
[ "func", "MaxPubAcksInflight", "(", "max", "int", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "error", "{", "o", ".", "MaxPubAcksInflight", "=", "max", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// MaxPubAcksInflight is an Option to set the maximum number of published // messages without outstanding ACKs from the server.
[ "MaxPubAcksInflight", "is", "an", "Option", "to", "set", "the", "maximum", "number", "of", "published", "messages", "without", "outstanding", "ACKs", "from", "the", "server", "." ]
3e2ff0719c7a6219b4e791e19c782de98c701f4a
https://github.com/nats-io/go-nats-streaming/blob/3e2ff0719c7a6219b4e791e19c782de98c701f4a/stan.go#L216-L221
151,569
nats-io/go-nats-streaming
stan.go
NatsConn
func NatsConn(nc *nats.Conn) Option { return func(o *Options) error { o.NatsConn = nc return nil } }
go
func NatsConn(nc *nats.Conn) Option { return func(o *Options) error { o.NatsConn = nc return nil } }
[ "func", "NatsConn", "(", "nc", "*", "nats", ".", "Conn", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "error", "{", "o", ".", "NatsConn", "=", "nc", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// NatsConn is an Option to set the underlying NATS connection to be used // by a streaming connection object. When such option is set, closing the // streaming connection does not close the provided NATS connection.
[ "NatsConn", "is", "an", "Option", "to", "set", "the", "underlying", "NATS", "connection", "to", "be", "used", "by", "a", "streaming", "connection", "object", ".", "When", "such", "option", "is", "set", "closing", "the", "streaming", "connection", "does", "not", "close", "the", "provided", "NATS", "connection", "." ]
3e2ff0719c7a6219b4e791e19c782de98c701f4a
https://github.com/nats-io/go-nats-streaming/blob/3e2ff0719c7a6219b4e791e19c782de98c701f4a/stan.go#L226-L231
151,570
nats-io/go-nats-streaming
stan.go
Pings
func Pings(interval, maxOut int) Option { return func(o *Options) error { // For tests, we may pass negative value that will be interpreted // by the library as milliseconds. If this test boolean is set, // do not check values. if !testAllowMillisecInPings { if interval < 1 || maxOut <= 2 { return fmt.Errorf("invalid ping values: interval=%v (min>0) maxOut=%v (min=2)", interval, maxOut) } } o.PingIterval = interval o.PingMaxOut = maxOut return nil } }
go
func Pings(interval, maxOut int) Option { return func(o *Options) error { // For tests, we may pass negative value that will be interpreted // by the library as milliseconds. If this test boolean is set, // do not check values. if !testAllowMillisecInPings { if interval < 1 || maxOut <= 2 { return fmt.Errorf("invalid ping values: interval=%v (min>0) maxOut=%v (min=2)", interval, maxOut) } } o.PingIterval = interval o.PingMaxOut = maxOut return nil } }
[ "func", "Pings", "(", "interval", ",", "maxOut", "int", ")", "Option", "{", "return", "func", "(", "o", "*", "Options", ")", "error", "{", "// For tests, we may pass negative value that will be interpreted", "// by the library as milliseconds. If this test boolean is set,", "// do not check values.", "if", "!", "testAllowMillisecInPings", "{", "if", "interval", "<", "1", "||", "maxOut", "<=", "2", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "interval", ",", "maxOut", ")", "\n", "}", "\n", "}", "\n", "o", ".", "PingIterval", "=", "interval", "\n", "o", ".", "PingMaxOut", "=", "maxOut", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// Pings is an Option to set the ping interval and max out values. // The interval needs to be at least 1 and represents the number // of seconds. // The maxOut needs to be at least 2, since the count of sent PINGs // increase whenever a PING is sent and reset to 0 when a response // is received. Setting to 1 would cause the library to close the // connection right away.
[ "Pings", "is", "an", "Option", "to", "set", "the", "ping", "interval", "and", "max", "out", "values", ".", "The", "interval", "needs", "to", "be", "at", "least", "1", "and", "represents", "the", "number", "of", "seconds", ".", "The", "maxOut", "needs", "to", "be", "at", "least", "2", "since", "the", "count", "of", "sent", "PINGs", "increase", "whenever", "a", "PING", "is", "sent", "and", "reset", "to", "0", "when", "a", "response", "is", "received", ".", "Setting", "to", "1", "would", "cause", "the", "library", "to", "close", "the", "connection", "right", "away", "." ]
3e2ff0719c7a6219b4e791e19c782de98c701f4a
https://github.com/nats-io/go-nats-streaming/blob/3e2ff0719c7a6219b4e791e19c782de98c701f4a/stan.go#L240-L254
151,571
nats-io/go-nats-streaming
stan.go
failConnect
func (sc *conn) failConnect(err error) { sc.cleanupOnClose(err) if sc.nc != nil && sc.ncOwned { sc.nc.Close() } }
go
func (sc *conn) failConnect(err error) { sc.cleanupOnClose(err) if sc.nc != nil && sc.ncOwned { sc.nc.Close() } }
[ "func", "(", "sc", "*", "conn", ")", "failConnect", "(", "err", "error", ")", "{", "sc", ".", "cleanupOnClose", "(", "err", ")", "\n", "if", "sc", ".", "nc", "!=", "nil", "&&", "sc", ".", "ncOwned", "{", "sc", ".", "nc", ".", "Close", "(", ")", "\n", "}", "\n", "}" ]
// Invoked on a failed connect. // Perform appropriate cleanup operations but do not attempt to send // a close request.
[ "Invoked", "on", "a", "failed", "connect", ".", "Perform", "appropriate", "cleanup", "operations", "but", "do", "not", "attempt", "to", "send", "a", "close", "request", "." ]
3e2ff0719c7a6219b4e791e19c782de98c701f4a
https://github.com/nats-io/go-nats-streaming/blob/3e2ff0719c7a6219b4e791e19c782de98c701f4a/stan.go#L460-L465
151,572
nats-io/go-nats-streaming
stan.go
closeDueToPing
func (sc *conn) closeDueToPing(err error) { sc.Lock() if sc.nc == nil { sc.Unlock() return } // Stop timer, unsubscribe, fail the pubs, etc.. sc.cleanupOnClose(err) // No need to send Close protocol, so simply close the underlying // NATS connection (if we own it, and if not already closed) if sc.ncOwned && !sc.nc.IsClosed() { sc.nc.Close() } // Mark this streaming connection as closed. Do this under pingMu lock. sc.pingMu.Lock() sc.nc = nil sc.pingMu.Unlock() // Capture callback (even though this is immutable). cb := sc.connLostCB sc.Unlock() if cb != nil { // Execute in separate go routine. go cb(sc, err) } }
go
func (sc *conn) closeDueToPing(err error) { sc.Lock() if sc.nc == nil { sc.Unlock() return } // Stop timer, unsubscribe, fail the pubs, etc.. sc.cleanupOnClose(err) // No need to send Close protocol, so simply close the underlying // NATS connection (if we own it, and if not already closed) if sc.ncOwned && !sc.nc.IsClosed() { sc.nc.Close() } // Mark this streaming connection as closed. Do this under pingMu lock. sc.pingMu.Lock() sc.nc = nil sc.pingMu.Unlock() // Capture callback (even though this is immutable). cb := sc.connLostCB sc.Unlock() if cb != nil { // Execute in separate go routine. go cb(sc, err) } }
[ "func", "(", "sc", "*", "conn", ")", "closeDueToPing", "(", "err", "error", ")", "{", "sc", ".", "Lock", "(", ")", "\n", "if", "sc", ".", "nc", "==", "nil", "{", "sc", ".", "Unlock", "(", ")", "\n", "return", "\n", "}", "\n", "// Stop timer, unsubscribe, fail the pubs, etc..", "sc", ".", "cleanupOnClose", "(", "err", ")", "\n", "// No need to send Close protocol, so simply close the underlying", "// NATS connection (if we own it, and if not already closed)", "if", "sc", ".", "ncOwned", "&&", "!", "sc", ".", "nc", ".", "IsClosed", "(", ")", "{", "sc", ".", "nc", ".", "Close", "(", ")", "\n", "}", "\n", "// Mark this streaming connection as closed. Do this under pingMu lock.", "sc", ".", "pingMu", ".", "Lock", "(", ")", "\n", "sc", ".", "nc", "=", "nil", "\n", "sc", ".", "pingMu", ".", "Unlock", "(", ")", "\n", "// Capture callback (even though this is immutable).", "cb", ":=", "sc", ".", "connLostCB", "\n", "sc", ".", "Unlock", "(", ")", "\n", "if", "cb", "!=", "nil", "{", "// Execute in separate go routine.", "go", "cb", "(", "sc", ",", "err", ")", "\n", "}", "\n", "}" ]
// Closes a connection and invoke the connection error callback if one // was registered when the connection was created.
[ "Closes", "a", "connection", "and", "invoke", "the", "connection", "error", "callback", "if", "one", "was", "registered", "when", "the", "connection", "was", "created", "." ]
3e2ff0719c7a6219b4e791e19c782de98c701f4a
https://github.com/nats-io/go-nats-streaming/blob/3e2ff0719c7a6219b4e791e19c782de98c701f4a/stan.go#L523-L547
151,573
nats-io/go-nats-streaming
stan.go
cleanupOnClose
func (sc *conn) cleanupOnClose(err error) { sc.pingMu.Lock() if sc.pingTimer != nil { sc.pingTimer.Stop() sc.pingTimer = nil } sc.pingMu.Unlock() // Unsubscribe only if the NATS connection is not already closed // and we don't own it (otherwise connection is going to be closed // so no need for explicit unsubscribe). if !sc.ncOwned && !sc.nc.IsClosed() { if sc.hbSubscription != nil { sc.hbSubscription.Unsubscribe() } if sc.pingSub != nil { sc.pingSub.Unsubscribe() } if sc.ackSubscription != nil { sc.ackSubscription.Unsubscribe() } } // Fail all pending pubs for guid, pubAck := range sc.pubAckMap { if pubAck.t != nil { pubAck.t.Stop() } if pubAck.ah != nil { pubAck.ah(guid, err) } else if pubAck.ch != nil { pubAck.ch <- err } delete(sc.pubAckMap, guid) if len(sc.pubAckChan) > 0 { <-sc.pubAckChan } } }
go
func (sc *conn) cleanupOnClose(err error) { sc.pingMu.Lock() if sc.pingTimer != nil { sc.pingTimer.Stop() sc.pingTimer = nil } sc.pingMu.Unlock() // Unsubscribe only if the NATS connection is not already closed // and we don't own it (otherwise connection is going to be closed // so no need for explicit unsubscribe). if !sc.ncOwned && !sc.nc.IsClosed() { if sc.hbSubscription != nil { sc.hbSubscription.Unsubscribe() } if sc.pingSub != nil { sc.pingSub.Unsubscribe() } if sc.ackSubscription != nil { sc.ackSubscription.Unsubscribe() } } // Fail all pending pubs for guid, pubAck := range sc.pubAckMap { if pubAck.t != nil { pubAck.t.Stop() } if pubAck.ah != nil { pubAck.ah(guid, err) } else if pubAck.ch != nil { pubAck.ch <- err } delete(sc.pubAckMap, guid) if len(sc.pubAckChan) > 0 { <-sc.pubAckChan } } }
[ "func", "(", "sc", "*", "conn", ")", "cleanupOnClose", "(", "err", "error", ")", "{", "sc", ".", "pingMu", ".", "Lock", "(", ")", "\n", "if", "sc", ".", "pingTimer", "!=", "nil", "{", "sc", ".", "pingTimer", ".", "Stop", "(", ")", "\n", "sc", ".", "pingTimer", "=", "nil", "\n", "}", "\n", "sc", ".", "pingMu", ".", "Unlock", "(", ")", "\n\n", "// Unsubscribe only if the NATS connection is not already closed", "// and we don't own it (otherwise connection is going to be closed", "// so no need for explicit unsubscribe).", "if", "!", "sc", ".", "ncOwned", "&&", "!", "sc", ".", "nc", ".", "IsClosed", "(", ")", "{", "if", "sc", ".", "hbSubscription", "!=", "nil", "{", "sc", ".", "hbSubscription", ".", "Unsubscribe", "(", ")", "\n", "}", "\n", "if", "sc", ".", "pingSub", "!=", "nil", "{", "sc", ".", "pingSub", ".", "Unsubscribe", "(", ")", "\n", "}", "\n", "if", "sc", ".", "ackSubscription", "!=", "nil", "{", "sc", ".", "ackSubscription", ".", "Unsubscribe", "(", ")", "\n", "}", "\n", "}", "\n", "// Fail all pending pubs", "for", "guid", ",", "pubAck", ":=", "range", "sc", ".", "pubAckMap", "{", "if", "pubAck", ".", "t", "!=", "nil", "{", "pubAck", ".", "t", ".", "Stop", "(", ")", "\n", "}", "\n", "if", "pubAck", ".", "ah", "!=", "nil", "{", "pubAck", ".", "ah", "(", "guid", ",", "err", ")", "\n", "}", "else", "if", "pubAck", ".", "ch", "!=", "nil", "{", "pubAck", ".", "ch", "<-", "err", "\n", "}", "\n", "delete", "(", "sc", ".", "pubAckMap", ",", "guid", ")", "\n", "if", "len", "(", "sc", ".", "pubAckChan", ")", ">", "0", "{", "<-", "sc", ".", "pubAckChan", "\n", "}", "\n", "}", "\n", "}" ]
// Do some cleanup when connection is lost or closed. // Connection lock is held on entry, and sc.nc is guaranteed not to be nil.
[ "Do", "some", "cleanup", "when", "connection", "is", "lost", "or", "closed", ".", "Connection", "lock", "is", "held", "on", "entry", "and", "sc", ".", "nc", "is", "guaranteed", "not", "to", "be", "nil", "." ]
3e2ff0719c7a6219b4e791e19c782de98c701f4a
https://github.com/nats-io/go-nats-streaming/blob/3e2ff0719c7a6219b4e791e19c782de98c701f4a/stan.go#L551-L588
151,574
nats-io/go-nats-streaming
stan.go
Close
func (sc *conn) Close() error { sc.Lock() defer sc.Unlock() if sc.nc == nil { // We are already closed. return nil } // Capture for NATS calls below. nc := sc.nc if sc.ncOwned { defer nc.Close() } // Now close ourselves. sc.cleanupOnClose(ErrConnectionClosed) // Signals we are closed. // Do this also under pingMu lock so that we don't need // to grab sc's lock in pingServer. sc.pingMu.Lock() sc.nc = nil sc.pingMu.Unlock() req := &pb.CloseRequest{ClientID: sc.clientID} b, _ := req.Marshal() reply, err := nc.Request(sc.closeRequests, b, sc.opts.ConnectTimeout) if err != nil { if err == nats.ErrTimeout { return ErrCloseReqTimeout } return err } cr := &pb.CloseResponse{} err = cr.Unmarshal(reply.Data) if err != nil { return err } if cr.Error != "" { return errors.New(cr.Error) } return nil }
go
func (sc *conn) Close() error { sc.Lock() defer sc.Unlock() if sc.nc == nil { // We are already closed. return nil } // Capture for NATS calls below. nc := sc.nc if sc.ncOwned { defer nc.Close() } // Now close ourselves. sc.cleanupOnClose(ErrConnectionClosed) // Signals we are closed. // Do this also under pingMu lock so that we don't need // to grab sc's lock in pingServer. sc.pingMu.Lock() sc.nc = nil sc.pingMu.Unlock() req := &pb.CloseRequest{ClientID: sc.clientID} b, _ := req.Marshal() reply, err := nc.Request(sc.closeRequests, b, sc.opts.ConnectTimeout) if err != nil { if err == nats.ErrTimeout { return ErrCloseReqTimeout } return err } cr := &pb.CloseResponse{} err = cr.Unmarshal(reply.Data) if err != nil { return err } if cr.Error != "" { return errors.New(cr.Error) } return nil }
[ "func", "(", "sc", "*", "conn", ")", "Close", "(", ")", "error", "{", "sc", ".", "Lock", "(", ")", "\n", "defer", "sc", ".", "Unlock", "(", ")", "\n\n", "if", "sc", ".", "nc", "==", "nil", "{", "// We are already closed.", "return", "nil", "\n", "}", "\n\n", "// Capture for NATS calls below.", "nc", ":=", "sc", ".", "nc", "\n", "if", "sc", ".", "ncOwned", "{", "defer", "nc", ".", "Close", "(", ")", "\n", "}", "\n\n", "// Now close ourselves.", "sc", ".", "cleanupOnClose", "(", "ErrConnectionClosed", ")", "\n\n", "// Signals we are closed.", "// Do this also under pingMu lock so that we don't need", "// to grab sc's lock in pingServer.", "sc", ".", "pingMu", ".", "Lock", "(", ")", "\n", "sc", ".", "nc", "=", "nil", "\n", "sc", ".", "pingMu", ".", "Unlock", "(", ")", "\n\n", "req", ":=", "&", "pb", ".", "CloseRequest", "{", "ClientID", ":", "sc", ".", "clientID", "}", "\n", "b", ",", "_", ":=", "req", ".", "Marshal", "(", ")", "\n", "reply", ",", "err", ":=", "nc", ".", "Request", "(", "sc", ".", "closeRequests", ",", "b", ",", "sc", ".", "opts", ".", "ConnectTimeout", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "nats", ".", "ErrTimeout", "{", "return", "ErrCloseReqTimeout", "\n", "}", "\n", "return", "err", "\n", "}", "\n", "cr", ":=", "&", "pb", ".", "CloseResponse", "{", "}", "\n", "err", "=", "cr", ".", "Unmarshal", "(", "reply", ".", "Data", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "cr", ".", "Error", "!=", "\"", "\"", "{", "return", "errors", ".", "New", "(", "cr", ".", "Error", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Close a connection to the stan system.
[ "Close", "a", "connection", "to", "the", "stan", "system", "." ]
3e2ff0719c7a6219b4e791e19c782de98c701f4a
https://github.com/nats-io/go-nats-streaming/blob/3e2ff0719c7a6219b4e791e19c782de98c701f4a/stan.go#L591-L634
151,575
nats-io/go-nats-streaming
stan.go
NatsConn
func (sc *conn) NatsConn() *nats.Conn { sc.RLock() nc := sc.nc sc.RUnlock() return nc }
go
func (sc *conn) NatsConn() *nats.Conn { sc.RLock() nc := sc.nc sc.RUnlock() return nc }
[ "func", "(", "sc", "*", "conn", ")", "NatsConn", "(", ")", "*", "nats", ".", "Conn", "{", "sc", ".", "RLock", "(", ")", "\n", "nc", ":=", "sc", ".", "nc", "\n", "sc", ".", "RUnlock", "(", ")", "\n", "return", "nc", "\n", "}" ]
// NatsConn returns the underlying NATS conn. Use this with care. For example, // closing the wrapped NATS conn will put the NATS Streaming Conn in an invalid // state.
[ "NatsConn", "returns", "the", "underlying", "NATS", "conn", ".", "Use", "this", "with", "care", ".", "For", "example", "closing", "the", "wrapped", "NATS", "conn", "will", "put", "the", "NATS", "Streaming", "Conn", "in", "an", "invalid", "state", "." ]
3e2ff0719c7a6219b4e791e19c782de98c701f4a
https://github.com/nats-io/go-nats-streaming/blob/3e2ff0719c7a6219b4e791e19c782de98c701f4a/stan.go#L639-L644
151,576
nats-io/go-nats-streaming
stan.go
processHeartBeat
func (sc *conn) processHeartBeat(m *nats.Msg) { // No payload assumed, just reply. sc.RLock() nc := sc.nc sc.RUnlock() if nc != nil { nc.Publish(m.Reply, nil) } }
go
func (sc *conn) processHeartBeat(m *nats.Msg) { // No payload assumed, just reply. sc.RLock() nc := sc.nc sc.RUnlock() if nc != nil { nc.Publish(m.Reply, nil) } }
[ "func", "(", "sc", "*", "conn", ")", "processHeartBeat", "(", "m", "*", "nats", ".", "Msg", ")", "{", "// No payload assumed, just reply.", "sc", ".", "RLock", "(", ")", "\n", "nc", ":=", "sc", ".", "nc", "\n", "sc", ".", "RUnlock", "(", ")", "\n", "if", "nc", "!=", "nil", "{", "nc", ".", "Publish", "(", "m", ".", "Reply", ",", "nil", ")", "\n", "}", "\n", "}" ]
// Process a heartbeat from the NATS Streaming cluster
[ "Process", "a", "heartbeat", "from", "the", "NATS", "Streaming", "cluster" ]
3e2ff0719c7a6219b4e791e19c782de98c701f4a
https://github.com/nats-io/go-nats-streaming/blob/3e2ff0719c7a6219b4e791e19c782de98c701f4a/stan.go#L647-L655
151,577
nats-io/go-nats-streaming
stan.go
processAck
func (sc *conn) processAck(m *nats.Msg) { pa := &pb.PubAck{} err := pa.Unmarshal(m.Data) if err != nil { panic(fmt.Errorf("error during ack unmarshal: %v", err)) } // Remove a := sc.removeAck(pa.Guid) if a != nil { // Capture error if it exists. if pa.Error != "" { err = errors.New(pa.Error) } if a.ah != nil { // Perform the ackHandler callback a.ah(pa.Guid, err) } else if a.ch != nil { // Send to channel directly a.ch <- err } } }
go
func (sc *conn) processAck(m *nats.Msg) { pa := &pb.PubAck{} err := pa.Unmarshal(m.Data) if err != nil { panic(fmt.Errorf("error during ack unmarshal: %v", err)) } // Remove a := sc.removeAck(pa.Guid) if a != nil { // Capture error if it exists. if pa.Error != "" { err = errors.New(pa.Error) } if a.ah != nil { // Perform the ackHandler callback a.ah(pa.Guid, err) } else if a.ch != nil { // Send to channel directly a.ch <- err } } }
[ "func", "(", "sc", "*", "conn", ")", "processAck", "(", "m", "*", "nats", ".", "Msg", ")", "{", "pa", ":=", "&", "pb", ".", "PubAck", "{", "}", "\n", "err", ":=", "pa", ".", "Unmarshal", "(", "m", ".", "Data", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "}", "\n\n", "// Remove", "a", ":=", "sc", ".", "removeAck", "(", "pa", ".", "Guid", ")", "\n", "if", "a", "!=", "nil", "{", "// Capture error if it exists.", "if", "pa", ".", "Error", "!=", "\"", "\"", "{", "err", "=", "errors", ".", "New", "(", "pa", ".", "Error", ")", "\n", "}", "\n", "if", "a", ".", "ah", "!=", "nil", "{", "// Perform the ackHandler callback", "a", ".", "ah", "(", "pa", ".", "Guid", ",", "err", ")", "\n", "}", "else", "if", "a", ".", "ch", "!=", "nil", "{", "// Send to channel directly", "a", ".", "ch", "<-", "err", "\n", "}", "\n", "}", "\n", "}" ]
// Process an ack from the NATS Streaming cluster
[ "Process", "an", "ack", "from", "the", "NATS", "Streaming", "cluster" ]
3e2ff0719c7a6219b4e791e19c782de98c701f4a
https://github.com/nats-io/go-nats-streaming/blob/3e2ff0719c7a6219b4e791e19c782de98c701f4a/stan.go#L658-L680
151,578
nats-io/go-nats-streaming
stan.go
Publish
func (sc *conn) Publish(subject string, data []byte) error { // Need to make this a buffered channel of 1 in case // a publish call is blocked in pubAckChan but cleanupOnClose() // is trying to push the error to this channel. ch := make(chan error, 1) _, err := sc.publishAsync(subject, data, nil, ch) if err == nil { err = <-ch } return err }
go
func (sc *conn) Publish(subject string, data []byte) error { // Need to make this a buffered channel of 1 in case // a publish call is blocked in pubAckChan but cleanupOnClose() // is trying to push the error to this channel. ch := make(chan error, 1) _, err := sc.publishAsync(subject, data, nil, ch) if err == nil { err = <-ch } return err }
[ "func", "(", "sc", "*", "conn", ")", "Publish", "(", "subject", "string", ",", "data", "[", "]", "byte", ")", "error", "{", "// Need to make this a buffered channel of 1 in case", "// a publish call is blocked in pubAckChan but cleanupOnClose()", "// is trying to push the error to this channel.", "ch", ":=", "make", "(", "chan", "error", ",", "1", ")", "\n", "_", ",", "err", ":=", "sc", ".", "publishAsync", "(", "subject", ",", "data", ",", "nil", ",", "ch", ")", "\n", "if", "err", "==", "nil", "{", "err", "=", "<-", "ch", "\n", "}", "\n", "return", "err", "\n", "}" ]
// Publish will publish to the cluster and wait for an ACK.
[ "Publish", "will", "publish", "to", "the", "cluster", "and", "wait", "for", "an", "ACK", "." ]
3e2ff0719c7a6219b4e791e19c782de98c701f4a
https://github.com/nats-io/go-nats-streaming/blob/3e2ff0719c7a6219b4e791e19c782de98c701f4a/stan.go#L683-L693
151,579
nats-io/go-nats-streaming
stan.go
PublishAsync
func (sc *conn) PublishAsync(subject string, data []byte, ah AckHandler) (string, error) { return sc.publishAsync(subject, data, ah, nil) }
go
func (sc *conn) PublishAsync(subject string, data []byte, ah AckHandler) (string, error) { return sc.publishAsync(subject, data, ah, nil) }
[ "func", "(", "sc", "*", "conn", ")", "PublishAsync", "(", "subject", "string", ",", "data", "[", "]", "byte", ",", "ah", "AckHandler", ")", "(", "string", ",", "error", ")", "{", "return", "sc", ".", "publishAsync", "(", "subject", ",", "data", ",", "ah", ",", "nil", ")", "\n", "}" ]
// PublishAsync will publish to the cluster on pubPrefix+subject and asynchronously // process the ACK or error state. It will return the GUID for the message being sent.
[ "PublishAsync", "will", "publish", "to", "the", "cluster", "on", "pubPrefix", "+", "subject", "and", "asynchronously", "process", "the", "ACK", "or", "error", "state", ".", "It", "will", "return", "the", "GUID", "for", "the", "message", "being", "sent", "." ]
3e2ff0719c7a6219b4e791e19c782de98c701f4a
https://github.com/nats-io/go-nats-streaming/blob/3e2ff0719c7a6219b4e791e19c782de98c701f4a/stan.go#L697-L699
151,580
nats-io/go-nats-streaming
stan.go
processMsg
func (sc *conn) processMsg(raw *nats.Msg) { msg := &Msg{} err := msg.Unmarshal(raw.Data) if err != nil { panic(fmt.Errorf("error processing unmarshal for msg: %v", err)) } // Lookup the subscription sc.RLock() nc := sc.nc isClosed := nc == nil sub := sc.subMap[raw.Subject] sc.RUnlock() // Check if sub is no longer valid or connection has been closed. if sub == nil || isClosed { return } // Store in msg for backlink msg.Sub = sub sub.RLock() cb := sub.cb ackSubject := sub.ackInbox isManualAck := sub.opts.ManualAcks subsc := sub.sc // Can be nil if sub has been unsubscribed. sub.RUnlock() // Perform the callback if cb != nil && subsc != nil { cb(msg) } // Process auto-ack if !isManualAck && nc != nil { ack := &pb.Ack{Subject: msg.Subject, Sequence: msg.Sequence} b, _ := ack.Marshal() // FIXME(dlc) - Async error handler? Retry? nc.Publish(ackSubject, b) } }
go
func (sc *conn) processMsg(raw *nats.Msg) { msg := &Msg{} err := msg.Unmarshal(raw.Data) if err != nil { panic(fmt.Errorf("error processing unmarshal for msg: %v", err)) } // Lookup the subscription sc.RLock() nc := sc.nc isClosed := nc == nil sub := sc.subMap[raw.Subject] sc.RUnlock() // Check if sub is no longer valid or connection has been closed. if sub == nil || isClosed { return } // Store in msg for backlink msg.Sub = sub sub.RLock() cb := sub.cb ackSubject := sub.ackInbox isManualAck := sub.opts.ManualAcks subsc := sub.sc // Can be nil if sub has been unsubscribed. sub.RUnlock() // Perform the callback if cb != nil && subsc != nil { cb(msg) } // Process auto-ack if !isManualAck && nc != nil { ack := &pb.Ack{Subject: msg.Subject, Sequence: msg.Sequence} b, _ := ack.Marshal() // FIXME(dlc) - Async error handler? Retry? nc.Publish(ackSubject, b) } }
[ "func", "(", "sc", "*", "conn", ")", "processMsg", "(", "raw", "*", "nats", ".", "Msg", ")", "{", "msg", ":=", "&", "Msg", "{", "}", "\n", "err", ":=", "msg", ".", "Unmarshal", "(", "raw", ".", "Data", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "}", "\n", "// Lookup the subscription", "sc", ".", "RLock", "(", ")", "\n", "nc", ":=", "sc", ".", "nc", "\n", "isClosed", ":=", "nc", "==", "nil", "\n", "sub", ":=", "sc", ".", "subMap", "[", "raw", ".", "Subject", "]", "\n", "sc", ".", "RUnlock", "(", ")", "\n\n", "// Check if sub is no longer valid or connection has been closed.", "if", "sub", "==", "nil", "||", "isClosed", "{", "return", "\n", "}", "\n\n", "// Store in msg for backlink", "msg", ".", "Sub", "=", "sub", "\n\n", "sub", ".", "RLock", "(", ")", "\n", "cb", ":=", "sub", ".", "cb", "\n", "ackSubject", ":=", "sub", ".", "ackInbox", "\n", "isManualAck", ":=", "sub", ".", "opts", ".", "ManualAcks", "\n", "subsc", ":=", "sub", ".", "sc", "// Can be nil if sub has been unsubscribed.", "\n", "sub", ".", "RUnlock", "(", ")", "\n\n", "// Perform the callback", "if", "cb", "!=", "nil", "&&", "subsc", "!=", "nil", "{", "cb", "(", "msg", ")", "\n", "}", "\n\n", "// Process auto-ack", "if", "!", "isManualAck", "&&", "nc", "!=", "nil", "{", "ack", ":=", "&", "pb", ".", "Ack", "{", "Subject", ":", "msg", ".", "Subject", ",", "Sequence", ":", "msg", ".", "Sequence", "}", "\n", "b", ",", "_", ":=", "ack", ".", "Marshal", "(", ")", "\n", "// FIXME(dlc) - Async error handler? Retry?", "nc", ".", "Publish", "(", "ackSubject", ",", "b", ")", "\n", "}", "\n", "}" ]
// Process an msg from the NATS Streaming cluster
[ "Process", "an", "msg", "from", "the", "NATS", "Streaming", "cluster" ]
3e2ff0719c7a6219b4e791e19c782de98c701f4a
https://github.com/nats-io/go-nats-streaming/blob/3e2ff0719c7a6219b4e791e19c782de98c701f4a/stan.go#L794-L834
151,581
nats-io/go-nats-streaming
sub.go
MaxInflight
func MaxInflight(m int) SubscriptionOption { return func(o *SubscriptionOptions) error { o.MaxInflight = m return nil } }
go
func MaxInflight(m int) SubscriptionOption { return func(o *SubscriptionOptions) error { o.MaxInflight = m return nil } }
[ "func", "MaxInflight", "(", "m", "int", ")", "SubscriptionOption", "{", "return", "func", "(", "o", "*", "SubscriptionOptions", ")", "error", "{", "o", ".", "MaxInflight", "=", "m", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// MaxInflight is an Option to set the maximum number of messages the cluster will send // without an ACK.
[ "MaxInflight", "is", "an", "Option", "to", "set", "the", "maximum", "number", "of", "messages", "the", "cluster", "will", "send", "without", "an", "ACK", "." ]
3e2ff0719c7a6219b4e791e19c782de98c701f4a
https://github.com/nats-io/go-nats-streaming/blob/3e2ff0719c7a6219b4e791e19c782de98c701f4a/sub.go#L139-L144
151,582
nats-io/go-nats-streaming
sub.go
AckWait
func AckWait(t time.Duration) SubscriptionOption { return func(o *SubscriptionOptions) error { o.AckWait = t return nil } }
go
func AckWait(t time.Duration) SubscriptionOption { return func(o *SubscriptionOptions) error { o.AckWait = t return nil } }
[ "func", "AckWait", "(", "t", "time", ".", "Duration", ")", "SubscriptionOption", "{", "return", "func", "(", "o", "*", "SubscriptionOptions", ")", "error", "{", "o", ".", "AckWait", "=", "t", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// AckWait is an Option to set the timeout for waiting for an ACK from the cluster's // point of view for delivered messages.
[ "AckWait", "is", "an", "Option", "to", "set", "the", "timeout", "for", "waiting", "for", "an", "ACK", "from", "the", "cluster", "s", "point", "of", "view", "for", "delivered", "messages", "." ]
3e2ff0719c7a6219b4e791e19c782de98c701f4a
https://github.com/nats-io/go-nats-streaming/blob/3e2ff0719c7a6219b4e791e19c782de98c701f4a/sub.go#L148-L153
151,583
nats-io/go-nats-streaming
sub.go
StartAt
func StartAt(sp pb.StartPosition) SubscriptionOption { return func(o *SubscriptionOptions) error { o.StartAt = sp return nil } }
go
func StartAt(sp pb.StartPosition) SubscriptionOption { return func(o *SubscriptionOptions) error { o.StartAt = sp return nil } }
[ "func", "StartAt", "(", "sp", "pb", ".", "StartPosition", ")", "SubscriptionOption", "{", "return", "func", "(", "o", "*", "SubscriptionOptions", ")", "error", "{", "o", ".", "StartAt", "=", "sp", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// StartAt sets the desired start position for the message stream.
[ "StartAt", "sets", "the", "desired", "start", "position", "for", "the", "message", "stream", "." ]
3e2ff0719c7a6219b4e791e19c782de98c701f4a
https://github.com/nats-io/go-nats-streaming/blob/3e2ff0719c7a6219b4e791e19c782de98c701f4a/sub.go#L156-L161
151,584
nats-io/go-nats-streaming
sub.go
StartAtSequence
func StartAtSequence(seq uint64) SubscriptionOption { return func(o *SubscriptionOptions) error { o.StartAt = pb.StartPosition_SequenceStart o.StartSequence = seq return nil } }
go
func StartAtSequence(seq uint64) SubscriptionOption { return func(o *SubscriptionOptions) error { o.StartAt = pb.StartPosition_SequenceStart o.StartSequence = seq return nil } }
[ "func", "StartAtSequence", "(", "seq", "uint64", ")", "SubscriptionOption", "{", "return", "func", "(", "o", "*", "SubscriptionOptions", ")", "error", "{", "o", ".", "StartAt", "=", "pb", ".", "StartPosition_SequenceStart", "\n", "o", ".", "StartSequence", "=", "seq", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// StartAtSequence sets the desired start sequence position and state.
[ "StartAtSequence", "sets", "the", "desired", "start", "sequence", "position", "and", "state", "." ]
3e2ff0719c7a6219b4e791e19c782de98c701f4a
https://github.com/nats-io/go-nats-streaming/blob/3e2ff0719c7a6219b4e791e19c782de98c701f4a/sub.go#L164-L170
151,585
nats-io/go-nats-streaming
sub.go
StartAtTime
func StartAtTime(start time.Time) SubscriptionOption { return func(o *SubscriptionOptions) error { o.StartAt = pb.StartPosition_TimeDeltaStart o.StartTime = start return nil } }
go
func StartAtTime(start time.Time) SubscriptionOption { return func(o *SubscriptionOptions) error { o.StartAt = pb.StartPosition_TimeDeltaStart o.StartTime = start return nil } }
[ "func", "StartAtTime", "(", "start", "time", ".", "Time", ")", "SubscriptionOption", "{", "return", "func", "(", "o", "*", "SubscriptionOptions", ")", "error", "{", "o", ".", "StartAt", "=", "pb", ".", "StartPosition_TimeDeltaStart", "\n", "o", ".", "StartTime", "=", "start", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// StartAtTime sets the desired start time position and state.
[ "StartAtTime", "sets", "the", "desired", "start", "time", "position", "and", "state", "." ]
3e2ff0719c7a6219b4e791e19c782de98c701f4a
https://github.com/nats-io/go-nats-streaming/blob/3e2ff0719c7a6219b4e791e19c782de98c701f4a/sub.go#L173-L179
151,586
nats-io/go-nats-streaming
sub.go
StartAtTimeDelta
func StartAtTimeDelta(ago time.Duration) SubscriptionOption { return func(o *SubscriptionOptions) error { o.StartAt = pb.StartPosition_TimeDeltaStart o.StartTime = time.Now().Add(-ago) return nil } }
go
func StartAtTimeDelta(ago time.Duration) SubscriptionOption { return func(o *SubscriptionOptions) error { o.StartAt = pb.StartPosition_TimeDeltaStart o.StartTime = time.Now().Add(-ago) return nil } }
[ "func", "StartAtTimeDelta", "(", "ago", "time", ".", "Duration", ")", "SubscriptionOption", "{", "return", "func", "(", "o", "*", "SubscriptionOptions", ")", "error", "{", "o", ".", "StartAt", "=", "pb", ".", "StartPosition_TimeDeltaStart", "\n", "o", ".", "StartTime", "=", "time", ".", "Now", "(", ")", ".", "Add", "(", "-", "ago", ")", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// StartAtTimeDelta sets the desired start time position and state using the delta.
[ "StartAtTimeDelta", "sets", "the", "desired", "start", "time", "position", "and", "state", "using", "the", "delta", "." ]
3e2ff0719c7a6219b4e791e19c782de98c701f4a
https://github.com/nats-io/go-nats-streaming/blob/3e2ff0719c7a6219b4e791e19c782de98c701f4a/sub.go#L182-L188
151,587
nats-io/go-nats-streaming
sub.go
StartWithLastReceived
func StartWithLastReceived() SubscriptionOption { return func(o *SubscriptionOptions) error { o.StartAt = pb.StartPosition_LastReceived return nil } }
go
func StartWithLastReceived() SubscriptionOption { return func(o *SubscriptionOptions) error { o.StartAt = pb.StartPosition_LastReceived return nil } }
[ "func", "StartWithLastReceived", "(", ")", "SubscriptionOption", "{", "return", "func", "(", "o", "*", "SubscriptionOptions", ")", "error", "{", "o", ".", "StartAt", "=", "pb", ".", "StartPosition_LastReceived", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// StartWithLastReceived is a helper function to set start position to last received.
[ "StartWithLastReceived", "is", "a", "helper", "function", "to", "set", "start", "position", "to", "last", "received", "." ]
3e2ff0719c7a6219b4e791e19c782de98c701f4a
https://github.com/nats-io/go-nats-streaming/blob/3e2ff0719c7a6219b4e791e19c782de98c701f4a/sub.go#L191-L196
151,588
nats-io/go-nats-streaming
sub.go
DeliverAllAvailable
func DeliverAllAvailable() SubscriptionOption { return func(o *SubscriptionOptions) error { o.StartAt = pb.StartPosition_First return nil } }
go
func DeliverAllAvailable() SubscriptionOption { return func(o *SubscriptionOptions) error { o.StartAt = pb.StartPosition_First return nil } }
[ "func", "DeliverAllAvailable", "(", ")", "SubscriptionOption", "{", "return", "func", "(", "o", "*", "SubscriptionOptions", ")", "error", "{", "o", ".", "StartAt", "=", "pb", ".", "StartPosition_First", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// DeliverAllAvailable will deliver all messages available.
[ "DeliverAllAvailable", "will", "deliver", "all", "messages", "available", "." ]
3e2ff0719c7a6219b4e791e19c782de98c701f4a
https://github.com/nats-io/go-nats-streaming/blob/3e2ff0719c7a6219b4e791e19c782de98c701f4a/sub.go#L199-L204
151,589
nats-io/go-nats-streaming
sub.go
DurableName
func DurableName(name string) SubscriptionOption { return func(o *SubscriptionOptions) error { o.DurableName = name return nil } }
go
func DurableName(name string) SubscriptionOption { return func(o *SubscriptionOptions) error { o.DurableName = name return nil } }
[ "func", "DurableName", "(", "name", "string", ")", "SubscriptionOption", "{", "return", "func", "(", "o", "*", "SubscriptionOptions", ")", "error", "{", "o", ".", "DurableName", "=", "name", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// DurableName sets the DurableName for the subscriber.
[ "DurableName", "sets", "the", "DurableName", "for", "the", "subscriber", "." ]
3e2ff0719c7a6219b4e791e19c782de98c701f4a
https://github.com/nats-io/go-nats-streaming/blob/3e2ff0719c7a6219b4e791e19c782de98c701f4a/sub.go#L215-L220
151,590
nats-io/go-nats-streaming
sub.go
Subscribe
func (sc *conn) Subscribe(subject string, cb MsgHandler, options ...SubscriptionOption) (Subscription, error) { return sc.subscribe(subject, "", cb, options...) }
go
func (sc *conn) Subscribe(subject string, cb MsgHandler, options ...SubscriptionOption) (Subscription, error) { return sc.subscribe(subject, "", cb, options...) }
[ "func", "(", "sc", "*", "conn", ")", "Subscribe", "(", "subject", "string", ",", "cb", "MsgHandler", ",", "options", "...", "SubscriptionOption", ")", "(", "Subscription", ",", "error", ")", "{", "return", "sc", ".", "subscribe", "(", "subject", ",", "\"", "\"", ",", "cb", ",", "options", "...", ")", "\n", "}" ]
// Subscribe will perform a subscription with the given options to the NATS Streaming cluster.
[ "Subscribe", "will", "perform", "a", "subscription", "with", "the", "given", "options", "to", "the", "NATS", "Streaming", "cluster", "." ]
3e2ff0719c7a6219b4e791e19c782de98c701f4a
https://github.com/nats-io/go-nats-streaming/blob/3e2ff0719c7a6219b4e791e19c782de98c701f4a/sub.go#L223-L225
151,591
nats-io/go-nats-streaming
sub.go
QueueSubscribe
func (sc *conn) QueueSubscribe(subject, qgroup string, cb MsgHandler, options ...SubscriptionOption) (Subscription, error) { return sc.subscribe(subject, qgroup, cb, options...) }
go
func (sc *conn) QueueSubscribe(subject, qgroup string, cb MsgHandler, options ...SubscriptionOption) (Subscription, error) { return sc.subscribe(subject, qgroup, cb, options...) }
[ "func", "(", "sc", "*", "conn", ")", "QueueSubscribe", "(", "subject", ",", "qgroup", "string", ",", "cb", "MsgHandler", ",", "options", "...", "SubscriptionOption", ")", "(", "Subscription", ",", "error", ")", "{", "return", "sc", ".", "subscribe", "(", "subject", ",", "qgroup", ",", "cb", ",", "options", "...", ")", "\n", "}" ]
// QueueSubscribe will perform a queue subscription with the given options to the NATS Streaming cluster.
[ "QueueSubscribe", "will", "perform", "a", "queue", "subscription", "with", "the", "given", "options", "to", "the", "NATS", "Streaming", "cluster", "." ]
3e2ff0719c7a6219b4e791e19c782de98c701f4a
https://github.com/nats-io/go-nats-streaming/blob/3e2ff0719c7a6219b4e791e19c782de98c701f4a/sub.go#L228-L230
151,592
nats-io/go-nats-streaming
sub.go
subscribe
func (sc *conn) subscribe(subject, qgroup string, cb MsgHandler, options ...SubscriptionOption) (Subscription, error) { sub := &subscription{subject: subject, qgroup: qgroup, inbox: nats.NewInbox(), cb: cb, sc: sc, opts: DefaultSubscriptionOptions} for _, opt := range options { if err := opt(&sub.opts); err != nil { return nil, err } } sc.Lock() if sc.nc == nil { sc.Unlock() return nil, ErrConnectionClosed } // Register subscription. sc.subMap[sub.inbox] = sub nc := sc.nc sc.Unlock() // Hold lock throughout. sub.Lock() defer sub.Unlock() // Listen for actual messages. nsub, err := nc.Subscribe(sub.inbox, sc.processMsg) if err != nil { return nil, err } sub.inboxSub = nsub // Create a subscription request // FIXME(dlc) add others. sr := &pb.SubscriptionRequest{ ClientID: sc.clientID, Subject: subject, QGroup: qgroup, Inbox: sub.inbox, MaxInFlight: int32(sub.opts.MaxInflight), AckWaitInSecs: int32(sub.opts.AckWait / time.Second), StartPosition: sub.opts.StartAt, DurableName: sub.opts.DurableName, } // Conditionals switch sr.StartPosition { case pb.StartPosition_TimeDeltaStart: sr.StartTimeDelta = time.Now().UnixNano() - sub.opts.StartTime.UnixNano() case pb.StartPosition_SequenceStart: sr.StartSequence = sub.opts.StartSequence } b, _ := sr.Marshal() reply, err := nc.Request(sc.subRequests, b, sc.opts.ConnectTimeout) if err != nil { sub.inboxSub.Unsubscribe() if err == nats.ErrTimeout { err = ErrSubReqTimeout } return nil, err } r := &pb.SubscriptionResponse{} if err := r.Unmarshal(reply.Data); err != nil { sub.inboxSub.Unsubscribe() return nil, err } if r.Error != "" { sub.inboxSub.Unsubscribe() return nil, errors.New(r.Error) } sub.ackInbox = r.AckInbox return sub, nil }
go
func (sc *conn) subscribe(subject, qgroup string, cb MsgHandler, options ...SubscriptionOption) (Subscription, error) { sub := &subscription{subject: subject, qgroup: qgroup, inbox: nats.NewInbox(), cb: cb, sc: sc, opts: DefaultSubscriptionOptions} for _, opt := range options { if err := opt(&sub.opts); err != nil { return nil, err } } sc.Lock() if sc.nc == nil { sc.Unlock() return nil, ErrConnectionClosed } // Register subscription. sc.subMap[sub.inbox] = sub nc := sc.nc sc.Unlock() // Hold lock throughout. sub.Lock() defer sub.Unlock() // Listen for actual messages. nsub, err := nc.Subscribe(sub.inbox, sc.processMsg) if err != nil { return nil, err } sub.inboxSub = nsub // Create a subscription request // FIXME(dlc) add others. sr := &pb.SubscriptionRequest{ ClientID: sc.clientID, Subject: subject, QGroup: qgroup, Inbox: sub.inbox, MaxInFlight: int32(sub.opts.MaxInflight), AckWaitInSecs: int32(sub.opts.AckWait / time.Second), StartPosition: sub.opts.StartAt, DurableName: sub.opts.DurableName, } // Conditionals switch sr.StartPosition { case pb.StartPosition_TimeDeltaStart: sr.StartTimeDelta = time.Now().UnixNano() - sub.opts.StartTime.UnixNano() case pb.StartPosition_SequenceStart: sr.StartSequence = sub.opts.StartSequence } b, _ := sr.Marshal() reply, err := nc.Request(sc.subRequests, b, sc.opts.ConnectTimeout) if err != nil { sub.inboxSub.Unsubscribe() if err == nats.ErrTimeout { err = ErrSubReqTimeout } return nil, err } r := &pb.SubscriptionResponse{} if err := r.Unmarshal(reply.Data); err != nil { sub.inboxSub.Unsubscribe() return nil, err } if r.Error != "" { sub.inboxSub.Unsubscribe() return nil, errors.New(r.Error) } sub.ackInbox = r.AckInbox return sub, nil }
[ "func", "(", "sc", "*", "conn", ")", "subscribe", "(", "subject", ",", "qgroup", "string", ",", "cb", "MsgHandler", ",", "options", "...", "SubscriptionOption", ")", "(", "Subscription", ",", "error", ")", "{", "sub", ":=", "&", "subscription", "{", "subject", ":", "subject", ",", "qgroup", ":", "qgroup", ",", "inbox", ":", "nats", ".", "NewInbox", "(", ")", ",", "cb", ":", "cb", ",", "sc", ":", "sc", ",", "opts", ":", "DefaultSubscriptionOptions", "}", "\n", "for", "_", ",", "opt", ":=", "range", "options", "{", "if", "err", ":=", "opt", "(", "&", "sub", ".", "opts", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "sc", ".", "Lock", "(", ")", "\n", "if", "sc", ".", "nc", "==", "nil", "{", "sc", ".", "Unlock", "(", ")", "\n", "return", "nil", ",", "ErrConnectionClosed", "\n", "}", "\n\n", "// Register subscription.", "sc", ".", "subMap", "[", "sub", ".", "inbox", "]", "=", "sub", "\n", "nc", ":=", "sc", ".", "nc", "\n", "sc", ".", "Unlock", "(", ")", "\n\n", "// Hold lock throughout.", "sub", ".", "Lock", "(", ")", "\n", "defer", "sub", ".", "Unlock", "(", ")", "\n\n", "// Listen for actual messages.", "nsub", ",", "err", ":=", "nc", ".", "Subscribe", "(", "sub", ".", "inbox", ",", "sc", ".", "processMsg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "sub", ".", "inboxSub", "=", "nsub", "\n\n", "// Create a subscription request", "// FIXME(dlc) add others.", "sr", ":=", "&", "pb", ".", "SubscriptionRequest", "{", "ClientID", ":", "sc", ".", "clientID", ",", "Subject", ":", "subject", ",", "QGroup", ":", "qgroup", ",", "Inbox", ":", "sub", ".", "inbox", ",", "MaxInFlight", ":", "int32", "(", "sub", ".", "opts", ".", "MaxInflight", ")", ",", "AckWaitInSecs", ":", "int32", "(", "sub", ".", "opts", ".", "AckWait", "/", "time", ".", "Second", ")", ",", "StartPosition", ":", "sub", ".", "opts", ".", "StartAt", ",", "DurableName", ":", "sub", ".", "opts", ".", "DurableName", ",", "}", "\n\n", "// Conditionals", "switch", "sr", ".", "StartPosition", "{", "case", "pb", ".", "StartPosition_TimeDeltaStart", ":", "sr", ".", "StartTimeDelta", "=", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", "-", "sub", ".", "opts", ".", "StartTime", ".", "UnixNano", "(", ")", "\n", "case", "pb", ".", "StartPosition_SequenceStart", ":", "sr", ".", "StartSequence", "=", "sub", ".", "opts", ".", "StartSequence", "\n", "}", "\n\n", "b", ",", "_", ":=", "sr", ".", "Marshal", "(", ")", "\n", "reply", ",", "err", ":=", "nc", ".", "Request", "(", "sc", ".", "subRequests", ",", "b", ",", "sc", ".", "opts", ".", "ConnectTimeout", ")", "\n", "if", "err", "!=", "nil", "{", "sub", ".", "inboxSub", ".", "Unsubscribe", "(", ")", "\n", "if", "err", "==", "nats", ".", "ErrTimeout", "{", "err", "=", "ErrSubReqTimeout", "\n", "}", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "r", ":=", "&", "pb", ".", "SubscriptionResponse", "{", "}", "\n", "if", "err", ":=", "r", ".", "Unmarshal", "(", "reply", ".", "Data", ")", ";", "err", "!=", "nil", "{", "sub", ".", "inboxSub", ".", "Unsubscribe", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "if", "r", ".", "Error", "!=", "\"", "\"", "{", "sub", ".", "inboxSub", ".", "Unsubscribe", "(", ")", "\n", "return", "nil", ",", "errors", ".", "New", "(", "r", ".", "Error", ")", "\n", "}", "\n", "sub", ".", "ackInbox", "=", "r", ".", "AckInbox", "\n\n", "return", "sub", ",", "nil", "\n", "}" ]
// subscribe will perform a subscription with the given options to the NATS Streaming cluster.
[ "subscribe", "will", "perform", "a", "subscription", "with", "the", "given", "options", "to", "the", "NATS", "Streaming", "cluster", "." ]
3e2ff0719c7a6219b4e791e19c782de98c701f4a
https://github.com/nats-io/go-nats-streaming/blob/3e2ff0719c7a6219b4e791e19c782de98c701f4a/sub.go#L233-L304
151,593
nats-io/go-nats-streaming
sub.go
closeOrUnsubscribe
func (sub *subscription) closeOrUnsubscribe(doClose bool) error { sub.Lock() sc := sub.sc if sc == nil { // Already closed. sub.Unlock() return ErrBadSubscription } sub.sc = nil sub.inboxSub.Unsubscribe() sub.inboxSub = nil sub.Unlock() sc.Lock() if sc.nc == nil { sc.Unlock() return ErrConnectionClosed } delete(sc.subMap, sub.inbox) reqSubject := sc.unsubRequests if doClose { reqSubject = sc.subCloseRequests if reqSubject == "" { sc.Unlock() return ErrNoServerSupport } } // Snapshot connection to avoid data race, since the connection may be // closing while we try to send the request nc := sc.nc sc.Unlock() usr := &pb.UnsubscribeRequest{ ClientID: sc.clientID, Subject: sub.subject, Inbox: sub.ackInbox, } b, _ := usr.Marshal() reply, err := nc.Request(reqSubject, b, sc.opts.ConnectTimeout) if err != nil { if err == nats.ErrTimeout { if doClose { return ErrCloseReqTimeout } return ErrUnsubReqTimeout } return err } r := &pb.SubscriptionResponse{} if err := r.Unmarshal(reply.Data); err != nil { return err } if r.Error != "" { return errors.New(r.Error) } return nil }
go
func (sub *subscription) closeOrUnsubscribe(doClose bool) error { sub.Lock() sc := sub.sc if sc == nil { // Already closed. sub.Unlock() return ErrBadSubscription } sub.sc = nil sub.inboxSub.Unsubscribe() sub.inboxSub = nil sub.Unlock() sc.Lock() if sc.nc == nil { sc.Unlock() return ErrConnectionClosed } delete(sc.subMap, sub.inbox) reqSubject := sc.unsubRequests if doClose { reqSubject = sc.subCloseRequests if reqSubject == "" { sc.Unlock() return ErrNoServerSupport } } // Snapshot connection to avoid data race, since the connection may be // closing while we try to send the request nc := sc.nc sc.Unlock() usr := &pb.UnsubscribeRequest{ ClientID: sc.clientID, Subject: sub.subject, Inbox: sub.ackInbox, } b, _ := usr.Marshal() reply, err := nc.Request(reqSubject, b, sc.opts.ConnectTimeout) if err != nil { if err == nats.ErrTimeout { if doClose { return ErrCloseReqTimeout } return ErrUnsubReqTimeout } return err } r := &pb.SubscriptionResponse{} if err := r.Unmarshal(reply.Data); err != nil { return err } if r.Error != "" { return errors.New(r.Error) } return nil }
[ "func", "(", "sub", "*", "subscription", ")", "closeOrUnsubscribe", "(", "doClose", "bool", ")", "error", "{", "sub", ".", "Lock", "(", ")", "\n", "sc", ":=", "sub", ".", "sc", "\n", "if", "sc", "==", "nil", "{", "// Already closed.", "sub", ".", "Unlock", "(", ")", "\n", "return", "ErrBadSubscription", "\n", "}", "\n", "sub", ".", "sc", "=", "nil", "\n", "sub", ".", "inboxSub", ".", "Unsubscribe", "(", ")", "\n", "sub", ".", "inboxSub", "=", "nil", "\n", "sub", ".", "Unlock", "(", ")", "\n\n", "sc", ".", "Lock", "(", ")", "\n", "if", "sc", ".", "nc", "==", "nil", "{", "sc", ".", "Unlock", "(", ")", "\n", "return", "ErrConnectionClosed", "\n", "}", "\n\n", "delete", "(", "sc", ".", "subMap", ",", "sub", ".", "inbox", ")", "\n", "reqSubject", ":=", "sc", ".", "unsubRequests", "\n", "if", "doClose", "{", "reqSubject", "=", "sc", ".", "subCloseRequests", "\n", "if", "reqSubject", "==", "\"", "\"", "{", "sc", ".", "Unlock", "(", ")", "\n", "return", "ErrNoServerSupport", "\n", "}", "\n", "}", "\n\n", "// Snapshot connection to avoid data race, since the connection may be", "// closing while we try to send the request", "nc", ":=", "sc", ".", "nc", "\n", "sc", ".", "Unlock", "(", ")", "\n\n", "usr", ":=", "&", "pb", ".", "UnsubscribeRequest", "{", "ClientID", ":", "sc", ".", "clientID", ",", "Subject", ":", "sub", ".", "subject", ",", "Inbox", ":", "sub", ".", "ackInbox", ",", "}", "\n", "b", ",", "_", ":=", "usr", ".", "Marshal", "(", ")", "\n", "reply", ",", "err", ":=", "nc", ".", "Request", "(", "reqSubject", ",", "b", ",", "sc", ".", "opts", ".", "ConnectTimeout", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "nats", ".", "ErrTimeout", "{", "if", "doClose", "{", "return", "ErrCloseReqTimeout", "\n", "}", "\n", "return", "ErrUnsubReqTimeout", "\n", "}", "\n", "return", "err", "\n", "}", "\n", "r", ":=", "&", "pb", ".", "SubscriptionResponse", "{", "}", "\n", "if", "err", ":=", "r", ".", "Unmarshal", "(", "reply", ".", "Data", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "r", ".", "Error", "!=", "\"", "\"", "{", "return", "errors", ".", "New", "(", "r", ".", "Error", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// closeOrUnsubscribe performs either close or unsubsribe based on // given boolean.
[ "closeOrUnsubscribe", "performs", "either", "close", "or", "unsubsribe", "based", "on", "given", "boolean", "." ]
3e2ff0719c7a6219b4e791e19c782de98c701f4a
https://github.com/nats-io/go-nats-streaming/blob/3e2ff0719c7a6219b4e791e19c782de98c701f4a/sub.go#L396-L455
151,594
twpayne/go-geom
xyz/xyz.go
Distance
func Distance(point1, point2 geom.Coord) float64 { // default to 2D distance if either Z is not set if math.IsNaN(point1[2]) || math.IsNaN(point2[2]) { return xy.Distance(point1, point2) } dx := point1[0] - point2[0] dy := point1[1] - point2[1] dz := point1[2] - point2[2] return math.Sqrt(dx*dx + dy*dy + dz*dz) }
go
func Distance(point1, point2 geom.Coord) float64 { // default to 2D distance if either Z is not set if math.IsNaN(point1[2]) || math.IsNaN(point2[2]) { return xy.Distance(point1, point2) } dx := point1[0] - point2[0] dy := point1[1] - point2[1] dz := point1[2] - point2[2] return math.Sqrt(dx*dx + dy*dy + dz*dz) }
[ "func", "Distance", "(", "point1", ",", "point2", "geom", ".", "Coord", ")", "float64", "{", "// default to 2D distance if either Z is not set", "if", "math", ".", "IsNaN", "(", "point1", "[", "2", "]", ")", "||", "math", ".", "IsNaN", "(", "point2", "[", "2", "]", ")", "{", "return", "xy", ".", "Distance", "(", "point1", ",", "point2", ")", "\n", "}", "\n\n", "dx", ":=", "point1", "[", "0", "]", "-", "point2", "[", "0", "]", "\n", "dy", ":=", "point1", "[", "1", "]", "-", "point2", "[", "1", "]", "\n", "dz", ":=", "point1", "[", "2", "]", "-", "point2", "[", "2", "]", "\n", "return", "math", ".", "Sqrt", "(", "dx", "*", "dx", "+", "dy", "*", "dy", "+", "dz", "*", "dz", ")", "\n", "}" ]
// Distance calculates the distance between the two coordinates in 3d space.
[ "Distance", "calculates", "the", "distance", "between", "the", "two", "coordinates", "in", "3d", "space", "." ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/xyz/xyz.go#L14-L24
151,595
twpayne/go-geom
xyz/xyz.go
DistancePointToLine
func DistancePointToLine(point, lineStart, lineEnd geom.Coord) float64 { // if start = end, then just compute distance to one of the endpoints if Equals(lineStart, lineEnd) { return Distance(point, lineStart) } // otherwise use comp.graphics.algorithms Frequently Asked Questions method /* * (1) r = AC dot AB * --------- * ||AB||^2 * * r has the following meaning: * r=0 P = A * r=1 P = B * r<0 P is on the backward extension of AB * r>1 P is on the forward extension of AB * 0<r<1 P is interior to AB */ len2 := (lineEnd[0]-lineStart[0])*(lineEnd[0]-lineStart[0]) + (lineEnd[1]-lineStart[1])*(lineEnd[1]-lineStart[1]) + (lineEnd[2]-lineStart[2])*(lineEnd[2]-lineStart[2]) if math.IsNaN(len2) { panic("Ordinates must not be NaN") } r := ((point[0]-lineStart[0])*(lineEnd[0]-lineStart[0]) + (point[1]-lineStart[1])*(lineEnd[1]-lineStart[1]) + (point[2]-lineStart[2])*(lineEnd[2]-lineStart[2])) / len2 if r <= 0.0 { return Distance(point, lineStart) } if r >= 1.0 { return Distance(point, lineEnd) } // compute closest point q on line segment qx := lineStart[0] + r*(lineEnd[0]-lineStart[0]) qy := lineStart[1] + r*(lineEnd[1]-lineStart[1]) qz := lineStart[2] + r*(lineEnd[2]-lineStart[2]) // result is distance from p to q dx := point[0] - qx dy := point[1] - qy dz := point[2] - qz return math.Sqrt(dx*dx + dy*dy + dz*dz) }
go
func DistancePointToLine(point, lineStart, lineEnd geom.Coord) float64 { // if start = end, then just compute distance to one of the endpoints if Equals(lineStart, lineEnd) { return Distance(point, lineStart) } // otherwise use comp.graphics.algorithms Frequently Asked Questions method /* * (1) r = AC dot AB * --------- * ||AB||^2 * * r has the following meaning: * r=0 P = A * r=1 P = B * r<0 P is on the backward extension of AB * r>1 P is on the forward extension of AB * 0<r<1 P is interior to AB */ len2 := (lineEnd[0]-lineStart[0])*(lineEnd[0]-lineStart[0]) + (lineEnd[1]-lineStart[1])*(lineEnd[1]-lineStart[1]) + (lineEnd[2]-lineStart[2])*(lineEnd[2]-lineStart[2]) if math.IsNaN(len2) { panic("Ordinates must not be NaN") } r := ((point[0]-lineStart[0])*(lineEnd[0]-lineStart[0]) + (point[1]-lineStart[1])*(lineEnd[1]-lineStart[1]) + (point[2]-lineStart[2])*(lineEnd[2]-lineStart[2])) / len2 if r <= 0.0 { return Distance(point, lineStart) } if r >= 1.0 { return Distance(point, lineEnd) } // compute closest point q on line segment qx := lineStart[0] + r*(lineEnd[0]-lineStart[0]) qy := lineStart[1] + r*(lineEnd[1]-lineStart[1]) qz := lineStart[2] + r*(lineEnd[2]-lineStart[2]) // result is distance from p to q dx := point[0] - qx dy := point[1] - qy dz := point[2] - qz return math.Sqrt(dx*dx + dy*dy + dz*dz) }
[ "func", "DistancePointToLine", "(", "point", ",", "lineStart", ",", "lineEnd", "geom", ".", "Coord", ")", "float64", "{", "// if start = end, then just compute distance to one of the endpoints", "if", "Equals", "(", "lineStart", ",", "lineEnd", ")", "{", "return", "Distance", "(", "point", ",", "lineStart", ")", "\n", "}", "\n\n", "// otherwise use comp.graphics.algorithms Frequently Asked Questions method", "/*\n\t * (1) r = AC dot AB\n\t * ---------\n\t * ||AB||^2\n\t *\n\t * r has the following meaning:\n\t * r=0 P = A\n\t * r=1 P = B\n\t * r<0 P is on the backward extension of AB\n\t * r>1 P is on the forward extension of AB\n\t * 0<r<1 P is interior to AB\n\t */", "len2", ":=", "(", "lineEnd", "[", "0", "]", "-", "lineStart", "[", "0", "]", ")", "*", "(", "lineEnd", "[", "0", "]", "-", "lineStart", "[", "0", "]", ")", "+", "(", "lineEnd", "[", "1", "]", "-", "lineStart", "[", "1", "]", ")", "*", "(", "lineEnd", "[", "1", "]", "-", "lineStart", "[", "1", "]", ")", "+", "(", "lineEnd", "[", "2", "]", "-", "lineStart", "[", "2", "]", ")", "*", "(", "lineEnd", "[", "2", "]", "-", "lineStart", "[", "2", "]", ")", "\n", "if", "math", ".", "IsNaN", "(", "len2", ")", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "r", ":=", "(", "(", "point", "[", "0", "]", "-", "lineStart", "[", "0", "]", ")", "*", "(", "lineEnd", "[", "0", "]", "-", "lineStart", "[", "0", "]", ")", "+", "(", "point", "[", "1", "]", "-", "lineStart", "[", "1", "]", ")", "*", "(", "lineEnd", "[", "1", "]", "-", "lineStart", "[", "1", "]", ")", "+", "(", "point", "[", "2", "]", "-", "lineStart", "[", "2", "]", ")", "*", "(", "lineEnd", "[", "2", "]", "-", "lineStart", "[", "2", "]", ")", ")", "/", "len2", "\n\n", "if", "r", "<=", "0.0", "{", "return", "Distance", "(", "point", ",", "lineStart", ")", "\n", "}", "\n", "if", "r", ">=", "1.0", "{", "return", "Distance", "(", "point", ",", "lineEnd", ")", "\n", "}", "\n\n", "// compute closest point q on line segment", "qx", ":=", "lineStart", "[", "0", "]", "+", "r", "*", "(", "lineEnd", "[", "0", "]", "-", "lineStart", "[", "0", "]", ")", "\n", "qy", ":=", "lineStart", "[", "1", "]", "+", "r", "*", "(", "lineEnd", "[", "1", "]", "-", "lineStart", "[", "1", "]", ")", "\n", "qz", ":=", "lineStart", "[", "2", "]", "+", "r", "*", "(", "lineEnd", "[", "2", "]", "-", "lineStart", "[", "2", "]", ")", "\n", "// result is distance from p to q", "dx", ":=", "point", "[", "0", "]", "-", "qx", "\n", "dy", ":=", "point", "[", "1", "]", "-", "qy", "\n", "dz", ":=", "point", "[", "2", "]", "-", "qz", "\n", "return", "math", ".", "Sqrt", "(", "dx", "*", "dx", "+", "dy", "*", "dy", "+", "dz", "*", "dz", ")", "\n", "}" ]
// DistancePointToLine calculates the distance from point to a point on the line
[ "DistancePointToLine", "calculates", "the", "distance", "from", "point", "to", "a", "point", "on", "the", "line" ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/xyz/xyz.go#L27-L69
151,596
twpayne/go-geom
xyz/xyz.go
Equals
func Equals(point1, other geom.Coord) bool { return (point1[0] == other[0]) && (point1[1] == other[1]) && ((point1[2] == other[2]) || (math.IsNaN(point1[2]) && math.IsNaN(other[2]))) }
go
func Equals(point1, other geom.Coord) bool { return (point1[0] == other[0]) && (point1[1] == other[1]) && ((point1[2] == other[2]) || (math.IsNaN(point1[2]) && math.IsNaN(other[2]))) }
[ "func", "Equals", "(", "point1", ",", "other", "geom", ".", "Coord", ")", "bool", "{", "return", "(", "point1", "[", "0", "]", "==", "other", "[", "0", "]", ")", "&&", "(", "point1", "[", "1", "]", "==", "other", "[", "1", "]", ")", "&&", "(", "(", "point1", "[", "2", "]", "==", "other", "[", "2", "]", ")", "||", "(", "math", ".", "IsNaN", "(", "point1", "[", "2", "]", ")", "&&", "math", ".", "IsNaN", "(", "other", "[", "2", "]", ")", ")", ")", "\n", "}" ]
// Equals determines if the two coordinates have equal in 3d space
[ "Equals", "determines", "if", "the", "two", "coordinates", "have", "equal", "in", "3d", "space" ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/xyz/xyz.go#L72-L76
151,597
twpayne/go-geom
xyz/xyz.go
DistanceLineToLine
func DistanceLineToLine(line1Start, line1End, line2Start, line2End geom.Coord) float64 { /** * This calculation is susceptible to roundoff errors when * passed large ordinate values. * It may be possible to improve this by using {@link DD} arithmetic. */ if Equals(line1Start, line1End) { return DistancePointToLine(line1Start, line2Start, line2End) } if Equals(line2Start, line1End) { return DistancePointToLine(line2Start, line1Start, line1End) } /** * Algorithm derived from http://softsurfer.com/Archive/algorithm_0106/algorithm_0106.htm */ a := VectorDot(line1Start, line1End, line1Start, line1End) b := VectorDot(line1Start, line1End, line2Start, line2End) c := VectorDot(line2Start, line2End, line2Start, line2End) d := VectorDot(line1Start, line1End, line2Start, line1Start) e := VectorDot(line2Start, line2End, line2Start, line1Start) denom := a*c - b*b if math.IsNaN(denom) { panic("Ordinates must not be NaN") } var s, t float64 if denom <= 0.0 { /** * The lines are parallel. * In this case solve for the parameters s and t by assuming s is 0. */ s = 0 // choose largest denominator for optimal numeric conditioning if b > c { t = d / b } else { t = e / c } } else { s = (b*e - c*d) / denom t = (a*e - b*d) / denom } switch { case s < 0: return DistancePointToLine(line1Start, line2Start, line2End) case s > 1: return DistancePointToLine(line1End, line2Start, line2End) case t < 0: return DistancePointToLine(line2Start, line1Start, line1End) case t > 1: return DistancePointToLine(line2End, line1Start, line1End) } /** * The closest points are in interiors of segments, * so compute them directly */ x1 := line1Start[0] + s*(line1End[0]-line1Start[0]) y1 := line1Start[1] + s*(line1End[1]-line1Start[1]) z1 := line1Start[2] + s*(line1End[2]-line1Start[2]) x2 := line2Start[0] + t*(line2End[0]-line2Start[0]) y2 := line2Start[1] + t*(line2End[1]-line2Start[1]) z2 := line2Start[2] + t*(line2End[2]-line2Start[2]) // length (p1-p2) return Distance(geom.Coord{x1, y1, z1}, geom.Coord{x2, y2, z2}) }
go
func DistanceLineToLine(line1Start, line1End, line2Start, line2End geom.Coord) float64 { /** * This calculation is susceptible to roundoff errors when * passed large ordinate values. * It may be possible to improve this by using {@link DD} arithmetic. */ if Equals(line1Start, line1End) { return DistancePointToLine(line1Start, line2Start, line2End) } if Equals(line2Start, line1End) { return DistancePointToLine(line2Start, line1Start, line1End) } /** * Algorithm derived from http://softsurfer.com/Archive/algorithm_0106/algorithm_0106.htm */ a := VectorDot(line1Start, line1End, line1Start, line1End) b := VectorDot(line1Start, line1End, line2Start, line2End) c := VectorDot(line2Start, line2End, line2Start, line2End) d := VectorDot(line1Start, line1End, line2Start, line1Start) e := VectorDot(line2Start, line2End, line2Start, line1Start) denom := a*c - b*b if math.IsNaN(denom) { panic("Ordinates must not be NaN") } var s, t float64 if denom <= 0.0 { /** * The lines are parallel. * In this case solve for the parameters s and t by assuming s is 0. */ s = 0 // choose largest denominator for optimal numeric conditioning if b > c { t = d / b } else { t = e / c } } else { s = (b*e - c*d) / denom t = (a*e - b*d) / denom } switch { case s < 0: return DistancePointToLine(line1Start, line2Start, line2End) case s > 1: return DistancePointToLine(line1End, line2Start, line2End) case t < 0: return DistancePointToLine(line2Start, line1Start, line1End) case t > 1: return DistancePointToLine(line2End, line1Start, line1End) } /** * The closest points are in interiors of segments, * so compute them directly */ x1 := line1Start[0] + s*(line1End[0]-line1Start[0]) y1 := line1Start[1] + s*(line1End[1]-line1Start[1]) z1 := line1Start[2] + s*(line1End[2]-line1Start[2]) x2 := line2Start[0] + t*(line2End[0]-line2Start[0]) y2 := line2Start[1] + t*(line2End[1]-line2Start[1]) z2 := line2Start[2] + t*(line2End[2]-line2Start[2]) // length (p1-p2) return Distance(geom.Coord{x1, y1, z1}, geom.Coord{x2, y2, z2}) }
[ "func", "DistanceLineToLine", "(", "line1Start", ",", "line1End", ",", "line2Start", ",", "line2End", "geom", ".", "Coord", ")", "float64", "{", "/**\n\t * This calculation is susceptible to roundoff errors when\n\t * passed large ordinate values.\n\t * It may be possible to improve this by using {@link DD} arithmetic.\n\t */", "if", "Equals", "(", "line1Start", ",", "line1End", ")", "{", "return", "DistancePointToLine", "(", "line1Start", ",", "line2Start", ",", "line2End", ")", "\n", "}", "\n", "if", "Equals", "(", "line2Start", ",", "line1End", ")", "{", "return", "DistancePointToLine", "(", "line2Start", ",", "line1Start", ",", "line1End", ")", "\n", "}", "\n\n", "/**\n\t * Algorithm derived from http://softsurfer.com/Archive/algorithm_0106/algorithm_0106.htm\n\t */", "a", ":=", "VectorDot", "(", "line1Start", ",", "line1End", ",", "line1Start", ",", "line1End", ")", "\n", "b", ":=", "VectorDot", "(", "line1Start", ",", "line1End", ",", "line2Start", ",", "line2End", ")", "\n", "c", ":=", "VectorDot", "(", "line2Start", ",", "line2End", ",", "line2Start", ",", "line2End", ")", "\n", "d", ":=", "VectorDot", "(", "line1Start", ",", "line1End", ",", "line2Start", ",", "line1Start", ")", "\n", "e", ":=", "VectorDot", "(", "line2Start", ",", "line2End", ",", "line2Start", ",", "line1Start", ")", "\n\n", "denom", ":=", "a", "*", "c", "-", "b", "*", "b", "\n", "if", "math", ".", "IsNaN", "(", "denom", ")", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "var", "s", ",", "t", "float64", "\n", "if", "denom", "<=", "0.0", "{", "/**\n\t\t * The lines are parallel.\n\t\t * In this case solve for the parameters s and t by assuming s is 0.\n\t\t */", "s", "=", "0", "\n", "// choose largest denominator for optimal numeric conditioning", "if", "b", ">", "c", "{", "t", "=", "d", "/", "b", "\n", "}", "else", "{", "t", "=", "e", "/", "c", "\n", "}", "\n", "}", "else", "{", "s", "=", "(", "b", "*", "e", "-", "c", "*", "d", ")", "/", "denom", "\n", "t", "=", "(", "a", "*", "e", "-", "b", "*", "d", ")", "/", "denom", "\n", "}", "\n", "switch", "{", "case", "s", "<", "0", ":", "return", "DistancePointToLine", "(", "line1Start", ",", "line2Start", ",", "line2End", ")", "\n", "case", "s", ">", "1", ":", "return", "DistancePointToLine", "(", "line1End", ",", "line2Start", ",", "line2End", ")", "\n", "case", "t", "<", "0", ":", "return", "DistancePointToLine", "(", "line2Start", ",", "line1Start", ",", "line1End", ")", "\n", "case", "t", ">", "1", ":", "return", "DistancePointToLine", "(", "line2End", ",", "line1Start", ",", "line1End", ")", "\n", "}", "\n", "/**\n\t * The closest points are in interiors of segments,\n\t * so compute them directly\n\t */", "x1", ":=", "line1Start", "[", "0", "]", "+", "s", "*", "(", "line1End", "[", "0", "]", "-", "line1Start", "[", "0", "]", ")", "\n", "y1", ":=", "line1Start", "[", "1", "]", "+", "s", "*", "(", "line1End", "[", "1", "]", "-", "line1Start", "[", "1", "]", ")", "\n", "z1", ":=", "line1Start", "[", "2", "]", "+", "s", "*", "(", "line1End", "[", "2", "]", "-", "line1Start", "[", "2", "]", ")", "\n\n", "x2", ":=", "line2Start", "[", "0", "]", "+", "t", "*", "(", "line2End", "[", "0", "]", "-", "line2Start", "[", "0", "]", ")", "\n", "y2", ":=", "line2Start", "[", "1", "]", "+", "t", "*", "(", "line2End", "[", "1", "]", "-", "line2Start", "[", "1", "]", ")", "\n", "z2", ":=", "line2Start", "[", "2", "]", "+", "t", "*", "(", "line2End", "[", "2", "]", "-", "line2Start", "[", "2", "]", ")", "\n\n", "// length (p1-p2)", "return", "Distance", "(", "geom", ".", "Coord", "{", "x1", ",", "y1", ",", "z1", "}", ",", "geom", ".", "Coord", "{", "x2", ",", "y2", ",", "z2", "}", ")", "\n", "}" ]
// DistanceLineToLine computes the distance between two 3D segments
[ "DistanceLineToLine", "computes", "the", "distance", "between", "two", "3D", "segments" ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/xyz/xyz.go#L79-L147
151,598
twpayne/go-geom
xy/angle.go
AngleBetween
func AngleBetween(tip1, tail, tip2 geom.Coord) float64 { a1 := Angle(tail, tip1) a2 := Angle(tail, tip2) return Diff(a1, a2) }
go
func AngleBetween(tip1, tail, tip2 geom.Coord) float64 { a1 := Angle(tail, tip1) a2 := Angle(tail, tip2) return Diff(a1, a2) }
[ "func", "AngleBetween", "(", "tip1", ",", "tail", ",", "tip2", "geom", ".", "Coord", ")", "float64", "{", "a1", ":=", "Angle", "(", "tail", ",", "tip1", ")", "\n", "a2", ":=", "Angle", "(", "tail", ",", "tip2", ")", "\n\n", "return", "Diff", "(", "a1", ",", "a2", ")", "\n", "}" ]
// AngleBetween calculates the un-oriented smallest angle between two vectors. // The computed angle will be in the range [0, Pi). // // Param tip1 - the tip of one vector // param tail - the tail of each vector // param tip2 - the tip of the other vector
[ "AngleBetween", "calculates", "the", "un", "-", "oriented", "smallest", "angle", "between", "two", "vectors", ".", "The", "computed", "angle", "will", "be", "in", "the", "range", "[", "0", "Pi", ")", ".", "Param", "tip1", "-", "the", "tip", "of", "one", "vector", "param", "tail", "-", "the", "tail", "of", "each", "vector", "param", "tip2", "-", "the", "tip", "of", "the", "other", "vector" ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/xy/angle.go#L62-L67
151,599
twpayne/go-geom
xy/angle.go
AngleOrientation
func AngleOrientation(ang1, ang2 float64) orientation.Type { crossproduct := math.Sin(ang2 - ang1) switch { case crossproduct > 0: return orientation.CounterClockwise case crossproduct < 0: return orientation.Clockwise default: return orientation.Collinear } }
go
func AngleOrientation(ang1, ang2 float64) orientation.Type { crossproduct := math.Sin(ang2 - ang1) switch { case crossproduct > 0: return orientation.CounterClockwise case crossproduct < 0: return orientation.Clockwise default: return orientation.Collinear } }
[ "func", "AngleOrientation", "(", "ang1", ",", "ang2", "float64", ")", "orientation", ".", "Type", "{", "crossproduct", ":=", "math", ".", "Sin", "(", "ang2", "-", "ang1", ")", "\n\n", "switch", "{", "case", "crossproduct", ">", "0", ":", "return", "orientation", ".", "CounterClockwise", "\n", "case", "crossproduct", "<", "0", ":", "return", "orientation", ".", "Clockwise", "\n", "default", ":", "return", "orientation", ".", "Collinear", "\n", "}", "\n", "}" ]
// AngleOrientation returns whether an angle must turn clockwise or counterclockwise // overlap another angle.
[ "AngleOrientation", "returns", "whether", "an", "angle", "must", "turn", "clockwise", "or", "counterclockwise", "overlap", "another", "angle", "." ]
e21b3afba225b21d05fbcbeb8ece2c79c96554c5
https://github.com/twpayne/go-geom/blob/e21b3afba225b21d05fbcbeb8ece2c79c96554c5/xy/angle.go#L93-L104