Basic BBSimCtl implementation

Change-Id: Ib5e6f7f462cdb10a3d976b99812658bf7e225dfb
diff --git a/internal/bbsimctl/commands/config.go b/internal/bbsimctl/commands/config.go
new file mode 100644
index 0000000..b05bb5b
--- /dev/null
+++ b/internal/bbsimctl/commands/config.go
@@ -0,0 +1,68 @@
+/*
+ * 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/jessevdk/go-flags"
+	"github.com/opencord/bbsim/internal/bbsimctl/config"
+	"gopkg.in/yaml.v2"
+)
+
+const copyrightNotice = `
+# 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.
+#
+`
+
+type ConfigOptions struct{}
+
+func RegisterConfigCommands(parent *flags.Parser) {
+	parent.AddCommand("config", "generate bbsimctl configuration", "Commands to generate bbsimctl configuration", &ConfigOptions{})
+}
+
+func (options *ConfigOptions) Execute(args []string) error {
+	//GlobalConfig
+	config.ProcessGlobalOptions()
+
+	b, err := yaml.Marshal(config.GlobalConfig)
+	if err != nil {
+		return err
+	}
+	fmt.Println(copyrightNotice)
+	fmt.Println(string(b))
+
+	fmt.Println("BBSimCtl details:")
+	fmt.Printf("\tVersion: %s \n", config.Version)
+	fmt.Printf("\tBuildTime: %s \n", config.BuildTime)
+	fmt.Printf("\tCommitHash: %s \n", config.CommitHash)
+	fmt.Printf("\tGitStatus: %s \n", config.GitStatus)
+	return nil
+}
diff --git a/internal/bbsimctl/commands/handler.go b/internal/bbsimctl/commands/handler.go
new file mode 100644
index 0000000..3c4b0ff
--- /dev/null
+++ b/internal/bbsimctl/commands/handler.go
@@ -0,0 +1,72 @@
+/*
+ * 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
+	}
+
+	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/internal/bbsimctl/commands/olt.go b/internal/bbsimctl/commands/olt.go
new file mode 100644
index 0000000..7f698f1
--- /dev/null
+++ b/internal/bbsimctl/commands/olt.go
@@ -0,0 +1,111 @@
+/*
+ * 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/jessevdk/go-flags"
+	pb "github.com/opencord/bbsim/api/bbsim"
+	"github.com/opencord/bbsim/internal/bbsimctl/config"
+	"github.com/opencord/cordctl/pkg/format"
+	log "github.com/sirupsen/logrus"
+	"google.golang.org/grpc"
+	"os"
+)
+
+const (
+	DEFAULT_OLT_DEVICE_HEADER_FORMAT = "table{{ .ID }}\t{{ .SerialNumber }}\t{{ .OperState }}\t{{ .InternalState }}"
+	DEFAULT_PORT_HEADER_FORMAT       = "table{{ .ID }}\t{{ .OperState }}"
+)
+
+type OltGet struct{}
+
+type OltNNIs struct{}
+
+type OltPONs struct{}
+
+// TODO add autocomplete
+type oltOptions struct {
+	Get OltGet  `command:"get"`
+	NNI OltNNIs `command:"nnis"`
+	PON OltPONs `command:"pons"`
+}
+
+func RegisterOltCommands(parser *flags.Parser) {
+	parser.AddCommand("olt", "OLT Commands", "Commands to query and manipulate the OLT device", &oltOptions{})
+}
+
+func getOLT() *pb.Olt {
+	conn, err := grpc.Dial(config.GlobalConfig.Server, grpc.WithInsecure())
+	if err != nil {
+		log.Fatal("did not connect: %v", err)
+		return nil
+	}
+	defer conn.Close()
+	c := pb.NewBBSimClient(conn)
+
+	// Contact the server and print out its response.
+
+	ctx, cancel := context.WithTimeout(context.Background(), config.GlobalConfig.Grpc.Timeout)
+	defer cancel()
+	olt, err := c.GetOlt(ctx, &pb.Empty{})
+	if err != nil {
+		log.Fatal("could not get OLT: %v", err)
+		return nil
+	}
+	return olt
+}
+
+func printOltHeader(prefix string, o *pb.Olt) {
+	fmt.Println(fmt.Sprintf("%s : %s", prefix, o.SerialNumber))
+	fmt.Println()
+}
+
+// TODO use voltctl or cordctl parser to print tables (this needs to be moved out of the internals package)
+func (o *OltGet) Execute(args []string) error {
+	olt := getOLT()
+
+	// print out
+	tableFormat := format.Format(DEFAULT_OLT_DEVICE_HEADER_FORMAT)
+	tableFormat.Execute(os.Stdout, true, olt)
+
+	return nil
+}
+
+func (o *OltNNIs) Execute(args []string) error {
+	olt := getOLT()
+
+	printOltHeader("NNI Ports for", olt)
+
+	tableFormat := format.Format(DEFAULT_PORT_HEADER_FORMAT)
+	tableFormat.Execute(os.Stdout, true, olt.NNIPorts)
+
+	return nil
+}
+
+func (o *OltPONs) Execute(args []string) error {
+	olt := getOLT()
+
+	printOltHeader("PON Ports for", olt)
+
+	tableFormat := format.Format(DEFAULT_PORT_HEADER_FORMAT)
+	tableFormat.Execute(os.Stdout, true, olt.PONPorts)
+
+	return nil
+}
diff --git a/internal/bbsimctl/commands/onu.go b/internal/bbsimctl/commands/onu.go
new file mode 100644
index 0000000..7d6da8e
--- /dev/null
+++ b/internal/bbsimctl/commands/onu.go
@@ -0,0 +1,73 @@
+/*
+ * 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/jessevdk/go-flags"
+	pb "github.com/opencord/bbsim/api/bbsim"
+	"github.com/opencord/bbsim/internal/bbsimctl/config"
+	"github.com/opencord/cordctl/pkg/format"
+	log "github.com/sirupsen/logrus"
+	"google.golang.org/grpc"
+	"os"
+)
+
+const (
+	DEFAULT_ONU_DEVICE_HEADER_FORMAT = "table{{ .PonPortID }}\t{{ .ID }}\t{{ .SerialNumber }}\t{{ .OperState }}\t{{ .InternalState }}"
+)
+
+type ONUOptions struct{}
+
+func RegisterONUCommands(parser *flags.Parser) {
+	parser.AddCommand("onus", "List ONU Devices", "Commands to list the ONU devices and their internal state", &ONUOptions{})
+}
+
+func getONUs() *pb.ONUs {
+	conn, err := grpc.Dial(config.GlobalConfig.Server, grpc.WithInsecure())
+
+	if err != nil {
+		log.Fatal("did not connect: %v", err)
+		return nil
+	}
+	defer conn.Close()
+	c := pb.NewBBSimClient(conn)
+
+	// Contact the server and print out its response.
+
+	ctx, cancel := context.WithTimeout(context.Background(), config.GlobalConfig.Grpc.Timeout)
+	defer cancel()
+	onus, err := c.GetONUs(ctx, &pb.Empty{})
+	if err != nil {
+		log.Fatal("could not get OLT: %v", err)
+		return nil
+	}
+	return onus
+}
+
+func (options *ONUOptions) Execute(args []string) error {
+	onus := getONUs()
+
+	// print out
+	tableFormat := format.Format(DEFAULT_ONU_DEVICE_HEADER_FORMAT)
+	if err := tableFormat.Execute(os.Stdout, true, onus.Items); err != nil {
+		log.Fatalf("Error while formatting ONUs table: %s", err)
+	}
+
+	return nil
+}