//setupPurgeReceiver set up the tcp socket where ban messages come //when a purge pattern is received it dispatches it to a Pub object func setupPurgeReceiver(incomingAddress *string, publisher *Publisher) { receiver, err := net.Listen("tcp", *incomingAddress) utils.CheckError(err, logger) go func() { ping := []byte("ping") for { time.Sleep(5 * time.Second) publisher.Pub(ping) } }() for { conn, err := receiver.Accept() utils.CheckError(err, logger) go func(c net.Conn) { defer conn.Close() b, err := ioutil.ReadAll(conn) if err != nil { logger.Info(fmt.Sprintln("Client connection error:", err)) } else { clean_purge := bytes.TrimSpace(b) logger.Info(fmt.Sprintln("<-", utils.ReverseName(conn), string(clean_purge))) publisher.Pub(clean_purge) conn.Write([]byte("OK\n")) } }(conn) } }
//handleVarnishClient is used to forward message received to the client func handleVarnishClient(conn net.Conn, publisher *Publisher, purgeOnStartup bool, secret *string) { defer conn.Close() wait := make(chan bool) client := client.NewVarnishClient(&conn, wait) err := client.AuthenticateIfNeeded(secret) if err != nil { logger.Crit(fmt.Sprintln("Varnish authentication failed:", err)) return } if purgeOnStartup { // flush the whole cache of the new client client.SendPurge([]byte(".*")) } // wait for purges publisher.Sub(client) <-wait // client has quit, clean up publisher.Unsub(client) logger.Info(fmt.Sprintln(utils.ReverseName(conn), "gone")) }
//setupPurgeSenderAndListen start listening to the socket where varnish cli connects //when a client connects it calls handleClient func setupPurgeSenderAndListen(outgoingAddress *string, purgeOnStartup bool, publisher *Publisher, secret *string) { ln, err := net.Listen("tcp", *outgoingAddress) utils.CheckError(err, logger) for { conn, err := ln.Accept() if err != nil { // handle error continue } logger.Info(fmt.Sprintln("New client:", utils.ReverseName(conn))) // connect client to the pubsub purge go handleVarnishClient(conn, publisher, purgeOnStartup, secret) } }