<commit_before>package config

import (
	"xd/lib/configparser"
)

type RPCConfig struct {
	Enabled bool
	Bind    string
	// TODO: authentication
}

const DefaultRPCAddr = "127.0.0.1:1488"

func (cfg *RPCConfig) Load(s *configparser.Section) error {
	if s != nil {
		cfg.Bind = s.Get("bind", DefaultRPCAddr)
		cfg.Enabled = s.Get("enabled", "1") == "1"
	}
	if cfg.Bind == "" {
		cfg.Bind = DefaultRPCAddr
	}
	return nil
}

func (cfg *RPCConfig) Save(s *configparser.Section) error {
	enabled := "1"
	if !cfg.Enabled {
		enabled = "0"
	}
	opts := map[string]string{
		"enabled": enabled,
	}
	if cfg.Bind != "" {
		opts["bind"] = cfg.Bind
	}

	for k := range opts {
		s.Add(k, opts[k])
	}

	return nil
}

func (cfg *RPCConfig) LoadEnv() {

}
<commit_msg>add environmental variable option for rpc config<commit_after>package config

import (
	"os"
	"xd/lib/configparser"
)

type RPCConfig struct {
	Enabled bool
	Bind    string
	// TODO: authentication
}

const DefaultRPCAddr = "127.0.0.1:1488"

func (cfg *RPCConfig) Load(s *configparser.Section) error {
	if s != nil {
		cfg.Bind = s.Get("bind", DefaultRPCAddr)
		cfg.Enabled = s.Get("enabled", "1") == "1"
	}
	if cfg.Bind == "" {
		cfg.Bind = DefaultRPCAddr
	}
	return nil
}

func (cfg *RPCConfig) Save(s *configparser.Section) error {
	enabled := "1"
	if !cfg.Enabled {
		enabled = "0"
	}
	opts := map[string]string{
		"enabled": enabled,
	}
	if cfg.Bind != "" {
		opts["bind"] = cfg.Bind
	}

	for k := range opts {
		s.Add(k, opts[k])
	}

	return nil
}

const EnvRPCAddr = "XD_RPC_ADDRESS"

func (cfg *RPCConfig) LoadEnv() {
	addr := os.Getenv(EnvRPCAddr)
	if addr != "" {
		cfg.Bind = addr
	}
}
<|endoftext|>


