go/svc/(dc stuff) -> dc/

We want to start keeping codebases separated per 'team'/intent, to then
have simple OWNER files/trees to specify review rules.

This means dc/ stuff can all be OWNED by q3k, and review will only
involve a +1 for style/readability, instead  of a +2 for approval.

Change-Id: I05afbc4e1018944b841ec0d88cd24cc95bec8bf1
diff --git a/dc/m6220-proxy/BUILD.bazel b/dc/m6220-proxy/BUILD.bazel
new file mode 100644
index 0000000..50fa692
--- /dev/null
+++ b/dc/m6220-proxy/BUILD.bazel
@@ -0,0 +1,27 @@
+load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library")
+
+go_library(
+    name = "go_default_library",
+    srcs = [
+        "cli.go",
+        "main.go",
+    ],
+    importpath = "code.hackerspace.pl/hscloud/dc/m6220-proxy",
+    visibility = ["//visibility:private"],
+    deps = [
+        "//dc/m6220-proxy/proto:go_default_library",
+        "//go/mirko:go_default_library",
+        "//proto/infra:go_default_library",
+        "@com_github_golang_glog//:go_default_library",
+        "@com_github_ziutek_telnet//:go_default_library",
+        "@org_golang_google_grpc//codes:go_default_library",
+        "@org_golang_google_grpc//status:go_default_library",
+        "@org_golang_x_net//trace:go_default_library",
+    ],
+)
+
+go_binary(
+    name = "m6220-proxy",
+    embed = [":go_default_library"],
+    visibility = ["//visibility:public"],
+)
diff --git a/dc/m6220-proxy/cli.go b/dc/m6220-proxy/cli.go
new file mode 100644
index 0000000..b9642cf
--- /dev/null
+++ b/dc/m6220-proxy/cli.go
@@ -0,0 +1,243 @@
+package main
+
+import (
+	"context"
+	"fmt"
+	"strings"
+
+	"github.com/golang/glog"
+	"github.com/ziutek/telnet"
+	"golang.org/x/net/trace"
+)
+
+type cliClient struct {
+	conn *telnet.Conn
+
+	username string
+	password string
+
+	loggedIn       bool
+	promptHostname string
+}
+
+func newCliClient(c *telnet.Conn, username, password string) *cliClient {
+	return &cliClient{
+		conn:     c,
+		username: username,
+		password: password,
+	}
+}
+
+func (c *cliClient) readUntil(ctx context.Context, delims ...string) (string, error) {
+	chStr := make(chan string, 1)
+	chErr := make(chan error, 1)
+	go func() {
+		s, err := c.conn.ReadUntil(delims...)
+		if err != nil {
+			chErr <- err
+			return
+		}
+		chStr <- string(s)
+	}()
+
+	select {
+	case <-ctx.Done():
+		return "", fmt.Errorf("context done")
+	case err := <-chErr:
+		c.trace(ctx, "readUntil failed: %v", err)
+		return "", err
+	case s := <-chStr:
+		c.trace(ctx, "readUntil <- %q", s)
+		return s, nil
+
+	}
+}
+
+func (c *cliClient) readString(ctx context.Context, delim byte) (string, error) {
+	chStr := make(chan string, 1)
+	chErr := make(chan error, 1)
+	go func() {
+		s, err := c.conn.ReadString(delim)
+		if err != nil {
+			chErr <- err
+			return
+		}
+		chStr <- s
+	}()
+
+	select {
+	case <-ctx.Done():
+		return "", fmt.Errorf("context done")
+	case err := <-chErr:
+		c.trace(ctx, "readString failed: %v", err)
+		return "", err
+	case s := <-chStr:
+		c.trace(ctx, "readString <- %q", s)
+		return s, nil
+
+	}
+}
+
+func (c *cliClient) writeLine(ctx context.Context, s string) error {
+	n, err := c.conn.Write([]byte(s + "\n"))
+	if got, want := n, len(s)+1; got != want {
+		err = fmt.Errorf("wrote %d bytes out of %d", got, want)
+	}
+	if err != nil {
+		c.trace(ctx, "writeLine failed: %v", err)
+		return err
+	}
+	c.trace(ctx, "writeLine -> %q", s)
+	return nil
+}
+
+func (c *cliClient) trace(ctx context.Context, f string, parts ...interface{}) {
+	tr, ok := trace.FromContext(ctx)
+	if !ok {
+		fmted := fmt.Sprintf(f, parts...)
+		glog.Infof("[no trace] %s", fmted)
+		return
+	}
+	tr.LazyPrintf(f, parts...)
+}
+
+func (c *cliClient) logIn(ctx context.Context) error {
+	if c.loggedIn {
+		return nil
+	}
+
+	// Provide username.
+	prompt, err := c.readString(ctx, ':')
+	if err != nil {
+		return fmt.Errorf("could not read username prompt: %v", err)
+	}
+	if !strings.HasSuffix(prompt, "User:") {
+		return fmt.Errorf("invalid username prompt: %v", err)
+	}
+	if err := c.writeLine(ctx, c.username); err != nil {
+		return fmt.Errorf("could not write username: %v")
+	}
+
+	// Provide password.
+	prompt, err = c.readString(ctx, ':')
+	if err != nil {
+		return fmt.Errorf("could not read password prompt: %v", err)
+	}
+	if !strings.HasSuffix(prompt, "Password:") {
+		return fmt.Errorf("invalid password prompt: %v", err)
+	}
+	if err := c.writeLine(ctx, c.password); err != nil {
+		return fmt.Errorf("could not write password: %v")
+	}
+
+	// Get unprivileged prompt.
+	prompt, err = c.readString(ctx, '>')
+	if err != nil {
+		return fmt.Errorf("could not read unprivileged prompt: %v", err)
+	}
+
+	parts := strings.Split(prompt, "\r\n")
+	c.promptHostname = strings.TrimSuffix(parts[len(parts)-1], ">")
+
+	// Enable privileged mode.
+
+	if err := c.writeLine(ctx, "enable"); err != nil {
+		return fmt.Errorf("could not write enable: %v")
+	}
+
+	// Provide password (again)
+	prompt, err = c.readString(ctx, ':')
+	if err != nil {
+		return fmt.Errorf("could not read password prompt: %v", err)
+	}
+	if !strings.HasSuffix(prompt, "Password:") {
+		return fmt.Errorf("invalid password prompt: %v", err)
+	}
+	if err := c.writeLine(ctx, c.password); err != nil {
+		return fmt.Errorf("could not write password: %v")
+	}
+
+	// Get privileged prompt.
+	prompt, err = c.readString(ctx, '#')
+	if err != nil {
+		return fmt.Errorf("could not read privileged prompt: %v", err)
+	}
+
+	if !strings.HasSuffix(prompt, c.promptHostname+"#") {
+		return fmt.Errorf("unexpected privileged prompt: %v", prompt)
+	}
+
+	// Disable pager.
+	if err := c.writeLine(ctx, "terminal length 0"); err != nil {
+		return fmt.Errorf("could not diable pager: %v", err)
+	}
+	prompt, err = c.readString(ctx, '#')
+	if err != nil {
+		return fmt.Errorf("could not disable pager: %v", err)
+	}
+	if !strings.HasSuffix(prompt, c.promptHostname+"#") {
+		return fmt.Errorf("unexpected privileged prompt: %v", prompt)
+	}
+
+	// Success!
+	c.loggedIn = true
+	c.trace(ctx, "logged into %v", c.promptHostname)
+	return nil
+}
+
+func (c *cliClient) runCommand(ctx context.Context, command string) ([]string, string, error) {
+	if err := c.logIn(ctx); err != nil {
+		return nil, "", fmt.Errorf("could not log in: %v", err)
+	}
+
+	// First, synchronize to prompt.
+	attempts := 3
+	for {
+		c.writeLine(ctx, "")
+		line, err := c.readString(ctx, '\n')
+		if err != nil {
+			return nil, "", fmt.Errorf("while synchronizing to prompt: %v", err)
+		}
+		line = strings.Trim(line, "\r\n")
+		if strings.HasSuffix(line, c.promptHostname+"#") {
+			break
+		}
+
+		attempts -= 1
+		if attempts == 0 {
+			return nil, "", fmt.Errorf("could not find prompt, last result %q", line)
+		}
+	}
+
+	// Send comand.
+	c.writeLine(ctx, command)
+
+	// First, read until prompt again.
+	if _, err := c.readUntil(ctx, c.promptHostname+"#"); err != nil {
+		return nil, "", fmt.Errorf("could not get command hostname echo: %v", err)
+	}
+
+	loopback, err := c.readUntil(ctx, "\r\n")
+	if err != nil {
+		return nil, "", fmt.Errorf("could not get command loopback: %v", err)
+	}
+	loopback = strings.Trim(loopback, "\r\n")
+	c.trace(ctx, "effective command: %q", loopback)
+
+	// Read until we have a standalone prompt with no newline afterwards.
+	data, err := c.readUntil(ctx, c.promptHostname+"#")
+	if err != nil {
+		return nil, "", fmt.Errorf("could not get command results: %v", err)
+	}
+
+	lines := []string{}
+	for _, line := range strings.Split(data, "\r\n") {
+		if line == c.promptHostname+"#" {
+			break
+		}
+		lines = append(lines, line)
+	}
+	c.trace(ctx, "command %q returned lines: %v", command, lines)
+
+	return lines, loopback, nil
+}
diff --git a/dc/m6220-proxy/main.go b/dc/m6220-proxy/main.go
new file mode 100644
index 0000000..6fd972d
--- /dev/null
+++ b/dc/m6220-proxy/main.go
@@ -0,0 +1,277 @@
+package main
+
+import (
+	"context"
+	"flag"
+	"fmt"
+	"reflect"
+	"strconv"
+	"strings"
+
+	"code.hackerspace.pl/hscloud/go/mirko"
+	"github.com/golang/glog"
+	"github.com/ziutek/telnet"
+	"google.golang.org/grpc/codes"
+	"google.golang.org/grpc/status"
+
+	pb "code.hackerspace.pl/hscloud/dc/m6220-proxy/proto"
+	ipb "code.hackerspace.pl/hscloud/proto/infra"
+)
+
+var (
+	flagSwitchAddress  string
+	flagSwitchUsername string
+	flagSwitchPassword string
+)
+
+func init() {
+	flag.Set("logtostderr", "true")
+}
+
+type service struct {
+	connectionSemaphore chan int
+}
+
+func (s *service) connect() (*cliClient, error) {
+	s.connectionSemaphore <- 1
+	conn, err := telnet.Dial("tcp", flagSwitchAddress)
+	if err != nil {
+		<-s.connectionSemaphore
+		return nil, err
+	}
+
+	cli := newCliClient(conn, flagSwitchUsername, flagSwitchPassword)
+	return cli, nil
+}
+
+func (s *service) disconnect() {
+	<-s.connectionSemaphore
+}
+
+func (s *service) RunCommand(ctx context.Context, req *pb.RunCommandRequest) (*pb.RunCommandResponse, error) {
+	if req.Command == "" {
+		return nil, status.Error(codes.InvalidArgument, "command cannot be null")
+	}
+
+	cli, err := s.connect()
+	if err != nil {
+		return nil, status.Error(codes.Unavailable, "could not connect to switch")
+	}
+	defer s.disconnect()
+
+	lines, effective, err := cli.runCommand(ctx, req.Command)
+	if err != nil {
+		return nil, err
+	}
+	res := &pb.RunCommandResponse{
+		EffectiveCommand: effective,
+		Lines:            lines,
+	}
+	return res, nil
+}
+
+func (s *service) parseInterfaceStatus(res *ipb.GetPortsResponse, lines []string) error {
+	if len(lines) < 4 {
+		return fmt.Errorf("need at least 4 lines of output, got %d", len(lines))
+	}
+	if lines[0] != "" {
+		return fmt.Errorf("expected first line to be empty, is %q", lines[0])
+	}
+	header1parts := strings.Fields(lines[1])
+	if want := []string{"Port", "Description", "Duplex", "Speed", "Neg", "Link", "Flow", "Control"}; !reflect.DeepEqual(want, header1parts) {
+		return fmt.Errorf("expected header1 to be %v, got %v", want, header1parts)
+	}
+
+	header2parts := strings.Fields(lines[2])
+	if want := []string{"State", "Status"}; !reflect.DeepEqual(want, header2parts) {
+		return fmt.Errorf("expected header2 to be %v, got %v", want, header2parts)
+	}
+
+	if lines[3][0] != '-' {
+		return fmt.Errorf("expected header3 to start with -, got %q", lines[3])
+	}
+
+	for _, line := range lines[4:] {
+		parts := strings.Fields(line)
+		if len(parts) < 6 {
+			break
+		}
+		portName := parts[0]
+		if strings.HasPrefix(portName, "Gi") && strings.HasPrefix(portName, "Ti") {
+			break
+		}
+
+		speedStr := parts[len(parts)-4]
+		stateStr := parts[len(parts)-2]
+
+		port := &ipb.SwitchPort{
+			Name: portName,
+		}
+		if speedStr == "100" {
+			port.Speed = ipb.SwitchPort_SPEED_100M
+		} else if speedStr == "1000" {
+			port.Speed = ipb.SwitchPort_SPEED_1G
+		} else if speedStr == "10000" {
+			port.Speed = ipb.SwitchPort_SPEED_10G
+		}
+		if stateStr == "Up" {
+			port.LinkState = ipb.SwitchPort_LINKSTATE_UP
+		} else if stateStr == "Down" {
+			port.LinkState = ipb.SwitchPort_LINKSTATE_DOWN
+		}
+
+		res.Ports = append(res.Ports, port)
+	}
+
+	return nil
+}
+
+func (s *service) parseInterfaceConfig(port *ipb.SwitchPort, lines []string) error {
+	glog.Infof("%+v", port)
+	for _, line := range lines {
+		glog.Infof("%s: %q", port.Name, line)
+		parts := strings.Fields(line)
+		if len(parts) < 1 {
+			continue
+		}
+
+		if len(parts) >= 2 && parts[0] == "switchport" {
+			if parts[1] == "mode" {
+				if port.PortMode != ipb.SwitchPort_PORTMODE_INVALID {
+					return fmt.Errorf("redefinition of switchport mode")
+				}
+				if parts[2] == "access" {
+					port.PortMode = ipb.SwitchPort_PORTMODE_SWITCHPORT_UNTAGGED
+				} else if parts[2] == "trunk" {
+					port.PortMode = ipb.SwitchPort_PORTMODE_SWITCHPORT_TAGGED
+				} else if parts[2] == "general" {
+					port.PortMode = ipb.SwitchPort_PORTMODE_SWITCHPORT_GENERIC
+				} else {
+					port.PortMode = ipb.SwitchPort_PORTMODE_MANGLED
+				}
+			}
+
+			if parts[1] == "access" {
+				if port.PortMode == ipb.SwitchPort_PORTMODE_INVALID {
+					port.PortMode = ipb.SwitchPort_PORTMODE_SWITCHPORT_UNTAGGED
+				}
+				if len(parts) > 3 && parts[2] == "vlan" {
+					vlan, err := strconv.Atoi(parts[3])
+					if err != nil {
+						return fmt.Errorf("invalid vlan: %q", parts[3])
+					}
+					port.VlanNative = int32(vlan)
+				}
+			}
+
+			if parts[1] == "trunk" {
+				if len(parts) >= 5 && parts[2] == "allowed" && parts[3] == "vlan" {
+					vlans := strings.Split(parts[4], ",")
+					for _, vlan := range vlans {
+						vlanNum, err := strconv.Atoi(vlan)
+						if err != nil {
+							return fmt.Errorf("invalid vlan: %q", parts[3])
+						}
+						port.VlanTagged = append(port.VlanTagged, int32(vlanNum))
+					}
+				}
+			}
+		} else if len(parts) >= 2 && parts[0] == "mtu" {
+			mtu, err := strconv.Atoi(parts[1])
+			if err != nil {
+				return fmt.Errorf("invalid mtu: %q", parts[3])
+			}
+			port.Mtu = int32(mtu)
+		} else if len(parts) >= 2 && parts[0] == "spanning-tree" && parts[1] == "portfast" {
+			port.SpanningTreeMode = ipb.SwitchPort_SPANNING_TREE_MODE_PORTFAST
+		}
+	}
+
+	// no mode -> access
+	if port.PortMode == ipb.SwitchPort_PORTMODE_INVALID {
+		port.PortMode = ipb.SwitchPort_PORTMODE_SWITCHPORT_UNTAGGED
+	}
+
+	// apply defaults
+	if port.Mtu == 0 {
+		port.Mtu = 1500
+	}
+	if port.SpanningTreeMode == ipb.SwitchPort_SPANNING_TREE_MODE_INVALID {
+		port.SpanningTreeMode = ipb.SwitchPort_SPANNING_TREE_MODE_AUTO_PORTFAST
+	}
+
+	// sanitize
+	if port.PortMode == ipb.SwitchPort_PORTMODE_SWITCHPORT_UNTAGGED {
+		port.VlanTagged = []int32{}
+		port.Prefixes = []string{}
+		if port.VlanNative == 0 {
+			port.VlanNative = 1
+		}
+	} else if port.PortMode == ipb.SwitchPort_PORTMODE_SWITCHPORT_TAGGED {
+		port.VlanNative = 0
+		port.Prefixes = []string{}
+	} else if port.PortMode == ipb.SwitchPort_PORTMODE_SWITCHPORT_GENERIC {
+		port.Prefixes = []string{}
+		if port.VlanNative == 0 {
+			port.VlanNative = 1
+		}
+	}
+	return nil
+}
+
+func (s *service) GetPorts(ctx context.Context, req *ipb.GetPortsRequest) (*ipb.GetPortsResponse, error) {
+	cli, err := s.connect()
+	if err != nil {
+		return nil, status.Error(codes.Unavailable, "could not connect to switch")
+	}
+	defer s.disconnect()
+	res := &ipb.GetPortsResponse{}
+
+	statusLines, _, err := cli.runCommand(ctx, "show interface status")
+	if err != nil {
+		return nil, status.Error(codes.Unavailable, "could not get interface status from switch")
+	}
+
+	err = s.parseInterfaceStatus(res, statusLines)
+	if err != nil {
+		return nil, status.Errorf(codes.Unavailable, "could not parse interface status from switch: %v", err)
+	}
+
+	for _, port := range res.Ports {
+		configLines, _, err := cli.runCommand(ctx, "show run interface "+port.Name)
+		if err != nil {
+			return nil, status.Error(codes.Unavailable, "could not get interface config from switch")
+		}
+		err = s.parseInterfaceConfig(port, configLines)
+		if err != nil {
+			return nil, status.Errorf(codes.Unavailable, "could not parse interface config from switch: %v", err)
+		}
+	}
+
+	return res, nil
+}
+
+func main() {
+	flag.StringVar(&flagSwitchAddress, "switch_address", "127.0.0.1:23", "Telnet address of M6220")
+	flag.StringVar(&flagSwitchUsername, "switch_username", "admin", "Switch login username")
+	flag.StringVar(&flagSwitchPassword, "switch_password", "admin", "Switch login password")
+	flag.Parse()
+
+	s := &service{
+		connectionSemaphore: make(chan int, 1),
+	}
+
+	m := mirko.New()
+	if err := m.Listen(); err != nil {
+		glog.Exitf("Listen(): %v", err)
+	}
+
+	pb.RegisterM6220ProxyServer(m.GRPC(), s)
+	ipb.RegisterSwitchControlServer(m.GRPC(), s)
+
+	if err := m.Serve(); err != nil {
+		glog.Exitf("Serve(): %v", err)
+	}
+
+	select {}
+}
diff --git a/dc/m6220-proxy/proto/.gitignore b/dc/m6220-proxy/proto/.gitignore
new file mode 100644
index 0000000..3cf12ab
--- /dev/null
+++ b/dc/m6220-proxy/proto/.gitignore
@@ -0,0 +1 @@
+proxy.pb.go
diff --git a/dc/m6220-proxy/proto/BUILD.bazel b/dc/m6220-proxy/proto/BUILD.bazel
new file mode 100644
index 0000000..4e0ae7e
--- /dev/null
+++ b/dc/m6220-proxy/proto/BUILD.bazel
@@ -0,0 +1,23 @@
+load("@io_bazel_rules_go//go:def.bzl", "go_library")
+load("@io_bazel_rules_go//proto:def.bzl", "go_proto_library")
+
+proto_library(
+    name = "proto_proto",
+    srcs = ["proxy.proto"],
+    visibility = ["//visibility:public"],
+)
+
+go_proto_library(
+    name = "proto_go_proto",
+    compilers = ["@io_bazel_rules_go//proto:go_grpc"],
+    importpath = "code.hackerspace.pl/hscloud/dc/m6220-proxy/proto",
+    proto = ":proto_proto",
+    visibility = ["//visibility:public"],
+)
+
+go_library(
+    name = "go_default_library",
+    embed = [":proto_go_proto"],
+    importpath = "code.hackerspace.pl/hscloud/dc/m6220-proxy/proto",
+    visibility = ["//visibility:public"],
+)
diff --git a/dc/m6220-proxy/proto/proxy.proto b/dc/m6220-proxy/proto/proxy.proto
new file mode 100644
index 0000000..b8444c3
--- /dev/null
+++ b/dc/m6220-proxy/proto/proxy.proto
@@ -0,0 +1,16 @@
+syntax = "proto3";
+package proto;
+option go_package = "code.hackerspace.pl/hscloud/dc/m6220-proxy/proto";
+
+message RunCommandRequest {
+    string command = 1;
+};
+
+message RunCommandResponse {
+    string effective_command = 1;
+    repeated string lines = 2;
+};
+
+service M6220Proxy {
+    rpc RunCommand(RunCommandRequest) returns (RunCommandResponse);
+};