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
engine/vserver.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/vserver.go#L208-L215
go
train
// String returns a string representing a destination.
func (d *destination) String() string
// String returns a string representing a destination. func (d *destination) String() string
{ if d.service.fwm != 0 { return fmt.Sprintf("%v", d.ip) } ip := d.ip.String() port := strconv.Itoa(int(d.service.port)) return fmt.Sprintf("%v/%v", net.JoinHostPort(ip, port), d.service.proto) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/vserver.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/vserver.go#L218-L220
go
train
// name returns the name of a destination.
func (d *destination) name() string
// name returns the name of a destination. func (d *destination) name() string
{ return fmt.Sprintf("%v/%v", d.service.vserver.String(), d.String()) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/vserver.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/vserver.go#L235-L246
go
train
// newCheckKey returns an initialised checkKey.
func newCheckKey(vip, bip seesaw.IP, port uint16, proto seesaw.IPProto, h *config.Healthcheck) checkKey
// newCheckKey returns an initialised checkKey. func newCheckKey(vip, bip seesaw.IP, port uint16, proto seesaw.IPProto, h *config.Healthcheck) checkKey
{ return checkKey{ vserverIP: vip, backendIP: bip, servicePort: port, serviceProtocol: proto, healthcheckMode: h.Mode, healthcheckType: h.Type, healthcheckPort: h.Port, name: h.Name, } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/vserver.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/vserver.go#L249-L254
go
train
// String returns the string representation of a checkKey.
func (c checkKey) String() string
// String returns the string representation of a checkKey. func (c checkKey) String() string
{ return fmt.Sprintf("%v:%d/%v backend %v:%d/%v %v %v port %d (%s)", c.vserverIP, c.servicePort, c.serviceProtocol, c.backendIP, c.servicePort, c.serviceProtocol, c.healthcheckMode, c.healthcheckType, c.healthcheckPort, c.name) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/vserver.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/vserver.go#L267-L273
go
train
// newCheck returns an initialised check.
func newCheck(key checkKey, v *vserver, h *config.Healthcheck) *check
// newCheck returns an initialised check. func newCheck(key checkKey, v *vserver, h *config.Healthcheck) *check
{ return &check{ key: key, vserver: v, healthcheck: h, } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/vserver.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/vserver.go#L290-L325
go
train
// expandServices returns a list of services that have been expanded from the // vserver configuration.
func (v *vserver) expandServices() map[serviceKey]*service
// expandServices returns a list of services that have been expanded from the // vserver configuration. func (v *vserver) expandServices() map[serviceKey]*service
{ if v.config.UseFWM { return v.expandFWMServices() } svcs := make(map[serviceKey]*service) for _, af := range seesaw.AFs() { var ip net.IP switch af { case seesaw.IPv4: ip = v.config.Host.IPv4Addr case seesaw.IPv6: ip = v.config.Host.IPv6Addr } if ip == nil { continue } for _, entry := range v.config.Entries { svc := &service{ serviceKey: serviceKey{ af: af, proto: entry.Proto, port: entry.Port, }, ip: seesaw.NewIP(ip), ventry: entry, vserver: v, dests: make(map[destinationKey]*destination, 0), stats: &seesaw.ServiceStats{}, } svc.ipvsSvc = svc.ipvsService() svcs[svc.serviceKey] = svc } } return svcs }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/vserver.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/vserver.go#L329-L373
go
train
// expandFWMServices returns a list of services that have been expanded from the // vserver configuration for a firewall mark based vserver.
func (v *vserver) expandFWMServices() map[serviceKey]*service
// expandFWMServices returns a list of services that have been expanded from the // vserver configuration for a firewall mark based vserver. func (v *vserver) expandFWMServices() map[serviceKey]*service
{ svcs := make(map[serviceKey]*service) for _, af := range seesaw.AFs() { var ip net.IP switch af { case seesaw.IPv4: ip = v.config.Host.IPv4Addr case seesaw.IPv6: ip = v.config.Host.IPv6Addr } if ip == nil { continue } // Persistence, etc., is stored in the VserverEntry. For FWM services, these // values must be the same for all VserverEntries, so just use the first // one. var ventry *config.VserverEntry for _, entry := range v.config.Entries { ventry = entry break } if v.fwm[af] == 0 { mark, err := v.engine.fwmAlloc.get() if err != nil { log.Fatalf("%v: failed to get mark: %v", v, err) } v.fwm[af] = mark } svc := &service{ serviceKey: serviceKey{ af: af, fwm: v.fwm[af], }, ip: seesaw.NewIP(ip), ventry: ventry, vserver: v, stats: &seesaw.ServiceStats{}, } svc.ipvsSvc = svc.ipvsService() svcs[svc.serviceKey] = svc } return svcs }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/vserver.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/vserver.go#L377-L401
go
train
// expandDests returns a list of destinations that have been expanded from the // vserver configuration and a given service.
func (v *vserver) expandDests(svc *service) map[destinationKey]*destination
// expandDests returns a list of destinations that have been expanded from the // vserver configuration and a given service. func (v *vserver) expandDests(svc *service) map[destinationKey]*destination
{ dsts := make(map[destinationKey]*destination, len(v.config.Backends)) for _, backend := range v.config.Backends { var ip net.IP switch svc.af { case seesaw.IPv4: ip = backend.Host.IPv4Addr case seesaw.IPv6: ip = backend.Host.IPv6Addr } if ip == nil { continue } dst := &destination{ destinationKey: newDestinationKey(ip), service: svc, backend: backend, weight: backend.Weight, } dst.ipvsDst = dst.ipvsDestination() dst.stats = &seesaw.DestinationStats{} dsts[dst.destinationKey] = dst } return dsts }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/vserver.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/vserver.go#L405-L448
go
train
// expandChecks returns a list of checks that have been expanded from the // vserver configuration.
func (v *vserver) expandChecks() map[checkKey]*check
// expandChecks returns a list of checks that have been expanded from the // vserver configuration. func (v *vserver) expandChecks() map[checkKey]*check
{ checks := make(map[checkKey]*check) for _, svc := range v.services { for _, dest := range svc.dests { dest.checks = make([]*check, 0) if !dest.backend.Enabled { continue } for _, hc := range v.config.Healthchecks { // vserver-level healthchecks key := newCheckKey(svc.ip, dest.ip, 0, 0, hc) c := checks[key] if c == nil { c = newCheck(key, v, hc) checks[key] = c } dest.checks = append(dest.checks, c) c.dests = append(c.dests, dest) } // ventry-level healthchecks if v.config.UseFWM { for _, ve := range svc.vserver.config.Entries { for _, hc := range ve.Healthchecks { key := newCheckKey(svc.ip, dest.ip, ve.Port, ve.Proto, hc) c := newCheck(key, v, hc) checks[key] = c dest.checks = append(dest.checks, c) c.dests = append(c.dests, dest) } } } else { for _, hc := range svc.ventry.Healthchecks { key := newCheckKey(svc.ip, dest.ip, svc.port, svc.proto, hc) c := newCheck(key, v, hc) checks[key] = c dest.checks = append(dest.checks, c) c.dests = append(c.dests, dest) } } } } return checks }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/vserver.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/vserver.go#L451-L457
go
train
// healthchecks returns the vserverChecks for a vserver.
func (v *vserver) healthchecks() vserverChecks
// healthchecks returns the vserverChecks for a vserver. func (v *vserver) healthchecks() vserverChecks
{ vc := vserverChecks{vserverName: v.config.Name} if v.enabled { vc.checks = v.checks } return vc }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/vserver.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/vserver.go#L462-L512
go
train
// run invokes a vserver. This is a long-lived Go routine that lasts for the // duration of the vserver, reacting to configuration changes and healthcheck // notifications.
func (v *vserver) run()
// run invokes a vserver. This is a long-lived Go routine that lasts for the // duration of the vserver, reacting to configuration changes and healthcheck // notifications. func (v *vserver) run()
{ statsTicker := time.NewTicker(v.engine.config.StatsInterval) for { select { case <-v.quit: // Shutdown active vservers, services and destinations. // There is no race between this and new healthcheck // notifications, since they are also handled via the // same vserver go routine. v.downAll() statsTicker.Stop() v.engine.hcManager.vcc <- vserverChecks{vserverName: v.config.Name} v.unconfigureVIPs() // Return any firewall marks that were allocated to // this vserver. for _, fwm := range v.fwm { v.engine.fwmAlloc.put(fwm) } v.stopped <- true return case o := <-v.overrideChan: v.handleOverride(o) v.engine.hcManager.vcc <- v.healthchecks() case config := <-v.update: v.handleConfigUpdate(config) v.engine.hcManager.vcc <- v.healthchecks() case n := <-v.notify: v.handleCheckNotification(n) case <-statsTicker.C: v.updateStats() } // Something changed - export a new vserver snapshot. // The goroutine that drains v.engine.vserverChan also does a blocking write // to each vserver's vserver.notify channel, which is drained by each // vserver's goroutine (i.e., this one). So we need a timeout to avoid a // deadlock. timeout := time.After(1 * time.Second) select { case v.engine.vserverChan <- v.snapshot(): case <-timeout: log.Warningf("%v: failed to send snapshot", v) } } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/vserver.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/vserver.go#L543-L611
go
train
// handleConfigUpdate updates the internal structures of a vserver using the // new configuration.
func (v *vserver) handleConfigUpdate(config *config.Vserver)
// handleConfigUpdate updates the internal structures of a vserver using the // new configuration. func (v *vserver) handleConfigUpdate(config *config.Vserver)
{ if config == nil { return } switch { case v.config == nil: v.configInit(config) return case v.enabled && !vserverEnabled(config, v.vserverOverride.State()): log.Infof("%v: disabling vserver", v) v.downAll() v.unconfigureVIPs() v.configInit(config) return case !v.enabled && !vserverEnabled(config, v.vserverOverride.State()): v.configInit(config) return case !v.enabled && vserverEnabled(config, v.vserverOverride.State()): log.Infof("%v: enabling vserver", v) v.configInit(config) return default: // Some updates require changes to the iptables rules. Since we currently // can't make fine-grained changes to the iptables rules, we must // re-initialise the entire vserver. This is necessary in the following // scenarios: // - A port or protocol is added, removed or changed // - A vserver is changed from FWM to non-FWM or vice versa // - A vserverEntry is changed from DSR to NAT or vice versa // // (Changing a VIP address also requires updating iptables, but // v.configUpdate() handles this case) // // TODO(angusc): Add support for finer-grained updates to ncc so we can // avoid re-initialising the vserver in these cases. reInit := false switch { case config.UseFWM != v.config.UseFWM: reInit = true case len(config.Entries) != len(v.config.Entries): reInit = true default: for k, entry := range config.Entries { if v.config.Entries[k] == nil { reInit = true break } if v.config.Entries[k].Mode != entry.Mode { reInit = true break } } } if reInit { log.Infof("%v: re-initialising vserver", v) v.downAll() v.unconfigureVIPs() v.configInit(config) return } v.config = config v.configUpdate() } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/vserver.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/vserver.go#L615-L637
go
train
// configInit initialises all services, destinations, healthchecks and VIPs for // a vserver.
func (v *vserver) configInit(config *config.Vserver)
// configInit initialises all services, destinations, healthchecks and VIPs for // a vserver. func (v *vserver) configInit(config *config.Vserver)
{ v.config = config v.enabled = vserverEnabled(config, v.vserverOverride.State()) newSvcs := v.expandServices() // Preserve stats if this is a reinit for svcK, svc := range newSvcs { svc.dests = v.expandDests(svc) if oldSvc, ok := v.services[svcK]; ok { *svc.stats = *oldSvc.stats for dstK, dst := range svc.dests { if oldDst, ok := oldSvc.dests[dstK]; ok { *dst.stats = *oldDst.stats } } } } v.services = newSvcs v.checks = v.expandChecks() if v.enabled { v.configureVIPs() } return }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/vserver.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/vserver.go#L641-L712
go
train
// configUpdate updates the services, destinations, checks, and VIPs for a // vserver.
func (v *vserver) configUpdate()
// configUpdate updates the services, destinations, checks, and VIPs for a // vserver. func (v *vserver) configUpdate()
{ newSvcs := v.expandServices() for svcKey, newSvc := range newSvcs { if svc, ok := v.services[svcKey]; ok { if svc.ip.Equal(newSvc.ip) { svc.update(newSvc) continue } log.Infof("%v: service %v: new IP address: %v", v, svc, newSvc.ip) v.deleteService(svc) } log.Infof("%v: adding new service: %v", v, newSvc) v.services[svcKey] = newSvc v.updateState(newSvc.ip) } for svcKey, svc := range v.services { if newSvcs[svcKey] == nil { // Service no longer exists v.deleteService(svc) continue } // Update destinations for this service newDests := v.expandDests(svc) for destKey, newDest := range newDests { if dest, ok := svc.dests[destKey]; ok { dest.update(newDest) continue } log.Infof("%v: service %v: adding new destination: %v", v, svc, newDest) svc.dests[destKey] = newDest } for destKey, dest := range svc.dests { if newDests[destKey] == nil { // Destination no longer exists if dest.active { dest.healthy = false svc.updateState() } log.Infof("%v: service %v: deleting destination: %v", v, svc, dest) delete(svc.dests, destKey) } } } // If a VIP has been re-IP'd or has no services configured, remove the old // VIP from the interface. needVIPs := make(map[seesaw.IP]bool) for _, svc := range v.services { needVIPs[svc.ip] = true } for vip := range v.vips { if !needVIPs[vip.IP] { log.Infof("%v: unconfiguring no longer needed VIP %v", v, vip.IP) v.unconfigureVIP(&vip) } } checks := v.expandChecks() for k, oldCheck := range v.checks { if checks[k] != nil { checks[k].description = oldCheck.description checks[k].status = oldCheck.status } } v.checks = checks // TODO(baptr): Should this only happen if it's enabled? v.configureVIPs() return }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/vserver.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/vserver.go#L715-L724
go
train
// deleteService deletes a service for a vserver.
func (v *vserver) deleteService(s *service)
// deleteService deletes a service for a vserver. func (v *vserver) deleteService(s *service)
{ if s.active { s.healthy = false v.updateState(s.ip) } log.Infof("%v: deleting service: %v", v, s) delete(v.services, s.serviceKey) // TODO(baptr): Once service contains seesaw.VIP, move check and // unconfigureVIP here. }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/vserver.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/vserver.go#L728-L749
go
train
// handleCheckNotification processes a checkNotification, bringing // destinations, services, and vservers up or down appropriately.
func (v *vserver) handleCheckNotification(n *checkNotification)
// handleCheckNotification processes a checkNotification, bringing // destinations, services, and vservers up or down appropriately. func (v *vserver) handleCheckNotification(n *checkNotification)
{ if !v.enabled { log.Infof("%v: ignoring healthcheck notification %s (vserver disabled)", v, n.description) return } check := v.checks[n.key] if check == nil { log.Warningf("%v: unknown check key %v", v, n.key) return } transition := (check.status.State != n.status.State) check.description = n.description check.status = n.status if transition { log.Infof("%v: healthcheck %s - %v (%s)", v, n.description, n.status.State, n.status.Message) for _, d := range check.dests { d.updateState() } } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/vserver.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/vserver.go#L752-L771
go
train
// handleOverride processes an Override.
func (v *vserver) handleOverride(o seesaw.Override)
// handleOverride processes an Override. func (v *vserver) handleOverride(o seesaw.Override)
{ switch override := o.(type) { case *seesaw.VserverOverride: if v.vserverOverride == *override { // No change return } v.vserverOverride = *override if vserverEnabled(v.config, o.State()) == v.enabled { // enable state not changed - nothing to do return } // TODO(angusc): handle backend and destination overrides. default: return } if v.config != nil { v.handleConfigUpdate(v.config) } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/vserver.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/vserver.go#L775-L785
go
train
// vserverEnabled returns true if a vserver having the given configuration // and override state should be enabled.
func vserverEnabled(config *config.Vserver, os seesaw.OverrideState) bool
// vserverEnabled returns true if a vserver having the given configuration // and override state should be enabled. func vserverEnabled(config *config.Vserver, os seesaw.OverrideState) bool
{ switch { case config == nil: return false case os == seesaw.OverrideDisable: return false case os == seesaw.OverrideEnable: return true } return config.Enabled }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/vserver.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/vserver.go#L788-L819
go
train
// snapshot exports the current running state of the vserver.
func (v *vserver) snapshot() *seesaw.Vserver
// snapshot exports the current running state of the vserver. func (v *vserver) snapshot() *seesaw.Vserver
{ if v.config == nil { return nil } sv := &seesaw.Vserver{ Name: v.config.Name, Entries: make([]*seesaw.VserverEntry, 0, len(v.config.Entries)), Host: seesaw.Host{ Hostname: v.config.Hostname, IPv4Addr: v.config.IPv4Addr, IPv4Mask: v.config.IPv4Mask, IPv6Addr: v.config.IPv6Addr, IPv6Mask: v.config.IPv6Mask, }, FWM: make(map[seesaw.AF]uint32), Services: make(map[seesaw.ServiceKey]*seesaw.Service, len(v.services)), OverrideState: v.vserverOverride.State(), Enabled: v.enabled, ConfigEnabled: v.config.Enabled, Warnings: v.config.Warnings, } for _, ve := range v.config.Entries { sv.Entries = append(sv.Entries, ve.Snapshot()) } sv.FWM[seesaw.IPv4] = v.fwm[seesaw.IPv4] sv.FWM[seesaw.IPv6] = v.fwm[seesaw.IPv6] for _, s := range v.services { ss := s.snapshot() sv.Services[ss.ServiceKey] = ss } return sv }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/vserver.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/vserver.go#L823-L851
go
train
// updateState updates the state of a destination based on the state of checks // and propagates state changes to the service level if necessary.
func (d *destination) updateState()
// updateState updates the state of a destination based on the state of checks // and propagates state changes to the service level if necessary. func (d *destination) updateState()
{ // The destination is healthy if the backend is enabled and *all* the checks // for that destination are healthy. healthy := d.backend.Enabled if healthy { for _, c := range d.checks { if c.status.State != healthcheck.StateHealthy { healthy = false break } } } if d.healthy == healthy { return } d.healthy = healthy switch { case d.service.active && d.healthy: // The service is already active. Bringing up the dest will have no effect // on the service or vserver state. d.up() case d.service.active != d.healthy || d.service.healthy != d.healthy: // The service may need to be brought up or down. d.service.updateState() } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/vserver.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/vserver.go#L854-L866
go
train
// up brings up a destination.
func (d *destination) up()
// up brings up a destination. func (d *destination) up()
{ d.active = true log.Infof("%v: %v backend %v up", d.service.vserver, d.service, d) ncc := d.service.vserver.ncc if err := ncc.Dial(); err != nil { log.Fatalf("%v: failed to connect to NCC: %v", d.service.vserver, err) } defer ncc.Close() if err := ncc.IPVSAddDestination(d.service.ipvsSvc, d.ipvsDst); err != nil { log.Fatalf("%v: failed to add destination %v: %v", d.service.vserver, d, err) } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/vserver.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/vserver.go#L869-L881
go
train
// down takes down a destination.
func (d *destination) down()
// down takes down a destination. func (d *destination) down()
{ d.active = false log.Infof("%v: %v backend %v down", d.service.vserver, d.service, d) ncc := d.service.vserver.ncc if err := ncc.Dial(); err != nil { log.Fatalf("%v: failed to connect to NCC: %v", d.service.vserver, err) } defer ncc.Close() if err := ncc.IPVSDeleteDestination(d.service.ipvsSvc, d.ipvsDst); err != nil { log.Fatalf("%v: failed to delete destination %v: %v", d.service.vserver, d, err) } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/vserver.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/vserver.go#L884-L923
go
train
// update updates a destination while preserving its running state.
func (d *destination) update(dest *destination)
// update updates a destination while preserving its running state. func (d *destination) update(dest *destination)
{ if d.destinationKey != dest.destinationKey { log.Fatalf("%v: can't update destination %v using %v: destinationKey mismatch: %v != %v", d.service.vserver, d, dest, d.destinationKey, dest.destinationKey) } log.Infof("%v: %v updating destination %v", d.service.vserver, d.service, d) updateIPVS := d.active && !d.ipvsEqual(dest) dest.active = d.active dest.healthy = d.healthy dest.stats = d.stats *d = *dest if !d.healthy { return } if !d.backend.Enabled { log.Infof("%v: %v disabling destination %v", d.service.vserver, d.service, d) d.healthy = false d.service.updateState() return } if !updateIPVS { return } log.Infof("%v: %v updating IPVS destination %v", d.service.vserver, d.service, d) ncc := d.service.vserver.ncc if err := ncc.Dial(); err != nil { log.Fatalf("%v: failed to connect to NCC: %v", d.service.vserver, err) } defer ncc.Close() if err := ncc.IPVSUpdateDestination(d.service.ipvsSvc, d.ipvsDst); err != nil { log.Fatalf("%v: failed to update destination %v: %v", d.service.vserver, d, err) } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/vserver.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/vserver.go#L926-L937
go
train
// snapshot exports the current running state of a destination.
func (d *destination) snapshot() *seesaw.Destination
// snapshot exports the current running state of a destination. func (d *destination) snapshot() *seesaw.Destination
{ return &seesaw.Destination{ Backend: d.backend, Name: d.name(), VserverName: d.service.vserver.String(), Stats: d.stats, Enabled: d.backend.Enabled, Weight: d.weight, Healthy: d.healthy, Active: d.active, } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/vserver.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/vserver.go#L941-L1005
go
train
// updateState updates the state of a service based on the state of its // destinations and propagates state changes to the vserver level if necessary.
func (s *service) updateState()
// updateState updates the state of a service based on the state of its // destinations and propagates state changes to the vserver level if necessary. func (s *service) updateState()
{ // The service is considered healthy if: // 1) No watermarks are configured, and at least one destination is healthy. // OR // 2) (Num healthy dests) / (Num backends) >= high watermark. // OR // 3) Service is already healthy, and // (Num healthy dests) / (Num backends) >= low watermark. numBackends := 0 numHealthyDests := 0 for _, d := range s.dests { if d.backend.InService { numBackends++ } if d.healthy { numHealthyDests++ } } threshold := s.ventry.LowWatermark if !s.healthy { threshold = s.ventry.HighWatermark } var healthy bool switch { case numBackends == 0 || numHealthyDests == 0: healthy = false case threshold == 0.0: healthy = numHealthyDests >= 1 default: healthy = float32(numHealthyDests)/float32(numBackends) >= threshold } if s.healthy == healthy { // no change in service state, just update destinations s.updateDests() return } oldHealth := "unhealthy" newHealth := "unhealthy" if s.healthy { oldHealth = "healthy" } if healthy { newHealth = "healthy" } log.Infof("%v: %v: %d/%d destinations are healthy, service was %v, now %v", s.vserver, s, numHealthyDests, numBackends, oldHealth, newHealth) s.healthy = healthy vserverActive := s.vserver.active[s.ip] switch { case vserverActive && s.healthy: // The vserver is already active. Bringing up the service will have no // effect on the vserver state. s.up() case vserverActive != s.healthy: // The vserver may need to be brought up or down. s.vserver.updateState(s.ip) } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/vserver.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/vserver.go#L1009-L1025
go
train
// updateDests brings the destinations for a service up or down based on the // state of the service and the health of each destination.
func (s *service) updateDests()
// updateDests brings the destinations for a service up or down based on the // state of the service and the health of each destination. func (s *service) updateDests()
{ for _, d := range s.dests { if !s.active { d.stats.DestinationStats = &ipvs.DestinationStats{} if d.active { d.down() } continue } switch { case !d.healthy && d.active: d.down() case d.healthy && !d.active: d.up() } } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/vserver.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/vserver.go#L1028-L1045
go
train
// up brings up a service and all healthy destinations.
func (s *service) up()
// up brings up a service and all healthy destinations. func (s *service) up()
{ s.active = true log.Infof("%v: %v service up", s.vserver, s) ncc := s.vserver.ncc if err := ncc.Dial(); err != nil { log.Fatalf("%v: failed to connect to NCC: %v", s.vserver, err) } defer ncc.Close() log.Infof("%v: adding IPVS service %v", s.vserver, s.ipvsSvc) if err := ncc.IPVSAddService(s.ipvsSvc); err != nil { log.Fatalf("%v: failed to add service %v: %v", s.vserver, s, err) } // Update destinations *after* the IPVS service exists. s.updateDests() }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/vserver.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/vserver.go#L1049-L1066
go
train
// down takes down all destinations for a service, then takes down the // service.
func (s *service) down()
// down takes down all destinations for a service, then takes down the // service. func (s *service) down()
{ s.active = false s.stats.ServiceStats = &ipvs.ServiceStats{} log.Infof("%v: %v service down", s.vserver, s) ncc := s.vserver.ncc if err := ncc.Dial(); err != nil { log.Fatalf("%v: failed to connect to NCC: %v", s.vserver, err) } defer ncc.Close() // Remove IPVS destinations *before* the IPVS service is removed. s.updateDests() if err := ncc.IPVSDeleteService(s.ipvsSvc); err != nil { log.Fatalf("%v: failed to delete service %v: %v", s.vserver, s, err) } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/vserver.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/vserver.go#L1069-L1097
go
train
// update updates a service while preserving its running state.
func (s *service) update(svc *service)
// update updates a service while preserving its running state. func (s *service) update(svc *service)
{ if s.serviceKey != svc.serviceKey { log.Fatalf("%v: can't update service %v using %v: serviceKey mismatch: %v != %v", s.vserver, s, svc, s.serviceKey, svc.serviceKey) } log.Infof("%v: updating service %v", s.vserver, s) updateIPVS := s.active && !s.ipvsEqual(svc) svc.active = s.active svc.healthy = s.healthy svc.stats = s.stats svc.dests = s.dests *s = *svc if !updateIPVS { return } log.Infof("%v: %v updating IPVS service", s.vserver, s) ncc := s.vserver.ncc if err := ncc.Dial(); err != nil { log.Fatalf("%v: failed to connect to NCC: %v", s.vserver, err) } defer ncc.Close() if err := ncc.IPVSUpdateService(s.ipvsSvc); err != nil { log.Fatalf("%v: failed to update service %v: %v", s.vserver, s, err) } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/vserver.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/vserver.go#L1100-L1133
go
train
// updateStats updates the IPVS statistics for this service.
func (s *service) updateStats()
// updateStats updates the IPVS statistics for this service. func (s *service) updateStats()
{ if !s.active { return } log.V(1).Infof("%v: updating IPVS statistics for %v", s.vserver, s) ncc := s.vserver.ncc if err := ncc.Dial(); err != nil { log.Fatalf("%v: failed to connect to NCC: %v", s.vserver, err) } defer ncc.Close() ipvsSvc, err := ncc.IPVSGetService(s.ipvsSvc) if err != nil { log.Warningf("%v: failed to get statistics for %v: %v", s.vserver, s, err) return } s.stats.ServiceStats = ipvsSvc.Statistics for _, ipvsDst := range ipvsSvc.Destinations { found := false for _, d := range s.dests { if d.ipvsDst.Address.Equal(ipvsDst.Address) && d.ipvsDst.Port == ipvsDst.Port { d.stats.DestinationStats = ipvsDst.Statistics found = true break } } if !found { log.Warningf("%v: got statistics for unknown destination %v", s.vserver, ipvsDst) } } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/vserver.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/vserver.go#L1136-L1176
go
train
// snapshot exports the current running state of a service.
func (s *service) snapshot() *seesaw.Service
// snapshot exports the current running state of a service. func (s *service) snapshot() *seesaw.Service
{ ss := &seesaw.Service{ ServiceKey: seesaw.ServiceKey{ AF: s.af, Proto: s.proto, Port: s.port, }, Mode: s.ventry.Mode, Scheduler: s.ventry.Scheduler, OnePacket: s.ventry.OnePacket, Persistence: s.ventry.Persistence, IP: s.ip.IP(), Healthy: s.healthy, Enabled: s.vserver.enabled, Active: s.active, Stats: s.stats, Destinations: make(map[string]*seesaw.Destination), LowWatermark: s.ventry.LowWatermark, HighWatermark: s.ventry.HighWatermark, } for _, d := range s.dests { sd := d.snapshot() ss.Destinations[sd.Backend.Hostname] = sd } numBackends := 0 numHealthyDests := 0 for _, d := range s.dests { if d.backend.InService { numBackends++ } if d.healthy { numHealthyDests++ } } if numBackends > 0 { ss.CurrentWatermark = float32(numHealthyDests) / float32(numBackends) } return ss }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/vserver.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/vserver.go#L1180-L1207
go
train
// updateState updates the state of an IP for a vserver based on the state of // that IP's services.
func (v *vserver) updateState(ip seesaw.IP)
// updateState updates the state of an IP for a vserver based on the state of // that IP's services. func (v *vserver) updateState(ip seesaw.IP)
{ // A vserver anycast IP is healthy if *all* services for that IP are healthy. // A vserver unicast IP is healthy if *any* services for that IP are healthy. var healthy bool for _, s := range v.services { if !s.ip.Equal(ip) { continue } healthy = s.healthy if !healthy && seesaw.IsAnycast(ip.IP()) { break } if healthy && !seesaw.IsAnycast(ip.IP()) { break } } if v.active[ip] == healthy { v.updateServices(ip) return } switch { case !healthy && v.active[ip]: v.down(ip) case healthy && !v.active[ip]: v.up(ip) } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/vserver.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/vserver.go#L1211-L1229
go
train
// updateServices brings the services for a vserver up or down based on the // state of the vserver and the health of each service.
func (v *vserver) updateServices(ip seesaw.IP)
// updateServices brings the services for a vserver up or down based on the // state of the vserver and the health of each service. func (v *vserver) updateServices(ip seesaw.IP)
{ for _, s := range v.services { if !s.ip.Equal(ip) { continue } if !v.active[ip] { if s.active { s.down() } continue } switch { case !s.healthy && s.active: s.down() case s.healthy && !s.active: s.up() } } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/vserver.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/vserver.go#L1233-L1274
go
train
// up brings up all healthy services for an IP address for a vserver, then // brings up the IP address.
func (v *vserver) up(ip seesaw.IP)
// up brings up all healthy services for an IP address for a vserver, then // brings up the IP address. func (v *vserver) up(ip seesaw.IP)
{ ncc := v.engine.ncc if err := ncc.Dial(); err != nil { log.Fatalf("%v: failed to connect to NCC: %v", v, err) } defer ncc.Close() v.active[ip] = true v.updateServices(ip) // If this is an anycast VIP, start advertising a BGP route. nip := ip.IP() if seesaw.IsAnycast(nip) { // TODO(jsing): Create an LBVserver that only encapsulates // the necessary state, rather than storing a full vserver // snapshot. lbVserver := v.snapshot() lbVserver.Services = nil lbVserver.Warnings = nil if err := v.engine.lbInterface.AddVserver(lbVserver, ip.AF()); err != nil { log.Fatalf("%v: failed to add Vserver: %v", v, err) } v.lbVservers[ip] = lbVserver vip := seesaw.NewVIP(nip, nil) if err := v.engine.lbInterface.AddVIP(vip); err != nil { log.Fatalf("%v: failed to add VIP %v: %v", v, ip, err) } // TODO(angusc): Filter out anycast VIPs for non-anycast clusters further // upstream. if v.engine.config.AnycastEnabled { log.Infof("%v: advertising BGP route for %v", v, ip) if err := ncc.BGPAdvertiseVIP(nip); err != nil { log.Fatalf("%v: failed to advertise VIP %v: %v", v, ip, err) } } else { log.Warningf("%v: %v is an anycast VIP, but anycast is not enabled", v, ip) } } log.Infof("%v: VIP %v up", v, ip) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/vserver.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/vserver.go#L1277-L1286
go
train
// downAll takes down all IP addresses and services for a vserver.
func (v *vserver) downAll()
// downAll takes down all IP addresses and services for a vserver. func (v *vserver) downAll()
{ for _, s := range v.services { if v.active[s.ip] { v.down(s.ip) } if s.active { s.down() } } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/vserver.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/vserver.go#L1290-L1320
go
train
// down takes down an IP address for a vserver, then takes down all services // for that IP address.
func (v *vserver) down(ip seesaw.IP)
// down takes down an IP address for a vserver, then takes down all services // for that IP address. func (v *vserver) down(ip seesaw.IP)
{ ncc := v.engine.ncc if err := ncc.Dial(); err != nil { log.Fatalf("%v: failed to connect to NCC: %v", v, err) } defer ncc.Close() // If this is an anycast VIP, withdraw the BGP route. nip := ip.IP() if seesaw.IsAnycast(nip) { if v.engine.config.AnycastEnabled { log.Infof("%v: withdrawing BGP route for %v", v, ip) if err := ncc.BGPWithdrawVIP(nip); err != nil { log.Fatalf("%v: failed to withdraw VIP %v: %v", v, ip, err) } } vip := seesaw.NewVIP(nip, nil) if err := v.engine.lbInterface.DeleteVIP(vip); err != nil { log.Fatalf("%v: failed to remove VIP %v: %v", v, ip, err) } if err := v.engine.lbInterface.DeleteVserver(v.lbVservers[ip], ip.AF()); err != nil { log.Fatalf("%v: failed to delete Vserver: %v", v, err) } delete(v.lbVservers, ip) } // TODO(jsing): Should we delay while the BGP routes propagate? delete(v.active, ip) v.updateServices(ip) log.Infof("%v: VIP %v down", v, ip) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/vserver.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/vserver.go#L1330-L1363
go
train
// configureVIPs configures VIPs on the load balancing interface.
func (v *vserver) configureVIPs()
// configureVIPs configures VIPs on the load balancing interface. func (v *vserver) configureVIPs()
{ ncc := v.engine.ncc if err := ncc.Dial(); err != nil { log.Fatalf("%v: failed to connect to NCC: %v", v, err) } defer ncc.Close() // TODO(ncope): Return to iterating over v.services once they contain seesaw.VIPs. for _, vip := range v.config.VIPs { if _, ok := v.vips[*vip]; ok { continue } // TODO(angusc): Set up anycast Vservers here as well (without bringing up the VIP). if vip.Type == seesaw.AnycastVIP { continue } // TODO(jsing): Create a ncc.LBVserver that only encapsulates // the necessary state, rather than storing a full vserver // snapshot. lbVserver := v.snapshot() lbVserver.Services = nil lbVserver.Warnings = nil if err := v.engine.lbInterface.AddVserver(lbVserver, vip.IP.AF()); err != nil { log.Fatalf("%v: failed to add Vserver: %v", v, err) } v.lbVservers[vip.IP] = lbVserver if err := v.engine.lbInterface.AddVIP(vip); err != nil { log.Fatalf("%v: failed to add VIP %v: %v", v, vip.IP, err) } v.vips[*vip] = true } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/vserver.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/vserver.go#L1366-L1387
go
train
// unconfigureVIP removes a unicast VIP from the load balancing interface.
func (v *vserver) unconfigureVIP(vip *seesaw.VIP)
// unconfigureVIP removes a unicast VIP from the load balancing interface. func (v *vserver) unconfigureVIP(vip *seesaw.VIP)
{ configured, ok := v.vips[*vip] if !ok { return } if configured { ncc := v.engine.ncc if err := ncc.Dial(); err != nil { log.Fatalf("%v: failed to connect to NCC: %v", v, err) } defer ncc.Close() if err := v.engine.lbInterface.DeleteVIP(vip); err != nil { log.Fatalf("%v: failed to remove VIP %v: %v", v, vip, err) } if err := v.engine.lbInterface.DeleteVserver(v.lbVservers[vip.IP], vip.IP.AF()); err != nil { log.Fatalf("%v: failed to delete Vserver: %v", v, err) } delete(v.lbVservers, vip.IP) } delete(v.vips, *vip) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/vserver.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/vserver.go#L1390-L1402
go
train
// unconfigureVIPs removes unicast VIPs from the load balancing interface.
func (v *vserver) unconfigureVIPs()
// unconfigureVIPs removes unicast VIPs from the load balancing interface. func (v *vserver) unconfigureVIPs()
{ ncc := v.engine.ncc if err := ncc.Dial(); err != nil { log.Fatalf("%v: failed to connect to NCC: %v", v, err) } defer ncc.Close() // TODO(jsing): At a later date this will need to support VLAN // interfaces and dedicated VIP subnets. for vip := range v.vips { v.unconfigureVIP(&vip) } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
engine/config/fetcher.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/engine/config/fetcher.go#L86-L130
go
train
// fetchFromHost attempts to fetch the specified URL from a specific host.
func (f *fetcher) fetchFromHost(ip net.IP, url, contentType string) ([]byte, error)
// fetchFromHost attempts to fetch the specified URL from a specific host. func (f *fetcher) fetchFromHost(ip net.IP, url, contentType string) ([]byte, error)
{ // TODO(angusc): connection timeout? tcpAddr := &net.TCPAddr{IP: ip, Port: f.port} tcpConn, err := net.DialTCP("tcp", nil, tcpAddr) if err != nil { return nil, err } defer tcpConn.Close() tcpConn.SetDeadline(time.Now().Add(f.timeout)) dialer := func(net string, addr string) (net.Conn, error) { return tcpConn, nil } client := &http.Client{ CheckRedirect: func(req *http.Request, via []*http.Request) error { return errors.New("HTTP redirect prohibited") }, Transport: &http.Transport{ Dial: dialer, DisableKeepAlives: true, TLSClientConfig: &tls.Config{ RootCAs: f.certs, }, }, } req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, err } req.Header.Add("Connection", "close") resp, err := client.Do(req) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("received HTTP status %s", resp.Status) } if ct := resp.Header.Get("Content-Type"); ct != contentType { return nil, fmt.Errorf("unexpected Content-Type: %q", ct) } return ioutil.ReadAll(resp.Body) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
netlink/netlink.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/netlink/netlink.go#L48-L51
go
train
// uint16FromNetwork converts the given value from its network byte order.
func uint16FromNetwork(u uint16) uint16
// uint16FromNetwork converts the given value from its network byte order. func uint16FromNetwork(u uint16) uint16
{ b := *(*[2]byte)(unsafe.Pointer(&u)) return binary.BigEndian.Uint16(b[:]) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
netlink/netlink.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/netlink/netlink.go#L54-L58
go
train
// uint16ToNetwork converts the given value to its network byte order.
func uint16ToNetwork(u uint16) uint16
// uint16ToNetwork converts the given value to its network byte order. func uint16ToNetwork(u uint16) uint16
{ var b [2]byte binary.BigEndian.PutUint16(b[:], u) return *(*uint16)(unsafe.Pointer(&b)) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
netlink/netlink.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/netlink/netlink.go#L61-L64
go
train
// uint32FromNetwork converts the given value from its network byte order.
func uint32FromNetwork(u uint32) uint32
// uint32FromNetwork converts the given value from its network byte order. func uint32FromNetwork(u uint32) uint32
{ b := *(*[4]byte)(unsafe.Pointer(&u)) return binary.BigEndian.Uint32(b[:]) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
netlink/netlink.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/netlink/netlink.go#L67-L71
go
train
// uint32ToNetwork converts the given value to its network byte order.
func uint32ToNetwork(u uint32) uint32
// uint32ToNetwork converts the given value to its network byte order. func uint32ToNetwork(u uint32) uint32
{ var b [4]byte binary.BigEndian.PutUint32(b[:], u) return *(*uint32)(unsafe.Pointer(&b)) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
netlink/netlink.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/netlink/netlink.go#L74-L77
go
train
// uint64FromNetwork converts the given value from its network byte order.
func uint64FromNetwork(u uint64) uint64
// uint64FromNetwork converts the given value from its network byte order. func uint64FromNetwork(u uint64) uint64
{ b := *(*[8]byte)(unsafe.Pointer(&u)) return binary.BigEndian.Uint64(b[:]) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
netlink/netlink.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/netlink/netlink.go#L80-L84
go
train
// uint64ToNetwork converts the given value to its network byte order.
func uint64ToNetwork(u uint64) uint64
// uint64ToNetwork converts the given value to its network byte order. func uint64ToNetwork(u uint64) uint64
{ var b [8]byte binary.BigEndian.PutUint64(b[:], u) return *(*uint64)(unsafe.Pointer(&b)) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
netlink/netlink.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/netlink/netlink.go#L130-L157
go
train
// structMaxAttrID returns the maximum attribute ID found on netlink tagged // fields within the given struct and any untagged structs it contains.
func structMaxAttrID(v reflect.Value) (uint16, error)
// structMaxAttrID returns the maximum attribute ID found on netlink tagged // fields within the given struct and any untagged structs it contains. func structMaxAttrID(v reflect.Value) (uint16, error)
{ if v.Kind() != reflect.Struct { return 0, fmt.Errorf("%v is not a struct", v.Type()) } st := v.Type() var maxAttrID uint16 for i := 0; i < st.NumField(); i++ { ft, fv := st.Field(i), v.Field(i) fp, err := parseFieldParams(ft.Tag.Get("netlink")) if err != nil { return 0, err } if fp != nil && fp.attr > maxAttrID { maxAttrID = fp.attr } if fp == nil && fv.Kind() == reflect.Struct { attrID, err := structMaxAttrID(fv) if err != nil { return 0, err } if attrID > maxAttrID { maxAttrID = attrID } } } return maxAttrID, nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
netlink/netlink.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/netlink/netlink.go#L539-L542
go
train
// Error returns the string representation of a netlink error.
func (e *Error) Error() string
// Error returns the string representation of a netlink error. func (e *Error) Error() string
{ nle := C.GoString(C.nl_geterror(e.errno)) return fmt.Sprintf("%s: %s", e.msg, strings.ToLower(nle)) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
netlink/netlink.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/netlink/netlink.go#L545-L564
go
train
// Family returns the family identifier for the specified family name.
func Family(name string) (int, error)
// Family returns the family identifier for the specified family name. func Family(name string) (int, error)
{ s, err := newSocket() if err != nil { return -1, err } defer s.free() if errno := C.genl_connect(s.nls); errno != 0 { return -1, &Error{errno, "failed to connect to netlink"} } defer C.nl_close((*C.struct_nl_sock)(s.nls)) cn := C.CString(name) defer C.free(unsafe.Pointer(cn)) family := C.genl_ctrl_resolve(s.nls, cn) if family < 0 { return -1, errors.New("failed to resolve family name") } return int(family), nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ncc/ip.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ncc/ip.go#L45-L50
go
train
// validateInterface validates the name of a network interface.
func validateInterface(iface *net.Interface) error
// validateInterface validates the name of a network interface. func validateInterface(iface *net.Interface) error
{ if !ifaceNameRegexp.MatchString(iface.Name) { return fmt.Errorf("Invalid interface name %q", iface.Name) } return nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ncc/ip.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ncc/ip.go#L54-L64
go
train
// ipRunOutput runs the Linux ip(1) command with the specified arguments and // returns the output.
func ipRunOutput(cmd string, args ...interface{}) (string, error)
// ipRunOutput runs the Linux ip(1) command with the specified arguments and // returns the output. func ipRunOutput(cmd string, args ...interface{}) (string, error)
{ cmdStr := fmt.Sprintf(cmd, args...) ipArgs := strings.Split(cmdStr, " ") log.Infof("%s %s", ipCmd, cmdStr) ip := exec.Command(ipCmd, ipArgs...) out, err := ip.Output() if err != nil { return "", fmt.Errorf("IP run %q: %v", cmdStr, err) } return string(out), nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ncc/ip.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ncc/ip.go#L67-L70
go
train
// ipRun runs the Linux ip(1) command with the specified arguments.
func ipRun(cmd string, args ...interface{}) error
// ipRun runs the Linux ip(1) command with the specified arguments. func ipRun(cmd string, args ...interface{}) error
{ _, err := ipRunOutput(cmd, args...) return err }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ncc/ip.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ncc/ip.go#L74-L84
go
train
// ipRunAFOutput runs the Linux ip(1) command with the given address family // and specified arguments and returns the output.
func ipRunAFOutput(family seesaw.AF, cmd string, args ...interface{}) (string, error)
// ipRunAFOutput runs the Linux ip(1) command with the given address family // and specified arguments and returns the output. func ipRunAFOutput(family seesaw.AF, cmd string, args ...interface{}) (string, error)
{ switch family { case seesaw.IPv4: cmd = fmt.Sprintf("-f inet %s", cmd) case seesaw.IPv6: cmd = fmt.Sprintf("-f inet6 %s", cmd) default: return "", fmt.Errorf("Unknown address family %s", family) } return ipRunOutput(cmd, args...) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ncc/ip.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ncc/ip.go#L88-L91
go
train
// ipRunAF runs the Linux ip(1) command with the given address family and // specified arguments.
func ipRunAF(family seesaw.AF, cmd string, args ...interface{}) error
// ipRunAF runs the Linux ip(1) command with the given address family and // specified arguments. func ipRunAF(family seesaw.AF, cmd string, args ...interface{}) error
{ _, err := ipRunAFOutput(family, cmd, args...) return err }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ncc/ip.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ncc/ip.go#L96-L102
go
train
// ipRunIface runs the Linux ip(1) command with the specified arguments, after // validating the given network interface name. This function should be called // if the interface name is included in the arguments.
func ipRunIface(iface *net.Interface, cmd string, args ...interface{}) error
// ipRunIface runs the Linux ip(1) command with the specified arguments, after // validating the given network interface name. This function should be called // if the interface name is included in the arguments. func ipRunIface(iface *net.Interface, cmd string, args ...interface{}) error
{ if err := validateInterface(iface); err != nil { return err } _, err := ipRunOutput(cmd, args...) return err }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ncc/ip.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ncc/ip.go#L106-L139
go
train
// ifaceDown sets the interface link state to down and preserves IPv6 addresses // for both the given interface and any associated VLAN interfaces.
func ifaceDown(pIface *net.Interface) error
// ifaceDown sets the interface link state to down and preserves IPv6 addresses // for both the given interface and any associated VLAN interfaces. func ifaceDown(pIface *net.Interface) error
{ out, err := ipRunOutput("link show dev %s", pIface.Name) if !strings.Contains(out, "state UP") { return nil } // Unlike IPv4, the kernel removes IPv6 addresses when the link goes down. We // don't want that behavior, so we have to preserve the addresses manually. // TODO(angusc): See if we can get a sysctl or something added to the kernel // so we can avoid doing this. ipv6Addrs := make(map[string]*net.Interface) ifaces, err := vlanInterfaces(pIface) if err != nil { return err } ifaces = append(ifaces, pIface) for _, iface := range ifaces { out, err = ipRunOutput("-6 addr show dev %s scope global", iface.Name) for _, line := range strings.Split(out, "\n") { if match := ipv6AddrRegexp.FindStringSubmatch(line); match != nil { ipv6Addrs[match[1]] = iface } } } if err := ifaceFastDown(pIface); err != nil { return err } for addr, iface := range ipv6Addrs { if err := ipRunIface(iface, "addr add %s dev %s", addr, iface.Name); err != nil { return err } } return nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ncc/ip.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ncc/ip.go#L153-L155
go
train
// ifaceSetMAC sets the interface MAC address.
func ifaceSetMAC(iface *net.Interface) error
// ifaceSetMAC sets the interface MAC address. func ifaceSetMAC(iface *net.Interface) error
{ return ipRunIface(iface, "link set %s address %s", iface.Name, iface.HardwareAddr) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ncc/ip.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ncc/ip.go#L158-L163
go
train
// ifaceAddIPAddr adds the given IP address to the network interface.
func ifaceAddIPAddr(iface *net.Interface, ip net.IP, mask net.IPMask) error
// ifaceAddIPAddr adds the given IP address to the network interface. func ifaceAddIPAddr(iface *net.Interface, ip net.IP, mask net.IPMask) error
{ if ip.To4() != nil { return ifaceAddIPv4Addr(iface, ip, mask) } return ifaceAddIPv6Addr(iface, ip, mask) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ncc/ip.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ncc/ip.go#L166-L177
go
train
// ifaceAddIPv4Addr adds the given IPv4 address to the network interface.
func ifaceAddIPv4Addr(iface *net.Interface, ip net.IP, mask net.IPMask) error
// ifaceAddIPv4Addr adds the given IPv4 address to the network interface. func ifaceAddIPv4Addr(iface *net.Interface, ip net.IP, mask net.IPMask) error
{ if ip.To4() == nil { return fmt.Errorf("IP %v is not a valid IPv4 address", ip) } brd := make(net.IP, net.IPv4len) copy(brd, ip.To4()) for i := 0; i < net.IPv4len; i++ { brd[i] |= ^mask[i] } prefixLen, _ := mask.Size() return ipRunIface(iface, "addr add %s/%d brd %s dev %s", ip, prefixLen, brd, iface.Name) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ncc/ip.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ncc/ip.go#L180-L183
go
train
// ifaceAddIPv6Addr adds the given IPv6 address to the network interface.
func ifaceAddIPv6Addr(iface *net.Interface, ip net.IP, mask net.IPMask) error
// ifaceAddIPv6Addr adds the given IPv6 address to the network interface. func ifaceAddIPv6Addr(iface *net.Interface, ip net.IP, mask net.IPMask) error
{ prefixLen, _ := mask.Size() return ipRunIface(iface, "addr add %s/%d dev %s", ip, prefixLen, iface.Name) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ncc/ip.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ncc/ip.go#L197-L228
go
train
// ifaceAddVLAN creates a new VLAN interface on the given physical interface.
func ifaceAddVLAN(iface *net.Interface, vlan *seesaw.VLAN) error
// ifaceAddVLAN creates a new VLAN interface on the given physical interface. func ifaceAddVLAN(iface *net.Interface, vlan *seesaw.VLAN) error
{ name := fmt.Sprintf("%s.%d", iface.Name, vlan.ID) err := ipRunIface(iface, "link add link %s name %s type vlan id %d", iface.Name, name, vlan.ID) if err != nil { return fmt.Errorf("Failed to create VLAN interface %q: %v", name, err) } vlanIface, err := net.InterfaceByName(name) if err != nil { return fmt.Errorf("Failed to find newly created VLAN interface %q: %v", name, err) } if err := sysctlInitIface(vlanIface.Name); err != nil { return fmt.Errorf("Failed to initialise sysctls for VLAN interface %q: %v", name, err) } if vlan.IPv4Addr != nil { if err := ifaceAddIPv4Addr(vlanIface, vlan.IPv4Addr, vlan.IPv4Mask); err != nil { return fmt.Errorf("Failed to add %v to VLAN interface %q", vlan.IPv4Addr, name) } } if vlan.IPv6Addr != nil { if err := ifaceAddIPv6Addr(vlanIface, vlan.IPv6Addr, vlan.IPv6Mask); err != nil { return fmt.Errorf("Failed to add %v to VLAN interface %q", vlan.IPv6Addr, name) } } if iface.Flags&net.FlagUp == 0 { return nil } return ifaceUp(vlanIface) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ncc/ip.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ncc/ip.go#L231-L238
go
train
// ifaceDelVLAN removes a VLAN interface from the given physical interface.
func ifaceDelVLAN(iface *net.Interface, vlan *seesaw.VLAN) error
// ifaceDelVLAN removes a VLAN interface from the given physical interface. func ifaceDelVLAN(iface *net.Interface, vlan *seesaw.VLAN) error
{ name := fmt.Sprintf("%s.%d", iface.Name, vlan.ID) vlanIface, err := net.InterfaceByName(name) if err != nil { return fmt.Errorf("Failed to find VLAN interface %q: %v", name, err) } return ipRunIface(vlanIface, "link del dev %s", vlanIface.Name) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ncc/ip.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ncc/ip.go#L242-L256
go
train
// ifaceFlushVLANs removes all VLAN interfaces from the given physical // interface.
func ifaceFlushVLANs(iface *net.Interface) error
// ifaceFlushVLANs removes all VLAN interfaces from the given physical // interface. func ifaceFlushVLANs(iface *net.Interface) error
{ if err := validateInterface(iface); err != nil { return err } vlanIfaces, err := vlanInterfaces(iface) if err != nil { return err } for _, vlanIface := range vlanIfaces { if err := ipRunIface(vlanIface, "link del dev %s", vlanIface.Name); err != nil { return fmt.Errorf("Failed to remove %s from %s: %v", vlanIface.Name, iface.Name, err) } } return nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ncc/ip.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ncc/ip.go#L259-L268
go
train
// routeDefaultIPv4 returns the default route for IPv4 traffic.
func routeDefaultIPv4() (net.IP, error)
// routeDefaultIPv4 returns the default route for IPv4 traffic. func routeDefaultIPv4() (net.IP, error)
{ out, err := ipRunAFOutput(seesaw.IPv4, "route show default") if err != nil { return nil, err } if dr := routeDefaultIPv4Regexp.FindStringSubmatch(out); dr != nil { return net.ParseIP(dr[1]).To4(), nil } return nil, fmt.Errorf("Default route not found") }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ncc/ip.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ncc/ip.go#L272-L278
go
train
// removeRoutes deletes the routing table entries for a VIP, from the specified // table.
func removeRoutes(table string, vip net.IP) error
// removeRoutes deletes the routing table entries for a VIP, from the specified // table. func removeRoutes(table string, vip net.IP) error
{ af := seesaw.IPv6 if vip.To4() != nil { af = seesaw.IPv4 } return ipRunAF(af, "route flush table %s %s", table, vip) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ncc/ip.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ncc/ip.go#L292-L303
go
train
// routeLocal removes all routes in the local routing table for the given VIP // and adds new routes with the correct source address.
func routeLocal(iface *net.Interface, vip net.IP, node seesaw.Host) error
// routeLocal removes all routes in the local routing table for the given VIP // and adds new routes with the correct source address. func routeLocal(iface *net.Interface, vip net.IP, node seesaw.Host) error
{ af := seesaw.IPv6 src := node.IPv6Addr if vip.To4() != nil { af = seesaw.IPv4 src = node.IPv4Addr } if err := removeLocalRoutes(vip); err != nil { return err } return ipRunAF(af, "route add table local local %s dev %s src %s", vip, iface.Name, src) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ncc/ip.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ncc/ip.go#L306-L316
go
train
// RouteDefaultIPv4 returns the default route for IPv4 traffic.
func (ncc *SeesawNCC) RouteDefaultIPv4(unused int, gateway *net.IP) error
// RouteDefaultIPv4 returns the default route for IPv4 traffic. func (ncc *SeesawNCC) RouteDefaultIPv4(unused int, gateway *net.IP) error
{ ip, err := routeDefaultIPv4() if err != nil { return err } if gateway != nil { *gateway = make(net.IP, len(ip)) copy(*gateway, ip) } return nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ncc/lb.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ncc/lb.go#L36-L116
go
train
// LBInterfaceInit initialises the load balancing interface for a Seesaw Node.
func (ncc *SeesawNCC) LBInterfaceInit(iface *ncctypes.LBInterface, out *int) error
// LBInterfaceInit initialises the load balancing interface for a Seesaw Node. func (ncc *SeesawNCC) LBInterfaceInit(iface *ncctypes.LBInterface, out *int) error
{ netIface, err := iface.Interface() if err != nil { return fmt.Errorf("Failed to get network interface: %v", err) } nodeIface, err := net.InterfaceByName(iface.NodeInterface) if err != nil { return fmt.Errorf("Failed to get node interface: %v", err) } if iface.RoutingTableID < 1 || iface.RoutingTableID > 250 { return fmt.Errorf("Invalid routing table ID: %d", iface.RoutingTableID) } vmac, err := net.ParseMAC(vrrpMAC) if err != nil { return fmt.Errorf("Failed to parse VRRP MAC %q: %v", vrrpMAC, err) } // The last byte of the VRRP MAC is determined by the VRID. vmac[len(vmac)-1] = iface.VRID netIface.HardwareAddr = vmac log.Infof("Initialising load balancing interface %s - VRID %d (VMAC %s)", iface.Name, iface.VRID, vmac) // Ensure interface is down and set VMAC address. if err := ifaceFastDown(netIface); err != nil { return fmt.Errorf("Failed to down interface: %v", err) } if err := ifaceSetMAC(netIface); err != nil { return fmt.Errorf("Failed to set MAC: %v", err) } // Remove VLAN interfaces associated with the load balancing interface. if err := ifaceFlushVLANs(netIface); err != nil { return fmt.Errorf("Failed to flush VLAN interfaces: %v", err) } // Configure sysctls for load balancing. if err := sysctlInitLB(nodeIface, netIface); err != nil { return fmt.Errorf("Failed to initialise sysctls: %v", err) } // Flush existing IP addresses and add cluster VIPs. if err := ifaceFlushIPAddr(netIface); err != nil { return fmt.Errorf("Failed to flush IP addresses: %v", err) } if iface.ClusterVIP.IPv4Addr != nil { if err := addClusterVIP(iface, netIface, nodeIface, iface.ClusterVIP.IPv4Addr); err != nil { return fmt.Errorf("Failed to add IPv4 cluster VIP: %v", err) } } if iface.ClusterVIP.IPv6Addr != nil { if err := addClusterVIP(iface, netIface, nodeIface, iface.ClusterVIP.IPv6Addr); err != nil { return fmt.Errorf("Failed to add IPv6 cluster VIP: %v", err) } } // Initialise iptables rules. if err := iptablesInit(iface.ClusterVIP); err != nil { return err } // Setup dummy interface. dummyIface, err := net.InterfaceByName(iface.DummyInterface) if err != nil { return fmt.Errorf("Failed to get dummy interface: %v", err) } if err := ifaceFastDown(dummyIface); err != nil { return fmt.Errorf("Failed to down dummy interface: %v", err) } if err := ifaceFlushIPAddr(dummyIface); err != nil { return fmt.Errorf("Failed to flush dummy interface: %v", err) } if err := ifaceUp(dummyIface); err != nil { return fmt.Errorf("Failed to up dummy interface: %v", err) } return nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ncc/lb.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ncc/lb.go#L120-L171
go
train
// addClusterVIP adds a cluster VIP to the load balancing interface and // performs additional network configuration.
func addClusterVIP(iface *ncctypes.LBInterface, netIface, nodeIface *net.Interface, clusterVIP net.IP) error
// addClusterVIP adds a cluster VIP to the load balancing interface and // performs additional network configuration. func addClusterVIP(iface *ncctypes.LBInterface, netIface, nodeIface *net.Interface, clusterVIP net.IP) error
{ nodeIP := iface.Node.IPv4Addr family := seesaw.IPv4 if clusterVIP.To4() == nil { nodeIP = iface.Node.IPv6Addr family = seesaw.IPv6 } if nodeIP == nil { return fmt.Errorf("Node does not have an %s address", family) } log.Infof("Adding %s cluster VIP %s on %s", family, clusterVIP, iface.Name) // Determine network for the node IP and ensure that the cluster VIP is // contained within this network. nodeNet, err := findNetwork(nodeIface, nodeIP) if err != nil { return fmt.Errorf("Failed to get node network: %v", err) } if !nodeNet.Contains(clusterVIP) { return fmt.Errorf("Node network %s does not contain cluster VIP %s", nodeNet, clusterVIP) } // Set up routing policy for IPv4. These rules and the associated routes // added in LBInterfaceUp tell the seesaw to: // 1) Respond to ARP requests for the seesaw VIP // 2) Send seesaw VIP reply traffic out eth1 // // For IPv6, policy routing won't work on physical machines until // b/10061534 is resolved. VIP reply traffic will go out eth0 which is fine, // and neighbor discovery for the seesaw VIP works fine without policy routing // anyway. // // TODO(angusc): Figure out how whether we can get rid of this. if family == seesaw.IPv4 { ipRunAF(family, "rule del to %s", clusterVIP) ipRunAF(family, "rule del from %s", clusterVIP) if err := ipRunAF(family, "rule add from all to %s lookup %d", clusterVIP, iface.RoutingTableID); err != nil { return fmt.Errorf("Failed to set up routing policy: %v", err) } if err := ipRunAF(family, "rule add from %s lookup %d", clusterVIP, iface.RoutingTableID); err != nil { return fmt.Errorf("Failed to set up routing policy: %v", err) } } // Add cluster VIP to interface. if err := ifaceAddIPAddr(netIface, clusterVIP, nodeNet.Mask); err != nil { return fmt.Errorf("Failed to add cluster VIP to interface: %v", err) } return nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ncc/lb.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ncc/lb.go#L174-L181
go
train
// LBInterfaceDown brings the load balancing interface down.
func (ncc *SeesawNCC) LBInterfaceDown(iface *ncctypes.LBInterface, out *int) error
// LBInterfaceDown brings the load balancing interface down. func (ncc *SeesawNCC) LBInterfaceDown(iface *ncctypes.LBInterface, out *int) error
{ netIface, err := iface.Interface() if err != nil { return err } log.Infof("Bringing down LB interface %s", netIface.Name) return ifaceDown(netIface) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ncc/lb.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ncc/lb.go#L184-L223
go
train
// LBInterfaceUp brings the load balancing interface up.
func (ncc *SeesawNCC) LBInterfaceUp(iface *ncctypes.LBInterface, out *int) error
// LBInterfaceUp brings the load balancing interface up. func (ncc *SeesawNCC) LBInterfaceUp(iface *ncctypes.LBInterface, out *int) error
{ // TODO(jsing): Handle IPv6-only, and improve IPv6 route setup. netIface, err := iface.Interface() if err != nil { return err } nodeIface, err := net.InterfaceByName(iface.NodeInterface) if err != nil { return fmt.Errorf("Failed to get node interface: %v", err) } nodeNet, err := findNetwork(nodeIface, iface.Node.IPv4Addr) if err != nil { return fmt.Errorf("Failed to get node network: %v", err) } log.Infof("Bringing up LB interface %s on %s", nodeNet, iface.Name) if !nodeNet.Contains(iface.ClusterVIP.IPv4Addr) { return fmt.Errorf("Node network %s does not contain cluster VIP %s", nodeNet, iface.ClusterVIP.IPv4Addr) } gateway, err := routeDefaultIPv4() if err != nil { return fmt.Errorf("Failed to get IPv4 default route: %v", err) } if err := ifaceUp(netIface); err != nil { return fmt.Errorf("Failed to bring interface up: %v", err) } // Configure routing. if err := ipRunIface(netIface, "route add %s dev %s table %d", nodeNet, iface.Name, iface.RoutingTableID); err != nil { return fmt.Errorf("Failed to configure routing: %v", err) } if err := ipRunIface(netIface, "route add 0/0 via %s dev %s table %d", gateway, iface.Name, iface.RoutingTableID); err != nil { return fmt.Errorf("Failed to configure routing: %v", err) } return nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ncc/lb.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ncc/lb.go#L226-L228
go
train
// LBInterfaceAddVserver adds the specified Vserver to the load balancing interface.
func (ncc *SeesawNCC) LBInterfaceAddVserver(lbVserver *ncctypes.LBInterfaceVserver, out *int) error
// LBInterfaceAddVserver adds the specified Vserver to the load balancing interface. func (ncc *SeesawNCC) LBInterfaceAddVserver(lbVserver *ncctypes.LBInterfaceVserver, out *int) error
{ return iptablesAddRules(lbVserver.Vserver, lbVserver.Iface.ClusterVIP, lbVserver.AF) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ncc/lb.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ncc/lb.go#L231-L233
go
train
// LBInterfaceDeleteVserver removes the specified Vserver from the load balancing interface.
func (ncc *SeesawNCC) LBInterfaceDeleteVserver(lbVserver *ncctypes.LBInterfaceVserver, out *int) error
// LBInterfaceDeleteVserver removes the specified Vserver from the load balancing interface. func (ncc *SeesawNCC) LBInterfaceDeleteVserver(lbVserver *ncctypes.LBInterfaceVserver, out *int) error
{ return iptablesDeleteRules(lbVserver.Vserver, lbVserver.Iface.ClusterVIP, lbVserver.AF) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ncc/lb.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ncc/lb.go#L236-L270
go
train
// LBInterfaceAddVIP adds the specified VIP to the load balancing interface.
func (ncc *SeesawNCC) LBInterfaceAddVIP(vip *ncctypes.LBInterfaceVIP, out *int) error
// LBInterfaceAddVIP adds the specified VIP to the load balancing interface. func (ncc *SeesawNCC) LBInterfaceAddVIP(vip *ncctypes.LBInterfaceVIP, out *int) error
{ switch vip.Type { case seesaw.UnicastVIP: netIface, err := vip.Iface.Interface() if err != nil { return err } iface, network, err := selectInterfaceNetwork(netIface, vip.IP.IP()) if err != nil { return fmt.Errorf("Failed to select interface and network for %v: %v", vip.VIP, err) } log.Infof("Adding VIP %s to %s", vip.IP.IP(), iface.Name) if err := ifaceAddIPAddr(iface, vip.IP.IP(), network.Mask); err != nil { return err } return routeLocal(iface, vip.IP.IP(), vip.Iface.Node) case seesaw.AnycastVIP, seesaw.DedicatedVIP: dummyIface, err := net.InterfaceByName(vip.Iface.DummyInterface) if err != nil { return fmt.Errorf("Failed to find dummy interface: %v", err) } prefixLen := net.IPv6len * 8 if vip.IP.IP().To4() != nil { prefixLen = net.IPv4len * 8 } mask := net.CIDRMask(prefixLen, prefixLen) log.Infof("Adding VIP %s to %s", vip.IP.IP(), dummyIface.Name) if err := ifaceAddIPAddr(dummyIface, vip.IP.IP(), mask); err != nil { return err } return routeLocal(dummyIface, vip.IP.IP(), vip.Iface.Node) default: return fmt.Errorf("Unknown VIPType for %v: %v", vip.VIP, vip.Type) } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ncc/lb.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ncc/lb.go#L274-L326
go
train
// LBInterfaceDeleteVIP removes the specified VIP from the load balancing // interface.
func (ncc *SeesawNCC) LBInterfaceDeleteVIP(vip *ncctypes.LBInterfaceVIP, out *int) error
// LBInterfaceDeleteVIP removes the specified VIP from the load balancing // interface. func (ncc *SeesawNCC) LBInterfaceDeleteVIP(vip *ncctypes.LBInterfaceVIP, out *int) error
{ switch vip.Type { case seesaw.UnicastVIP: netIface, err := vip.Iface.Interface() if err != nil { return err } iface, network, err := findInterfaceNetwork(netIface, vip.IP.IP()) if err != nil { return fmt.Errorf("Failed to find interface and network for %v: %v", vip.VIP, err) } log.Infof("Removing VIP %s from %s", vip.IP.IP(), iface.Name) if err := ifaceDelIPAddr(iface, vip.IP.IP(), network.Mask); err != nil { return fmt.Errorf("Failed to delete VIP %s: %v", vip.VIP, err) } if err := removeLocalRoutes(vip.IP.IP()); err != nil { log.Infof("Failed to remove local routes for VIP %s: %v", vip.VIP, err) } if err := removeMainRoutes(vip.VIP.IP.IP()); err != nil { log.Infof("Failed to remove main routes for VIP %s: %v", vip.VIP, err) } return nil case seesaw.AnycastVIP, seesaw.DedicatedVIP: dummyIface, err := net.InterfaceByName(vip.Iface.DummyInterface) if err != nil { return fmt.Errorf("Failed to find dummy interface: %v", err) } prefixLen := net.IPv6len * 8 if vip.IP.IP().To4() != nil { prefixLen = net.IPv4len * 8 } mask := net.CIDRMask(prefixLen, prefixLen) log.Infof("Removing VIP %s from %s", vip.IP.IP(), dummyIface.Name) if err = ifaceDelIPAddr(dummyIface, vip.IP.IP(), mask); err != nil { return fmt.Errorf("Failed to delete VIP %s: %v", vip.VIP, err) } // Workaround for kernel bug(?). The route should have been removed when // address was removed, but this doesn't always happen. An error is // non-fatal since it probably means the route doesn't exist. if err := removeLocalRoutes(vip.VIP.IP.IP()); err != nil { log.Infof("Failed to remove local routes for VIP %s: %v", vip.VIP, err) } if err := removeMainRoutes(vip.VIP.IP.IP()); err != nil { log.Infof("Failed to remove main routes for VIP %s: %v", vip.VIP, err) } return nil default: return fmt.Errorf("Unknown VIPType for %v: %v", vip.VIP, vip.VIP.Type) } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ncc/lb.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ncc/lb.go#L329-L335
go
train
// LBInterfaceAddVLAN creates a VLAN interface on the load balancing interface.
func (ncc *SeesawNCC) LBInterfaceAddVLAN(vlan *ncctypes.LBInterfaceVLAN, out *int) error
// LBInterfaceAddVLAN creates a VLAN interface on the load balancing interface. func (ncc *SeesawNCC) LBInterfaceAddVLAN(vlan *ncctypes.LBInterfaceVLAN, out *int) error
{ netIface, err := vlan.Iface.Interface() if err != nil { return err } return ifaceAddVLAN(netIface, vlan.VLAN) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ncc/lb.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ncc/lb.go#L338-L344
go
train
// LBInterfaceDeleteVLAN deletes a VLAN interface from the load balancing interface.
func (ncc *SeesawNCC) LBInterfaceDeleteVLAN(vlan *ncctypes.LBInterfaceVLAN, out *int) error
// LBInterfaceDeleteVLAN deletes a VLAN interface from the load balancing interface. func (ncc *SeesawNCC) LBInterfaceDeleteVLAN(vlan *ncctypes.LBInterfaceVLAN, out *int) error
{ netIface, err := vlan.Iface.Interface() if err != nil { return err } return ifaceDelVLAN(netIface, vlan.VLAN) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ncc/lb.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ncc/lb.go#L348-L361
go
train
// vlanInterfaces returns a slice containing the VLAN interfaces associated // with a physical interface.
func vlanInterfaces(pIface *net.Interface) ([]*net.Interface, error)
// vlanInterfaces returns a slice containing the VLAN interfaces associated // with a physical interface. func vlanInterfaces(pIface *net.Interface) ([]*net.Interface, error)
{ allIfaces, err := net.Interfaces() if err != nil { return nil, err } ifaces := make([]*net.Interface, 0, len(allIfaces)) prefix := fmt.Sprintf("%s.", pIface.Name) for i, iface := range allIfaces { if strings.HasPrefix(iface.Name, prefix) { ifaces = append(ifaces, &allIfaces[i]) } } return ifaces, nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ncc/lb.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ncc/lb.go#L366-L378
go
train
// findInterfaceNetwork searches for the given IP address on the given physical // interface and its associated VLAN interfaces. If the address is not // configured on any interface, an error is returned.
func findInterfaceNetwork(pIface *net.Interface, ip net.IP) (*net.Interface, *net.IPNet, error)
// findInterfaceNetwork searches for the given IP address on the given physical // interface and its associated VLAN interfaces. If the address is not // configured on any interface, an error is returned. func findInterfaceNetwork(pIface *net.Interface, ip net.IP) (*net.Interface, *net.IPNet, error)
{ ifaces, err := vlanInterfaces(pIface) ifaces = append(ifaces, pIface) if err != nil { return nil, nil, err } for _, iface := range ifaces { if network, _ := findNetwork(iface, ip); network != nil { return iface, network, nil } } return nil, nil, fmt.Errorf("Failed to find IP %v on any interface", ip) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ncc/lb.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ncc/lb.go#L383-L399
go
train
// findNetwork returns the network for the given IP address on the given // interface. If the address is not configured on the interface, an error is // returned.
func findNetwork(iface *net.Interface, ip net.IP) (*net.IPNet, error)
// findNetwork returns the network for the given IP address on the given // interface. If the address is not configured on the interface, an error is // returned. func findNetwork(iface *net.Interface, ip net.IP) (*net.IPNet, error)
{ addrs, err := iface.Addrs() if err != nil { return nil, fmt.Errorf("Failed to get addresses for interface %q: %v", iface.Name, err) } for _, addr := range addrs { ipStr := addr.String() ipAddr, ipNet, err := net.ParseCIDR(ipStr) if err != nil { return nil, fmt.Errorf("Failed to parse interface address %q - %v: %v", iface.Name, ipStr, err) } if ipAddr.Equal(ip) { return ipNet, nil } } return nil, fmt.Errorf("Failed to find IP %v on interface %q", ip, iface.Name) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
watchdog/service.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/watchdog/service.go#L70-L85
go
train
// newService returns an initialised service.
func newService(name, binary string) *Service
// newService returns an initialised service. func newService(name, binary string) *Service
{ return &Service{ name: name, binary: binary, args: make([]string, 0), dependencies: make(map[string]*Service), dependents: make(map[string]*Service), done: make(chan bool), shutdown: make(chan bool, 1), started: make(chan bool, 1), stopped: make(chan bool, 1), termTimeout: 5 * time.Second, } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
watchdog/service.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/watchdog/service.go#L93-L95
go
train
// AddArgs adds the given string as arguments.
func (svc *Service) AddArgs(args string)
// AddArgs adds the given string as arguments. func (svc *Service) AddArgs(args string)
{ svc.args = strings.Fields(args) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
watchdog/service.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/watchdog/service.go#L98-L104
go
train
// SetPriority sets the process priority for a service.
func (svc *Service) SetPriority(priority int) error
// SetPriority sets the process priority for a service. func (svc *Service) SetPriority(priority int) error
{ if priority < -20 || priority > 19 { return fmt.Errorf("Invalid priority %d - must be between -20 and 19", priority) } svc.priority = priority return nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
watchdog/service.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/watchdog/service.go#L112-L128
go
train
// SetUser sets the user for a service.
func (svc *Service) SetUser(username string) error
// SetUser sets the user for a service. func (svc *Service) SetUser(username string) error
{ u, err := user.Lookup(username) if err != nil { return err } uid, err := strconv.Atoi(u.Uid) if err != nil { return err } gid, err := strconv.Atoi(u.Gid) if err != nil { return err } svc.uid = uint32(uid) svc.gid = uint32(gid) return nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
watchdog/service.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/watchdog/service.go#L132-L173
go
train
// run runs a service and restarts it upon termination, unless a shutdown // notification has been received.
func (svc *Service) run()
// run runs a service and restarts it upon termination, unless a shutdown // notification has been received. func (svc *Service) run()
{ // Wait for dependencies to start. for _, dep := range svc.dependencies { log.Infof("Service %s waiting for %s to start", svc.name, dep.name) select { case started := <-dep.started: dep.started <- started case <-svc.shutdown: goto done } } for { if svc.failures > 0 { delay := time.Duration(svc.failures) * restartBackoff if delay > restartBackoffMax { delay = restartBackoffMax } log.Infof("Service %s has failed %d times - delaying %s before restart", svc.name, svc.failures, delay) select { case <-time.After(delay): case <-svc.shutdown: goto done } } svc.restarts++ svc.lastRestart = time.Now() svc.runOnce() select { case <-time.After(restartDelay): case <-svc.shutdown: goto done } } done: svc.done <- true }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
watchdog/service.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/watchdog/service.go#L176-L195
go
train
// logFile creates a log file for this service.
func (svc *Service) logFile() (*os.File, error)
// logFile creates a log file for this service. func (svc *Service) logFile() (*os.File, error)
{ name := "seesaw_" + svc.name t := time.Now() logName := fmt.Sprintf("%s.log.%04d%02d%02d-%02d%02d%02d", name, t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second()) f, err := os.Create(path.Join(logDir, logName)) if err != nil { return nil, err } logLink := path.Join(logDir, name+".log") os.Remove(logLink) os.Symlink(logName, logLink) fmt.Fprintf(f, "Log file for %s (stdout/stderr)\n", name) fmt.Fprintf(f, "Created at: %s\n", t.Format("2006/01/02 15:04:05")) return f, nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
watchdog/service.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/watchdog/service.go#L199-L206
go
train
// logSink copies output from the given reader to a log file, before closing // both the reader and the log file.
func (svc *Service) logSink(f *os.File, r io.ReadCloser)
// logSink copies output from the given reader to a log file, before closing // both the reader and the log file. func (svc *Service) logSink(f *os.File, r io.ReadCloser)
{ _, err := io.Copy(f, r) if err != nil { log.Warningf("Service %s - log sink failed: %v", svc.name, err) } f.Close() r.Close() }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
watchdog/service.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/watchdog/service.go#L210-L295
go
train
// runOnce runs a service once, returning once an error occurs or the process // has exited.
func (svc *Service) runOnce()
// runOnce runs a service once, returning once an error occurs or the process // has exited. func (svc *Service) runOnce()
{ args := make([]string, len(svc.args)+1) args[0] = "seesaw_" + svc.name copy(args[1:], svc.args) null, err := os.Open(os.DevNull) if err != nil { log.Warningf("Service %s - failed to open %s: %v", svc.name, os.DevNull, err) return } pr, pw, err := os.Pipe() if err != nil { log.Warningf("Service %s - failed to create pipes: %v", svc.name, err) null.Close() return } f, err := svc.logFile() if err != nil { log.Warningf("Service %s - failed to create log file: %v", svc.name, err) null.Close() pr.Close() pw.Close() return } go svc.logSink(f, pr) attr := &os.ProcAttr{ Dir: svc.path, Files: []*os.File{null, pw, pw}, Sys: &syscall.SysProcAttr{ Credential: &syscall.Credential{ Uid: svc.uid, Gid: svc.gid, }, Setpgid: true, }, } log.Infof("Starting service %s...", svc.name) proc, err := os.StartProcess(svc.binary, args, attr) if err != nil { log.Warningf("Service %s failed to start: %v", svc.name, err) svc.lastFailure = time.Now() svc.failures++ null.Close() pw.Close() return } null.Close() pw.Close() svc.lock.Lock() svc.process = proc svc.lock.Unlock() if _, _, err := syscall.Syscall(syscall.SYS_SETPRIORITY, uintptr(prioProcess), uintptr(proc.Pid), uintptr(svc.priority)); err != 0 { log.Warningf("Failed to set priority to %d for service %s: %v", svc.priority, svc.name, err) } select { case svc.started <- true: default: } state, err := svc.process.Wait() if err != nil { log.Warningf("Service %s wait failed with %v", svc.name, err) svc.lastFailure = time.Now() svc.failures++ return } if !state.Success() { log.Warningf("Service %s exited with %v", svc.name, state) svc.lastFailure = time.Now() svc.failures++ return } // TODO(jsing): Reset failures after process has been running for some // given duration, so that failures with large intervals do not result // in backoff. However, we also want to count the total number of // failures and export it for monitoring purposes. svc.failures = 0 log.Infof("Service %s exited normally.", svc.name) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
watchdog/service.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/watchdog/service.go#L298-L305
go
train
// signal sends a signal to the service.
func (svc *Service) signal(sig os.Signal) error
// signal sends a signal to the service. func (svc *Service) signal(sig os.Signal) error
{ svc.lock.Lock() defer svc.lock.Unlock() if svc.process == nil { return nil } return svc.process.Signal(sig) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
watchdog/service.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/watchdog/service.go#L308-L329
go
train
// stop stops a running service.
func (svc *Service) stop()
// stop stops a running service. func (svc *Service) stop()
{ // TODO(jsing): Check if it is actually running? log.Infof("Stopping service %s...", svc.name) // Wait for dependents to shutdown. for _, dep := range svc.dependents { log.Infof("Service %s waiting for %s to stop", svc.name, dep.name) stopped := <-dep.stopped dep.stopped <- stopped } svc.shutdown <- true svc.signal(syscall.SIGTERM) select { case <-svc.done: case <-time.After(svc.termTimeout): svc.signal(syscall.SIGKILL) <-svc.done } log.Infof("Service %s stopped", svc.name) svc.stopped <- true }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ncc/arp.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ncc/arp.go#L70-L82
go
train
// bytes returns the wire representation of the ARP message.
func (m *arpMessage) bytes() ([]byte, error)
// bytes returns the wire representation of the ARP message. func (m *arpMessage) bytes() ([]byte, error)
{ buf := new(bytes.Buffer) if err := binary.Write(buf, binary.BigEndian, m.arpHeader); err != nil { return nil, fmt.Errorf("binary write failed: %v", err) } buf.Write(m.senderHardwareAddress) buf.Write(m.senderProtocolAddress) buf.Write(m.targetHardwareAddress) buf.Write(m.targetProtocolAddress) return buf.Bytes(), nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ncc/arp.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ncc/arp.go#L86-L109
go
train
// gratuitousARPReply returns an ARP message that contains a gratuitous ARP // reply from the specified sender.
func gratuitousARPReply(ip net.IP, mac net.HardwareAddr) (*arpMessage, error)
// gratuitousARPReply returns an ARP message that contains a gratuitous ARP // reply from the specified sender. func gratuitousARPReply(ip net.IP, mac net.HardwareAddr) (*arpMessage, error)
{ if ip.To4() == nil { return nil, fmt.Errorf("%q is not an IPv4 address", ip) } if len(mac) != hwLen { return nil, fmt.Errorf("%q is not an Ethernet MAC address", mac) } m := &arpMessage{ arpHeader{ 1, // Ethernet 0x0800, // IPv4 hwLen, // 48-bit MAC Address net.IPv4len, // 32-bit IPv4 Address opARPReply, // ARP Reply }, mac, ip.To4(), ethernetBroadcast, net.IPv4bcast, } return m, nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ncc/arp.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ncc/arp.go#L112-L151
go
train
// sendARP sends the given ARP message via the specified interface.
func sendARP(iface *net.Interface, m *arpMessage) error
// sendARP sends the given ARP message via the specified interface. func sendARP(iface *net.Interface, m *arpMessage) error
{ fd, err := syscall.Socket(syscall.AF_PACKET, syscall.SOCK_DGRAM, int(htons(syscall.ETH_P_ARP))) if err != nil { return fmt.Errorf("failed to get raw socket: %v", err) } defer syscall.Close(fd) if err := syscall.BindToDevice(fd, iface.Name); err != nil { return fmt.Errorf("failed to bind to device: %v", err) } ll := syscall.SockaddrLinklayer{ Protocol: htons(syscall.ETH_P_ARP), Ifindex: iface.Index, Pkttype: 0, // syscall.PACKET_HOST Hatype: m.hardwareType, Halen: m.hardwareAddressLength, } target := ethernetBroadcast if m.opcode == opARPReply { target = m.targetHardwareAddress } for i := 0; i < len(target); i++ { ll.Addr[i] = target[i] } b, err := m.bytes() if err != nil { return fmt.Errorf("failed to convert ARP message: %v", err) } if err := syscall.Bind(fd, &ll); err != nil { return fmt.Errorf("failed to bind: %v", err) } if err := syscall.Sendto(fd, b, 0, &ll); err != nil { return fmt.Errorf("failed to send: %v", err) } return nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
ncc/arp.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/ncc/arp.go#L154-L165
go
train
// ARPSendGratuitous sends a gratuitous ARP message via the specified interface.
func (ncc *SeesawNCC) ARPSendGratuitous(arp *ncctypes.ARPGratuitous, out *int) error
// ARPSendGratuitous sends a gratuitous ARP message via the specified interface. func (ncc *SeesawNCC) ARPSendGratuitous(arp *ncctypes.ARPGratuitous, out *int) error
{ iface, err := net.InterfaceByName(arp.IfaceName) if err != nil { return fmt.Errorf("failed to get interface %q: %v", arp.IfaceName, err) } log.V(2).Infof("Sending gratuitous ARP for %s (%s) via %s", arp.IP, iface.HardwareAddr, iface.Name) m, err := gratuitousARPReply(arp.IP, iface.HardwareAddr) if err != nil { return err } return sendARP(iface, m) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
healthcheck/radius.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/healthcheck/radius.go#L81-L86
go
train
// String returns the string representation of a RADIUS code.
func (rc radiusCode) String() string
// String returns the string representation of a RADIUS code. func (rc radiusCode) String() string
{ if name, ok := rcNames[rc]; ok { return name } return fmt.Sprintf("(unknown %d)", rc) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
healthcheck/radius.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/healthcheck/radius.go#L144-L149
go
train
// String returns the string representation of a RADIUS attribute type.
func (rat radiusAttributeType) String() string
// String returns the string representation of a RADIUS attribute type. func (rat radiusAttributeType) String() string
{ if name, ok := ratNames[rat]; ok { return name } return fmt.Sprintf("(unknown %d)", rat) }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
healthcheck/radius.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/healthcheck/radius.go#L241-L263
go
train
// radiusPassword encodes a password using the algorithm described in RFC2865 // section 5.2.
func radiusPassword(passwd, secret string, authenticator *radiusAuthenticator) []byte
// radiusPassword encodes a password using the algorithm described in RFC2865 // section 5.2. func radiusPassword(passwd, secret string, authenticator *radiusAuthenticator) []byte
{ const blockSize = 16 length := (len(passwd) + 0xf) &^ 0xf if length > 128 { length = 128 } blocks := make([]byte, length) copy(blocks, []byte(passwd)) for i := 0; i < length; i += blockSize { hash := md5.New() hash.Write([]byte(secret)) if i >= blockSize { hash.Write(blocks[i-blockSize : i]) } else { hash.Write(authenticator[:]) } h := hash.Sum(nil) for j := 0; j < blockSize; j++ { blocks[i+j] ^= h[j] } } return blocks }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
healthcheck/radius.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/healthcheck/radius.go#L267-L282
go
train
// responseAuthenticator calculates the response authenticator for a RADIUS // response packet, as per RFC2865 section 3.
func responseAuthenticator(rp *radiusPacket, requestAuthenticator *radiusAuthenticator, secret string) (*radiusAuthenticator, error)
// responseAuthenticator calculates the response authenticator for a RADIUS // response packet, as per RFC2865 section 3. func responseAuthenticator(rp *radiusPacket, requestAuthenticator *radiusAuthenticator, secret string) (*radiusAuthenticator, error)
{ hash := md5.New() hash.Write([]byte{byte(rp.Code), byte(rp.Identifier)}) if err := binary.Write(hash, binary.BigEndian, rp.Length); err != nil { return nil, err } hash.Write(requestAuthenticator[:]) for _, ra := range rp.attributes { hash.Write(ra.encode()) } hash.Write([]byte(secret)) h := hash.Sum(nil) var authenticator radiusAuthenticator copy(authenticator[:], h[:]) return &authenticator, nil }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
healthcheck/radius.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/healthcheck/radius.go#L294-L303
go
train
// NewRADIUSChecker returns an initialised RADIUSChecker.
func NewRADIUSChecker(ip net.IP, port int) *RADIUSChecker
// NewRADIUSChecker returns an initialised RADIUSChecker. func NewRADIUSChecker(ip net.IP, port int) *RADIUSChecker
{ return &RADIUSChecker{ Target: Target{ IP: ip, Port: port, Proto: seesaw.IPProtoUDP, }, Response: "accept", } }
google/seesaw
34716af0775ecb1fad239a726390d63d6b0742dd
healthcheck/radius.go
https://github.com/google/seesaw/blob/34716af0775ecb1fad239a726390d63d6b0742dd/healthcheck/radius.go#L311-L445
go
train
// Check executes a RADIUS healthcheck.
func (hc *RADIUSChecker) Check(timeout time.Duration) *Result
// Check executes a RADIUS healthcheck. func (hc *RADIUSChecker) Check(timeout time.Duration) *Result
{ msg := fmt.Sprintf("RADIUS %s to port %d", rcAccessRequest, hc.Port) start := time.Now() if timeout == time.Duration(0) { timeout = defaultRADIUSTimeout } deadline := start.Add(timeout) conn, err := dialUDP(hc.network(), hc.addr(), timeout, hc.Mark) if err != nil { return complete(start, msg, false, err) } defer conn.Close() // Build a RADIUS Access-Request packet. authenticator, err := newRADIUSAuthenticator() if err != nil { return complete(start, msg, false, err) } identifier := newRADIUSIdentifier() rp := &radiusPacket{ radiusHeader: radiusHeader{ Code: rcAccessRequest, Identifier: identifier, }, } copy(rp.Authenticator[:], authenticator[:]) // NAS Identifier. hostname, err := os.Hostname() if err != nil { return complete(start, msg, false, err) } ra := &radiusAttribute{raType: ratNASIdentifier} ra.value = []byte(hostname) rp.addAttribute(ra) // Username. ra = &radiusAttribute{raType: ratUserName} ra.value = []byte(hc.Username) rp.addAttribute(ra) // User Password. ra = &radiusAttribute{raType: ratUserPassword} ra.value = radiusPassword(hc.Password, hc.Secret, authenticator) rp.addAttribute(ra) // NAS IP Address. nasIP := net.ParseIP(conn.LocalAddr().String()) if ip := nasIP.To4(); ip != nil { ra := &radiusAttribute{raType: ratNASIPAddress} ra.value = ip rp.addAttribute(ra) } // NAS Port Type (virtual). ra = &radiusAttribute{raType: ratNASPortType} ra.value = []byte{0x0, 0x0, 0x0, 0x5} rp.addAttribute(ra) // Service Type (login). ra = &radiusAttribute{raType: ratServiceType} ra.value = []byte{0x0, 0x0, 0x0, 0x1} rp.addAttribute(ra) // Send a RADIUS request. rpb := rp.encode() err = conn.SetDeadline(deadline) if err != nil { msg = fmt.Sprintf("%s; failed to set deadline", msg) return complete(start, msg, false, err) } if _, err := conn.Write(rpb); err != nil { msg = fmt.Sprintf("%s; failed to send request", msg) return complete(start, msg, false, err) } // Read and decode the RADIUS response. reply := make([]byte, radiusMaximumSize) n, _, err := conn.ReadFrom(reply) if err != nil { msg = fmt.Sprintf("%s; failed to read response", msg) return complete(start, msg, false, err) } reader := bytes.NewReader(reply[0:n]) if err := rp.decode(reader); err != nil { msg = fmt.Sprintf("%s; failed to decode response", msg) return complete(start, msg, false, err) } // The Access-Request should result in an Access-Accept, // Access-Reject or Access-Challenge response. if rp.Identifier != identifier { msg = fmt.Sprintf("%s; identifier mismatch", msg) return complete(start, msg, false, err) } // TODO(jsing): Consider adding a flag to disable the response // authenticator check. This would allow healthchecks to be performed // without needing a valid secret (although the host still needs to be // configured as a RADIUS client). respAuth, err := responseAuthenticator(rp, authenticator, hc.Secret) if err != nil { return complete(start, msg, false, err) } if !bytes.Equal(rp.Authenticator[:], respAuth[:]) { msg = fmt.Sprintf("%s; response authenticator mismatch (incorrect secret?)", msg) return complete(start, msg, false, err) } msg = fmt.Sprintf("%s; got RADIUS %s response", msg, rp.Code) switch { case hc.Response == "any": return complete(start, msg, true, err) case hc.Response == "accept" && rp.Code == rcAccessAccept: return complete(start, msg, true, err) case hc.Response == "challenge" && rp.Code == rcAccessChallenge: return complete(start, msg, true, err) case hc.Response == "reject" && rp.Code == rcAccessReject: return complete(start, msg, true, err) } switch rp.Code { case rcAccessAccept, rcAccessChallenge, rcAccessReject: msg = fmt.Sprintf("%s; want %s response", msg, hc.Response) default: msg = fmt.Sprintf("%s; unknown RADIUS response %d", msg, rp.Code) } return complete(start, msg, false, err) }