<commit_before>package web

import (
	"bufio"
	"fmt"
	"ldpserver/fileio"
	"ldpserver/ldp"
	"ldpserver/rdf"
	"ldpserver/server"
	"ldpserver/util"
	"log"
	"net/http"
	"os"
	"strings"
)

var stdin *bufio.Reader
var theServer server.Server

func Start(address, dataPath string) {
	theServer = server.NewServer("http://"+address, dataPath)
	stdin = bufio.NewReader(os.Stdin)
	log.Printf("Listening for requests at %s\n", "http://"+address)
	log.Printf("Data folder: %s\n", dataPath)
	http.HandleFunc("/", homePage)
	err := http.ListenAndServe(address, nil)
	if err != nil {
		log.Fatal("Failed to start the web server: ", err)
	}
}

func homePage(resp http.ResponseWriter, req *http.Request) {
	readline()
	if req.Method == "GET" {
		handleGet(true, resp, req)
	} else if req.Method == "HEAD" {
		handleGet(false, resp, req)
	} else if req.Method == "POST" {
		handlePost(resp, req)
	} else if req.Method == "PUT" {
		handlePut(resp, req)
	} else if req.Method == "PATCH" {
		handlePatch(resp, req)
	} else if req.Method == "OPTIONS" {
		handleOptions(resp, req)
	} else {
		log.Printf("Unknown request type %s", req.Method)
	}
}

func handleGet(includeBody bool, resp http.ResponseWriter, req *http.Request) {
	var node ldp.Node
	var err error

	logHeaders(req)
	path := safePath(req.URL.Path)
	if includeBody {
		log.Printf("GET request %s", path)
		node, err = theServer.GetNode(path)
	} else {
		log.Printf("HEAD request %s", path)
		node, err = theServer.GetHead(path)
	}
	if err != nil {
		if err == ldp.NodeNotFoundError {
			log.Printf("Not found %s", path)
			http.NotFound(resp, req)
		} else {
			log.Printf("Error %s", err)
			http.Error(resp, "Could not fetch resource", http.StatusInternalServerError)
		}
		return
	}

	for key, header := range node.Headers() {
		for _, value := range header {
			resp.Header().Add(key, value)
		}
	}

	if etag := requestIfNoneMatch(req.Header); etag != "" {
		if etag == node.Etag() {
			resp.WriteHeader(http.StatusNotModified)
			return
		}
	}

	fmt.Fprint(resp, node.Content())
}

func handleOptions(resp http.ResponseWriter, req *http.Request) {
	logHeaders(req)
	path := safePath(req.URL.Path)
	node, err := theServer.GetNode(path)
	if err != nil {
		log.Printf("Error %s", err)
		http.Error(resp, "Could not fetch resource", http.StatusInternalServerError)
		return
	}

	for key, header := range node.Headers() {
		for _, value := range header {
			resp.Header().Add(key, value)
		}
	}
}

func handlePost(resp http.ResponseWriter, req *http.Request) {
	logHeaders(req)
	slug := getSlug(req.Header)
	path := safePath(req.URL.Path)
	doPostPut(resp, req, path, slug)
}

func handlePut(resp http.ResponseWriter, req *http.Request) {
	logHeaders(req)

	if getSlug(req.Header) != "" {
		logReqError(req, "Unexpected client provided Slug in PUT request", http.StatusBadRequest)
		http.Error(resp, "Slug is not accepted on PUT requests", http.StatusBadRequest)
		return
	}

	// Use the last segment of the path as the
	// slug (i.e. the ID of the resource to write.)
	//
	// TODO: handle
	// testE := []string{"a", ".", "a"}
	// testF := []string{"a/", ".", "a"}
	// testG := []string{"/a/", "/", "a"}
	//
	path, slug := util.DirBasePath(safePath(req.URL.Path))
	doPut(resp, req, path, slug)
}

func doPut(resp http.ResponseWriter, req *http.Request, path string, slug string) {
	var node ldp.Node
	var triples string
	var err error

	etag := requestIfMatch(req.Header)

	if isNonRdfPost(req.Header) {
		panic("TODO: re-implement PUT for non rdf")
		// // We should pass some hints too
		// // (e.g. application type, file name)
		// log.Printf("Creating Non-RDF Source at %s", path)
		// node, err = theServer.CreateNonRdfSource(req.Body, path, slug)
	} else {
		log.Printf("Creating RDF Source %s at %s", slug, path)
		triples, err = fileio.ReaderToString(req.Body)
		if err != nil {
			logReqError(req, err.Error(), http.StatusBadRequest)
			http.Error(resp, "Invalid request body received", http.StatusBadRequest)
			return
		}
		node, err = theServer.ReplaceRdfSource(triples, path, slug, etag)
	}

	if err != nil {
		errorMsg := err.Error()
		errorCode := http.StatusBadRequest
		if err == ldp.NodeNotFoundError {
			errorMsg = "Parent container [" + path + "] not found."
			errorCode = http.StatusNotFound
		} else if err == ldp.DuplicateNodeError {
			errorMsg = fmt.Sprintf("Resource already exists. Path: %s Slug: %s", path, slug)
			errorCode = http.StatusConflict
		} else if err == ldp.EtagMissingError {
			errorMsg = fmt.Sprintf("Etag missing. Path: %s Slug: %s", path, slug)
			errorCode = 428 // precondition required
		} else if err == ldp.EtagMismatchError {
			errorMsg = fmt.Sprintf("Etag mismatch. Path: %s Slug: %s", path, slug)
			errorCode = http.StatusPreconditionFailed
		}
		logReqError(req, errorMsg, errorCode)
		http.Error(resp, errorMsg, errorCode)
		return
	}

	resp.Header().Add("Location", node.Uri())
	resp.WriteHeader(http.StatusCreated)
	log.Printf("Resource created at %s", node.Uri())
	fmt.Fprint(resp, node.Uri())
}

func doPostPut(resp http.ResponseWriter, req *http.Request, path string, slug string) {
	var node ldp.Node
	var triples string
	var err error

	if isNonRdfPost(req.Header) {
		// We should pass some hints too
		// (e.g. application type, file name)
		log.Printf("Creating Non-RDF Source at %s", path)
		node, err = theServer.CreateNonRdfSource(req.Body, path, slug)
	} else {
		log.Printf("Creating RDF Source %s at %s", slug, path)
		triples, err = fileio.ReaderToString(req.Body)
		if err != nil {
			logReqError(req, err.Error(), http.StatusBadRequest)
			http.Error(resp, "Invalid request body received", http.StatusBadRequest)
			return
		}
		node, err = theServer.CreateRdfSource(triples, path, slug)
	}

	if err == nil {
		resp.Header().Add("Location", node.Uri())
		resp.WriteHeader(http.StatusCreated)
	} else {
		errorMsg := err.Error()
		errorCode := http.StatusBadRequest
		if err == ldp.NodeNotFoundError {
			errorMsg = "Parent container [" + path + "] not found."
			errorCode = http.StatusNotFound
		} else if err == ldp.DuplicateNodeError {
			errorMsg = fmt.Sprintf("Resource already exists. Path: %s Slug: %s", path, slug)
			errorCode = http.StatusConflict
		}
		logReqError(req, errorMsg, errorCode)
		http.Error(resp, errorMsg, errorCode)
		return
	}

	log.Printf("Resource created at %s", node.Uri())
	fmt.Fprint(resp, node.Uri())
}

func handlePatch(resp http.ResponseWriter, req *http.Request) {

	if !isRdfContentType(req.Header) {
		errorMsg := fmt.Sprintf("Invalid Content-Type (%s) received", requestContentType(req.Header))
		logReqError(req, errorMsg, http.StatusBadRequest)
		http.Error(resp, errorMsg, http.StatusBadRequest)
		return
	}

	path := safePath(req.URL.Path)
	log.Printf("Patching %s", path)

	triples, err := fileio.ReaderToString(req.Body)
	if err != nil {
		errorMsg := fmt.Sprintf("Invalid body received. Error: %s", err.Error())
		logReqError(req, errorMsg, http.StatusBadRequest)
		http.Error(resp, errorMsg, http.StatusBadRequest)
		return
	}

	err = theServer.PatchNode(path, triples)
	if err != nil {
		errorMsg := err.Error()
		if err == ldp.NodeNotFoundError {
			logReqError(req, errorMsg, http.StatusNotFound)
			http.NotFound(resp, req)
		} else {
			logReqError(req, errorMsg, http.StatusInternalServerError)
			http.Error(resp, errorMsg, http.StatusInternalServerError)
		}
		return
	}

	fmt.Fprint(resp, req.URL.Path)
}

func isNonRdfPost(header http.Header) bool {
	return !isRdfContentType(header)
}

func safePath(rawPath string) string {
	if strings.HasSuffix(rawPath, "/") {
		return rawPath
	}
	return rawPath + "/"
}

func getSlug(header http.Header) string {
	for _, value := range header["Slug"] {
		return value
	}
	return ""
}

func requestContentType(header http.Header) string {
	for _, value := range header["Content-Type"] {
		return value
	}
	return rdf.TurtleContentType
}

func requestIfNoneMatch(header http.Header) string {
	for _, value := range header["If-None-Match"] {
		return value
	}
	return ""
}

func requestIfMatch(header http.Header) string {
	for _, value := range header["If-Match"] {
		return value
	}
	return ""
}

func isRdfContentType(header http.Header) bool {
	contentType := requestContentType(header)
	return strings.HasPrefix(contentType, rdf.TurtleContentType)
}

func logHeaders(req *http.Request) {
	log.Printf("==> HTTP Headers %s %s", req.Method, req.URL.Path)
	for header, values := range req.Header {
		for _, value := range values {
			log.Printf("\t\t %s %s", header, value)
		}
	}
}

func logReqError(req *http.Request, message string, code int) {
	log.Printf("Error %d on %s %s: %s", code, req.Method, req.URL.Path, message)
}

func readline() {
	return
	log.Print("Hit [ENTER]")
	stdin.ReadString('\n')
}
<commit_msg>Refactor code that handles PUT and POST<commit_after>package web

import (
	"bufio"
	"errors"
	"fmt"
	"ldpserver/fileio"
	"ldpserver/ldp"
	"ldpserver/rdf"
	"ldpserver/server"
	"ldpserver/util"
	"log"
	"net/http"
	"os"
	"strings"
)

var stdin *bufio.Reader
var theServer server.Server

func Start(address, dataPath string) {
	theServer = server.NewServer("http://"+address, dataPath)
	stdin = bufio.NewReader(os.Stdin)
	log.Printf("Listening for requests at %s\n", "http://"+address)
	log.Printf("Data folder: %s\n", dataPath)
	http.HandleFunc("/", homePage)
	err := http.ListenAndServe(address, nil)
	if err != nil {
		log.Fatal("Failed to start the web server: ", err)
	}
}

func homePage(resp http.ResponseWriter, req *http.Request) {
	readline()
	if req.Method == "GET" {
		handleGet(true, resp, req)
	} else if req.Method == "HEAD" {
		handleGet(false, resp, req)
	} else if req.Method == "POST" {
		handlePost(resp, req)
	} else if req.Method == "PUT" {
		handlePut(resp, req)
	} else if req.Method == "PATCH" {
		handlePatch(resp, req)
	} else if req.Method == "OPTIONS" {
		handleOptions(resp, req)
	} else {
		log.Printf("Unknown request type %s", req.Method)
	}
}

func handleGet(includeBody bool, resp http.ResponseWriter, req *http.Request) {
	var node ldp.Node
	var err error

	logHeaders(req)
	path := safePath(req.URL.Path)
	if includeBody {
		log.Printf("GET request %s", path)
		node, err = theServer.GetNode(path)
	} else {
		log.Printf("HEAD request %s", path)
		node, err = theServer.GetHead(path)
	}
	if err != nil {
		if err == ldp.NodeNotFoundError {
			log.Printf("Not found %s", path)
			http.NotFound(resp, req)
		} else {
			log.Printf("Error %s", err)
			http.Error(resp, "Could not fetch resource", http.StatusInternalServerError)
		}
		return
	}

	for key, header := range node.Headers() {
		for _, value := range header {
			resp.Header().Add(key, value)
		}
	}

	if etag := requestIfNoneMatch(req.Header); etag != "" {
		if etag == node.Etag() {
			resp.WriteHeader(http.StatusNotModified)
			return
		}
	}

	fmt.Fprint(resp, node.Content())
}

func handleOptions(resp http.ResponseWriter, req *http.Request) {
	logHeaders(req)
	path := safePath(req.URL.Path)
	node, err := theServer.GetNode(path)
	if err != nil {
		log.Printf("Error %s", err)
		http.Error(resp, "Could not fetch resource", http.StatusInternalServerError)
		return
	}

	for key, header := range node.Headers() {
		for _, value := range header {
			resp.Header().Add(key, value)
		}
	}
}

