Skip to content

Commit

Permalink
Merge pull request #31 from overmindtech/new-commands
Browse files Browse the repository at this point in the history
New commands: start-change, end-change, create-bookmark
  • Loading branch information
DavidS-ovm authored Aug 3, 2023
2 parents 9c730e6 + 2b32439 commit fdb5e58
Show file tree
Hide file tree
Showing 6 changed files with 369 additions and 6 deletions.
135 changes: 135 additions & 0 deletions cmd/createbookmark.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
package cmd

import (
"context"
"encoding/json"
"fmt"
"io"
"os"
"os/signal"
"syscall"
"time"

"github.com/bufbuild/connect-go"
"github.com/google/uuid"
"github.com/overmindtech/ovm-cli/tracing"
"github.com/overmindtech/sdp-go"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
)

// createBookmarkCmd represents the get-bookmark command
var createBookmarkCmd = &cobra.Command{
Use: "create-bookmark [--file FILE]",
Short: "Creates a bookmark from JSON.",
PreRun: func(cmd *cobra.Command, args []string) {
// Bind these to viper
err := viper.BindPFlags(cmd.Flags())
if err != nil {
log.WithError(err).Fatal("could not bind `create-bookmark` flags")
}
},
Run: func(cmd *cobra.Command, args []string) {
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)

exitcode := CreateBookmark(sigs, nil)
tracing.ShutdownTracer()
os.Exit(exitcode)
},
}

func CreateBookmark(signals chan os.Signal, ready chan bool) int {
timeout, err := time.ParseDuration(viper.GetString("timeout"))
if err != nil {
log.Errorf("invalid --timeout value '%v', error: %v", viper.GetString("timeout"), err)
return 1
}

in := os.Stdin
if viper.GetString("file") != "" {
in, err = os.Open(viper.GetString("file"))
if err != nil {
log.WithError(err).WithFields(log.Fields{
"file": viper.GetString("file"),
}).Error("failed to open input")
return 1
}
}

ctx := context.Background()
ctx, span := tracing.Tracer().Start(ctx, "CLI CreateBookmark", trace.WithAttributes(
attribute.String("om.config", fmt.Sprintf("%v", viper.AllSettings())),
))
defer span.End()

ctx, err = ensureToken(ctx, signals)
if err != nil {
log.WithContext(ctx).WithError(err).WithFields(log.Fields{
"url": viper.GetString("url"),
}).Error("failed to authenticate")
return 1
}

// apply a timeout to the main body of processing
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()

contents, err := io.ReadAll(in)
if err != nil {
log.WithContext(ctx).WithError(err).Error("failed to read file")
return 1
}
msg := sdp.BookmarkProperties{}
err = json.Unmarshal(contents, &msg)
if err != nil {
log.WithContext(ctx).WithError(err).Error("failed to parse input")
return 1
}
client := AuthenticatedBookmarkClient(ctx)
response, err := client.CreateBookmark(ctx, &connect.Request[sdp.CreateBookmarkRequest]{
Msg: &sdp.CreateBookmarkRequest{
Properties: &msg,
},
})
if err != nil {
log.WithContext(ctx).WithError(err).WithFields(log.Fields{
"bookmark-url": viper.GetString("bookmark-url"),
}).Error("failed to get bookmark")
return 1
}
log.WithContext(ctx).WithFields(log.Fields{
"bookmark-uuid": uuid.UUID(response.Msg.Bookmark.Metadata.UUID),
"bookmark-created": response.Msg.Bookmark.Metadata.Created,
"bookmark-name": response.Msg.Bookmark.Properties.Name,
"bookmark-description": response.Msg.Bookmark.Properties.Description,
}).Info("created bookmark")
for _, q := range response.Msg.Bookmark.Properties.Queries {
log.WithContext(ctx).WithFields(log.Fields{
"bookmark-query": q,
}).Info("created bookmark query")
}
for _, i := range response.Msg.Bookmark.Properties.ExcludedItems {
log.WithContext(ctx).WithFields(log.Fields{
"bookmark-excluded-item": i,
}).Info("created bookmark excluded item")
}

b, _ := json.MarshalIndent(response.Msg.Bookmark.Properties, "", " ")
log.Info(string(b))

return 0
}

func init() {
rootCmd.AddCommand(createBookmarkCmd)

createBookmarkCmd.PersistentFlags().String("bookmark-url", "", "The bookmark service API endpoint (defaults to --url)")

createBookmarkCmd.PersistentFlags().String("file", "", "JSON formatted file to read bookmark. (defaults to stdin)")

createBookmarkCmd.PersistentFlags().String("timeout", "1m", "How long to wait for responses")
}
108 changes: 108 additions & 0 deletions cmd/endchange.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
package cmd

import (
"context"
"fmt"
"os"
"os/signal"
"syscall"
"time"

"github.com/bufbuild/connect-go"
"github.com/google/uuid"
"github.com/overmindtech/ovm-cli/tracing"
"github.com/overmindtech/sdp-go"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
)