<commit_before>/*
Copyright IBM Corp 2016 All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

		 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package main

import (
	"errors"
	"fmt"
	//"encoding/json"

	"github.com/hyperledger/fabric/core/chaincode/shim"

)

// SimpleChaincode example simple Chaincode implementation
type SimpleChaincode struct {
}

type Emp struct{
	empId string `json:"empId"`
	name string `json:"name"`
	title string `json:"title"`

}

func main() {
	err := shim.Start(new(SimpleChaincode))
	if err != nil {
		fmt.Printf("Error starting Simple chaincode: %s", err)
	}
}

// Init resets all the things
func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {

	if len(args) != 1 {
		return nil, errors.New("Incorrect number of arguments. Expecting 1")
	}

	  err := stub.PutState("table_ibminsert", []byte(args[0]))
	if err != nil {
		return nil, err
	}

	// Check if table already exists
	_,  err = stub.GetTable("EmpTable")

	if err == nil {
		// Table already exists; do not recreate
		return nil, nil
	}
     fmt.Println("ready to create the table: ")
	// Create application Table
	err = stub.CreateTable("EmpTable", []*shim.ColumnDefinition{
		&shim.ColumnDefinition{Name: "empId", Type: shim.ColumnDefinition_STRING, Key: true},
		&shim.ColumnDefinition{Name: "name", Type: shim.ColumnDefinition_STRING, Key: false},
		&shim.ColumnDefinition{Name: "title", Type: shim.ColumnDefinition_STRING, Key: false},

	})
	if err != nil {
		return nil, errors.New("Failed creating ApplicationTable.")

	}

	return nil, nil
	}

// Invoke isur entry point to invoke a chaincode function
func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	fmt.Println("invoke is running " + function)

	// Handle different functions
	if function == "init" {
		return t.Init(stub, "init", args)
	} else if function == "write" {
		return t.write(stub, args)
	}
	fmt.Println("invoke did not find func: " + function)

	if function == "submitEmp" {
		if len(args) != 3 {
			return nil, fmt.Errorf("Incorrect number of arguments. Expecting 20. Got: %d.", len(args))
		}

		empId := args[0]
		name := args[1]
		title := args[2]

		//insert a row

		ok, err := stub.InsertRow("EmpTable", shim.Row{
		Columns: []*shim.Column{
				&shim.Column{Value: &shim.Column_String_{String_: empId}},
				&shim.Column{Value: &shim.Column_String_{String_: name}},
				&shim.Column{Value: &shim.Column_String_{String_: title}},
				}})

	if !ok && err == nil {
			return nil, errors.New("Row already exists.")
		}

	}
	fmt.Println("values Inserted in the table: ")

	return nil, errors.New("Received unknown function invocation: " + function)
}

// Query is our entry point for queries
func (t *SimpleChaincode) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {

	fmt.Println("query is running " + function)

	// Handle different functions
	if function == "read" { //read a variable
		return t.read(stub, args)
	}
	fmt.Println("query did not find func: " + function)

	return nil, errors.New("Received unknown function query: " + function)
}

// write - invoke function to write key/value pair
func (t *SimpleChaincode) write(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
	var key, value string
	var err error
	fmt.Println("running write()")

	if len(args) != 2 {
		return nil, errors.New("Incorrect number of arguments. Expecting 2. name of the key and value to set")
	}

	key = args[0] //rename for funsies
	value = args[1]
	err = stub.PutState(key, []byte(value)) //write the variable into the chaincode state
	if err != nil {
		return nil, err
	}
	return nil, nil
}

// read - query function to read key/value pair
func (t *SimpleChaincode) read(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {

	if len(args) != 1 {
		return nil, errors.New("Incorrect number of arguments. Expecting applicationid to query")
	}

	fmt.Println("came into read func and geting empid: ")

	empId := args[0]

fmt.Println("came into read func and geting empid: "+empId)

// Get the row pertaining to this applicationId
	var columns []shim.Column
	col1 := shim.Column{Value: &shim.Column_String_{String_: empId}}
	columns = append(columns, col1)

	row, err := stub.GetRow("EmpTable", columns)
	if err != nil {
		jsonResp := "{\"Error\":\"Failed to get the data for the dataaa " + empId + "\"}"
		return nil, errors.New(jsonResp)
	}

	if len(row.Columns) == 0 || row.Columns[2] == nil {
		fmt.Println("no rows returned")

		return nil, errors.New("row or column value not found")
	}

	//res2E := Emp{}

	//res2E.empId = row.Columns[0].GetString_()
	//res2E.name = row.Columns[1].GetString_()
	//res2E.title = row.Columns[2].GetString_()

	//mapB, _ := json.Marshal(res2E)

	//fmt.Println(string(mapB))

	return nil, nil
}
<commit_msg>empstoreandretri<commit_after>
package main
import (
	"errors"

	"fmt"

	//"encoding/json"

	"github.com/hyperledger/fabric/core/chaincode/shim"
)

type SampleChaincode struct {
}

//custom data models
type EMPInfo struct {
	EmpId     string  `json:"empid"`
	Firstname string `json:"firstname"`
	Lastname  string `json:"lastname"`
	Email     string `json:"email"`
	Mobile    string `json:"mobile"`
}

type EMPDetails struct {
	MonthlySalary      int `json:"monthlySalary"`
	MonthlyRent        int `json:"monthlyRent"`
	OtherExpenditure   int `json:"otherExpenditure"`

}

func CreateEmploye(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {

	fmt.Printf("enter to create emp")

	if len(args) < 2 {

		return nil, errors.New("Expected atleast two arguments  for creation")
	}

	var EmpId= args[0]
	var EmpDetails = args[1]

	err := stub.PutState(EmpId, []byte(EmpDetails))
	if err != nil {

		return nil, err
	}

	fmt.Printf("created Emp")
	return nil, nil

}

func GetEmpDetails(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {

	if len(args) < 1 {

		return nil, errors.New("Missing loan emp ID")
	}

	var EmpId = args[0]
	bytes, err := stub.GetState(EmpId)
	if err != nil {

		return nil, err
	}
	return bytes, nil
}

func (t *SampleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	return nil, nil
}

func (t *SampleChaincode) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	if function == "GetEmpDetails" {
		return GetEmpDetails(stub, args)
	}
	return nil, nil
}

func (t *SampleChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	if function == "CreateLoanApplication" {

			return CreateEmploye(stub, args)
		} else {
			return nil, errors.New(" does not have access to create a loan application")
		}
return nil, nil
	}

func main() {

	err := shim.Start(new(SampleChaincode))
	if err != nil {

	} else {

	}

}<|endoftext|>


<commit_before>// Copyright 2015 Google Inc. All Rights Reserved.
// Author: jacobsa@google.com (Aaron Jacobs)

package gcsproxy

import (
	"container/list"
	"errors"
	"fmt"
	"reflect"
	"sort"
	"time"

	"github.com/jacobsa/gcloud/gcs"
	"github.com/jacobsa/gcloud/gcs/gcsutil"
	"github.com/jacobsa/gcsfuse/timeutil"
	"golang.org/x/net/context"
	"google.golang.org/cloud/storage"
)

// A view on a "directory" in GCS that caches listings and modifications.
//
// Directories are by convention defined by '/' characters in object names. A
// directory is uniquely identified by an object name prefix that ends with a
// '/', or the empty string for the root directory. Given such a prefix P, the
// contents of directory P are:
//
//  *  The "files" within the directory: all objects named N such that
//      *  P is a strict prefix of N.
//      *  The portion of N following the prefix P contains no slashes.
//
//  *  The immediate "sub-directories": all strings P' such that
//      *  P' is a legal directory prefix according to the definition above.
//      *  P is a strict prefix of P'.
//      *  The portion of P' following the prefix P contains exactly one slash.
//      *  There is at least one objcet with name N such that N has P' as a
//         prefix.
//
// So for example, imagine a bucket contains the following objects:
//
//  *  burrito/
//  *  enchilada/
//  *  enchilada/0
//  *  enchilada/1
//  *  queso/carne/carnitas
//  *  queso/carne/nachos/
//  *  taco
//
// Then the directory structure looks like the following, where a trailing
// slash indicates a directory and the top level is the contents of the root
// directory:
//
//     burrito/
//     enchilada/
//         0
//         1
//     queso/
//         carne/
//             carnitas
//             nachos/
//     taco
//
// In particular, note that some directories are explicitly defined by a
// placeholder object, whether empty (burrito/, queso/carne/nachos/) or
// non-empty (enchilada/), and others are implicitly defined by
// their children (queso/carne/).
//
// Not safe for concurrent access. The user must provide external
// synchronization if necessary.
type ListingProxy struct {
	/////////////////////////
	// Dependencies
	/////////////////////////

	bucket gcs.Bucket
	clock  timeutil.Clock

	/////////////////////////
	// Constant data
	/////////////////////////

	// INVARIANT: checkDirName(name) == nil
	name string

	/////////////////////////
	// Mutable state
	/////////////////////////

	// Our current best understanding of the contents of the directory in GCS,
	// formed by listing the bucket and then patching according to child
	// modification records at the time, and patched since then by subsequent
	// modifications.
	//
	// The time after which this should be generated anew from a new listing is
	// also stored. This is set to the time at which the listing completed plus
	// the listing cache TTL.
	//
	// Sub-directories are of type string, and objects are of type
	// *storage.Object.
	//
	// INVARIANT: contents != nil
	// INVARIANT: All values are of type string or *storage.Object.
	// INVARIANT: For all string values v, checkDirName(v) == nil
	// INVARIANT: For all string values v, name is a strict prefix of v
	// INVARIANT: For all object values o, checkDirName(o.Name) != nil
	// INVARIANT: For all object values o, name is a strict prefix of o.Name
	// INVARIANT: All entries are indexed by the correct name.
	contents           map[string]interface{}
	contentsExpiration time.Time

	// A collection of children that have recently been added or removed locally
	// and the time at which it happened, ordered by the sequence in which it
	// happened. Elements M with M.node == nil are removals; all others are
	// additions.
	//
	// For a record M in this list with M's age less than the modification TTL,
	// any listing from the bucket should be augmented by pretending M just
	// happened.
	//
	// INVARIANT: All elements are of type childModification.
	// INVARIANT: Contains no duplicate names.
	// INVARIANT: For each M with M.node == nil, contents does not contain M.name.
	// INVARIANT: For each M with M.node != nil, contents[M.name] == M.node.
	childModifications list.List

	// An index of childModifications by name.
	//
	// INVARIANT: childModificationsIndex != nil
	// INVARIANT: For all names N in the map, the indexed modification has name N.
	// INVARIANT: Contains exactly the set of names in childModifications.
	childModificationsIndex map[string]*list.Element
}

// See ListingProxy.childModifications.
type childModification struct {
	time time.Time
	name string

	// INVARIANT: node == nil or node is of type string or *storage.Object
	node interface{}
}

// How long we cache the most recent listing for a particular directory from
// GCS before regarding it as stale.
//
// Intended to paper over performance issues caused by quick follow-up calls;
// for example when the fuse VFS performs a readdir followed quickly by a
// lookup for each child. The drawback is that this increases the time before a
// write by a foreign machine within a recently-listed directory will be seen
// locally.
//
// TODO(jacobsa): Do we need this at all? Maybe the VFS layer does appropriate
// caching. Experiment with setting it to zero or ripping out the code.
//
// TODO(jacobsa): Set this according to real-world performance issues when the
// kernel does e.g. ReadDir followed by Lookup. Can probably be set quite
// small.
//
// TODO(jacobsa): Can this be moved to a decorator implementation of gcs.Bucket
// instead of living here?
const ListingProxy_ListingCacheTTL = 10 * time.Second

// How long we remember that we took some action on the contents of a directory
// (linking or unlinking), and pretend the action is reflected in the listing
// even if it is not reflected in a call to Bucket.ListObjects.
//
// Intended to paper over the fact that GCS doesn't offer list-your-own-writes
// consistency: it may be an arbitrarily long time before you see the creation
// or deletion of an object in a subsequent listing, and even if you see it in
// one listing you may not see it in the next. The drawback is that foreign
// modifications to recently-locally-modified directories will not be reflected
// locally for awhile.
//
// TODO(jacobsa): Set this according to information about listing staleness
// distributions from the GCS team.
//
// TODO(jacobsa): Can this be moved to a decorator implementation of gcs.Bucket
// instead of living here?
const ListingProxy_ModificationMemoryTTL = 5 * time.Minute

// Create a listing proxy object for the directory identified by the given
// prefix (see comments on ListingProxy). The supplied clock will be used for
// cache TTLs.
func NewListingProxy(
	bucket gcs.Bucket,
	clock timeutil.Clock,
	dir string) (lp *ListingProxy, err error) {
	// Make sure the directory name is legal.
	if err = checkDirName(dir); err != nil {
		err = fmt.Errorf("Illegal directory name (%v): %s", err, dir)
		return
	}

	// Create the object.
	lp = &ListingProxy{
		bucket:                  bucket,
		clock:                   clock,
		name:                    dir,
		contents:                make(map[string]interface{}),
		childModificationsIndex: make(map[string]*list.Element),
	}

	return
}

// Return the directory prefix with which this object was configured.
func (lp *ListingProxy) Name() string {
	return lp.name
}

// Panic if any internal invariants are violated. Careful users can call this
// at appropriate times to help debug weirdness. Consider using
// syncutil.InvariantMutex to automate the process.
func (lp *ListingProxy) CheckInvariants() {
	if err := checkDirName(lp.name); err != nil {
		panic("Illegal name: " + err.Error())
	}

	// Check that maps are non-nil.
	if lp.contents == nil || lp.childModificationsIndex == nil {
		panic("Expected contents and childModificationsIndex to be non-nil.")
	}

	// Check each element of the contents map.
	for name, node := range lp.contents {
		switch typedNode := node.(type) {
		default:
			panic(fmt.Sprintf("Bad type for node: %v", node))

		case string:
			// Sub-directory
			if name != typedNode {
				panic(fmt.Sprintf("Name mismatch: %s vs. %s", name, typedNode))
			}

			if err := checkDirName(typedNode); err != nil {
				panic("Illegal directory name: " + typedNode)
			}

		case *storage.Object:
			if name != typedNode.Name {
				panic(fmt.Sprintf("Name mismatch: %s vs. %s", name, typedNode.Name))
			}

			if err := checkDirName(typedNode.Name); err == nil {
				panic("Illegal object name: " + typedNode.Name)
			}
		}
	}

	// Check each child modification. Build a list of names we've seen while
	// doing so.
	var listNames sort.StringSlice
	for e := lp.childModifications.Front(); e != nil; e = e.Next() {
		m := e.Value.(childModification)
		listNames = append(listNames, m.name)

		if m.node == nil {
			if n, ok := lp.contents[m.name]; ok {
				panic(fmt.Sprintf("lp.contents[%s] == %v for removal", m.name, n))
			}
		} else {
			if n := lp.contents[m.name]; n != m.node {
				panic(fmt.Sprintf("lp.contents[%s] == %v, not %v", m.name, n, m.node))
			}
		}
	}

	sort.Sort(listNames)

	// Check that there were no duplicate names.
	for i, name := range listNames {
		if i == 0 {
			continue
		}

		if name == listNames[i-1] {
			panic("Duplicated name in childModifications: " + name)
		}
	}

	// Check the index. Build a list of names it contains While doing so.
	var indexNames sort.StringSlice
	for name, e := range lp.childModificationsIndex {
		indexNames = append(indexNames, name)

		m := e.Value.(childModification)
		if m.name != name {
			panic(fmt.Sprintf("Index name mismatch: %s vs. %s", m.name, name))
		}
	}

	sort.Sort(indexNames)

	// Check that the index contains the same set of names.
	if !reflect.DeepEqual(listNames, indexNames) {
		panic(fmt.Sprintf("Names mismatch:\n%v\n%v", listNames, indexNames))
	}
}

// Obtain a listing of the objects directly within the directory and the
// immediate sub-directories. (See comments on ListingProxy for precise
// semantics.) Object and sub-directory names are fully specified, not
// relative.
//
// This listing reflects any additions and removals set up with NoteNewObject,
// NoteNewSubdirectory, or NoteRemoval.
func (lp *ListingProxy) List(
	ctx context.Context) (objects []*storage.Object, subdirs []string, err error) {
	// List the directory.
	query := &storage.Query{
		Delimiter: "/",
		Prefix:    lp.name,
	}

	if objects, subdirs, err = gcsutil.List(ctx, lp.bucket, query); err != nil {
		err = fmt.Errorf("gcsutil.List: %v", err)
		return
	}

	return
}

// Note that an object has been added to the directory, overriding any previous
// additions or removals with the same name. For awhile after this call, the
// response to a call to List will contain this object even if it is not
// present in a listing from the underlying bucket.
func (lp *ListingProxy) NoteNewObject(o *storage.Object) (err error) {
	err = errors.New("TODO: Implement NoteNewObject.")
	return
}

// Note that a sub-directory has been added to the directory, overriding any
// previous additions or removals with the same name. For awhile after this
// call, the response to a call to List will contain this object even if it is
// not present in a listing from the underlying bucket.
//
// The name must be a legal directory prefix for a sub-directory of this
// directory. See notes on ListingProxy for more details.
func (lp *ListingProxy) NoteNewSubdirectory(name string) (err error) {
	err = errors.New("TODO: Implement NoteNewSubdirectory.")
	return
}

// Note that an object or directory prefix has been removed from the directory,
// overriding any previous additions or removals. For awhile after this call,
// the response to a call to List will not contain this name even if it is
// present in a listing from the underlying bucket.
func (lp *ListingProxy) NoteRemoval(name string) (err error) {
	err = errors.New("TODO: Implement NoteRemoval.")
	return
}

func checkDirName(name string) (err error) {
	if name == "" || name[len(name)-1] == '/' {
		return
	}

	err = errors.New("Non-empty names must end with a slash.")
	return
}
<commit_msg>Sanity check responses.<commit_after>// Copyright 2015 Google Inc. All Rights Reserved.
// Author: jacobsa@google.com (Aaron Jacobs)

package gcsproxy

import (
	"container/list"
	"errors"
	"fmt"
	"reflect"
	"sort"
	"time"

	"github.com/jacobsa/gcloud/gcs"
	"github.com/jacobsa/gcloud/gcs/gcsutil"
	"github.com/jacobsa/gcsfuse/timeutil"
	"golang.org/x/net/context"
	"google.golang.org/cloud/storage"
)

// A view on a "directory" in GCS that caches listings and modifications.
//
// Directories are by convention defined by '/' characters in object names. A
// directory is uniquely identified by an object name prefix that ends with a
// '/', or the empty string for the root directory. Given such a prefix P, the
// contents of directory P are:
//
//  *  The "files" within the directory: all objects named N such that
//      *  P is a strict prefix of N.
//      *  The portion of N following the prefix P contains no slashes.
//
//  *  The immediate "sub-directories": all strings P' such that
//      *  P' is a legal directory prefix according to the definition above.
//      *  P is a strict prefix of P'.
//      *  The portion of P' following the prefix P contains exactly one slash.
//      *  There is at least one objcet with name N such that N has P' as a
//         prefix.
//
// So for example, imagine a bucket contains the following objects:
//
//  *  burrito/
//  *  enchilada/
//  *  enchilada/0
//  *  enchilada/1
//  *  queso/carne/carnitas
//  *  queso/carne/nachos/
//  *  taco
//
// Then the directory structure looks like the following, where a trailing
// slash indicates a directory and the top level is the contents of the root
// directory:
//
//     burrito/
//     enchilada/
//         0
//         1
//     queso/
//         carne/
//             carnitas
//             nachos/
//     taco
//
// In particular, note that some directories are explicitly defined by a
// placeholder object, whether empty (burrito/, queso/carne/nachos/) or
// non-empty (enchilada/), and others are implicitly defined by
// their children (queso/carne/).
//
// Not safe for concurrent access. The user must provide external
// synchronization if necessary.
type ListingProxy struct {
	/////////////////////////
	// Dependencies
	/////////////////////////

	bucket gcs.Bucket
	clock  timeutil.Clock

	/////////////////////////
	// Constant data
	/////////////////////////

	// INVARIANT: checkDirName(name) == nil
	name string

	/////////////////////////
	// Mutable state
	/////////////////////////

	// Our current best understanding of the contents of the directory in GCS,
	// formed by listing the bucket and then patching according to child
	// modification records at the time, and patched since then by subsequent
	// modifications.
	//
	// The time after which this should be generated anew from a new listing is
	// also stored. This is set to the time at which the listing completed plus
	// the listing cache TTL.
	//
	// Sub-directories are of type string, and objects are of type
	// *storage.Object.
	//
	// INVARIANT: contents != nil
	// INVARIANT: All values are of type string or *storage.Object.
	// INVARIANT: For all string values v, checkDirName(v) == nil
	// INVARIANT: For all string values v, name is a strict prefix of v
	// INVARIANT: For all object values o, checkDirName(o.Name) != nil
	// INVARIANT: For all object values o, name is a strict prefix of o.Name
	// INVARIANT: All entries are indexed by the correct name.
	contents           map[string]interface{}
	contentsExpiration time.Time

	// A collection of children that have recently been added or removed locally
	// and the time at which it happened, ordered by the sequence in which it
	// happened. Elements M with M.node == nil are removals; all others are
	// additions.
	//
	// For a record M in this list with M's age less than the modification TTL,
	// any listing from the bucket should be augmented by pretending M just
	// happened.
	//
	// INVARIANT: All elements are of type childModification.
	// INVARIANT: Contains no duplicate names.
	// INVARIANT: For each M with M.node == nil, contents does not contain M.name.
	// INVARIANT: For each M with M.node != nil, contents[M.name] == M.node.
	childModifications list.List

	// An index of childModifications by name.
	//
	// INVARIANT: childModificationsIndex != nil
	// INVARIANT: For all names N in the map, the indexed modification has name N.
	// INVARIANT: Contains exactly the set of names in childModifications.
	childModificationsIndex map[string]*list.Element
}

// See ListingProxy.childModifications.
type childModification struct {
	time time.Time
	name string

	// INVARIANT: node == nil or node is of type string or *storage.Object
	node interface{}
}

// How long we cache the most recent listing for a particular directory from
// GCS before regarding it as stale.
//
// Intended to paper over performance issues caused by quick follow-up calls;
// for example when the fuse VFS performs a readdir followed quickly by a
// lookup for each child. The drawback is that this increases the time before a
// write by a foreign machine within a recently-listed directory will be seen
// locally.
//
// TODO(jacobsa): Do we need this at all? Maybe the VFS layer does appropriate
// caching. Experiment with setting it to zero or ripping out the code.
//
// TODO(jacobsa): Set this according to real-world performance issues when the
// kernel does e.g. ReadDir followed by Lookup. Can probably be set quite
// small.
//
// TODO(jacobsa): Can this be moved to a decorator implementation of gcs.Bucket
// instead of living here?
const ListingProxy_ListingCacheTTL = 10 * time.Second

// How long we remember that we took some action on the contents of a directory
// (linking or unlinking), and pretend the action is reflected in the listing
// even if it is not reflected in a call to Bucket.ListObjects.
//
// Intended to paper over the fact that GCS doesn't offer list-your-own-writes
// consistency: it may be an arbitrarily long time before you see the creation
// or deletion of an object in a subsequent listing, and even if you see it in
// one listing you may not see it in the next. The drawback is that foreign
// modifications to recently-locally-modified directories will not be reflected
// locally for awhile.
//
// TODO(jacobsa): Set this according to information about listing staleness
// distributions from the GCS team.
//
// TODO(jacobsa): Can this be moved to a decorator implementation of gcs.Bucket
// instead of living here?
const ListingProxy_ModificationMemoryTTL = 5 * time.Minute

// Create a listing proxy object for the directory identified by the given
// prefix (see comments on ListingProxy). The supplied clock will be used for
// cache TTLs.
func NewListingProxy(
	bucket gcs.Bucket,
	clock timeutil.Clock,
	dir string) (lp *ListingProxy, err error) {
	// Make sure the directory name is legal.
	if err = checkDirName(dir); err != nil {
		err = fmt.Errorf("Illegal directory name (%v): %s", err, dir)
		return
	}

	// Create the object.
	lp = &ListingProxy{
		bucket:                  bucket,
		clock:                   clock,
		name:                    dir,
		contents:                make(map[string]interface{}),
		childModificationsIndex: make(map[string]*list.Element),
	}

	return
}

// Return the directory prefix with which this object was configured.
func (lp *ListingProxy) Name() string {
	return lp.name
}

// Panic if any internal invariants are violated. Careful users can call this
// at appropriate times to help debug weirdness. Consider using
// syncutil.InvariantMutex to automate the process.
func (lp *ListingProxy) CheckInvariants() {
	if err := checkDirName(lp.name); err != nil {
		panic("Illegal name: " + err.Error())
	}

	// Check that maps are non-nil.
	if lp.contents == nil || lp.childModificationsIndex == nil {
		panic("Expected contents and childModificationsIndex to be non-nil.")
	}

	// Check each element of the contents map.
	for name, node := range lp.contents {
		switch typedNode := node.(type) {
		default:
			panic(fmt.Sprintf("Bad type for node: %v", node))

		case string:
			// Sub-directory
			if name != typedNode {
				panic(fmt.Sprintf("Name mismatch: %s vs. %s", name, typedNode))
			}

			if err := checkDirName(typedNode); err != nil {
				panic("Illegal directory name: " + typedNode)
			}

		case *storage.Object:
			if name != typedNode.Name {
				panic(fmt.Sprintf("Name mismatch: %s vs. %s", name, typedNode.Name))
			}

			if err := checkDirName(typedNode.Name); err == nil {
				panic("Illegal object name: " + typedNode.Name)
			}
		}
	}

	// Check each child modification. Build a list of names we've seen while
	// doing so.
	var listNames sort.StringSlice
	for e := lp.childModifications.Front(); e != nil; e = e.Next() {
		m := e.Value.(childModification)
		listNames = append(listNames, m.name)

		if m.node == nil {
			if n, ok := lp.contents[m.name]; ok {
				panic(fmt.Sprintf("lp.contents[%s] == %v for removal", m.name, n))
			}
		} else {
			if n := lp.contents[m.name]; n != m.node {
				panic(fmt.Sprintf("lp.contents[%s] == %v, not %v", m.name, n, m.node))
			}
		}
	}

	sort.Sort(listNames)

	// Check that there were no duplicate names.
	for i, name := range listNames {
		if i == 0 {
			continue
		}

		if name == listNames[i-1] {
			panic("Duplicated name in childModifications: " + name)
		}
	}

	// Check the index. Build a list of names it contains While doing so.
	var indexNames sort.StringSlice
	for name, e := range lp.childModificationsIndex {
		indexNames = append(indexNames, name)

		m := e.Value.(childModification)
		if m.name != name {
			panic(fmt.Sprintf("Index name mismatch: %s vs. %s", m.name, name))
		}
	}

	sort.Sort(indexNames)

	// Check that the index contains the same set of names.
	if !reflect.DeepEqual(listNames, indexNames) {
		panic(fmt.Sprintf("Names mismatch:\n%v\n%v", listNames, indexNames))
	}
}

// Obtain a listing of the objects directly within the directory and the
// immediate sub-directories. (See comments on ListingProxy for precise
// semantics.) Object and sub-directory names are fully specified, not
// relative.
//
// This listing reflects any additions and removals set up with NoteNewObject,
// NoteNewSubdirectory, or NoteRemoval.
func (lp *ListingProxy) List(
	ctx context.Context) (objects []*storage.Object, subdirs []string, err error) {
	// List the directory.
	query := &storage.Query{
		Delimiter: "/",
		Prefix:    lp.name,
	}

	if objects, subdirs, err = gcsutil.List(ctx, lp.bucket, query); err != nil {
		err = fmt.Errorf("gcsutil.List: %v", err)
		return
	}

	// Make sure the response is valid.
	for _, o := range objects {
		if err = checkDirName(o.Name); err == nil {
			err = fmt.Errorf("Illegal object name returned by List: %s", o.Name)
			return
		}
	}

	for _, subdir := range subdirs {
		if err = checkDirName(subdir); err != nil {
			err = fmt.Errorf(
				"Illegal directory name returned by List (%v): %s",
				err,
				subdir)
			return
		}
	}

	return
}

// Note that an object has been added to the directory, overriding any previous
// additions or removals with the same name. For awhile after this call, the
// response to a call to List will contain this object even if it is not
// present in a listing from the underlying bucket.
func (lp *ListingProxy) NoteNewObject(o *storage.Object) (err error) {
	err = errors.New("TODO: Implement NoteNewObject.")
	return
}

// Note that a sub-directory has been added to the directory, overriding any
// previous additions or removals with the same name. For awhile after this
// call, the response to a call to List will contain this object even if it is
// not present in a listing from the underlying bucket.
//
// The name must be a legal directory prefix for a sub-directory of this
// directory. See notes on ListingProxy for more details.
func (lp *ListingProxy) NoteNewSubdirectory(name string) (err error) {
	err = errors.New("TODO: Implement NoteNewSubdirectory.")
	return
}

// Note that an object or directory prefix has been removed from the directory,
// overriding any previous additions or removals. For awhile after this call,
// the response to a call to List will not contain this name even if it is
// present in a listing from the underlying bucket.
func (lp *ListingProxy) NoteRemoval(name string) (err error) {
	err = errors.New("TODO: Implement NoteRemoval.")
	return
}

func checkDirName(name string) (err error) {
	if name == "" || name[len(name)-1] == '/' {
		return
	}

	err = errors.New("Non-empty names must end with a slash")
	return
}
<|endoftext|>


<commit_before>package netlinkAudit

import (
	"encoding/binary"
	"fmt"
	"syscall"
	"sync/atomic"
	"unsafe"
)

var nextSeqNr uint32

type AuditStatus struct {
	Mask          uint32 /* Bit mask for valid entries */
	Enabled       uint32 /* 1 = enabled, 0 = disabled */
	Failure       uint32 /* Failure-to-log action */
	Pid           uint32 /* pid of auditd process */
	Rate_limit    uint32 /* messages rate limit (per second) */
	Backlog_limit uint32 /* waiting messages limit */
	Lost          uint32 /* messages lost */
	Backlog       uint32 /* messages waiting in queue */
}

