Skip to content

Commit

Permalink
Address issues (#9)
Browse files Browse the repository at this point in the history
* Show terminal errors without -v flag. Closes #6

* Started configure command

* Add configure command. Closes #7

* Update README

* update readme

* Allow short name as an option
  • Loading branch information
derekbekoe authored Mar 3, 2019
1 parent d3b4946 commit f799685
Show file tree
Hide file tree
Showing 3 changed files with 114 additions and 23 deletions.
30 changes: 19 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,11 @@ Hello world

## Configuration

Set configuration with the `convey configure` command.
```bash
convey configure --nats-url nats://localhost:4222 --nats-cluster test-cluster
```

By default, configuration is loaded from `$HOME/.convey.yaml`.

This is an example of `.convey.yaml`:
Expand All @@ -57,26 +62,29 @@ go run main.go
go build -o bin/convey
```

## Platform Builds
## Host your own NATS Streaming Server

**Deploy to a local Docker container**

```bash
go get github.com/mitchellh/gox
gox -ldflags "-X github.com/derekbekoe/convey/cmd.VersionGitCommit=$(git rev-list -1 HEAD) -X github.com/derekbekoe/convey/cmd.VersionGitTag=VERSION" -os="linux darwin" -arch="amd64" -output="bin/{{.Dir}}_{{.OS}}_{{.Arch}}"
docker run -p 4222:4222 nats-streaming:linux
convey configure --nats-url nats://localhost:4222 --nats-cluster test-cluster
```
See https://golang.org/doc/install/source#environment

## Starting NATS Streaming Server
**Deploy to an Azure Container Instance**

note: We only include this as an illustration to keep the command simple as traffic is not encrypted.
```bash
docker run -p 4223:4223 -p 8223:8223 nats-streaming:linux -p 4223 -m 8223
az container create --image nats-streaming:linux --ports 4222 --ip-address Public -g RG -n nats1
convey configure --nats-url nats://<IPADDRESS>:4222 --nats-cluster test-cluster
```

OR

**Deploy to Azure Container Instances**
We only include this as an illustration to keep the command simple as traffic is not encrypted.
## Platform Builds
```bash
az container create --image nats-streaming:linux --ports 4222 8222 --ip-address Public -g RG -n nats1
go get github.com/mitchellh/gox
gox -ldflags "-X github.com/derekbekoe/convey/cmd.VersionGitCommit=$(git rev-list -1 HEAD) -X github.com/derekbekoe/convey/cmd.VersionGitTag=VERSION" -os="linux darwin" -arch="amd64" -output="bin/{{.Dir}}_{{.OS}}_{{.Arch}}"
```
See https://golang.org/doc/install/source#environment

## FAQ

Expand Down
63 changes: 63 additions & 0 deletions cmd/configure.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package cmd

import (
"fmt"
"path"

homedir "github.com/mitchellh/go-homedir"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)

var natsURL string
var natsClusterID string
var useShortName bool
var forceWrite bool

func init() {
rootCmd.AddCommand(configureCmd)
configureCmd.PersistentFlags().StringVar(&natsURL, "nats-url", "", "NATS server url")
configureCmd.PersistentFlags().StringVar(&natsClusterID, "nats-cluster", "", "NATS cluster id")
configureCmd.PersistentFlags().BoolVar(&useShortName, "short-name", false, "Use short channel names. Channel conflicts may occur.")
configureCmd.PersistentFlags().BoolVar(&forceWrite, "overwrite", false, "Overwrite current configuration")
}

var configureCmd = &cobra.Command{
Use: "configure",
Short: "Configure Convey",
Run: ConfigureCommandFunc,
}

// ConfigureCommandFunc is a handler for the configure command
func ConfigureCommandFunc(cmd *cobra.Command, args []string) {
viper.Set(configKeyNatsURL, natsURL)
viper.Set(configKeyNatsClusterID, natsClusterID)
viper.Set(configKeyUseShortName, useShortName)

// If a config file is found, read it in.
configFileExists := false
if err := viper.ReadInConfig(); err == nil {
configFileExists = true
}

// If config file doesn't exist and it hasn't been set in viper, set it
if !configFileExists && viper.ConfigFileUsed() == "" {
home, err := homedir.Dir()
if err != nil {
errorExit(err.Error())
}
viper.SetConfigFile(path.Join(home, ".convey.yaml"))
}

configFilePath := viper.ConfigFileUsed()

if forceWrite || !configFileExists {
err := viper.WriteConfigAs(configFilePath)
if err != nil {
errorExit(err.Error())
}
} else {
msg := fmt.Sprintf("Config file exists. Use --overwrite to overwrite the config file at %s", configFilePath)
errorExit(msg)
}
}
44 changes: 32 additions & 12 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import (
"strings"
"syscall"

"github.com/docker/docker/pkg/namesgenerator"
homedir "github.com/mitchellh/go-homedir"
stan "github.com/nats-io/go-nats-streaming"
uuid "github.com/satori/go.uuid"
Expand All @@ -38,10 +39,16 @@ var verbose bool

const configKeyNatsURL = "NatsURL"
const configKeyNatsClusterID = "NatsClusterID"
const configKeyUseShortName = "UseShortName"

// ETX is End Of Text Sequence
var ETX = []byte{3}

func errorExit(msg string) {
fmt.Fprintln(os.Stderr, msg)
os.Exit(1)
}

// positionalArgsValidator valids the positional args
func positionalArgsValidator(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
Expand Down Expand Up @@ -69,25 +76,29 @@ func RootCommandFunc(cmd *cobra.Command, args []string) {
} else if len(args) == 1 {
SubscribeModeFunc(args[0])
} else {
log.Fatal("Too many args")
errorExit("Too many args")
}
}

func createChannelName() string {
func createChannelNameUUID() string {
u1, err := uuid.NewV1()
if err != nil {
s := fmt.Sprintf("Failed to create channel name: %s\n", err)
log.Fatal(s)
errorExit(s)
}
// Remove dashes from UUID to make copy-paste easier in terminal
return strings.Replace(u1.String(), "-", "", -1)
}

func createChannelNameShort() string {
return namesgenerator.GetRandomName(0)
}

func getClientID(prefix string) string {
u1, err := uuid.NewV1()
if err != nil {
s := fmt.Sprintf("Failed to create client ID: %s\n", err)
log.Fatal(s)
errorExit(s)
}
return fmt.Sprintf("%s-%s", prefix, u1.String())
}
Expand All @@ -98,7 +109,10 @@ func connectToStan(clientID string) stan.Conn {
natsClusterID := viper.GetString(configKeyNatsClusterID)

if natsURL == "" || natsClusterID == "" {
log.Fatalf("The configuration options '%s' and '%s' must be set.", configKeyNatsURL, configKeyNatsClusterID)
s := fmt.Sprintf("The configuration options '%s' and '%s' are not set. Use `convey configure` to set.",
configKeyNatsURL,
configKeyNatsClusterID)
errorExit(s)
}

sc, err := stan.Connect(
Expand All @@ -109,7 +123,8 @@ func connectToStan(clientID string) stan.Conn {
log.Printf("Lost connection due to error - %s", err)
}))
if err != nil {
log.Fatalf("Failed to connect to streaming server due to error - %s", err)
s := fmt.Sprintf("Failed to connect to streaming server due to error - %s", err)
errorExit(s)
}
return sc
}
Expand All @@ -119,7 +134,13 @@ func PublishModeFunc() {
clientID := getClientID("convey-pub")
sc := connectToStan(clientID)

channelName := createChannelName()
useShortName := viper.GetBool(configKeyUseShortName)
channelName := ""
if useShortName {
channelName = createChannelNameShort()
} else {
channelName = createChannelNameUUID()
}

// Print channel to console for user to copy
fmt.Println(channelName)
Expand Down Expand Up @@ -168,7 +189,8 @@ func SubscribeModeFunc(channelName string) {
}, stan.DeliverAllAvailable())

if subErr != nil {
log.Fatalf("Failed to subscribe to channel %s due to error %s", channelName, subErr)
s := fmt.Sprintf("Failed to subscribe to channel %s due to error %s", channelName, subErr)
errorExit(s)
}

<-doneSubscribe
Expand All @@ -181,8 +203,7 @@ func SubscribeModeFunc(channelName string) {
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
errorExit(err.Error())
}
}

Expand All @@ -206,8 +227,7 @@ func initConfig() {
// Find home directory.
home, err := homedir.Dir()
if err != nil {
fmt.Println(err)
os.Exit(1)
errorExit(err.Error())
}

// Search config in home directory with name ".convey" (without extension).
Expand Down

0 comments on commit f799685

Please sign in to comment.