SEBA-580 cordctl CLI for XOS
Change-Id: I807821a12d3d0fe4aee89791e2fe46e973da8eda
diff --git a/Gopkg.toml b/Gopkg.toml
new file mode 100644
index 0000000..8b8b7a0
--- /dev/null
+++ b/Gopkg.toml
@@ -0,0 +1,54 @@
+# Gopkg.toml example
+#
+# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md
+# for detailed Gopkg.toml documentation.
+#
+# required = ["github.com/user/thing/cmd/thing"]
+# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"]
+#
+# [[constraint]]
+# name = "github.com/user/project"
+# version = "1.0.0"
+#
+# [[constraint]]
+# name = "github.com/user/project2"
+# branch = "dev"
+# source = "github.com/myfork/project2"
+#
+# [[override]]
+# name = "github.com/x/y"
+# version = "2.4.0"
+#
+# [prune]
+# non-go = false
+# go-tests = true
+# unused-packages = true
+
+
+[[constraint]]
+ name = "github.com/fullstorydev/grpcurl"
+ version = "1.2.1"
+
+[[constraint]]
+ name = "github.com/golang/protobuf"
+ version = "1.3.1"
+
+[[constraint]]
+ name = "github.com/jessevdk/go-flags"
+ version = "1.4.0"
+
+[[constraint]]
+ name = "github.com/jhump/protoreflect"
+ version = "1.2.0"
+
+[[constraint]]
+ name = "google.golang.org/grpc"
+ version = "1.20.1"
+
+[[constraint]]
+ name = "gopkg.in/yaml.v2"
+ version = "2.2.2"
+
+[prune]
+ go-tests = true
+ unused-packages = true
diff --git a/LICENSE.md b/LICENSE.md
new file mode 100644
index 0000000..261eeb9
--- /dev/null
+++ b/LICENSE.md
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ 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.
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..8ed55fc
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,39 @@
+ifeq ($(GOPATH),)
+$(error Please set your GOPATH)
+endif
+
+VERSION=$(shell cat $(GOPATH)/src/github.com/opencord/cordctl/VERSION)
+GITCOMMIT=$(shell git log --pretty=format:"%h" -n 1)
+GOVERSION=$(shell go version 2>&1 | sed -E 's/.*(go[0-9]+\.[0-9]+\.[0-9]+).*/\1/g')
+OSTYPE=$(shell uname -s | tr A-Z a-z)
+OSARCH=$(shell uname -p | tr A-Z a-z)
+BUILDTIME=$(shell date -u +"%Y-%m-%dT%H:%M:%SZ")
+
+LDFLAGS=-ldflags \
+ '-X "github.com/opencord/cordctl/cli/version.Version=$(VERSION)" \
+ -X "github.com/opencord/cordctl/cli/version.GitCommit=$(GITCOMMIT)" \
+ -X "github.com/opencord/cordctl/cli/version.GoVersion=$(GOVERSION)" \
+ -X "github.com/opencord/cordctl/cli/version.Os=$(OSTYPE)" \
+ -X "github.com/opencord/cordctl/cli/version.Arch=$(OSARCH)" \
+ -X "github.com/opencord/cordctl/cli/version.BuildTime=$(BUILDTIME)"' \
+
+help:
+
+build: dependencies
+ go build $(LDFLAGS) cmd/cordctl.go
+
+dependencies:
+ dep ensure
+
+lint: dependencies
+ find $(GOPATH)/src/github.com/opencord/cordctl -name "*.go" -not -path '$(GOPATH)/src/github.com/opencord/cordctl/vendor/*' | xargs gofmt -l
+ go vet ./...
+ dep check
+
+test: dependencies
+ @mkdir -p ./tests/results
+ @go test -v -coverprofile ./tests/results/go-test-coverage.out -covermode count ./... 2>&1 | tee ./tests/results/go-test-results.out ;\
+ RETURN=$$? ;\
+ go-junit-report < ./tests/results/go-test-results.out > ./tests/results/go-test-results.xml ;\
+ gocover-cobertura < ./tests/results/go-test-coverage.out > ./tests/results/go-test-coverage.xml ;\
+ exit $$RETURN
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..5a1b8e3
--- /dev/null
+++ b/README.md
@@ -0,0 +1,11 @@
+TODO: This readme will discuss cordctl
+
+# Development Environment
+
+To run unit tests, `go-junit-report` and `gocover-obertura` tools must be installed. One way to do this is to install them with `go get`, and then ensure your `GOPATH` is part of your `PATH` (editing your `~/.profile` as necessary).
+
+```bash
+go get -u github.com/jstemmer/go-junit-report
+go get -u github.com/t-yuki/gocover-cobertura
+```
+
diff --git a/VERSION b/VERSION
new file mode 100644
index 0000000..05639a5
--- /dev/null
+++ b/VERSION
@@ -0,0 +1 @@
+1.0.0-dev
diff --git a/cli/version/version.go b/cli/version/version.go
new file mode 100644
index 0000000..dcae592
--- /dev/null
+++ b/cli/version/version.go
@@ -0,0 +1,29 @@
+/*
+ * Portions copyright 2019-present Open Networking Foundation
+ * Original copyright 2019-present Ciena Corporation
+ *
+ * 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.
+ */
+package version
+
+// Default build-time variable.
+// These values can (should) be overridden via ldflags when built with
+// `make`
+var (
+ Version = "unknown-version"
+ GoVersion = "unknown-goversion"
+ GitCommit = "unknown-commit"
+ BuildTime = "unknown-buildtime"
+ Os = "unknown-os"
+ Arch = "unknown-arch"
+)
diff --git a/cmd/cordctl.go b/cmd/cordctl.go
new file mode 100644
index 0000000..7648182
--- /dev/null
+++ b/cmd/cordctl.go
@@ -0,0 +1,51 @@
+/*
+ * Portions copyright 2019-present Open Networking Foundation
+ * Original copyright 2019-present Ciena Corporation
+ *
+ * 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.
+ */
+package main
+
+import (
+ flags "github.com/jessevdk/go-flags"
+ "github.com/opencord/cordctl/commands"
+ "os"
+ "path"
+)
+
+func main() {
+
+ parser := flags.NewNamedParser(path.Base(os.Args[0]), flags.Default|flags.PassAfterNonOption)
+ _, err := parser.AddGroup("Global Options", "", &commands.GlobalOptions)
+ if err != nil {
+ panic(err)
+ }
+ commands.RegisterModelCommands(parser)
+ commands.RegisterServiceCommands(parser)
+ commands.RegisterTransferCommands(parser)
+ commands.RegisterVersionCommands(parser)
+
+ _, err = parser.ParseArgs(os.Args[1:])
+ if err != nil {
+ _, ok := err.(*flags.Error)
+ if ok {
+ real := err.(*flags.Error)
+ if real.Type == flags.ErrHelp {
+ return
+ }
+ } else {
+ panic(err)
+ }
+ os.Exit(1)
+ }
+}
diff --git a/commands/command.go b/commands/command.go
new file mode 100644
index 0000000..329fee1
--- /dev/null
+++ b/commands/command.go
@@ -0,0 +1,179 @@
+/*
+ * Portions copyright 2019-present Open Networking Foundation
+ * Original copyright 2019-present Ciena Corporation
+ *
+ * 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.
+ */
+package commands
+
+import (
+ "encoding/json"
+ "fmt"
+ "github.com/opencord/cordctl/format"
+ "google.golang.org/grpc"
+ "gopkg.in/yaml.v2"
+ "io/ioutil"
+ "log"
+ "os"
+ "strings"
+ "time"
+)
+
+type OutputType uint8
+
+const (
+ OUTPUT_TABLE OutputType = iota
+ OUTPUT_JSON
+ OUTPUT_YAML
+)
+
+var CharReplacer = strings.NewReplacer("\\t", "\t", "\\n", "\n")
+
+type GrpcConfigSpec struct {
+ Timeout time.Duration `yaml:"timeout"`
+}
+
+type TlsConfigSpec struct {
+ UseTls bool `yaml:"useTls"`
+ CACert string `yaml:"caCert"`
+ Cert string `yaml:"cert"`
+ Key string `yaml:"key"`
+ Verify string `yaml:"verify"`
+}
+
+type GlobalConfigSpec struct {
+ ApiVersion string `yaml:"apiVersion"`
+ Server string `yaml:"server"`
+ Username string `yaml:"username"`
+ Password string `yaml:"password"`
+ Tls TlsConfigSpec `yaml:"tls"`
+ Grpc GrpcConfigSpec
+}
+
+var GlobalConfig = GlobalConfigSpec{
+ ApiVersion: "v1",
+ Server: "localhost",
+ Tls: TlsConfigSpec{
+ UseTls: false,
+ },
+ Grpc: GrpcConfigSpec{
+ Timeout: time.Second * 10,
+ },
+}
+
+var GlobalOptions struct {
+ Config string `short:"c" long:"config" env:"CORDCONFIG" value-name:"FILE" default:"" description:"Location of client config file"`
+ Server string `short:"s" long:"server" default:"" value-name:"SERVER:PORT" description:"IP/Host and port of XOS"`
+ Username string `short:"u" long:"username" value-name:"USERNAME" default:"" description:"Username to authenticate with XOS"`
+ Password string `short:"p" long:"password" value-name:"PASSWORD" default:"" description:"Password to authenticate with XOS"`
+ ApiVersion string `short:"a" long:"apiversion" description:"API version" value-name:"VERSION" choice:"v1" choice:"v2"`
+ Debug bool `short:"d" long:"debug" description:"Enable debug mode"`
+ UseTLS bool `long:"tls" description:"Use TLS"`
+ CACert string `long:"tlscacert" value-name:"CA_CERT_FILE" description:"Trust certs signed only by this CA"`
+ Cert string `long:"tlscert" value-name:"CERT_FILE" description:"Path to TLS vertificate file"`
+ Key string `long:"tlskey" value-name:"KEY_FILE" description:"Path to TLS key file"`
+ Verify bool `long:"tlsverify" description:"Use TLS and verify the remote"`
+}
+
+type OutputOptions struct {
+ Format string `long:"format" value-name:"FORMAT" default:"" description:"Format to use to output structured data"`
+ Quiet bool `short:"q" long:"quiet" description:"Output only the IDs of the objects"`
+ OutputAs string `short:"o" long:"outputas" default:"table" choice:"table" choice:"json" choice:"yaml" description:"Type of output to generate"`
+}
+
+func toOutputType(in string) OutputType {
+ switch in {
+ case "table":
+ fallthrough
+ default:
+ return OUTPUT_TABLE
+ case "json":
+ return OUTPUT_JSON
+ case "yaml":
+ return OUTPUT_YAML
+ }
+}
+
+type CommandResult struct {
+ Format format.Format
+ OutputAs OutputType
+ Data interface{}
+}
+
+type config struct {
+ ApiVersion string `yaml:"apiVersion"`
+ Server string `yaml:"server"`
+}
+
+func NewConnection() (*grpc.ClientConn, error) {
+ if len(GlobalOptions.Config) == 0 {
+ home := os.Getenv("HOME")
+ // TODO: Replace after Jenkins updated to go 1.12
+ /*
+ home, err := os.UserHomeDir()
+ if err != nil {
+ log.Printf("Unable to discover they users home directory: %s\n", err)
+ }
+ */
+ GlobalOptions.Config = fmt.Sprintf("%s/.cord/config", home)
+ }
+
+ info, err := os.Stat(GlobalOptions.Config)
+ if err == nil && !info.IsDir() {
+ configFile, err := ioutil.ReadFile(GlobalOptions.Config)
+ if err != nil {
+ log.Printf("configFile.Get err #%v ", err)
+ }
+ err = yaml.Unmarshal(configFile, &GlobalConfig)
+ if err != nil {
+ log.Fatalf("Unmarshal: %v", err)
+ }
+ }
+
+ // Override from command line
+ if GlobalOptions.Server != "" {
+ GlobalConfig.Server = GlobalOptions.Server
+ }
+ if GlobalOptions.ApiVersion != "" {
+ GlobalConfig.ApiVersion = GlobalOptions.ApiVersion
+ }
+ if GlobalOptions.Username != "" {
+ GlobalConfig.Username = GlobalOptions.Username
+ }
+ if GlobalOptions.Password != "" {
+ GlobalConfig.Password = GlobalOptions.Password
+ }
+
+ return grpc.Dial(GlobalConfig.Server, grpc.WithInsecure())
+}
+
+func GenerateOutput(result *CommandResult) {
+ if result != nil && result.Data != nil {
+ if result.OutputAs == OUTPUT_TABLE {
+ tableFormat := format.Format(result.Format)
+ tableFormat.Execute(os.Stdout, true, result.Data)
+ } else if result.OutputAs == OUTPUT_JSON {
+ asJson, err := json.Marshal(&result.Data)
+ if err != nil {
+ panic(err)
+ }
+ fmt.Printf("%s", asJson)
+ } else if result.OutputAs == OUTPUT_YAML {
+ asYaml, err := yaml.Marshal(&result.Data)
+ if err != nil {
+ panic(err)
+ }
+ fmt.Printf("%s", asYaml)
+ }
+ }
+}
diff --git a/commands/common.go b/commands/common.go
new file mode 100644
index 0000000..493b302
--- /dev/null
+++ b/commands/common.go
@@ -0,0 +1,28 @@
+/*
+ * Copyright 2019-present Open Networking Foundation
+ *
+ * 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.
+ */
+package commands
+
+import (
+ b64 "encoding/base64"
+)
+
+func GenerateHeaders() []string {
+ username := GlobalConfig.Username
+ password := GlobalConfig.Password
+ sEnc := b64.StdEncoding.EncodeToString([]byte(username + ":" + password))
+ headers := []string{"authorization: basic " + sEnc}
+ return headers
+}
diff --git a/commands/funcmap.go b/commands/funcmap.go
new file mode 100644
index 0000000..0342653
--- /dev/null
+++ b/commands/funcmap.go
@@ -0,0 +1,75 @@
+/*
+ * Portions copyright 2019-present Open Networking Foundation
+ * Original copyright 2019-present Ciena Corporation
+ *
+ * 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.
+ */
+package commands
+
+import (
+ "fmt"
+ "github.com/fullstorydev/grpcurl"
+ "github.com/jhump/protoreflect/dynamic"
+ "github.com/jhump/protoreflect/grpcreflect"
+ "golang.org/x/net/context"
+ "google.golang.org/grpc"
+ reflectpb "google.golang.org/grpc/reflection/grpc_reflection_v1alpha"
+)
+
+type MethodNotFoundError struct {
+ Name string
+}
+
+func (e *MethodNotFoundError) Error() string {
+ return fmt.Sprintf("Method '%s' not found in function map", e.Name)
+}
+
+type MethodVersionNotFoundError struct {
+ Name string
+ Version string
+}
+
+func (e *MethodVersionNotFoundError) Error() string {
+ return fmt.Sprintf("Method '%s' does not have a verison for '%s' specfied in function map", e.Name, e.Version)
+}
+
+type DescriptorNotFoundError struct {
+ Version string
+}
+
+func (e *DescriptorNotFoundError) Error() string {
+ return fmt.Sprintf("Protocol buffer descriptor for API version '%s' not found", e.Version)
+}
+
+type UnableToParseDescriptorErrror struct {
+ err error
+ Version string
+}
+
+func (e *UnableToParseDescriptorErrror) Error() string {
+ return fmt.Sprintf("Unable to parse protocal buffer descriptor for version '%s': %s", e.Version, e.err)
+}
+
+func GetReflectionMethod(conn *grpc.ClientConn, name string) (grpcurl.DescriptorSource, string, error) {
+ refClient := grpcreflect.NewClient(context.Background(), reflectpb.NewServerReflectionClient(conn))
+ defer refClient.Reset()
+
+ desc := grpcurl.DescriptorSourceFromServer(context.Background(), refClient)
+
+ return desc, name, nil
+}
+
+func GetEnumValue(val *dynamic.Message, name string) string {
+ return val.FindFieldDescriptorByName(name).GetEnumType().
+ FindValueByNumber(val.GetFieldByName(name).(int32)).GetName()
+}
diff --git a/commands/handler.go b/commands/handler.go
new file mode 100644
index 0000000..01fb091
--- /dev/null
+++ b/commands/handler.go
@@ -0,0 +1,75 @@
+/*
+ * Portions copyright 2019-present Open Networking Foundation
+ * Original copyright 2019-present Ciena Corporation
+ *
+ * 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.
+ */
+package commands
+
+import (
+ "github.com/golang/protobuf/proto"
+ "github.com/jhump/protoreflect/desc"
+ "github.com/jhump/protoreflect/dynamic"
+ "google.golang.org/grpc/metadata"
+ "google.golang.org/grpc/status"
+ "io"
+)
+
+type RpcEventHandler struct {
+ Response proto.Message
+ Status *status.Status
+ Data []byte
+ Fields map[string]map[string]interface{}
+}
+
+func (h *RpcEventHandler) OnResolveMethod(*desc.MethodDescriptor) {
+}
+
+func (h *RpcEventHandler) OnSendHeaders(metadata.MD) {
+}
+
+func (h *RpcEventHandler) OnReceiveHeaders(metadata.MD) {
+}
+
+func (h *RpcEventHandler) OnReceiveResponse(m proto.Message) {
+ h.Response = m
+}
+
+func (h *RpcEventHandler) OnReceiveTrailers(s *status.Status, m metadata.MD) {
+ h.Status = s
+}
+
+func (h *RpcEventHandler) GetParams(msg proto.Message) error {
+ dmsg, err := dynamic.AsDynamicMessage(msg)
+ if err != nil {
+ return err
+ }
+
+ //fmt.Printf("MessageName: %s\n", dmsg.XXX_MessageName())
+
+ if h.Fields == nil || len(h.Fields) == 0 {
+ return io.EOF
+ }
+
+ fields, ok := h.Fields[dmsg.XXX_MessageName()]
+ if !ok {
+ return nil
+ }
+
+ for k, v := range fields {
+ dmsg.TrySetFieldByName(k, v)
+ }
+ delete(h.Fields, dmsg.XXX_MessageName())
+
+ return nil
+}
diff --git a/commands/models.go b/commands/models.go
new file mode 100644
index 0000000..11067e7
--- /dev/null
+++ b/commands/models.go
@@ -0,0 +1,167 @@
+/*
+ * Portions copyright 2019-present Open Networking Foundation
+ * Original copyright 2019-present Ciena Corporation
+ *
+ * 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.
+ */
+package commands
+
+import (
+ "context"
+ "fmt"
+ "github.com/fullstorydev/grpcurl"
+ pbdescriptor "github.com/golang/protobuf/protoc-gen-go/descriptor"
+ flags "github.com/jessevdk/go-flags"
+ "github.com/jhump/protoreflect/dynamic"
+ "github.com/opencord/cordctl/format"
+ "strings"
+)
+
+const (
+ DEFAULT_MODEL_FORMAT = "table{{ .id }}\t{{ .name }}"
+)
+
+type ModelList struct {
+ OutputOptions
+ ShowHidden bool `long:"showhidden" description:"Show hidden fields in default output"`
+ ShowFeedback bool `long:"showfeedback" description:"Show feedback fields in default output"`
+ Args struct {
+ ModelName string
+ } `positional-args:"yes" required:"yes"`
+}
+
+type ModelOpts struct {
+ List ModelList `command:"list"`
+}
+
+var modelOpts = ModelOpts{}
+
+func RegisterModelCommands(parser *flags.Parser) {
+ parser.AddCommand("model", "model commands", "Commands to query and manipulate XOS models", &modelOpts)
+}
+
+func (options *ModelList) Execute(args []string) error {
+
+ conn, err := NewConnection()
+ if err != nil {
+ return err
+ }
+ defer conn.Close()
+
+ // TODO: Validate ModelName
+
+ method_name := "xos.xos/List" + options.Args.ModelName
+
+ descriptor, method, err := GetReflectionMethod(conn, method_name)
+ if err != nil {
+ return err
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), GlobalConfig.Grpc.Timeout)
+ defer cancel()
+
+ headers := GenerateHeaders()
+
+ h := &RpcEventHandler{}
+ err = grpcurl.InvokeRPC(ctx, descriptor, conn, method, headers, h, h.GetParams)
+ if err != nil {
+ return err
+ }
+
+ if h.Status != nil && h.Status.Err() != nil {
+ return h.Status.Err()
+ }
+
+ d, err := dynamic.AsDynamicMessage(h.Response)
+ if err != nil {
+ return err
+ }
+
+ items, err := d.TryGetFieldByName("items")
+ if err != nil {
+ return err
+ }
+
+ field_names := make(map[string]bool)
+ data := make([]map[string]interface{}, len(items.([]interface{})))
+ for i, item := range items.([]interface{}) {
+ val := item.(*dynamic.Message)
+ data[i] = make(map[string]interface{})
+ for _, field_desc := range val.GetKnownFields() {
+ field_name := field_desc.GetName()
+ field_type := field_desc.GetType()
+
+ isGuiHidden := strings.Contains(field_desc.GetFieldOptions().String(), "1005:1")
+ isFeedback := strings.Contains(field_desc.GetFieldOptions().String(), "1006:1")
+ isBookkeeping := strings.Contains(field_desc.GetFieldOptions().String(), "1007:1")
+
+ if isGuiHidden && (!options.ShowHidden) {
+ continue
+ }
+
+ if isFeedback && (!options.ShowFeedback) {
+ continue
+ }
+
+ if isBookkeeping {
+ continue
+ }
+
+ if field_desc.IsRepeated() {
+ continue
+ }
+
+ switch field_type {
+ case pbdescriptor.FieldDescriptorProto_TYPE_STRING:
+ data[i][field_name] = val.GetFieldByName(field_name).(string)
+ case pbdescriptor.FieldDescriptorProto_TYPE_INT32:
+ data[i][field_name] = val.GetFieldByName(field_name).(int32)
+ case pbdescriptor.FieldDescriptorProto_TYPE_BOOL:
+ data[i][field_name] = val.GetFieldByName(field_name).(bool)
+ // case pbdescriptor.FieldDescriptorProto_TYPE_DOUBLE:
+ // data[i][field_name] = val.GetFieldByName(field_name).(double)
+ }
+
+ field_names[field_name] = true
+ }
+ }
+
+ var default_format strings.Builder
+ default_format.WriteString("table")
+ first := true
+ for field_name, _ := range field_names {
+ if first {
+ fmt.Fprintf(&default_format, "{{ .%s }}", field_name)
+ first = false
+ } else {
+ fmt.Fprintf(&default_format, "\t{{ .%s }}", field_name)
+ }
+ }
+
+ outputFormat := CharReplacer.Replace(options.Format)
+ if outputFormat == "" {
+ outputFormat = default_format.String()
+ }
+ if options.Quiet {
+ outputFormat = "{{.Id}}"
+ }
+
+ result := CommandResult{
+ Format: format.Format(outputFormat),
+ OutputAs: toOutputType(options.OutputAs),
+ Data: data,
+ }
+
+ GenerateOutput(&result)
+ return nil
+}
diff --git a/commands/services.go b/commands/services.go
new file mode 100644
index 0000000..a38c469
--- /dev/null
+++ b/commands/services.go
@@ -0,0 +1,114 @@
+/*
+ * Portions copyright 2019-present Open Networking Foundation
+ * Original copyright 2019-present Ciena Corporation
+ *
+ * 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.
+ */
+package commands
+
+import (
+ "context"
+ "github.com/fullstorydev/grpcurl"
+ flags "github.com/jessevdk/go-flags"
+ "github.com/jhump/protoreflect/dynamic"
+ "github.com/opencord/cordctl/format"
+)
+
+const (
+ DEFAULT_SERVICE_FORMAT = "table{{ .Name }}\t{{.Version}}\t{{.State}}"
+)
+
+type ServiceList struct {
+ OutputOptions
+}
+
+type ServiceListOutput struct {
+ Name string `json:"name"`
+ Version string `json:"version"`
+ State string `json:"state"`
+}
+
+type ServiceOpts struct {
+ List ServiceList `command:"list"`
+}
+
+var serviceOpts = ServiceOpts{}
+
+func RegisterServiceCommands(parser *flags.Parser) {
+ parser.AddCommand("service", "service commands", "Commands to query and manipulate dynamically loaded XOS Services", &serviceOpts)
+}
+
+func (options *ServiceList) Execute(args []string) error {
+
+ conn, err := NewConnection()
+ if err != nil {
+ return err
+ }
+ defer conn.Close()
+
+ descriptor, method, err := GetReflectionMethod(conn, "xos.dynamicload.GetLoadStatus")
+ if err != nil {
+ return err
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), GlobalConfig.Grpc.Timeout)
+ defer cancel()
+
+ headers := GenerateHeaders()
+
+ h := &RpcEventHandler{}
+ err = grpcurl.InvokeRPC(ctx, descriptor, conn, method, headers, h, h.GetParams)
+ if err != nil {
+ return err
+ }
+
+ if h.Status != nil && h.Status.Err() != nil {
+ return h.Status.Err()
+ }
+
+ d, err := dynamic.AsDynamicMessage(h.Response)
+ if err != nil {
+ return err
+ }
+
+ items, err := d.TryGetFieldByName("services")
+ if err != nil {
+ return err
+ }
+
+ outputFormat := CharReplacer.Replace(options.Format)
+ if outputFormat == "" {
+ outputFormat = DEFAULT_SERVICE_FORMAT
+ }
+ if options.Quiet {
+ outputFormat = "{{.Id}}"
+ }
+
+ data := make([]ServiceListOutput, len(items.([]interface{})))
+
+ for i, item := range items.([]interface{}) {
+ val := item.(*dynamic.Message)
+ data[i].Name = val.GetFieldByName("name").(string)
+ data[i].Version = val.GetFieldByName("version").(string)
+ data[i].State = val.GetFieldByName("state").(string)
+ }
+
+ result := CommandResult{
+ Format: format.Format(outputFormat),
+ OutputAs: toOutputType(options.OutputAs),
+ Data: data,
+ }
+
+ GenerateOutput(&result)
+ return nil
+}
diff --git a/commands/transfer.go b/commands/transfer.go
new file mode 100644
index 0000000..8a42af3
--- /dev/null
+++ b/commands/transfer.go
@@ -0,0 +1,271 @@
+/*
+ * Portions copyright 2019-present Open Networking Foundation
+ * Original copyright 2019-present Ciena Corporation
+ *
+ * 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.
+ */
+package commands
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "github.com/fullstorydev/grpcurl"
+ "github.com/golang/protobuf/proto"
+ flags "github.com/jessevdk/go-flags"
+ "github.com/jhump/protoreflect/dynamic"
+ "github.com/opencord/cordctl/format"
+ "io"
+ "os"
+ "strings"
+)
+
+const (
+ DEFAULT_TRANSFER_FORMAT = "table{{ .Status }}\t{{ .Checksum }}\t{{ .Chunks }}\t{{ .Bytes }}"
+)
+
+type TransferOutput struct {
+ Status string `json:"status"`
+ Checksum string `json:"checksum"`
+ Chunks int `json:"chunks"`
+ Bytes int `json:"bytes"`
+}
+
+type TransferUpload struct {
+ OutputOptions
+ ChunkSize int `short:"h" long:"chunksize" default:"65536" description:"Host and port"`
+ Args struct {
+ LocalFileName string
+ URI string
+ } `positional-args:"yes" required:"yes"`
+}
+
+type TransferDownload struct {
+ OutputOptions
+ Args struct {
+ URI string
+ LocalFileName string
+ } `positional-args:"yes" required:"yes"`
+}
+
+type TransferOpts struct {
+ Upload TransferUpload `command:"upload"`
+ Download TransferDownload `command:"download"`
+}
+
+var transferOpts = TransferOpts{}
+
+func RegisterTransferCommands(parser *flags.Parser) {
+ parser.AddCommand("transfer", "file transfer commands", "Commands to transfer files to and from XOS", &transferOpts)
+}
+
+/* Handlers for streaming upload and download */
+
+type DownloadHandler struct {
+ RpcEventHandler
+ f *os.File
+ chunks int
+ bytes int
+ status string
+}
+
+type UploadHandler struct {
+ RpcEventHandler
+ chunksize int
+ f *os.File
+ uri string
+}
+
+func (h *DownloadHandler) OnReceiveResponse(m proto.Message) {
+ d, err := dynamic.AsDynamicMessage(m)
+ if err != nil {
+ h.status = "ERROR"
+ // TODO(smbaker): How to raise an exception?
+ return
+ }
+ chunk := d.GetFieldByName("chunk").(string)
+ h.f.Write([]byte(chunk))
+ h.chunks += 1
+ h.bytes += len(chunk)
+}
+
+func (h *UploadHandler) GetParams(msg proto.Message) error {
+ dmsg, err := dynamic.AsDynamicMessage(msg)
+ if err != nil {
+ return err
+ }
+
+ fmt.Printf("streamer, MessageName: %s\n", dmsg.XXX_MessageName())
+
+ block := make([]byte, h.chunksize)
+ bytes_read, err := h.f.Read(block)
+
+ if err == io.EOF {
+ h.f.Close()
+ fmt.Print("EOF\n")
+ return err
+ }
+
+ if err != nil {
+ fmt.Print("ERROR!\n")
+ return err
+ }
+
+ dmsg.TrySetFieldByName("uri", h.uri)
+ dmsg.TrySetFieldByName("chunk", string(block[:bytes_read]))
+
+ return nil
+}
+
+/* Command processors */
+
+func (options *TransferUpload) Execute(args []string) error {
+
+ conn, err := NewConnection()
+ if err != nil {
+ return err
+ }
+ defer conn.Close()
+
+ local_name := options.Args.LocalFileName
+ uri := options.Args.URI
+
+ descriptor, method, err := GetReflectionMethod(conn, "xos.filetransfer/Upload")
+ if err != nil {
+ return err
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), GlobalConfig.Grpc.Timeout)
+ defer cancel()
+
+ headers := GenerateHeaders()
+
+ f, err := os.Open(local_name)
+ if err != nil {
+ return err
+ }
+
+ h := &UploadHandler{uri: uri, f: f, chunksize: options.ChunkSize}
+
+ err = grpcurl.InvokeRPC(ctx, descriptor, conn, method, headers, h, h.GetParams)
+ if err != nil {
+ return err
+ }
+ d, err := dynamic.AsDynamicMessage(h.Response)
+ if err != nil {
+ return err
+ }
+
+ outputFormat := CharReplacer.Replace(options.Format)
+ if outputFormat == "" {
+ outputFormat = DEFAULT_TRANSFER_FORMAT
+ }
+ if options.Quiet {
+ outputFormat = "{{.Status}}"
+ }
+
+ data := make([]TransferOutput, 1)
+ data[0].Checksum = d.GetFieldByName("checksum").(string)
+ data[0].Chunks = int(d.GetFieldByName("chunks_received").(int32))
+ data[0].Bytes = int(d.GetFieldByName("bytes_received").(int32))
+ data[0].Status = GetEnumValue(d, "status")
+
+ result := CommandResult{
+ Format: format.Format(outputFormat),
+ OutputAs: toOutputType(options.OutputAs),
+ Data: data,
+ }
+
+ GenerateOutput(&result)
+
+ return nil
+}
+
+func IsFileUri(s string) bool {
+ return strings.HasPrefix(s, "file://")
+}
+
+func (options *TransferDownload) Execute(args []string) error {
+
+ conn, err := NewConnection()
+ if err != nil {
+ return err
+ }
+ defer conn.Close()
+
+ local_name := options.Args.LocalFileName
+ uri := options.Args.URI
+
+ if IsFileUri(local_name) {
+ return errors.New("local_name argument should not be a uri")
+ }
+
+ if !IsFileUri(uri) {
+ return errors.New("uri argument should be a file:// uri")
+ }
+
+ descriptor, method, err := GetReflectionMethod(conn, "xos.filetransfer/Download")
+ if err != nil {
+ return err
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), GlobalConfig.Grpc.Timeout)
+ defer cancel()
+
+ headers := GenerateHeaders()
+
+ f, err := os.Create(local_name)
+ if err != nil {
+ return err
+ }
+
+ dm := make(map[string]interface{})
+ dm["uri"] = uri
+
+ h := &DownloadHandler{
+ RpcEventHandler: RpcEventHandler{
+ Fields: map[string]map[string]interface{}{"xos.FileRequest": dm},
+ },
+ f: f,
+ chunks: 0,
+ bytes: 0,
+ status: "SUCCESS"}
+
+ err = grpcurl.InvokeRPC(ctx, descriptor, conn, method, headers, h, h.GetParams)
+ if err != nil {
+ return err
+ }
+
+ outputFormat := CharReplacer.Replace(options.Format)
+ if outputFormat == "" {
+ outputFormat = DEFAULT_TRANSFER_FORMAT
+ }
+ if options.Quiet {
+ outputFormat = "{{.Status}}"
+ }
+
+ data := make([]TransferOutput, 1)
+ data[0].Chunks = h.chunks
+ data[0].Bytes = h.bytes
+ data[0].Status = h.status
+
+ result := CommandResult{
+ Format: format.Format(outputFormat),
+ OutputAs: toOutputType(options.OutputAs),
+ Data: data,
+ }
+
+ GenerateOutput(&result)
+
+ return nil
+}
diff --git a/commands/version.go b/commands/version.go
new file mode 100644
index 0000000..7f7daf4
--- /dev/null
+++ b/commands/version.go
@@ -0,0 +1,76 @@
+/*
+ * Portions copyright 2019-present Open Networking Foundation
+ * Original copyright 2019-present Ciena Corporation
+ *
+ * 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.
+ */
+package commands
+
+import (
+ flags "github.com/jessevdk/go-flags"
+ "github.com/opencord/cordctl/cli/version"
+ "github.com/opencord/cordctl/format"
+)
+
+type VersionDetails struct {
+ Version string `json:"version"`
+ GoVersion string `json:"goversion"`
+ GitCommit string `json:"gitcommit"`
+ BuildTime string `json:"buildtime"`
+ Os string `json:"os"`
+ Arch string `json:"arch"`
+}
+
+type VersionOutput struct {
+ Client VersionDetails `json:"client"`
+}
+
+type VersionOpts struct {
+ OutputAs string `short:"o" long:"outputas" default:"table" choice:"table" choice:"json" choice:"yaml" description:"Type of output to generate"`
+}
+
+var versionOpts = VersionOpts{}
+
+var versionInfo = VersionOutput{
+ Client: VersionDetails{
+ Version: version.Version,
+ GoVersion: version.GoVersion,
+ GitCommit: version.GitCommit,
+ Os: version.Os,
+ Arch: version.Arch,
+ BuildTime: version.BuildTime,
+ },
+}
+
+func RegisterVersionCommands(parent *flags.Parser) {
+ parent.AddCommand("version", "display version", "Display client version", &versionOpts)
+}
+
+const DefaultFormat = `Client:
+ Version {{.Client.Version}}
+ Go version: {{.Client.GoVersion}}
+ Git commit: {{.Client.GitCommit}}
+ Built: {{.Client.BuildTime}}
+ OS/Arch: {{.Client.Os}}/{{.Client.Arch}}
+`
+
+func (options *VersionOpts) Execute(args []string) error {
+ result := CommandResult{
+ Format: format.Format(DefaultFormat),
+ OutputAs: toOutputType(options.OutputAs),
+ Data: versionInfo,
+ }
+
+ GenerateOutput(&result)
+ return nil
+}
diff --git a/cordctl.config b/cordctl.config
new file mode 100644
index 0000000..e9ce437
--- /dev/null
+++ b/cordctl.config
@@ -0,0 +1,6 @@
+apiVersion: v1
+server: 10.201.101.33:30011
+username: admin@opencord.org
+password: letmein
+grpc:
+ timeout: 10s
diff --git a/format/formatter.go b/format/formatter.go
new file mode 100644
index 0000000..dc92dec
--- /dev/null
+++ b/format/formatter.go
@@ -0,0 +1,94 @@
+/*
+ * Copyright 2019-present Ciena Corporation
+ *
+ * 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.
+ */
+package format
+
+import (
+ "io"
+ "reflect"
+ "regexp"
+ "strings"
+ "text/tabwriter"
+ "text/template"
+ "text/template/parse"
+)
+
+var nameFinder = regexp.MustCompile(`\.([_A-Za-z0-9]*)}}`)
+
+type Format string
+
+func (f Format) IsTable() bool {
+ return strings.HasPrefix(string(f), "table")
+}
+
+func (f Format) Execute(writer io.Writer, withHeaders bool, data interface{}) error {
+ var tabWriter *tabwriter.Writer = nil
+ format := f
+
+ if f.IsTable() {
+ tabWriter = tabwriter.NewWriter(writer, 0, 4, 4, ' ', 0)
+ format = Format(strings.TrimPrefix(string(f), "table"))
+ }
+
+ tmpl, err := template.New("output").Parse(string(format))
+ if err != nil {
+ return err
+ }
+
+ if f.IsTable() && withHeaders {
+ var header string
+ for _, n := range tmpl.Tree.Root.Nodes {
+ switch n.Type() {
+ case parse.NodeText:
+ header += n.String()
+ case parse.NodeString:
+ header += n.String()
+ case parse.NodeAction:
+ found := nameFinder.FindStringSubmatch(n.String())
+ if len(found) == 2 {
+ header += strings.ToUpper(found[1])
+ }
+ }
+ }
+ tabWriter.Write([]byte(header))
+ tabWriter.Write([]byte("\n"))
+
+ slice := reflect.ValueOf(data)
+ if slice.Kind() == reflect.Slice {
+ for i := 0; i < slice.Len(); i++ {
+ tmpl.Execute(tabWriter, slice.Index(i).Interface())
+ tabWriter.Write([]byte("\n"))
+ }
+ } else {
+ tmpl.Execute(tabWriter, data)
+ tabWriter.Write([]byte("\n"))
+ }
+ tabWriter.Flush()
+ return nil
+ }
+
+ slice := reflect.ValueOf(data)
+ if slice.Kind() == reflect.Slice {
+ for i := 0; i < slice.Len(); i++ {
+ tmpl.Execute(writer, slice.Index(i).Interface())
+ writer.Write([]byte("\n"))
+ }
+ } else {
+ tmpl.Execute(writer, data)
+ writer.Write([]byte("\n"))
+ }
+ return nil
+
+}
diff --git a/format/formatter_test.go b/format/formatter_test.go
new file mode 100644
index 0000000..62d9c39
--- /dev/null
+++ b/format/formatter_test.go
@@ -0,0 +1,156 @@
+/*
+ * Portions copyright 2019-present Open Networking Foundation
+ * Original copyright 2019-present Ciena Corporation
+ *
+ * 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.
+ */
+package format
+
+import (
+ "fmt"
+ "strings"
+ "testing"
+)
+
+type TestSubStructure struct {
+ Value string
+}
+
+type TestStructure struct {
+ Field1 string
+ Field2 *string
+ Field3 bool
+ Field4 int
+ Field5 []string
+ Field6 [][]string
+ Field7 TestSubStructure
+ Field8 []TestSubStructure
+ Field9 *TestSubStructure
+}
+
+func generateTestData(rows int) []TestStructure {
+ data := make([]TestStructure, rows)
+
+ abc := "abc"
+ for i := 0; i < rows; i += 1 {
+ data[i].Field1 = fmt.Sprintf("0x%05x", i)
+ data[i].Field2 = &abc
+ if i%2 == 0 {
+ data[i].Field3 = true
+ }
+ data[i].Field4 = i
+ data[i].Field5 = []string{"a", "b", "c", "d"}
+ data[i].Field6 = [][]string{{"x", "y", "z"}}
+ data[i].Field7.Value = "abc"
+ data[i].Field8 = []TestSubStructure{{Value: "abc"}}
+ data[i].Field9 = &TestSubStructure{Value: "abc"}
+ }
+ return data
+}
+
+func TestTableFormat(t *testing.T) {
+ expected := "" +
+ "FIELD1 FIELD2 FIELD3 FIELD4 FIELD5 FIELD6 VALUE FIELD8 FIELD9\n" +
+ "0x00000 abc true 0 [a b c d] [[x y z]] abc [{abc}] {abc}\n" +
+ "0x00001 abc false 1 [a b c d] [[x y z]] abc [{abc}] {abc}\n" +
+ "0x00002 abc true 2 [a b c d] [[x y z]] abc [{abc}] {abc}\n" +
+ "0x00003 abc false 3 [a b c d] [[x y z]] abc [{abc}] {abc}\n" +
+ "0x00004 abc true 4 [a b c d] [[x y z]] abc [{abc}] {abc}\n" +
+ "0x00005 abc false 5 [a b c d] [[x y z]] abc [{abc}] {abc}\n" +
+ "0x00006 abc true 6 [a b c d] [[x y z]] abc [{abc}] {abc}\n" +
+ "0x00007 abc false 7 [a b c d] [[x y z]] abc [{abc}] {abc}\n" +
+ "0x00008 abc true 8 [a b c d] [[x y z]] abc [{abc}] {abc}\n" +
+ "0x00009 abc false 9 [a b c d] [[x y z]] abc [{abc}] {abc}\n"
+ got := &strings.Builder{}
+ format := Format("table{{.Field1}}\t{{.Field2}}\t{{.Field3}}\t{{.Field4}}\t{{.Field5}}\t{{.Field6}}\t{{.Field7.Value}}\t{{.Field8}}\t{{.Field9}}")
+ data := generateTestData(10)
+ err := format.Execute(got, true, data)
+ if err != nil {
+ t.Errorf("%s: unexpected error result: %s", t.Name(), err)
+ }
+ if got.String() != expected {
+ t.Logf("RECEIVED:\n%s\n", got.String())
+ t.Logf("EXPECTED:\n%s\n", expected)
+ t.Errorf("%s: expected and received did not match", t.Name())
+ }
+}
+
+func TestNoTableFormat(t *testing.T) {
+ expected := "" +
+ "0x00000,abc,true,0,[a b c d],[[x y z]],abc,[{abc}],{abc}\n" +
+ "0x00001,abc,false,1,[a b c d],[[x y z]],abc,[{abc}],{abc}\n" +
+ "0x00002,abc,true,2,[a b c d],[[x y z]],abc,[{abc}],{abc}\n" +
+ "0x00003,abc,false,3,[a b c d],[[x y z]],abc,[{abc}],{abc}\n" +
+ "0x00004,abc,true,4,[a b c d],[[x y z]],abc,[{abc}],{abc}\n" +
+ "0x00005,abc,false,5,[a b c d],[[x y z]],abc,[{abc}],{abc}\n" +
+ "0x00006,abc,true,6,[a b c d],[[x y z]],abc,[{abc}],{abc}\n" +
+ "0x00007,abc,false,7,[a b c d],[[x y z]],abc,[{abc}],{abc}\n" +
+ "0x00008,abc,true,8,[a b c d],[[x y z]],abc,[{abc}],{abc}\n" +
+ "0x00009,abc,false,9,[a b c d],[[x y z]],abc,[{abc}],{abc}\n"
+ got := &strings.Builder{}
+ format := Format("{{.Field1}},{{.Field2}},{{.Field3}},{{.Field4}},{{.Field5}},{{.Field6}},{{.Field7.Value}},{{.Field8}},{{.Field9}}")
+ data := generateTestData(10)
+ err := format.Execute(got, false, data)
+ if err != nil {
+ t.Errorf("%s: unexpected error result: %s", t.Name(), err)
+ }
+ if got.String() != expected {
+ t.Logf("RECEIVED:\n%s\n", got.String())
+ t.Logf("EXPECTED:\n%s\n", expected)
+ t.Errorf("%s: expected and received did not match", t.Name())
+ }
+}
+
+func TestTableSingleFormat(t *testing.T) {
+ expected := "" +
+ "FIELD1 FIELD2 FIELD3 FIELD4 FIELD5 FIELD6 VALUE FIELD8 FIELD9\n" +
+ "0x00000 abc true 0 [a b c d] [[x y z]] abc [{abc}] {abc}\n"
+ got := &strings.Builder{}
+ format := Format("table{{.Field1}}\t{{.Field2}}\t{{.Field3}}\t{{.Field4}}\t{{.Field5}}\t{{.Field6}}\t{{.Field7.Value}}\t{{.Field8}}\t{{.Field9}}")
+ data := generateTestData(1)
+ err := format.Execute(got, true, data[0])
+ if err != nil {
+ t.Errorf("%s: unexpected error result: %s", t.Name(), err)
+ }
+ if got.String() != expected {
+ t.Logf("RECEIVED:\n%s\n", got.String())
+ t.Logf("EXPECTED:\n%s\n", expected)
+ t.Errorf("%s: expected and received did not match", t.Name())
+ }
+}
+
+func TestNoTableSingleFormat(t *testing.T) {
+ expected := "0x00000,abc,true,0,[a b c d],[[x y z]],abc,[{abc}],{abc}\n"
+ got := &strings.Builder{}
+ format := Format("{{.Field1}},{{.Field2}},{{.Field3}},{{.Field4}},{{.Field5}},{{.Field6}},{{.Field7.Value}},{{.Field8}},{{.Field9}}")
+ data := generateTestData(1)
+ err := format.Execute(got, false, data[0])
+ if err != nil {
+ t.Errorf("%s: unexpected error result: %s", t.Name(), err)
+ }
+ if got.String() != expected {
+ t.Logf("RECEIVED:\n%s\n", got.String())
+ t.Logf("EXPECTED:\n%s\n", expected)
+ t.Errorf("%s: expected and received did not match", t.Name())
+ }
+}
+
+func TestBadFormat(t *testing.T) {
+ format := Format("table{{.Field1}\t{{.Field2}}\t{{.Field3}}\t{{.Field4}}\t{{.Field5}}\t{{.Field6}}\t{{.Field7.Value}}\t{{.Field8}}\t{{.Field9}}")
+ got := &strings.Builder{}
+ data := generateTestData(10)
+ err := format.Execute(got, true, data)
+ if err == nil {
+ t.Errorf("%s: expected error (bad format) got none", t.Name())
+ }
+}