type AuditRuleData struct {
	Flags       uint32 /* AUDIT_PER_{TASK,CALL}, AUDIT_PREPEND */
	Action      uint32 /* AUDIT_NEVER, AUDIT_POSSIBLE, AUDIT_ALWAYS */
	Field_count uint32
	Mask        [AUDIT_BITMASK_SIZE]uint32 /* syscall(s) affected */
	Fields      [AUDIT_MAX_FIELDS]uint32
	Values      [AUDIT_MAX_FIELDS]uint32
	Fieldflags  [AUDIT_MAX_FIELDS]uint32
	Buflen      uint32  /* total length of string fields */
	Buf         [0]byte //[0]string /* string fields buffer */
}

type NetlinkSocket struct {
	fd  int
	lsa syscall.SockaddrNetlink
}

type NetlinkAuditRequest struct {
	Header syscall.NlMsghdr
	Data   []byte
}

// for config
type CMap struct {
	Name  string
	Id  int
}

// for config
type Config struct {
	Xmap []CMap
}

func nativeEndian() binary.ByteOrder {
	var x uint32 = 0x01020304
	if *(*byte)(unsafe.Pointer(&x)) == 0x01 {
		return binary.BigEndian
	}
	return binary.LittleEndian
}

//The recvfrom in go takes only a byte [] to put the data recieved from the kernel that removes the need
//for having a separate audit_reply Struct for recieving data from kernel.
func (rr *NetlinkAuditRequest) ToWireFormat() []byte {
	b := make([]byte, rr.Header.Len)
	*(*uint32)(unsafe.Pointer(&b[0:4][0])) = rr.Header.Len
	*(*uint16)(unsafe.Pointer(&b[4:6][0])) = rr.Header.Type
	*(*uint16)(unsafe.Pointer(&b[6:8][0])) = rr.Header.Flags
	*(*uint32)(unsafe.Pointer(&b[8:12][0])) = rr.Header.Seq
	*(*uint32)(unsafe.Pointer(&b[12:16][0])) = rr.Header.Pid
	b = append(b[:16], rr.Data[:]...) //Important b[:16]
	return b
}

func newNetlinkAuditRequest(proto /*seq,*/, family, sizeofData int) *NetlinkAuditRequest {
	rr := &NetlinkAuditRequest{}

	rr.Header.Len = uint32(syscall.NLMSG_HDRLEN + sizeofData)
	rr.Header.Type = uint16(proto)
	rr.Header.Flags = syscall.NLM_F_REQUEST | syscall.NLM_F_ACK
	rr.Header.Seq = atomic.AddUint32(&nextSeqNr, 1) //Autoincrementing Sequence
	return rr
	//	return rr.ToWireFormat()
}

// Round the length of a netlink message up to align it properly.
func nlmAlignOf(msglen int) int {
	return (msglen + syscall.NLMSG_ALIGNTO - 1) & ^(syscall.NLMSG_ALIGNTO - 1)
}

/*
 NLMSG_HDRLEN     ((int) NLMSG_ALIGN(sizeof(struct nlmsghdr)))
 NLMSG_LENGTH(len) ((len) + NLMSG_HDRLEN)
 NLMSG_SPACE(len) NLMSG_ALIGN(NLMSG_LENGTH(len))
 NLMSG_DATA(nlh)  ((void*)(((char*)nlh) + NLMSG_LENGTH(0)))
 NLMSG_NEXT(nlh,len)      ((len) -= NLMSG_ALIGN((nlh)->nlmsg_len), \
                                    (struct nlmsghdr*)(((char*)(nlh)) + NLMSG_ALIGN((nlh)->nlmsg_len)))
 NLMSG_OK(nlh,len) ((len) >= (int)sizeof(struct nlmsghdr) && \
                             (nlh)->nlmsg_len >= sizeof(struct nlmsghdr) && \
                             (nlh)->nlmsg_len <= (len))
*/

