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

Commit

Permalink
Merge branch 'main' of https://github.com/edgexfoundry/edgex-cli into…
Browse files Browse the repository at this point in the history
… add-core-command

� Conflicts:
�	internal/cmd/common.go
  • Loading branch information
MonicaisHer committed Oct 21, 2021
2 parents 337d45e + f76e4f8 commit de53349
Show file tree
Hide file tree
Showing 12 changed files with 713 additions and 91 deletions.
46 changes: 17 additions & 29 deletions .github/PULL_REQUEST_TEMPLATE.md
Original file line number Diff line number Diff line change
@@ -1,35 +1,23 @@
## PR Checklist
Please check if your PR fulfills the following requirements:

- [ ] Tests for the changes have been added (for bug fixes / features)
- [ ] Docs have been added / updated (for bug fixes / features)

**If your build fails** due to your commit message not passing the build checks, please review the guidelines here: https://github.com/edgexfoundry/edgex-cli/blob/master/.github/Contributing.md.

## What is the current behavior?
<!-- Please describe the current behavior and link to a relevant issue. -->


## Issue Number:
<!-- Expected Commit Message Description (imported automatically by GitHub) -->
<!-- Must conform to [conventional commits guidelines](https://github.com/edgexfoundry/edgex-cli/blob/main/.github/Contributing.md) -->
<!-- Expected Commit message must contain Closes/Fixes #IssueNumber statement when there is a related issue -->

<!-- Add additional detailed description of need for change if no related issue -->

## What is the new behavior?
**If your build fails** due to your commit message not passing the build checks, please review the guidelines here: https://github.com/edgexfoundry/edgex-cli/blob/main/.github/Contributing.md

## PR Checklist
Please check if your PR fulfills the following requirements:

## Does this PR introduce a breaking change?
<!-- If this PR contains a breaking change, please describe the impact and migration path for existing applications below. -->

- [ ] Yes
- [ ] No

## New Imports
<!-- Are there any new imports or modules? If so, what are they used for and why? -->

- [ ] Yes
- [ ] No

## Specific Instructions
Are there any specific instructions or things that should be known prior to reviewing?
- [ ] I am not introducing a breaking change (if you are, flag in conventional commit message with `BREAKING CHANGE:` describing the break)
- [ ] I am not introducing a new dependency (add notes below if you are)
- [ ] I have added unit tests for the new feature or bug fix (if not, why?)
- [ ] I have fully tested (add details below) this the new feature or bug fix (if not, why?)
- [ ] I have opened a PR for the related docs change (if not, why?)
<link to docs PR>

## Testing Instructions
<!-- How can the reviewers test your change? -->

## Other information
## New Dependency Instructions (If applicable)
<!-- Please follow [vetting instructions](https://wiki.edgexfoundry.org/display/FA/Vetting+Process+for+3rd+Party+Dependencies) and place results here -->
9 changes: 8 additions & 1 deletion 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 getCoreCommandService() service.Service {
return config.GetCoreService(common.CoreCommandServiceKey)
}
Expand All @@ -58,9 +62,12 @@ 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, "verbose", "v", false, "show verbose/debug output")

}

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())
}
} 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`,
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

0 comments on commit de53349

Please sign in to comment.