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 |
|---|---|---|---|---|---|---|---|---|---|
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | link_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/link_linux.go#L645-L647 | go | train | // LinkSetMasterByIndex sets the master of the link device.
// Equivalent to: `ip link set $link master $master` | func LinkSetMasterByIndex(link Link, masterIndex int) error | // LinkSetMasterByIndex sets the master of the link device.
// Equivalent to: `ip link set $link master $master`
func LinkSetMasterByIndex(link Link, masterIndex int) error | {
return pkgHandle.LinkSetMasterByIndex(link, masterIndex)
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | link_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/link_linux.go#L673-L675 | go | train | // LinkSetNsPid puts the device into a new network namespace. The
// pid must be a pid of a running process.
// Equivalent to: `ip link set $link netns $pid` | func LinkSetNsPid(link Link, nspid int) error | // LinkSetNsPid puts the device into a new network namespace. The
// pid must be a pid of a running process.
// Equivalent to: `ip link set $link netns $pid`
func LinkSetNsPid(link Link, nspid int) error | {
return pkgHandle.LinkSetNsPid(link, nspid)
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | link_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/link_linux.go#L702-L704 | go | train | // LinkSetNsFd puts the device into a new network namespace. The
// fd must be an open file descriptor to a network namespace.
// Similar to: `ip link set $link netns $ns` | func LinkSetNsFd(link Link, fd int) error | // LinkSetNsFd puts the device into a new network namespace. The
// fd must be an open file descriptor to a network namespace.
// Similar to: `ip link set $link netns $ns`
func LinkSetNsFd(link Link, fd int) error | {
return pkgHandle.LinkSetNsFd(link, fd)
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | link_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/link_linux.go#L736-L749 | go | train | // LinkSetXdpFdWithFlags adds a bpf function to the driver with the given
// options. The fd must be a bpf program loaded with bpf(type=BPF_PROG_TYPE_XDP) | func LinkSetXdpFdWithFlags(link Link, fd, flags int) error | // LinkSetXdpFdWithFlags adds a bpf function to the driver with the given
// options. The fd must be a bpf program loaded with bpf(type=BPF_PROG_TYPE_XDP)
func LinkSetXdpFdWithFlags(link Link, fd, flags int) error | {
base := link.Attrs()
ensureIndex(base)
req := nl.NewNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Index = int32(base.Index)
req.AddData(msg)
addXdpAttrs(&LinkXdp{Fd: fd, Flags: uint32(flags)}, req)
_, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | link_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/link_linux.go#L947-L949 | go | train | // LinkAdd adds a new link device. The type and features of the device
// are taken from the parameters in the link object.
// Equivalent to: `ip link add $link` | func (h *Handle) LinkAdd(link Link) error | // LinkAdd adds a new link device. The type and features of the device
// are taken from the parameters in the link object.
// Equivalent to: `ip link add $link`
func (h *Handle) LinkAdd(link Link) error | {
return h.linkModify(link, unix.NLM_F_CREATE|unix.NLM_F_EXCL|unix.NLM_F_ACK)
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | link_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/link_linux.go#L1234-L1247 | go | train | // LinkDel deletes link device. Either Index or Name must be set in
// the link object for it to be deleted. The other values are ignored.
// Equivalent to: `ip link del $link` | func (h *Handle) LinkDel(link Link) error | // LinkDel deletes link device. Either Index or Name must be set in
// the link object for it to be deleted. The other values are ignored.
// Equivalent to: `ip link del $link`
func (h *Handle) LinkDel(link Link) error | {
base := link.Attrs()
h.ensureIndex(base)
req := h.newNetlinkRequest(unix.RTM_DELLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Index = int32(base.Index)
req.AddData(msg)
_, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | link_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/link_linux.go#L1283-L1308 | go | train | // LinkByName finds a link by name and returns a pointer to the object. | func (h *Handle) LinkByName(name string) (Link, error) | // LinkByName finds a link by name and returns a pointer to the object.
func (h *Handle) LinkByName(name string) (Link, error) | {
if h.lookupByDump {
return h.linkByNameDump(name)
}
req := h.newNetlinkRequest(unix.RTM_GETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
req.AddData(msg)
attr := nl.NewRtAttr(unix.IFLA_EXT_MASK, nl.Uint32Attr(nl.RTEXT_FILTER_VF))
req.AddData(attr)
nameData := nl.NewRtAttr(unix.IFLA_IFNAME, nl.ZeroTerminated(name))
req.AddData(nameData)
link, err := execGetLink(req)
if err == unix.EINVAL {
// older kernels don't support looking up via IFLA_IFNAME
// so fall back to dumping all links
h.lookupByDump = true
return h.linkByNameDump(name)
}
return link, err
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | link_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/link_linux.go#L1318-L1343 | go | train | // LinkByAlias finds a link by its alias and returns a pointer to the object.
// If there are multiple links with the alias it returns the first one | func (h *Handle) LinkByAlias(alias string) (Link, error) | // LinkByAlias finds a link by its alias and returns a pointer to the object.
// If there are multiple links with the alias it returns the first one
func (h *Handle) LinkByAlias(alias string) (Link, error) | {
if h.lookupByDump {
return h.linkByAliasDump(alias)
}
req := h.newNetlinkRequest(unix.RTM_GETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
req.AddData(msg)
attr := nl.NewRtAttr(unix.IFLA_EXT_MASK, nl.Uint32Attr(nl.RTEXT_FILTER_VF))
req.AddData(attr)
nameData := nl.NewRtAttr(unix.IFLA_IFALIAS, nl.ZeroTerminated(alias))
req.AddData(nameData)
link, err := execGetLink(req)
if err == unix.EINVAL {
// older kernels don't support looking up via IFLA_IFALIAS
// so fall back to dumping all links
h.lookupByDump = true
return h.linkByAliasDump(alias)
}
return link, err
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | link_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/link_linux.go#L1351-L1361 | go | train | // LinkByIndex finds a link by index and returns a pointer to the object. | func (h *Handle) LinkByIndex(index int) (Link, error) | // LinkByIndex finds a link by index and returns a pointer to the object.
func (h *Handle) LinkByIndex(index int) (Link, error) | {
req := h.newNetlinkRequest(unix.RTM_GETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Index = int32(index)
req.AddData(msg)
attr := nl.NewRtAttr(unix.IFLA_EXT_MASK, nl.Uint32Attr(nl.RTEXT_FILTER_VF))
req.AddData(attr)
return execGetLink(req)
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | link_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/link_linux.go#L1388-L1580 | go | train | // linkDeserialize deserializes a raw message received from netlink into
// a link object. | func LinkDeserialize(hdr *unix.NlMsghdr, m []byte) (Link, error) | // linkDeserialize deserializes a raw message received from netlink into
// a link object.
func LinkDeserialize(hdr *unix.NlMsghdr, m []byte) (Link, error) | {
msg := nl.DeserializeIfInfomsg(m)
attrs, err := nl.ParseRouteAttr(m[msg.Len():])
if err != nil {
return nil, err
}
base := LinkAttrs{Index: int(msg.Index), RawFlags: msg.Flags, Flags: linkFlags(msg.Flags), EncapType: msg.EncapType()}
if msg.Flags&unix.IFF_PROMISC != 0 {
base.Promisc = 1
}
var (
link Link
stats32 []byte
stats64 []byte
linkType string
)
for _, attr := range attrs {
switch attr.Attr.Type {
case unix.IFLA_LINKINFO:
infos, err := nl.ParseRouteAttr(attr.Value)
if err != nil {
return nil, err
}
for _, info := range infos {
switch info.Attr.Type {
case nl.IFLA_INFO_KIND:
linkType = string(info.Value[:len(info.Value)-1])
switch linkType {
case "dummy":
link = &Dummy{}
case "ifb":
link = &Ifb{}
case "bridge":
link = &Bridge{}
case "vlan":
link = &Vlan{}
case "veth":
link = &Veth{}
case "vxlan":
link = &Vxlan{}
case "bond":
link = &Bond{}
case "ipvlan":
link = &IPVlan{}
case "macvlan":
link = &Macvlan{}
case "macvtap":
link = &Macvtap{}
case "gretap":
link = &Gretap{}
case "ip6gretap":
link = &Gretap{}
case "ipip":
link = &Iptun{}
case "sit":
link = &Sittun{}
case "gre":
link = &Gretun{}
case "ip6gre":
link = &Gretun{}
case "vti", "vti6":
link = &Vti{}
case "vrf":
link = &Vrf{}
case "gtp":
link = >P{}
case "xfrm":
link = &Xfrmi{}
default:
link = &GenericLink{LinkType: linkType}
}
case nl.IFLA_INFO_DATA:
data, err := nl.ParseRouteAttr(info.Value)
if err != nil {
return nil, err
}
switch linkType {
case "vlan":
parseVlanData(link, data)
case "vxlan":
parseVxlanData(link, data)
case "bond":
parseBondData(link, data)
case "ipvlan":
parseIPVlanData(link, data)
case "macvlan":
parseMacvlanData(link, data)
case "macvtap":
parseMacvtapData(link, data)
case "gretap":
parseGretapData(link, data)
case "ip6gretap":
parseGretapData(link, data)
case "ipip":
parseIptunData(link, data)
case "sit":
parseSittunData(link, data)
case "gre":
parseGretunData(link, data)
case "ip6gre":
parseGretunData(link, data)
case "vti", "vti6":
parseVtiData(link, data)
case "vrf":
parseVrfData(link, data)
case "bridge":
parseBridgeData(link, data)
case "gtp":
parseGTPData(link, data)
case "xfrm":
parseXfrmiData(link, data)
}
}
}
case unix.IFLA_ADDRESS:
var nonzero bool
for _, b := range attr.Value {
if b != 0 {
nonzero = true
}
}
if nonzero {
base.HardwareAddr = attr.Value[:]
}
case unix.IFLA_IFNAME:
base.Name = string(attr.Value[:len(attr.Value)-1])
case unix.IFLA_MTU:
base.MTU = int(native.Uint32(attr.Value[0:4]))
case unix.IFLA_LINK:
base.ParentIndex = int(native.Uint32(attr.Value[0:4]))
case unix.IFLA_MASTER:
base.MasterIndex = int(native.Uint32(attr.Value[0:4]))
case unix.IFLA_TXQLEN:
base.TxQLen = int(native.Uint32(attr.Value[0:4]))
case unix.IFLA_IFALIAS:
base.Alias = string(attr.Value[:len(attr.Value)-1])
case unix.IFLA_STATS:
stats32 = attr.Value[:]
case unix.IFLA_STATS64:
stats64 = attr.Value[:]
case unix.IFLA_XDP:
xdp, err := parseLinkXdp(attr.Value[:])
if err != nil {
return nil, err
}
base.Xdp = xdp
case unix.IFLA_PROTINFO | unix.NLA_F_NESTED:
if hdr != nil && hdr.Type == unix.RTM_NEWLINK &&
msg.Family == unix.AF_BRIDGE {
attrs, err := nl.ParseRouteAttr(attr.Value[:])
if err != nil {
return nil, err
}
protinfo := parseProtinfo(attrs)
base.Protinfo = &protinfo
}
case unix.IFLA_OPERSTATE:
base.OperState = LinkOperState(uint8(attr.Value[0]))
case unix.IFLA_LINK_NETNSID:
base.NetNsID = int(native.Uint32(attr.Value[0:4]))
case unix.IFLA_GSO_MAX_SIZE:
base.GSOMaxSize = native.Uint32(attr.Value[0:4])
case unix.IFLA_GSO_MAX_SEGS:
base.GSOMaxSegs = native.Uint32(attr.Value[0:4])
case unix.IFLA_VFINFO_LIST:
data, err := nl.ParseRouteAttr(attr.Value)
if err != nil {
return nil, err
}
vfs, err := parseVfInfoList(data)
if err != nil {
return nil, err
}
base.Vfs = vfs
}
}
if stats64 != nil {
base.Statistics = parseLinkStats64(stats64)
} else if stats32 != nil {
base.Statistics = parseLinkStats32(stats32)
}
// Links that don't have IFLA_INFO_KIND are hardware devices
if link == nil {
link = &Device{}
}
*link.Attrs() = base
return link, nil
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | link_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/link_linux.go#L1590-L1615 | go | train | // LinkList gets a list of link devices.
// Equivalent to: `ip link show` | func (h *Handle) LinkList() ([]Link, error) | // LinkList gets a list of link devices.
// Equivalent to: `ip link show`
func (h *Handle) LinkList() ([]Link, error) | {
// NOTE(vish): This duplicates functionality in net/iface_linux.go, but we need
// to get the message ourselves to parse link type.
req := h.newNetlinkRequest(unix.RTM_GETLINK, unix.NLM_F_DUMP)
msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
req.AddData(msg)
attr := nl.NewRtAttr(unix.IFLA_EXT_MASK, nl.Uint32Attr(nl.RTEXT_FILTER_VF))
req.AddData(attr)
msgs, err := req.Execute(unix.NETLINK_ROUTE, unix.RTM_NEWLINK)
if err != nil {
return nil, err
}
var res []Link
for _, m := range msgs {
link, err := LinkDeserialize(nil, m)
if err != nil {
return nil, err
}
res = append(res, link)
}
return res, nil
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | link_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/link_linux.go#L1626-L1628 | go | train | // LinkSubscribe takes a chan down which notifications will be sent
// when links change. Close the 'done' chan to stop subscription. | func LinkSubscribe(ch chan<- LinkUpdate, done <-chan struct{}) error | // LinkSubscribe takes a chan down which notifications will be sent
// when links change. Close the 'done' chan to stop subscription.
func LinkSubscribe(ch chan<- LinkUpdate, done <-chan struct{}) error | {
return linkSubscribeAt(netns.None(), netns.None(), ch, done, nil, false)
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | link_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/link_linux.go#L1632-L1634 | go | train | // LinkSubscribeAt works like LinkSubscribe plus it allows the caller
// to choose the network namespace in which to subscribe (ns). | func LinkSubscribeAt(ns netns.NsHandle, ch chan<- LinkUpdate, done <-chan struct{}) error | // LinkSubscribeAt works like LinkSubscribe plus it allows the caller
// to choose the network namespace in which to subscribe (ns).
func LinkSubscribeAt(ns netns.NsHandle, ch chan<- LinkUpdate, done <-chan struct{}) error | {
return linkSubscribeAt(ns, netns.None(), ch, done, nil, false)
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | link_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/link_linux.go#L1647-L1653 | go | train | // LinkSubscribeWithOptions work like LinkSubscribe but enable to
// provide additional options to modify the behavior. Currently, the
// namespace can be provided as well as an error callback. | func LinkSubscribeWithOptions(ch chan<- LinkUpdate, done <-chan struct{}, options LinkSubscribeOptions) error | // LinkSubscribeWithOptions work like LinkSubscribe but enable to
// provide additional options to modify the behavior. Currently, the
// namespace can be provided as well as an error callback.
func LinkSubscribeWithOptions(ch chan<- LinkUpdate, done <-chan struct{}, options LinkSubscribeOptions) error | {
if options.Namespace == nil {
none := netns.None()
options.Namespace = &none
}
return linkSubscribeAt(*options.Namespace, netns.None(), ch, done, options.ErrorCallback, options.ListExisting)
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | link_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/link_linux.go#L1802-L1804 | go | train | // LinkSetTxQLen sets the transaction queue length for the link.
// Equivalent to: `ip link set $link txqlen $qlen` | func LinkSetTxQLen(link Link, qlen int) error | // LinkSetTxQLen sets the transaction queue length for the link.
// Equivalent to: `ip link set $link txqlen $qlen`
func LinkSetTxQLen(link Link, qlen int) error | {
return pkgHandle.LinkSetTxQLen(link, qlen)
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | link_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/link_linux.go#L1808-L1825 | go | train | // LinkSetTxQLen sets the transaction queue length for the link.
// Equivalent to: `ip link set $link txqlen $qlen` | func (h *Handle) LinkSetTxQLen(link Link, qlen int) error | // LinkSetTxQLen sets the transaction queue length for the link.
// Equivalent to: `ip link set $link txqlen $qlen`
func (h *Handle) LinkSetTxQLen(link Link, qlen int) error | {
base := link.Attrs()
h.ensureIndex(base)
req := h.newNetlinkRequest(unix.RTM_SETLINK, unix.NLM_F_ACK)
msg := nl.NewIfInfomsg(unix.AF_UNSPEC)
msg.Index = int32(base.Index)
req.AddData(msg)
b := make([]byte, 4)
native.PutUint32(b, uint32(qlen))
data := nl.NewRtAttr(unix.IFLA_TXQLEN, b)
req.AddData(data)
_, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | link_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/link_linux.go#L2004-L2022 | go | train | // copied from pkg/net_linux.go | func linkFlags(rawFlags uint32) net.Flags | // copied from pkg/net_linux.go
func linkFlags(rawFlags uint32) net.Flags | {
var f net.Flags
if rawFlags&unix.IFF_UP != 0 {
f |= net.FlagUp
}
if rawFlags&unix.IFF_BROADCAST != 0 {
f |= net.FlagBroadcast
}
if rawFlags&unix.IFF_LOOPBACK != 0 {
f |= net.FlagLoopback
}
if rawFlags&unix.IFF_POINTOPOINT != 0 {
f |= net.FlagPointToPoint
}
if rawFlags&unix.IFF_MULTICAST != 0 {
f |= net.FlagMulticast
}
return f
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | link_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/link_linux.go#L2531-L2545 | go | train | // LinkSetBondSlave add slave to bond link via ioctl interface. | func LinkSetBondSlave(link Link, master *Bond) error | // LinkSetBondSlave add slave to bond link via ioctl interface.
func LinkSetBondSlave(link Link, master *Bond) error | {
fd, err := getSocketUDP()
if err != nil {
return err
}
defer syscall.Close(fd)
ifreq := newIocltSlaveReq(link.Attrs().Name, master.Attrs().Name)
_, _, errno := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), unix.SIOCBONDENSLAVE, uintptr(unsafe.Pointer(ifreq)))
if errno != 0 {
return fmt.Errorf("Failed to enslave %q to %q, errno=%v", link.Attrs().Name, master.Attrs().Name, errno)
}
return nil
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | link_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/link_linux.go#L2548-L2582 | go | train | // VethPeerIndex get veth peer index. | func VethPeerIndex(link *Veth) (int, error) | // VethPeerIndex get veth peer index.
func VethPeerIndex(link *Veth) (int, error) | {
fd, err := getSocketUDP()
if err != nil {
return -1, err
}
defer syscall.Close(fd)
ifreq, sSet := newIocltStringSetReq(link.Name)
_, _, errno := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), SIOCETHTOOL, uintptr(unsafe.Pointer(ifreq)))
if errno != 0 {
return -1, fmt.Errorf("SIOCETHTOOL request for %q failed, errno=%v", link.Attrs().Name, errno)
}
gstrings := ðtoolGstrings{
cmd: ETHTOOL_GSTRINGS,
stringSet: ETH_SS_STATS,
length: sSet.data[0],
}
ifreq.Data = uintptr(unsafe.Pointer(gstrings))
_, _, errno = syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), SIOCETHTOOL, uintptr(unsafe.Pointer(ifreq)))
if errno != 0 {
return -1, fmt.Errorf("SIOCETHTOOL request for %q failed, errno=%v", link.Attrs().Name, errno)
}
stats := ðtoolStats{
cmd: ETHTOOL_GSTATS,
nStats: gstrings.length,
}
ifreq.Data = uintptr(unsafe.Pointer(stats))
_, _, errno = syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), SIOCETHTOOL, uintptr(unsafe.Pointer(ifreq)))
if errno != 0 {
return -1, fmt.Errorf("SIOCETHTOOL request for %q failed, errno=%v", link.Attrs().Name, errno)
}
return int(stats.data[0]), nil
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | netns_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/netns_linux.go#L32-L34 | go | train | // GetNetNsIdByPid looks up the network namespace ID for a given pid (really thread id).
// Returns -1 if the namespace does not have an ID set. | func (h *Handle) GetNetNsIdByPid(pid int) (int, error) | // GetNetNsIdByPid looks up the network namespace ID for a given pid (really thread id).
// Returns -1 if the namespace does not have an ID set.
func (h *Handle) GetNetNsIdByPid(pid int) (int, error) | {
return h.getNetNsId(NETNSA_PID, uint32(pid))
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | netns_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/netns_linux.go#L44-L46 | go | train | // SetNetNSIdByPid sets the ID of the network namespace for a given pid (really thread id).
// The ID can only be set for namespaces without an ID already set. | func (h *Handle) SetNetNsIdByPid(pid, nsid int) error | // SetNetNSIdByPid sets the ID of the network namespace for a given pid (really thread id).
// The ID can only be set for namespaces without an ID already set.
func (h *Handle) SetNetNsIdByPid(pid, nsid int) error | {
return h.setNetNsId(NETNSA_PID, uint32(pid), uint32(nsid))
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | netns_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/netns_linux.go#L57-L59 | go | train | // GetNetNsIdByFd looks up the network namespace ID for a given fd.
// fd must be an open file descriptor to a namespace file.
// Returns -1 if the namespace does not have an ID set. | func (h *Handle) GetNetNsIdByFd(fd int) (int, error) | // GetNetNsIdByFd looks up the network namespace ID for a given fd.
// fd must be an open file descriptor to a namespace file.
// Returns -1 if the namespace does not have an ID set.
func (h *Handle) GetNetNsIdByFd(fd int) (int, error) | {
return h.getNetNsId(NETNSA_FD, uint32(fd))
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | netns_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/netns_linux.go#L71-L73 | go | train | // SetNetNSIdByFd sets the ID of the network namespace for a given fd.
// fd must be an open file descriptor to a namespace file.
// The ID can only be set for namespaces without an ID already set. | func (h *Handle) SetNetNsIdByFd(fd, nsid int) error | // SetNetNSIdByFd sets the ID of the network namespace for a given fd.
// fd must be an open file descriptor to a namespace file.
// The ID can only be set for namespaces without an ID already set.
func (h *Handle) SetNetNsIdByFd(fd, nsid int) error | {
return h.setNetNsId(NETNSA_FD, uint32(fd), uint32(nsid))
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | netns_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/netns_linux.go#L84-L118 | go | train | // getNetNsId requests the netnsid for a given type-val pair
// type should be either NETNSA_PID or NETNSA_FD | func (h *Handle) getNetNsId(attrType int, val uint32) (int, error) | // getNetNsId requests the netnsid for a given type-val pair
// type should be either NETNSA_PID or NETNSA_FD
func (h *Handle) getNetNsId(attrType int, val uint32) (int, error) | {
req := h.newNetlinkRequest(unix.RTM_GETNSID, unix.NLM_F_REQUEST)
rtgen := nl.NewRtGenMsg()
req.AddData(rtgen)
b := make([]byte, 4, 4)
native.PutUint32(b, val)
attr := nl.NewRtAttr(attrType, b)
req.AddData(attr)
msgs, err := req.Execute(unix.NETLINK_ROUTE, unix.RTM_NEWNSID)
if err != nil {
return 0, err
}
for _, m := range msgs {
msg := nl.DeserializeRtGenMsg(m)
attrs, err := nl.ParseRouteAttr(m[msg.Len():])
if err != nil {
return 0, err
}
for _, attr := range attrs {
switch attr.Attr.Type {
case NETNSA_NSID:
return int(int32(native.Uint32(attr.Value))), nil
}
}
}
return 0, fmt.Errorf("unexpected empty result")
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | netns_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/netns_linux.go#L123-L141 | go | train | // setNetNsId sets the netnsid for a given type-val pair
// type should be either NETNSA_PID or NETNSA_FD
// The ID can only be set for namespaces without an ID already set | func (h *Handle) setNetNsId(attrType int, val uint32, newnsid uint32) error | // setNetNsId sets the netnsid for a given type-val pair
// type should be either NETNSA_PID or NETNSA_FD
// The ID can only be set for namespaces without an ID already set
func (h *Handle) setNetNsId(attrType int, val uint32, newnsid uint32) error | {
req := h.newNetlinkRequest(unix.RTM_NEWNSID, unix.NLM_F_REQUEST|unix.NLM_F_ACK)
rtgen := nl.NewRtGenMsg()
req.AddData(rtgen)
b := make([]byte, 4, 4)
native.PutUint32(b, val)
attr := nl.NewRtAttr(attrType, b)
req.AddData(attr)
b1 := make([]byte, 4, 4)
native.PutUint32(b1, newnsid)
attr1 := nl.NewRtAttr(NETNSA_NSID, b1)
req.AddData(attr1)
_, err := req.Execute(unix.NETLINK_ROUTE, unix.RTM_NEWNSID)
return err
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | route.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/route.go#L170-L180 | go | train | // ipNetEqual returns true iff both IPNet are equal | func ipNetEqual(ipn1 *net.IPNet, ipn2 *net.IPNet) bool | // ipNetEqual returns true iff both IPNet are equal
func ipNetEqual(ipn1 *net.IPNet, ipn2 *net.IPNet) bool | {
if ipn1 == ipn2 {
return true
}
if ipn1 == nil || ipn2 == nil {
return false
}
m1, _ := ipn1.Mask.Size()
m2, _ := ipn2.Mask.Size()
return m1 == m2 && ipn1.IP.Equal(ipn2.IP)
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | bridge_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/bridge_linux.go#L18-L55 | go | train | // BridgeVlanList gets a map of device id to bridge vlan infos.
// Equivalent to: `bridge vlan show` | func (h *Handle) BridgeVlanList() (map[int32][]*nl.BridgeVlanInfo, error) | // BridgeVlanList gets a map of device id to bridge vlan infos.
// Equivalent to: `bridge vlan show`
func (h *Handle) BridgeVlanList() (map[int32][]*nl.BridgeVlanInfo, error) | {
req := h.newNetlinkRequest(unix.RTM_GETLINK, unix.NLM_F_DUMP)
msg := nl.NewIfInfomsg(unix.AF_BRIDGE)
req.AddData(msg)
req.AddData(nl.NewRtAttr(unix.IFLA_EXT_MASK, nl.Uint32Attr(uint32(nl.RTEXT_FILTER_BRVLAN))))
msgs, err := req.Execute(unix.NETLINK_ROUTE, unix.RTM_NEWLINK)
if err != nil {
return nil, err
}
ret := make(map[int32][]*nl.BridgeVlanInfo)
for _, m := range msgs {
msg := nl.DeserializeIfInfomsg(m)
attrs, err := nl.ParseRouteAttr(m[msg.Len():])
if err != nil {
return nil, err
}
for _, attr := range attrs {
switch attr.Attr.Type {
case unix.IFLA_AF_SPEC:
//nested attr
nestAttrs, err := nl.ParseRouteAttr(attr.Value)
if err != nil {
return nil, fmt.Errorf("failed to parse nested attr %v", err)
}
for _, nestAttr := range nestAttrs {
switch nestAttr.Attr.Type {
case nl.IFLA_BRIDGE_VLAN_INFO:
vlanInfo := nl.DeserializeBridgeVlanInfo(nestAttr.Value)
ret[msg.Index] = append(ret[msg.Index], vlanInfo)
}
}
}
}
}
return ret, nil
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | bridge_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/bridge_linux.go#L65-L67 | go | train | // BridgeVlanAdd adds a new vlan filter entry
// Equivalent to: `bridge vlan add dev DEV vid VID [ pvid ] [ untagged ] [ self ] [ master ]` | func (h *Handle) BridgeVlanAdd(link Link, vid uint16, pvid, untagged, self, master bool) error | // BridgeVlanAdd adds a new vlan filter entry
// Equivalent to: `bridge vlan add dev DEV vid VID [ pvid ] [ untagged ] [ self ] [ master ]`
func (h *Handle) BridgeVlanAdd(link Link, vid uint16, pvid, untagged, self, master bool) error | {
return h.bridgeVlanModify(unix.RTM_SETLINK, link, vid, pvid, untagged, self, master)
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | bridge_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/bridge_linux.go#L71-L73 | go | train | // BridgeVlanDel adds a new vlan filter entry
// Equivalent to: `bridge vlan del dev DEV vid VID [ pvid ] [ untagged ] [ self ] [ master ]` | func BridgeVlanDel(link Link, vid uint16, pvid, untagged, self, master bool) error | // BridgeVlanDel adds a new vlan filter entry
// Equivalent to: `bridge vlan del dev DEV vid VID [ pvid ] [ untagged ] [ self ] [ master ]`
func BridgeVlanDel(link Link, vid uint16, pvid, untagged, self, master bool) error | {
return pkgHandle.BridgeVlanDel(link, vid, pvid, untagged, self, master)
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | bridge_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/bridge_linux.go#L77-L79 | go | train | // BridgeVlanDel adds a new vlan filter entry
// Equivalent to: `bridge vlan del dev DEV vid VID [ pvid ] [ untagged ] [ self ] [ master ]` | func (h *Handle) BridgeVlanDel(link Link, vid uint16, pvid, untagged, self, master bool) error | // BridgeVlanDel adds a new vlan filter entry
// Equivalent to: `bridge vlan del dev DEV vid VID [ pvid ] [ untagged ] [ self ] [ master ]`
func (h *Handle) BridgeVlanDel(link Link, vid uint16, pvid, untagged, self, master bool) error | {
return h.bridgeVlanModify(unix.RTM_DELLINK, link, vid, pvid, untagged, self, master)
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | nl/seg6local_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/nl/seg6local_linux.go#L44-L76 | go | train | // Helper functions | func SEG6LocalActionString(action int) string | // Helper functions
func SEG6LocalActionString(action int) string | {
switch action {
case SEG6_LOCAL_ACTION_END:
return "End"
case SEG6_LOCAL_ACTION_END_X:
return "End.X"
case SEG6_LOCAL_ACTION_END_T:
return "End.T"
case SEG6_LOCAL_ACTION_END_DX2:
return "End.DX2"
case SEG6_LOCAL_ACTION_END_DX6:
return "End.DX6"
case SEG6_LOCAL_ACTION_END_DX4:
return "End.DX4"
case SEG6_LOCAL_ACTION_END_DT6:
return "End.DT6"
case SEG6_LOCAL_ACTION_END_DT4:
return "End.DT4"
case SEG6_LOCAL_ACTION_END_B6:
return "End.B6"
case SEG6_LOCAL_ACTION_END_B6_ENCAPS:
return "End.B6.Encaps"
case SEG6_LOCAL_ACTION_END_BM:
return "End.BM"
case SEG6_LOCAL_ACTION_END_S:
return "End.S"
case SEG6_LOCAL_ACTION_END_AS:
return "End.AS"
case SEG6_LOCAL_ACTION_END_AM:
return "End.AM"
}
return "unknown"
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | ioctl_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/ioctl_linux.go#L75-L80 | go | train | // newIocltSlaveReq returns filled IfreqSlave with proper interface names
// It is used by ioctl to assign slave to bond master | func newIocltSlaveReq(slave, master string) *IfreqSlave | // newIocltSlaveReq returns filled IfreqSlave with proper interface names
// It is used by ioctl to assign slave to bond master
func newIocltSlaveReq(slave, master string) *IfreqSlave | {
ifreq := &IfreqSlave{}
copy(ifreq.Name[:unix.IFNAMSIZ-1], master)
copy(ifreq.Slave[:unix.IFNAMSIZ-1], slave)
return ifreq
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | ioctl_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/ioctl_linux.go#L83-L92 | go | train | // newIocltStringSetReq creates request to get interface string set | func newIocltStringSetReq(linkName string) (*Ifreq, *ethtoolSset) | // newIocltStringSetReq creates request to get interface string set
func newIocltStringSetReq(linkName string) (*Ifreq, *ethtoolSset) | {
e := ðtoolSset{
cmd: ETHTOOL_GSSET_INFO,
mask: 1 << ETH_SS_STATS,
}
ifreq := &Ifreq{Data: uintptr(unsafe.Pointer(e))}
copy(ifreq.Name[:unix.IFNAMSIZ-1], linkName)
return ifreq, e
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | addr.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/addr.go#L23-L25 | go | train | // String returns $ip/$netmask $label | func (a Addr) String() string | // String returns $ip/$netmask $label
func (a Addr) String() string | {
return strings.TrimSpace(fmt.Sprintf("%s %s", a.IPNet, a.Label))
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | addr.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/addr.go#L29-L41 | go | train | // ParseAddr parses the string representation of an address in the
// form $ip/$netmask $label. The label portion is optional | func ParseAddr(s string) (*Addr, error) | // ParseAddr parses the string representation of an address in the
// form $ip/$netmask $label. The label portion is optional
func ParseAddr(s string) (*Addr, error) | {
label := ""
parts := strings.Split(s, " ")
if len(parts) > 1 {
s = parts[0]
label = parts[1]
}
m, err := ParseIPNet(s)
if err != nil {
return nil, err
}
return &Addr{IPNet: m, Label: label}, nil
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | addr.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/addr.go#L44-L49 | go | train | // Equal returns true if both Addrs have the same net.IPNet value. | func (a Addr) Equal(x Addr) bool | // Equal returns true if both Addrs have the same net.IPNet value.
func (a Addr) Equal(x Addr) bool | {
sizea, _ := a.Mask.Size()
sizeb, _ := x.Mask.Size()
// ignore label for comparison
return a.IP.Equal(x.IP) && sizea == sizeb
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | socket_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/socket_linux.go#L108-L159 | go | train | // SocketGet returns the Socket identified by its local and remote addresses. | func SocketGet(local, remote net.Addr) (*Socket, error) | // SocketGet returns the Socket identified by its local and remote addresses.
func SocketGet(local, remote net.Addr) (*Socket, error) | {
localTCP, ok := local.(*net.TCPAddr)
if !ok {
return nil, ErrNotImplemented
}
remoteTCP, ok := remote.(*net.TCPAddr)
if !ok {
return nil, ErrNotImplemented
}
localIP := localTCP.IP.To4()
if localIP == nil {
return nil, ErrNotImplemented
}
remoteIP := remoteTCP.IP.To4()
if remoteIP == nil {
return nil, ErrNotImplemented
}
s, err := nl.Subscribe(unix.NETLINK_INET_DIAG)
if err != nil {
return nil, err
}
defer s.Close()
req := nl.NewNetlinkRequest(nl.SOCK_DIAG_BY_FAMILY, 0)
req.AddData(&socketRequest{
Family: unix.AF_INET,
Protocol: unix.IPPROTO_TCP,
ID: SocketID{
SourcePort: uint16(localTCP.Port),
DestinationPort: uint16(remoteTCP.Port),
Source: localIP,
Destination: remoteIP,
Cookie: [2]uint32{nl.TCPDIAG_NOCOOKIE, nl.TCPDIAG_NOCOOKIE},
},
})
s.Send(req)
msgs, err := s.Receive()
if err != nil {
return nil, err
}
if len(msgs) == 0 {
return nil, errors.New("no message nor error from netlink")
}
if len(msgs) > 2 {
return nil, fmt.Errorf("multiple (%d) matching sockets", len(msgs))
}
sock := &Socket{}
if err := sock.deserialize(msgs[0].Data); err != nil {
return nil, err
}
return sock, nil
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | route_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/route_linux.go#L454-L458 | go | train | // RouteAdd will add a route to the system.
// Equivalent to: `ip route add $route` | func (h *Handle) RouteAdd(route *Route) error | // RouteAdd will add a route to the system.
// Equivalent to: `ip route add $route`
func (h *Handle) RouteAdd(route *Route) error | {
flags := unix.NLM_F_CREATE | unix.NLM_F_EXCL | unix.NLM_F_ACK
req := h.newNetlinkRequest(unix.RTM_NEWROUTE, flags)
return h.routeHandle(route, req, nl.NewRtMsg())
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | route_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/route_linux.go#L468-L472 | go | train | // RouteReplace will add a route to the system.
// Equivalent to: `ip route replace $route` | func (h *Handle) RouteReplace(route *Route) error | // RouteReplace will add a route to the system.
// Equivalent to: `ip route replace $route`
func (h *Handle) RouteReplace(route *Route) error | {
flags := unix.NLM_F_CREATE | unix.NLM_F_REPLACE | unix.NLM_F_ACK
req := h.newNetlinkRequest(unix.RTM_NEWROUTE, flags)
return h.routeHandle(route, req, nl.NewRtMsg())
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | route_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/route_linux.go#L482-L485 | go | train | // RouteDel will delete a route from the system.
// Equivalent to: `ip route del $route` | func (h *Handle) RouteDel(route *Route) error | // RouteDel will delete a route from the system.
// Equivalent to: `ip route del $route`
func (h *Handle) RouteDel(route *Route) error | {
req := h.newNetlinkRequest(unix.RTM_DELROUTE, unix.NLM_F_ACK)
return h.routeHandle(route, req, nl.NewRtDelMsg())
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | route_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/route_linux.go#L687-L689 | go | train | // RouteList gets a list of routes in the system.
// Equivalent to: `ip route show`.
// The list can be filtered by link and ip family. | func RouteList(link Link, family int) ([]Route, error) | // RouteList gets a list of routes in the system.
// Equivalent to: `ip route show`.
// The list can be filtered by link and ip family.
func RouteList(link Link, family int) ([]Route, error) | {
return pkgHandle.RouteList(link, family)
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | route_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/route_linux.go#L694-L702 | go | train | // RouteList gets a list of routes in the system.
// Equivalent to: `ip route show`.
// The list can be filtered by link and ip family. | func (h *Handle) RouteList(link Link, family int) ([]Route, error) | // RouteList gets a list of routes in the system.
// Equivalent to: `ip route show`.
// The list can be filtered by link and ip family.
func (h *Handle) RouteList(link Link, family int) ([]Route, error) | {
var routeFilter *Route
if link != nil {
routeFilter = &Route{
LinkIndex: link.Attrs().Index,
}
}
return h.RouteListFiltered(family, routeFilter, RT_FILTER_OIF)
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | route_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/route_linux.go#L706-L708 | go | train | // RouteListFiltered gets a list of routes in the system filtered with specified rules.
// All rules must be defined in RouteFilter struct | func RouteListFiltered(family int, filter *Route, filterMask uint64) ([]Route, error) | // RouteListFiltered gets a list of routes in the system filtered with specified rules.
// All rules must be defined in RouteFilter struct
func RouteListFiltered(family int, filter *Route, filterMask uint64) ([]Route, error) | {
return pkgHandle.RouteListFiltered(family, filter, filterMask)
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | route_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/route_linux.go#L712-L772 | go | train | // RouteListFiltered gets a list of routes in the system filtered with specified rules.
// All rules must be defined in RouteFilter struct | func (h *Handle) RouteListFiltered(family int, filter *Route, filterMask uint64) ([]Route, error) | // RouteListFiltered gets a list of routes in the system filtered with specified rules.
// All rules must be defined in RouteFilter struct
func (h *Handle) RouteListFiltered(family int, filter *Route, filterMask uint64) ([]Route, error) | {
req := h.newNetlinkRequest(unix.RTM_GETROUTE, unix.NLM_F_DUMP)
infmsg := nl.NewIfInfomsg(family)
req.AddData(infmsg)
msgs, err := req.Execute(unix.NETLINK_ROUTE, unix.RTM_NEWROUTE)
if err != nil {
return nil, err
}
var res []Route
for _, m := range msgs {
msg := nl.DeserializeRtMsg(m)
if msg.Flags&unix.RTM_F_CLONED != 0 {
// Ignore cloned routes
continue
}
if msg.Table != unix.RT_TABLE_MAIN {
if filter == nil || filter != nil && filterMask&RT_FILTER_TABLE == 0 {
// Ignore non-main tables
continue
}
}
route, err := deserializeRoute(m)
if err != nil {
return nil, err
}
if filter != nil {
switch {
case filterMask&RT_FILTER_TABLE != 0 && filter.Table != unix.RT_TABLE_UNSPEC && route.Table != filter.Table:
continue
case filterMask&RT_FILTER_PROTOCOL != 0 && route.Protocol != filter.Protocol:
continue
case filterMask&RT_FILTER_SCOPE != 0 && route.Scope != filter.Scope:
continue
case filterMask&RT_FILTER_TYPE != 0 && route.Type != filter.Type:
continue
case filterMask&RT_FILTER_TOS != 0 && route.Tos != filter.Tos:
continue
case filterMask&RT_FILTER_OIF != 0 && route.LinkIndex != filter.LinkIndex:
continue
case filterMask&RT_FILTER_IIF != 0 && route.ILinkIndex != filter.ILinkIndex:
continue
case filterMask&RT_FILTER_GW != 0 && !route.Gw.Equal(filter.Gw):
continue
case filterMask&RT_FILTER_SRC != 0 && !route.Src.Equal(filter.Src):
continue
case filterMask&RT_FILTER_DST != 0:
if filter.MPLSDst == nil || route.MPLSDst == nil || (*filter.MPLSDst) != (*route.MPLSDst) {
if !ipNetEqual(route.Dst, filter.Dst) {
continue
}
}
case filterMask&RT_FILTER_HOPLIMIT != 0 && route.Hoplimit != filter.Hoplimit:
continue
}
}
res = append(res, route)
}
return res, nil
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | route_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/route_linux.go#L775-L939 | go | train | // deserializeRoute decodes a binary netlink message into a Route struct | func deserializeRoute(m []byte) (Route, error) | // deserializeRoute decodes a binary netlink message into a Route struct
func deserializeRoute(m []byte) (Route, error) | {
msg := nl.DeserializeRtMsg(m)
attrs, err := nl.ParseRouteAttr(m[msg.Len():])
if err != nil {
return Route{}, err
}
route := Route{
Scope: Scope(msg.Scope),
Protocol: int(msg.Protocol),
Table: int(msg.Table),
Type: int(msg.Type),
Tos: int(msg.Tos),
Flags: int(msg.Flags),
}
native := nl.NativeEndian()
var encap, encapType syscall.NetlinkRouteAttr
for _, attr := range attrs {
switch attr.Attr.Type {
case unix.RTA_GATEWAY:
route.Gw = net.IP(attr.Value)
case unix.RTA_PREFSRC:
route.Src = net.IP(attr.Value)
case unix.RTA_DST:
if msg.Family == nl.FAMILY_MPLS {
stack := nl.DecodeMPLSStack(attr.Value)
if len(stack) == 0 || len(stack) > 1 {
return route, fmt.Errorf("invalid MPLS RTA_DST")
}
route.MPLSDst = &stack[0]
} else {
route.Dst = &net.IPNet{
IP: attr.Value,
Mask: net.CIDRMask(int(msg.Dst_len), 8*len(attr.Value)),
}
}
case unix.RTA_OIF:
route.LinkIndex = int(native.Uint32(attr.Value[0:4]))
case unix.RTA_IIF:
route.ILinkIndex = int(native.Uint32(attr.Value[0:4]))
case unix.RTA_PRIORITY:
route.Priority = int(native.Uint32(attr.Value[0:4]))
case unix.RTA_TABLE:
route.Table = int(native.Uint32(attr.Value[0:4]))
case unix.RTA_MULTIPATH:
parseRtNexthop := func(value []byte) (*NexthopInfo, []byte, error) {
if len(value) < unix.SizeofRtNexthop {
return nil, nil, fmt.Errorf("lack of bytes")
}
nh := nl.DeserializeRtNexthop(value)
if len(value) < int(nh.RtNexthop.Len) {
return nil, nil, fmt.Errorf("lack of bytes")
}
info := &NexthopInfo{
LinkIndex: int(nh.RtNexthop.Ifindex),
Hops: int(nh.RtNexthop.Hops),
Flags: int(nh.RtNexthop.Flags),
}
attrs, err := nl.ParseRouteAttr(value[unix.SizeofRtNexthop:int(nh.RtNexthop.Len)])
if err != nil {
return nil, nil, err
}
var encap, encapType syscall.NetlinkRouteAttr
for _, attr := range attrs {
switch attr.Attr.Type {
case unix.RTA_GATEWAY:
info.Gw = net.IP(attr.Value)
case nl.RTA_NEWDST:
var d Destination
switch msg.Family {
case nl.FAMILY_MPLS:
d = &MPLSDestination{}
}
if err := d.Decode(attr.Value); err != nil {
return nil, nil, err
}
info.NewDst = d
case nl.RTA_ENCAP_TYPE:
encapType = attr
case nl.RTA_ENCAP:
encap = attr
}
}
if len(encap.Value) != 0 && len(encapType.Value) != 0 {
typ := int(native.Uint16(encapType.Value[0:2]))
var e Encap
switch typ {
case nl.LWTUNNEL_ENCAP_MPLS:
e = &MPLSEncap{}
if err := e.Decode(encap.Value); err != nil {
return nil, nil, err
}
}
info.Encap = e
}
return info, value[int(nh.RtNexthop.Len):], nil
}
rest := attr.Value
for len(rest) > 0 {
info, buf, err := parseRtNexthop(rest)
if err != nil {
return route, err
}
route.MultiPath = append(route.MultiPath, info)
rest = buf
}
case nl.RTA_NEWDST:
var d Destination
switch msg.Family {
case nl.FAMILY_MPLS:
d = &MPLSDestination{}
}
if err := d.Decode(attr.Value); err != nil {
return route, err
}
route.NewDst = d
case nl.RTA_ENCAP_TYPE:
encapType = attr
case nl.RTA_ENCAP:
encap = attr
case unix.RTA_METRICS:
metrics, err := nl.ParseRouteAttr(attr.Value)
if err != nil {
return route, err
}
for _, metric := range metrics {
switch metric.Attr.Type {
case unix.RTAX_MTU:
route.MTU = int(native.Uint32(metric.Value[0:4]))
case unix.RTAX_ADVMSS:
route.AdvMSS = int(native.Uint32(metric.Value[0:4]))
case unix.RTAX_HOPLIMIT:
route.Hoplimit = int(native.Uint32(metric.Value[0:4]))
}
}
}
}
if len(encap.Value) != 0 && len(encapType.Value) != 0 {
typ := int(native.Uint16(encapType.Value[0:2]))
var e Encap
switch typ {
case nl.LWTUNNEL_ENCAP_MPLS:
e = &MPLSEncap{}
if err := e.Decode(encap.Value); err != nil {
return route, err
}
case nl.LWTUNNEL_ENCAP_SEG6:
e = &SEG6Encap{}
if err := e.Decode(encap.Value); err != nil {
return route, err
}
case nl.LWTUNNEL_ENCAP_SEG6_LOCAL:
e = &SEG6LocalEncap{}
if err := e.Decode(encap.Value); err != nil {
return route, err
}
}
route.Encap = e
}
return route, nil
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | route_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/route_linux.go#L949-L984 | go | train | // RouteGet gets a route to a specific destination from the host system.
// Equivalent to: 'ip route get'. | func (h *Handle) RouteGet(destination net.IP) ([]Route, error) | // RouteGet gets a route to a specific destination from the host system.
// Equivalent to: 'ip route get'.
func (h *Handle) RouteGet(destination net.IP) ([]Route, error) | {
req := h.newNetlinkRequest(unix.RTM_GETROUTE, unix.NLM_F_REQUEST)
family := nl.GetIPFamily(destination)
var destinationData []byte
var bitlen uint8
if family == FAMILY_V4 {
destinationData = destination.To4()
bitlen = 32
} else {
destinationData = destination.To16()
bitlen = 128
}
msg := &nl.RtMsg{}
msg.Family = uint8(family)
msg.Dst_len = bitlen
req.AddData(msg)
rtaDst := nl.NewRtAttr(unix.RTA_DST, destinationData)
req.AddData(rtaDst)
msgs, err := req.Execute(unix.NETLINK_ROUTE, unix.RTM_NEWROUTE)
if err != nil {
return nil, err
}
var res []Route
for _, m := range msgs {
route, err := deserializeRoute(m)
if err != nil {
return nil, err
}
res = append(res, route)
}
return res, nil
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | route_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/route_linux.go#L988-L990 | go | train | // RouteSubscribe takes a chan down which notifications will be sent
// when routes are added or deleted. Close the 'done' chan to stop subscription. | func RouteSubscribe(ch chan<- RouteUpdate, done <-chan struct{}) error | // RouteSubscribe takes a chan down which notifications will be sent
// when routes are added or deleted. Close the 'done' chan to stop subscription.
func RouteSubscribe(ch chan<- RouteUpdate, done <-chan struct{}) error | {
return routeSubscribeAt(netns.None(), netns.None(), ch, done, nil, false)
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | route_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/route_linux.go#L994-L996 | go | train | // RouteSubscribeAt works like RouteSubscribe plus it allows the caller
// to choose the network namespace in which to subscribe (ns). | func RouteSubscribeAt(ns netns.NsHandle, ch chan<- RouteUpdate, done <-chan struct{}) error | // RouteSubscribeAt works like RouteSubscribe plus it allows the caller
// to choose the network namespace in which to subscribe (ns).
func RouteSubscribeAt(ns netns.NsHandle, ch chan<- RouteUpdate, done <-chan struct{}) error | {
return routeSubscribeAt(ns, netns.None(), ch, done, nil, false)
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | route_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/route_linux.go#L1009-L1015 | go | train | // RouteSubscribeWithOptions work like RouteSubscribe but enable to
// provide additional options to modify the behavior. Currently, the
// namespace can be provided as well as an error callback. | func RouteSubscribeWithOptions(ch chan<- RouteUpdate, done <-chan struct{}, options RouteSubscribeOptions) error | // RouteSubscribeWithOptions work like RouteSubscribe but enable to
// provide additional options to modify the behavior. Currently, the
// namespace can be provided as well as an error callback.
func RouteSubscribeWithOptions(ch chan<- RouteUpdate, done <-chan struct{}, options RouteSubscribeOptions) error | {
if options.Namespace == nil {
none := netns.None()
options.Namespace = &none
}
return routeSubscribeAt(*options.Namespace, netns.None(), ch, done, options.ErrorCallback, options.ListExisting)
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | bpf_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/bpf_linux.go#L33-L53 | go | train | // loadSimpleBpf loads a trivial bpf program for testing purposes. | func loadSimpleBpf(progType BpfProgType, ret uint32) (int, error) | // loadSimpleBpf loads a trivial bpf program for testing purposes.
func loadSimpleBpf(progType BpfProgType, ret uint32) (int, error) | {
insns := []uint64{
0x00000000000000b7 | (uint64(ret) << 32),
0x0000000000000095,
}
license := []byte{'A', 'S', 'L', '2', '\x00'}
attr := BPFAttr{
ProgType: uint32(progType),
InsnCnt: uint32(len(insns)),
Insns: uintptr(unsafe.Pointer(&insns[0])),
License: uintptr(unsafe.Pointer(&license[0])),
}
fd, _, errno := unix.Syscall(unix.SYS_BPF,
5, /* bpf cmd */
uintptr(unsafe.Pointer(&attr)),
unsafe.Sizeof(attr))
if errno != 0 {
return 0, errno
}
return int(fd), nil
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | filter_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/filter_linux.go#L129-L143 | go | train | // FilterDel will delete a filter from the system.
// Equivalent to: `tc filter del $filter` | func (h *Handle) FilterDel(filter Filter) error | // FilterDel will delete a filter from the system.
// Equivalent to: `tc filter del $filter`
func (h *Handle) FilterDel(filter Filter) error | {
req := h.newNetlinkRequest(unix.RTM_DELTFILTER, unix.NLM_F_ACK)
base := filter.Attrs()
msg := &nl.TcMsg{
Family: nl.FAMILY_ALL,
Ifindex: int32(base.LinkIndex),
Handle: base.Handle,
Parent: base.Parent,
Info: MakeHandle(base.Priority, nl.Swap16(base.Protocol)),
}
req.AddData(msg)
_, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | filter_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/filter_linux.go#L153-L274 | go | train | // FilterAdd will add a filter to the system.
// Equivalent to: `tc filter add $filter` | func (h *Handle) FilterAdd(filter Filter) error | // FilterAdd will add a filter to the system.
// Equivalent to: `tc filter add $filter`
func (h *Handle) FilterAdd(filter Filter) error | {
native = nl.NativeEndian()
req := h.newNetlinkRequest(unix.RTM_NEWTFILTER, unix.NLM_F_CREATE|unix.NLM_F_EXCL|unix.NLM_F_ACK)
base := filter.Attrs()
msg := &nl.TcMsg{
Family: nl.FAMILY_ALL,
Ifindex: int32(base.LinkIndex),
Handle: base.Handle,
Parent: base.Parent,
Info: MakeHandle(base.Priority, nl.Swap16(base.Protocol)),
}
req.AddData(msg)
req.AddData(nl.NewRtAttr(nl.TCA_KIND, nl.ZeroTerminated(filter.Type())))
options := nl.NewRtAttr(nl.TCA_OPTIONS, nil)
switch filter := filter.(type) {
case *U32:
sel := filter.Sel
if sel == nil {
// match all
sel = &nl.TcU32Sel{
Nkeys: 1,
Flags: nl.TC_U32_TERMINAL,
}
sel.Keys = append(sel.Keys, nl.TcU32Key{})
}
if native != networkOrder {
// Copy TcU32Sel.
cSel := *sel
keys := make([]nl.TcU32Key, cap(sel.Keys))
copy(keys, sel.Keys)
cSel.Keys = keys
sel = &cSel
// Handle the endianness of attributes
sel.Offmask = native.Uint16(htons(sel.Offmask))
sel.Hmask = native.Uint32(htonl(sel.Hmask))
for i, key := range sel.Keys {
sel.Keys[i].Mask = native.Uint32(htonl(key.Mask))
sel.Keys[i].Val = native.Uint32(htonl(key.Val))
}
}
sel.Nkeys = uint8(len(sel.Keys))
options.AddRtAttr(nl.TCA_U32_SEL, sel.Serialize())
if filter.ClassId != 0 {
options.AddRtAttr(nl.TCA_U32_CLASSID, nl.Uint32Attr(filter.ClassId))
}
if filter.Divisor != 0 {
if (filter.Divisor-1)&filter.Divisor != 0 {
return fmt.Errorf("illegal divisor %d. Must be a power of 2", filter.Divisor)
}
options.AddRtAttr(nl.TCA_U32_DIVISOR, nl.Uint32Attr(filter.Divisor))
}
if filter.Hash != 0 {
options.AddRtAttr(nl.TCA_U32_HASH, nl.Uint32Attr(filter.Hash))
}
actionsAttr := options.AddRtAttr(nl.TCA_U32_ACT, nil)
// backwards compatibility
if filter.RedirIndex != 0 {
filter.Actions = append([]Action{NewMirredAction(filter.RedirIndex)}, filter.Actions...)
}
if err := EncodeActions(actionsAttr, filter.Actions); err != nil {
return err
}
case *Fw:
if filter.Mask != 0 {
b := make([]byte, 4)
native.PutUint32(b, filter.Mask)
options.AddRtAttr(nl.TCA_FW_MASK, b)
}
if filter.InDev != "" {
options.AddRtAttr(nl.TCA_FW_INDEV, nl.ZeroTerminated(filter.InDev))
}
if (filter.Police != nl.TcPolice{}) {
police := options.AddRtAttr(nl.TCA_FW_POLICE, nil)
police.AddRtAttr(nl.TCA_POLICE_TBF, filter.Police.Serialize())
if (filter.Police.Rate != nl.TcRateSpec{}) {
payload := SerializeRtab(filter.Rtab)
police.AddRtAttr(nl.TCA_POLICE_RATE, payload)
}
if (filter.Police.PeakRate != nl.TcRateSpec{}) {
payload := SerializeRtab(filter.Ptab)
police.AddRtAttr(nl.TCA_POLICE_PEAKRATE, payload)
}
}
if filter.ClassId != 0 {
b := make([]byte, 4)
native.PutUint32(b, filter.ClassId)
options.AddRtAttr(nl.TCA_FW_CLASSID, b)
}
case *BpfFilter:
var bpfFlags uint32
if filter.ClassId != 0 {
options.AddRtAttr(nl.TCA_BPF_CLASSID, nl.Uint32Attr(filter.ClassId))
}
if filter.Fd >= 0 {
options.AddRtAttr(nl.TCA_BPF_FD, nl.Uint32Attr((uint32(filter.Fd))))
}
if filter.Name != "" {
options.AddRtAttr(nl.TCA_BPF_NAME, nl.ZeroTerminated(filter.Name))
}
if filter.DirectAction {
bpfFlags |= nl.TCA_BPF_FLAG_ACT_DIRECT
}
options.AddRtAttr(nl.TCA_BPF_FLAGS, nl.Uint32Attr(bpfFlags))
case *MatchAll:
actionsAttr := options.AddRtAttr(nl.TCA_MATCHALL_ACT, nil)
if err := EncodeActions(actionsAttr, filter.Actions); err != nil {
return err
}
if filter.ClassId != 0 {
options.AddRtAttr(nl.TCA_MATCHALL_CLASSID, nl.Uint32Attr(filter.ClassId))
}
}
req.AddData(options)
_, err := req.Execute(unix.NETLINK_ROUTE, 0)
return err
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | filter_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/filter_linux.go#L279-L281 | go | train | // FilterList gets a list of filters in the system.
// Equivalent to: `tc filter show`.
// Generally returns nothing if link and parent are not specified. | func FilterList(link Link, parent uint32) ([]Filter, error) | // FilterList gets a list of filters in the system.
// Equivalent to: `tc filter show`.
// Generally returns nothing if link and parent are not specified.
func FilterList(link Link, parent uint32) ([]Filter, error) | {
return pkgHandle.FilterList(link, parent)
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | filter_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/filter_linux.go#L286-L379 | go | train | // FilterList gets a list of filters in the system.
// Equivalent to: `tc filter show`.
// Generally returns nothing if link and parent are not specified. | func (h *Handle) FilterList(link Link, parent uint32) ([]Filter, error) | // FilterList gets a list of filters in the system.
// Equivalent to: `tc filter show`.
// Generally returns nothing if link and parent are not specified.
func (h *Handle) FilterList(link Link, parent uint32) ([]Filter, error) | {
req := h.newNetlinkRequest(unix.RTM_GETTFILTER, unix.NLM_F_DUMP)
msg := &nl.TcMsg{
Family: nl.FAMILY_ALL,
Parent: parent,
}
if link != nil {
base := link.Attrs()
h.ensureIndex(base)
msg.Ifindex = int32(base.Index)
}
req.AddData(msg)
msgs, err := req.Execute(unix.NETLINK_ROUTE, unix.RTM_NEWTFILTER)
if err != nil {
return nil, err
}
var res []Filter
for _, m := range msgs {
msg := nl.DeserializeTcMsg(m)
attrs, err := nl.ParseRouteAttr(m[msg.Len():])
if err != nil {
return nil, err
}
base := FilterAttrs{
LinkIndex: int(msg.Ifindex),
Handle: msg.Handle,
Parent: msg.Parent,
}
base.Priority, base.Protocol = MajorMinor(msg.Info)
base.Protocol = nl.Swap16(base.Protocol)
var filter Filter
filterType := ""
detailed := false
for _, attr := range attrs {
switch attr.Attr.Type {
case nl.TCA_KIND:
filterType = string(attr.Value[:len(attr.Value)-1])
switch filterType {
case "u32":
filter = &U32{}
case "fw":
filter = &Fw{}
case "bpf":
filter = &BpfFilter{}
case "matchall":
filter = &MatchAll{}
default:
filter = &GenericFilter{FilterType: filterType}
}
case nl.TCA_OPTIONS:
data, err := nl.ParseRouteAttr(attr.Value)
if err != nil {
return nil, err
}
switch filterType {
case "u32":
detailed, err = parseU32Data(filter, data)
if err != nil {
return nil, err
}
case "fw":
detailed, err = parseFwData(filter, data)
if err != nil {
return nil, err
}
case "bpf":
detailed, err = parseBpfData(filter, data)
if err != nil {
return nil, err
}
case "matchall":
detailed, err = parseMatchAllData(filter, data)
if err != nil {
return nil, err
}
default:
detailed = true
}
}
}
// only return the detailed version of the filter
if detailed {
*filter.Attrs() = base
res = append(res, filter)
}
}
return res, nil
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | rule.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/rule.go#L32-L42 | go | train | // NewRule return empty rules. | func NewRule() *Rule | // NewRule return empty rules.
func NewRule() *Rule | {
return &Rule{
SuppressIfgroup: -1,
SuppressPrefixlen: -1,
Priority: -1,
Mark: -1,
Mask: -1,
Goto: -1,
Flow: -1,
}
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | qdisc_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/qdisc_linux.go#L15-L77 | go | train | // NOTE function is here because it uses other linux functions | func NewNetem(attrs QdiscAttrs, nattrs NetemQdiscAttrs) *Netem | // NOTE function is here because it uses other linux functions
func NewNetem(attrs QdiscAttrs, nattrs NetemQdiscAttrs) *Netem | {
var limit uint32 = 1000
var lossCorr, delayCorr, duplicateCorr uint32
var reorderProb, reorderCorr uint32
var corruptProb, corruptCorr uint32
latency := nattrs.Latency
loss := Percentage2u32(nattrs.Loss)
gap := nattrs.Gap
duplicate := Percentage2u32(nattrs.Duplicate)
jitter := nattrs.Jitter
// Correlation
if latency > 0 && jitter > 0 {
delayCorr = Percentage2u32(nattrs.DelayCorr)
}
if loss > 0 {
lossCorr = Percentage2u32(nattrs.LossCorr)
}
if duplicate > 0 {
duplicateCorr = Percentage2u32(nattrs.DuplicateCorr)
}
// FIXME should validate values(like loss/duplicate are percentages...)
latency = time2Tick(latency)
if nattrs.Limit != 0 {
limit = nattrs.Limit
}
// Jitter is only value if latency is > 0
if latency > 0 {
jitter = time2Tick(jitter)
}
reorderProb = Percentage2u32(nattrs.ReorderProb)
reorderCorr = Percentage2u32(nattrs.ReorderCorr)
if reorderProb > 0 {
// ERROR if lantency == 0
if gap == 0 {
gap = 1
}
}
corruptProb = Percentage2u32(nattrs.CorruptProb)
corruptCorr = Percentage2u32(nattrs.CorruptCorr)
return &Netem{
QdiscAttrs: attrs,
Latency: latency,
DelayCorr: delayCorr,
Limit: limit,
Loss: loss,
LossCorr: lossCorr,
Gap: gap,
Duplicate: duplicate,
DuplicateCorr: duplicateCorr,
Jitter: jitter,
ReorderProb: reorderProb,
ReorderCorr: reorderCorr,
CorruptProb: corruptProb,
CorruptCorr: corruptCorr,
}
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | qdisc_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/qdisc_linux.go#L87-L89 | go | train | // QdiscDel will delete a qdisc from the system.
// Equivalent to: `tc qdisc del $qdisc` | func (h *Handle) QdiscDel(qdisc Qdisc) error | // QdiscDel will delete a qdisc from the system.
// Equivalent to: `tc qdisc del $qdisc`
func (h *Handle) QdiscDel(qdisc Qdisc) error | {
return h.qdiscModify(unix.RTM_DELQDISC, 0, qdisc)
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | qdisc_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/qdisc_linux.go#L101-L103 | go | train | // QdiscChange will change a qdisc in place
// Equivalent to: `tc qdisc change $qdisc`
// The parent and handle MUST NOT be changed. | func (h *Handle) QdiscChange(qdisc Qdisc) error | // QdiscChange will change a qdisc in place
// Equivalent to: `tc qdisc change $qdisc`
// The parent and handle MUST NOT be changed.
func (h *Handle) QdiscChange(qdisc Qdisc) error | {
return h.qdiscModify(unix.RTM_NEWQDISC, 0, qdisc)
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | qdisc_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/qdisc_linux.go#L115-L120 | go | train | // QdiscReplace will replace a qdisc to the system.
// Equivalent to: `tc qdisc replace $qdisc`
// The handle MUST change. | func (h *Handle) QdiscReplace(qdisc Qdisc) error | // QdiscReplace will replace a qdisc to the system.
// Equivalent to: `tc qdisc replace $qdisc`
// The handle MUST change.
func (h *Handle) QdiscReplace(qdisc Qdisc) error | {
return h.qdiscModify(
unix.RTM_NEWQDISC,
unix.NLM_F_CREATE|unix.NLM_F_REPLACE,
qdisc)
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | qdisc_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/qdisc_linux.go#L130-L135 | go | train | // QdiscAdd will add a qdisc to the system.
// Equivalent to: `tc qdisc add $qdisc` | func (h *Handle) QdiscAdd(qdisc Qdisc) error | // QdiscAdd will add a qdisc to the system.
// Equivalent to: `tc qdisc add $qdisc`
func (h *Handle) QdiscAdd(qdisc Qdisc) error | {
return h.qdiscModify(
unix.RTM_NEWQDISC,
unix.NLM_F_CREATE|unix.NLM_F_EXCL,
qdisc)
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | qdisc_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/qdisc_linux.go#L301-L430 | go | train | // QdiscList gets a list of qdiscs in the system.
// Equivalent to: `tc qdisc show`.
// The list can be filtered by link. | func (h *Handle) QdiscList(link Link) ([]Qdisc, error) | // QdiscList gets a list of qdiscs in the system.
// Equivalent to: `tc qdisc show`.
// The list can be filtered by link.
func (h *Handle) QdiscList(link Link) ([]Qdisc, error) | {
req := h.newNetlinkRequest(unix.RTM_GETQDISC, unix.NLM_F_DUMP)
index := int32(0)
if link != nil {
base := link.Attrs()
h.ensureIndex(base)
index = int32(base.Index)
}
msg := &nl.TcMsg{
Family: nl.FAMILY_ALL,
Ifindex: index,
}
req.AddData(msg)
msgs, err := req.Execute(unix.NETLINK_ROUTE, unix.RTM_NEWQDISC)
if err != nil {
return nil, err
}
var res []Qdisc
for _, m := range msgs {
msg := nl.DeserializeTcMsg(m)
attrs, err := nl.ParseRouteAttr(m[msg.Len():])
if err != nil {
return nil, err
}
// skip qdiscs from other interfaces
if link != nil && msg.Ifindex != index {
continue
}
base := QdiscAttrs{
LinkIndex: int(msg.Ifindex),
Handle: msg.Handle,
Parent: msg.Parent,
Refcnt: msg.Info,
}
var qdisc Qdisc
qdiscType := ""
for _, attr := range attrs {
switch attr.Attr.Type {
case nl.TCA_KIND:
qdiscType = string(attr.Value[:len(attr.Value)-1])
switch qdiscType {
case "pfifo_fast":
qdisc = &PfifoFast{}
case "prio":
qdisc = &Prio{}
case "tbf":
qdisc = &Tbf{}
case "ingress":
qdisc = &Ingress{}
case "htb":
qdisc = &Htb{}
case "fq":
qdisc = &Fq{}
case "hfsc":
qdisc = &Hfsc{}
case "fq_codel":
qdisc = &FqCodel{}
case "netem":
qdisc = &Netem{}
default:
qdisc = &GenericQdisc{QdiscType: qdiscType}
}
case nl.TCA_OPTIONS:
switch qdiscType {
case "pfifo_fast":
// pfifo returns TcPrioMap directly without wrapping it in rtattr
if err := parsePfifoFastData(qdisc, attr.Value); err != nil {
return nil, err
}
case "prio":
// prio returns TcPrioMap directly without wrapping it in rtattr
if err := parsePrioData(qdisc, attr.Value); err != nil {
return nil, err
}
case "tbf":
data, err := nl.ParseRouteAttr(attr.Value)
if err != nil {
return nil, err
}
if err := parseTbfData(qdisc, data); err != nil {
return nil, err
}
case "hfsc":
if err := parseHfscData(qdisc, attr.Value); err != nil {
return nil, err
}
case "htb":
data, err := nl.ParseRouteAttr(attr.Value)
if err != nil {
return nil, err
}
if err := parseHtbData(qdisc, data); err != nil {
return nil, err
}
case "fq":
data, err := nl.ParseRouteAttr(attr.Value)
if err != nil {
return nil, err
}
if err := parseFqData(qdisc, data); err != nil {
return nil, err
}
case "fq_codel":
data, err := nl.ParseRouteAttr(attr.Value)
if err != nil {
return nil, err
}
if err := parseFqCodelData(qdisc, data); err != nil {
return nil, err
}
case "netem":
if err := parseNetemData(qdisc, attr.Value); err != nil {
return nil, err
}
// no options for ingress
}
}
}
*qdisc.Attrs() = base
res = append(res, qdisc)
}
return res, nil
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | handle_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/handle_linux.go#L25-L28 | go | train | // SupportsNetlinkFamily reports whether the passed netlink family is supported by this Handle | func (h *Handle) SupportsNetlinkFamily(nlFamily int) bool | // SupportsNetlinkFamily reports whether the passed netlink family is supported by this Handle
func (h *Handle) SupportsNetlinkFamily(nlFamily int) bool | {
_, ok := h.sockets[nlFamily]
return ok
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | handle_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/handle_linux.go#L34-L36 | go | train | // NewHandle returns a netlink handle on the current network namespace.
// Caller may specify the netlink families the handle should support.
// If no families are specified, all the families the netlink package
// supports will be automatically added. | func NewHandle(nlFamilies ...int) (*Handle, error) | // NewHandle returns a netlink handle on the current network namespace.
// Caller may specify the netlink families the handle should support.
// If no families are specified, all the families the netlink package
// supports will be automatically added.
func NewHandle(nlFamilies ...int) (*Handle, error) | {
return newHandle(netns.None(), netns.None(), nlFamilies...)
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | handle_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/handle_linux.go#L42-L56 | go | train | // SetSocketTimeout sets the send and receive timeout for each socket in the
// netlink handle. Although the socket timeout has granularity of one
// microsecond, the effective granularity is floored by the kernel timer tick,
// which default value is four milliseconds. | func (h *Handle) SetSocketTimeout(to time.Duration) error | // SetSocketTimeout sets the send and receive timeout for each socket in the
// netlink handle. Although the socket timeout has granularity of one
// microsecond, the effective granularity is floored by the kernel timer tick,
// which default value is four milliseconds.
func (h *Handle) SetSocketTimeout(to time.Duration) error | {
if to < time.Microsecond {
return fmt.Errorf("invalid timeout, minimul value is %s", time.Microsecond)
}
tv := unix.NsecToTimeval(to.Nanoseconds())
for _, sh := range h.sockets {
if err := sh.Socket.SetSendTimeout(&tv); err != nil {
return err
}
if err := sh.Socket.SetReceiveTimeout(&tv); err != nil {
return err
}
}
return nil
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | handle_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/handle_linux.go#L61-L74 | go | train | // SetSocketReceiveBufferSize sets the receive buffer size for each
// socket in the netlink handle. The maximum value is capped by
// /proc/sys/net/core/rmem_max. | func (h *Handle) SetSocketReceiveBufferSize(size int, force bool) error | // SetSocketReceiveBufferSize sets the receive buffer size for each
// socket in the netlink handle. The maximum value is capped by
// /proc/sys/net/core/rmem_max.
func (h *Handle) SetSocketReceiveBufferSize(size int, force bool) error | {
opt := unix.SO_RCVBUF
if force {
opt = unix.SO_RCVBUFFORCE
}
for _, sh := range h.sockets {
fd := sh.Socket.GetFd()
err := unix.SetsockoptInt(fd, unix.SOL_SOCKET, opt, size)
if err != nil {
return err
}
}
return nil
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | handle_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/handle_linux.go#L79-L92 | go | train | // GetSocketReceiveBufferSize gets the receiver buffer size for each
// socket in the netlink handle. The retrieved value should be the
// double to the one set for SetSocketReceiveBufferSize. | func (h *Handle) GetSocketReceiveBufferSize() ([]int, error) | // GetSocketReceiveBufferSize gets the receiver buffer size for each
// socket in the netlink handle. The retrieved value should be the
// double to the one set for SetSocketReceiveBufferSize.
func (h *Handle) GetSocketReceiveBufferSize() ([]int, error) | {
results := make([]int, len(h.sockets))
i := 0
for _, sh := range h.sockets {
fd := sh.Socket.GetFd()
size, err := unix.GetsockoptInt(fd, unix.SOL_SOCKET, unix.SO_RCVBUF)
if err != nil {
return nil, err
}
results[i] = size
i++
}
return results, nil
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | handle_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/handle_linux.go#L97-L99 | go | train | // NewHandleAt returns a netlink handle on the network namespace
// specified by ns. If ns=netns.None(), current network namespace
// will be assumed | func NewHandleAt(ns netns.NsHandle, nlFamilies ...int) (*Handle, error) | // NewHandleAt returns a netlink handle on the network namespace
// specified by ns. If ns=netns.None(), current network namespace
// will be assumed
func NewHandleAt(ns netns.NsHandle, nlFamilies ...int) (*Handle, error) | {
return newHandle(ns, netns.None(), nlFamilies...)
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | handle_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/handle_linux.go#L103-L105 | go | train | // NewHandleAtFrom works as NewHandle but allows client to specify the
// new and the origin netns Handle. | func NewHandleAtFrom(newNs, curNs netns.NsHandle) (*Handle, error) | // NewHandleAtFrom works as NewHandle but allows client to specify the
// new and the origin netns Handle.
func NewHandleAtFrom(newNs, curNs netns.NsHandle) (*Handle, error) | {
return newHandle(newNs, curNs)
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | handle_linux.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/handle_linux.go#L124-L129 | go | train | // Delete releases the resources allocated to this handle | func (h *Handle) Delete() | // Delete releases the resources allocated to this handle
func (h *Handle) Delete() | {
for _, sh := range h.sockets {
sh.Close()
}
h.sockets = nil
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | conntrack_unspecified.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/conntrack_unspecified.go#L32-L34 | go | train | // ConntrackDeleteFilter deletes entries on the specified table on the base of the filter
// conntrack -D [table] parameters Delete conntrack or expectation | func ConntrackDeleteFilter(table ConntrackTableType, family InetFamily, filter *ConntrackFilter) (uint, error) | // ConntrackDeleteFilter deletes entries on the specified table on the base of the filter
// conntrack -D [table] parameters Delete conntrack or expectation
func ConntrackDeleteFilter(table ConntrackTableType, family InetFamily, filter *ConntrackFilter) (uint, error) | {
return 0, ErrNotImplemented
} |
vishvananda/netlink | fd97bf4e47867b5e794234baa6b8a7746135ec10 | conntrack_unspecified.go | https://github.com/vishvananda/netlink/blob/fd97bf4e47867b5e794234baa6b8a7746135ec10/conntrack_unspecified.go#L38-L40 | go | train | // ConntrackTableList returns the flow list of a table of a specific family using the netlink handle passed
// conntrack -L [table] [options] List conntrack or expectation table | func (h *Handle) ConntrackTableList(table ConntrackTableType, family InetFamily) ([]*ConntrackFlow, error) | // ConntrackTableList returns the flow list of a table of a specific family using the netlink handle passed
// conntrack -L [table] [options] List conntrack or expectation table
func (h *Handle) ConntrackTableList(table ConntrackTableType, family InetFamily) ([]*ConntrackFlow, error) | {
return nil, ErrNotImplemented
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/controller/cache/util.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/controller/cache/util.go#L30-L32 | go | train | // MakeSnapshotName makes a full name for a snapshot that includes
// the namespace and the short name | func MakeSnapshotName(snapshot *crdv1.VolumeSnapshot) string | // MakeSnapshotName makes a full name for a snapshot that includes
// the namespace and the short name
func MakeSnapshotName(snapshot *crdv1.VolumeSnapshot) string | {
return snapshot.Metadata.Namespace + "/" + snapshot.Metadata.Name + "-" + string(snapshot.Metadata.UID)
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | gluster/glusterfs/pkg/volume/config.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/gluster/glusterfs/pkg/volume/config.go#L41-L84 | go | train | // NewProvisionerConfig create ProvisionerConfig from parameters of StorageClass | func NewProvisionerConfig(pvName string, params map[string]string) (*ProvisionerConfig, error) | // NewProvisionerConfig create ProvisionerConfig from parameters of StorageClass
func NewProvisionerConfig(pvName string, params map[string]string) (*ProvisionerConfig, error) | {
var config ProvisionerConfig
var err error
// Set default volume type
forceCreate := false
volumeType := ""
namespace := "default"
selector := "glusterfs-node==pod"
var brickRootPaths []BrickRootPath
for k, v := range params {
switch strings.ToLower(k) {
case "brickrootpaths":
brickRootPaths, err = parseBrickRootPaths(v)
if err != nil {
return nil, err
}
case "volumetype":
volumeType = strings.TrimSpace(v)
case "namespace":
namespace = strings.TrimSpace(v)
case "selector":
selector = strings.TrimSpace(v)
case "forcecreate":
v = strings.TrimSpace(v)
forceCreate = strings.ToLower(v) == "true"
}
}
config.BrickRootPaths = brickRootPaths
config.VolumeName = pvName
config.VolumeType = volumeType
config.Namespace = namespace
config.LabelSelector = selector
config.ForceCreate = forceCreate
err = config.validate()
if err != nil {
return nil, err
}
return &config, nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/volume/gcepd/processor.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/volume/gcepd/processor.go#L189-L194 | go | train | // FindSnapshot finds a VolumeSnapshot by matching metadata | func (plugin *gcePersistentDiskPlugin) FindSnapshot(tags *map[string]string) (*crdv1.VolumeSnapshotDataSource, *[]crdv1.VolumeSnapshotCondition, error) | // FindSnapshot finds a VolumeSnapshot by matching metadata
func (plugin *gcePersistentDiskPlugin) FindSnapshot(tags *map[string]string) (*crdv1.VolumeSnapshotDataSource, *[]crdv1.VolumeSnapshotCondition, error) | {
glog.Infof("FindSnapshot by tags: %#v", *tags)
// TODO: Implement FindSnapshot
return nil, nil, fmt.Errorf("Snapshot not found")
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | nfs/pkg/volume/export.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/nfs/pkg/volume/export.go#L123-L136 | go | train | // Export exports the given directory using NFS Ganesha, assuming it is running
// and can be connected to using D-Bus. | func (e *ganeshaExporter) Export(path string) error | // Export exports the given directory using NFS Ganesha, assuming it is running
// and can be connected to using D-Bus.
func (e *ganeshaExporter) Export(path string) error | {
// Call AddExport using dbus
conn, err := dbus.SystemBus()
if err != nil {
return fmt.Errorf("error getting dbus session bus: %v", err)
}
obj := conn.Object("org.ganesha.nfsd", "/org/ganesha/nfsd/ExportMgr")
call := obj.Call("org.ganesha.nfsd.exportmgr.AddExport", 0, e.config, fmt.Sprintf("export(path = %s)", path))
if call.Err != nil {
return fmt.Errorf("error calling org.ganesha.nfsd.exportmgr.AddExport: %v", call.Err)
}
return nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | nfs/pkg/volume/export.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/nfs/pkg/volume/export.go#L193-L202 | go | train | // Export exports all directories listed in /etc/exports | func (e *kernelExporter) Export(_ string) error | // Export exports all directories listed in /etc/exports
func (e *kernelExporter) Export(_ string) error | {
// Execute exportfs
cmd := exec.Command("exportfs", "-r")
out, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("exportfs -r failed with error: %v, output: %s", err, out)
}
return nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | nfs/pkg/volume/export.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/nfs/pkg/volume/export.go#L220-L226 | go | train | // CreateBlock creates the text block to add to the /etc/exports file. | func (e *kernelExportBlockCreator) CreateExportBlock(exportID, path string, rootSquash bool, exportSubnet string) string | // CreateBlock creates the text block to add to the /etc/exports file.
func (e *kernelExportBlockCreator) CreateExportBlock(exportID, path string, rootSquash bool, exportSubnet string) string | {
squash := "no_root_squash"
if rootSquash {
squash = "root_squash"
}
return "\n" + path + " " + exportSubnet + "(rw,insecure," + squash + ",fsid=" + exportID + ")\n"
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/controller/reconciler/reconciler.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/controller/reconciler/reconciler.go#L52-L68 | go | train | // NewReconciler is the constructor of Reconciler | func NewReconciler(
loopPeriod time.Duration,
syncDuration time.Duration,
disableReconciliationSync bool,
desiredStateOfWorld cache.DesiredStateOfWorld,
actualStateOfWorld cache.ActualStateOfWorld,
snapshotter snapshotter.VolumeSnapshotter) Reconciler | // NewReconciler is the constructor of Reconciler
func NewReconciler(
loopPeriod time.Duration,
syncDuration time.Duration,
disableReconciliationSync bool,
desiredStateOfWorld cache.DesiredStateOfWorld,
actualStateOfWorld cache.ActualStateOfWorld,
snapshotter snapshotter.VolumeSnapshotter) Reconciler | {
return &reconciler{
loopPeriod: loopPeriod,
syncDuration: syncDuration,
disableReconciliationSync: disableReconciliationSync,
desiredStateOfWorld: desiredStateOfWorld,
actualStateOfWorld: actualStateOfWorld,
snapshotter: snapshotter,
timeOfLastSync: time.Now(),
}
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/aws/retry_handler.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/aws/retry_handler.go#L50-L61 | go | train | // BeforeSign is added to the Sign chain; called before each request | func (c *CrossRequestRetryDelay) BeforeSign(r *request.Request) | // BeforeSign is added to the Sign chain; called before each request
func (c *CrossRequestRetryDelay) BeforeSign(r *request.Request) | {
now := time.Now()
delay := c.backoff.ComputeDelayForRequest(now)
if delay > 0 {
glog.Warningf("Inserting delay before AWS request (%s) to avoid RequestLimitExceeded: %s",
describeRequest(r), delay.String())
r.Config.SleepDelay(delay)
// Avoid clock skew problems
r.Time = now
}
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/aws/retry_handler.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/aws/retry_handler.go#L64-L73 | go | train | // Return a user-friendly string describing the request, for use in log messages | func describeRequest(r *request.Request) string | // Return a user-friendly string describing the request, for use in log messages
func describeRequest(r *request.Request) string | {
service := r.ClientInfo.ServiceName
name := "?"
if r.Operation != nil {
name = r.Operation.Name
}
return service + "::" + name
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/cloudprovider/providers/aws/retry_handler.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/cloudprovider/providers/aws/retry_handler.go#L76-L89 | go | train | // AfterRetry is added to the AfterRetry chain; called after any error | func (c *CrossRequestRetryDelay) AfterRetry(r *request.Request) | // AfterRetry is added to the AfterRetry chain; called after any error
func (c *CrossRequestRetryDelay) AfterRetry(r *request.Request) | {
if r.Error == nil {
return
}
awsError, ok := r.Error.(awserr.Error)
if !ok {
return
}
if awsError.Code() == "RequestLimitExceeded" {
c.backoff.ReportError()
glog.Warningf("Got RequestLimitExceeded error on AWS request (%s)",
describeRequest(r))
}
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/volume/cinder/processor.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/volume/cinder/processor.go#L43-L45 | go | train | // Init inits volume plugin | func (c *cinderPlugin) Init(cloud cloudprovider.Interface) | // Init inits volume plugin
func (c *cinderPlugin) Init(cloud cloudprovider.Interface) | {
c.cloud = cloud.(*openstack.OpenStack)
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/volume/cinder/processor.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/volume/cinder/processor.go#L58-L69 | go | train | // VolumeDelete deletes the specified volume passed on pv | func (c *cinderPlugin) VolumeDelete(pv *v1.PersistentVolume) error | // VolumeDelete deletes the specified volume passed on pv
func (c *cinderPlugin) VolumeDelete(pv *v1.PersistentVolume) error | {
if pv == nil || pv.Spec.Cinder == nil {
return fmt.Errorf("invalid Cinder PV: %v", pv)
}
volumeID := pv.Spec.Cinder.VolumeID
err := c.cloud.DeleteVolume(volumeID)
if err != nil {
return err
}
return nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/volume/cinder/processor.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/volume/cinder/processor.go#L72-L95 | go | train | // SnapshotCreate creates a VolumeSnapshot from a PersistentVolumeSpec | func (c *cinderPlugin) SnapshotCreate(
snapshot *crdv1.VolumeSnapshot,
pv *v1.PersistentVolume,
tags *map[string]string,
) (*crdv1.VolumeSnapshotDataSource, *[]crdv1.VolumeSnapshotCondition, error) | // SnapshotCreate creates a VolumeSnapshot from a PersistentVolumeSpec
func (c *cinderPlugin) SnapshotCreate(
snapshot *crdv1.VolumeSnapshot,
pv *v1.PersistentVolume,
tags *map[string]string,
) (*crdv1.VolumeSnapshotDataSource, *[]crdv1.VolumeSnapshotCondition, error) | {
spec := &pv.Spec
if spec == nil || spec.Cinder == nil {
return nil, nil, fmt.Errorf("invalid PV spec %v", spec)
}
volumeID := spec.Cinder.VolumeID
snapshotName := string(pv.Name) + fmt.Sprintf("%d", time.Now().UnixNano())
snapshotDescription := "kubernetes snapshot"
glog.Infof("issuing Cinder.CreateSnapshot - SourceVol: %s, Name: %s, tags: %#v", volumeID, snapshotName, *tags)
snapID, status, err := c.cloud.CreateSnapshot(volumeID, snapshotName, snapshotDescription, *tags)
if err != nil {
return nil, nil, err
}
return &crdv1.VolumeSnapshotDataSource{
CinderSnapshot: &crdv1.CinderVolumeSnapshotSource{
SnapshotID: snapID,
},
}, c.convertSnapshotStatus(status), nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/volume/cinder/processor.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/volume/cinder/processor.go#L99-L109 | go | train | // SnapshotDelete deletes a VolumeSnapshot
// PersistentVolume is provided for volume types, if any, that need PV Spec to delete snapshot | func (c *cinderPlugin) SnapshotDelete(src *crdv1.VolumeSnapshotDataSource, _ *v1.PersistentVolume) error | // SnapshotDelete deletes a VolumeSnapshot
// PersistentVolume is provided for volume types, if any, that need PV Spec to delete snapshot
func (c *cinderPlugin) SnapshotDelete(src *crdv1.VolumeSnapshotDataSource, _ *v1.PersistentVolume) error | {
if src == nil || src.CinderSnapshot == nil {
return fmt.Errorf("invalid VolumeSnapshotDataSource: %v", src)
}
snapshotID := src.CinderSnapshot.SnapshotID
err := c.cloud.DeleteSnapshot(snapshotID)
if err != nil {
return err
}
return nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/volume/cinder/processor.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/volume/cinder/processor.go#L112-L155 | go | train | // SnapshotRestore creates a new Volume using the data on the specified Snapshot | func (c *cinderPlugin) SnapshotRestore(snapshotData *crdv1.VolumeSnapshotData, pvc *v1.PersistentVolumeClaim, pvName string, parameters map[string]string) (*v1.PersistentVolumeSource, map[string]string, error) | // SnapshotRestore creates a new Volume using the data on the specified Snapshot
func (c *cinderPlugin) SnapshotRestore(snapshotData *crdv1.VolumeSnapshotData, pvc *v1.PersistentVolumeClaim, pvName string, parameters map[string]string) (*v1.PersistentVolumeSource, map[string]string, error) | {
var tags = make(map[string]string)
var vType string
var zone string
if snapshotData == nil || snapshotData.Spec.CinderSnapshot == nil {
return nil, nil, fmt.Errorf("failed to retrieve Snapshot spec")
}
if pvc == nil {
return nil, nil, fmt.Errorf("no pvc specified")
}
snapID := snapshotData.Spec.CinderSnapshot.SnapshotID
volName := pvName
capacity := pvc.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)]
requestedSz := capacity.Value()
szGB := k8sVol.RoundUpSize(requestedSz, 1024*1024*1024)
for k, v := range parameters {
switch strings.ToLower(k) {
case "type":
vType = v
case "zone":
zone = v
default:
return nil, nil, fmt.Errorf("invalid option %q for volume plugin %s", k, GetPluginName())
}
}
// FIXME(j-griffith): Should probably use int64 in gophercloud?
volumeID, _, err := c.cloud.CreateVolume(volName, int(szGB), vType, zone, snapID, &tags)
if err != nil {
glog.Errorf("error create volume from snapshot: %v", err)
return nil, nil, err
}
glog.V(2).Infof("Successfully created Cinder Volume from Snapshot, Volume: %s", volumeID)
pv := &v1.PersistentVolumeSource{
Cinder: &v1.CinderPersistentVolumeSource{
VolumeID: volumeID,
FSType: "ext4",
ReadOnly: false,
},
}
return pv, nil, nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/volume/cinder/processor.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/volume/cinder/processor.go#L158-L169 | go | train | // DescribeSnapshot retrieves info for the specified Snapshot | func (c *cinderPlugin) DescribeSnapshot(snapshotData *crdv1.VolumeSnapshotData) (*[]crdv1.VolumeSnapshotCondition, bool, error) | // DescribeSnapshot retrieves info for the specified Snapshot
func (c *cinderPlugin) DescribeSnapshot(snapshotData *crdv1.VolumeSnapshotData) (*[]crdv1.VolumeSnapshotCondition, bool, error) | {
if snapshotData == nil || snapshotData.Spec.CinderSnapshot == nil {
return nil, false, fmt.Errorf("invalid VolumeSnapshotDataSource: %v", snapshotData)
}
snapshotID := snapshotData.Spec.CinderSnapshot.SnapshotID
status, isComplete, err := c.cloud.DescribeSnapshot(snapshotID)
glog.Infof("DescribeSnapshot: Snapshot %s, Status %s, isComplete: %v", snapshotID, status, isComplete)
if err != nil {
return c.convertSnapshotStatus(status), false, err
}
return c.convertSnapshotStatus(status), isComplete, nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/volume/cinder/processor.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/volume/cinder/processor.go#L172-L204 | go | train | // convertSnapshotStatus converts Cinder snapshot status to crdv1.VolumeSnapshotCondition | func (c *cinderPlugin) convertSnapshotStatus(status string) *[]crdv1.VolumeSnapshotCondition | // convertSnapshotStatus converts Cinder snapshot status to crdv1.VolumeSnapshotCondition
func (c *cinderPlugin) convertSnapshotStatus(status string) *[]crdv1.VolumeSnapshotCondition | {
var snapConditions []crdv1.VolumeSnapshotCondition
if status == "available" {
snapConditions = []crdv1.VolumeSnapshotCondition{
{
Type: crdv1.VolumeSnapshotConditionReady,
Status: v1.ConditionTrue,
Message: "Snapshot created successfully and it is ready",
LastTransitionTime: metav1.Now(),
},
}
} else if status == "creating" {
snapConditions = []crdv1.VolumeSnapshotCondition{
{
Type: crdv1.VolumeSnapshotConditionPending,
Status: v1.ConditionUnknown,
Message: "Snapshot is being created",
LastTransitionTime: metav1.Now(),
},
}
} else {
snapConditions = []crdv1.VolumeSnapshotCondition{
{
Type: crdv1.VolumeSnapshotConditionError,
Status: v1.ConditionTrue,
Message: "Snapshot creation failed",
LastTransitionTime: metav1.Now(),
},
}
}
return &snapConditions
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/volume/cinder/processor.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/volume/cinder/processor.go#L207-L225 | go | train | // FindSnapshot finds a VolumeSnapshot by matching metadata | func (c *cinderPlugin) FindSnapshot(tags *map[string]string) (*crdv1.VolumeSnapshotDataSource, *[]crdv1.VolumeSnapshotCondition, error) | // FindSnapshot finds a VolumeSnapshot by matching metadata
func (c *cinderPlugin) FindSnapshot(tags *map[string]string) (*crdv1.VolumeSnapshotDataSource, *[]crdv1.VolumeSnapshotCondition, error) | {
glog.Infof("Cinder.FindSnapshot by tags: %#v", *tags)
snapIDs, statuses, err := c.cloud.FindSnapshot(*tags)
if err != nil {
glog.Infof("Cinder.FindSnapshot by tags: %#v. Error: %v", *tags, err)
//return nil, err
}
if len(snapIDs) > 0 && len(statuses) > 0 {
glog.Infof("Found snapshot %s by tags: %#v", snapIDs[0], *tags)
return &crdv1.VolumeSnapshotDataSource{
CinderSnapshot: &crdv1.CinderVolumeSnapshotSource{
SnapshotID: snapIDs[0],
},
}, c.convertSnapshotStatus(statuses[0]), nil
}
return nil, nil, fmt.Errorf("Snapshot not found")
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | repo-infra/kazel/diff.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/repo-infra/kazel/diff.go#L27-L60 | go | train | // Diff prints the unified diff of the two provided byte slices
// using the unix diff command. | func Diff(left, right []byte) error | // Diff prints the unified diff of the two provided byte slices
// using the unix diff command.
func Diff(left, right []byte) error | {
lf, err := ioutil.TempFile("/tmp", "actual-file-")
if err != nil {
return err
}
defer lf.Close()
defer os.Remove(lf.Name())
rf, err := ioutil.TempFile("/tmp", "expected-file-")
if err != nil {
return err
}
defer rf.Close()
defer os.Remove(rf.Name())
_, err = lf.Write(left)
if err != nil {
return err
}
lf.Close()
_, err = rf.Write(right)
if err != nil {
return err
}
rf.Close()
cmd := exec.Command("/usr/bin/diff", "-u", lf.Name(), rf.Name())
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Run()
return nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | local-volume/provisioner/pkg/controller/controller.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/local-volume/provisioner/pkg/controller/controller.go#L44-L114 | go | train | // StartLocalController starts the sync loop for the local PV discovery and deleter | func StartLocalController(client *kubernetes.Clientset, ptable deleter.ProcTable, config *common.UserConfig) | // StartLocalController starts the sync loop for the local PV discovery and deleter
func StartLocalController(client *kubernetes.Clientset, ptable deleter.ProcTable, config *common.UserConfig) | {
glog.Info("Initializing volume cache\n")
var provisionerName string
if config.UseNodeNameOnly {
provisionerName = fmt.Sprintf("local-volume-provisioner-%v", config.Node.Name)
} else {
provisionerName = fmt.Sprintf("local-volume-provisioner-%v-%v", config.Node.Name, config.Node.UID)
}
broadcaster := record.NewBroadcaster()
broadcaster.StartRecordingToSink(&v1core.EventSinkImpl{Interface: v1core.New(client.CoreV1().RESTClient()).Events("")})
recorder := broadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: provisionerName})
// We choose a random resync period between MinResyncPeriod and 2 *
// MinResyncPeriod, so that local provisioners deployed on multiple nodes
// at same time don't list the apiserver simultaneously.
resyncPeriod := time.Duration(config.MinResyncPeriod.Seconds()*(1+rand.Float64())) * time.Second
runtimeConfig := &common.RuntimeConfig{
UserConfig: config,
Cache: cache.NewVolumeCache(),
VolUtil: util.NewVolumeUtil(),
APIUtil: util.NewAPIUtil(client),
Client: client,
Name: provisionerName,
Recorder: recorder,
Mounter: mount.New("" /* default mount path */),
InformerFactory: informers.NewSharedInformerFactory(client, resyncPeriod),
}
populator.NewPopulator(runtimeConfig)
var jobController deleter.JobController
var err error
if runtimeConfig.UseJobForCleaning {
labels := map[string]string{common.NodeNameLabel: config.Node.Name}
jobController, err = deleter.NewJobController(labels, runtimeConfig)
if err != nil {
glog.Fatalf("Error initializing jobController: %v", err)
}
glog.Infof("Enabling Jobs based cleaning.")
}
cleanupTracker := &deleter.CleanupStatusTracker{ProcTable: ptable, JobController: jobController}
discoverer, err := discovery.NewDiscoverer(runtimeConfig, cleanupTracker)
if err != nil {
glog.Fatalf("Error initializing discoverer: %v", err)
}
deleter := deleter.NewDeleter(runtimeConfig, cleanupTracker)
// Start informers after all event listeners are registered.
runtimeConfig.InformerFactory.Start(wait.NeverStop)
// Wait for all started informers' cache were synced.
for v, synced := range runtimeConfig.InformerFactory.WaitForCacheSync(wait.NeverStop) {
if !synced {
glog.Fatalf("Error syncing informer for %v", v)
}
}
// Run controller logic.
if jobController != nil {
go jobController.Run(wait.NeverStop)
}
glog.Info("Controller started\n")
for {
deleter.DeletePVs()
discoverer.DiscoverLocalVolumes()
time.Sleep(10 * time.Second)
}
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | flex/pkg/volume/provision.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/flex/pkg/volume/provision.go#L41-L43 | go | train | // NewFlexProvisioner creates a new flex provisioner | func NewFlexProvisioner(client kubernetes.Interface, execCommand string, flexDriver string) controller.Provisioner | // NewFlexProvisioner creates a new flex provisioner
func NewFlexProvisioner(client kubernetes.Interface, execCommand string, flexDriver string) controller.Provisioner | {
return newFlexProvisionerInternal(client, execCommand, flexDriver)
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | flex/pkg/volume/provision.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/flex/pkg/volume/provision.go#L71-L108 | go | train | // Provision creates a volume i.e. the storage asset and returns a PV object for
// the volume. | func (p *flexProvisioner) Provision(options controller.VolumeOptions) (*v1.PersistentVolume, error) | // Provision creates a volume i.e. the storage asset and returns a PV object for
// the volume.
func (p *flexProvisioner) Provision(options controller.VolumeOptions) (*v1.PersistentVolume, error) | {
err := p.createVolume(options)
if err != nil {
return nil, err
}
annotations := make(map[string]string)
annotations[annCreatedBy] = createdBy
annotations[annProvisionerID] = string(p.identity)
/*
The flex script for flexDriver=<vendor>/<driver> is in
/usr/libexec/kubernetes/kubelet-plugins/volume/exec/<vendor>~<driver>/<driver>
*/
pv := &v1.PersistentVolume{
ObjectMeta: metav1.ObjectMeta{
Name: options.PVName,
Labels: map[string]string{},
Annotations: annotations,
},
Spec: v1.PersistentVolumeSpec{
PersistentVolumeReclaimPolicy: options.PersistentVolumeReclaimPolicy,
AccessModes: options.PVC.Spec.AccessModes,
Capacity: v1.ResourceList{
v1.ResourceName(v1.ResourceStorage): options.PVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)],
},
PersistentVolumeSource: v1.PersistentVolumeSource{
FlexVolume: &v1.FlexPersistentVolumeSource{
Driver: p.flexDriver,
Options: map[string]string{},
ReadOnly: false,
},
},
},
}
return pv, nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/volume/hostpath/processor.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/volume/hostpath/processor.go#L142-L147 | go | train | // FindSnapshot finds a VolumeSnapshot by matching metadata | func (h *hostPathPlugin) FindSnapshot(tags *map[string]string) (*crdv1.VolumeSnapshotDataSource, *[]crdv1.VolumeSnapshotCondition, error) | // FindSnapshot finds a VolumeSnapshot by matching metadata
func (h *hostPathPlugin) FindSnapshot(tags *map[string]string) (*crdv1.VolumeSnapshotDataSource, *[]crdv1.VolumeSnapshotCondition, error) | {
glog.Infof("FindSnapshot by tags: %#v", *tags)
// TODO: Implement FindSnapshot
return nil, nil, fmt.Errorf("Snapshot not found")
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/controller/cache/desired_state_of_world.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/controller/cache/desired_state_of_world.go#L59-L64 | go | train | // NewDesiredStateOfWorld returns a new instance of DesiredStateOfWorld. | func NewDesiredStateOfWorld() DesiredStateOfWorld | // NewDesiredStateOfWorld returns a new instance of DesiredStateOfWorld.
func NewDesiredStateOfWorld() DesiredStateOfWorld | {
m := make(map[string]*crdv1.VolumeSnapshot)
return &desiredStateOfWorld{
snapshots: m,
}
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/controller/cache/desired_state_of_world.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/controller/cache/desired_state_of_world.go#L67-L79 | go | train | // Adds a snapshot to the list of snapshots to be created | func (dsw *desiredStateOfWorld) AddSnapshot(snapshot *crdv1.VolumeSnapshot) error | // Adds a snapshot to the list of snapshots to be created
func (dsw *desiredStateOfWorld) AddSnapshot(snapshot *crdv1.VolumeSnapshot) error | {
if snapshot == nil {
return fmt.Errorf("nil snapshot spec")
}
dsw.Lock()
defer dsw.Unlock()
snapshotName := MakeSnapshotName(snapshot)
glog.Infof("Adding new snapshot to desired state of world: %s", snapshotName)
dsw.snapshots[snapshotName] = snapshot
return nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/controller/cache/desired_state_of_world.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/controller/cache/desired_state_of_world.go#L82-L90 | go | train | // Removes the snapshot from the list of existing snapshots | func (dsw *desiredStateOfWorld) DeleteSnapshot(snapshotName string) error | // Removes the snapshot from the list of existing snapshots
func (dsw *desiredStateOfWorld) DeleteSnapshot(snapshotName string) error | {
dsw.Lock()
defer dsw.Unlock()
glog.Infof("Deleting snapshot from desired state of world: %s", snapshotName)
delete(dsw.snapshots, snapshotName)
return nil
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/controller/cache/desired_state_of_world.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/controller/cache/desired_state_of_world.go#L93-L104 | go | train | // Returns a copy of the list of the snapshots known to the actual state of world. | func (dsw *desiredStateOfWorld) GetSnapshots() map[string]*crdv1.VolumeSnapshot | // Returns a copy of the list of the snapshots known to the actual state of world.
func (dsw *desiredStateOfWorld) GetSnapshots() map[string]*crdv1.VolumeSnapshot | {
dsw.RLock()
defer dsw.RUnlock()
snapshots := make(map[string]*crdv1.VolumeSnapshot)
for snapName, snapshot := range dsw.snapshots {
snapshots[snapName] = snapshot
}
return snapshots
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | snapshot/pkg/controller/cache/desired_state_of_world.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/snapshot/pkg/controller/cache/desired_state_of_world.go#L107-L113 | go | train | // Checks for the existence of the snapshot | func (dsw *desiredStateOfWorld) SnapshotExists(snapshotName string) bool | // Checks for the existence of the snapshot
func (dsw *desiredStateOfWorld) SnapshotExists(snapshotName string) bool | {
dsw.RLock()
defer dsw.RUnlock()
_, snapshotExists := dsw.snapshots[snapshotName]
return snapshotExists
} |
kubernetes-incubator/external-storage | fbfedbf60da4e5ee25a3151bfe8504f3e3281319 | nfs/pkg/volume/provision.go | https://github.com/kubernetes-incubator/external-storage/blob/fbfedbf60da4e5ee25a3151bfe8504f3e3281319/nfs/pkg/volume/provision.go#L81-L99 | go | train | // NewNFSProvisioner creates a Provisioner that provisions NFS PVs backed by
// the given directory. | func NewNFSProvisioner(exportDir string, client kubernetes.Interface, outOfCluster bool, useGanesha bool, ganeshaConfig string, enableXfsQuota bool, serverHostname string, maxExports int, exportSubnet string) controller.Provisioner | // NewNFSProvisioner creates a Provisioner that provisions NFS PVs backed by
// the given directory.
func NewNFSProvisioner(exportDir string, client kubernetes.Interface, outOfCluster bool, useGanesha bool, ganeshaConfig string, enableXfsQuota bool, serverHostname string, maxExports int, exportSubnet string) controller.Provisioner | {
var exp exporter
if useGanesha {
exp = newGaneshaExporter(ganeshaConfig)
} else {
exp = newKernelExporter()
}
var quotaer quotaer
var err error
if enableXfsQuota {
quotaer, err = newXfsQuotaer(exportDir)
if err != nil {
glog.Fatalf("Error creating xfs quotaer! %v", err)
}
} else {
quotaer = newDummyQuotaer()
}
return newNFSProvisionerInternal(exportDir, client, outOfCluster, exp, quotaer, serverHostname, maxExports, exportSubnet)
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.