func handlePatch(resp http.ResponseWriter, req *http.Request) {
	if !isRdfContentType(req.Header) {
		errorMsg := fmt.Sprintf("Invalid Content-Type (%s) received", requestContentType(req.Header))
		logReqError(req, errorMsg, http.StatusBadRequest)
		http.Error(resp, errorMsg, http.StatusBadRequest)
		return
	}

	path := safePath(req.URL.Path)
	log.Printf("Patching %s", path)

	triples, err := fileio.ReaderToString(req.Body)
	if err != nil {
		errorMsg := fmt.Sprintf("Invalid body received. Error: %s", err.Error())
		logReqError(req, errorMsg, http.StatusBadRequest)
		http.Error(resp, errorMsg, http.StatusBadRequest)
		return
	}

	err = theServer.PatchNode(path, triples)
	if err != nil {
		errorMsg := err.Error()
		if err == ldp.NodeNotFoundError {
			logReqError(req, errorMsg, http.StatusNotFound)
			http.NotFound(resp, req)
		} else {
			logReqError(req, errorMsg, http.StatusInternalServerError)
			http.Error(resp, errorMsg, http.StatusInternalServerError)
		}
		return
	}

	fmt.Fprint(resp, req.URL.Path)
}

func handlePost(resp http.ResponseWriter, req *http.Request) {
	logHeaders(req)

	slug := getSlug(req.Header)
	path := safePath(req.URL.Path)
	node, err := doPost(resp, req, path, slug)
	if err != nil {
		handlePostPutError(resp, req, err)
		return
	}

	handlePostPutSuccess(resp, node)
}

func handlePostPutSuccess(resp http.ResponseWriter, node ldp.Node) {
	resp.Header().Add("Location", node.Uri())
	resp.WriteHeader(http.StatusCreated)
	log.Printf("Resource created at %s", node.Uri())
	fmt.Fprint(resp, node.Uri())
}

func handlePostPutError(resp http.ResponseWriter, req *http.Request, err error) {
	errorMsg := err.Error()
	errorCode := http.StatusBadRequest
	path := req.URL.Path
	slug := getSlug(req.Header)
	if err == ldp.NodeNotFoundError {
		errorMsg = "Parent container [" + path + "] not found."
		errorCode = http.StatusNotFound
	} else if err == ldp.DuplicateNodeError {
		errorMsg = fmt.Sprintf("Resource already exists. Path: %s Slug: %s", path, slug)
		errorCode = http.StatusConflict
	} else if err == ldp.EtagMissingError {
		errorMsg = fmt.Sprintf("Etag missing. Path: %s Slug: %s", path, slug)
		errorCode = 428 // precondition required
	} else if err == ldp.EtagMismatchError {
		errorMsg = fmt.Sprintf("Etag mismatch. Path: %s Slug: %s", path, slug)
		errorCode = http.StatusPreconditionFailed
	}
	logReqError(req, errorMsg, errorCode)
	http.Error(resp, errorMsg, errorCode)
}

func handlePut(resp http.ResponseWriter, req *http.Request) {
	logHeaders(req)

	node, err := doPut(resp, req)
	if err != nil {
		handlePostPutError(resp, req, err)
		return
	}

	handlePostPutSuccess(resp, node)
}

func doPost(resp http.ResponseWriter, req *http.Request, path string, slug string) (ldp.Node, error) {
	if isNonRdfPost(req.Header) {
		// We should pass some hints too
		// (e.g. application type, file name)
		log.Printf("Creating Non-RDF Source at %s", path)
		return theServer.CreateNonRdfSource(req.Body, path, slug)
	}

	log.Printf("Creating RDF Source %s at %s", slug, path)
	triples, err := fileio.ReaderToString(req.Body)
	if err != nil {
		return ldp.Node{}, err
	}
	return theServer.CreateRdfSource(triples, path, slug)
}

func doPut(resp http.ResponseWriter, req *http.Request) (ldp.Node, error) {
	if getSlug(req.Header) != "" {
		return ldp.Node{}, errors.New("Slug is not accepted on PUT requests")
	}

	etag := requestIfMatch(req.Header)

	if isNonRdfPost(req.Header) {
		// We should pass some hints too
		// (e.g. application type, file name)
		path := req.URL.Path
		log.Printf("Creating Non-RDF Source at %s", path)
		return theServer.ReplaceNonRdfSource(req.Body, path, etag)
	}

	path, slug := util.DirBasePath(safePath(req.URL.Path))
	log.Printf("Creating RDF Source %s at %s", slug, path)
	triples, err := fileio.ReaderToString(req.Body)
	if err != nil {
		return ldp.Node{}, errors.New("Invalid request body received")
	}
	return theServer.ReplaceRdfSource(triples, path, slug, etag)
}

func isNonRdfPost(header http.Header) bool {
	return !isRdfContentType(header)
}

func safePath(rawPath string) string {
	if strings.HasSuffix(rawPath, "/") {
		return rawPath
	}
	return rawPath + "/"
}

func getSlug(header http.Header) string {
	for _, value := range header["Slug"] {
		return value
	}
	return ""
}

func requestContentType(header http.Header) string {
	for _, value := range header["Content-Type"] {
		return value
	}
	return rdf.TurtleContentType
}

func requestIfNoneMatch(header http.Header) string {
	for _, value := range header["If-None-Match"] {
		return value
	}
	return ""
}

func requestIfMatch(header http.Header) string {
	for _, value := range header["If-Match"] {
		return value
	}
	return ""
}

func isRdfContentType(header http.Header) bool {
	contentType := requestContentType(header)
	return strings.HasPrefix(contentType, rdf.TurtleContentType)
}

func logHeaders(req *http.Request) {
	log.Printf("==> HTTP Headers %s %s", req.Method, req.URL.Path)
	for header, values := range req.Header {
		for _, value := range values {
			log.Printf("\t\t %s %s", header, value)
		}
	}
}

func logReqError(req *http.Request, message string, code int) {
	log.Printf("Error %d on %s %s: %s", code, req.Method, req.URL.Path, message)
}

func readline() {
	return
	log.Print("Hit [ENTER]")
	stdin.ReadString('\n')
}
<|endoftext|>


<commit_before>package adapter

import (
	"net/http"
	"regexp"
	"strings"

	"github.com/CenturyLinkLabs/pmxadapter"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/api"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/api/errors"
)

var (
	DefaultExecutor       Executor
	illegalNameCharacters = regexp.MustCompile(`[\W_]+`)
)

func init() {
	// TODO Need to instantiate with the correct connection info?
	DefaultExecutor = NewKubernetesExecutor("http://104.131.157.89:8080")
}

type KubernetesAdapter struct{}

func (a KubernetesAdapter) GetServices() ([]pmxadapter.ServiceDeployment, *pmxadapter.Error) {
	rcs, err := DefaultExecutor.GetReplicationControllers()
	if err != nil {
		pmxErr := pmxadapter.NewError(http.StatusInternalServerError, err.Error())
		return []pmxadapter.ServiceDeployment{}, pmxErr
	}

	sds := make([]pmxadapter.ServiceDeployment, len(rcs))
	for i, rc := range rcs {
		sds[i].ID = rc.ObjectMeta.Name
		sds[i].ActualState = statusFromReplicationController(rc)
	}
	return sds, nil
}

func (a KubernetesAdapter) GetService(id string) (pmxadapter.ServiceDeployment, *pmxadapter.Error) {
	rc, err := DefaultExecutor.GetReplicationController(id)
	if err != nil {
		if sErr, ok := err.(*errors.StatusError); ok && sErr.ErrStatus.Reason == api.StatusReasonNotFound {
			return pmxadapter.ServiceDeployment{}, pmxadapter.NewError(http.StatusNotFound, err.Error())
		}

		pmxErr := pmxadapter.NewError(http.StatusInternalServerError, err.Error())
		return pmxadapter.ServiceDeployment{}, pmxErr
	}

	sd := pmxadapter.ServiceDeployment{
		ID:          rc.ObjectMeta.Name,
		ActualState: statusFromReplicationController(rc),
	}
	return sd, nil
}

func (a KubernetesAdapter) CreateServices(services []*pmxadapter.Service) ([]pmxadapter.ServiceDeployment, *pmxadapter.Error) {
	deployments := make([]pmxadapter.ServiceDeployment, len(services))

	for i, s := range services {
		safeName := sanitizeServiceName(s.Name)

		rcSpec := api.ReplicationController{
			ObjectMeta: api.ObjectMeta{
				Name: safeName,
			},
			Spec: api.ReplicationControllerSpec{
				Replicas: s.Deployment.Count,
				Selector: map[string]string{"name": safeName},
				Template: &api.PodTemplateSpec{
					ObjectMeta: api.ObjectMeta{
						Labels: map[string]string{"name": safeName},
					},
					Spec: api.PodSpec{
						Containers: []api.Container{
							{
								// You're still missing a huge number of these things, from
								// Brian's 'manifest'.
								//container[:command] = command if command
								//container[:ports] = port_mapping if ports.any?
								//container[:env] = environment_mapping if environment.any?
								Name:    safeName,
								Image:   s.Source,
								Command: []string{s.Command},
							},
						},
					},
				},
			},
		}

		rc, err := DefaultExecutor.CreateReplicationController(rcSpec)
		if err != nil {
			if sErr, ok := err.(*errors.StatusError); ok && sErr.ErrStatus.Reason == api.StatusReasonAlreadyExists {
				return nil, pmxadapter.NewError(http.StatusConflict, err.Error())
			}
			return nil, pmxadapter.NewError(http.StatusInternalServerError, err.Error())
		}

		deployments[i].ID = rc.ObjectMeta.Name
		deployments[i].ActualState = statusFromReplicationController(rc)
	}

	return deployments, nil
}

func (a KubernetesAdapter) UpdateService(s *pmxadapter.Service) *pmxadapter.Error {
	return nil
}

func (a KubernetesAdapter) DestroyService(id string) *pmxadapter.Error {
	err := DefaultExecutor.DeleteReplicationController(id)
	if err != nil {
		if sErr, ok := err.(*errors.StatusError); ok && sErr.ErrStatus.Reason == api.StatusReasonNotFound {
			return pmxadapter.NewError(http.StatusNotFound, err.Error())
		}

		return pmxadapter.NewError(http.StatusInternalServerError, err.Error())
	}

	return nil
}

func (a KubernetesAdapter) GetMetadata() pmxadapter.Metadata {
	return pmxadapter.Metadata{Type: "Sample", Version: "0.1"}
}

func sanitizeServiceName(n string) string {
	s := illegalNameCharacters.ReplaceAllString(n, "-")
	return strings.ToLower(s)
}

func statusFromReplicationController(rc api.ReplicationController) string {
	desired := rc.Spec.Replicas
	actual := rc.Status.Replicas

	if actual < desired {
		return "pending"
	} else if desired == actual {
		return "running"
	}
	return "unknown"
}
<commit_msg>Remove unneeded UpdateService method.<commit_after>package adapter

import (
	"net/http"
	"regexp"
	"strings"

	"github.com/CenturyLinkLabs/pmxadapter"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/api"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/api/errors"
)

var (
	DefaultExecutor       Executor
	illegalNameCharacters = regexp.MustCompile(`[\W_]+`)
)

func init() {
	// TODO Need to instantiate with the correct connection info?
	DefaultExecutor = NewKubernetesExecutor("http://104.131.157.89:8080")
}

type KubernetesAdapter struct{}

func (a KubernetesAdapter) GetServices() ([]pmxadapter.ServiceDeployment, *pmxadapter.Error) {
	rcs, err := DefaultExecutor.GetReplicationControllers()
	if err != nil {
		pmxErr := pmxadapter.NewError(http.StatusInternalServerError, err.Error())
		return []pmxadapter.ServiceDeployment{}, pmxErr
	}

	sds := make([]pmxadapter.ServiceDeployment, len(rcs))
	for i, rc := range rcs {
		sds[i].ID = rc.ObjectMeta.Name
		sds[i].ActualState = statusFromReplicationController(rc)
	}
	return sds, nil
}

func (a KubernetesAdapter) GetService(id string) (pmxadapter.ServiceDeployment, *pmxadapter.Error) {
	rc, err := DefaultExecutor.GetReplicationController(id)
	if err != nil {
		if sErr, ok := err.(*errors.StatusError); ok && sErr.ErrStatus.Reason == api.StatusReasonNotFound {
			return pmxadapter.ServiceDeployment{}, pmxadapter.NewError(http.StatusNotFound, err.Error())
		}

		pmxErr := pmxadapter.NewError(http.StatusInternalServerError, err.Error())
		return pmxadapter.ServiceDeployment{}, pmxErr
	}

	sd := pmxadapter.ServiceDeployment{
		ID:          rc.ObjectMeta.Name,
		ActualState: statusFromReplicationController(rc),
	}
	return sd, nil
}

