idx int64 0 41.8k | question stringlengths 65 3.39k | target stringlengths 10 1.09k |
|---|---|---|
200 | func GetDefaultConfig ( ) * Config { return & Config { Enable : defaultEnable , Port : defaultPort , Address : defaultAddress , HTTPS : defaultHTTPS , RestCertificate : defaultRestCertificate , RestKey : defaultRestKey , RestAuth : defaultAuth , RestAuthPassword : defaultAuthPassword , portSetByConfig : defaultPortSetB... | GetDefaultConfig gets the default snapteld configuration |
201 | func TaskDeadlineDuration ( v time . Duration ) TaskOption { return func ( t Task ) TaskOption { previous := t . DeadlineDuration ( )
t . SetDeadlineDuration ( v )
log . WithFields ( log . Fields { "_module" : "core" , "_block" : "TaskDeadlineDuration" , "task-id" : t . ID ( ) , "task-name" : t . GetName ( ) , "tas... | TaskDeadlineDuration sets the tasks deadline . The deadline is the amount of time that can pass before a worker begins processing the tasks collect job . |
202 | func OptionStopOnFailure ( v int ) TaskOption { return func ( t Task ) TaskOption { previous := t . GetStopOnFailure ( )
t . SetStopOnFailure ( v )
log . WithFields ( log . Fields { "_module" : "core" , "_block" : "OptionStopOnFailure" , "task-id" : t . ID ( ) , "task-name" : t . GetName ( ) , "consecutive failure ... | TaskStopOnFailure sets the tasks stopOnFailure The stopOnFailure is the number of consecutive task failures that will trigger disabling the task |
203 | func CacheExpiration ( t time . Duration ) PluginControlOpt { return func ( c * pluginControl ) { strategy . GlobalCacheExpiration = t
}
} | CacheExpiration is the PluginControlOpt which sets the global metric cache TTL |
204 | func OptSetConfig ( cfg * Config ) PluginControlOpt { return func ( c * pluginControl ) { c . Config = cfg
c . pluginManager . SetPluginConfig ( cfg . Plugins )
c . pluginManager . SetPluginLoadTimeout ( c . Config . PluginLoadTimeout )
c . pluginRunner . SetPluginLoadTimeout ( c . Config . PluginLoadTimeout )
... | OptSetConfig sets the plugin control configuration . |
205 | func OptSetTags ( tags map [ string ] map [ string ] string ) PluginControlOpt { return func ( c * pluginControl ) { c . pluginManager . SetPluginTags ( tags )
}
} | OptSetTags sets the plugin control tags . |
206 | func New ( cfg * Config ) * pluginControl { opts := [ ] PluginControlOpt { MaxRunningPlugins ( cfg . MaxRunningPlugins ) , CacheExpiration ( cfg . CacheExpiration . Duration ) , OptSetConfig ( cfg ) , OptSetTags ( cfg . Tags ) , MaxPluginRestarts ( cfg ) , }
c := & pluginControl { }
c . Config = cfg
c . eventMana... | New returns a new pluginControl instance |
207 | func ( p * pluginControl ) Load ( rp * core . RequestedPlugin ) ( core . CatalogedPlugin , serror . SnapError ) { f := map [ string ] interface { } { "_block" : "load" , }
details , serr := p . returnPluginDetails ( rp )
if serr != nil { return nil , serr
}
if details . IsPackage { defer os . RemoveAll ( filepa... | Load is the public method to load a plugin into the LoadedPlugins array and issue an event when successful . |
208 | func ( p * pluginControl ) SubscribeDeps ( id string , requested [ ] core . RequestedMetric , plugins [ ] core . SubscribedPlugin , configTree * cdata . ConfigDataTree ) ( serrs [ ] serror . SnapError ) { return p . subscriptionGroups . Add ( id , requested , configTree , plugins )
} | SubscribeDeps will subscribe to collectors processors and publishers . The collectors are subscribed by mapping the provided array of core . RequestedMetrics to the corresponding plugins while processors and publishers provided in the array of core . Plugin will be subscribed directly . The ID provides a logical groupi... |
209 | func ( p * pluginControl ) UnsubscribeDeps ( id string ) [ ] serror . SnapError { return p . subscriptionGroups . Remove ( id )
} | UnsubscribeDeps unsubscribes a group of dependencies provided the subscription group ID |
210 | func ( p * pluginControl ) SetMonitorOptions ( options ... monitorOption ) { p . pluginRunner . Monitor ( ) . Option ( options ... )
} | SetMonitorOptions exposes monitors options |
211 | func ( p * pluginControl ) CollectMetrics ( id string , allTags map [ string ] map [ string ] string ) ( metrics [ ] core . Metric , errs [ ] error ) { if ! p . Started { return nil , [ ] error { ErrControllerNotStarted }
}
pluginToMetricMap , serrs , err := p . subscriptionGroups . Get ( id )
if err != nil { con... | CollectMetrics is a blocking call to collector plugins returning a collection of metrics and errors . If an error is encountered no metrics will be returned . |
212 | func New ( cfg * Config ) * scheduler { schedulerLogger . WithFields ( log . Fields { "_block" : "New" , "value" : cfg . WorkManagerQueueSize , } ) . Info ( "Setting work manager queue size" )
schedulerLogger . WithFields ( log . Fields { "_block" : "New" , "value" : cfg . WorkManagerPoolSize , } ) . Info ( "Setting ... | New returns an instance of the scheduler The MetricManager must be set before the scheduler can be started . The MetricManager must be started before it can be used . |
213 | func ( s * scheduler ) CreateTask ( sch schedule . Schedule , wfMap * wmap . WorkflowMap , startOnCreate bool , opts ... core . TaskOption ) ( core . Task , core . TaskErrors ) { return s . createTask ( sch , wfMap , startOnCreate , "user" , opts ... )
} | CreateTask creates and returns task |
214 | func ( s * scheduler ) GetTasks ( ) map [ string ] core . Task { tasks := make ( map [ string ] core . Task )
for id , t := range s . tasks . Table ( ) { tasks [ id ] = t
}
return tasks
} | GetTasks returns a copy of the tasks in a map where the task id is the key |
215 | func ( s * scheduler ) GetTask ( id string ) ( core . Task , error ) { t , err := s . getTask ( id )
if err != nil { schedulerLogger . WithFields ( log . Fields { "_block" : "get-task" , "_error" : ErrTaskNotFound , "task-id" : id , } ) . Error ( "error getting task" )
return nil , err
}
return t , nil
} | GetTask provided the task id a task is returned |
216 | func ( s * scheduler ) StartTask ( id string ) [ ] serror . SnapError { return s . startTask ( id , "user" )
} | StartTask provided a task id a task is started |
217 | func ( s * scheduler ) StopTask ( id string ) [ ] serror . SnapError { return s . stopTask ( id , "user" )
} | StopTask provided a task id a task is stopped |
218 | func ( s * scheduler ) EnableTask ( id string ) ( core . Task , error ) { t , e := s . getTask ( id )
if e != nil { schedulerLogger . WithFields ( log . Fields { "_block" : "enable-task" , "_error" : ErrTaskNotFound , "task-id" : id , } ) . Error ( "error enabling task" )
return nil , e
}
err := t . Enable ( ) ... | EnableTask changes state from disabled to stopped |
219 | func ( s * scheduler ) SetMetricManager ( mm managesMetrics ) { s . metricManager = mm
schedulerLogger . WithFields ( log . Fields { "_block" : "set-metric-manager" , } ) . Debug ( "metric manager linked" )
} | Set metricManager for scheduler |
220 | func ( s * scheduler ) HandleGomitEvent ( e gomit . Event ) { switch v := e . Body . ( type ) { case * scheduler_event . MetricCollectedEvent : log . WithFields ( log . Fields { "_module" : "scheduler-events" , "_block" : "handle-events" , "event-namespace" : e . Namespace ( ) , "task-id" : v . TaskID , "metric-count" ... | Central handling for all async events in scheduler |
221 | func ( s * apiV1 ) enableTask ( w http . ResponseWriter , r * http . Request , p httprouter . Params ) { id := p . ByName ( "id" )
tsk , err := s . taskManager . EnableTask ( id )
if err != nil { if strings . Contains ( err . Error ( ) , ErrTaskNotFound . Error ( ) ) { rbody . Write ( 404 , rbody . FromError ( err ... | enableTask changes the task state from Disabled to Stopped |
222 | func Manifest ( f io . ReadSeeker ) ( * schema . ImageManifest , error ) { m , err := specaci . ManifestFromImage ( f )
if err != nil { return nil , err
}
return m , nil
} | Manifest returns the ImageManifest inside the ACI file |
223 | func Extract ( f io . ReadSeeker ) ( string , error ) { fileMode := os . FileMode ( 0755 )
tr , err := specaci . NewCompressedTarReader ( f )
if err != nil { return "" , err
}
defer tr . Close ( )
dir , err := ioutil . TempDir ( "" , "" )
if err != nil { return "" , err
}
aciLogger . WithField ( "direct... | Extract expands the ACI file to a temporary directory returning the directory path where the ACI was expanded or an error |
224 | func Validate ( f io . ReadSeeker ) error { tr , err := specaci . NewCompressedTarReader ( f )
defer tr . Close ( )
if err != nil { return err
}
if err := specaci . ValidateArchive ( tr . Reader ) ; err != nil { return err
}
return nil
} | Validate makes sure the archive is valid . Otherwise an error is returned |
225 | func ( s subscriptionGroups ) Remove ( id string ) [ ] serror . SnapError { s . Lock ( )
defer s . Unlock ( )
return s . remove ( id )
} | Remove removes a subscription group given a subscription group ID . |
226 | func ( s * subscriptionGroups ) validatePluginUnloading ( pluginToUnload * loadedPlugin ) ( errs [ ] serror . SnapError ) { s . Lock ( )
defer s . Unlock ( )
for id , group := range s . subscriptionMap { if err := group . validatePluginUnloading ( id , pluginToUnload ) ; err != nil { errs = append ( errs , err )
... | validatePluginUnloading checks if process of unloading the plugin is safe for existing running tasks . If the plugin is used by running task and there is no replacements return an error with appropriate message containing ids of tasks which use the plugin what blocks unloading process until they are stopped |
227 | func ( s * subscriptionGroup ) pluginIsSubscribed ( plugin * loadedPlugin ) bool { for _ , sp := range s . plugins { if sp . TypeName ( ) == plugin . TypeName ( ) && sp . Name ( ) == plugin . Name ( ) && sp . Version ( ) == plugin . Version ( ) { return true
}
}
return false
} | pluginIsSubscribed returns true if a provided plugin has been found among subscribed plugins in the following subscription group |
228 | func ( s * subscriptionGroup ) validatePluginUnloading ( id string , plgToUnload * loadedPlugin ) ( serr serror . SnapError ) { impacted := false
if ! s . pluginIsSubscribed ( plgToUnload ) { return nil
}
controlLogger . WithFields ( log . Fields { "_block" : "subscriptionGroup.validatePluginUnloading" , "task-id... | validatePluginUnloading verifies if a given plugin might be unloaded without causing running task failures |
229 | func comparePlugins ( newPlugins , oldPlugins [ ] core . SubscribedPlugin ) ( adds , removes [ ] core . SubscribedPlugin ) { newMap := make ( map [ string ] int )
oldMap := make ( map [ string ] int )
for _ , n := range newPlugins { newMap [ key ( n ) ] ++
}
for _ , o := range oldPlugins { oldMap [ key ( o ) ] ... | comparePlugins compares the new state of plugins with the previous state . It returns an array of plugins that need to be subscribed and an array of plugins that need to be unsubscribed . |
230 | func ( c * Client ) LoadPlugin ( p [ ] string ) * LoadPluginResult { r := new ( LoadPluginResult )
resp , err := c . pluginUploadRequest ( p )
if err != nil { r . Err = serror . New ( err )
return r
}
switch resp . Meta . Type { case rbody . PluginsLoadedType : pl := resp . Body . ( * rbody . PluginsLoaded ) ... | LoadPlugin loads plugins for the given plugin names . A slide of loaded plugins returns if succeeded . Otherwise an error is returned . |
231 | func ( c * Client ) UnloadPlugin ( pluginType , name string , version int ) * UnloadPluginResult { r := & UnloadPluginResult { }
resp , err := c . do ( "DELETE" , fmt . Sprintf ( "/plugins/%s/%s/%d" , pluginType , url . QueryEscape ( name ) , version ) , ContentTypeJSON )
if err != nil { r . Err = err
return r
... | UnloadPlugin unloads a plugin given plugin type name and version through an HTTP DELETE request . The unloaded plugin returns if succeeded . Otherwise an error is returned . |
232 | func ( c * Client ) GetPlugins ( details bool ) * GetPluginsResult { r := & GetPluginsResult { }
var path string
if details { path = "/plugins?details"
} else { path = "/plugins"
}
resp , err := c . do ( "GET" , path , ContentTypeJSON )
if err != nil { r . Err = err
return r
}
switch resp . Meta . Typ... | GetPlugins returns the loaded and available plugins through an HTTP GET request . By specifying the details flag to tweak output info . An error returns if it failed . |
233 | func ( c * Client ) GetPlugin ( typ , name string , ver int ) * GetPluginResult { r := & GetPluginResult { }
path := "/plugins/" + typ + "/" + name + "/" + strconv . Itoa ( ver )
resp , err := c . do ( "GET" , path , ContentTypeJSON )
if err != nil { r . Err = err
return r
}
switch resp . Meta . Type { case... | GetPlugin returns the requested plugin through an HTTP GET request . An error returns if it failed . |
234 | func ( t * TaskWatcher ) Close ( ) error { for _ , x := range t . taskIDs { t . parent . rm ( x , t )
}
return nil
} | Close stops watching a task . Cannot be restarted . |
235 | func ( p * pool ) Insert ( a AvailablePlugin ) error { if a . Type ( ) != plugin . CollectorPluginType && a . Type ( ) != plugin . ProcessorPluginType && a . Type ( ) != plugin . PublisherPluginType && a . Type ( ) != plugin . StreamCollectorPluginType { return ErrBadType
}
if len ( p . plugins ) == 0 { if err := p... | Insert inserts an AvailablePlugin into the pool |
236 | func ( p * pool ) applyPluginMeta ( a AvailablePlugin ) error { if a . Exclusive ( ) { p . max = 1
}
cacheTTL := GlobalCacheExpiration
if a . CacheTTL ( ) != 0 && a . CacheTTL ( ) > GlobalCacheExpiration { cacheTTL = a . CacheTTL ( )
}
p . concurrencyCount = a . ConcurrencyCount ( )
switch a . RoutingStrate... | applyPluginMeta is called when the first plugin is added to the pool |
237 | func ( p * pool ) Subscribe ( taskID string ) { p . Lock ( )
defer p . Unlock ( )
if _ , exists := p . subs [ taskID ] ; ! exists { p . subs [ taskID ] = & subscription { TaskID : taskID , Version : p . version , }
}
} | subscribe adds a subscription to the pool . Using subscribe is idempotent . |
238 | func ( p * pool ) Unsubscribe ( taskID string ) { p . Lock ( )
defer p . Unlock ( )
delete ( p . subs , taskID )
} | unsubscribe removes a subscription from the pool . Using unsubscribe is idempotent . |
239 | func ( p * pool ) Eligible ( ) bool { p . RLock ( )
defer p . RUnlock ( )
if len ( p . plugins ) >= p . max { return false
}
if len ( p . subs ) > p . concurrencyCount * len ( p . plugins ) { return true
}
return false
} | Eligible returns a bool indicating whether the pool is eligible to grow |
240 | func ( p * pool ) Kill ( id uint32 , reason string ) { p . Lock ( )
defer p . Unlock ( )
ap , ok := p . plugins [ id ]
if ok { ap . Kill ( reason )
delete ( p . plugins , id )
}
} | kill kills and removes the available plugin from its pool . Using kill is idempotent . |
241 | func ( p * pool ) KillAll ( reason string ) { for id , rp := range p . plugins { log . WithFields ( log . Fields { "_block" : "KillAll" , "reason" : reason , } ) . Debug ( fmt . Sprintf ( "handling 'KillAll' for pool '%v', killing plugin '%v:%v'" , p . String ( ) , rp . Name ( ) , rp . Version ( ) ) )
if err := rp . ... | Kill all instances of a plugin |
242 | func ( p * pool ) SelectAndKill ( id , reason string ) { rp , err := p . Remove ( p . plugins . Values ( ) , id )
if err != nil { log . WithFields ( log . Fields { "_block" : "SelectAndKill" , "taskID" : id , "reason" : reason , } ) . Error ( err )
return
}
if err := rp . Stop ( reason ) ; err != nil { log . Wi... | SelectAndKill selects kills and removes the available plugin from the pool |
243 | func ( p * pool ) remove ( id uint32 ) { p . Lock ( )
defer p . Unlock ( )
delete ( p . plugins , id )
} | remove removes an available plugin from the the pool . using remove is idempotent . |
244 | func ( p * pool ) Count ( ) int { p . RLock ( )
defer p . RUnlock ( )
return len ( p . plugins )
} | Count returns the number of plugins in the pool |
245 | func ( p * pool ) SubscriptionCount ( ) int { p . RLock ( )
defer p . RUnlock ( )
return len ( p . subs )
} | SubscriptionCount returns the number of subscriptions in the pool |
246 | func ( p * pool ) SelectAP ( taskID string , config map [ string ] ctypes . ConfigValue ) ( AvailablePlugin , serror . SnapError ) { aps := p . plugins . Values ( )
var id string
switch p . Strategy ( ) . String ( ) { case "least-recently-used" : id = ""
case "sticky" : id = taskID
case "config-based" : id = id... | SelectAP selects an available plugin from the pool the method is not thread safe it should be protected outside of the body |
247 | func ( p * pool ) generatePID ( ) uint32 { atomic . AddUint32 ( & p . pidCounter , 1 )
return p . pidCounter
} | generatePID returns the next available pid for the pool |
248 | func ( p * pool ) CacheTTL ( taskID string ) ( time . Duration , error ) { if len ( p . plugins ) == 0 { return 0 , ErrPoolEmpty
}
return p . RoutingAndCaching . CacheTTL ( taskID )
} | CacheTTL returns the cacheTTL for the pool |
249 | func ( s * SigningManager ) ValidateSignature ( keyringFiles [ ] string , signedFile string , signature [ ] byte ) error { var signedby string
var e error
var checked * openpgp . Entity
signed , err := os . Open ( signedFile )
if err != nil { return fmt . Errorf ( "%v: %v\n%v" , \n , ErrSignedFileNotFound , sig... | ValidateSignature is exported for plugin authoring |
250 | func SupportedTypes ( ) [ ] string { t := [ ] string { ConfigValueStr { } . Type ( ) , ConfigValueInt { } . Type ( ) , ConfigValueFloat { } . Type ( ) , ConfigValueBool { } . Type ( ) , }
return t
} | Returns a slice of string keywords for the types supported by ConfigValue . |
251 | func NewExecutablePlugin ( a Arg , commands ... string ) ( * ExecutablePlugin , error ) { jsonArgs , err := json . Marshal ( a )
if err != nil { return nil , err
}
cmd := & exec . Cmd { Path : commands [ 0 ] , Args : append ( commands , string ( jsonArgs ) ) , }
stdout , err := cmd . StdoutPipe ( )
if err != ... | NewExecutablePlugin returns a new ExecutablePlugin . |
252 | func ( e * ExecutablePlugin ) Run ( timeout time . Duration ) ( Response , error ) { var ( respReceived bool
resp Response
err error
respBytes [ ] byte
)
doneChan := make ( chan struct { } )
stdOutScanner := bufio . NewScanner ( e . stdout )
if err = e . cmd . Start ( ) ; err != nil { return resp , err
... | Run executes the plugin and waits for a response or times out . |
253 | func ( n Namespace ) Strings ( ) [ ] string { var ns [ ] string
for _ , namespaceElement := range n { ns = append ( ns , namespaceElement . Value )
}
return ns
} | Strings returns an array of strings that represent the elements of the namespace . |
254 | func ( n Namespace ) getSeparator ( ) string { smap := initSeparatorMap ( )
for _ , e := range n { for _ , r := range e . Value { ch := fmt . Sprintf ( "%c" , r )
if v , ok := smap [ ch ] ; ok && ! v { smap [ ch ] = true
}
}
}
for _ , s := range nsPriorityList { if v , ok := smap [ s ] ; ok && ! v { return ... | getSeparator returns the highest suitable separator from the nsPriorityList . Otherwise the core separator is returned . |
255 | func initSeparatorMap ( ) map [ string ] bool { m := map [ string ] bool { }
for _ , s := range nsPriorityList { m [ s ] = false
}
return m
} | initSeparatorMap populates the local map of nsPriorityList . |
256 | func NewNamespace ( ns ... string ) Namespace { n := make ( [ ] NamespaceElement , len ( ns ) )
for i , ns := range ns { n [ i ] = NamespaceElement { Value : ns }
}
return n
} | NewNamespace takes an array of strings and returns a Namespace . A Namespace is an array of NamespaceElements . The provided array of strings is used to set the corresponding Value fields in the array of NamespaceElements . |
257 | func ( n Namespace ) AddDynamicElement ( name , description string ) Namespace { nse := NamespaceElement { Name : name , Description : description , Value : "*" }
return append ( n , nse )
} | AddDynamicElement adds a dynamic element to the given Namespace . A dynamic NamespaceElement is defined by having a nonempty Name field . |
258 | func ( n Namespace ) AddStaticElement ( value string ) Namespace { nse := NamespaceElement { Value : value }
return append ( n , nse )
} | AddStaticElement adds a static element to the given Namespace . A static NamespaceElement is defined by having an empty Name field . |
259 | func ( n Namespace ) AddStaticElements ( values ... string ) Namespace { for _ , value := range values { n = append ( n , NamespaceElement { Value : value } )
}
return n
} | AddStaticElements adds a static elements to the given Namespace . A static NamespaceElement is defined by having an empty Name field . |
260 | func ( w * worker ) start ( ) { for { select { case q := <- w . rcv : if chrono . Chrono . Now ( ) . Before ( q . Job ( ) . Deadline ( ) ) { q . Job ( ) . Run ( )
} else { q . Job ( ) . AddErrors ( errors . New ( "Worker refused to run overdue job." ) )
}
q . Promise ( ) . Complete ( q . Job ( ) . Errors ( ) )
... | begin a worker |
261 | func ( c * Client ) FetchMetrics ( ns string , ver int ) * GetMetricsResult { r := & GetMetricsResult { }
q := fmt . Sprintf ( "/metrics?ns=%s&ver=%d" , ns , ver )
resp , err := c . do ( "GET" , q , ContentTypeJSON )
if err != nil { return & GetMetricsResult { Err : err }
}
switch resp . Meta . Type { case rb... | FetchMetrics retrieves the metric catalog given metric namespace and version through an HTTP GET request . It returns the corresponding metric catalog if succeeded . Otherwise an error is returned . |
262 | func ( c * Client ) GetMetricVersions ( ns string ) * GetMetricsResult { r := & GetMetricsResult { }
q := fmt . Sprintf ( "/metrics?ns=%s" , ns )
resp , err := c . do ( "GET" , q , ContentTypeJSON )
if err != nil { return & GetMetricsResult { Err : err }
}
switch resp . Meta . Type { case rbody . MetricsRetur... | GetMetricVersions retrieves all versions of a metric at a given namespace . |
263 | func GetFirstChar ( s string ) string { firstChar := ""
for _ , r := range s { firstChar = fmt . Sprintf ( "%c" , r )
break
}
return firstChar
} | GetFirstChar returns the first character from the input string . |
264 | func ( c * ConfigTree ) GobEncode ( ) ( [ ] byte , error ) { w := new ( bytes . Buffer )
encoder := gob . NewEncoder ( w )
if c . root == nil { c . root = & node { }
}
if err := encoder . Encode ( c . root ) ; err != nil { return nil , err
}
return w . Bytes ( ) , nil
} | GobEncode returns the encoded ConfigTree . Otherwise an error is returned |
265 | func ( c * ConfigTree ) GobDecode ( buf [ ] byte ) error { r := bytes . NewBuffer ( buf )
decoder := gob . NewDecoder ( r )
if err := decoder . Decode ( & c . root ) ; err != nil { return err
}
return nil
} | GobDecode decodes the ConfigTree . |
266 | func ( c * ConfigTree ) MarshalJSON ( ) ( [ ] byte , error ) { return json . Marshal ( & struct { Root * node `json:"root"`
} { Root : c . root , } )
} | MarshalJSON marshals ConfigTree |
267 | func ( c * ConfigTree ) Add ( ns [ ] string , inNode Node ) { c . log ( fmt . Sprintf ( "Adding %v at %s\n" , \n , inNode ) )
ns
if len ( ns ) == 0 { c . log ( fmt . Sprintln ( "ns is empty - returning with no change to tree" ) )
return
}
f , remain := ns [ 0 ] , ns [ 1 : ]
c . log ( fmt . Sprintf ( "first ... | Add adds a new tree node |
268 | func ( c * ConfigTree ) Get ( ns [ ] string ) Node { c . log ( fmt . Sprintf ( "Get on ns (%s)\n" , \n ) )
ns
retNodes := new ( [ ] Node )
if c . root == nil { c . log ( fmt . Sprintln ( "ctree: no root - returning nil" ) )
return nil
}
if len ( c . root . keys ) == 0 { return nil
}
rootKeyLength := len... | Get returns a tree node given the namespace |
269 | func ( n * node ) MarshalJSON ( ) ( [ ] byte , error ) { return json . Marshal ( & struct { Nodes [ ] * node `json:"nodes"`
Keys [ ] string `json:"keys"`
KeysBytes [ ] byte `json:"keysbytes"`
Node Node `json:"node"`
} { Nodes : n . nodes , Keys : n . keys , KeysBytes : n . keysBytes , Node : n . Node , } )
} | MarshalJSON marshals the ConfigTree . |
270 | func ( n * node ) GobEncode ( ) ( [ ] byte , error ) { w := new ( bytes . Buffer )
encoder := gob . NewEncoder ( w )
if err := encoder . Encode ( n . nodes ) ; err != nil { return nil , err
}
if err := encoder . Encode ( n . keys ) ; err != nil { return nil , err
}
if err := encoder . Encode ( n . keysBytes... | GobEncode encodes every member of node struct instance |
271 | func ( n * node ) GobDecode ( buf [ ] byte ) error { r := bytes . NewBuffer ( buf )
decoder := gob . NewDecoder ( r )
if err := decoder . Decode ( & n . nodes ) ; err != nil { return err
}
if err := decoder . Decode ( & n . keys ) ; err != nil { return err
}
if err := decoder . Decode ( & n . keysBytes ) ; ... | GobDecode decodes every member of node struct instance |
272 | func ( f * FloatRule ) 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,omi... | MarshalJSON marshals a FloatRule into JSON |
273 | func ( f * FloatRule ) GobEncode ( ) ( [ ] byte , error ) { w := new ( bytes . Buffer )
encoder := gob . NewEncoder ( w )
if err := encoder . Encode ( f . key ) ; err != nil { return nil , err
}
if err := encoder . Encode ( f . required ) ; err != nil { return nil , err
}
if f . default_ == nil { encoder . ... | GobEncode encodes a FloatRule into a GOB |
274 | func ( f * FloatRule ) Default ( ) ctypes . ConfigValue { if f . default_ != nil { return ctypes . ConfigValueFloat { Value : * f . default_ }
}
return nil
} | Default returns the rule s default value |
275 | func parseURL ( url string ) error { if ! govalidator . IsURL ( url ) || ! strings . HasPrefix ( url , "http" ) { return fmt . Errorf ( "URL %s is not in the format of http(s)://<ip>:<port>" , url )
}
return nil
} | Checks validity of URL |
276 | func Password ( p string ) metaOp { return func ( c * Client ) { c . Password = strings . TrimSpace ( p )
}
} | Password is an option than can be provided to the func client . New . |
277 | func Timeout ( t time . Duration ) metaOp { return func ( c * Client ) { c . http . Timeout = t
}
} | Timeout is an option that can be provided to the func client . New in order to set HTTP connection timeout . |
278 | func New ( url , ver string , insecure bool , opts ... metaOp ) ( * Client , error ) { if err := parseURL ( url ) ; err != nil { return nil , err
}
if ver == "" { ver = "v1"
}
var t * http . Transport
if insecure { t = insecureTransport
} else { t = secureTransport
}
c := & Client { URL : url , Version ... | New returns a pointer to a snap api client if ver is an empty string v1 is used by default |
279 | func ( c * Client ) TribeRequest ( ) ( * http . Response , error ) { req , err := http . NewRequest ( "GET" , c . URL , nil )
if err != nil { return nil , err
}
addAuth ( req , "snap" , c . Password )
rsp , err := c . http . Do ( req )
if err != nil { return nil , err
}
return rsp , nil
} | Passthrough for tribe request to allow use of client auth . |
280 | func CollectWkrSizeOption ( v uint ) workManagerOption { return func ( w * workManager ) workManagerOption { previous := w . collectWkrSize
w . collectWkrSize = v
return CollectWkrSizeOption ( previous )
}
} | CollectWkrSizeOption sets the collector worker pool size and returns the previous collector worker pool state . |
281 | func ProcessWkrSizeOption ( v uint ) workManagerOption { return func ( w * workManager ) workManagerOption { previous := w . processWkrSize
w . processWkrSize = v
return ProcessWkrSizeOption ( previous )
}
} | ProcessWkrSizeOption sets the processor worker pool size and return the previous processor worker pool state . |
282 | func PublishWkrSizeOption ( v uint ) workManagerOption { return func ( w * workManager ) workManagerOption { previous := w . publishWkrSize
w . publishWkrSize = v
return PublishWkrSizeOption ( previous )
}
} | PublishWkrSizeOption sets the publisher worker pool size and returns the previous previous publisher worker pool state . |
283 | func ( w * workManager ) Start ( ) { w . mutex . Lock ( )
defer w . mutex . Unlock ( )
if w . state == workManagerStopped { w . state = workManagerRunning
go func ( ) { for { select { case <- w . collectq . Err : case <- w . processq . Err : case <- w . publishq . Err : case <- w . kill : return
}
}
} ( )
... | Start workManager s loop just handles queuing errors . |
284 | func ( w * workManager ) Stop ( ) { w . collectq . Stop ( )
close ( workerKillChan )
close ( w . kill )
} | Stop closes the collector queue and worker |
285 | func ( w * workManager ) Work ( j job ) queuedJob { qj := newQueuedJob ( j )
switch j . Type ( ) { case collectJobType : w . collectq . Event <- qj
case processJobType : w . processq . Event <- qj
case publishJobType : w . publishq . Event <- qj
}
return qj
} | Work dispatches jobs to worker pools for processing . Returns a queued job to the caller which will be completed by the work queue aubsystem . |
286 | func ( w * workManager ) AddCollectWorker ( ) { nw := newWorker ( w . collectchan )
go nw . start ( )
w . collectWkrs = append ( w . collectWkrs , nw )
w . collectWkrSize ++
} | AddCollectWorker adds a new worker to the collector worker pool |
287 | func ( w * workManager ) AddPublishWorker ( ) { nw := newWorker ( w . publishchan )
go nw . start ( )
w . publishWkrs = append ( w . publishWkrs , nw )
w . publishWkrSize ++
} | AddPublishWorker adds a new worker to the publisher worker pool |
288 | func ( w * workManager ) AddProcessWorker ( ) { nw := newWorker ( w . processchan )
go nw . start ( )
w . processWkrs = append ( w . processWkrs , nw )
w . processWkrSize ++
} | AddProcessWorker adds a new worker to the processor worker pool |
289 | func ( w * workManager ) sendToWorker ( j queuedJob ) { switch j . Job ( ) . Type ( ) { case collectJobType : w . collectchan <- j
case publishJobType : w . publishchan <- j
case processJobType : w . processchan <- j
}
} | sendToWorker is the handler given to the queue . it dispatches work to the worker pool . |
290 | func ( c * ConfigPolicy ) UnmarshalJSON ( data [ ] byte ) error { m := map [ string ] map [ string ] interface { } { }
decoder := json . NewDecoder ( bytes . NewReader ( data ) )
if err := decoder . Decode ( & m ) ; err != nil { return err
}
c . config = ctree . New ( )
if config , ok := m [ "config" ] ; ok {... | UnmarshalJSON unmarshals JSON into a ConfigPolicy |
291 | func ( c * ConfigPolicy ) MarshalJSON ( ) ( [ ] byte , error ) { return json . Marshal ( & struct { Config * ctree . ConfigTree `json:"config"`
} { Config : c . config , } )
} | MarshalJSON marshals a ConfigPolicy into JSON |
292 | func ( c * ConfigPolicy ) Add ( ns [ ] string , cpn * ConfigPolicyNode ) { c . config . Add ( ns , cpn )
} | Adds a ConfigPolicyNode at the provided namespace . |
293 | func ( c * ConfigPolicy ) Get ( ns [ ] string ) * ConfigPolicyNode { n := c . config . Get ( ns )
if n == nil { return NewPolicyNode ( )
}
switch t := n . ( type ) { case ConfigPolicyNode : return & t
default : return t . ( * ConfigPolicyNode )
}
} | Returns a ConfigPolicyNode that is a merged version of the namespace provided . |
294 | func NewMetricType ( namespace core . Namespace , timestamp time . Time , tags map [ string ] string , unit string , data interface { } ) * MetricType { return & MetricType { Namespace_ : namespace , Tags_ : tags , Data_ : data , Timestamp_ : timestamp , LastAdvertisedTime_ : timestamp , Unit_ : unit , }
} | NewMetricType returns a Constructor |
295 | func SwapMetricContentType ( contentType , requestedContentType string , payload [ ] byte ) ( [ ] byte , string , error ) { metrics , err1 := UnmarshallMetricTypes ( contentType , payload )
if err1 != nil { log . WithFields ( log . Fields { "_module" : "control-plugin" , "block" : "swap-content-type" , "error" : err1... | SwapMetricContentType swaps a payload with one content type to another one . |
296 | func ( this * Response ) ReadAll ( ) ( [ ] byte , error ) { var reader io . ReadCloser
var err error
switch this . Header . Get ( "Content-Encoding" ) { case "gzip" : reader , err = gzip . NewReader ( this . Body )
if err != nil { return nil , err
}
default : reader = this . Body
}
defer reader . Close ( ... | Read response body into a byte slice . |
297 | func ( this * Response ) ToString ( ) ( string , error ) { bytes , err := this . ReadAll ( )
if err != nil { return "" , err
}
return string ( bytes ) , nil
} | Read response body into string . |
298 | func prepareRequest ( method string , url_ string , headers map [ string ] string , body io . Reader , options map [ int ] interface { } ) ( * http . Request , error ) { req , err := http . NewRequest ( method , url_ , body )
if err != nil { return nil , err
}
if referer , ok := options [ OPT_REFERER ] ; ok { if ... | Prepare a request . |
299 | func prepareRedirect ( options map [ int ] interface { } ) ( func ( req * http . Request , via [ ] * http . Request ) error , error ) { var redirectPolicy func ( req * http . Request , via [ ] * http . Request ) error
if redirectPolicy_ , ok := options [ OPT_REDIRECT_POLICY ] ; ok { if redirectPolicy , ok = redirectP... | Prepare a redirect policy . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.