| 1 |
// Copyright 2018-2022 The NATS Authors |
| 2 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 |
// you may not use this file except in compliance with the License. |
| 4 |
// You may obtain a copy of the License at |
| 5 |
// |
| 6 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
// |
| 8 |
// Unless required by applicable law or agreed to in writing, software |
| 9 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 |
// See the License for the specific language governing permissions and |
| 12 |
// limitations under the License. |
| 13 |
|
| 14 |
package main |
| 15 |
|
| 16 |
import ( |
| 17 |
"encoding/json" |
| 18 |
"flag" |
| 19 |
"fmt" |
| 20 |
"io" |
| 21 |
"log" |
| 22 |
"net/http" |
| 23 |
"os" |
| 24 |
"os/signal" |
| 25 |
"runtime" |
| 26 |
"syscall" |
| 27 |
"time" |
| 28 |
|
| 29 |
"github.com/nats-io/nats.go" |
| 30 |
) |
| 31 |
|
| 32 |
// NOTE: Can test with demo servers. |
| 33 |
// nats-echo -s demo.nats.io <subject> |
| 34 |
|
| 35 |
func usage() { |
| 36 |
log.Printf("Usage: nats-echo [-s server] [-creds file] [-t] <subject>\n") |
| 37 |
flag.PrintDefaults() |
| 38 |
} |
| 39 |
|
| 40 |
func showUsageAndExit(exitcode int) { |
| 41 |
usage() |
| 42 |
os.Exit(exitcode) |
| 43 |
} |
| 44 |
|
| 45 |
func printMsg(m *nats.Msg, i int) { |
| 46 |
log.Printf("[#%d] Echoing from [%s] to [%s]: %q", i, m.Subject, m.Reply, m.Data) |
| 47 |
} |
| 48 |
|
| 49 |
func printStatusMsg(m *nats.Msg, i int) { |
| 50 |
log.Printf("[#%d] Sending status from [%s] to [%s]: %q", i, m.Subject, m.Reply, m.Data) |
| 51 |
} |
| 52 |
|
| 53 |
type serviceStatus struct { |
| 54 |
Id string `json:"id"` |
| 55 |
Geo string `json:"geo"` |
| 56 |
} |
| 57 |
|
| 58 |
func main() { |
| 59 |
var urls = flag.String("s", nats.DefaultURL, "The nats server URLs (separated by comma)") |
| 60 |
var userCreds = flag.String("creds", "", "User Credentials File") |
| 61 |
var nkeyFile = flag.String("nkey", "", "NKey Seed File") |
| 62 |
var serviceId = flag.String("id", "NATS Echo Service", "Identifier for this service") |
| 63 |
var showTime = flag.Bool("t", false, "Display timestamps") |
| 64 |
var showHelp = flag.Bool("h", false, "Show help message") |
| 65 |
var geoloc = flag.Bool("geo", false, "Display geo location of echo service") |
| 66 |
var geo string = "unknown" |
| 67 |
|
| 68 |
log.SetFlags(0) |
| 69 |
flag.Usage = usage |
| 70 |
flag.Parse() |
| 71 |
|
| 72 |
if *showHelp { |
| 73 |
showUsageAndExit(0) |
| 74 |
} |
| 75 |
|
| 76 |
args := flag.Args() |
| 77 |
if len(args) != 1 { |
| 78 |
showUsageAndExit(1) |
| 79 |
} |
| 80 |
|
| 81 |
// Lookup geo if requested |
| 82 |
if *geoloc { |
| 83 |
geo = lookupGeo() |
| 84 |
} |
| 85 |
// Connect Options. |
| 86 |
opts := []nats.Option{nats.Name(*serviceId)} |
| 87 |
opts = setupConnOptions(opts) |
| 88 |
|
| 89 |
if *userCreds != "" && *nkeyFile != "" { |
| 90 |
log.Fatal("specify -seed or -creds") |
| 91 |
} |
| 92 |
|
| 93 |
// Use UserCredentials |
| 94 |
if *userCreds != "" { |
| 95 |
opts = append(opts, nats.UserCredentials(*userCreds)) |
| 96 |
} |
| 97 |
|
| 98 |
// Use Nkey authentication. |
| 99 |
if *nkeyFile != "" { |
| 100 |
opt, err := nats.NkeyOptionFromSeed(*nkeyFile) |
| 101 |
if err != nil { |
| 102 |
log.Fatal(err) |
| 103 |
} |
| 104 |
opts = append(opts, opt) |
| 105 |
} |
| 106 |
|
| 107 |
// Connect to NATS |
| 108 |
nc, err := nats.Connect(*urls, opts...) |
| 109 |
if err != nil { |
| 110 |
log.Fatal(err) |
| 111 |
} |
| 112 |
|
| 113 |
subj, iEcho, iStatus := args[0], 0, 0 |
| 114 |
statusSubj := subj + ".status" |
| 115 |
|
| 116 |
nc.QueueSubscribe(subj, "echo", func(msg *nats.Msg) { |
| 117 |
iEcho++ |
| 118 |
printMsg(msg, iEcho) |
| 119 |
if msg.Reply != "" { |
| 120 |
// Just echo back what they sent us. |
| 121 |
var payload []byte |
| 122 |
if geo != "unknown" { |
| 123 |
payload = []byte(fmt.Sprintf("[%s]: %q", geo, msg.Data)) |
| 124 |
} else { |
| 125 |
payload = msg.Data |
| 126 |
} |
| 127 |
nc.Publish(msg.Reply, payload) |
| 128 |
} |
| 129 |
}) |
| 130 |
nc.Subscribe(statusSubj, func(msg *nats.Msg) { |
| 131 |
iStatus++ |
| 132 |
printStatusMsg(msg, iStatus) |
| 133 |
if msg.Reply != "" { |
| 134 |
payload, _ := json.Marshal(&serviceStatus{Id: *serviceId, Geo: geo}) |
| 135 |
nc.Publish(msg.Reply, payload) |
| 136 |
} |
| 137 |
}) |
| 138 |
nc.Flush() |
| 139 |
|
| 140 |
if err := nc.LastError(); err != nil { |
| 141 |
log.Fatal(err) |
| 142 |
} |
| 143 |
|
| 144 |
log.Printf("Echo Service ID: [%s]", *serviceId) |
| 145 |
log.Printf("Echo Service listening on [%s]\n", subj) |
| 146 |
log.Printf("Echo Service (Status) listening on [%s]\n", statusSubj) |
| 147 |
|
| 148 |
// Now handle signal to terminate so we can drain on exit. |
| 149 |
c := make(chan os.Signal, 1) |
| 150 |
signal.Notify(c, syscall.SIGINT) |
| 151 |
|
| 152 |
go func() { |
| 153 |
// Wait for signal |
| 154 |
<-c |
| 155 |
log.Printf("<caught signal - draining>") |
| 156 |
nc.Drain() |
| 157 |
}() |
| 158 |
|
| 159 |
if *showTime { |
| 160 |
log.SetFlags(log.LstdFlags) |
| 161 |
} |
| 162 |
|
| 163 |
runtime.Goexit() |
| 164 |
} |
| 165 |
|
| 166 |
func setupConnOptions(opts []nats.Option) []nats.Option { |
| 167 |
totalWait := 10 * time.Minute |
| 168 |
reconnectDelay := time.Second |
| 169 |
|
| 170 |
opts = append(opts, nats.ReconnectWait(reconnectDelay)) |
| 171 |
opts = append(opts, nats.MaxReconnects(int(totalWait/reconnectDelay))) |
| 172 |
opts = append(opts, nats.DisconnectErrHandler(func(nc *nats.Conn, err error) { |
| 173 |
if !nc.IsClosed() { |
| 174 |
log.Printf("Disconnected due to: %s, will attempt reconnects for %.0fm", err, totalWait.Minutes()) |
| 175 |
} |
| 176 |
})) |
| 177 |
opts = append(opts, nats.ReconnectHandler(func(nc *nats.Conn) { |
| 178 |
log.Printf("Reconnected [%s]", nc.ConnectedUrl()) |
| 179 |
})) |
| 180 |
opts = append(opts, nats.ClosedHandler(func(nc *nats.Conn) { |
| 181 |
if !nc.IsClosed() { |
| 182 |
log.Fatal("Exiting: no servers available") |
| 183 |
} else { |
| 184 |
log.Fatal("Exiting") |
| 185 |
} |
| 186 |
})) |
| 187 |
return opts |
| 188 |
} |
| 189 |
|
| 190 |
// We only want region, country |
| 191 |
type geo struct { |
| 192 |
// There are others.. |
| 193 |
Region string |
| 194 |
Country string |
| 195 |
} |
| 196 |
|
| 197 |
// lookup our current region and country.. |
| 198 |
func lookupGeo() string { |
| 199 |
c := &http.Client{Timeout: 2 * time.Second} |
| 200 |
|
| 201 |
url := os.Getenv("ECHO_SVC_GEO_URL") |
| 202 |
if len(url) == 0 { |
| 203 |
url = "https://ipapi.co/json" |
| 204 |
} |
| 205 |
|
| 206 |
resp, err := c.Get(url) |
| 207 |
if err != nil || resp == nil { |
| 208 |
log.Fatalf("Could not retrieve geo location data: %v", err) |
| 209 |
} |
| 210 |
defer resp.Body.Close() |
| 211 |
body, _ := io.ReadAll(resp.Body) |
| 212 |
g := geo{} |
| 213 |
if err := json.Unmarshal(body, &g); err != nil { |
| 214 |
log.Fatalf("Error unmarshalling geo: %v", err) |
| 215 |
} |
| 216 |
return g.Region + ", " + g.Country |
| 217 |
} |