Skip to content
This repository has been archived by the owner on May 26, 2023. It is now read-only.

feat: add support for core-data endpoints #416

Merged
merged 1 commit into from
Oct 20, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions internal/cmd/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,10 @@ func getSelectedServiceKey() string {
}
}

func getCoreDataService() service.Service {
return config.GetCoreService(common.CoreDataServiceKey)
}

func getSelectedServices() map[string]service.Service {
key := getSelectedServiceKey()
if key == "" {
Expand All @@ -54,15 +58,18 @@ func getSelectedServices() map[string]service.Service {

}

func addVerboseFlag(cmd *cobra.Command) {
cmd.Flags().BoolVarP(&verbose, "verbose", "v", false, "show verbose/debug output")
}

func addFormatFlags(cmd *cobra.Command) {
cmd.Flags().BoolVarP(&json, "json", "j", false, "show the raw JSON response")
cmd.Flags().BoolVarP(&verbose, "debug", "d", false, "show verbose/debug output")

}

func addStandardFlags(cmd *cobra.Command) {
addFormatFlags(cmd)
cmd.Flags().BoolVarP(&data, "data", "", false, "use core-data service endpoint")
cmd.Flags().BoolVarP(&data, "data", "d", false, "use core-data service endpoint")
cmd.Flags().BoolVarP(&command, "command", "c", false, "use core-command service endpoint")
cmd.Flags().BoolVarP(&metadata, "metadata", "m", false, "use core-metadata service endpoint")
cmd.Flags().BoolVarP(&scheduler, "scheduler", "s", false, "use support-scheduler service endpoint")
Expand Down
11 changes: 6 additions & 5 deletions internal/cmd/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package cmd

import (
jsonpkg "encoding/json"
"fmt"

"github.com/spf13/cobra"
)
Expand Down Expand Up @@ -48,22 +49,22 @@ func showConfig(cmd *cobra.Command) error {
if json {
return err
} else if verbose {
cmd.Printf("%s: %s: %s\n", serviceName, url, err.Error())
fmt.Printf("%s: %s: %s\n", serviceName, url, err.Error())
siggiskulason marked this conversation as resolved.
Show resolved Hide resolved
}
} else {
if json {
cmd.Println(jsonValue)
fmt.Println(jsonValue)
} else if verbose {
cmd.Printf("%s: %s: %s\n", serviceName, url, jsonValue)
fmt.Printf("%s: %s: %s\n", serviceName, url, jsonValue)
} else {
cmd.Println(serviceName + ":")
fmt.Println(serviceName + ":")
var result map[string]interface{}
jsonpkg.Unmarshal([]byte(jsonValue), &result)
b, err := jsonpkg.MarshalIndent(result["config"], "", " ")
if err != nil {
return err
}
cmd.Println(string(b))
fmt.Println(string(b))
}
}
}
Expand Down
218 changes: 218 additions & 0 deletions internal/cmd/event.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
/*
* Copyright (C) 2021 Canonical Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
* SPDX-License-Identifier: Apache-2.0'
*/

package cmd

import (
"fmt"
"os"
"text/tabwriter"
"time"

"github.com/spf13/cobra"
)

var eventLimit, eventOffset int
var eventDevice, eventProfile, eventSource, readingsValueType string
var eventAge int
var numberOfReadings int

func init() {
eventCmd := initEventCommand()
initListEventCommand(eventCmd)
initCountEventCommand(eventCmd)
initRmEventCommand(eventCmd)
initAddEventCommand(eventCmd)
}

func initEventCommand() *cobra.Command {
var cmd = &cobra.Command{
Use: "event",
Short: "Add, remove and list events",
Long: ``,
SilenceUsage: true,
}

rootCmd.AddCommand(cmd)
return cmd
}

func initListEventCommand(cmd *cobra.Command) {
var listCmd = &cobra.Command{
Use: "list",
Short: "List events",
Long: `List all events, optionally specifying a limit and offset`,
RunE: handleListEvents,
SilenceUsage: true,
}

cmd.AddCommand(listCmd)
addFormatFlags(listCmd)
addVerboseFlag(listCmd)
listCmd.Flags().IntVarP(&eventLimit, "limit", "l", 50, "The number of items to return. Specifying -1 will return all remaining items")
listCmd.Flags().IntVarP(&eventOffset, "offset", "o", 0, "The number of items to skip")
}

func initCountEventCommand(cmd *cobra.Command) {
var countCmd = &cobra.Command{
Use: "count",
Short: "Count available events",
Long: `Count the number of events in core data, optionally filtering by device name`,
RunE: handleCountEvents,
SilenceUsage: true,
}

countCmd.Flags().StringVarP(&eventDevice, "device", "d", "", "Device name")
cmd.AddCommand(countCmd)
addFormatFlags(countCmd)
}

func initRmEventCommand(cmd *cobra.Command) {
var rmCmd = &cobra.Command{
Use: "rm",
Short: "Remove events",
Long: `Remove events, specifying either device name or maximum event age in milliseconds

'edgex-cli event rm --device {devicename}' removes all events for the specified device
'edgex-cli event rm --age {ms}' removes all events generated in the last {ms} milliseconds`,
RunE: handleRmEvents,
SilenceUsage: true,
}

rmCmd.Flags().StringVarP(&eventDevice, "device", "d", "", "Device name")
rmCmd.Flags().IntVarP(&eventAge, "age", "a", 0, "Event age (in milliseconds)")
cmd.AddCommand(rmCmd)
}

func initAddEventCommand(cmd *cobra.Command) {
var addCmd = &cobra.Command{
Use: "add",
Short: "Create an event",
Long: `Create an event with a specified number of random readings`,
siggiskulason marked this conversation as resolved.
Show resolved Hide resolved
RunE: handleAddEvents,
SilenceUsage: true,
}
addCmd.Flags().StringVarP(&eventDevice, "device", "d", "", "Device name")
addCmd.Flags().StringVarP(&eventProfile, "profile", "p", "", "Profile name")
addCmd.Flags().StringVarP(&readingsValueType, "type", "t", "string", "Readings value type [bool | string | uint8 | uint16 | uint32 | uint64 | int8 | int16 | int32 | int64 | float32 | float64 ]")
addCmd.Flags().StringVarP(&eventSource, "source", "s", "", "Event source name (ResourceName or CommandName)")
addCmd.Flags().IntVarP(&numberOfReadings, "readings", "r", 1, "Number of sample readings to create")
addCmd.MarkFlagRequired("device")
addCmd.MarkFlagRequired("profile")
addCmd.MarkFlagRequired("source")
cmd.AddCommand(addCmd)
}

func handleAddEvents(cmd *cobra.Command, args []string) error {
id, err := getCoreDataService().CreateEvent(eventDevice, eventProfile, eventSource, readingsValueType, numberOfReadings)
if err != nil {
return err
}

fmt.Println("Event " + id + " created")
return nil
}

func handleRmEvents(cmd *cobra.Command, args []string) error {
err := getCoreDataService().RemoveEvents(eventDevice, eventAge)
return err
}

func handleCountEvents(cmd *cobra.Command, args []string) error {
if json {
var json string
var err error

if eventDevice != "" {
json, _, err = getCoreDataService().CountEventsByDeviceJSON(eventDevice)
} else {
json, _, err = getCoreDataService().CountEventsJSON()
}

if err != nil {
return err
}
fmt.Print(json)

} else {
count, err := getCoreDataService().CountEvents(eventDevice)
if err != nil {
return err
}
if eventDevice != "" {
fmt.Printf("Total %s events: %v\n", eventDevice, count.Count)
} else {
fmt.Printf("Total events: %v\n", count.Count)
}
}
return nil
}

func handleListEvents(cmd *cobra.Command, args []string) error {
var err error

if json {
var json string

json, _, err = getCoreDataService().ListAllEventsJSON(eventOffset, eventLimit)

if err != nil {
return err
}

fmt.Print(json)

} else {
events, err := getCoreDataService().ListAllEvents(eventOffset, eventLimit)
if err != nil {
return err
}
if len(events) == 0 {
fmt.Println("No events available")
return nil
}

w := tabwriter.NewWriter(os.Stdout, 1, 1, 2, ' ', 0)
if verbose {
fmt.Fprintln(w, "Origin\tDevice\tProfile\tSource\tId\tVersionable\tReadings")
for _, event := range events {
fmt.Fprintf(w, "%v\t%v\t%v\t%v\t%v\t%v\t%v\n",
time.Unix(0, event.Origin).Format(time.RFC822),
event.DeviceName,
event.ProfileName,
event.SourceName,
event.Id,
event.Versionable,
event.Readings)
}

} else {
fmt.Fprintln(w, "Origin\tDevice\tProfile\tSource\tNumber of readings")
for _, event := range events {
tm := time.Unix(0, event.Origin)
sTime := tm.Format(time.RFC822)
nReadings := 0
if event.Readings != nil {
nReadings = len(event.Readings)
}
fmt.Fprintf(w, "%s\t%s\t%s\t%v\t%d\n",
sTime, event.DeviceName, event.ProfileName, event.SourceName, nReadings)
}
}
w.Flush()
}
return nil
}
4 changes: 2 additions & 2 deletions internal/cmd/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,9 @@ func showMetrics(cmd *cobra.Command) error {
return err
} else {
if json {
cmd.Println(jsonValue)
fmt.Println(jsonValue)
} else {
cmd.Printf("%s: %s: %s\n", serviceName, url, jsonValue)
fmt.Printf("%s: %s: %s\n", serviceName, url, jsonValue)
}
}
}
Expand Down
9 changes: 5 additions & 4 deletions internal/cmd/ping.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package cmd

import (
jsonpkg "encoding/json"
"fmt"

"github.com/spf13/cobra"
)
Expand Down Expand Up @@ -49,17 +50,17 @@ func showPing(cmd *cobra.Command) error {
if json {
return err
} else if verbose {
cmd.Printf("%s: %s: %s\n", serviceName, url, err.Error())
fmt.Printf("%s: %s: %s\n", serviceName, url, err.Error())
}
} else {
if json {
cmd.Println(jsonValue)
fmt.Println(jsonValue)
} else if verbose {
cmd.Printf("%s: %s: %s\n", serviceName, url, jsonValue)
fmt.Printf("%s: %s: %s\n", serviceName, url, jsonValue)
} else {
var result map[string]interface{}
jsonpkg.Unmarshal([]byte(jsonValue), &result)
cmd.Println(serviceName + ": " + result["timestamp"].(string))
fmt.Println(serviceName + ": " + result["timestamp"].(string))

}
}
Expand Down
Loading