// endChangeCmd represents the end-change command
var endChangeCmd = &cobra.Command{
Use: "end-change --uuid ID",
Short: "Finishes the specified change. Call this just after you finished the change. This will store a snapshot of the current system state for later reference.",
PreRun: func(cmd *cobra.Command, args []string) {
// Bind these to viper
err := viper.BindPFlags(cmd.Flags())
if err != nil {
log.WithError(err).Fatal("could not bind `end-change` flags")
}
},
Run: func(cmd *cobra.Command, args []string) {
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)

exitcode := EndChange(sigs, nil)
tracing.ShutdownTracer()
os.Exit(exitcode)
},
}

func EndChange(signals chan os.Signal, ready chan bool) int {
timeout, err := time.ParseDuration(viper.GetString("timeout"))
if err != nil {
log.Errorf("invalid --timeout value '%v', error: %v", viper.GetString("timeout"), err)
return 1
}

snapshotUuid, err := uuid.Parse(viper.GetString("uuid"))
if err != nil {
log.Errorf("invalid --uuid value '%v', error: %v", viper.GetString("uuid"), err)
return 1
}

ctx := context.Background()
ctx, span := tracing.Tracer().Start(ctx, "CLI EndChange", trace.WithAttributes(
attribute.String("om.config", fmt.Sprintf("%v", viper.AllSettings())),
))
defer span.End()

lf := log.Fields{
"uuid": snapshotUuid.String(),
}

ctx, err = ensureToken(ctx, signals)
if err != nil {
log.WithContext(ctx).WithFields(lf).WithError(err).Error("failed to authenticate")
return 1
}

// apply a timeout to the main body of processing
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()

// snapClient := AuthenticatedSnapshotsClient(ctx)
client := AuthenticatedChangesClient(ctx)
stream, err := client.EndChange(ctx, &connect.Request[sdp.EndChangeRequest]{
Msg: &sdp.EndChangeRequest{
ChangeUUID: snapshotUuid[:],
},
})
if err != nil {
log.WithContext(ctx).WithFields(lf).WithError(err).Error("failed to start change")
return 1
}
log.WithContext(ctx).WithFields(lf).Info("processing")
for stream.Receive() {
msg := stream.Msg()
log.WithContext(ctx).WithFields(lf).WithFields(log.Fields{
"state": msg.State,
"items": msg.NumItems,
"edges": msg.NumEdges,
}).Info("progress")
}
log.WithContext(ctx).WithFields(lf).Info("started change")
return 0
}

func init() {
rootCmd.AddCommand(endChangeCmd)

endChangeCmd.PersistentFlags().String("frontend", "https://app.overmind.tech/", "The frontend base URL")

endChangeCmd.PersistentFlags().String("uuid", "", "The UUID of the snapshot that should be displayed.")

endChangeCmd.PersistentFlags().String("timeout", "1m", "How long to wait for responses")
}
8 changes: 6 additions & 2 deletions cmd/getbookmark.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package cmd

import (
"context"
"encoding/json"
"fmt"
"os"
"os/signal"
Expand Down Expand Up @@ -84,7 +85,7 @@ func GetBookmark(signals chan os.Signal, ready chan bool) int {
return 1
}
log.WithContext(ctx).WithFields(log.Fields{
"bookmark-uuid": response.Msg.Bookmark.Metadata.UUID,
"bookmark-uuid": uuid.UUID(response.Msg.Bookmark.Metadata.UUID),
"bookmark-created": response.Msg.Bookmark.Metadata.Created,
"bookmark-name": response.Msg.Bookmark.Properties.Name,
"bookmark-description": response.Msg.Bookmark.Properties.Description,
Expand All @@ -99,14 +100,17 @@ func GetBookmark(signals chan os.Signal, ready chan bool) int {
"bookmark-excluded-item": i,
}).Info("found bookmark excluded item")
}

b, _ := json.MarshalIndent(response.Msg.Bookmark.Properties, "", " ")
log.Info(string(b))

return 0
}

func init() {
rootCmd.AddCommand(getBookmarkCmd)

getBookmarkCmd.PersistentFlags().String("bookmark-url", "", "The bookmark service API endpoint (defaults to --url)")
getBookmarkCmd.PersistentFlags().String("frontend", "https://app.overmind.tech/", "The frontend base URL")

getBookmarkCmd.PersistentFlags().String("uuid", "", "The UUID of the bookmark that should be displayed.")

Expand Down
5 changes: 1 addition & 4 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -233,10 +233,7 @@ func init() {
}

log.AddHook(otellogrus.NewHook(otellogrus.WithLevels(
log.PanicLevel,
log.FatalLevel,
log.ErrorLevel,
log.WarnLevel,
log.AllLevels[:log.GetLevel()]...,
)))
}
// shut down tracing at the end of the process
Expand Down
Loading

0 comments on commit fdb5e58

Please sign in to comment.