func ParseAuditNetlinkMessage(b []byte) ([]syscall.NetlinkMessage, error) {
	var msgs []syscall.NetlinkMessage
	//What is the reason for looping ?
	//	for len(b) >= syscall.NLMSG_HDRLEN {
	h, dbuf, dlen, err := netlinkMessageHeaderAndData(b)
	if err != nil {
		fmt.Println("Error in parsing")
		return nil, err
	}
	//fmt.Println("Get 3", h, dbuf, dlen, len(b))
	m := syscall.NetlinkMessage{Header: *h, Data: dbuf[:int(h.Len) /* -syscall.NLMSG_HDRLEN*/]}
	//Commented the subtraction. Leading to trimming of the output Data string
	msgs = append(msgs, m)
	b = b[dlen:]
	//	}
	return msgs, nil
}

func netlinkMessageHeaderAndData(b []byte) (*syscall.NlMsghdr, []byte, int, error) {

	h := (*syscall.NlMsghdr)(unsafe.Pointer(&b[0]))
	if int(h.Len) < syscall.NLMSG_HDRLEN || int(h.Len) > len(b) {
		foo := int32(nativeEndian().Uint32(b[0:4]))
		fmt.Println("Headerlength with ", foo, b[0]) //!bug ! FIX THIS
		//IT happens only when message don't contain any useful message only dummy strings
		fmt.Println("Error due to....HDRLEN:", syscall.NLMSG_HDRLEN, " Header Length:", h.Len, " Length of BYTE Array:", len(b))
		return nil, nil, 0, syscall.EINVAL
	}
	return h, b[syscall.NLMSG_HDRLEN:], nlmAlignOf(int(h.Len)), nil
}
<commit_msg>Now we are getting logs; First deleting rules then adding rules<commit_after><|endoftext|>


<commit_before>//  Copyright (c) 2013 Couchbase, Inc.
//  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 http

import (
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/http"

	"github.com/couchbaselabs/tuqtng/network"
	"github.com/couchbaselabs/tuqtng/query"
	"github.com/gorilla/mux"
)

type HttpResponse struct {
	w       http.ResponseWriter
	results query.ValueChannel
	err     bool
}

func (this *HttpResponse) SendError(err error) {
	this.err = true
	showError(this.w, fmt.Sprintf("%v", err), 500)
	close(this.results)
}

func (this *HttpResponse) SendResult(val query.Value) {
	this.results <- val
}

func (this *HttpResponse) NoMoreResults() {
	close(this.results)
}

type HttpEndpoint struct {
	queryChannel network.QueryChannel
}

func NewHttpEndpoint(address string) *HttpEndpoint {
	rv := &HttpEndpoint{}

	r := mux.NewRouter()

	r.HandleFunc("/", welcome).Methods("GET")
	r.Handle("/query", rv).Methods("GET", "POST")

	go func() {
		err := http.ListenAndServe(address, r)
		if err != nil {
			log.Fatal("ListenAndServe: ", err)
		}
	}()

	return rv
}

func (this *HttpEndpoint) SendQueriesTo(queryChannel network.QueryChannel) {
	this.queryChannel = queryChannel
}

func welcome(w http.ResponseWriter, r *http.Request) {
	mustEncode(w, map[string]interface{}{
		"tuqtng":  "where no query has relaxed before",
		"version": "tuqtng 0.0",
	})
}

func (this *HttpEndpoint) ServeHTTP(w http.ResponseWriter, r *http.Request) {

	queryString := r.FormValue("q")
	if queryString == "" && r.Method == "POST" {
		queryStringBytes, err := ioutil.ReadAll(r.Body)
		if err == nil {
			queryString = string(queryStringBytes)
		}
	}

	if queryString == "" {
		showError(w, "Missing required query string", 500)
		return
	} else {
		log.Printf("Query String: %v", queryString)
	}

	response := HttpResponse{w: w, results: make(query.ValueChannel)}
	query := network.Query{
		Request:  network.UNQLStringQueryRequest{QueryString: queryString},
		Response: &response,
	}

	this.queryChannel <- query

	first := true
	count := 0
	for val := range response.results {
		if first {
			// open up our response
			fmt.Fprint(w, "{\n")
			fmt.Fprint(w, "    \"resultset\": [\n")
			first = false
		} else {
			fmt.Fprint(w, ",\n")
		}
		body, err := json.MarshalIndent(val, "        ", "    ")
		if err != nil {
			log.Printf("Unable to format result to display %#v, %v", val, err)
		} else {
			fmt.Fprintf(w, "        %v", string(body))
		}
		count++
	}

	if !response.err {
		if count == 0 {
			fmt.Fprint(w, "{\n")
			fmt.Fprint(w, "    \"resultset\": [")
		}
		fmt.Fprint(w, "\n    ],\n")
		fmt.Fprintf(w, "    \"total_rows\": %d\n", count)
		fmt.Fprint(w, "}\n")
	}
}

func mustEncode(w io.Writer, i interface{}) {
	if headered, ok := w.(http.ResponseWriter); ok {
		headered.Header().Set("Cache-Control", "no-cache")
		headered.Header().Set("Content-type", "application/json")
	}

	e := json.NewEncoder(w)
	if err := e.Encode(i); err != nil {
		panic(err)
	}
}

func showError(w http.ResponseWriter, msg string, code int) {
	log.Printf("Reporting error %v/%v", code, msg)
	http.Error(w, msg, code)
}
<commit_msg>HTTP returns json even on error<commit_after>//  Copyright (c) 2013 Couchbase, Inc.
//  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 http

import (
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/http"

	"github.com/couchbaselabs/tuqtng/network"
	"github.com/couchbaselabs/tuqtng/query"
	"github.com/gorilla/mux"
)

type HttpResponse struct {
	w       http.ResponseWriter
	results query.ValueChannel
	err     bool
}

func (this *HttpResponse) SendError(err error) {
	this.err = true
	showError(this.w, fmt.Sprintf(`{"error":"%v"}`, err), 500)
	close(this.results)
}

func (this *HttpResponse) SendResult(val query.Value) {
	this.results <- val
}

func (this *HttpResponse) NoMoreResults() {
	close(this.results)
}

type HttpEndpoint struct {
	queryChannel network.QueryChannel
}

func NewHttpEndpoint(address string) *HttpEndpoint {
	rv := &HttpEndpoint{}

	r := mux.NewRouter()

	r.HandleFunc("/", welcome).Methods("GET")
	r.Handle("/query", rv).Methods("GET", "POST")

	go func() {
		err := http.ListenAndServe(address, r)
		if err != nil {
			log.Fatal("ListenAndServe: ", err)
		}
	}()

	return rv
}

func (this *HttpEndpoint) SendQueriesTo(queryChannel network.QueryChannel) {
	this.queryChannel = queryChannel
}

func welcome(w http.ResponseWriter, r *http.Request) {
	mustEncode(w, map[string]interface{}{
		"tuqtng":  "where no query has relaxed before",
		"version": "tuqtng 0.0",
	})
}

func (this *HttpEndpoint) ServeHTTP(w http.ResponseWriter, r *http.Request) {

	queryString := r.FormValue("q")
	if queryString == "" && r.Method == "POST" {
		queryStringBytes, err := ioutil.ReadAll(r.Body)
		if err == nil {
			queryString = string(queryStringBytes)
		}
	}

	if queryString == "" {
		showError(w, "Missing required query string", 500)
		return
	} else {
		log.Printf("Query String: %v", queryString)
	}

	response := HttpResponse{w: w, results: make(query.ValueChannel)}
	query := network.Query{
		Request:  network.UNQLStringQueryRequest{QueryString: queryString},
		Response: &response,
	}

	this.queryChannel <- query

	first := true
	count := 0
	for val := range response.results {
		if first {
			// open up our response
			fmt.Fprint(w, "{\n")
			fmt.Fprint(w, "    \"resultset\": [\n")
			first = false
		} else {
			fmt.Fprint(w, ",\n")
		}
		body, err := json.MarshalIndent(val, "        ", "    ")
		if err != nil {
			log.Printf("Unable to format result to display %#v, %v", val, err)
		} else {
			fmt.Fprintf(w, "        %v", string(body))
		}
		count++
	}

	if !response.err {
		if count == 0 {
			fmt.Fprint(w, "{\n")
			fmt.Fprint(w, "    \"resultset\": [")
		}
		fmt.Fprint(w, "\n    ],\n")
		fmt.Fprintf(w, "    \"total_rows\": %d\n", count)
		fmt.Fprint(w, "}\n")
	}
}

func mustEncode(w io.Writer, i interface{}) {
	if headered, ok := w.(http.ResponseWriter); ok {
		headered.Header().Set("Cache-Control", "no-cache")
		headered.Header().Set("Content-type", "application/json")
	}

	e := json.NewEncoder(w)
	if err := e.Encode(i); err != nil {
		panic(err)
	}
}

func showError(w http.ResponseWriter, msg string, code int) {
	log.Printf("Reporting error %v/%v", code, msg)
	http.Error(w, msg, code)
}
<|endoftext|>


<commit_before>// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package main

import (
	"context"
	"fmt"
	"io/ioutil"
	"log"
	"net"
	"os"
	"regexp"
	"strings"

	"opentelemetry-trace-codelab-go/server/shakesapp"

	"cloud.google.com/go/storage"
	cloudtrace "github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/trace"
	"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/propagation"
	sdktrace "go.opentelemetry.io/otel/sdk/trace"
	"go.opentelemetry.io/otel/trace"
	"google.golang.org/api/iterator"
	"google.golang.org/api/option"
	"google.golang.org/grpc"
	healthpb "google.golang.org/grpc/health/grpc_health_v1"
)

const (
	listenPort = "5050"

	bucketName   = "dataflow-samples"
	bucketPrefix = "shakespeare/"
)

type serverService struct {
	shakesapp.UnimplementedShakespeareServiceServer
	healthpb.UnimplementedHealthServer
}

func NewServerService() *serverService {
	return &serverService{}
}

// step2. add OpenTelemetry initialization function
func initTracer() (*sdktrace.TracerProvider, error) {
	// step3. replace stdout exporter with Cloud Trace exporter
	// cloudtrace.New() finds the credentials to Cloud Trace automatically following the
	// rules defined by golang.org/x/oauth2/google.findDefaultCredentailsWithParams.
	// https://pkg.go.dev/golang.org/x/oauth2/google#FindDefaultCredentialsWithParams
	exporter, err := cloudtrace.New()
	// step3. end replacing exporter
	if err != nil {
		return nil, err
	}
	// for the demonstration, we use AlwaysSmaple sampler to take all spans.
	// do not use this option in production.
	tp := sdktrace.NewTracerProvider(
		sdktrace.WithSampler(sdktrace.AlwaysSample()),
		sdktrace.WithBatcher(exporter),
	)
	otel.SetTracerProvider(tp)
	otel.SetTextMapPropagator(propagation.TraceContext{})
	return tp, nil
}

// step2: end OpenTelemetry initialization function

// step5: add Profiler initializer
func initProfiler() {
	cfg := profiler.Config{
		Service:              "server",
		ServiceVersion:       "1.1.0",
		NoHeapProfiling:      true,
		NoAllocProfiling:     true,
		NoGoroutineProfiling: true,
		NoCPUProfiling:       false,
	}
	if err := profiler.Start(cfg); err != nil {
		log.Fatalf("failed to launch profiler agent: %v", err)
	}
}

// step5: end Profiler initializer

// TODO: instrument the application with Cloud Profiler agent
func main() {
	port := listenPort
	if os.Getenv("PORT") != "" {
		port = os.Getenv("PORT")
	}

	lis, err := net.Listen("tcp", fmt.Sprintf(":%s", port))
	if err != nil {
		log.Fatalf("error %v; error listening port %v", err, port)
	}

	// step2. setup OpenTelemetry
	tp, err := initTracer()
	if err != nil {
		log.Fatalf("failed to initialize TracerProvider: %v", err)
	}
	defer func() {
		if err := tp.Shutdown(context.Background()); err != nil {
			log.Fatalf("error shutting down TracerProvider: %v", err)
		}
	}()
	// step2. end setup

	// step5. start profiler
	go initProfiler()
	// step5. end

	svc := NewServerService()
	// step2: add interceptor
	interceptorOpt := otelgrpc.WithTracerProvider(otel.GetTracerProvider())
	srv := grpc.NewServer(
		grpc.UnaryInterceptor(otelgrpc.UnaryServerInterceptor(interceptorOpt)),
		grpc.StreamInterceptor(otelgrpc.StreamServerInterceptor(interceptorOpt)),
	)
	// step2: end adding interceptor
	shakesapp.RegisterShakespeareServiceServer(srv, svc)
	healthpb.RegisterHealthServer(srv, svc)
	if err := srv.Serve(lis); err != nil {
		log.Fatalf("error serving server: %v", err)
	}
}