func (a KubernetesAdapter) CreateServices(services []*pmxadapter.Service) ([]pmxadapter.ServiceDeployment, *pmxadapter.Error) {
	deployments := make([]pmxadapter.ServiceDeployment, len(services))

	for i, s := range services {
		safeName := sanitizeServiceName(s.Name)

		rcSpec := api.ReplicationController{
			ObjectMeta: api.ObjectMeta{
				Name: safeName,
			},
			Spec: api.ReplicationControllerSpec{
				Replicas: s.Deployment.Count,
				Selector: map[string]string{"name": safeName},
				Template: &api.PodTemplateSpec{
					ObjectMeta: api.ObjectMeta{
						Labels: map[string]string{"name": safeName},
					},
					Spec: api.PodSpec{
						Containers: []api.Container{
							{
								// You're still missing a huge number of these things, from
								// Brian's 'manifest'.
								//container[:command] = command if command
								//container[:ports] = port_mapping if ports.any?
								//container[:env] = environment_mapping if environment.any?
								Name:    safeName,
								Image:   s.Source,
								Command: []string{s.Command},
							},
						},
					},
				},
			},
		}

		rc, err := DefaultExecutor.CreateReplicationController(rcSpec)
		if err != nil {
			if sErr, ok := err.(*errors.StatusError); ok && sErr.ErrStatus.Reason == api.StatusReasonAlreadyExists {
				return nil, pmxadapter.NewError(http.StatusConflict, err.Error())
			}
			return nil, pmxadapter.NewError(http.StatusInternalServerError, err.Error())
		}

		deployments[i].ID = rc.ObjectMeta.Name
		deployments[i].ActualState = statusFromReplicationController(rc)
	}

	return deployments, nil
}

func (a KubernetesAdapter) DestroyService(id string) *pmxadapter.Error {
	err := DefaultExecutor.DeleteReplicationController(id)
	if err != nil {
		if sErr, ok := err.(*errors.StatusError); ok && sErr.ErrStatus.Reason == api.StatusReasonNotFound {
			return pmxadapter.NewError(http.StatusNotFound, err.Error())
		}

		return pmxadapter.NewError(http.StatusInternalServerError, err.Error())
	}

	return nil
}

func (a KubernetesAdapter) GetMetadata() pmxadapter.Metadata {
	return pmxadapter.Metadata{Type: "Sample", Version: "0.1"}
}

func sanitizeServiceName(n string) string {
	s := illegalNameCharacters.ReplaceAllString(n, "-")
	return strings.ToLower(s)
}

func statusFromReplicationController(rc api.ReplicationController) string {
	desired := rc.Spec.Replicas
	actual := rc.Status.Replicas

	if actual < desired {
		return "pending"
	} else if desired == actual {
		return "running"
	}
	return "unknown"
}
<|endoftext|>


<commit_before>package commands

import (
	cmds "github.com/jbenet/go-ipfs/commands"
	u "github.com/jbenet/go-ipfs/util"
)

var log = u.Logger("core/commands")

type TestOutput struct {
	Foo string
	Bar int
}

var Root = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "global p2p merkle-dag filesystem",
		Synopsis: `
ipfs [<flags>] <command> [<arg>] ...
`,
		ShortDescription: `
Basic commands:

    init          Initialize ipfs local configurationx
    add <path>    Add an object to ipfs
    cat <ref>     Show ipfs object data
    ls <ref>      List links from an object

Tool commands:

    config        Manage configuration
    update        Download and apply go-ipfs updates
    version       Show ipfs version information
    commands      List all available commands
    id            Show info about ipfs peers

Advanced Commands:

    daemon        Start a long-running daemon process
    mount         Mount an ipfs read-only mountpoint
    serve         Serve an interface to ipfs
    diag          Print diagnostics

Plumbing commands:

    block         Interact with raw blocks in the datastore
    object        Interact with raw dag nodes

Use 'ipfs <command> --help' to learn more about each command.
`,
	},
	Options: []cmds.Option{
		cmds.StringOption("config", "c", "Path to the configuration file to use"),
		cmds.BoolOption("debug", "D", "Operate in debug mode"),
		cmds.BoolOption("help", "Show the full command help text"),
		cmds.BoolOption("h", "Show a short version of the command help text"),
		cmds.BoolOption("local", "L", "Run the command locally, instead of using the daemon"),
	},
}

// commandsDaemonCmd is the "ipfs commands" command for daemon
var CommandsDaemonCmd = CommandsCmd(Root)

var rootSubcommands = map[string]*cmds.Command{
	"cat":       catCmd,
	"ls":        lsCmd,
	"commands":  CommandsDaemonCmd,
	"name":      nameCmd,
	"add":       addCmd,
	"log":       LogCmd,
	"diag":      DiagCmd,
	"pin":       pinCmd,
	"version":   VersionCmd,
	"config":    configCmd,
	"bootstrap": bootstrapCmd,
	"mount":     mountCmd,
	"block":     blockCmd,
	"update":    UpdateCmd,
	"object":    objectCmd,
	"refs":      refsCmd,
	"id":        idCmd,
	"swarm":     swarmCmd,
}

func init() {
	Root.Subcommands = rootSubcommands
	u.SetLogLevel("core/commands", "info")
}

type MessageOutput struct {
	Message string
}

func MessageTextMarshaler(res cmds.Response) ([]byte, error) {
	return []byte(res.Output().(*MessageOutput).Message), nil
}
<commit_msg>cmds: remove info logging<commit_after>package commands

import (
	cmds "github.com/jbenet/go-ipfs/commands"
	u "github.com/jbenet/go-ipfs/util"
)

var log = u.Logger("core/commands")

type TestOutput struct {
	Foo string
	Bar int
}

var Root = &cmds.Command{
	Helptext: cmds.HelpText{
		Tagline: "global p2p merkle-dag filesystem",
		Synopsis: `
ipfs [<flags>] <command> [<arg>] ...
`,
		ShortDescription: `
Basic commands:

    init          Initialize ipfs local configurationx
    add <path>    Add an object to ipfs
    cat <ref>     Show ipfs object data
    ls <ref>      List links from an object

Tool commands:

    config        Manage configuration
    update        Download and apply go-ipfs updates
    version       Show ipfs version information
    commands      List all available commands
    id            Show info about ipfs peers

Advanced Commands:

    daemon        Start a long-running daemon process
    mount         Mount an ipfs read-only mountpoint
    serve         Serve an interface to ipfs
    diag          Print diagnostics

Plumbing commands:

    block         Interact with raw blocks in the datastore
    object        Interact with raw dag nodes

Use 'ipfs <command> --help' to learn more about each command.
`,
	},
	Options: []cmds.Option{
		cmds.StringOption("config", "c", "Path to the configuration file to use"),
		cmds.BoolOption("debug", "D", "Operate in debug mode"),
		cmds.BoolOption("help", "Show the full command help text"),
		cmds.BoolOption("h", "Show a short version of the command help text"),
		cmds.BoolOption("local", "L", "Run the command locally, instead of using the daemon"),
	},
}

// commandsDaemonCmd is the "ipfs commands" command for daemon
var CommandsDaemonCmd = CommandsCmd(Root)

var rootSubcommands = map[string]*cmds.Command{
	"cat":       catCmd,
	"ls":        lsCmd,
	"commands":  CommandsDaemonCmd,
	"name":      nameCmd,
	"add":       addCmd,
	"log":       LogCmd,
	"diag":      DiagCmd,
	"pin":       pinCmd,
	"version":   VersionCmd,
	"config":    configCmd,
	"bootstrap": bootstrapCmd,
	"mount":     mountCmd,
	"block":     blockCmd,
	"update":    UpdateCmd,
	"object":    objectCmd,
	"refs":      refsCmd,
	"id":        idCmd,
	"swarm":     swarmCmd,
}

func init() {
	Root.Subcommands = rootSubcommands
}

type MessageOutput struct {
	Message string
}

func MessageTextMarshaler(res cmds.Response) ([]byte, error) {
	return []byte(res.Output().(*MessageOutput).Message), nil
}
<|endoftext|>


<commit_before>package converter

import "github.com/lastbackend/lastbackend/libs/model"

func ToDocker (model *model.Container) {

}

func FromDocker () *model.Container{

}
<commit_msg>fix docker convertor<commit_after>package converter

import "github.com/lastbackend/lastbackend/libs/model"

func ToDocker (model *model.Container) {
}

func FromDocker () *model.Container{
	return new(model.Container)
}
<|endoftext|>


<commit_before>// Copyright (c) 2015 Andrii Pylypenko. All rights reserved.
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package sippy_types

import (
    "sync"
    "time"

    "sippy/conf"
    "sippy/headers"
    "sippy/sdp"
    "sippy/time"
)

type CallController interface {
    RecvEvent(CCEvent, UA)
}

type RequestReceiver interface {
    RecvRequest(SipRequest, ServerTransaction) *Ua_context
}

type ResponseReceiver interface {
    RecvResponse(SipResponse, ClientTransaction)
}

type CallMap interface {
    OnNewDialog(SipRequest, ServerTransaction) (UA, RequestReceiver, SipResponse)
}

type SipMsg interface {
    GetSipUserAgent() *sippy_header.SipUserAgent
    GetSipServer() *sippy_header.SipServer
    LocalStr(hostport *sippy_conf.HostPort, compact bool) string
    GetCSeq() *sippy_header.SipCSeq
    GetTId(wCSM, wBRN, wTTG bool) *sippy_header.TID
    GetTo() *sippy_header.SipTo
    GetReason() *sippy_header.SipReason
    AppendHeader(hdr sippy_header.SipHeader)
    GetVias() []*sippy_header.SipVia
    GetCallId() *sippy_header.SipCallId
    SetRtime(*sippy_time.MonoTime)
    GetTarget() *sippy_conf.HostPort
    SetTarget(address *sippy_conf.HostPort)
    InsertFirstVia(*sippy_header.SipVia)
    RemoveFirstVia()
    SetRoutes([]*sippy_header.SipRoute)
    GetFrom() *sippy_header.SipFrom
    GetRtime() *sippy_time.MonoTime
    GetAlso() []*sippy_header.SipAlso
    GetBody() MsgBody
    SetBody(MsgBody)
    GetContacts() []*sippy_header.SipContact
    GetRecordRoutes() []*sippy_header.SipRecordRoute
    GetCGUID() *sippy_header.SipCiscoGUID
    GetH323ConfId() *sippy_header.SipH323ConfId
    GetSipAuthorization() *sippy_header.SipAuthorization
    GetSource() *sippy_conf.HostPort
    GetFirstHF(string) sippy_header.SipHeader
    GetHFs(string) []sippy_header.SipHeader
}

type SipRequest interface {
    SipMsg
    GetSipProxyAuthorization() *sippy_header.SipProxyAuthorization
    GenResponse(int, string, MsgBody, *sippy_header.SipServer) SipResponse
    GetMethod() string
    GetExpires() *sippy_header.SipExpires
    GenACK(to *sippy_header.SipTo, config sippy_conf.Config) SipRequest
    GenCANCEL(sippy_conf.Config) SipRequest
    GetRURI() *sippy_header.SipURL
    SetRURI(ruri *sippy_header.SipURL)
    GetReferTo() *sippy_header.SipReferTo
    GetNated() bool
}

type SipResponse interface {
    SipMsg
    GetSCode() (int, string)
    SetSCode(int, string)
    GetSCodeNum() int
    GetSipWWWAuthenticate() *sippy_header.SipWWWAuthenticate
    GetSipProxyAuthenticate() *sippy_header.SipProxyAuthenticate
    SetReason(string)
    GetCopy() SipResponse
}

type UdpServer interface {
    GetLaddress() *sippy_conf.HostPort
    SendTo([]byte, string, string)
}

type MsgBody interface {
    String() string
    GetMtype() string
    LocalStr(hostport *sippy_conf.HostPort) string
    GetCopy() MsgBody
    NeedsUpdate() bool
    SetNeedsUpdate(bool)
    GetParsedBody() ParsedMsgBody
    AppendAHeader(string)
}

type ParsedMsgBody interface {
    String() string
    LocalStr(hostport *sippy_conf.HostPort) string
    GetCopy() ParsedMsgBody
    SetCHeaderAddr(string)
    GetSections() []*sippy_sdp.SdpMediaDescription
    SetSections([]*sippy_sdp.SdpMediaDescription)
    RemoveSection(int)
    SetOHeader(*sippy_sdp.SdpOrigin)
    AppendAHeader(string)
}

