func unixgram_coll(_, address string) (Listener, error) { var err error r := new(unixgram_receiver) r.network = "unixgram" r.address = address r.end = make(chan struct{}) r.listener, err = net.ListenUnixgram("unixgram", &net.UnixAddr{address, "unixgram"}) for err != nil { switch err.(type) { case *net.OpError: if err.(*net.OpError).Err.Error() != "bind: address already in use" { return nil, err } default: return nil, err } if _, r_err := os.Stat(address); r_err != nil { return nil, err } os.Remove(address) r.listener, err = net.ListenUnixgram("unixgram", &net.UnixAddr{address, "unixgram"}) } return r, nil }
func (jrnl *JournalReader) Run(dest chan<- Message, errchan chan<- error) { jrnl.end = make(chan bool, 1) conn, err := net.ListenUnixgram("unixgram", &net.UnixAddr{jrnl.Journald, "unixgram"}) for err != nil { switch err.(type) { case *net.OpError: if err.(*net.OpError).Err.Error() != "bind: address already in use" { errchan <- &InputError{jrnl.Driver, jrnl.Id, "listen " + jrnl.Journald, err} return } default: errchan <- &InputError{jrnl.Driver, jrnl.Id, "listen " + jrnl.Journald, err} return } if _, r_err := os.Stat(jrnl.Journald); r_err != nil { errchan <- &InputError{jrnl.Driver, jrnl.Id, "lstat " + jrnl.Journald, err} return } os.Remove(jrnl.Journald) conn, err = net.ListenUnixgram("unixgram", &net.UnixAddr{jrnl.Journald, "unixgram"}) } defer conn.Close() for { select { case <-jrnl.end: return default: buffer := make([]byte, 65536) _, _, err := conn.ReadFrom(buffer) if err != nil { errchan <- &InputError{jrnl.Driver, jrnl.Id, "ReadFrom " + jrnl.Journald, err} return } line := string(bytes.TrimRight(buffer, "\t \n\r\000")) if line == "" { continue } pos := strings.Index(line, ">") if pos > 0 && unicode.IsDigit(rune(line[pos+1])) { dest <- packmsg(jrnl.Id, *message.ParseMessage_5424(line)) } else { dest <- packmsg(jrnl.Id, *message.ParseMessage_3164(line)) } } } }
// Listen starts gorutine that receives syslog messages on specified address. // addr can be a path (for unix domain sockets) or host:port (for UDP). func (s *Server) Listen(addr string) error { var c net.PacketConn if strings.IndexRune(addr, ':') != -1 { a, err := net.ResolveUDPAddr("udp", addr) if err != nil { return err } c, err = net.ListenUDP("udp", a) if err != nil { return err } } else { a, err := net.ResolveUnixAddr("unixgram", addr) if err != nil { return err } c, err = net.ListenUnixgram("unixgram", a) if err != nil { return err } } s.conns = append(s.conns, c) go s.receiver(c) return nil }
func (haProxy *HAProxy) Init() { if len(*logstash) == 0 { logger.Notice("No Logstash host:port set - not sending HAProxy logs.") return } logger.Info(fmt.Sprintf("Connecting to haproxy log socket: %s", haProxy.LogSocket)) // Set the socket HAProxy can write logs to. conn, err := net.ListenUnixgram("unixgram", &net.UnixAddr{haProxy.LogSocket, "unixgram"}) if err != nil { logger.Error("Error while connecting to haproxy log socket: ", err.Error()) return } logger.Info(fmt.Sprintf("Opened Unix socket at: %s. Creating Logstash sender.", haProxy.LogSocket)) logstash := Logstash{ Address: *logstash, Reader: conn, } logstash.Pipe() }
func newProxy(src, dst string) (*unixProxy, error) { os.Remove(src) // start listening local, err := net.ListenUnixgram("unixgram", &net.UnixAddr{ Name: src, Net: "unixgram", }) if err != nil { return nil, err } remote, err := net.DialUnix("unixgram", nil, &net.UnixAddr{ Name: dst, Net: "unixgram", }) if err != nil { return nil, err } return &unixProxy{ local: local, remote: remote, }, nil }
func main() { path := "/tmp/example.sock" addr, err := net.ResolveUnixAddr("unixgram", path) if err != nil { fmt.Printf("ResolveUnixAddr err: %s\n", err) return } conn, err := net.ListenUnixgram("unixgram", addr) if err != nil { fmt.Printf("ListenUnixgram err: %s\n", err) return } // Ensure world writable access os.Chmod(path, 0666) data := make([]byte, 4096) length, _, err := conn.ReadFrom(data) if err != nil { fmt.Printf("conn.ReadFrom error: %s\n", err) return } fmt.Printf("Got: %d bytes\n", length) }
// setupSockets sets up the sockets used to communicate between the client // and the server. If successful it spins up another goroutine to handle // all communication from that client. func (s *Server) setupSockets(remoteID string) { log.Infof("server: dialing client socket") out, err := net.DialUnix( udsType, nil, &net.UnixAddr{path.Join(os.TempDir(), remoteID), udsType}, ) if err != nil { log.Infof("problem dialing client's socket: %s", err) return } log.Infof("server: preparing to listen on new socket") uid := uuid.New() p := path.Join(os.TempDir(), uid) in, err := net.ListenUnixgram(udsType, &net.UnixAddr{p, udsType}) if err != nil { out.Close() log.Infof("could not listen on domain socket %q: %s", p, err) return } log.Infof("server: sending a uid to the client") if err := SetupEncode(uid, out); err != nil { out.Close() log.Infof("problem encoding UUIDv4 for setup: %s", err) return } go s.serveConn(in, out) }
func setUnixSocket(c *C) *net.UnixConn { os.Remove("/tmp/vulcand_trace_test.sock") unixAddr, err := net.ResolveUnixAddr("unixgram", "/tmp/vulcand_trace_test.sock") c.Assert(err, IsNil) conn, err := net.ListenUnixgram("unixgram", unixAddr) c.Assert(err, IsNil) return conn }
// DialServer dials a Unix Domain Socket where a server is listening and // returns a client to the server. func DialServer(uid string) (*Client, error) { // Have the client start listening for responses from the server. clientUID := uuid.New() clientPath := path.Join(os.TempDir(), clientUID) outConn, err := net.ListenUnixgram(udsType, &net.UnixAddr{clientPath, udsType}) if err != nil { return nil, err } // Dial the server. log.Infof("client: dialing the server") setupConn, err := net.DialUnix( udsType, nil, &net.UnixAddr{path.Join(os.TempDir(), uid), udsType}, ) if err != nil { return nil, err } log.Infof("client: sending uid to server") if err := SetupEncode(clientUID, setupConn); err != nil { return nil, err } setupConn.Close() // Get the socket the server is going to listen on. out := bufio.NewReader(outConn) inUUID, err := SetupDecode(out) if err != nil { return nil, err } log.Infof("client: received server uid for conn") // Dial the server. in, err := net.DialUnix( udsType, nil, &net.UnixAddr{path.Join(os.TempDir(), inUUID), udsType}, ) if err != nil { return nil, err } log.Infof("client: dialed server") c := &Client{ inConn: in, outConn: out, reqCh: make(chan request, 50), responses: make(map[uint64]chan response), } go c.send() go c.receive() return c, nil }
func BenchmarkSend(b *testing.B) { conn, _ := net.ListenUnixgram("unixgram", &net.UnixAddr{Name: "@dummy", Net: "unixgram"}) go io.Copy(ioutil.Discard, conn) defer conn.Close() h := &Handle{path: "@dummy"} for i := 0; i < b.N; i++ { h.Send("MESSAGE=hello world") } }
func logListener(socket string) { log.Info("Starting log listener") conn, err := net.ListenUnixgram("unixgram", &net.UnixAddr{socket, "unixgram"}) if err != nil { log.Fatal("listen error:", err) } go logPrinter(conn) }
// TestSdNotify func TestSdNotify(t *testing.T) { testDir, e := ioutil.TempDir("/tmp/", "test-") if e != nil { panic(e) } defer os.RemoveAll(testDir) notifySocket := testDir + "/notify-socket.sock" laddr := net.UnixAddr{ Name: notifySocket, Net: "unixgram", } _, e = net.ListenUnixgram("unixgram", &laddr) if e != nil { panic(e) } tests := []struct { unsetEnv bool envSocket string wsent bool werr bool }{ // (true, nil) - notification supported, data has been sent {false, notifySocket, true, false}, // (false, err) - notification supported, but failure happened {true, testDir + "/missing.sock", false, true}, // (false, nil) - notification not supported {true, "", false, false}, } for i, tt := range tests { must(os.Unsetenv("NOTIFY_SOCKET")) if tt.envSocket != "" { must(os.Setenv("NOTIFY_SOCKET", tt.envSocket)) } sent, err := SdNotify(tt.unsetEnv, fmt.Sprintf("TestSdNotify test message #%d", i)) if sent != tt.wsent { t.Errorf("#%d: expected send result %t, got %t", i, tt.wsent, sent) } if tt.werr && err == nil { t.Errorf("#%d: want non-nil err, got nil", i) } else if !tt.werr && err != nil { t.Errorf("#%d: want nil err, got %v", i, err) } if tt.unsetEnv && tt.envSocket != "" && os.Getenv("NOTIFY_SOCKET") != "" { t.Errorf("#%d: environment variable not cleaned up", i) } } }
// New is the constructor for Server. func NewServer(setupSocket string) (*Server, error) { p := path.Join(os.TempDir(), setupSocket) conn, err := net.ListenUnixgram(udsType, &net.UnixAddr{p, udsType}) if err != nil { return nil, fmt.Errorf("could not listen on domain socket %q: %s", setupSocket, err) } s := &Server{setupConn: conn, registry: make(map[string]*register, 1)} return s, nil }
// TestSdNotify func TestSdNotify(t *testing.T) { notificationSupportedDataSent := "Notification supported, data sent" notificationSupportedFailure := "Notification supported, but failure happened" notificationNotSupported := "Notification not supported" testDir, e := ioutil.TempDir("/tmp/", "test-") if e != nil { panic(e) } defer os.RemoveAll(testDir) notifySocket := testDir + "/notify-socket.sock" laddr := net.UnixAddr{ Name: notifySocket, Net: "unixgram", } _, e = net.ListenUnixgram("unixgram", &laddr) if e != nil { panic(e) } // (true, nil) - notification supported, data has been sent e = os.Setenv("NOTIFY_SOCKET", notifySocket) if e != nil { panic(e) } sent, err := SdNotify(notificationSupportedDataSent) if !sent || err != nil { t.Errorf("TEST: %s FAILED", notificationSupportedDataSent) } // (false, err) - notification supported, but failure happened e = os.Setenv("NOTIFY_SOCKET", testDir+"/not-exist.sock") if e != nil { panic(e) } sent, err = SdNotify(notificationSupportedFailure) if sent && err == nil { t.Errorf("TEST: %s FAILED", notificationSupportedFailure) } // (false, nil) - notification not supported e = os.Unsetenv("NOTIFY_SOCKET") if e != nil { panic(e) } sent, err = SdNotify(notificationNotSupported) if sent || err != nil { t.Errorf("TEST: %s FAILED", notificationNotSupported) } }
func (jrnl *JournalReader) Run(dest chan<- Message) { conn, err := net.ListenUnixgram("unixgram", &net.UnixAddr{jrnl.Journald, "unixgram"}) for err != nil { switch err.(type) { case *net.OpError: if err.(*net.OpError).Err.Error() != "bind: address already in use" { jrnl.errchan <- &InputError{jrnl.Driver, jrnl.Id, "listen " + jrnl.Journald, err} return } default: jrnl.errchan <- &InputError{jrnl.Driver, jrnl.Id, "listen " + jrnl.Journald, err} return } if _, r_err := os.Stat(jrnl.Journald); r_err != nil { jrnl.errchan <- &InputError{jrnl.Driver, jrnl.Id, "lstat " + jrnl.Journald, err} return } os.Remove(jrnl.Journald) conn, err = net.ListenUnixgram("unixgram", &net.UnixAddr{jrnl.Journald, "unixgram"}) } defer conn.Close() for { select { case <-jrnl.end: return default: jrnl.cope_with(conn, make([]byte, 65536), dest) } } }
func (u *UdpInput) Init(config interface{}) (err error) { u.config = config.(*UdpInputConfig) if u.config.Net == "unixgram" { if runtime.GOOS == "windows" { return errors.New( "Can't use Unix datagram sockets on Windows.") } unixAddr, err := net.ResolveUnixAddr(u.config.Net, u.config.Address) if err != nil { return fmt.Errorf("Error resolving unixgram address: %s", err) } u.listener, err = net.ListenUnixgram(u.config.Net, unixAddr) if err != nil { return fmt.Errorf("Error listening on unixgram: %s", err) } // Make sure socket file is world writable. if err = os.Chmod(u.config.Address, 0666); err != nil { return fmt.Errorf("Error changing unixgram socket permissions: %s", err) } } else if len(u.config.Address) > 3 && u.config.Address[:3] == "fd:" { // File descriptor fdStr := u.config.Address[3:] fdInt, err := strconv.ParseUint(fdStr, 0, 0) if err != nil { return fmt.Errorf("Error parsing file descriptor '%s': %s", u.config.Address, err) } fd := uintptr(fdInt) udpFile := os.NewFile(fd, "udpFile") u.listener, err = net.FileConn(udpFile) if err != nil { return fmt.Errorf("Error accessing UDP fd: %s\n", err.Error()) } } else { // IP address udpAddr, err := net.ResolveUDPAddr(u.config.Net, u.config.Address) if err != nil { return fmt.Errorf("ResolveUDPAddr failed: %s\n", err.Error()) } u.listener, err = net.ListenUDP(u.config.Net, udpAddr) if err != nil { return fmt.Errorf("ListenUDP failed: %s\n", err.Error()) } } u.stopChan = make(chan struct{}) return }
func (devlog *DevLogReader) Run(dest chan<- Message) { conn, err := net.ListenUnixgram("unixgram", &net.UnixAddr{devlog.Devlog, "unixgram"}) for err != nil { switch err.(type) { case *net.OpError: if err.(*net.OpError).Err.Error() != "bind: address already in use" { devlog.errchan <- &InputError{devlog.Driver, devlog.Id, "Listen " + devlog.Devlog, err} return } default: devlog.errchan <- &InputError{devlog.Driver, devlog.Id, "Listen " + devlog.Devlog, err} return } if _, r_err := os.Stat(devlog.Devlog); r_err != nil { devlog.errchan <- &InputError{devlog.Driver, devlog.Id, "lstat " + devlog.Devlog, err} return } os.Remove(devlog.Devlog) conn, err = net.ListenUnixgram("unixgram", &net.UnixAddr{devlog.Devlog, "unixgram"}) } defer conn.Close() for { select { case <-devlog.end: return default: devlog.cope_with(conn, make([]byte, 65536), dest) } } }
//Configure the server for listen on an unix datagram socket func (s *Server) ListenUnixgram(addr string) error { unixAddr, err := net.ResolveUnixAddr("unixgram", addr) if err != nil { return err } connection, err := net.ListenUnixgram("unixgram", unixAddr) if err != nil { return err } connection.SetReadBuffer(datagramReadBufferSize) s.connections = append(s.connections, connection) return nil }
func (syslog Syslog) run() { if _, err := os.Stat(socketPath); nil == err { os.Remove(socketPath) } connection, error := net.ListenUnixgram("unixgram", &net.UnixAddr{socketPath, "unixgram"}) if nil != error { log.Fatal("Listen error:", error) } if err := os.Chmod(socketPath, 0777); nil != err { log.Fatal("Impossible to change the socket permission.") } syslog.listen(connection) }
func TestListenUnixgramReadFrom(t *testing.T) { switch runtime.GOOS { case "linux": // run this on linux. default: t.Logf("skipping test on %q", runtime.GOOS) return } // TODO: use mktmp to create this file. path := "/tmp/example.sock" addr, err := net.ResolveUnixAddr("unixgram", path) if err != nil { t.Fatalf("ResolveUnixAddr failed on %v: %v", path, err) return } //var reader *net.UnixConn reader, err := net.ListenUnixgram("unixgram", addr) if err != nil { t.Fatalf("ListenUnixgram failed on %v: %v", path, err) return } defer reader.Close() // Make something that writes to it. writer, err := net.DialUnix("unixgram", nil, addr) if err != nil { t.Fatalf("DialUnix failed: %v", err) return } defer writer.Close() expected := "Hello world" writer.Write([]byte(expected)) actual := make([]byte, 100) length, _, err := reader.ReadFrom(actual) if err != nil { t.Fatalf("UnixConn.ReadFromfailed: %v", err) } if string(actual[0:length]) != expected { t.Fatalf("Expected %v, got %v", expected, actual) } }
func main() { conn, err := net.ListenUnixgram("unixgram", &net.UnixAddr{"/tmp/unixdomain", "unixgram"}) if err != nil { log.Fatalln(err) } fmt.Println("Server listening for incoming messages") var buf [1024]byte for { n, err := conn.Read(buf[:]) if err != nil { log.Fatalln(err) } fmt.Printf("%s\n", string(buf[:n])) } }
func listen() (listener, error) { dir, err := ioutil.TempDir("", "sdnotify") if err != nil { return listener{}, err } path := filepath.Join(dir, "notify.sock") conn, err := net.ListenUnixgram(netType, &net.UnixAddr{ Net: netType, Name: path, }) if err != nil { return listener{}, err } l := listener{ Path: path, tempDir: dir, conn: conn} return l, nil }
// Listen starts gorutine that receives syslog messages on specified address. // addr can be a path (for unix domain sockets) or host:port (for UDP). func (s *Server) Listen(netType, addr string) error { var c net.Conn switch netType { case "udp": a, err := net.ResolveUDPAddr("udp", addr) if err != nil { return err } c, err = net.ListenUDP("udp", a) if err != nil { return err } case "unix": a, err := net.ResolveUnixAddr("unixgram", addr) if err != nil { return err } c, err = net.ListenUnixgram("unixgram", a) if err != nil { return err } case "tcp": a, err := net.ResolveTCPAddr("tcp", addr) if err != nil { return err } conn, err := net.ListenTCP("tcp", a) if err != nil { return err } c, err = conn.Accept() if err != nil { return err } } s.conns = append(s.conns, c) go s.receiver(c) return nil }
// Listen starts gorutine that receives syslog messages on specified address. // addr can be a path (for unix domain sockets) or host:port (for UDP). func (s *UDPServer) Run() { var c net.PacketConn if strings.IndexRune(s.uri, ':') != -1 { a, err := net.ResolveUDPAddr("udp", s.uri) if err != nil { panic(err) } c, err = net.ListenUDP("udp", a) if err != nil { panic(err) } } else { a, err := net.ResolveUnixAddr("unixgram", s.uri) if err != nil { panic(err) } c, err = net.ListenUnixgram("unixgram", a) if err != nil { panic(err) } } s.conn = c go s.receiver() }
func TestUnixConnSpecificMethods(t *testing.T) { switch runtime.GOOS { case "plan9", "windows": t.Logf("skipping test on %q", runtime.GOOS) return } p1, p2, p3 := "/tmp/gotest.net1", "/tmp/gotest.net2", "/tmp/gotest.net3" os.Remove(p1) os.Remove(p2) os.Remove(p3) a1, err := net.ResolveUnixAddr("unixgram", p1) if err != nil { t.Fatalf("net.ResolveUnixAddr failed: %v", err) } c1, err := net.DialUnix("unixgram", a1, nil) if err != nil { t.Fatalf("net.DialUnix failed: %v", err) } c1.LocalAddr() c1.RemoteAddr() c1.SetDeadline(time.Now().Add(100 * time.Millisecond)) c1.SetReadDeadline(time.Now().Add(100 * time.Millisecond)) c1.SetWriteDeadline(time.Now().Add(100 * time.Millisecond)) c1.SetReadBuffer(2048) c1.SetWriteBuffer(2048) defer c1.Close() defer os.Remove(p1) a2, err := net.ResolveUnixAddr("unixgram", p2) if err != nil { t.Errorf("net.ResolveUnixAddr failed: %v", err) return } c2, err := net.DialUnix("unixgram", a2, nil) if err != nil { t.Errorf("net.DialUnix failed: %v", err) return } c2.LocalAddr() c2.RemoteAddr() c2.SetDeadline(time.Now().Add(100 * time.Millisecond)) c2.SetReadDeadline(time.Now().Add(100 * time.Millisecond)) c2.SetWriteDeadline(time.Now().Add(100 * time.Millisecond)) c2.SetReadBuffer(2048) c2.SetWriteBuffer(2048) defer c2.Close() defer os.Remove(p2) a3, err := net.ResolveUnixAddr("unixgram", p3) if err != nil { t.Errorf("net.ResolveUnixAddr failed: %v", err) return } c3, err := net.ListenUnixgram("unixgram", a3) if err != nil { t.Errorf("net.ListenUnixgram failed: %v", err) return } c3.LocalAddr() c3.RemoteAddr() c3.SetDeadline(time.Now().Add(100 * time.Millisecond)) c3.SetReadDeadline(time.Now().Add(100 * time.Millisecond)) c3.SetWriteDeadline(time.Now().Add(100 * time.Millisecond)) c3.SetReadBuffer(2048) c3.SetWriteBuffer(2048) defer c3.Close() defer os.Remove(p3) wb := []byte("UNIXCONN TEST") rb1 := make([]byte, 128) rb2 := make([]byte, 128) rb3 := make([]byte, 128) if _, _, err := c1.WriteMsgUnix(wb, nil, a2); err != nil { t.Errorf("net.UnixConn.WriteMsgUnix failed: %v", err) return } if _, _, _, _, err := c2.ReadMsgUnix(rb2, nil); err != nil { t.Errorf("net.UnixConn.ReadMsgUnix failed: %v", err) return } if _, err := c2.WriteToUnix(wb, a1); err != nil { t.Errorf("net.UnixConn.WriteToUnix failed: %v", err) return } if _, _, err := c1.ReadFromUnix(rb1); err != nil { t.Errorf("net.UnixConn.ReadFromUnix failed: %v", err) return } if _, err := c3.WriteToUnix(wb, a1); err != nil { t.Errorf("net.UnixConn.WriteToUnix failed: %v", err) return } if _, _, err := c1.ReadFromUnix(rb1); err != nil { t.Errorf("net.UnixConn.ReadFromUnix failed: %v", err) return } if _, err := c2.WriteToUnix(wb, a3); err != nil { t.Errorf("net.UnixConn.WriteToUnix failed: %v", err) return } if _, _, err := c3.ReadFromUnix(rb3); err != nil { t.Errorf("net.UnixConn.ReadFromUnix failed: %v", err) return } if f, err := c1.File(); err != nil { t.Errorf("net.UnixConn.File failed: %v", err) return } else { f.Close() } }
func (u *UdpInput) Init(config interface{}) (err error) { u.config = config.(*UdpInputConfig) if u.config.Net == "unixgram" { if runtime.GOOS == "windows" { return errors.New( "Can't use Unix datagram sockets on Windows.") } unixAddr, err := net.ResolveUnixAddr(u.config.Net, u.config.Address) if err != nil { return fmt.Errorf("Error resolving unixgram address: %s", err) } u.listener, err = net.ListenUnixgram(u.config.Net, unixAddr) if err != nil { return fmt.Errorf("Error listening on unixgram: %s", err) } // Make sure socket file is world writable. if err = os.Chmod(u.config.Address, 0666); err != nil { return fmt.Errorf("Error changing unixgram socket permissions: ", err) } } else if len(u.config.Address) > 3 && u.config.Address[:3] == "fd:" { // File descriptor fdStr := u.config.Address[3:] fdInt, err := strconv.ParseUint(fdStr, 0, 0) if err != nil { return fmt.Errorf("Error parsing file descriptor '%s': %s", u.config.Address, err) } fd := uintptr(fdInt) udpFile := os.NewFile(fd, "udpFile") u.listener, err = net.FileConn(udpFile) if err != nil { return fmt.Errorf("Error accessing UDP fd: %s\n", err.Error()) } } else { // IP address udpAddr, err := net.ResolveUDPAddr(u.config.Net, u.config.Address) if err != nil { return fmt.Errorf("ResolveUDPAddr failed: %s\n", err.Error()) } u.listener, err = net.ListenUDP(u.config.Net, udpAddr) if err != nil { return fmt.Errorf("ListenUDP failed: %s\n", err.Error()) } } if u.config.ParserType == "message.proto" { mp := NewMessageProtoParser() u.parser = mp u.parseFunction = NetworkMessageProtoParser if u.config.Decoder == "" { return fmt.Errorf("The message.proto parser must have a decoder") } } else if u.config.ParserType == "regexp" { rp := NewRegexpParser() u.parser = rp u.parseFunction = NetworkPayloadParser if err = rp.SetDelimiter(u.config.Delimiter); err != nil { return err } if err = rp.SetDelimiterLocation(u.config.DelimiterLocation); err != nil { return err } } else if u.config.ParserType == "token" { tp := NewTokenParser() u.parser = tp u.parseFunction = NetworkPayloadParser switch len(u.config.Delimiter) { case 0: // no value was set, the default provided by the StreamParser will be used case 1: tp.SetDelimiter(u.config.Delimiter[0]) default: return fmt.Errorf("invalid delimiter: %s", u.config.Delimiter) } } else { return fmt.Errorf("unknown parser type: %s", u.config.ParserType) } u.parser.SetMinimumBufferSize(1024 * 64) u.stopChan = make(chan struct{}) return }
func TestZeusBoots(t *testing.T) { if os.Getenv("ZEUS_LISTENER_BINARY") == "" { t.Fatal("Missing ZEUS_LISTENER_BINARY env var") } dir, err := ioutil.TempDir("", "zeus_test") if err != nil { t.Fatal(err) } defer os.RemoveAll(dir) if err := writeTestFiles(dir); err != nil { t.Fatal(err) } config.ConfigFile = filepath.Join(dir, "zeus.json") unixsocket.SetZeusSockName(filepath.Join(dir, ".zeus.sock")) connections := map[string]*net.UnixConn{ "cmd": nil, "data": nil, "code": nil, } for name := range connections { sockName := filepath.Join(dir, fmt.Sprintf("%s.sock", name)) c, err := net.ListenUnixgram("unixgram", &net.UnixAddr{ Name: sockName, Net: "unixgram", }) if err != nil { t.Fatalf("Error opening %q socket: %v", sockName, err) } defer c.Close() connections[name] = c } me, err := os.FindProcess(os.Getpid()) if err != nil { t.Fatal(err) } if err := os.Chdir(dir); err != nil { t.Fatal(err) } // TODO: Find a way to redirect stdout so we can look for crashed // processes. enableTracing() zexit := make(chan int) go func() { zexit <- zeusmaster.Run() }() expects := map[string]string{ // TODO: Use the zeusclient to spawn a command to test // that path. // "cmd": "pong", "data": "YAML the Camel is a Mammal with Enamel", "code": "Hello, world!", } for name, want := range expects { if err := readAndCompare(connections[name], want); err != nil { t.Fatalf("%s: %v", name, err) } } // TODO: It appears the filewatcher takes some time to initialize // so we need to wait for it to propagate before changing things. // Even then there appears to be a bad enough race somewhere that // we get flaky tests if we change more than one file. time.Sleep(1 * time.Second) for _, f := range []string{"code.rb" /*, "data.yaml"*/} { from := filepath.Join(dir, fmt.Sprintf("other-%s", f)) to := filepath.Join(dir, f) if err := os.Rename(from, to); err != nil { t.Fatalf("Error renaming %s: %v", f, err) } } expects = map[string]string{ // "data": "Hi", "code": "there!", } for name, want := range expects { if err := readAndCompare(connections[name], want); err != nil { t.Fatalf("%s: %v", name, err) } } // The zeusmaster catches the interrupt and exits gracefully me.Signal(os.Interrupt) if code := <-zexit; code != 0 { t.Fatalf("Zeus exited with %d", code) } }
func (u *UdpInput) Init(config interface{}) (err error) { u.config = config.(*UdpInputConfig) if u.config.Net == "unixgram" { if runtime.GOOS == "windows" { return errors.New( "Can't use Unix datagram sockets on Windows.") } if runtime.GOOS != "linux" && strings.HasPrefix(u.config.Address, "@") { return errors.New( "Abstract sockets are linux-specific.") } if u.config.SetHostname { return errors.New( "Can't set Hostname from Unix datagram.") } unixAddr, err := net.ResolveUnixAddr(u.config.Net, u.config.Address) if err != nil { return fmt.Errorf("Error resolving unixgram address: %s", err) } u.listener, err = net.ListenUnixgram(u.config.Net, unixAddr) if err != nil { return fmt.Errorf("Error listening on unixgram: %s", err) } // Ensure socket file is world writable, unless socket is abstract. if !strings.HasPrefix(u.config.Address, "@") { if err = os.Chmod(u.config.Address, 0666); err != nil { return fmt.Errorf( "Error changing unixgram socket permissions: %s", err) } } } else if len(u.config.Address) > 3 && u.config.Address[:3] == "fd:" { // File descriptor if u.config.SetHostname { return errors.New( "Can't set Hostname from file descriptor.") } fdStr := u.config.Address[3:] fdInt, err := strconv.ParseUint(fdStr, 0, 0) if err != nil { return fmt.Errorf("Error parsing file descriptor '%s': %s", u.config.Address, err) } fd := uintptr(fdInt) udpFile := os.NewFile(fd, "udpFile") u.listener, err = net.FileConn(udpFile) if err != nil { return fmt.Errorf("Error accessing UDP fd: %s\n", err.Error()) } } else { // IP address udpAddr, err := net.ResolveUDPAddr(u.config.Net, u.config.Address) if err != nil { return fmt.Errorf("ResolveUDPAddr failed: %s\n", err.Error()) } u.listener, err = net.ListenUDP(u.config.Net, udpAddr) if err != nil { return fmt.Errorf("ListenUDP failed: %s\n", err.Error()) } if u.config.SetHostname { u.reader = UdpInputReader{ u.listener.(*net.UDPConn), u, } } } u.stopChan = make(chan struct{}) return }
func (s *TraceSuite) TestHandler(c *C) { os.Remove("/tmp/vulcand_trace_test.sock") unixAddr, err := net.ResolveUnixAddr("unixgram", "/tmp/vulcand_trace_test.sock") c.Assert(err, IsNil) conn, err := net.ListenUnixgram("unixgram", unixAddr) c.Assert(err, IsNil) defer conn.Close() outC := make(chan []byte, 1000) closeC := make(chan bool) defer close(closeC) go func() { for { buf := make([]byte, 65536) bytes, err := conn.Read(buf) if err != nil { return } outbuf := make([]byte, bytes) copy(outbuf, buf) select { case <-closeC: return case outC <- outbuf: continue } } }() responder := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { w.Header().Add("X-Resp-A", "h2") w.Write([]byte("hello")) }) h, err := New("syslog:///tmp/vulcand_trace_test.sock", []string{"X-Req-A"}, []string{"X-Resp-A"}) c.Assert(err, IsNil) handler, err := h.NewHandler(responder) c.Assert(err, IsNil) srv := httptest.NewServer(handler) defer srv.Close() re, _, err := testutils.Get(srv.URL+"/hello", testutils.Header("X-Req-A", "yo")) c.Assert(err, IsNil) c.Assert(re.StatusCode, Equals, http.StatusOK) var buf []byte select { case buf = <-outC: case <-time.After(10 * time.Millisecond): c.Fatalf("timeout") } vals := strings.Split(string(buf), SyslogPrefix) var r *oxytrace.Record c.Assert(json.Unmarshal([]byte(vals[1]), &r), IsNil) c.Assert(r.Request.URL, Equals, "/hello") c.Assert(r.Request.Headers, DeepEquals, http.Header{"X-Req-A": []string{"yo"}}) c.Assert(r.Response.Headers, DeepEquals, http.Header{"X-Resp-A": []string{"h2"}}) }