// GetMatchCount implements a server for ShakespeareService.
//
// TODO: instrument the application to take the latency of the request to Cloud Storage
func (s *serverService) GetMatchCount(ctx context.Context, req *shakesapp.ShakespeareRequest) (*shakesapp.ShakespeareResponse, error) {
	resp := &shakesapp.ShakespeareResponse{}
	texts, err := readFiles(ctx, bucketName, bucketPrefix)
	if err != nil {
		return resp, fmt.Errorf("fails to read files: %s", err)
	}
	for _, text := range texts {
		for _, line := range strings.Split(text, "\n") {
			line, query := strings.ToLower(line), strings.ToLower(req.Query)
			// TODO: Compiling and matching a regular expression on every request
			// might be too expensive? Consider optimizing.
			isMatch, err := regexp.MatchString(query, line)
			if err != nil {
				return resp, err
			}
			if isMatch {
				resp.MatchCount++
			}
		}
	}
	return resp, nil
}

// readFiles reads the content of files within the specified bucket with the
// specified prefix path in parallel and returns their content. It fails if
// operations to find or read any of the files fails.
func readFiles(ctx context.Context, bucketName, prefix string) ([]string, error) {
	type resp struct {
		s   string
		err error
	}

	// step4: add an extra span
	span := trace.SpanFromContext(ctx)
	span.SetName("server.readFiles")
	span.SetAttributes(attribute.Key("bucketname").String(bucketName))
	defer span.End()
	// step4: end add span

	client, err := storage.NewClient(ctx, option.WithoutAuthentication())
	if err != nil {
		return []string{}, fmt.Errorf("failed to create storage client: %s", err)
	}
	defer client.Close()

	bucket := client.Bucket(bucketName)

	var paths []string
	it := bucket.Objects(ctx, &storage.Query{Prefix: bucketPrefix})
	for {
		attrs, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return []string{}, fmt.Errorf("failed to iterate over files in %s starting with %s: %v", bucketName, prefix, err)
		}
		if attrs.Name != "" {
			paths = append(paths, attrs.Name)
		}
	}

	resps := make(chan resp)
	for _, path := range paths {
		go func(path string) {
			obj := bucket.Object(path)
			r, err := obj.NewReader(ctx)
			if err != nil {
				resps <- resp{"", err}
			}
			defer r.Close()
			data, err := ioutil.ReadAll(r)
			resps <- resp{string(data), err}
		}(path)
	}
	ret := make([]string, len(paths))
	for i := 0; i < len(paths); i++ {
		r := <-resps
		if r.err != nil {
			err = r.err
		}
		ret[i] = r.s
	}
	return ret, err
}

// Check is for health checking.
func (s *serverService) Check(ctx context.Context, req *healthpb.HealthCheckRequest) (*healthpb.HealthCheckResponse, error) {
	return &healthpb.HealthCheckResponse{Status: healthpb.HealthCheckResponse_SERVING}, nil
}

// Watch is for health checking.
func (s *serverService) Watch(req *healthpb.HealthCheckRequest, server healthpb.Health_WatchServer) error {
	return nil
}
<commit_msg>fix(step5): go.mod for Cloud Profiler<commit_after>// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package main

import (
	"context"
	"fmt"
	"io/ioutil"
	"log"
	"net"
	"os"
	"regexp"
	"strings"

	"opentelemetry-trace-codelab-go/server/shakesapp"

	"cloud.google.com/go/profiler"
	"cloud.google.com/go/storage"
	cloudtrace "github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/trace"
	"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/attribute"
	"go.opentelemetry.io/otel/propagation"
	sdktrace "go.opentelemetry.io/otel/sdk/trace"
	"go.opentelemetry.io/otel/trace"
	"google.golang.org/api/iterator"
	"google.golang.org/api/option"
	"google.golang.org/grpc"
	healthpb "google.golang.org/grpc/health/grpc_health_v1"
)

const (
	listenPort = "5050"

	bucketName   = "dataflow-samples"
	bucketPrefix = "shakespeare/"
)

type serverService struct {
	shakesapp.UnimplementedShakespeareServiceServer
	healthpb.UnimplementedHealthServer
}

func NewServerService() *serverService {
	return &serverService{}
}

// step2. add OpenTelemetry initialization function
func initTracer() (*sdktrace.TracerProvider, error) {
	// step3. replace stdout exporter with Cloud Trace exporter
	// cloudtrace.New() finds the credentials to Cloud Trace automatically following the
	// rules defined by golang.org/x/oauth2/google.findDefaultCredentailsWithParams.
	// https://pkg.go.dev/golang.org/x/oauth2/google#FindDefaultCredentialsWithParams
	exporter, err := cloudtrace.New()
	// step3. end replacing exporter
	if err != nil {
		return nil, err
	}
	// for the demonstration, we use AlwaysSmaple sampler to take all spans.
	// do not use this option in production.
	tp := sdktrace.NewTracerProvider(
		sdktrace.WithSampler(sdktrace.AlwaysSample()),
		sdktrace.WithBatcher(exporter),
	)
	otel.SetTracerProvider(tp)
	otel.SetTextMapPropagator(propagation.TraceContext{})
	return tp, nil
}

// step2: end OpenTelemetry initialization function

// step5: add Profiler initializer
func initProfiler() {
	cfg := profiler.Config{
		Service:              "server",
		ServiceVersion:       "1.1.0",
		NoHeapProfiling:      true,
		NoAllocProfiling:     true,
		NoGoroutineProfiling: true,
		NoCPUProfiling:       false,
	}
	if err := profiler.Start(cfg); err != nil {
		log.Fatalf("failed to launch profiler agent: %v", err)
	}
}

// step5: end Profiler initializer

// TODO: instrument the application with Cloud Profiler agent
func main() {
	port := listenPort
	if os.Getenv("PORT") != "" {
		port = os.Getenv("PORT")
	}

	lis, err := net.Listen("tcp", fmt.Sprintf(":%s", port))
	if err != nil {
		log.Fatalf("error %v; error listening port %v", err, port)
	}

	// step2. setup OpenTelemetry
	tp, err := initTracer()
	if err != nil {
		log.Fatalf("failed to initialize TracerProvider: %v", err)
	}
	defer func() {
		if err := tp.Shutdown(context.Background()); err != nil {
			log.Fatalf("error shutting down TracerProvider: %v", err)
		}
	}()
	// step2. end setup

	// step5. start profiler
	go initProfiler()
	// step5. end

	svc := NewServerService()
	// step2: add interceptor
	interceptorOpt := otelgrpc.WithTracerProvider(otel.GetTracerProvider())
	srv := grpc.NewServer(
		grpc.UnaryInterceptor(otelgrpc.UnaryServerInterceptor(interceptorOpt)),
		grpc.StreamInterceptor(otelgrpc.StreamServerInterceptor(interceptorOpt)),
	)
	// step2: end adding interceptor
	shakesapp.RegisterShakespeareServiceServer(srv, svc)
	healthpb.RegisterHealthServer(srv, svc)
	if err := srv.Serve(lis); err != nil {
		log.Fatalf("error serving server: %v", err)
	}
}

// GetMatchCount implements a server for ShakespeareService.
//
// TODO: instrument the application to take the latency of the request to Cloud Storage
func (s *serverService) GetMatchCount(ctx context.Context, req *shakesapp.ShakespeareRequest) (*shakesapp.ShakespeareResponse, error) {
	resp := &shakesapp.ShakespeareResponse{}
	texts, err := readFiles(ctx, bucketName, bucketPrefix)
	if err != nil {
		return resp, fmt.Errorf("fails to read files: %s", err)
	}
	for _, text := range texts {
		for _, line := range strings.Split(text, "\n") {
			line, query := strings.ToLower(line), strings.ToLower(req.Query)
			// TODO: Compiling and matching a regular expression on every request
			// might be too expensive? Consider optimizing.
			isMatch, err := regexp.MatchString(query, line)
			if err != nil {
				return resp, err
			}
			if isMatch {
				resp.MatchCount++
			}
		}
	}
	return resp, nil
}

// readFiles reads the content of files within the specified bucket with the
// specified prefix path in parallel and returns their content. It fails if
// operations to find or read any of the files fails.
func readFiles(ctx context.Context, bucketName, prefix string) ([]string, error) {
	type resp struct {
		s   string
		err error
	}

	// step4: add an extra span
	span := trace.SpanFromContext(ctx)
	span.SetName("server.readFiles")
	span.SetAttributes(attribute.Key("bucketname").String(bucketName))
	defer span.End()
	// step4: end add span

	client, err := storage.NewClient(ctx, option.WithoutAuthentication())
	if err != nil {
		return []string{}, fmt.Errorf("failed to create storage client: %s", err)
	}
	defer client.Close()

	bucket := client.Bucket(bucketName)

	var paths []string
	it := bucket.Objects(ctx, &storage.Query{Prefix: bucketPrefix})
	for {
		attrs, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return []string{}, fmt.Errorf("failed to iterate over files in %s starting with %s: %v", bucketName, prefix, err)
		}
		if attrs.Name != "" {
			paths = append(paths, attrs.Name)
		}
	}

	resps := make(chan resp)
	for _, path := range paths {
		go func(path string) {
			obj := bucket.Object(path)
			r, err := obj.NewReader(ctx)
			if err != nil {
				resps <- resp{"", err}
			}
			defer r.Close()
			data, err := ioutil.ReadAll(r)
			resps <- resp{string(data), err}
		}(path)
	}
	ret := make([]string, len(paths))
	for i := 0; i < len(paths); i++ {
		r := <-resps
		if r.err != nil {
			err = r.err
		}
		ret[i] = r.s
	}
	return ret, err
}

// Check is for health checking.
func (s *serverService) Check(ctx context.Context, req *healthpb.HealthCheckRequest) (*healthpb.HealthCheckResponse, error) {
	return &healthpb.HealthCheckResponse{Status: healthpb.HealthCheckResponse_SERVING}, nil
}

// Watch is for health checking.
func (s *serverService) Watch(req *healthpb.HealthCheckRequest, server healthpb.Health_WatchServer) error {
	return nil
}
<|endoftext|>


<commit_before>// Copyright 2015 Keybase, Inc. All rights reserved. Use of
// this source code is governed by the included BSD license.

package libkb

import (
	"testing"

	keybase1 "github.com/keybase/client/go/protocol/keybase1"
)

func TestLoadUserPlusKeys(t *testing.T) {
	tc := SetupTest(t, "user plus keys", 1)
	defer tc.Cleanup()

	// this is kind of pointless as there is no cache anymore
	for i := 0; i < 10; i++ {
		u, err := LoadUserPlusKeys(tc.G, "295a7eea607af32040647123732bc819")
		if err != nil {
			t.Fatal(err)
		}
		if u.Username != "t_alice" {
			t.Errorf("username: %s, expected t_alice", u.Username)
		}
		if len(u.RevokedDeviceKeys) > 0 {
			t.Errorf("t_alice found with %d revoked keys, expected 0", len(u.RevokedDeviceKeys))
		}
	}

	for _, uid := range []keybase1.UID{"295a7eea607af32040647123732bc819", "afb5eda3154bc13c1df0189ce93ba119", "9d56bd0c02ac2711e142faf484ea9519", "c4c565570e7e87cafd077509abf5f619", "561247eb1cc3b0f5dc9d9bf299da5e19"} {
		_, err := LoadUserPlusKeys(tc.G, uid)
		if err != nil {
			t.Fatal(err)
		}
	}
}

