repo
stringlengths
5
67
sha
stringlengths
40
40
path
stringlengths
4
234
url
stringlengths
85
339
language
stringclasses
6 values
split
stringclasses
3 values
doc
stringlengths
3
51.2k
sign
stringlengths
5
8.01k
problem
stringlengths
13
51.2k
output
stringlengths
0
3.87M
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
common/conn/ipc.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/common/conn/ipc.go#L120-L126
go
train
// VLANs requests a list of VLANs configured on the cluster.
func (c *engineIPC) VLANs() (*seesaw.VLANs, error)
// VLANs requests a list of VLANs configured on the cluster. func (c *engineIPC) VLANs() (*seesaw.VLANs, error)
{ var v seesaw.VLANs if err := c.client.Call("SeesawEngine.VLANs", c.ctx, &v); err != nil { return nil, err } return &v, nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
common/conn/ipc.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/common/conn/ipc.go#L129-L135
go
train
// Vservers requests a list of all vservers that are configured on the cluster.
func (c *engineIPC) Vservers() (map[string]*seesaw.Vserver, error)
// Vservers requests a list of all vservers that are configured on the cluster. func (c *engineIPC) Vservers() (map[string]*seesaw.Vserver, error)
{ var vm seesaw.VserverMap if err := c.client.Call("SeesawEngine.Vservers", c.ctx, &vm); err != nil { return nil, err } return vm.Vservers, nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
common/conn/ipc.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/common/conn/ipc.go#L153-L156
go
train
// OverrideDestination requests that the specified DestinationOverride be applied.
func (c *engineIPC) OverrideDestination(destination *seesaw.DestinationOverride) error
// OverrideDestination requests that the specified DestinationOverride be applied. func (c *engineIPC) OverrideDestination(destination *seesaw.DestinationOverride) error
{ override := &ipc.Override{Ctx: c.ctx, Destination: destination} return c.client.Call("SeesawEngine.OverrideDestination", override, nil) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
common/conn/ipc.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/common/conn/ipc.go#L159-L162
go
train
// OverrideVserver requests that the specified VserverOverride be applied.
func (c *engineIPC) OverrideVserver(vserver *seesaw.VserverOverride) error
// OverrideVserver requests that the specified VserverOverride be applied. func (c *engineIPC) OverrideVserver(vserver *seesaw.VserverOverride) error
{ override := &ipc.Override{Ctx: c.ctx, Vserver: vserver} return c.client.Call("SeesawEngine.OverrideVserver", override, nil) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
common/conn/ipc.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/common/conn/ipc.go#L165-L167
go
train
// Failover requests a failover between the Seesaw Nodes.
func (c *engineIPC) Failover() error
// Failover requests a failover between the Seesaw Nodes. func (c *engineIPC) Failover() error
{ return c.client.Call("SeesawEngine.Failover", c.ctx, nil) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ha/engine_client.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ha/engine_client.go#L47-L62
go
train
// HAConfig requests the HAConfig from the Seesaw Engine.
func (e *EngineClient) HAConfig() (*seesaw.HAConfig, error)
// HAConfig requests the HAConfig from the Seesaw Engine. func (e *EngineClient) HAConfig() (*seesaw.HAConfig, error)
{ engineConn, err := net.DialTimeout("unix", e.Socket, engineTimeout) if err != nil { return nil, fmt.Errorf("HAConfig: Dial failed: %v", err) } engineConn.SetDeadline(time.Now().Add(engineTimeout)) engine := rpc.NewClient(engineConn) defer engine.Close() var config seesaw.HAConfig ctx := ipc.NewTrustedContext(seesaw.SCHA) if err := engine.Call("SeesawEngine.HAConfig", ctx, &config); err != nil { return nil, fmt.Errorf("HAConfig: SeesawEngine.HAConfig failed: %v", err) } return &config, nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ha/engine_client.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ha/engine_client.go#L84-L99
go
train
// HAUpdate informs the Seesaw Engine of the current HAStatus. // The Seesaw Engine may request a failover in response.
func (e *EngineClient) HAUpdate(status seesaw.HAStatus) (bool, error)
// HAUpdate informs the Seesaw Engine of the current HAStatus. // The Seesaw Engine may request a failover in response. func (e *EngineClient) HAUpdate(status seesaw.HAStatus) (bool, error)
{ engineConn, err := net.DialTimeout("unix", e.Socket, engineTimeout) if err != nil { return false, fmt.Errorf("HAUpdate: Dial failed: %v", err) } engineConn.SetDeadline(time.Now().Add(engineTimeout)) engine := rpc.NewClient(engineConn) defer engine.Close() var failover bool ctx := ipc.NewTrustedContext(seesaw.SCHA) if err := engine.Call("SeesawEngine.HAUpdate", &ipc.HAStatus{ctx, status}, &failover); err != nil { return false, fmt.Errorf("HAUpdate: SeesawEngine.HAUpdate failed: %v", err) } return failover, nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ha/engine_client.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ha/engine_client.go#L117-L119
go
train
// HAUpdate does nothing.
func (e *DummyEngine) HAUpdate(status seesaw.HAStatus) (bool, error)
// HAUpdate does nothing. func (e *DummyEngine) HAUpdate(status seesaw.HAStatus) (bool, error)
{ return false, nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
common/server/server.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/common/server/server.go#L48-L53
go
train
// signalName returns a string containing the standard name for a given signal.
func signalName(s syscall.Signal) string
// signalName returns a string containing the standard name for a given signal. func signalName(s syscall.Signal) string
{ if name, ok := signalNames[s]; ok { return name } return fmt.Sprintf("SIG %d", s) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
common/server/server.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/common/server/server.go#L57-L70
go
train
// ShutdownHandler configures signal handling and initiates a shutdown if a // SIGINT, SIGQUIT or SIGTERM is received by the process.
func ShutdownHandler(server Shutdowner)
// ShutdownHandler configures signal handling and initiates a shutdown if a // SIGINT, SIGQUIT or SIGTERM is received by the process. func ShutdownHandler(server Shutdowner)
{ sigc := make(chan os.Signal, 3) signal.Notify(sigc, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGTERM) go func() { for s := range sigc { name := s.String() if sig, ok := s.(syscall.Signal); ok { name = signalName(sig) } log.Infof("Received %v, initiating shutdown...", name) server.Shutdown() } }() }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
common/server/server.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/common/server/server.go#L74-L85
go
train
// RemoveUnixSocket checks to see if the given socket already exists and // removes it if nothing responds to connections.
func RemoveUnixSocket(socket string) error
// RemoveUnixSocket checks to see if the given socket already exists and // removes it if nothing responds to connections. func RemoveUnixSocket(socket string) error
{ if _, err := os.Stat(socket); err == nil { c, err := net.DialTimeout("unix", socket, 5*time.Second) if err == nil { c.Close() return fmt.Errorf("Socket %v is in use", socket) } log.Infof("Removing stale socket %v", socket) return os.Remove(socket) } return nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
common/server/server.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/common/server/server.go#L89-L104
go
train
// ServerRunDirectory ensures that the run directory exists and has the // appropriate ownership and permissions.
func ServerRunDirectory(server string, owner, group int) error
// ServerRunDirectory ensures that the run directory exists and has the // appropriate ownership and permissions. func ServerRunDirectory(server string, owner, group int) error
{ serverRunDir := path.Join(seesaw.RunPath, server) if err := os.MkdirAll(seesaw.RunPath, 0755); err != nil { return fmt.Errorf("Failed to make run directory: %v", err) } if err := os.MkdirAll(serverRunDir, 0700); err != nil { return fmt.Errorf("Failed to make run directory: %v", err) } if err := os.Chown(serverRunDir, owner, group); err != nil { return fmt.Errorf("Failed to change ownership on run directory: %v", err) } if err := os.Chmod(serverRunDir, 0770); err != nil { return fmt.Errorf("Failed to change permissions on run directory: %v", err) } return nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
common/server/server.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/common/server/server.go#L110-L129
go
train
// RPCAccept accepts connections on the listener and dispatches them to the // RPC server for service. Unfortunately the native Go rpc.Accept function // fatals on any accept error, including temporary failures and closure of // the listener.
func RPCAccept(ln net.Listener, server *rpc.Server) error
// RPCAccept accepts connections on the listener and dispatches them to the // RPC server for service. Unfortunately the native Go rpc.Accept function // fatals on any accept error, including temporary failures and closure of // the listener. func RPCAccept(ln net.Listener, server *rpc.Server) error
{ errClosing := errors.New("use of closed network connection") for { conn, err := ln.Accept() if err != nil { if ne, ok := err.(net.Error); ok && ne.Temporary() { log.Warningf("RPC accept temporary error: %v", err) time.Sleep(1 * time.Second) continue } if oe, ok := err.(*net.OpError); ok && oe.Err.Error() == errClosing.Error() { log.Infoln("RPC accept connection closed") return nil } log.Errorf("RPC accept error: %v", err) return err } go server.ServeConn(conn) } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/config/config.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/config/config.go#L62-L69
go
train
// SourceByName returns the source that has the given name.
func SourceByName(name string) (Source, error)
// SourceByName returns the source that has the given name. func SourceByName(name string) (Source, error)
{ for s, n := range sourceNames { if n == name { return s, nil } } return -1, fmt.Errorf("unknown source %q", name) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/config/config.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/config/config.go#L72-L77
go
train
// String returns the string representation of a source.
func (s Source) String() string
// String returns the string representation of a source. func (s Source) String() string
{ if name, ok := sourceNames[s]; ok { return name } return "(unknown)" }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/config/config.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/config/config.go#L94-L109
go
train
// ReadConfig reads a cluster configuration file.
func ReadConfig(filename, clusterName string) (*Notification, error)
// ReadConfig reads a cluster configuration file. func ReadConfig(filename, clusterName string) (*Notification, error)
{ p := &pb.Cluster{} b, err := ioutil.ReadFile(filename) if err != nil { return nil, err } if err = proto.UnmarshalText(string(b), p); err != nil { return nil, err } c, err := protoToCluster(p, clusterName) if err != nil { return nil, err } return &Notification{c, false, p, SourceDisk, filename, time.Now()}, nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/config/config.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/config/config.go#L112-L117
go
train
// ConfigFromServer fetches the cluster configuration for the given cluster.
func ConfigFromServer(cluster string) (*Notification, error)
// ConfigFromServer fetches the cluster configuration for the given cluster. func ConfigFromServer(cluster string) (*Notification, error)
{ cfg := DefaultEngineConfig() cfg.ClusterName = cluster n := &Notifier{engineCfg: &cfg} return n.configFromServer() }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/config/config.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/config/config.go#L548-L575
go
train
// pruneArchive removes files from the given directory to ensure that the specified // maximums are not exceeded. It returns the number of the files removed along with // the maximums observed in the current archive.
func pruneArchive(archiveDir string, refTime time.Time, max archiveConfig) (*pruneStats, error)
// pruneArchive removes files from the given directory to ensure that the specified // maximums are not exceeded. It returns the number of the files removed along with // the maximums observed in the current archive. func pruneArchive(archiveDir string, refTime time.Time, max archiveConfig) (*pruneStats, error)
{ d, err := os.Open(archiveDir) if err != nil { return nil, err } defer d.Close() files, err := d.Readdir(0) if err != nil { return nil, err } sort.Sort(sort.Reverse(byModTime(files))) var seen, curr pruneStats for i := 0; i < len(files); i++ { curr.age = refTime.Sub(files[i].ModTime()) curr.bytes = seen.bytes + files[i].Size() curr.count = seen.count + 1 if curr.count > max.count || curr.bytes > max.bytes || curr.age > max.age { seen.filesRemoved, seen.filesErrored = removeFiles(archiveDir, files[i:]) return &seen, nil } seen = curr } return &seen, nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ncc/core.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ncc/core.go#L55-L60
go
train
// NewServer returns an initialised NCC Server struct.
func NewServer(socket string) *Server
// NewServer returns an initialised NCC Server struct. func NewServer(socket string) *Server
{ return &Server{ nccSocket: socket, shutdown: make(chan bool), } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ncc/core.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ncc/core.go#L63-L79
go
train
// Run starts the NCC server.
func (n *Server) Run()
// Run starts the NCC server. func (n *Server) Run()
{ if err := server.RemoveUnixSocket(n.nccSocket); err != nil { log.Fatalf("Failed to remove socket: %v", err) } ln, err := net.Listen("unix", n.nccSocket) if err != nil { log.Fatalf("listen error: %v", err) } defer ln.Close() defer os.Remove(n.nccSocket) seesawNCC := rpc.NewServer() seesawNCC.Register(&SeesawNCC{}) go server.RPCAccept(ln, seesawNCC) <-n.shutdown }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ha/core.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ha/core.go#L93-L107
go
train
// NewNode creates a new Node with the given NodeConfig and HAConn.
func NewNode(cfg NodeConfig, conn HAConn, engine Engine) *Node
// NewNode creates a new Node with the given NodeConfig and HAConn. func NewNode(cfg NodeConfig, conn HAConn, engine Engine) *Node
{ n := &Node{ NodeConfig: cfg, conn: conn, engine: engine, lastMasterAdvertTime: time.Now(), errChannel: make(chan error), recvChannel: make(chan *advertisement, 20), stopSenderChannel: make(chan seesaw.HAState), shutdownChannel: make(chan bool), } n.setState(seesaw.HABackup) n.resetMasterDownInterval(cfg.MasterAdvertInterval) return n }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ha/core.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ha/core.go#L110-L118
go
train
// resetMasterDownInterval calculates masterDownInterval per RFC 5798.
func (n *Node) resetMasterDownInterval(advertInterval time.Duration)
// resetMasterDownInterval calculates masterDownInterval per RFC 5798. func (n *Node) resetMasterDownInterval(advertInterval time.Duration)
{ skewTime := (time.Duration((256 - int(n.Priority))) * (advertInterval)) / 256 masterDownInterval := 3*(advertInterval) + skewTime if masterDownInterval != n.masterDownInterval { n.masterDownInterval = masterDownInterval log.Infof("resetMasterDownInterval: skewTime=%v, masterDownInterval=%v", skewTime, masterDownInterval) } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ha/core.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ha/core.go#L121-L125
go
train
// state returns the current HA state for this node.
func (n *Node) state() seesaw.HAState
// state returns the current HA state for this node. func (n *Node) state() seesaw.HAState
{ n.statusLock.RLock() defer n.statusLock.RUnlock() return n.haStatus.State }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ha/core.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ha/core.go#L128-L136
go
train
// setState changes the HA state for this node.
func (n *Node) setState(s seesaw.HAState)
// setState changes the HA state for this node. func (n *Node) setState(s seesaw.HAState)
{ n.statusLock.Lock() defer n.statusLock.Unlock() if n.haStatus.State != s { n.haStatus.State = s n.haStatus.Since = time.Now() n.haStatus.Transitions++ } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ha/core.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ha/core.go#L139-L146
go
train
// status returns the current HA status for this node.
func (n *Node) status() seesaw.HAStatus
// status returns the current HA status for this node. func (n *Node) status() seesaw.HAStatus
{ n.statusLock.Lock() defer n.statusLock.Unlock() n.haStatus.Sent = atomic.LoadUint64(&n.sendCount) n.haStatus.Received = atomic.LoadUint64(&n.receiveCount) n.haStatus.ReceivedQueued = uint64(len(n.recvChannel)) return n.haStatus }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ha/core.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ha/core.go#L149-L156
go
train
// newAdvertisement creates a new advertisement with this Node's VRID and priority.
func (n *Node) newAdvertisement() *advertisement
// newAdvertisement creates a new advertisement with this Node's VRID and priority. func (n *Node) newAdvertisement() *advertisement
{ return &advertisement{ VersionType: vrrpVersionType, VRID: n.VRID, Priority: n.Priority, AdvertInt: uint16(n.MasterAdvertInterval / time.Millisecond / 10), // AdvertInt is in centiseconds } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ha/core.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ha/core.go#L161-L172
go
train
// Run sends and receives advertisements, changes this Node's state in response to incoming // advertisements, and periodically notifies the engine of the current state. Run does not return // until Shutdown is called or an unrecoverable error occurs.
func (n *Node) Run() error
// Run sends and receives advertisements, changes this Node's state in response to incoming // advertisements, and periodically notifies the engine of the current state. Run does not return // until Shutdown is called or an unrecoverable error occurs. func (n *Node) Run() error
{ go n.receiveAdvertisements() go n.reportStatus() go n.checkConfig() for n.state() != seesaw.HAShutdown { if err := n.runOnce(); err != nil { return err } } return nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
netlink/message.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/netlink/message.go#L77-L87
go
train
// registerCallback registers a callback and returns the allocated callback ID.
func registerCallback(cbArg *callbackArg) uintptr
// registerCallback registers a callback and returns the allocated callback ID. func registerCallback(cbArg *callbackArg) uintptr
{ callbacksLock.Lock() defer callbacksLock.Unlock() cbArg.id = nextCallbackID nextCallbackID++ if _, ok := callbacks[cbArg.id]; ok { panic(fmt.Sprintf("Callback ID %d already in use", cbArg.id)) } callbacks[cbArg.id] = cbArg return cbArg.id }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
netlink/message.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/netlink/message.go#L90-L97
go
train
// unregisterCallback unregisters a callback.
func unregisterCallback(cbArg *callbackArg)
// unregisterCallback unregisters a callback. func unregisterCallback(cbArg *callbackArg)
{ callbacksLock.Lock() defer callbacksLock.Unlock() if _, ok := callbacks[cbArg.id]; !ok { panic(fmt.Sprintf("Callback ID %d not registered", cbArg.id)) } delete(callbacks, cbArg.id) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
netlink/message.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/netlink/message.go#L103-L119
go
train
// callback is the Go callback trampoline that is called from the // callbackGateway C function, which in turn gets called from libnl. // //export callback
func callback(nlm *C.struct_nl_msg, nla unsafe.Pointer) C.int
// callback is the Go callback trampoline that is called from the // callbackGateway C function, which in turn gets called from libnl. // //export callback func callback(nlm *C.struct_nl_msg, nla unsafe.Pointer) C.int
{ cbID := uintptr(nla) callbacksLock.RLock() cbArg := callbacks[cbID] callbacksLock.RUnlock() if cbArg == nil { panic(fmt.Sprintf("No netlink callback with ID %d", cbID)) } cbMsg := &Message{nlm: nlm} if err := cbArg.fn(cbMsg, cbArg.arg); err != nil { cbArg.err = err return C.NL_STOP } return C.NL_OK }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
netlink/message.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/netlink/message.go#L135-L142
go
train
// NewMessage returns an initialised netlink message.
func NewMessage(command, family, flags int) (*Message, error)
// NewMessage returns an initialised netlink message. func NewMessage(command, family, flags int) (*Message, error)
{ nlm := C.nlmsg_alloc() if nlm == nil { return nil, errors.New("failed to create netlink message") } C.genlmsg_put(nlm, C.NL_AUTO_PID, C.NL_AUTO_SEQ, C.int(family), 0, C.int(flags), C.uint8_t(command), genlVersion) return &Message{nlm: nlm}, nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
netlink/message.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/netlink/message.go#L146-L154
go
train
// NewMessageFromBytes returns a netlink message that is initialised from the // given byte slice.
func NewMessageFromBytes(nlb []byte) (*Message, error)
// NewMessageFromBytes returns a netlink message that is initialised from the // given byte slice. func NewMessageFromBytes(nlb []byte) (*Message, error)
{ nlm := C.nlmsg_alloc_size(C.size_t(len(nlb))) if nlm == nil { return nil, errors.New("failed to create netlink message") } nlh := C.nlmsg_hdr(nlm) copy((*[1 << 20]byte)(unsafe.Pointer(nlh))[:len(nlb)], nlb) return &Message{nlm: nlm}, nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
netlink/message.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/netlink/message.go#L157-L160
go
train
// Free frees resources associated with a netlink message.
func (m *Message) Free()
// Free frees resources associated with a netlink message. func (m *Message) Free()
{ C.nlmsg_free(m.nlm) m.nlm = nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
netlink/message.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/netlink/message.go#L163-L171
go
train
// Bytes returns the byte slice representation of a netlink message.
func (m *Message) Bytes() ([]byte, error)
// Bytes returns the byte slice representation of a netlink message. func (m *Message) Bytes() ([]byte, error)
{ if m.nlm == nil { return nil, errors.New("no netlink message") } nlh := C.nlmsg_hdr(m.nlm) nlb := make([]byte, nlh.nlmsg_len) copy(nlb, (*[1 << 20]byte)(unsafe.Pointer(nlh))[:nlh.nlmsg_len]) return nlb, nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
netlink/message.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/netlink/message.go#L198-L204
go
train
// Marshal converts the given struct into a netlink message. Each field within // the struct is added as netlink data, with structs and pointers to structs // being recursively added as nested data. // // Supported data types and their netlink mappings are as follows: // // uint8: NLA_U8 // uint16: NLA_U16 // uint32: NLA_U32 // uint64: NLA_U64 // string: NLA_STRING // byte array: NLA_UNSPEC // struct: NLA_NESTED // net.IP: NLA_UNSPEC // // Each field must have a `netlink' tag, which can contain the following // comma separated options: // // attr:x specify the netlink attribute for this field (required) // network value will be converted to its network byte order // omitempty if the field has a zero value it will be omitted // optional mark the field as being an optional (for unmarshalling) // // Other Go data types are unsupported and an error will be returned if one // is encountered.
func (m *Message) Marshal(v interface{}) error
// Marshal converts the given struct into a netlink message. Each field within // the struct is added as netlink data, with structs and pointers to structs // being recursively added as nested data. // // Supported data types and their netlink mappings are as follows: // // uint8: NLA_U8 // uint16: NLA_U16 // uint32: NLA_U32 // uint64: NLA_U64 // string: NLA_STRING // byte array: NLA_UNSPEC // struct: NLA_NESTED // net.IP: NLA_UNSPEC // // Each field must have a `netlink' tag, which can contain the following // comma separated options: // // attr:x specify the netlink attribute for this field (required) // network value will be converted to its network byte order // omitempty if the field has a zero value it will be omitted // optional mark the field as being an optional (for unmarshalling) // // Other Go data types are unsupported and an error will be returned if one // is encountered. func (m *Message) Marshal(v interface{}) error
{ val := reflect.Indirect(reflect.ValueOf(v)) if val.Kind() != reflect.Struct { return fmt.Errorf("%v is not a struct or a pointer to a struct", reflect.TypeOf(v)) } return marshal(val, "", nil, m.nlm) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
netlink/message.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/netlink/message.go#L209-L223
go
train
// Unmarshal parses the netlink message and fills the struct referenced by the // given pointer. The supported data types and netlink encodings are the same // as for Marshal.
func (m *Message) Unmarshal(v interface{}) error
// Unmarshal parses the netlink message and fills the struct referenced by the // given pointer. The supported data types and netlink encodings are the same // as for Marshal. func (m *Message) Unmarshal(v interface{}) error
{ val := reflect.Indirect(reflect.ValueOf(v)) if val.Kind() != reflect.Struct || !val.CanSet() { return fmt.Errorf("%v is not a pointer to a struct", reflect.TypeOf(v)) } maxAttrID, err := structMaxAttrID(val) if err != nil { return err } attrs, err := parseMessage(m.nlm, maxAttrID) if err != nil { return err } return unmarshal(val, "", nil, attrs) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
netlink/message.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/netlink/message.go#L232-L260
go
train
// SendCallback sends the netlink message. The specified callback function // will be called for each message that is received in response.
func (m *Message) SendCallback(fn CallbackFunc, arg interface{}) error
// SendCallback sends the netlink message. The specified callback function // will be called for each message that is received in response. func (m *Message) SendCallback(fn CallbackFunc, arg interface{}) error
{ s, err := newSocket() if err != nil { return err } defer s.free() if errno := C.genl_connect(s.nls); errno != 0 { return &Error{errno, "failed to connect to netlink"} } defer C.nl_close(s.nls) cbArg := &callbackArg{fn: fn, arg: arg} cbID := registerCallback(cbArg) defer unregisterCallback(cbArg) if errno := C._nl_socket_modify_cb(s.nls, C.NL_CB_VALID, C.NL_CB_CUSTOM, (C.nl_recvmsg_msg_cb_t)(unsafe.Pointer(C.callbackGateway)), C.uintptr_t(cbID)); errno != 0 { return &Error{errno, "failed to modify callback"} } // nl_send_auto_complete returns number of bytes sent or a negative // errno on failure. if errno := C.nl_send_auto_complete(s.nls, m.nlm); errno < 0 { return &Error{errno, "failed to send netlink message"} } if errno := C.nl_recvmsgs_default(s.nls); errno != 0 { return &Error{errno, "failed to receive messages"} } return nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
netlink/message.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/netlink/message.go#L263-L265
go
train
// SendMessage creates and sends a netlink message.
func SendMessage(command, family, flags int) error
// SendMessage creates and sends a netlink message. func SendMessage(command, family, flags int) error
{ return SendMessageCallback(command, family, flags, callbackDefault, nil) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
netlink/message.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/netlink/message.go#L270-L278
go
train
// SendMessageCallback creates and sends a netlink message. The specified // callback function will be called for each message that is received in // response.
func SendMessageCallback(command, family, flags int, cb CallbackFunc, arg interface{}) error
// SendMessageCallback creates and sends a netlink message. The specified // callback function will be called for each message that is received in // response. func SendMessageCallback(command, family, flags int, cb CallbackFunc, arg interface{}) error
{ msg, err := NewMessage(command, family, flags) if err != nil { return err } defer msg.Free() return msg.SendCallback(cb, arg) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
netlink/message.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/netlink/message.go#L282-L293
go
train
// SendMessageMarshalled creates a netlink message and marshals the given // struct into the message, before sending it.
func SendMessageMarshalled(command, family, flags int, v interface{}) error
// SendMessageMarshalled creates a netlink message and marshals the given // struct into the message, before sending it. func SendMessageMarshalled(command, family, flags int, v interface{}) error
{ msg, err := NewMessage(command, family, flags) if err != nil { return err } defer msg.Free() if err := msg.Marshal(v); err != nil { return err } return msg.Send() }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
netlink/message.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/netlink/message.go#L297-L299
go
train
// SendMessageUnmarshal creates and sends a netlink message. All messages // received in response will be unmarshalled into the given struct.
func SendMessageUnmarshal(command, family, flags int, v interface{}) error
// SendMessageUnmarshal creates and sends a netlink message. All messages // received in response will be unmarshalled into the given struct. func SendMessageUnmarshal(command, family, flags int, v interface{}) error
{ return SendMessageCallback(command, family, flags, callbackUnmarshal, v) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
binaries/seesaw_ha/main.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/binaries/seesaw_ha/main.go#L81-L96
go
train
// config reads the HAConfig from the engine. It does not return until it // successfully retrieves an HAConfig that has HA peering enabled.
func config(e ha.Engine) *seesaw.HAConfig
// config reads the HAConfig from the engine. It does not return until it // successfully retrieves an HAConfig that has HA peering enabled. func config(e ha.Engine) *seesaw.HAConfig
{ for { c, err := e.HAConfig() switch { case err != nil: log.Errorf("config: Failed to retrieve HAConfig: %v", err) case !c.Enabled: log.Infof("config: HA peering is currently disabled for this node") default: return c } time.Sleep(*initConfigRetryDelay) } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/bgp.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/bgp.go#L41-L43
go
train
// newBGPManager returns an initialised bgpManager struct.
func newBGPManager(engine *Engine, interval time.Duration) *bgpManager
// newBGPManager returns an initialised bgpManager struct. func newBGPManager(engine *Engine, interval time.Duration) *bgpManager
{ return &bgpManager{engine: engine, updateInterval: interval} }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/bgp.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/bgp.go#L46-L53
go
train
// run runs the BGP configuration manager.
func (b *bgpManager) run()
// run runs the BGP configuration manager. func (b *bgpManager) run()
{ ticker := time.NewTicker(b.updateInterval) for { log.V(1).Infof("Updating BGP state and statistics...") b.update() <-ticker.C } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/bgp.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/bgp.go#L56-L72
go
train
// update updates BGP related state and statistics from the BGP daemon.
func (b *bgpManager) update()
// update updates BGP related state and statistics from the BGP daemon. func (b *bgpManager) update()
{ ncc := b.engine.ncc if err := ncc.Dial(); err != nil { log.Warningf("BGP manager failed to connect to NCC: %v", err) return } defer ncc.Close() neighbors, err := ncc.BGPNeighbors() if err != nil { log.Warningf("Failed to get BGP neighbors: %v", err) return } b.lock.Lock() b.neighbors = neighbors b.lock.Unlock() }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
healthcheck/http.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/healthcheck/http.go#L52-L67
go
train
// NewHTTPChecker returns an initialised HTTPChecker.
func NewHTTPChecker(ip net.IP, port int) *HTTPChecker
// NewHTTPChecker returns an initialised HTTPChecker. func NewHTTPChecker(ip net.IP, port int) *HTTPChecker
{ return &HTTPChecker{ Target: Target{ IP: ip, Port: port, Proto: seesaw.IPProtoTCP, }, Secure: false, TLSVerify: true, Method: "GET", Proxy: false, Request: "/", Response: "", ResponseCode: 200, } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
healthcheck/http.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/healthcheck/http.go#L70-L83
go
train
// String returns the string representation of an HTTP healthcheck.
func (hc *HTTPChecker) String() string
// String returns the string representation of an HTTP healthcheck. func (hc *HTTPChecker) String() string
{ attr := []string{fmt.Sprintf("code %d", hc.ResponseCode)} if hc.Proxy { attr = append(attr, "proxy") } if hc.Secure { attr = append(attr, "secure") if hc.TLSVerify { attr = append(attr, "verify") } } s := strings.Join(attr, "; ") return fmt.Sprintf("HTTP %s %s [%s] %s", hc.Method, hc.Request, s, hc.Target) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
healthcheck/http.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/healthcheck/http.go#L86-L176
go
train
// Check executes a HTTP healthcheck.
func (hc *HTTPChecker) Check(timeout time.Duration) *Result
// Check executes a HTTP healthcheck. func (hc *HTTPChecker) Check(timeout time.Duration) *Result
{ msg := fmt.Sprintf("HTTP %s to %s", hc.Method, hc.addr()) start := time.Now() if timeout == time.Duration(0) { timeout = defaultHTTPTimeout } deadline := start.Add(timeout) u, err := url.Parse(hc.Request) if err != nil { return complete(start, "", false, err) } if hc.Secure { u.Scheme = "https" } else { u.Scheme = "http" } if u.Host == "" { u.Host = hc.IP.String() } proxy := (func(*http.Request) (*url.URL, error))(nil) if hc.Proxy { proxy = http.ProxyURL(u) } conn, err := dialTCP(hc.network(), hc.addr(), timeout, hc.Mark) if err != nil { return complete(start, "", false, err) } defer conn.Close() dialer := func(net string, addr string) (net.Conn, error) { return conn, nil } tlsConfig := &tls.Config{ InsecureSkipVerify: !hc.TLSVerify, } client := &http.Client{ CheckRedirect: func(req *http.Request, via []*http.Request) error { return errors.New("redirect not permitted") }, Transport: &http.Transport{ Dial: dialer, Proxy: proxy, TLSClientConfig: tlsConfig, }, } req, err := http.NewRequest(hc.Method, hc.Request, nil) req.URL = u // If we received a response we want to process it, even in the // presence of an error - a redirect 3xx will result in both the // response and an error being returned. conn.SetDeadline(deadline) resp, err := client.Do(req) if resp == nil { return complete(start, "", false, err) } if resp.Body != nil { defer resp.Body.Close() } err = nil // Check response code. var codeOk bool if hc.ResponseCode == 0 { codeOk = true } else if resp.StatusCode == hc.ResponseCode { codeOk = true } // Check response body. var bodyOk bool msg = fmt.Sprintf("%s; got %s", msg, resp.Status) if hc.Response == "" { bodyOk = true } else if resp.Body != nil { buf := make([]byte, len(hc.Response)) n, err := io.ReadFull(resp.Body, buf) if err != nil && err != io.ErrUnexpectedEOF { msg = fmt.Sprintf("%s; failed to read HTTP response", msg) } else if string(buf) != hc.Response { msg = fmt.Sprintf("%s; unexpected response - %q", msg, string(buf[0:n])) } else { bodyOk = true } } return complete(start, msg, codeOk && bodyOk, err) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
healthcheck/tcp.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/healthcheck/tcp.go#L46-L54
go
train
// NewTCPChecker returns an initialised TCPChecker.
func NewTCPChecker(ip net.IP, port int) *TCPChecker
// NewTCPChecker returns an initialised TCPChecker. func NewTCPChecker(ip net.IP, port int) *TCPChecker
{ return &TCPChecker{ Target: Target{ IP: ip, Port: port, Proto: seesaw.IPProtoTCP, }, } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
healthcheck/tcp.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/healthcheck/tcp.go#L57-L70
go
train
// String returns the string representation of a TCP healthcheck.
func (hc *TCPChecker) String() string
// String returns the string representation of a TCP healthcheck. func (hc *TCPChecker) String() string
{ attr := []string{} if hc.Secure { attr = append(attr, "secure") if hc.TLSVerify { attr = append(attr, "verify") } } var s string if len(attr) > 0 { s = fmt.Sprintf(" [%s]", strings.Join(attr, "; ")) } return fmt.Sprintf("TCP%s %s", s, hc.Target) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
healthcheck/tcp.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/healthcheck/tcp.go#L73-L141
go
train
// Check executes a TCP healthcheck.
func (hc *TCPChecker) Check(timeout time.Duration) *Result
// Check executes a TCP healthcheck. func (hc *TCPChecker) Check(timeout time.Duration) *Result
{ msg := fmt.Sprintf("TCP connect to %s", hc.addr()) start := time.Now() if timeout == time.Duration(0) { timeout = defaultTCPTimeout } deadline := start.Add(timeout) tcpConn, err := dialTCP(hc.network(), hc.addr(), timeout, hc.Mark) if err != nil { msg = fmt.Sprintf("%s; failed to connect", msg) return complete(start, msg, false, err) } conn := net.Conn(tcpConn) defer conn.Close() // Negotiate TLS if this is required. if hc.Secure { // TODO(jsing): We probably should allow the server name to // be specified via configuration... host, _, err := net.SplitHostPort(hc.addr()) if err != nil { msg = msg + "; failed to split host" return complete(start, msg, false, err) } tlsConfig := &tls.Config{ InsecureSkipVerify: !hc.TLSVerify, ServerName: host, } tlsConn := tls.Client(conn, tlsConfig) if err := tlsConn.Handshake(); err != nil { return complete(start, msg, false, err) } conn = tlsConn } if hc.Send == "" && hc.Receive == "" { return complete(start, msg, true, err) } err = conn.SetDeadline(deadline) if err != nil { msg = fmt.Sprintf("%s; failed to set deadline", msg) return complete(start, msg, false, err) } if hc.Send != "" { err = writeFull(conn, []byte(hc.Send)) if err != nil { msg = fmt.Sprintf("%s; failed to send request", msg) return complete(start, msg, false, err) } } if hc.Receive != "" { buf := make([]byte, len(hc.Receive)) n, err := io.ReadFull(conn, buf) if err != nil { msg = fmt.Sprintf("%s; failed to read response", msg) return complete(start, msg, false, err) } got := string(buf[0:n]) if got != hc.Receive { msg = fmt.Sprintf("%s; unexpected response - %q", msg, got) return complete(start, msg, false, err) } } return complete(start, msg, true, err) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ncc/types/ncc_types.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ncc/types/ncc_types.go#L73-L79
go
train
// Interface returns the network interface associated with the LBInterface.
func (lb *LBInterface) Interface() (*net.Interface, error)
// Interface returns the network interface associated with the LBInterface. func (lb *LBInterface) Interface() (*net.Interface, error)
{ iface, err := net.InterfaceByName(lb.Name) if err != nil { return nil, err } return iface, nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
cli/show.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/cli/show.go#L554-L561
go
train
// label returns a string containing the label with indentation and padding.
func label(l string, indent, width int) string
// label returns a string containing the label with indentation and padding. func label(l string, indent, width int) string
{ pad := width - indent - len(l) if pad < 0 { pad = 0 } return fmt.Sprintf("%s%s%s", strings.Repeat(" ", indent), l, strings.Repeat(" ", pad)) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
cli/show.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/cli/show.go#L569-L572
go
train
// printFmt formats and prints a given value with the specified label.
func printFmt(l, v string, args ...interface{})
// printFmt formats and prints a given value with the specified label. func printFmt(l, v string, args ...interface{})
{ l = label(l, subIndent, valIndent) fmt.Printf("%s %s\n", l, fmt.Sprintf(v, args...)) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
cli/show.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/cli/show.go#L575-L584
go
train
// printVal prints the given value with the specified label.
func printVal(l string, v interface{})
// printVal prints the given value with the specified label. func printVal(l string, v interface{})
{ switch f := v.(type) { case uint, uint64: printFmt(l, "%d", f) case string: printFmt(l, "%s", f) default: printFmt(l, "%v", f) } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/sync.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/sync.go#L73-L78
go
train
// String returns the string representation of a synchronisation notification // type.
func (snt SyncNoteType) String() string
// String returns the string representation of a synchronisation notification // type. func (snt SyncNoteType) String() string
{ if name, ok := syncNoteTypeNames[snt]; ok { return name } return fmt.Sprintf("(Unknown %d)", snt) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/sync.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/sync.go#L103-L125
go
train
// Register registers our Seesaw peer for synchronisation notifications.
func (s *SeesawSync) Register(node net.IP, id *SyncSessionID) error
// Register registers our Seesaw peer for synchronisation notifications. func (s *SeesawSync) Register(node net.IP, id *SyncSessionID) error
{ if id == nil { return errors.New("id is nil") } // TODO(jsing): Reject if not master? s.sync.sessionLock.Lock() session := newSyncSession(node, s.sync.nextSessionID) s.sync.nextSessionID++ s.sync.sessions[session.id] = session s.sync.sessionLock.Unlock() session.Lock() session.expiryTime = time.Now().Add(sessionDeadtime) session.Unlock() *id = session.id log.Infof("Synchronisation session %d registered by %v", *id, node) return nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/sync.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/sync.go#L128-L139
go
train
// Deregister deregisters a Seesaw peer for synchronisation.
func (s *SeesawSync) Deregister(id SyncSessionID, reply *int) error
// Deregister deregisters a Seesaw peer for synchronisation. func (s *SeesawSync) Deregister(id SyncSessionID, reply *int) error
{ s.sync.sessionLock.Lock() session, ok := s.sync.sessions[id] delete(s.sync.sessions, id) s.sync.sessionLock.Unlock() if ok { log.Infof("Synchronisation session %d deregistered with %v", id, session.node) } return nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/sync.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/sync.go#L144-L188
go
train
// Poll returns one or more synchronisation notifications to the caller, // blocking until at least one notification becomes available or the poll // timeout is reached.
func (s *SeesawSync) Poll(id SyncSessionID, sn *SyncNotes) error
// Poll returns one or more synchronisation notifications to the caller, // blocking until at least one notification becomes available or the poll // timeout is reached. func (s *SeesawSync) Poll(id SyncSessionID, sn *SyncNotes) error
{ if sn == nil { return errors.New("sync notes is nil") } s.sync.sessionLock.RLock() session, ok := s.sync.sessions[id] s.sync.sessionLock.RUnlock() if !ok { return errors.New("no session with ID %d") } // Reset expiry time and check for desynchronisation. session.Lock() session.expiryTime = time.Now().Add(sessionDeadtime) if session.desync { // TODO(jsing): Discard pending notes? sn.Notes = append(sn.Notes, SyncNote{Type: SNTDesync}) session.desync = false session.Unlock() return nil } session.Unlock() // Block until a notification becomes available or our poll expires. select { case note := <-session.notes: sn.Notes = append(sn.Notes, *note) case <-time.After(syncPollTimeout): return errors.New("poll timeout") } pollLoop: for i := 0; i < syncPollMsgLimit; i++ { select { case note := <-session.notes: sn.Notes = append(sn.Notes, *note) default: break pollLoop } } log.V(1).Infof("Sync server poll returning %d notifications", len(sn.Notes)) return nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/sync.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/sync.go#L191-L193
go
train
// Config requests the current configuration from the peer Seesaw node.
func (s *SeesawSync) Config(arg int, config *config.Notification) error
// Config requests the current configuration from the peer Seesaw node. func (s *SeesawSync) Config(arg int, config *config.Notification) error
{ return errors.New("unimplemented") }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/sync.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/sync.go#L196-L198
go
train
// Failover requests that we relinquish master state.
func (s *SeesawSync) Failover(arg int, reply *int) error
// Failover requests that we relinquish master state. func (s *SeesawSync) Failover(arg int, reply *int) error
{ return s.sync.engine.haManager.requestFailover(true) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/sync.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/sync.go#L201-L203
go
train
// Healthchecks requests the current healthchecks from the peer Seesaw node.
func (s *SeesawSync) Healthchecks(arg int, reply *int) error
// Healthchecks requests the current healthchecks from the peer Seesaw node. func (s *SeesawSync) Healthchecks(arg int, reply *int) error
{ return errors.New("unimplemented") }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/sync.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/sync.go#L218-L227
go
train
// newSyncSession returns an initialised synchronisation session.
func newSyncSession(node net.IP, id SyncSessionID) *syncSession
// newSyncSession returns an initialised synchronisation session. func newSyncSession(node net.IP, id SyncSessionID) *syncSession
{ return &syncSession{ id: id, node: node, desync: true, startTime: time.Now(), expiryTime: time.Now().Add(sessionDeadtime), notes: make(chan *SyncNote, sessionNotesQueueSize), } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/sync.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/sync.go#L232-L243
go
train
// addNote adds a notification to the synchronisation session. If the notes // channel is full the session is marked as desynchronised and the notification // is discarded.
func (ss *syncSession) addNote(note *SyncNote)
// addNote adds a notification to the synchronisation session. If the notes // channel is full the session is marked as desynchronised and the notification // is discarded. func (ss *syncSession) addNote(note *SyncNote)
{ select { case ss.notes <- note: default: ss.Lock() if !ss.desync { log.Warningf("Sync session with %v is desynchronised", ss.node) ss.desync = true } ss.Unlock() } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/sync.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/sync.go#L257-L263
go
train
// newSyncServer returns an initalised synchronisation server.
func newSyncServer(e *Engine) *syncServer
// newSyncServer returns an initalised synchronisation server. func newSyncServer(e *Engine) *syncServer
{ return &syncServer{ engine: e, heartbeatInterval: syncHeartbeatInterval, sessions: make(map[SyncSessionID]*syncSession), } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/sync.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/sync.go#L268-L299
go
train
// serve accepts connections from the given TCP listener and dispatches each // connection to the RPC server. Connections are only accepted from localhost // and the seesaw node that we are configured to peer with.
func (s *syncServer) serve(l *net.TCPListener) error
// serve accepts connections from the given TCP listener and dispatches each // connection to the RPC server. Connections are only accepted from localhost // and the seesaw node that we are configured to peer with. func (s *syncServer) serve(l *net.TCPListener) error
{ defer l.Close() s.server = rpc.NewServer() s.server.Register(&SeesawSync{s}) for { c, err := l.AcceptTCP() if err != nil { if ne, ok := err.(net.Error); ok && ne.Temporary() { time.Sleep(100 * time.Millisecond) continue } return err } raddr := c.RemoteAddr().String() host, _, err := net.SplitHostPort(raddr) if err != nil { log.Errorf("Failed to parse remote address %q: %v", raddr, err) c.Close() continue } rip := net.ParseIP(host) if rip == nil || (!rip.IsLoopback() && !rip.Equal(s.engine.config.Peer.IPv4Addr) && !rip.Equal(s.engine.config.Peer.IPv6Addr)) { log.Warningf("Rejecting connection from non-peer (%s)...", rip) c.Close() continue } log.Infof("Sync connection established from %s", rip) go s.server.ServeConn(c) } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/sync.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/sync.go#L303-L310
go
train
// notify queues a synchronisation notification with each of the active // synchronisation sessions.
func (s *syncServer) notify(sn *SyncNote)
// notify queues a synchronisation notification with each of the active // synchronisation sessions. func (s *syncServer) notify(sn *SyncNote)
{ s.sessionLock.RLock() sessions := s.sessions s.sessionLock.RUnlock() for _, ss := range sessions { ss.addNote(sn) } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/sync.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/sync.go#L314-L335
go
train
// run runs the synchronisation server, which is responsible for queueing // heartbeat notifications and removing expired synchronisation sessions.
func (s *syncServer) run() error
// run runs the synchronisation server, which is responsible for queueing // heartbeat notifications and removing expired synchronisation sessions. func (s *syncServer) run() error
{ heartbeat := time.NewTicker(s.heartbeatInterval) for { select { case <-heartbeat.C: now := time.Now() s.sessionLock.Lock() for id, ss := range s.sessions { ss.RLock() expiry := ss.expiryTime ss.RUnlock() if now.After(expiry) { log.Warningf("Sync session %d with %v has expired", id, ss.node) delete(s.sessions, id) continue } ss.addNote(&SyncNote{Type: SNTHeartbeat}) } s.sessionLock.Unlock() } } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/sync.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/sync.go#L354-L364
go
train
// newSyncClient returns an initialised synchronisation client.
func newSyncClient(e *Engine) *syncClient
// newSyncClient returns an initialised synchronisation client. func newSyncClient(e *Engine) *syncClient
{ sc := &syncClient{ engine: e, quit: make(chan bool), start: make(chan bool), stopped: make(chan bool, 1), } sc.dispatch = sc.handleNote sc.stopped <- true return sc }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/sync.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/sync.go#L367-L390
go
train
// dial establishes a connection to our peer Seesaw node.
func (sc *syncClient) dial() error
// dial establishes a connection to our peer Seesaw node. func (sc *syncClient) dial() error
{ sc.lock.Lock() defer sc.lock.Unlock() if sc.client != nil { sc.refs++ return nil } // TODO(jsing): Make this default to IPv6, if configured. peer := &net.TCPAddr{ IP: sc.engine.config.Peer.IPv4Addr, Port: sc.engine.config.SyncPort, } self := &net.TCPAddr{ IP: sc.engine.config.Node.IPv4Addr, } conn, err := net.DialTCP("tcp", self, peer) if err != nil { return fmt.Errorf("failed to connect: %v", err) } sc.client = rpc.NewClient(conn) sc.refs = 1 return nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/sync.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/sync.go#L393-L409
go
train
// close closes an existing connection to our peer Seesaw node.
func (sc *syncClient) close() error
// close closes an existing connection to our peer Seesaw node. func (sc *syncClient) close() error
{ sc.lock.Lock() defer sc.lock.Unlock() if sc.client == nil { return nil } sc.refs-- if sc.refs > 0 { return nil } if err := sc.client.Close(); err != nil { sc.client = nil return fmt.Errorf("client close failed: %v", err) } sc.client = nil return nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/sync.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/sync.go#L412-L421
go
train
// failover requests that the peer node initiate a failover.
func (sc *syncClient) failover() error
// failover requests that the peer node initiate a failover. func (sc *syncClient) failover() error
{ if err := sc.dial(); err != nil { return err } defer sc.close() if err := sc.client.Call("SeesawSync.Failover", 0, nil); err != nil { return err } return nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/sync.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/sync.go#L425-L452
go
train
// runOnce establishes a connection to the synchronisation server, registers // for notifications, polls for notifications, then deregisters.
func (sc *syncClient) runOnce()
// runOnce establishes a connection to the synchronisation server, registers // for notifications, polls for notifications, then deregisters. func (sc *syncClient) runOnce()
{ if err := sc.dial(); err != nil { log.Warningf("Sync client dial failed: %v", err) return } defer sc.close() var sid SyncSessionID self := sc.engine.config.Node.IPv4Addr // Register for synchronisation events. // TODO(jsing): Implement timeout on RPC? if err := sc.client.Call("SeesawSync.Register", self, &sid); err != nil { log.Warningf("Sync registration failed: %v", err) return } log.Infof("Registered for synchronisation notifications (ID %d)", sid) // TODO(jsing): Export synchronisation data to ECU/CLI. sc.poll(sid) // Attempt to deregister for notifications. // TODO(jsing): Implement timeout on RPC? if err := sc.client.Call("SeesawSync.Deregister", sid, nil); err != nil { log.Warningf("Sync deregistration failed: %v", err) } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/sync.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/sync.go#L456-L479
go
train
// poll polls the synchronisation server for notifications, then dispatches // them for processing.
func (sc *syncClient) poll(sid SyncSessionID)
// poll polls the synchronisation server for notifications, then dispatches // them for processing. func (sc *syncClient) poll(sid SyncSessionID)
{ for { var sn SyncNotes poll := sc.client.Go("SeesawSync.Poll", sid, &sn, nil) select { case <-poll.Done: if poll.Error != nil { log.Errorf("Synchronisation polling failed: %v", poll.Error) return } for _, note := range sn.Notes { sc.dispatch(&note) } case <-sc.quit: sc.stopped <- true return case <-time.After(syncPollTimeout): log.Warningf("Synchronisation polling timed out after %s", syncPollTimeout) return } } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/sync.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/sync.go#L482-L502
go
train
// handleNote dispatches a synchronisation note to the appropriate handler.
func (sc *syncClient) handleNote(note *SyncNote)
// handleNote dispatches a synchronisation note to the appropriate handler. func (sc *syncClient) handleNote(note *SyncNote)
{ switch note.Type { case SNTHeartbeat: log.V(1).Infoln("Sync client received heartbeat") case SNTDesync: sc.handleDesync() case SNTConfigUpdate: sc.handleConfigUpdate(note) case SNTHealthcheck: sc.handleHealthcheck(note) case SNTOverride: sc.handleOverride(note) default: log.Errorf("Unable to handle sync notification type %s (%d)", note.Type, note.Type) } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/sync.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/sync.go#L523-L535
go
train
// handleOverride handles an override notification.
func (sc *syncClient) handleOverride(sn *SyncNote)
// handleOverride handles an override notification. func (sc *syncClient) handleOverride(sn *SyncNote)
{ log.V(1).Infoln("Sync client received override notification") if o := sn.VserverOverride; o != nil { sc.engine.queueOverride(o) } if o := sn.DestinationOverride; o != nil { sc.engine.queueOverride(o) } if o := sn.BackendOverride; o != nil { sc.engine.queueOverride(o) } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/sync.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/sync.go#L538-L553
go
train
// run runs the synchronisation client.
func (sc *syncClient) run() error
// run runs the synchronisation client. func (sc *syncClient) run() error
{ for { select { case <-sc.stopped: <-sc.start log.Infof("Starting sync client...") default: sc.runOnce() select { case <-time.After(5 * time.Second): case <-sc.quit: sc.stopped <- true } } } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/sync.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/sync.go#L556-L564
go
train
// enable enables synchronisation with our peer Seesaw node.
func (sc *syncClient) enable()
// enable enables synchronisation with our peer Seesaw node. func (sc *syncClient) enable()
{ sc.lock.Lock() start := !sc.enabled sc.enabled = true sc.lock.Unlock() if start { sc.start <- true } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/sync.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/sync.go#L567-L575
go
train
// disable disables synchronisation with our peer Seesaw node.
func (sc *syncClient) disable()
// disable disables synchronisation with our peer Seesaw node. func (sc *syncClient) disable()
{ sc.lock.Lock() quit := sc.enabled sc.enabled = false sc.lock.Unlock() if quit { sc.quit <- true } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
common/seesaw/seesaw.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/common/seesaw/seesaw.go#L93-L98
go
train
// String returns the string representation of a Component.
func (sc Component) String() string
// String returns the string representation of a Component. func (sc Component) String() string
{ if name, ok := componentNames[sc]; ok { return name } return "(unknown)" }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
common/seesaw/seesaw.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/common/seesaw/seesaw.go#L159-L181
go
train
// String returns the name for the given HealthcheckType.
func (h HealthcheckType) String() string
// String returns the name for the given HealthcheckType. func (h HealthcheckType) String() string
{ switch h { case HCTypeDNS: return "DNS" case HCTypeHTTP: return "HTTP" // TODO(angusc): Drop HTTPS as a separate type. case HCTypeHTTPS: return "HTTP" // NB: Not HTTPS case HCTypeICMP: return "ICMP" case HCTypeRADIUS: return "RADIUS" case HCTypeTCP: return "TCP" // TODO(angusc): Drop TCPTLS as a separate type. case HCTypeTCPTLS: return "TCP" // NB: Not TCPTLS case HCTypeUDP: return "UDP" } return "(unknown)" }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
common/seesaw/seesaw.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/common/seesaw/seesaw.go#L213-L215
go
train
// String returns the string representation of a VIP.
func (v VIP) String() string
// String returns the string representation of a VIP. func (v VIP) String() string
{ return fmt.Sprintf("%v (%v)", v.IP, v.Type) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
common/seesaw/seesaw.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/common/seesaw/seesaw.go#L218-L230
go
train
// NewVIP returns a seesaw VIP.
func NewVIP(ip net.IP, vipSubnets map[string]*net.IPNet) *VIP
// NewVIP returns a seesaw VIP. func NewVIP(ip net.IP, vipSubnets map[string]*net.IPNet) *VIP
{ vipType := UnicastVIP switch { case IsAnycast(ip): vipType = AnycastVIP case InSubnets(ip, vipSubnets): vipType = DedicatedVIP } return &VIP{ IP: NewIP(ip), Type: vipType, } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
common/seesaw/seesaw.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/common/seesaw/seesaw.go#L236-L240
go
train
// NewIP returns a seesaw IP initialised from a net.IP address.
func NewIP(nip net.IP) IP
// NewIP returns a seesaw IP initialised from a net.IP address. func NewIP(nip net.IP) IP
{ var ip IP copy(ip[:], nip.To16()) return ip }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
common/seesaw/seesaw.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/common/seesaw/seesaw.go#L250-L252
go
train
// Equal returns true of the given seesaw.IP addresses are equal, as // determined by net.IP.Equal().
func (ip IP) Equal(eip IP) bool
// Equal returns true of the given seesaw.IP addresses are equal, as // determined by net.IP.Equal(). func (ip IP) Equal(eip IP) bool
{ return ip.IP().Equal(eip.IP()) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
common/seesaw/seesaw.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/common/seesaw/seesaw.go#L260-L265
go
train
// AF returns the address family of a seesaw IP address.
func (ip IP) AF() AF
// AF returns the address family of a seesaw IP address. func (ip IP) AF() AF
{ if ip.IP().To4() != nil { return IPv4 } return IPv6 }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
common/seesaw/seesaw.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/common/seesaw/seesaw.go#L283-L295
go
train
// String returns the name for the given protocol value.
func (proto IPProto) String() string
// String returns the name for the given protocol value. func (proto IPProto) String() string
{ switch proto { case IPProtoICMP: return "ICMP" case IPProtoICMPv6: return "ICMPv6" case IPProtoTCP: return "TCP" case IPProtoUDP: return "UDP" } return fmt.Sprintf("IP(%d)", proto) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
common/seesaw/seesaw.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/common/seesaw/seesaw.go#L313-L318
go
train
// String returns the string representation of a LBMode.
func (lbm LBMode) String() string
// String returns the string representation of a LBMode. func (lbm LBMode) String() string
{ if name, ok := modeNames[lbm]; ok { return name } return "(unknown)" }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
common/seesaw/seesaw.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/common/seesaw/seesaw.go#L342-L347
go
train
// String returns the string representation of a LBScheduler.
func (lbs LBScheduler) String() string
// String returns the string representation of a LBScheduler. func (lbs LBScheduler) String() string
{ if name, ok := schedulerNames[lbs]; ok { return name } return "(unknown)" }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
healthcheck/dial.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/healthcheck/dial.go#L68-L153
go
train
// dialTCP dials a TCP connection to the specified host and sets marking on the // socket. The host must be given as an IP address. A mark of zero results in a // normal (non-marked) connection.
func dialTCP(network, addr string, timeout time.Duration, mark int) (nc net.Conn, err error)
// dialTCP dials a TCP connection to the specified host and sets marking on the // socket. The host must be given as an IP address. A mark of zero results in a // normal (non-marked) connection. func dialTCP(network, addr string, timeout time.Duration, mark int) (nc net.Conn, err error)
{ host, port, err := net.SplitHostPort(addr) if err != nil { return nil, err } ip := net.ParseIP(host) if ip == nil { return nil, fmt.Errorf("invalid IP address %q", host) } p, err := strconv.ParseUint(port, 10, 16) if err != nil { return nil, fmt.Errorf("invalid port number %q", port) } var domain int var rsa syscall.Sockaddr switch network { case "tcp4": domain = syscall.AF_INET if ip.To4() == nil { return nil, fmt.Errorf("invalid IPv4 address %q", host) } sa := &syscall.SockaddrInet4{Port: int(p)} copy(sa.Addr[:], ip.To4()) rsa = sa case "tcp6": domain = syscall.AF_INET6 if ip.To4() != nil { return nil, fmt.Errorf("invalid IPv6 address %q", host) } sa := &syscall.SockaddrInet6{Port: int(p)} copy(sa.Addr[:], ip.To16()) rsa = sa default: return nil, fmt.Errorf("unsupported network %q", network) } c := &conn{} defer func() { if err != nil { c.Close() } }() c.fd, err = syscall.Socket(domain, syscall.SOCK_STREAM|syscall.SOCK_CLOEXEC, 0) if err != nil { return nil, os.NewSyscallError("socket", err) } if mark != 0 { if err := setSocketMark(c.fd, mark); err != nil { return nil, err } } if err := setSocketTimeout(c.fd, timeout); err != nil { return nil, err } if err := syscall.Connect(c.fd, rsa); err != nil { return nil, os.NewSyscallError("connect", err) } if err := setSocketTimeout(c.fd, 0); err != nil { return nil, err } lsa, _ := syscall.Getsockname(c.fd) rsa, _ = syscall.Getpeername(c.fd) name := fmt.Sprintf("%s %s -> %s", network, sockaddrToString(lsa), sockaddrToString(rsa)) c.f = os.NewFile(uintptr(c.fd), name) // When we call net.FileConn the socket will be made non-blocking and // we will get a *net.TCPConn in return. The *os.File needs to be // closed in addition to the *net.TCPConn when we're done (conn.Close // takes care of that for us). if c.Conn, err = net.FileConn(c.f); err != nil { return nil, err } if _, ok := c.Conn.(*net.TCPConn); !ok { return nil, fmt.Errorf("%T is not a *net.TCPConn", c.Conn) } return c, nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
healthcheck/dial.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/healthcheck/dial.go#L157-L195
go
train
// dialUDP dials a UDP connection to the specified host and sets marking on the // socket. A mark of zero results in a normal (non-marked) connection.
func dialUDP(network, addr string, timeout time.Duration, mark int) (*net.UDPConn, error)
// dialUDP dials a UDP connection to the specified host and sets marking on the // socket. A mark of zero results in a normal (non-marked) connection. func dialUDP(network, addr string, timeout time.Duration, mark int) (*net.UDPConn, error)
{ d := net.Dialer{Timeout: timeout} conn, err := d.Dial(network, addr) if err != nil { return nil, err } udpConn, ok := conn.(*net.UDPConn) if !ok { conn.Close() return nil, errors.New("dial did not return a *net.UDPConn") } if mark == 0 { return udpConn, nil } f, err := udpConn.File() if err != nil { udpConn.Close() return nil, err } defer f.Close() fd := int(f.Fd()) // Calling File results in the socket being set to blocking mode. // We need to undo this. if err := syscall.SetNonblock(fd, true); err != nil { udpConn.Close() return nil, err } if err := setSocketMark(fd, mark); err != nil { udpConn.Close() return nil, err } return udpConn, nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
healthcheck/dial.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/healthcheck/dial.go#L198-L203
go
train
// setSocketMark sets packet marking on the given socket.
func setSocketMark(fd, mark int) error
// setSocketMark sets packet marking on the given socket. func setSocketMark(fd, mark int) error
{ if err := syscall.SetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_MARK, mark); err != nil { return os.NewSyscallError("failed to set mark", err) } return nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
healthcheck/dial.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/healthcheck/dial.go#L206-L214
go
train
// setSocketTimeout sets the receive and send timeouts on the given socket.
func setSocketTimeout(fd int, timeout time.Duration) error
// setSocketTimeout sets the receive and send timeouts on the given socket. func setSocketTimeout(fd int, timeout time.Duration) error
{ tv := syscall.NsecToTimeval(timeout.Nanoseconds()) for _, opt := range []int{syscall.SO_RCVTIMEO, syscall.SO_SNDTIMEO} { if err := syscall.SetsockoptTimeval(fd, syscall.SOL_SOCKET, opt, &tv); err != nil { return os.NewSyscallError("setsockopt", err) } } return nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/vserver.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/vserver.go#L61-L78
go
train
// newVserver returns an initialised vserver struct.
func newVserver(e *Engine) *vserver
// newVserver returns an initialised vserver struct. func newVserver(e *Engine) *vserver
{ return &vserver{ engine: e, ncc: ncclient.NewNCC(e.config.NCCSocket), fwm: make(map[seesaw.AF]uint32), active: make(map[seesaw.IP]bool), lbVservers: make(map[seesaw.IP]*seesaw.Vserver), vips: make(map[seesaw.VIP]bool), overrideChan: make(chan seesaw.Override, 5), notify: make(chan *checkNotification, 20), update: make(chan *config.Vserver, 1), quit: make(chan bool, 1), stopped: make(chan bool, 1), } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/vserver.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/vserver.go#L81-L86
go
train
// String returns a string representing a vserver.
func (v *vserver) String() string
// String returns a string representing a vserver. func (v *vserver) String() string
{ if v.config != nil { return v.config.Name } return fmt.Sprintf("Unconfigured vserver %+v", *v) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/vserver.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/vserver.go#L110-L136
go
train
// ipvsService returns an IPVS Service for the given service.
func (svc *service) ipvsService() *ipvs.Service
// ipvsService returns an IPVS Service for the given service. func (svc *service) ipvsService() *ipvs.Service
{ var flags ipvs.ServiceFlags if svc.ventry.Persistence > 0 { flags |= ipvs.SFPersistent } if svc.ventry.OnePacket { flags |= ipvs.SFOnePacket } var ip net.IP switch { case svc.fwm > 0 && svc.af == seesaw.IPv4: ip = net.IPv4zero case svc.fwm > 0 && svc.af == seesaw.IPv6: ip = net.IPv6zero default: ip = svc.ip.IP() } return &ipvs.Service{ Address: ip, Protocol: ipvs.IPProto(svc.proto), Port: svc.port, Scheduler: svc.ventry.Scheduler.String(), FirewallMark: svc.fwm, Flags: flags, Timeout: uint32(svc.ventry.Persistence), } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/vserver.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/vserver.go#L140-L145
go
train
// ipvsEqual returns true if two services have the same IPVS configuration. // Transient state and the services' destinations are ignored.
func (s *service) ipvsEqual(other *service) bool
// ipvsEqual returns true if two services have the same IPVS configuration. // Transient state and the services' destinations are ignored. func (s *service) ipvsEqual(other *service) bool
{ return s.ipvsSvc.Equal(*other.ipvsSvc) && s.ventry.Mode == other.ventry.Mode && s.ventry.LThreshold == other.ventry.LThreshold && s.ventry.UThreshold == other.ventry.UThreshold }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/vserver.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/vserver.go#L148-L155
go
train
// String returns a string representing a service.
func (s *service) String() string
// String returns a string representing a service. func (s *service) String() string
{ if s.fwm != 0 { return fmt.Sprintf("%v/fwm:%d", s.ip, s.fwm) } ip := s.ip.String() port := strconv.Itoa(int(s.port)) return fmt.Sprintf("%v/%v", net.JoinHostPort(ip, port), s.proto) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/vserver.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/vserver.go#L181-L199
go
train
// ipvsDestination returns an IPVS Destination for the given destination.
func (dst *destination) ipvsDestination() *ipvs.Destination
// ipvsDestination returns an IPVS Destination for the given destination. func (dst *destination) ipvsDestination() *ipvs.Destination
{ var flags ipvs.DestinationFlags switch dst.service.ventry.Mode { case seesaw.LBModeNone: log.Warningf("%v: Unspecified LB mode", dst) case seesaw.LBModeDSR: flags |= ipvs.DFForwardRoute case seesaw.LBModeNAT: flags |= ipvs.DFForwardMasq } return &ipvs.Destination{ Address: dst.ip.IP(), Port: dst.service.port, Weight: dst.weight, Flags: flags, LowerThreshold: uint32(dst.service.ventry.LThreshold), UpperThreshold: uint32(dst.service.ventry.UThreshold), } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/vserver.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/vserver.go#L203-L205
go
train
// ipvsEqual returns true if two destinations have the same IPVS configuration. // Transient state is ignored.
func (d *destination) ipvsEqual(other *destination) bool
// ipvsEqual returns true if two destinations have the same IPVS configuration. // Transient state is ignored. func (d *destination) ipvsEqual(other *destination) bool
{ return d.ipvsDst.Equal(*other.ipvsDst) }