type UA interface {
    OnUnregister()
    RequestReceiver
    ResponseReceiver
    GetSessionLock() sync.Locker
    RecvEvent(CCEvent)
    SipTM() SipTransactionManager
    GetSetupTs() *sippy_time.MonoTime
    SetSetupTs(*sippy_time.MonoTime)
    GetDisconnectTs() *sippy_time.MonoTime
    SetDisconnectTs(*sippy_time.MonoTime)
    GetOrigin() string
    SetOrigin(string)
    HasOnLocalSdpChange() bool
    OnLocalSdpChange(MsgBody, CCEvent, func(MsgBody))
    SetOnLocalSdpChange(OnLocalSdpChange)
    ResetOnLocalSdpChange()
    OnRemoteSdpChange(MsgBody, SipMsg, func(MsgBody))
    HasOnRemoteSdpChange() bool
    ResetOnRemoteSdpChange()
    SetCallId(*sippy_header.SipCallId)
    GetCallId() *sippy_header.SipCallId
    SetRTarget(*sippy_header.SipURL)
    GetRAddr() *sippy_conf.HostPort
    SetRAddr(addr *sippy_conf.HostPort)
    GetRAddr0() *sippy_conf.HostPort
    SetRAddr0(addr *sippy_conf.HostPort)
    GetRTarget() *sippy_header.SipURL
    SetRUri(*sippy_header.SipTo)
    GetRuriUserparams() []string
    SetRuriUserparams([]string)
    GetRUri() *sippy_header.SipTo
    GetToUsername() string
    SetToUsername(string)
    GetUsername() string
    SetUsername(string)
    GetPassword() string
    SetPassword(string)
    SetLUri(*sippy_header.SipFrom)
    GetLUri() *sippy_header.SipFrom
    GetFromDomain() string
    SetFromDomain(string)
    GetLTag() string
    SetLCSeq(int)
    SetLContact(*sippy_header.SipContact)
    GetLContact() *sippy_header.SipContact
    SetRoutes([]*sippy_header.SipRoute)
    GetCGUID() *sippy_header.SipCiscoGUID
    SetCGUID(*sippy_header.SipCiscoGUID)
    SetH323ConfId(*sippy_header.SipH323ConfId)
    GetLSDP() MsgBody
    SetLSDP(MsgBody)
    GetRSDP() MsgBody
    SetRSDP(MsgBody)
    GenRequest(method string, body MsgBody, nonce string, realm string, SipXXXAuthorization sippy_header.NewSipXXXAuthorizationFunc, extra_headers ...sippy_header.SipHeader) SipRequest
    IncLCSeq()
    GetSourceAddress() *sippy_conf.HostPort
    SetSourceAddress(*sippy_conf.HostPort)
    GetClientTransaction() ClientTransaction
    SetClientTransaction(ClientTransaction)
    GetOutboundProxy() *sippy_conf.HostPort
    SetOutboundProxy(*sippy_conf.HostPort)
    GetNoReplyTime() time.Duration
    SetNoReplyTime(time.Duration)
    GetExpireTime() time.Duration
    SetExpireTime(time.Duration)
    GetNoProgressTime() time.Duration
    SetNoProgressTime(time.Duration)
    StartNoReplyTimer(*sippy_time.MonoTime)
    StartNoProgressTimer(*sippy_time.MonoTime)
    StartExpireTimer(*sippy_time.MonoTime)
    CancelExpireTimer()
    GetDiscCbs() []OnDisconnectListener
    SetDiscCbs([]OnDisconnectListener)
    GetFailCbs() []OnFailureListener
    SetFailCbs([]OnFailureListener)
    GetConnCbs() []OnConnectListener
    SetConnCbs([]OnConnectListener)
    GetRingCbs() []OnRingingListener
    GetDeadCbs() []OnDeadListener
    SetDeadCbs([]OnDeadListener)
    IsYours(SipRequest, bool) bool
    GetLocalUA() *sippy_header.SipUserAgent
    SetLocalUA(*sippy_header.SipUserAgent)
    Enqueue(CCEvent)
    GetUasResp() SipResponse
    SetUasResp(SipResponse)
    CancelCreditTimer()
    StartCreditTimer(*sippy_time.MonoTime)
    SetCreditTime(time.Duration)
    ResetCreditTime(*sippy_time.MonoTime, map[int64]*sippy_time.MonoTime)
    ShouldUseRefer() bool
    GetState() UaState
    Disconnect(*sippy_time.MonoTime)
    SetKaInterval(time.Duration)
    GetKaInterval() time.Duration
    OnDead()
    GetGoDeadTimeout() time.Duration
    ChangeState(UaState)
    GetLastScode() int
    SetLastScode(int)
    HasNoReplyTimer() bool
    CancelNoReplyTimer()
    GetNpMtime() *sippy_time.MonoTime
    SetNpMtime(*sippy_time.MonoTime)
    GetExMtime() *sippy_time.MonoTime
    SetExMtime(*sippy_time.MonoTime)
    GetP100Ts() *sippy_time.MonoTime
    SetP100Ts(*sippy_time.MonoTime)
    HasNoProgressTimer() bool
    CancelNoProgressTimer()
    DelayedRemoteSdpUpdate(event CCEvent, remote_sdp_body MsgBody)
    GetP1xxTs() *sippy_time.MonoTime
    SetP1xxTs(*sippy_time.MonoTime)
    UpdateRouting(SipResponse, bool, bool)
    GetConnectTs() *sippy_time.MonoTime
    SetConnectTs(*sippy_time.MonoTime)
    SetBranch(string)
    SetAuth(sippy_header.SipHeader)
    GetNrMtime() *sippy_time.MonoTime
    SetNrMtime(*sippy_time.MonoTime)
    SendUasResponse(t ServerTransaction, scode int, reason string, body MsgBody /*= nil*/, contact *sippy_header.SipContact /*= nil*/, ack_wait bool /*false*/, extra_headers ...sippy_header.SipHeader)
    EmitEvent(CCEvent)
    String() string
    GetPendingTr() ClientTransaction
    SetPendingTr(ClientTransaction)
    GetLateMedia() bool
    SetLateMedia(bool)
    GetPassAuth() bool
    GetOnLocalSdpChange() OnLocalSdpChange
    GetOnRemoteSdpChange() OnRemoteSdpChange
    SetOnRemoteSdpChange(OnRemoteSdpChange)
    GetRemoteUA() string
    SetExtraHeaders([]sippy_header.SipHeader)
    GetAcct(*sippy_time.MonoTime) (time.Duration, time.Duration, bool, bool)
}

type baseTransaction interface {
    GetHost() string
    Lock()
    Unlock()
    StartTimers()
}

type ClientTransaction interface {
    baseTransaction
    IncomingResponse(resp SipResponse, checksum string)
    SetOutboundProxy(*sippy_conf.HostPort)
    Cancel(...sippy_header.SipHeader)
    GetACK() SipRequest
    SendACK()
    SetUAck(bool)
}

type ServerTransaction interface {
    baseTransaction
    IncomingRequest(req SipRequest, checksum string)
    TimersAreActive() bool
    SetCancelCB(func(*sippy_time.MonoTime, SipRequest))
    SetNoackCB(func(*sippy_time.MonoTime))
    SendResponse(resp SipResponse, retrans bool, ack_cb func(SipRequest))
    Cleanup()
    UpgradeToSessionLock(sync.Locker)
    SetServer(*sippy_header.SipServer)
}

type SipTransactionManager interface {
    RegConsumer(UA, string)
    UnregConsumer(UA, string)
    NewClientTransaction(SipRequest, ResponseReceiver, sync.Locker, *sippy_conf.HostPort, UdpServer) (ClientTransaction, error)
    SendResponse(resp SipResponse, lock bool, ack_cb func(SipRequest))
    Run()
}

type UaState interface {
    RecvEvent(CCEvent) (UaState, error)
    RecvResponse(SipResponse, ClientTransaction) UaState
    RecvRequest(SipRequest, ServerTransaction) UaState
    Cancel(*sippy_time.MonoTime, SipRequest)
    OnStateChange()
    String() string
    OnActivation()
    RecvACK(SipRequest)
    IsConnected() bool
}

type CCEvent interface {
    GetSeq() int64
    GetRtime() *sippy_time.MonoTime
    GetOrigin() string
    GetExtraHeaders() []sippy_header.SipHeader
    SetReason(*sippy_header.SipReason)
    GetReason() *sippy_header.SipReason
    String() string
    AppendExtraHeader(sippy_header.SipHeader)
}

type StatefulProxy interface {
    RequestReceiver
}

type OnRingingListener func(*sippy_time.MonoTime, string, int)
type OnDisconnectListener func(*sippy_time.MonoTime, string, int)
type OnFailureListener func(*sippy_time.MonoTime, string, int)
type OnConnectListener func(*sippy_time.MonoTime, string)
type OnDeadListener func()
type OnLocalSdpChange func(MsgBody, CCEvent, func(MsgBody))
type OnRemoteSdpChange func(MsgBody, SipMsg, func(MsgBody))

type RtpProxyClient interface {
    SendCommand(string, func(string))
    SBindSupported() bool
    IsLocal() bool
    TNotSupported() bool
    GetProxyAddress() string
    IsOnline() bool
}
<commit_msg>More public API.<commit_after>// Copyright (c) 2015 Andrii Pylypenko. All rights reserved.
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package sippy_types

import (
    "sync"
    "time"

    "sippy/conf"
    "sippy/headers"
    "sippy/sdp"
    "sippy/time"
)

type CallController interface {
    RecvEvent(CCEvent, UA)
}

type RequestReceiver interface {
    RecvRequest(SipRequest, ServerTransaction) *Ua_context
}

type ResponseReceiver interface {
    RecvResponse(SipResponse, ClientTransaction)
}

type CallMap interface {
    OnNewDialog(SipRequest, ServerTransaction) (UA, RequestReceiver, SipResponse)
}

type SipMsg interface {
    GetSipUserAgent() *sippy_header.SipUserAgent
    GetSipServer() *sippy_header.SipServer
    LocalStr(hostport *sippy_conf.HostPort, compact bool) string
    GetCSeq() *sippy_header.SipCSeq
    GetTId(wCSM, wBRN, wTTG bool) *sippy_header.TID
    GetTo() *sippy_header.SipTo
    GetReason() *sippy_header.SipReason
    AppendHeader(hdr sippy_header.SipHeader)
    GetVias() []*sippy_header.SipVia
    GetCallId() *sippy_header.SipCallId
    SetRtime(*sippy_time.MonoTime)
    GetTarget() *sippy_conf.HostPort
    SetTarget(address *sippy_conf.HostPort)
    InsertFirstVia(*sippy_header.SipVia)
    RemoveFirstVia()
    SetRoutes([]*sippy_header.SipRoute)
    GetFrom() *sippy_header.SipFrom
    GetRtime() *sippy_time.MonoTime
    GetAlso() []*sippy_header.SipAlso
    GetBody() MsgBody
    SetBody(MsgBody)
    GetContacts() []*sippy_header.SipContact
    GetRecordRoutes() []*sippy_header.SipRecordRoute
    GetCGUID() *sippy_header.SipCiscoGUID
    GetH323ConfId() *sippy_header.SipH323ConfId
    GetSipAuthorization() *sippy_header.SipAuthorization
    GetSource() *sippy_conf.HostPort
    GetFirstHF(string) sippy_header.SipHeader
    GetHFs(string) []sippy_header.SipHeader
}

type SipRequest interface {
    SipMsg
    GetSipProxyAuthorization() *sippy_header.SipProxyAuthorization
    GenResponse(int, string, MsgBody, *sippy_header.SipServer) SipResponse
    GetMethod() string
    GetExpires() *sippy_header.SipExpires
    GenACK(to *sippy_header.SipTo, config sippy_conf.Config) SipRequest
    GenCANCEL(sippy_conf.Config) SipRequest
    GetRURI() *sippy_header.SipURL
    SetRURI(ruri *sippy_header.SipURL)
    GetReferTo() *sippy_header.SipReferTo
    GetNated() bool
}

type SipResponse interface {
    SipMsg
    GetSCode() (int, string)
    SetSCode(int, string)
    GetSCodeNum() int
    GetSipWWWAuthenticate() *sippy_header.SipWWWAuthenticate
    GetSipProxyAuthenticate() *sippy_header.SipProxyAuthenticate
    SetReason(string)
    GetCopy() SipResponse
}

type UdpServer interface {
    GetLaddress() *sippy_conf.HostPort
    SendTo([]byte, string, string)
}

type MsgBody interface {
    String() string
    GetMtype() string
    LocalStr(hostport *sippy_conf.HostPort) string
    GetCopy() MsgBody
    NeedsUpdate() bool
    SetNeedsUpdate(bool)
    GetParsedBody() ParsedMsgBody
    AppendAHeader(string)
}

type ParsedMsgBody interface {
    String() string
    LocalStr(hostport *sippy_conf.HostPort) string
    GetCopy() ParsedMsgBody
    SetCHeaderAddr(string)
    GetSections() []*sippy_sdp.SdpMediaDescription
    SetSections([]*sippy_sdp.SdpMediaDescription)
    RemoveSection(int)
    SetOHeader(*sippy_sdp.SdpOrigin)
    AppendAHeader(string)
}