func TestRevokedKeys(t *testing.T) {
	tc := SetupTest(t, "revoked keys", 1)
	defer tc.Cleanup()

	u, err := LoadUserPlusKeys(tc.G, "ff261e3b26543a24ba6c0693820ead19")
	if err != nil {
		t.Fatal(err)
	}
	if u.Username != "t_mike" {
		t.Errorf("username: %s, expected t_mike", u.Username)
	}
	if len(u.RevokedDeviceKeys) != 2 {
		t.Errorf("t_mike found with %d revoked keys, expected 2", len(u.RevokedDeviceKeys))
	}

	kid := keybase1.KID("012073f26b5996912393f7d2961ca90968e4e83d6140e9771ba890ff8ba6ea97777e0a")
	for index, k := range u.RevokedDeviceKeys {
		if k.By != kid {
			t.Errorf("wrong revoking KID (index: %d) %s != %s", index, k.By, kid)
		}
	}
}

func BenchmarkLoadSigChains(b *testing.B) {
	tc := SetupTest(b, "benchmark load user", 1)
	u, err := LoadUser(NewLoadUserByNameArg(tc.G, "t_george"))
	if err != nil {
		b.Fatal(err)
	}
	if u == nil {
		b.Fatal("no user")
	}
	u.sigChainMem = nil
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		if err = u.LoadSigChains(true, &u.leaf, false); err != nil {
			b.Fatal(err)
		}
		u.sigChainMem = nil
	}
}

func BenchmarkLoadUserPlusKeys(b *testing.B) {
	tc := SetupTest(b, "bench_user_plus_keys", 1)
	u, err := LoadUser(NewLoadUserByNameArg(tc.G, "t_george"))
	if err != nil {
		b.Fatal(err)
	}
	if u == nil {
		b.Fatal("no user")
	}
	uid := u.GetUID()

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		_, err := LoadUserPlusKeys(tc.G, uid)
		if err != nil {
			b.Fatal(err)
		}
	}
}
<commit_msg>Add test for LoadUserPlusKeys on user w/ no keys<commit_after>// Copyright 2015 Keybase, Inc. All rights reserved. Use of
// this source code is governed by the included BSD license.

package libkb

import (
	"testing"

	keybase1 "github.com/keybase/client/go/protocol/keybase1"
)

func TestLoadUserPlusKeys(t *testing.T) {
	tc := SetupTest(t, "user plus keys", 1)
	defer tc.Cleanup()

	// this is kind of pointless as there is no cache anymore
	for i := 0; i < 10; i++ {
		u, err := LoadUserPlusKeys(tc.G, "295a7eea607af32040647123732bc819")
		if err != nil {
			t.Fatal(err)
		}
		if u.Username != "t_alice" {
			t.Errorf("username: %s, expected t_alice", u.Username)
		}
		if len(u.RevokedDeviceKeys) > 0 {
			t.Errorf("t_alice found with %d revoked keys, expected 0", len(u.RevokedDeviceKeys))
		}
	}

	for _, uid := range []keybase1.UID{"295a7eea607af32040647123732bc819", "afb5eda3154bc13c1df0189ce93ba119", "9d56bd0c02ac2711e142faf484ea9519", "c4c565570e7e87cafd077509abf5f619", "561247eb1cc3b0f5dc9d9bf299da5e19"} {
		_, err := LoadUserPlusKeys(tc.G, uid)
		if err != nil {
			t.Fatal(err)
		}
	}
}

func TestLoadUserPlusKeysNoKeys(t *testing.T) {
	tc := SetupTest(t, "user plus keys", 1)
	defer tc.Cleanup()

	// t_ellen has no keys.  There should be no error loading her.
	u, err := LoadUserPlusKeys(tc.G, "561247eb1cc3b0f5dc9d9bf299da5e19")
	if err != nil {
		t.Fatal(err)
	}
	if u.Username != "t_ellen" {
		t.Errorf("username: %s, expected t_ellen", u.Username)
	}
}

func TestRevokedKeys(t *testing.T) {
	tc := SetupTest(t, "revoked keys", 1)
	defer tc.Cleanup()

	u, err := LoadUserPlusKeys(tc.G, "ff261e3b26543a24ba6c0693820ead19")
	if err != nil {
		t.Fatal(err)
	}
	if u.Username != "t_mike" {
		t.Errorf("username: %s, expected t_mike", u.Username)
	}
	if len(u.RevokedDeviceKeys) != 2 {
		t.Errorf("t_mike found with %d revoked keys, expected 2", len(u.RevokedDeviceKeys))
	}

	kid := keybase1.KID("012073f26b5996912393f7d2961ca90968e4e83d6140e9771ba890ff8ba6ea97777e0a")
	for index, k := range u.RevokedDeviceKeys {
		if k.By != kid {
			t.Errorf("wrong revoking KID (index: %d) %s != %s", index, k.By, kid)
		}
	}
}

func BenchmarkLoadSigChains(b *testing.B) {
	tc := SetupTest(b, "benchmark load user", 1)
	u, err := LoadUser(NewLoadUserByNameArg(tc.G, "t_george"))
	if err != nil {
		b.Fatal(err)
	}
	if u == nil {
		b.Fatal("no user")
	}
	u.sigChainMem = nil
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		if err = u.LoadSigChains(true, &u.leaf, false); err != nil {
			b.Fatal(err)
		}
		u.sigChainMem = nil
	}
}

func BenchmarkLoadUserPlusKeys(b *testing.B) {
	tc := SetupTest(b, "bench_user_plus_keys", 1)
	u, err := LoadUser(NewLoadUserByNameArg(tc.G, "t_george"))
	if err != nil {
		b.Fatal(err)
	}
	if u == nil {
		b.Fatal("no user")
	}
	uid := u.GetUID()

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		_, err := LoadUserPlusKeys(tc.G, uid)
		if err != nil {
			b.Fatal(err)
		}
	}
}
<|endoftext|>


<commit_before>package gqldecode

import (
	"testing"

	"github.com/sprucehealth/backend/libs/test"
)

func TestIsValidPlane0Unicode(t *testing.T) {
	test.Equals(t, true, IsValidPlane0Unicode(`This is a välid string`))
	test.Equals(t, false, IsValidPlane0Unicode(`This is not 😡`))
}
<commit_msg>remove test dependency on private repository<commit_after>package gqldecode

import (
	"testing"
)

func TestIsValidPlane0Unicode(t *testing.T) {
	if !IsValidPlane0Unicode(`This is a välid string`) {
		t.Fail()
	}
	if IsValidPlane0Unicode(`This is not 😡`) {
		t.Fail()
	}
}
<|endoftext|>


<commit_before>package objects

import "github.com/jinzhu/gorm"

type MediaInfo struct {
	Type             string `json:"type"`
	Title            string `json:"title"`
	Container        string `json:"container"`
	Year             int    `json:"year"`
	ReleaseGroup     string `json:"release_group"`
	Format           string `json:"format"`
	ScreenSize       string `json:"screen_size"`
	AudioChannels    string `json:"audio_channels"`
	AudioCodecs      string `json:"audio_codecs"`
	Language         string `json:"language"`
	SubtitleLanguage string `json:"subtitle_language"`
	Size             string `json:"size"`
}

type EpisodeTorrentInfo struct {
	Type           string `json:"type"`
	Title          string `json:"title"`
	Year           int    `json:"year"`
	Season         int    `json:"season"`
	Episode        int    `json:"episode"`
	EpisodeCount   int    `json:"episode_count"`
	EpisodeDetails string `json:"episode_details"`
	EpisodeFormat  string `json:"episode_format"`
	Part           int    `json:"part"`
	Version        string `json:"version"`
}

type MediaIds struct {
	gorm.Model
	Name  string
	Trakt int
	Tmdb  int
	Imdb  string
	Tvdb  int
}
<commit_msg>Removed unused fields in guessit mediainfo structs<commit_after>package objects

import "github.com/jinzhu/gorm"

type MediaInfo struct {
	Type       string `json:"type"`
	Title      string `json:"title"`
	Container  string `json:"container"`
	Year       int    `json:"year"`
	ScreenSize string `json:"screen_size"`
	Size       string `json:"size"`
}

type EpisodeTorrentInfo struct {
	Type           string `json:"type"`
	Title          string `json:"title"`
	Year           int    `json:"year"`
	Season         int    `json:"season"`
	Episode        int    `json:"episode"`
	EpisodeCount   int    `json:"episode_count"`
	EpisodeDetails string `json:"episode_details"`
	EpisodeFormat  string `json:"episode_format"`
	Part           int    `json:"part"`
	Version        string `json:"version"`
}

type MediaIds struct {
	gorm.Model
	Name  string
	Trakt int
	Tmdb  int
	Imdb  string
	Tvdb  int
}
<|endoftext|>


<commit_before>package iptables

import (
	"errors"
	"fmt"
	"net"
	"os"
	"os/exec"
	"strconv"
	"strings"
)

type Action string

const (
	Add    Action = "-A"
	Delete Action = "-D"
)

var (
	ErrIptablesNotFound = errors.New("Iptables not found")
	nat                 = []string{"-t", "nat"}
	supportsXlock       = false
)

type Chain struct {
	Name   string
	Bridge string
}

func init() {
	supportsXlock = exec.Command("iptables", "--wait", "-L", "-n").Run() == nil
}

func NewChain(name, bridge string) (*Chain, error) {
	if output, err := Raw("-t", "nat", "-N", name); err != nil {
		return nil, err
	} else if len(output) != 0 {
		return nil, fmt.Errorf("Error creating new iptables chain: %s", output)
	}
	chain := &Chain{
		Name:   name,
		Bridge: bridge,
	}

	if err := chain.Prerouting(Add, "-m", "addrtype", "--dst-type", "LOCAL"); err != nil {
		return nil, fmt.Errorf("Failed to inject docker in PREROUTING chain: %s", err)
	}
	if err := chain.Output(Add, "-m", "addrtype", "--dst-type", "LOCAL", "!", "--dst", "127.0.0.0/8"); err != nil {
		return nil, fmt.Errorf("Failed to inject docker in OUTPUT chain: %s", err)
	}
	return chain, nil
}

func RemoveExistingChain(name string) error {
	chain := &Chain{
		Name: name,
	}
	return chain.Remove()
}

func (c *Chain) Forward(action Action, ip net.IP, port int, proto, dest_addr string, dest_port int) error {
	daddr := ip.String()
	if ip.IsUnspecified() {
		// iptables interprets "0.0.0.0" as "0.0.0.0/32", whereas we
		// want "0.0.0.0/0". "0/0" is correctly interpreted as "any
		// value" by both iptables and ip6tables.
		daddr = "0/0"
	}
	if output, err := Raw("-t", "nat", fmt.Sprint(action), c.Name,
		"-p", proto,
		"-d", daddr,
		"--dport", strconv.Itoa(port),
		"!", "-i", c.Bridge,
		"-j", "DNAT",
		"--to-destination", net.JoinHostPort(dest_addr, strconv.Itoa(dest_port))); err != nil {
		return err
	} else if len(output) != 0 {
		return fmt.Errorf("Error iptables forward: %s", output)
	}

	fAction := action
	if fAction == Add {
		fAction = "-I"
	}
	if output, err := Raw(string(fAction), "FORWARD",
		"!", "-i", c.Bridge,
		"-o", c.Bridge,
		"-p", proto,
		"-d", dest_addr,
		"--dport", strconv.Itoa(dest_port),
		"-j", "ACCEPT"); err != nil {
		return err
	} else if len(output) != 0 {
		return fmt.Errorf("Error iptables forward: %s", output)
	}

	return nil
}

func (c *Chain) Prerouting(action Action, args ...string) error {
	a := append(nat, fmt.Sprint(action), "PREROUTING")
	if len(args) > 0 {
		a = append(a, args...)
	}
	if output, err := Raw(append(a, "-j", c.Name)...); err != nil {
		return err
	} else if len(output) != 0 {
		return fmt.Errorf("Error iptables prerouting: %s", output)
	}
	return nil
}

func (c *Chain) Output(action Action, args ...string) error {
	a := append(nat, fmt.Sprint(action), "OUTPUT")
	if len(args) > 0 {
		a = append(a, args...)
	}
	if output, err := Raw(append(a, "-j", c.Name)...); err != nil {
		return err
	} else if len(output) != 0 {
		return fmt.Errorf("Error iptables output: %s", output)
	}
	return nil
}

