Merge pull request #2705 from weaveworks/bump-tcptracer-bpf-version

bump tcptracer-bpf version
This commit is contained in:
Matthias Radestock
2017-07-12 08:39:27 +01:00
committed by GitHub
25 changed files with 283 additions and 511 deletions

View File

@@ -80,7 +80,7 @@ func newEbpfTracker() (*EbpfTracker, error) {
openConnections: map[fourTuple]ebpfConnection{},
}
tracer, err := tracer.NewTracer(tracker.tcpEventCbV4, tracker.tcpEventCbV6, tracker.lostCb)
tracer, err := tracer.NewTracer(tracker)
if err != nil {
return nil, err
}
@@ -91,7 +91,8 @@ func newEbpfTracker() (*EbpfTracker, error) {
return tracker, nil
}
func (t *EbpfTracker) tcpEventCbV4(e tracer.TcpV4) {
// TCPEventV4 handles IPv4 TCP events from the eBPF tracer
func (t *EbpfTracker) TCPEventV4(e tracer.TcpV4) {
if t.lastTimestampV4 > e.Timestamp {
// A kernel bug can cause the timestamps to be wrong (e.g. on Ubuntu with Linux 4.4.0-47.68)
// Upgrading the kernel will fix the problem. For further info see:
@@ -111,15 +112,24 @@ func (t *EbpfTracker) tcpEventCbV4(e tracer.TcpV4) {
}
}
func (t *EbpfTracker) tcpEventCbV6(e tracer.TcpV6) {
// TCPEventV6 handles IPv6 TCP events from the eBPF tracer. This is
// currently a no-op.
func (t *EbpfTracker) TCPEventV6(e tracer.TcpV6) {
// TODO: IPv6 not supported in Scope
}
func (t *EbpfTracker) lostCb(count uint64) {
// LostV4 handles IPv4 TCP event misses from the eBPF tracer.
func (t *EbpfTracker) LostV4(count uint64) {
log.Errorf("tcp tracer lost %d events. Stopping the eBPF tracker", count)
t.stop()
}
// LostV6 handles IPv4 TCP event misses from the eBPF tracer. This is
// currently a no-op.
func (t *EbpfTracker) LostV6(count uint64) {
// TODO: IPv6 not supported in Scope
}
func tupleFromPidFd(pid int, fd int) (tuple fourTuple, netns string, ok bool) {
// read /proc/$pid/ns/net
//

View File

@@ -210,11 +210,11 @@ func TestInvalidTimeStampDead(t *testing.T) {
openConnections: map[fourTuple]ebpfConnection{},
}
event.Timestamp = 0
mockEbpfTracker.tcpEventCbV4(event)
mockEbpfTracker.TCPEventV4(event)
event2 := event
event2.SPort = 1
event2.Timestamp = 2
mockEbpfTracker.tcpEventCbV4(event2)
mockEbpfTracker.TCPEventV4(event2)
mockEbpfTracker.walkConnections(func(e ebpfConnection) {
cnt++
})
@@ -226,7 +226,7 @@ func TestInvalidTimeStampDead(t *testing.T) {
}
cnt = 0
event.Timestamp = 1
mockEbpfTracker.tcpEventCbV4(event)
mockEbpfTracker.TCPEventV4(event)
mockEbpfTracker.walkConnections(func(e ebpfConnection) {
cnt++
})

View File

@@ -1,14 +0,0 @@
Copyright 2016 PLUMgrid
Copyright 2016 Kinvolk
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.

View File

@@ -1,201 +0,0 @@
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
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
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.

View File

@@ -1,14 +0,0 @@
Copyright 2016 PLUMgrid
Copyright 2016 Kinvolk
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.

View File

@@ -1,201 +0,0 @@
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
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
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.

View File

@@ -31,7 +31,7 @@ func TracerAsset() ([]byte, error) {
return buf, nil
}
func NewTracer(tcpEventCbV4 func(TcpV4), tcpEventCbV6 func(TcpV6), lostCb func(lost uint64)) (*Tracer, error) {
func NewTracer(cb Callback) (*Tracer, error) {
buf, err := Asset("tcptracer-ebpf.o")
if err != nil {
return nil, fmt.Errorf("couldn't find asset: %s", err)
@@ -81,9 +81,9 @@ func NewTracer(tcpEventCbV4 func(TcpV4), tcpEventCbV6 func(TcpV6), lostCb func(l
case <-stopChan:
return
case data := <-channelV4:
tcpEventCbV4(tcpV4ToGo(&data))
cb.TCPEventV4(tcpV4ToGo(&data))
case lost := <-lostChanV4:
lostCb(lost)
cb.LostV4(lost)
}
}
}()
@@ -94,9 +94,9 @@ func NewTracer(tcpEventCbV4 func(TcpV4), tcpEventCbV6 func(TcpV6), lostCb func(l
case <-stopChan:
return
case data := <-channelV6:
tcpEventCbV6(tcpV6ToGo(&data))
cb.TCPEventV6(tcpV6ToGo(&data))
case lost := <-lostChanV6:
lostCb(lost)
cb.LostV6(lost)
}
}
}()

View File

@@ -0,0 +1,8 @@
package tracer
type Callback interface {
TCPEventV4(TcpV4)
TCPEventV6(TcpV6)
LostV4(uint64)
LostV6(uint64)
}

View File

@@ -12,7 +12,7 @@ func TracerAsset() ([]byte, error) {
return nil, fmt.Errorf("not supported on non-Linux systems")
}
func NewTracer(tcpEventCbV4 func(TcpV4), tcpEventCbV6 func(TcpV6), lostCb func(lost uint64)) (*Tracer, error) {
func NewTracer(cb Callback) (*Tracer, error) {
return nil, fmt.Errorf("not supported on non-Linux systems")
}
func (t *Tracer) Start() {

View File

@@ -12,10 +12,13 @@ import (
)
var watchFdInstallPids string
var lastTimestampV4 uint64
var lastTimestampV6 uint64
func tcpEventCbV4(e tracer.TcpV4) {
type tcpEventTracer struct {
lastTimestampV4 uint64
lastTimestampV6 uint64
}
func (t *tcpEventTracer) TCPEventV4(e tracer.TcpV4) {
if e.Type == tracer.EventFdInstall {
fmt.Printf("%v cpu#%d %s %v %s %v\n",
e.Timestamp, e.CPU, e.Type, e.Pid, e.Comm, e.Fd)
@@ -24,27 +27,32 @@ func tcpEventCbV4(e tracer.TcpV4) {
e.Timestamp, e.CPU, e.Type, e.Pid, e.Comm, e.SAddr, e.SPort, e.DAddr, e.DPort, e.NetNS)
}
if lastTimestampV4 > e.Timestamp {
if t.lastTimestampV4 > e.Timestamp {
fmt.Printf("ERROR: late event!\n")
os.Exit(1)
}
lastTimestampV4 = e.Timestamp
t.lastTimestampV4 = e.Timestamp
}
func tcpEventCbV6(e tracer.TcpV6) {
func (t *tcpEventTracer) TCPEventV6(e tracer.TcpV6) {
fmt.Printf("%v cpu#%d %s %v %s %v:%v %v:%v %v\n",
e.Timestamp, e.CPU, e.Type, e.Pid, e.Comm, e.SAddr, e.SPort, e.DAddr, e.DPort, e.NetNS)
if lastTimestampV6 > e.Timestamp {
if t.lastTimestampV6 > e.Timestamp {
fmt.Printf("ERROR: late event!\n")
os.Exit(1)
}
lastTimestampV6 = e.Timestamp
t.lastTimestampV6 = e.Timestamp
}
func lostCb(count uint64) {
func (t *tcpEventTracer) LostV4(count uint64) {
fmt.Printf("ERROR: lost %d events!\n", count)
os.Exit(1)
}
func (t *tcpEventTracer) LostV6(count uint64) {
fmt.Printf("ERROR: lost %d events!\n", count)
os.Exit(1)
}
@@ -61,7 +69,7 @@ func main() {
os.Exit(1)
}
t, err := tracer.NewTracer(tcpEventCbV4, tcpEventCbV6, lostCb)
t, err := tracer.NewTracer(&tcpEventTracer{})
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)

View File

@@ -31,7 +31,8 @@ import (
"syscall"
"unsafe"
"github.com/iovisor/gobpf/bpffs"
"github.com/iovisor/gobpf/pkg/bpffs"
"github.com/iovisor/gobpf/pkg/cpuonline"
)
/*
@@ -331,7 +332,7 @@ func elfReadMaps(file *elf.File) (map[string]*Map, error) {
return nil, err
}
if len(data) != C.sizeof_struct_bpf_map_def {
return nil, fmt.Errorf("only one map with size %d allowed per section", C.sizeof_struct_bpf_map_def)
return nil, fmt.Errorf("only one map with size %d bytes allowed per section (check bpf_map_def)", C.sizeof_struct_bpf_map_def)
}
name := strings.TrimPrefix(section.Name, "maps/")
@@ -474,7 +475,7 @@ func (b *Module) Load(parameters map[string]SectionParams) error {
return err
}
if version == useCurrentKernelVersion {
version, err = currentVersion()
version, err = CurrentKernelVersion()
if err != nil {
return err
}
@@ -513,6 +514,7 @@ func (b *Module) Load(parameters map[string]SectionParams) error {
isKretprobe := strings.HasPrefix(secName, "kretprobe/")
isCgroupSkb := strings.HasPrefix(secName, "cgroup/skb")
isCgroupSock := strings.HasPrefix(secName, "cgroup/sock")
isSocketFilter := strings.HasPrefix(secName, "socket")
var progType uint32
switch {
@@ -524,9 +526,11 @@ func (b *Module) Load(parameters map[string]SectionParams) error {
progType = uint32(C.BPF_PROG_TYPE_CGROUP_SKB)
case isCgroupSock:
progType = uint32(C.BPF_PROG_TYPE_CGROUP_SOCK)
case isSocketFilter:
progType = uint32(C.BPF_PROG_TYPE_SOCKET_FILTER)
}
if isKprobe || isKretprobe || isCgroupSkb || isCgroupSock {
if isKprobe || isKretprobe || isCgroupSkb || isCgroupSock || isSocketFilter {
rdata, err := rsection.Data()
if err != nil {
return err
@@ -543,12 +547,12 @@ func (b *Module) Load(parameters map[string]SectionParams) error {
insns := (*C.struct_bpf_insn)(unsafe.Pointer(&rdata[0]))
progFd := C.bpf_prog_load(progType,
progFd, err := C.bpf_prog_load(progType,
insns, C.int(rsection.Size),
(*C.char)(lp), C.int(version),
(*C.char)(unsafe.Pointer(&b.log[0])), C.int(len(b.log)))
if progFd < 0 {
return fmt.Errorf("error while loading %q:\n%s", secName, b.log)
return fmt.Errorf("error while loading %q (%v):\n%s", secName, err, b.log)
}
switch {
@@ -559,6 +563,7 @@ func (b *Module) Load(parameters map[string]SectionParams) error {
Name: secName,
insns: insns,
fd: int(progFd),
efd: -1,
}
case isCgroupSkb:
fallthrough
@@ -568,6 +573,12 @@ func (b *Module) Load(parameters map[string]SectionParams) error {
insns: insns,
fd: int(progFd),
}
case isSocketFilter:
b.socketFilters[secName] = &SocketFilter{
Name: secName,
insns: insns,
fd: int(progFd),
}
}
}
}
@@ -584,6 +595,7 @@ func (b *Module) Load(parameters map[string]SectionParams) error {
isKretprobe := strings.HasPrefix(secName, "kretprobe/")
isCgroupSkb := strings.HasPrefix(secName, "cgroup/skb")
isCgroupSock := strings.HasPrefix(secName, "cgroup/sock")
isSocketFilter := strings.HasPrefix(secName, "socket")
var progType uint32
switch {
@@ -595,9 +607,11 @@ func (b *Module) Load(parameters map[string]SectionParams) error {
progType = uint32(C.BPF_PROG_TYPE_CGROUP_SKB)
case isCgroupSock:
progType = uint32(C.BPF_PROG_TYPE_CGROUP_SOCK)
case isSocketFilter:
progType = uint32(C.BPF_PROG_TYPE_SOCKET_FILTER)
}
if isKprobe || isKretprobe || isCgroupSkb || isCgroupSock {
if isKprobe || isKretprobe || isCgroupSkb || isCgroupSock || isSocketFilter {
data, err := section.Data()
if err != nil {
return err
@@ -609,12 +623,12 @@ func (b *Module) Load(parameters map[string]SectionParams) error {
insns := (*C.struct_bpf_insn)(unsafe.Pointer(&data[0]))
progFd := C.bpf_prog_load(progType,
progFd, err := C.bpf_prog_load(progType,
insns, C.int(section.Size),
(*C.char)(lp), C.int(version),
(*C.char)(unsafe.Pointer(&b.log[0])), C.int(len(b.log)))
if progFd < 0 {
return fmt.Errorf("error while loading %q:\n%s", section.Name, b.log)
return fmt.Errorf("error while loading %q (%v):\n%s", section.Name, err, b.log)
}
switch {
@@ -625,6 +639,7 @@ func (b *Module) Load(parameters map[string]SectionParams) error {
Name: secName,
insns: insns,
fd: int(progFd),
efd: -1,
}
case isCgroupSkb:
fallthrough
@@ -634,6 +649,12 @@ func (b *Module) Load(parameters map[string]SectionParams) error {
insns: insns,
fd: int(progFd),
}
case isSocketFilter:
b.socketFilters[secName] = &SocketFilter{
Name: secName,
insns: insns,
fd: int(progFd),
}
}
}
}
@@ -643,8 +664,6 @@ func (b *Module) Load(parameters map[string]SectionParams) error {
func (b *Module) initializePerfMaps(parameters map[string]SectionParams) error {
for name, m := range b.maps {
var cpu C.int = 0
if m.m != nil && m.m.def._type != C.BPF_MAP_TYPE_PERF_EVENT_ARRAY {
continue
}
@@ -665,13 +684,16 @@ func (b *Module) initializePerfMaps(parameters map[string]SectionParams) error {
}
}
for {
pmuFD, err := C.perf_event_open_map(-1 /* pid */, cpu /* cpu */, -1 /* group_fd */, C.PERF_FLAG_FD_CLOEXEC)
cpus, err := cpuonline.Get()
if err != nil {
return fmt.Errorf("failed to determine online cpus: %v", err)
}
for _, cpu := range cpus {
cpuC := C.int(cpu)
pmuFD, err := C.perf_event_open_map(-1 /* pid */, cpuC /* cpu */, -1 /* group_fd */, C.PERF_FLAG_FD_CLOEXEC)
if pmuFD < 0 {
if cpu == 0 {
return fmt.Errorf("perf_event_open for map error: %v", err)
}
break
return fmt.Errorf("perf_event_open for map error: %v", err)
}
// mmap
@@ -689,15 +711,13 @@ func (b *Module) initializePerfMaps(parameters map[string]SectionParams) error {
}
// assign perf fd to map
ret, err := C.bpf_update_element(C.int(b.maps[name].m.fd), unsafe.Pointer(&cpu), unsafe.Pointer(&pmuFD), C.BPF_ANY)
ret, err := C.bpf_update_element(C.int(b.maps[name].m.fd), unsafe.Pointer(&cpuC), unsafe.Pointer(&pmuFD), C.BPF_ANY)
if ret != 0 {
return fmt.Errorf("cannot assign perf fd to map %q: %v (cpu %d)", name, err, cpu)
return fmt.Errorf("cannot assign perf fd to map %q: %v (cpu %d)", name, err, cpuC)
}
b.maps[name].pmuFDs = append(b.maps[name].pmuFDs, pmuFD)
b.maps[name].headers = append(b.maps[name].headers, (*C.struct_perf_event_mmap_page)(unsafe.Pointer(&base[0])))
cpu++
}
}

View File

@@ -27,7 +27,10 @@ import (
var versionRegex = regexp.MustCompile(`^(\d+)\.(\d+).(\d+).*$`)
func kernelVersionFromReleaseString(releaseString string) (uint32, error) {
// KernelVersionFromReleaseString converts a release string with format
// 4.4.2[-1] to a kernel version number in LINUX_VERSION_CODE format.
// That is, for kernel "a.b.c", the version number will be (a<<16 + b<<8 + c)
func KernelVersionFromReleaseString(releaseString string) (uint32, error) {
versionParts := versionRegex.FindStringSubmatch(releaseString)
if len(versionParts) != 4 {
return 0, fmt.Errorf("got invalid release version %q (expected format '4.3.2-1')", releaseString)
@@ -56,7 +59,7 @@ func currentVersionUname() (uint32, error) {
return 0, err
}
releaseString := strings.Trim(utsnameStr(buf.Release[:]), "\x00")
return kernelVersionFromReleaseString(releaseString)
return KernelVersionFromReleaseString(releaseString)
}
func currentVersionUbuntu() (uint32, error) {
@@ -69,7 +72,7 @@ func currentVersionUbuntu() (uint32, error) {
if err != nil {
return 0, err
}
return kernelVersionFromReleaseString(releaseString)
return KernelVersionFromReleaseString(releaseString)
}
var debianVersionRegex = regexp.MustCompile(`.* SMP Debian (\d+\.\d+.\d+-\d+) .*`)
@@ -83,10 +86,12 @@ func currentVersionDebian() (uint32, error) {
if len(match) != 2 {
return 0, fmt.Errorf("failed to get kernel version from /proc/version: %s", procVersion)
}
return kernelVersionFromReleaseString(match[1])
return KernelVersionFromReleaseString(match[1])
}
func currentVersion() (uint32, error) {
// CurrentKernelVersion returns the current kernel version in
// LINUX_VERSION_CODE format (see KernelVersionFromReleaseString())
func CurrentKernelVersion() (uint32, error) {
// We need extra checks for Debian and Ubuntu as they modify
// the kernel version patch number for compatibilty with
// out-of-tree modules. Linux perf tools do the same for Ubuntu

View File

@@ -39,6 +39,7 @@ import (
#include "include/bpf.h"
#include <linux/perf_event.h>
#include <linux/unistd.h>
#include <sys/socket.h>
static int perf_event_open_tracepoint(int tracepoint_id, int pid, int cpu,
int group_fd, unsigned long flags)
@@ -63,8 +64,29 @@ int bpf_prog_attach(int prog_fd, int target_fd, enum bpf_attach_type type)
attr.attach_bpf_fd = prog_fd;
attr.attach_type = type;
// BPF_PROG_ATTACH = 8
return syscall(__NR_bpf, 8, &attr, sizeof(attr));
return syscall(__NR_bpf, BPF_PROG_ATTACH, &attr, sizeof(attr));
}
int bpf_prog_detach(int prog_fd, int target_fd, enum bpf_attach_type type)
{
union bpf_attr attr;
bzero(&attr, sizeof(attr));
attr.target_fd = target_fd;
attr.attach_bpf_fd = prog_fd;
attr.attach_type = type;
return syscall(__NR_bpf, BPF_PROG_DETACH, &attr, sizeof(attr));
}
int bpf_attach_socket(int sock, int fd)
{
return setsockopt(sock, SOL_SOCKET, SO_ATTACH_BPF, &fd, sizeof(fd));
}
int bpf_detach_socket(int sock)
{
return setsockopt(sock, SOL_SOCKET, SO_DETACH_BPF, NULL, 0);
}
*/
import "C"
@@ -78,6 +100,7 @@ type Module struct {
maps map[string]*Map
probes map[string]*Kprobe
cgroupPrograms map[string]*CgroupProgram
socketFilters map[string]*SocketFilter
}
// Kprobe represents a kprobe or kretprobe and has to be declared
@@ -104,20 +127,30 @@ type CgroupProgram struct {
fd int
}
// SocketFilter represents a socket filter
type SocketFilter struct {
Name string
insns *C.struct_bpf_insn
fd int
}
func NewModule(fileName string) *Module {
return &Module{
fileName: fileName,
probes: make(map[string]*Kprobe),
cgroupPrograms: make(map[string]*CgroupProgram),
socketFilters: make(map[string]*SocketFilter),
log: make([]byte, 65536),
}
}
func NewModuleFromReader(fileReader io.ReaderAt) *Module {
return &Module{
fileReader: fileReader,
probes: make(map[string]*Kprobe),
log: make([]byte, 65536),
fileReader: fileReader,
probes: make(map[string]*Kprobe),
cgroupPrograms: make(map[string]*CgroupProgram),
socketFilters: make(map[string]*SocketFilter),
log: make([]byte, 65536),
}
}
@@ -248,7 +281,7 @@ func (b *Module) CgroupProgram(name string) *CgroupProgram {
return b.cgroupPrograms[name]
}
func (b *Module) AttachCgroupProgram(cgroupProg *CgroupProgram, cgroupPath string, attachType AttachType) error {
func AttachCgroupProgram(cgroupProg *CgroupProgram, cgroupPath string, attachType AttachType) error {
f, err := os.Open(cgroupPath)
if err != nil {
return fmt.Errorf("error opening cgroup %q: %v", cgroupPath, err)
@@ -265,6 +298,60 @@ func (b *Module) AttachCgroupProgram(cgroupProg *CgroupProgram, cgroupPath strin
return nil
}
func DetachCgroupProgram(cgroupProg *CgroupProgram, cgroupPath string, attachType AttachType) error {
f, err := os.Open(cgroupPath)
if err != nil {
return fmt.Errorf("error opening cgroup %q: %v", cgroupPath, err)
}
defer f.Close()
progFd := C.int(cgroupProg.fd)
cgroupFd := C.int(f.Fd())
ret, err := C.bpf_prog_detach(progFd, cgroupFd, uint32(attachType))
if ret < 0 {
return fmt.Errorf("failed to detach prog from cgroup %q: %v", cgroupPath, err)
}
return nil
}
func (b *Module) IterSocketFilter() <-chan *SocketFilter {
ch := make(chan *SocketFilter)
go func() {
for name := range b.socketFilters {
ch <- b.socketFilters[name]
}
close(ch)
}()
return ch
}
func (b *Module) SocketFilter(name string) *SocketFilter {
return b.socketFilters[name]
}
func AttachSocketFilter(socketFilter *SocketFilter, sockFd int) error {
ret, err := C.bpf_attach_socket(C.int(sockFd), C.int(socketFilter.fd))
if ret != 0 {
return fmt.Errorf("error attaching BPF socket filter: %v", err)
}
return nil
}
func (sf *SocketFilter) Fd() int {
return sf.fd
}
func DetachSocketFilter(sockFd int) error {
ret, err := C.bpf_detach_socket(C.int(sockFd))
if ret != 0 {
return fmt.Errorf("error detaching BPF socket filter: %v", err)
}
return nil
}
func (b *Module) Kprobe(name string) *Kprobe {
return b.probes[name]
}
@@ -299,8 +386,11 @@ func disableKprobe(eventName string) error {
func (b *Module) closeProbes() error {
var funcName string
for _, probe := range b.probes {
if err := syscall.Close(probe.efd); err != nil {
return fmt.Errorf("error closing perf event fd: %v", err)
if probe.efd != -1 {
if err := syscall.Close(probe.efd); err != nil {
return fmt.Errorf("error closing perf event fd: %v", err)
}
probe.efd = -1
}
if err := syscall.Close(probe.fd); err != nil {
return fmt.Errorf("error closing probe fd: %v", err)
@@ -331,6 +421,15 @@ func (b *Module) closeCgroupPrograms() error {
return nil
}
func (b *Module) closeSocketFilters() error {
for _, filter := range b.socketFilters {
if err := syscall.Close(filter.fd); err != nil {
return fmt.Errorf("error closing socket filter fd: %v", err)
}
}
return nil
}
func unpinMap(m *Map) error {
if m.m.def.pinning == 0 {
return nil
@@ -340,9 +439,10 @@ func unpinMap(m *Map) error {
return syscall.Unlink(mapPath)
}
func (b *Module) closeMaps() error {
func (b *Module) closeMaps(options map[string]CloseOptions) error {
for _, m := range b.maps {
if m.m.def.pinning > 0 {
doUnpin := options[fmt.Sprintf("maps/%s", m.Name)].Unpin
if m.m.def.pinning > 0 && doUnpin {
unpinMap(m)
}
for _, fd := range m.pmuFDs {
@@ -358,9 +458,30 @@ func (b *Module) closeMaps() error {
return nil
}
// Close takes care of terminating all underlying BPF programs and structures
// CloseOptions can be used for custom `Close` parameters
type CloseOptions struct {
// Set Unpin to true to close pinned maps as well
Unpin bool
}
// Close takes care of terminating all underlying BPF programs and structures.
// That is:
//
// * Closing map file descriptors and unpinning them where applicable
// * Detaching BPF programs from kprobes and closing their file descriptors
// * Closing cgroup-bpf file descriptors
// * Closing socket filter file descriptors
//
// It doesn't detach BPF programs from cgroups or sockets because they're
// considered resources the user controls.
// It also doesn't unpin pinned maps. Use CloseExt and set Unpin to do this.
func (b *Module) Close() error {
if err := b.closeMaps(); err != nil {
return b.CloseExt(nil)
}
// CloseExt takes a map "elf section -> CloseOptions"
func (b *Module) CloseExt(options map[string]CloseOptions) error {
if err := b.closeMaps(options); err != nil {
return err
}
if err := b.closeProbes(); err != nil {
@@ -369,5 +490,8 @@ func (b *Module) Close() error {
if err := b.closeCgroupPrograms(); err != nil {
return err
}
if err := b.closeSocketFilters(); err != nil {
return err
}
return nil
}

View File

@@ -238,6 +238,8 @@ func (pm *PerfMap) PollStart() {
}()
}
// PollStop stops the goroutine that polls the perf event map. Make
// sure to close the receiverChan only *after* calling PollStop.
func (pm *PerfMap) PollStop() {
pm.pollStop <- true
}

View File

@@ -8,7 +8,7 @@ import (
"path/filepath"
"unsafe"
"github.com/iovisor/gobpf/bpffs"
"github.com/iovisor/gobpf/pkg/bpffs"
)
/*

View File

@@ -0,0 +1,43 @@
package cpuonline
import (
"io/ioutil"
"strconv"
"strings"
)
const cpuOnline = "/sys/devices/system/cpu/online"
// loosely based on https://github.com/iovisor/bcc/blob/v0.3.0/src/python/bcc/utils.py#L15
func readCPURange(cpuRangeStr string) ([]uint, error) {
var cpus []uint
cpuRangeStr = strings.Trim(cpuRangeStr, "\n ")
for _, cpuRange := range strings.Split(cpuRangeStr, ",") {
rangeOp := strings.SplitN(cpuRange, "-", 2)
first, err := strconv.ParseUint(rangeOp[0], 10, 32)
if err != nil {
return nil, err
}
if len(rangeOp) == 1 {
cpus = append(cpus, uint(first))
continue
}
last, err := strconv.ParseUint(rangeOp[1], 10, 32)
if err != nil {
return nil, err
}
for n := first; n <= last; n++ {
cpus = append(cpus, uint(n))
}
}
return cpus, nil
}
// Get returns a slice with the online CPUs, for example `[0, 2, 3]`
func Get() ([]uint, error) {
buf, err := ioutil.ReadFile(cpuOnline)
if err != nil {
return nil, err
}
return readCPURange(string(buf))
}

20
vendor/manifest vendored
View File

@@ -575,24 +575,6 @@
"revision": "76626ae9c91c4f2a10f34cad8ce83ea42c93bb75",
"branch": "master"
},
{
"importpath": "github.com/iovisor/gobpf/bpffs",
"repository": "https://github.com/iovisor/gobpf",
"vcs": "git",
"revision": "aef06278f7e7142309a608d0e14e69cf94a5adae",
"branch": "master",
"path": "/bpffs",
"notests": true
},
{
"importpath": "github.com/iovisor/gobpf/elf",
"repository": "https://github.com/iovisor/gobpf",
"vcs": "git",
"revision": "aef06278f7e7142309a608d0e14e69cf94a5adae",
"branch": "master",
"path": "/elf",
"notests": true
},
{
"importpath": "github.com/jmespath/go-jmespath",
"repository": "https://github.com/jmespath/go-jmespath",
@@ -1038,7 +1020,7 @@
"importpath": "github.com/weaveworks/tcptracer-bpf",
"repository": "https://github.com/weaveworks/tcptracer-bpf",
"vcs": "git",
"revision": "fc80d1659bf07dabebbb42c5507578440103d66f",
"revision": "53a889d82fbd8a4fc4ef3f0013a9f88a3e9f4ccc",
"branch": "master",
"notests": true
},