type UA interface {
    OnUnregister()
    RequestReceiver
    ResponseReceiver
    GetSessionLock() sync.Locker
    RecvEvent(CCEvent)
    SipTM() SipTransactionManager
    GetSetupTs() *sippy_time.MonoTime
    SetSetupTs(*sippy_time.MonoTime)
    GetDisconnectTs() *sippy_time.MonoTime
    SetDisconnectTs(*sippy_time.MonoTime)
    GetOrigin() string
    SetOrigin(string)
    HasOnLocalSdpChange() bool
    OnLocalSdpChange(MsgBody, CCEvent, func(MsgBody))
    SetOnLocalSdpChange(OnLocalSdpChange)
    ResetOnLocalSdpChange()
    OnRemoteSdpChange(MsgBody, SipMsg, func(MsgBody))
    HasOnRemoteSdpChange() bool
    ResetOnRemoteSdpChange()
    SetCallId(*sippy_header.SipCallId)
    GetCallId() *sippy_header.SipCallId
    SetRTarget(*sippy_header.SipURL)
    GetRAddr() *sippy_conf.HostPort
    SetRAddr(addr *sippy_conf.HostPort)
    GetRAddr0() *sippy_conf.HostPort
    SetRAddr0(addr *sippy_conf.HostPort)
    GetRTarget() *sippy_header.SipURL
    SetRUri(*sippy_header.SipTo)
    GetRuriUserparams() []string
    SetRuriUserparams([]string)
    GetRUri() *sippy_header.SipTo
    GetToUsername() string
    SetToUsername(string)
    GetUsername() string
    SetUsername(string)
    GetPassword() string
    SetPassword(string)
    SetLUri(*sippy_header.SipFrom)
    GetLUri() *sippy_header.SipFrom
    GetFromDomain() string
    SetFromDomain(string)
    GetLTag() string
    SetLCSeq(int)
    SetLContact(*sippy_header.SipContact)
    GetLContact() *sippy_header.SipContact
    SetRoutes([]*sippy_header.SipRoute)
    GetCGUID() *sippy_header.SipCiscoGUID
    SetCGUID(*sippy_header.SipCiscoGUID)
    SetH323ConfId(*sippy_header.SipH323ConfId)
    GetLSDP() MsgBody
    SetLSDP(MsgBody)
    GetRSDP() MsgBody
    SetRSDP(MsgBody)
    GenRequest(method string, body MsgBody, nonce string, realm string, SipXXXAuthorization sippy_header.NewSipXXXAuthorizationFunc, extra_headers ...sippy_header.SipHeader) SipRequest
    IncLCSeq()
    GetSourceAddress() *sippy_conf.HostPort
    SetSourceAddress(*sippy_conf.HostPort)
    GetClientTransaction() ClientTransaction
    SetClientTransaction(ClientTransaction)
    GetOutboundProxy() *sippy_conf.HostPort
    SetOutboundProxy(*sippy_conf.HostPort)
    GetNoReplyTime() time.Duration
    SetNoReplyTime(time.Duration)
    GetExpireTime() time.Duration
    SetExpireTime(time.Duration)
    GetNoProgressTime() time.Duration
    SetNoProgressTime(time.Duration)
    StartNoReplyTimer(*sippy_time.MonoTime)
    StartNoProgressTimer(*sippy_time.MonoTime)
    StartExpireTimer(*sippy_time.MonoTime)
    CancelExpireTimer()
    GetDiscCbs() []OnDisconnectListener
    SetDiscCbs([]OnDisconnectListener)
    GetFailCbs() []OnFailureListener
    SetFailCbs([]OnFailureListener)
    GetConnCbs() []OnConnectListener
    SetConnCbs([]OnConnectListener)
    GetRingCbs() []OnRingingListener
    GetDeadCbs() []OnDeadListener
    SetDeadCbs([]OnDeadListener)
    IsYours(SipRequest, bool) bool
    GetLocalUA() *sippy_header.SipUserAgent
    SetLocalUA(*sippy_header.SipUserAgent)
    Enqueue(CCEvent)
    GetUasResp() SipResponse
    SetUasResp(SipResponse)
    CancelCreditTimer()
    StartCreditTimer(*sippy_time.MonoTime)
    SetCreditTime(time.Duration)
    ResetCreditTime(*sippy_time.MonoTime, map[int64]*sippy_time.MonoTime)
    ShouldUseRefer() bool
    GetState() UaState
    Disconnect(*sippy_time.MonoTime)
    SetKaInterval(time.Duration)
    GetKaInterval() time.Duration
    OnDead()
    GetGoDeadTimeout() time.Duration
    ChangeState(UaState)
    GetLastScode() int
    SetLastScode(int)
    HasNoReplyTimer() bool
    CancelNoReplyTimer()
    GetNpMtime() *sippy_time.MonoTime
    SetNpMtime(*sippy_time.MonoTime)
    GetExMtime() *sippy_time.MonoTime
    SetExMtime(*sippy_time.MonoTime)
    GetP100Ts() *sippy_time.MonoTime
    SetP100Ts(*sippy_time.MonoTime)
    HasNoProgressTimer() bool
    CancelNoProgressTimer()
    DelayedRemoteSdpUpdate(event CCEvent, remote_sdp_body MsgBody)
    GetP1xxTs() *sippy_time.MonoTime
    SetP1xxTs(*sippy_time.MonoTime)
    UpdateRouting(SipResponse, bool, bool)
    GetConnectTs() *sippy_time.MonoTime
    SetConnectTs(*sippy_time.MonoTime)
    SetBranch(string)
    SetAuth(sippy_header.SipHeader)
    GetNrMtime() *sippy_time.MonoTime
    SetNrMtime(*sippy_time.MonoTime)
    SendUasResponse(t ServerTransaction, scode int, reason string, body MsgBody /*= nil*/, contact *sippy_header.SipContact /*= nil*/, ack_wait bool /*false*/, extra_headers ...sippy_header.SipHeader)
    EmitEvent(CCEvent)
    String() string
    GetPendingTr() ClientTransaction
    SetPendingTr(ClientTransaction)
    GetLateMedia() bool
    SetLateMedia(bool)
    GetPassAuth() bool
    GetOnLocalSdpChange() OnLocalSdpChange
    GetOnRemoteSdpChange() OnRemoteSdpChange
    SetOnRemoteSdpChange(OnRemoteSdpChange)
    GetRemoteUA() string
    SetExtraHeaders([]sippy_header.SipHeader)
    GetAcct(*sippy_time.MonoTime) (time.Duration, time.Duration, bool, bool)
    GetCLI() string
    GetCLD() string
}

type baseTransaction interface {
    GetHost() string
    Lock()
    Unlock()
    StartTimers()
}

type ClientTransaction interface {
    baseTransaction
    IncomingResponse(resp SipResponse, checksum string)
    SetOutboundProxy(*sippy_conf.HostPort)
    Cancel(...sippy_header.SipHeader)
    GetACK() SipRequest
    SendACK()
    SetUAck(bool)
}

type ServerTransaction interface {
    baseTransaction
    IncomingRequest(req SipRequest, checksum string)
    TimersAreActive() bool
    SetCancelCB(func(*sippy_time.MonoTime, SipRequest))
    SetNoackCB(func(*sippy_time.MonoTime))
    SendResponse(resp SipResponse, retrans bool, ack_cb func(SipRequest))
    Cleanup()
    UpgradeToSessionLock(sync.Locker)
    SetServer(*sippy_header.SipServer)
}

type SipTransactionManager interface {
    RegConsumer(UA, string)
    UnregConsumer(UA, string)
    NewClientTransaction(SipRequest, ResponseReceiver, sync.Locker, *sippy_conf.HostPort, UdpServer) (ClientTransaction, error)
    SendResponse(resp SipResponse, lock bool, ack_cb func(SipRequest))
    Run()
}

type UaState interface {
    RecvEvent(CCEvent) (UaState, error)
    RecvResponse(SipResponse, ClientTransaction) UaState
    RecvRequest(SipRequest, ServerTransaction) UaState
    Cancel(*sippy_time.MonoTime, SipRequest)
    OnStateChange()
    String() string
    OnActivation()
    RecvACK(SipRequest)
    IsConnected() bool
}

type CCEvent interface {
    GetSeq() int64
    GetRtime() *sippy_time.MonoTime
    GetOrigin() string
    GetExtraHeaders() []sippy_header.SipHeader
    SetReason(*sippy_header.SipReason)
    GetReason() *sippy_header.SipReason
    String() string
    AppendExtraHeader(sippy_header.SipHeader)
}

type StatefulProxy interface {
    RequestReceiver
}

type OnRingingListener func(*sippy_time.MonoTime, string, int)
type OnDisconnectListener func(*sippy_time.MonoTime, string, int)
type OnFailureListener func(*sippy_time.MonoTime, string, int)
type OnConnectListener func(*sippy_time.MonoTime, string)
type OnDeadListener func()
type OnLocalSdpChange func(MsgBody, CCEvent, func(MsgBody))
type OnRemoteSdpChange func(MsgBody, SipMsg, func(MsgBody))

type RtpProxyClient interface {
    SendCommand(string, func(string))
    SBindSupported() bool
    IsLocal() bool
    TNotSupported() bool
    GetProxyAddress() string
    IsOnline() bool
}
<|endoftext|>


<commit_before>package @OPT[|@USE::package.|]core

// ---------------------------------------------------------------------------------------------------------------------

import "encoding/json"
import "fmt"
import "strings"
import "errors"

// ---------------------------------------------------------------------------------------------------------------------
// JSon type definition
// ---------------------------------------------------------------------------------------------------------------------

type JSon interface {
    isJSon()
    String() string
    ToJSonString() string
    RawValue() interface{}
    SetValue(path []string, value JSon) JSon
}

// ---------------------------------------------------------------------------------------------------------------------
// Abstract JSon type
// ---------------------------------------------------------------------------------------------------------------------

type abstractJSon struct {}
func (abstractJSon) isJSon() {}
func (this abstractJSon) String() string {
    return "" // TODO manage error case in a better way
}
func (this abstractJSon) ToJSonString() string {
    return this.String()
}
func (this abstractJSon) SetValue(path []string, value JSon) JSon {
    return value
}

// ---------------------------------------------------------------------------------------------------------------------
// Number JSon type
// ---------------------------------------------------------------------------------------------------------------------

type Number struct {
	abstractJSon
	value float64
}
func (this Number) String() string {
    return fmt.Sprintf("%f", this.value)
}
func (this Number) RawValue() interface{} {
    return this.value
}
func NewNumber(value float64) JSon {
    o := new(Number)
    o.value = value
    return *o
}
// ---------------------------------------------------------------------------------------------------------------------
// String JSon type
// ---------------------------------------------------------------------------------------------------------------------

type String struct {
	abstractJSon
	value string
}
func (this String) String() string {
    return this.value
}
func (this String) ToJSonString() string {
    return fmt.Sprintf("\"%s\"", this.value)
}
func (this String) RawValue() interface{} {
    return this.value
}
func NewString(value string) JSon {
     o := new(String)
     o.value = value
     return *o
}

// ---------------------------------------------------------------------------------------------------------------------
// Boolean JSon type
// ---------------------------------------------------------------------------------------------------------------------

type Boolean struct {
	abstractJSon
	value bool
}
func (this Boolean) String() string {
    if this.value {
        return "true"
    } else {
        return "false"
    }
}
func (this Boolean) RawValue() interface{} {
    return this.value
}
func NewBoolean(value bool) JSon {
    o := new(Boolean)
    o.value = value
    return o
}

// ---------------------------------------------------------------------------------------------------------------------
// Null JSon type
// ---------------------------------------------------------------------------------------------------------------------

type Null struct { abstractJSon }
func (this Null) String() string {
    return "null"
}
func (this Null) RawValue() interface{} {
    return nil
}
func NewNull() JSon {
    return *new (Null)
}

// ---------------------------------------------------------------------------------------------------------------------
// Array JSon type
// ---------------------------------------------------------------------------------------------------------------------

type Array struct {
	abstractJSon
	value []JSon
}
func (this Array) String() string {
    var data = make([]string, len(this.value))
    for k := range this.value {
        data[k] = this.value[k].String()
    }
    return fmt.Sprintf("[ %s ]", strings.Join(data, ", "))
}
func (this Array) RawValue() interface{} {
    var data []interface{}
    for k := range this.value {
        data = append(data, this.value[k].RawValue())
    }
    return data
}
func NewArray(value []JSon) JSon {
     o := new(Array)
     o.value = value
     return o
}

// ---------------------------------------------------------------------------------------------------------------------
// Map JSon type
// ---------------------------------------------------------------------------------------------------------------------

