Basic BBSimCtl implementation

Change-Id: Ib5e6f7f462cdb10a3d976b99812658bf7e225dfb
diff --git a/internal/bbsim/devices/olt.go b/internal/bbsim/devices/olt.go
index 66abe14..6ce09a1 100644
--- a/internal/bbsim/devices/olt.go
+++ b/internal/bbsim/devices/olt.go
@@ -57,6 +57,7 @@
 
 	olt = OltDevice{
 		ID: seq,
+		SerialNumber: fmt.Sprintf("BBSIM_OLT_%d", seq),
 		OperState: getOperStateFSM(func(e *fsm.Event) {
 			oltLogger.Debugf("Changing OLT OperState from %s to %s", e.Src, e.Dst)
 		}),
@@ -469,7 +470,7 @@
 	devinfo.GemportIdEnd = 65535
 	devinfo.FlowIdStart = 1
 	devinfo.FlowIdEnd = 16383
-	devinfo.DeviceSerialNumber = fmt.Sprintf("BBSIM_OLT_%d", o.ID)
+	devinfo.DeviceSerialNumber = o.SerialNumber
 
 	return devinfo, nil
 }
diff --git a/internal/bbsim/devices/types.go b/internal/bbsim/devices/types.go
index e3439f5..65aa09e 100644
--- a/internal/bbsim/devices/types.go
+++ b/internal/bbsim/devices/types.go
@@ -89,6 +89,7 @@
 type OltDevice struct {
 	// BBSIM Internals
 	ID int
+	SerialNumber string
 	NumNni int
 	NumPon int
 	NumOnuPerPon int
diff --git a/internal/bbsim/grpc_api_server.go b/internal/bbsim/grpc_api_server.go
index 3c3ab3e..304d3fa 100644
--- a/internal/bbsim/grpc_api_server.go
+++ b/internal/bbsim/grpc_api_server.go
@@ -28,22 +28,22 @@
 })
 
 var (
-	version 	string
-	buildTime  	string
-	commitHash 	string
-	gitStatus	string
+	version    string
+	buildTime  string
+	commitHash string
+	gitStatus  string
 )
 
 type BBSimServer struct {
 }
 
-func (s BBSimServer) Version(ctx context.Context, req *bbsim.Empty) (*bbsim.VersionNumber, error)  {
+func (s BBSimServer) Version(ctx context.Context, req *bbsim.Empty) (*bbsim.VersionNumber, error) {
 	// TODO add a flag to specofy whether the tree was clean at this commit or not
 	return &bbsim.VersionNumber{
-		Version: version,
-		BuildTime: buildTime,
+		Version:    version,
+		BuildTime:  buildTime,
 		CommitHash: commitHash,
-		GitStatus: gitStatus,
+		GitStatus:  gitStatus,
 	}, nil
 }
 
@@ -54,7 +54,7 @@
 
 	for _, nni := range olt.Nnis {
 		n := bbsim.NNIPort{
-			ID: int32(nni.ID),
+			ID:        int32(nni.ID),
 			OperState: nni.OperState.Current(),
 		}
 		nnis = append(nnis, &n)
@@ -62,23 +62,24 @@
 
 	for _, pon := range olt.Pons {
 		p := bbsim.PONPort{
-			ID: int32(pon.ID),
+			ID:        int32(pon.ID),
 			OperState: pon.OperState.Current(),
 		}
 		pons = append(pons, &p)
 	}
 
 	res := bbsim.Olt{
-		ID: int32(olt.ID),
-		OperState: olt.OperState.Current(),
+		ID:            int32(olt.ID),
+		SerialNumber:  olt.SerialNumber,
+		OperState:     olt.OperState.Current(),
 		InternalState: olt.InternalState.Current(),
-		NNIPorts: nnis,
-		PONPorts: pons,
+		NNIPorts:      nnis,
+		PONPorts:      pons,
 	}
 	return &res, nil
 }
 
-func (s BBSimServer) GetONUs(ctx context.Context, req *bbsim.Empty) (*bbsim.ONUs, error){
+func (s BBSimServer) GetONUs(ctx context.Context, req *bbsim.Empty) (*bbsim.ONUs, error) {
 	olt := devices.GetOLT()
 	onus := bbsim.ONUs{
 		Items: []*bbsim.ONU{},
@@ -87,14 +88,14 @@
 	for _, pon := range olt.Pons {
 		for _, o := range pon.Onus {
 			onu := bbsim.ONU{
-				ID: int32(o.ID),
-				SerialNumber: o.SerialNumber.String(),
-				OperState: o.OperState.Current(),
+				ID:            int32(o.ID),
+				SerialNumber:  o.SerialNumber.String(),
+				OperState:     o.OperState.Current(),
 				InternalState: o.InternalState.Current(),
-				PonPortID: int32(o.PonPortID),
+				PonPortID:     int32(o.PonPortID),
 			}
 			onus.Items = append(onus.Items, &onu)
 		}
 	}
 	return &onus, nil
-}
\ No newline at end of file
+}
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
+}
diff --git a/internal/bbsimctl/config/config.go b/internal/bbsimctl/config/config.go
new file mode 100644
index 0000000..caf0601
--- /dev/null
+++ b/internal/bbsimctl/config/config.go
@@ -0,0 +1,105 @@
+/*
+ * 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 config
+
+import (
+	log "github.com/sirupsen/logrus"
+	"io/ioutil"
+	"net"
+	"os"
+	"fmt"
+	"time"
+	"gopkg.in/yaml.v2"
+)
+
+var (
+	Version 	string
+	BuildTime  	string
+	CommitHash 	string
+	GitStatus	string
+)
+
+var GlobalOptions struct {
+	Config   string `short:"c" long:"config" env:"BBSIMCTL_CONFIG" 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"`
+	//Protoset string `long:"protoset" value-name:"FILENAME" description:"Load protobuf definitions from protoset instead of reflection api"`
+	Debug    bool   `short:"d" long:"debug" description:"Enable debug mode"`
+}
+
+type GrpcConfigSpec struct {
+	Timeout time.Duration `yaml:"timeout"`
+}
+
+type GlobalConfigSpec struct {
+	Server   string        `yaml:"server"`
+	Grpc     GrpcConfigSpec
+}
+
+var GlobalConfig = GlobalConfigSpec{
+	Server: "localhost:50070",
+	Grpc: GrpcConfigSpec{
+		Timeout: time.Second * 10,
+	},
+}
+
+func ProcessGlobalOptions() {
+	if len(GlobalOptions.Config) == 0 {
+		home, err := os.UserHomeDir()
+		if err != nil {
+			log.Printf("Unable to discover the users home directory: %s\n", err)
+		}
+		GlobalOptions.Config = fmt.Sprintf("%s/.bbsim/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 environment
+	//    in particualr, for passing env vars via `go test`
+	env_server, present := os.LookupEnv("BBSIMCTL_SERVER")
+	if present {
+		GlobalConfig.Server = env_server
+	}
+
+	// Override from command line
+	if GlobalOptions.Server != "" {
+		GlobalConfig.Server = GlobalOptions.Server
+	}
+
+
+	// Generate error messages for required settings
+	if GlobalConfig.Server == "" {
+		log.Fatal("Server is not set. Please update config file or use the -s option")
+	}
+
+	//Try to resolve hostname if provided for the server
+	if host, port, err := net.SplitHostPort(GlobalConfig.Server); err == nil {
+		if addrs, err := net.LookupHost(host); err == nil {
+			GlobalConfig.Server = net.JoinHostPort(addrs[0], port)
+		}
+	}
+}
\ No newline at end of file