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
sequence | docstring
stringlengths 6
2.61k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|---|
4,600 | ligato/cn-infra | processmanager/process.go | Start | func (p *Process) Start() (err error) {
if p.command, err = p.startProcess(); err != nil {
return err
}
p.log.Debugf("New process %s was started (PID: %d)", p.GetName(), p.GetPid())
return nil
} | go | func (p *Process) Start() (err error) {
if p.command, err = p.startProcess(); err != nil {
return err
}
p.log.Debugf("New process %s was started (PID: %d)", p.GetName(), p.GetPid())
return nil
} | [
"func",
"(",
"p",
"*",
"Process",
")",
"Start",
"(",
")",
"(",
"err",
"error",
")",
"{",
"if",
"p",
".",
"command",
",",
"err",
"=",
"p",
".",
"startProcess",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"p",
".",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"p",
".",
"GetName",
"(",
")",
",",
"p",
".",
"GetPid",
"(",
")",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Start a process with defined arguments. Every process is watched for liveness and status changes | [
"Start",
"a",
"process",
"with",
"defined",
"arguments",
".",
"Every",
"process",
"is",
"watched",
"for",
"liveness",
"and",
"status",
"changes"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/processmanager/process.go#L106-L113 |
4,601 | ligato/cn-infra | processmanager/process.go | Restart | func (p *Process) Restart() (err error) {
if p.isAlive() {
if _, err = p.StopAndWait(); err != nil {
p.log.Warnf("Cannot stop process %s due to error, trying force stop... (err: %v)", p.GetName(), err)
if err = p.forceStopProcess(); err != nil {
return err
}
}
}
p.command, err = p.startProcess()
p.log.Debugf("Process %s was restarted (PID: %d)", p.GetName(), p.GetPid())
return err
} | go | func (p *Process) Restart() (err error) {
if p.isAlive() {
if _, err = p.StopAndWait(); err != nil {
p.log.Warnf("Cannot stop process %s due to error, trying force stop... (err: %v)", p.GetName(), err)
if err = p.forceStopProcess(); err != nil {
return err
}
}
}
p.command, err = p.startProcess()
p.log.Debugf("Process %s was restarted (PID: %d)", p.GetName(), p.GetPid())
return err
} | [
"func",
"(",
"p",
"*",
"Process",
")",
"Restart",
"(",
")",
"(",
"err",
"error",
")",
"{",
"if",
"p",
".",
"isAlive",
"(",
")",
"{",
"if",
"_",
",",
"err",
"=",
"p",
".",
"StopAndWait",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"p",
".",
"log",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"p",
".",
"GetName",
"(",
")",
",",
"err",
")",
"\n",
"if",
"err",
"=",
"p",
".",
"forceStopProcess",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"p",
".",
"command",
",",
"err",
"=",
"p",
".",
"startProcess",
"(",
")",
"\n",
"p",
".",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"p",
".",
"GetName",
"(",
")",
",",
"p",
".",
"GetPid",
"(",
")",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // Restart the process, or start it if it is not running | [
"Restart",
"the",
"process",
"or",
"start",
"it",
"if",
"it",
"is",
"not",
"running"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/processmanager/process.go#L121-L133 |
4,602 | ligato/cn-infra | processmanager/process.go | Stop | func (p *Process) Stop() error {
if err := p.stopProcess(); err != nil {
return err
}
p.log.Debugf("Process %s was stopped (last PID: %d)", p.GetName(), p.GetPid())
return nil
} | go | func (p *Process) Stop() error {
if err := p.stopProcess(); err != nil {
return err
}
p.log.Debugf("Process %s was stopped (last PID: %d)", p.GetName(), p.GetPid())
return nil
} | [
"func",
"(",
"p",
"*",
"Process",
")",
"Stop",
"(",
")",
"error",
"{",
"if",
"err",
":=",
"p",
".",
"stopProcess",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"p",
".",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"p",
".",
"GetName",
"(",
")",
",",
"p",
".",
"GetPid",
"(",
")",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Stop sends the SIGTERM signal to stop given process | [
"Stop",
"sends",
"the",
"SIGTERM",
"signal",
"to",
"stop",
"given",
"process"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/processmanager/process.go#L136-L142 |
4,603 | ligato/cn-infra | processmanager/process.go | StopAndWait | func (p *Process) StopAndWait() (*os.ProcessState, error) {
if err := p.stopProcess(); err != nil {
return nil, err
}
state, err := p.waitOnProcess()
if err != nil {
return nil, errors.Errorf("process exit with error: %v", err)
}
p.log.Debugf("Process %s was stopped (last PID: %d)", p.GetName(), p.GetPid())
return state, nil
} | go | func (p *Process) StopAndWait() (*os.ProcessState, error) {
if err := p.stopProcess(); err != nil {
return nil, err
}
state, err := p.waitOnProcess()
if err != nil {
return nil, errors.Errorf("process exit with error: %v", err)
}
p.log.Debugf("Process %s was stopped (last PID: %d)", p.GetName(), p.GetPid())
return state, nil
} | [
"func",
"(",
"p",
"*",
"Process",
")",
"StopAndWait",
"(",
")",
"(",
"*",
"os",
".",
"ProcessState",
",",
"error",
")",
"{",
"if",
"err",
":=",
"p",
".",
"stopProcess",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"state",
",",
"err",
":=",
"p",
".",
"waitOnProcess",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"p",
".",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"p",
".",
"GetName",
"(",
")",
",",
"p",
".",
"GetPid",
"(",
")",
")",
"\n",
"return",
"state",
",",
"nil",
"\n",
"}"
] | // StopAndWait sends the SIGTERM signal to stop given process and waits until it is completed | [
"StopAndWait",
"sends",
"the",
"SIGTERM",
"signal",
"to",
"stop",
"given",
"process",
"and",
"waits",
"until",
"it",
"is",
"completed"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/processmanager/process.go#L145-L155 |
4,604 | ligato/cn-infra | processmanager/process.go | Kill | func (p *Process) Kill() error {
if err := p.forceStopProcess(); err != nil {
return err
}
p.log.Debugf("Process %s was forced to stop (last PID: %d)", p.GetName(), p.GetPid())
return nil
} | go | func (p *Process) Kill() error {
if err := p.forceStopProcess(); err != nil {
return err
}
p.log.Debugf("Process %s was forced to stop (last PID: %d)", p.GetName(), p.GetPid())
return nil
} | [
"func",
"(",
"p",
"*",
"Process",
")",
"Kill",
"(",
")",
"error",
"{",
"if",
"err",
":=",
"p",
".",
"forceStopProcess",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"p",
".",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"p",
".",
"GetName",
"(",
")",
",",
"p",
".",
"GetPid",
"(",
")",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Kill sends the SIGKILL signal to force stop given process | [
"Kill",
"sends",
"the",
"SIGKILL",
"signal",
"to",
"force",
"stop",
"given",
"process"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/processmanager/process.go#L158-L164 |
4,605 | ligato/cn-infra | processmanager/process.go | Signal | func (p *Process) Signal(signal os.Signal) error {
return p.signalToProcess(signal)
} | go | func (p *Process) Signal(signal os.Signal) error {
return p.signalToProcess(signal)
} | [
"func",
"(",
"p",
"*",
"Process",
")",
"Signal",
"(",
"signal",
"os",
".",
"Signal",
")",
"error",
"{",
"return",
"p",
".",
"signalToProcess",
"(",
"signal",
")",
"\n",
"}"
] | // Signal sends custom signal to the process | [
"Signal",
"sends",
"custom",
"signal",
"to",
"the",
"process"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/processmanager/process.go#L172-L174 |
4,606 | ligato/cn-infra | processmanager/process.go | GetPid | func (p *Process) GetPid() int {
if p.command != nil && p.command.Process != nil {
return p.command.Process.Pid
}
return p.status.Pid
} | go | func (p *Process) GetPid() int {
if p.command != nil && p.command.Process != nil {
return p.command.Process.Pid
}
return p.status.Pid
} | [
"func",
"(",
"p",
"*",
"Process",
")",
"GetPid",
"(",
")",
"int",
"{",
"if",
"p",
".",
"command",
"!=",
"nil",
"&&",
"p",
".",
"command",
".",
"Process",
"!=",
"nil",
"{",
"return",
"p",
".",
"command",
".",
"Process",
".",
"Pid",
"\n",
"}",
"\n",
"return",
"p",
".",
"status",
".",
"Pid",
"\n",
"}"
] | // GetPid returns process ID | [
"GetPid",
"returns",
"process",
"ID"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/processmanager/process.go#L187-L192 |
4,607 | ligato/cn-infra | processmanager/process.go | GetArguments | func (p *Process) GetArguments() []string {
if p.options.args == nil {
return []string{}
}
return p.options.args
} | go | func (p *Process) GetArguments() []string {
if p.options.args == nil {
return []string{}
}
return p.options.args
} | [
"func",
"(",
"p",
"*",
"Process",
")",
"GetArguments",
"(",
")",
"[",
"]",
"string",
"{",
"if",
"p",
".",
"options",
".",
"args",
"==",
"nil",
"{",
"return",
"[",
"]",
"string",
"{",
"}",
"\n",
"}",
"\n",
"return",
"p",
".",
"options",
".",
"args",
"\n",
"}"
] | // GetArguments returns arguments process was started with, if any. May be empty also for attached processes | [
"GetArguments",
"returns",
"arguments",
"process",
"was",
"started",
"with",
"if",
"any",
".",
"May",
"be",
"empty",
"also",
"for",
"attached",
"processes"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/processmanager/process.go#L200-L205 |
4,608 | ligato/cn-infra | processmanager/process.go | GetStatus | func (p *Process) GetStatus(pid int) (statusFile *status.File, err error) {
p.status, err = p.sh.ReadStatusFromPID(pid)
if err != nil {
return &status.File{}, errors.Errorf("failed to read status file for process ID %d: %v", pid, err)
}
return p.status, nil
} | go | func (p *Process) GetStatus(pid int) (statusFile *status.File, err error) {
p.status, err = p.sh.ReadStatusFromPID(pid)
if err != nil {
return &status.File{}, errors.Errorf("failed to read status file for process ID %d: %v", pid, err)
}
return p.status, nil
} | [
"func",
"(",
"p",
"*",
"Process",
")",
"GetStatus",
"(",
"pid",
"int",
")",
"(",
"statusFile",
"*",
"status",
".",
"File",
",",
"err",
"error",
")",
"{",
"p",
".",
"status",
",",
"err",
"=",
"p",
".",
"sh",
".",
"ReadStatusFromPID",
"(",
"pid",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"&",
"status",
".",
"File",
"{",
"}",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"pid",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"p",
".",
"status",
",",
"nil",
"\n",
"}"
] | // GetStatus updates actual process status and returns status file | [
"GetStatus",
"updates",
"actual",
"process",
"status",
"and",
"returns",
"status",
"file"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/processmanager/process.go#L208-L214 |
4,609 | ligato/cn-infra | processmanager/process.go | GetNotificationChan | func (p *Process) GetNotificationChan() <-chan status.ProcessStatus {
if p.options != nil && p.options.notifyChan != nil {
return p.options.notifyChan
}
return nil
} | go | func (p *Process) GetNotificationChan() <-chan status.ProcessStatus {
if p.options != nil && p.options.notifyChan != nil {
return p.options.notifyChan
}
return nil
} | [
"func",
"(",
"p",
"*",
"Process",
")",
"GetNotificationChan",
"(",
")",
"<-",
"chan",
"status",
".",
"ProcessStatus",
"{",
"if",
"p",
".",
"options",
"!=",
"nil",
"&&",
"p",
".",
"options",
".",
"notifyChan",
"!=",
"nil",
"{",
"return",
"p",
".",
"options",
".",
"notifyChan",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // GetNotificationChan returns channel listening on notifications about process status changes | [
"GetNotificationChan",
"returns",
"channel",
"listening",
"on",
"notifications",
"about",
"process",
"status",
"changes"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/processmanager/process.go#L217-L222 |
4,610 | ligato/cn-infra | processmanager/process.go | GetUptime | func (p *Process) GetUptime() time.Duration {
if p.startTime.Nanosecond() == 0 {
return 0
}
return time.Since(p.startTime)
} | go | func (p *Process) GetUptime() time.Duration {
if p.startTime.Nanosecond() == 0 {
return 0
}
return time.Since(p.startTime)
} | [
"func",
"(",
"p",
"*",
"Process",
")",
"GetUptime",
"(",
")",
"time",
".",
"Duration",
"{",
"if",
"p",
".",
"startTime",
".",
"Nanosecond",
"(",
")",
"==",
"0",
"{",
"return",
"0",
"\n",
"}",
"\n",
"return",
"time",
".",
"Since",
"(",
"p",
".",
"startTime",
")",
"\n",
"}"
] | // GetUptime returns process uptime since the last start | [
"GetUptime",
"returns",
"process",
"uptime",
"since",
"the",
"last",
"start"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/processmanager/process.go#L230-L235 |
4,611 | ligato/cn-infra | db/keyval/filedb/client.go | NewClient | func NewClient(cfgPaths []string, statusPath string, dcs []decoder.API, fsh filesystem.API, log logging.Logger) (*Client, error) {
// Init client object
c := &Client{
cfgPaths: cfgPaths,
statusPath: statusPath,
fsHandler: fsh,
watchers: make(map[string]chan keyedData),
db: database.NewDbClient(),
decoders: dcs,
log: log,
}
// Init filesystem handler
filePaths, err := c.fsHandler.GetFileNames(c.cfgPaths)
if err != nil {
return nil, errors.Errorf("failed to read files from provided paths: %v", err)
}
// Decode initial configuration
for _, filePath := range filePaths {
if dc := c.getFileDecoder(filePath); dc != nil {
byteFile, err := c.fsHandler.ReadFile(filePath)
if err != nil {
return nil, errors.Errorf("failed to read file %s content: %v", filePath, err)
}
fileEntries, err := dc.Decode(byteFile)
file := &decoder.File{Path: filePath, Data: fileEntries}
if err != nil {
return nil, errors.Errorf("failed to decode file %s: %v", filePath, err)
}
// Put all the configuration to the database
for _, data := range file.Data {
c.db.Add(file.Path, &decoder.FileDataEntry{Key: data.Key, Value: data.Value})
}
}
}
// Validate and prepare the status file and decoder
if c.statusPath != "" {
c.statusDecoder = c.getFileDecoder(c.statusPath)
if c.statusDecoder == nil {
return nil, errors.Errorf("failed to get decoder for status file (unknown extension) %s: %v", c.statusPath, err)
}
filePath, err := c.fsHandler.GetFileNames([]string{c.statusPath})
if err != nil {
return nil, errors.Errorf("failed to read status file: %v", err)
}
// Expected is at most single entry
if len(filePath) == 0 {
if err := c.fsHandler.CreateFile(c.statusPath); err != nil {
return nil, errors.Errorf("failed to create status file: %v", err)
}
} else if len(filePath) > 1 {
return nil, errors.Errorf("failed to process status file, unexpected processing output: %v", err)
}
}
return c, nil
} | go | func NewClient(cfgPaths []string, statusPath string, dcs []decoder.API, fsh filesystem.API, log logging.Logger) (*Client, error) {
// Init client object
c := &Client{
cfgPaths: cfgPaths,
statusPath: statusPath,
fsHandler: fsh,
watchers: make(map[string]chan keyedData),
db: database.NewDbClient(),
decoders: dcs,
log: log,
}
// Init filesystem handler
filePaths, err := c.fsHandler.GetFileNames(c.cfgPaths)
if err != nil {
return nil, errors.Errorf("failed to read files from provided paths: %v", err)
}
// Decode initial configuration
for _, filePath := range filePaths {
if dc := c.getFileDecoder(filePath); dc != nil {
byteFile, err := c.fsHandler.ReadFile(filePath)
if err != nil {
return nil, errors.Errorf("failed to read file %s content: %v", filePath, err)
}
fileEntries, err := dc.Decode(byteFile)
file := &decoder.File{Path: filePath, Data: fileEntries}
if err != nil {
return nil, errors.Errorf("failed to decode file %s: %v", filePath, err)
}
// Put all the configuration to the database
for _, data := range file.Data {
c.db.Add(file.Path, &decoder.FileDataEntry{Key: data.Key, Value: data.Value})
}
}
}
// Validate and prepare the status file and decoder
if c.statusPath != "" {
c.statusDecoder = c.getFileDecoder(c.statusPath)
if c.statusDecoder == nil {
return nil, errors.Errorf("failed to get decoder for status file (unknown extension) %s: %v", c.statusPath, err)
}
filePath, err := c.fsHandler.GetFileNames([]string{c.statusPath})
if err != nil {
return nil, errors.Errorf("failed to read status file: %v", err)
}
// Expected is at most single entry
if len(filePath) == 0 {
if err := c.fsHandler.CreateFile(c.statusPath); err != nil {
return nil, errors.Errorf("failed to create status file: %v", err)
}
} else if len(filePath) > 1 {
return nil, errors.Errorf("failed to process status file, unexpected processing output: %v", err)
}
}
return c, nil
} | [
"func",
"NewClient",
"(",
"cfgPaths",
"[",
"]",
"string",
",",
"statusPath",
"string",
",",
"dcs",
"[",
"]",
"decoder",
".",
"API",
",",
"fsh",
"filesystem",
".",
"API",
",",
"log",
"logging",
".",
"Logger",
")",
"(",
"*",
"Client",
",",
"error",
")",
"{",
"// Init client object",
"c",
":=",
"&",
"Client",
"{",
"cfgPaths",
":",
"cfgPaths",
",",
"statusPath",
":",
"statusPath",
",",
"fsHandler",
":",
"fsh",
",",
"watchers",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"chan",
"keyedData",
")",
",",
"db",
":",
"database",
".",
"NewDbClient",
"(",
")",
",",
"decoders",
":",
"dcs",
",",
"log",
":",
"log",
",",
"}",
"\n\n",
"// Init filesystem handler",
"filePaths",
",",
"err",
":=",
"c",
".",
"fsHandler",
".",
"GetFileNames",
"(",
"c",
".",
"cfgPaths",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"// Decode initial configuration",
"for",
"_",
",",
"filePath",
":=",
"range",
"filePaths",
"{",
"if",
"dc",
":=",
"c",
".",
"getFileDecoder",
"(",
"filePath",
")",
";",
"dc",
"!=",
"nil",
"{",
"byteFile",
",",
"err",
":=",
"c",
".",
"fsHandler",
".",
"ReadFile",
"(",
"filePath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"filePath",
",",
"err",
")",
"\n",
"}",
"\n",
"fileEntries",
",",
"err",
":=",
"dc",
".",
"Decode",
"(",
"byteFile",
")",
"\n",
"file",
":=",
"&",
"decoder",
".",
"File",
"{",
"Path",
":",
"filePath",
",",
"Data",
":",
"fileEntries",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"filePath",
",",
"err",
")",
"\n",
"}",
"\n",
"// Put all the configuration to the database",
"for",
"_",
",",
"data",
":=",
"range",
"file",
".",
"Data",
"{",
"c",
".",
"db",
".",
"Add",
"(",
"file",
".",
"Path",
",",
"&",
"decoder",
".",
"FileDataEntry",
"{",
"Key",
":",
"data",
".",
"Key",
",",
"Value",
":",
"data",
".",
"Value",
"}",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"// Validate and prepare the status file and decoder",
"if",
"c",
".",
"statusPath",
"!=",
"\"",
"\"",
"{",
"c",
".",
"statusDecoder",
"=",
"c",
".",
"getFileDecoder",
"(",
"c",
".",
"statusPath",
")",
"\n",
"if",
"c",
".",
"statusDecoder",
"==",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"c",
".",
"statusPath",
",",
"err",
")",
"\n",
"}",
"\n",
"filePath",
",",
"err",
":=",
"c",
".",
"fsHandler",
".",
"GetFileNames",
"(",
"[",
"]",
"string",
"{",
"c",
".",
"statusPath",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"// Expected is at most single entry",
"if",
"len",
"(",
"filePath",
")",
"==",
"0",
"{",
"if",
"err",
":=",
"c",
".",
"fsHandler",
".",
"CreateFile",
"(",
"c",
".",
"statusPath",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"else",
"if",
"len",
"(",
"filePath",
")",
">",
"1",
"{",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"c",
",",
"nil",
"\n",
"}"
] | // NewClient initializes file watcher, database and registers paths provided via plugin configuration file | [
"NewClient",
"initializes",
"file",
"watcher",
"database",
"and",
"registers",
"paths",
"provided",
"via",
"plugin",
"configuration",
"file"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/client.go#L69-L125 |
4,612 | ligato/cn-infra | db/keyval/filedb/client.go | GetDataForFile | func (c *Client) GetDataForFile(path string) []*decoder.FileDataEntry {
return c.db.GetDataForFile(path)
} | go | func (c *Client) GetDataForFile(path string) []*decoder.FileDataEntry {
return c.db.GetDataForFile(path)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"GetDataForFile",
"(",
"path",
"string",
")",
"[",
"]",
"*",
"decoder",
".",
"FileDataEntry",
"{",
"return",
"c",
".",
"db",
".",
"GetDataForFile",
"(",
"path",
")",
"\n",
"}"
] | // GetDataForFile returns data gor given file | [
"GetDataForFile",
"returns",
"data",
"gor",
"given",
"file"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/client.go#L133-L135 |
4,613 | ligato/cn-infra | db/keyval/filedb/client.go | GetDataForKey | func (c *Client) GetDataForKey(key string) (*decoder.FileDataEntry, bool) {
return c.db.GetDataForKey(key)
} | go | func (c *Client) GetDataForKey(key string) (*decoder.FileDataEntry, bool) {
return c.db.GetDataForKey(key)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"GetDataForKey",
"(",
"key",
"string",
")",
"(",
"*",
"decoder",
".",
"FileDataEntry",
",",
"bool",
")",
"{",
"return",
"c",
".",
"db",
".",
"GetDataForKey",
"(",
"key",
")",
"\n",
"}"
] | // GetDataForKey returns data gor given file | [
"GetDataForKey",
"returns",
"data",
"gor",
"given",
"file"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/client.go#L138-L140 |
4,614 | ligato/cn-infra | db/keyval/filedb/client.go | Put | func (c *Client) Put(key string, data []byte, opts ...datasync.PutOption) error {
newEntry := &decoder.FileDataEntry{Key: key, Value: data}
statusDataEntries := c.db.GetDataForFile(c.statusPath)
// Add/update data
var updated bool
for _, statusDataEntry := range statusDataEntries {
if statusDataEntry.Key == key {
statusDataEntry.Value = data
updated = true
break
}
}
if !updated {
statusDataEntries = append(statusDataEntries, newEntry)
}
c.db.Add(c.statusPath, newEntry)
// Encode and write
stFileEntries, err := c.statusDecoder.Encode(statusDataEntries)
if err != nil {
return errors.Errorf("failed to write status to fileDB: unable to encode status file %s: %v", c.statusPath, err)
}
err = c.fsHandler.WriteFile(c.statusPath, stFileEntries)
if err != nil {
return errors.Errorf("failed to write status %s to fileDB: %v", c.statusPath, err)
}
return nil
} | go | func (c *Client) Put(key string, data []byte, opts ...datasync.PutOption) error {
newEntry := &decoder.FileDataEntry{Key: key, Value: data}
statusDataEntries := c.db.GetDataForFile(c.statusPath)
// Add/update data
var updated bool
for _, statusDataEntry := range statusDataEntries {
if statusDataEntry.Key == key {
statusDataEntry.Value = data
updated = true
break
}
}
if !updated {
statusDataEntries = append(statusDataEntries, newEntry)
}
c.db.Add(c.statusPath, newEntry)
// Encode and write
stFileEntries, err := c.statusDecoder.Encode(statusDataEntries)
if err != nil {
return errors.Errorf("failed to write status to fileDB: unable to encode status file %s: %v", c.statusPath, err)
}
err = c.fsHandler.WriteFile(c.statusPath, stFileEntries)
if err != nil {
return errors.Errorf("failed to write status %s to fileDB: %v", c.statusPath, err)
}
return nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Put",
"(",
"key",
"string",
",",
"data",
"[",
"]",
"byte",
",",
"opts",
"...",
"datasync",
".",
"PutOption",
")",
"error",
"{",
"newEntry",
":=",
"&",
"decoder",
".",
"FileDataEntry",
"{",
"Key",
":",
"key",
",",
"Value",
":",
"data",
"}",
"\n",
"statusDataEntries",
":=",
"c",
".",
"db",
".",
"GetDataForFile",
"(",
"c",
".",
"statusPath",
")",
"\n",
"// Add/update data",
"var",
"updated",
"bool",
"\n",
"for",
"_",
",",
"statusDataEntry",
":=",
"range",
"statusDataEntries",
"{",
"if",
"statusDataEntry",
".",
"Key",
"==",
"key",
"{",
"statusDataEntry",
".",
"Value",
"=",
"data",
"\n",
"updated",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"updated",
"{",
"statusDataEntries",
"=",
"append",
"(",
"statusDataEntries",
",",
"newEntry",
")",
"\n",
"}",
"\n",
"c",
".",
"db",
".",
"Add",
"(",
"c",
".",
"statusPath",
",",
"newEntry",
")",
"\n",
"// Encode and write",
"stFileEntries",
",",
"err",
":=",
"c",
".",
"statusDecoder",
".",
"Encode",
"(",
"statusDataEntries",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"c",
".",
"statusPath",
",",
"err",
")",
"\n",
"}",
"\n",
"err",
"=",
"c",
".",
"fsHandler",
".",
"WriteFile",
"(",
"c",
".",
"statusPath",
",",
"stFileEntries",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"c",
".",
"statusPath",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Put reads status file, add data to it and performs write | [
"Put",
"reads",
"status",
"file",
"add",
"data",
"to",
"it",
"and",
"performs",
"write"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/client.go#L165-L191 |
4,615 | ligato/cn-infra | db/keyval/filedb/client.go | GetValue | func (c *Client) GetValue(key string) (data []byte, found bool, revision int64, err error) {
var entry *decoder.FileDataEntry
entry, found = c.db.GetDataForKey(key)
data = entry.Value
return
} | go | func (c *Client) GetValue(key string) (data []byte, found bool, revision int64, err error) {
var entry *decoder.FileDataEntry
entry, found = c.db.GetDataForKey(key)
data = entry.Value
return
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"GetValue",
"(",
"key",
"string",
")",
"(",
"data",
"[",
"]",
"byte",
",",
"found",
"bool",
",",
"revision",
"int64",
",",
"err",
"error",
")",
"{",
"var",
"entry",
"*",
"decoder",
".",
"FileDataEntry",
"\n",
"entry",
",",
"found",
"=",
"c",
".",
"db",
".",
"GetDataForKey",
"(",
"key",
")",
"\n",
"data",
"=",
"entry",
".",
"Value",
"\n",
"return",
"\n",
"}"
] | // GetValue returns a value for given key | [
"GetValue",
"returns",
"a",
"value",
"for",
"given",
"key"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/client.go#L200-L205 |
4,616 | ligato/cn-infra | db/keyval/filedb/client.go | ListValues | func (c *Client) ListValues(prefix string) (keyval.BytesKeyValIterator, error) {
keyValues := c.db.GetDataForPrefix(prefix)
data := make([]*decoder.FileDataEntry, 0, len(keyValues))
for _, entry := range keyValues {
data = append(data, &decoder.FileDataEntry{
Key: entry.Key,
Value: entry.Value,
})
}
return &bytesKeyValIterator{len: len(data), data: data}, nil
} | go | func (c *Client) ListValues(prefix string) (keyval.BytesKeyValIterator, error) {
keyValues := c.db.GetDataForPrefix(prefix)
data := make([]*decoder.FileDataEntry, 0, len(keyValues))
for _, entry := range keyValues {
data = append(data, &decoder.FileDataEntry{
Key: entry.Key,
Value: entry.Value,
})
}
return &bytesKeyValIterator{len: len(data), data: data}, nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"ListValues",
"(",
"prefix",
"string",
")",
"(",
"keyval",
".",
"BytesKeyValIterator",
",",
"error",
")",
"{",
"keyValues",
":=",
"c",
".",
"db",
".",
"GetDataForPrefix",
"(",
"prefix",
")",
"\n",
"data",
":=",
"make",
"(",
"[",
"]",
"*",
"decoder",
".",
"FileDataEntry",
",",
"0",
",",
"len",
"(",
"keyValues",
")",
")",
"\n",
"for",
"_",
",",
"entry",
":=",
"range",
"keyValues",
"{",
"data",
"=",
"append",
"(",
"data",
",",
"&",
"decoder",
".",
"FileDataEntry",
"{",
"Key",
":",
"entry",
".",
"Key",
",",
"Value",
":",
"entry",
".",
"Value",
",",
"}",
")",
"\n",
"}",
"\n",
"return",
"&",
"bytesKeyValIterator",
"{",
"len",
":",
"len",
"(",
"data",
")",
",",
"data",
":",
"data",
"}",
",",
"nil",
"\n",
"}"
] | // ListValues returns a list of values for given prefix | [
"ListValues",
"returns",
"a",
"list",
"of",
"values",
"for",
"given",
"prefix"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/client.go#L208-L218 |
4,617 | ligato/cn-infra | db/keyval/filedb/client.go | ListKeys | func (c *Client) ListKeys(prefix string) (keyval.BytesKeyIterator, error) {
entries := c.db.GetDataForPrefix(prefix)
var keysWithoutPrefix []string
for _, entry := range entries {
keysWithoutPrefix = append(keysWithoutPrefix, entry.Key)
}
return &bytesKeyIterator{len: len(keysWithoutPrefix), keys: keysWithoutPrefix, prefix: prefix}, nil
} | go | func (c *Client) ListKeys(prefix string) (keyval.BytesKeyIterator, error) {
entries := c.db.GetDataForPrefix(prefix)
var keysWithoutPrefix []string
for _, entry := range entries {
keysWithoutPrefix = append(keysWithoutPrefix, entry.Key)
}
return &bytesKeyIterator{len: len(keysWithoutPrefix), keys: keysWithoutPrefix, prefix: prefix}, nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"ListKeys",
"(",
"prefix",
"string",
")",
"(",
"keyval",
".",
"BytesKeyIterator",
",",
"error",
")",
"{",
"entries",
":=",
"c",
".",
"db",
".",
"GetDataForPrefix",
"(",
"prefix",
")",
"\n",
"var",
"keysWithoutPrefix",
"[",
"]",
"string",
"\n",
"for",
"_",
",",
"entry",
":=",
"range",
"entries",
"{",
"keysWithoutPrefix",
"=",
"append",
"(",
"keysWithoutPrefix",
",",
"entry",
".",
"Key",
")",
"\n",
"}",
"\n",
"return",
"&",
"bytesKeyIterator",
"{",
"len",
":",
"len",
"(",
"keysWithoutPrefix",
")",
",",
"keys",
":",
"keysWithoutPrefix",
",",
"prefix",
":",
"prefix",
"}",
",",
"nil",
"\n",
"}"
] | // ListKeys returns a set of keys for given prefix | [
"ListKeys",
"returns",
"a",
"set",
"of",
"keys",
"for",
"given",
"prefix"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/client.go#L221-L228 |
4,618 | ligato/cn-infra | db/keyval/filedb/client.go | Delete | func (c *Client) Delete(key string, opts ...datasync.DelOption) (existed bool, err error) {
c.log.Warnf("deleting configuration from fileDB is currently not allowed")
return false, nil
} | go | func (c *Client) Delete(key string, opts ...datasync.DelOption) (existed bool, err error) {
c.log.Warnf("deleting configuration from fileDB is currently not allowed")
return false, nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Delete",
"(",
"key",
"string",
",",
"opts",
"...",
"datasync",
".",
"DelOption",
")",
"(",
"existed",
"bool",
",",
"err",
"error",
")",
"{",
"c",
".",
"log",
".",
"Warnf",
"(",
"\"",
"\"",
")",
"\n",
"return",
"false",
",",
"nil",
"\n",
"}"
] | // Delete is not allowed for fileDB, configuration file is read-only | [
"Delete",
"is",
"not",
"allowed",
"for",
"fileDB",
"configuration",
"file",
"is",
"read",
"-",
"only"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/client.go#L231-L234 |
4,619 | ligato/cn-infra | db/keyval/filedb/client.go | Watch | func (c *Client) Watch(resp func(response keyval.BytesWatchResp), closeChan chan string, keys ...string) error {
c.Lock()
defer c.Unlock()
for _, key := range keys {
dc := make(chan keyedData)
go c.watch(resp, dc, closeChan, key)
c.watchers[key] = dc
}
return nil
} | go | func (c *Client) Watch(resp func(response keyval.BytesWatchResp), closeChan chan string, keys ...string) error {
c.Lock()
defer c.Unlock()
for _, key := range keys {
dc := make(chan keyedData)
go c.watch(resp, dc, closeChan, key)
c.watchers[key] = dc
}
return nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Watch",
"(",
"resp",
"func",
"(",
"response",
"keyval",
".",
"BytesWatchResp",
")",
",",
"closeChan",
"chan",
"string",
",",
"keys",
"...",
"string",
")",
"error",
"{",
"c",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"Unlock",
"(",
")",
"\n\n",
"for",
"_",
",",
"key",
":=",
"range",
"keys",
"{",
"dc",
":=",
"make",
"(",
"chan",
"keyedData",
")",
"\n",
"go",
"c",
".",
"watch",
"(",
"resp",
",",
"dc",
",",
"closeChan",
",",
"key",
")",
"\n",
"c",
".",
"watchers",
"[",
"key",
"]",
"=",
"dc",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Watch starts single watcher for every key prefix. Every watcher listens on its own data channel. | [
"Watch",
"starts",
"single",
"watcher",
"for",
"every",
"key",
"prefix",
".",
"Every",
"watcher",
"listens",
"on",
"its",
"own",
"data",
"channel",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/client.go#L237-L248 |
4,620 | ligato/cn-infra | db/keyval/filedb/client.go | Close | func (c *Client) Close() error {
if c.fsHandler != nil {
return c.fsHandler.Close()
}
return nil
} | go | func (c *Client) Close() error {
if c.fsHandler != nil {
return c.fsHandler.Close()
}
return nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Close",
"(",
")",
"error",
"{",
"if",
"c",
".",
"fsHandler",
"!=",
"nil",
"{",
"return",
"c",
".",
"fsHandler",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Close closes all readers | [
"Close",
"closes",
"all",
"readers"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/client.go#L251-L256 |
4,621 | ligato/cn-infra | db/keyval/filedb/client.go | watch | func (c *Client) watch(resp func(response keyval.BytesWatchResp), dataChan chan keyedData, closeChan chan string, key string) {
for {
select {
case keyedData, ok := <-dataChan:
if !ok {
return
}
if keyedData.Op == datasync.Delete || !bytes.Equal(keyedData.PrevValue, keyedData.Value) {
resp(&keyedData.watchResp)
}
case <-closeChan:
return
}
}
} | go | func (c *Client) watch(resp func(response keyval.BytesWatchResp), dataChan chan keyedData, closeChan chan string, key string) {
for {
select {
case keyedData, ok := <-dataChan:
if !ok {
return
}
if keyedData.Op == datasync.Delete || !bytes.Equal(keyedData.PrevValue, keyedData.Value) {
resp(&keyedData.watchResp)
}
case <-closeChan:
return
}
}
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"watch",
"(",
"resp",
"func",
"(",
"response",
"keyval",
".",
"BytesWatchResp",
")",
",",
"dataChan",
"chan",
"keyedData",
",",
"closeChan",
"chan",
"string",
",",
"key",
"string",
")",
"{",
"for",
"{",
"select",
"{",
"case",
"keyedData",
",",
"ok",
":=",
"<-",
"dataChan",
":",
"if",
"!",
"ok",
"{",
"return",
"\n",
"}",
"\n",
"if",
"keyedData",
".",
"Op",
"==",
"datasync",
".",
"Delete",
"||",
"!",
"bytes",
".",
"Equal",
"(",
"keyedData",
".",
"PrevValue",
",",
"keyedData",
".",
"Value",
")",
"{",
"resp",
"(",
"&",
"keyedData",
".",
"watchResp",
")",
"\n",
"}",
"\n",
"case",
"<-",
"closeChan",
":",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Awaits changes from data channel, prepares responses and sends them to the response function | [
"Awaits",
"changes",
"from",
"data",
"channel",
"prepares",
"responses",
"and",
"sends",
"them",
"to",
"the",
"response",
"function"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/client.go#L259-L273 |
4,622 | ligato/cn-infra | db/keyval/filedb/client.go | eventWatcher | func (c *Client) eventWatcher() {
c.fsHandler.Watch(c.cfgPaths, c.onEvent, c.onClose)
} | go | func (c *Client) eventWatcher() {
c.fsHandler.Watch(c.cfgPaths, c.onEvent, c.onClose)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"eventWatcher",
"(",
")",
"{",
"c",
".",
"fsHandler",
".",
"Watch",
"(",
"c",
".",
"cfgPaths",
",",
"c",
".",
"onEvent",
",",
"c",
".",
"onClose",
")",
"\n",
"}"
] | // Event watcher starts file system watcher for every reader available. | [
"Event",
"watcher",
"starts",
"file",
"system",
"watcher",
"for",
"every",
"reader",
"available",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/client.go#L276-L278 |
4,623 | ligato/cn-infra | db/keyval/filedb/client.go | onEvent | func (c *Client) onEvent(event fsnotify.Event) {
// If file was removed, delete all configuration associated with it. Do the same action for
// rename, following action will be create with the new name which re-applies the configuration
// (if new name is in scope of the defined path)
if (event.Op == fsnotify.Rename || event.Op == fsnotify.Remove) && !c.fsHandler.FileExists(event.Name) {
entries := c.db.GetDataForFile(event.Name)
for _, entry := range entries {
// Value from DB does not need to be checked
keyed := keyedData{
path: event.Name,
watchResp: watchResp{Op: datasync.Delete, Key: entry.Key, Value: nil, PrevValue: entry.Value},
}
c.sendToChannel(keyed)
c.db.DeleteFile(event.Name)
}
return
}
// Read data from file
dc := c.getFileDecoder(event.Name)
if dc == nil {
return
}
byteFile, err := c.fsHandler.ReadFile(event.Name)
if err != nil {
c.log.Errorf("failed to process filesystem event: file cannot be read %s: %v", event.Name, err)
return
}
decodedFileEntries, err := dc.Decode(byteFile)
if err != nil {
c.log.Errorf("failed to process filesystem event: file cannot be decoded %s: %v", event.Name, err)
return
}
file := &decoder.File{Path: event.Name, Data: decodedFileEntries}
latestFile := &decoder.File{Path: event.Name, Data: c.db.GetDataForFile(event.Name)}
changed, removed := file.CompareTo(latestFile)
// Update database and propagate data to channel
for _, fileDataEntry := range removed {
keyed := keyedData{
path: event.Name,
watchResp: watchResp{Op: datasync.Delete, Key: fileDataEntry.Key, Value: nil, PrevValue: fileDataEntry.Value},
}
c.sendToChannel(keyed)
c.db.Delete(event.Name, keyed.Key)
}
for _, fileDataEntry := range changed {
// Get last key-val configuration item if exists
var prevVal []byte
if prevValEntry, ok := c.db.GetDataForKey(fileDataEntry.Key); ok {
prevVal = prevValEntry.Value
}
keyed := keyedData{
path: event.Name,
watchResp: watchResp{Op: datasync.Put, Key: fileDataEntry.Key, Value: fileDataEntry.Value, PrevValue: prevVal},
}
c.sendToChannel(keyed)
c.db.Add(event.Name, &decoder.FileDataEntry{
Key: keyed.Key,
Value: keyed.Value,
})
}
} | go | func (c *Client) onEvent(event fsnotify.Event) {
// If file was removed, delete all configuration associated with it. Do the same action for
// rename, following action will be create with the new name which re-applies the configuration
// (if new name is in scope of the defined path)
if (event.Op == fsnotify.Rename || event.Op == fsnotify.Remove) && !c.fsHandler.FileExists(event.Name) {
entries := c.db.GetDataForFile(event.Name)
for _, entry := range entries {
// Value from DB does not need to be checked
keyed := keyedData{
path: event.Name,
watchResp: watchResp{Op: datasync.Delete, Key: entry.Key, Value: nil, PrevValue: entry.Value},
}
c.sendToChannel(keyed)
c.db.DeleteFile(event.Name)
}
return
}
// Read data from file
dc := c.getFileDecoder(event.Name)
if dc == nil {
return
}
byteFile, err := c.fsHandler.ReadFile(event.Name)
if err != nil {
c.log.Errorf("failed to process filesystem event: file cannot be read %s: %v", event.Name, err)
return
}
decodedFileEntries, err := dc.Decode(byteFile)
if err != nil {
c.log.Errorf("failed to process filesystem event: file cannot be decoded %s: %v", event.Name, err)
return
}
file := &decoder.File{Path: event.Name, Data: decodedFileEntries}
latestFile := &decoder.File{Path: event.Name, Data: c.db.GetDataForFile(event.Name)}
changed, removed := file.CompareTo(latestFile)
// Update database and propagate data to channel
for _, fileDataEntry := range removed {
keyed := keyedData{
path: event.Name,
watchResp: watchResp{Op: datasync.Delete, Key: fileDataEntry.Key, Value: nil, PrevValue: fileDataEntry.Value},
}
c.sendToChannel(keyed)
c.db.Delete(event.Name, keyed.Key)
}
for _, fileDataEntry := range changed {
// Get last key-val configuration item if exists
var prevVal []byte
if prevValEntry, ok := c.db.GetDataForKey(fileDataEntry.Key); ok {
prevVal = prevValEntry.Value
}
keyed := keyedData{
path: event.Name,
watchResp: watchResp{Op: datasync.Put, Key: fileDataEntry.Key, Value: fileDataEntry.Value, PrevValue: prevVal},
}
c.sendToChannel(keyed)
c.db.Add(event.Name, &decoder.FileDataEntry{
Key: keyed.Key,
Value: keyed.Value,
})
}
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"onEvent",
"(",
"event",
"fsnotify",
".",
"Event",
")",
"{",
"// If file was removed, delete all configuration associated with it. Do the same action for",
"// rename, following action will be create with the new name which re-applies the configuration",
"// (if new name is in scope of the defined path)",
"if",
"(",
"event",
".",
"Op",
"==",
"fsnotify",
".",
"Rename",
"||",
"event",
".",
"Op",
"==",
"fsnotify",
".",
"Remove",
")",
"&&",
"!",
"c",
".",
"fsHandler",
".",
"FileExists",
"(",
"event",
".",
"Name",
")",
"{",
"entries",
":=",
"c",
".",
"db",
".",
"GetDataForFile",
"(",
"event",
".",
"Name",
")",
"\n",
"for",
"_",
",",
"entry",
":=",
"range",
"entries",
"{",
"// Value from DB does not need to be checked",
"keyed",
":=",
"keyedData",
"{",
"path",
":",
"event",
".",
"Name",
",",
"watchResp",
":",
"watchResp",
"{",
"Op",
":",
"datasync",
".",
"Delete",
",",
"Key",
":",
"entry",
".",
"Key",
",",
"Value",
":",
"nil",
",",
"PrevValue",
":",
"entry",
".",
"Value",
"}",
",",
"}",
"\n",
"c",
".",
"sendToChannel",
"(",
"keyed",
")",
"\n",
"c",
".",
"db",
".",
"DeleteFile",
"(",
"event",
".",
"Name",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Read data from file",
"dc",
":=",
"c",
".",
"getFileDecoder",
"(",
"event",
".",
"Name",
")",
"\n",
"if",
"dc",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"byteFile",
",",
"err",
":=",
"c",
".",
"fsHandler",
".",
"ReadFile",
"(",
"event",
".",
"Name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"c",
".",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"event",
".",
"Name",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"decodedFileEntries",
",",
"err",
":=",
"dc",
".",
"Decode",
"(",
"byteFile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"c",
".",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"event",
".",
"Name",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"file",
":=",
"&",
"decoder",
".",
"File",
"{",
"Path",
":",
"event",
".",
"Name",
",",
"Data",
":",
"decodedFileEntries",
"}",
"\n",
"latestFile",
":=",
"&",
"decoder",
".",
"File",
"{",
"Path",
":",
"event",
".",
"Name",
",",
"Data",
":",
"c",
".",
"db",
".",
"GetDataForFile",
"(",
"event",
".",
"Name",
")",
"}",
"\n",
"changed",
",",
"removed",
":=",
"file",
".",
"CompareTo",
"(",
"latestFile",
")",
"\n",
"// Update database and propagate data to channel",
"for",
"_",
",",
"fileDataEntry",
":=",
"range",
"removed",
"{",
"keyed",
":=",
"keyedData",
"{",
"path",
":",
"event",
".",
"Name",
",",
"watchResp",
":",
"watchResp",
"{",
"Op",
":",
"datasync",
".",
"Delete",
",",
"Key",
":",
"fileDataEntry",
".",
"Key",
",",
"Value",
":",
"nil",
",",
"PrevValue",
":",
"fileDataEntry",
".",
"Value",
"}",
",",
"}",
"\n",
"c",
".",
"sendToChannel",
"(",
"keyed",
")",
"\n",
"c",
".",
"db",
".",
"Delete",
"(",
"event",
".",
"Name",
",",
"keyed",
".",
"Key",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"fileDataEntry",
":=",
"range",
"changed",
"{",
"// Get last key-val configuration item if exists",
"var",
"prevVal",
"[",
"]",
"byte",
"\n",
"if",
"prevValEntry",
",",
"ok",
":=",
"c",
".",
"db",
".",
"GetDataForKey",
"(",
"fileDataEntry",
".",
"Key",
")",
";",
"ok",
"{",
"prevVal",
"=",
"prevValEntry",
".",
"Value",
"\n",
"}",
"\n",
"keyed",
":=",
"keyedData",
"{",
"path",
":",
"event",
".",
"Name",
",",
"watchResp",
":",
"watchResp",
"{",
"Op",
":",
"datasync",
".",
"Put",
",",
"Key",
":",
"fileDataEntry",
".",
"Key",
",",
"Value",
":",
"fileDataEntry",
".",
"Value",
",",
"PrevValue",
":",
"prevVal",
"}",
",",
"}",
"\n",
"c",
".",
"sendToChannel",
"(",
"keyed",
")",
"\n",
"c",
".",
"db",
".",
"Add",
"(",
"event",
".",
"Name",
",",
"&",
"decoder",
".",
"FileDataEntry",
"{",
"Key",
":",
"keyed",
".",
"Key",
",",
"Value",
":",
"keyed",
".",
"Value",
",",
"}",
")",
"\n",
"}",
"\n",
"}"
] | // OnEvent is common method called when new event from file system arrives. Different files may require different
// reader, but the data processing is the same. | [
"OnEvent",
"is",
"common",
"method",
"called",
"when",
"new",
"event",
"from",
"file",
"system",
"arrives",
".",
"Different",
"files",
"may",
"require",
"different",
"reader",
"but",
"the",
"data",
"processing",
"is",
"the",
"same",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/client.go#L282-L343 |
4,624 | ligato/cn-infra | db/keyval/filedb/client.go | sendToChannel | func (c *Client) sendToChannel(keyed keyedData) {
c.Lock()
defer c.Unlock()
for key, channel := range c.watchers {
if strings.Contains(keyed.Key, key) {
channel <- keyed
return
}
}
} | go | func (c *Client) sendToChannel(keyed keyedData) {
c.Lock()
defer c.Unlock()
for key, channel := range c.watchers {
if strings.Contains(keyed.Key, key) {
channel <- keyed
return
}
}
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"sendToChannel",
"(",
"keyed",
"keyedData",
")",
"{",
"c",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"Unlock",
"(",
")",
"\n\n",
"for",
"key",
",",
"channel",
":=",
"range",
"c",
".",
"watchers",
"{",
"if",
"strings",
".",
"Contains",
"(",
"keyed",
".",
"Key",
",",
"key",
")",
"{",
"channel",
"<-",
"keyed",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // Send data to correct channel | [
"Send",
"data",
"to",
"correct",
"channel"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/client.go#L353-L363 |
4,625 | ligato/cn-infra | db/keyval/filedb/client.go | getFileDecoder | func (c *Client) getFileDecoder(file string) decoder.API {
for _, dc := range c.decoders {
if dc.IsProcessable(file) {
return dc
}
}
return nil
} | go | func (c *Client) getFileDecoder(file string) decoder.API {
for _, dc := range c.decoders {
if dc.IsProcessable(file) {
return dc
}
}
return nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"getFileDecoder",
"(",
"file",
"string",
")",
"decoder",
".",
"API",
"{",
"for",
"_",
",",
"dc",
":=",
"range",
"c",
".",
"decoders",
"{",
"if",
"dc",
".",
"IsProcessable",
"(",
"file",
")",
"{",
"return",
"dc",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Use known decoders to decide whether the file can or cannot be processed. If so, return proper decoder. | [
"Use",
"known",
"decoders",
"to",
"decide",
"whether",
"the",
"file",
"can",
"or",
"cannot",
"be",
"processed",
".",
"If",
"so",
"return",
"proper",
"decoder",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/client.go#L366-L373 |
4,626 | ligato/cn-infra | db/sql/sql_expression.go | SELECT | func SELECT(entity interface{}, afterKeyword Expression, binding ...interface{}) Expression {
return &PrefixedExp{"SELECT", []Expression{FROM(entity, afterKeyword)}, "", binding}
} | go | func SELECT(entity interface{}, afterKeyword Expression, binding ...interface{}) Expression {
return &PrefixedExp{"SELECT", []Expression{FROM(entity, afterKeyword)}, "", binding}
} | [
"func",
"SELECT",
"(",
"entity",
"interface",
"{",
"}",
",",
"afterKeyword",
"Expression",
",",
"binding",
"...",
"interface",
"{",
"}",
")",
"Expression",
"{",
"return",
"&",
"PrefixedExp",
"{",
"\"",
"\"",
",",
"[",
"]",
"Expression",
"{",
"FROM",
"(",
"entity",
",",
"afterKeyword",
")",
"}",
",",
"\"",
"\"",
",",
"binding",
"}",
"\n",
"}"
] | // SELECT keyword of an SQL expression. | [
"SELECT",
"keyword",
"of",
"an",
"SQL",
"expression",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/sql/sql_expression.go#L119-L121 |
4,627 | ligato/cn-infra | datasync/restsync/http_handlers.go | putMessage | func (adapter *Adapter) putMessage(formatter *render.Render) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
body, err := req.GetBody()
if err != nil {
var data []byte
data, err = ioutil.ReadAll(body)
defer req.Body.Close()
if err != nil {
localtxn := local.NewBytesTxn(adapter.base.PropagateChanges)
localtxn.Put(req.RequestURI, data)
err = localtxn.Commit(context.Background())
}
}
if err != nil {
formatter.JSON(w, http.StatusInternalServerError, struct{ Test string }{err.Error()})
} else {
formatter.JSON(w, http.StatusOK, struct{ Test string }{"OK"})
}
}
} | go | func (adapter *Adapter) putMessage(formatter *render.Render) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
body, err := req.GetBody()
if err != nil {
var data []byte
data, err = ioutil.ReadAll(body)
defer req.Body.Close()
if err != nil {
localtxn := local.NewBytesTxn(adapter.base.PropagateChanges)
localtxn.Put(req.RequestURI, data)
err = localtxn.Commit(context.Background())
}
}
if err != nil {
formatter.JSON(w, http.StatusInternalServerError, struct{ Test string }{err.Error()})
} else {
formatter.JSON(w, http.StatusOK, struct{ Test string }{"OK"})
}
}
} | [
"func",
"(",
"adapter",
"*",
"Adapter",
")",
"putMessage",
"(",
"formatter",
"*",
"render",
".",
"Render",
")",
"http",
".",
"HandlerFunc",
"{",
"return",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
")",
"{",
"body",
",",
"err",
":=",
"req",
".",
"GetBody",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"var",
"data",
"[",
"]",
"byte",
"\n",
"data",
",",
"err",
"=",
"ioutil",
".",
"ReadAll",
"(",
"body",
")",
"\n",
"defer",
"req",
".",
"Body",
".",
"Close",
"(",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"localtxn",
":=",
"local",
".",
"NewBytesTxn",
"(",
"adapter",
".",
"base",
".",
"PropagateChanges",
")",
"\n",
"localtxn",
".",
"Put",
"(",
"req",
".",
"RequestURI",
",",
"data",
")",
"\n",
"err",
"=",
"localtxn",
".",
"Commit",
"(",
"context",
".",
"Background",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"formatter",
".",
"JSON",
"(",
"w",
",",
"http",
".",
"StatusInternalServerError",
",",
"struct",
"{",
"Test",
"string",
"}",
"{",
"err",
".",
"Error",
"(",
")",
"}",
")",
"\n",
"}",
"else",
"{",
"formatter",
".",
"JSON",
"(",
"w",
",",
"http",
".",
"StatusOK",
",",
"struct",
"{",
"Test",
"string",
"}",
"{",
"\"",
"\"",
"}",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // putMessage is only a stub prepared for later implementation. | [
"putMessage",
"is",
"only",
"a",
"stub",
"prepared",
"for",
"later",
"implementation",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/datasync/restsync/http_handlers.go#L28-L49 |
4,628 | ligato/cn-infra | datasync/restsync/http_handlers.go | delMessage | func (adapter *Adapter) delMessage(formatter *render.Render) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
localtxn := local.NewBytesTxn(adapter.base.PropagateChanges)
localtxn.Delete(req.RequestURI)
err := localtxn.Commit(context.Background())
if err != nil {
formatter.JSON(w, http.StatusInternalServerError, struct{ Test string }{err.Error()})
} else {
formatter.JSON(w, http.StatusOK, struct{ Test string }{"OK"})
}
}
} | go | func (adapter *Adapter) delMessage(formatter *render.Render) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
localtxn := local.NewBytesTxn(adapter.base.PropagateChanges)
localtxn.Delete(req.RequestURI)
err := localtxn.Commit(context.Background())
if err != nil {
formatter.JSON(w, http.StatusInternalServerError, struct{ Test string }{err.Error()})
} else {
formatter.JSON(w, http.StatusOK, struct{ Test string }{"OK"})
}
}
} | [
"func",
"(",
"adapter",
"*",
"Adapter",
")",
"delMessage",
"(",
"formatter",
"*",
"render",
".",
"Render",
")",
"http",
".",
"HandlerFunc",
"{",
"return",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
")",
"{",
"localtxn",
":=",
"local",
".",
"NewBytesTxn",
"(",
"adapter",
".",
"base",
".",
"PropagateChanges",
")",
"\n",
"localtxn",
".",
"Delete",
"(",
"req",
".",
"RequestURI",
")",
"\n",
"err",
":=",
"localtxn",
".",
"Commit",
"(",
"context",
".",
"Background",
"(",
")",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"formatter",
".",
"JSON",
"(",
"w",
",",
"http",
".",
"StatusInternalServerError",
",",
"struct",
"{",
"Test",
"string",
"}",
"{",
"err",
".",
"Error",
"(",
")",
"}",
")",
"\n",
"}",
"else",
"{",
"formatter",
".",
"JSON",
"(",
"w",
",",
"http",
".",
"StatusOK",
",",
"struct",
"{",
"Test",
"string",
"}",
"{",
"\"",
"\"",
"}",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // delMessage only calls local dbadapter delete. | [
"delMessage",
"only",
"calls",
"local",
"dbadapter",
"delete",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/datasync/restsync/http_handlers.go#L52-L64 |
4,629 | ligato/cn-infra | db/sql/cassandra/plugin_impl_cassa.go | Init | func (p *Plugin) Init() (err error) {
if p.session != nil {
return nil // skip initialization
}
// Retrieve config
var cfg Config
found, err := p.Cfg.LoadValue(&cfg)
// need to be strict about config presence for ETCD
if !found {
p.Log.Info("cassandra client config not found ", p.Cfg.GetConfigName(),
" - skip loading this plugin")
return nil
}
if err != nil {
return err
}
// Init session
p.clientConfig, err = ConfigToClientConfig(&cfg)
if err != nil {
return err
}
if p.session == nil && p.clientConfig != nil {
session, err := CreateSessionFromConfig(p.clientConfig)
if err != nil {
return err
}
p.session = gockle.NewSession(session)
}
return nil
} | go | func (p *Plugin) Init() (err error) {
if p.session != nil {
return nil // skip initialization
}
// Retrieve config
var cfg Config
found, err := p.Cfg.LoadValue(&cfg)
// need to be strict about config presence for ETCD
if !found {
p.Log.Info("cassandra client config not found ", p.Cfg.GetConfigName(),
" - skip loading this plugin")
return nil
}
if err != nil {
return err
}
// Init session
p.clientConfig, err = ConfigToClientConfig(&cfg)
if err != nil {
return err
}
if p.session == nil && p.clientConfig != nil {
session, err := CreateSessionFromConfig(p.clientConfig)
if err != nil {
return err
}
p.session = gockle.NewSession(session)
}
return nil
} | [
"func",
"(",
"p",
"*",
"Plugin",
")",
"Init",
"(",
")",
"(",
"err",
"error",
")",
"{",
"if",
"p",
".",
"session",
"!=",
"nil",
"{",
"return",
"nil",
"// skip initialization",
"\n",
"}",
"\n\n",
"// Retrieve config",
"var",
"cfg",
"Config",
"\n",
"found",
",",
"err",
":=",
"p",
".",
"Cfg",
".",
"LoadValue",
"(",
"&",
"cfg",
")",
"\n",
"// need to be strict about config presence for ETCD",
"if",
"!",
"found",
"{",
"p",
".",
"Log",
".",
"Info",
"(",
"\"",
"\"",
",",
"p",
".",
"Cfg",
".",
"GetConfigName",
"(",
")",
",",
"\"",
"\"",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Init session",
"p",
".",
"clientConfig",
",",
"err",
"=",
"ConfigToClientConfig",
"(",
"&",
"cfg",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"p",
".",
"session",
"==",
"nil",
"&&",
"p",
".",
"clientConfig",
"!=",
"nil",
"{",
"session",
",",
"err",
":=",
"CreateSessionFromConfig",
"(",
"p",
".",
"clientConfig",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"p",
".",
"session",
"=",
"gockle",
".",
"NewSession",
"(",
"session",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Init is called at plugin startup. The session to Cassandra is established. | [
"Init",
"is",
"called",
"at",
"plugin",
"startup",
".",
"The",
"session",
"to",
"Cassandra",
"is",
"established",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/sql/cassandra/plugin_impl_cassa.go#L62-L96 |
4,630 | ligato/cn-infra | db/sql/cassandra/plugin_impl_cassa.go | AfterInit | func (p *Plugin) AfterInit() error {
if p.StatusCheck != nil && p.session != nil {
p.StatusCheck.Register(p.PluginName, func() (statuscheck.PluginState, error) {
broker := p.NewBroker()
err := broker.Exec(`select keyspace_name from system_schema.keyspaces`)
if err == nil {
return statuscheck.OK, nil
}
return statuscheck.Error, err
})
p.Log.Warnf("Status check for %s was started", p.PluginName)
}
return nil
} | go | func (p *Plugin) AfterInit() error {
if p.StatusCheck != nil && p.session != nil {
p.StatusCheck.Register(p.PluginName, func() (statuscheck.PluginState, error) {
broker := p.NewBroker()
err := broker.Exec(`select keyspace_name from system_schema.keyspaces`)
if err == nil {
return statuscheck.OK, nil
}
return statuscheck.Error, err
})
p.Log.Warnf("Status check for %s was started", p.PluginName)
}
return nil
} | [
"func",
"(",
"p",
"*",
"Plugin",
")",
"AfterInit",
"(",
")",
"error",
"{",
"if",
"p",
".",
"StatusCheck",
"!=",
"nil",
"&&",
"p",
".",
"session",
"!=",
"nil",
"{",
"p",
".",
"StatusCheck",
".",
"Register",
"(",
"p",
".",
"PluginName",
",",
"func",
"(",
")",
"(",
"statuscheck",
".",
"PluginState",
",",
"error",
")",
"{",
"broker",
":=",
"p",
".",
"NewBroker",
"(",
")",
"\n",
"err",
":=",
"broker",
".",
"Exec",
"(",
"`select keyspace_name from system_schema.keyspaces`",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"statuscheck",
".",
"OK",
",",
"nil",
"\n",
"}",
"\n",
"return",
"statuscheck",
".",
"Error",
",",
"err",
"\n",
"}",
")",
"\n",
"p",
".",
"Log",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"p",
".",
"PluginName",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // AfterInit registers Cassandra to status check. | [
"AfterInit",
"registers",
"Cassandra",
"to",
"status",
"check",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/sql/cassandra/plugin_impl_cassa.go#L99-L113 |
4,631 | ligato/cn-infra | datasync/kvdbsync/change_event.go | NewChangeWatchResp | func NewChangeWatchResp(ctx context.Context, delegate datasync.ProtoWatchResp, prevVal datasync.LazyValue) *ChangeWatchResp {
return &ChangeWatchResp{
ctx: ctx,
changes: []datasync.ProtoWatchResp{
&changePrev{
ProtoWatchResp: delegate,
prev: prevVal,
},
},
DoneChannel: &syncbase.DoneChannel{DoneChan: nil},
}
} | go | func NewChangeWatchResp(ctx context.Context, delegate datasync.ProtoWatchResp, prevVal datasync.LazyValue) *ChangeWatchResp {
return &ChangeWatchResp{
ctx: ctx,
changes: []datasync.ProtoWatchResp{
&changePrev{
ProtoWatchResp: delegate,
prev: prevVal,
},
},
DoneChannel: &syncbase.DoneChannel{DoneChan: nil},
}
} | [
"func",
"NewChangeWatchResp",
"(",
"ctx",
"context",
".",
"Context",
",",
"delegate",
"datasync",
".",
"ProtoWatchResp",
",",
"prevVal",
"datasync",
".",
"LazyValue",
")",
"*",
"ChangeWatchResp",
"{",
"return",
"&",
"ChangeWatchResp",
"{",
"ctx",
":",
"ctx",
",",
"changes",
":",
"[",
"]",
"datasync",
".",
"ProtoWatchResp",
"{",
"&",
"changePrev",
"{",
"ProtoWatchResp",
":",
"delegate",
",",
"prev",
":",
"prevVal",
",",
"}",
",",
"}",
",",
"DoneChannel",
":",
"&",
"syncbase",
".",
"DoneChannel",
"{",
"DoneChan",
":",
"nil",
"}",
",",
"}",
"\n",
"}"
] | // NewChangeWatchResp creates a new instance of ChangeWatchResp. | [
"NewChangeWatchResp",
"creates",
"a",
"new",
"instance",
"of",
"ChangeWatchResp",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/datasync/kvdbsync/change_event.go#L34-L45 |
4,632 | ligato/cn-infra | datasync/kvdbsync/change_event.go | GetValue | func (ev *changePrev) GetValue(val proto.Message) (err error) {
if ev.ProtoWatchResp.GetChangeType() != datasync.Delete {
return ev.ProtoWatchResp.GetValue(val)
}
return nil
} | go | func (ev *changePrev) GetValue(val proto.Message) (err error) {
if ev.ProtoWatchResp.GetChangeType() != datasync.Delete {
return ev.ProtoWatchResp.GetValue(val)
}
return nil
} | [
"func",
"(",
"ev",
"*",
"changePrev",
")",
"GetValue",
"(",
"val",
"proto",
".",
"Message",
")",
"(",
"err",
"error",
")",
"{",
"if",
"ev",
".",
"ProtoWatchResp",
".",
"GetChangeType",
"(",
")",
"!=",
"datasync",
".",
"Delete",
"{",
"return",
"ev",
".",
"ProtoWatchResp",
".",
"GetValue",
"(",
"val",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // GetValue returns previous value associated with a change. For description of parameter and output
// values, see the comment in implemented interface datasync.ChangeEvent. | [
"GetValue",
"returns",
"previous",
"value",
"associated",
"with",
"a",
"change",
".",
"For",
"description",
"of",
"parameter",
"and",
"output",
"values",
"see",
"the",
"comment",
"in",
"implemented",
"interface",
"datasync",
".",
"ChangeEvent",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/datasync/kvdbsync/change_event.go#L64-L69 |
4,633 | ligato/cn-infra | datasync/kvdbsync/change_event.go | GetPrevValue | func (ev *changePrev) GetPrevValue(prevVal proto.Message) (exists bool, err error) {
if ev.prev != nil {
return true, ev.prev.GetValue(prevVal)
}
return false, nil
} | go | func (ev *changePrev) GetPrevValue(prevVal proto.Message) (exists bool, err error) {
if ev.prev != nil {
return true, ev.prev.GetValue(prevVal)
}
return false, nil
} | [
"func",
"(",
"ev",
"*",
"changePrev",
")",
"GetPrevValue",
"(",
"prevVal",
"proto",
".",
"Message",
")",
"(",
"exists",
"bool",
",",
"err",
"error",
")",
"{",
"if",
"ev",
".",
"prev",
"!=",
"nil",
"{",
"return",
"true",
",",
"ev",
".",
"prev",
".",
"GetValue",
"(",
"prevVal",
")",
"\n",
"}",
"\n",
"return",
"false",
",",
"nil",
"\n",
"}"
] | // GetPrevValue returns previous value associated with a change. For description of parameter and output
// values, see the comment in implemented interface datasync.ChangeEvent. | [
"GetPrevValue",
"returns",
"previous",
"value",
"associated",
"with",
"a",
"change",
".",
"For",
"description",
"of",
"parameter",
"and",
"output",
"values",
"see",
"the",
"comment",
"in",
"implemented",
"interface",
"datasync",
".",
"ChangeEvent",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/datasync/kvdbsync/change_event.go#L73-L78 |
4,634 | ligato/cn-infra | rpc/prometheus/plugin_impl_prometheus.go | Init | func (p *Plugin) Init() error {
p.regs = map[string]*registry{}
// add default registry
p.regs[DefaultRegistry] = ®istry{
Gatherer: prometheus.DefaultGatherer,
Registerer: prometheus.DefaultRegisterer,
}
return nil
} | go | func (p *Plugin) Init() error {
p.regs = map[string]*registry{}
// add default registry
p.regs[DefaultRegistry] = ®istry{
Gatherer: prometheus.DefaultGatherer,
Registerer: prometheus.DefaultRegisterer,
}
return nil
} | [
"func",
"(",
"p",
"*",
"Plugin",
")",
"Init",
"(",
")",
"error",
"{",
"p",
".",
"regs",
"=",
"map",
"[",
"string",
"]",
"*",
"registry",
"{",
"}",
"\n\n",
"// add default registry",
"p",
".",
"regs",
"[",
"DefaultRegistry",
"]",
"=",
"&",
"registry",
"{",
"Gatherer",
":",
"prometheus",
".",
"DefaultGatherer",
",",
"Registerer",
":",
"prometheus",
".",
"DefaultRegisterer",
",",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Init initializes the internal structures | [
"Init",
"initializes",
"the",
"internal",
"structures"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/rpc/prometheus/plugin_impl_prometheus.go#L68-L78 |
4,635 | ligato/cn-infra | rpc/prometheus/plugin_impl_prometheus.go | AfterInit | func (p *Plugin) AfterInit() error {
if p.HTTP != nil {
p.Lock()
defer p.Unlock()
for path, reg := range p.regs {
p.HTTP.RegisterHTTPHandler(path, p.createHandlerHandler(reg.Gatherer, reg.httpOpts), "GET")
p.Log.Infof("Serving %s on port %d", path, p.HTTP.GetPort())
}
} else {
p.Log.Info("Unable to register Prometheus metrics handlers, HTTP is nil")
}
return nil
} | go | func (p *Plugin) AfterInit() error {
if p.HTTP != nil {
p.Lock()
defer p.Unlock()
for path, reg := range p.regs {
p.HTTP.RegisterHTTPHandler(path, p.createHandlerHandler(reg.Gatherer, reg.httpOpts), "GET")
p.Log.Infof("Serving %s on port %d", path, p.HTTP.GetPort())
}
} else {
p.Log.Info("Unable to register Prometheus metrics handlers, HTTP is nil")
}
return nil
} | [
"func",
"(",
"p",
"*",
"Plugin",
")",
"AfterInit",
"(",
")",
"error",
"{",
"if",
"p",
".",
"HTTP",
"!=",
"nil",
"{",
"p",
".",
"Lock",
"(",
")",
"\n",
"defer",
"p",
".",
"Unlock",
"(",
")",
"\n",
"for",
"path",
",",
"reg",
":=",
"range",
"p",
".",
"regs",
"{",
"p",
".",
"HTTP",
".",
"RegisterHTTPHandler",
"(",
"path",
",",
"p",
".",
"createHandlerHandler",
"(",
"reg",
".",
"Gatherer",
",",
"reg",
".",
"httpOpts",
")",
",",
"\"",
"\"",
")",
"\n",
"p",
".",
"Log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"path",
",",
"p",
".",
"HTTP",
".",
"GetPort",
"(",
")",
")",
"\n\n",
"}",
"\n",
"}",
"else",
"{",
"p",
".",
"Log",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // AfterInit registers HTTP handlers. | [
"AfterInit",
"registers",
"HTTP",
"handlers",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/rpc/prometheus/plugin_impl_prometheus.go#L81-L95 |
4,636 | ligato/cn-infra | rpc/prometheus/plugin_impl_prometheus.go | Register | func (p *Plugin) Register(registryPath string, collector prometheus.Collector) error {
p.Lock()
defer p.Unlock()
reg, found := p.regs[registryPath]
if !found {
p.Log.WithField("path", registryPath).Error(ErrRegistryNotFound)
return ErrRegistryNotFound
}
return reg.Register(collector)
} | go | func (p *Plugin) Register(registryPath string, collector prometheus.Collector) error {
p.Lock()
defer p.Unlock()
reg, found := p.regs[registryPath]
if !found {
p.Log.WithField("path", registryPath).Error(ErrRegistryNotFound)
return ErrRegistryNotFound
}
return reg.Register(collector)
} | [
"func",
"(",
"p",
"*",
"Plugin",
")",
"Register",
"(",
"registryPath",
"string",
",",
"collector",
"prometheus",
".",
"Collector",
")",
"error",
"{",
"p",
".",
"Lock",
"(",
")",
"\n",
"defer",
"p",
".",
"Unlock",
"(",
")",
"\n\n",
"reg",
",",
"found",
":=",
"p",
".",
"regs",
"[",
"registryPath",
"]",
"\n",
"if",
"!",
"found",
"{",
"p",
".",
"Log",
".",
"WithField",
"(",
"\"",
"\"",
",",
"registryPath",
")",
".",
"Error",
"(",
"ErrRegistryNotFound",
")",
"\n",
"return",
"ErrRegistryNotFound",
"\n",
"}",
"\n",
"return",
"reg",
".",
"Register",
"(",
"collector",
")",
"\n",
"}"
] | // Register registers prometheus metric to a specified registry. In order to add metrics
// to default registry use prometheus.DefaultRegistry const. | [
"Register",
"registers",
"prometheus",
"metric",
"to",
"a",
"specified",
"registry",
".",
"In",
"order",
"to",
"add",
"metrics",
"to",
"default",
"registry",
"use",
"prometheus",
".",
"DefaultRegistry",
"const",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/rpc/prometheus/plugin_impl_prometheus.go#L129-L139 |
4,637 | ligato/cn-infra | rpc/prometheus/plugin_impl_prometheus.go | Unregister | func (p *Plugin) Unregister(registryPath string, collector prometheus.Collector) bool {
p.Lock()
defer p.Unlock()
reg, found := p.regs[registryPath]
if !found {
return false
}
return reg.Unregister(collector)
} | go | func (p *Plugin) Unregister(registryPath string, collector prometheus.Collector) bool {
p.Lock()
defer p.Unlock()
reg, found := p.regs[registryPath]
if !found {
return false
}
return reg.Unregister(collector)
} | [
"func",
"(",
"p",
"*",
"Plugin",
")",
"Unregister",
"(",
"registryPath",
"string",
",",
"collector",
"prometheus",
".",
"Collector",
")",
"bool",
"{",
"p",
".",
"Lock",
"(",
")",
"\n",
"defer",
"p",
".",
"Unlock",
"(",
")",
"\n\n",
"reg",
",",
"found",
":=",
"p",
".",
"regs",
"[",
"registryPath",
"]",
"\n",
"if",
"!",
"found",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"reg",
".",
"Unregister",
"(",
"collector",
")",
"\n",
"}"
] | // Unregister unregisters the given metric. The function
// returns whether a Collector was unregistered. | [
"Unregister",
"unregisters",
"the",
"given",
"metric",
".",
"The",
"function",
"returns",
"whether",
"a",
"Collector",
"was",
"unregistered",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/rpc/prometheus/plugin_impl_prometheus.go#L143-L152 |
4,638 | ligato/cn-infra | rpc/prometheus/plugin_impl_prometheus.go | RegisterGaugeFunc | func (p *Plugin) RegisterGaugeFunc(registryPath string, namespace string, subsystem string, name string, help string,
labels prometheus.Labels, valueFunc func() float64) error {
p.Lock()
defer p.Unlock()
reg, found := p.regs[registryPath]
if !found {
p.Log.WithField("path", registryPath).Error(ErrRegistryNotFound)
return ErrRegistryNotFound
}
gaugeName := name
if subsystem != "" {
gaugeName = subsystem + "_" + gaugeName
}
if namespace != "" {
gaugeName = namespace + "_" + gaugeName
}
err := reg.Register(prometheus.NewGaugeFunc(
prometheus.GaugeOpts{
Namespace: namespace,
Subsystem: subsystem,
Name: name,
Help: help,
ConstLabels: labels,
},
valueFunc,
))
if err != nil {
p.Log.Errorf("GaugeFunc('%s') registration failed: %s", gaugeName, err)
return err
}
p.Log.Infof("GaugeFunc('%s') registered.", gaugeName)
return nil
} | go | func (p *Plugin) RegisterGaugeFunc(registryPath string, namespace string, subsystem string, name string, help string,
labels prometheus.Labels, valueFunc func() float64) error {
p.Lock()
defer p.Unlock()
reg, found := p.regs[registryPath]
if !found {
p.Log.WithField("path", registryPath).Error(ErrRegistryNotFound)
return ErrRegistryNotFound
}
gaugeName := name
if subsystem != "" {
gaugeName = subsystem + "_" + gaugeName
}
if namespace != "" {
gaugeName = namespace + "_" + gaugeName
}
err := reg.Register(prometheus.NewGaugeFunc(
prometheus.GaugeOpts{
Namespace: namespace,
Subsystem: subsystem,
Name: name,
Help: help,
ConstLabels: labels,
},
valueFunc,
))
if err != nil {
p.Log.Errorf("GaugeFunc('%s') registration failed: %s", gaugeName, err)
return err
}
p.Log.Infof("GaugeFunc('%s') registered.", gaugeName)
return nil
} | [
"func",
"(",
"p",
"*",
"Plugin",
")",
"RegisterGaugeFunc",
"(",
"registryPath",
"string",
",",
"namespace",
"string",
",",
"subsystem",
"string",
",",
"name",
"string",
",",
"help",
"string",
",",
"labels",
"prometheus",
".",
"Labels",
",",
"valueFunc",
"func",
"(",
")",
"float64",
")",
"error",
"{",
"p",
".",
"Lock",
"(",
")",
"\n",
"defer",
"p",
".",
"Unlock",
"(",
")",
"\n\n",
"reg",
",",
"found",
":=",
"p",
".",
"regs",
"[",
"registryPath",
"]",
"\n",
"if",
"!",
"found",
"{",
"p",
".",
"Log",
".",
"WithField",
"(",
"\"",
"\"",
",",
"registryPath",
")",
".",
"Error",
"(",
"ErrRegistryNotFound",
")",
"\n",
"return",
"ErrRegistryNotFound",
"\n",
"}",
"\n\n",
"gaugeName",
":=",
"name",
"\n",
"if",
"subsystem",
"!=",
"\"",
"\"",
"{",
"gaugeName",
"=",
"subsystem",
"+",
"\"",
"\"",
"+",
"gaugeName",
"\n",
"}",
"\n",
"if",
"namespace",
"!=",
"\"",
"\"",
"{",
"gaugeName",
"=",
"namespace",
"+",
"\"",
"\"",
"+",
"gaugeName",
"\n",
"}",
"\n\n",
"err",
":=",
"reg",
".",
"Register",
"(",
"prometheus",
".",
"NewGaugeFunc",
"(",
"prometheus",
".",
"GaugeOpts",
"{",
"Namespace",
":",
"namespace",
",",
"Subsystem",
":",
"subsystem",
",",
"Name",
":",
"name",
",",
"Help",
":",
"help",
",",
"ConstLabels",
":",
"labels",
",",
"}",
",",
"valueFunc",
",",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"p",
".",
"Log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"gaugeName",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"p",
".",
"Log",
".",
"Infof",
"(",
"\"",
"\"",
",",
"gaugeName",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // RegisterGaugeFunc registers custom gauge with specific valueFunc to report status when invoked.
// This method simplifies using of Register for common use case. If you want create metric different from
// GagugeFunc or you're adding a metric that will be unregister later on, use generic Register method instead.
// RegistryPath identifies the registry where gauge is added. | [
"RegisterGaugeFunc",
"registers",
"custom",
"gauge",
"with",
"specific",
"valueFunc",
"to",
"report",
"status",
"when",
"invoked",
".",
"This",
"method",
"simplifies",
"using",
"of",
"Register",
"for",
"common",
"use",
"case",
".",
"If",
"you",
"want",
"create",
"metric",
"different",
"from",
"GagugeFunc",
"or",
"you",
"re",
"adding",
"a",
"metric",
"that",
"will",
"be",
"unregister",
"later",
"on",
"use",
"generic",
"Register",
"method",
"instead",
".",
"RegistryPath",
"identifies",
"the",
"registry",
"where",
"gauge",
"is",
"added",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/rpc/prometheus/plugin_impl_prometheus.go#L158-L194 |
4,639 | ligato/cn-infra | messaging/kafka/client/config.go | NewConfig | func NewConfig(log logging.Logger) *Config {
cfg := &Config{
Logger: log,
Config: cluster.NewConfig(),
Partition: -1,
Partitioner: sarama.NewHashPartitioner,
RequiredAcks: AcksUnset,
}
return cfg
} | go | func NewConfig(log logging.Logger) *Config {
cfg := &Config{
Logger: log,
Config: cluster.NewConfig(),
Partition: -1,
Partitioner: sarama.NewHashPartitioner,
RequiredAcks: AcksUnset,
}
return cfg
} | [
"func",
"NewConfig",
"(",
"log",
"logging",
".",
"Logger",
")",
"*",
"Config",
"{",
"cfg",
":=",
"&",
"Config",
"{",
"Logger",
":",
"log",
",",
"Config",
":",
"cluster",
".",
"NewConfig",
"(",
")",
",",
"Partition",
":",
"-",
"1",
",",
"Partitioner",
":",
"sarama",
".",
"NewHashPartitioner",
",",
"RequiredAcks",
":",
"AcksUnset",
",",
"}",
"\n\n",
"return",
"cfg",
"\n",
"}"
] | // NewConfig return a new Config object. | [
"NewConfig",
"return",
"a",
"new",
"Config",
"object",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/client/config.go#L124-L135 |
4,640 | ligato/cn-infra | messaging/kafka/client/config.go | SetTopics | func (ref *Config) SetTopics(topics string) {
ref.Topics = strings.Split(topics, ",")
} | go | func (ref *Config) SetTopics(topics string) {
ref.Topics = strings.Split(topics, ",")
} | [
"func",
"(",
"ref",
"*",
"Config",
")",
"SetTopics",
"(",
"topics",
"string",
")",
"{",
"ref",
".",
"Topics",
"=",
"strings",
".",
"Split",
"(",
"topics",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // SetTopics sets the Config.Topics field | [
"SetTopics",
"sets",
"the",
"Config",
".",
"Topics",
"field"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/client/config.go#L143-L145 |
4,641 | ligato/cn-infra | messaging/kafka/client/config.go | SetDebug | func (ref *Config) SetDebug(val bool) {
if val {
ref.Debug = val
sarama.Logger = ref.Logger
ref.SetLevel(logging.DebugLevel)
} else {
ref.Debug = val
}
} | go | func (ref *Config) SetDebug(val bool) {
if val {
ref.Debug = val
sarama.Logger = ref.Logger
ref.SetLevel(logging.DebugLevel)
} else {
ref.Debug = val
}
} | [
"func",
"(",
"ref",
"*",
"Config",
")",
"SetDebug",
"(",
"val",
"bool",
")",
"{",
"if",
"val",
"{",
"ref",
".",
"Debug",
"=",
"val",
"\n",
"sarama",
".",
"Logger",
"=",
"ref",
".",
"Logger",
"\n",
"ref",
".",
"SetLevel",
"(",
"logging",
".",
"DebugLevel",
")",
"\n",
"}",
"else",
"{",
"ref",
".",
"Debug",
"=",
"val",
"\n",
"}",
"\n",
"}"
] | // SetDebug sets the Config.Debug field | [
"SetDebug",
"sets",
"the",
"Config",
".",
"Debug",
"field"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/client/config.go#L148-L156 |
4,642 | ligato/cn-infra | messaging/kafka/client/config.go | SetPartitioner | func (ref *Config) SetPartitioner(val string) {
switch val {
default:
ref.Errorf("Invalid partitioner %s - defaulting to ''", val)
fallthrough
case "":
if ref.Partition >= 0 {
ref.Partitioner = sarama.NewManualPartitioner
} else {
ref.Partitioner = sarama.NewHashPartitioner
}
case Hash:
ref.Partitioner = sarama.NewHashPartitioner
ref.Partition = -1
case Random:
ref.Partitioner = sarama.NewRandomPartitioner
ref.Partition = -1
case Manual:
ref.Partitioner = sarama.NewManualPartitioner
if ref.Partition < 0 {
ref.Infof("Invalid partition %d - defaulting to 0", ref.Partition)
ref.Partition = 0
}
}
} | go | func (ref *Config) SetPartitioner(val string) {
switch val {
default:
ref.Errorf("Invalid partitioner %s - defaulting to ''", val)
fallthrough
case "":
if ref.Partition >= 0 {
ref.Partitioner = sarama.NewManualPartitioner
} else {
ref.Partitioner = sarama.NewHashPartitioner
}
case Hash:
ref.Partitioner = sarama.NewHashPartitioner
ref.Partition = -1
case Random:
ref.Partitioner = sarama.NewRandomPartitioner
ref.Partition = -1
case Manual:
ref.Partitioner = sarama.NewManualPartitioner
if ref.Partition < 0 {
ref.Infof("Invalid partition %d - defaulting to 0", ref.Partition)
ref.Partition = 0
}
}
} | [
"func",
"(",
"ref",
"*",
"Config",
")",
"SetPartitioner",
"(",
"val",
"string",
")",
"{",
"switch",
"val",
"{",
"default",
":",
"ref",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"val",
")",
"\n",
"fallthrough",
"\n",
"case",
"\"",
"\"",
":",
"if",
"ref",
".",
"Partition",
">=",
"0",
"{",
"ref",
".",
"Partitioner",
"=",
"sarama",
".",
"NewManualPartitioner",
"\n",
"}",
"else",
"{",
"ref",
".",
"Partitioner",
"=",
"sarama",
".",
"NewHashPartitioner",
"\n",
"}",
"\n",
"case",
"Hash",
":",
"ref",
".",
"Partitioner",
"=",
"sarama",
".",
"NewHashPartitioner",
"\n",
"ref",
".",
"Partition",
"=",
"-",
"1",
"\n",
"case",
"Random",
":",
"ref",
".",
"Partitioner",
"=",
"sarama",
".",
"NewRandomPartitioner",
"\n",
"ref",
".",
"Partition",
"=",
"-",
"1",
"\n",
"case",
"Manual",
":",
"ref",
".",
"Partitioner",
"=",
"sarama",
".",
"NewManualPartitioner",
"\n",
"if",
"ref",
".",
"Partition",
"<",
"0",
"{",
"ref",
".",
"Infof",
"(",
"\"",
"\"",
",",
"ref",
".",
"Partition",
")",
"\n",
"ref",
".",
"Partition",
"=",
"0",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // SetPartitioner sets the Config.SetPartitioner field | [
"SetPartitioner",
"sets",
"the",
"Config",
".",
"SetPartitioner",
"field"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/client/config.go#L234-L258 |
4,643 | ligato/cn-infra | messaging/kafka/client/config.go | SetTLS | func (ref *Config) SetTLS(tlsConfig *tls.Config) (err error) {
ref.Net.TLS.Enable = true
ref.Net.TLS.Config = tlsConfig
return nil
} | go | func (ref *Config) SetTLS(tlsConfig *tls.Config) (err error) {
ref.Net.TLS.Enable = true
ref.Net.TLS.Config = tlsConfig
return nil
} | [
"func",
"(",
"ref",
"*",
"Config",
")",
"SetTLS",
"(",
"tlsConfig",
"*",
"tls",
".",
"Config",
")",
"(",
"err",
"error",
")",
"{",
"ref",
".",
"Net",
".",
"TLS",
".",
"Enable",
"=",
"true",
"\n",
"ref",
".",
"Net",
".",
"TLS",
".",
"Config",
"=",
"tlsConfig",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // SetTLS sets the TLS configuration | [
"SetTLS",
"sets",
"the",
"TLS",
"configuration"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/client/config.go#L261-L266 |
4,644 | ligato/cn-infra | messaging/kafka/client/config.go | ValidateAsyncProducerConfig | func (ref *Config) ValidateAsyncProducerConfig() error {
if ref.Brokers == nil {
return errors.New("invalid Brokers - one or more brokers must be specified")
}
if ref.SendSuccess && ref.SuccessChan == nil {
return errors.New("success channel not specified")
}
if ref.SendError && ref.ErrorChan == nil {
return errors.New("error channel not specified")
}
return ref.ProducerConfig().Validate()
} | go | func (ref *Config) ValidateAsyncProducerConfig() error {
if ref.Brokers == nil {
return errors.New("invalid Brokers - one or more brokers must be specified")
}
if ref.SendSuccess && ref.SuccessChan == nil {
return errors.New("success channel not specified")
}
if ref.SendError && ref.ErrorChan == nil {
return errors.New("error channel not specified")
}
return ref.ProducerConfig().Validate()
} | [
"func",
"(",
"ref",
"*",
"Config",
")",
"ValidateAsyncProducerConfig",
"(",
")",
"error",
"{",
"if",
"ref",
".",
"Brokers",
"==",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"ref",
".",
"SendSuccess",
"&&",
"ref",
".",
"SuccessChan",
"==",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"ref",
".",
"SendError",
"&&",
"ref",
".",
"ErrorChan",
"==",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"ref",
".",
"ProducerConfig",
"(",
")",
".",
"Validate",
"(",
")",
"\n",
"}"
] | // ValidateAsyncProducerConfig validates config for an Async Producer | [
"ValidateAsyncProducerConfig",
"validates",
"config",
"for",
"an",
"Async",
"Producer"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/client/config.go#L269-L280 |
4,645 | ligato/cn-infra | messaging/kafka/client/config.go | ValidateSyncProducerConfig | func (ref *Config) ValidateSyncProducerConfig() error {
if ref.Brokers == nil {
return errors.New("invalid Brokers - one or more brokers must be specified")
}
return ref.ProducerConfig().Validate()
} | go | func (ref *Config) ValidateSyncProducerConfig() error {
if ref.Brokers == nil {
return errors.New("invalid Brokers - one or more brokers must be specified")
}
return ref.ProducerConfig().Validate()
} | [
"func",
"(",
"ref",
"*",
"Config",
")",
"ValidateSyncProducerConfig",
"(",
")",
"error",
"{",
"if",
"ref",
".",
"Brokers",
"==",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"ref",
".",
"ProducerConfig",
"(",
")",
".",
"Validate",
"(",
")",
"\n",
"}"
] | // ValidateSyncProducerConfig validates config for a Sync Producer | [
"ValidateSyncProducerConfig",
"validates",
"config",
"for",
"a",
"Sync",
"Producer"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/client/config.go#L283-L288 |
4,646 | ligato/cn-infra | messaging/kafka/client/config.go | ValidateConsumerConfig | func (ref *Config) ValidateConsumerConfig() error {
if ref.Brokers == nil {
return errors.New("invalid Brokers - one or more brokers must be specified")
}
if ref.GroupID == "" {
return errors.New("invalid GroupID - no GroupID specified")
}
if ref.RecvNotification && ref.RecvNotificationChan == nil {
return errors.New("notification channel not specified")
}
if ref.RecvError && ref.RecvErrorChan == nil {
return errors.New("error channel not specified")
}
if ref.RecvMessageChan == nil {
return errors.New("recvMessageChan not specified")
}
return ref.ConsumerConfig().Validate()
} | go | func (ref *Config) ValidateConsumerConfig() error {
if ref.Brokers == nil {
return errors.New("invalid Brokers - one or more brokers must be specified")
}
if ref.GroupID == "" {
return errors.New("invalid GroupID - no GroupID specified")
}
if ref.RecvNotification && ref.RecvNotificationChan == nil {
return errors.New("notification channel not specified")
}
if ref.RecvError && ref.RecvErrorChan == nil {
return errors.New("error channel not specified")
}
if ref.RecvMessageChan == nil {
return errors.New("recvMessageChan not specified")
}
return ref.ConsumerConfig().Validate()
} | [
"func",
"(",
"ref",
"*",
"Config",
")",
"ValidateConsumerConfig",
"(",
")",
"error",
"{",
"if",
"ref",
".",
"Brokers",
"==",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"ref",
".",
"GroupID",
"==",
"\"",
"\"",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"ref",
".",
"RecvNotification",
"&&",
"ref",
".",
"RecvNotificationChan",
"==",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"ref",
".",
"RecvError",
"&&",
"ref",
".",
"RecvErrorChan",
"==",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"ref",
".",
"RecvMessageChan",
"==",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"ref",
".",
"ConsumerConfig",
"(",
")",
".",
"Validate",
"(",
")",
"\n",
"}"
] | // ValidateConsumerConfig validates config for Consumer | [
"ValidateConsumerConfig",
"validates",
"config",
"for",
"Consumer"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/messaging/kafka/client/config.go#L291-L308 |
4,647 | ligato/cn-infra | db/keyval/consul/consul.go | NewClient | func NewClient(cfg *api.Config) (store *Client, err error) {
var c *api.Client
if c, err = api.NewClient(cfg); err != nil {
return nil, fmt.Errorf("failed to create Consul client %s", err)
}
peers, err := c.Status().Peers()
if err != nil {
return nil, err
}
consulLogger.Infof("consul peers: %v", peers)
return &Client{
client: c,
}, nil
} | go | func NewClient(cfg *api.Config) (store *Client, err error) {
var c *api.Client
if c, err = api.NewClient(cfg); err != nil {
return nil, fmt.Errorf("failed to create Consul client %s", err)
}
peers, err := c.Status().Peers()
if err != nil {
return nil, err
}
consulLogger.Infof("consul peers: %v", peers)
return &Client{
client: c,
}, nil
} | [
"func",
"NewClient",
"(",
"cfg",
"*",
"api",
".",
"Config",
")",
"(",
"store",
"*",
"Client",
",",
"err",
"error",
")",
"{",
"var",
"c",
"*",
"api",
".",
"Client",
"\n",
"if",
"c",
",",
"err",
"=",
"api",
".",
"NewClient",
"(",
"cfg",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"peers",
",",
"err",
":=",
"c",
".",
"Status",
"(",
")",
".",
"Peers",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"consulLogger",
".",
"Infof",
"(",
"\"",
"\"",
",",
"peers",
")",
"\n\n",
"return",
"&",
"Client",
"{",
"client",
":",
"c",
",",
"}",
",",
"nil",
"\n\n",
"}"
] | // NewClient creates new client for Consul using given address. | [
"NewClient",
"creates",
"new",
"client",
"for",
"Consul",
"using",
"given",
"address",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/consul/consul.go#L50-L66 |
4,648 | ligato/cn-infra | db/keyval/consul/consul.go | Put | func (c *Client) Put(key string, data []byte, opts ...datasync.PutOption) error {
consulLogger.Debugf("Put: %q", key)
p := &api.KVPair{Key: transformKey(key), Value: data}
_, err := c.client.KV().Put(p, nil)
if err != nil {
return err
}
return nil
} | go | func (c *Client) Put(key string, data []byte, opts ...datasync.PutOption) error {
consulLogger.Debugf("Put: %q", key)
p := &api.KVPair{Key: transformKey(key), Value: data}
_, err := c.client.KV().Put(p, nil)
if err != nil {
return err
}
return nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Put",
"(",
"key",
"string",
",",
"data",
"[",
"]",
"byte",
",",
"opts",
"...",
"datasync",
".",
"PutOption",
")",
"error",
"{",
"consulLogger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"key",
")",
"\n",
"p",
":=",
"&",
"api",
".",
"KVPair",
"{",
"Key",
":",
"transformKey",
"(",
"key",
")",
",",
"Value",
":",
"data",
"}",
"\n",
"_",
",",
"err",
":=",
"c",
".",
"client",
".",
"KV",
"(",
")",
".",
"Put",
"(",
"p",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Put stores given data for the key. | [
"Put",
"stores",
"given",
"data",
"for",
"the",
"key",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/consul/consul.go#L69-L78 |
4,649 | ligato/cn-infra | db/keyval/consul/consul.go | GetValue | func (c *Client) GetValue(key string) (data []byte, found bool, revision int64, err error) {
consulLogger.Debugf("GetValue: %q", key)
pair, _, err := c.client.KV().Get(transformKey(key), nil)
if err != nil {
return nil, false, 0, err
} else if pair == nil {
return nil, false, 0, nil
}
return pair.Value, true, int64(pair.ModifyIndex), nil
} | go | func (c *Client) GetValue(key string) (data []byte, found bool, revision int64, err error) {
consulLogger.Debugf("GetValue: %q", key)
pair, _, err := c.client.KV().Get(transformKey(key), nil)
if err != nil {
return nil, false, 0, err
} else if pair == nil {
return nil, false, 0, nil
}
return pair.Value, true, int64(pair.ModifyIndex), nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"GetValue",
"(",
"key",
"string",
")",
"(",
"data",
"[",
"]",
"byte",
",",
"found",
"bool",
",",
"revision",
"int64",
",",
"err",
"error",
")",
"{",
"consulLogger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"key",
")",
"\n",
"pair",
",",
"_",
",",
"err",
":=",
"c",
".",
"client",
".",
"KV",
"(",
")",
".",
"Get",
"(",
"transformKey",
"(",
"key",
")",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"false",
",",
"0",
",",
"err",
"\n",
"}",
"else",
"if",
"pair",
"==",
"nil",
"{",
"return",
"nil",
",",
"false",
",",
"0",
",",
"nil",
"\n",
"}",
"\n\n",
"return",
"pair",
".",
"Value",
",",
"true",
",",
"int64",
"(",
"pair",
".",
"ModifyIndex",
")",
",",
"nil",
"\n",
"}"
] | // GetValue returns data for the given key. | [
"GetValue",
"returns",
"data",
"for",
"the",
"given",
"key",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/consul/consul.go#L88-L98 |
4,650 | ligato/cn-infra | db/keyval/consul/consul.go | ListValues | func (c *Client) ListValues(key string) (keyval.BytesKeyValIterator, error) {
pairs, _, err := c.client.KV().List(transformKey(key), nil)
if err != nil {
return nil, err
}
return &bytesKeyValIterator{len: len(pairs), pairs: pairs}, nil
} | go | func (c *Client) ListValues(key string) (keyval.BytesKeyValIterator, error) {
pairs, _, err := c.client.KV().List(transformKey(key), nil)
if err != nil {
return nil, err
}
return &bytesKeyValIterator{len: len(pairs), pairs: pairs}, nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"ListValues",
"(",
"key",
"string",
")",
"(",
"keyval",
".",
"BytesKeyValIterator",
",",
"error",
")",
"{",
"pairs",
",",
"_",
",",
"err",
":=",
"c",
".",
"client",
".",
"KV",
"(",
")",
".",
"List",
"(",
"transformKey",
"(",
"key",
")",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"bytesKeyValIterator",
"{",
"len",
":",
"len",
"(",
"pairs",
")",
",",
"pairs",
":",
"pairs",
"}",
",",
"nil",
"\n",
"}"
] | // ListValues returns interator with key-value pairs for given key prefix. | [
"ListValues",
"returns",
"interator",
"with",
"key",
"-",
"value",
"pairs",
"for",
"given",
"key",
"prefix",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/consul/consul.go#L101-L108 |
4,651 | ligato/cn-infra | db/keyval/consul/consul.go | ListKeys | func (c *Client) ListKeys(prefix string) (keyval.BytesKeyIterator, error) {
keys, _, err := c.client.KV().Keys(transformKey(prefix), "", nil)
if err != nil {
return nil, err
}
return &bytesKeyIterator{len: len(keys), keys: keys}, nil
} | go | func (c *Client) ListKeys(prefix string) (keyval.BytesKeyIterator, error) {
keys, _, err := c.client.KV().Keys(transformKey(prefix), "", nil)
if err != nil {
return nil, err
}
return &bytesKeyIterator{len: len(keys), keys: keys}, nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"ListKeys",
"(",
"prefix",
"string",
")",
"(",
"keyval",
".",
"BytesKeyIterator",
",",
"error",
")",
"{",
"keys",
",",
"_",
",",
"err",
":=",
"c",
".",
"client",
".",
"KV",
"(",
")",
".",
"Keys",
"(",
"transformKey",
"(",
"prefix",
")",
",",
"\"",
"\"",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"bytesKeyIterator",
"{",
"len",
":",
"len",
"(",
"keys",
")",
",",
"keys",
":",
"keys",
"}",
",",
"nil",
"\n",
"}"
] | // ListKeys returns interator with keys for given key prefix. | [
"ListKeys",
"returns",
"interator",
"with",
"keys",
"for",
"given",
"key",
"prefix",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/consul/consul.go#L111-L118 |
4,652 | ligato/cn-infra | db/keyval/consul/consul.go | Delete | func (c *Client) Delete(key string, opts ...datasync.DelOption) (existed bool, err error) {
consulLogger.Debugf("Delete: %q", key)
if _, err := c.client.KV().Delete(transformKey(key), nil); err != nil {
return false, err
}
return true, nil
} | go | func (c *Client) Delete(key string, opts ...datasync.DelOption) (existed bool, err error) {
consulLogger.Debugf("Delete: %q", key)
if _, err := c.client.KV().Delete(transformKey(key), nil); err != nil {
return false, err
}
return true, nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"Delete",
"(",
"key",
"string",
",",
"opts",
"...",
"datasync",
".",
"DelOption",
")",
"(",
"existed",
"bool",
",",
"err",
"error",
")",
"{",
"consulLogger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"key",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"c",
".",
"client",
".",
"KV",
"(",
")",
".",
"Delete",
"(",
"transformKey",
"(",
"key",
")",
",",
"nil",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"true",
",",
"nil",
"\n",
"}"
] | // Delete deletes given key. | [
"Delete",
"deletes",
"given",
"key",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/consul/consul.go#L121-L128 |
4,653 | ligato/cn-infra | rpc/rest/mock/httpmock.go | NewRequest | func (mock *HTTPMock) NewRequest(method, url string, body io.Reader) (*http.Response, error) {
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, err
}
recorder := httptest.NewRecorder()
mock.handler.ServeHTTP(recorder, req)
return recorder.Result(), nil
} | go | func (mock *HTTPMock) NewRequest(method, url string, body io.Reader) (*http.Response, error) {
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, err
}
recorder := httptest.NewRecorder()
mock.handler.ServeHTTP(recorder, req)
return recorder.Result(), nil
} | [
"func",
"(",
"mock",
"*",
"HTTPMock",
")",
"NewRequest",
"(",
"method",
",",
"url",
"string",
",",
"body",
"io",
".",
"Reader",
")",
"(",
"*",
"http",
".",
"Response",
",",
"error",
")",
"{",
"req",
",",
"err",
":=",
"http",
".",
"NewRequest",
"(",
"method",
",",
"url",
",",
"body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"recorder",
":=",
"httptest",
".",
"NewRecorder",
"(",
")",
"\n",
"mock",
".",
"handler",
".",
"ServeHTTP",
"(",
"recorder",
",",
"req",
")",
"\n",
"return",
"recorder",
".",
"Result",
"(",
")",
",",
"nil",
"\n",
"}"
] | // NewRequest propagates the request to the httpmux | [
"NewRequest",
"propagates",
"the",
"request",
"to",
"the",
"httpmux"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/rpc/rest/mock/httpmock.go#L45-L54 |
4,654 | ligato/cn-infra | db/cryptodata/decrypter.go | IsEncrypted | func (d DecrypterJSON) IsEncrypted(object interface{}) bool {
inData, ok := object.([]byte)
if !ok {
return false
}
var jsonData EncryptionCheck
err := json.Unmarshal(inData, &jsonData)
return err == nil && jsonData.IsEncrypted
} | go | func (d DecrypterJSON) IsEncrypted(object interface{}) bool {
inData, ok := object.([]byte)
if !ok {
return false
}
var jsonData EncryptionCheck
err := json.Unmarshal(inData, &jsonData)
return err == nil && jsonData.IsEncrypted
} | [
"func",
"(",
"d",
"DecrypterJSON",
")",
"IsEncrypted",
"(",
"object",
"interface",
"{",
"}",
")",
"bool",
"{",
"inData",
",",
"ok",
":=",
"object",
".",
"(",
"[",
"]",
"byte",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"false",
"\n",
"}",
"\n\n",
"var",
"jsonData",
"EncryptionCheck",
"\n",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"inData",
",",
"&",
"jsonData",
")",
"\n",
"return",
"err",
"==",
"nil",
"&&",
"jsonData",
".",
"IsEncrypted",
"\n",
"}"
] | // IsEncrypted checks if provided data are marked as encrypted. First it tries to unmarshal JSON to EncryptionCheck
// and then check the IsEncrypted for being true | [
"IsEncrypted",
"checks",
"if",
"provided",
"data",
"are",
"marked",
"as",
"encrypted",
".",
"First",
"it",
"tries",
"to",
"unmarshal",
"JSON",
"to",
"EncryptionCheck",
"and",
"then",
"check",
"the",
"IsEncrypted",
"for",
"being",
"true"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/cryptodata/decrypter.go#L63-L72 |
4,655 | ligato/cn-infra | db/cryptodata/decrypter.go | decryptJSON | func (d DecrypterJSON) decryptJSON(data map[string]interface{}, decryptFunc DecryptFunc) error {
for k, v := range data {
switch t := v.(type) {
case string:
if s := strings.TrimPrefix(t, d.prefix); s != t {
s, err := base64.URLEncoding.DecodeString(s)
if err != nil {
return err
}
decryptedData, err := decryptFunc(s)
if err != nil {
return err
}
data[k] = string(decryptedData)
}
case map[string]interface{}:
err := d.decryptJSON(t, decryptFunc)
if err != nil {
return err
}
}
}
return nil
} | go | func (d DecrypterJSON) decryptJSON(data map[string]interface{}, decryptFunc DecryptFunc) error {
for k, v := range data {
switch t := v.(type) {
case string:
if s := strings.TrimPrefix(t, d.prefix); s != t {
s, err := base64.URLEncoding.DecodeString(s)
if err != nil {
return err
}
decryptedData, err := decryptFunc(s)
if err != nil {
return err
}
data[k] = string(decryptedData)
}
case map[string]interface{}:
err := d.decryptJSON(t, decryptFunc)
if err != nil {
return err
}
}
}
return nil
} | [
"func",
"(",
"d",
"DecrypterJSON",
")",
"decryptJSON",
"(",
"data",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"decryptFunc",
"DecryptFunc",
")",
"error",
"{",
"for",
"k",
",",
"v",
":=",
"range",
"data",
"{",
"switch",
"t",
":=",
"v",
".",
"(",
"type",
")",
"{",
"case",
"string",
":",
"if",
"s",
":=",
"strings",
".",
"TrimPrefix",
"(",
"t",
",",
"d",
".",
"prefix",
")",
";",
"s",
"!=",
"t",
"{",
"s",
",",
"err",
":=",
"base64",
".",
"URLEncoding",
".",
"DecodeString",
"(",
"s",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"decryptedData",
",",
"err",
":=",
"decryptFunc",
"(",
"s",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"data",
"[",
"k",
"]",
"=",
"string",
"(",
"decryptedData",
")",
"\n",
"}",
"\n",
"case",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
":",
"err",
":=",
"d",
".",
"decryptJSON",
"(",
"t",
",",
"decryptFunc",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // decryptJSON recursively navigates JSON structure and tries to decrypt all string values with Prefix | [
"decryptJSON",
"recursively",
"navigates",
"JSON",
"structure",
"and",
"tries",
"to",
"decrypt",
"all",
"string",
"values",
"with",
"Prefix"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/cryptodata/decrypter.go#L100-L126 |
4,656 | ligato/cn-infra | db/cryptodata/decrypter.go | RegisterMapping | func (d DecrypterProto) RegisterMapping(object proto.Message, paths ...[]string) {
d.mapping[reflect.TypeOf(object)] = paths
} | go | func (d DecrypterProto) RegisterMapping(object proto.Message, paths ...[]string) {
d.mapping[reflect.TypeOf(object)] = paths
} | [
"func",
"(",
"d",
"DecrypterProto",
")",
"RegisterMapping",
"(",
"object",
"proto",
".",
"Message",
",",
"paths",
"...",
"[",
"]",
"string",
")",
"{",
"d",
".",
"mapping",
"[",
"reflect",
".",
"TypeOf",
"(",
"object",
")",
"]",
"=",
"paths",
"\n",
"}"
] | // RegisterMapping registers mapping to decrypter that maps proto.Message type to path used to access encrypted values | [
"RegisterMapping",
"registers",
"mapping",
"to",
"decrypter",
"that",
"maps",
"proto",
".",
"Message",
"type",
"to",
"path",
"used",
"to",
"access",
"encrypted",
"values"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/cryptodata/decrypter.go#L140-L142 |
4,657 | ligato/cn-infra | db/cryptodata/decrypter.go | IsEncrypted | func (d DecrypterProto) IsEncrypted(object interface{}) bool {
_, ok := object.(proto.Message)
if !ok {
return false
}
_, ok = d.mapping[reflect.TypeOf(object)]
return ok
} | go | func (d DecrypterProto) IsEncrypted(object interface{}) bool {
_, ok := object.(proto.Message)
if !ok {
return false
}
_, ok = d.mapping[reflect.TypeOf(object)]
return ok
} | [
"func",
"(",
"d",
"DecrypterProto",
")",
"IsEncrypted",
"(",
"object",
"interface",
"{",
"}",
")",
"bool",
"{",
"_",
",",
"ok",
":=",
"object",
".",
"(",
"proto",
".",
"Message",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"false",
"\n",
"}",
"\n",
"_",
",",
"ok",
"=",
"d",
".",
"mapping",
"[",
"reflect",
".",
"TypeOf",
"(",
"object",
")",
"]",
"\n",
"return",
"ok",
"\n",
"}"
] | // IsEncrypted checks if provided data type is contained in the Mapping | [
"IsEncrypted",
"checks",
"if",
"provided",
"data",
"type",
"is",
"contained",
"in",
"the",
"Mapping"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/cryptodata/decrypter.go#L145-L152 |
4,658 | ligato/cn-infra | db/cryptodata/decrypter.go | Decrypt | func (d DecrypterProto) Decrypt(object interface{}, decryptFunc DecryptFunc) (interface{}, error) {
if !d.IsEncrypted(object) {
return object, nil
}
for _, path := range d.mapping[reflect.TypeOf(object)] {
if err := d.decryptStruct(object, path, decryptFunc); err != nil {
return nil, err
}
}
return object, nil
} | go | func (d DecrypterProto) Decrypt(object interface{}, decryptFunc DecryptFunc) (interface{}, error) {
if !d.IsEncrypted(object) {
return object, nil
}
for _, path := range d.mapping[reflect.TypeOf(object)] {
if err := d.decryptStruct(object, path, decryptFunc); err != nil {
return nil, err
}
}
return object, nil
} | [
"func",
"(",
"d",
"DecrypterProto",
")",
"Decrypt",
"(",
"object",
"interface",
"{",
"}",
",",
"decryptFunc",
"DecryptFunc",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"if",
"!",
"d",
".",
"IsEncrypted",
"(",
"object",
")",
"{",
"return",
"object",
",",
"nil",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"path",
":=",
"range",
"d",
".",
"mapping",
"[",
"reflect",
".",
"TypeOf",
"(",
"object",
")",
"]",
"{",
"if",
"err",
":=",
"d",
".",
"decryptStruct",
"(",
"object",
",",
"path",
",",
"decryptFunc",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"object",
",",
"nil",
"\n",
"}"
] | // Decrypt tries to find encrypted values in protobuf data and decrypt them. It uses IsEncrypted function on the
// data to check if it contains any encrypted data.
// Then it goes through provided mapping and tries to reflect all fields in the mapping and decrypt string values the
// mappings must point to.
// This function can accept only proto.Message and return proto.Message | [
"Decrypt",
"tries",
"to",
"find",
"encrypted",
"values",
"in",
"protobuf",
"data",
"and",
"decrypt",
"them",
".",
"It",
"uses",
"IsEncrypted",
"function",
"on",
"the",
"data",
"to",
"check",
"if",
"it",
"contains",
"any",
"encrypted",
"data",
".",
"Then",
"it",
"goes",
"through",
"provided",
"mapping",
"and",
"tries",
"to",
"reflect",
"all",
"fields",
"in",
"the",
"mapping",
"and",
"decrypt",
"string",
"values",
"the",
"mappings",
"must",
"point",
"to",
".",
"This",
"function",
"can",
"accept",
"only",
"proto",
".",
"Message",
"and",
"return",
"proto",
".",
"Message"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/cryptodata/decrypter.go#L159-L171 |
4,659 | ligato/cn-infra | db/cryptodata/decrypter.go | decryptStruct | func (d DecrypterProto) decryptStruct(object interface{}, path []string, decryptFunc DecryptFunc) error {
v, ok := object.(reflect.Value)
if !ok {
v = reflect.ValueOf(object)
}
for pathIndex, key := range path {
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
if v.Kind() == reflect.Struct {
v = v.FieldByName(key)
}
if v.Kind() == reflect.Slice {
for i := 0; i < v.Len(); i++ {
val := v.Index(i)
kind := val.Kind()
index := pathIndex
if kind == reflect.Struct || kind == reflect.Ptr {
index++
}
if err := d.decryptStruct(val, path[index:], decryptFunc); err != nil {
return err
}
}
return nil
}
if v.Kind() == reflect.String {
val := v.String()
if val == "" {
continue
}
decoded, err := base64.URLEncoding.DecodeString(val)
if err != nil {
return err
}
decrypted, err := decryptFunc(decoded)
if err != nil {
return err
}
v.SetString(string(decrypted))
return nil
}
return fmt.Errorf("failed to process path on %v", v)
}
return nil
} | go | func (d DecrypterProto) decryptStruct(object interface{}, path []string, decryptFunc DecryptFunc) error {
v, ok := object.(reflect.Value)
if !ok {
v = reflect.ValueOf(object)
}
for pathIndex, key := range path {
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
if v.Kind() == reflect.Struct {
v = v.FieldByName(key)
}
if v.Kind() == reflect.Slice {
for i := 0; i < v.Len(); i++ {
val := v.Index(i)
kind := val.Kind()
index := pathIndex
if kind == reflect.Struct || kind == reflect.Ptr {
index++
}
if err := d.decryptStruct(val, path[index:], decryptFunc); err != nil {
return err
}
}
return nil
}
if v.Kind() == reflect.String {
val := v.String()
if val == "" {
continue
}
decoded, err := base64.URLEncoding.DecodeString(val)
if err != nil {
return err
}
decrypted, err := decryptFunc(decoded)
if err != nil {
return err
}
v.SetString(string(decrypted))
return nil
}
return fmt.Errorf("failed to process path on %v", v)
}
return nil
} | [
"func",
"(",
"d",
"DecrypterProto",
")",
"decryptStruct",
"(",
"object",
"interface",
"{",
"}",
",",
"path",
"[",
"]",
"string",
",",
"decryptFunc",
"DecryptFunc",
")",
"error",
"{",
"v",
",",
"ok",
":=",
"object",
".",
"(",
"reflect",
".",
"Value",
")",
"\n",
"if",
"!",
"ok",
"{",
"v",
"=",
"reflect",
".",
"ValueOf",
"(",
"object",
")",
"\n",
"}",
"\n\n",
"for",
"pathIndex",
",",
"key",
":=",
"range",
"path",
"{",
"if",
"v",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Ptr",
"{",
"v",
"=",
"v",
".",
"Elem",
"(",
")",
"\n",
"}",
"\n\n",
"if",
"v",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Struct",
"{",
"v",
"=",
"v",
".",
"FieldByName",
"(",
"key",
")",
"\n",
"}",
"\n\n",
"if",
"v",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Slice",
"{",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"v",
".",
"Len",
"(",
")",
";",
"i",
"++",
"{",
"val",
":=",
"v",
".",
"Index",
"(",
"i",
")",
"\n",
"kind",
":=",
"val",
".",
"Kind",
"(",
")",
"\n",
"index",
":=",
"pathIndex",
"\n\n",
"if",
"kind",
"==",
"reflect",
".",
"Struct",
"||",
"kind",
"==",
"reflect",
".",
"Ptr",
"{",
"index",
"++",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"d",
".",
"decryptStruct",
"(",
"val",
",",
"path",
"[",
"index",
":",
"]",
",",
"decryptFunc",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"if",
"v",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"String",
"{",
"val",
":=",
"v",
".",
"String",
"(",
")",
"\n",
"if",
"val",
"==",
"\"",
"\"",
"{",
"continue",
"\n",
"}",
"\n\n",
"decoded",
",",
"err",
":=",
"base64",
".",
"URLEncoding",
".",
"DecodeString",
"(",
"val",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"decrypted",
",",
"err",
":=",
"decryptFunc",
"(",
"decoded",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"v",
".",
"SetString",
"(",
"string",
"(",
"decrypted",
")",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"v",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // decryptStruct recursively tries to decrypt fields in object on provided path using provided decryptFunc | [
"decryptStruct",
"recursively",
"tries",
"to",
"decrypt",
"fields",
"in",
"object",
"on",
"provided",
"path",
"using",
"provided",
"decryptFunc"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/cryptodata/decrypter.go#L174-L231 |
4,660 | ligato/cn-infra | rpc/rest/config.go | FixConfig | func FixConfig(cfg *Config) {
if cfg == nil {
return
}
if cfg.Endpoint == "" {
cfg.Endpoint = DefaultEndpoint
}
} | go | func FixConfig(cfg *Config) {
if cfg == nil {
return
}
if cfg.Endpoint == "" {
cfg.Endpoint = DefaultEndpoint
}
} | [
"func",
"FixConfig",
"(",
"cfg",
"*",
"Config",
")",
"{",
"if",
"cfg",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"if",
"cfg",
".",
"Endpoint",
"==",
"\"",
"\"",
"{",
"cfg",
".",
"Endpoint",
"=",
"DefaultEndpoint",
"\n",
"}",
"\n",
"}"
] | // FixConfig fill default values for empty fields | [
"FixConfig",
"fill",
"default",
"values",
"for",
"empty",
"fields"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/rpc/rest/config.go#L140-L147 |
4,661 | ligato/cn-infra | examples/process-manager-plugin/templates/main.go | runExample | func (p *PMExample) runExample() {
// Process templates (create a template, start process using template)
if err := p.templateExample(); err != nil {
p.Log.Errorf("simple process manager example failed with error: %v", err)
}
close(p.finished)
return
} | go | func (p *PMExample) runExample() {
// Process templates (create a template, start process using template)
if err := p.templateExample(); err != nil {
p.Log.Errorf("simple process manager example failed with error: %v", err)
}
close(p.finished)
return
} | [
"func",
"(",
"p",
"*",
"PMExample",
")",
"runExample",
"(",
")",
"{",
"// Process templates (create a template, start process using template)",
"if",
"err",
":=",
"p",
".",
"templateExample",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"p",
".",
"Log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"close",
"(",
"p",
".",
"finished",
")",
"\n",
"return",
"\n",
"}"
] | // Runs example with step by step description | [
"Runs",
"example",
"with",
"step",
"by",
"step",
"description"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/examples/process-manager-plugin/templates/main.go#L78-L85 |
4,662 | ligato/cn-infra | db/keyval/filedb/filesystem/mock_filesystem.go | NewFileSystemMock | func NewFileSystemMock() *Mock {
return &Mock{
responses: make([]*WhenResp, 0),
eventChan: make(chan fsnotify.Event),
}
} | go | func NewFileSystemMock() *Mock {
return &Mock{
responses: make([]*WhenResp, 0),
eventChan: make(chan fsnotify.Event),
}
} | [
"func",
"NewFileSystemMock",
"(",
")",
"*",
"Mock",
"{",
"return",
"&",
"Mock",
"{",
"responses",
":",
"make",
"(",
"[",
"]",
"*",
"WhenResp",
",",
"0",
")",
",",
"eventChan",
":",
"make",
"(",
"chan",
"fsnotify",
".",
"Event",
")",
",",
"}",
"\n",
"}"
] | // NewFileSystemMock creates new instance of the mock and initializes response list | [
"NewFileSystemMock",
"creates",
"new",
"instance",
"of",
"the",
"mock",
"and",
"initializes",
"response",
"list"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/filesystem/mock_filesystem.go#L28-L33 |
4,663 | ligato/cn-infra | db/keyval/filedb/filesystem/mock_filesystem.go | CreateFile | func (mock *Mock) CreateFile(file string) error {
items := mock.getReturnValues("CreateFile")
return items[0].(error)
} | go | func (mock *Mock) CreateFile(file string) error {
items := mock.getReturnValues("CreateFile")
return items[0].(error)
} | [
"func",
"(",
"mock",
"*",
"Mock",
")",
"CreateFile",
"(",
"file",
"string",
")",
"error",
"{",
"items",
":=",
"mock",
".",
"getReturnValues",
"(",
"\"",
"\"",
")",
"\n",
"return",
"items",
"[",
"0",
"]",
".",
"(",
"error",
")",
"\n",
"}"
] | // CreateFile mocks original method | [
"CreateFile",
"mocks",
"original",
"method"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/filesystem/mock_filesystem.go#L81-L84 |
4,664 | ligato/cn-infra | db/keyval/filedb/filesystem/mock_filesystem.go | ReadFile | func (mock *Mock) ReadFile(file string) ([]byte, error) {
items := mock.getReturnValues("ReadFile")
if len(items) == 1 {
switch typed := items[0].(type) {
case []byte:
return typed, nil
case error:
return []byte{}, typed
}
} else if len(items) == 2 {
return items[0].([]byte), items[1].(error)
}
return []byte{}, nil
} | go | func (mock *Mock) ReadFile(file string) ([]byte, error) {
items := mock.getReturnValues("ReadFile")
if len(items) == 1 {
switch typed := items[0].(type) {
case []byte:
return typed, nil
case error:
return []byte{}, typed
}
} else if len(items) == 2 {
return items[0].([]byte), items[1].(error)
}
return []byte{}, nil
} | [
"func",
"(",
"mock",
"*",
"Mock",
")",
"ReadFile",
"(",
"file",
"string",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"items",
":=",
"mock",
".",
"getReturnValues",
"(",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"items",
")",
"==",
"1",
"{",
"switch",
"typed",
":=",
"items",
"[",
"0",
"]",
".",
"(",
"type",
")",
"{",
"case",
"[",
"]",
"byte",
":",
"return",
"typed",
",",
"nil",
"\n",
"case",
"error",
":",
"return",
"[",
"]",
"byte",
"{",
"}",
",",
"typed",
"\n",
"}",
"\n",
"}",
"else",
"if",
"len",
"(",
"items",
")",
"==",
"2",
"{",
"return",
"items",
"[",
"0",
"]",
".",
"(",
"[",
"]",
"byte",
")",
",",
"items",
"[",
"1",
"]",
".",
"(",
"error",
")",
"\n",
"}",
"\n",
"return",
"[",
"]",
"byte",
"{",
"}",
",",
"nil",
"\n",
"}"
] | // ReadFile mocks original method | [
"ReadFile",
"mocks",
"original",
"method"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/filesystem/mock_filesystem.go#L87-L100 |
4,665 | ligato/cn-infra | db/keyval/filedb/filesystem/mock_filesystem.go | WriteFile | func (mock *Mock) WriteFile(file string, data []byte) error {
items := mock.getReturnValues("WriteFile")
return items[0].(error)
} | go | func (mock *Mock) WriteFile(file string, data []byte) error {
items := mock.getReturnValues("WriteFile")
return items[0].(error)
} | [
"func",
"(",
"mock",
"*",
"Mock",
")",
"WriteFile",
"(",
"file",
"string",
",",
"data",
"[",
"]",
"byte",
")",
"error",
"{",
"items",
":=",
"mock",
".",
"getReturnValues",
"(",
"\"",
"\"",
")",
"\n",
"return",
"items",
"[",
"0",
"]",
".",
"(",
"error",
")",
"\n",
"}"
] | // WriteFile mocks original method | [
"WriteFile",
"mocks",
"original",
"method"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/filesystem/mock_filesystem.go#L103-L106 |
4,666 | ligato/cn-infra | db/keyval/filedb/filesystem/mock_filesystem.go | FileExists | func (mock *Mock) FileExists(file string) bool {
items := mock.getReturnValues("FileExists")
return items[0].(bool)
} | go | func (mock *Mock) FileExists(file string) bool {
items := mock.getReturnValues("FileExists")
return items[0].(bool)
} | [
"func",
"(",
"mock",
"*",
"Mock",
")",
"FileExists",
"(",
"file",
"string",
")",
"bool",
"{",
"items",
":=",
"mock",
".",
"getReturnValues",
"(",
"\"",
"\"",
")",
"\n",
"return",
"items",
"[",
"0",
"]",
".",
"(",
"bool",
")",
"\n",
"}"
] | // FileExists mocks original method | [
"FileExists",
"mocks",
"original",
"method"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/filesystem/mock_filesystem.go#L109-L112 |
4,667 | ligato/cn-infra | db/keyval/filedb/filesystem/mock_filesystem.go | GetFileNames | func (mock *Mock) GetFileNames(paths []string) ([]string, error) {
items := mock.getReturnValues("GetFileNames")
if len(items) == 1 {
switch typed := items[0].(type) {
case []string:
return typed, nil
case error:
return []string{}, typed
}
} else if len(items) == 2 {
return items[0].([]string), items[1].(error)
}
return []string{}, nil
} | go | func (mock *Mock) GetFileNames(paths []string) ([]string, error) {
items := mock.getReturnValues("GetFileNames")
if len(items) == 1 {
switch typed := items[0].(type) {
case []string:
return typed, nil
case error:
return []string{}, typed
}
} else if len(items) == 2 {
return items[0].([]string), items[1].(error)
}
return []string{}, nil
} | [
"func",
"(",
"mock",
"*",
"Mock",
")",
"GetFileNames",
"(",
"paths",
"[",
"]",
"string",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"items",
":=",
"mock",
".",
"getReturnValues",
"(",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"items",
")",
"==",
"1",
"{",
"switch",
"typed",
":=",
"items",
"[",
"0",
"]",
".",
"(",
"type",
")",
"{",
"case",
"[",
"]",
"string",
":",
"return",
"typed",
",",
"nil",
"\n",
"case",
"error",
":",
"return",
"[",
"]",
"string",
"{",
"}",
",",
"typed",
"\n",
"}",
"\n",
"}",
"else",
"if",
"len",
"(",
"items",
")",
"==",
"2",
"{",
"return",
"items",
"[",
"0",
"]",
".",
"(",
"[",
"]",
"string",
")",
",",
"items",
"[",
"1",
"]",
".",
"(",
"error",
")",
"\n",
"}",
"\n",
"return",
"[",
"]",
"string",
"{",
"}",
",",
"nil",
"\n",
"}"
] | // GetFileNames mocks original method | [
"GetFileNames",
"mocks",
"original",
"method"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/filesystem/mock_filesystem.go#L115-L128 |
4,668 | ligato/cn-infra | db/keyval/filedb/filesystem/mock_filesystem.go | Watch | func (mock *Mock) Watch(paths []string, onEvent func(event fsnotify.Event), onClose func()) error {
go func() {
for {
select {
case event, ok := <-mock.eventChan:
if !ok {
onClose()
return
}
onEvent(event)
}
}
}()
return nil
} | go | func (mock *Mock) Watch(paths []string, onEvent func(event fsnotify.Event), onClose func()) error {
go func() {
for {
select {
case event, ok := <-mock.eventChan:
if !ok {
onClose()
return
}
onEvent(event)
}
}
}()
return nil
} | [
"func",
"(",
"mock",
"*",
"Mock",
")",
"Watch",
"(",
"paths",
"[",
"]",
"string",
",",
"onEvent",
"func",
"(",
"event",
"fsnotify",
".",
"Event",
")",
",",
"onClose",
"func",
"(",
")",
")",
"error",
"{",
"go",
"func",
"(",
")",
"{",
"for",
"{",
"select",
"{",
"case",
"event",
",",
"ok",
":=",
"<-",
"mock",
".",
"eventChan",
":",
"if",
"!",
"ok",
"{",
"onClose",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"onEvent",
"(",
"event",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // Watch calls onEvent when event arrives and onClose when channel is closed | [
"Watch",
"calls",
"onEvent",
"when",
"event",
"arrives",
"and",
"onClose",
"when",
"channel",
"is",
"closed"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/filedb/filesystem/mock_filesystem.go#L131-L145 |
4,669 | ligato/cn-infra | rpc/rest/security/rest_security.go | NewAuthenticator | func NewAuthenticator(router *mux.Router, ctx *Settings, log logging.Logger) AuthenticatorAPI {
a := &authenticator{
router: router,
log: log,
formatter: render.New(render.Options{
IndentJSON: true,
}),
groupDb: make(map[string][]*access.PermissionGroup_Permissions),
expTime: ctx.ExpTime,
}
// Authentication store
if ctx.AuthStore != nil {
a.userDb = ctx.AuthStore
} else {
a.userDb = CreateDefaultAuthDB()
}
// Set token signature
signature = ctx.Signature
if a.expTime == 0 {
a.expTime = defaultExpTime
a.log.Debugf("Token expiration time claim not set, defaulting to 1 hour")
}
// Hash of default admin password, hashed with cost 10
hash := "$2a$10$q5s1LP7xbCJWJlLet1g/h.rGrsHtciILps90bNRdJ.6DRekw9b.zK"
if err := a.userDb.AddUser(admin, hash, []string{admin}); err != nil {
a.log.Errorf("failed to add admin user: %v", err)
}
for _, user := range ctx.Users {
if user.Name == admin {
a.log.Errorf("rejected to create user-defined account named 'admin'")
continue
}
if err := a.userDb.AddUser(user.Name, user.PasswordHash, user.Permissions); err != nil {
a.log.Errorf("failed to add user %s: %v", user.Name, err)
continue
}
a.log.Debug("Registered user %s, permissions: %v", user.Name, user.Permissions)
}
// Admin-group, available by default and always enabled for all URLs
a.groupDb[admin] = []*access.PermissionGroup_Permissions{}
a.registerSecurityHandlers()
return a
} | go | func NewAuthenticator(router *mux.Router, ctx *Settings, log logging.Logger) AuthenticatorAPI {
a := &authenticator{
router: router,
log: log,
formatter: render.New(render.Options{
IndentJSON: true,
}),
groupDb: make(map[string][]*access.PermissionGroup_Permissions),
expTime: ctx.ExpTime,
}
// Authentication store
if ctx.AuthStore != nil {
a.userDb = ctx.AuthStore
} else {
a.userDb = CreateDefaultAuthDB()
}
// Set token signature
signature = ctx.Signature
if a.expTime == 0 {
a.expTime = defaultExpTime
a.log.Debugf("Token expiration time claim not set, defaulting to 1 hour")
}
// Hash of default admin password, hashed with cost 10
hash := "$2a$10$q5s1LP7xbCJWJlLet1g/h.rGrsHtciILps90bNRdJ.6DRekw9b.zK"
if err := a.userDb.AddUser(admin, hash, []string{admin}); err != nil {
a.log.Errorf("failed to add admin user: %v", err)
}
for _, user := range ctx.Users {
if user.Name == admin {
a.log.Errorf("rejected to create user-defined account named 'admin'")
continue
}
if err := a.userDb.AddUser(user.Name, user.PasswordHash, user.Permissions); err != nil {
a.log.Errorf("failed to add user %s: %v", user.Name, err)
continue
}
a.log.Debug("Registered user %s, permissions: %v", user.Name, user.Permissions)
}
// Admin-group, available by default and always enabled for all URLs
a.groupDb[admin] = []*access.PermissionGroup_Permissions{}
a.registerSecurityHandlers()
return a
} | [
"func",
"NewAuthenticator",
"(",
"router",
"*",
"mux",
".",
"Router",
",",
"ctx",
"*",
"Settings",
",",
"log",
"logging",
".",
"Logger",
")",
"AuthenticatorAPI",
"{",
"a",
":=",
"&",
"authenticator",
"{",
"router",
":",
"router",
",",
"log",
":",
"log",
",",
"formatter",
":",
"render",
".",
"New",
"(",
"render",
".",
"Options",
"{",
"IndentJSON",
":",
"true",
",",
"}",
")",
",",
"groupDb",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"*",
"access",
".",
"PermissionGroup_Permissions",
")",
",",
"expTime",
":",
"ctx",
".",
"ExpTime",
",",
"}",
"\n\n",
"// Authentication store",
"if",
"ctx",
".",
"AuthStore",
"!=",
"nil",
"{",
"a",
".",
"userDb",
"=",
"ctx",
".",
"AuthStore",
"\n",
"}",
"else",
"{",
"a",
".",
"userDb",
"=",
"CreateDefaultAuthDB",
"(",
")",
"\n",
"}",
"\n\n",
"// Set token signature",
"signature",
"=",
"ctx",
".",
"Signature",
"\n",
"if",
"a",
".",
"expTime",
"==",
"0",
"{",
"a",
".",
"expTime",
"=",
"defaultExpTime",
"\n",
"a",
".",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Hash of default admin password, hashed with cost 10",
"hash",
":=",
"\"",
"\"",
"\n",
"if",
"err",
":=",
"a",
".",
"userDb",
".",
"AddUser",
"(",
"admin",
",",
"hash",
",",
"[",
"]",
"string",
"{",
"admin",
"}",
")",
";",
"err",
"!=",
"nil",
"{",
"a",
".",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"user",
":=",
"range",
"ctx",
".",
"Users",
"{",
"if",
"user",
".",
"Name",
"==",
"admin",
"{",
"a",
".",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"if",
"err",
":=",
"a",
".",
"userDb",
".",
"AddUser",
"(",
"user",
".",
"Name",
",",
"user",
".",
"PasswordHash",
",",
"user",
".",
"Permissions",
")",
";",
"err",
"!=",
"nil",
"{",
"a",
".",
"log",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"user",
".",
"Name",
",",
"err",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"a",
".",
"log",
".",
"Debug",
"(",
"\"",
"\"",
",",
"user",
".",
"Name",
",",
"user",
".",
"Permissions",
")",
"\n",
"}",
"\n\n",
"// Admin-group, available by default and always enabled for all URLs",
"a",
".",
"groupDb",
"[",
"admin",
"]",
"=",
"[",
"]",
"*",
"access",
".",
"PermissionGroup_Permissions",
"{",
"}",
"\n\n",
"a",
".",
"registerSecurityHandlers",
"(",
")",
"\n\n",
"return",
"a",
"\n",
"}"
] | // NewAuthenticator prepares new instance of authenticator. | [
"NewAuthenticator",
"prepares",
"new",
"instance",
"of",
"authenticator",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/rpc/rest/security/rest_security.go#L110-L159 |
4,670 | ligato/cn-infra | rpc/rest/security/rest_security.go | AddPermissionGroup | func (a *authenticator) AddPermissionGroup(group ...*access.PermissionGroup) {
for _, newPermissionGroup := range group {
if _, ok := a.groupDb[newPermissionGroup.Name]; ok {
a.log.Warnf("permission group %s already exists, skipped")
continue
}
a.log.Debugf("added HTTP permission group %s", newPermissionGroup.Name)
a.groupDb[newPermissionGroup.Name] = newPermissionGroup.Permissions
}
} | go | func (a *authenticator) AddPermissionGroup(group ...*access.PermissionGroup) {
for _, newPermissionGroup := range group {
if _, ok := a.groupDb[newPermissionGroup.Name]; ok {
a.log.Warnf("permission group %s already exists, skipped")
continue
}
a.log.Debugf("added HTTP permission group %s", newPermissionGroup.Name)
a.groupDb[newPermissionGroup.Name] = newPermissionGroup.Permissions
}
} | [
"func",
"(",
"a",
"*",
"authenticator",
")",
"AddPermissionGroup",
"(",
"group",
"...",
"*",
"access",
".",
"PermissionGroup",
")",
"{",
"for",
"_",
",",
"newPermissionGroup",
":=",
"range",
"group",
"{",
"if",
"_",
",",
"ok",
":=",
"a",
".",
"groupDb",
"[",
"newPermissionGroup",
".",
"Name",
"]",
";",
"ok",
"{",
"a",
".",
"log",
".",
"Warnf",
"(",
"\"",
"\"",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"a",
".",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"newPermissionGroup",
".",
"Name",
")",
"\n",
"a",
".",
"groupDb",
"[",
"newPermissionGroup",
".",
"Name",
"]",
"=",
"newPermissionGroup",
".",
"Permissions",
"\n",
"}",
"\n",
"}"
] | // AddPermissionGroup adds new permission group. | [
"AddPermissionGroup",
"adds",
"new",
"permission",
"group",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/rpc/rest/security/rest_security.go#L162-L171 |
4,671 | ligato/cn-infra | rpc/rest/security/rest_security.go | Validate | func (a *authenticator) Validate(provider http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
// Token may be accessed via cookie, or from authentication header
tokenString, errCode, err := a.getTokenStringFromRequest(req)
if err != nil {
a.formatter.Text(w, errCode, err.Error())
return
}
// Retrieve token object from raw string
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
if _, ok := jwt.GetSigningMethod(token.Header["alg"].(string)).(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("error parsing token")
}
return []byte(signature), nil
})
if err != nil {
errStr := fmt.Sprintf("500 internal server error: %s", err)
a.formatter.Text(w, http.StatusInternalServerError, errStr)
return
}
// Validate token claims
if token.Claims != nil {
if err := token.Claims.Valid(); err != nil {
errStr := fmt.Sprintf("401 Unauthorized: %v", err)
a.formatter.Text(w, http.StatusUnauthorized, errStr)
return
}
}
// Validate token itself
if err := a.validateToken(token, req.URL.Path, req.Method); err != nil {
errStr := fmt.Sprintf("401 Unauthorized: %v", err)
a.formatter.Text(w, http.StatusUnauthorized, errStr)
return
}
provider.ServeHTTP(w, req)
})
} | go | func (a *authenticator) Validate(provider http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
// Token may be accessed via cookie, or from authentication header
tokenString, errCode, err := a.getTokenStringFromRequest(req)
if err != nil {
a.formatter.Text(w, errCode, err.Error())
return
}
// Retrieve token object from raw string
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
if _, ok := jwt.GetSigningMethod(token.Header["alg"].(string)).(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("error parsing token")
}
return []byte(signature), nil
})
if err != nil {
errStr := fmt.Sprintf("500 internal server error: %s", err)
a.formatter.Text(w, http.StatusInternalServerError, errStr)
return
}
// Validate token claims
if token.Claims != nil {
if err := token.Claims.Valid(); err != nil {
errStr := fmt.Sprintf("401 Unauthorized: %v", err)
a.formatter.Text(w, http.StatusUnauthorized, errStr)
return
}
}
// Validate token itself
if err := a.validateToken(token, req.URL.Path, req.Method); err != nil {
errStr := fmt.Sprintf("401 Unauthorized: %v", err)
a.formatter.Text(w, http.StatusUnauthorized, errStr)
return
}
provider.ServeHTTP(w, req)
})
} | [
"func",
"(",
"a",
"*",
"authenticator",
")",
"Validate",
"(",
"provider",
"http",
".",
"HandlerFunc",
")",
"http",
".",
"HandlerFunc",
"{",
"return",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
")",
"{",
"// Token may be accessed via cookie, or from authentication header",
"tokenString",
",",
"errCode",
",",
"err",
":=",
"a",
".",
"getTokenStringFromRequest",
"(",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"a",
".",
"formatter",
".",
"Text",
"(",
"w",
",",
"errCode",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"// Retrieve token object from raw string",
"token",
",",
"err",
":=",
"jwt",
".",
"Parse",
"(",
"tokenString",
",",
"func",
"(",
"token",
"*",
"jwt",
".",
"Token",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"if",
"_",
",",
"ok",
":=",
"jwt",
".",
"GetSigningMethod",
"(",
"token",
".",
"Header",
"[",
"\"",
"\"",
"]",
".",
"(",
"string",
")",
")",
".",
"(",
"*",
"jwt",
".",
"SigningMethodHMAC",
")",
";",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"[",
"]",
"byte",
"(",
"signature",
")",
",",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"errStr",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"a",
".",
"formatter",
".",
"Text",
"(",
"w",
",",
"http",
".",
"StatusInternalServerError",
",",
"errStr",
")",
"\n",
"return",
"\n",
"}",
"\n",
"// Validate token claims",
"if",
"token",
".",
"Claims",
"!=",
"nil",
"{",
"if",
"err",
":=",
"token",
".",
"Claims",
".",
"Valid",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"errStr",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"a",
".",
"formatter",
".",
"Text",
"(",
"w",
",",
"http",
".",
"StatusUnauthorized",
",",
"errStr",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"// Validate token itself",
"if",
"err",
":=",
"a",
".",
"validateToken",
"(",
"token",
",",
"req",
".",
"URL",
".",
"Path",
",",
"req",
".",
"Method",
")",
";",
"err",
"!=",
"nil",
"{",
"errStr",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"a",
".",
"formatter",
".",
"Text",
"(",
"w",
",",
"http",
".",
"StatusUnauthorized",
",",
"errStr",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"provider",
".",
"ServeHTTP",
"(",
"w",
",",
"req",
")",
"\n",
"}",
")",
"\n",
"}"
] | // Validate the request | [
"Validate",
"the",
"request"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/rpc/rest/security/rest_security.go#L174-L211 |
4,672 | ligato/cn-infra | rpc/rest/security/rest_security.go | registerSecurityHandlers | func (a *authenticator) registerSecurityHandlers() {
a.router.HandleFunc(login, a.loginHandler).Methods(http.MethodGet, http.MethodPost)
a.router.HandleFunc(authenticate, a.authenticationHandler).Methods(http.MethodPost)
a.router.HandleFunc(logout, a.logoutHandler).Methods(http.MethodPost)
} | go | func (a *authenticator) registerSecurityHandlers() {
a.router.HandleFunc(login, a.loginHandler).Methods(http.MethodGet, http.MethodPost)
a.router.HandleFunc(authenticate, a.authenticationHandler).Methods(http.MethodPost)
a.router.HandleFunc(logout, a.logoutHandler).Methods(http.MethodPost)
} | [
"func",
"(",
"a",
"*",
"authenticator",
")",
"registerSecurityHandlers",
"(",
")",
"{",
"a",
".",
"router",
".",
"HandleFunc",
"(",
"login",
",",
"a",
".",
"loginHandler",
")",
".",
"Methods",
"(",
"http",
".",
"MethodGet",
",",
"http",
".",
"MethodPost",
")",
"\n",
"a",
".",
"router",
".",
"HandleFunc",
"(",
"authenticate",
",",
"a",
".",
"authenticationHandler",
")",
".",
"Methods",
"(",
"http",
".",
"MethodPost",
")",
"\n",
"a",
".",
"router",
".",
"HandleFunc",
"(",
"logout",
",",
"a",
".",
"logoutHandler",
")",
".",
"Methods",
"(",
"http",
".",
"MethodPost",
")",
"\n",
"}"
] | // Register authenticator-wide security handlers | [
"Register",
"authenticator",
"-",
"wide",
"security",
"handlers"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/rpc/rest/security/rest_security.go#L214-L218 |
4,673 | ligato/cn-infra | rpc/rest/security/rest_security.go | loginHandler | func (a *authenticator) loginHandler(w http.ResponseWriter, req *http.Request) {
// GET returns login page. Submit redirects to authenticate.
if req.Method == http.MethodGet {
r := render.New(render.Options{
Directory: "templates",
Asset: Asset,
AssetNames: AssetNames,
})
r.HTML(w, http.StatusOK, "login", nil)
} else {
// POST decodes provided credentials
credentials := &credentials{}
decoder := json.NewDecoder(req.Body)
err := decoder.Decode(&credentials)
if err != nil {
errStr := fmt.Sprintf("500 internal server error: failed to decode json: %v", err)
a.formatter.Text(w, http.StatusInternalServerError, errStr)
return
}
token, errCode, err := a.getTokenFor(credentials)
if err != nil {
a.formatter.Text(w, errCode, err.Error())
return
}
// Returns token string.
a.formatter.Text(w, http.StatusOK, token)
}
} | go | func (a *authenticator) loginHandler(w http.ResponseWriter, req *http.Request) {
// GET returns login page. Submit redirects to authenticate.
if req.Method == http.MethodGet {
r := render.New(render.Options{
Directory: "templates",
Asset: Asset,
AssetNames: AssetNames,
})
r.HTML(w, http.StatusOK, "login", nil)
} else {
// POST decodes provided credentials
credentials := &credentials{}
decoder := json.NewDecoder(req.Body)
err := decoder.Decode(&credentials)
if err != nil {
errStr := fmt.Sprintf("500 internal server error: failed to decode json: %v", err)
a.formatter.Text(w, http.StatusInternalServerError, errStr)
return
}
token, errCode, err := a.getTokenFor(credentials)
if err != nil {
a.formatter.Text(w, errCode, err.Error())
return
}
// Returns token string.
a.formatter.Text(w, http.StatusOK, token)
}
} | [
"func",
"(",
"a",
"*",
"authenticator",
")",
"loginHandler",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
")",
"{",
"// GET returns login page. Submit redirects to authenticate.",
"if",
"req",
".",
"Method",
"==",
"http",
".",
"MethodGet",
"{",
"r",
":=",
"render",
".",
"New",
"(",
"render",
".",
"Options",
"{",
"Directory",
":",
"\"",
"\"",
",",
"Asset",
":",
"Asset",
",",
"AssetNames",
":",
"AssetNames",
",",
"}",
")",
"\n",
"r",
".",
"HTML",
"(",
"w",
",",
"http",
".",
"StatusOK",
",",
"\"",
"\"",
",",
"nil",
")",
"\n",
"}",
"else",
"{",
"// POST decodes provided credentials",
"credentials",
":=",
"&",
"credentials",
"{",
"}",
"\n",
"decoder",
":=",
"json",
".",
"NewDecoder",
"(",
"req",
".",
"Body",
")",
"\n",
"err",
":=",
"decoder",
".",
"Decode",
"(",
"&",
"credentials",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"errStr",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"a",
".",
"formatter",
".",
"Text",
"(",
"w",
",",
"http",
".",
"StatusInternalServerError",
",",
"errStr",
")",
"\n",
"return",
"\n",
"}",
"\n",
"token",
",",
"errCode",
",",
"err",
":=",
"a",
".",
"getTokenFor",
"(",
"credentials",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"a",
".",
"formatter",
".",
"Text",
"(",
"w",
",",
"errCode",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Returns token string.",
"a",
".",
"formatter",
".",
"Text",
"(",
"w",
",",
"http",
".",
"StatusOK",
",",
"token",
")",
"\n",
"}",
"\n",
"}"
] | // Login handler shows simple page to log in | [
"Login",
"handler",
"shows",
"simple",
"page",
"to",
"log",
"in"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/rpc/rest/security/rest_security.go#L221-L249 |
4,674 | ligato/cn-infra | rpc/rest/security/rest_security.go | logoutHandler | func (a *authenticator) logoutHandler(w http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(req.Body)
var credentials credentials
err := decoder.Decode(&credentials)
if err != nil {
errStr := fmt.Sprintf("500 internal server error: failed to decode json: %v", err)
a.formatter.Text(w, http.StatusInternalServerError, errStr)
return
}
a.userDb.SetLogoutTime(credentials.Username)
a.log.Debugf("user %s was logged out", credentials.Username)
} | go | func (a *authenticator) logoutHandler(w http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(req.Body)
var credentials credentials
err := decoder.Decode(&credentials)
if err != nil {
errStr := fmt.Sprintf("500 internal server error: failed to decode json: %v", err)
a.formatter.Text(w, http.StatusInternalServerError, errStr)
return
}
a.userDb.SetLogoutTime(credentials.Username)
a.log.Debugf("user %s was logged out", credentials.Username)
} | [
"func",
"(",
"a",
"*",
"authenticator",
")",
"logoutHandler",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
")",
"{",
"decoder",
":=",
"json",
".",
"NewDecoder",
"(",
"req",
".",
"Body",
")",
"\n",
"var",
"credentials",
"credentials",
"\n",
"err",
":=",
"decoder",
".",
"Decode",
"(",
"&",
"credentials",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"errStr",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"a",
".",
"formatter",
".",
"Text",
"(",
"w",
",",
"http",
".",
"StatusInternalServerError",
",",
"errStr",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"a",
".",
"userDb",
".",
"SetLogoutTime",
"(",
"credentials",
".",
"Username",
")",
"\n",
"a",
".",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"credentials",
".",
"Username",
")",
"\n",
"}"
] | // Removes token endpoint from the DB. During processing, token will not be found and will be considered as invalid. | [
"Removes",
"token",
"endpoint",
"from",
"the",
"DB",
".",
"During",
"processing",
"token",
"will",
"not",
"be",
"found",
"and",
"will",
"be",
"considered",
"as",
"invalid",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/rpc/rest/security/rest_security.go#L277-L289 |
4,675 | ligato/cn-infra | rpc/rest/security/rest_security.go | getTokenStringFromRequest | func (a *authenticator) getTokenStringFromRequest(req *http.Request) (result string, errCode int, err error) {
// Try to read header, validate it if exists.
authHeader := req.Header.Get(AuthHeaderKey)
if authHeader != "" {
bearerToken := strings.Split(authHeader, " ")
if len(bearerToken) != 2 {
return "", http.StatusUnauthorized, fmt.Errorf("401 Unauthorized: invalid authorization token")
}
// Parse token header constant
if bearerToken[0] != "Bearer" {
return "", http.StatusUnauthorized, fmt.Errorf("401 Unauthorized: invalid authorization header")
}
return bearerToken[1], 0, nil
}
a.log.Debugf("Authentication header not found (err: %v)", err)
// Otherwise read cookie
cookie, err := req.Cookie(cookieName)
if err == nil && cookie != nil {
return cookie.Value, 0, nil
}
a.log.Debugf("Authentication cookie not found (err: %v)", err)
return "", http.StatusUnauthorized, fmt.Errorf("401 Unauthorized: authorization required")
} | go | func (a *authenticator) getTokenStringFromRequest(req *http.Request) (result string, errCode int, err error) {
// Try to read header, validate it if exists.
authHeader := req.Header.Get(AuthHeaderKey)
if authHeader != "" {
bearerToken := strings.Split(authHeader, " ")
if len(bearerToken) != 2 {
return "", http.StatusUnauthorized, fmt.Errorf("401 Unauthorized: invalid authorization token")
}
// Parse token header constant
if bearerToken[0] != "Bearer" {
return "", http.StatusUnauthorized, fmt.Errorf("401 Unauthorized: invalid authorization header")
}
return bearerToken[1], 0, nil
}
a.log.Debugf("Authentication header not found (err: %v)", err)
// Otherwise read cookie
cookie, err := req.Cookie(cookieName)
if err == nil && cookie != nil {
return cookie.Value, 0, nil
}
a.log.Debugf("Authentication cookie not found (err: %v)", err)
return "", http.StatusUnauthorized, fmt.Errorf("401 Unauthorized: authorization required")
} | [
"func",
"(",
"a",
"*",
"authenticator",
")",
"getTokenStringFromRequest",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"(",
"result",
"string",
",",
"errCode",
"int",
",",
"err",
"error",
")",
"{",
"// Try to read header, validate it if exists.",
"authHeader",
":=",
"req",
".",
"Header",
".",
"Get",
"(",
"AuthHeaderKey",
")",
"\n",
"if",
"authHeader",
"!=",
"\"",
"\"",
"{",
"bearerToken",
":=",
"strings",
".",
"Split",
"(",
"authHeader",
",",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"bearerToken",
")",
"!=",
"2",
"{",
"return",
"\"",
"\"",
",",
"http",
".",
"StatusUnauthorized",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"// Parse token header constant",
"if",
"bearerToken",
"[",
"0",
"]",
"!=",
"\"",
"\"",
"{",
"return",
"\"",
"\"",
",",
"http",
".",
"StatusUnauthorized",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"bearerToken",
"[",
"1",
"]",
",",
"0",
",",
"nil",
"\n",
"}",
"\n",
"a",
".",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n\n",
"// Otherwise read cookie",
"cookie",
",",
"err",
":=",
"req",
".",
"Cookie",
"(",
"cookieName",
")",
"\n",
"if",
"err",
"==",
"nil",
"&&",
"cookie",
"!=",
"nil",
"{",
"return",
"cookie",
".",
"Value",
",",
"0",
",",
"nil",
"\n",
"}",
"\n",
"a",
".",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n\n",
"return",
"\"",
"\"",
",",
"http",
".",
"StatusUnauthorized",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // Read raw token from request. | [
"Read",
"raw",
"token",
"from",
"request",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/rpc/rest/security/rest_security.go#L292-L316 |
4,676 | ligato/cn-infra | rpc/rest/security/rest_security.go | getTokenFor | func (a *authenticator) getTokenFor(credentials *credentials) (string, int, error) {
name, errCode, err := a.validateCredentials(credentials)
if err != nil {
return "", errCode, err
}
claims := jwt.StandardClaims{
Audience: name,
ExpiresAt: a.expTime.Nanoseconds(),
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := token.SignedString([]byte(signature))
if err != nil {
return "", http.StatusInternalServerError, fmt.Errorf("500 internal server error: failed to sign token: %v", err)
}
a.userDb.SetLoginTime(name)
a.log.Debugf("user %s was logged in", name)
return tokenString, 0, nil
} | go | func (a *authenticator) getTokenFor(credentials *credentials) (string, int, error) {
name, errCode, err := a.validateCredentials(credentials)
if err != nil {
return "", errCode, err
}
claims := jwt.StandardClaims{
Audience: name,
ExpiresAt: a.expTime.Nanoseconds(),
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := token.SignedString([]byte(signature))
if err != nil {
return "", http.StatusInternalServerError, fmt.Errorf("500 internal server error: failed to sign token: %v", err)
}
a.userDb.SetLoginTime(name)
a.log.Debugf("user %s was logged in", name)
return tokenString, 0, nil
} | [
"func",
"(",
"a",
"*",
"authenticator",
")",
"getTokenFor",
"(",
"credentials",
"*",
"credentials",
")",
"(",
"string",
",",
"int",
",",
"error",
")",
"{",
"name",
",",
"errCode",
",",
"err",
":=",
"a",
".",
"validateCredentials",
"(",
"credentials",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"errCode",
",",
"err",
"\n",
"}",
"\n",
"claims",
":=",
"jwt",
".",
"StandardClaims",
"{",
"Audience",
":",
"name",
",",
"ExpiresAt",
":",
"a",
".",
"expTime",
".",
"Nanoseconds",
"(",
")",
",",
"}",
"\n",
"token",
":=",
"jwt",
".",
"NewWithClaims",
"(",
"jwt",
".",
"SigningMethodHS256",
",",
"claims",
")",
"\n",
"tokenString",
",",
"err",
":=",
"token",
".",
"SignedString",
"(",
"[",
"]",
"byte",
"(",
"signature",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"http",
".",
"StatusInternalServerError",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"a",
".",
"userDb",
".",
"SetLoginTime",
"(",
"name",
")",
"\n",
"a",
".",
"log",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n\n",
"return",
"tokenString",
",",
"0",
",",
"nil",
"\n",
"}"
] | // Get token for credentials | [
"Get",
"token",
"for",
"credentials"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/rpc/rest/security/rest_security.go#L319-L337 |
4,677 | ligato/cn-infra | rpc/rest/security/rest_security.go | validateToken | func (a *authenticator) validateToken(token *jwt.Token, url, method string) error {
var userName string
// Read audience from the token
switch v := token.Claims.(type) {
case jwt.MapClaims:
var ok bool
if userName, ok = v["aud"].(string); !ok {
return fmt.Errorf("failed to validate token claims audience")
}
case jwt.StandardClaims:
userName = v.Audience
default:
return fmt.Errorf("failed to validate token claims")
}
loggedOut, err := a.userDb.IsLoggedOut(userName)
if err != nil {
return fmt.Errorf("failed to validate token: %v", err)
}
if loggedOut {
// User logged out
token.Valid = false
return fmt.Errorf("invalid token")
}
user, err := a.userDb.GetUser(userName)
if err != nil {
return fmt.Errorf("failed to validate token: %v", err)
}
// Do not check for permissions if user is admin
if userIsAdmin(user) {
return nil
}
perms := a.getPermissionsForURL(url, method)
for _, userPerm := range user.Permissions {
for _, perm := range perms {
if userPerm == perm {
return nil
}
}
}
return fmt.Errorf("not permitted")
} | go | func (a *authenticator) validateToken(token *jwt.Token, url, method string) error {
var userName string
// Read audience from the token
switch v := token.Claims.(type) {
case jwt.MapClaims:
var ok bool
if userName, ok = v["aud"].(string); !ok {
return fmt.Errorf("failed to validate token claims audience")
}
case jwt.StandardClaims:
userName = v.Audience
default:
return fmt.Errorf("failed to validate token claims")
}
loggedOut, err := a.userDb.IsLoggedOut(userName)
if err != nil {
return fmt.Errorf("failed to validate token: %v", err)
}
if loggedOut {
// User logged out
token.Valid = false
return fmt.Errorf("invalid token")
}
user, err := a.userDb.GetUser(userName)
if err != nil {
return fmt.Errorf("failed to validate token: %v", err)
}
// Do not check for permissions if user is admin
if userIsAdmin(user) {
return nil
}
perms := a.getPermissionsForURL(url, method)
for _, userPerm := range user.Permissions {
for _, perm := range perms {
if userPerm == perm {
return nil
}
}
}
return fmt.Errorf("not permitted")
} | [
"func",
"(",
"a",
"*",
"authenticator",
")",
"validateToken",
"(",
"token",
"*",
"jwt",
".",
"Token",
",",
"url",
",",
"method",
"string",
")",
"error",
"{",
"var",
"userName",
"string",
"\n",
"// Read audience from the token",
"switch",
"v",
":=",
"token",
".",
"Claims",
".",
"(",
"type",
")",
"{",
"case",
"jwt",
".",
"MapClaims",
":",
"var",
"ok",
"bool",
"\n",
"if",
"userName",
",",
"ok",
"=",
"v",
"[",
"\"",
"\"",
"]",
".",
"(",
"string",
")",
";",
"!",
"ok",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"case",
"jwt",
".",
"StandardClaims",
":",
"userName",
"=",
"v",
".",
"Audience",
"\n",
"default",
":",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"loggedOut",
",",
"err",
":=",
"a",
".",
"userDb",
".",
"IsLoggedOut",
"(",
"userName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"loggedOut",
"{",
"// User logged out",
"token",
".",
"Valid",
"=",
"false",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"user",
",",
"err",
":=",
"a",
".",
"userDb",
".",
"GetUser",
"(",
"userName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"// Do not check for permissions if user is admin",
"if",
"userIsAdmin",
"(",
"user",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"perms",
":=",
"a",
".",
"getPermissionsForURL",
"(",
"url",
",",
"method",
")",
"\n",
"for",
"_",
",",
"userPerm",
":=",
"range",
"user",
".",
"Permissions",
"{",
"for",
"_",
",",
"perm",
":=",
"range",
"perms",
"{",
"if",
"userPerm",
"==",
"perm",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // Validates token itself and permissions | [
"Validates",
"token",
"itself",
"and",
"permissions"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/rpc/rest/security/rest_security.go#L352-L393 |
4,678 | ligato/cn-infra | rpc/rest/security/rest_security.go | userIsAdmin | func userIsAdmin(user *User) bool {
for _, permission := range user.Permissions {
if permission == admin {
return true
}
}
return false
} | go | func userIsAdmin(user *User) bool {
for _, permission := range user.Permissions {
if permission == admin {
return true
}
}
return false
} | [
"func",
"userIsAdmin",
"(",
"user",
"*",
"User",
")",
"bool",
"{",
"for",
"_",
",",
"permission",
":=",
"range",
"user",
".",
"Permissions",
"{",
"if",
"permission",
"==",
"admin",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // Checks user admin permission | [
"Checks",
"user",
"admin",
"permission"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/rpc/rest/security/rest_security.go#L415-L422 |
4,679 | ligato/cn-infra | examples/logs-plugin/main.go | AfterInit | func (plugin *ExamplePlugin) AfterInit() (err error) {
late := plugin.Log.NewLogger("late")
late.Debugf("late debug message")
// End the example
plugin.Log.Info("logs in plugin example finished, sending shutdown ...")
close(plugin.exampleFinished)
return nil
} | go | func (plugin *ExamplePlugin) AfterInit() (err error) {
late := plugin.Log.NewLogger("late")
late.Debugf("late debug message")
// End the example
plugin.Log.Info("logs in plugin example finished, sending shutdown ...")
close(plugin.exampleFinished)
return nil
} | [
"func",
"(",
"plugin",
"*",
"ExamplePlugin",
")",
"AfterInit",
"(",
")",
"(",
"err",
"error",
")",
"{",
"late",
":=",
"plugin",
".",
"Log",
".",
"NewLogger",
"(",
"\"",
"\"",
")",
"\n",
"late",
".",
"Debugf",
"(",
"\"",
"\"",
")",
"\n\n",
"// End the example",
"plugin",
".",
"Log",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"close",
"(",
"plugin",
".",
"exampleFinished",
")",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // AfterInit demonstrates the usage of PluginLogger API. | [
"AfterInit",
"demonstrates",
"the",
"usage",
"of",
"PluginLogger",
"API",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/examples/logs-plugin/main.go#L96-L105 |
4,680 | ligato/cn-infra | examples/logs-plugin/main.go | showPanicLog | func (plugin *ExamplePlugin) showPanicLog() {
defer func() {
if err := recover(); err != nil {
plugin.Log.Info("Recovered from panic")
}
}()
plugin.Log.Panic("Panic log: calls panic() after log, will be recovered") //calls panic() after logging
} | go | func (plugin *ExamplePlugin) showPanicLog() {
defer func() {
if err := recover(); err != nil {
plugin.Log.Info("Recovered from panic")
}
}()
plugin.Log.Panic("Panic log: calls panic() after log, will be recovered") //calls panic() after logging
} | [
"func",
"(",
"plugin",
"*",
"ExamplePlugin",
")",
"showPanicLog",
"(",
")",
"{",
"defer",
"func",
"(",
")",
"{",
"if",
"err",
":=",
"recover",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"plugin",
".",
"Log",
".",
"Info",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n",
"plugin",
".",
"Log",
".",
"Panic",
"(",
"\"",
"\"",
")",
"//calls panic() after logging",
"\n",
"}"
] | // showPanicLog demonstrates panic log + recovering. | [
"showPanicLog",
"demonstrates",
"panic",
"log",
"+",
"recovering",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/examples/logs-plugin/main.go#L113-L120 |
4,681 | ligato/cn-infra | infra/infra.go | SetupLog | func (d *PluginDeps) SetupLog() {
if d.Log == nil {
d.Log = logging.ForPlugin(d.String())
}
} | go | func (d *PluginDeps) SetupLog() {
if d.Log == nil {
d.Log = logging.ForPlugin(d.String())
}
} | [
"func",
"(",
"d",
"*",
"PluginDeps",
")",
"SetupLog",
"(",
")",
"{",
"if",
"d",
".",
"Log",
"==",
"nil",
"{",
"d",
".",
"Log",
"=",
"logging",
".",
"ForPlugin",
"(",
"d",
".",
"String",
"(",
")",
")",
"\n",
"}",
"\n",
"}"
] | // SetupLog sets up default instance for plugin log dep. | [
"SetupLog",
"sets",
"up",
"default",
"instance",
"for",
"plugin",
"log",
"dep",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/infra/infra.go#L68-L72 |
4,682 | ligato/cn-infra | infra/infra.go | Setup | func (d *PluginDeps) Setup() {
d.SetupLog()
if d.Cfg == nil {
d.Cfg = config.ForPlugin(d.String())
}
} | go | func (d *PluginDeps) Setup() {
d.SetupLog()
if d.Cfg == nil {
d.Cfg = config.ForPlugin(d.String())
}
} | [
"func",
"(",
"d",
"*",
"PluginDeps",
")",
"Setup",
"(",
")",
"{",
"d",
".",
"SetupLog",
"(",
")",
"\n",
"if",
"d",
".",
"Cfg",
"==",
"nil",
"{",
"d",
".",
"Cfg",
"=",
"config",
".",
"ForPlugin",
"(",
"d",
".",
"String",
"(",
")",
")",
"\n",
"}",
"\n",
"}"
] | // Setup sets up default instances for plugin deps. | [
"Setup",
"sets",
"up",
"default",
"instances",
"for",
"plugin",
"deps",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/infra/infra.go#L75-L80 |
4,683 | ligato/cn-infra | datasync/syncbase/prev_revisions.go | Get | func (r *PrevRevisions) Get(key string) (found bool, value datasync.KeyVal) {
r.mu.RLock()
prev, found := r.revisions[key]
r.mu.RUnlock()
return found, prev
} | go | func (r *PrevRevisions) Get(key string) (found bool, value datasync.KeyVal) {
r.mu.RLock()
prev, found := r.revisions[key]
r.mu.RUnlock()
return found, prev
} | [
"func",
"(",
"r",
"*",
"PrevRevisions",
")",
"Get",
"(",
"key",
"string",
")",
"(",
"found",
"bool",
",",
"value",
"datasync",
".",
"KeyVal",
")",
"{",
"r",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"prev",
",",
"found",
":=",
"r",
".",
"revisions",
"[",
"key",
"]",
"\n",
"r",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n\n",
"return",
"found",
",",
"prev",
"\n",
"}"
] | // Get gets the last proto.Message with it's revision. | [
"Get",
"gets",
"the",
"last",
"proto",
".",
"Message",
"with",
"it",
"s",
"revision",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/datasync/syncbase/prev_revisions.go#L37-L43 |
4,684 | ligato/cn-infra | datasync/syncbase/prev_revisions.go | Put | func (r *PrevRevisions) Put(key string, val datasync.LazyValue) (
found bool, prev datasync.KeyVal, currRev int64) {
found, prev = r.Get(key)
if prev != nil {
currRev = prev.GetRevision() + 1
} else {
currRev = 0
}
r.mu.Lock()
r.revisions[key] = &valWithRev{
LazyValue: val,
key: key,
rev: currRev,
}
r.mu.Unlock()
return found, prev, currRev
} | go | func (r *PrevRevisions) Put(key string, val datasync.LazyValue) (
found bool, prev datasync.KeyVal, currRev int64) {
found, prev = r.Get(key)
if prev != nil {
currRev = prev.GetRevision() + 1
} else {
currRev = 0
}
r.mu.Lock()
r.revisions[key] = &valWithRev{
LazyValue: val,
key: key,
rev: currRev,
}
r.mu.Unlock()
return found, prev, currRev
} | [
"func",
"(",
"r",
"*",
"PrevRevisions",
")",
"Put",
"(",
"key",
"string",
",",
"val",
"datasync",
".",
"LazyValue",
")",
"(",
"found",
"bool",
",",
"prev",
"datasync",
".",
"KeyVal",
",",
"currRev",
"int64",
")",
"{",
"found",
",",
"prev",
"=",
"r",
".",
"Get",
"(",
"key",
")",
"\n",
"if",
"prev",
"!=",
"nil",
"{",
"currRev",
"=",
"prev",
".",
"GetRevision",
"(",
")",
"+",
"1",
"\n",
"}",
"else",
"{",
"currRev",
"=",
"0",
"\n",
"}",
"\n\n",
"r",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"r",
".",
"revisions",
"[",
"key",
"]",
"=",
"&",
"valWithRev",
"{",
"LazyValue",
":",
"val",
",",
"key",
":",
"key",
",",
"rev",
":",
"currRev",
",",
"}",
"\n",
"r",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"found",
",",
"prev",
",",
"currRev",
"\n",
"}"
] | // Put updates the entry in the revisions and returns previous value. | [
"Put",
"updates",
"the",
"entry",
"in",
"the",
"revisions",
"and",
"returns",
"previous",
"value",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/datasync/syncbase/prev_revisions.go#L46-L65 |
4,685 | ligato/cn-infra | datasync/syncbase/prev_revisions.go | PutWithRevision | func (r *PrevRevisions) PutWithRevision(key string, inCurrent datasync.KeyVal) (
found bool, prev datasync.KeyVal) {
found, prev = r.Get(key)
currentRev := inCurrent.GetRevision()
if currentRev == 0 && prev != nil {
currentRev = prev.GetRevision() + 1
}
r.mu.Lock()
r.revisions[key] = &valWithRev{
LazyValue: inCurrent,
key: key,
rev: currentRev,
}
r.mu.Unlock()
return found, prev
} | go | func (r *PrevRevisions) PutWithRevision(key string, inCurrent datasync.KeyVal) (
found bool, prev datasync.KeyVal) {
found, prev = r.Get(key)
currentRev := inCurrent.GetRevision()
if currentRev == 0 && prev != nil {
currentRev = prev.GetRevision() + 1
}
r.mu.Lock()
r.revisions[key] = &valWithRev{
LazyValue: inCurrent,
key: key,
rev: currentRev,
}
r.mu.Unlock()
return found, prev
} | [
"func",
"(",
"r",
"*",
"PrevRevisions",
")",
"PutWithRevision",
"(",
"key",
"string",
",",
"inCurrent",
"datasync",
".",
"KeyVal",
")",
"(",
"found",
"bool",
",",
"prev",
"datasync",
".",
"KeyVal",
")",
"{",
"found",
",",
"prev",
"=",
"r",
".",
"Get",
"(",
"key",
")",
"\n\n",
"currentRev",
":=",
"inCurrent",
".",
"GetRevision",
"(",
")",
"\n",
"if",
"currentRev",
"==",
"0",
"&&",
"prev",
"!=",
"nil",
"{",
"currentRev",
"=",
"prev",
".",
"GetRevision",
"(",
")",
"+",
"1",
"\n",
"}",
"\n\n",
"r",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"r",
".",
"revisions",
"[",
"key",
"]",
"=",
"&",
"valWithRev",
"{",
"LazyValue",
":",
"inCurrent",
",",
"key",
":",
"key",
",",
"rev",
":",
"currentRev",
",",
"}",
"\n",
"r",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"return",
"found",
",",
"prev",
"\n",
"}"
] | // PutWithRevision updates the entry in the revisions and returns previous value. | [
"PutWithRevision",
"updates",
"the",
"entry",
"in",
"the",
"revisions",
"and",
"returns",
"previous",
"value",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/datasync/syncbase/prev_revisions.go#L68-L87 |
4,686 | ligato/cn-infra | datasync/syncbase/prev_revisions.go | Del | func (r *PrevRevisions) Del(key string) (found bool, prev datasync.KeyVal) {
found, prev = r.Get(key)
if found {
r.mu.Lock()
delete(r.revisions, key)
r.mu.Unlock()
}
return found, prev
} | go | func (r *PrevRevisions) Del(key string) (found bool, prev datasync.KeyVal) {
found, prev = r.Get(key)
if found {
r.mu.Lock()
delete(r.revisions, key)
r.mu.Unlock()
}
return found, prev
} | [
"func",
"(",
"r",
"*",
"PrevRevisions",
")",
"Del",
"(",
"key",
"string",
")",
"(",
"found",
"bool",
",",
"prev",
"datasync",
".",
"KeyVal",
")",
"{",
"found",
",",
"prev",
"=",
"r",
".",
"Get",
"(",
"key",
")",
"\n\n",
"if",
"found",
"{",
"r",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"delete",
"(",
"r",
".",
"revisions",
",",
"key",
")",
"\n",
"r",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"}",
"\n\n",
"return",
"found",
",",
"prev",
"\n",
"}"
] | // Del deletes the entry from revisions and returns previous value. | [
"Del",
"deletes",
"the",
"entry",
"from",
"revisions",
"and",
"returns",
"previous",
"value",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/datasync/syncbase/prev_revisions.go#L90-L100 |
4,687 | ligato/cn-infra | datasync/syncbase/prev_revisions.go | ListKeys | func (r *PrevRevisions) ListKeys() (ret []string) {
r.mu.RLock()
for key := range r.revisions {
ret = append(ret, key)
}
r.mu.RUnlock()
return ret
} | go | func (r *PrevRevisions) ListKeys() (ret []string) {
r.mu.RLock()
for key := range r.revisions {
ret = append(ret, key)
}
r.mu.RUnlock()
return ret
} | [
"func",
"(",
"r",
"*",
"PrevRevisions",
")",
"ListKeys",
"(",
")",
"(",
"ret",
"[",
"]",
"string",
")",
"{",
"r",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"for",
"key",
":=",
"range",
"r",
".",
"revisions",
"{",
"ret",
"=",
"append",
"(",
"ret",
",",
"key",
")",
"\n",
"}",
"\n",
"r",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"ret",
"\n",
"}"
] | // ListKeys returns all stored keys. | [
"ListKeys",
"returns",
"all",
"stored",
"keys",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/datasync/syncbase/prev_revisions.go#L103-L110 |
4,688 | ligato/cn-infra | datasync/syncbase/prev_revisions.go | Cleanup | func (r *PrevRevisions) Cleanup() {
r.mu.Lock()
defer r.mu.Unlock()
r.revisions = make(map[string]datasync.KeyVal)
} | go | func (r *PrevRevisions) Cleanup() {
r.mu.Lock()
defer r.mu.Unlock()
r.revisions = make(map[string]datasync.KeyVal)
} | [
"func",
"(",
"r",
"*",
"PrevRevisions",
")",
"Cleanup",
"(",
")",
"{",
"r",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"r",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"r",
".",
"revisions",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"datasync",
".",
"KeyVal",
")",
"\n",
"}"
] | // Cleanup removes all data from the registry | [
"Cleanup",
"removes",
"all",
"data",
"from",
"the",
"registry"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/datasync/syncbase/prev_revisions.go#L113-L118 |
4,689 | ligato/cn-infra | examples/cryptodata-plugin/main.go | Close | func (plugin *ExamplePlugin) Close() error {
if plugin.db != nil {
return plugin.db.Close()
}
return nil
} | go | func (plugin *ExamplePlugin) Close() error {
if plugin.db != nil {
return plugin.db.Close()
}
return nil
} | [
"func",
"(",
"plugin",
"*",
"ExamplePlugin",
")",
"Close",
"(",
")",
"error",
"{",
"if",
"plugin",
".",
"db",
"!=",
"nil",
"{",
"return",
"plugin",
".",
"db",
".",
"Close",
"(",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Close closes ExamplePlugin | [
"Close",
"closes",
"ExamplePlugin"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/examples/cryptodata-plugin/main.go#L133-L138 |
4,690 | ligato/cn-infra | examples/cryptodata-plugin/main.go | etcdKey | func (plugin *ExamplePlugin) etcdKey(label string) string {
return "/vnf-agent/" + plugin.ServiceLabel.GetAgentLabel() + "/api/v1/example/db/simple/" + label
} | go | func (plugin *ExamplePlugin) etcdKey(label string) string {
return "/vnf-agent/" + plugin.ServiceLabel.GetAgentLabel() + "/api/v1/example/db/simple/" + label
} | [
"func",
"(",
"plugin",
"*",
"ExamplePlugin",
")",
"etcdKey",
"(",
"label",
"string",
")",
"string",
"{",
"return",
"\"",
"\"",
"+",
"plugin",
".",
"ServiceLabel",
".",
"GetAgentLabel",
"(",
")",
"+",
"\"",
"\"",
"+",
"label",
"\n",
"}"
] | // The ETCD key prefix used for this example | [
"The",
"ETCD",
"key",
"prefix",
"used",
"for",
"this",
"example"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/examples/cryptodata-plugin/main.go#L141-L143 |
4,691 | ligato/cn-infra | examples/cryptodata-plugin/main.go | encryptData | func (plugin *ExamplePlugin) encryptData(value string, publicKey *rsa.PublicKey) (string, error) {
encryptedValue, err := plugin.CryptoData.EncryptData([]byte(value), publicKey)
if err != nil {
return "", err
}
return base64.URLEncoding.EncodeToString(encryptedValue), nil
} | go | func (plugin *ExamplePlugin) encryptData(value string, publicKey *rsa.PublicKey) (string, error) {
encryptedValue, err := plugin.CryptoData.EncryptData([]byte(value), publicKey)
if err != nil {
return "", err
}
return base64.URLEncoding.EncodeToString(encryptedValue), nil
} | [
"func",
"(",
"plugin",
"*",
"ExamplePlugin",
")",
"encryptData",
"(",
"value",
"string",
",",
"publicKey",
"*",
"rsa",
".",
"PublicKey",
")",
"(",
"string",
",",
"error",
")",
"{",
"encryptedValue",
",",
"err",
":=",
"plugin",
".",
"CryptoData",
".",
"EncryptData",
"(",
"[",
"]",
"byte",
"(",
"value",
")",
",",
"publicKey",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"return",
"base64",
".",
"URLEncoding",
".",
"EncodeToString",
"(",
"encryptedValue",
")",
",",
"nil",
"\n",
"}"
] | // encryptData first encrypts the provided value using crypto layer and then encodes
// the data with base64 for JSON compatibility | [
"encryptData",
"first",
"encrypts",
"the",
"provided",
"value",
"using",
"crypto",
"layer",
"and",
"then",
"encodes",
"the",
"data",
"with",
"base64",
"for",
"JSON",
"compatibility"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/examples/cryptodata-plugin/main.go#L147-L153 |
4,692 | ligato/cn-infra | examples/cryptodata-plugin/main.go | newEtcdConnection | func (plugin *ExamplePlugin) newEtcdConnection(configPath string) (*etcd.BytesConnectionEtcd, error) {
etcdFileConfig := &etcd.Config{}
err := config.ParseConfigFromYamlFile(configPath, etcdFileConfig)
if err != nil {
return nil, err
}
etcdConfig, err := etcd.ConfigToClient(etcdFileConfig)
if err != nil {
return nil, err
}
return etcd.NewEtcdConnectionWithBytes(*etcdConfig, plugin.Log)
} | go | func (plugin *ExamplePlugin) newEtcdConnection(configPath string) (*etcd.BytesConnectionEtcd, error) {
etcdFileConfig := &etcd.Config{}
err := config.ParseConfigFromYamlFile(configPath, etcdFileConfig)
if err != nil {
return nil, err
}
etcdConfig, err := etcd.ConfigToClient(etcdFileConfig)
if err != nil {
return nil, err
}
return etcd.NewEtcdConnectionWithBytes(*etcdConfig, plugin.Log)
} | [
"func",
"(",
"plugin",
"*",
"ExamplePlugin",
")",
"newEtcdConnection",
"(",
"configPath",
"string",
")",
"(",
"*",
"etcd",
".",
"BytesConnectionEtcd",
",",
"error",
")",
"{",
"etcdFileConfig",
":=",
"&",
"etcd",
".",
"Config",
"{",
"}",
"\n",
"err",
":=",
"config",
".",
"ParseConfigFromYamlFile",
"(",
"configPath",
",",
"etcdFileConfig",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"etcdConfig",
",",
"err",
":=",
"etcd",
".",
"ConfigToClient",
"(",
"etcdFileConfig",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"etcd",
".",
"NewEtcdConnectionWithBytes",
"(",
"*",
"etcdConfig",
",",
"plugin",
".",
"Log",
")",
"\n",
"}"
] | // newEtcdConnection creates new ETCD bytes connection from provided etcd config path | [
"newEtcdConnection",
"creates",
"new",
"ETCD",
"bytes",
"connection",
"from",
"provided",
"etcd",
"config",
"path"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/examples/cryptodata-plugin/main.go#L156-L169 |
4,693 | ligato/cn-infra | examples/cryptodata-plugin/main.go | readPublicKey | func readPublicKey(path string) (*rsa.PublicKey, error) {
bytes, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
block, _ := pem.Decode(bytes)
if block == nil {
return nil, errors.New("failed to decode PEM for key " + path)
}
pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return nil, err
}
publicKey, ok := pubInterface.(*rsa.PublicKey)
if !ok {
return nil, errors.New("failed to convert public key to rsa.PublicKey")
}
return publicKey, nil
} | go | func readPublicKey(path string) (*rsa.PublicKey, error) {
bytes, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
block, _ := pem.Decode(bytes)
if block == nil {
return nil, errors.New("failed to decode PEM for key " + path)
}
pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return nil, err
}
publicKey, ok := pubInterface.(*rsa.PublicKey)
if !ok {
return nil, errors.New("failed to convert public key to rsa.PublicKey")
}
return publicKey, nil
} | [
"func",
"readPublicKey",
"(",
"path",
"string",
")",
"(",
"*",
"rsa",
".",
"PublicKey",
",",
"error",
")",
"{",
"bytes",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"block",
",",
"_",
":=",
"pem",
".",
"Decode",
"(",
"bytes",
")",
"\n",
"if",
"block",
"==",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
"+",
"path",
")",
"\n",
"}",
"\n",
"pubInterface",
",",
"err",
":=",
"x509",
".",
"ParsePKIXPublicKey",
"(",
"block",
".",
"Bytes",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"publicKey",
",",
"ok",
":=",
"pubInterface",
".",
"(",
"*",
"rsa",
".",
"PublicKey",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"publicKey",
",",
"nil",
"\n",
"}"
] | // readPublicKey reads rsa public key from PEM file on provided path | [
"readPublicKey",
"reads",
"rsa",
"public",
"key",
"from",
"PEM",
"file",
"on",
"provided",
"path"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/examples/cryptodata-plugin/main.go#L172-L191 |
4,694 | ligato/cn-infra | db/cryptodata/wrapper_bytes.go | NewKvBytesPluginWrapper | func NewKvBytesPluginWrapper(cbw keyval.KvBytesPlugin, decrypter ArbitraryDecrypter, decryptFunc DecryptFunc) *KvBytesPluginWrapper {
return &KvBytesPluginWrapper{
KvBytesPlugin: cbw,
decryptData: decryptData{
decryptFunc: decryptFunc,
decrypter: decrypter,
},
}
} | go | func NewKvBytesPluginWrapper(cbw keyval.KvBytesPlugin, decrypter ArbitraryDecrypter, decryptFunc DecryptFunc) *KvBytesPluginWrapper {
return &KvBytesPluginWrapper{
KvBytesPlugin: cbw,
decryptData: decryptData{
decryptFunc: decryptFunc,
decrypter: decrypter,
},
}
} | [
"func",
"NewKvBytesPluginWrapper",
"(",
"cbw",
"keyval",
".",
"KvBytesPlugin",
",",
"decrypter",
"ArbitraryDecrypter",
",",
"decryptFunc",
"DecryptFunc",
")",
"*",
"KvBytesPluginWrapper",
"{",
"return",
"&",
"KvBytesPluginWrapper",
"{",
"KvBytesPlugin",
":",
"cbw",
",",
"decryptData",
":",
"decryptData",
"{",
"decryptFunc",
":",
"decryptFunc",
",",
"decrypter",
":",
"decrypter",
",",
"}",
",",
"}",
"\n",
"}"
] | // NewKvBytesPluginWrapper creates wrapper for provided CoreBrokerWatcher, adding support for decrypting encrypted
// data | [
"NewKvBytesPluginWrapper",
"creates",
"wrapper",
"for",
"provided",
"CoreBrokerWatcher",
"adding",
"support",
"for",
"decrypting",
"encrypted",
"data"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/cryptodata/wrapper_bytes.go#L57-L65 |
4,695 | ligato/cn-infra | db/cryptodata/wrapper_bytes.go | NewBytesBrokerWrapper | func NewBytesBrokerWrapper(pb keyval.BytesBroker, decrypter ArbitraryDecrypter, decryptFunc DecryptFunc) *BytesBrokerWrapper {
return &BytesBrokerWrapper{
BytesBroker: pb,
decryptData: decryptData{
decryptFunc: decryptFunc,
decrypter: decrypter,
},
}
} | go | func NewBytesBrokerWrapper(pb keyval.BytesBroker, decrypter ArbitraryDecrypter, decryptFunc DecryptFunc) *BytesBrokerWrapper {
return &BytesBrokerWrapper{
BytesBroker: pb,
decryptData: decryptData{
decryptFunc: decryptFunc,
decrypter: decrypter,
},
}
} | [
"func",
"NewBytesBrokerWrapper",
"(",
"pb",
"keyval",
".",
"BytesBroker",
",",
"decrypter",
"ArbitraryDecrypter",
",",
"decryptFunc",
"DecryptFunc",
")",
"*",
"BytesBrokerWrapper",
"{",
"return",
"&",
"BytesBrokerWrapper",
"{",
"BytesBroker",
":",
"pb",
",",
"decryptData",
":",
"decryptData",
"{",
"decryptFunc",
":",
"decryptFunc",
",",
"decrypter",
":",
"decrypter",
",",
"}",
",",
"}",
"\n",
"}"
] | // NewBytesBrokerWrapper creates wrapper for provided BytesBroker, adding support for decrypting encrypted data | [
"NewBytesBrokerWrapper",
"creates",
"wrapper",
"for",
"provided",
"BytesBroker",
"adding",
"support",
"for",
"decrypting",
"encrypted",
"data"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/cryptodata/wrapper_bytes.go#L68-L76 |
4,696 | ligato/cn-infra | db/cryptodata/wrapper_bytes.go | NewBytesWatcherWrapper | func NewBytesWatcherWrapper(pb keyval.BytesWatcher, decrypter ArbitraryDecrypter, decryptFunc DecryptFunc) *BytesWatcherWrapper {
return &BytesWatcherWrapper{
BytesWatcher: pb,
decryptData: decryptData{
decryptFunc: decryptFunc,
decrypter: decrypter,
},
}
} | go | func NewBytesWatcherWrapper(pb keyval.BytesWatcher, decrypter ArbitraryDecrypter, decryptFunc DecryptFunc) *BytesWatcherWrapper {
return &BytesWatcherWrapper{
BytesWatcher: pb,
decryptData: decryptData{
decryptFunc: decryptFunc,
decrypter: decrypter,
},
}
} | [
"func",
"NewBytesWatcherWrapper",
"(",
"pb",
"keyval",
".",
"BytesWatcher",
",",
"decrypter",
"ArbitraryDecrypter",
",",
"decryptFunc",
"DecryptFunc",
")",
"*",
"BytesWatcherWrapper",
"{",
"return",
"&",
"BytesWatcherWrapper",
"{",
"BytesWatcher",
":",
"pb",
",",
"decryptData",
":",
"decryptData",
"{",
"decryptFunc",
":",
"decryptFunc",
",",
"decrypter",
":",
"decrypter",
",",
"}",
",",
"}",
"\n",
"}"
] | // NewBytesWatcherWrapper creates wrapper for provided BytesWatcher, adding support for decrypting encrypted data | [
"NewBytesWatcherWrapper",
"creates",
"wrapper",
"for",
"provided",
"BytesWatcher",
"adding",
"support",
"for",
"decrypting",
"encrypted",
"data"
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/cryptodata/wrapper_bytes.go#L79-L87 |
4,697 | ligato/cn-infra | db/cryptodata/wrapper_bytes.go | GetValue | func (cbb *BytesBrokerWrapper) GetValue(key string) (data []byte, found bool, revision int64, err error) {
data, found, revision, err = cbb.BytesBroker.GetValue(key)
if err == nil {
objData, err := cbb.decrypter.Decrypt(data, cbb.decryptFunc)
if err != nil {
return data, found, revision, err
}
outData, ok := objData.([]byte)
if !ok {
return data, found, revision, err
}
return outData, found, revision, err
}
return
} | go | func (cbb *BytesBrokerWrapper) GetValue(key string) (data []byte, found bool, revision int64, err error) {
data, found, revision, err = cbb.BytesBroker.GetValue(key)
if err == nil {
objData, err := cbb.decrypter.Decrypt(data, cbb.decryptFunc)
if err != nil {
return data, found, revision, err
}
outData, ok := objData.([]byte)
if !ok {
return data, found, revision, err
}
return outData, found, revision, err
}
return
} | [
"func",
"(",
"cbb",
"*",
"BytesBrokerWrapper",
")",
"GetValue",
"(",
"key",
"string",
")",
"(",
"data",
"[",
"]",
"byte",
",",
"found",
"bool",
",",
"revision",
"int64",
",",
"err",
"error",
")",
"{",
"data",
",",
"found",
",",
"revision",
",",
"err",
"=",
"cbb",
".",
"BytesBroker",
".",
"GetValue",
"(",
"key",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"objData",
",",
"err",
":=",
"cbb",
".",
"decrypter",
".",
"Decrypt",
"(",
"data",
",",
"cbb",
".",
"decryptFunc",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"data",
",",
"found",
",",
"revision",
",",
"err",
"\n",
"}",
"\n",
"outData",
",",
"ok",
":=",
"objData",
".",
"(",
"[",
"]",
"byte",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"data",
",",
"found",
",",
"revision",
",",
"err",
"\n",
"}",
"\n",
"return",
"outData",
",",
"found",
",",
"revision",
",",
"err",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // GetValue retrieves and tries to decrypt one item under the provided key. | [
"GetValue",
"retrieves",
"and",
"tries",
"to",
"decrypt",
"one",
"item",
"under",
"the",
"provided",
"key",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/cryptodata/wrapper_bytes.go#L105-L119 |
4,698 | ligato/cn-infra | rpc/rest/listen_and_serve.go | ListenAndServe | func ListenAndServe(config Config, handler http.Handler) (srv *http.Server, err error) {
server := &http.Server{
Addr: config.Endpoint,
ReadTimeout: config.ReadTimeout,
ReadHeaderTimeout: config.ReadHeaderTimeout,
WriteTimeout: config.WriteTimeout,
IdleTimeout: config.IdleTimeout,
MaxHeaderBytes: config.MaxHeaderBytes,
Handler: handler,
}
if len(config.ClientCerts) > 0 {
// require client certificate
caCertPool := x509.NewCertPool()
for _, c := range config.ClientCerts {
caCert, err := ioutil.ReadFile(c)
if err != nil {
return nil, err
}
caCertPool.AppendCertsFromPEM(caCert)
}
server.TLSConfig = &tls.Config{
ClientAuth: tls.RequireAndVerifyClientCert,
ClientCAs: caCertPool,
}
}
ln, err := net.Listen("tcp", server.Addr)
if err != nil {
return nil, err
}
l := tcpKeepAliveListener{ln.(*net.TCPListener)}
go func() {
var err error
if config.UseHTTPS() {
// if server certificate and key is configured use HTTPS
err = server.ServeTLS(l, config.ServerCertfile, config.ServerKeyfile)
} else {
err = server.Serve(l)
}
// Serve always returns non-nil error
logging.DefaultLogger.Debugf("HTTP server Serve: %v", err)
}()
return server, nil
} | go | func ListenAndServe(config Config, handler http.Handler) (srv *http.Server, err error) {
server := &http.Server{
Addr: config.Endpoint,
ReadTimeout: config.ReadTimeout,
ReadHeaderTimeout: config.ReadHeaderTimeout,
WriteTimeout: config.WriteTimeout,
IdleTimeout: config.IdleTimeout,
MaxHeaderBytes: config.MaxHeaderBytes,
Handler: handler,
}
if len(config.ClientCerts) > 0 {
// require client certificate
caCertPool := x509.NewCertPool()
for _, c := range config.ClientCerts {
caCert, err := ioutil.ReadFile(c)
if err != nil {
return nil, err
}
caCertPool.AppendCertsFromPEM(caCert)
}
server.TLSConfig = &tls.Config{
ClientAuth: tls.RequireAndVerifyClientCert,
ClientCAs: caCertPool,
}
}
ln, err := net.Listen("tcp", server.Addr)
if err != nil {
return nil, err
}
l := tcpKeepAliveListener{ln.(*net.TCPListener)}
go func() {
var err error
if config.UseHTTPS() {
// if server certificate and key is configured use HTTPS
err = server.ServeTLS(l, config.ServerCertfile, config.ServerKeyfile)
} else {
err = server.Serve(l)
}
// Serve always returns non-nil error
logging.DefaultLogger.Debugf("HTTP server Serve: %v", err)
}()
return server, nil
} | [
"func",
"ListenAndServe",
"(",
"config",
"Config",
",",
"handler",
"http",
".",
"Handler",
")",
"(",
"srv",
"*",
"http",
".",
"Server",
",",
"err",
"error",
")",
"{",
"server",
":=",
"&",
"http",
".",
"Server",
"{",
"Addr",
":",
"config",
".",
"Endpoint",
",",
"ReadTimeout",
":",
"config",
".",
"ReadTimeout",
",",
"ReadHeaderTimeout",
":",
"config",
".",
"ReadHeaderTimeout",
",",
"WriteTimeout",
":",
"config",
".",
"WriteTimeout",
",",
"IdleTimeout",
":",
"config",
".",
"IdleTimeout",
",",
"MaxHeaderBytes",
":",
"config",
".",
"MaxHeaderBytes",
",",
"Handler",
":",
"handler",
",",
"}",
"\n\n",
"if",
"len",
"(",
"config",
".",
"ClientCerts",
")",
">",
"0",
"{",
"// require client certificate",
"caCertPool",
":=",
"x509",
".",
"NewCertPool",
"(",
")",
"\n\n",
"for",
"_",
",",
"c",
":=",
"range",
"config",
".",
"ClientCerts",
"{",
"caCert",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"c",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"caCertPool",
".",
"AppendCertsFromPEM",
"(",
"caCert",
")",
"\n",
"}",
"\n\n",
"server",
".",
"TLSConfig",
"=",
"&",
"tls",
".",
"Config",
"{",
"ClientAuth",
":",
"tls",
".",
"RequireAndVerifyClientCert",
",",
"ClientCAs",
":",
"caCertPool",
",",
"}",
"\n",
"}",
"\n\n",
"ln",
",",
"err",
":=",
"net",
".",
"Listen",
"(",
"\"",
"\"",
",",
"server",
".",
"Addr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"l",
":=",
"tcpKeepAliveListener",
"{",
"ln",
".",
"(",
"*",
"net",
".",
"TCPListener",
")",
"}",
"\n\n",
"go",
"func",
"(",
")",
"{",
"var",
"err",
"error",
"\n",
"if",
"config",
".",
"UseHTTPS",
"(",
")",
"{",
"// if server certificate and key is configured use HTTPS",
"err",
"=",
"server",
".",
"ServeTLS",
"(",
"l",
",",
"config",
".",
"ServerCertfile",
",",
"config",
".",
"ServerKeyfile",
")",
"\n",
"}",
"else",
"{",
"err",
"=",
"server",
".",
"Serve",
"(",
"l",
")",
"\n",
"}",
"\n",
"// Serve always returns non-nil error",
"logging",
".",
"DefaultLogger",
".",
"Debugf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"(",
")",
"\n\n",
"return",
"server",
",",
"nil",
"\n",
"}"
] | // ListenAndServe starts a http server. | [
"ListenAndServe",
"starts",
"a",
"http",
"server",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/rpc/rest/listen_and_serve.go#L29-L77 |
4,699 | ligato/cn-infra | db/keyval/proto_serializer.go | Unmarshal | func (sp *SerializerProto) Unmarshal(data []byte, protoData proto.Message) error {
return proto.Unmarshal(data, protoData)
} | go | func (sp *SerializerProto) Unmarshal(data []byte, protoData proto.Message) error {
return proto.Unmarshal(data, protoData)
} | [
"func",
"(",
"sp",
"*",
"SerializerProto",
")",
"Unmarshal",
"(",
"data",
"[",
"]",
"byte",
",",
"protoData",
"proto",
".",
"Message",
")",
"error",
"{",
"return",
"proto",
".",
"Unmarshal",
"(",
"data",
",",
"protoData",
")",
"\n",
"}"
] | // Unmarshal deserializes data from slice of bytes into the provided protobuf
// message using proto marshaller. | [
"Unmarshal",
"deserializes",
"data",
"from",
"slice",
"of",
"bytes",
"into",
"the",
"provided",
"protobuf",
"message",
"using",
"proto",
"marshaller",
"."
] | 6552f4407e293b0986ec353eb0f01968cbecb928 | https://github.com/ligato/cn-infra/blob/6552f4407e293b0986ec353eb0f01968cbecb928/db/keyval/proto_serializer.go#L42-L44 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.