0

I'm using this to receive SNMP traps: https://github.com/soniah/gosnmp Now, lets say I want to programmatically break out of the (taken from here):

err := tl.Listen("0.0.0.0:9162")

What are my best approaches to this?

I'm somewhat new to Golang and didnt find a way to break out of a goroutine that I have no way of modifying ("3rd party").

Thanks,

snoofkin
  • 8,725
  • 14
  • 49
  • 86
  • 1
    From a quick examination, it does not appear that you can. `TrapListener` should have exposed a `Close()` or `Shutdown()` method that closed the underlying network listener. –  Oct 10 '17 at 16:12
  • Exactly! I thought though, that there is some way to do that. thanks – snoofkin Oct 10 '17 at 16:15
  • 3
    Possible duplicate of [cancel a blocking operation in Go](https://stackoverflow.com/questions/28240133/cancel-a-blocking-operation-in-go/28240299#28240299); and [Goroutine execution inside an http handler](https://stackoverflow.com/questions/31116870/goroutine-execution-inside-an-http-handler/31116947#31116947). – icza Oct 10 '17 at 16:17
  • this may help: https://rakyll.org/leakingctx/ https://blog.golang.org/context – Yandry Pozo Oct 10 '17 at 17:28

2 Answers2

5

Short answer: You can't. There's no way to kill a goroutine (short of killing the entire program) from outside the goroutine.

Long answer: A goroutine can listen for some sort of "terminate" signal (via channels, signals, or any other mechanism). But ultimately, the goroutine must terminate from within.

Looking at the library in your example, it appears this functionality is not provided.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
1

Standard https://golang.org/pkg/net/#Conn interface provides special methods SetDeadline (together with SetReadDeadline and SetWriteDeadline) to set a hard connection break time for staled connections. As I see in the source code:

type GoSNMP struct {
    // Conn is net connection to use, typically established using GoSNMP.Connect()
    Conn net.Conn
     ...

    // Timeout is the timeout for the SNMP Query
    Timeout time.Duration
    ...

net.Conn interface is exported - so you may try to get direct access to it to set up a deadline.

type TrapListener struct {
    OnNewTrap func(s *SnmpPacket, u *net.UDPAddr)
    Params    *GoSNMP
    ...
}

In its turn TrapListener exports GoSNMP struct so you may have access to it. Try this:

tl := TrapListener{...}
tl.Params.Conn.SetDeadline(time.Now().Add(1*time.Second))
tl.Listen(...)

However this line disensures me - looks like it doesn't use stored connection and its options:

func (t *TrapListener) Listen(addr string) (err error) {
    ...
    conn, err := net.ListenUDP("udp", udpAddr)
    ....
}

But you may try :)

Eugene Lisitsky
  • 12,113
  • 5
  • 38
  • 59