func (c *Chain) Remove() error {
	// Ignore errors - This could mean the chains were never set up
	c.Prerouting(Delete, "-m", "addrtype", "--dst-type", "LOCAL")
	c.Output(Delete, "-m", "addrtype", "--dst-type", "LOCAL", "!", "--dst", "127.0.0.0/8")
	c.Output(Delete, "-m", "addrtype", "--dst-type", "LOCAL") // Created in versions <= 0.1.6

	c.Prerouting(Delete)
	c.Output(Delete)

	Raw("-t", "nat", "-F", c.Name)
	Raw("-t", "nat", "-X", c.Name)

	return nil
}

// Check if an existing rule exists
func Exists(args ...string) bool {
	if _, err := Raw(append([]string{"-C"}, args...)...); err != nil {
		return false
	}
	return true
}

func Raw(args ...string) ([]byte, error) {
	path, err := exec.LookPath("iptables")
	if err != nil {
		return nil, ErrIptablesNotFound
	}

	if supportsXlock {
		args = append([]string{"--wait"}, args...)
	}

	if os.Getenv("DEBUG") != "" {
		fmt.Fprintf(os.Stderr, fmt.Sprintf("[debug] %s, %v\n", path, args))
	}

	output, err := exec.Command(path, args...).CombinedOutput()
	if err != nil {
		return nil, fmt.Errorf("iptables failed: iptables %v: %s (%s)", strings.Join(args, " "), output, err)
	}

	// ignore iptables' message about xtables lock
	if strings.Contains(string(output), "waiting for it to exit") {
		output = []byte("")
	}

	return output, err
}
<commit_msg>Support hairpin NAT<commit_after>package iptables

import (
	"errors"
	"fmt"
	"net"
	"os"
	"os/exec"
	"strconv"
	"strings"
)

type Action string

const (
	Add    Action = "-A"
	Delete Action = "-D"
)

var (
	ErrIptablesNotFound = errors.New("Iptables not found")
	nat                 = []string{"-t", "nat"}
	supportsXlock       = false
)

type Chain struct {
	Name   string
	Bridge string
}

func init() {
	supportsXlock = exec.Command("iptables", "--wait", "-L", "-n").Run() == nil
}

func NewChain(name, bridge string) (*Chain, error) {
	if output, err := Raw("-t", "nat", "-N", name); err != nil {
		return nil, err
	} else if len(output) != 0 {
		return nil, fmt.Errorf("Error creating new iptables chain: %s", output)
	}
	chain := &Chain{
		Name:   name,
		Bridge: bridge,
	}

	if err := chain.Prerouting(Add, "-m", "addrtype", "--dst-type", "LOCAL"); err != nil {
		return nil, fmt.Errorf("Failed to inject docker in PREROUTING chain: %s", err)
	}
	if err := chain.Output(Add, "-m", "addrtype", "--dst-type", "LOCAL", "!", "--dst", "127.0.0.0/8"); err != nil {
		return nil, fmt.Errorf("Failed to inject docker in OUTPUT chain: %s", err)
	}
	return chain, nil
}

func RemoveExistingChain(name string) error {
	chain := &Chain{
		Name: name,
	}
	return chain.Remove()
}

func (c *Chain) Forward(action Action, ip net.IP, port int, proto, dest_addr string, dest_port int) error {
	daddr := ip.String()
	if ip.IsUnspecified() {
		// iptables interprets "0.0.0.0" as "0.0.0.0/32", whereas we
		// want "0.0.0.0/0". "0/0" is correctly interpreted as "any
		// value" by both iptables and ip6tables.
		daddr = "0/0"
	}
	if output, err := Raw("-t", "nat", fmt.Sprint(action), c.Name,
		"-p", proto,
		"-d", daddr,
		"--dport", strconv.Itoa(port),
		"-j", "DNAT",
		"--to-destination", net.JoinHostPort(dest_addr, strconv.Itoa(dest_port))); err != nil {
		return err
	} else if len(output) != 0 {
		return fmt.Errorf("Error iptables forward: %s", output)
	}

	fAction := action
	if fAction == Add {
		fAction = "-I"
	}
	if output, err := Raw(string(fAction), "FORWARD",
		"!", "-i", c.Bridge,
		"-o", c.Bridge,
		"-p", proto,
		"-d", dest_addr,
		"--dport", strconv.Itoa(dest_port),
		"-j", "ACCEPT"); err != nil {
		return err
	} else if len(output) != 0 {
		return fmt.Errorf("Error iptables forward: %s", output)
	}

	if output, err := Raw("-t", "nat", string(fAction), "POSTROUTING",
		"-p", proto,
		"-s", dest_addr,
		"-d", dest_addr,
		"--dport", strconv.Itoa(dest_port),
		"-j", "MASQUERADE"); err != nil {
		return err
	} else if len(output) != 0 {
		return fmt.Errorf("Error iptables forward: %s", output)
	}

	return nil
}

func (c *Chain) Prerouting(action Action, args ...string) error {
	a := append(nat, fmt.Sprint(action), "PREROUTING")
	if len(args) > 0 {
		a = append(a, args...)
	}
	if output, err := Raw(append(a, "-j", c.Name)...); err != nil {
		return err
	} else if len(output) != 0 {
		return fmt.Errorf("Error iptables prerouting: %s", output)
	}
	return nil
}

func (c *Chain) Output(action Action, args ...string) error {
	a := append(nat, fmt.Sprint(action), "OUTPUT")
	if len(args) > 0 {
		a = append(a, args...)
	}
	if output, err := Raw(append(a, "-j", c.Name)...); err != nil {
		return err
	} else if len(output) != 0 {
		return fmt.Errorf("Error iptables output: %s", output)
	}
	return nil
}

func (c *Chain) Remove() error {
	// Ignore errors - This could mean the chains were never set up
	c.Prerouting(Delete, "-m", "addrtype", "--dst-type", "LOCAL")
	c.Output(Delete, "-m", "addrtype", "--dst-type", "LOCAL", "!", "--dst", "127.0.0.0/8")
	c.Output(Delete, "-m", "addrtype", "--dst-type", "LOCAL") // Created in versions <= 0.1.6

	c.Prerouting(Delete)
	c.Output(Delete)

	Raw("-t", "nat", "-F", c.Name)
	Raw("-t", "nat", "-X", c.Name)

	return nil
}

// Check if an existing rule exists
func Exists(args ...string) bool {
	if _, err := Raw(append([]string{"-C"}, args...)...); err != nil {
		return false
	}
	return true
}

func Raw(args ...string) ([]byte, error) {
	path, err := exec.LookPath("iptables")
	if err != nil {
		return nil, ErrIptablesNotFound
	}

	if supportsXlock {
		args = append([]string{"--wait"}, args...)
	}

	if os.Getenv("DEBUG") != "" {
		fmt.Fprintf(os.Stderr, fmt.Sprintf("[debug] %s, %v\n", path, args))
	}

	output, err := exec.Command(path, args...).CombinedOutput()
	if err != nil {
		return nil, fmt.Errorf("iptables failed: iptables %v: %s (%s)", strings.Join(args, " "), output, err)
	}

	// ignore iptables' message about xtables lock
	if strings.Contains(string(output), "waiting for it to exit") {
		output = []byte("")
	}

	return output, err
}
<|endoftext|>


<commit_before>package rdb

// #include <stdlib.h>
// #include "rocksdb/c.h"
import "C"
import (
	"bytes"
	"errors"
	"unsafe"
)

// Iterator provides a way to seek to specific keys and iterate through
// the keyspace from that point, as well as access the values of those keys.
//
// For example:
//
//      it := db.NewIterator(readOpts)
//      defer it.Close()
//
//      it.Seek([]byte("foo"))
//		for ; it.Valid(); it.Next() {
//          fmt.Printf("Key: %v Value: %v\n", it.Key().Data(), it.Value().Data())
// 		}
//
//      if err := it.Err(); err != nil {
//          return err
//      }
//
type Iterator struct {
	c *C.rocksdb_iterator_t
}

// NewNativeIterator creates a Iterator object.
func NewNativeIterator(c unsafe.Pointer) *Iterator {
	return &Iterator{(*C.rocksdb_iterator_t)(c)}
}

// Valid returns false only when an Iterator has iterated past either the
// first or the last key in the database.
func (iter *Iterator) Valid() bool {
	return C.rocksdb_iter_valid(iter.c) != 0
}

// ValidForPrefix returns false only when an Iterator has iterated past the
// first or the last key in the database or the specified prefix.
func (iter *Iterator) ValidForPrefix(prefix []byte) bool {
	return C.rocksdb_iter_valid(iter.c) != 0 && bytes.HasPrefix(iter.Key().Data(), prefix)
}

// Key returns the key the iterator currently holds.
func (iter *Iterator) Key() *Slice {
	var cLen C.size_t
	cKey := C.rocksdb_iter_key(iter.c, &cLen)
	if cKey == nil {
		return nil
	}
	return &Slice{cKey, cLen, true}
}

// Value returns the value in the database the iterator currently holds.
func (iter *Iterator) Value() *Slice {
	var cLen C.size_t
	cVal := C.rocksdb_iter_value(iter.c, &cLen)
	if cVal == nil {
		return nil
	}
	return &Slice{cVal, cLen, true}
}

// Next moves the iterator to the next sequential key in the database.
func (iter *Iterator) Next() {
	C.rocksdb_iter_next(iter.c)
}

// Prev moves the iterator to the previous sequential key in the database.
func (iter *Iterator) Prev() {
	C.rocksdb_iter_prev(iter.c)
}

// SeekToFirst moves the iterator to the first key in the database.
func (iter *Iterator) SeekToFirst() {
	C.rocksdb_iter_seek_to_first(iter.c)
}

// SeekToLast moves the iterator to the last key in the database.
func (iter *Iterator) SeekToLast() {
	C.rocksdb_iter_seek_to_last(iter.c)
}

// Seek moves the iterator to the position greater than or equal to the key.
func (iter *Iterator) Seek(key []byte) {
	cKey := byteToChar(key)
	C.rocksdb_iter_seek(iter.c, cKey, C.size_t(len(key)))
}

// Err returns nil if no errors happened during iteration, or the actual
// error otherwise.
func (iter *Iterator) Err() error {
	var cErr *C.char
	C.rocksdb_iter_get_error(iter.c, &cErr)
	if cErr != nil {
		defer C.rocksdb_free(unsafe.Pointer(cErr))
		return errors.New(C.GoString(cErr))
	}
	return nil
}

// Close closes the iterator.
func (iter *Iterator) Close() {
	C.rocksdb_iter_destroy(iter.c)
	iter.c = nil
}
<commit_msg>update<commit_after>package rdb

// #include <stdlib.h>
// #include "rocksdb/c.h"
import "C"
import (
	"bytes"
	"errors"
	"unsafe"
)

// Iterator provides a way to seek to specific keys and iterate through
// the keyspace from that point, as well as access the values of those keys.
//
// For example:
//
//      it := db.NewIterator(readOpts)
//      defer it.Close()
//
//      it.Seek([]byte("foo"))
//		for ; it.Valid(); it.Next() {
//          fmt.Printf("Key: %v Value: %v\n", it.Key().Data(), it.Value().Data())
// 		}
//
//      if err := it.Err(); err != nil {
//          return err
//      }
//
type Iterator struct {
	c *C.rocksdb_iterator_t
}

// NewNativeIterator creates a Iterator object.
func NewNativeIterator(c unsafe.Pointer) *Iterator {
	return &Iterator{(*C.rocksdb_iterator_t)(c)}
}

// Valid returns false only when an Iterator has iterated past either the
// first or the last key in the database.
func (iter *Iterator) Valid() bool {
	return C.rocksdb_iter_valid(iter.c) != 0
}

// ValidForPrefix returns false only when an Iterator has iterated past the
// first or the last key in the database or the specified prefix.
func (iter *Iterator) ValidForPrefix(prefix []byte) bool {
	return C.rocksdb_iter_valid(iter.c) != 0 && bytes.HasPrefix(iter.Key().Data(), prefix)
}

// Consider changing as here
// https://github.com/siddontang/ledisdb/blob/master/store/rocksdb/iterator.go#L20:L38
//
// Key returns the key the iterator currently holds.
func (iter *Iterator) Key() *Slice {
	var cLen C.size_t
	cKey := C.rocksdb_iter_key(iter.c, &cLen)
	if cKey == nil {
		return nil
	}
	return &Slice{cKey, cLen, true}
}

