idx
int64
0
41.8k
question
stringlengths
69
3.84k
target
stringlengths
11
1.18k
300
func ResetIterate ( p * dt . Plugin , in * dt . Msg ) { p . DeleteMemory ( in , keySelection ) }
ResetIterate should be called from within your plugin s SetOnReset function if you use the Iterable task .
301
func ( hm HandlerMap ) AddRoutes ( prefix string , r * httprouter . Router ) { for httpRoute , h := range hm { p := path . Join ( "/" , prefix , httpRoute . Path ) r . HandlerFunc ( httpRoute . Method , p , h ) } }
AddRoutes to the router dynamically enabling drivers to add routes to an application at runtime usually as part of their initialization .
302
func NewHandlerMap ( rhs [ ] RouteHandler ) HandlerMap { hm := HandlerMap { } for _ , rh := range rhs { route := HTTPRoute { Path : rh . Path , Method : rh . Method , } hm [ route ] = rh . Handler } return hm }
NewHandlerMap builds a HandlerMap from a slice of RouteHandlers . This is a convenience function since using RouteHandlers directly is very verbose for plugins .
303
func ( c * Conn ) Send ( to , msg string ) error { return c . conn . Send ( to , msg ) }
Send an SMS message through an opened driver connection . The from number is handled by the driver .
304
func Contains ( wordList [ ] string , s string ) bool { s = strings . TrimRight ( strings . ToLower ( s ) , ".,;:!?'\"" ) \" for _ , word := range wordList { if s == word { return true } } }
Contains determines whether a slice of strings contains a specific word .
305
func newRouter ( ) * httprouter . Router { router := httprouter . New ( ) router . ServeFiles ( "/public/*filepath" , http . Dir ( "public" ) ) if os . Getenv ( "ABOT_ENV" ) != "production" { initCMDGroup ( router ) } router . HandlerFunc ( "GET" , "/" , hIndex ) router . HandlerFunc ( "POST" , "/" , hMain ) ...
newRouter initializes and returns a router .
306
func hIndex ( w http . ResponseWriter , r * http . Request ) { var err error env := os . Getenv ( "ABOT_ENV" ) if env != "production" && env != "test" { p := filepath . Join ( "assets" , "html" , "layout.html" ) tmplLayout , err = template . ParseFiles ( p ) if err != nil { writeErrorInternal ( w , err ) retu...
hIndex presents the homepage to the user and populates the HTML with server - side variables .
307
func hMain ( w http . ResponseWriter , r * http . Request ) { errMsg := "Something went wrong with my wiring... I'll get that fixed up soon." ret , err := ProcessText ( r ) if err != nil { if len ( ret ) > 0 { ret = errMsg } log . Info ( "failed to process text." , err ) } w . Header ( ) . Set ( "Access-Con...
hMain is the endpoint to hit when you want a direct response via JSON . The Abot console uses this endpoint .
308
func hOptions ( w http . ResponseWriter , r * http . Request ) { w . Header ( ) . Set ( "Access-Control-Allow-Origin" , "*" ) w . Header ( ) . Set ( "Access-Control-Allow-Headers" , "Content-Type,Access-Control-Allow-Origin" ) w . WriteHeader ( http . StatusOK ) }
hOptions sets appropriate response headers in cases like browser - based communication with Abot .
309
func hapiLogoutSubmit ( w http . ResponseWriter , r * http . Request ) { cookie , err := r . Cookie ( "id" ) if err != nil { writeError ( w , err ) return } uid := cookie . Value if uid == "null" { http . Error ( w , "id was null" , http . StatusBadRequest ) return } q := `DELETE FROM sessions WHERE use...
hapiLogoutSubmit processes a logout request deleting the session from the server .
310
func hapiLoginSubmit ( w http . ResponseWriter , r * http . Request ) { var req struct { Email string Password string } if err := json . NewDecoder ( r . Body ) . Decode ( & req ) ; err != nil { writeErrorInternal ( w , err ) return } var u struct { ID uint64 Password [ ] byte Admin bool } q := `SEL...
hapiLoginSubmit processes a logout request deleting the session from the server .
311
func hapiProfile ( w http . ResponseWriter , r * http . Request ) { if os . Getenv ( "ABOT_ENV" ) != "test" { if ! isLoggedIn ( w , r ) { return } } cookie , err := r . Cookie ( "id" ) if err != nil { writeErrorInternal ( w , err ) return } uid := cookie . Value var user struct { Name string Email str...
hapiProfile shows a user profile with the user s current addresses credit cards and contact information .
312
func hapiForgotPasswordSubmit ( w http . ResponseWriter , r * http . Request ) { var req struct { Email string } if err := json . NewDecoder ( r . Body ) . Decode ( & req ) ; err != nil { writeErrorInternal ( w , err ) return } var user dt . User q := `SELECT id, name, email FROM users WHERE email=$1` err :...
hapiForgotPasswordSubmit asks the server to send the user a Forgot Password email with instructions for resetting their password .
313
func hapiResetPasswordSubmit ( w http . ResponseWriter , r * http . Request ) { var req struct { Password string Secret string } if err := json . NewDecoder ( r . Body ) . Decode ( & req ) ; err != nil { writeErrorInternal ( w , err ) return } if len ( req . Password ) < 8 { writeError ( w , errors . New ( ...
hapiResetPasswordSubmit is arrived at through the email generated by hapiForgotPasswordSubmit . This endpoint resets the user password with another bcrypt hash after validating on the server that their new password is sufficient .
314
func hapiAdminExists ( w http . ResponseWriter , r * http . Request ) { var count int q := `SELECT COUNT(*) FROM users WHERE admin=TRUE LIMIT 1` if err := db . Get ( & count , q ) ; err != nil { writeErrorInternal ( w , err ) return } byt , err := json . Marshal ( count > 0 ) if err != nil { writeErrorInter...
hapiAdminExists checks if an admin exists in the database .
315
func hapiPlugins ( w http . ResponseWriter , r * http . Request ) { if os . Getenv ( "ABOT_ENV" ) != "test" { if ! isAdmin ( w , r ) { return } if ! isLoggedIn ( w , r ) { return } } var settings [ ] struct { Name string Value string PluginName string } q := `SELECT name, value, pluginname FROM settin...
hapiPlugins responds with all of the server s installed plugin configurations from each their respective plugin . json files and database - stored configuration .
316
func hapiConversationsNeedTraining ( w http . ResponseWriter , r * http . Request ) { if os . Getenv ( "ABOT_ENV" ) != "test" { if ! isAdmin ( w , r ) { return } if ! isLoggedIn ( w , r ) { return } } msgs := [ ] struct { Sentence string FlexID * string CreatedAt time . Time UserID uint64 FlexIDType *...
hapiConversationsNeedTraining returns a list of all sentences that require a human response .
317
func hapiSendMessage ( w http . ResponseWriter , r * http . Request ) { if os . Getenv ( "ABOT_ENV" ) != "test" { if ! isAdmin ( w , r ) { return } if ! isLoggedIn ( w , r ) { return } if ! isValidCSRF ( w , r ) { return } } var req struct { UserID uint64 FlexID string FlexIDType dt . FlexIDType Nam...
hapiSendMessage enables an admin to send a message to a user on behalf of Abot from the Response Panel .
318
func hapiAdmins ( w http . ResponseWriter , r * http . Request ) { if os . Getenv ( "ABOT_ENV" ) != "test" { if ! isAdmin ( w , r ) { return } if ! isLoggedIn ( w , r ) { return } } var admins [ ] struct { ID uint64 Name string Email string } q := `SELECT id, name, email FROM users WHERE admin=TRUE` ...
hapiAdmins returns a list of all admins with the training and manage team permissions .
319
func hapiAdminsUpdate ( w http . ResponseWriter , r * http . Request ) { if os . Getenv ( "ABOT_ENV" ) != "test" { if ! isAdmin ( w , r ) { return } if ! isLoggedIn ( w , r ) { return } if ! isValidCSRF ( w , r ) { return } } var req struct { ID uint64 Email string Admin bool } if err := json . Ne...
hapiAdminsUpdate adds or removes admin permission from a given user .
320
func hapiRemoteTokens ( w http . ResponseWriter , r * http . Request ) { if os . Getenv ( "ABOT_ENV" ) != "test" { if ! isAdmin ( w , r ) { return } if ! isLoggedIn ( w , r ) { return } } auths := [ ] struct { Token string Email string CreatedAt time . Time PluginIDs dt . Uint64Slice } { } q := `SEL...
hapiRemoteTokens returns the final six bytes of each auth token used to authenticate to the remote service and when .
321
func hapiRemoteTokensSubmit ( w http . ResponseWriter , r * http . Request ) { if os . Getenv ( "ABOT_ENV" ) != "test" { if ! isAdmin ( w , r ) { return } if ! isLoggedIn ( w , r ) { return } if ! isValidCSRF ( w , r ) { return } } var req struct { Token string PluginIDs dt . Uint64Slice } if err :=...
hapiRemoteTokensSubmit adds a remote token for modifying ITSABOT_URL s plugin training data .
322
func hapiRemoteTokensDelete ( w http . ResponseWriter , r * http . Request ) { if os . Getenv ( "ABOT_ENV" ) != "test" { if ! isAdmin ( w , r ) { return } if ! isLoggedIn ( w , r ) { return } if ! isValidCSRF ( w , r ) { return } } var req struct { Token string Email string } if err := json . NewDec...
hapiRemoteTokensDelete removes a remote token from the DB and responds with 200 OK .
323
func hapiSettingsUpdate ( w http . ResponseWriter , r * http . Request ) { if os . Getenv ( "ABOT_ENV" ) != "test" { if ! isAdmin ( w , r ) { return } if ! isLoggedIn ( w , r ) { return } } var req map [ string ] map [ string ] string if err := json . NewDecoder ( r . Body ) . Decode ( & req ) ; err != nil ...
hapiSettingsUpdate updates settings in the database for plugins .
324
func createCSRFToken ( u * dt . User ) ( token string , err error ) { q := `INSERT INTO sessions (token, userid, label) VALUES ($1, $2, 'csrfToken') ON CONFLICT (userid, label) DO UPDATE SET token=$1` token = RandSeq ( 32 ) if _ , err := db . Exec ( q , token , u . ID ) ; err != nil { return "" , err ...
createCSRFToken creates a new token invalidating any existing token .
325
func getAuthToken ( u * dt . User ) ( header * Header , authToken string , err error ) { scopes := [ ] string { } if u . Admin { scopes = append ( scopes , "admin" ) } header = & Header { ID : u . ID , Email : u . Email , Scopes : scopes , IssuedAt : time . Now ( ) . Unix ( ) , } byt , err := json . Marshal ( h...
getAuthToken returns a token used for future client authorization with a CSRF token .
326
func isValidCSRF ( w http . ResponseWriter , r * http . Request ) bool { log . Debug ( "validating csrf" ) var label string q := `SELECT label FROM sessions WHERE userid=$1 AND label='csrfToken' AND token=$2` cookie , err := r . Cookie ( "id" ) if err == http . ErrNoCookie { writeErrorAuth ( w , err ) r...
isValidCSRF ensures that any forms posted to Abot are protected against Cross - Site Request Forgery . Without this function Abot would be vulnerable to the attack because tokens are stored client - side in cookies .
327
func ExtractCurrency ( s string ) ( int64 , error ) { s = regexCurrency . FindString ( s ) if len ( s ) == 0 { return 0 , ErrNotFound } val , err := strconv . ParseFloat ( s , 64 ) if err != nil { return 0 , err } log . Debug ( "found value" , val ) return int64 ( val * 100 ) , nil }
ExtractCurrency returns an int64 if a currency is found and throws an error if one isn t .
328
func ExtractCities ( db * sqlx . DB , in * dt . Msg ) ( [ ] dt . City , error ) { var args [ ] interface { } var start int for i := range in . Stems { switch in . Stems [ i ] { case "at" , "in" , "on" : start = i break } } tmp := regexNonWords . ReplaceAllString ( in . Sentence , "" ) words := strings . F...
ExtractCities efficiently from a user s message .
329
func ExtractEmails ( s string ) ( [ ] string , error ) { emails := regexEmail . FindAllString ( s , - 1 ) if emails == nil { return [ ] string { } , ErrNotFound } return emails , nil }
ExtractEmails from a user s message .
330
func sendEvents ( evtChan chan * dt . ScheduledEvent , interval time . Duration ) { t := time . NewTicker ( time . Minute ) select { case now := <- t . C : sendEventsTick ( evtChan , now ) sendEvents ( evtChan , interval ) } }
sendEvents recursively calls itself to continue running .
331
func NewStateMachine ( p * Plugin ) * StateMachine { sm := StateMachine { state : 0 , plugin : p , } sm . states = map [ string ] int { } sm . resetFn = func ( * Msg ) { } return & sm }
NewStateMachine initializes a stateMachine to its starting state .
332
func ( sm * StateMachine ) LoadState ( in * Msg ) { tmp , err := json . Marshal ( sm . state ) if err != nil { sm . plugin . Log . Info ( "failed to marshal state for db." , err ) return } if in . User . ID > 0 { q := `INSERT INTO states (key, userid, value, pluginname) VALUES ($1, $2, $3, $4)` _ , err...
LoadState upserts state into the database . If there is an existing state for a given user and plugin the stateMachine will load it . If not the stateMachine will insert a starting state into the database .
333
func ( sm * StateMachine ) setEntered ( in * Msg ) { sm . stateEntered = true sm . plugin . SetMemory ( in , stateEnteredKey , true ) }
setEntered is used internally to set a state as having been entered both in memory and persisted to the database . This ensures that a stateMachine does not run a state s OnEntry function twice .
334
func New ( url string ) ( * dt . Plugin , error ) { if err := core . LoadEnvVars ( ) ; err != nil { log . Fatal ( err ) } db , err := core . ConnectDB ( "" ) if err != nil { return nil , err } c := dt . PluginConfig { } if len ( os . Getenv ( "ABOT_PATH" ) ) > 0 { p := filepath . Join ( os . Getenv ( "ABOT_...
New builds a Plugin with its trigger RPC and configuration settings from its plugin . json .
335
func SetKeywords ( p * dt . Plugin , khs ... dt . KeywordHandler ) { p . Keywords = & dt . Keywords { Dict : map [ string ] dt . KeywordFn { } , } for _ , kh := range khs { for _ , intent := range kh . Trigger . Intents { intent = strings . ToLower ( intent ) if ! language . Contains ( p . Trigger . Intents , inten...
SetKeywords processes and registers keywords with Abot s core for routing .
336
func SetStates ( p * dt . Plugin , states [ ] [ ] dt . State ) { p . States = [ ] dt . State { } for _ , ss := range states { p . States = append ( p . States , ss ... ) } }
SetStates is a convenience function provided to match the API of NewKeywords and AppendTrigger .
337
func AppendTrigger ( p * dt . Plugin , t * dt . StructuredInput ) { eng := porter2 . Stemmer for _ , cmd := range t . Commands { cmd = eng . Stem ( cmd ) if ! language . Contains ( p . Trigger . Commands , cmd ) { p . Trigger . Commands = append ( p . Trigger . Commands , cmd ) } } for _ , obj := range t . Ob...
AppendTrigger appends the StructuredInput s modified contents to a plugin . All Commands and Objects stemmed using the Porter2 Snowball algorithm .
338
func GetUser ( db * sqlx . DB , req * Request ) ( * User , error ) { u := & User { } u . FlexID = req . FlexID u . FlexIDType = req . FlexIDType if req . UserID == 0 { if req . FlexID == "" { return nil , ErrMissingFlexID } switch req . FlexIDType { case FIDTEmail , FIDTPhone , FIDTSession : default : return ...
GetUser from an HTTP request .
339
func ( u * User ) Create ( db * sqlx . DB , fidT FlexIDType , fid string ) error { hpw , err := bcrypt . GenerateFromPassword ( [ ] byte ( u . Password ) , 10 ) if err != nil { return err } tx , err := db . Beginx ( ) if err != nil { return err } q := `INSERT INTO users (name, email, password, locationid, a...
Create a new user in the database .
340
func ( u * User ) DeleteSessions ( db * sqlx . DB ) error { q := `DELETE FROM sessions WHERE userid=$1` _ , err := db . Exec ( q , u . ID ) if err != nil && err != sql . ErrNoRows { return err } return nil }
DeleteSessions removes any open sessions by the user . This enables logging out of the web - based client .
341
func ( k * Keywords ) handle ( m * Msg ) string { if k == nil { return "" } for _ , intent := range m . StructuredInput . Intents { fn , ok := k . Dict [ "I_" + intent ] if ! ok { continue } return fn ( m ) } eng := porter2 . Stemmer for _ , cmd := range m . StructuredInput . Commands { cmd = strings . ...
handle runs the first matching KeywordFn in the sentence .
342
func Dial ( ifi * net . Interface ) ( * Client , error ) { p , err := raw . ListenPacket ( ifi , protocolARP , nil ) if err != nil { return nil , err } return New ( ifi , p ) }
Dial creates a new Client using the specified network interface . Dial retrieves the IPv4 address of the interface and binds a raw socket to send and receive ARP packets .
343
func newClient ( ifi * net . Interface , p net . PacketConn , addrs [ ] net . Addr ) ( * Client , error ) { ip , err := firstIPv4Addr ( addrs ) if err != nil { return nil , err } return & Client { ifi : ifi , ip : ip , p : p , } , nil }
newClient is the internal generic implementation of newClient . It is used to allow an arbitrary net . PacketConn to be used in a Client so testing is easier to accomplish .
344
func ( c * Client ) Request ( ip net . IP ) error { if c . ip == nil { return errNoIPv4Addr } arp , err := NewPacket ( OperationRequest , c . ifi . HardwareAddr , c . ip , ethernet . Broadcast , ip ) if err != nil { return err } return c . WriteTo ( arp , ethernet . Broadcast ) }
Request sends an ARP request asking for the hardware address associated with an IPv4 address . The response if any can be read with the Read method . Unlike Resolve which provides an easier interface for getting the hardware address Request allows sending many requests in a row retrieving the responses afterwards .
345
func ( c * Client ) Read ( ) ( * Packet , * ethernet . Frame , error ) { buf := make ( [ ] byte , 128 ) for { n , _ , err := c . p . ReadFrom ( buf ) if err != nil { return nil , nil , err } p , eth , err := parsePacket ( buf [ : n ] ) if err != nil { if err == errInvalidARPPacket { continue } return nil ...
Read reads a single ARP packet and returns it together with its ethernet frame .
346
func ( c * Client ) WriteTo ( p * Packet , addr net . HardwareAddr ) error { pb , err := p . MarshalBinary ( ) if err != nil { return err } f := & ethernet . Frame { Destination : p . TargetHardwareAddr , Source : p . SenderHardwareAddr , EtherType : ethernet . EtherTypeARP , Payload : pb , } fb , err := f . Ma...
WriteTo writes a single ARP packet to addr . Note that addr should but doesn t have to match the target hardware address of the ARP packet .
347
func ( c * Client ) Reply ( req * Packet , hwAddr net . HardwareAddr , ip net . IP ) error { p , err := NewPacket ( OperationReply , hwAddr , ip , req . SenderHardwareAddr , req . SenderIP ) if err != nil { return err } return c . WriteTo ( p , req . SenderHardwareAddr ) }
Reply constructs and sends a reply to an ARP request . On the ARP layer it will be addressed to the sender address of the packet . On the ethernet layer it will be sent to the actual remote address from which the request was received . For more fine - grained control use WriteTo to write a custom response .
348
func firstIPv4Addr ( addrs [ ] net . Addr ) ( net . IP , error ) { for _ , a := range addrs { if a . Network ( ) != "ip+net" { continue } ip , _ , err := net . ParseCIDR ( a . String ( ) ) if err != nil { return nil , err } if ip4 := ip . To4 ( ) ; ip4 != nil { return ip4 , nil } } return nil , nil }
firstIPv4Addr attempts to retrieve the first detected IPv4 address from an input slice of network addresses .
349
func ( p * Packet ) MarshalBinary ( ) ( [ ] byte , error ) { b := make ( [ ] byte , 2 + 2 + 1 + 1 + 2 + ( p . IPLength * 2 ) + ( p . HardwareAddrLength * 2 ) ) binary . BigEndian . PutUint16 ( b [ 0 : 2 ] , p . HardwareType ) binary . BigEndian . PutUint16 ( b [ 2 : 4 ] , p . ProtocolType ) b [ 4 ] = p . Hardware...
MarshalBinary allocates a byte slice containing the data from a Packet . MarshalBinary never returns an error .
350
func ( p * Packet ) UnmarshalBinary ( b [ ] byte ) error { if len ( b ) < 8 { return io . ErrUnexpectedEOF } p . HardwareType = binary . BigEndian . Uint16 ( b [ 0 : 2 ] ) p . ProtocolType = binary . BigEndian . Uint16 ( b [ 2 : 4 ] ) p . HardwareAddrLength = b [ 4 ] p . IPLength = b [ 5 ] p . Operation = O...
UnmarshalBinary unmarshals a raw byte slice into a Packet .
351
func ParseFile ( path string ) ( Queries , error ) { file , err := os . Open ( path ) if err != nil { return nil , err } defer file . Close ( ) return ParseReader ( file ) }
Some helpers to read files ParseFile reads a file and return Queries or an error
352
func MustParseFile ( path string ) Queries { queries , err := ParseFile ( path ) if err != nil { panic ( err ) } return queries }
MustParseFile calls ParseFile but panic if an error occurs
353
func MustParseBytes ( b [ ] byte ) Queries { queries , err := ParseBytes ( b ) if err != nil { panic ( err ) } return queries }
MustParseBytes parses bytes but panics if an error occurs .
354
func ParseReader ( reader io . Reader ) ( Queries , error ) { var ( lastTag Tag lastLine parsedLine ) queries := make ( Queries ) scanner := bufio . NewScanner ( reader ) for scanner . Scan ( ) { line := parseLine ( scanner . Text ( ) ) switch line . Type { case lineBlank , lineComment : continue case lin...
ParseReader takes an io . Reader and returns Queries or an error .
355
func ( s * Client ) Close ( ) error { if s == nil { return nil } err := s . sender . Close ( ) return err }
Close closes the connection and cleans up .
356
func ( s * Client ) submit ( stat , vprefix string , value interface { } , suffix string , rate float32 ) error { data := bufPool . Get ( ) defer bufPool . Put ( data ) if s . prefix != "" { data . WriteString ( s . prefix ) data . WriteString ( "." ) } data . WriteString ( stat ) data . WriteString ( ":" )...
submit an already sampled raw stat
357
func ( s * Client ) includeStat ( rate float32 ) bool { if s == nil { return false } if s . sampler != nil { return s . sampler ( rate ) } return DefaultSampler ( rate ) }
check for nil client and perform sampling calculation
358
func ( s * Client ) NewSubStatter ( prefix string ) SubStatter { var c * Client if s != nil { c = & Client { prefix : joinPathComp ( s . prefix , prefix ) , sender : s . sender , sampler : s . sampler , } } return c }
NewSubStatter returns a SubStatter with appended prefix
359
func NewClientWithSender ( sender Sender , prefix string ) ( Statter , error ) { if sender == nil { return nil , fmt . Errorf ( "Client sender may not be nil" ) } return & Client { prefix : prefix , sender : sender } , nil }
NewClientWithSender returns a pointer to a new Client and an error . sender is an instance of a statsd . Sender interface and may not be nil prefix is the stastd client prefix . Can be if no prefix is desired .
360
func joinPathComp ( prefix , suffix string ) string { suffix = strings . TrimLeft ( suffix , "." ) if prefix != "" && suffix != "" { return prefix + "." + suffix } return prefix + suffix }
joinPathComp is a helper that ensures we combine path components with a dot when it s appropriate to do so ; prefix is the existing prefix and suffix is the new component being added . It returns the joined prefix .
361
func ( s * BufferedSender ) Send ( data [ ] byte ) ( int , error ) { s . runmx . RLock ( ) if ! s . running { s . runmx . RUnlock ( ) return 0 , fmt . Errorf ( "BufferedSender is not running" ) } s . withBufferLock ( func ( ) { blen := s . buffer . Len ( ) if blen > 0 && blen + len ( data ) + 1 >= s . flushBy...
Send bytes .
362
func ( s * BufferedSender ) Close ( ) error { s . runmx . Lock ( ) defer s . runmx . Unlock ( ) if ! s . running { return nil } errChan := make ( chan error ) s . running = false s . shutdown <- errChan return <- errChan }
Close Buffered Sender
363
func ( s * BufferedSender ) Start ( ) { s . runmx . Lock ( ) defer s . runmx . Unlock ( ) if s . running { return } s . running = true s . bufs = make ( chan * bytes . Buffer , 32 ) go s . run ( ) }
Start Buffered Sender Begins ticker and read loop
364
func ( s * BufferedSender ) flush ( b * bytes . Buffer ) ( int , error ) { bb := b . Bytes ( ) bbl := len ( bb ) if bb [ bbl - 1 ] == '\n' { bb = bb [ : bbl - 1 ] } n , err := s . sender . Send ( bb ) b . Truncate ( 0 ) return n , err }
send to remove endpoint and truncate buffer
365
func CheckName ( stat string ) error { if ! safeName . MatchString ( stat ) { return fmt . Errorf ( "invalid stat name: %s" , stat ) } return nil }
CheckName may be used to validate whether a stat name contains invalid characters . If invalid characters are found the function will return an error .
366
func ( s * SimpleSender ) Send ( data [ ] byte ) ( int , error ) { n , err := s . c . ( * net . UDPConn ) . WriteToUDP ( data , s . ra ) if err != nil { return 0 , err } if n == 0 { return n , errors . New ( "Wrote no bytes" ) } return n , nil }
Send sends the data to the server endpoint .
367
func NewErrors ( ) * Errors { return & Errors { Errors : make ( map [ string ] [ ] string ) , Lock : new ( sync . RWMutex ) , } }
NewErrors returns a pointer to a Errors object that has been primed and ready to go .
368
func ( v * Errors ) Append ( ers * Errors ) { for key , value := range ers . Errors { for _ , msg := range value { v . Add ( key , msg ) } } }
Append concatenates two Errors objects together . This will modify the first object in place .
369
func ( v * Errors ) Add ( key string , msg string ) { v . Lock . Lock ( ) v . Errors [ key ] = append ( v . Errors [ key ] , msg ) v . Lock . Unlock ( ) }
Add will add a new message to the list of errors using the given key . If the key already exists the message will be appended to the array of the existing messages .
370
func ( v * Errors ) Keys ( ) [ ] string { keys := [ ] string { } for key := range v . Errors { keys = append ( keys , key ) } return keys }
Keys return all field names which have error
371
func ( v * StringsMatch ) IsValid ( errors * validate . Errors ) { if strings . TrimSpace ( v . Field ) != strings . TrimSpace ( v . Field2 ) { if v . Message == "" { v . Message = fmt . Sprintf ( "%s does not equal %s." , v . Field , v . Field2 ) } errors . Add ( GenerateKey ( v . Name ) , v . Message ) } }
IsValid performs the validation equality of two strings .
372
func ( v * IntIsPresent ) IsValid ( errors * validate . Errors ) { if v . Field != 0 { return } if len ( v . Message ) > 0 { errors . Add ( GenerateKey ( v . Name ) , v . Message ) return } errors . Add ( GenerateKey ( v . Name ) , fmt . Sprintf ( "%s can not be blank." , v . Name ) ) }
IsValid adds an error if the field equals 0 .
373
func ( v * UUIDIsPresent ) IsValid ( errors * validate . Errors ) { s := v . Field . String ( ) if strings . TrimSpace ( s ) != "" && v . Field != uuid . Nil { return } if len ( v . Message ) > 0 { errors . Add ( GenerateKey ( v . Name ) , v . Message ) return } errors . Add ( GenerateKey ( v . Name ) , fmt...
IsValid adds an error if the field is not a valid uuid .
374
func ( v * TimeIsBeforeTime ) IsValid ( errors * validate . Errors ) { if v . FirstTime . UnixNano ( ) <= v . SecondTime . UnixNano ( ) { return } if len ( v . Message ) > 0 { errors . Add ( GenerateKey ( v . FirstName ) , v . Message ) return } errors . Add ( GenerateKey ( v . FirstName ) , fmt . Sprintf ( "...
IsValid adds an error if the FirstTime is after the SecondTime .
375
func ( v * TimeIsPresent ) IsValid ( errors * validate . Errors ) { t := time . Time { } if v . Field . UnixNano ( ) != t . UnixNano ( ) { return } if len ( v . Message ) > 0 { errors . Add ( GenerateKey ( v . Name ) , v . Message ) return } errors . Add ( GenerateKey ( v . Name ) , fmt . Sprintf ( "%s can ...
IsValid adds an error if the field is not a valid time .
376
func ( v * StringIsPresent ) IsValid ( errors * validate . Errors ) { if strings . TrimSpace ( v . Field ) != "" { return } if len ( v . Message ) > 0 { errors . Add ( GenerateKey ( v . Name ) , v . Message ) return } errors . Add ( GenerateKey ( v . Name ) , fmt . Sprintf ( "%s can not be blank." , v . Name ...
IsValid adds an error if the field is empty .
377
func ( v * EmailIsPresent ) IsValid ( errors * validate . Errors ) { if ! rxEmail . Match ( [ ] byte ( v . Field ) ) { if v . Message == "" { v . Message = fmt . Sprintf ( "%s does not match the email format." , v . Name ) } errors . Add ( GenerateKey ( v . Name ) , v . Message ) } }
IsValid performs the validation based on the email regexp match .
378
func ( v * EmailLike ) IsValid ( errors * validate . Errors ) { parts := strings . Split ( v . Field , "@" ) if len ( parts ) != 2 || len ( parts [ 0 ] ) == 0 || len ( parts [ 1 ] ) == 0 { if v . Message == "" { v . Message = fmt . Sprintf ( "%s does not match the email format." , v . Name ) } errors . Add ( Gene...
IsValid performs the validation based on email struct ( username
379
func ( v * RegexMatch ) IsValid ( errors * validate . Errors ) { r := regexp . MustCompile ( v . Expr ) if r . Match ( [ ] byte ( v . Field ) ) { return } if len ( v . Message ) > 0 { errors . Add ( GenerateKey ( v . Name ) , v . Message ) return } errors . Add ( GenerateKey ( v . Name ) , fmt . Sprintf ( "...
IsValid performs the validation based on the regexp match .
380
func MustNormalizeURLString ( u string , f NormalizationFlags ) string { result , e := NormalizeURLString ( u , f ) if e != nil { panic ( e ) } return result }
MustNormalizeURLString returns the normalized string and panics if an error occurs . It takes an URL string as input as well as the normalization flags .
381
func NormalizeURLString ( u string , f NormalizationFlags ) ( string , error ) { parsed , err := url . Parse ( u ) if err != nil { return "" , err } if f & FlagLowercaseHost == FlagLowercaseHost { parsed . Host = strings . ToLower ( parsed . Host ) } parsed . Host = width . Fold . String ( parsed . Host ) p...
NormalizeURLString returns the normalized string or an error if it can t be parsed into an URL object . It takes an URL string as input as well as the normalization flags .
382
func NormalizeURL ( u * url . URL , f NormalizationFlags ) string { for _ , k := range flagsOrder { if f & k == k { flags [ k ] ( u ) } } return urlesc . Escape ( u ) }
NormalizeURL returns the normalized string . It takes a parsed URL object as input as well as the normalization flags .
383
func WithTimeout ( t time . Duration ) Option { return func ( o * opts ) { o . timeout = t } }
WithTimeout is an Option that sets the timeout used by the interceptor .
384
func WithLockProvider ( p mwtypes . VolumeLockerProvider ) Option { return func ( o * opts ) { o . locker = p } }
WithLockProvider is an Option that sets the lock provider used by the interceptor .
385
func New ( ctx context . Context , domain string , ttl time . Duration , config * etcd . Config ) ( mwtypes . VolumeLockerProvider , error ) { fields := map [ string ] interface { } { } if domain == "" { domain = csictx . Getenv ( ctx , EnvVarDomain ) } domain = path . Join ( "/" , domain ) fields [ "serialvol....
New returns a new etcd volume lock provider .
386
func ( m * TryMutex ) Lock ( ) { ctx := m . LockCtx if ctx == nil { ctx = m . ctx } if err := m . mtx . Lock ( ctx ) ; err != nil { log . Debugf ( "TryMutex: lock err: %v" , err ) if err != context . Canceled && err != context . DeadlineExceeded { log . Panicf ( "TryMutex: lock panic: %v" , err ) } } }
Lock locks m . If the lock is already in use the calling goroutine blocks until the mutex is available .
387
func ( m * TryMutex ) Unlock ( ) { ctx := m . UnlockCtx if ctx == nil { ctx = m . ctx } if err := m . mtx . Unlock ( ctx ) ; err != nil { log . Debugf ( "TryMutex: unlock err: %v" , err ) if err != context . Canceled && err != context . DeadlineExceeded { log . Panicf ( "TryMutex: unlock panic: %v" , err ) } ...
Unlock unlocks m . It is a run - time error if m is not locked on entry to Unlock . A locked TryMutex is not associated with a particular goroutine . It is allowed for one goroutine to lock a Mutex and then arrange for another goroutine to unlock it .
388
func ( m * TryMutex ) Close ( ) error { if err := m . sess . Close ( ) ; err != nil { log . Errorf ( "TryMutex: close err: %v" , err ) return err } return nil }
Close closes and cleans up the underlying concurrency session .
389
func ( m * TryMutex ) TryLock ( timeout time . Duration ) bool { ctx := m . TryLockCtx if ctx == nil { ctx = m . ctx } if timeout > 0 { var cancel context . CancelFunc ctx , cancel = context . WithTimeout ( ctx , timeout ) defer cancel ( ) } if err := m . mtx . Lock ( ctx ) ; err != nil { log . Debugf ( "...
TryLock attempts to lock m . If no lock can be obtained in the specified duration then a false value is returned .
390
func ( sp * StoragePlugin ) Serve ( ctx context . Context , lis net . Listener ) error { var err error sp . serveOnce . Do ( func ( ) { ctx = csictx . WithLookupEnv ( ctx , sp . lookupEnv ) ctx = csictx . WithSetenv ( ctx , sp . setenv ) sp . initEnvVars ( ctx ) if err = sp . initEndpointPerms ( ctx , lis ) ; e...
Serve accepts incoming connections on the listener lis creating a new ServerTransport and service goroutine for each . The service goroutine read gRPC requests and then call the registered handlers to reply to them . Serve returns when lis . Accept fails with fatal errors . lis will be closed when this method returns ....
391
func isExitSignal ( s os . Signal ) ( bool , bool ) { switch s { case syscall . SIGTERM , syscall . SIGHUP , syscall . SIGINT , syscall . SIGQUIT : return true , true default : return false , false } }
isExitSignal returns a flag indicating whether a signal SIGHUP SIGINT SIGTERM or SIGQUIT . The second return value is whether it is a graceful exit . This flag is true for SIGTERM SIGHUP SIGINT and SIGQUIT .
392
func WithRequestLogging ( w io . Writer ) Option { return func ( o * opts ) { if w == nil { w = os . Stdout } o . reqw = w } }
WithRequestLogging is a Option that enables request logging for the logging interceptor .
393
func WithResponseLogging ( w io . Writer ) Option { return func ( o * opts ) { if w == nil { w = os . Stdout } o . repw = w } }
WithResponseLogging is a Option that enables response logging for the logging interceptor .
394
func rprintReqOrRep ( w io . Writer , obj interface { } ) { rv := reflect . ValueOf ( obj ) . Elem ( ) tv := rv . Type ( ) nf := tv . NumField ( ) printedColon := false printComma := false for i := 0 ; i < nf ; i ++ { name := tv . Field ( i ) . Name if strings . Contains ( name , "Secrets" ) { continue } ...
rprintReqOrRep is used by the server - side interceptors that log requests and responses .
395
func New ( ) Service { s := & service { nodeID : Name } s . vols = [ ] csi . Volume { s . newVolume ( "Mock Volume 1" , gib100 ) , s . newVolume ( "Mock Volume 2" , gib100 ) , s . newVolume ( "Mock Volume 3" , gib100 ) , } return s }
New returns a new Service .
396
func GetCSIEndpoint ( ) ( network , addr string , err error ) { protoAddr := os . Getenv ( CSIEndpoint ) if emptyRX . MatchString ( protoAddr ) { return "" , "" , errors . New ( "missing CSI_ENDPOINT" ) } return ParseProtoAddr ( protoAddr ) }
GetCSIEndpoint returns the network address specified by the environment variable CSI_ENDPOINT .
397
func GetCSIEndpointListener ( ) ( net . Listener , error ) { proto , addr , err := GetCSIEndpoint ( ) if err != nil { return nil , err } return net . Listen ( proto , addr ) }
GetCSIEndpointListener returns the net . Listener for the endpoint specified by the environment variable CSI_ENDPOINT .
398
func ParseProtoAddr ( protoAddr string ) ( proto string , addr string , err error ) { if emptyRX . MatchString ( protoAddr ) { return "" , "" , ErrParseProtoAddrRequired } if ! protoAddrGuessRX . MatchString ( protoAddr ) { if _ , err := os . Stat ( protoAddr ) ; ! os . IsNotExist ( err ) { return "unix" , protoAdd...
ParseProtoAddr parses a Golang network address .
399
func PageVolumes ( ctx context . Context , client csi . ControllerClient , req csi . ListVolumesRequest , opts ... grpc . CallOption ) ( <- chan csi . Volume , <- chan error ) { var ( cvol = make ( chan csi . Volume ) cerr = make ( chan error ) ) go func ( ) { var ( wg sync . WaitGroup pages int cancel contex...
PageVolumes issues one or more ListVolumes requests to retrieve all available volumes returning them over a Go channel .