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
listlengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
listlengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
15,300
intelsdi-x/snap
scheduler/task.go
Spin
func (t *task) Spin() { // We need to lock long enough to change state t.Lock() defer t.Unlock() // if this task is a streaming task if t.isStream { t.state = core.TaskSpinning t.killChan = make(chan struct{}) go t.stream() return } // Reset the lastFireTime at each Spin. // This ensures misses are tracked only forward of the point // in time that a task starts spinning. E.g. stopping a task, // waiting a period of time, and starting the task won't show // misses for the interval while stopped. t.lastFireTime = time.Time{} if t.state == core.TaskStopped || t.state == core.TaskEnded { t.state = core.TaskSpinning t.killChan = make(chan struct{}) // spin in a goroutine go t.spin() } }
go
func (t *task) Spin() { // We need to lock long enough to change state t.Lock() defer t.Unlock() // if this task is a streaming task if t.isStream { t.state = core.TaskSpinning t.killChan = make(chan struct{}) go t.stream() return } // Reset the lastFireTime at each Spin. // This ensures misses are tracked only forward of the point // in time that a task starts spinning. E.g. stopping a task, // waiting a period of time, and starting the task won't show // misses for the interval while stopped. t.lastFireTime = time.Time{} if t.state == core.TaskStopped || t.state == core.TaskEnded { t.state = core.TaskSpinning t.killChan = make(chan struct{}) // spin in a goroutine go t.spin() } }
[ "func", "(", "t", "*", "task", ")", "Spin", "(", ")", "{", "// We need to lock long enough to change state", "t", ".", "Lock", "(", ")", "\n", "defer", "t", ".", "Unlock", "(", ")", "\n", "// if this task is a streaming task", "if", "t", ".", "isStream", "{", "t", ".", "state", "=", "core", ".", "TaskSpinning", "\n", "t", ".", "killChan", "=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "go", "t", ".", "stream", "(", ")", "\n", "return", "\n", "}", "\n\n", "// Reset the lastFireTime at each Spin.", "// This ensures misses are tracked only forward of the point", "// in time that a task starts spinning. E.g. stopping a task,", "// waiting a period of time, and starting the task won't show", "// misses for the interval while stopped.", "t", ".", "lastFireTime", "=", "time", ".", "Time", "{", "}", "\n\n", "if", "t", ".", "state", "==", "core", ".", "TaskStopped", "||", "t", ".", "state", "==", "core", ".", "TaskEnded", "{", "t", ".", "state", "=", "core", ".", "TaskSpinning", "\n", "t", ".", "killChan", "=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "// spin in a goroutine", "go", "t", ".", "spin", "(", ")", "\n", "}", "\n", "}" ]
// Spin will start a task spinning in its own routine while it waits for its // schedule.
[ "Spin", "will", "start", "a", "task", "spinning", "in", "its", "own", "routine", "while", "it", "waits", "for", "its", "schedule", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/scheduler/task.go#L239-L264
15,301
intelsdi-x/snap
scheduler/task.go
stream
func (t *task) stream() { var consecutiveFailures int resetTime := time.Second * 3 for { metricsChan, errChan, err := t.metricsManager.StreamMetrics( t.id, t.workflow.tags, t.maxCollectDuration, t.maxMetricsBuffer) if err != nil { consecutiveFailures++ // check task failures if t.stopOnFailure >= 0 && consecutiveFailures >= t.stopOnFailure { taskLogger.WithFields(log.Fields{ "_block": "stream", "task-id": t.id, "task-name": t.name, "consecutive failures": consecutiveFailures, "error": t.lastFailureMessage, }).Error(ErrTaskDisabledOnFailures) // disable the task t.disable(t.lastFailureMessage) return } // If we are unsuccessful at setting up the stream // wait for a second and then try again until either // the connection is successful or we pass the // acceptable number of consecutive failures time.Sleep(resetTime) continue } else { consecutiveFailures = 0 } done := false for !done { if errChan == nil { break } select { case <-t.killChan: t.Lock() t.state = core.TaskStopped t.Unlock() done = true event := new(scheduler_event.TaskStoppedEvent) event.TaskID = t.id defer t.eventEmitter.Emit(event) return case mts, ok := <-metricsChan: if !ok { metricsChan = nil break } if len(mts) == 0 { continue } t.hitCount++ consecutiveFailures = 0 t.workflow.StreamStart(t, mts) case err := <-errChan: taskLogger.WithFields(log.Fields{ "_block": "stream", "task-id": t.id, "task-name": t.name, }).Error("Error: " + err.Error()) consecutiveFailures++ if err.Error() == "connection broken" { // Wait here before trying to reconnect to allow time // for plugin restarts. time.Sleep(resetTime) done = true } // check task failures if t.stopOnFailure >= 0 && consecutiveFailures >= t.stopOnFailure { taskLogger.WithFields(log.Fields{ "_block": "stream", "task-id": t.id, "task-name": t.name, "consecutive failures": consecutiveFailures, "error": t.lastFailureMessage, }).Error(ErrTaskDisabledOnFailures) // disable the task t.disable(t.lastFailureMessage) return } } } } }
go
func (t *task) stream() { var consecutiveFailures int resetTime := time.Second * 3 for { metricsChan, errChan, err := t.metricsManager.StreamMetrics( t.id, t.workflow.tags, t.maxCollectDuration, t.maxMetricsBuffer) if err != nil { consecutiveFailures++ // check task failures if t.stopOnFailure >= 0 && consecutiveFailures >= t.stopOnFailure { taskLogger.WithFields(log.Fields{ "_block": "stream", "task-id": t.id, "task-name": t.name, "consecutive failures": consecutiveFailures, "error": t.lastFailureMessage, }).Error(ErrTaskDisabledOnFailures) // disable the task t.disable(t.lastFailureMessage) return } // If we are unsuccessful at setting up the stream // wait for a second and then try again until either // the connection is successful or we pass the // acceptable number of consecutive failures time.Sleep(resetTime) continue } else { consecutiveFailures = 0 } done := false for !done { if errChan == nil { break } select { case <-t.killChan: t.Lock() t.state = core.TaskStopped t.Unlock() done = true event := new(scheduler_event.TaskStoppedEvent) event.TaskID = t.id defer t.eventEmitter.Emit(event) return case mts, ok := <-metricsChan: if !ok { metricsChan = nil break } if len(mts) == 0 { continue } t.hitCount++ consecutiveFailures = 0 t.workflow.StreamStart(t, mts) case err := <-errChan: taskLogger.WithFields(log.Fields{ "_block": "stream", "task-id": t.id, "task-name": t.name, }).Error("Error: " + err.Error()) consecutiveFailures++ if err.Error() == "connection broken" { // Wait here before trying to reconnect to allow time // for plugin restarts. time.Sleep(resetTime) done = true } // check task failures if t.stopOnFailure >= 0 && consecutiveFailures >= t.stopOnFailure { taskLogger.WithFields(log.Fields{ "_block": "stream", "task-id": t.id, "task-name": t.name, "consecutive failures": consecutiveFailures, "error": t.lastFailureMessage, }).Error(ErrTaskDisabledOnFailures) // disable the task t.disable(t.lastFailureMessage) return } } } } }
[ "func", "(", "t", "*", "task", ")", "stream", "(", ")", "{", "var", "consecutiveFailures", "int", "\n", "resetTime", ":=", "time", ".", "Second", "*", "3", "\n", "for", "{", "metricsChan", ",", "errChan", ",", "err", ":=", "t", ".", "metricsManager", ".", "StreamMetrics", "(", "t", ".", "id", ",", "t", ".", "workflow", ".", "tags", ",", "t", ".", "maxCollectDuration", ",", "t", ".", "maxMetricsBuffer", ")", "\n", "if", "err", "!=", "nil", "{", "consecutiveFailures", "++", "\n", "// check task failures", "if", "t", ".", "stopOnFailure", ">=", "0", "&&", "consecutiveFailures", ">=", "t", ".", "stopOnFailure", "{", "taskLogger", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "t", ".", "id", ",", "\"", "\"", ":", "t", ".", "name", ",", "\"", "\"", ":", "consecutiveFailures", ",", "\"", "\"", ":", "t", ".", "lastFailureMessage", ",", "}", ")", ".", "Error", "(", "ErrTaskDisabledOnFailures", ")", "\n", "// disable the task", "t", ".", "disable", "(", "t", ".", "lastFailureMessage", ")", "\n", "return", "\n", "}", "\n", "// If we are unsuccessful at setting up the stream", "// wait for a second and then try again until either", "// the connection is successful or we pass the", "// acceptable number of consecutive failures", "time", ".", "Sleep", "(", "resetTime", ")", "\n", "continue", "\n", "}", "else", "{", "consecutiveFailures", "=", "0", "\n", "}", "\n", "done", ":=", "false", "\n", "for", "!", "done", "{", "if", "errChan", "==", "nil", "{", "break", "\n", "}", "\n", "select", "{", "case", "<-", "t", ".", "killChan", ":", "t", ".", "Lock", "(", ")", "\n", "t", ".", "state", "=", "core", ".", "TaskStopped", "\n", "t", ".", "Unlock", "(", ")", "\n", "done", "=", "true", "\n", "event", ":=", "new", "(", "scheduler_event", ".", "TaskStoppedEvent", ")", "\n", "event", ".", "TaskID", "=", "t", ".", "id", "\n", "defer", "t", ".", "eventEmitter", ".", "Emit", "(", "event", ")", "\n", "return", "\n", "case", "mts", ",", "ok", ":=", "<-", "metricsChan", ":", "if", "!", "ok", "{", "metricsChan", "=", "nil", "\n", "break", "\n", "}", "\n", "if", "len", "(", "mts", ")", "==", "0", "{", "continue", "\n", "}", "\n", "t", ".", "hitCount", "++", "\n", "consecutiveFailures", "=", "0", "\n", "t", ".", "workflow", ".", "StreamStart", "(", "t", ",", "mts", ")", "\n", "case", "err", ":=", "<-", "errChan", ":", "taskLogger", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "t", ".", "id", ",", "\"", "\"", ":", "t", ".", "name", ",", "}", ")", ".", "Error", "(", "\"", "\"", "+", "err", ".", "Error", "(", ")", ")", "\n", "consecutiveFailures", "++", "\n", "if", "err", ".", "Error", "(", ")", "==", "\"", "\"", "{", "// Wait here before trying to reconnect to allow time", "// for plugin restarts.", "time", ".", "Sleep", "(", "resetTime", ")", "\n", "done", "=", "true", "\n", "}", "\n", "// check task failures", "if", "t", ".", "stopOnFailure", ">=", "0", "&&", "consecutiveFailures", ">=", "t", ".", "stopOnFailure", "{", "taskLogger", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "t", ".", "id", ",", "\"", "\"", ":", "t", ".", "name", ",", "\"", "\"", ":", "consecutiveFailures", ",", "\"", "\"", ":", "t", ".", "lastFailureMessage", ",", "}", ")", ".", "Error", "(", "ErrTaskDisabledOnFailures", ")", "\n", "// disable the task", "t", ".", "disable", "(", "t", ".", "lastFailureMessage", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// Fork stream stuff here
[ "Fork", "stream", "stuff", "here" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/scheduler/task.go#L267-L355
15,302
intelsdi-x/snap
scheduler/task.go
UnsubscribePlugins
func (t *task) UnsubscribePlugins() []serror.SnapError { depGroups := getWorkflowPlugins(t.workflow.processNodes, t.workflow.publishNodes, t.workflow.metrics) var errs []serror.SnapError for k := range depGroups { event := &scheduler_event.PluginsUnsubscribedEvent{ TaskID: t.ID(), Plugins: depGroups[k].subscribedPlugins, } defer t.eventEmitter.Emit(event) mgr, err := t.RemoteManagers.Get(k) if err != nil { errs = append(errs, serror.New(err)) } else { uerrs := mgr.UnsubscribeDeps(t.ID()) if len(uerrs) > 0 { errs = append(errs, uerrs...) } } } for _, err := range errs { taskLogger.WithFields(log.Fields{ "_block": "UnsubscribePlugins", "task-id": t.id, "task-name": t.name, "task-state": t.state, }).Error(err) } return errs }
go
func (t *task) UnsubscribePlugins() []serror.SnapError { depGroups := getWorkflowPlugins(t.workflow.processNodes, t.workflow.publishNodes, t.workflow.metrics) var errs []serror.SnapError for k := range depGroups { event := &scheduler_event.PluginsUnsubscribedEvent{ TaskID: t.ID(), Plugins: depGroups[k].subscribedPlugins, } defer t.eventEmitter.Emit(event) mgr, err := t.RemoteManagers.Get(k) if err != nil { errs = append(errs, serror.New(err)) } else { uerrs := mgr.UnsubscribeDeps(t.ID()) if len(uerrs) > 0 { errs = append(errs, uerrs...) } } } for _, err := range errs { taskLogger.WithFields(log.Fields{ "_block": "UnsubscribePlugins", "task-id": t.id, "task-name": t.name, "task-state": t.state, }).Error(err) } return errs }
[ "func", "(", "t", "*", "task", ")", "UnsubscribePlugins", "(", ")", "[", "]", "serror", ".", "SnapError", "{", "depGroups", ":=", "getWorkflowPlugins", "(", "t", ".", "workflow", ".", "processNodes", ",", "t", ".", "workflow", ".", "publishNodes", ",", "t", ".", "workflow", ".", "metrics", ")", "\n", "var", "errs", "[", "]", "serror", ".", "SnapError", "\n", "for", "k", ":=", "range", "depGroups", "{", "event", ":=", "&", "scheduler_event", ".", "PluginsUnsubscribedEvent", "{", "TaskID", ":", "t", ".", "ID", "(", ")", ",", "Plugins", ":", "depGroups", "[", "k", "]", ".", "subscribedPlugins", ",", "}", "\n", "defer", "t", ".", "eventEmitter", ".", "Emit", "(", "event", ")", "\n", "mgr", ",", "err", ":=", "t", ".", "RemoteManagers", ".", "Get", "(", "k", ")", "\n", "if", "err", "!=", "nil", "{", "errs", "=", "append", "(", "errs", ",", "serror", ".", "New", "(", "err", ")", ")", "\n", "}", "else", "{", "uerrs", ":=", "mgr", ".", "UnsubscribeDeps", "(", "t", ".", "ID", "(", ")", ")", "\n", "if", "len", "(", "uerrs", ")", ">", "0", "{", "errs", "=", "append", "(", "errs", ",", "uerrs", "...", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "for", "_", ",", "err", ":=", "range", "errs", "{", "taskLogger", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "t", ".", "id", ",", "\"", "\"", ":", "t", ".", "name", ",", "\"", "\"", ":", "t", ".", "state", ",", "}", ")", ".", "Error", "(", "err", ")", "\n", "}", "\n", "return", "errs", "\n", "}" ]
// UnsubscribePlugins groups task dependencies by the node they live in workflow and unsubscribe them
[ "UnsubscribePlugins", "groups", "task", "dependencies", "by", "the", "node", "they", "live", "in", "workflow", "and", "unsubscribe", "them" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/scheduler/task.go#L367-L395
15,303
intelsdi-x/snap
scheduler/task.go
SubscribePlugins
func (t *task) SubscribePlugins() ([]string, []serror.SnapError) { depGroups := getWorkflowPlugins(t.workflow.processNodes, t.workflow.publishNodes, t.workflow.metrics) var subbedDeps []string for k := range depGroups { var errs []serror.SnapError mgr, err := t.RemoteManagers.Get(k) if err != nil { errs = append(errs, serror.New(err)) } else { errs = mgr.SubscribeDeps(t.ID(), depGroups[k].requestedMetrics, depGroups[k].subscribedPlugins, t.workflow.configTree) } // If there are errors with subscribing any deps, go through and unsubscribe all other // deps that may have already been subscribed then return the errors. if len(errs) > 0 { for _, key := range subbedDeps { mgr, err := t.RemoteManagers.Get(key) if err != nil { errs = append(errs, serror.New(err)) } else { // sending empty mts to unsubscribe to indicate task should not start uerrs := mgr.UnsubscribeDeps(t.ID()) errs = append(errs, uerrs...) } } return nil, errs } // If subscribed successfully add to subbedDeps subbedDeps = append(subbedDeps, k) } return subbedDeps, nil }
go
func (t *task) SubscribePlugins() ([]string, []serror.SnapError) { depGroups := getWorkflowPlugins(t.workflow.processNodes, t.workflow.publishNodes, t.workflow.metrics) var subbedDeps []string for k := range depGroups { var errs []serror.SnapError mgr, err := t.RemoteManagers.Get(k) if err != nil { errs = append(errs, serror.New(err)) } else { errs = mgr.SubscribeDeps(t.ID(), depGroups[k].requestedMetrics, depGroups[k].subscribedPlugins, t.workflow.configTree) } // If there are errors with subscribing any deps, go through and unsubscribe all other // deps that may have already been subscribed then return the errors. if len(errs) > 0 { for _, key := range subbedDeps { mgr, err := t.RemoteManagers.Get(key) if err != nil { errs = append(errs, serror.New(err)) } else { // sending empty mts to unsubscribe to indicate task should not start uerrs := mgr.UnsubscribeDeps(t.ID()) errs = append(errs, uerrs...) } } return nil, errs } // If subscribed successfully add to subbedDeps subbedDeps = append(subbedDeps, k) } return subbedDeps, nil }
[ "func", "(", "t", "*", "task", ")", "SubscribePlugins", "(", ")", "(", "[", "]", "string", ",", "[", "]", "serror", ".", "SnapError", ")", "{", "depGroups", ":=", "getWorkflowPlugins", "(", "t", ".", "workflow", ".", "processNodes", ",", "t", ".", "workflow", ".", "publishNodes", ",", "t", ".", "workflow", ".", "metrics", ")", "\n", "var", "subbedDeps", "[", "]", "string", "\n", "for", "k", ":=", "range", "depGroups", "{", "var", "errs", "[", "]", "serror", ".", "SnapError", "\n", "mgr", ",", "err", ":=", "t", ".", "RemoteManagers", ".", "Get", "(", "k", ")", "\n", "if", "err", "!=", "nil", "{", "errs", "=", "append", "(", "errs", ",", "serror", ".", "New", "(", "err", ")", ")", "\n", "}", "else", "{", "errs", "=", "mgr", ".", "SubscribeDeps", "(", "t", ".", "ID", "(", ")", ",", "depGroups", "[", "k", "]", ".", "requestedMetrics", ",", "depGroups", "[", "k", "]", ".", "subscribedPlugins", ",", "t", ".", "workflow", ".", "configTree", ")", "\n", "}", "\n", "// If there are errors with subscribing any deps, go through and unsubscribe all other", "// deps that may have already been subscribed then return the errors.", "if", "len", "(", "errs", ")", ">", "0", "{", "for", "_", ",", "key", ":=", "range", "subbedDeps", "{", "mgr", ",", "err", ":=", "t", ".", "RemoteManagers", ".", "Get", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "errs", "=", "append", "(", "errs", ",", "serror", ".", "New", "(", "err", ")", ")", "\n", "}", "else", "{", "// sending empty mts to unsubscribe to indicate task should not start", "uerrs", ":=", "mgr", ".", "UnsubscribeDeps", "(", "t", ".", "ID", "(", ")", ")", "\n", "errs", "=", "append", "(", "errs", ",", "uerrs", "...", ")", "\n", "}", "\n", "}", "\n", "return", "nil", ",", "errs", "\n", "}", "\n", "// If subscribed successfully add to subbedDeps", "subbedDeps", "=", "append", "(", "subbedDeps", ",", "k", ")", "\n", "}", "\n\n", "return", "subbedDeps", ",", "nil", "\n", "}" ]
// SubscribePlugins groups task dependencies by the node they live in workflow and subscribe them. // If there are errors with subscribing any deps, manage unsubscribing all other deps that may have already been subscribed // and then return the errors.
[ "SubscribePlugins", "groups", "task", "dependencies", "by", "the", "node", "they", "live", "in", "workflow", "and", "subscribe", "them", ".", "If", "there", "are", "errors", "with", "subscribing", "any", "deps", "manage", "unsubscribing", "all", "other", "deps", "that", "may", "have", "already", "been", "subscribed", "and", "then", "return", "the", "errors", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/scheduler/task.go#L400-L431
15,304
intelsdi-x/snap
scheduler/task.go
Enable
func (t *task) Enable() error { t.Lock() defer t.Unlock() if t.state != core.TaskDisabled { return ErrTaskNotDisabled } t.state = core.TaskStopped return nil }
go
func (t *task) Enable() error { t.Lock() defer t.Unlock() if t.state != core.TaskDisabled { return ErrTaskNotDisabled } t.state = core.TaskStopped return nil }
[ "func", "(", "t", "*", "task", ")", "Enable", "(", ")", "error", "{", "t", ".", "Lock", "(", ")", "\n", "defer", "t", ".", "Unlock", "(", ")", "\n\n", "if", "t", ".", "state", "!=", "core", ".", "TaskDisabled", "{", "return", "ErrTaskNotDisabled", "\n", "}", "\n", "t", ".", "state", "=", "core", ".", "TaskStopped", "\n\n", "return", "nil", "\n", "}" ]
//Enable changes the state from Disabled to Stopped
[ "Enable", "changes", "the", "state", "from", "Disabled", "to", "Stopped" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/scheduler/task.go#L434-L444
15,305
intelsdi-x/snap
scheduler/task.go
disable
func (t *task) disable(failureMsg string) { t.Lock() t.state = core.TaskDisabled t.Unlock() // Send task disabled event event := new(scheduler_event.TaskDisabledEvent) event.TaskID = t.id event.Why = fmt.Sprintf("Task disabled with error: %s", failureMsg) defer t.eventEmitter.Emit(event) }
go
func (t *task) disable(failureMsg string) { t.Lock() t.state = core.TaskDisabled t.Unlock() // Send task disabled event event := new(scheduler_event.TaskDisabledEvent) event.TaskID = t.id event.Why = fmt.Sprintf("Task disabled with error: %s", failureMsg) defer t.eventEmitter.Emit(event) }
[ "func", "(", "t", "*", "task", ")", "disable", "(", "failureMsg", "string", ")", "{", "t", ".", "Lock", "(", ")", "\n", "t", ".", "state", "=", "core", ".", "TaskDisabled", "\n", "t", ".", "Unlock", "(", ")", "\n\n", "// Send task disabled event", "event", ":=", "new", "(", "scheduler_event", ".", "TaskDisabledEvent", ")", "\n", "event", ".", "TaskID", "=", "t", ".", "id", "\n", "event", ".", "Why", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "failureMsg", ")", "\n", "defer", "t", ".", "eventEmitter", ".", "Emit", "(", "event", ")", "\n", "}" ]
// disable proceeds disabling a task which consists of changing task state to disabled and emitting an appropriate event
[ "disable", "proceeds", "disabling", "a", "task", "which", "consists", "of", "changing", "task", "state", "to", "disabled", "and", "emitting", "an", "appropriate", "event" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/scheduler/task.go#L552-L562
15,306
intelsdi-x/snap
scheduler/task.go
RecordFailure
func (t *task) RecordFailure(e []error) { // We synchronize this update to ensure it is atomic t.failureMutex.Lock() defer t.failureMutex.Unlock() t.failedRuns++ t.lastFailureTime = t.lastFireTime t.lastFailureMessage = e[len(e)-1].Error() }
go
func (t *task) RecordFailure(e []error) { // We synchronize this update to ensure it is atomic t.failureMutex.Lock() defer t.failureMutex.Unlock() t.failedRuns++ t.lastFailureTime = t.lastFireTime t.lastFailureMessage = e[len(e)-1].Error() }
[ "func", "(", "t", "*", "task", ")", "RecordFailure", "(", "e", "[", "]", "error", ")", "{", "// We synchronize this update to ensure it is atomic", "t", ".", "failureMutex", ".", "Lock", "(", ")", "\n", "defer", "t", ".", "failureMutex", ".", "Unlock", "(", ")", "\n", "t", ".", "failedRuns", "++", "\n", "t", ".", "lastFailureTime", "=", "t", ".", "lastFireTime", "\n", "t", ".", "lastFailureMessage", "=", "e", "[", "len", "(", "e", ")", "-", "1", "]", ".", "Error", "(", ")", "\n", "}" ]
// RecordFailure updates the failed runs and last failure properties
[ "RecordFailure", "updates", "the", "failed", "runs", "and", "last", "failure", "properties" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/scheduler/task.go#L573-L580
15,307
intelsdi-x/snap
scheduler/task.go
Get
func (t *taskCollection) Get(id string) *task { t.Lock() defer t.Unlock() if t, ok := t.table[id]; ok { return t } return nil }
go
func (t *taskCollection) Get(id string) *task { t.Lock() defer t.Unlock() if t, ok := t.table[id]; ok { return t } return nil }
[ "func", "(", "t", "*", "taskCollection", ")", "Get", "(", "id", "string", ")", "*", "task", "{", "t", ".", "Lock", "(", ")", "\n", "defer", "t", ".", "Unlock", "(", ")", "\n\n", "if", "t", ",", "ok", ":=", "t", ".", "table", "[", "id", "]", ";", "ok", "{", "return", "t", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Get given a task id returns a Task or nil if not found
[ "Get", "given", "a", "task", "id", "returns", "a", "Task", "or", "nil", "if", "not", "found" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/scheduler/task.go#L597-L605
15,308
intelsdi-x/snap
scheduler/task.go
add
func (t *taskCollection) add(task *task) error { t.Lock() defer t.Unlock() if _, ok := t.table[task.id]; !ok { //If we don't already have this task in the collection save it t.table[task.id] = task } else { taskLogger.WithFields(log.Fields{ "_module": "scheduler-taskCollection", "_block": "add", "task id": task.id, }).Error(ErrTaskHasAlreadyBeenAdded.Error()) return ErrTaskHasAlreadyBeenAdded } return nil }
go
func (t *taskCollection) add(task *task) error { t.Lock() defer t.Unlock() if _, ok := t.table[task.id]; !ok { //If we don't already have this task in the collection save it t.table[task.id] = task } else { taskLogger.WithFields(log.Fields{ "_module": "scheduler-taskCollection", "_block": "add", "task id": task.id, }).Error(ErrTaskHasAlreadyBeenAdded.Error()) return ErrTaskHasAlreadyBeenAdded } return nil }
[ "func", "(", "t", "*", "taskCollection", ")", "add", "(", "task", "*", "task", ")", "error", "{", "t", ".", "Lock", "(", ")", "\n", "defer", "t", ".", "Unlock", "(", ")", "\n\n", "if", "_", ",", "ok", ":=", "t", ".", "table", "[", "task", ".", "id", "]", ";", "!", "ok", "{", "//If we don't already have this task in the collection save it", "t", ".", "table", "[", "task", ".", "id", "]", "=", "task", "\n", "}", "else", "{", "taskLogger", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "task", ".", "id", ",", "}", ")", ".", "Error", "(", "ErrTaskHasAlreadyBeenAdded", ".", "Error", "(", ")", ")", "\n", "return", "ErrTaskHasAlreadyBeenAdded", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Add given a reference to a task adds it to the collection of tasks. An // error is returned if the task already exists in the collection.
[ "Add", "given", "a", "reference", "to", "a", "task", "adds", "it", "to", "the", "collection", "of", "tasks", ".", "An", "error", "is", "returned", "if", "the", "task", "already", "exists", "in", "the", "collection", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/scheduler/task.go#L609-L626
15,309
intelsdi-x/snap
scheduler/task.go
remove
func (t *taskCollection) remove(task *task) error { t.Lock() defer t.Unlock() if _, ok := t.table[task.id]; ok { if task.state != core.TaskStopped && task.state != core.TaskDisabled && task.state != core.TaskEnded { taskLogger.WithFields(log.Fields{ "_block": "remove", "task id": task.id, }).Error(ErrTaskNotStopped) return ErrTaskNotStopped } delete(t.table, task.id) } else { taskLogger.WithFields(log.Fields{ "_block": "remove", "task id": task.id, }).Error(ErrTaskNotFound) return ErrTaskNotFound } return nil }
go
func (t *taskCollection) remove(task *task) error { t.Lock() defer t.Unlock() if _, ok := t.table[task.id]; ok { if task.state != core.TaskStopped && task.state != core.TaskDisabled && task.state != core.TaskEnded { taskLogger.WithFields(log.Fields{ "_block": "remove", "task id": task.id, }).Error(ErrTaskNotStopped) return ErrTaskNotStopped } delete(t.table, task.id) } else { taskLogger.WithFields(log.Fields{ "_block": "remove", "task id": task.id, }).Error(ErrTaskNotFound) return ErrTaskNotFound } return nil }
[ "func", "(", "t", "*", "taskCollection", ")", "remove", "(", "task", "*", "task", ")", "error", "{", "t", ".", "Lock", "(", ")", "\n", "defer", "t", ".", "Unlock", "(", ")", "\n", "if", "_", ",", "ok", ":=", "t", ".", "table", "[", "task", ".", "id", "]", ";", "ok", "{", "if", "task", ".", "state", "!=", "core", ".", "TaskStopped", "&&", "task", ".", "state", "!=", "core", ".", "TaskDisabled", "&&", "task", ".", "state", "!=", "core", ".", "TaskEnded", "{", "taskLogger", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "task", ".", "id", ",", "}", ")", ".", "Error", "(", "ErrTaskNotStopped", ")", "\n", "return", "ErrTaskNotStopped", "\n", "}", "\n", "delete", "(", "t", ".", "table", ",", "task", ".", "id", ")", "\n", "}", "else", "{", "taskLogger", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "task", ".", "id", ",", "}", ")", ".", "Error", "(", "ErrTaskNotFound", ")", "\n", "return", "ErrTaskNotFound", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// remove will remove a given task from tasks. The task must be stopped. // Can return errors ErrTaskNotFound and ErrTaskNotStopped.
[ "remove", "will", "remove", "a", "given", "task", "from", "tasks", ".", "The", "task", "must", "be", "stopped", ".", "Can", "return", "errors", "ErrTaskNotFound", "and", "ErrTaskNotStopped", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/scheduler/task.go#L630-L650
15,310
intelsdi-x/snap
scheduler/task.go
Table
func (t *taskCollection) Table() map[string]*task { t.Lock() defer t.Unlock() tasks := make(map[string]*task) for id, t := range t.table { tasks[id] = t } return tasks }
go
func (t *taskCollection) Table() map[string]*task { t.Lock() defer t.Unlock() tasks := make(map[string]*task) for id, t := range t.table { tasks[id] = t } return tasks }
[ "func", "(", "t", "*", "taskCollection", ")", "Table", "(", ")", "map", "[", "string", "]", "*", "task", "{", "t", ".", "Lock", "(", ")", "\n", "defer", "t", ".", "Unlock", "(", ")", "\n", "tasks", ":=", "make", "(", "map", "[", "string", "]", "*", "task", ")", "\n", "for", "id", ",", "t", ":=", "range", "t", ".", "table", "{", "tasks", "[", "id", "]", "=", "t", "\n", "}", "\n", "return", "tasks", "\n", "}" ]
// Table returns a copy of the taskCollection
[ "Table", "returns", "a", "copy", "of", "the", "taskCollection" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/scheduler/task.go#L653-L661
15,311
intelsdi-x/snap
scheduler/task.go
createTaskClients
func createTaskClients(mgrs *managers, wf *schedulerWorkflow) error { return walkWorkflow(wf.processNodes, wf.publishNodes, mgrs) }
go
func createTaskClients(mgrs *managers, wf *schedulerWorkflow) error { return walkWorkflow(wf.processNodes, wf.publishNodes, mgrs) }
[ "func", "createTaskClients", "(", "mgrs", "*", "managers", ",", "wf", "*", "schedulerWorkflow", ")", "error", "{", "return", "walkWorkflow", "(", "wf", ".", "processNodes", ",", "wf", ".", "publishNodes", ",", "mgrs", ")", "\n", "}" ]
// createTaskClients walks the workflowmap and creates clients for this task // remoteManagers so that nodes that require proxy request can make them.
[ "createTaskClients", "walks", "the", "workflowmap", "and", "creates", "clients", "for", "this", "task", "remoteManagers", "so", "that", "nodes", "that", "require", "proxy", "request", "can", "make", "them", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/scheduler/task.go#L665-L667
15,312
intelsdi-x/snap
control/strategy/sticky.go
Select
func (s *sticky) Select(aps []AvailablePlugin, taskID string) (AvailablePlugin, error) { if ap, ok := s.plugins[taskID]; ok && ap != nil { return ap, nil } return s.selectPlugin(aps, taskID) }
go
func (s *sticky) Select(aps []AvailablePlugin, taskID string) (AvailablePlugin, error) { if ap, ok := s.plugins[taskID]; ok && ap != nil { return ap, nil } return s.selectPlugin(aps, taskID) }
[ "func", "(", "s", "*", "sticky", ")", "Select", "(", "aps", "[", "]", "AvailablePlugin", ",", "taskID", "string", ")", "(", "AvailablePlugin", ",", "error", ")", "{", "if", "ap", ",", "ok", ":=", "s", ".", "plugins", "[", "taskID", "]", ";", "ok", "&&", "ap", "!=", "nil", "{", "return", "ap", ",", "nil", "\n", "}", "\n", "return", "s", ".", "selectPlugin", "(", "aps", ",", "taskID", ")", "\n", "}" ]
// Select selects an available plugin using the sticky plugin strategy.
[ "Select", "selects", "an", "available", "plugin", "using", "the", "sticky", "plugin", "strategy", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/strategy/sticky.go#L56-L61
15,313
intelsdi-x/snap
control/runner.go
OptEnableRunnerTLS
func OptEnableRunnerTLS(grpcSecurity client.GRPCSecurity) pluginRunnerOpt { return func(r *runner) { r.grpcSecurity = grpcSecurity } }
go
func OptEnableRunnerTLS(grpcSecurity client.GRPCSecurity) pluginRunnerOpt { return func(r *runner) { r.grpcSecurity = grpcSecurity } }
[ "func", "OptEnableRunnerTLS", "(", "grpcSecurity", "client", ".", "GRPCSecurity", ")", "pluginRunnerOpt", "{", "return", "func", "(", "r", "*", "runner", ")", "{", "r", ".", "grpcSecurity", "=", "grpcSecurity", "\n", "}", "\n", "}" ]
// OptEnableRunnerTLS enables the TLS configuration in runner
[ "OptEnableRunnerTLS", "enables", "the", "TLS", "configuration", "in", "runner" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/runner.go#L99-L103
15,314
intelsdi-x/snap
control/runner.go
Start
func (r *runner) Start() error { // Delegates must be added before starting if none exist // then this Runner can do nothing and should not start. if len(r.delegates) == 0 { return errors.New("No delegates added before called Start()") } // For each delegate register needed handlers for _, del := range r.delegates { e := del.RegisterHandler(HandlerRegistrationName, r) if e != nil { return e } } // Start the monitor r.monitor.Start(r.availablePlugins) runnerLog.WithFields(log.Fields{ "_block": "start", }).Debug("started") return nil }
go
func (r *runner) Start() error { // Delegates must be added before starting if none exist // then this Runner can do nothing and should not start. if len(r.delegates) == 0 { return errors.New("No delegates added before called Start()") } // For each delegate register needed handlers for _, del := range r.delegates { e := del.RegisterHandler(HandlerRegistrationName, r) if e != nil { return e } } // Start the monitor r.monitor.Start(r.availablePlugins) runnerLog.WithFields(log.Fields{ "_block": "start", }).Debug("started") return nil }
[ "func", "(", "r", "*", "runner", ")", "Start", "(", ")", "error", "{", "// Delegates must be added before starting if none exist", "// then this Runner can do nothing and should not start.", "if", "len", "(", "r", ".", "delegates", ")", "==", "0", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// For each delegate register needed handlers", "for", "_", ",", "del", ":=", "range", "r", ".", "delegates", "{", "e", ":=", "del", ".", "RegisterHandler", "(", "HandlerRegistrationName", ",", "r", ")", "\n", "if", "e", "!=", "nil", "{", "return", "e", "\n", "}", "\n", "}", "\n\n", "// Start the monitor", "r", ".", "monitor", ".", "Start", "(", "r", ".", "availablePlugins", ")", "\n", "runnerLog", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "\"", "\"", ",", "}", ")", ".", "Debug", "(", "\"", "\"", ")", "\n", "return", "nil", "\n", "}" ]
// Begin handing events and managing available plugins
[ "Begin", "handing", "events", "and", "managing", "available", "plugins" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/runner.go#L144-L165
15,315
intelsdi-x/snap
control/runner.go
Stop
func (r *runner) Stop() []error { var errs []error // Stop the monitor r.monitor.Stop() // TODO: Actually stop the plugins // For each delegate unregister needed handlers for _, del := range r.delegates { e := del.UnregisterHandler(HandlerRegistrationName) if e != nil { errs = append(errs, e) } } defer runnerLog.WithFields(log.Fields{ "_block": "start-plugin", }).Debug("stopped") return errs }
go
func (r *runner) Stop() []error { var errs []error // Stop the monitor r.monitor.Stop() // TODO: Actually stop the plugins // For each delegate unregister needed handlers for _, del := range r.delegates { e := del.UnregisterHandler(HandlerRegistrationName) if e != nil { errs = append(errs, e) } } defer runnerLog.WithFields(log.Fields{ "_block": "start-plugin", }).Debug("stopped") return errs }
[ "func", "(", "r", "*", "runner", ")", "Stop", "(", ")", "[", "]", "error", "{", "var", "errs", "[", "]", "error", "\n\n", "// Stop the monitor", "r", ".", "monitor", ".", "Stop", "(", ")", "\n\n", "// TODO: Actually stop the plugins", "// For each delegate unregister needed handlers", "for", "_", ",", "del", ":=", "range", "r", ".", "delegates", "{", "e", ":=", "del", ".", "UnregisterHandler", "(", "HandlerRegistrationName", ")", "\n", "if", "e", "!=", "nil", "{", "errs", "=", "append", "(", "errs", ",", "e", ")", "\n", "}", "\n", "}", "\n", "defer", "runnerLog", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "\"", "\"", ",", "}", ")", ".", "Debug", "(", "\"", "\"", ")", "\n", "return", "errs", "\n", "}" ]
// Stop handling, gracefully stop all plugins.
[ "Stop", "handling", "gracefully", "stop", "all", "plugins", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/runner.go#L168-L187
15,316
intelsdi-x/snap
control/runner.go
HandleGomitEvent
func (r *runner) HandleGomitEvent(e gomit.Event) { switch v := e.Body.(type) { case *control_event.DeadAvailablePluginEvent: runnerLog.WithFields(log.Fields{ "_block": "handle-events", "event": v.Namespace(), "aplugin": v.String, }).Warning("handling dead available plugin event") pool, err := r.availablePlugins.getPool(v.Key) if err != nil { runnerLog.WithFields(log.Fields{ "_block": "handle-events", "aplugin": v.String, }).Error(err.Error()) return } if pool != nil { pool.Kill(v.Id, "plugin dead") } if pool.Eligible() { if pool.RestartCount() < MaxPluginRestartCount || MaxPluginRestartCount == -1 { e := r.restartPlugin(v.Key) if e != nil { runnerLog.WithFields(log.Fields{ "_block": "handle-events", "aplugin": v.String, }).Error(e.Error()) return } pool.IncRestartCount() runnerLog.WithFields(log.Fields{ "_block": "handle-events", "aplugin": v.String, "restart-count": pool.RestartCount(), }).Warning("plugin restarted") r.emitter.Emit(&control_event.RestartedAvailablePluginEvent{ Id: v.Id, Name: v.Name, Version: v.Version, Key: v.Key, Type: v.Type, }) } else { runnerLog.WithFields(log.Fields{ "_block": "handle-events", "aplugin": v.String, }).Warning("plugin disabled due to exceeding restart limit: ", MaxPluginRestartCount) r.emitter.Emit(&control_event.MaxPluginRestartsExceededEvent{ Id: v.Id, Name: v.Name, Version: v.Version, Key: v.Key, Type: v.Type, }) } } case *control_event.PluginUnsubscriptionEvent: runnerLog.WithFields(log.Fields{ "_block": "subscribe-pool", "event": v.Namespace(), "plugin-name": v.PluginName, "plugin-version": v.PluginVersion, "plugin-type": core.PluginType(v.PluginType).String(), }).Debug("handling plugin unsubscription event") err := r.handleUnsubscription(core.PluginType(v.PluginType).String(), v.PluginName, v.PluginVersion, v.TaskId) if err != nil { return } default: runnerLog.WithFields(log.Fields{ "_block": "handle-events", "event": v.Namespace(), }).Info("Nothing to do for this event") } }
go
func (r *runner) HandleGomitEvent(e gomit.Event) { switch v := e.Body.(type) { case *control_event.DeadAvailablePluginEvent: runnerLog.WithFields(log.Fields{ "_block": "handle-events", "event": v.Namespace(), "aplugin": v.String, }).Warning("handling dead available plugin event") pool, err := r.availablePlugins.getPool(v.Key) if err != nil { runnerLog.WithFields(log.Fields{ "_block": "handle-events", "aplugin": v.String, }).Error(err.Error()) return } if pool != nil { pool.Kill(v.Id, "plugin dead") } if pool.Eligible() { if pool.RestartCount() < MaxPluginRestartCount || MaxPluginRestartCount == -1 { e := r.restartPlugin(v.Key) if e != nil { runnerLog.WithFields(log.Fields{ "_block": "handle-events", "aplugin": v.String, }).Error(e.Error()) return } pool.IncRestartCount() runnerLog.WithFields(log.Fields{ "_block": "handle-events", "aplugin": v.String, "restart-count": pool.RestartCount(), }).Warning("plugin restarted") r.emitter.Emit(&control_event.RestartedAvailablePluginEvent{ Id: v.Id, Name: v.Name, Version: v.Version, Key: v.Key, Type: v.Type, }) } else { runnerLog.WithFields(log.Fields{ "_block": "handle-events", "aplugin": v.String, }).Warning("plugin disabled due to exceeding restart limit: ", MaxPluginRestartCount) r.emitter.Emit(&control_event.MaxPluginRestartsExceededEvent{ Id: v.Id, Name: v.Name, Version: v.Version, Key: v.Key, Type: v.Type, }) } } case *control_event.PluginUnsubscriptionEvent: runnerLog.WithFields(log.Fields{ "_block": "subscribe-pool", "event": v.Namespace(), "plugin-name": v.PluginName, "plugin-version": v.PluginVersion, "plugin-type": core.PluginType(v.PluginType).String(), }).Debug("handling plugin unsubscription event") err := r.handleUnsubscription(core.PluginType(v.PluginType).String(), v.PluginName, v.PluginVersion, v.TaskId) if err != nil { return } default: runnerLog.WithFields(log.Fields{ "_block": "handle-events", "event": v.Namespace(), }).Info("Nothing to do for this event") } }
[ "func", "(", "r", "*", "runner", ")", "HandleGomitEvent", "(", "e", "gomit", ".", "Event", ")", "{", "switch", "v", ":=", "e", ".", "Body", ".", "(", "type", ")", "{", "case", "*", "control_event", ".", "DeadAvailablePluginEvent", ":", "runnerLog", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "v", ".", "Namespace", "(", ")", ",", "\"", "\"", ":", "v", ".", "String", ",", "}", ")", ".", "Warning", "(", "\"", "\"", ")", "\n\n", "pool", ",", "err", ":=", "r", ".", "availablePlugins", ".", "getPool", "(", "v", ".", "Key", ")", "\n", "if", "err", "!=", "nil", "{", "runnerLog", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "v", ".", "String", ",", "}", ")", ".", "Error", "(", "err", ".", "Error", "(", ")", ")", "\n", "return", "\n", "}", "\n\n", "if", "pool", "!=", "nil", "{", "pool", ".", "Kill", "(", "v", ".", "Id", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "pool", ".", "Eligible", "(", ")", "{", "if", "pool", ".", "RestartCount", "(", ")", "<", "MaxPluginRestartCount", "||", "MaxPluginRestartCount", "==", "-", "1", "{", "e", ":=", "r", ".", "restartPlugin", "(", "v", ".", "Key", ")", "\n", "if", "e", "!=", "nil", "{", "runnerLog", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "v", ".", "String", ",", "}", ")", ".", "Error", "(", "e", ".", "Error", "(", ")", ")", "\n", "return", "\n", "}", "\n", "pool", ".", "IncRestartCount", "(", ")", "\n\n", "runnerLog", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "v", ".", "String", ",", "\"", "\"", ":", "pool", ".", "RestartCount", "(", ")", ",", "}", ")", ".", "Warning", "(", "\"", "\"", ")", "\n\n", "r", ".", "emitter", ".", "Emit", "(", "&", "control_event", ".", "RestartedAvailablePluginEvent", "{", "Id", ":", "v", ".", "Id", ",", "Name", ":", "v", ".", "Name", ",", "Version", ":", "v", ".", "Version", ",", "Key", ":", "v", ".", "Key", ",", "Type", ":", "v", ".", "Type", ",", "}", ")", "\n", "}", "else", "{", "runnerLog", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "v", ".", "String", ",", "}", ")", ".", "Warning", "(", "\"", "\"", ",", "MaxPluginRestartCount", ")", "\n\n", "r", ".", "emitter", ".", "Emit", "(", "&", "control_event", ".", "MaxPluginRestartsExceededEvent", "{", "Id", ":", "v", ".", "Id", ",", "Name", ":", "v", ".", "Name", ",", "Version", ":", "v", ".", "Version", ",", "Key", ":", "v", ".", "Key", ",", "Type", ":", "v", ".", "Type", ",", "}", ")", "\n", "}", "\n", "}", "\n", "case", "*", "control_event", ".", "PluginUnsubscriptionEvent", ":", "runnerLog", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "v", ".", "Namespace", "(", ")", ",", "\"", "\"", ":", "v", ".", "PluginName", ",", "\"", "\"", ":", "v", ".", "PluginVersion", ",", "\"", "\"", ":", "core", ".", "PluginType", "(", "v", ".", "PluginType", ")", ".", "String", "(", ")", ",", "}", ")", ".", "Debug", "(", "\"", "\"", ")", "\n\n", "err", ":=", "r", ".", "handleUnsubscription", "(", "core", ".", "PluginType", "(", "v", ".", "PluginType", ")", ".", "String", "(", ")", ",", "v", ".", "PluginName", ",", "v", ".", "PluginVersion", ",", "v", ".", "TaskId", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "default", ":", "runnerLog", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "v", ".", "Namespace", "(", ")", ",", "}", ")", ".", "Info", "(", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// Empty handler acting as placeholder until implementation. This helps tests // pass to ensure registration works.
[ "Empty", "handler", "acting", "as", "placeholder", "until", "implementation", ".", "This", "helps", "tests", "pass", "to", "ensure", "registration", "works", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/runner.go#L274-L355
15,317
intelsdi-x/snap
scheduler/queue.go
Start
func (q *queue) Start() { q.mutex.Lock() defer q.mutex.Unlock() if q.status == queueStopped { q.status = queueRunning go q.start() } }
go
func (q *queue) Start() { q.mutex.Lock() defer q.mutex.Unlock() if q.status == queueStopped { q.status = queueRunning go q.start() } }
[ "func", "(", "q", "*", "queue", ")", "Start", "(", ")", "{", "q", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "q", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "if", "q", ".", "status", "==", "queueStopped", "{", "q", ".", "status", "=", "queueRunning", "\n", "go", "q", ".", "start", "(", ")", "\n", "}", "\n", "}" ]
// begins the queue handling loop
[ "begins", "the", "queue", "handling", "loop" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/scheduler/queue.go#L78-L87
15,318
intelsdi-x/snap
scheduler/queue.go
Stop
func (q *queue) Stop() { q.mutex.Lock() defer q.mutex.Unlock() if q.status != queueStopped { close(q.kill) q.status = queueStopped } }
go
func (q *queue) Stop() { q.mutex.Lock() defer q.mutex.Unlock() if q.status != queueStopped { close(q.kill) q.status = queueStopped } }
[ "func", "(", "q", "*", "queue", ")", "Stop", "(", ")", "{", "q", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "q", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "if", "q", ".", "status", "!=", "queueStopped", "{", "close", "(", "q", ".", "kill", ")", "\n", "q", ".", "status", "=", "queueStopped", "\n", "}", "\n", "}" ]
// Stop closes both Err and Event channels, and // causes the handling loop to exit.
[ "Stop", "closes", "both", "Err", "and", "Event", "channels", "and", "causes", "the", "handling", "loop", "to", "exit", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/scheduler/queue.go#L91-L100
15,319
intelsdi-x/snap
core/plugin.go
IsUri
func IsUri(url string) bool { if !govalidator.IsURL(url) || !strings.HasPrefix(url, "http") { return false } return true }
go
func IsUri(url string) bool { if !govalidator.IsURL(url) || !strings.HasPrefix(url, "http") { return false } return true }
[ "func", "IsUri", "(", "url", "string", ")", "bool", "{", "if", "!", "govalidator", ".", "IsURL", "(", "url", ")", "||", "!", "strings", ".", "HasPrefix", "(", "url", ",", "\"", "\"", ")", "{", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}" ]
// Checks if string is URL
[ "Checks", "if", "string", "is", "URL" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/core/plugin.go#L209-L214
15,320
intelsdi-x/snap
control/plugin/cpolicy/integer.go
MarshalJSON
func (i *IntRule) MarshalJSON() ([]byte, error) { return json.Marshal(&struct { Key string `json:"key"` Required bool `json:"required"` Default ctypes.ConfigValue `json:"default,omitempty"` Minimum ctypes.ConfigValue `json:"minimum,omitempty"` Maximum ctypes.ConfigValue `json:"maximum,omitempty"` Type string `json:"type"` }{ Key: i.key, Required: i.required, Default: i.Default(), Minimum: i.Minimum(), Maximum: i.Maximum(), Type: IntegerType, }) }
go
func (i *IntRule) MarshalJSON() ([]byte, error) { return json.Marshal(&struct { Key string `json:"key"` Required bool `json:"required"` Default ctypes.ConfigValue `json:"default,omitempty"` Minimum ctypes.ConfigValue `json:"minimum,omitempty"` Maximum ctypes.ConfigValue `json:"maximum,omitempty"` Type string `json:"type"` }{ Key: i.key, Required: i.required, Default: i.Default(), Minimum: i.Minimum(), Maximum: i.Maximum(), Type: IntegerType, }) }
[ "func", "(", "i", "*", "IntRule", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "json", ".", "Marshal", "(", "&", "struct", "{", "Key", "string", "`json:\"key\"`", "\n", "Required", "bool", "`json:\"required\"`", "\n", "Default", "ctypes", ".", "ConfigValue", "`json:\"default,omitempty\"`", "\n", "Minimum", "ctypes", ".", "ConfigValue", "`json:\"minimum,omitempty\"`", "\n", "Maximum", "ctypes", ".", "ConfigValue", "`json:\"maximum,omitempty\"`", "\n", "Type", "string", "`json:\"type\"`", "\n", "}", "{", "Key", ":", "i", ".", "key", ",", "Required", ":", "i", ".", "required", ",", "Default", ":", "i", ".", "Default", "(", ")", ",", "Minimum", ":", "i", ".", "Minimum", "(", ")", ",", "Maximum", ":", "i", ".", "Maximum", "(", ")", ",", "Type", ":", "IntegerType", ",", "}", ")", "\n", "}" ]
// MarshalJSON marshals a IntRule into JSON
[ "MarshalJSON", "marshals", "a", "IntRule", "into", "JSON" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/plugin/cpolicy/integer.go#L70-L86
15,321
intelsdi-x/snap
control/plugin/cpolicy/integer.go
GobDecode
func (i *IntRule) GobDecode(buf []byte) error { r := bytes.NewBuffer(buf) decoder := gob.NewDecoder(r) if err := decoder.Decode(&i.key); err != nil { return err } if err := decoder.Decode(&i.required); err != nil { return err } var is_default_set bool decoder.Decode(&is_default_set) if is_default_set { return decoder.Decode(&i.default_) } var is_minimum_set bool decoder.Decode(&is_minimum_set) if is_minimum_set { if err := decoder.Decode(&i.minimum); err != nil { return err } } var is_maximum_set bool decoder.Decode(&is_maximum_set) if is_maximum_set { if err := decoder.Decode(&i.maximum); err != nil { return err } } return nil }
go
func (i *IntRule) GobDecode(buf []byte) error { r := bytes.NewBuffer(buf) decoder := gob.NewDecoder(r) if err := decoder.Decode(&i.key); err != nil { return err } if err := decoder.Decode(&i.required); err != nil { return err } var is_default_set bool decoder.Decode(&is_default_set) if is_default_set { return decoder.Decode(&i.default_) } var is_minimum_set bool decoder.Decode(&is_minimum_set) if is_minimum_set { if err := decoder.Decode(&i.minimum); err != nil { return err } } var is_maximum_set bool decoder.Decode(&is_maximum_set) if is_maximum_set { if err := decoder.Decode(&i.maximum); err != nil { return err } } return nil }
[ "func", "(", "i", "*", "IntRule", ")", "GobDecode", "(", "buf", "[", "]", "byte", ")", "error", "{", "r", ":=", "bytes", ".", "NewBuffer", "(", "buf", ")", "\n", "decoder", ":=", "gob", ".", "NewDecoder", "(", "r", ")", "\n", "if", "err", ":=", "decoder", ".", "Decode", "(", "&", "i", ".", "key", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "decoder", ".", "Decode", "(", "&", "i", ".", "required", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "var", "is_default_set", "bool", "\n", "decoder", ".", "Decode", "(", "&", "is_default_set", ")", "\n", "if", "is_default_set", "{", "return", "decoder", ".", "Decode", "(", "&", "i", ".", "default_", ")", "\n", "}", "\n", "var", "is_minimum_set", "bool", "\n", "decoder", ".", "Decode", "(", "&", "is_minimum_set", ")", "\n", "if", "is_minimum_set", "{", "if", "err", ":=", "decoder", ".", "Decode", "(", "&", "i", ".", "minimum", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "var", "is_maximum_set", "bool", "\n", "decoder", ".", "Decode", "(", "&", "is_maximum_set", ")", "\n", "if", "is_maximum_set", "{", "if", "err", ":=", "decoder", ".", "Decode", "(", "&", "i", ".", "maximum", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// GobDecode decodes a GOB into a IntRule
[ "GobDecode", "decodes", "a", "GOB", "into", "a", "IntRule" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/plugin/cpolicy/integer.go#L126-L155
15,322
intelsdi-x/snap
control/plugin/cpolicy/integer.go
Default
func (i *IntRule) Default() ctypes.ConfigValue { if i.default_ != nil { return ctypes.ConfigValueInt{Value: *i.default_} } return nil }
go
func (i *IntRule) Default() ctypes.ConfigValue { if i.default_ != nil { return ctypes.ConfigValueInt{Value: *i.default_} } return nil }
[ "func", "(", "i", "*", "IntRule", ")", "Default", "(", ")", "ctypes", ".", "ConfigValue", "{", "if", "i", ".", "default_", "!=", "nil", "{", "return", "ctypes", ".", "ConfigValueInt", "{", "Value", ":", "*", "i", ".", "default_", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Default return this rules default value
[ "Default", "return", "this", "rules", "default", "value" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/plugin/cpolicy/integer.go#L183-L188
15,323
intelsdi-x/snap
snapteld.go
readConfig
func readConfig(cfg *Config, fpath string) { var path string if !defaultConfigFile() && fpath == "" { return } if defaultConfigFile() && fpath == "" { path = defaultConfigPath } if fpath != "" { f, err := os.Stat(fpath) if err != nil { log.Fatal(err) } if f.IsDir() { log.Fatal("configuration path provided must be a file") } path = fpath } serrs := cfgfile.Read(path, &cfg, CONFIG_CONSTRAINTS) if serrs != nil { for _, serr := range serrs { log.WithFields(serr.Fields()).Error(serr.Error()) } log.Fatal("Errors found while parsing global configuration file") } }
go
func readConfig(cfg *Config, fpath string) { var path string if !defaultConfigFile() && fpath == "" { return } if defaultConfigFile() && fpath == "" { path = defaultConfigPath } if fpath != "" { f, err := os.Stat(fpath) if err != nil { log.Fatal(err) } if f.IsDir() { log.Fatal("configuration path provided must be a file") } path = fpath } serrs := cfgfile.Read(path, &cfg, CONFIG_CONSTRAINTS) if serrs != nil { for _, serr := range serrs { log.WithFields(serr.Fields()).Error(serr.Error()) } log.Fatal("Errors found while parsing global configuration file") } }
[ "func", "readConfig", "(", "cfg", "*", "Config", ",", "fpath", "string", ")", "{", "var", "path", "string", "\n", "if", "!", "defaultConfigFile", "(", ")", "&&", "fpath", "==", "\"", "\"", "{", "return", "\n", "}", "\n", "if", "defaultConfigFile", "(", ")", "&&", "fpath", "==", "\"", "\"", "{", "path", "=", "defaultConfigPath", "\n", "}", "\n", "if", "fpath", "!=", "\"", "\"", "{", "f", ",", "err", ":=", "os", ".", "Stat", "(", "fpath", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatal", "(", "err", ")", "\n", "}", "\n", "if", "f", ".", "IsDir", "(", ")", "{", "log", ".", "Fatal", "(", "\"", "\"", ")", "\n", "}", "\n", "path", "=", "fpath", "\n", "}", "\n\n", "serrs", ":=", "cfgfile", ".", "Read", "(", "path", ",", "&", "cfg", ",", "CONFIG_CONSTRAINTS", ")", "\n", "if", "serrs", "!=", "nil", "{", "for", "_", ",", "serr", ":=", "range", "serrs", "{", "log", ".", "WithFields", "(", "serr", ".", "Fields", "(", ")", ")", ".", "Error", "(", "serr", ".", "Error", "(", ")", ")", "\n", "}", "\n", "log", ".", "Fatal", "(", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// Read the snapteld configuration from a configuration file
[ "Read", "the", "snapteld", "configuration", "from", "a", "configuration", "file" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/snapteld.go#L565-L591
15,324
intelsdi-x/snap
snapteld.go
setBoolVal
func setBoolVal(field bool, ctx runtimeFlagsContext, flagName string, inverse ...bool) bool { // check to see if a value was set (either on the command-line or via the associated // environment variable, if any); if so, use that as value for the input field val := ctx.Bool(flagName) if ctx.IsSet(flagName) || val { field = val if len(inverse) > 0 { field = !field } } return field }
go
func setBoolVal(field bool, ctx runtimeFlagsContext, flagName string, inverse ...bool) bool { // check to see if a value was set (either on the command-line or via the associated // environment variable, if any); if so, use that as value for the input field val := ctx.Bool(flagName) if ctx.IsSet(flagName) || val { field = val if len(inverse) > 0 { field = !field } } return field }
[ "func", "setBoolVal", "(", "field", "bool", ",", "ctx", "runtimeFlagsContext", ",", "flagName", "string", ",", "inverse", "...", "bool", ")", "bool", "{", "// check to see if a value was set (either on the command-line or via the associated", "// environment variable, if any); if so, use that as value for the input field", "val", ":=", "ctx", ".", "Bool", "(", "flagName", ")", "\n", "if", "ctx", ".", "IsSet", "(", "flagName", ")", "||", "val", "{", "field", "=", "val", "\n", "if", "len", "(", "inverse", ")", ">", "0", "{", "field", "=", "!", "field", "\n", "}", "\n", "}", "\n", "return", "field", "\n", "}" ]
// used to set fields in the configuration to values from the // command line context if the corresponding flagName is set // in that context
[ "used", "to", "set", "fields", "in", "the", "configuration", "to", "values", "from", "the", "command", "line", "context", "if", "the", "corresponding", "flagName", "is", "set", "in", "that", "context" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/snapteld.go#L604-L615
15,325
intelsdi-x/snap
snapteld.go
checkCmdLineFlags
func checkCmdLineFlags(ctx runtimeFlagsContext) (int, bool, error) { tlsCert := ctx.String("tls-cert") tlsKey := ctx.String("tls-key") if _, err := checkTLSEnabled(tlsCert, tlsKey, commandLineErrorPrefix); err != nil { return -1, false, err } // Check to see if the API address is specified (either via the CLI or through // the associated environment variable); if so, grab the port and check that the // address and port against the constraints (above) addr := ctx.String("api-addr") port := ctx.Int("api-port") if ctx.IsSet("api-addr") || addr != "" { portInAddr, err := checkHostPortVals(addr, &port, commandLineErrorPrefix) if err != nil { return -1, portInAddr, err } return port, portInAddr, nil } return port, false, nil }
go
func checkCmdLineFlags(ctx runtimeFlagsContext) (int, bool, error) { tlsCert := ctx.String("tls-cert") tlsKey := ctx.String("tls-key") if _, err := checkTLSEnabled(tlsCert, tlsKey, commandLineErrorPrefix); err != nil { return -1, false, err } // Check to see if the API address is specified (either via the CLI or through // the associated environment variable); if so, grab the port and check that the // address and port against the constraints (above) addr := ctx.String("api-addr") port := ctx.Int("api-port") if ctx.IsSet("api-addr") || addr != "" { portInAddr, err := checkHostPortVals(addr, &port, commandLineErrorPrefix) if err != nil { return -1, portInAddr, err } return port, portInAddr, nil } return port, false, nil }
[ "func", "checkCmdLineFlags", "(", "ctx", "runtimeFlagsContext", ")", "(", "int", ",", "bool", ",", "error", ")", "{", "tlsCert", ":=", "ctx", ".", "String", "(", "\"", "\"", ")", "\n", "tlsKey", ":=", "ctx", ".", "String", "(", "\"", "\"", ")", "\n", "if", "_", ",", "err", ":=", "checkTLSEnabled", "(", "tlsCert", ",", "tlsKey", ",", "commandLineErrorPrefix", ")", ";", "err", "!=", "nil", "{", "return", "-", "1", ",", "false", ",", "err", "\n", "}", "\n", "// Check to see if the API address is specified (either via the CLI or through", "// the associated environment variable); if so, grab the port and check that the", "// address and port against the constraints (above)", "addr", ":=", "ctx", ".", "String", "(", "\"", "\"", ")", "\n", "port", ":=", "ctx", ".", "Int", "(", "\"", "\"", ")", "\n", "if", "ctx", ".", "IsSet", "(", "\"", "\"", ")", "||", "addr", "!=", "\"", "\"", "{", "portInAddr", ",", "err", ":=", "checkHostPortVals", "(", "addr", ",", "&", "port", ",", "commandLineErrorPrefix", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "portInAddr", ",", "err", "\n", "}", "\n", "return", "port", ",", "portInAddr", ",", "nil", "\n", "}", "\n\n", "return", "port", ",", "false", ",", "nil", "\n", "}" ]
// santiy check of the command-line flags to ensure that values are set // appropriately; returns the port read from the command-line arguments, a flag // indicating whether or not a port was detected in the address read from the // command-line arguments, and an error if one is detected
[ "santiy", "check", "of", "the", "command", "-", "line", "flags", "to", "ensure", "that", "values", "are", "set", "appropriately", ";", "returns", "the", "port", "read", "from", "the", "command", "-", "line", "arguments", "a", "flag", "indicating", "whether", "or", "not", "a", "port", "was", "detected", "in", "the", "address", "read", "from", "the", "command", "-", "line", "arguments", "and", "an", "error", "if", "one", "is", "detected" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/snapteld.go#L769-L789
15,326
intelsdi-x/snap
snapteld.go
checkCfgSettings
func checkCfgSettings(cfg *Config) (int, bool, error) { tlsCert := cfg.Control.TLSCertPath tlsKey := cfg.Control.TLSKeyPath if _, err := checkTLSEnabled(tlsCert, tlsKey, configFileErrorPrefix); err != nil { return -1, false, err } addr := cfg.RestAPI.Address var port int if cfg.RestAPI.PortSetByConfigFile() { port = cfg.RestAPI.Port } else { port = -1 } portInAddr, err := checkHostPortVals(addr, &port, configFileErrorPrefix) if err != nil { return -1, portInAddr, err } return port, portInAddr, nil }
go
func checkCfgSettings(cfg *Config) (int, bool, error) { tlsCert := cfg.Control.TLSCertPath tlsKey := cfg.Control.TLSKeyPath if _, err := checkTLSEnabled(tlsCert, tlsKey, configFileErrorPrefix); err != nil { return -1, false, err } addr := cfg.RestAPI.Address var port int if cfg.RestAPI.PortSetByConfigFile() { port = cfg.RestAPI.Port } else { port = -1 } portInAddr, err := checkHostPortVals(addr, &port, configFileErrorPrefix) if err != nil { return -1, portInAddr, err } return port, portInAddr, nil }
[ "func", "checkCfgSettings", "(", "cfg", "*", "Config", ")", "(", "int", ",", "bool", ",", "error", ")", "{", "tlsCert", ":=", "cfg", ".", "Control", ".", "TLSCertPath", "\n", "tlsKey", ":=", "cfg", ".", "Control", ".", "TLSKeyPath", "\n", "if", "_", ",", "err", ":=", "checkTLSEnabled", "(", "tlsCert", ",", "tlsKey", ",", "configFileErrorPrefix", ")", ";", "err", "!=", "nil", "{", "return", "-", "1", ",", "false", ",", "err", "\n", "}", "\n", "addr", ":=", "cfg", ".", "RestAPI", ".", "Address", "\n", "var", "port", "int", "\n", "if", "cfg", ".", "RestAPI", ".", "PortSetByConfigFile", "(", ")", "{", "port", "=", "cfg", ".", "RestAPI", ".", "Port", "\n", "}", "else", "{", "port", "=", "-", "1", "\n", "}", "\n", "portInAddr", ",", "err", ":=", "checkHostPortVals", "(", "addr", ",", "&", "port", ",", "configFileErrorPrefix", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "portInAddr", ",", "err", "\n", "}", "\n", "return", "port", ",", "portInAddr", ",", "nil", "\n", "}" ]
// santiy check of the configuration file parameters to ensure that values are set // appropriately; returns the port read from the global configuration file, a flag // indicating whether or not a port was detected in the address read from the // global configuration file, and an error if one is detected
[ "santiy", "check", "of", "the", "configuration", "file", "parameters", "to", "ensure", "that", "values", "are", "set", "appropriately", ";", "returns", "the", "port", "read", "from", "the", "global", "configuration", "file", "a", "flag", "indicating", "whether", "or", "not", "a", "port", "was", "detected", "in", "the", "address", "read", "from", "the", "global", "configuration", "file", "and", "an", "error", "if", "one", "is", "detected" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/snapteld.go#L795-L813
15,327
intelsdi-x/snap
snapteld.go
setMaxProcs
func setMaxProcs(maxProcs int) { var _maxProcs int numProcs := runtime.NumCPU() if maxProcs <= 0 { // We prefer sane values for GOMAXPROCS log.WithFields( log.Fields{ "_block": "main", "_module": logModule, "maxprocs": maxProcs, }).Error("Trying to set GOMAXPROCS to an invalid value") _maxProcs = 1 log.WithFields( log.Fields{ "_block": "main", "_module": logModule, "maxprocs": _maxProcs, }).Warning("Setting GOMAXPROCS to 1") _maxProcs = 1 } else if maxProcs <= numProcs { _maxProcs = maxProcs } else { log.WithFields( log.Fields{ "_block": "main", "_module": logModule, "maxprocs": maxProcs, }).Error("Trying to set GOMAXPROCS larger than number of CPUs available on system") _maxProcs = numProcs log.WithFields( log.Fields{ "_block": "main", "_module": logModule, "maxprocs": _maxProcs, }).Warning("Setting GOMAXPROCS to number of CPUs on host") } log.Info("setting GOMAXPROCS to: ", _maxProcs, " core(s)") runtime.GOMAXPROCS(_maxProcs) //Verify setting worked actualNumProcs := runtime.GOMAXPROCS(0) if actualNumProcs != _maxProcs { log.WithFields( log.Fields{ "block": "main", "_module": logModule, "given maxprocs": _maxProcs, "real maxprocs": actualNumProcs, }).Warning("not using given maxprocs") } }
go
func setMaxProcs(maxProcs int) { var _maxProcs int numProcs := runtime.NumCPU() if maxProcs <= 0 { // We prefer sane values for GOMAXPROCS log.WithFields( log.Fields{ "_block": "main", "_module": logModule, "maxprocs": maxProcs, }).Error("Trying to set GOMAXPROCS to an invalid value") _maxProcs = 1 log.WithFields( log.Fields{ "_block": "main", "_module": logModule, "maxprocs": _maxProcs, }).Warning("Setting GOMAXPROCS to 1") _maxProcs = 1 } else if maxProcs <= numProcs { _maxProcs = maxProcs } else { log.WithFields( log.Fields{ "_block": "main", "_module": logModule, "maxprocs": maxProcs, }).Error("Trying to set GOMAXPROCS larger than number of CPUs available on system") _maxProcs = numProcs log.WithFields( log.Fields{ "_block": "main", "_module": logModule, "maxprocs": _maxProcs, }).Warning("Setting GOMAXPROCS to number of CPUs on host") } log.Info("setting GOMAXPROCS to: ", _maxProcs, " core(s)") runtime.GOMAXPROCS(_maxProcs) //Verify setting worked actualNumProcs := runtime.GOMAXPROCS(0) if actualNumProcs != _maxProcs { log.WithFields( log.Fields{ "block": "main", "_module": logModule, "given maxprocs": _maxProcs, "real maxprocs": actualNumProcs, }).Warning("not using given maxprocs") } }
[ "func", "setMaxProcs", "(", "maxProcs", "int", ")", "{", "var", "_maxProcs", "int", "\n", "numProcs", ":=", "runtime", ".", "NumCPU", "(", ")", "\n", "if", "maxProcs", "<=", "0", "{", "// We prefer sane values for GOMAXPROCS", "log", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "logModule", ",", "\"", "\"", ":", "maxProcs", ",", "}", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "_maxProcs", "=", "1", "\n", "log", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "logModule", ",", "\"", "\"", ":", "_maxProcs", ",", "}", ")", ".", "Warning", "(", "\"", "\"", ")", "\n", "_maxProcs", "=", "1", "\n", "}", "else", "if", "maxProcs", "<=", "numProcs", "{", "_maxProcs", "=", "maxProcs", "\n", "}", "else", "{", "log", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "logModule", ",", "\"", "\"", ":", "maxProcs", ",", "}", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "_maxProcs", "=", "numProcs", "\n", "log", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "logModule", ",", "\"", "\"", ":", "_maxProcs", ",", "}", ")", ".", "Warning", "(", "\"", "\"", ")", "\n", "}", "\n\n", "log", ".", "Info", "(", "\"", "\"", ",", "_maxProcs", ",", "\"", "\"", ")", "\n", "runtime", ".", "GOMAXPROCS", "(", "_maxProcs", ")", "\n", "//Verify setting worked", "actualNumProcs", ":=", "runtime", ".", "GOMAXPROCS", "(", "0", ")", "\n", "if", "actualNumProcs", "!=", "_maxProcs", "{", "log", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "logModule", ",", "\"", "\"", ":", "_maxProcs", ",", "\"", "\"", ":", "actualNumProcs", ",", "}", ")", ".", "Warning", "(", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// setMaxProcs configures runtime.GOMAXPROCS for snapteld. GOMAXPROCS can be set by using // the env variable GOMAXPROCS and snapteld will honor this setting. A user can override the env // variable by setting max-procs flag on the command line. snapteld will be limited to the max CPUs // on the system even if the env variable or the command line setting is set above the max CPUs. // The default value if the env variable or the command line option is not set is 1.
[ "setMaxProcs", "configures", "runtime", ".", "GOMAXPROCS", "for", "snapteld", ".", "GOMAXPROCS", "can", "be", "set", "by", "using", "the", "env", "variable", "GOMAXPROCS", "and", "snapteld", "will", "honor", "this", "setting", ".", "A", "user", "can", "override", "the", "env", "variable", "by", "setting", "max", "-", "procs", "flag", "on", "the", "command", "line", ".", "snapteld", "will", "be", "limited", "to", "the", "max", "CPUs", "on", "the", "system", "even", "if", "the", "env", "variable", "or", "the", "command", "line", "setting", "is", "set", "above", "the", "max", "CPUs", ".", "The", "default", "value", "if", "the", "env", "variable", "or", "the", "command", "line", "option", "is", "not", "set", "is", "1", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/snapteld.go#L921-L971
15,328
intelsdi-x/snap
core/serror/serror.go
New
func New(e error, fields ...map[string]interface{}) *snapError { // Catch someone trying to wrap a serror around a serror. // We throw a panic to make them fix this. if _, ok := e.(SnapError); ok { panic("You are trying to wrap a snapError around a snapError. Don't do this.") } p := &snapError{ err: e, fields: make(map[string]interface{}), } // insert fields into new snapError for _, f := range fields { for k, v := range f { p.fields[k] = v } } return p }
go
func New(e error, fields ...map[string]interface{}) *snapError { // Catch someone trying to wrap a serror around a serror. // We throw a panic to make them fix this. if _, ok := e.(SnapError); ok { panic("You are trying to wrap a snapError around a snapError. Don't do this.") } p := &snapError{ err: e, fields: make(map[string]interface{}), } // insert fields into new snapError for _, f := range fields { for k, v := range f { p.fields[k] = v } } return p }
[ "func", "New", "(", "e", "error", ",", "fields", "...", "map", "[", "string", "]", "interface", "{", "}", ")", "*", "snapError", "{", "// Catch someone trying to wrap a serror around a serror.", "// We throw a panic to make them fix this.", "if", "_", ",", "ok", ":=", "e", ".", "(", "SnapError", ")", ";", "ok", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "p", ":=", "&", "snapError", "{", "err", ":", "e", ",", "fields", ":", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", ",", "}", "\n\n", "// insert fields into new snapError", "for", "_", ",", "f", ":=", "range", "fields", "{", "for", "k", ",", "v", ":=", "range", "f", "{", "p", ".", "fields", "[", "k", "]", "=", "v", "\n", "}", "\n", "}", "\n\n", "return", "p", "\n", "}" ]
// New returns an initialized SnapError. // The variadic signature allows fields to optionally // be added at construction.
[ "New", "returns", "an", "initialized", "SnapError", ".", "The", "variadic", "signature", "allows", "fields", "to", "optionally", "be", "added", "at", "construction", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/core/serror/serror.go#L38-L58
15,329
intelsdi-x/snap
control/monitor.go
MonitorDurationOption
func MonitorDurationOption(v time.Duration) monitorOption { return func(m *monitor) monitorOption { previous := m.duration m.duration = v return MonitorDurationOption(previous) } }
go
func MonitorDurationOption(v time.Duration) monitorOption { return func(m *monitor) monitorOption { previous := m.duration m.duration = v return MonitorDurationOption(previous) } }
[ "func", "MonitorDurationOption", "(", "v", "time", ".", "Duration", ")", "monitorOption", "{", "return", "func", "(", "m", "*", "monitor", ")", "monitorOption", "{", "previous", ":=", "m", ".", "duration", "\n", "m", ".", "duration", "=", "v", "\n", "return", "MonitorDurationOption", "(", "previous", ")", "\n", "}", "\n", "}" ]
// MonitorDurationOption sets monitor's duration to v.
[ "MonitorDurationOption", "sets", "monitor", "s", "duration", "to", "v", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/monitor.go#L56-L62
15,330
intelsdi-x/snap
control/monitor.go
Start
func (m *monitor) Start(availablePlugins *availablePlugins) { //start a routine that will be fired every X duration looping //over available plugins and firing a health check routine ticker := time.NewTicker(m.duration) m.quit = make(chan struct{}) go func() { for { select { case <-ticker.C: go func() { availablePlugins.RLock() for _, ap := range availablePlugins.all() { if !ap.IsRemote() { go ap.CheckHealth() } } availablePlugins.RUnlock() }() case <-m.quit: ticker.Stop() m.State = MonitorStopped return } } }() m.State = MonitorStarted }
go
func (m *monitor) Start(availablePlugins *availablePlugins) { //start a routine that will be fired every X duration looping //over available plugins and firing a health check routine ticker := time.NewTicker(m.duration) m.quit = make(chan struct{}) go func() { for { select { case <-ticker.C: go func() { availablePlugins.RLock() for _, ap := range availablePlugins.all() { if !ap.IsRemote() { go ap.CheckHealth() } } availablePlugins.RUnlock() }() case <-m.quit: ticker.Stop() m.State = MonitorStopped return } } }() m.State = MonitorStarted }
[ "func", "(", "m", "*", "monitor", ")", "Start", "(", "availablePlugins", "*", "availablePlugins", ")", "{", "//start a routine that will be fired every X duration looping", "//over available plugins and firing a health check routine", "ticker", ":=", "time", ".", "NewTicker", "(", "m", ".", "duration", ")", "\n", "m", ".", "quit", "=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "go", "func", "(", ")", "{", "for", "{", "select", "{", "case", "<-", "ticker", ".", "C", ":", "go", "func", "(", ")", "{", "availablePlugins", ".", "RLock", "(", ")", "\n", "for", "_", ",", "ap", ":=", "range", "availablePlugins", ".", "all", "(", ")", "{", "if", "!", "ap", ".", "IsRemote", "(", ")", "{", "go", "ap", ".", "CheckHealth", "(", ")", "\n", "}", "\n", "}", "\n", "availablePlugins", ".", "RUnlock", "(", ")", "\n", "}", "(", ")", "\n", "case", "<-", "m", ".", "quit", ":", "ticker", ".", "Stop", "(", ")", "\n", "m", ".", "State", "=", "MonitorStopped", "\n", "return", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n", "m", ".", "State", "=", "MonitorStarted", "\n", "}" ]
// Start starts the monitor
[ "Start", "starts", "the", "monitor" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/monitor.go#L77-L103
15,331
intelsdi-x/snap
plugin/collector/snap-plugin-collector-mock2-grpc/mock/mock.go
GetConfigPolicy
func (f *Mock) GetConfigPolicy() (plugin.ConfigPolicy, error) { p := plugin.NewConfigPolicy() err := p.AddNewStringRule([]string{"intel", "mock", "test%>"}, "name", false, plugin.SetDefaultString("bob")) if err != nil { return *p, err } err = p.AddNewStringRule([]string{"intel", "mock", "/foo=㊽"}, "password", true) return *p, err }
go
func (f *Mock) GetConfigPolicy() (plugin.ConfigPolicy, error) { p := plugin.NewConfigPolicy() err := p.AddNewStringRule([]string{"intel", "mock", "test%>"}, "name", false, plugin.SetDefaultString("bob")) if err != nil { return *p, err } err = p.AddNewStringRule([]string{"intel", "mock", "/foo=㊽"}, "password", true) return *p, err }
[ "func", "(", "f", "*", "Mock", ")", "GetConfigPolicy", "(", ")", "(", "plugin", ".", "ConfigPolicy", ",", "error", ")", "{", "p", ":=", "plugin", ".", "NewConfigPolicy", "(", ")", "\n\n", "err", ":=", "p", ".", "AddNewStringRule", "(", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", "}", ",", "\"", "\"", ",", "false", ",", "plugin", ".", "SetDefaultString", "(", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "*", "p", ",", "err", "\n", "}", "\n\n", "err", "=", "p", ".", "AddNewStringRule", "(", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", ",", " ", "\"", "a", " ", "t", "ue)", "", "\n\n", "return", "*", "p", ",", "err", "\n", "}" ]
// GetConfigPolicy returns a ConfigPolicy for testing
[ "GetConfigPolicy", "returns", "a", "ConfigPolicy", "for", "testing" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/plugin/collector/snap-plugin-collector-mock2-grpc/mock/mock.go#L159-L170
15,332
intelsdi-x/snap
mgmt/rest/client/config.go
GetPluginConfig
func (c *Client) GetPluginConfig(pluginType, name, version string) *GetPluginConfigResult { r := &GetPluginConfigResult{} resp, err := c.do("GET", fmt.Sprintf("/plugins/%s/%s/%s/config", pluginType, url.QueryEscape(name), version), ContentTypeJSON) if err != nil { r.Err = err return r } switch resp.Meta.Type { case rbody.PluginConfigItemType: // Success config := resp.Body.(*rbody.PluginConfigItem) r = &GetPluginConfigResult{config, nil} case rbody.ErrorType: r.Err = resp.Body.(*rbody.Error) default: r.Err = ErrAPIResponseMetaType } return r }
go
func (c *Client) GetPluginConfig(pluginType, name, version string) *GetPluginConfigResult { r := &GetPluginConfigResult{} resp, err := c.do("GET", fmt.Sprintf("/plugins/%s/%s/%s/config", pluginType, url.QueryEscape(name), version), ContentTypeJSON) if err != nil { r.Err = err return r } switch resp.Meta.Type { case rbody.PluginConfigItemType: // Success config := resp.Body.(*rbody.PluginConfigItem) r = &GetPluginConfigResult{config, nil} case rbody.ErrorType: r.Err = resp.Body.(*rbody.Error) default: r.Err = ErrAPIResponseMetaType } return r }
[ "func", "(", "c", "*", "Client", ")", "GetPluginConfig", "(", "pluginType", ",", "name", ",", "version", "string", ")", "*", "GetPluginConfigResult", "{", "r", ":=", "&", "GetPluginConfigResult", "{", "}", "\n", "resp", ",", "err", ":=", "c", ".", "do", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "pluginType", ",", "url", ".", "QueryEscape", "(", "name", ")", ",", "version", ")", ",", "ContentTypeJSON", ")", "\n", "if", "err", "!=", "nil", "{", "r", ".", "Err", "=", "err", "\n", "return", "r", "\n", "}", "\n\n", "switch", "resp", ".", "Meta", ".", "Type", "{", "case", "rbody", ".", "PluginConfigItemType", ":", "// Success", "config", ":=", "resp", ".", "Body", ".", "(", "*", "rbody", ".", "PluginConfigItem", ")", "\n", "r", "=", "&", "GetPluginConfigResult", "{", "config", ",", "nil", "}", "\n", "case", "rbody", ".", "ErrorType", ":", "r", ".", "Err", "=", "resp", ".", "Body", ".", "(", "*", "rbody", ".", "Error", ")", "\n", "default", ":", "r", ".", "Err", "=", "ErrAPIResponseMetaType", "\n", "}", "\n", "return", "r", "\n", "}" ]
// GetPluginConfig retrieves the merged plugin config given the type of plugin, // name and version. If plugin type, name and version are all empty strings // the plugin config for "all" plugins will be returned. If the plugin type is // provided and the name and version are empty strings the config for that plugin // type will be returned. So on and so forth for the rest of the arguments.
[ "GetPluginConfig", "retrieves", "the", "merged", "plugin", "config", "given", "the", "type", "of", "plugin", "name", "and", "version", ".", "If", "plugin", "type", "name", "and", "version", "are", "all", "empty", "strings", "the", "plugin", "config", "for", "all", "plugins", "will", "be", "returned", ".", "If", "the", "plugin", "type", "is", "provided", "and", "the", "name", "and", "version", "are", "empty", "strings", "the", "config", "for", "that", "plugin", "type", "will", "be", "returned", ".", "So", "on", "and", "so", "forth", "for", "the", "rest", "of", "the", "arguments", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/mgmt/rest/client/config.go#L36-L55
15,333
intelsdi-x/snap
mgmt/rest/client/config.go
SetPluginConfig
func (c *Client) SetPluginConfig(pluginType, name, version string, key string, value ctypes.ConfigValue) *SetPluginConfigResult { r := &SetPluginConfigResult{} b, err := json.Marshal(map[string]ctypes.ConfigValue{key: value}) if err != nil { r.Err = err return r } resp, err := c.do("PUT", fmt.Sprintf("/plugins/%s/%s/%s/config", pluginType, url.QueryEscape(name), version), ContentTypeJSON, b) if err != nil { r.Err = err return r } switch resp.Meta.Type { case rbody.SetPluginConfigItemType: // Success config := resp.Body.(*rbody.SetPluginConfigItem) r = &SetPluginConfigResult{config, nil} case rbody.ErrorType: r.Err = resp.Body.(*rbody.Error) default: r.Err = ErrAPIResponseMetaType } return r }
go
func (c *Client) SetPluginConfig(pluginType, name, version string, key string, value ctypes.ConfigValue) *SetPluginConfigResult { r := &SetPluginConfigResult{} b, err := json.Marshal(map[string]ctypes.ConfigValue{key: value}) if err != nil { r.Err = err return r } resp, err := c.do("PUT", fmt.Sprintf("/plugins/%s/%s/%s/config", pluginType, url.QueryEscape(name), version), ContentTypeJSON, b) if err != nil { r.Err = err return r } switch resp.Meta.Type { case rbody.SetPluginConfigItemType: // Success config := resp.Body.(*rbody.SetPluginConfigItem) r = &SetPluginConfigResult{config, nil} case rbody.ErrorType: r.Err = resp.Body.(*rbody.Error) default: r.Err = ErrAPIResponseMetaType } return r }
[ "func", "(", "c", "*", "Client", ")", "SetPluginConfig", "(", "pluginType", ",", "name", ",", "version", "string", ",", "key", "string", ",", "value", "ctypes", ".", "ConfigValue", ")", "*", "SetPluginConfigResult", "{", "r", ":=", "&", "SetPluginConfigResult", "{", "}", "\n", "b", ",", "err", ":=", "json", ".", "Marshal", "(", "map", "[", "string", "]", "ctypes", ".", "ConfigValue", "{", "key", ":", "value", "}", ")", "\n", "if", "err", "!=", "nil", "{", "r", ".", "Err", "=", "err", "\n", "return", "r", "\n", "}", "\n", "resp", ",", "err", ":=", "c", ".", "do", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "pluginType", ",", "url", ".", "QueryEscape", "(", "name", ")", ",", "version", ")", ",", "ContentTypeJSON", ",", "b", ")", "\n", "if", "err", "!=", "nil", "{", "r", ".", "Err", "=", "err", "\n", "return", "r", "\n", "}", "\n\n", "switch", "resp", ".", "Meta", ".", "Type", "{", "case", "rbody", ".", "SetPluginConfigItemType", ":", "// Success", "config", ":=", "resp", ".", "Body", ".", "(", "*", "rbody", ".", "SetPluginConfigItem", ")", "\n", "r", "=", "&", "SetPluginConfigResult", "{", "config", ",", "nil", "}", "\n", "case", "rbody", ".", "ErrorType", ":", "r", ".", "Err", "=", "resp", ".", "Body", ".", "(", "*", "rbody", ".", "Error", ")", "\n", "default", ":", "r", ".", "Err", "=", "ErrAPIResponseMetaType", "\n", "}", "\n", "return", "r", "\n", "}" ]
// SetPluginConfig sets the plugin config given the type, name and version // of a plugin. Like GetPluginConfig if the type, name and version are all // empty strings the plugin config is set for all plugins. When config data // is set it is merged with the existing data if present.
[ "SetPluginConfig", "sets", "the", "plugin", "config", "given", "the", "type", "name", "and", "version", "of", "a", "plugin", ".", "Like", "GetPluginConfig", "if", "the", "type", "name", "and", "version", "are", "all", "empty", "strings", "the", "plugin", "config", "is", "set", "for", "all", "plugins", ".", "When", "config", "data", "is", "set", "it", "is", "merged", "with", "the", "existing", "data", "if", "present", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/mgmt/rest/client/config.go#L61-L85
15,334
intelsdi-x/snap
mgmt/rest/client/config.go
DeletePluginConfig
func (c *Client) DeletePluginConfig(pluginType, name, version string, key string) *DeletePluginConfigResult { r := &DeletePluginConfigResult{} b, err := json.Marshal([]string{key}) if err != nil { r.Err = err return r } resp, err := c.do("DELETE", fmt.Sprintf("/plugins/%s/%s/%s/config", pluginType, url.QueryEscape(name), version), ContentTypeJSON, b) if err != nil { r.Err = err return r } switch resp.Meta.Type { case rbody.DeletePluginConfigItemType: // Success config := resp.Body.(*rbody.DeletePluginConfigItem) r = &DeletePluginConfigResult{config, nil} case rbody.ErrorType: r.Err = resp.Body.(*rbody.Error) default: r.Err = ErrAPIResponseMetaType } return r }
go
func (c *Client) DeletePluginConfig(pluginType, name, version string, key string) *DeletePluginConfigResult { r := &DeletePluginConfigResult{} b, err := json.Marshal([]string{key}) if err != nil { r.Err = err return r } resp, err := c.do("DELETE", fmt.Sprintf("/plugins/%s/%s/%s/config", pluginType, url.QueryEscape(name), version), ContentTypeJSON, b) if err != nil { r.Err = err return r } switch resp.Meta.Type { case rbody.DeletePluginConfigItemType: // Success config := resp.Body.(*rbody.DeletePluginConfigItem) r = &DeletePluginConfigResult{config, nil} case rbody.ErrorType: r.Err = resp.Body.(*rbody.Error) default: r.Err = ErrAPIResponseMetaType } return r }
[ "func", "(", "c", "*", "Client", ")", "DeletePluginConfig", "(", "pluginType", ",", "name", ",", "version", "string", ",", "key", "string", ")", "*", "DeletePluginConfigResult", "{", "r", ":=", "&", "DeletePluginConfigResult", "{", "}", "\n", "b", ",", "err", ":=", "json", ".", "Marshal", "(", "[", "]", "string", "{", "key", "}", ")", "\n", "if", "err", "!=", "nil", "{", "r", ".", "Err", "=", "err", "\n", "return", "r", "\n", "}", "\n", "resp", ",", "err", ":=", "c", ".", "do", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "pluginType", ",", "url", ".", "QueryEscape", "(", "name", ")", ",", "version", ")", ",", "ContentTypeJSON", ",", "b", ")", "\n", "if", "err", "!=", "nil", "{", "r", ".", "Err", "=", "err", "\n", "return", "r", "\n", "}", "\n\n", "switch", "resp", ".", "Meta", ".", "Type", "{", "case", "rbody", ".", "DeletePluginConfigItemType", ":", "// Success", "config", ":=", "resp", ".", "Body", ".", "(", "*", "rbody", ".", "DeletePluginConfigItem", ")", "\n", "r", "=", "&", "DeletePluginConfigResult", "{", "config", ",", "nil", "}", "\n", "case", "rbody", ".", "ErrorType", ":", "r", ".", "Err", "=", "resp", ".", "Body", ".", "(", "*", "rbody", ".", "Error", ")", "\n", "default", ":", "r", ".", "Err", "=", "ErrAPIResponseMetaType", "\n", "}", "\n", "return", "r", "\n", "}" ]
// DeletePluginConfig removes the plugin config item given the plugin type, name // and version.
[ "DeletePluginConfig", "removes", "the", "plugin", "config", "item", "given", "the", "plugin", "type", "name", "and", "version", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/mgmt/rest/client/config.go#L89-L113
15,335
intelsdi-x/snap
control/metrics.go
init
func init() { host, err := os.Hostname() if err != nil { log.WithFields(log.Fields{ "_module": "control", "_file": "metrics.go,", "_block": "addStandardAndWorkflowTags", "error": err.Error(), }).Error("Unable to determine hostname") host = "not_found" } hostnameReader = &hostnameReaderType{hostname: host, hostnameRefreshTTL: time.Hour, lastRefresh: time.Now()} }
go
func init() { host, err := os.Hostname() if err != nil { log.WithFields(log.Fields{ "_module": "control", "_file": "metrics.go,", "_block": "addStandardAndWorkflowTags", "error": err.Error(), }).Error("Unable to determine hostname") host = "not_found" } hostnameReader = &hostnameReaderType{hostname: host, hostnameRefreshTTL: time.Hour, lastRefresh: time.Now()} }
[ "func", "init", "(", ")", "{", "host", ",", "err", ":=", "os", ".", "Hostname", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "err", ".", "Error", "(", ")", ",", "}", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "host", "=", "\"", "\"", "\n", "}", "\n", "hostnameReader", "=", "&", "hostnameReaderType", "{", "hostname", ":", "host", ",", "hostnameRefreshTTL", ":", "time", ".", "Hour", ",", "lastRefresh", ":", "time", ".", "Now", "(", ")", "}", "\n", "}" ]
// hostnameReader, hostnamer created for mocking
[ "hostnameReader", "hostnamer", "created", "for", "mocking" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/metrics.go#L47-L59
15,336
intelsdi-x/snap
control/metrics.go
RmUnloadedPluginMetrics
func (mc *metricCatalog) RmUnloadedPluginMetrics(lp *loadedPlugin) { mc.mutex.Lock() defer mc.mutex.Unlock() mc.tree.DeleteByPlugin(lp) // Update metric catalog keys mc.keys = []string{} mts := mc.tree.gatherMetricTypes() for _, m := range mts { mc.keys = append(mc.keys, m.Namespace().String()) } }
go
func (mc *metricCatalog) RmUnloadedPluginMetrics(lp *loadedPlugin) { mc.mutex.Lock() defer mc.mutex.Unlock() mc.tree.DeleteByPlugin(lp) // Update metric catalog keys mc.keys = []string{} mts := mc.tree.gatherMetricTypes() for _, m := range mts { mc.keys = append(mc.keys, m.Namespace().String()) } }
[ "func", "(", "mc", "*", "metricCatalog", ")", "RmUnloadedPluginMetrics", "(", "lp", "*", "loadedPlugin", ")", "{", "mc", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "mc", ".", "mutex", ".", "Unlock", "(", ")", "\n", "mc", ".", "tree", ".", "DeleteByPlugin", "(", "lp", ")", "\n\n", "// Update metric catalog keys", "mc", ".", "keys", "=", "[", "]", "string", "{", "}", "\n", "mts", ":=", "mc", ".", "tree", ".", "gatherMetricTypes", "(", ")", "\n", "for", "_", ",", "m", ":=", "range", "mts", "{", "mc", ".", "keys", "=", "append", "(", "mc", ".", "keys", ",", "m", ".", "Namespace", "(", ")", ".", "String", "(", ")", ")", "\n", "}", "\n", "}" ]
// RmUnloadedPluginMetrics removes plugin metrics which was unloaded, // consequently cataloged metrics are changed, so matching map is being updated too
[ "RmUnloadedPluginMetrics", "removes", "plugin", "metrics", "which", "was", "unloaded", "consequently", "cataloged", "metrics", "are", "changed", "so", "matching", "map", "is", "being", "updated", "too" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/metrics.go#L400-L411
15,337
intelsdi-x/snap
control/metrics.go
Add
func (mc *metricCatalog) Add(m *metricType) { mc.mutex.Lock() defer mc.mutex.Unlock() key := m.Namespace().String() // adding key as a cataloged keys (mc.keys) mc.keys = appendIfMissing(mc.keys, key) mc.tree.Add(m) }
go
func (mc *metricCatalog) Add(m *metricType) { mc.mutex.Lock() defer mc.mutex.Unlock() key := m.Namespace().String() // adding key as a cataloged keys (mc.keys) mc.keys = appendIfMissing(mc.keys, key) mc.tree.Add(m) }
[ "func", "(", "mc", "*", "metricCatalog", ")", "Add", "(", "m", "*", "metricType", ")", "{", "mc", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "mc", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "key", ":=", "m", ".", "Namespace", "(", ")", ".", "String", "(", ")", "\n\n", "// adding key as a cataloged keys (mc.keys)", "mc", ".", "keys", "=", "appendIfMissing", "(", "mc", ".", "keys", ",", "key", ")", "\n", "mc", ".", "tree", ".", "Add", "(", "m", ")", "\n", "}" ]
// Add adds a metricType
[ "Add", "adds", "a", "metricType" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/metrics.go#L414-L423
15,338
intelsdi-x/snap
control/metrics.go
GetMetric
func (mc *metricCatalog) GetMetric(requested core.Namespace, version int) (*metricType, error) { mc.mutex.Lock() defer mc.mutex.Unlock() var ns core.Namespace catalogedmt, err := mc.tree.GetMetric(requested.Strings(), version) if err != nil { log.WithFields(log.Fields{ "_module": "control", "_file": "metrics.go,", "_block": "get-metric", "error": err, }).Error("error getting metric") return nil, err } ns = catalogedmt.Namespace() if isDynamic, _ := ns.IsDynamic(); isDynamic { // when namespace is dynamic and the cataloged namespace (e.g. ns=/intel/mock/*/bar) is different than // the requested (e.g. requested=/intel/mock/host0/bar), than specify an instance of dynamic element, // so as a result the dynamic element will have set a value (e.g. ns[2].Value equals "host0") if ns.String() != requested.String() { ns = specifyInstanceOfDynamicMetric(ns, requested) } } returnedmt := &metricType{ Plugin: catalogedmt.Plugin, namespace: ns, version: catalogedmt.Version(), lastAdvertisedTime: catalogedmt.LastAdvertisedTime(), tags: catalogedmt.Tags(), policy: catalogedmt.Plugin.Policy().Get(catalogedmt.Namespace().Strings()), config: catalogedmt.Config(), unit: catalogedmt.Unit(), description: catalogedmt.Description(), subscriptions: catalogedmt.SubscriptionCount(), } return returnedmt, nil }
go
func (mc *metricCatalog) GetMetric(requested core.Namespace, version int) (*metricType, error) { mc.mutex.Lock() defer mc.mutex.Unlock() var ns core.Namespace catalogedmt, err := mc.tree.GetMetric(requested.Strings(), version) if err != nil { log.WithFields(log.Fields{ "_module": "control", "_file": "metrics.go,", "_block": "get-metric", "error": err, }).Error("error getting metric") return nil, err } ns = catalogedmt.Namespace() if isDynamic, _ := ns.IsDynamic(); isDynamic { // when namespace is dynamic and the cataloged namespace (e.g. ns=/intel/mock/*/bar) is different than // the requested (e.g. requested=/intel/mock/host0/bar), than specify an instance of dynamic element, // so as a result the dynamic element will have set a value (e.g. ns[2].Value equals "host0") if ns.String() != requested.String() { ns = specifyInstanceOfDynamicMetric(ns, requested) } } returnedmt := &metricType{ Plugin: catalogedmt.Plugin, namespace: ns, version: catalogedmt.Version(), lastAdvertisedTime: catalogedmt.LastAdvertisedTime(), tags: catalogedmt.Tags(), policy: catalogedmt.Plugin.Policy().Get(catalogedmt.Namespace().Strings()), config: catalogedmt.Config(), unit: catalogedmt.Unit(), description: catalogedmt.Description(), subscriptions: catalogedmt.SubscriptionCount(), } return returnedmt, nil }
[ "func", "(", "mc", "*", "metricCatalog", ")", "GetMetric", "(", "requested", "core", ".", "Namespace", ",", "version", "int", ")", "(", "*", "metricType", ",", "error", ")", "{", "mc", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "mc", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "var", "ns", "core", ".", "Namespace", "\n\n", "catalogedmt", ",", "err", ":=", "mc", ".", "tree", ".", "GetMetric", "(", "requested", ".", "Strings", "(", ")", ",", "version", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "err", ",", "}", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "ns", "=", "catalogedmt", ".", "Namespace", "(", ")", "\n\n", "if", "isDynamic", ",", "_", ":=", "ns", ".", "IsDynamic", "(", ")", ";", "isDynamic", "{", "// when namespace is dynamic and the cataloged namespace (e.g. ns=/intel/mock/*/bar) is different than", "// the requested (e.g. requested=/intel/mock/host0/bar), than specify an instance of dynamic element,", "// so as a result the dynamic element will have set a value (e.g. ns[2].Value equals \"host0\")", "if", "ns", ".", "String", "(", ")", "!=", "requested", ".", "String", "(", ")", "{", "ns", "=", "specifyInstanceOfDynamicMetric", "(", "ns", ",", "requested", ")", "\n", "}", "\n", "}", "\n\n", "returnedmt", ":=", "&", "metricType", "{", "Plugin", ":", "catalogedmt", ".", "Plugin", ",", "namespace", ":", "ns", ",", "version", ":", "catalogedmt", ".", "Version", "(", ")", ",", "lastAdvertisedTime", ":", "catalogedmt", ".", "LastAdvertisedTime", "(", ")", ",", "tags", ":", "catalogedmt", ".", "Tags", "(", ")", ",", "policy", ":", "catalogedmt", ".", "Plugin", ".", "Policy", "(", ")", ".", "Get", "(", "catalogedmt", ".", "Namespace", "(", ")", ".", "Strings", "(", ")", ")", ",", "config", ":", "catalogedmt", ".", "Config", "(", ")", ",", "unit", ":", "catalogedmt", ".", "Unit", "(", ")", ",", "description", ":", "catalogedmt", ".", "Description", "(", ")", ",", "subscriptions", ":", "catalogedmt", ".", "SubscriptionCount", "(", ")", ",", "}", "\n", "return", "returnedmt", ",", "nil", "\n", "}" ]
// GetMetric retrieves a metric for a given requested namespace and version. // If provided a version of -1 the latest plugin will be returned.
[ "GetMetric", "retrieves", "a", "metric", "for", "a", "given", "requested", "namespace", "and", "version", ".", "If", "provided", "a", "version", "of", "-", "1", "the", "latest", "plugin", "will", "be", "returned", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/metrics.go#L427-L468
15,339
intelsdi-x/snap
control/metrics.go
GetVersions
func (mc *metricCatalog) GetVersions(ns core.Namespace) ([]*metricType, error) { mc.mutex.Lock() defer mc.mutex.Unlock() mts, err := mc.tree.GetVersions(ns.Strings()) if err != nil { log.WithFields(log.Fields{ "_module": "control", "_file": "metrics.go,", "_block": "get-versions", "error": err, }).Error("error getting plugin version") return nil, err } return mts, nil }
go
func (mc *metricCatalog) GetVersions(ns core.Namespace) ([]*metricType, error) { mc.mutex.Lock() defer mc.mutex.Unlock() mts, err := mc.tree.GetVersions(ns.Strings()) if err != nil { log.WithFields(log.Fields{ "_module": "control", "_file": "metrics.go,", "_block": "get-versions", "error": err, }).Error("error getting plugin version") return nil, err } return mts, nil }
[ "func", "(", "mc", "*", "metricCatalog", ")", "GetVersions", "(", "ns", "core", ".", "Namespace", ")", "(", "[", "]", "*", "metricType", ",", "error", ")", "{", "mc", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "mc", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "mts", ",", "err", ":=", "mc", ".", "tree", ".", "GetVersions", "(", "ns", ".", "Strings", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "err", ",", "}", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "return", "mts", ",", "nil", "\n", "}" ]
// GetVersions retrieves all versions of a given metric namespace.
[ "GetVersions", "retrieves", "all", "versions", "of", "a", "given", "metric", "namespace", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/metrics.go#L523-L538
15,340
intelsdi-x/snap
control/metrics.go
Remove
func (mc *metricCatalog) Remove(ns core.Namespace) { mc.mutex.Lock() defer mc.mutex.Unlock() mc.tree.Remove(ns.Strings()) }
go
func (mc *metricCatalog) Remove(ns core.Namespace) { mc.mutex.Lock() defer mc.mutex.Unlock() mc.tree.Remove(ns.Strings()) }
[ "func", "(", "mc", "*", "metricCatalog", ")", "Remove", "(", "ns", "core", ".", "Namespace", ")", "{", "mc", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "mc", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "mc", ".", "tree", ".", "Remove", "(", "ns", ".", "Strings", "(", ")", ")", "\n", "}" ]
// Remove removes a metricType from the catalog and from matching map
[ "Remove", "removes", "a", "metricType", "from", "the", "catalog", "and", "from", "matching", "map" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/metrics.go#L559-L564
15,341
intelsdi-x/snap
control/metrics.go
Subscribe
func (mc *metricCatalog) Subscribe(ns []string, version int) error { mc.mutex.Lock() defer mc.mutex.Unlock() m, err := mc.tree.GetMetric(ns, version) if err != nil { log.WithFields(log.Fields{ "_module": "control", "_file": "metrics.go,", "_block": "subscribe", "error": err, }).Error("error getting metric") return err } m.Subscribe() return nil }
go
func (mc *metricCatalog) Subscribe(ns []string, version int) error { mc.mutex.Lock() defer mc.mutex.Unlock() m, err := mc.tree.GetMetric(ns, version) if err != nil { log.WithFields(log.Fields{ "_module": "control", "_file": "metrics.go,", "_block": "subscribe", "error": err, }).Error("error getting metric") return err } m.Subscribe() return nil }
[ "func", "(", "mc", "*", "metricCatalog", ")", "Subscribe", "(", "ns", "[", "]", "string", ",", "version", "int", ")", "error", "{", "mc", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "mc", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "m", ",", "err", ":=", "mc", ".", "tree", ".", "GetMetric", "(", "ns", ",", "version", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "err", ",", "}", ")", ".", "Error", "(", "\"", "\"", ")", "\n", "return", "err", "\n", "}", "\n\n", "m", ".", "Subscribe", "(", ")", "\n", "return", "nil", "\n", "}" ]
// Subscribe atomically increments a metric's subscription count in the table.
[ "Subscribe", "atomically", "increments", "a", "metric", "s", "subscription", "count", "in", "the", "table", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/metrics.go#L567-L584
15,342
intelsdi-x/snap
control/metrics.go
containsTuple
func containsTuple(nsElement string) (bool, []string) { tupleItems := []string{} if isTuple(nsElement) { if strings.ContainsAny(nsElement, "*") { // an asterisk covers all tuples cases (eg. /intel/mock/(host0;host1;*)/baz) // so to avoid retrieving the same metric more than once, return only '*' as a tuple's items tupleItems = []string{"*"} } else { tuple := strings.TrimSuffix(strings.TrimPrefix(nsElement, core.TuplePrefix), core.TupleSuffix) items := strings.Split(tuple, core.TupleSeparator) // removing all leading and trailing white space for _, item := range items { tupleItems = append(tupleItems, strings.TrimSpace(item)) } } return true, tupleItems } return false, nil }
go
func containsTuple(nsElement string) (bool, []string) { tupleItems := []string{} if isTuple(nsElement) { if strings.ContainsAny(nsElement, "*") { // an asterisk covers all tuples cases (eg. /intel/mock/(host0;host1;*)/baz) // so to avoid retrieving the same metric more than once, return only '*' as a tuple's items tupleItems = []string{"*"} } else { tuple := strings.TrimSuffix(strings.TrimPrefix(nsElement, core.TuplePrefix), core.TupleSuffix) items := strings.Split(tuple, core.TupleSeparator) // removing all leading and trailing white space for _, item := range items { tupleItems = append(tupleItems, strings.TrimSpace(item)) } } return true, tupleItems } return false, nil }
[ "func", "containsTuple", "(", "nsElement", "string", ")", "(", "bool", ",", "[", "]", "string", ")", "{", "tupleItems", ":=", "[", "]", "string", "{", "}", "\n", "if", "isTuple", "(", "nsElement", ")", "{", "if", "strings", ".", "ContainsAny", "(", "nsElement", ",", "\"", "\"", ")", "{", "// an asterisk covers all tuples cases (eg. /intel/mock/(host0;host1;*)/baz)", "// so to avoid retrieving the same metric more than once, return only '*' as a tuple's items", "tupleItems", "=", "[", "]", "string", "{", "\"", "\"", "}", "\n", "}", "else", "{", "tuple", ":=", "strings", ".", "TrimSuffix", "(", "strings", ".", "TrimPrefix", "(", "nsElement", ",", "core", ".", "TuplePrefix", ")", ",", "core", ".", "TupleSuffix", ")", "\n", "items", ":=", "strings", ".", "Split", "(", "tuple", ",", "core", ".", "TupleSeparator", ")", "\n", "// removing all leading and trailing white space", "for", "_", ",", "item", ":=", "range", "items", "{", "tupleItems", "=", "append", "(", "tupleItems", ",", "strings", ".", "TrimSpace", "(", "item", ")", ")", "\n", "}", "\n", "}", "\n", "return", "true", ",", "tupleItems", "\n", "}", "\n", "return", "false", ",", "nil", "\n", "}" ]
// containsTuple checks if a given element of namespace has a tuple; if yes, returns true and recognized tuple's items
[ "containsTuple", "checks", "if", "a", "given", "element", "of", "namespace", "has", "a", "tuple", ";", "if", "yes", "returns", "true", "and", "recognized", "tuple", "s", "items" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/metrics.go#L667-L685
15,343
intelsdi-x/snap
control/metrics.go
specifyInstanceOfDynamicMetric
func specifyInstanceOfDynamicMetric(catalogedNamespace core.Namespace, requestedNamespace core.Namespace) core.Namespace { specifiedNamespace := make(core.Namespace, len(catalogedNamespace)) copy(specifiedNamespace, catalogedNamespace) _, indexes := catalogedNamespace.IsDynamic() for _, index := range indexes { if len(requestedNamespace) > index { // use namespace's element of requested metric declared in task manifest // to specify a dynamic instance of the cataloged metric specifiedNamespace[index].Value = requestedNamespace[index].Value } } return specifiedNamespace }
go
func specifyInstanceOfDynamicMetric(catalogedNamespace core.Namespace, requestedNamespace core.Namespace) core.Namespace { specifiedNamespace := make(core.Namespace, len(catalogedNamespace)) copy(specifiedNamespace, catalogedNamespace) _, indexes := catalogedNamespace.IsDynamic() for _, index := range indexes { if len(requestedNamespace) > index { // use namespace's element of requested metric declared in task manifest // to specify a dynamic instance of the cataloged metric specifiedNamespace[index].Value = requestedNamespace[index].Value } } return specifiedNamespace }
[ "func", "specifyInstanceOfDynamicMetric", "(", "catalogedNamespace", "core", ".", "Namespace", ",", "requestedNamespace", "core", ".", "Namespace", ")", "core", ".", "Namespace", "{", "specifiedNamespace", ":=", "make", "(", "core", ".", "Namespace", ",", "len", "(", "catalogedNamespace", ")", ")", "\n", "copy", "(", "specifiedNamespace", ",", "catalogedNamespace", ")", "\n\n", "_", ",", "indexes", ":=", "catalogedNamespace", ".", "IsDynamic", "(", ")", "\n\n", "for", "_", ",", "index", ":=", "range", "indexes", "{", "if", "len", "(", "requestedNamespace", ")", ">", "index", "{", "// use namespace's element of requested metric declared in task manifest", "// to specify a dynamic instance of the cataloged metric", "specifiedNamespace", "[", "index", "]", ".", "Value", "=", "requestedNamespace", "[", "index", "]", ".", "Value", "\n", "}", "\n", "}", "\n", "return", "specifiedNamespace", "\n", "}" ]
// specifyInstanceOfDynamicMetric returns specified namespace of incoming cataloged metric's namespace // based on requested metric namespace
[ "specifyInstanceOfDynamicMetric", "returns", "specified", "namespace", "of", "incoming", "cataloged", "metric", "s", "namespace", "based", "on", "requested", "metric", "namespace" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/metrics.go#L741-L755
15,344
intelsdi-x/snap
control/metrics.go
validateMetricNamespace
func validateMetricNamespace(ns core.Namespace) error { value := "" for _, i := range ns { // A dynamic element requires the name while a static element does not. if i.Name != "" && i.Value != "*" { return errorMetricStaticElementHasName(i.Value, i.Name, ns.String()) } if i.Name == "" && i.Value == "*" { return errorMetricDynamicElementHasNoName(i.Value, ns.String()) } if isTuple(i.Value) { return errorMetricElementHasTuple(i.Value, ns.String()) } value += i.Value } // plugin should NOT advertise metrics ending with a wildcard if strings.HasSuffix(value, "*") { return errorMetricEndsWithAsterisk(ns.String()) } return nil }
go
func validateMetricNamespace(ns core.Namespace) error { value := "" for _, i := range ns { // A dynamic element requires the name while a static element does not. if i.Name != "" && i.Value != "*" { return errorMetricStaticElementHasName(i.Value, i.Name, ns.String()) } if i.Name == "" && i.Value == "*" { return errorMetricDynamicElementHasNoName(i.Value, ns.String()) } if isTuple(i.Value) { return errorMetricElementHasTuple(i.Value, ns.String()) } value += i.Value } // plugin should NOT advertise metrics ending with a wildcard if strings.HasSuffix(value, "*") { return errorMetricEndsWithAsterisk(ns.String()) } return nil }
[ "func", "validateMetricNamespace", "(", "ns", "core", ".", "Namespace", ")", "error", "{", "value", ":=", "\"", "\"", "\n", "for", "_", ",", "i", ":=", "range", "ns", "{", "// A dynamic element requires the name while a static element does not.", "if", "i", ".", "Name", "!=", "\"", "\"", "&&", "i", ".", "Value", "!=", "\"", "\"", "{", "return", "errorMetricStaticElementHasName", "(", "i", ".", "Value", ",", "i", ".", "Name", ",", "ns", ".", "String", "(", ")", ")", "\n", "}", "\n", "if", "i", ".", "Name", "==", "\"", "\"", "&&", "i", ".", "Value", "==", "\"", "\"", "{", "return", "errorMetricDynamicElementHasNoName", "(", "i", ".", "Value", ",", "ns", ".", "String", "(", ")", ")", "\n", "}", "\n", "if", "isTuple", "(", "i", ".", "Value", ")", "{", "return", "errorMetricElementHasTuple", "(", "i", ".", "Value", ",", "ns", ".", "String", "(", ")", ")", "\n", "}", "\n", "value", "+=", "i", ".", "Value", "\n", "}", "\n", "// plugin should NOT advertise metrics ending with a wildcard", "if", "strings", ".", "HasSuffix", "(", "value", ",", "\"", "\"", ")", "{", "return", "errorMetricEndsWithAsterisk", "(", "ns", ".", "String", "(", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// validateMetricNamespace validates metric namespace in terms of containing properly defined dynamic elements, // not ending with an asterisk and not contain elements which might be erroneously recognized as a tuple
[ "validateMetricNamespace", "validates", "metric", "namespace", "in", "terms", "of", "containing", "properly", "defined", "dynamic", "elements", "not", "ending", "with", "an", "asterisk", "and", "not", "contain", "elements", "which", "might", "be", "erroneously", "recognized", "as", "a", "tuple" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/metrics.go#L759-L779
15,345
intelsdi-x/snap
control/plugin/cpolicy/bool.go
MarshalJSON
func (b *BoolRule) MarshalJSON() ([]byte, error) { return json.Marshal(&struct { Key string `json:"key"` Required bool `json:"required"` Default ctypes.ConfigValue `json:"default,omitempty"` Type string `json:"type"` }{ Key: b.key, Required: b.required, Default: b.Default(), Type: BoolType, }) }
go
func (b *BoolRule) MarshalJSON() ([]byte, error) { return json.Marshal(&struct { Key string `json:"key"` Required bool `json:"required"` Default ctypes.ConfigValue `json:"default,omitempty"` Type string `json:"type"` }{ Key: b.key, Required: b.required, Default: b.Default(), Type: BoolType, }) }
[ "func", "(", "b", "*", "BoolRule", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "json", ".", "Marshal", "(", "&", "struct", "{", "Key", "string", "`json:\"key\"`", "\n", "Required", "bool", "`json:\"required\"`", "\n", "Default", "ctypes", ".", "ConfigValue", "`json:\"default,omitempty\"`", "\n", "Type", "string", "`json:\"type\"`", "\n", "}", "{", "Key", ":", "b", ".", "key", ",", "Required", ":", "b", ".", "required", ",", "Default", ":", "b", ".", "Default", "(", ")", ",", "Type", ":", "BoolType", ",", "}", ")", "\n", "}" ]
// MarshalJSON marshals a BoolRule into JSON
[ "MarshalJSON", "marshals", "a", "BoolRule", "into", "JSON" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/plugin/cpolicy/bool.go#L66-L78
15,346
intelsdi-x/snap
control/plugin/cpolicy/bool.go
GobEncode
func (b *BoolRule) GobEncode() ([]byte, error) { w := new(bytes.Buffer) encoder := gob.NewEncoder(w) if err := encoder.Encode(b.key); err != nil { return nil, err } if err := encoder.Encode(b.required); err != nil { return nil, err } if b.default_ == nil { encoder.Encode(false) } else { encoder.Encode(true) if err := encoder.Encode(&b.default_); err != nil { return nil, err } } return w.Bytes(), nil }
go
func (b *BoolRule) GobEncode() ([]byte, error) { w := new(bytes.Buffer) encoder := gob.NewEncoder(w) if err := encoder.Encode(b.key); err != nil { return nil, err } if err := encoder.Encode(b.required); err != nil { return nil, err } if b.default_ == nil { encoder.Encode(false) } else { encoder.Encode(true) if err := encoder.Encode(&b.default_); err != nil { return nil, err } } return w.Bytes(), nil }
[ "func", "(", "b", "*", "BoolRule", ")", "GobEncode", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "w", ":=", "new", "(", "bytes", ".", "Buffer", ")", "\n", "encoder", ":=", "gob", ".", "NewEncoder", "(", "w", ")", "\n", "if", "err", ":=", "encoder", ".", "Encode", "(", "b", ".", "key", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "err", ":=", "encoder", ".", "Encode", "(", "b", ".", "required", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "b", ".", "default_", "==", "nil", "{", "encoder", ".", "Encode", "(", "false", ")", "\n", "}", "else", "{", "encoder", ".", "Encode", "(", "true", ")", "\n", "if", "err", ":=", "encoder", ".", "Encode", "(", "&", "b", ".", "default_", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "return", "w", ".", "Bytes", "(", ")", ",", "nil", "\n", "}" ]
//GobEncode encodes a BoolRule in to a GOB
[ "GobEncode", "encodes", "a", "BoolRule", "in", "to", "a", "GOB" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/plugin/cpolicy/bool.go#L81-L99
15,347
intelsdi-x/snap
control/plugin/cpolicy/bool.go
GobDecode
func (b *BoolRule) GobDecode(buf []byte) error { r := bytes.NewBuffer(buf) decoder := gob.NewDecoder(r) if err := decoder.Decode(&b.key); err != nil { return err } if err := decoder.Decode(&b.required); err != nil { return err } var isDefaultSet bool decoder.Decode(&isDefaultSet) if isDefaultSet { return decoder.Decode(&b.default_) } return nil }
go
func (b *BoolRule) GobDecode(buf []byte) error { r := bytes.NewBuffer(buf) decoder := gob.NewDecoder(r) if err := decoder.Decode(&b.key); err != nil { return err } if err := decoder.Decode(&b.required); err != nil { return err } var isDefaultSet bool decoder.Decode(&isDefaultSet) if isDefaultSet { return decoder.Decode(&b.default_) } return nil }
[ "func", "(", "b", "*", "BoolRule", ")", "GobDecode", "(", "buf", "[", "]", "byte", ")", "error", "{", "r", ":=", "bytes", ".", "NewBuffer", "(", "buf", ")", "\n", "decoder", ":=", "gob", ".", "NewDecoder", "(", "r", ")", "\n", "if", "err", ":=", "decoder", ".", "Decode", "(", "&", "b", ".", "key", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "decoder", ".", "Decode", "(", "&", "b", ".", "required", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "var", "isDefaultSet", "bool", "\n", "decoder", ".", "Decode", "(", "&", "isDefaultSet", ")", "\n", "if", "isDefaultSet", "{", "return", "decoder", ".", "Decode", "(", "&", "b", ".", "default_", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// GobDecode decodes a GOB into a BoolRule
[ "GobDecode", "decodes", "a", "GOB", "into", "a", "BoolRule" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/plugin/cpolicy/bool.go#L102-L117
15,348
intelsdi-x/snap
control/plugin/cpolicy/bool.go
Validate
func (b *BoolRule) Validate(cv ctypes.ConfigValue) error { // Check that type is correct if cv.Type() != BoolType { return wrongType(b.key, cv.Type(), BoolType) } return nil }
go
func (b *BoolRule) Validate(cv ctypes.ConfigValue) error { // Check that type is correct if cv.Type() != BoolType { return wrongType(b.key, cv.Type(), BoolType) } return nil }
[ "func", "(", "b", "*", "BoolRule", ")", "Validate", "(", "cv", "ctypes", ".", "ConfigValue", ")", "error", "{", "// Check that type is correct", "if", "cv", ".", "Type", "(", ")", "!=", "BoolType", "{", "return", "wrongType", "(", "b", ".", "key", ",", "cv", ".", "Type", "(", ")", ",", "BoolType", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Validate validates a config value against this rule.
[ "Validate", "validates", "a", "config", "value", "against", "this", "rule", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/plugin/cpolicy/bool.go#L125-L131
15,349
intelsdi-x/snap
control/plugin/cpolicy/bool.go
Default
func (b *BoolRule) Default() ctypes.ConfigValue { if b.default_ != nil { return ctypes.ConfigValueBool{Value: *b.default_} } return nil }
go
func (b *BoolRule) Default() ctypes.ConfigValue { if b.default_ != nil { return ctypes.ConfigValueBool{Value: *b.default_} } return nil }
[ "func", "(", "b", "*", "BoolRule", ")", "Default", "(", ")", "ctypes", ".", "ConfigValue", "{", "if", "b", ".", "default_", "!=", "nil", "{", "return", "ctypes", ".", "ConfigValueBool", "{", "Value", ":", "*", "b", ".", "default_", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Default returns a default value is it exists.
[ "Default", "returns", "a", "default", "value", "is", "it", "exists", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/plugin/cpolicy/bool.go#L134-L139
15,350
intelsdi-x/snap
control/plugin/session_deprecated.go
GetConfigPolicy
func (s *SessionState) GetConfigPolicy(args []byte, reply *[]byte) error { defer catchPluginPanic(s.Logger()) s.logger.Debug("GetConfigPolicy called") policy, err := s.plugin.GetConfigPolicy() if err != nil { return errors.New(fmt.Sprintf("GetConfigPolicy call error : %s", err.Error())) } r := GetConfigPolicyReply{Policy: policy} *reply, err = s.Encode(r) if err != nil { return err } return nil }
go
func (s *SessionState) GetConfigPolicy(args []byte, reply *[]byte) error { defer catchPluginPanic(s.Logger()) s.logger.Debug("GetConfigPolicy called") policy, err := s.plugin.GetConfigPolicy() if err != nil { return errors.New(fmt.Sprintf("GetConfigPolicy call error : %s", err.Error())) } r := GetConfigPolicyReply{Policy: policy} *reply, err = s.Encode(r) if err != nil { return err } return nil }
[ "func", "(", "s", "*", "SessionState", ")", "GetConfigPolicy", "(", "args", "[", "]", "byte", ",", "reply", "*", "[", "]", "byte", ")", "error", "{", "defer", "catchPluginPanic", "(", "s", ".", "Logger", "(", ")", ")", "\n\n", "s", ".", "logger", ".", "Debug", "(", "\"", "\"", ")", "\n\n", "policy", ",", "err", ":=", "s", ".", "plugin", ".", "GetConfigPolicy", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "New", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", ")", "\n", "}", "\n\n", "r", ":=", "GetConfigPolicyReply", "{", "Policy", ":", "policy", "}", "\n", "*", "reply", ",", "err", "=", "s", ".", "Encode", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// GetConfigPolicy returns the plugin's policy
[ "GetConfigPolicy", "returns", "the", "plugin", "s", "policy" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/plugin/session_deprecated.go#L97-L114
15,351
intelsdi-x/snap
control/plugin/session_deprecated.go
Ping
func (s *SessionState) Ping(arg []byte, reply *[]byte) error { // For now we return nil. We can return an error if we are shutting // down or otherwise in a state we should signal poor health. // Reply should contain any context. s.ResetHeartbeat() s.logger.Debug("Ping received") *reply = []byte{} return nil }
go
func (s *SessionState) Ping(arg []byte, reply *[]byte) error { // For now we return nil. We can return an error if we are shutting // down or otherwise in a state we should signal poor health. // Reply should contain any context. s.ResetHeartbeat() s.logger.Debug("Ping received") *reply = []byte{} return nil }
[ "func", "(", "s", "*", "SessionState", ")", "Ping", "(", "arg", "[", "]", "byte", ",", "reply", "*", "[", "]", "byte", ")", "error", "{", "// For now we return nil. We can return an error if we are shutting", "// down or otherwise in a state we should signal poor health.", "// Reply should contain any context.", "s", ".", "ResetHeartbeat", "(", ")", "\n", "s", ".", "logger", ".", "Debug", "(", "\"", "\"", ")", "\n", "*", "reply", "=", "[", "]", "byte", "{", "}", "\n", "return", "nil", "\n", "}" ]
// Ping returns nothing in normal operation
[ "Ping", "returns", "nothing", "in", "normal", "operation" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/plugin/session_deprecated.go#L117-L125
15,352
intelsdi-x/snap
control/plugin/session_deprecated.go
Kill
func (s *SessionState) Kill(args []byte, reply *[]byte) error { a := &KillArgs{} err := s.Decode(args, a) if err != nil { return err } s.logger.Debugf("Kill called by agent, reason: %s\n", a.Reason) go func() { time.Sleep(time.Second * 2) s.killChan <- 0 }() *reply = []byte{} return nil }
go
func (s *SessionState) Kill(args []byte, reply *[]byte) error { a := &KillArgs{} err := s.Decode(args, a) if err != nil { return err } s.logger.Debugf("Kill called by agent, reason: %s\n", a.Reason) go func() { time.Sleep(time.Second * 2) s.killChan <- 0 }() *reply = []byte{} return nil }
[ "func", "(", "s", "*", "SessionState", ")", "Kill", "(", "args", "[", "]", "byte", ",", "reply", "*", "[", "]", "byte", ")", "error", "{", "a", ":=", "&", "KillArgs", "{", "}", "\n", "err", ":=", "s", ".", "Decode", "(", "args", ",", "a", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "s", ".", "logger", ".", "Debugf", "(", "\"", "\\n", "\"", ",", "a", ".", "Reason", ")", "\n", "go", "func", "(", ")", "{", "time", ".", "Sleep", "(", "time", ".", "Second", "*", "2", ")", "\n", "s", ".", "killChan", "<-", "0", "\n", "}", "(", ")", "\n", "*", "reply", "=", "[", "]", "byte", "{", "}", "\n", "return", "nil", "\n", "}" ]
// Kill will stop a running plugin
[ "Kill", "will", "stop", "a", "running", "plugin" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/plugin/session_deprecated.go#L128-L141
15,353
intelsdi-x/snap
control/mttrie.go
DeleteByPlugin
func (m *MTTrie) DeleteByPlugin(cp core.CatalogedPlugin) { for _, mt := range m.gatherMetricTypes() { mtPluginKey := fmt.Sprintf("%s"+core.Separator+"%s"+core.Separator+"%d", mt.Plugin.TypeName(), mt.Plugin.Name(), mt.Plugin.Version()) cpKey := fmt.Sprintf("%s"+core.Separator+"%s"+core.Separator+"%d", cp.TypeName(), cp.Name(), cp.Version()) if mtPluginKey == cpKey { // remove this metric m.RemoveMetric(mt) } } }
go
func (m *MTTrie) DeleteByPlugin(cp core.CatalogedPlugin) { for _, mt := range m.gatherMetricTypes() { mtPluginKey := fmt.Sprintf("%s"+core.Separator+"%s"+core.Separator+"%d", mt.Plugin.TypeName(), mt.Plugin.Name(), mt.Plugin.Version()) cpKey := fmt.Sprintf("%s"+core.Separator+"%s"+core.Separator+"%d", cp.TypeName(), cp.Name(), cp.Version()) if mtPluginKey == cpKey { // remove this metric m.RemoveMetric(mt) } } }
[ "func", "(", "m", "*", "MTTrie", ")", "DeleteByPlugin", "(", "cp", "core", ".", "CatalogedPlugin", ")", "{", "for", "_", ",", "mt", ":=", "range", "m", ".", "gatherMetricTypes", "(", ")", "{", "mtPluginKey", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "core", ".", "Separator", "+", "\"", "\"", "+", "core", ".", "Separator", "+", "\"", "\"", ",", "mt", ".", "Plugin", ".", "TypeName", "(", ")", ",", "mt", ".", "Plugin", ".", "Name", "(", ")", ",", "mt", ".", "Plugin", ".", "Version", "(", ")", ")", "\n", "cpKey", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "core", ".", "Separator", "+", "\"", "\"", "+", "core", ".", "Separator", "+", "\"", "\"", ",", "cp", ".", "TypeName", "(", ")", ",", "cp", ".", "Name", "(", ")", ",", "cp", ".", "Version", "(", ")", ")", "\n", "if", "mtPluginKey", "==", "cpKey", "{", "// remove this metric", "m", ".", "RemoveMetric", "(", "mt", ")", "\n", "}", "\n", "}", "\n", "}" ]
// DeleteByPlugin removes all metrics from the catalog if they match a loadedPlugin
[ "DeleteByPlugin", "removes", "all", "metrics", "from", "the", "catalog", "if", "they", "match", "a", "loadedPlugin" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/mttrie.go#L98-L107
15,354
intelsdi-x/snap
control/mttrie.go
RemoveMetric
func (m *MTTrie) RemoveMetric(mt metricType) { a, _ := m.find(mt.Namespace().Strings()) if a != nil { for v, x := range a.mts { if mt.Version() == x.Version() { // delete this metric from the node delete(a.mts, v) } } } }
go
func (m *MTTrie) RemoveMetric(mt metricType) { a, _ := m.find(mt.Namespace().Strings()) if a != nil { for v, x := range a.mts { if mt.Version() == x.Version() { // delete this metric from the node delete(a.mts, v) } } } }
[ "func", "(", "m", "*", "MTTrie", ")", "RemoveMetric", "(", "mt", "metricType", ")", "{", "a", ",", "_", ":=", "m", ".", "find", "(", "mt", ".", "Namespace", "(", ")", ".", "Strings", "(", ")", ")", "\n", "if", "a", "!=", "nil", "{", "for", "v", ",", "x", ":=", "range", "a", ".", "mts", "{", "if", "mt", ".", "Version", "(", ")", "==", "x", ".", "Version", "(", ")", "{", "// delete this metric from the node", "delete", "(", "a", ".", "mts", ",", "v", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// RemoveMetric removes a specific metric by namespace and version from the tree
[ "RemoveMetric", "removes", "a", "specific", "metric", "by", "namespace", "and", "version", "from", "the", "tree" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/mttrie.go#L110-L120
15,355
intelsdi-x/snap
control/mttrie.go
Add
func (mtt *mttNode) Add(mt *metricType) { ns := mt.Namespace() node, index := mtt.walk(ns.Strings()) if index == len(ns) { if node.mts == nil { node.mts = make(map[int]*metricType) } node.mts[mt.Version()] = mt return } // walk through the remaining namespace and build out the // new branch in the trie. for _, n := range ns[index:] { if node.children == nil { node.children = make(map[string]*mttNode) } node.children[n.Value] = &mttNode{} node = node.children[n.Value] } node.mts = make(map[int]*metricType) node.mts[mt.Version()] = mt }
go
func (mtt *mttNode) Add(mt *metricType) { ns := mt.Namespace() node, index := mtt.walk(ns.Strings()) if index == len(ns) { if node.mts == nil { node.mts = make(map[int]*metricType) } node.mts[mt.Version()] = mt return } // walk through the remaining namespace and build out the // new branch in the trie. for _, n := range ns[index:] { if node.children == nil { node.children = make(map[string]*mttNode) } node.children[n.Value] = &mttNode{} node = node.children[n.Value] } node.mts = make(map[int]*metricType) node.mts[mt.Version()] = mt }
[ "func", "(", "mtt", "*", "mttNode", ")", "Add", "(", "mt", "*", "metricType", ")", "{", "ns", ":=", "mt", ".", "Namespace", "(", ")", "\n", "node", ",", "index", ":=", "mtt", ".", "walk", "(", "ns", ".", "Strings", "(", ")", ")", "\n", "if", "index", "==", "len", "(", "ns", ")", "{", "if", "node", ".", "mts", "==", "nil", "{", "node", ".", "mts", "=", "make", "(", "map", "[", "int", "]", "*", "metricType", ")", "\n", "}", "\n", "node", ".", "mts", "[", "mt", ".", "Version", "(", ")", "]", "=", "mt", "\n", "return", "\n", "}", "\n", "// walk through the remaining namespace and build out the", "// new branch in the trie.", "for", "_", ",", "n", ":=", "range", "ns", "[", "index", ":", "]", "{", "if", "node", ".", "children", "==", "nil", "{", "node", ".", "children", "=", "make", "(", "map", "[", "string", "]", "*", "mttNode", ")", "\n", "}", "\n", "node", ".", "children", "[", "n", ".", "Value", "]", "=", "&", "mttNode", "{", "}", "\n", "node", "=", "node", ".", "children", "[", "n", ".", "Value", "]", "\n", "}", "\n", "node", ".", "mts", "=", "make", "(", "map", "[", "int", "]", "*", "metricType", ")", "\n", "node", ".", "mts", "[", "mt", ".", "Version", "(", ")", "]", "=", "mt", "\n", "}" ]
// Add adds a node with the given namespace with the given MetricType
[ "Add", "adds", "a", "node", "with", "the", "given", "namespace", "with", "the", "given", "MetricType" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/mttrie.go#L123-L144
15,356
intelsdi-x/snap
control/mttrie.go
Fetch
func (mtt *mttNode) Fetch(ns []string) ([]*metricType, error) { children := mtt.fetch(ns) var mts []*metricType for _, child := range children { for _, mt := range child.mts { mts = append(mts, mt) } } if len(mts) == 0 && len(ns) > 0 { return nil, errorMetricsNotFound("/" + strings.Join(ns, "/")) } return mts, nil }
go
func (mtt *mttNode) Fetch(ns []string) ([]*metricType, error) { children := mtt.fetch(ns) var mts []*metricType for _, child := range children { for _, mt := range child.mts { mts = append(mts, mt) } } if len(mts) == 0 && len(ns) > 0 { return nil, errorMetricsNotFound("/" + strings.Join(ns, "/")) } return mts, nil }
[ "func", "(", "mtt", "*", "mttNode", ")", "Fetch", "(", "ns", "[", "]", "string", ")", "(", "[", "]", "*", "metricType", ",", "error", ")", "{", "children", ":=", "mtt", ".", "fetch", "(", "ns", ")", "\n", "var", "mts", "[", "]", "*", "metricType", "\n", "for", "_", ",", "child", ":=", "range", "children", "{", "for", "_", ",", "mt", ":=", "range", "child", ".", "mts", "{", "mts", "=", "append", "(", "mts", ",", "mt", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "mts", ")", "==", "0", "&&", "len", "(", "ns", ")", ">", "0", "{", "return", "nil", ",", "errorMetricsNotFound", "(", "\"", "\"", "+", "strings", ".", "Join", "(", "ns", ",", "\"", "\"", ")", ")", "\n", "}", "\n", "return", "mts", ",", "nil", "\n", "}" ]
// Fetch collects all children below a given namespace // and concatenates their metric types into a single slice
[ "Fetch", "collects", "all", "children", "below", "a", "given", "namespace", "and", "concatenates", "their", "metric", "types", "into", "a", "single", "slice" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/mttrie.go#L148-L160
15,357
intelsdi-x/snap
control/mttrie.go
Remove
func (mtt *mttNode) Remove(ns []string) error { _, err := mtt.find(ns) if err != nil { return err } parent, err := mtt.find(ns[:len(ns)-1]) if err != nil { return err } // remove node from parent delete(parent.children, ns[len(ns)-1:][0]) return nil }
go
func (mtt *mttNode) Remove(ns []string) error { _, err := mtt.find(ns) if err != nil { return err } parent, err := mtt.find(ns[:len(ns)-1]) if err != nil { return err } // remove node from parent delete(parent.children, ns[len(ns)-1:][0]) return nil }
[ "func", "(", "mtt", "*", "mttNode", ")", "Remove", "(", "ns", "[", "]", "string", ")", "error", "{", "_", ",", "err", ":=", "mtt", ".", "find", "(", "ns", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "parent", ",", "err", ":=", "mtt", ".", "find", "(", "ns", "[", ":", "len", "(", "ns", ")", "-", "1", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "// remove node from parent", "delete", "(", "parent", ".", "children", ",", "ns", "[", "len", "(", "ns", ")", "-", "1", ":", "]", "[", "0", "]", ")", "\n\n", "return", "nil", "\n", "}" ]
// Remove removes all descendants nodes below a given namespace
[ "Remove", "removes", "all", "descendants", "nodes", "below", "a", "given", "namespace" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/mttrie.go#L163-L177
15,358
intelsdi-x/snap
control/mttrie.go
GetVersions
func (mtt *mttNode) GetVersions(ns []string) ([]*metricType, error) { var nodes []*mttNode var mts []*metricType if len(ns) == 0 { return nil, errorEmptyNamespace() } nodes = mtt.search(nodes, ns) for _, node := range nodes { // concatenates metric types in ALL versions into a single slice for _, mt := range node.mts { mts = append(mts, mt) } } if len(mts) == 0 { return nil, errorMetricNotFound("/" + strings.Join(ns, "/")) } return mts, nil }
go
func (mtt *mttNode) GetVersions(ns []string) ([]*metricType, error) { var nodes []*mttNode var mts []*metricType if len(ns) == 0 { return nil, errorEmptyNamespace() } nodes = mtt.search(nodes, ns) for _, node := range nodes { // concatenates metric types in ALL versions into a single slice for _, mt := range node.mts { mts = append(mts, mt) } } if len(mts) == 0 { return nil, errorMetricNotFound("/" + strings.Join(ns, "/")) } return mts, nil }
[ "func", "(", "mtt", "*", "mttNode", ")", "GetVersions", "(", "ns", "[", "]", "string", ")", "(", "[", "]", "*", "metricType", ",", "error", ")", "{", "var", "nodes", "[", "]", "*", "mttNode", "\n", "var", "mts", "[", "]", "*", "metricType", "\n\n", "if", "len", "(", "ns", ")", "==", "0", "{", "return", "nil", ",", "errorEmptyNamespace", "(", ")", "\n", "}", "\n\n", "nodes", "=", "mtt", ".", "search", "(", "nodes", ",", "ns", ")", "\n\n", "for", "_", ",", "node", ":=", "range", "nodes", "{", "// concatenates metric types in ALL versions into a single slice", "for", "_", ",", "mt", ":=", "range", "node", ".", "mts", "{", "mts", "=", "append", "(", "mts", ",", "mt", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "mts", ")", "==", "0", "{", "return", "nil", ",", "errorMetricNotFound", "(", "\"", "\"", "+", "strings", ".", "Join", "(", "ns", ",", "\"", "\"", ")", ")", "\n", "}", "\n", "return", "mts", ",", "nil", "\n", "}" ]
// GetVersions returns all versions of MTs below the given namespace
[ "GetVersions", "returns", "all", "versions", "of", "MTs", "below", "the", "given", "namespace" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/mttrie.go#L222-L242
15,359
intelsdi-x/snap
control/mttrie.go
fetch
func (mtt *mttNode) fetch(ns []string) []*mttNode { node, err := mtt.find(ns) if err != nil { return nil } var children []*mttNode if node.mts != nil { children = append(children, node) } if node.children != nil { children = gatherDescendants(children, node) } return children }
go
func (mtt *mttNode) fetch(ns []string) []*mttNode { node, err := mtt.find(ns) if err != nil { return nil } var children []*mttNode if node.mts != nil { children = append(children, node) } if node.children != nil { children = gatherDescendants(children, node) } return children }
[ "func", "(", "mtt", "*", "mttNode", ")", "fetch", "(", "ns", "[", "]", "string", ")", "[", "]", "*", "mttNode", "{", "node", ",", "err", ":=", "mtt", ".", "find", "(", "ns", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", "\n", "}", "\n\n", "var", "children", "[", "]", "*", "mttNode", "\n\n", "if", "node", ".", "mts", "!=", "nil", "{", "children", "=", "append", "(", "children", ",", "node", ")", "\n", "}", "\n", "if", "node", ".", "children", "!=", "nil", "{", "children", "=", "gatherDescendants", "(", "children", ",", "node", ")", "\n", "}", "\n", "return", "children", "\n", "}" ]
// fetch collects all descendants nodes below the given namespace
[ "fetch", "collects", "all", "descendants", "nodes", "below", "the", "given", "namespace" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/mttrie.go#L245-L260
15,360
intelsdi-x/snap
control/mttrie.go
search
func (mtt *mttNode) search(nodes []*mttNode, ns []string) []*mttNode { parent := mtt var children []*mttNode if parent.children == nil { return nodes } if len(ns) == 1 { // the last element of ns is under searching process switch ns[0] { case "*": // fetch all descendants when wildcard ends namespace children = parent.fetch([]string{}) default: children = parent.gatherChildren(ns[0]) } nodes = append(nodes, children...) return nodes } children = parent.gatherChildren(ns[0]) for _, child := range children { nodes = child.search(nodes, ns[1:]) } return nodes }
go
func (mtt *mttNode) search(nodes []*mttNode, ns []string) []*mttNode { parent := mtt var children []*mttNode if parent.children == nil { return nodes } if len(ns) == 1 { // the last element of ns is under searching process switch ns[0] { case "*": // fetch all descendants when wildcard ends namespace children = parent.fetch([]string{}) default: children = parent.gatherChildren(ns[0]) } nodes = append(nodes, children...) return nodes } children = parent.gatherChildren(ns[0]) for _, child := range children { nodes = child.search(nodes, ns[1:]) } return nodes }
[ "func", "(", "mtt", "*", "mttNode", ")", "search", "(", "nodes", "[", "]", "*", "mttNode", ",", "ns", "[", "]", "string", ")", "[", "]", "*", "mttNode", "{", "parent", ":=", "mtt", "\n", "var", "children", "[", "]", "*", "mttNode", "\n\n", "if", "parent", ".", "children", "==", "nil", "{", "return", "nodes", "\n", "}", "\n", "if", "len", "(", "ns", ")", "==", "1", "{", "// the last element of ns is under searching process", "switch", "ns", "[", "0", "]", "{", "case", "\"", "\"", ":", "// fetch all descendants when wildcard ends namespace", "children", "=", "parent", ".", "fetch", "(", "[", "]", "string", "{", "}", ")", "\n", "default", ":", "children", "=", "parent", ".", "gatherChildren", "(", "ns", "[", "0", "]", ")", "\n", "}", "\n", "nodes", "=", "append", "(", "nodes", ",", "children", "...", ")", "\n", "return", "nodes", "\n", "}", "\n", "children", "=", "parent", ".", "gatherChildren", "(", "ns", "[", "0", "]", ")", "\n\n", "for", "_", ",", "child", ":=", "range", "children", "{", "nodes", "=", "child", ".", "search", "(", "nodes", ",", "ns", "[", "1", ":", "]", ")", "\n", "}", "\n", "return", "nodes", "\n", "}" ]
// search returns leaf nodes in the trie below the given namespace
[ "search", "returns", "leaf", "nodes", "in", "the", "trie", "below", "the", "given", "namespace" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/mttrie.go#L284-L309
15,361
intelsdi-x/snap
control/mttrie.go
gatherDescendants
func gatherDescendants(descendants []*mttNode, node *mttNode) []*mttNode { for _, child := range node.children { if child.mts != nil { descendants = append(descendants, child) } if child.children != nil { descendants = gatherDescendants(descendants, child) } } return descendants }
go
func gatherDescendants(descendants []*mttNode, node *mttNode) []*mttNode { for _, child := range node.children { if child.mts != nil { descendants = append(descendants, child) } if child.children != nil { descendants = gatherDescendants(descendants, child) } } return descendants }
[ "func", "gatherDescendants", "(", "descendants", "[", "]", "*", "mttNode", ",", "node", "*", "mttNode", ")", "[", "]", "*", "mttNode", "{", "for", "_", ",", "child", ":=", "range", "node", ".", "children", "{", "if", "child", ".", "mts", "!=", "nil", "{", "descendants", "=", "append", "(", "descendants", ",", "child", ")", "\n", "}", "\n\n", "if", "child", ".", "children", "!=", "nil", "{", "descendants", "=", "gatherDescendants", "(", "descendants", ",", "child", ")", "\n", "}", "\n", "}", "\n", "return", "descendants", "\n", "}" ]
// gatherDescendants returns all descendants of a given node
[ "gatherDescendants", "returns", "all", "descendants", "of", "a", "given", "node" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/mttrie.go#L347-L359
15,362
intelsdi-x/snap
control/plugin/cpolicy/string.go
MarshalJSON
func (s *StringRule) MarshalJSON() ([]byte, error) { return json.Marshal(&struct { Key string `json:"key"` Required bool `json:"required"` Default ctypes.ConfigValue `json:"default"` Type string `json:"type"` }{ Key: s.key, Required: s.required, Default: s.Default(), Type: StringType, }) }
go
func (s *StringRule) MarshalJSON() ([]byte, error) { return json.Marshal(&struct { Key string `json:"key"` Required bool `json:"required"` Default ctypes.ConfigValue `json:"default"` Type string `json:"type"` }{ Key: s.key, Required: s.required, Default: s.Default(), Type: StringType, }) }
[ "func", "(", "s", "*", "StringRule", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "json", ".", "Marshal", "(", "&", "struct", "{", "Key", "string", "`json:\"key\"`", "\n", "Required", "bool", "`json:\"required\"`", "\n", "Default", "ctypes", ".", "ConfigValue", "`json:\"default\"`", "\n", "Type", "string", "`json:\"type\"`", "\n", "}", "{", "Key", ":", "s", ".", "key", ",", "Required", ":", "s", ".", "required", ",", "Default", ":", "s", ".", "Default", "(", ")", ",", "Type", ":", "StringType", ",", "}", ")", "\n", "}" ]
// MarshalJSON marshals a StringRule into JSON
[ "MarshalJSON", "marshals", "a", "StringRule", "into", "JSON" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/plugin/cpolicy/string.go#L67-L79
15,363
intelsdi-x/snap
control/plugin/cpolicy/string.go
GobDecode
func (s *StringRule) GobDecode(buf []byte) error { r := bytes.NewBuffer(buf) decoder := gob.NewDecoder(r) if err := decoder.Decode(&s.key); err != nil { return err } if err := decoder.Decode(&s.required); err != nil { return err } var is_default_set bool decoder.Decode(&is_default_set) if is_default_set { return decoder.Decode(&s.default_) } return nil }
go
func (s *StringRule) GobDecode(buf []byte) error { r := bytes.NewBuffer(buf) decoder := gob.NewDecoder(r) if err := decoder.Decode(&s.key); err != nil { return err } if err := decoder.Decode(&s.required); err != nil { return err } var is_default_set bool decoder.Decode(&is_default_set) if is_default_set { return decoder.Decode(&s.default_) } return nil }
[ "func", "(", "s", "*", "StringRule", ")", "GobDecode", "(", "buf", "[", "]", "byte", ")", "error", "{", "r", ":=", "bytes", ".", "NewBuffer", "(", "buf", ")", "\n", "decoder", ":=", "gob", ".", "NewDecoder", "(", "r", ")", "\n", "if", "err", ":=", "decoder", ".", "Decode", "(", "&", "s", ".", "key", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "decoder", ".", "Decode", "(", "&", "s", ".", "required", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "var", "is_default_set", "bool", "\n", "decoder", ".", "Decode", "(", "&", "is_default_set", ")", "\n", "if", "is_default_set", "{", "return", "decoder", ".", "Decode", "(", "&", "s", ".", "default_", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// GobDecode decodes a GOB into a StringRule
[ "GobDecode", "decodes", "a", "GOB", "into", "a", "StringRule" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/plugin/cpolicy/string.go#L103-L118
15,364
intelsdi-x/snap
control/plugin/cpolicy/string.go
Validate
func (s *StringRule) Validate(cv ctypes.ConfigValue) error { // Check that type is correct if cv.Type() != StringType { return wrongType(s.key, cv.Type(), StringType) } return nil }
go
func (s *StringRule) Validate(cv ctypes.ConfigValue) error { // Check that type is correct if cv.Type() != StringType { return wrongType(s.key, cv.Type(), StringType) } return nil }
[ "func", "(", "s", "*", "StringRule", ")", "Validate", "(", "cv", "ctypes", ".", "ConfigValue", ")", "error", "{", "// Check that type is correct", "if", "cv", ".", "Type", "(", ")", "!=", "StringType", "{", "return", "wrongType", "(", "s", ".", "key", ",", "cv", ".", "Type", "(", ")", ",", "StringType", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Validates a config value against this rule.
[ "Validates", "a", "config", "value", "against", "this", "rule", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/plugin/cpolicy/string.go#L126-L132
15,365
intelsdi-x/snap
control/plugin/cpolicy/string.go
Default
func (s *StringRule) Default() ctypes.ConfigValue { if s.default_ != nil { return ctypes.ConfigValueStr{Value: *s.default_} } return nil }
go
func (s *StringRule) Default() ctypes.ConfigValue { if s.default_ != nil { return ctypes.ConfigValueStr{Value: *s.default_} } return nil }
[ "func", "(", "s", "*", "StringRule", ")", "Default", "(", ")", "ctypes", ".", "ConfigValue", "{", "if", "s", ".", "default_", "!=", "nil", "{", "return", "ctypes", ".", "ConfigValueStr", "{", "Value", ":", "*", "s", ".", "default_", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Returns a default value is it exists.
[ "Returns", "a", "default", "value", "is", "it", "exists", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/plugin/cpolicy/string.go#L135-L140
15,366
intelsdi-x/snap
control/available_plugin.go
Stop
func (a *availablePlugin) Stop(r string) error { log.WithFields(log.Fields{ "_module": "control-aplugin", "block": "stop", "plugin_name": a, }).Info("stopping available plugin") if a.IsRemote() { return a.client.Close() } return a.client.Kill(r) }
go
func (a *availablePlugin) Stop(r string) error { log.WithFields(log.Fields{ "_module": "control-aplugin", "block": "stop", "plugin_name": a, }).Info("stopping available plugin") if a.IsRemote() { return a.client.Close() } return a.client.Kill(r) }
[ "func", "(", "a", "*", "availablePlugin", ")", "Stop", "(", "r", "string", ")", "error", "{", "log", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "a", ",", "}", ")", ".", "Info", "(", "\"", "\"", ")", "\n", "if", "a", ".", "IsRemote", "(", ")", "{", "return", "a", ".", "client", ".", "Close", "(", ")", "\n", "}", "\n", "return", "a", ".", "client", ".", "Kill", "(", "r", ")", "\n", "}" ]
// Stop halts a running availablePlugin
[ "Stop", "halts", "a", "running", "availablePlugin" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/available_plugin.go#L261-L271
15,367
intelsdi-x/snap
control/available_plugin.go
Kill
func (a *availablePlugin) Kill(r string) error { log.WithFields(log.Fields{ "_module": "control-aplugin", "block": "kill", "plugin_name": a, }).Info("hard killing available plugin") if a.fromPackage { log.WithFields(log.Fields{ "_module": "control-aplugin", "block": "kill", "plugin_name": a, "pluginPath": a.execPath, }).Debug("deleting available plugin package") os.RemoveAll(filepath.Dir(a.execPath)) } // If it's a streaming plugin, we need to signal the scheduler that // this plugin is being killed. if c, ok := a.client.(client.PluginStreamCollectorClient); ok { c.Killed() } if a.ePlugin != nil { return a.ePlugin.Kill() } return nil }
go
func (a *availablePlugin) Kill(r string) error { log.WithFields(log.Fields{ "_module": "control-aplugin", "block": "kill", "plugin_name": a, }).Info("hard killing available plugin") if a.fromPackage { log.WithFields(log.Fields{ "_module": "control-aplugin", "block": "kill", "plugin_name": a, "pluginPath": a.execPath, }).Debug("deleting available plugin package") os.RemoveAll(filepath.Dir(a.execPath)) } // If it's a streaming plugin, we need to signal the scheduler that // this plugin is being killed. if c, ok := a.client.(client.PluginStreamCollectorClient); ok { c.Killed() } if a.ePlugin != nil { return a.ePlugin.Kill() } return nil }
[ "func", "(", "a", "*", "availablePlugin", ")", "Kill", "(", "r", "string", ")", "error", "{", "log", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "a", ",", "}", ")", ".", "Info", "(", "\"", "\"", ")", "\n", "if", "a", ".", "fromPackage", "{", "log", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "a", ",", "\"", "\"", ":", "a", ".", "execPath", ",", "}", ")", ".", "Debug", "(", "\"", "\"", ")", "\n", "os", ".", "RemoveAll", "(", "filepath", ".", "Dir", "(", "a", ".", "execPath", ")", ")", "\n", "}", "\n\n", "// If it's a streaming plugin, we need to signal the scheduler that", "// this plugin is being killed.", "if", "c", ",", "ok", ":=", "a", ".", "client", ".", "(", "client", ".", "PluginStreamCollectorClient", ")", ";", "ok", "{", "c", ".", "Killed", "(", ")", "\n", "}", "\n\n", "if", "a", ".", "ePlugin", "!=", "nil", "{", "return", "a", ".", "ePlugin", ".", "Kill", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Kill assumes a plugin is not able to hear a Kill RPC call
[ "Kill", "assumes", "a", "plugin", "is", "not", "able", "to", "hear", "a", "Kill", "RPC", "call" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/available_plugin.go#L274-L300
15,368
intelsdi-x/snap
control/available_plugin.go
CheckHealth
func (a *availablePlugin) CheckHealth() { go func() { a.healthChan <- a.client.Ping() }() select { case err := <-a.healthChan: if err == nil { if a.failedHealthChecks > 0 { // only log on first ok health check log.WithFields(log.Fields{ "_module": "control-aplugin", "block": "check-health", "plugin_name": a, }).Debug("health is ok") } a.failedHealthChecks = 0 } else { a.healthCheckFailed() } case <-time.After(DefaultHealthCheckTimeout): a.healthCheckFailed() } }
go
func (a *availablePlugin) CheckHealth() { go func() { a.healthChan <- a.client.Ping() }() select { case err := <-a.healthChan: if err == nil { if a.failedHealthChecks > 0 { // only log on first ok health check log.WithFields(log.Fields{ "_module": "control-aplugin", "block": "check-health", "plugin_name": a, }).Debug("health is ok") } a.failedHealthChecks = 0 } else { a.healthCheckFailed() } case <-time.After(DefaultHealthCheckTimeout): a.healthCheckFailed() } }
[ "func", "(", "a", "*", "availablePlugin", ")", "CheckHealth", "(", ")", "{", "go", "func", "(", ")", "{", "a", ".", "healthChan", "<-", "a", ".", "client", ".", "Ping", "(", ")", "\n", "}", "(", ")", "\n", "select", "{", "case", "err", ":=", "<-", "a", ".", "healthChan", ":", "if", "err", "==", "nil", "{", "if", "a", ".", "failedHealthChecks", ">", "0", "{", "// only log on first ok health check", "log", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "a", ",", "}", ")", ".", "Debug", "(", "\"", "\"", ")", "\n", "}", "\n", "a", ".", "failedHealthChecks", "=", "0", "\n", "}", "else", "{", "a", ".", "healthCheckFailed", "(", ")", "\n", "}", "\n", "case", "<-", "time", ".", "After", "(", "DefaultHealthCheckTimeout", ")", ":", "a", ".", "healthCheckFailed", "(", ")", "\n", "}", "\n", "}" ]
// CheckHealth checks the health of a plugin and updates // a.failedHealthChecks
[ "CheckHealth", "checks", "the", "health", "of", "a", "plugin", "and", "updates", "a", ".", "failedHealthChecks" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/available_plugin.go#L304-L326
15,369
intelsdi-x/snap
control/available_plugin.go
healthCheckFailed
func (a *availablePlugin) healthCheckFailed() { log.WithFields(log.Fields{ "_module": "control-aplugin", "block": "check-health", "plugin_name": a, }).Warning("heartbeat missed") a.failedHealthChecks++ if a.failedHealthChecks >= DefaultHealthCheckFailureLimit { log.WithFields(log.Fields{ "_module": "control-aplugin", "block": "check-health", "plugin_name": a, }).Warning("heartbeat failed") pde := &control_event.DeadAvailablePluginEvent{ Name: a.name, Version: a.version, Type: int(a.pluginType), Key: a.key, Id: a.ID(), String: a.String(), } defer a.emitter.Emit(pde) } hcfe := &control_event.HealthCheckFailedEvent{ Name: a.name, Version: a.version, Type: int(a.pluginType), } defer a.emitter.Emit(hcfe) }
go
func (a *availablePlugin) healthCheckFailed() { log.WithFields(log.Fields{ "_module": "control-aplugin", "block": "check-health", "plugin_name": a, }).Warning("heartbeat missed") a.failedHealthChecks++ if a.failedHealthChecks >= DefaultHealthCheckFailureLimit { log.WithFields(log.Fields{ "_module": "control-aplugin", "block": "check-health", "plugin_name": a, }).Warning("heartbeat failed") pde := &control_event.DeadAvailablePluginEvent{ Name: a.name, Version: a.version, Type: int(a.pluginType), Key: a.key, Id: a.ID(), String: a.String(), } defer a.emitter.Emit(pde) } hcfe := &control_event.HealthCheckFailedEvent{ Name: a.name, Version: a.version, Type: int(a.pluginType), } defer a.emitter.Emit(hcfe) }
[ "func", "(", "a", "*", "availablePlugin", ")", "healthCheckFailed", "(", ")", "{", "log", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "a", ",", "}", ")", ".", "Warning", "(", "\"", "\"", ")", "\n", "a", ".", "failedHealthChecks", "++", "\n", "if", "a", ".", "failedHealthChecks", ">=", "DefaultHealthCheckFailureLimit", "{", "log", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "a", ",", "}", ")", ".", "Warning", "(", "\"", "\"", ")", "\n", "pde", ":=", "&", "control_event", ".", "DeadAvailablePluginEvent", "{", "Name", ":", "a", ".", "name", ",", "Version", ":", "a", ".", "version", ",", "Type", ":", "int", "(", "a", ".", "pluginType", ")", ",", "Key", ":", "a", ".", "key", ",", "Id", ":", "a", ".", "ID", "(", ")", ",", "String", ":", "a", ".", "String", "(", ")", ",", "}", "\n", "defer", "a", ".", "emitter", ".", "Emit", "(", "pde", ")", "\n", "}", "\n", "hcfe", ":=", "&", "control_event", ".", "HealthCheckFailedEvent", "{", "Name", ":", "a", ".", "name", ",", "Version", ":", "a", ".", "version", ",", "Type", ":", "int", "(", "a", ".", "pluginType", ")", ",", "}", "\n", "defer", "a", ".", "emitter", ".", "Emit", "(", "hcfe", ")", "\n", "}" ]
// healthCheckFailed increments a.failedHealthChecks and emits a DisabledPluginEvent // and a HealthCheckFailedEvent
[ "healthCheckFailed", "increments", "a", ".", "failedHealthChecks", "and", "emits", "a", "DisabledPluginEvent", "and", "a", "HealthCheckFailedEvent" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/available_plugin.go#L330-L359
15,370
intelsdi-x/snap
mgmt/rest/client/task.go
CreateTask
func (c *Client) CreateTask(s *Schedule, wf *wmap.WorkflowMap, name string, deadline string, startTask bool, maxFailures int) *CreateTaskResult { t := core.TaskCreationRequest{ Schedule: &core.Schedule{ Type: s.Type, Interval: s.Interval, StartTimestamp: s.StartTimestamp, StopTimestamp: s.StopTimestamp, Count: s.Count, }, Workflow: wf, Start: startTask, MaxFailures: maxFailures, } if name != "" { t.Name = name } if deadline != "" { t.Deadline = deadline } // Marshal to JSON for request body j, err := json.Marshal(t) if err != nil { return &CreateTaskResult{Err: err} } resp, err := c.do("POST", "/tasks", ContentTypeJSON, j) if err != nil { return &CreateTaskResult{Err: err} } switch resp.Meta.Type { case rbody.AddScheduledTaskType: // Success return &CreateTaskResult{resp.Body.(*rbody.AddScheduledTask), nil} case rbody.ErrorType: return &CreateTaskResult{Err: resp.Body.(*rbody.Error)} default: return &CreateTaskResult{Err: ErrAPIResponseMetaType} } }
go
func (c *Client) CreateTask(s *Schedule, wf *wmap.WorkflowMap, name string, deadline string, startTask bool, maxFailures int) *CreateTaskResult { t := core.TaskCreationRequest{ Schedule: &core.Schedule{ Type: s.Type, Interval: s.Interval, StartTimestamp: s.StartTimestamp, StopTimestamp: s.StopTimestamp, Count: s.Count, }, Workflow: wf, Start: startTask, MaxFailures: maxFailures, } if name != "" { t.Name = name } if deadline != "" { t.Deadline = deadline } // Marshal to JSON for request body j, err := json.Marshal(t) if err != nil { return &CreateTaskResult{Err: err} } resp, err := c.do("POST", "/tasks", ContentTypeJSON, j) if err != nil { return &CreateTaskResult{Err: err} } switch resp.Meta.Type { case rbody.AddScheduledTaskType: // Success return &CreateTaskResult{resp.Body.(*rbody.AddScheduledTask), nil} case rbody.ErrorType: return &CreateTaskResult{Err: resp.Body.(*rbody.Error)} default: return &CreateTaskResult{Err: ErrAPIResponseMetaType} } }
[ "func", "(", "c", "*", "Client", ")", "CreateTask", "(", "s", "*", "Schedule", ",", "wf", "*", "wmap", ".", "WorkflowMap", ",", "name", "string", ",", "deadline", "string", ",", "startTask", "bool", ",", "maxFailures", "int", ")", "*", "CreateTaskResult", "{", "t", ":=", "core", ".", "TaskCreationRequest", "{", "Schedule", ":", "&", "core", ".", "Schedule", "{", "Type", ":", "s", ".", "Type", ",", "Interval", ":", "s", ".", "Interval", ",", "StartTimestamp", ":", "s", ".", "StartTimestamp", ",", "StopTimestamp", ":", "s", ".", "StopTimestamp", ",", "Count", ":", "s", ".", "Count", ",", "}", ",", "Workflow", ":", "wf", ",", "Start", ":", "startTask", ",", "MaxFailures", ":", "maxFailures", ",", "}", "\n", "if", "name", "!=", "\"", "\"", "{", "t", ".", "Name", "=", "name", "\n", "}", "\n", "if", "deadline", "!=", "\"", "\"", "{", "t", ".", "Deadline", "=", "deadline", "\n", "}", "\n", "// Marshal to JSON for request body", "j", ",", "err", ":=", "json", ".", "Marshal", "(", "t", ")", "\n", "if", "err", "!=", "nil", "{", "return", "&", "CreateTaskResult", "{", "Err", ":", "err", "}", "\n", "}", "\n\n", "resp", ",", "err", ":=", "c", ".", "do", "(", "\"", "\"", ",", "\"", "\"", ",", "ContentTypeJSON", ",", "j", ")", "\n", "if", "err", "!=", "nil", "{", "return", "&", "CreateTaskResult", "{", "Err", ":", "err", "}", "\n", "}", "\n\n", "switch", "resp", ".", "Meta", ".", "Type", "{", "case", "rbody", ".", "AddScheduledTaskType", ":", "// Success", "return", "&", "CreateTaskResult", "{", "resp", ".", "Body", ".", "(", "*", "rbody", ".", "AddScheduledTask", ")", ",", "nil", "}", "\n", "case", "rbody", ".", "ErrorType", ":", "return", "&", "CreateTaskResult", "{", "Err", ":", "resp", ".", "Body", ".", "(", "*", "rbody", ".", "Error", ")", "}", "\n", "default", ":", "return", "&", "CreateTaskResult", "{", "Err", ":", "ErrAPIResponseMetaType", "}", "\n", "}", "\n", "}" ]
// CreateTask creates a task given the schedule, workflow, task name, and task state. // If the startTask flag is true, the newly created task is started after the creation. // Otherwise, it's in the Stopped state. CreateTask is accomplished through a POST HTTP JSON request. // A ScheduledTask is returned if it succeeds, otherwise an error is returned.
[ "CreateTask", "creates", "a", "task", "given", "the", "schedule", "workflow", "task", "name", "and", "task", "state", ".", "If", "the", "startTask", "flag", "is", "true", "the", "newly", "created", "task", "is", "started", "after", "the", "creation", ".", "Otherwise", "it", "s", "in", "the", "Stopped", "state", ".", "CreateTask", "is", "accomplished", "through", "a", "POST", "HTTP", "JSON", "request", ".", "A", "ScheduledTask", "is", "returned", "if", "it", "succeeds", "otherwise", "an", "error", "is", "returned", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/mgmt/rest/client/task.go#L54-L93
15,371
intelsdi-x/snap
mgmt/rest/client/task.go
WatchTask
func (c *Client) WatchTask(id string) *WatchTasksResult { // during watch we don't want to have a timeout // Store the old timeout so we can restore when we are through oldTimeout := c.http.Timeout c.http.Timeout = time.Duration(0) r := &WatchTasksResult{ EventChan: make(chan *rbody.StreamedTaskEvent), DoneChan: make(chan struct{}), } url := fmt.Sprintf("%s/tasks/%v/watch", c.prefix, id) req, err := http.NewRequest("GET", url, nil) addAuth(req, c.Username, c.Password) if err != nil { r.Err = err r.Close() return r } resp, err := c.http.Do(req) if err != nil { if strings.Contains(err.Error(), "tls: oversized record") || strings.Contains(err.Error(), "malformed HTTP response") { r.Err = fmt.Errorf("error connecting to API URI: %s. Do you have an http/https mismatch?", c.URL) } else { r.Err = err } r.Close() return r } if resp.StatusCode != 200 { ar, err := httpRespToAPIResp(resp) if err != nil { r.Err = err } else { r.Err = errors.New(ar.Meta.Message) } r.Close() return r } // Start watching go func() { reader := bufio.NewReader(resp.Body) defer func() { c.http.Timeout = oldTimeout }() for { select { case <-r.DoneChan: resp.Body.Close() return default: line, _ := reader.ReadBytes('\n') sline := string(line) if sline == "" || sline == "\n" { continue } if strings.HasPrefix(sline, "data:") { sline = strings.TrimPrefix(sline, "data:") line = []byte(sline) } ste := &rbody.StreamedTaskEvent{} err := json.Unmarshal(line, ste) if err != nil { r.Err = err r.Close() return } switch ste.EventType { case rbody.TaskWatchTaskDisabled: r.EventChan <- ste r.Close() case rbody.TaskWatchTaskStopped, rbody.TaskWatchTaskEnded, rbody.TaskWatchTaskStarted, rbody.TaskWatchMetricEvent: r.EventChan <- ste } } } }() return r }
go
func (c *Client) WatchTask(id string) *WatchTasksResult { // during watch we don't want to have a timeout // Store the old timeout so we can restore when we are through oldTimeout := c.http.Timeout c.http.Timeout = time.Duration(0) r := &WatchTasksResult{ EventChan: make(chan *rbody.StreamedTaskEvent), DoneChan: make(chan struct{}), } url := fmt.Sprintf("%s/tasks/%v/watch", c.prefix, id) req, err := http.NewRequest("GET", url, nil) addAuth(req, c.Username, c.Password) if err != nil { r.Err = err r.Close() return r } resp, err := c.http.Do(req) if err != nil { if strings.Contains(err.Error(), "tls: oversized record") || strings.Contains(err.Error(), "malformed HTTP response") { r.Err = fmt.Errorf("error connecting to API URI: %s. Do you have an http/https mismatch?", c.URL) } else { r.Err = err } r.Close() return r } if resp.StatusCode != 200 { ar, err := httpRespToAPIResp(resp) if err != nil { r.Err = err } else { r.Err = errors.New(ar.Meta.Message) } r.Close() return r } // Start watching go func() { reader := bufio.NewReader(resp.Body) defer func() { c.http.Timeout = oldTimeout }() for { select { case <-r.DoneChan: resp.Body.Close() return default: line, _ := reader.ReadBytes('\n') sline := string(line) if sline == "" || sline == "\n" { continue } if strings.HasPrefix(sline, "data:") { sline = strings.TrimPrefix(sline, "data:") line = []byte(sline) } ste := &rbody.StreamedTaskEvent{} err := json.Unmarshal(line, ste) if err != nil { r.Err = err r.Close() return } switch ste.EventType { case rbody.TaskWatchTaskDisabled: r.EventChan <- ste r.Close() case rbody.TaskWatchTaskStopped, rbody.TaskWatchTaskEnded, rbody.TaskWatchTaskStarted, rbody.TaskWatchMetricEvent: r.EventChan <- ste } } } }() return r }
[ "func", "(", "c", "*", "Client", ")", "WatchTask", "(", "id", "string", ")", "*", "WatchTasksResult", "{", "// during watch we don't want to have a timeout", "// Store the old timeout so we can restore when we are through", "oldTimeout", ":=", "c", ".", "http", ".", "Timeout", "\n", "c", ".", "http", ".", "Timeout", "=", "time", ".", "Duration", "(", "0", ")", "\n\n", "r", ":=", "&", "WatchTasksResult", "{", "EventChan", ":", "make", "(", "chan", "*", "rbody", ".", "StreamedTaskEvent", ")", ",", "DoneChan", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "}", "\n\n", "url", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "c", ".", "prefix", ",", "id", ")", "\n", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "\"", "\"", ",", "url", ",", "nil", ")", "\n", "addAuth", "(", "req", ",", "c", ".", "Username", ",", "c", ".", "Password", ")", "\n", "if", "err", "!=", "nil", "{", "r", ".", "Err", "=", "err", "\n", "r", ".", "Close", "(", ")", "\n", "return", "r", "\n", "}", "\n", "resp", ",", "err", ":=", "c", ".", "http", ".", "Do", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "if", "strings", ".", "Contains", "(", "err", ".", "Error", "(", ")", ",", "\"", "\"", ")", "||", "strings", ".", "Contains", "(", "err", ".", "Error", "(", ")", ",", "\"", "\"", ")", "{", "r", ".", "Err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "c", ".", "URL", ")", "\n", "}", "else", "{", "r", ".", "Err", "=", "err", "\n", "}", "\n", "r", ".", "Close", "(", ")", "\n", "return", "r", "\n", "}", "\n\n", "if", "resp", ".", "StatusCode", "!=", "200", "{", "ar", ",", "err", ":=", "httpRespToAPIResp", "(", "resp", ")", "\n", "if", "err", "!=", "nil", "{", "r", ".", "Err", "=", "err", "\n", "}", "else", "{", "r", ".", "Err", "=", "errors", ".", "New", "(", "ar", ".", "Meta", ".", "Message", ")", "\n", "}", "\n", "r", ".", "Close", "(", ")", "\n", "return", "r", "\n", "}", "\n\n", "// Start watching", "go", "func", "(", ")", "{", "reader", ":=", "bufio", ".", "NewReader", "(", "resp", ".", "Body", ")", "\n", "defer", "func", "(", ")", "{", "c", ".", "http", ".", "Timeout", "=", "oldTimeout", "}", "(", ")", "\n", "for", "{", "select", "{", "case", "<-", "r", ".", "DoneChan", ":", "resp", ".", "Body", ".", "Close", "(", ")", "\n", "return", "\n", "default", ":", "line", ",", "_", ":=", "reader", ".", "ReadBytes", "(", "'\\n'", ")", "\n", "sline", ":=", "string", "(", "line", ")", "\n", "if", "sline", "==", "\"", "\"", "||", "sline", "==", "\"", "\\n", "\"", "{", "continue", "\n", "}", "\n", "if", "strings", ".", "HasPrefix", "(", "sline", ",", "\"", "\"", ")", "{", "sline", "=", "strings", ".", "TrimPrefix", "(", "sline", ",", "\"", "\"", ")", "\n", "line", "=", "[", "]", "byte", "(", "sline", ")", "\n", "}", "\n", "ste", ":=", "&", "rbody", ".", "StreamedTaskEvent", "{", "}", "\n", "err", ":=", "json", ".", "Unmarshal", "(", "line", ",", "ste", ")", "\n", "if", "err", "!=", "nil", "{", "r", ".", "Err", "=", "err", "\n", "r", ".", "Close", "(", ")", "\n", "return", "\n", "}", "\n", "switch", "ste", ".", "EventType", "{", "case", "rbody", ".", "TaskWatchTaskDisabled", ":", "r", ".", "EventChan", "<-", "ste", "\n", "r", ".", "Close", "(", ")", "\n", "case", "rbody", ".", "TaskWatchTaskStopped", ",", "rbody", ".", "TaskWatchTaskEnded", ",", "rbody", ".", "TaskWatchTaskStarted", ",", "rbody", ".", "TaskWatchMetricEvent", ":", "r", ".", "EventChan", "<-", "ste", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n", "return", "r", "\n", "}" ]
// WatchTask retrieves running tasks by running a goroutine to // interactive with Event and Done channels. An HTTP GET request retrieves tasks. // StreamedTaskEvent returns if it succeeds. Otherwise, an error is returned.
[ "WatchTask", "retrieves", "running", "tasks", "by", "running", "a", "goroutine", "to", "interactive", "with", "Event", "and", "Done", "channels", ".", "An", "HTTP", "GET", "request", "retrieves", "tasks", ".", "StreamedTaskEvent", "returns", "if", "it", "succeeds", ".", "Otherwise", "an", "error", "is", "returned", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/mgmt/rest/client/task.go#L98-L176
15,372
intelsdi-x/snap
mgmt/rest/client/task.go
GetTasks
func (c *Client) GetTasks() *GetTasksResult { resp, err := c.do("GET", "/tasks", ContentTypeJSON, nil) if err != nil { return &GetTasksResult{Err: err} } switch resp.Meta.Type { case rbody.ScheduledTaskListReturnedType: // Success return &GetTasksResult{resp.Body.(*rbody.ScheduledTaskListReturned), nil} case rbody.ErrorType: return &GetTasksResult{Err: resp.Body.(*rbody.Error)} default: return &GetTasksResult{Err: ErrAPIResponseMetaType} } }
go
func (c *Client) GetTasks() *GetTasksResult { resp, err := c.do("GET", "/tasks", ContentTypeJSON, nil) if err != nil { return &GetTasksResult{Err: err} } switch resp.Meta.Type { case rbody.ScheduledTaskListReturnedType: // Success return &GetTasksResult{resp.Body.(*rbody.ScheduledTaskListReturned), nil} case rbody.ErrorType: return &GetTasksResult{Err: resp.Body.(*rbody.Error)} default: return &GetTasksResult{Err: ErrAPIResponseMetaType} } }
[ "func", "(", "c", "*", "Client", ")", "GetTasks", "(", ")", "*", "GetTasksResult", "{", "resp", ",", "err", ":=", "c", ".", "do", "(", "\"", "\"", ",", "\"", "\"", ",", "ContentTypeJSON", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "&", "GetTasksResult", "{", "Err", ":", "err", "}", "\n", "}", "\n\n", "switch", "resp", ".", "Meta", ".", "Type", "{", "case", "rbody", ".", "ScheduledTaskListReturnedType", ":", "// Success", "return", "&", "GetTasksResult", "{", "resp", ".", "Body", ".", "(", "*", "rbody", ".", "ScheduledTaskListReturned", ")", ",", "nil", "}", "\n", "case", "rbody", ".", "ErrorType", ":", "return", "&", "GetTasksResult", "{", "Err", ":", "resp", ".", "Body", ".", "(", "*", "rbody", ".", "Error", ")", "}", "\n", "default", ":", "return", "&", "GetTasksResult", "{", "Err", ":", "ErrAPIResponseMetaType", "}", "\n", "}", "\n", "}" ]
// GetTasks retrieves a slice of tasks through an HTTP GET call. // A list of scheduled tasks returns if it succeeds. // Otherwise. an error is returned.
[ "GetTasks", "retrieves", "a", "slice", "of", "tasks", "through", "an", "HTTP", "GET", "call", ".", "A", "list", "of", "scheduled", "tasks", "returns", "if", "it", "succeeds", ".", "Otherwise", ".", "an", "error", "is", "returned", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/mgmt/rest/client/task.go#L181-L196
15,373
intelsdi-x/snap
mgmt/rest/client/task.go
GetTask
func (c *Client) GetTask(id string) *GetTaskResult { resp, err := c.do("GET", fmt.Sprintf("/tasks/%v", id), ContentTypeJSON, nil) if err != nil { return &GetTaskResult{Err: err} } switch resp.Meta.Type { case rbody.ScheduledTaskReturnedType: // Success return &GetTaskResult{resp.Body.(*rbody.ScheduledTaskReturned), nil} case rbody.ErrorType: return &GetTaskResult{Err: resp.Body.(*rbody.Error)} default: return &GetTaskResult{Err: ErrAPIResponseMetaType} } }
go
func (c *Client) GetTask(id string) *GetTaskResult { resp, err := c.do("GET", fmt.Sprintf("/tasks/%v", id), ContentTypeJSON, nil) if err != nil { return &GetTaskResult{Err: err} } switch resp.Meta.Type { case rbody.ScheduledTaskReturnedType: // Success return &GetTaskResult{resp.Body.(*rbody.ScheduledTaskReturned), nil} case rbody.ErrorType: return &GetTaskResult{Err: resp.Body.(*rbody.Error)} default: return &GetTaskResult{Err: ErrAPIResponseMetaType} } }
[ "func", "(", "c", "*", "Client", ")", "GetTask", "(", "id", "string", ")", "*", "GetTaskResult", "{", "resp", ",", "err", ":=", "c", ".", "do", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "id", ")", ",", "ContentTypeJSON", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "&", "GetTaskResult", "{", "Err", ":", "err", "}", "\n", "}", "\n", "switch", "resp", ".", "Meta", ".", "Type", "{", "case", "rbody", ".", "ScheduledTaskReturnedType", ":", "// Success", "return", "&", "GetTaskResult", "{", "resp", ".", "Body", ".", "(", "*", "rbody", ".", "ScheduledTaskReturned", ")", ",", "nil", "}", "\n", "case", "rbody", ".", "ErrorType", ":", "return", "&", "GetTaskResult", "{", "Err", ":", "resp", ".", "Body", ".", "(", "*", "rbody", ".", "Error", ")", "}", "\n", "default", ":", "return", "&", "GetTaskResult", "{", "Err", ":", "ErrAPIResponseMetaType", "}", "\n", "}", "\n", "}" ]
// GetTask retrieves the task given a task id through an HTTP GET call. // A scheduled task returns if it succeeds. Otherwise, an error is returned.
[ "GetTask", "retrieves", "the", "task", "given", "a", "task", "id", "through", "an", "HTTP", "GET", "call", ".", "A", "scheduled", "task", "returns", "if", "it", "succeeds", ".", "Otherwise", "an", "error", "is", "returned", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/mgmt/rest/client/task.go#L200-L214
15,374
intelsdi-x/snap
mgmt/rest/client/task.go
StartTask
func (c *Client) StartTask(id string) *StartTasksResult { resp, err := c.do("PUT", fmt.Sprintf("/tasks/%v/start", id), ContentTypeJSON) if err != nil { return &StartTasksResult{Err: err} } switch resp.Meta.Type { case rbody.ScheduledTaskStartedType: // Success return &StartTasksResult{resp.Body.(*rbody.ScheduledTaskStarted), nil} case rbody.ErrorType: return &StartTasksResult{Err: resp.Body.(*rbody.Error)} default: return &StartTasksResult{Err: ErrAPIResponseMetaType} } }
go
func (c *Client) StartTask(id string) *StartTasksResult { resp, err := c.do("PUT", fmt.Sprintf("/tasks/%v/start", id), ContentTypeJSON) if err != nil { return &StartTasksResult{Err: err} } switch resp.Meta.Type { case rbody.ScheduledTaskStartedType: // Success return &StartTasksResult{resp.Body.(*rbody.ScheduledTaskStarted), nil} case rbody.ErrorType: return &StartTasksResult{Err: resp.Body.(*rbody.Error)} default: return &StartTasksResult{Err: ErrAPIResponseMetaType} } }
[ "func", "(", "c", "*", "Client", ")", "StartTask", "(", "id", "string", ")", "*", "StartTasksResult", "{", "resp", ",", "err", ":=", "c", ".", "do", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "id", ")", ",", "ContentTypeJSON", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "&", "StartTasksResult", "{", "Err", ":", "err", "}", "\n", "}", "\n\n", "switch", "resp", ".", "Meta", ".", "Type", "{", "case", "rbody", ".", "ScheduledTaskStartedType", ":", "// Success", "return", "&", "StartTasksResult", "{", "resp", ".", "Body", ".", "(", "*", "rbody", ".", "ScheduledTaskStarted", ")", ",", "nil", "}", "\n", "case", "rbody", ".", "ErrorType", ":", "return", "&", "StartTasksResult", "{", "Err", ":", "resp", ".", "Body", ".", "(", "*", "rbody", ".", "Error", ")", "}", "\n", "default", ":", "return", "&", "StartTasksResult", "{", "Err", ":", "ErrAPIResponseMetaType", "}", "\n", "}", "\n", "}" ]
// StartTask starts a task given a task id. The scheduled task will be in // the started state if it succeeds. Otherwise, an error is returned.
[ "StartTask", "starts", "a", "task", "given", "a", "task", "id", ".", "The", "scheduled", "task", "will", "be", "in", "the", "started", "state", "if", "it", "succeeds", ".", "Otherwise", "an", "error", "is", "returned", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/mgmt/rest/client/task.go#L218-L234
15,375
intelsdi-x/snap
mgmt/rest/client/task.go
StopTask
func (c *Client) StopTask(id string) *StopTasksResult { resp, err := c.do("PUT", fmt.Sprintf("/tasks/%v/stop", id), ContentTypeJSON) if err != nil { return &StopTasksResult{Err: err} } if resp == nil { return nil } switch resp.Meta.Type { case rbody.ScheduledTaskStoppedType: // Success return &StopTasksResult{resp.Body.(*rbody.ScheduledTaskStopped), nil} case rbody.ErrorType: return &StopTasksResult{Err: resp.Body.(*rbody.Error)} default: return &StopTasksResult{Err: ErrAPIResponseMetaType} } }
go
func (c *Client) StopTask(id string) *StopTasksResult { resp, err := c.do("PUT", fmt.Sprintf("/tasks/%v/stop", id), ContentTypeJSON) if err != nil { return &StopTasksResult{Err: err} } if resp == nil { return nil } switch resp.Meta.Type { case rbody.ScheduledTaskStoppedType: // Success return &StopTasksResult{resp.Body.(*rbody.ScheduledTaskStopped), nil} case rbody.ErrorType: return &StopTasksResult{Err: resp.Body.(*rbody.Error)} default: return &StopTasksResult{Err: ErrAPIResponseMetaType} } }
[ "func", "(", "c", "*", "Client", ")", "StopTask", "(", "id", "string", ")", "*", "StopTasksResult", "{", "resp", ",", "err", ":=", "c", ".", "do", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "id", ")", ",", "ContentTypeJSON", ")", "\n", "if", "err", "!=", "nil", "{", "return", "&", "StopTasksResult", "{", "Err", ":", "err", "}", "\n", "}", "\n\n", "if", "resp", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "switch", "resp", ".", "Meta", ".", "Type", "{", "case", "rbody", ".", "ScheduledTaskStoppedType", ":", "// Success", "return", "&", "StopTasksResult", "{", "resp", ".", "Body", ".", "(", "*", "rbody", ".", "ScheduledTaskStopped", ")", ",", "nil", "}", "\n", "case", "rbody", ".", "ErrorType", ":", "return", "&", "StopTasksResult", "{", "Err", ":", "resp", ".", "Body", ".", "(", "*", "rbody", ".", "Error", ")", "}", "\n", "default", ":", "return", "&", "StopTasksResult", "{", "Err", ":", "ErrAPIResponseMetaType", "}", "\n", "}", "\n", "}" ]
// StopTask stops a running task given a task id. It uses an HTTP PUT call. // The stopped task id returns if it succeeds. Otherwise, an error is returned.
[ "StopTask", "stops", "a", "running", "task", "given", "a", "task", "id", ".", "It", "uses", "an", "HTTP", "PUT", "call", ".", "The", "stopped", "task", "id", "returns", "if", "it", "succeeds", ".", "Otherwise", "an", "error", "is", "returned", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/mgmt/rest/client/task.go#L238-L256
15,376
intelsdi-x/snap
mgmt/rest/client/task.go
RemoveTask
func (c *Client) RemoveTask(id string) *RemoveTasksResult { resp, err := c.do("DELETE", fmt.Sprintf("/tasks/%v", id), ContentTypeJSON) if err != nil { return &RemoveTasksResult{Err: err} } switch resp.Meta.Type { case rbody.ScheduledTaskRemovedType: // Success return &RemoveTasksResult{resp.Body.(*rbody.ScheduledTaskRemoved), nil} case rbody.ErrorType: return &RemoveTasksResult{Err: resp.Body.(*rbody.Error)} default: return &RemoveTasksResult{Err: ErrAPIResponseMetaType} } }
go
func (c *Client) RemoveTask(id string) *RemoveTasksResult { resp, err := c.do("DELETE", fmt.Sprintf("/tasks/%v", id), ContentTypeJSON) if err != nil { return &RemoveTasksResult{Err: err} } switch resp.Meta.Type { case rbody.ScheduledTaskRemovedType: // Success return &RemoveTasksResult{resp.Body.(*rbody.ScheduledTaskRemoved), nil} case rbody.ErrorType: return &RemoveTasksResult{Err: resp.Body.(*rbody.Error)} default: return &RemoveTasksResult{Err: ErrAPIResponseMetaType} } }
[ "func", "(", "c", "*", "Client", ")", "RemoveTask", "(", "id", "string", ")", "*", "RemoveTasksResult", "{", "resp", ",", "err", ":=", "c", ".", "do", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "id", ")", ",", "ContentTypeJSON", ")", "\n", "if", "err", "!=", "nil", "{", "return", "&", "RemoveTasksResult", "{", "Err", ":", "err", "}", "\n", "}", "\n\n", "switch", "resp", ".", "Meta", ".", "Type", "{", "case", "rbody", ".", "ScheduledTaskRemovedType", ":", "// Success", "return", "&", "RemoveTasksResult", "{", "resp", ".", "Body", ".", "(", "*", "rbody", ".", "ScheduledTaskRemoved", ")", ",", "nil", "}", "\n", "case", "rbody", ".", "ErrorType", ":", "return", "&", "RemoveTasksResult", "{", "Err", ":", "resp", ".", "Body", ".", "(", "*", "rbody", ".", "Error", ")", "}", "\n", "default", ":", "return", "&", "RemoveTasksResult", "{", "Err", ":", "ErrAPIResponseMetaType", "}", "\n", "}", "\n", "}" ]
// RemoveTask removes a task from the schedule tasks given a task id. It's through an HTTP DELETE call. // The removed task id returns if it succeeds. Otherwise, an error is returned.
[ "RemoveTask", "removes", "a", "task", "from", "the", "schedule", "tasks", "given", "a", "task", "id", ".", "It", "s", "through", "an", "HTTP", "DELETE", "call", ".", "The", "removed", "task", "id", "returns", "if", "it", "succeeds", ".", "Otherwise", "an", "error", "is", "returned", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/mgmt/rest/client/task.go#L260-L275
15,377
intelsdi-x/snap
mgmt/rest/client/task.go
EnableTask
func (c *Client) EnableTask(id string) *EnableTaskResult { resp, err := c.do("PUT", fmt.Sprintf("/tasks/%v/enable", id), ContentTypeJSON) if err != nil { return &EnableTaskResult{Err: err} } switch resp.Meta.Type { case rbody.ScheduledTaskEnabledType: return &EnableTaskResult{resp.Body.(*rbody.ScheduledTaskEnabled), nil} case rbody.ErrorType: return &EnableTaskResult{Err: resp.Body.(*rbody.Error)} default: return &EnableTaskResult{Err: ErrAPIResponseMetaType} } }
go
func (c *Client) EnableTask(id string) *EnableTaskResult { resp, err := c.do("PUT", fmt.Sprintf("/tasks/%v/enable", id), ContentTypeJSON) if err != nil { return &EnableTaskResult{Err: err} } switch resp.Meta.Type { case rbody.ScheduledTaskEnabledType: return &EnableTaskResult{resp.Body.(*rbody.ScheduledTaskEnabled), nil} case rbody.ErrorType: return &EnableTaskResult{Err: resp.Body.(*rbody.Error)} default: return &EnableTaskResult{Err: ErrAPIResponseMetaType} } }
[ "func", "(", "c", "*", "Client", ")", "EnableTask", "(", "id", "string", ")", "*", "EnableTaskResult", "{", "resp", ",", "err", ":=", "c", ".", "do", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "id", ")", ",", "ContentTypeJSON", ")", "\n", "if", "err", "!=", "nil", "{", "return", "&", "EnableTaskResult", "{", "Err", ":", "err", "}", "\n", "}", "\n\n", "switch", "resp", ".", "Meta", ".", "Type", "{", "case", "rbody", ".", "ScheduledTaskEnabledType", ":", "return", "&", "EnableTaskResult", "{", "resp", ".", "Body", ".", "(", "*", "rbody", ".", "ScheduledTaskEnabled", ")", ",", "nil", "}", "\n", "case", "rbody", ".", "ErrorType", ":", "return", "&", "EnableTaskResult", "{", "Err", ":", "resp", ".", "Body", ".", "(", "*", "rbody", ".", "Error", ")", "}", "\n", "default", ":", "return", "&", "EnableTaskResult", "{", "Err", ":", "ErrAPIResponseMetaType", "}", "\n", "}", "\n", "}" ]
// EnableTask enables a disabled task given a task id. The request is an HTTP PUT call. // The enabled task id returns if it succeeds. Otherwise, an error is returned.
[ "EnableTask", "enables", "a", "disabled", "task", "given", "a", "task", "id", ".", "The", "request", "is", "an", "HTTP", "PUT", "call", ".", "The", "enabled", "task", "id", "returns", "if", "it", "succeeds", ".", "Otherwise", "an", "error", "is", "returned", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/mgmt/rest/client/task.go#L279-L293
15,378
intelsdi-x/snap
control/plugin/cpolicy/node.go
UnmarshalJSON
func (c *ConfigPolicyNode) UnmarshalJSON(data []byte) error { m := map[string]interface{}{} decoder := json.NewDecoder(bytes.NewReader(data)) if err := decoder.Decode(&m); err != nil { return err } if rs, ok := m["rules"]; ok { if rules, ok := rs.(map[string]interface{}); ok { addRulesToConfigPolicyNode(rules, c) } } return nil }
go
func (c *ConfigPolicyNode) UnmarshalJSON(data []byte) error { m := map[string]interface{}{} decoder := json.NewDecoder(bytes.NewReader(data)) if err := decoder.Decode(&m); err != nil { return err } if rs, ok := m["rules"]; ok { if rules, ok := rs.(map[string]interface{}); ok { addRulesToConfigPolicyNode(rules, c) } } return nil }
[ "func", "(", "c", "*", "ConfigPolicyNode", ")", "UnmarshalJSON", "(", "data", "[", "]", "byte", ")", "error", "{", "m", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "}", "\n", "decoder", ":=", "json", ".", "NewDecoder", "(", "bytes", ".", "NewReader", "(", "data", ")", ")", "\n", "if", "err", ":=", "decoder", ".", "Decode", "(", "&", "m", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "rs", ",", "ok", ":=", "m", "[", "\"", "\"", "]", ";", "ok", "{", "if", "rules", ",", "ok", ":=", "rs", ".", "(", "map", "[", "string", "]", "interface", "{", "}", ")", ";", "ok", "{", "addRulesToConfigPolicyNode", "(", "rules", ",", "c", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// UnmarshalJSON unmarshals JSON into a ConfigPolicyNode
[ "UnmarshalJSON", "unmarshals", "JSON", "into", "a", "ConfigPolicyNode" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/plugin/cpolicy/node.go#L123-L135
15,379
intelsdi-x/snap
control/plugin/cpolicy/node.go
Add
func (p *ConfigPolicyNode) Add(rules ...Rule) { p.mutex.Lock() defer p.mutex.Unlock() for _, r := range rules { p.rules[r.Key()] = r } }
go
func (p *ConfigPolicyNode) Add(rules ...Rule) { p.mutex.Lock() defer p.mutex.Unlock() for _, r := range rules { p.rules[r.Key()] = r } }
[ "func", "(", "p", "*", "ConfigPolicyNode", ")", "Add", "(", "rules", "...", "Rule", ")", "{", "p", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "mutex", ".", "Unlock", "(", ")", "\n", "for", "_", ",", "r", ":=", "range", "rules", "{", "p", ".", "rules", "[", "r", ".", "Key", "(", ")", "]", "=", "r", "\n", "}", "\n", "}" ]
// Adds a rule to this policy node
[ "Adds", "a", "rule", "to", "this", "policy", "node" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/plugin/cpolicy/node.go#L162-L168
15,380
intelsdi-x/snap
control/plugin/cpolicy/node.go
Process
func (c *ConfigPolicyNode) Process(m map[string]ctypes.ConfigValue) (*map[string]ctypes.ConfigValue, *ProcessingErrors) { c.mutex.Lock() defer c.mutex.Unlock() pErrors := NewProcessingErrors() // Loop through each rule and process for key, rule := range c.rules { // items exists for rule if cv, ok := m[key]; ok { // Validate versus matching data e := rule.Validate(cv) if e != nil { pErrors.AddError(e) } } else { // If it was required add error if rule.Required() { e := fmt.Errorf("required key missing (%s)", key) pErrors.AddError(e) } else { // If default returns we should add it cv := rule.Default() if cv != nil { m[key] = cv } } } } if pErrors.HasErrors() { return nil, pErrors } return &m, pErrors }
go
func (c *ConfigPolicyNode) Process(m map[string]ctypes.ConfigValue) (*map[string]ctypes.ConfigValue, *ProcessingErrors) { c.mutex.Lock() defer c.mutex.Unlock() pErrors := NewProcessingErrors() // Loop through each rule and process for key, rule := range c.rules { // items exists for rule if cv, ok := m[key]; ok { // Validate versus matching data e := rule.Validate(cv) if e != nil { pErrors.AddError(e) } } else { // If it was required add error if rule.Required() { e := fmt.Errorf("required key missing (%s)", key) pErrors.AddError(e) } else { // If default returns we should add it cv := rule.Default() if cv != nil { m[key] = cv } } } } if pErrors.HasErrors() { return nil, pErrors } return &m, pErrors }
[ "func", "(", "c", "*", "ConfigPolicyNode", ")", "Process", "(", "m", "map", "[", "string", "]", "ctypes", ".", "ConfigValue", ")", "(", "*", "map", "[", "string", "]", "ctypes", ".", "ConfigValue", ",", "*", "ProcessingErrors", ")", "{", "c", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mutex", ".", "Unlock", "(", ")", "\n", "pErrors", ":=", "NewProcessingErrors", "(", ")", "\n", "// Loop through each rule and process", "for", "key", ",", "rule", ":=", "range", "c", ".", "rules", "{", "// items exists for rule", "if", "cv", ",", "ok", ":=", "m", "[", "key", "]", ";", "ok", "{", "// Validate versus matching data", "e", ":=", "rule", ".", "Validate", "(", "cv", ")", "\n", "if", "e", "!=", "nil", "{", "pErrors", ".", "AddError", "(", "e", ")", "\n", "}", "\n", "}", "else", "{", "// If it was required add error", "if", "rule", ".", "Required", "(", ")", "{", "e", ":=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "key", ")", "\n", "pErrors", ".", "AddError", "(", "e", ")", "\n", "}", "else", "{", "// If default returns we should add it", "cv", ":=", "rule", ".", "Default", "(", ")", "\n", "if", "cv", "!=", "nil", "{", "m", "[", "key", "]", "=", "cv", "\n", "}", "\n\n", "}", "\n", "}", "\n", "}", "\n\n", "if", "pErrors", ".", "HasErrors", "(", ")", "{", "return", "nil", ",", "pErrors", "\n", "}", "\n", "return", "&", "m", ",", "pErrors", "\n", "}" ]
// Validates and returns a processed policy node or nil and error if validation has failed
[ "Validates", "and", "returns", "a", "processed", "policy", "node", "or", "nil", "and", "error", "if", "validation", "has", "failed" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/plugin/cpolicy/node.go#L219-L252
15,381
intelsdi-x/snap
control/plugin/cpolicy/node.go
addRulesToConfigPolicyNode
func addRulesToConfigPolicyNode(rules map[string]interface{}, cpn *ConfigPolicyNode) error { for k, rule := range rules { if rule, ok := rule.(map[string]interface{}); ok { req, _ := rule["required"].(bool) switch rule["type"] { case "integer": r, _ := NewIntegerRule(k, req) if d, ok := rule["default"]; ok { // json encoding an int results in a float when decoding def_, _ := d.(float64) def := int(def_) r.default_ = &def } if m, ok := rule["minimum"]; ok { min_, _ := m.(float64) min := int(min_) r.minimum = &min } if m, ok := rule["maximum"]; ok { max_, _ := m.(float64) max := int(max_) r.maximum = &max } cpn.Add(r) case "string": r, _ := NewStringRule(k, req) if d, ok := rule["default"]; ok { def, _ := d.(string) if def != "" { r.default_ = &def } } cpn.Add(r) case "bool": r, _ := NewBoolRule(k, req) if d, ok := rule["default"]; ok { def, _ := d.(bool) r.default_ = &def } cpn.Add(r) case "float": r, _ := NewFloatRule(k, req) if d, ok := rule["default"]; ok { def, _ := d.(float64) r.default_ = &def } if m, ok := rule["minimum"]; ok { min, _ := m.(float64) r.minimum = &min } if m, ok := rule["maximum"]; ok { max, _ := m.(float64) r.maximum = &max } cpn.Add(r) default: return errors.New("unknown type") } } } return nil }
go
func addRulesToConfigPolicyNode(rules map[string]interface{}, cpn *ConfigPolicyNode) error { for k, rule := range rules { if rule, ok := rule.(map[string]interface{}); ok { req, _ := rule["required"].(bool) switch rule["type"] { case "integer": r, _ := NewIntegerRule(k, req) if d, ok := rule["default"]; ok { // json encoding an int results in a float when decoding def_, _ := d.(float64) def := int(def_) r.default_ = &def } if m, ok := rule["minimum"]; ok { min_, _ := m.(float64) min := int(min_) r.minimum = &min } if m, ok := rule["maximum"]; ok { max_, _ := m.(float64) max := int(max_) r.maximum = &max } cpn.Add(r) case "string": r, _ := NewStringRule(k, req) if d, ok := rule["default"]; ok { def, _ := d.(string) if def != "" { r.default_ = &def } } cpn.Add(r) case "bool": r, _ := NewBoolRule(k, req) if d, ok := rule["default"]; ok { def, _ := d.(bool) r.default_ = &def } cpn.Add(r) case "float": r, _ := NewFloatRule(k, req) if d, ok := rule["default"]; ok { def, _ := d.(float64) r.default_ = &def } if m, ok := rule["minimum"]; ok { min, _ := m.(float64) r.minimum = &min } if m, ok := rule["maximum"]; ok { max, _ := m.(float64) r.maximum = &max } cpn.Add(r) default: return errors.New("unknown type") } } } return nil }
[ "func", "addRulesToConfigPolicyNode", "(", "rules", "map", "[", "string", "]", "interface", "{", "}", ",", "cpn", "*", "ConfigPolicyNode", ")", "error", "{", "for", "k", ",", "rule", ":=", "range", "rules", "{", "if", "rule", ",", "ok", ":=", "rule", ".", "(", "map", "[", "string", "]", "interface", "{", "}", ")", ";", "ok", "{", "req", ",", "_", ":=", "rule", "[", "\"", "\"", "]", ".", "(", "bool", ")", "\n", "switch", "rule", "[", "\"", "\"", "]", "{", "case", "\"", "\"", ":", "r", ",", "_", ":=", "NewIntegerRule", "(", "k", ",", "req", ")", "\n", "if", "d", ",", "ok", ":=", "rule", "[", "\"", "\"", "]", ";", "ok", "{", "// json encoding an int results in a float when decoding", "def_", ",", "_", ":=", "d", ".", "(", "float64", ")", "\n", "def", ":=", "int", "(", "def_", ")", "\n", "r", ".", "default_", "=", "&", "def", "\n", "}", "\n", "if", "m", ",", "ok", ":=", "rule", "[", "\"", "\"", "]", ";", "ok", "{", "min_", ",", "_", ":=", "m", ".", "(", "float64", ")", "\n", "min", ":=", "int", "(", "min_", ")", "\n", "r", ".", "minimum", "=", "&", "min", "\n", "}", "\n", "if", "m", ",", "ok", ":=", "rule", "[", "\"", "\"", "]", ";", "ok", "{", "max_", ",", "_", ":=", "m", ".", "(", "float64", ")", "\n", "max", ":=", "int", "(", "max_", ")", "\n", "r", ".", "maximum", "=", "&", "max", "\n", "}", "\n", "cpn", ".", "Add", "(", "r", ")", "\n", "case", "\"", "\"", ":", "r", ",", "_", ":=", "NewStringRule", "(", "k", ",", "req", ")", "\n", "if", "d", ",", "ok", ":=", "rule", "[", "\"", "\"", "]", ";", "ok", "{", "def", ",", "_", ":=", "d", ".", "(", "string", ")", "\n", "if", "def", "!=", "\"", "\"", "{", "r", ".", "default_", "=", "&", "def", "\n", "}", "\n", "}", "\n\n", "cpn", ".", "Add", "(", "r", ")", "\n", "case", "\"", "\"", ":", "r", ",", "_", ":=", "NewBoolRule", "(", "k", ",", "req", ")", "\n", "if", "d", ",", "ok", ":=", "rule", "[", "\"", "\"", "]", ";", "ok", "{", "def", ",", "_", ":=", "d", ".", "(", "bool", ")", "\n", "r", ".", "default_", "=", "&", "def", "\n", "}", "\n\n", "cpn", ".", "Add", "(", "r", ")", "\n", "case", "\"", "\"", ":", "r", ",", "_", ":=", "NewFloatRule", "(", "k", ",", "req", ")", "\n", "if", "d", ",", "ok", ":=", "rule", "[", "\"", "\"", "]", ";", "ok", "{", "def", ",", "_", ":=", "d", ".", "(", "float64", ")", "\n", "r", ".", "default_", "=", "&", "def", "\n", "}", "\n", "if", "m", ",", "ok", ":=", "rule", "[", "\"", "\"", "]", ";", "ok", "{", "min", ",", "_", ":=", "m", ".", "(", "float64", ")", "\n", "r", ".", "minimum", "=", "&", "min", "\n", "}", "\n", "if", "m", ",", "ok", ":=", "rule", "[", "\"", "\"", "]", ";", "ok", "{", "max", ",", "_", ":=", "m", ".", "(", "float64", ")", "\n", "r", ".", "maximum", "=", "&", "max", "\n", "}", "\n", "cpn", ".", "Add", "(", "r", ")", "\n", "default", ":", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// addRulesToConfigPolicyNode accepts a map of empty interfaces that will be // marshalled into rules which will be added to the ConfigPolicyNode provided // as the second argument. This function is called used by the UnmarshalJSON // for ConfigPolicy and ConfigPolicyNode.
[ "addRulesToConfigPolicyNode", "accepts", "a", "map", "of", "empty", "interfaces", "that", "will", "be", "marshalled", "into", "rules", "which", "will", "be", "added", "to", "the", "ConfigPolicyNode", "provided", "as", "the", "second", "argument", ".", "This", "function", "is", "called", "used", "by", "the", "UnmarshalJSON", "for", "ConfigPolicy", "and", "ConfigPolicyNode", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/plugin/cpolicy/node.go#L306-L369
15,382
intelsdi-x/snap
control/plugin/plugin.go
SetCertPath
func (a Arg) SetCertPath(certPath string) Arg { a.CertPath = certPath return a }
go
func (a Arg) SetCertPath(certPath string) Arg { a.CertPath = certPath return a }
[ "func", "(", "a", "Arg", ")", "SetCertPath", "(", "certPath", "string", ")", "Arg", "{", "a", ".", "CertPath", "=", "certPath", "\n", "return", "a", "\n", "}" ]
// SetCertPath sets path to TLS certificate in plugin arguments
[ "SetCertPath", "sets", "path", "to", "TLS", "certificate", "in", "plugin", "arguments" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/plugin/plugin.go#L160-L163
15,383
intelsdi-x/snap
control/plugin/plugin.go
SetKeyPath
func (a Arg) SetKeyPath(keyPath string) Arg { a.KeyPath = keyPath return a }
go
func (a Arg) SetKeyPath(keyPath string) Arg { a.KeyPath = keyPath return a }
[ "func", "(", "a", "Arg", ")", "SetKeyPath", "(", "keyPath", "string", ")", "Arg", "{", "a", ".", "KeyPath", "=", "keyPath", "\n", "return", "a", "\n", "}" ]
// SetKeyPath sets path to TLS key in plugin arguments
[ "SetKeyPath", "sets", "path", "to", "TLS", "key", "in", "plugin", "arguments" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/plugin/plugin.go#L166-L169
15,384
intelsdi-x/snap
control/plugin/plugin.go
SetTLSEnabled
func (a Arg) SetTLSEnabled(tlsEnabled bool) Arg { a.TLSEnabled = tlsEnabled return a }
go
func (a Arg) SetTLSEnabled(tlsEnabled bool) Arg { a.TLSEnabled = tlsEnabled return a }
[ "func", "(", "a", "Arg", ")", "SetTLSEnabled", "(", "tlsEnabled", "bool", ")", "Arg", "{", "a", ".", "TLSEnabled", "=", "tlsEnabled", "\n", "return", "a", "\n", "}" ]
// SetTLSEnabled sets flag enabling TLS security in plugin arguments
[ "SetTLSEnabled", "sets", "flag", "enabling", "TLS", "security", "in", "plugin", "arguments" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/plugin/plugin.go#L172-L175
15,385
intelsdi-x/snap
control/plugin/plugin.go
SetCACertPaths
func (a Arg) SetCACertPaths(caCertPaths string) Arg { a.CACertPaths = caCertPaths return a }
go
func (a Arg) SetCACertPaths(caCertPaths string) Arg { a.CACertPaths = caCertPaths return a }
[ "func", "(", "a", "Arg", ")", "SetCACertPaths", "(", "caCertPaths", "string", ")", "Arg", "{", "a", ".", "CACertPaths", "=", "caCertPaths", "\n", "return", "a", "\n", "}" ]
// SetCACertPaths sets list of certificate paths for client verification
[ "SetCACertPaths", "sets", "list", "of", "certificate", "paths", "for", "client", "verification" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/plugin/plugin.go#L178-L181
15,386
intelsdi-x/snap
control/plugin/plugin.go
NewArg
func NewArg(logLevel int, pprof bool) Arg { return Arg{ LogLevel: log.Level(logLevel), PingTimeoutDuration: PingTimeoutDurationDefault, Pprof: pprof, } }
go
func NewArg(logLevel int, pprof bool) Arg { return Arg{ LogLevel: log.Level(logLevel), PingTimeoutDuration: PingTimeoutDurationDefault, Pprof: pprof, } }
[ "func", "NewArg", "(", "logLevel", "int", ",", "pprof", "bool", ")", "Arg", "{", "return", "Arg", "{", "LogLevel", ":", "log", ".", "Level", "(", "logLevel", ")", ",", "PingTimeoutDuration", ":", "PingTimeoutDurationDefault", ",", "Pprof", ":", "pprof", ",", "}", "\n", "}" ]
// NewArg returns new plugin arguments structure
[ "NewArg", "returns", "new", "plugin", "arguments", "structure" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/plugin/plugin.go#L184-L190
15,387
intelsdi-x/snap
pkg/schedule/windowed_schedule.go
NewWindowedSchedule
func NewWindowedSchedule(i time.Duration, start *time.Time, stop *time.Time, count uint) *WindowedSchedule { // if stop and count were both defined, ignore the `count` if count != 0 && stop != nil { count = 0 // log about ignoring the `count` logger.WithFields(log.Fields{ "_block": "NewWindowedSchedule", }).Warning("The window stop timestamp and the count cannot be specified simultaneously. The parameter `count` has been ignored.") } return &WindowedSchedule{ Interval: i, StartTime: start, StopTime: stop, Count: count, } }
go
func NewWindowedSchedule(i time.Duration, start *time.Time, stop *time.Time, count uint) *WindowedSchedule { // if stop and count were both defined, ignore the `count` if count != 0 && stop != nil { count = 0 // log about ignoring the `count` logger.WithFields(log.Fields{ "_block": "NewWindowedSchedule", }).Warning("The window stop timestamp and the count cannot be specified simultaneously. The parameter `count` has been ignored.") } return &WindowedSchedule{ Interval: i, StartTime: start, StopTime: stop, Count: count, } }
[ "func", "NewWindowedSchedule", "(", "i", "time", ".", "Duration", ",", "start", "*", "time", ".", "Time", ",", "stop", "*", "time", ".", "Time", ",", "count", "uint", ")", "*", "WindowedSchedule", "{", "// if stop and count were both defined, ignore the `count`", "if", "count", "!=", "0", "&&", "stop", "!=", "nil", "{", "count", "=", "0", "\n", "// log about ignoring the `count`", "logger", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "\"", "\"", ",", "}", ")", ".", "Warning", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "&", "WindowedSchedule", "{", "Interval", ":", "i", ",", "StartTime", ":", "start", ",", "StopTime", ":", "stop", ",", "Count", ":", "count", ",", "}", "\n", "}" ]
// NewWindowedSchedule returns an instance of WindowedSchedule with given interval, start and stop timestamp // and count of expected runs. The value of `count` determines stop time, so specifying it together with `stop` // is not allowed and the count will be set to defaults 0 in such cases.
[ "NewWindowedSchedule", "returns", "an", "instance", "of", "WindowedSchedule", "with", "given", "interval", "start", "and", "stop", "timestamp", "and", "count", "of", "expected", "runs", ".", "The", "value", "of", "count", "determines", "stop", "time", "so", "specifying", "it", "together", "with", "stop", "is", "not", "allowed", "and", "the", "count", "will", "be", "set", "to", "defaults", "0", "in", "such", "cases", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/pkg/schedule/windowed_schedule.go#L45-L61
15,388
intelsdi-x/snap
pkg/schedule/windowed_schedule.go
setStopOnTime
func (w *WindowedSchedule) setStopOnTime() { if w.StopTime == nil && w.Count != 0 { // determine the window stop based on the `count` and `interval` var newStop time.Time // if start is not set or points in the past, // use the current time to calculate stopOnTime if w.StartTime != nil && time.Now().Before(*w.StartTime) { newStop = w.StartTime.Add(time.Duration(w.Count) * w.Interval) } else { // set a new stop timestamp from this point in time newStop = time.Now().Add(time.Duration(w.Count) * w.Interval) } // set calculated new stop w.stopOnTime = &newStop return } // stopOnTime is determined by StopTime w.stopOnTime = w.StopTime }
go
func (w *WindowedSchedule) setStopOnTime() { if w.StopTime == nil && w.Count != 0 { // determine the window stop based on the `count` and `interval` var newStop time.Time // if start is not set or points in the past, // use the current time to calculate stopOnTime if w.StartTime != nil && time.Now().Before(*w.StartTime) { newStop = w.StartTime.Add(time.Duration(w.Count) * w.Interval) } else { // set a new stop timestamp from this point in time newStop = time.Now().Add(time.Duration(w.Count) * w.Interval) } // set calculated new stop w.stopOnTime = &newStop return } // stopOnTime is determined by StopTime w.stopOnTime = w.StopTime }
[ "func", "(", "w", "*", "WindowedSchedule", ")", "setStopOnTime", "(", ")", "{", "if", "w", ".", "StopTime", "==", "nil", "&&", "w", ".", "Count", "!=", "0", "{", "// determine the window stop based on the `count` and `interval`", "var", "newStop", "time", ".", "Time", "\n\n", "// if start is not set or points in the past,", "// use the current time to calculate stopOnTime", "if", "w", ".", "StartTime", "!=", "nil", "&&", "time", ".", "Now", "(", ")", ".", "Before", "(", "*", "w", ".", "StartTime", ")", "{", "newStop", "=", "w", ".", "StartTime", ".", "Add", "(", "time", ".", "Duration", "(", "w", ".", "Count", ")", "*", "w", ".", "Interval", ")", "\n", "}", "else", "{", "// set a new stop timestamp from this point in time", "newStop", "=", "time", ".", "Now", "(", ")", ".", "Add", "(", "time", ".", "Duration", "(", "w", ".", "Count", ")", "*", "w", ".", "Interval", ")", "\n", "}", "\n", "// set calculated new stop", "w", ".", "stopOnTime", "=", "&", "newStop", "\n", "return", "\n", "}", "\n\n", "// stopOnTime is determined by StopTime", "w", ".", "stopOnTime", "=", "w", ".", "StopTime", "\n", "}" ]
// setStopOnTime calculates and set the value of the windowed `stopOnTime` which is the right window boundary. // `stopOnTime` is determined by `StopTime` or, if it is not provided, calculated based on count and interval.
[ "setStopOnTime", "calculates", "and", "set", "the", "value", "of", "the", "windowed", "stopOnTime", "which", "is", "the", "right", "window", "boundary", ".", "stopOnTime", "is", "determined", "by", "StopTime", "or", "if", "it", "is", "not", "provided", "calculated", "based", "on", "count", "and", "interval", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/pkg/schedule/windowed_schedule.go#L65-L85
15,389
intelsdi-x/snap
pkg/schedule/windowed_schedule.go
Validate
func (w *WindowedSchedule) Validate() error { // if the stop time was set but it is in the past, return an error if w.StopTime != nil && time.Now().After(*w.StopTime) { return ErrInvalidStopTime } // if the start and stop time were both set and the stop time is before // the start time, return an error if w.StopTime != nil && w.StartTime != nil && w.StopTime.Before(*w.StartTime) { return ErrStopBeforeStart } // if the interval is less than zero, return an error if w.Interval <= 0 { return ErrInvalidInterval } // the schedule passed validation, set as active w.state = Active return nil }
go
func (w *WindowedSchedule) Validate() error { // if the stop time was set but it is in the past, return an error if w.StopTime != nil && time.Now().After(*w.StopTime) { return ErrInvalidStopTime } // if the start and stop time were both set and the stop time is before // the start time, return an error if w.StopTime != nil && w.StartTime != nil && w.StopTime.Before(*w.StartTime) { return ErrStopBeforeStart } // if the interval is less than zero, return an error if w.Interval <= 0 { return ErrInvalidInterval } // the schedule passed validation, set as active w.state = Active return nil }
[ "func", "(", "w", "*", "WindowedSchedule", ")", "Validate", "(", ")", "error", "{", "// if the stop time was set but it is in the past, return an error", "if", "w", ".", "StopTime", "!=", "nil", "&&", "time", ".", "Now", "(", ")", ".", "After", "(", "*", "w", ".", "StopTime", ")", "{", "return", "ErrInvalidStopTime", "\n", "}", "\n\n", "// if the start and stop time were both set and the stop time is before", "// the start time, return an error", "if", "w", ".", "StopTime", "!=", "nil", "&&", "w", ".", "StartTime", "!=", "nil", "&&", "w", ".", "StopTime", ".", "Before", "(", "*", "w", ".", "StartTime", ")", "{", "return", "ErrStopBeforeStart", "\n", "}", "\n", "// if the interval is less than zero, return an error", "if", "w", ".", "Interval", "<=", "0", "{", "return", "ErrInvalidInterval", "\n", "}", "\n\n", "// the schedule passed validation, set as active", "w", ".", "state", "=", "Active", "\n", "return", "nil", "\n", "}" ]
// Validate validates the start, stop and duration interval of WindowedSchedule
[ "Validate", "validates", "the", "start", "stop", "and", "duration", "interval", "of", "WindowedSchedule" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/pkg/schedule/windowed_schedule.go#L93-L112
15,390
intelsdi-x/snap
pkg/schedule/windowed_schedule.go
Wait
func (w *WindowedSchedule) Wait(last time.Time) Response { // If within the window we wait our interval and return // otherwise we exit with a completed state. var m uint if (last == time.Time{}) { // the first waiting in cycles, so // set the `stopOnTime` determining the right-window boundary w.setStopOnTime() } // Do we even have a specific start time? if w.StartTime != nil { // Wait till it is time to start if before the window start if time.Now().Before(*w.StartTime) { wait := w.StartTime.Sub(time.Now()) logger.WithFields(log.Fields{ "_block": "windowed-wait", "sleep-duration": wait, }).Debug("Waiting for window to start") time.Sleep(wait) } } // Do we even have a stop time? if w.stopOnTime != nil { if time.Now().Before(*w.stopOnTime) { logger.WithFields(log.Fields{ "_block": "windowed-wait", "time-before-stop": w.stopOnTime.Sub(time.Now()), }).Debug("Within window, calling interval") m, _ = waitOnInterval(last, w.Interval) // check if the schedule should be ended after waiting on interval if time.Now().After(*w.stopOnTime) { logger.WithFields(log.Fields{ "_block": "windowed-wait", }).Debug("schedule has ended") w.state = Ended } } else { logger.WithFields(log.Fields{ "_block": "windowed-wait", }).Debug("schedule has ended") w.state = Ended m = 0 } } else { // This has no end like a simple schedule m, _ = waitOnInterval(last, w.Interval) } return &WindowedScheduleResponse{ state: w.GetState(), missed: m, lastTime: time.Now(), } }
go
func (w *WindowedSchedule) Wait(last time.Time) Response { // If within the window we wait our interval and return // otherwise we exit with a completed state. var m uint if (last == time.Time{}) { // the first waiting in cycles, so // set the `stopOnTime` determining the right-window boundary w.setStopOnTime() } // Do we even have a specific start time? if w.StartTime != nil { // Wait till it is time to start if before the window start if time.Now().Before(*w.StartTime) { wait := w.StartTime.Sub(time.Now()) logger.WithFields(log.Fields{ "_block": "windowed-wait", "sleep-duration": wait, }).Debug("Waiting for window to start") time.Sleep(wait) } } // Do we even have a stop time? if w.stopOnTime != nil { if time.Now().Before(*w.stopOnTime) { logger.WithFields(log.Fields{ "_block": "windowed-wait", "time-before-stop": w.stopOnTime.Sub(time.Now()), }).Debug("Within window, calling interval") m, _ = waitOnInterval(last, w.Interval) // check if the schedule should be ended after waiting on interval if time.Now().After(*w.stopOnTime) { logger.WithFields(log.Fields{ "_block": "windowed-wait", }).Debug("schedule has ended") w.state = Ended } } else { logger.WithFields(log.Fields{ "_block": "windowed-wait", }).Debug("schedule has ended") w.state = Ended m = 0 } } else { // This has no end like a simple schedule m, _ = waitOnInterval(last, w.Interval) } return &WindowedScheduleResponse{ state: w.GetState(), missed: m, lastTime: time.Now(), } }
[ "func", "(", "w", "*", "WindowedSchedule", ")", "Wait", "(", "last", "time", ".", "Time", ")", "Response", "{", "// If within the window we wait our interval and return", "// otherwise we exit with a completed state.", "var", "m", "uint", "\n\n", "if", "(", "last", "==", "time", ".", "Time", "{", "}", ")", "{", "// the first waiting in cycles, so", "// set the `stopOnTime` determining the right-window boundary", "w", ".", "setStopOnTime", "(", ")", "\n", "}", "\n\n", "// Do we even have a specific start time?", "if", "w", ".", "StartTime", "!=", "nil", "{", "// Wait till it is time to start if before the window start", "if", "time", ".", "Now", "(", ")", ".", "Before", "(", "*", "w", ".", "StartTime", ")", "{", "wait", ":=", "w", ".", "StartTime", ".", "Sub", "(", "time", ".", "Now", "(", ")", ")", "\n", "logger", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "wait", ",", "}", ")", ".", "Debug", "(", "\"", "\"", ")", "\n", "time", ".", "Sleep", "(", "wait", ")", "\n", "}", "\n", "}", "\n\n", "// Do we even have a stop time?", "if", "w", ".", "stopOnTime", "!=", "nil", "{", "if", "time", ".", "Now", "(", ")", ".", "Before", "(", "*", "w", ".", "stopOnTime", ")", "{", "logger", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "w", ".", "stopOnTime", ".", "Sub", "(", "time", ".", "Now", "(", ")", ")", ",", "}", ")", ".", "Debug", "(", "\"", "\"", ")", "\n\n", "m", ",", "_", "=", "waitOnInterval", "(", "last", ",", "w", ".", "Interval", ")", "\n\n", "// check if the schedule should be ended after waiting on interval", "if", "time", ".", "Now", "(", ")", ".", "After", "(", "*", "w", ".", "stopOnTime", ")", "{", "logger", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "\"", "\"", ",", "}", ")", ".", "Debug", "(", "\"", "\"", ")", "\n", "w", ".", "state", "=", "Ended", "\n", "}", "\n", "}", "else", "{", "logger", ".", "WithFields", "(", "log", ".", "Fields", "{", "\"", "\"", ":", "\"", "\"", ",", "}", ")", ".", "Debug", "(", "\"", "\"", ")", "\n", "w", ".", "state", "=", "Ended", "\n", "m", "=", "0", "\n", "}", "\n", "}", "else", "{", "// This has no end like a simple schedule", "m", ",", "_", "=", "waitOnInterval", "(", "last", ",", "w", ".", "Interval", ")", "\n\n", "}", "\n", "return", "&", "WindowedScheduleResponse", "{", "state", ":", "w", ".", "GetState", "(", ")", ",", "missed", ":", "m", ",", "lastTime", ":", "time", ".", "Now", "(", ")", ",", "}", "\n", "}" ]
// Wait waits the window interval and return. // Otherwise, it exits with a completed state
[ "Wait", "waits", "the", "window", "interval", "and", "return", ".", "Otherwise", "it", "exits", "with", "a", "completed", "state" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/pkg/schedule/windowed_schedule.go#L116-L174
15,391
intelsdi-x/snap
pkg/netutil/net.go
GetIP
func GetIP() string { ifaces, err := net.Interfaces() if err != nil { return "127.0.0.1" } for _, i := range ifaces { addrs, err := i.Addrs() if err != nil { return "127.0.0.1" } for _, addr := range addrs { var ip net.IP switch v := addr.(type) { case *net.IPAddr: ip = v.IP case *net.IPNet: ip = v.IP } if ip == nil || ip.IsLoopback() { continue } ip = ip.To4() if ip == nil { continue // not an ipv4 address } return ip.String() } } return "127.0.0.1" }
go
func GetIP() string { ifaces, err := net.Interfaces() if err != nil { return "127.0.0.1" } for _, i := range ifaces { addrs, err := i.Addrs() if err != nil { return "127.0.0.1" } for _, addr := range addrs { var ip net.IP switch v := addr.(type) { case *net.IPAddr: ip = v.IP case *net.IPNet: ip = v.IP } if ip == nil || ip.IsLoopback() { continue } ip = ip.To4() if ip == nil { continue // not an ipv4 address } return ip.String() } } return "127.0.0.1" }
[ "func", "GetIP", "(", ")", "string", "{", "ifaces", ",", "err", ":=", "net", ".", "Interfaces", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", "\n", "}", "\n", "for", "_", ",", "i", ":=", "range", "ifaces", "{", "addrs", ",", "err", ":=", "i", ".", "Addrs", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", "\n", "}", "\n", "for", "_", ",", "addr", ":=", "range", "addrs", "{", "var", "ip", "net", ".", "IP", "\n", "switch", "v", ":=", "addr", ".", "(", "type", ")", "{", "case", "*", "net", ".", "IPAddr", ":", "ip", "=", "v", ".", "IP", "\n", "case", "*", "net", ".", "IPNet", ":", "ip", "=", "v", ".", "IP", "\n", "}", "\n", "if", "ip", "==", "nil", "||", "ip", ".", "IsLoopback", "(", ")", "{", "continue", "\n", "}", "\n", "ip", "=", "ip", ".", "To4", "(", ")", "\n", "if", "ip", "==", "nil", "{", "continue", "// not an ipv4 address", "\n", "}", "\n", "return", "ip", ".", "String", "(", ")", "\n", "}", "\n", "}", "\n", "return", "\"", "\"", "\n", "}" ]
// GetIP returns the first non-loopback ipv4 interface. The loopback interface // is returned if no other interface is present.
[ "GetIP", "returns", "the", "first", "non", "-", "loopback", "ipv4", "interface", ".", "The", "loopback", "interface", "is", "returned", "if", "no", "other", "interface", "is", "present", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/pkg/netutil/net.go#L26-L55
15,392
intelsdi-x/snap
control/plugin_manager.go
add
func (l *loadedPlugins) add(lp *loadedPlugin) serror.SnapError { l.Lock() defer l.Unlock() if _, exists := l.table[lp.Key()]; exists { return serror.New(ErrPluginAlreadyLoaded, map[string]interface{}{ "plugin-name": lp.Meta.Name, "plugin-version": lp.Meta.Version, "plugin-type": lp.Type.String(), }) } l.table[lp.Key()] = lp return nil }
go
func (l *loadedPlugins) add(lp *loadedPlugin) serror.SnapError { l.Lock() defer l.Unlock() if _, exists := l.table[lp.Key()]; exists { return serror.New(ErrPluginAlreadyLoaded, map[string]interface{}{ "plugin-name": lp.Meta.Name, "plugin-version": lp.Meta.Version, "plugin-type": lp.Type.String(), }) } l.table[lp.Key()] = lp return nil }
[ "func", "(", "l", "*", "loadedPlugins", ")", "add", "(", "lp", "*", "loadedPlugin", ")", "serror", ".", "SnapError", "{", "l", ".", "Lock", "(", ")", "\n", "defer", "l", ".", "Unlock", "(", ")", "\n\n", "if", "_", ",", "exists", ":=", "l", ".", "table", "[", "lp", ".", "Key", "(", ")", "]", ";", "exists", "{", "return", "serror", ".", "New", "(", "ErrPluginAlreadyLoaded", ",", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "lp", ".", "Meta", ".", "Name", ",", "\"", "\"", ":", "lp", ".", "Meta", ".", "Version", ",", "\"", "\"", ":", "lp", ".", "Type", ".", "String", "(", ")", ",", "}", ")", "\n", "}", "\n", "l", ".", "table", "[", "lp", ".", "Key", "(", ")", "]", "=", "lp", "\n", "return", "nil", "\n", "}" ]
// add adds a loadedPlugin pointer to the table
[ "add", "adds", "a", "loadedPlugin", "pointer", "to", "the", "table" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/plugin_manager.go#L103-L116
15,393
intelsdi-x/snap
control/plugin_manager.go
get
func (l *loadedPlugins) get(key string) (*loadedPlugin, error) { l.RLock() defer l.RUnlock() lp, ok := l.table[key] if !ok { tnv := strings.Split(key, core.Separator) if len(tnv) != 3 { return nil, ErrBadKey } v, err := strconv.Atoi(tnv[2]) if err != nil { return nil, ErrBadKey } if v < 1 { pmLogger.Info("finding latest plugin") return l.findLatest(tnv[0], tnv[1]) } return nil, ErrPluginNotFound } return lp, nil }
go
func (l *loadedPlugins) get(key string) (*loadedPlugin, error) { l.RLock() defer l.RUnlock() lp, ok := l.table[key] if !ok { tnv := strings.Split(key, core.Separator) if len(tnv) != 3 { return nil, ErrBadKey } v, err := strconv.Atoi(tnv[2]) if err != nil { return nil, ErrBadKey } if v < 1 { pmLogger.Info("finding latest plugin") return l.findLatest(tnv[0], tnv[1]) } return nil, ErrPluginNotFound } return lp, nil }
[ "func", "(", "l", "*", "loadedPlugins", ")", "get", "(", "key", "string", ")", "(", "*", "loadedPlugin", ",", "error", ")", "{", "l", ".", "RLock", "(", ")", "\n", "defer", "l", ".", "RUnlock", "(", ")", "\n\n", "lp", ",", "ok", ":=", "l", ".", "table", "[", "key", "]", "\n", "if", "!", "ok", "{", "tnv", ":=", "strings", ".", "Split", "(", "key", ",", "core", ".", "Separator", ")", "\n", "if", "len", "(", "tnv", ")", "!=", "3", "{", "return", "nil", ",", "ErrBadKey", "\n", "}", "\n\n", "v", ",", "err", ":=", "strconv", ".", "Atoi", "(", "tnv", "[", "2", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "ErrBadKey", "\n", "}", "\n", "if", "v", "<", "1", "{", "pmLogger", ".", "Info", "(", "\"", "\"", ")", "\n", "return", "l", ".", "findLatest", "(", "tnv", "[", "0", "]", ",", "tnv", "[", "1", "]", ")", "\n", "}", "\n", "return", "nil", ",", "ErrPluginNotFound", "\n", "}", "\n", "return", "lp", ",", "nil", "\n", "}" ]
// get retrieves a plugin from the table
[ "get", "retrieves", "a", "plugin", "from", "the", "table" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/plugin_manager.go#L119-L141
15,394
intelsdi-x/snap
control/plugin_manager.go
Key
func (lp *loadedPlugin) Key() string { return fmt.Sprintf("%s"+core.Separator+"%s"+core.Separator+"%d", lp.TypeName(), lp.Name(), lp.Version()) }
go
func (lp *loadedPlugin) Key() string { return fmt.Sprintf("%s"+core.Separator+"%s"+core.Separator+"%d", lp.TypeName(), lp.Name(), lp.Version()) }
[ "func", "(", "lp", "*", "loadedPlugin", ")", "Key", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "core", ".", "Separator", "+", "\"", "\"", "+", "core", ".", "Separator", "+", "\"", "\"", ",", "lp", ".", "TypeName", "(", ")", ",", "lp", ".", "Name", "(", ")", ",", "lp", ".", "Version", "(", ")", ")", "\n", "}" ]
// Key returns plugin type, name and version
[ "Key", "returns", "plugin", "type", "name", "and", "version" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/plugin_manager.go#L213-L215
15,395
intelsdi-x/snap
control/plugin_manager.go
OptEnableManagerTLS
func OptEnableManagerTLS(grpcSecurity client.GRPCSecurity) pluginManagerOpt { return func(p *pluginManager) { p.grpcSecurity = grpcSecurity } }
go
func OptEnableManagerTLS(grpcSecurity client.GRPCSecurity) pluginManagerOpt { return func(p *pluginManager) { p.grpcSecurity = grpcSecurity } }
[ "func", "OptEnableManagerTLS", "(", "grpcSecurity", "client", ".", "GRPCSecurity", ")", "pluginManagerOpt", "{", "return", "func", "(", "p", "*", "pluginManager", ")", "{", "p", ".", "grpcSecurity", "=", "grpcSecurity", "\n", "}", "\n", "}" ]
// OptEnableManagerTLS enables the TLS configuration in plugin manager.
[ "OptEnableManagerTLS", "enables", "the", "TLS", "configuration", "in", "plugin", "manager", "." ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/plugin_manager.go#L303-L307
15,396
intelsdi-x/snap
control/plugin_manager.go
OptSetPluginTags
func OptSetPluginTags(tags map[string]map[string]string) pluginManagerOpt { return func(p *pluginManager) { p.pluginTags = tags } }
go
func OptSetPluginTags(tags map[string]map[string]string) pluginManagerOpt { return func(p *pluginManager) { p.pluginTags = tags } }
[ "func", "OptSetPluginTags", "(", "tags", "map", "[", "string", "]", "map", "[", "string", "]", "string", ")", "pluginManagerOpt", "{", "return", "func", "(", "p", "*", "pluginManager", ")", "{", "p", ".", "pluginTags", "=", "tags", "\n", "}", "\n", "}" ]
// OptSetPluginTags sets the tags on the plugin manager
[ "OptSetPluginTags", "sets", "the", "tags", "on", "the", "plugin", "manager" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/plugin_manager.go#L317-L321
15,397
intelsdi-x/snap
control/plugin_manager.go
SetPluginTags
func (p *pluginManager) SetPluginTags(tags map[string]map[string]string) { p.pluginTags = tags }
go
func (p *pluginManager) SetPluginTags(tags map[string]map[string]string) { p.pluginTags = tags }
[ "func", "(", "p", "*", "pluginManager", ")", "SetPluginTags", "(", "tags", "map", "[", "string", "]", "map", "[", "string", "]", "string", ")", "{", "p", ".", "pluginTags", "=", "tags", "\n", "}" ]
// SetPluginTags sets plugin tags
[ "SetPluginTags", "sets", "plugin", "tags" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/plugin_manager.go#L345-L347
15,398
intelsdi-x/snap
control/plugin_manager.go
GenerateArgs
func (p *pluginManager) GenerateArgs(logLevel int) plugin.Arg { return plugin.NewArg(logLevel, p.pprof) }
go
func (p *pluginManager) GenerateArgs(logLevel int) plugin.Arg { return plugin.NewArg(logLevel, p.pprof) }
[ "func", "(", "p", "*", "pluginManager", ")", "GenerateArgs", "(", "logLevel", "int", ")", "plugin", ".", "Arg", "{", "return", "plugin", ".", "NewArg", "(", "logLevel", ",", "p", ".", "pprof", ")", "\n", "}" ]
// GenerateArgs generates the cli args to send when stating a plugin
[ "GenerateArgs", "generates", "the", "cli", "args", "to", "send", "when", "stating", "a", "plugin" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/control/plugin_manager.go#L764-L766
15,399
intelsdi-x/snap
mgmt/rest/server.go
New
func New(cfg *Config) (*Server, error) { // pull a few parameters from the configuration passed in by snapteld s := &Server{ err: make(chan error), killChan: make(chan struct{}), addrString: cfg.Address, pprof: cfg.Pprof, } if cfg.HTTPS { var err error s.snapTLS, err = newtls(cfg.RestCertificate, cfg.RestKey) if err != nil { return nil, err } protocolPrefix = "https" } restLogger.Info(fmt.Sprintf("Configuring REST API with HTTPS set to: %v", cfg.HTTPS)) s.apis = []api.API{ v1.New(&s.wg, s.killChan, protocolPrefix), v2.New(&s.wg, s.killChan, protocolPrefix), } s.n = negroni.New( NewLogger(), negroni.NewRecovery(), negroni.HandlerFunc(s.authMiddleware), ) s.r = httprouter.New() // CORS has to be turned on explicitly in the global config. // Otherwise, it defauts to the same origin. origins, err := s.getAllowedOrigins(cfg.Corsd) if err != nil { return nil, err } if len(origins) > 0 { c := cors.New(cors.Options{ AllowedOrigins: origins, AllowedMethods: []string{allowedMethods}, AllowedHeaders: []string{allowedHeaders}, MaxAge: maxAge, }) s.n.Use(c) } // Use negroni to handle routes s.n.UseHandler(s.r) return s, nil }
go
func New(cfg *Config) (*Server, error) { // pull a few parameters from the configuration passed in by snapteld s := &Server{ err: make(chan error), killChan: make(chan struct{}), addrString: cfg.Address, pprof: cfg.Pprof, } if cfg.HTTPS { var err error s.snapTLS, err = newtls(cfg.RestCertificate, cfg.RestKey) if err != nil { return nil, err } protocolPrefix = "https" } restLogger.Info(fmt.Sprintf("Configuring REST API with HTTPS set to: %v", cfg.HTTPS)) s.apis = []api.API{ v1.New(&s.wg, s.killChan, protocolPrefix), v2.New(&s.wg, s.killChan, protocolPrefix), } s.n = negroni.New( NewLogger(), negroni.NewRecovery(), negroni.HandlerFunc(s.authMiddleware), ) s.r = httprouter.New() // CORS has to be turned on explicitly in the global config. // Otherwise, it defauts to the same origin. origins, err := s.getAllowedOrigins(cfg.Corsd) if err != nil { return nil, err } if len(origins) > 0 { c := cors.New(cors.Options{ AllowedOrigins: origins, AllowedMethods: []string{allowedMethods}, AllowedHeaders: []string{allowedHeaders}, MaxAge: maxAge, }) s.n.Use(c) } // Use negroni to handle routes s.n.UseHandler(s.r) return s, nil }
[ "func", "New", "(", "cfg", "*", "Config", ")", "(", "*", "Server", ",", "error", ")", "{", "// pull a few parameters from the configuration passed in by snapteld", "s", ":=", "&", "Server", "{", "err", ":", "make", "(", "chan", "error", ")", ",", "killChan", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "addrString", ":", "cfg", ".", "Address", ",", "pprof", ":", "cfg", ".", "Pprof", ",", "}", "\n", "if", "cfg", ".", "HTTPS", "{", "var", "err", "error", "\n", "s", ".", "snapTLS", ",", "err", "=", "newtls", "(", "cfg", ".", "RestCertificate", ",", "cfg", ".", "RestKey", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "protocolPrefix", "=", "\"", "\"", "\n", "}", "\n", "restLogger", ".", "Info", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "cfg", ".", "HTTPS", ")", ")", "\n\n", "s", ".", "apis", "=", "[", "]", "api", ".", "API", "{", "v1", ".", "New", "(", "&", "s", ".", "wg", ",", "s", ".", "killChan", ",", "protocolPrefix", ")", ",", "v2", ".", "New", "(", "&", "s", ".", "wg", ",", "s", ".", "killChan", ",", "protocolPrefix", ")", ",", "}", "\n\n", "s", ".", "n", "=", "negroni", ".", "New", "(", "NewLogger", "(", ")", ",", "negroni", ".", "NewRecovery", "(", ")", ",", "negroni", ".", "HandlerFunc", "(", "s", ".", "authMiddleware", ")", ",", ")", "\n", "s", ".", "r", "=", "httprouter", ".", "New", "(", ")", "\n\n", "// CORS has to be turned on explicitly in the global config.", "// Otherwise, it defauts to the same origin.", "origins", ",", "err", ":=", "s", ".", "getAllowedOrigins", "(", "cfg", ".", "Corsd", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "origins", ")", ">", "0", "{", "c", ":=", "cors", ".", "New", "(", "cors", ".", "Options", "{", "AllowedOrigins", ":", "origins", ",", "AllowedMethods", ":", "[", "]", "string", "{", "allowedMethods", "}", ",", "AllowedHeaders", ":", "[", "]", "string", "{", "allowedHeaders", "}", ",", "MaxAge", ":", "maxAge", ",", "}", ")", "\n", "s", ".", "n", ".", "Use", "(", "c", ")", "\n", "}", "\n\n", "// Use negroni to handle routes", "s", ".", "n", ".", "UseHandler", "(", "s", ".", "r", ")", "\n", "return", "s", ",", "nil", "\n", "}" ]
// New creates a REST API server with a given config
[ "New", "creates", "a", "REST", "API", "server", "with", "a", "given", "config" ]
e3a6c8e39994b3980df0c7b069d5ede810622952
https://github.com/intelsdi-x/snap/blob/e3a6c8e39994b3980df0c7b069d5ede810622952/mgmt/rest/server.go#L78-L127