First commit
parent
7f4b2b37a0
commit
6502dfe8f5
|
@ -0,0 +1,26 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"runtime"
|
||||
"time"
|
||||
)
|
||||
|
||||
func init() {
|
||||
|
||||
fmt.Println("Garbage Collector Thread Starting")
|
||||
|
||||
go memoryCleanerThread()
|
||||
|
||||
}
|
||||
|
||||
func memoryCleanerThread() {
|
||||
|
||||
for {
|
||||
time.Sleep(10 * time.Minute)
|
||||
fmt.Println("Time to clean memory...")
|
||||
runtime.GC()
|
||||
fmt.Println("Garbage Collection done.")
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,53 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"os"
|
||||
)
|
||||
|
||||
type AbstractConfig struct {
|
||||
MulticastConfig struct {
|
||||
MIPAddr string `json:"MIpAddr"`
|
||||
MPort string `json:"MPort"`
|
||||
} `json:"MulticastConfig"`
|
||||
InterfaceConfig struct {
|
||||
ExistingInterface string `json:"ExistingInterface"`
|
||||
BridgeIPCIDR string `json:"BridgeIpCIDR"`
|
||||
} `json:"InterfaceConfig"`
|
||||
}
|
||||
|
||||
var a AbstractConfig
|
||||
|
||||
func init() {
|
||||
|
||||
//reading json file
|
||||
file, err := ioutil.ReadFile("zoreide.json")
|
||||
|
||||
if err != nil {
|
||||
log.Println("Cannot open config file", err.Error())
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
err = json.Unmarshal([]byte(file), &a)
|
||||
|
||||
if err != nil {
|
||||
log.Println("Cannot marshal json: ", err.Error())
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
MulticastEntity.MIpAddr = a.MulticastConfig.MIPAddr
|
||||
MulticastEntity.MPort = a.MulticastConfig.MPort
|
||||
MulticastEntity.MaxDatagramSize = numberlenght
|
||||
|
||||
ZoreideBridge.BridgeIpCIDR = a.InterfaceConfig.BridgeIPCIDR
|
||||
ZoreideBridge.ExistingInterface = a.InterfaceConfig.ExistingInterface
|
||||
ZoreideBridge.IsActive = false
|
||||
ZoreideBridge.IsAlpha = true
|
||||
|
||||
log.Println("Inizialized Generic Config: ", a)
|
||||
log.Println("Inizialized Interface Config: ", ZoreideBridge)
|
||||
log.Println("Inizialized Multicast Config: ", MulticastEntity)
|
||||
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
module zoreide
|
||||
|
||||
go 1.17
|
||||
|
||||
require (
|
||||
github.com/go-ping/ping v0.0.0-20211130115550-779d1e919534
|
||||
github.com/milosgajdos/tenus v0.0.3
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/docker/libcontainer v2.2.1+incompatible // indirect
|
||||
github.com/google/uuid v1.2.0 // indirect
|
||||
golang.org/x/net v0.0.0-20210316092652-d523dce5a7f4 // indirect
|
||||
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect
|
||||
golang.org/x/sys v0.0.0-20210315160823-c6e025ad8005 // indirect
|
||||
)
|
|
@ -0,0 +1,18 @@
|
|||
github.com/docker/libcontainer v2.2.1+incompatible h1:++SbbkCw+X8vAd4j2gOCzZ2Nn7s2xFALTf7LZKmM1/0=
|
||||
github.com/docker/libcontainer v2.2.1+incompatible/go.mod h1:osvj61pYsqhNCMLGX31xr7klUBhHb/ZBuXS0o1Fvwbw=
|
||||
github.com/go-ping/ping v0.0.0-20211130115550-779d1e919534 h1:dhy9OQKGBh4zVXbjwbxxHjRxMJtLXj3zfgpBYQaR4Q4=
|
||||
github.com/go-ping/ping v0.0.0-20211130115550-779d1e919534/go.mod h1:xIFjORFzTxqIV/tDVGO4eDy/bLuSyawEeojSm3GfRGk=
|
||||
github.com/google/uuid v1.2.0 h1:qJYtXnJRWmpe7m/3XlyhrsLrEURqHRM2kxzoxXqyUDs=
|
||||
github.com/google/uuid v1.2.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/milosgajdos/tenus v0.0.3 h1:jmaJzwaY1DUyYVD0lM4U+uvP2kkEg1VahDqRFxIkVBE=
|
||||
github.com/milosgajdos/tenus v0.0.3/go.mod h1:eIjx29vNeDOYWJuCnaHY2r4fq5egetV26ry3on7p8qY=
|
||||
golang.org/x/net v0.0.0-20210316092652-d523dce5a7f4 h1:b0LrWgu8+q7z4J+0Y3Umo5q1dL7NXBkKBWkaVkAq17E=
|
||||
golang.org/x/net v0.0.0-20210316092652-d523dce5a7f4/go.mod h1:RBQZq4jEuRlivfhVLdyRGr576XBO4/greRjx4P4O3yc=
|
||||
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c h1:5KslGYwFpkhGh+Q16bwMP3cOontH8FOep7tGV86Y7SQ=
|
||||
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210315160823-c6e025ad8005 h1:pDMpM2zh2MT0kHy037cKlSby2nEhD50SYqwQk76Nm40=
|
||||
golang.org/x/sys v0.0.0-20210315160823-c6e025ad8005/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
|
@ -0,0 +1,118 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"math/rand"
|
||||
"net"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/go-ping/ping"
|
||||
"github.com/milosgajdos/tenus"
|
||||
)
|
||||
|
||||
type AbstractBridge struct {
|
||||
ExistingInterface string
|
||||
BridgeIpCIDR string
|
||||
IsActive bool
|
||||
IsAlpha bool
|
||||
hIerarchyNumber int64
|
||||
}
|
||||
|
||||
var ZoreideBridge AbstractBridge
|
||||
|
||||
func init() {
|
||||
|
||||
ZoreideBridge.initializeHierarchy()
|
||||
|
||||
}
|
||||
|
||||
func (b *AbstractBridge) initializeHierarchy() {
|
||||
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
var letterRunes = []rune("123456789")
|
||||
|
||||
num := make([]rune, numberlenght)
|
||||
for i := range num {
|
||||
num[i] = letterRunes[rand.Intn(len(letterRunes))]
|
||||
}
|
||||
|
||||
zz, err := strconv.ParseInt(string(num), 10, 64)
|
||||
if err != nil {
|
||||
log.Println("Error generating number: ", err.Error())
|
||||
b.hIerarchyNumber = 0
|
||||
return
|
||||
} else {
|
||||
b.hIerarchyNumber = zz
|
||||
log.Println("Success generating number: ", b.hIerarchyNumber)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (b *AbstractBridge) configureIpAndBridgeUp() {
|
||||
// we want the program to recover in case of issues
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
|
||||
fmt.Println("Recovered. Error:\n", r)
|
||||
}
|
||||
}()
|
||||
|
||||
// first we check the IP is free. Something weird could have happened in some
|
||||
// other server
|
||||
brIp, brIpNet, err := net.ParseCIDR(b.BridgeIpCIDR)
|
||||
if err != nil {
|
||||
log.Println(err.Error())
|
||||
}
|
||||
|
||||
if doesIpExists(brIp.String()) {
|
||||
log.Println("Cannot take this IP, it exists already: " + brIp.String())
|
||||
return
|
||||
}
|
||||
|
||||
br, err := tenus.NewLinkFrom(b.ExistingInterface)
|
||||
if err != nil {
|
||||
log.Println(err.Error())
|
||||
}
|
||||
|
||||
if err := br.SetLinkIp(brIp, brIpNet); err != nil {
|
||||
log.Println(err.Error())
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (b *AbstractBridge) removeIPandBridgeInt() {
|
||||
|
||||
br, err := tenus.NewLinkFrom(b.ExistingInterface)
|
||||
if err != nil {
|
||||
log.Println(err.Error())
|
||||
}
|
||||
|
||||
brIp, brIpNet, err := net.ParseCIDR(b.BridgeIpCIDR)
|
||||
if err != nil {
|
||||
log.Println(err.Error())
|
||||
}
|
||||
if err := br.UnsetLinkIp(brIp, brIpNet); err != nil {
|
||||
log.Println(err.Error())
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func doesIpExists(bridgeip string) bool {
|
||||
|
||||
pinger, err := ping.NewPinger(bridgeip)
|
||||
if err != nil {
|
||||
log.Println("Ping error: " + err.Error())
|
||||
}
|
||||
// just in case it doesn't stops alone
|
||||
defer pinger.Stop()
|
||||
pinger.Count = 3
|
||||
pinger.Interval = time.Duration(10 * time.Millisecond)
|
||||
pinger.Timeout = time.Duration(1 * time.Second)
|
||||
pinger.Run() // blocks until finished
|
||||
stats := pinger.Statistics()
|
||||
|
||||
return stats.PacketsRecv > 0
|
||||
|
||||
}
|
|
@ -0,0 +1,30 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
var MulticastEntity AbstractMulticast
|
||||
var BstChannel = make(chan string, 1)
|
||||
|
||||
const numberlenght = 18
|
||||
|
||||
func main() {
|
||||
|
||||
MulticastEntity.GetMulticastReady()
|
||||
go MulticastEntity.WriteNumberToMulticast()
|
||||
go MulticastEntity.ReadNumberFromMulticast()
|
||||
go ZoreideBridge.BeTheBeta()
|
||||
go ZoreideBridge.WaitForBeAlpha()
|
||||
|
||||
// Just a nice way to wait until the Operating system sends a kill signal.
|
||||
// select{} was just horrible.
|
||||
c := make(chan os.Signal, 1)
|
||||
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
|
||||
<-c
|
||||
ZoreideBridge.removeIPandBridgeInt()
|
||||
os.Exit(0)
|
||||
|
||||
}
|
|
@ -0,0 +1,67 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net"
|
||||
)
|
||||
|
||||
type AbstractMulticast struct {
|
||||
MIpAddr string
|
||||
MPort string
|
||||
MaxDatagramSize int
|
||||
MWaddr *net.UDPAddr
|
||||
MRaddr *net.UDPAddr
|
||||
Wconn *net.UDPConn
|
||||
Rconn *net.UDPConn
|
||||
}
|
||||
|
||||
func (mip *AbstractMulticast) CreateUdpAddr() {
|
||||
|
||||
// This Will create the local UDP Address
|
||||
addr, err := net.ResolveUDPAddr("udp4", mip.MIpAddr+":"+mip.MPort)
|
||||
if err != nil {
|
||||
log.Fatal(err.Error())
|
||||
}
|
||||
|
||||
mip.MRaddr = addr
|
||||
log.Println("Multicast Listen addr created: ", mip.MRaddr.String())
|
||||
|
||||
// This will create the Writing UDP Addr
|
||||
|
||||
mip.MWaddr = addr
|
||||
log.Println("Multicast Writing addr created: ", mip.MWaddr.String())
|
||||
|
||||
}
|
||||
|
||||
func (mip *AbstractMulticast) CreateWritingSocket() {
|
||||
|
||||
conn, err := net.DialUDP("udp4", nil, mip.MWaddr)
|
||||
if err != nil {
|
||||
log.Fatal(err.Error())
|
||||
}
|
||||
|
||||
mip.Wconn = conn
|
||||
log.Println("Multicast Writing Socket Created: ", mip.Wconn.LocalAddr().String(), "->", mip.Wconn.RemoteAddr().String())
|
||||
|
||||
}
|
||||
func (mip *AbstractMulticast) CreateReadingSocket() {
|
||||
|
||||
// Open up a connection
|
||||
conn, err := net.ListenMulticastUDP("udp", nil, mip.MRaddr)
|
||||
if err != nil {
|
||||
log.Fatal("UDP " + err.Error())
|
||||
}
|
||||
|
||||
conn.SetReadBuffer(mip.MaxDatagramSize)
|
||||
|
||||
mip.Rconn = conn
|
||||
log.Println("Multicast Reading Socket Created: ", mip.Rconn.LocalAddr().String())
|
||||
|
||||
}
|
||||
|
||||
func (mip *AbstractMulticast) GetMulticastReady() {
|
||||
|
||||
mip.CreateUdpAddr()
|
||||
mip.CreateWritingSocket()
|
||||
mip.CreateReadingSocket()
|
||||
}
|
|
@ -0,0 +1,87 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (mip *AbstractMulticast) WriteNumberToMulticast() {
|
||||
|
||||
log.Println("Initiating ticker")
|
||||
|
||||
bstNumber := fmt.Sprintf("%d", ZoreideBridge.hIerarchyNumber)
|
||||
|
||||
for range time.Tick(1 * time.Second) {
|
||||
|
||||
_, err := mip.Wconn.Write([]byte(bstNumber))
|
||||
if err != nil {
|
||||
log.Println("Cannot write to multicast:" + err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (mip *AbstractMulticast) ReadNumberFromMulticast() {
|
||||
|
||||
log.Println("Initiating reader")
|
||||
buffer := make([]byte, mip.MaxDatagramSize)
|
||||
|
||||
// Loop forever reading from the socket
|
||||
for {
|
||||
|
||||
_, _, err := mip.Rconn.ReadFromUDP(buffer)
|
||||
if err != nil {
|
||||
log.Println("ReadFromUDP failed:", err)
|
||||
}
|
||||
|
||||
BstChannel <- string(buffer)
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (b *AbstractBridge) BeTheBeta() {
|
||||
|
||||
log.Println("Inizializing Descalator")
|
||||
|
||||
ownNumber := b.hIerarchyNumber
|
||||
|
||||
for bstNumber := range BstChannel {
|
||||
|
||||
brdNumber, err := strconv.ParseInt(bstNumber, 10, 64)
|
||||
if err != nil {
|
||||
log.Println("Garbage received on multicast: ", bstNumber)
|
||||
log.Println("Cannot convert to int64:", err.Error())
|
||||
continue
|
||||
}
|
||||
|
||||
if brdNumber > ownNumber {
|
||||
log.Println("GULP! There is a bigger one, better descalating")
|
||||
b.IsAlpha = false
|
||||
if b.IsActive {
|
||||
b.removeIPandBridgeInt()
|
||||
b.IsActive = false
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (b *AbstractBridge) WaitForBeAlpha() {
|
||||
|
||||
log.Println("Inizializing Escalator")
|
||||
|
||||
for range time.Tick(5 * time.Second) {
|
||||
|
||||
if b.IsAlpha && !b.IsActive {
|
||||
log.Println("I'm the ALPHA! Get out my path, losers!")
|
||||
b.configureIpAndBridgeUp()
|
||||
b.IsActive = true
|
||||
}
|
||||
|
||||
b.IsAlpha = true
|
||||
}
|
||||
}
|
|
@ -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 Docker, Inc.
|
||||
|
||||
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.
|
|
@ -0,0 +1,16 @@
|
|||
libcontainer
|
||||
Copyright 2012-2015 Docker, Inc.
|
||||
|
||||
This product includes software developed at Docker, Inc. (http://www.docker.com).
|
||||
|
||||
The following is courtesy of our legal counsel:
|
||||
|
||||
|
||||
Use and transfer of Docker may be subject to certain restrictions by the
|
||||
United States and other governments.
|
||||
It is your responsibility to ensure that your use and/or transfer does not
|
||||
violate applicable laws.
|
||||
|
||||
For more information, please see http://www.bis.doc.gov
|
||||
|
||||
See also http://www.apache.org/dev/crypto.html and/or seek legal counsel.
|
|
@ -0,0 +1,2 @@
|
|||
Michael Crosby <michael@crosbymichael.com> (@crosbymichael)
|
||||
Guillaume J. Charmes <guillaume@docker.com> (@creack)
|
|
@ -0,0 +1,31 @@
|
|||
// Packet netlink provide access to low level Netlink sockets and messages.
|
||||
//
|
||||
// Actual implementations are in:
|
||||
// netlink_linux.go
|
||||
// netlink_darwin.go
|
||||
package netlink
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrWrongSockType = errors.New("Wrong socket type")
|
||||
ErrShortResponse = errors.New("Got short response from netlink")
|
||||
ErrInterfaceExists = errors.New("Network interface already exists")
|
||||
)
|
||||
|
||||
// A Route is a subnet associated with the interface to reach it.
|
||||
type Route struct {
|
||||
*net.IPNet
|
||||
Iface *net.Interface
|
||||
Default bool
|
||||
}
|
||||
|
||||
// An IfAddr defines IP network settings for a given network interface
|
||||
type IfAddr struct {
|
||||
Iface *net.Interface
|
||||
IP net.IP
|
||||
IPNet *net.IPNet
|
||||
}
|
File diff suppressed because it is too large
Load Diff
7
vendor/github.com/docker/libcontainer/netlink/netlink_linux_armppc64.go
generated
vendored
Normal file
7
vendor/github.com/docker/libcontainer/netlink/netlink_linux_armppc64.go
generated
vendored
Normal file
|
@ -0,0 +1,7 @@
|
|||
// +build arm ppc64 ppc64le
|
||||
|
||||
package netlink
|
||||
|
||||
func ifrDataByte(b byte) uint8 {
|
||||
return uint8(b)
|
||||
}
|
7
vendor/github.com/docker/libcontainer/netlink/netlink_linux_notarm.go
generated
vendored
Normal file
7
vendor/github.com/docker/libcontainer/netlink/netlink_linux_notarm.go
generated
vendored
Normal file
|
@ -0,0 +1,7 @@
|
|||
// +build !arm,!ppc64,!ppc64le
|
||||
|
||||
package netlink
|
||||
|
||||
func ifrDataByte(b byte) int8 {
|
||||
return int8(b)
|
||||
}
|
88
vendor/github.com/docker/libcontainer/netlink/netlink_unsupported.go
generated
vendored
Normal file
88
vendor/github.com/docker/libcontainer/netlink/netlink_unsupported.go
generated
vendored
Normal file
|
@ -0,0 +1,88 @@
|
|||
// +build !linux
|
||||
|
||||
package netlink
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNotImplemented = errors.New("not implemented")
|
||||
)
|
||||
|
||||
func NetworkGetRoutes() ([]Route, error) {
|
||||
return nil, ErrNotImplemented
|
||||
}
|
||||
|
||||
func NetworkLinkAdd(name string, linkType string) error {
|
||||
return ErrNotImplemented
|
||||
}
|
||||
|
||||
func NetworkLinkDel(name string) error {
|
||||
return ErrNotImplemented
|
||||
}
|
||||
|
||||
func NetworkLinkUp(iface *net.Interface) error {
|
||||
return ErrNotImplemented
|
||||
}
|
||||
|
||||
func NetworkLinkAddIp(iface *net.Interface, ip net.IP, ipNet *net.IPNet) error {
|
||||
return ErrNotImplemented
|
||||
}
|
||||
|
||||
func NetworkLinkDelIp(iface *net.Interface, ip net.IP, ipNet *net.IPNet) error {
|
||||
return ErrNotImplemented
|
||||
}
|
||||
|
||||
func AddRoute(destination, source, gateway, device string) error {
|
||||
return ErrNotImplemented
|
||||
}
|
||||
|
||||
func AddDefaultGw(ip, device string) error {
|
||||
return ErrNotImplemented
|
||||
}
|
||||
|
||||
func NetworkSetMTU(iface *net.Interface, mtu int) error {
|
||||
return ErrNotImplemented
|
||||
}
|
||||
|
||||
func NetworkSetTxQueueLen(iface *net.Interface, txQueueLen int) error {
|
||||
return ErrNotImplemented
|
||||
}
|
||||
|
||||
func NetworkCreateVethPair(name1, name2 string, txQueueLen int) error {
|
||||
return ErrNotImplemented
|
||||
}
|
||||
|
||||
func NetworkChangeName(iface *net.Interface, newName string) error {
|
||||
return ErrNotImplemented
|
||||
}
|
||||
|
||||
func NetworkSetNsFd(iface *net.Interface, fd int) error {
|
||||
return ErrNotImplemented
|
||||
}
|
||||
|
||||
func NetworkSetNsPid(iface *net.Interface, nspid int) error {
|
||||
return ErrNotImplemented
|
||||
}
|
||||
|
||||
func NetworkSetMaster(iface, master *net.Interface) error {
|
||||
return ErrNotImplemented
|
||||
}
|
||||
|
||||
func NetworkLinkDown(iface *net.Interface) error {
|
||||
return ErrNotImplemented
|
||||
}
|
||||
|
||||
func CreateBridge(name string, setMacAddr bool) error {
|
||||
return ErrNotImplemented
|
||||
}
|
||||
|
||||
func DeleteBridge(name string) error {
|
||||
return ErrNotImplemented
|
||||
}
|
||||
|
||||
func AddToBridge(iface, master *net.Interface) error {
|
||||
return ErrNotImplemented
|
||||
}
|
|
@ -0,0 +1,77 @@
|
|||
// +build linux
|
||||
|
||||
package system
|
||||
|
||||
import (
|
||||
"os/exec"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
type ParentDeathSignal int
|
||||
|
||||
func (p ParentDeathSignal) Restore() error {
|
||||
if p == 0 {
|
||||
return nil
|
||||
}
|
||||
current, err := GetParentDeathSignal()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if p == current {
|
||||
return nil
|
||||
}
|
||||
return p.Set()
|
||||
}
|
||||
|
||||
func (p ParentDeathSignal) Set() error {
|
||||
return SetParentDeathSignal(uintptr(p))
|
||||
}
|
||||
|
||||
func Execv(cmd string, args []string, env []string) error {
|
||||
name, err := exec.LookPath(cmd)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return syscall.Exec(name, args, env)
|
||||
}
|
||||
|
||||
func SetParentDeathSignal(sig uintptr) error {
|
||||
if _, _, err := syscall.RawSyscall(syscall.SYS_PRCTL, syscall.PR_SET_PDEATHSIG, sig, 0); err != 0 {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func GetParentDeathSignal() (ParentDeathSignal, error) {
|
||||
var sig int
|
||||
_, _, err := syscall.RawSyscall(syscall.SYS_PRCTL, syscall.PR_GET_PDEATHSIG, uintptr(unsafe.Pointer(&sig)), 0)
|
||||
if err != 0 {
|
||||
return -1, err
|
||||
}
|
||||
return ParentDeathSignal(sig), nil
|
||||
}
|
||||
|
||||
func SetKeepCaps() error {
|
||||
if _, _, err := syscall.RawSyscall(syscall.SYS_PRCTL, syscall.PR_SET_KEEPCAPS, 1, 0); err != 0 {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func ClearKeepCaps() error {
|
||||
if _, _, err := syscall.RawSyscall(syscall.SYS_PRCTL, syscall.PR_SET_KEEPCAPS, 0, 0); err != 0 {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func Setctty() error {
|
||||
if _, _, err := syscall.RawSyscall(syscall.SYS_IOCTL, 0, uintptr(syscall.TIOCSCTTY), 0); err != 0 {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
package system
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// look in /proc to find the process start time so that we can verify
|
||||
// that this pid has started after ourself
|
||||
func GetProcessStartTime(pid int) (string, error) {
|
||||
data, err := ioutil.ReadFile(filepath.Join("/proc", strconv.Itoa(pid), "stat"))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
parts := strings.Split(string(data), " ")
|
||||
// the starttime is located at pos 22
|
||||
// from the man page
|
||||
//
|
||||
// starttime %llu (was %lu before Linux 2.6)
|
||||
// (22) The time the process started after system boot. In kernels before Linux 2.6, this
|
||||
// value was expressed in jiffies. Since Linux 2.6, the value is expressed in clock ticks
|
||||
// (divide by sysconf(_SC_CLK_TCK)).
|
||||
return parts[22-1], nil // starts at 1
|
||||
}
|
|
@ -0,0 +1,40 @@
|
|||
package system
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"runtime"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// Via http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=7b21fddd087678a70ad64afc0f632e0f1071b092
|
||||
//
|
||||
// We need different setns values for the different platforms and arch
|
||||
// We are declaring the macro here because the SETNS syscall does not exist in th stdlib
|
||||
var setNsMap = map[string]uintptr{
|
||||
"linux/386": 346,
|
||||
"linux/arm64": 268,
|
||||
"linux/amd64": 308,
|
||||
"linux/arm": 375,
|
||||
"linux/ppc": 350,
|
||||
"linux/ppc64": 350,
|
||||
"linux/ppc64le": 350,
|
||||
"linux/s390x": 339,
|
||||
}
|
||||
|
||||
var sysSetns = setNsMap[fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH)]
|
||||
|
||||
func SysSetns() uint32 {
|
||||
return uint32(sysSetns)
|
||||
}
|
||||
|
||||
func Setns(fd uintptr, flags uintptr) error {
|
||||
ns, exists := setNsMap[fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH)]
|
||||
if !exists {
|
||||
return fmt.Errorf("unsupported platform %s/%s", runtime.GOOS, runtime.GOARCH)
|
||||
}
|
||||
_, _, err := syscall.RawSyscall(ns, fd, flags, 0)
|
||||
if err != 0 {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
// +build linux,386
|
||||
package system
|
||||
|
||||
import (
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// Setuid sets the uid of the calling thread to the specified uid.
|
||||
func Setuid(uid int) (err error) {
|
||||
_, _, e1 := syscall.RawSyscall(syscall.SYS_SETUID, uintptr(uid), 0, 0)
|
||||
if e1 != 0 {
|
||||
err = e1
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Setgid sets the gid of the calling thread to the specified gid.
|
||||
func Setgid(gid int) (err error) {
|
||||
_, _, e1 := syscall.RawSyscall(syscall.SYS_SETGID32, uintptr(gid), 0, 0)
|
||||
if e1 != 0 {
|
||||
err = e1
|
||||
}
|
||||
return
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
// +build linux,arm64 linux,amd64 linux,ppc linux,ppc64 linux,ppc64le linux,s390x
|
||||
|
||||
package system
|
||||
|
||||
import (
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// Setuid sets the uid of the calling thread to the specified uid.
|
||||
func Setuid(uid int) (err error) {
|
||||
_, _, e1 := syscall.RawSyscall(syscall.SYS_SETUID, uintptr(uid), 0, 0)
|
||||
if e1 != 0 {
|
||||
err = e1
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Setgid sets the gid of the calling thread to the specified gid.
|
||||
func Setgid(gid int) (err error) {
|
||||
_, _, e1 := syscall.RawSyscall(syscall.SYS_SETGID, uintptr(gid), 0, 0)
|
||||
if e1 != 0 {
|
||||
err = e1
|
||||
}
|
||||
return
|
||||
}
|
|
@ -0,0 +1,24 @@
|
|||
// +build linux,arm
|
||||
package system
|
||||
|
||||
import (
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// Setuid sets the uid of the calling thread to the specified uid.
|
||||
func Setuid(uid int) (err error) {
|
||||
_, _, e1 := syscall.RawSyscall(syscall.SYS_SETUID32, uintptr(uid), 0, 0)
|
||||
if e1 != 0 {
|
||||
err = e1
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Setgid sets the gid of the calling thread to the specified gid.
|
||||
func Setgid(gid int) (err error) {
|
||||
_, _, e1 := syscall.RawSyscall(syscall.SYS_SETGID32, uintptr(gid), 0, 0)
|
||||
if e1 != 0 {
|
||||
err = e1
|
||||
}
|
||||
return
|
||||
}
|
|
@ -0,0 +1,12 @@
|
|||
// +build cgo,linux cgo,freebsd
|
||||
|
||||
package system
|
||||
|
||||
/*
|
||||
#include <unistd.h>
|
||||
*/
|
||||
import "C"
|
||||
|
||||
func GetClockTicks() int {
|
||||
return int(C.sysconf(C._SC_CLK_TCK))
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
// +build !cgo windows
|
||||
|
||||
package system
|
||||
|
||||
func GetClockTicks() int {
|
||||
// TODO figure out a better alternative for platforms where we're missing cgo
|
||||
//
|
||||
// TODO Windows. This could be implemented using Win32 QueryPerformanceFrequency().
|
||||
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms644905(v=vs.85).aspx
|
||||
//
|
||||
// An example of its usage can be found here.
|
||||
// https://msdn.microsoft.com/en-us/library/windows/desktop/dn553408(v=vs.85).aspx
|
||||
|
||||
return 100
|
||||
}
|
|
@ -0,0 +1,99 @@
|
|||
package system
|
||||
|
||||
import (
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
var _zero uintptr
|
||||
|
||||
// Returns the size of xattrs and nil error
|
||||
// Requires path, takes allocated []byte or nil as last argument
|
||||
func Llistxattr(path string, dest []byte) (size int, err error) {
|
||||
pathBytes, err := syscall.BytePtrFromString(path)
|
||||
if err != nil {
|
||||
return -1, err
|
||||
}
|
||||
var newpathBytes unsafe.Pointer
|
||||
if len(dest) > 0 {
|
||||
newpathBytes = unsafe.Pointer(&dest[0])
|
||||
} else {
|
||||
newpathBytes = unsafe.Pointer(&_zero)
|
||||
}
|
||||
|
||||
_size, _, errno := syscall.Syscall6(syscall.SYS_LLISTXATTR, uintptr(unsafe.Pointer(pathBytes)), uintptr(newpathBytes), uintptr(len(dest)), 0, 0, 0)
|
||||
size = int(_size)
|
||||
if errno != 0 {
|
||||
return -1, errno
|
||||
}
|
||||
|
||||
return size, nil
|
||||
}
|
||||
|
||||
// Returns a []byte slice if the xattr is set and nil otherwise
|
||||
// Requires path and its attribute as arguments
|
||||
func Lgetxattr(path string, attr string) ([]byte, error) {
|
||||
var sz int
|
||||
pathBytes, err := syscall.BytePtrFromString(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
attrBytes, err := syscall.BytePtrFromString(attr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Start with a 128 length byte array
|
||||
sz = 128
|
||||
dest := make([]byte, sz)
|
||||
destBytes := unsafe.Pointer(&dest[0])
|
||||
_sz, _, errno := syscall.Syscall6(syscall.SYS_LGETXATTR, uintptr(unsafe.Pointer(pathBytes)), uintptr(unsafe.Pointer(attrBytes)), uintptr(destBytes), uintptr(len(dest)), 0, 0)
|
||||
|
||||
switch {
|
||||
case errno == syscall.ENODATA:
|
||||
return nil, errno
|
||||
case errno == syscall.ENOTSUP:
|
||||
return nil, errno
|
||||
case errno == syscall.ERANGE:
|
||||
// 128 byte array might just not be good enough,
|
||||
// A dummy buffer is used ``uintptr(0)`` to get real size
|
||||
// of the xattrs on disk
|
||||
_sz, _, errno = syscall.Syscall6(syscall.SYS_LGETXATTR, uintptr(unsafe.Pointer(pathBytes)), uintptr(unsafe.Pointer(attrBytes)), uintptr(unsafe.Pointer(nil)), uintptr(0), 0, 0)
|
||||
sz = int(_sz)
|
||||
if sz < 0 {
|
||||
return nil, errno
|
||||
}
|
||||
dest = make([]byte, sz)
|
||||
destBytes := unsafe.Pointer(&dest[0])
|
||||
_sz, _, errno = syscall.Syscall6(syscall.SYS_LGETXATTR, uintptr(unsafe.Pointer(pathBytes)), uintptr(unsafe.Pointer(attrBytes)), uintptr(destBytes), uintptr(len(dest)), 0, 0)
|
||||
if errno != 0 {
|
||||
return nil, errno
|
||||
}
|
||||
case errno != 0:
|
||||
return nil, errno
|
||||
}
|
||||
sz = int(_sz)
|
||||
return dest[:sz], nil
|
||||
}
|
||||
|
||||
func Lsetxattr(path string, attr string, data []byte, flags int) error {
|
||||
pathBytes, err := syscall.BytePtrFromString(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
attrBytes, err := syscall.BytePtrFromString(attr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var dataBytes unsafe.Pointer
|
||||
if len(data) > 0 {
|
||||
dataBytes = unsafe.Pointer(&data[0])
|
||||
} else {
|
||||
dataBytes = unsafe.Pointer(&_zero)
|
||||
}
|
||||
_, _, errno := syscall.Syscall6(syscall.SYS_LSETXATTR, uintptr(unsafe.Pointer(pathBytes)), uintptr(unsafe.Pointer(attrBytes)), uintptr(dataBytes), uintptr(len(data)), uintptr(flags), 0)
|
||||
if errno != 0 {
|
||||
return errno
|
||||
}
|
||||
return nil
|
||||
}
|
|
@ -0,0 +1,16 @@
|
|||
# https://editorconfig.org
|
||||
|
||||
root = true
|
||||
|
||||
[*]
|
||||
end_of_line = lf
|
||||
insert_final_newline = true
|
||||
trim_trailing_whitespace = true
|
||||
charset = utf-8
|
||||
indent_style = space
|
||||
|
||||
[Makefile]
|
||||
indent_style = tab
|
||||
|
||||
[*.go]
|
||||
indent_style = tab
|
|
@ -0,0 +1,2 @@
|
|||
/ping
|
||||
/dist
|
|
@ -0,0 +1,6 @@
|
|||
---
|
||||
issues:
|
||||
exclude-rules:
|
||||
- path: _test.go
|
||||
linters:
|
||||
- errcheck
|
|
@ -0,0 +1,46 @@
|
|||
project_name: ping
|
||||
before:
|
||||
hooks:
|
||||
- go mod download
|
||||
builds:
|
||||
- binary: ping
|
||||
dir: cmd/ping
|
||||
goarch:
|
||||
- amd64
|
||||
- arm
|
||||
- arm64
|
||||
goarm:
|
||||
- 6
|
||||
- 7
|
||||
goos:
|
||||
- darwin
|
||||
- freebsd
|
||||
- linux
|
||||
- windows
|
||||
archives:
|
||||
- files:
|
||||
- LICENSE
|
||||
- README.md
|
||||
format_overrides:
|
||||
- goos: windows
|
||||
format: zip
|
||||
wrap_in_directory: true
|
||||
# TODO: Decide if we want packages (name conflcits with /bin/ping?)
|
||||
# nfpms:
|
||||
# homepage: https://github.com/go-ping/ping
|
||||
# maintainer: 'Go Ping Maintainers <go-ping@example.com>'
|
||||
# description: Ping written in Go.
|
||||
# license: MIT
|
||||
# formats:
|
||||
# - deb
|
||||
# - rpm
|
||||
checksum:
|
||||
name_template: 'checksums.txt'
|
||||
snapshot:
|
||||
name_template: "{{ .Tag }}-{{ .ShortCommit }}"
|
||||
changelog:
|
||||
sort: asc
|
||||
filters:
|
||||
exclude:
|
||||
- '^docs:'
|
||||
- '^test:'
|
|
@ -0,0 +1,44 @@
|
|||
# Contributing
|
||||
|
||||
First off, thanks for taking the time to contribute!
|
||||
|
||||
Remember that this is open source software so please consider the other people who will read your code.
|
||||
Make it look nice for them, document your logic in comments and add or update the unit test cases.
|
||||
|
||||
This library is used by various other projects, companies and individuals in live production environments so please discuss any breaking changes with us before making them.
|
||||
Feel free to join us in the #go-ping channel of the [Gophers Slack](https://invite.slack.golangbridge.org/).
|
||||
|
||||
## Pull Requests
|
||||
|
||||
[Fork the repo on GitHub](https://github.com/go-ping/ping/fork) and clone it to your local machine.
|
||||
|
||||
```bash
|
||||
git clone https://github.com/YOUR_USERNAME/ping.git && cd ping
|
||||
```
|
||||
|
||||
Here is a guide on [how to configure a remote repository](https://docs.github.com/en/free-pro-team@latest/github/collaborating-with-issues-and-pull-requests/configuring-a-remote-for-a-fork).
|
||||
|
||||
Check out a new branch, make changes, run tests, commit & sign-off, then push branch to your fork.
|
||||
|
||||
```bash
|
||||
$ git checkout -b <BRANCH_NAME>
|
||||
# edit files
|
||||
$ make style vet test
|
||||
$ git add <CHANGED_FILES>
|
||||
$ git commit -s
|
||||
$ git push <FORK> <BRANCH_NAME>
|
||||
```
|
||||
|
||||
Open a [new pull request](https://github.com/go-ping/ping/compare) in the main `go-ping/ping` repository.
|
||||
Please describe the purpose of your PR and remember link it to any related issues.
|
||||
|
||||
*We may ask you to rebase your feature branch or squash the commits in order to keep the history clean.*
|
||||
|
||||
## Development Guides
|
||||
|
||||
- Run `make style vet test` before committing your changes.
|
||||
- Document your logic in code comments.
|
||||
- Add tests for bug fixes and new features.
|
||||
- Use UNIX-style (LF) line endings.
|
||||
- End every file with a single blank line.
|
||||
- Use the UTF-8 character set.
|
|
@ -0,0 +1,21 @@
|
|||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2016 Cameron Sparr and contributors.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
|
@ -0,0 +1,32 @@
|
|||
GO ?= go
|
||||
GOFMT ?= $(GO)fmt
|
||||
GOOPTS ?=
|
||||
GO111MODULE :=
|
||||
pkgs = ./...
|
||||
|
||||
all: style vet build test
|
||||
|
||||
.PHONY: build
|
||||
build:
|
||||
@echo ">> building ping"
|
||||
GO111MODULE=$(GO111MODULE) $(GO) build $(GOOPTS) ./cmd/ping
|
||||
|
||||
.PHONY: style
|
||||
style:
|
||||
@echo ">> checking code style"
|
||||
@fmtRes=$$($(GOFMT) -d $$(find . -path ./vendor -prune -o -name '*.go' -print)); \
|
||||
if [ -n "$${fmtRes}" ]; then \
|
||||
echo "gofmt checking failed!"; echo "$${fmtRes}"; echo; \
|
||||
echo "Please ensure you are using $$($(GO) version) for formatting code."; \
|
||||
exit 1; \
|
||||
fi
|
||||
|
||||
.PHONY: test
|
||||
test:
|
||||
@echo ">> running all tests"
|
||||
GO111MODULE=$(GO111MODULE) $(GO) test -race -cover $(GOOPTS) $(pkgs)
|
||||
|
||||
.PHONY: vet
|
||||
vet:
|
||||
@echo ">> vetting code"
|
||||
GO111MODULE=$(GO111MODULE) $(GO) vet $(GOOPTS) $(pkgs)
|
|
@ -0,0 +1,141 @@
|
|||
# go-ping
|
||||
[](https://pkg.go.dev/github.com/go-ping/ping)
|
||||
[](https://circleci.com/gh/go-ping/ping)
|
||||
|
||||
A simple but powerful ICMP echo (ping) library for Go, inspired by
|
||||
[go-fastping](https://github.com/tatsushid/go-fastping).
|
||||
|
||||
Here is a very simple example that sends and receives three packets:
|
||||
|
||||
```go
|
||||
pinger, err := ping.NewPinger("www.google.com")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
pinger.Count = 3
|
||||
err = pinger.Run() // Blocks until finished.
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
stats := pinger.Statistics() // get send/receive/duplicate/rtt stats
|
||||
```
|
||||
|
||||
Here is an example that emulates the traditional UNIX ping command:
|
||||
|
||||
```go
|
||||
pinger, err := ping.NewPinger("www.google.com")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// Listen for Ctrl-C.
|
||||
c := make(chan os.Signal, 1)
|
||||
signal.Notify(c, os.Interrupt)
|
||||
go func() {
|
||||
for _ = range c {
|
||||
pinger.Stop()
|
||||
}
|
||||
}()
|
||||
|
||||
pinger.OnRecv = func(pkt *ping.Packet) {
|
||||
fmt.Printf("%d bytes from %s: icmp_seq=%d time=%v\n",
|
||||
pkt.Nbytes, pkt.IPAddr, pkt.Seq, pkt.Rtt)
|
||||
}
|
||||
|
||||
pinger.OnDuplicateRecv = func(pkt *ping.Packet) {
|
||||
fmt.Printf("%d bytes from %s: icmp_seq=%d time=%v ttl=%v (DUP!)\n",
|
||||
pkt.Nbytes, pkt.IPAddr, pkt.Seq, pkt.Rtt, pkt.Ttl)
|
||||
}
|
||||
|
||||
pinger.OnFinish = func(stats *ping.Statistics) {
|
||||
fmt.Printf("\n--- %s ping statistics ---\n", stats.Addr)
|
||||
fmt.Printf("%d packets transmitted, %d packets received, %v%% packet loss\n",
|
||||
stats.PacketsSent, stats.PacketsRecv, stats.PacketLoss)
|
||||
fmt.Printf("round-trip min/avg/max/stddev = %v/%v/%v/%v\n",
|
||||
stats.MinRtt, stats.AvgRtt, stats.MaxRtt, stats.StdDevRtt)
|
||||
}
|
||||
|
||||
fmt.Printf("PING %s (%s):\n", pinger.Addr(), pinger.IPAddr())
|
||||
err = pinger.Run()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
```
|
||||
|
||||
It sends ICMP Echo Request packet(s) and waits for an Echo Reply in
|
||||
response. If it receives a response, it calls the `OnRecv` callback
|
||||
unless a packet with that sequence number has already been received,
|
||||
in which case it calls the `OnDuplicateRecv` callback. When it's
|
||||
finished, it calls the `OnFinish` callback.
|
||||
|
||||
For a full ping example, see
|
||||
[cmd/ping/ping.go](https://github.com/go-ping/ping/blob/master/cmd/ping/ping.go).
|
||||
|
||||
## Installation
|
||||
|
||||
```
|
||||
go get -u github.com/go-ping/ping
|
||||
```
|
||||
|
||||
To install the native Go ping executable:
|
||||
|
||||
```bash
|
||||
go get -u github.com/go-ping/ping/...
|
||||
$GOPATH/bin/ping
|
||||
```
|
||||
|
||||
## Supported Operating Systems
|
||||
|
||||
### Linux
|
||||
This library attempts to send an "unprivileged" ping via UDP. On Linux,
|
||||
this must be enabled with the following sysctl command:
|
||||
|
||||
```
|
||||
sudo sysctl -w net.ipv4.ping_group_range="0 2147483647"
|
||||
```
|
||||
|
||||
If you do not wish to do this, you can call `pinger.SetPrivileged(true)`
|
||||
in your code and then use setcap on your binary to allow it to bind to
|
||||
raw sockets (or just run it as root):
|
||||
|
||||
```
|
||||
setcap cap_net_raw=+ep /path/to/your/compiled/binary
|
||||
```
|
||||
|
||||
See [this blog](https://sturmflut.github.io/linux/ubuntu/2015/01/17/unprivileged-icmp-sockets-on-linux/)
|
||||
and the Go [x/net/icmp](https://godoc.org/golang.org/x/net/icmp) package
|
||||
for more details.
|
||||
|
||||
### Windows
|
||||
|
||||
You must use `pinger.SetPrivileged(true)`, otherwise you will receive
|
||||
the following error:
|
||||
|
||||
```
|
||||
socket: The requested protocol has not been configured into the system, or no implementation for it exists.
|
||||
```
|
||||
|
||||
Despite the method name, this should work without the need to elevate
|
||||
privileges and has been tested on Windows 10. Please note that accessing
|
||||
packet TTL values is not supported due to limitations in the Go
|
||||
x/net/ipv4 and x/net/ipv6 packages.
|
||||
|
||||
### Plan 9 from Bell Labs
|
||||
|
||||
There is no support for Plan 9. This is because the entire `x/net/ipv4`
|
||||
and `x/net/ipv6` packages are not implemented by the Go programming
|
||||
language.
|
||||
|
||||
## Maintainers and Getting Help:
|
||||
|
||||
This repo was originally in the personal account of
|
||||
[sparrc](https://github.com/sparrc), but is now maintained by the
|
||||
[go-ping organization](https://github.com/go-ping).
|
||||
|
||||
For support and help, you usually find us in the #go-ping channel of
|
||||
Gophers Slack. See https://invite.slack.golangbridge.org/ for an invite
|
||||
to the Gophers Slack org.
|
||||
|
||||
## Contributing
|
||||
|
||||
Refer to [CONTRIBUTING.md](https://github.com/go-ping/ping/blob/master/CONTRIBUTING.md)
|
|
@ -0,0 +1,53 @@
|
|||
package ping
|
||||
|
||||
import "log"
|
||||
|
||||
type Logger interface {
|
||||
Fatalf(format string, v ...interface{})
|
||||
Errorf(format string, v ...interface{})
|
||||
Warnf(format string, v ...interface{})
|
||||
Infof(format string, v ...interface{})
|
||||
Debugf(format string, v ...interface{})
|
||||
}
|
||||
|
||||
type StdLogger struct {
|
||||
Logger *log.Logger
|
||||
}
|
||||
|
||||
func (l StdLogger) Fatalf(format string, v ...interface{}) {
|
||||
l.Logger.Printf("FATAL: "+format, v...)
|
||||
}
|
||||
|
||||
func (l StdLogger) Errorf(format string, v ...interface{}) {
|
||||
l.Logger.Printf("ERROR: "+format, v...)
|
||||
}
|
||||
|
||||
func (l StdLogger) Warnf(format string, v ...interface{}) {
|
||||
l.Logger.Printf("WARN: "+format, v...)
|
||||
}
|
||||
|
||||
func (l StdLogger) Infof(format string, v ...interface{}) {
|
||||
l.Logger.Printf("INFO: "+format, v...)
|
||||
}
|
||||
|
||||
func (l StdLogger) Debugf(format string, v ...interface{}) {
|
||||
l.Logger.Printf("DEBUG: "+format, v...)
|
||||
}
|
||||
|
||||
type NoopLogger struct {
|
||||
}
|
||||
|
||||
func (l NoopLogger) Fatalf(format string, v ...interface{}) {
|
||||
}
|
||||
|
||||
func (l NoopLogger) Errorf(format string, v ...interface{}) {
|
||||
}
|
||||
|
||||
func (l NoopLogger) Warnf(format string, v ...interface{}) {
|
||||
}
|
||||
|
||||
func (l NoopLogger) Infof(format string, v ...interface{}) {
|
||||
}
|
||||
|
||||
func (l NoopLogger) Debugf(format string, v ...interface{}) {
|
||||
}
|
|
@ -0,0 +1,103 @@
|
|||