type Map struct {
	abstractJSon
	value map[string]JSon
}
func (this Map) String() string {
    var data []string
    for k := range this.value {
        data = append(data, fmt.Sprintf("\"%s\": %s",this.value[k].String()))
    }
    return fmt.Sprintf("{ %s }", strings.Join(data, ", "))
}
func (this Map) RawValue() interface{} {
    var data = map[string]interface{}{}
    for k := range this.value {
        data[k] = this.value[k].RawValue()
    }
    return data
}
func NewMap(value map[string]JSon) JSon {
    o := new(Map)
    o.value = value
    return o
}

// ---------------------------------------------------------------------------------------------------------------------
// JSon conversion function
// ---------------------------------------------------------------------------------------------------------------------

func ValueOfJSon(v interface{}) (JSon,error) {
    switch e := v.(type) {
    case int:
        return NewNumber(float64(e)), nil
    case float64:
        return NewNumber(e), nil
    case string:
        return NewString(e), nil
    case bool:
        return NewBoolean(e), nil
    case []interface{}:
        var data = make([]JSon, len(e))
        for v := range e {
           result,error := ValueOfJSon(e[v])
           if (error != nil) {
            return nil, error
           } else {
            data[v] = result
           }
        }
        return NewArray(data), nil
    case map[string]interface{}:
        var data map[string]JSon
        for v := range e {
           result,error := ValueOfJSon(e[v])
           if (error != nil) {
            return nil, error
           } else {
            data[v] = result
           }
        }
        return NewMap(data), nil
    case nil:
        return NewNull(), nil
    default:
        return nil, errors.New(fmt.Sprintf("Unexpected type %T while creating JSon data", e))
    }
}

func StringOfJSon(s string) (JSon, error) {
    var v interface{}
    error := json.Unmarshal([]byte(s),&v)
    if (error != nil) {
	return nil, error
    }
    return ValueOfJSon(v)
}

func main() {
    json,error := StringOfJSon(`["a",1]`)
    if (error == nil) {
	fmt.Printf(json.String())
    } else {
	fmt.Println(error)
    }
}<commit_msg>golang backend in progress - indentation and remove useless code<commit_after>package @OPT[|@USE::package.|]core

// ---------------------------------------------------------------------------------------------------------------------

import "encoding/json"
import "fmt"
import "strings"
import "errors"

// ---------------------------------------------------------------------------------------------------------------------
// JSon type definition
// ---------------------------------------------------------------------------------------------------------------------

type JSon interface {
    isJSon()
    String() string
    ToJSonString() string
    RawValue() interface{}
    SetValue(path []string, value JSon) JSon
}

// ---------------------------------------------------------------------------------------------------------------------
// Abstract JSon type
// ---------------------------------------------------------------------------------------------------------------------

type abstractJSon struct {}
func (abstractJSon) isJSon() {}
func (this abstractJSon) String() string {
    return "" // TODO manage error case in a better way
}
func (this abstractJSon) ToJSonString() string {
    return this.String()
}
func (this abstractJSon) SetValue(path []string, value JSon) JSon {
    return value
}

// ---------------------------------------------------------------------------------------------------------------------
// Number JSon type
// ---------------------------------------------------------------------------------------------------------------------

type Number struct {
	abstractJSon
	value float64
}
func (this Number) String() string {
    return fmt.Sprintf("%f", this.value)
}
func (this Number) RawValue() interface{} {
    return this.value
}
func NewNumber(value float64) JSon {
    o := new(Number)
    o.value = value
    return *o
}
// ---------------------------------------------------------------------------------------------------------------------
// String JSon type
// ---------------------------------------------------------------------------------------------------------------------

type String struct {
	abstractJSon
	value string
}
func (this String) String() string {
    return this.value
}
func (this String) ToJSonString() string {
    return fmt.Sprintf("\"%s\"", this.value)
}
func (this String) RawValue() interface{} {
    return this.value
}
func NewString(value string) JSon {
     o := new(String)
     o.value = value
     return *o
}

// ---------------------------------------------------------------------------------------------------------------------
// Boolean JSon type
// ---------------------------------------------------------------------------------------------------------------------

type Boolean struct {
	abstractJSon
	value bool
}
func (this Boolean) String() string {
    if this.value {
        return "true"
    } else {
        return "false"
    }
}
func (this Boolean) RawValue() interface{} {
    return this.value
}
func NewBoolean(value bool) JSon {
    o := new(Boolean)
    o.value = value
    return o
}

// ---------------------------------------------------------------------------------------------------------------------
// Null JSon type
// ---------------------------------------------------------------------------------------------------------------------

type Null struct { abstractJSon }
func (this Null) String() string {
    return "null"
}
func (this Null) RawValue() interface{} {
    return nil
}
func NewNull() JSon {
    return *new (Null)
}

// ---------------------------------------------------------------------------------------------------------------------
// Array JSon type
// ---------------------------------------------------------------------------------------------------------------------

type Array struct {
	abstractJSon
	value []JSon
}
func (this Array) String() string {
    var data = make([]string, len(this.value))
    for k := range this.value {
        data[k] = this.value[k].String()
    }
    return fmt.Sprintf("[ %s ]", strings.Join(data, ", "))
}
func (this Array) RawValue() interface{} {
    var data []interface{}
    for k := range this.value {
        data = append(data, this.value[k].RawValue())
    }
    return data
}
func NewArray(value []JSon) JSon {
     o := new(Array)
     o.value = value
     return o
}

// ---------------------------------------------------------------------------------------------------------------------
// Map JSon type
// ---------------------------------------------------------------------------------------------------------------------

type Map struct {
	abstractJSon
	value map[string]JSon
}
func (this Map) String() string {
    var data []string
    for k := range this.value {
        data = append(data, fmt.Sprintf("\"%s\": %s",this.value[k].String()))
    }
    return fmt.Sprintf("{ %s }", strings.Join(data, ", "))
}
func (this Map) RawValue() interface{} {
    var data = map[string]interface{}{}
    for k := range this.value {
        data[k] = this.value[k].RawValue()
    }
    return data
}
func NewMap(value map[string]JSon) JSon {
    o := new(Map)
    o.value = value
    return o
}

// ---------------------------------------------------------------------------------------------------------------------
// JSon conversion function
// ---------------------------------------------------------------------------------------------------------------------

func ValueOfJSon(v interface{}) (JSon,error) {
    switch e := v.(type) {
    case int:
        return NewNumber(float64(e)), nil
    case float64:
        return NewNumber(e), nil
    case string:
        return NewString(e), nil
    case bool:
        return NewBoolean(e), nil
    case []interface{}:
        var data = make([]JSon, len(e))
        for v := range e {
           result,error := ValueOfJSon(e[v])
           if (error != nil) {
            return nil, error
           } else {
            data[v] = result
           }
        }
        return NewArray(data), nil
    case map[string]interface{}:
        var data map[string]JSon
        for v := range e {
           result,error := ValueOfJSon(e[v])
           if (error != nil) {
            return nil, error
           } else {
            data[v] = result
           }
        }
        return NewMap(data), nil
    case nil:
        return NewNull(), nil
    default:
        return nil, errors.New(fmt.Sprintf("Unexpected type %T while creating JSon data", e))
    }
}

func StringOfJSon(s string) (JSon,error) {
    var v interface{}
    error := json.Unmarshal([]byte(s),&v)
    if (error != nil) {
	return nil, error
    }
    return ValueOfJSon(v)
}
<|endoftext|>


<commit_before>package jobs

import (
	"fmt"
	"strings"

	"github.com/hyperledger/burrow/deploy/def"
	"github.com/hyperledger/burrow/deploy/util"
	log "github.com/sirupsen/logrus"
)

func RunJobs(do *def.Packages) error {
	// Dial the chain
	err := do.Dial()
	if err != nil {
		return err
	}

	// ADD DefaultAddr and DefaultSet to jobs array....
	// These work in reverse order and the addendums to the
	// the ordering from the loading process is lifo
	if len(do.DefaultSets) >= 1 {
		defaultSetJobs(do)
	}

	if do.Address != "" {
		defaultAddrJob(do)
	}

	err = do.Validate()
	if err != nil {
		return fmt.Errorf("error validating Burrow package file at %s: %v", do.YAMLPath, err)
	}

	for _, job := range do.Package.Jobs {
		payload, err := job.Payload()
		if err != nil {
			return fmt.Errorf("could not get Job payload: %v", payload)
		}
		err = util.PreProcessFields(payload, do)
		if err != nil {
			return err
		}
		// Revalidate with possible replacements
		err = payload.Validate()
		if err != nil {
			return fmt.Errorf("error validating job %s after pre-processing variables: %v", job.Name, err)
		}
		switch payload.(type) {
		// Meta Job
		case *def.Meta:
			announce(job.Name, "Meta")
			do.CurrentOutput = fmt.Sprintf("%s.output.json", job.Name)
			job.Result, err = MetaJob(job.Meta, do)

		// Governance
		case *def.UpdateAccount:
			announce(job.Name, "UpdateAccount")
			job.Result, job.Variables, err = UpdateAccountJob(job.UpdateAccount, do)

		// Util jobs
		case *def.Account:
			announce(job.Name, "Account")
			job.Result, err = SetAccountJob(job.Account, do)
		case *def.Set:
			announce(job.Name, "Set")
			job.Result, err = SetValJob(job.Set, do)

		// Transaction jobs
		case *def.Send:
			announce(job.Name, "Sent")
			job.Result, err = SendJob(job.Send, do)
		case *def.RegisterName:
			announce(job.Name, "RegisterName")
			job.Result, err = RegisterNameJob(job.RegisterName, do)
		case *def.Permission:
			announce(job.Name, "Permission")
			job.Result, err = PermissionJob(job.Permission, do)

		// Contracts jobs
		case *def.Deploy:
			announce(job.Name, "Deploy")
			job.Result, err = DeployJob(job.Deploy, do)
		case *def.Call:
			announce(job.Name, "Call")
			job.Result, job.Variables, err = CallJob(job.Call, do)
		case *def.Build:
			announce(job.Name, "Build")
			job.Result, err = BuildJob(job.Build, do)

		// State jobs
		case *def.RestoreState:
			announce(job.Name, "RestoreState")
			job.Result, err = RestoreStateJob(job.RestoreState, do)
		case *def.DumpState:
			announce(job.Name, "DumpState")
			job.Result, err = DumpStateJob(job.DumpState, do)

		// Test jobs
		case *def.QueryAccount:
			announce(job.Name, "QueryAccount")
			job.Result, err = QueryAccountJob(job.QueryAccount, do)
		case *def.QueryContract:
			announce(job.Name, "QueryContract")
			job.Result, job.Variables, err = QueryContractJob(job.QueryContract, do)
		case *def.QueryName:
			announce(job.Name, "QueryName")
			job.Result, err = QueryNameJob(job.QueryName, do)
		case *def.QueryVals:
			announce(job.Name, "QueryVals")
			job.Result, err = QueryValsJob(job.QueryVals, do)
		case *def.Assert:
			announce(job.Name, "Assert")
			job.Result, err = AssertJob(job.Assert, do)

		default:
			log.Error("")
			return fmt.Errorf("the Job specified in deploy.yaml and parsed as '%v' is not recognised as a valid job",
				job)
		}

		if len(job.Variables) != 0 {
			for _, theJob := range job.Variables {
				log.WithField("=>", fmt.Sprintf("%s,%s", theJob.Name, theJob.Value)).Info("Job Vars")
			}
		}

		if err != nil {
			return err
		}
	}

	postProcess(do)
	return nil
}

func announce(job, typ string) {
	log.Warn("*****Executing Job*****\n")
	log.WithField("=>", job).Warn("Job Name")
	log.WithField("=>", typ).Info("Type")
	log.Warn("\n")
}

func defaultAddrJob(do *def.Packages) {
	oldJobs := do.Package.Jobs

	newJob := &def.Job{
		Name: "defaultAddr",
		Account: &def.Account{
			Address: do.Address,
		},
	}

	do.Package.Jobs = append([]*def.Job{newJob}, oldJobs...)
}

func defaultSetJobs(do *def.Packages) {
	oldJobs := do.Package.Jobs

	newJobs := []*def.Job{}

	for _, setr := range do.DefaultSets {
		blowdUp := strings.Split(setr, "=")
		if blowdUp[0] != "" {
			newJobs = append(newJobs, &def.Job{
				Name: blowdUp[0],
				Set: &def.Set{
					Value: blowdUp[1],
				},
			})
		}
	}

	do.Package.Jobs = append(newJobs, oldJobs...)
}

