seba-321 implemented reflow logic

Change-Id: I4a67a38104dbcb9bbfa830b38fc4fc21c42c2dbd
diff --git a/internal/pkg/impl/abstractChassis.go b/internal/pkg/impl/abstractChassis.go
new file mode 100644
index 0000000..a2e05b3
--- /dev/null
+++ b/internal/pkg/impl/abstractChassis.go
@@ -0,0 +1,63 @@
+/*
+ Copyright 2017 the original author or authors.
+
+ 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 impl
+
+import (
+	"errors"
+	"fmt"
+	"log"
+	"net"
+	"strings"
+
+	"gerrit.opencord.org/abstract-olt/internal/pkg/settings"
+	"gerrit.opencord.org/abstract-olt/models"
+	"gerrit.opencord.org/abstract-olt/models/abstract"
+	"gerrit.opencord.org/abstract-olt/models/physical"
+)
+
+/*
+CreateChassis - allocates a new Chassis struct and stores it in chassisMap
+*/
+func CreateChassis(clli string, xosAddress net.TCPAddr, xosUser string, xosPassword string, shelf int, rack int) (string, error) {
+	myChan := getSyncChannel()
+	<-myChan
+	defer done(myChan, true)
+	chassisMap := models.GetChassisMap()
+
+	loginWorked := testLogin(xosUser, xosPassword, xosAddress.IP, xosAddress.Port)
+	if !loginWorked {
+		return "", errors.New("Unable to validate login not creating Abstract Chassis")
+	}
+
+	chassisHolder := (*chassisMap)[clli]
+	if chassisHolder != nil {
+		errMsg := fmt.Sprintf("AbstractChassis %s already exists", clli)
+		return "", errors.New(errMsg)
+	}
+
+	abstractChassis := abstract.GenerateChassis(clli, rack, shelf)
+	phyChassis := physical.Chassis{CLLI: clli, XOSUser: xosUser, XOSPassword: xosPassword, XOSAddress: xosAddress, Rack: rack, Shelf: shelf}
+
+	chassisHolder = &models.ChassisHolder{AbstractChassis: abstractChassis, PhysicalChassis: phyChassis}
+	if settings.GetDebug() {
+		output := fmt.Sprintf("%v", abstractChassis)
+		formatted := strings.Replace(output, "{", "\n{", -1)
+		log.Printf("new chassis %s\n", formatted)
+	}
+	(*chassisMap)[clli] = chassisHolder
+	isDirty = true
+	return clli, nil
+}
diff --git a/internal/pkg/impl/echo.go b/internal/pkg/impl/echo.go
new file mode 100644
index 0000000..1727afe
--- /dev/null
+++ b/internal/pkg/impl/echo.go
@@ -0,0 +1,26 @@
+/*
+ Copyright 2017 the original author or authors.
+
+ 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 impl
+
+/*
+Echo - Tester function which just returns same string sent to it
+*/
+func Echo(ping string) (string, error) {
+	myChan := getSyncChannel()
+	<-myChan
+	defer done(myChan, true)
+	return ping, nil
+}
diff --git a/internal/pkg/impl/olt.go b/internal/pkg/impl/olt.go
new file mode 100644
index 0000000..b878a9b
--- /dev/null
+++ b/internal/pkg/impl/olt.go
@@ -0,0 +1,60 @@
+/*
+ Copyright 2017 the original author or authors.
+
+ 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 impl
+
+import (
+	"errors"
+	"fmt"
+	"net"
+
+	"gerrit.opencord.org/abstract-olt/models"
+	"gerrit.opencord.org/abstract-olt/models/physical"
+)
+
+/*
+CreateOLTChassis adds an OLT chassis/line card to the Physical chassis
+*/
+func CreateOLTChassis(clli string, oltType string, address net.TCPAddr, hostname string) (string, error) {
+	myChan := getSyncChannel()
+	<-myChan
+	defer done(myChan, true)
+	chassisMap := models.GetChassisMap()
+	chassisHolder := (*chassisMap)[clli]
+	if chassisHolder == nil {
+		errString := fmt.Sprintf("There is no chassis with CLLI of %s", clli)
+		return "", errors.New(errString)
+	}
+	physicalChassis := &chassisHolder.PhysicalChassis
+	sOlt := physical.SimpleOLT{CLLI: clli, Hostname: hostname, Address: address, Parent: physicalChassis}
+	switch oltType {
+	case "edgecore":
+		sOlt.CreateEdgecore()
+	case "adtran":
+	case "tibit":
+	}
+	physicalChassis.AddOLTChassis(sOlt)
+	ports := sOlt.GetPorts()
+	for i := 0; i < len(ports); i++ {
+		absPort, _ := chassisHolder.AbstractChassis.NextPort()
+
+		absPort.PhysPort = &ports[i]
+		//AssignTraits(&ports[i], absPort)
+	}
+	isDirty = true
+	return clli, nil
+
+}
diff --git a/internal/pkg/impl/ont.go b/internal/pkg/impl/ont.go
new file mode 100644
index 0000000..932ee5e
--- /dev/null
+++ b/internal/pkg/impl/ont.go
@@ -0,0 +1,74 @@
+/*
+ Copyright 2017 the original author or authors.
+
+ 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 impl
+
+import (
+	"errors"
+	"fmt"
+
+	"gerrit.opencord.org/abstract-olt/models"
+)
+
+/*
+ProvsionOnt - provisions ont using sTag,cTag,NasPortID, and CircuitID generated internally
+*/
+func ProvisionOnt(clli string, slotNumber int, portNumber int, ontNumber int, serialNumber string) (bool, error) {
+	myChan := getSyncChannel()
+	<-myChan
+	defer done(myChan, true)
+	chassisMap := models.GetChassisMap()
+	chassisHolder := (*chassisMap)[clli]
+	if chassisHolder == nil {
+		errString := fmt.Sprintf("There is no chassis with CLLI of %s", clli)
+		return false, errors.New(errString)
+	}
+	err := chassisHolder.AbstractChassis.ActivateONT(slotNumber, portNumber, ontNumber, serialNumber)
+	isDirty = true
+	return true, err
+}
+
+/*
+ProvsionOntFull - provisions ont using sTag,cTag,NasPortID, and CircuitID passed in
+*/
+func ProvisionOntFull(clli string, slotNumber int, portNumber int, ontNumber int, serialNumber string, cTag uint32, sTag uint32, nasPortID string, circuitID string) (bool, error) {
+	myChan := getSyncChannel()
+	<-myChan
+	defer done(myChan, true)
+	chassisMap := models.GetChassisMap()
+	chassisHolder := (*chassisMap)[clli]
+	if chassisHolder == nil {
+		errString := fmt.Sprintf("There is no chassis with CLLI of %s", clli)
+		return false, errors.New(errString)
+	}
+	err := chassisHolder.AbstractChassis.ActivateONTFull(slotNumber, portNumber, ontNumber, serialNumber, cTag, sTag, nasPortID, circuitID)
+	isDirty = true
+	return true, err
+}
+
+/*
+DeleteOnt - deletes a previously provision ont
+*/
+func DeleteOnt(clli string, slotNumber int, portNumber int, ontNumber int, serialNumber string) (bool, error) {
+	myChan := getSyncChannel()
+	<-myChan
+	defer done(myChan, true)
+	chassisMap := models.GetChassisMap()
+	chassisHolder := (*chassisMap)[clli]
+	err := chassisHolder.AbstractChassis.DeleteONT(slotNumber, portNumber, ontNumber, serialNumber)
+	isDirty = true
+	return true, err
+}
diff --git a/internal/pkg/impl/ouput.go b/internal/pkg/impl/ouput.go
new file mode 100644
index 0000000..aa2ea7e
--- /dev/null
+++ b/internal/pkg/impl/ouput.go
@@ -0,0 +1,93 @@
+/*
+ Copyright 2017 the original author or authors.
+
+ 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 impl
+
+import (
+	"fmt"
+	"log"
+	"os"
+
+	"gerrit.opencord.org/abstract-olt/internal/pkg/settings"
+	"gerrit.opencord.org/abstract-olt/models"
+	"github.com/mongodb/mongo-go-driver/bson"
+	"github.com/mongodb/mongo-go-driver/mongo"
+	"github.com/mongodb/mongo-go-driver/mongo/updateopt"
+	context "golang.org/x/net/context"
+)
+
+/*
+DoOutput - creates a backup and stores it to disk/mongodb
+*/
+func DoOutput() (bool, error) {
+	if isDirty {
+		myChan := getSyncChannel()
+		<-myChan
+		defer done(myChan, true)
+		chassisMap := models.GetChassisMap()
+		if settings.GetMongo() {
+			client, err := mongo.NewClient(settings.GetMongodb())
+			client.Connect(context.Background())
+			if err != nil {
+				log.Printf("client connect to mongo db @%s failed with %v\n", settings.GetMongodb(), err)
+			}
+			defer client.Disconnect(context.Background())
+			for clli, chassisHolder := range *chassisMap {
+				json, _ := (chassisHolder).Serialize()
+				collection := client.Database("AbstractOLT").Collection("backup")
+				doc := bson.NewDocument(bson.EC.String("_id", clli))
+				filter := bson.NewDocument(bson.EC.String("_id", clli))
+				doc.Append(bson.EC.Binary("body", json))
+
+				updateDoc := bson.NewDocument(bson.EC.SubDocument("$set", doc))
+				//update or insert if not existent
+				res, err := collection.UpdateOne(context.Background(), filter, updateDoc, updateopt.Upsert(true))
+				if err != nil {
+					log.Printf("collection.UpdateOne failed with %v\n", err)
+				} else {
+					id := res.UpsertedID
+					if settings.GetDebug() {
+						log.Printf("Update Succeeded with id %v\n", id)
+					}
+				}
+			}
+		} else {
+			for clli, chassisHolder := range *chassisMap {
+
+				json, _ := (chassisHolder).Serialize()
+				if settings.GetMongo() {
+
+				} else {
+					//TODO parameterize dump location
+					backupFile := fmt.Sprintf("backup/%s", clli)
+					f, _ := os.Create(backupFile)
+
+					defer f.Close()
+
+					_, _ = f.WriteString(string(json))
+					f.Sync()
+				}
+			}
+		}
+		isDirty = false
+	} else {
+		if settings.GetDebug() {
+			log.Print("Not dirty not dumping config")
+		}
+
+	}
+	return true, nil
+
+}
diff --git a/internal/pkg/impl/reflow.go b/internal/pkg/impl/reflow.go
new file mode 100644
index 0000000..e178054
--- /dev/null
+++ b/internal/pkg/impl/reflow.go
@@ -0,0 +1,50 @@
+/*
+ Copyright 2017 the original author or authors.
+
+ 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 impl
+
+import "gerrit.opencord.org/abstract-olt/models"
+
+/*
+Reflow - takes internal config and resends to xos
+*/
+func Reflow() (bool, error) {
+	myChan := getSyncChannel()
+	<-myChan
+	defer done(myChan, true)
+	chassisMap := models.GetChassisMap()
+	for _, chassisHolder := range *chassisMap {
+		physical := chassisHolder.PhysicalChassis
+		for index := range physical.Linecards {
+			olt := physical.Linecards[index]
+			physical.SendOltTosca(olt)
+			for portIndex := range olt.Ports {
+				port := olt.Ports[portIndex]
+				for ontIndex := range port.Onts {
+					ont := port.Onts[ontIndex]
+					if ont.Active {
+						physical.SendOntTosca(ont)
+						physical.SendSubscriberTosca(ont)
+
+					}
+
+				}
+
+			}
+		}
+	}
+	return true, nil
+	//TODO lots of this could throw errors
+}
diff --git a/internal/pkg/impl/sync.go b/internal/pkg/impl/sync.go
new file mode 100644
index 0000000..65f5c35
--- /dev/null
+++ b/internal/pkg/impl/sync.go
@@ -0,0 +1,35 @@
+/*
+ Copyright 2017 the original author or authors.
+
+ 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 impl
+
+import "sync"
+
+var syncChan chan bool
+var isDirty bool
+
+var runOnce sync.Once
+
+func getSyncChannel() chan bool {
+	runOnce.Do(func() {
+		syncChan = make(chan bool, 1)
+		syncChan <- true
+	})
+
+	return syncChan
+}
+func done(myChan chan bool, done bool) {
+	myChan <- done
+}
diff --git a/internal/pkg/impl/xosuser.go b/internal/pkg/impl/xosuser.go
new file mode 100644
index 0000000..77a9367
--- /dev/null
+++ b/internal/pkg/impl/xosuser.go
@@ -0,0 +1,96 @@
+/*
+ Copyright 2017 the original author or authors.
+
+ 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 impl
+
+import (
+	"errors"
+	"fmt"
+	"io/ioutil"
+	"log"
+	"net"
+	"net/http"
+	"strings"
+
+	"gerrit.opencord.org/abstract-olt/internal/pkg/settings"
+	"gerrit.opencord.org/abstract-olt/models"
+)
+
+/*
+ChangeXOSUserPassword - allows update of xos credentials
+*/
+func ChangeXOSUserPassword(clli string, xosUser string, xosPassword string) (bool, error) {
+	myChan := getSyncChannel()
+	<-myChan
+	defer done(myChan, true)
+	chassisMap := models.GetChassisMap()
+	chassisHolder := (*chassisMap)[clli]
+	if chassisHolder == nil {
+		errString := fmt.Sprintf("There is no chassis with CLLI of %s", clli)
+		return false, errors.New(errString)
+	}
+	xosIP := chassisHolder.PhysicalChassis.XOSAddress.IP
+	xosPort := chassisHolder.PhysicalChassis.XOSAddress.Port
+	loginWorked := testLogin(xosUser, xosPassword, xosIP, xosPort)
+	if !loginWorked {
+		return false, errors.New("Unable to validate login when changing password")
+	}
+
+	chassisHolder.PhysicalChassis.XOSUser = xosUser
+	chassisHolder.PhysicalChassis.XOSPassword = xosPassword
+	isDirty = true
+	return true, nil
+
+}
+
+func testLogin(xosUser string, xosPassword string, xosIP net.IP, xosPort int) bool {
+	if settings.GetDummy() {
+		return true
+	}
+	var dummyYaml = `
+tosca_definitions_version: tosca_simple_yaml_1_0
+imports:
+  - custom_types/site.yaml
+description: anything
+topology_template:
+  node_templates:
+    mysite:
+      type: tosca.nodes.Site
+      properties:
+        must-exist: true
+        name: mysite
+`
+	client := &http.Client{}
+	requestList := fmt.Sprintf("http://%s:%d/run", xosIP, xosPort)
+	req, err := http.NewRequest("POST", requestList, strings.NewReader(dummyYaml))
+	req.Header.Add("xos-username", xosUser)
+	req.Header.Add("xos-password", xosPassword)
+	resp, err := client.Do(req)
+	log.Printf("testLogin resp:%v", resp)
+	if err != nil {
+		log.Printf("Unable to validate XOS Login Information %v", err)
+		return false
+	}
+	defer resp.Body.Close()
+
+	if resp.StatusCode == http.StatusOK {
+		bodyBytes, _ := ioutil.ReadAll(resp.Body)
+		bodyString := string(bodyBytes)
+		fmt.Println(bodyString)
+		return true
+	}
+	return false
+
+}