SEBA-619 implement event subscriber to subscribe events
Scope of this story was augmented to include functionality to modify properties of a subscription
subscribe to events 1 by 1 instead of a list of events
get subscription destination ip from an env variable configured thru helm charts

Change-Id: If72848bd804c11998b4584634669d68bd9d9e7e0
diff --git a/event_subscriber.go b/event_subscriber.go
new file mode 100644
index 0000000..a44d32f
--- /dev/null
+++ b/event_subscriber.go
@@ -0,0 +1,90 @@
+// Copyright 2018 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 main
+
+import (
+	"encoding/json"
+	"fmt"
+	"net/http"
+	"bytes"
+	"regexp"
+	"strconv"
+	"time"
+	"os"
+)
+
+const REDFISH_PATH = "/redfish/v1/EventService/Subscriptions/"
+const CONTENT_TYPE = "application/json"
+
+func add_subscription(ip string, event string) (rtn bool, id uint) {
+	rtn = false
+	id = 0
+
+	destip := os.Getenv("DEVICE_MANAGEMENT_DESTIP") + ":" + os.Getenv("DEVICE_MANAGEMENT_DESTPORT")
+	subscrpt_info := map[string]interface{}{"Context":"TBD","Protocol":"Redfish"}
+	subscrpt_info["Name"] = event + " event subscription"
+	subscrpt_info["Destination"] = "https://" + destip
+	subscrpt_info["EventTypes"] = []string{event}
+	sRequestJson, err := json.Marshal(subscrpt_info)
+	uri := ip + REDFISH_PATH
+	client := http.Client{Timeout: 10 * time.Second}
+	resp, err := client.Post(uri, CONTENT_TYPE, bytes.NewBuffer(sRequestJson))
+	if err != nil {
+		fmt.Println(err)
+		return
+	}
+	defer resp.Body.Close()
+
+	if resp.StatusCode != 201 {
+		result := make(map[string]interface{})
+		json.NewDecoder(resp.Body).Decode(&result)
+		fmt.Println(result)
+		fmt.Println(result["data"])
+		fmt.Println("Add ", event, " subscription failed. HTTP response status: ",  resp.Status)
+		return
+	}
+
+	rtn = true
+	loc := resp.Header["Location"]
+	re := regexp.MustCompile(`/(\w+)$`)
+	match := re.FindStringSubmatch(loc[0])
+	idint, _ := strconv.Atoi(match[1])
+	id = uint(idint)
+	fmt.Println("Subscription", event, "id", id, "was successfully added")
+	return
+}
+
+func remove_subscription(ip string, id uint) bool {
+	uri := ip + REDFISH_PATH + strconv.Itoa(int(id))
+	req, _ := http.NewRequest("DELETE", uri, nil)
+	resp, err := http.DefaultClient.Do(req)
+	if err != nil {
+		fmt.Println(err)
+		return false
+	}
+	defer resp.Body.Close()
+
+	if code := resp.StatusCode; code < 200 && code > 299 {
+		result := make(map[string]interface{})
+		json.NewDecoder(resp.Body).Decode(&result)
+		fmt.Println(result)
+		fmt.Println(result["data"])
+		fmt.Println("Remove subscription failed. HTTP response status:", resp.Status)
+		return false
+	}
+	fmt.Println("Subscription id", id, "was successfully removed")
+	return true
+}
+
diff --git a/main.go b/main.go
index 477568f..6394ba7 100644
--- a/main.go
+++ b/main.go
@@ -24,6 +24,7 @@
 	"github.com/Shopify/sarama"
 	"google.golang.org/grpc"
 	"golang.org/x/net/context"
+	"crypto/tls"
 	empty "github.com/golang/protobuf/ptypes/empty"
         importer "./proto"
 )
@@ -35,8 +36,10 @@
 
 var DataProducer sarama.AsyncProducer
 
+var default_events = [...]string{"ResourceAdded","ResourceRemoved","Alert"}
+
 type device struct  {
-	subscription []string
+	subscriptions map[string]uint
 	freq uint32
 }
 
@@ -49,6 +52,7 @@
 
 func (s *Server) SendDeviceInfo(c context.Context,  info *importer.DeviceInfo) (*empty.Empty, error) {
 	d := device {
+		subscriptions: make(map[string]uint),
 		freq:	info.Frequency,
 	}
 	s.devicemap[info.IpAddress] = &d
@@ -56,15 +60,24 @@
 	return &empty.Empty{}, nil
 }
 func(s *Server) subscribeevents() {
+	http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
 	for {
 		select {
-			case info:= <-s.devicechan:
-				ip_address:= info.IpAddress
+		case info:= <-s.devicechan:
+			ip_address:= info.IpAddress
 			fmt.Println("Configuring  %s ...", ip_address)
 			// call subscription function with info.IpAddress
+			for _, event := range default_events {
+				rtn, id := add_subscription(ip_address, event)
+				if rtn {
+					s.devicemap[ip_address].subscriptions[event] = id
+					fmt.Println("subscription added", event, id)
+				}
+			}
 		}
 	}
 }
+
 func NewGrpcServer(grpcport string) (l net.Listener, g *grpc.Server, e error) {
         fmt.Println("Listening %s ...", grpcport)
         g = grpc.NewServer()