// Value returns the value in the database the iterator currently holds.
func (iter *Iterator) Value() *Slice {
	var cLen C.size_t
	cVal := C.rocksdb_iter_value(iter.c, &cLen)
	if cVal == nil {
		return nil
	}
	return &Slice{cVal, cLen, true}
}

// Next moves the iterator to the next sequential key in the database.
func (iter *Iterator) Next() {
	C.rocksdb_iter_next(iter.c)
}

// Prev moves the iterator to the previous sequential key in the database.
func (iter *Iterator) Prev() {
	C.rocksdb_iter_prev(iter.c)
}

// SeekToFirst moves the iterator to the first key in the database.
func (iter *Iterator) SeekToFirst() {
	C.rocksdb_iter_seek_to_first(iter.c)
}

// SeekToLast moves the iterator to the last key in the database.
func (iter *Iterator) SeekToLast() {
	C.rocksdb_iter_seek_to_last(iter.c)
}

// Seek moves the iterator to the position greater than or equal to the key.
func (iter *Iterator) Seek(key []byte) {
	cKey := byteToChar(key)
	C.rocksdb_iter_seek(iter.c, cKey, C.size_t(len(key)))
}

// Err returns nil if no errors happened during iteration, or the actual
// error otherwise.
func (iter *Iterator) Err() error {
	var cErr *C.char
	C.rocksdb_iter_get_error(iter.c, &cErr)
	if cErr != nil {
		defer C.rocksdb_free(unsafe.Pointer(cErr))
		return errors.New(C.GoString(cErr))
	}
	return nil
}

// Close closes the iterator.
func (iter *Iterator) Close() {
	C.rocksdb_iter_destroy(iter.c)
	iter.c = nil
}
<|endoftext|>


<commit_before>package wats

import (
	"crypto/tls"
	"encoding/xml"
	"net/http"
	"os"
	"strconv"
	"strings"

	"github.com/cloudfoundry-incubator/cf-test-helpers/helpers"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

const soapBody = `<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
	<s:Body>
		<Echo xmlns="http://tempuri.org/">
			<msg>test</msg>
		</Echo>
	</s:Body>
</s:Envelope>
`

var _ = Describe("WCF", func() {
	Describe("A WCF application", func() {
		It("can have multiple routable instances on the same cell", func() {
			numWinCells, err := strconv.Atoi(os.Getenv("NUM_WIN_CELLS"))
			Expect(err).NotTo(HaveOccurred(), "Please provide NUM_WIN_CELLS (The number of windows cells in tested deployment)")

			By("pushing multiple instances of it", func() {
				Eventually(pushApp(appName, "../../assets/wcf/Hello.Service.IIS", numWinCells+1, "256m"), CF_PUSH_TIMEOUT).Should(Succeed())
			})

			enableDiego(appName)
			Eventually(runCf("start", appName), CF_PUSH_TIMEOUT).Should(Succeed())

			By("verifying it's up")
			type WCFResponse struct {
				Msg          string
				InstanceGuid string
				CFInstanceIp string
			}

			wcfRequest := func(appName string) WCFResponse {
				uri := helpers.AppUri(appName, "/Hello.svc?wsdl")

				helloMsg := `<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body><Echo xmlns="http://tempuri.org/"><msg>WATS!!!</msg></Echo></s:Body></s:Envelope>`
				buf := strings.NewReader(helloMsg)
				req, err := http.NewRequest("POST", uri, buf)
				req.Header.Add("Content-Type", "text/xml")
				req.Header.Add("SOAPAction", "http://tempuri.org/IHelloService/Echo")
				client := &http.Client{Transport: &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}}
				resp, err := client.Do(req)
				Expect(err).To(BeNil())
				defer resp.Body.Close()

				xmlDecoder := xml.NewDecoder(resp.Body)
				type SoapResponse struct {
					XMLResult string `xml:"Body>EchoResponse>EchoResult"`
				}
				xmlResponse := SoapResponse{}
				Expect(xmlDecoder.Decode(&xmlResponse)).To(BeNil())
				results := strings.Split(xmlResponse.XMLResult, ",")
				Expect(len(results)).To(Equal(3))
				return WCFResponse{
					Msg:          results[0],
					CFInstanceIp: results[1],
					InstanceGuid: results[2],
				}
			}

			Eventually(wcfRequest(appName).Msg).Should(Equal("WATS!!!"))
			isServiceRunningOnTheSameCell := func(appName string) bool {
				// Keep track of the IDs of the instances we have reached
				output := map[string]string{}
				for i := 0; i < numWinCells*5; i++ {
					res := wcfRequest(appName)
					guids := output[res.CFInstanceIp]
					if guids != "" && !strings.Contains(guids, res.InstanceGuid) {
						return true
					}
					output[res.CFInstanceIp] = res.InstanceGuid
				}
				return false
			}

			Expect(isServiceRunningOnTheSameCell(appName)).To(BeTrue())
		})
	})
})
<commit_msg>Use Eventually instead of Expect for wcf test<commit_after>package wats

import (
	"crypto/tls"
	"encoding/xml"
	"net/http"
	"os"
	"strconv"
	"strings"

	"github.com/cloudfoundry-incubator/cf-test-helpers/helpers"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

const soapBody = `<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
	<s:Body>
		<Echo xmlns="http://tempuri.org/">
			<msg>test</msg>
		</Echo>
	</s:Body>
</s:Envelope>
`

var _ = Describe("WCF", func() {
	Describe("A WCF application", func() {
		It("can have multiple routable instances on the same cell", func() {
			numWinCells, err := strconv.Atoi(os.Getenv("NUM_WIN_CELLS"))
			Expect(err).NotTo(HaveOccurred(), "Please provide NUM_WIN_CELLS (The number of windows cells in tested deployment)")

			By("pushing multiple instances of it", func() {
				Eventually(pushApp(appName, "../../assets/wcf/Hello.Service.IIS", numWinCells+1, "256m"), CF_PUSH_TIMEOUT).Should(Succeed())
			})

			enableDiego(appName)
			Eventually(runCf("start", appName), CF_PUSH_TIMEOUT).Should(Succeed())

			By("verifying it's up")
			type WCFResponse struct {
				Msg          string
				InstanceGuid string
				CFInstanceIp string
			}

			wcfRequest := func(appName string) WCFResponse {
				uri := helpers.AppUri(appName, "/Hello.svc?wsdl")

				helloMsg := `<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body><Echo xmlns="http://tempuri.org/"><msg>WATS!!!</msg></Echo></s:Body></s:Envelope>`
				buf := strings.NewReader(helloMsg)
				req, err := http.NewRequest("POST", uri, buf)
				req.Header.Add("Content-Type", "text/xml")
				req.Header.Add("SOAPAction", "http://tempuri.org/IHelloService/Echo")
				client := &http.Client{Transport: &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}}
				resp, err := client.Do(req)
				Expect(err).To(BeNil())
				defer resp.Body.Close()

				xmlDecoder := xml.NewDecoder(resp.Body)
				type SoapResponse struct {
					XMLResult string `xml:"Body>EchoResponse>EchoResult"`
				}
				xmlResponse := SoapResponse{}
				Expect(xmlDecoder.Decode(&xmlResponse)).To(BeNil())
				results := strings.Split(xmlResponse.XMLResult, ",")
				Expect(len(results)).To(Equal(3))
				return WCFResponse{
					Msg:          results[0],
					CFInstanceIp: results[1],
					InstanceGuid: results[2],
				}
			}

			Eventually(wcfRequest(appName).Msg).Should(Equal("WATS!!!"))
			isServiceRunningOnTheSameCell := func(appName string) bool {
				// Keep track of the IDs of the instances we have reached
				output := map[string]string{}
				for i := 0; i < numWinCells*5; i++ {
					res := wcfRequest(appName)
					guids := output[res.CFInstanceIp]
					if guids != "" && !strings.Contains(guids, res.InstanceGuid) {
						return true
					}
					output[res.CFInstanceIp] = res.InstanceGuid
				}
				return false
			}

			Eventually(isServiceRunningOnTheSameCell(appName), CF_PUSH_TIMEOUT).Should(BeTrue())
		})
	})
})
<|endoftext|>


<commit_before>package web

import (
    "io"
	"net/http"
	"draringi/codejam2013/src/forecasting"
	"draringi/codejam2013/src/data"
    "encoding/json"
    "time"
    "sync"
)

type dataError struct {
    What string
    When time.Time
}

func (self *dataError) Error() string {
    return "["+self.When.Format(data.ISO)+"] " + self.What
}

type future struct {
    Records []record
}

type record struct {
    Date string
    Power float64
}

type dashboardHelper struct {
}

type Dashboard struct {
	channel chan ([]data.Record)
	JSONAid dashboardHelper
    Forcast *future
    Data []data.Record
    Lock sync.Mutex
}

func (self *Dashboard) Init () {
	self.Lock.Lock()
	self.channel = make(chan ([]data.Record), 1)
	self.Data = nil
	self.Forcast = nil
	self.Lock.Unlock()
	go forecasting.PredictPulse(self.channel)
	for {
		tmp := <-self.channel
		if tmp != nil {
			self.Data = tmp
			self.Build()
		}
	}
}

type Static struct{
}

func (self *Static) ServeHTTP (w http.ResponseWriter, request *http.Request) {
	http.ServeFile(w, request, "dashboard.html")
}

func (self *Dashboard) Build () {
    Data := self.Data
    self.Forcast = new(future)
    self.Forcast.Records = make([]record,len(Data))
    for i :=0; i<len(Data); i++ {
        self.Forcast.Records[i].Date = Data[i].Time.Format(data.ISO)
        self.Forcast.Records[i].Power = Data[i].Power
    }
}

func (self *Dashboard) jsonify (w io.Writer) error {
    encoder := json.NewEncoder(w)
    if self.Data != nil {
        encoder.Encode(self.Forcast)
        return nil
    } else {
        return &dataError{"Error: Could not load data", time.Now()}
    }
}

func (self *Dashboard) ServeHTTP (w http.ResponseWriter, request *http.Request) {
    err := self.jsonify(w)
    if err != nil {
        http.Error(w,err.Error(), 404)
    }
}
<commit_msg>js fixes<commit_after>package web

import (
    "io"
	"net/http"
	"draringi/codejam2013/src/forecasting"
	"draringi/codejam2013/src/data"
    "encoding/json"
    "time"
    "sync"
)

type dataError struct {
    What string
    When time.Time
}

func (self *dataError) Error() string {
    return "["+self.When.Format(data.ISO)+"] " + self.What
}

type future struct {
    Records []record
}

type record struct {
    Date string
    Power float64
}

type dashboardHelper struct {
}

type Dashboard struct {
	channel chan ([]data.Record)
	JSONAid dashboardHelper
    Forcast *future
    Data []data.Record
    Lock sync.Mutex
}

func (self *Dashboard) Init () {
	self.Lock.Lock()
	self.channel = make(chan ([]data.Record), 1)
	self.Data = nil
	self.Forcast = nil
	self.Lock.Unlock()
	go forecasting.PredictPulse(self.channel)
	for {
		tmp := <-self.channel
		if tmp != nil {
			self.Data = tmp
			self.Build()
		}
	}
}

type Static struct{
}

func (self *Static) ServeHTTP (w http.ResponseWriter, request *http.Request) {
	http.ServeFile(w, request, "dashboard.html")
}

func (self *Dashboard) Build () {
    Data := self.Data
    self.Forcast = new(future)
    self.Forcast.Records = make([]record,len(Data))
    for i :=0; i<len(Data); i++ {
        self.Forcast.Records[i].Date = Data[i].Time.Format(time.ANSIC)
        self.Forcast.Records[i].Power = Data[i].Power
    }
}

func (self *Dashboard) jsonify (w io.Writer) error {
    encoder := json.NewEncoder(w)
    if self.Data != nil {
        encoder.Encode(self.Forcast)
        return nil
    } else {
        return &dataError{"Error: Could not load data", time.Now()}
    }
}

func (self *Dashboard) ServeHTTP (w http.ResponseWriter, request *http.Request) {
    err := self.jsonify(w)
    if err != nil {
        http.Error(w,err.Error(), 404)
    }
}
<|endoftext|>