func postProcess(do *def.Packages) error {
	// Formulate the results map
	results := make(map[string]interface{})
	for _, job := range do.Package.Jobs {
		results[job.Name] = job.Result
	}

	// check do.YAMLPath and do.DefaultOutput
	var yaml string
	yamlName := strings.LastIndexByte(do.YAMLPath, '.')
	if yamlName >= 0 {
		yaml = do.YAMLPath[:yamlName]
	} else {
		return fmt.Errorf("invalid jobs file path (%s)", do.YAMLPath)
	}

	// if do.YAMLPath is not default and do.DefaultOutput is default, over-ride do.DefaultOutput
	if yaml != "deploy" && do.DefaultOutput == "deploy.output.json" {
		do.DefaultOutput = fmt.Sprintf("%s.output.json", yaml)
	}

	// if CurrentOutput set, we're in a meta job
	if do.CurrentOutput != "" {
		log.Warn(fmt.Sprintf("Writing meta output of [%s] to current directory", do.CurrentOutput))
		return WriteJobResultJSON(results, do.CurrentOutput)
	}

	// Write the output
	log.Warn(fmt.Sprintf("Writing [%s] to current directory", do.DefaultOutput))
	return WriteJobResultJSON(results, do.DefaultOutput)
}
<commit_msg>Do not connect to burrow unless needed<commit_after>package jobs

import (
	"fmt"
	"strings"

	"github.com/hyperledger/burrow/deploy/def"
	"github.com/hyperledger/burrow/deploy/util"
	log "github.com/sirupsen/logrus"
)

func RunJobs(do *def.Packages) error {

	// Dial the chain if needed
	err, needed := burrowConnectionNeeded(do)
	if err != nil {
		return err
	}

	if needed {
		err = do.Dial()
		if err != nil {
			return err
		}
	}

	// ADD DefaultAddr and DefaultSet to jobs array....
	// These work in reverse order and the addendums to the
	// the ordering from the loading process is lifo
	if len(do.DefaultSets) >= 1 {
		defaultSetJobs(do)
	}

	if do.Address != "" {
		defaultAddrJob(do)
	}

	err = do.Validate()
	if err != nil {
		return fmt.Errorf("error validating Burrow package file at %s: %v", do.YAMLPath, err)
	}

	for _, job := range do.Package.Jobs {
		payload, err := job.Payload()
		if err != nil {
			return fmt.Errorf("could not get Job payload: %v", payload)
		}
		err = util.PreProcessFields(payload, do)
		if err != nil {
			return err
		}
		// Revalidate with possible replacements
		err = payload.Validate()
		if err != nil {
			return fmt.Errorf("error validating job %s after pre-processing variables: %v", job.Name, err)
		}
		switch payload.(type) {
		// Meta Job
		case *def.Meta:
			announce(job.Name, "Meta")
			do.CurrentOutput = fmt.Sprintf("%s.output.json", job.Name)
			job.Result, err = MetaJob(job.Meta, do)

		// Governance
		case *def.UpdateAccount:
			announce(job.Name, "UpdateAccount")
			job.Result, job.Variables, err = UpdateAccountJob(job.UpdateAccount, do)

		// Util jobs
		case *def.Account:
			announce(job.Name, "Account")
			job.Result, err = SetAccountJob(job.Account, do)
		case *def.Set:
			announce(job.Name, "Set")
			job.Result, err = SetValJob(job.Set, do)

		// Transaction jobs
		case *def.Send:
			announce(job.Name, "Sent")
			job.Result, err = SendJob(job.Send, do)
		case *def.RegisterName:
			announce(job.Name, "RegisterName")
			job.Result, err = RegisterNameJob(job.RegisterName, do)
		case *def.Permission:
			announce(job.Name, "Permission")
			job.Result, err = PermissionJob(job.Permission, do)

		// Contracts jobs
		case *def.Deploy:
			announce(job.Name, "Deploy")
			job.Result, err = DeployJob(job.Deploy, do)
		case *def.Call:
			announce(job.Name, "Call")
			job.Result, job.Variables, err = CallJob(job.Call, do)
		case *def.Build:
			announce(job.Name, "Build")
			job.Result, err = BuildJob(job.Build, do)

		// State jobs
		case *def.RestoreState:
			announce(job.Name, "RestoreState")
			job.Result, err = RestoreStateJob(job.RestoreState, do)
		case *def.DumpState:
			announce(job.Name, "DumpState")
			job.Result, err = DumpStateJob(job.DumpState, do)

		// Test jobs
		case *def.QueryAccount:
			announce(job.Name, "QueryAccount")
			job.Result, err = QueryAccountJob(job.QueryAccount, do)
		case *def.QueryContract:
			announce(job.Name, "QueryContract")
			job.Result, job.Variables, err = QueryContractJob(job.QueryContract, do)
		case *def.QueryName:
			announce(job.Name, "QueryName")
			job.Result, err = QueryNameJob(job.QueryName, do)
		case *def.QueryVals:
			announce(job.Name, "QueryVals")
			job.Result, err = QueryValsJob(job.QueryVals, do)
		case *def.Assert:
			announce(job.Name, "Assert")
			job.Result, err = AssertJob(job.Assert, do)

		default:
			log.Error("")
			return fmt.Errorf("the Job specified in deploy.yaml and parsed as '%v' is not recognised as a valid job",
				job)
		}

		if len(job.Variables) != 0 {
			for _, theJob := range job.Variables {
				log.WithField("=>", fmt.Sprintf("%s,%s", theJob.Name, theJob.Value)).Info("Job Vars")
			}
		}

		if err != nil {
			return err
		}
	}

	postProcess(do)
	return nil
}

func announce(job, typ string) {
	log.Warn("*****Executing Job*****\n")
	log.WithField("=>", job).Warn("Job Name")
	log.WithField("=>", typ).Info("Type")
	log.Warn("\n")
}

func defaultAddrJob(do *def.Packages) {
	oldJobs := do.Package.Jobs

	newJob := &def.Job{
		Name: "defaultAddr",
		Account: &def.Account{
			Address: do.Address,
		},
	}

	do.Package.Jobs = append([]*def.Job{newJob}, oldJobs...)
}

func defaultSetJobs(do *def.Packages) {
	oldJobs := do.Package.Jobs

	newJobs := []*def.Job{}

	for _, setr := range do.DefaultSets {
		blowdUp := strings.Split(setr, "=")
		if blowdUp[0] != "" {
			newJobs = append(newJobs, &def.Job{
				Name: blowdUp[0],
				Set: &def.Set{
					Value: blowdUp[1],
				},
			})
		}
	}

	do.Package.Jobs = append(newJobs, oldJobs...)
}

func postProcess(do *def.Packages) error {
	// Formulate the results map
	results := make(map[string]interface{})
	for _, job := range do.Package.Jobs {
		results[job.Name] = job.Result
	}

	// check do.YAMLPath and do.DefaultOutput
	var yaml string
	yamlName := strings.LastIndexByte(do.YAMLPath, '.')
	if yamlName >= 0 {
		yaml = do.YAMLPath[:yamlName]
	} else {
		return fmt.Errorf("invalid jobs file path (%s)", do.YAMLPath)
	}

	// if do.YAMLPath is not default and do.DefaultOutput is default, over-ride do.DefaultOutput
	if yaml != "deploy" && do.DefaultOutput == "deploy.output.json" {
		do.DefaultOutput = fmt.Sprintf("%s.output.json", yaml)
	}

	// if CurrentOutput set, we're in a meta job
	if do.CurrentOutput != "" {
		log.Warn(fmt.Sprintf("Writing meta output of [%s] to current directory", do.CurrentOutput))
		return WriteJobResultJSON(results, do.CurrentOutput)
	}

	// Write the output
	log.Warn(fmt.Sprintf("Writing [%s] to current directory", do.DefaultOutput))
	return WriteJobResultJSON(results, do.DefaultOutput)
}

func burrowConnectionNeeded(do *def.Packages) (error, bool) {
	// Dial the chain if needed
	for _, job := range do.Package.Jobs {
		payload, err := job.Payload()
		if err != nil {
			return fmt.Errorf("could not get Job payload: %v", payload), false
		}
		switch payload.(type) {
		case *def.Build:
			continue
		case *def.Set:
			continue
		default:
			return nil, true
		}
	}

	return nil, false
}
<|endoftext|>


