Copy dependencies into vendor dir, using dep

This commit is contained in:
Bryan Boreham committed 2018-04-27 14:34:48 +01:00
1 parent 549ccff5eb
commit b534ea60f5
2857 files changed
+945317

No files matched your search

+191
View File
@@ -0,0 +1,191 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
Copyright 2014-2015 Weaveworks Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+172
View File
@@ -0,0 +1,172 @@
package odp
import (
"fmt"
"syscall"
)
// Datapaths are identified by the ifindex of their netdev.
type DatapathID int32
type datapathInfo struct {
ifindex DatapathID
name string
}
func (dpif *Dpif) parseDatapathInfo(msg *NlMsgParser) (res datapathInfo, err error) {
_, ovshdr, err := dpif.checkNlMsgHeaders(msg, DATAPATH, OVS_DP_CMD_NEW)
if err != nil {
return
}
res.ifindex = ovshdr.datapathID()
attrs, err := msg.TakeAttrs()
if err != nil {
return
}
res.name, err = attrs.GetString(OVS_DP_ATTR_NAME)
return
}
type DatapathHandle struct {
dpif *Dpif
ifindex DatapathID
}
func (dp DatapathHandle) ID() DatapathID {
return dp.ifindex
}
func (dp DatapathHandle) Reopen() (DatapathHandle, error) {
dpif, err := dp.dpif.Reopen()
return DatapathHandle{dpif: dpif, ifindex: dp.ifindex}, err
}
func (dpif *Dpif) CreateDatapath(name string) (DatapathHandle, error) {
var features uint32 = OVS_DP_F_UNALIGNED | OVS_DP_F_VPORT_PIDS
req := NewNlMsgBuilder(RequestFlags, dpif.families[DATAPATH].id)
req.PutGenlMsghdr(OVS_DP_CMD_NEW, OVS_DATAPATH_VERSION)
req.putOvsHeader(0)
req.PutStringAttr(OVS_DP_ATTR_NAME, name)
req.PutUint32Attr(OVS_DP_ATTR_UPCALL_PID, 0)
req.PutUint32Attr(OVS_DP_ATTR_USER_FEATURES, features)
resp, err := dpif.sock.Request(req)
if err != nil {
return DatapathHandle{}, err
}
dpi, err := dpif.parseDatapathInfo(resp)
if err != nil {
return DatapathHandle{}, err
}
return DatapathHandle{dpif: dpif, ifindex: dpi.ifindex}, nil
}
func IsDatapathNameAlreadyExistsError(err error) bool {
return err == NetlinkError(syscall.EEXIST)
}
func (dpif *Dpif) LookupDatapath(name string) (DatapathHandle, error) {
req := NewNlMsgBuilder(RequestFlags, dpif.families[DATAPATH].id)
req.PutGenlMsghdr(OVS_DP_CMD_GET, OVS_DATAPATH_VERSION)
req.putOvsHeader(0)
req.PutStringAttr(OVS_DP_ATTR_NAME, name)
resp, err := dpif.sock.Request(req)
if err != nil {
return DatapathHandle{}, err
}
dpi, err := dpif.parseDatapathInfo(resp)
if err != nil {
return DatapathHandle{}, err
}
return DatapathHandle{dpif: dpif, ifindex: dpi.ifindex}, nil
}
type Datapath struct {
Handle DatapathHandle
Name string
}
func (dpif *Dpif) LookupDatapathByID(ifindex DatapathID) (Datapath, error) {
req := NewNlMsgBuilder(RequestFlags, dpif.families[DATAPATH].id)
req.PutGenlMsghdr(OVS_DP_CMD_GET, OVS_DATAPATH_VERSION)
req.putOvsHeader(ifindex)
resp, err := dpif.sock.Request(req)
if err != nil {
return Datapath{}, err
}
dpi, err := dpif.parseDatapathInfo(resp)
if err != nil {
return Datapath{}, err
}
return Datapath{
Handle: DatapathHandle{dpif: dpif, ifindex: ifindex},
Name: dpi.name,
}, nil
}
func IsNoSuchDatapathError(err error) bool {
return err == NetlinkError(syscall.ENODEV)
}
func (dpif *Dpif) EnumerateDatapaths() (map[string]DatapathHandle, error) {
res := make(map[string]DatapathHandle)
req := NewNlMsgBuilder(DumpFlags, dpif.families[DATAPATH].id)
req.PutGenlMsghdr(OVS_DP_CMD_GET, OVS_DATAPATH_VERSION)
req.putOvsHeader(0)
consumer := func(resp *NlMsgParser) error {
dpi, err := dpif.parseDatapathInfo(resp)
if err != nil {
return err
}
res[dpi.name] = DatapathHandle{dpif: dpif, ifindex: dpi.ifindex}
return nil
}
err := dpif.sock.RequestMulti(req, consumer)
if err != nil {
return nil, err
}
return res, nil
}
func (dp DatapathHandle) Delete() error {
req := NewNlMsgBuilder(RequestFlags, dp.dpif.families[DATAPATH].id)
req.PutGenlMsghdr(OVS_DP_CMD_DEL, OVS_DATAPATH_VERSION)
req.putOvsHeader(dp.ifindex)
_, err := dp.dpif.sock.Request(req)
if err != nil {
return err
}
dp.dpif = nil
dp.ifindex = 0
return nil
}
func (dp DatapathHandle) checkNlMsgHeaders(msg *NlMsgParser, family int, cmd int) error {
_, ovshdr, err := dp.dpif.checkNlMsgHeaders(msg, family, cmd)
if err != nil {
return err
}
if ovshdr.datapathID() != dp.ifindex {
return fmt.Errorf("wrong datapath ifindex received (got %d, expected %d)", ovshdr.datapathID(), dp.ifindex)
}
return nil
}
+181
View File
@@ -0,0 +1,181 @@
package odp
import (
"fmt"
"syscall"
"unsafe"
)
const (
DATAPATH = iota
VPORT = iota
FLOW = iota
PACKET = iota
FAMILY_COUNT = iota
)
var familyNames = [FAMILY_COUNT]string{
"ovs_datapath",
"ovs_vport",
"ovs_flow",
"ovs_packet",
}
type Dpif struct {
sock *NetlinkSocket
families [FAMILY_COUNT]GenlFamily
}
type familyUnavailableError struct {
family string
}
func (fue familyUnavailableError) Error() string {
return fmt.Sprintf("Generic netlink family '%s' unavailable; the Open vSwitch kernel module is probably not loaded, try 'modprobe openvswitch'", fue.family)
}
func IsKernelLacksODPError(err error) bool {
_, ok := err.(familyUnavailableError)
return ok
}
func lookupFamily(sock *NetlinkSocket, name string) (GenlFamily, error) {
family, err := sock.LookupGenlFamily(name)
if err == nil {
return family, nil
}
if err == NetlinkError(syscall.ENOENT) {
loadOpenvswitchModule()
// The module might be loaded now, so try again
family, err = sock.LookupGenlFamily(name)
if err == nil {
return family, nil
}
if err == NetlinkError(syscall.ENOENT) {
err = familyUnavailableError{name}
}
}
return GenlFamily{}, err
}
var triedLoadOpenvswitchModule bool
// This tries to provoke the kernel into loading the openvswitch
// module. Yes, netdev ioctls can be used to load arbitrary modules,
// if you have CAP_SYS_MODULE.
func loadOpenvswitchModule() {
if triedLoadOpenvswitchModule {
return
}
// netdev ioctls don't seem to work on netlink sockets, so we
// need a new socket for this purpose.
s, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_DGRAM, 0)
if err != nil {
triedLoadOpenvswitchModule = true
return
}
defer syscall.Close(s)
var req ifreqIfindex
copy(req.name[:], []byte("openvswitch"))
syscall.Syscall(syscall.SYS_IOCTL, uintptr(s),
syscall.SIOCGIFINDEX, uintptr(unsafe.Pointer(&req)))
triedLoadOpenvswitchModule = true
}
func NewDpif() (*Dpif, error) {
sock, err := OpenNetlinkSocket(syscall.NETLINK_GENERIC)
if err != nil {
return nil, err
}
dpif := &Dpif{sock: sock}
for i := 0; i < FAMILY_COUNT; i++ {
dpif.families[i], err = lookupFamily(sock, familyNames[i])
if err != nil {
sock.Close()
return nil, err
}
}
return dpif, nil
}
// Open a dpif with a new socket, but reuing the family info
func (dpif *Dpif) Reopen() (*Dpif, error) {
sock, err := OpenNetlinkSocket(syscall.NETLINK_GENERIC)
if err != nil {
return nil, err
}
return &Dpif{sock: sock, families: dpif.families}, nil
}
func (dpif *Dpif) getMCGroup(family int, name string) (uint32, error) {
mcGroup, ok := dpif.families[family].mcGroups[name]
if !ok {
return 0, fmt.Errorf("No genl MC group %s in family %s", name, familyNames[family])
}
return mcGroup, nil
}
func (dpif *Dpif) Close() error {
return dpif.sock.Close()
}
func (nlmsg *NlMsgBuilder) putOvsHeader(ifindex DatapathID) {
pos := nlmsg.AlignGrow(syscall.NLMSG_ALIGNTO, SizeofOvsHeader)
h := ovsHeaderAt(nlmsg.buf, pos)
h.DpIfIndex = int32(ifindex)
}
func (nlmsg *NlMsgParser) takeOvsHeader() (*OvsHeader, error) {
pos, err := nlmsg.AlignAdvance(syscall.NLMSG_ALIGNTO, SizeofOvsHeader)
if err != nil {
return nil, err
}
return ovsHeaderAt(nlmsg.data, pos), nil
}
func (ovshdr OvsHeader) datapathID() DatapathID {
return DatapathID(ovshdr.DpIfIndex)
}
func (dpif *Dpif) checkNlMsgHeaders(msg *NlMsgParser, family int, cmd int) (*GenlMsghdr, *OvsHeader, error) {
if _, err := msg.ExpectNlMsghdr(dpif.families[family].id); err != nil {
return nil, nil, err
}
genlhdr, err := msg.CheckGenlMsghdr(cmd)
if err != nil {
return nil, nil, err
}
ovshdr, err := msg.takeOvsHeader()
if err != nil {
return nil, nil, err
}
return genlhdr, ovshdr, nil
}
type Cancelable interface {
Cancel() error
}
type cancelableDpif struct {
*Dpif
}
func (dpif cancelableDpif) Cancel() error {
return dpif.Close()
}
+1398
View File
File diff suppressed because it is too large. Load diff
+101
View File
@@ -0,0 +1,101 @@
package odp
import (
"fmt"
"syscall"
)
type GenlFamily struct {
id uint16
mcGroups map[string]uint32
}
func (nlmsg *NlMsgBuilder) PutGenlMsghdr(cmd uint8, version uint8) *GenlMsghdr {
pos := nlmsg.AlignGrow(syscall.NLMSG_ALIGNTO, SizeofGenlMsghdr)
res := genlMsghdrAt(nlmsg.buf, pos)
res.Cmd = cmd
res.Version = version
return res
}
func (nlmsg *NlMsgParser) CheckGenlMsghdr(cmd int) (*GenlMsghdr, error) {
pos, err := nlmsg.AlignAdvance(syscall.NLMSG_ALIGNTO, SizeofGenlMsghdr)
if err != nil {
return nil, err
}
gh := genlMsghdrAt(nlmsg.data, pos)
if cmd >= 0 && gh.Cmd != uint8(cmd) {
return nil, fmt.Errorf("generic netlink response has wrong cmd (got %d, expected %d)", gh.Cmd, cmd)
}
// Deliberately ignore the version field in the genl header.
// It's unclear exactly what its meaning is, and how we should
// handle it. E.g., if the version is higher than we expect,
// should we still try to handle the message? It's unclear,
// but the fact that ODP bumped the kernel
// OVS_DATAPATH_VERSION from 1 to 2 while expecting existing
// userspace to keep working suggests that we should be
// libreral in what we accept.
return gh, nil
}
func (s *NetlinkSocket) LookupGenlFamily(name string) (family GenlFamily, err error) {
req := NewNlMsgBuilder(RequestFlags, GENL_ID_CTRL)
req.PutGenlMsghdr(CTRL_CMD_GETFAMILY, 0)
req.PutStringAttr(CTRL_ATTR_FAMILY_NAME, name)
resp, err := s.Request(req)
if err != nil {
return
}
_, err = resp.ExpectNlMsghdr(GENL_ID_CTRL)
if err != nil {
return
}
_, err = resp.CheckGenlMsghdr(CTRL_CMD_NEWFAMILY)
if err != nil {
return
}
attrs, err := resp.TakeAttrs()
if err != nil {
return
}
family.id, err = attrs.GetUint16(CTRL_ATTR_FAMILY_ID)
if err != nil {
return
}
mcGroupAttrs, err := attrs.GetNestedAttrs(CTRL_ATTR_MCAST_GROUPS, true)
if err != nil || mcGroupAttrs == nil {
return
}
family.mcGroups = make(map[string]uint32)
for _, data := range mcGroupAttrs {
groupAttrs, err := ParseNestedAttrs(data)
if err != nil {
return family, err
}
id, err := groupAttrs.GetUint32(CTRL_ATTR_MCAST_GRP_ID)
if err != nil {
return family, err
}
name, err := groupAttrs.GetString(CTRL_ATTR_MCAST_GRP_NAME)
if err != nil {
return family, err
}
family.mcGroups[name] = id
}
return
}
+698
View File
@@ -0,0 +1,698 @@
package odp
import (
"fmt"
"reflect"
"sync/atomic"
"syscall"
)
func align(n int, a int) int {
return (n + a - 1) & -a
}
type NetlinkSocket struct {
fd int
addr *syscall.SockaddrNetlink
buf []byte
}
func OpenNetlinkSocket(protocol int) (*NetlinkSocket, error) {
fd, err := syscall.Socket(syscall.AF_NETLINK, syscall.SOCK_RAW, protocol)
if err != nil {
return nil, err
}
success := false
defer func() {
if !success {
syscall.Close(fd)
}
}()
// It's fairly easy to provoke ENOBUFS from a netlink socket
// receiving miss upcalls when every packet misses. The
// default socket buffer size is relatively small at 200KB,
// and the default of /proc/sys/net/core/rmem_max means we
// can't easily increase it.
if err := syscall.SetsockoptInt(fd, SOL_NETLINK, syscall.NETLINK_NO_ENOBUFS, 1); err != nil {
return nil, err
}
addr := syscall.SockaddrNetlink{Family: syscall.AF_NETLINK}
if err := syscall.Bind(fd, &addr); err != nil {
return nil, err
}
localaddr, err := syscall.Getsockname(fd)
if err != nil {
return nil, err
}
nladdr, ok := localaddr.(*syscall.SockaddrNetlink)
if !ok {
return nil, fmt.Errorf("Expected netlink sockaddr, got %s", reflect.TypeOf(localaddr))
}
success = true
return &NetlinkSocket{
fd: fd,
addr: nladdr,
// netlink messages can be bigger than this, but it
// seems unlikely in practice, and this is similar to
// the limit that the OVS userspace imposes.
buf: make([]byte, 65536),
}, nil
}
func (s *NetlinkSocket) PortId() uint32 {
return s.addr.Pid
}
func (s *NetlinkSocket) Close() error {
if s.fd < 0 {
return nil
}
err := syscall.Close(s.fd)
s.fd = -1
return err
}
type NlMsgBuilder struct {
buf []byte
}
func NewNlMsgBuilder(flags uint16, typ uint16) *NlMsgBuilder {
buf := MakeAlignedByteSlice(syscall.NLMSG_HDRLEN)
nlmsg := &NlMsgBuilder{buf: buf}
h := nlMsghdrAt(buf, 0)
h.Flags = flags
h.Type = typ
return nlmsg
}
// Expand the array underlying a slice to have capacity of at least l
func expand(buf []byte, l int) []byte {
c := (cap(buf) + 1) * 3 / 2
for l > c {
c = (c + 1) * 3 / 2
}
new := MakeAlignedByteSliceCap(len(buf), c)
copy(new, buf)
return new
}
func (nlmsg *NlMsgBuilder) Align(a int) {
l := align(len(nlmsg.buf), a)
if l > cap(nlmsg.buf) {
nlmsg.buf = expand(nlmsg.buf, l)
}
nlmsg.buf = nlmsg.buf[:l]
}
func (nlmsg *NlMsgBuilder) Grow(size uintptr) int {
pos := len(nlmsg.buf)
l := pos + int(size)
if l > cap(nlmsg.buf) {
nlmsg.buf = expand(nlmsg.buf, l)
}
nlmsg.buf = nlmsg.buf[:l]
return pos
}
func (nlmsg *NlMsgBuilder) AlignGrow(a int, size uintptr) int {
apos := align(len(nlmsg.buf), a)
l := apos + int(size)
if l > cap(nlmsg.buf) {
nlmsg.buf = expand(nlmsg.buf, l)
}
nlmsg.buf = nlmsg.buf[:l]
return apos
}
var nextSeqNo uint32
func (nlmsg *NlMsgBuilder) Finish() (res []byte, seq uint32) {
h := nlMsghdrAt(nlmsg.buf, 0)
h.Len = uint32(len(nlmsg.buf))
seq = atomic.AddUint32(&nextSeqNo, 1)
h.Seq = seq
res = nlmsg.buf
nlmsg.buf = nil
return
}
func (nlmsg *NlMsgBuilder) PutAttr(typ uint16, gen func()) {
pos := nlmsg.AlignGrow(syscall.NLA_ALIGNTO, syscall.SizeofNlAttr)
gen()
nla := nlAttrAt(nlmsg.buf, pos)
nla.Type = typ
nla.Len = uint16(len(nlmsg.buf) - pos)
}
func (nlmsg *NlMsgBuilder) PutNestedAttrs(typ uint16, gen func()) {
nlmsg.PutAttr(typ, func() {
gen()
// The kernel nlattr parser expects the alignment
// padding at the end of a nested attributes value to
// be included in the length of the enclosing
// attribute
nlmsg.Align(syscall.NLA_ALIGNTO)
})
}
func (nlmsg *NlMsgBuilder) PutEmptyAttr(typ uint16) {
nlmsg.PutAttr(typ, func() {})
}
func (nlmsg *NlMsgBuilder) PutUint8Attr(typ uint16, val uint8) {
nlmsg.PutAttr(typ, func() {
pos := nlmsg.Grow(1)
nlmsg.buf[pos] = val
})
}
func (nlmsg *NlMsgBuilder) PutUint16Attr(typ uint16, val uint16) {
nlmsg.PutAttr(typ, func() {
pos := nlmsg.Grow(2)
*uint16At(nlmsg.buf, pos) = val
})
}
func (nlmsg *NlMsgBuilder) PutUint32Attr(typ uint16, val uint32) {
nlmsg.PutAttr(typ, func() {
pos := nlmsg.Grow(4)
*uint32At(nlmsg.buf, pos) = val
})
}
func (nlmsg *NlMsgBuilder) putStringZ(str string) {
l := len(str)
pos := nlmsg.Grow(uintptr(l) + 1)
copy(nlmsg.buf[pos:], str)
nlmsg.buf[pos+l] = 0
}
func (nlmsg *NlMsgBuilder) PutStringAttr(typ uint16, str string) {
nlmsg.PutAttr(typ, func() { nlmsg.putStringZ(str) })
}
func (nlmsg *NlMsgBuilder) PutSliceAttr(typ uint16, data []byte) {
nlmsg.PutAttr(typ, func() {
pos := nlmsg.Grow(uintptr(len(data)))
copy(nlmsg.buf[pos:], data)
})
}
type NetlinkError syscall.Errno
func (err NetlinkError) Error() string {
return fmt.Sprintf("netlink error response: %s", syscall.Errno(err))
}
type NlMsgParser struct {
data []byte
pos int
}
func (nlmsg *NlMsgParser) Advance(size uintptr) error {
if err := nlmsg.CheckAvailable(size); err != nil {
return err
}
nlmsg.pos += int(size)
return nil
}
func (nlmsg *NlMsgParser) AlignAdvance(a int, size uintptr) (int, error) {
pos := align(nlmsg.pos, a)
nlmsg.pos = pos
if err := nlmsg.Advance(size); err != nil {
return 0, err
}
return pos, nil
}
func (nlmsg *NlMsgParser) NlMsghdr() *syscall.NlMsghdr {
return nlMsghdrAt(nlmsg.data, nlmsg.pos)
}
func (msg *NlMsgParser) nextNlMsg() (*NlMsgParser, error) {
pos := msg.pos
avail := len(msg.data) - pos
if avail <= 0 {
return nil, nil
}
if avail < syscall.SizeofNlMsghdr {
return nil, fmt.Errorf("netlink message header truncated")
}
h := msg.NlMsghdr()
if avail < int(h.Len) {
return nil, fmt.Errorf("netlink message truncated (%d bytes available, %d expected)", avail, h.Len)
}
end := pos + int(h.Len)
msg.pos = align(end, syscall.NLMSG_ALIGNTO)
return &NlMsgParser{data: msg.data[:end], pos: pos}, nil
}
func (nlmsg *NlMsgParser) CheckAvailable(size uintptr) error {
if nlmsg.pos+int(size) > len(nlmsg.data) {
return fmt.Errorf("netlink message truncated")
}
return nil
}
func (nlmsg *NlMsgParser) checkHeader() error {
// nextNlMsg ensures that there is an nlmsghdr-worth of data
// present
h := nlmsg.NlMsghdr()
if h.Type == syscall.NLMSG_ERROR {
nlerr := nlMsgerrAt(nlmsg.data, nlmsg.pos+syscall.NLMSG_HDRLEN)
if nlerr.Error != 0 {
return NetlinkError(-nlerr.Error)
}
// an error code of 0 means the error is an ack, so
// return normally.
}
return nil
}
func (nlmsg *NlMsgParser) checkResponseHeader(expectedPortId uint32, expectedSeq uint32) (relevant bool, err error) {
// nextNlMsg ensures that there is an nlmsghdr-worth of data
// present
h := nlmsg.NlMsghdr()
if h.Pid != expectedPortId {
return true, fmt.Errorf("netlink reply port id mismatch (got %d, expected %d)", h.Pid, expectedPortId)
}
if h.Seq != expectedSeq {
// This doesn't necessarily indicate an error. For
// example, if an early requestMulti was interrupted
// due to an error, we might still be getting its
// response messages back that, and we should discard
// them. On the other hand, sequence number
// mismatches might indicate bugs, so it is sometimes
// nice to see them in development.
fmt.Printf("netlink reply sequence number mismatch (got %d, expected %d)\n", h.Seq, expectedSeq)
return false, nil
}
return true, nlmsg.checkHeader()
}
func (nlmsg *NlMsgParser) ExpectNlMsghdr(typ uint16) (*syscall.NlMsghdr, error) {
h := nlmsg.NlMsghdr()
if err := nlmsg.Advance(syscall.SizeofNlMsghdr); err != nil {
return nil, err
}
if h.Type != typ {
return nil, fmt.Errorf("netlink response has wrong type (got %d, expected %d)", h.Type, typ)
}
return h, nil
}
type Attrs map[uint16][]byte
func (attrs Attrs) Get(typ uint16, optional bool) ([]byte, error) {
val, ok := attrs[typ]
if !ok && !optional {
return nil, fmt.Errorf("missing netlink attribute %d", typ)
}
return val, nil
}
func (attrs Attrs) GetFixedBytes(typ uint16, expect int, optional bool) ([]byte, error) {
val, err := attrs.Get(typ, optional)
if err != nil || val == nil {
return nil, err
}
if len(val) != expect {
return nil, fmt.Errorf("attribute %d has wrong length (got %d bytes, expected %d bytes)", typ, len(val), expect)
}
return val, nil
}
func (attrs Attrs) GetOptionalBytes(typ uint16, dest []byte) (bool, error) {
val, err := attrs.GetFixedBytes(typ, len(dest), true)
if err != nil || val == nil {
return false, err
}
copy(dest, val)
return true, nil
}
func (attrs Attrs) GetEmpty(typ uint16) (bool, error) {
val, err := attrs.Get(typ, true)
if err != nil || val == nil {
return false, err
}
if len(val) != 0 {
return false, fmt.Errorf("empty attribute %d has wrong length (%d bytes)", typ, len(val))
}
return true, nil
}
func (attrs Attrs) GetOptionalUint8(typ uint16) (uint8, bool, error) {
val, err := attrs.Get(typ, true)
if err != nil || val == nil {
return 0, false, err
}
if len(val) != 1 {
return 0, false, fmt.Errorf("uint8 attribute %d has wrong length (%d bytes)", typ, len(val))
}
return val[0], true, nil
}
func (attrs Attrs) getUint16(typ uint16, optional bool) (uint16, bool, error) {
val, err := attrs.Get(typ, optional)
if err != nil || val == nil {
return 0, false, err
}
if len(val) != 2 {
return 0, false, fmt.Errorf("uint16 attribute %d has wrong length (%d bytes)", typ, len(val))
}
return *uint16At(val, 0), true, nil
}
func (attrs Attrs) GetUint16(typ uint16) (uint16, error) {
res, _, err := attrs.getUint16(typ, false)
return res, err
}
func (attrs Attrs) GetOptionalUint16(typ uint16) (uint16, bool, error) {
return attrs.getUint16(typ, true)
}
func (attrs Attrs) GetUint32(typ uint16) (uint32, error) {
val, err := attrs.Get(typ, false)
if err != nil {
return 0, err
}
if len(val) != 4 {
return 0, fmt.Errorf("uint32 attribute %d has wrong length (%d bytes)", typ, len(val))
}
return *uint32At(val, 0), nil
}
func (attrs Attrs) getUint64(typ uint16, optional bool) (uint64, bool, error) {
val, err := attrs.Get(typ, optional)
if err != nil || val == nil {
return 0, false, err
}
if len(val) != 8 {
return 0, false, fmt.Errorf("uint64 attribute %d has wrong length (%d bytes)", typ, len(val))
}
return *uint64At(val, 0), true, nil
}
func (attrs Attrs) GetUint64(typ uint16) (uint64, error) {
res, _, err := attrs.getUint64(typ, false)
return res, err
}
func (attrs Attrs) GetOptionalUint64(typ uint16) (uint64, bool, error) {
return attrs.getUint64(typ, true)
}
func (attrs Attrs) GetString(typ uint16) (string, error) {
val, err := attrs.Get(typ, false)
if err != nil {
return "", err
}
if len(val) == 0 {
return "", fmt.Errorf("string attribute %d has zero length", typ)
}
if val[len(val)-1] != 0 {
return "", fmt.Errorf("string attribute %d does not end with nul byte", typ)
}
return string(val[0 : len(val)-1]), nil
}
func (nlmsg *NlMsgParser) checkData(l uintptr, obj string) error {
if nlmsg.pos+int(l) <= len(nlmsg.data) {
return nil
} else {
return fmt.Errorf("truncated %s (have %d bytes, expected %d)", obj, len(nlmsg.data)-nlmsg.pos, l)
}
}
func (nlmsg *NlMsgParser) parseAttrs(consumer func(uint16, []byte)) error {
for {
apos := align(nlmsg.pos, syscall.NLA_ALIGNTO)
if len(nlmsg.data) <= apos {
break
}
nlmsg.pos = apos
if err := nlmsg.checkData(syscall.SizeofNlAttr, "netlink attribute"); err != nil {
return err
}
nla := nlAttrAt(nlmsg.data, nlmsg.pos)
if err := nlmsg.checkData(uintptr(nla.Len), "netlink attribute"); err != nil {
return err
}
valpos := align(nlmsg.pos+syscall.SizeofNlAttr, syscall.NLA_ALIGNTO)
consumer(nla.Type, nlmsg.data[valpos:nlmsg.pos+int(nla.Len)])
nlmsg.pos += int(nla.Len)
}
return nil
}
func (nlmsg *NlMsgParser) TakeAttrs() (Attrs, error) {
res := make(Attrs)
err := nlmsg.parseAttrs(func(typ uint16, val []byte) {
res[typ] = val
})
return res, err
}
func ParseNestedAttrs(data []byte) (Attrs, error) {
parser := NlMsgParser{data: data, pos: 0}
return parser.TakeAttrs()
}
func (attrs Attrs) GetNestedAttrs(typ uint16, optional bool) (Attrs, error) {
val, err := attrs.Get(typ, optional)
if val == nil {
return nil, err
}
return ParseNestedAttrs(val)
}
// Usually we parse attributes into a map, but there are cases where
// attribute order matters.
type Attr struct {
typ uint16
val []byte
}
func (attrs Attrs) GetOrderedAttrs(typ uint16) ([]Attr, error) {
val, err := attrs.Get(typ, false)
if val == nil {
return nil, err
}
parser := NlMsgParser{data: val, pos: 0}
res := make([]Attr, 0)
err = parser.parseAttrs(func(typ uint16, val []byte) {
res = append(res, Attr{typ, val})
})
return res, err
}
func (s *NetlinkSocket) send(msg *NlMsgBuilder) (uint32, error) {
sa := syscall.SockaddrNetlink{
Family: syscall.AF_NETLINK,
Pid: 0,
Groups: 0,
}
data, seq := msg.Finish()
return seq, syscall.Sendto(s.fd, data, 0, &sa)
}
func (s *NetlinkSocket) recv(peer uint32) (*NlMsgParser, error) {
nr, from, err := syscall.Recvfrom(s.fd, s.buf, 0)
if err != nil {
return nil, err
}
buf := MakeAlignedByteSlice(nr)
copy(buf, s.buf)
switch nlfrom := from.(type) {
case *syscall.SockaddrNetlink:
if nlfrom.Pid != peer {
return nil, fmt.Errorf("wrong netlink peer pid (expected %d, got %d)", peer, nlfrom.Pid)
}
return &NlMsgParser{data: buf, pos: 0}, nil
default:
return nil, fmt.Errorf("Expected netlink sockaddr, got %s", reflect.TypeOf(from))
}
}
func (s *NetlinkSocket) Receive(consumer func(*NlMsgParser) (bool, error)) error {
for {
resp, err := s.recv(0)
if err != nil {
return err
}
msg, err := resp.nextNlMsg()
if err != nil {
return err
}
if msg == nil {
return fmt.Errorf("netlink response message missing")
}
for {
done, err := consumer(msg)
if done || err != nil {
return err
}
msg, err = resp.nextNlMsg()
if err != nil {
return err
}
if msg == nil {
break
}
}
}
}
// Some generic netlink operations always return a reply message (e.g
// *_GET), others don't by default (e.g. *_NEW). In the latter case,
// NLM_F_ECHO forces a reply. This is undocumented AFAICT.
const RequestFlags = syscall.NLM_F_REQUEST | syscall.NLM_F_ECHO
// Do a netlink request that yields a single response message.
func (s *NetlinkSocket) Request(req *NlMsgBuilder) (resp *NlMsgParser, err error) {
seq, err := s.send(req)
if err != nil {
return nil, err
}
err = s.Receive(func(msg *NlMsgParser) (bool, error) {
relevant, err := msg.checkResponseHeader(s.PortId(), seq)
if relevant && err == nil {
resp = msg
}
return true, err
})
return
}
const DumpFlags = syscall.NLM_F_DUMP | syscall.NLM_F_REQUEST
// Do a netlink request that yield multiple response messages.
func (s *NetlinkSocket) RequestMulti(req *NlMsgBuilder, consumer func(*NlMsgParser) error) error {
seq, err := s.send(req)
if err != nil {
return err
}
return s.Receive(func(msg *NlMsgParser) (bool, error) {
relevant, err := msg.checkResponseHeader(s.PortId(), seq)
if !relevant || err != nil {
return false, err
}
if msg.NlMsghdr().Type == syscall.NLMSG_DONE {
return true, processNlMsgDone(msg)
}
err = consumer(msg)
if err != nil {
return true, err
}
return false, nil
})
}
func processNlMsgDone(msg *NlMsgParser) error {
err := msg.Advance(syscall.SizeofNlMsghdr)
if err != nil {
return err
}
err = msg.checkData(4, "NLMSG_DONE error code")
if err != nil {
return err
}
errno := *int32At(msg.data, msg.pos)
if errno == 0 {
return nil
} else {
return NetlinkError(-errno)
}
}
type Consumer interface {
Error(err error, stopped bool)
}
func (s *NetlinkSocket) consume(consumer Consumer, handler func(*NlMsgParser) error) {
for {
err := s.Receive(func(msg *NlMsgParser) (bool, error) {
err := msg.checkHeader()
if err == nil {
err = handler(msg)
if err == nil {
return false, nil
}
}
consumer.Error(err, false)
return false, nil
})
if err != nil {
consumer.Error(err, true)
break
}
}
}
+173
View File
@@ -0,0 +1,173 @@
package odp
import (
"sync"
)
type MissConsumer interface {
Miss(packet []byte, flowKeys FlowKeys) error
Error(err error, stopped bool)
}
func (origDP DatapathHandle) ConsumeMisses(consumer MissConsumer) (Cancelable, error) {
// We end up needing 3 netlink sockets: one to consume
// misses, one to consume vport events, and one for general
// use.
dp, err := origDP.Reopen()
if err != nil {
return nil, err
}
success := false
defer func() {
if !success {
dp.dpif.Close()
}
}()
missDP, err := origDP.Reopen()
if err != nil {
return nil, err
}
defer func() {
if !success {
missDP.dpif.Close()
}
}()
// We need to set the upcall port ID on all vports. That
// includes vports that get added while we are listening, so
// we need to listen for them too.
vportConsumer := &missVportConsumer{
dp: dp,
upcallPortId: missDP.dpif.sock.PortId(),
missConsumer: consumer,
vportsDone: make(map[VportID]struct{}),
}
vportCancel, err := origDP.ConsumeVportEvents(vportConsumer)
if err != nil {
return nil, err
}
defer func() {
if !success {
vportCancel.Cancel()
}
}()
vports, err := origDP.EnumerateVports()
if err != nil {
return nil, err
}
for _, vport := range vports {
err = vportConsumer.setVportUpcallPortId(vport.ID)
if err != nil {
return nil, err
}
}
success = true
vportConsumer.cancel = vportCancel
go missDP.consumeMisses(consumer, vportConsumer)
return cancelableDpif{missDP.dpif}, nil
}
type missVportConsumer struct {
dp DatapathHandle
upcallPortId uint32
missConsumer MissConsumer
cancel Cancelable
lock sync.Mutex
vportsDone map[VportID]struct{}
}
// Set a vport's upcall port ID. This generates a OVS_VPORT_CMD_NEW
// (not a OVS_VPORT_CMD_SET), leading to a call of the New method
// below. So we need to record which vports we already processed in
// order to avoid a vicious circle.
func (c *missVportConsumer) setVportUpcallPortId(vport VportID) error {
c.lock.Lock()
defer c.lock.Unlock()
if _, doneAlready := c.vportsDone[vport]; doneAlready {
return nil
}
if err := c.dp.setVportUpcallPortId(vport, c.upcallPortId); err != nil {
return err
}
c.vportsDone[vport] = struct{}{}
return nil
}
func (c *missVportConsumer) VportCreated(dpid DatapathID, vport Vport) error {
return c.setVportUpcallPortId(vport.ID)
}
func (c *missVportConsumer) VportDeleted(dpid DatapathID, vport Vport) error {
c.lock.Lock()
delete(c.vportsDone, vport.ID)
c.lock.Unlock()
return nil
}
func (c *missVportConsumer) Error(err error, stopped bool) {
c.missConsumer.Error(err, stopped)
}
func (dp DatapathHandle) consumeMisses(consumer MissConsumer, vportConsumer *missVportConsumer) {
dp.dpif.sock.consume(consumer, func(msg *NlMsgParser) error {
if err := dp.checkNlMsgHeaders(msg, PACKET, OVS_PACKET_CMD_MISS); err != nil {
return err
}
attrs, err := msg.TakeAttrs()
if err != nil {
return err
}
fkattrs, err := attrs.GetNestedAttrs(OVS_PACKET_ATTR_KEY, false)
if err != nil {
return err
}
fks, err := ParseFlowKeys(fkattrs, nil)
if err != nil {
return err
}
return consumer.Miss(attrs[OVS_PACKET_ATTR_PACKET], fks)
})
vportConsumer.cancel.Cancel()
vportConsumer.dp.dpif.Close()
}
func (dp DatapathHandle) Execute(packet []byte, keys FlowKeys, actions []Action) error {
dpif := dp.dpif
req := NewNlMsgBuilder(RequestFlags, dpif.families[PACKET].id)
req.PutGenlMsghdr(OVS_PACKET_CMD_EXECUTE, OVS_PACKET_VERSION)
req.putOvsHeader(dp.ifindex)
req.PutSliceAttr(OVS_PACKET_ATTR_PACKET, packet)
req.PutNestedAttrs(OVS_PACKET_ATTR_KEY, func() {
for _, k := range keys {
k.putKeyNlAttr(req)
}
})
req.PutNestedAttrs(OVS_PACKET_ATTR_ACTIONS, func() {
for _, a := range actions {
a.toNlAttr(req)
}
})
_, err := dpif.sock.send(req)
return err
}
+224
View File
@@ -0,0 +1,224 @@
package odp
import "syscall"
// from linux/include/linux/socket.h
const SOL_NETLINK = 270
type GenlMsghdr struct {
Cmd uint8
Version uint8
Reserved uint16
}
const SizeofGenlMsghdr = 4
// reserved static generic netlink identifiers:
const (
GENL_ID_GENERATE = 0
GENL_ID_CTRL = syscall.NLMSG_MIN_TYPE
GENL_ID_VFS_DQUOT = syscall.NLMSG_MIN_TYPE + 1
GENL_ID_PMCRAID = syscall.NLMSG_MIN_TYPE + 2
)
const (
CTRL_CMD_UNSPEC = 0
CTRL_CMD_NEWFAMILY = 1
CTRL_CMD_DELFAMILY = 2
CTRL_CMD_GETFAMILY = 3
CTRL_CMD_NEWOPS = 4
CTRL_CMD_DELOPS = 5
CTRL_CMD_GETOPS = 6
CTRL_CMD_NEWMCAST_GRP = 7
CTRL_CMD_DELMCAST_GRP = 8
)
const (
CTRL_ATTR_UNSPEC = 0
CTRL_ATTR_FAMILY_ID = 1
CTRL_ATTR_FAMILY_NAME = 2
CTRL_ATTR_VERSION = 3
CTRL_ATTR_HDRSIZE = 4
CTRL_ATTR_MAXATTR = 5
CTRL_ATTR_OPS = 6
CTRL_ATTR_MCAST_GROUPS = 7
)
const (
CTRL_ATTR_MCAST_GRP_UNSPEC = 0
CTRL_ATTR_MCAST_GRP_NAME = 1
CTRL_ATTR_MCAST_GRP_ID = 2
)
type OvsHeader struct {
DpIfIndex int32
}
const SizeofOvsHeader = 4
const (
OVS_DATAPATH_VERSION = 2
OVS_VPORT_VERSION = 1
OVS_FLOW_VERSION = 1
OVS_PACKET_VERSION = 1
)
const ( // ovs_datapath_cmd
OVS_DP_CMD_UNSPEC = 0
OVS_DP_CMD_NEW = 1
OVS_DP_CMD_DEL = 2
OVS_DP_CMD_GET = 3
OVS_DP_CMD_SET = 4
)
const ( // ovs_datapath_attr
OVS_DP_ATTR_UNSPEC = 0
OVS_DP_ATTR_NAME = 1
OVS_DP_ATTR_UPCALL_PID = 2
OVS_DP_ATTR_STATS = 3
OVS_DP_ATTR_MEGAFLOW_STATS = 4
OVS_DP_ATTR_USER_FEATURES = 5
)
const (
OVS_DP_F_UNALIGNED = 1
OVS_DP_F_VPORT_PIDS = 2
)
const ( // ovs_vport_cmd
OVS_VPORT_CMD_UNSPEC = 0
OVS_VPORT_CMD_NEW = 1
OVS_VPORT_CMD_DEL = 2
OVS_VPORT_CMD_GET = 3
OVS_VPORT_CMD_SET = 4
)
const ( // ovs_vport_attr
OVS_VPORT_ATTR_UNSPEC = 0
OVS_VPORT_ATTR_PORT_NO = 1
OVS_VPORT_ATTR_TYPE = 2
OVS_VPORT_ATTR_NAME = 3
OVS_VPORT_ATTR_OPTIONS = 4
OVS_VPORT_ATTR_UPCALL_PID = 5
OVS_VPORT_ATTR_STATS = 6
)
const ( // ovs_vport_type
OVS_VPORT_TYPE_UNSPEC = 0
OVS_VPORT_TYPE_NETDEV = 1
OVS_VPORT_TYPE_INTERNAL = 2
OVS_VPORT_TYPE_GRE = 3
OVS_VPORT_TYPE_VXLAN = 4
OVS_VPORT_TYPE_GENEVE = 5
)
const ( // OVS_VPORT_ATTR_OPTIONS attributes for tunnels
OVS_TUNNEL_ATTR_UNSPEC = 0
OVS_TUNNEL_ATTR_DST_PORT = 1
)
const ( // ovs_flow_cmd
OVS_FLOW_CMD_UNSPEC = 0
OVS_FLOW_CMD_NEW = 1
OVS_FLOW_CMD_DEL = 2
OVS_FLOW_CMD_GET = 3
OVS_FLOW_CMD_SET = 4
)
const ( // ovs_flow_attr
OVS_FLOW_ATTR_UNSPEC = 0
OVS_FLOW_ATTR_KEY = 1
OVS_FLOW_ATTR_ACTIONS = 2
OVS_FLOW_ATTR_STATS = 3
OVS_FLOW_ATTR_TCP_FLAGS = 4
OVS_FLOW_ATTR_USED = 5
OVS_FLOW_ATTR_CLEAR = 6
OVS_FLOW_ATTR_MASK = 7
)
type OvsFlowStats struct {
NPackets uint64
NBytes uint64
}
const SizeofOvsFlowStats = 16
const ( // ovs_key_attr
OVS_KEY_ATTR_UNSPEC = 0
OVS_KEY_ATTR_ENCAP = 1
OVS_KEY_ATTR_PRIORITY = 2
OVS_KEY_ATTR_IN_PORT = 3
OVS_KEY_ATTR_ETHERNET = 4
OVS_KEY_ATTR_VLAN = 5
OVS_KEY_ATTR_ETHERTYPE = 6
OVS_KEY_ATTR_IPV4 = 7
OVS_KEY_ATTR_IPV6 = 8
OVS_KEY_ATTR_TCP = 9
OVS_KEY_ATTR_UDP = 10
OVS_KEY_ATTR_ICMP = 11
OVS_KEY_ATTR_ICMPV6 = 12
OVS_KEY_ATTR_ARP = 13
OVS_KEY_ATTR_ND = 14
OVS_KEY_ATTR_SKB_MARK = 15
OVS_KEY_ATTR_TUNNEL = 16
OVS_KEY_ATTR_SCTP = 17
OVS_KEY_ATTR_TCP_FLAGS = 18
OVS_KEY_ATTR_DP_HASH = 19
OVS_KEY_ATTR_RECIRC_ID = 20
)
const ( // ovs_tunnel_key_attr
OVS_TUNNEL_KEY_ATTR_ID = 0
OVS_TUNNEL_KEY_ATTR_IPV4_SRC = 1
OVS_TUNNEL_KEY_ATTR_IPV4_DST = 2
OVS_TUNNEL_KEY_ATTR_TOS = 3
OVS_TUNNEL_KEY_ATTR_TTL = 4
OVS_TUNNEL_KEY_ATTR_DONT_FRAGMENT = 5
OVS_TUNNEL_KEY_ATTR_CSUM = 6
OVS_TUNNEL_KEY_ATTR_OAM = 7
OVS_TUNNEL_KEY_ATTR_GENEVE_OPTS = 8
OVS_TUNNEL_KEY_ATTR_TP_SRC = 9
OVS_TUNNEL_KEY_ATTR_TP_DST = 10
OVS_TUNNEL_KEY_ATTR_VXLAN_OPTS = 11
OVS_TUNNEL_KEY_ATTR_IPV6_SRC = 12
OVS_TUNNEL_KEY_ATTR_IPV6_DST = 13
)
const ETH_ALEN = 6
type OvsKeyEthernet struct {
EthSrc [ETH_ALEN]byte
EthDst [ETH_ALEN]byte
}
const SizeofOvsKeyEthernet = 12
const ( // ovs_action_attr
OVS_ACTION_ATTR_UNSPEC = 0
OVS_ACTION_ATTR_OUTPUT = 1
OVS_ACTION_ATTR_USERSPACE = 2
OVS_ACTION_ATTR_SET = 3
OVS_ACTION_ATTR_PUSH_VLAN = 4
OVS_ACTION_ATTR_POP_VLAN = 5
OVS_ACTION_ATTR_SAMPLE = 6
)
const ( // ovs_packet_cmd
OVS_PACKET_CMD_UNSPEC = 0
OVS_PACKET_CMD_MISS = 1
OVS_PACKET_CMD_ACTION = 2
OVS_PACKET_CMD_EXECUTE = 3
)
const ( // ovs_packet_attr
OVS_PACKET_ATTR_UNSPEC = 0
OVS_PACKET_ATTR_PACKET = 1
OVS_PACKET_ATTR_KEY = 2
OVS_PACKET_ATTR_ACTIONS = 3
OVS_PACKET_ATTR_USERDATA = 4
)
type ifreqIfindex struct {
name [syscall.IFNAMSIZ]byte
ifindex int32
}
+82
View File
@@ -0,0 +1,82 @@
package odp
import (
"syscall"
"unsafe"
)
const ALIGN_BUFFERS = 8
// Normal slice or array allocations in golang do not appear to be
// guaranteed to be aligned (though in practice they are). Unaligned
// access are slow on some architectures and blow up on others. So
// this allocates a slice aligned to ALIGN_BUFFERS.
func MakeAlignedByteSliceCap(len int, cap int) []byte {
b := make([]byte, cap+ALIGN_BUFFERS-1)
off := int(uintptr(unsafe.Pointer(&b[0])) & (ALIGN_BUFFERS - 1))
if off == 0 {
// Already aligned
return b[:len]
} else {
// Need to offset the slice to make it aligned
off = ALIGN_BUFFERS - off
return b[off : len+off]
}
}
func MakeAlignedByteSlice(len int) []byte {
return MakeAlignedByteSliceCap(len, len)
}
func uint16At(data []byte, pos int) *uint16 {
return (*uint16)(unsafe.Pointer(&data[pos]))
}
func uint32At(data []byte, pos int) *uint32 {
return (*uint32)(unsafe.Pointer(&data[pos]))
}
func int32At(data []byte, pos int) *int32 {
return (*int32)(unsafe.Pointer(&data[pos]))
}
func uint64At(data []byte, pos int) *uint64 {
return (*uint64)(unsafe.Pointer(&data[pos]))
}
func nlMsghdrAt(data []byte, pos int) *syscall.NlMsghdr {
return (*syscall.NlMsghdr)(unsafe.Pointer(&data[pos]))
}
func nlAttrAt(data []byte, pos int) *syscall.NlAttr {
return (*syscall.NlAttr)(unsafe.Pointer(&data[pos]))
}
func nlMsgerrAt(data []byte, pos int) *syscall.NlMsgerr {
return (*syscall.NlMsgerr)(unsafe.Pointer(&data[pos]))
}
func genlMsghdrAt(data []byte, pos int) *GenlMsghdr {
return (*GenlMsghdr)(unsafe.Pointer(&data[pos]))
}
func ovsHeaderAt(data []byte, pos int) *OvsHeader {
return (*OvsHeader)(unsafe.Pointer(&data[pos]))
}
func ovsKeyEthernetAt(data []byte, pos int) *OvsKeyEthernet {
return (*OvsKeyEthernet)(unsafe.Pointer(&data[pos]))
}
func ovsFlowStatsAt(data []byte, pos int) *OvsFlowStats {
return (*OvsFlowStats)(unsafe.Pointer(&data[pos]))
}
func uint16FromBE(n uint16) uint16 {
a := (*[2]byte)(unsafe.Pointer(&n))
return uint16(a[0])<<8 + uint16(a[1])
}
func uint16ToBE(n uint16) uint16 {
return uint16FromBE(n)
}
+416
View File
@@ -0,0 +1,416 @@
package odp
import (
"fmt"
"syscall"
)
type VportSpec interface {
TypeName() string
Name() string
typeId() uint32
optionNlAttrs(req *NlMsgBuilder)
}
type VportSpecBase struct {
name string
}
func (v VportSpecBase) Name() string {
return v.name
}
type SimpleVportSpec struct {
VportSpecBase
typ uint32
typeName string
}
func (s SimpleVportSpec) TypeName() string {
return s.typeName
}
func (s SimpleVportSpec) typeId() uint32 {
return s.typ
}
func (SimpleVportSpec) optionNlAttrs(req *NlMsgBuilder) {
}
func NewNetdevVportSpec(name string) VportSpec {
return SimpleVportSpec{
VportSpecBase{name},
OVS_VPORT_TYPE_NETDEV,
"netdev",
}
}
func NewInternalVportSpec(name string) VportSpec {
return SimpleVportSpec{
VportSpecBase{name},
OVS_VPORT_TYPE_INTERNAL,
"internal",
}
}
// GRE vports
type GreVportSpec struct {
VportSpecBase
}
func (GreVportSpec) TypeName() string {
return "gre"
}
func (GreVportSpec) typeId() uint32 {
return OVS_VPORT_TYPE_GRE
}
func (v GreVportSpec) optionNlAttrs(req *NlMsgBuilder) {
}
func NewGreVportSpec(name string) VportSpec {
return GreVportSpec{VportSpecBase{name}}
}
// VXLAN vports
type udpVportSpec struct {
VportSpecBase
Port uint16
}
func (v udpVportSpec) optionNlAttrs(req *NlMsgBuilder) {
req.PutUint16Attr(OVS_TUNNEL_ATTR_DST_PORT, v.Port)
}
func parseUdpVportSpec(name string, opts Attrs) (udpVportSpec, error) {
port, err := opts.GetUint16(OVS_TUNNEL_ATTR_DST_PORT)
if err != nil {
return udpVportSpec{}, err
}
return udpVportSpec{VportSpecBase{name}, port}, nil
}
type VxlanVportSpec struct {
udpVportSpec
}
func (VxlanVportSpec) TypeName() string {
return "vxlan"
}
func (VxlanVportSpec) typeId() uint32 {
return OVS_VPORT_TYPE_VXLAN
}
func NewVxlanVportSpec(name string, port uint16) VportSpec {
return VxlanVportSpec{udpVportSpec{VportSpecBase{name}, port}}
}
// GENEVE vports
type GeneveVportSpec struct {
udpVportSpec
}
func (GeneveVportSpec) TypeName() string {
return "geneve"
}
func (GeneveVportSpec) typeId() uint32 {
return OVS_VPORT_TYPE_GENEVE
}
func NewGeneveVportSpec(name string, port uint16) VportSpec {
return GeneveVportSpec{udpVportSpec{VportSpecBase{name}, port}}
}
// Vport numbers are scoped to a particular datapath
type VportID uint32
func parseVport(msg *NlMsgParser) (id VportID, s VportSpec, err error) {
attrs, err := msg.TakeAttrs()
if err != nil {
return
}
rawid, err := attrs.GetUint32(OVS_VPORT_ATTR_PORT_NO)
if err != nil {
return
}
id = VportID(rawid)
typ, err := attrs.GetUint32(OVS_VPORT_ATTR_TYPE)
if err != nil {
return
}
name, err := attrs.GetString(OVS_VPORT_ATTR_NAME)
if err != nil {
return
}
opts, err := attrs.GetNestedAttrs(OVS_VPORT_ATTR_OPTIONS, true)
if err != nil {
return
}
if opts == nil {
opts = make(Attrs)
}
switch typ {
case OVS_VPORT_TYPE_NETDEV:
s = NewNetdevVportSpec(name)
case OVS_VPORT_TYPE_INTERNAL:
s = NewInternalVportSpec(name)
case OVS_VPORT_TYPE_GRE:
s = NewGreVportSpec(name)
case OVS_VPORT_TYPE_VXLAN:
u, err := parseUdpVportSpec(name, opts)
if err == nil {
s = VxlanVportSpec{u}
}
case OVS_VPORT_TYPE_GENEVE:
u, err := parseUdpVportSpec(name, opts)
if err == nil {
s = GeneveVportSpec{u}
}
default:
err = fmt.Errorf("unsupported vport type %d", typ)
}
return
}
func (dp DatapathHandle) CreateVport(spec VportSpec) (VportID, error) {
dpif := dp.dpif
req := NewNlMsgBuilder(RequestFlags, dpif.families[VPORT].id)
req.PutGenlMsghdr(OVS_VPORT_CMD_NEW, OVS_VPORT_VERSION)
req.putOvsHeader(dp.ifindex)
req.PutStringAttr(OVS_VPORT_ATTR_NAME, spec.Name())
req.PutUint32Attr(OVS_VPORT_ATTR_TYPE, spec.typeId())
req.PutNestedAttrs(OVS_VPORT_ATTR_OPTIONS, func() {
spec.optionNlAttrs(req)
})
req.PutUint32Attr(OVS_VPORT_ATTR_UPCALL_PID, 0)
resp, err := dpif.sock.Request(req)
if err != nil {
return 0, err
}
_, _, err = dpif.checkNlMsgHeaders(resp, VPORT, OVS_VPORT_CMD_NEW)
if err != nil {
return 0, err
}
id, _, err := parseVport(resp)
if err != nil {
return 0, err
}
return id, nil
}
func IsNoSuchVportError(err error) bool {
return err == NetlinkError(syscall.ENODEV)
}
type Vport struct {
ID VportID
Spec VportSpec
}
func lookupVport(dpif *Dpif, dpifindex DatapathID, name string) (DatapathID, Vport, error) {
req := NewNlMsgBuilder(RequestFlags, dpif.families[VPORT].id)
req.PutGenlMsghdr(OVS_VPORT_CMD_GET, OVS_VPORT_VERSION)
req.putOvsHeader(dpifindex)
req.PutStringAttr(OVS_VPORT_ATTR_NAME, name)
resp, err := dpif.sock.Request(req)
if err != nil {
return 0, Vport{}, err
}
_, ovshdr, err := dpif.checkNlMsgHeaders(resp, VPORT, OVS_VPORT_CMD_NEW)
if err != nil {
return 0, Vport{}, err
}
id, s, err := parseVport(resp)
if err != nil {
return 0, Vport{}, err
}
return ovshdr.datapathID(), Vport{id, s}, nil
}
func (dpif *Dpif) LookupVportByName(name string) (DatapathHandle, Vport, error) {
dpifindex, vport, err := lookupVport(dpif, 0, name)
return DatapathHandle{dpif: dpif, ifindex: dpifindex}, vport, err
}
func (dp DatapathHandle) LookupVportByName(name string) (Vport, error) {
_, vport, err := lookupVport(dp.dpif, dp.ifindex, name)
return vport, err
}
func (dp DatapathHandle) LookupVport(id VportID) (Vport, error) {
req := NewNlMsgBuilder(RequestFlags, dp.dpif.families[VPORT].id)
req.PutGenlMsghdr(OVS_VPORT_CMD_GET, OVS_VPORT_VERSION)
req.putOvsHeader(dp.ifindex)
req.PutUint32Attr(OVS_VPORT_ATTR_PORT_NO, uint32(id))
resp, err := dp.dpif.sock.Request(req)
if err != nil {
return Vport{}, err
}
err = dp.checkNlMsgHeaders(resp, VPORT, OVS_VPORT_CMD_NEW)
if err != nil {
return Vport{}, err
}
id, s, err := parseVport(resp)
if err != nil {
return Vport{}, err
}
return Vport{id, s}, nil
}
func (dp DatapathHandle) LookupVportName(id VportID) (string, error) {
vport, err := dp.LookupVport(id)
if err != nil {
if !IsNoSuchVportError(err) {
return "", err
}
// No vport with the given port number, so just
// show the number
return fmt.Sprintf("%d:%d", dp.ifindex, id), nil
}
return vport.Spec.Name(), nil
}
func (dp DatapathHandle) EnumerateVports() ([]Vport, error) {
req := NewNlMsgBuilder(DumpFlags, dp.dpif.families[VPORT].id)
req.PutGenlMsghdr(OVS_VPORT_CMD_GET, OVS_VPORT_VERSION)
req.putOvsHeader(dp.ifindex)
var res []Vport
consumer := func(resp *NlMsgParser) error {
err := dp.checkNlMsgHeaders(resp, VPORT, OVS_VPORT_CMD_NEW)
if err != nil {
return err
}
id, spec, err := parseVport(resp)
if err != nil {
return err
}
res = append(res, Vport{id, spec})
return nil
}
err := dp.dpif.sock.RequestMulti(req, consumer)
if err != nil {
return nil, err
}
return res, nil
}
func (dp DatapathHandle) DeleteVport(id VportID) error {
req := NewNlMsgBuilder(RequestFlags, dp.dpif.families[VPORT].id)
req.PutGenlMsghdr(OVS_VPORT_CMD_DEL, OVS_VPORT_VERSION)
req.putOvsHeader(dp.ifindex)
req.PutUint32Attr(OVS_VPORT_ATTR_PORT_NO, uint32(id))
_, err := dp.dpif.sock.Request(req)
return err
}
func (dp DatapathHandle) setVportUpcallPortId(id VportID, pid uint32) error {
req := NewNlMsgBuilder(RequestFlags, dp.dpif.families[VPORT].id)
req.PutGenlMsghdr(OVS_VPORT_CMD_SET, OVS_VPORT_VERSION)
req.putOvsHeader(dp.ifindex)
req.PutUint32Attr(OVS_VPORT_ATTR_PORT_NO, uint32(id))
req.PutUint32Attr(OVS_VPORT_ATTR_UPCALL_PID, pid)
_, err := dp.dpif.sock.Request(req)
return err
}
type VportEventsConsumer interface {
VportCreated(dpid DatapathID, vport Vport) error
VportDeleted(dpid DatapathID, vport Vport) error
Error(err error, stopped bool)
}
func (dpif *Dpif) ConsumeVportEvents(consumer VportEventsConsumer) (Cancelable, error) {
return DatapathHandle{dpif, -1}.ConsumeVportEvents(consumer)
}
func (dp DatapathHandle) ConsumeVportEvents(consumer VportEventsConsumer) (Cancelable, error) {
mcGroup, err := dp.dpif.getMCGroup(VPORT, "ovs_vport")
if err != nil {
return nil, err
}
consumeDpif, err := dp.dpif.Reopen()
if err != nil {
return nil, err
}
err = syscall.SetsockoptInt(consumeDpif.sock.fd, SOL_NETLINK, syscall.NETLINK_ADD_MEMBERSHIP, int(mcGroup))
if err != nil {
consumeDpif.Close()
return nil, err
}
go consumeDpif.consumeVportEvents(consumer, dp.ifindex)
return cancelableDpif{consumeDpif}, nil
}
func (dpif *Dpif) consumeVportEvents(consumer VportEventsConsumer, ifindex DatapathID) {
dpif.sock.consume(consumer, func(msg *NlMsgParser) error {
genlhdr, ovshdr, err := dpif.checkNlMsgHeaders(msg, VPORT, -1)
if err != nil {
return err
}
// filter by ifindex, if consuming on a specific datapath
if ifindex >= 0 && ovshdr.datapathID() != ifindex {
return nil
}
id, spec, err := parseVport(msg)
if err != nil {
return err
}
switch genlhdr.Cmd {
case OVS_VPORT_CMD_NEW:
return consumer.VportCreated(ovshdr.datapathID(), Vport{id, spec})
case OVS_VPORT_CMD_DEL:
return consumer.VportDeleted(ovshdr.datapathID(), Vport{id, spec})
default:
return nil
}
})
}