<commit_before>/*
Copyright 2020 The Knative 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 mtping

import (
	"context"
	"fmt"
	"sync"

	"github.com/robfig/cron/v3"
	"go.uber.org/zap"
	corev1 "k8s.io/api/core/v1"
	"knative.dev/pkg/logging"
	pkgreconciler "knative.dev/pkg/reconciler"

	"knative.dev/eventing/pkg/apis/eventing"
	"knative.dev/eventing/pkg/apis/sources/v1beta1"
	pingsourcereconciler "knative.dev/eventing/pkg/client/injection/reconciler/sources/v1beta1/pingsource"
)

// Reconciler reconciles PingSources
type Reconciler struct {
	cronRunner *cronJobsRunner
	entryidMu  sync.RWMutex
	entryids   map[string]cron.EntryID // key: resource namespace/name
}

// Check that our Reconciler implements ReconcileKind.
var _ pingsourcereconciler.Interface = (*Reconciler)(nil)

// Check that our Reconciler implements FinalizeKind.
var _ pingsourcereconciler.Finalizer = (*Reconciler)(nil)

func (r *Reconciler) ReconcileKind(ctx context.Context, source *v1beta1.PingSource) pkgreconciler.Event {
	scope, ok := source.Annotations[eventing.ScopeAnnotationKey]
	if ok && scope != eventing.ScopeCluster {
		// Not our responsibility
		logging.FromContext(ctx).Infow("Skipping non-cluster-scoped PingSource", zap.Any("namespace", source.Namespace), zap.Any("name", source.Name))
		return nil
	}

	if !source.Status.IsReady() {
		return fmt.Errorf("PingSource is not ready. Cannot configure the cron jobs runner")
	}

	reconcileErr := r.reconcile(ctx, source)
	if reconcileErr != nil {
		logging.FromContext(ctx).Errorw("Error reconciling PingSource", zap.Error(reconcileErr))
	} else {
		logging.FromContext(ctx).Debug("PingSource reconciled")
	}
	return reconcileErr
}

func (r *Reconciler) reconcile(ctx context.Context, source *v1beta1.PingSource) error {
	logging.FromContext(ctx).Info("synchronizing schedule")

	key := fmt.Sprintf("%s/%s", source.Namespace, source.Name)
	// Is the schedule already cached?
	r.entryidMu.RLock()
	id, ok := r.entryids[key]
	r.entryidMu.RUnlock()

	if ok {
		r.cronRunner.RemoveSchedule(id)
	}

	config := PingConfig{
		ObjectReference: corev1.ObjectReference{
			Namespace: source.Namespace,
			Name:      source.Name,
		},
		Schedule: source.Spec.Schedule,
		JsonData: source.Spec.JsonData,

		SinkURI: source.Status.SinkURI.String(),
	}
	if source.Spec.CloudEventOverrides != nil {
		config.Extensions = source.Spec.CloudEventOverrides.Extensions
	}

	id = r.cronRunner.AddSchedule(config)

	r.entryidMu.Lock()
	r.entryids[key] = id
	r.entryidMu.Unlock()

	return nil
}

func (r *Reconciler) FinalizeKind(ctx context.Context, source *v1beta1.PingSource) pkgreconciler.Event {
	key := fmt.Sprintf("%s/%s", source.Namespace, source.Name)

	r.entryidMu.RLock()
	id, ok := r.entryids[key]
	r.entryidMu.RUnlock()

	if ok {
		r.cronRunner.RemoveSchedule(id)

		r.entryidMu.Lock()
		delete(r.entryids, key)
		r.entryidMu.Unlock()
	}

	return nil
}
<commit_msg>remove useless scope test (#3997)<commit_after>/*
Copyright 2020 The Knative 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 mtping

import (
	"context"
	"fmt"
	"sync"

	"github.com/robfig/cron/v3"
	"go.uber.org/zap"
	corev1 "k8s.io/api/core/v1"
	"knative.dev/pkg/logging"
	pkgreconciler "knative.dev/pkg/reconciler"

	"knative.dev/eventing/pkg/apis/sources/v1beta1"
	pingsourcereconciler "knative.dev/eventing/pkg/client/injection/reconciler/sources/v1beta1/pingsource"
)

// Reconciler reconciles PingSources
type Reconciler struct {
	cronRunner *cronJobsRunner
	entryidMu  sync.RWMutex
	entryids   map[string]cron.EntryID // key: resource namespace/name
}

// Check that our Reconciler implements ReconcileKind.
var _ pingsourcereconciler.Interface = (*Reconciler)(nil)

// Check that our Reconciler implements FinalizeKind.
var _ pingsourcereconciler.Finalizer = (*Reconciler)(nil)

func (r *Reconciler) ReconcileKind(ctx context.Context, source *v1beta1.PingSource) pkgreconciler.Event {
	if !source.Status.IsReady() {
		return fmt.Errorf("PingSource is not ready. Cannot configure the cron jobs runner")
	}

	reconcileErr := r.reconcile(ctx, source)
	if reconcileErr != nil {
		logging.FromContext(ctx).Errorw("Error reconciling PingSource", zap.Error(reconcileErr))
	} else {
		logging.FromContext(ctx).Debug("PingSource reconciled")
	}
	return reconcileErr
}

func (r *Reconciler) reconcile(ctx context.Context, source *v1beta1.PingSource) error {
	logging.FromContext(ctx).Info("synchronizing schedule")

	key := fmt.Sprintf("%s/%s", source.Namespace, source.Name)
	// Is the schedule already cached?
	r.entryidMu.RLock()
	id, ok := r.entryids[key]
	r.entryidMu.RUnlock()

	if ok {
		r.cronRunner.RemoveSchedule(id)
	}

	config := PingConfig{
		ObjectReference: corev1.ObjectReference{
			Namespace: source.Namespace,
			Name:      source.Name,
		},
		Schedule: source.Spec.Schedule,
		JsonData: source.Spec.JsonData,

		SinkURI: source.Status.SinkURI.String(),
	}
	if source.Spec.CloudEventOverrides != nil {
		config.Extensions = source.Spec.CloudEventOverrides.Extensions
	}

	id = r.cronRunner.AddSchedule(config)

	r.entryidMu.Lock()
	r.entryids[key] = id
	r.entryidMu.Unlock()

	return nil
}

func (r *Reconciler) FinalizeKind(ctx context.Context, source *v1beta1.PingSource) pkgreconciler.Event {
	key := fmt.Sprintf("%s/%s", source.Namespace, source.Name)

	r.entryidMu.RLock()
	id, ok := r.entryids[key]
	r.entryidMu.RUnlock()

	if ok {
		r.cronRunner.RemoveSchedule(id)

		r.entryidMu.Lock()
		delete(r.entryids, key)
		r.entryidMu.Unlock()
	}

	return nil
}
<|endoftext|>


<commit_before>package decoders

import (
	"errors"
	"fmt"
	"log"
	"math"
	"regexp"
	"strconv"

	"github.com/seadsystem/Backend/DB/landingzone/constants"
)

type SeadPacket struct {
	Type      byte
	Location  byte
	Timestamp float64
	Period    float64
	Count     uint
	Data      float32
	Serial    int
}

var headerRegex *regexp.Regexp
var InvalidHeader = errors.New("Invalid header.")
var InvalidPacket = errors.New("Invalid packet.")
var InvalidTime = errors.New("Invalid time.")

// init sets up stuff we need with proper error handling. If it isn't complicated or doesn't need error handling, it can probably just be assigned directly.
func init() {
	var err error
	headerRegex, err = regexp.Compile(constants.HEADER_REGEX)
	if err != nil {
		log.Panic("Regex compile error:", err)
	}
}

// DecodeHeader verifies that the header is in the correct format and extracts the serial number
func DecodeHeader(packet []byte) (serial int, err error) {
	serialStrings := headerRegex.FindSubmatch(packet)

	if serialStrings == nil || len(serialStrings) != 2 {
		err = InvalidHeader
		return
	}

	log.Printf("Header serial string: %s\n", string(serialStrings[1]))

	serial, err = strconv.Atoi(string(serialStrings[1]))
	return
}

// DecodePacket extracts the data sent from sensor
func DecodePacket(buffer []byte) (packet SeadPacket, err error) {
	for i := 0; i < len(buffer); {
		datatype := buffer[i]
		i++

		// Switch on the type of data sent in the packet
		switch {
		case datatype == 'T':
			// Type
			packet.Type = buffer[i]
			i++
		case datatype == 'l':
			// Location
			packet.Location = buffer[i]
			i++
		case datatype == 't':
			// Timestamp
			packet.Timestamp, err = asciiTimeToDouble(buffer[i : i+14])
			i += 14
		case datatype == 'P':
			// Period separator
			packet.Period, err = asciiTimeToDouble(buffer[i : i+14])
			i += 14
		case datatype == 'C':
			// Count
			packet.Count = Binary2uint(buffer[i : i+2])
			i += 2
		case datatype == 'D':
			// Data
			// if count isn't set, return error
			if packet.Count == 0 {
				err = InvalidPacket
			} else {
				count := 2 * int(packet.Count)
				packet.Data = math.Float32frombits(uint32(Binary2uint(buffer[i : i+count])))
				i += count
			}
		case datatype == 'S':
			// Serial
			packet.Serial, err = strconv.Atoi(string(buffer[i : i+6]))
			i += 6
		case datatype == 'X':
			return
		default:
			err = InvalidPacket
		}

		if err != nil {
			return
		}
	}
	err = InvalidPacket
	return
}

func doubleToAsciiTime(double_time float64) string {
	// TODO: Check if this logic is correct or if we need to use http://golang.org/pkg/math/#Mod
	int_time := int(double_time)
	var days = math.Floor(double_time / (60 * 60 * 24))
	var hours = (int_time % (60 * 60 * 24)) / (60 * 60)
	var minutes = (int_time % (60 * 60)) / 60
	var seconds = (int_time % (60)) / 1
	var milliseconds = (int_time * 1000) % 1000
	var clock_time = (int_time * 12000) % 12

	return fmt.Sprintf("%03d%02d%02d%02d%03d%02d", days, hours, minutes, seconds, milliseconds, clock_time)
}

func asciiTimeToDouble(ascii_time []byte) (time float64, err error) {
	// Check time string format
	if len(ascii_time) != 16 {
		err = InvalidTime
	}
	_, err = strconv.Atoi(string(ascii_time))
	if err != nil {
		return
	}

	// Do the conversion now that we know it should work
	var ptr int = 0
	days, err := strconv.Atoi(string(ascii_time[ptr : ptr+3]))
	if err != nil {
		return
	}
	ptr += 3
	time += float64(60 * 60 * 24 * days)
	hours, err := strconv.Atoi(string(ascii_time[ptr : ptr+2]))
	if err != nil {
		return
	}
	ptr += 2
	time += float64(60 * 60 * hours)
	minutes, err := strconv.Atoi(string(ascii_time[ptr : ptr+2]))
	if err != nil {
		return
	}
	ptr += 2
	time += float64(60 * minutes)
	seconds, err := strconv.Atoi(string(ascii_time[ptr : ptr+2]))
	if err != nil {
		return
	}
	ptr += 2
	time += float64(seconds)
	milliseconds, err := strconv.Atoi(string(ascii_time[ptr : ptr+3]))
	if err != nil {
		return
	}
	ptr += 3
	time += float64(milliseconds) / 1000.0
	clock, err := strconv.Atoi(string(ascii_time[ptr : ptr+2]))
	if err != nil {
		return
	}
	ptr += 2
	time += float64(clock) / 12000.0
	return
}

// Every checks if every byte in a slice meets some criteria
func Every(data []byte, check func(byte) bool) bool {
	for _, element := range data {
		if !check(element) {
			return false
		}
	}
	return true
}

// Binary2uint converts a byte array containing binary data into an int
func Binary2uint(data []byte) (total uint) {
	for index, element := range data {
		total += uint(element) << uint(index*8)
	}
	return
}

// Binary2uint64 converts a byte array containing binary data into an int
func Binary2uint64(data []byte) (total uint64) {
	for index, element := range data {
		total += uint64(element) << uint64(index*8)
	}
	return
}
<commit_msg>Converted float64 time to int64 time.<commit_after>package decoders

import (
	"errors"
	"fmt"
	"log"
	"math"
	"regexp"
	"strconv"

	"github.com/seadsystem/Backend/DB/landingzone/constants"
)

type SeadPacket struct {
	Type      byte
	Location  byte
	Timestamp int64
	Period    float64
	Count     uint
	Data      float32
	Serial    int
}

var headerRegex *regexp.Regexp
var InvalidHeader = errors.New("Invalid header.")
var InvalidPacket = errors.New("Invalid packet.")
var InvalidTime = errors.New("Invalid time.")

// init sets up stuff we need with proper error handling. If it isn't complicated or doesn't need error handling, it can probably just be assigned directly.
func init() {
	var err error
	headerRegex, err = regexp.Compile(constants.HEADER_REGEX)
	if err != nil {
		log.Panic("Regex compile error:", err)
	}
}

// DecodeHeader verifies that the header is in the correct format and extracts the serial number
func DecodeHeader(packet []byte) (serial int, err error) {
	serialStrings := headerRegex.FindSubmatch(packet)

	if serialStrings == nil || len(serialStrings) != 2 {
		err = InvalidHeader
		return
	}

	log.Printf("Header serial string: %s\n", string(serialStrings[1]))

	serial, err = strconv.Atoi(string(serialStrings[1]))
	return
}

// DecodePacket extracts the data sent from sensor
func DecodePacket(buffer []byte) (packet SeadPacket, err error) {
	for i := 0; i < len(buffer); {
		datatype := buffer[i]
		i++

		// Switch on the type of data sent in the packet
		switch {
		case datatype == 'T':
			// Type
			packet.Type = buffer[i]
			i++
		case datatype == 'l':
			// Location
			packet.Location = buffer[i]
			i++
		case datatype == 't':
			// Timestamp
			packet.Timestamp, err = int64(asciiTimeToDouble(buffer[i : i+14]) * math.Pow10(12))
			i += 14
		case datatype == 'P':
			// Period separator
			packet.Period, err = asciiTimeToDouble(buffer[i : i+14])
			i += 14
		case datatype == 'C':
			// Count
			packet.Count = Binary2uint(buffer[i : i+2])
			i += 2
		case datatype == 'D':
			// Data
			// if count isn't set, return error
			if packet.Count == 0 {
				err = InvalidPacket
			} else {
				count := 2 * int(packet.Count)
				packet.Data = math.Float32frombits(uint32(Binary2uint(buffer[i : i+count])))
				i += count
			}
		case datatype == 'S':
			// Serial
			packet.Serial, err = strconv.Atoi(string(buffer[i : i+6]))
			i += 6
		case datatype == 'X':
			return
		default:
			err = InvalidPacket
		}

		if err != nil {
			return
		}
	}
	err = InvalidPacket
	return
}

func doubleToAsciiTime(double_time float64) string {
	// TODO: Check if this logic is correct or if we need to use http://golang.org/pkg/math/#Mod
	int_time := int(double_time)
	var days = math.Floor(double_time / (60 * 60 * 24))
	var hours = (int_time % (60 * 60 * 24)) / (60 * 60)
	var minutes = (int_time % (60 * 60)) / 60
	var seconds = (int_time % (60)) / 1
	var milliseconds = (int_time * 1000) % 1000
	var clock_time = (int_time * 12000) % 12

	return fmt.Sprintf("%03d%02d%02d%02d%03d%02d", days, hours, minutes, seconds, milliseconds, clock_time)
}

func asciiTimeToDouble(ascii_time []byte) (time float64, err error) {
	// Check time string format
	if len(ascii_time) != 16 {
		err = InvalidTime
	}
	_, err = strconv.Atoi(string(ascii_time))
	if err != nil {
		return
	}

	// Do the conversion now that we know it should work
	var ptr int = 0
	days, err := strconv.Atoi(string(ascii_time[ptr : ptr+3]))
	if err != nil {
		return
	}
	ptr += 3
	time += float64(60 * 60 * 24 * days)
	hours, err := strconv.Atoi(string(ascii_time[ptr : ptr+2]))
	if err != nil {
		return
	}
	ptr += 2
	time += float64(60 * 60 * hours)
	minutes, err := strconv.Atoi(string(ascii_time[ptr : ptr+2]))
	if err != nil {
		return
	}
	ptr += 2
	time += float64(60 * minutes)
	seconds, err := strconv.Atoi(string(ascii_time[ptr : ptr+2]))
	if err != nil {
		return
	}
	ptr += 2
	time += float64(seconds)
	milliseconds, err := strconv.Atoi(string(ascii_time[ptr : ptr+3]))
	if err != nil {
		return
	}
	ptr += 3
	time += float64(milliseconds) / 1000.0
	clock, err := strconv.Atoi(string(ascii_time[ptr : ptr+2]))
	if err != nil {
		return
	}
	ptr += 2
	time += float64(clock) / 12000.0
	return
}

// Every checks if every byte in a slice meets some criteria
func Every(data []byte, check func(byte) bool) bool {
	for _, element := range data {
		if !check(element) {
			return false
		}
	}
	return true
}

// Binary2uint converts a byte array containing binary data into an int
func Binary2uint(data []byte) (total uint) {
	for index, element := range data {
		total += uint(element) << uint(index*8)
	}
	return
}

// Binary2uint64 converts a byte array containing binary data into an int
func Binary2uint64(data []byte) (total uint64) {
	for index, element := range data {
		total += uint64(element) << uint64(index*8)
	}
	return
}
<|endoftext|>