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

package e2e

import (
	"encoding/json"
	"testing"

	pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
	"github.com/coreos/etcd/pkg/testutil"
)

func TestV3CurlPutGetNoTLS(t *testing.T)     { testCurlPutGetGRPCGateway(t, &configNoTLS) }
func TestV3CurlPutGetAutoTLS(t *testing.T)   { testCurlPutGetGRPCGateway(t, &configAutoTLS) }
func TestV3CurlPutGetAllTLS(t *testing.T)    { testCurlPutGetGRPCGateway(t, &configTLS) }
func TestV3CurlPutGetPeerTLS(t *testing.T)   { testCurlPutGetGRPCGateway(t, &configPeerTLS) }
func TestV3CurlPutGetClientTLS(t *testing.T) { testCurlPutGetGRPCGateway(t, &configClientTLS) }
func testCurlPutGetGRPCGateway(t *testing.T, cfg *etcdProcessClusterConfig) {
	defer testutil.AfterTest(t)

	epc, err := newEtcdProcessCluster(cfg)
	if err != nil {
		t.Fatalf("could not start etcd process cluster (%v)", err)
	}
	defer func() {
		if cerr := epc.Close(); err != nil {
			t.Fatalf("error closing etcd processes (%v)", cerr)
		}
	}()

	var (
		key   = []byte("foo")
		value = []byte("bar") // this will be automatically base64-encoded by Go

		expectPut = `"revision":"`
		expectGet = `"value":"`
	)
	putData, err := json.Marshal(&pb.PutRequest{
		Key:   key,
		Value: value,
	})
	if err != nil {
		t.Fatal(err)
	}
	rangeData, err := json.Marshal(&pb.RangeRequest{
		Key: key,
	})
	if err != nil {
		t.Fatal(err)
	}

	if err := cURLPost(epc, cURLReq{endpoint: "/v3alpha/kv/put", value: string(putData), expected: expectPut}); err != nil {
		t.Fatalf("failed put with curl (%v)", err)
	}
	if err := cURLPost(epc, cURLReq{endpoint: "/v3alpha/kv/range", value: string(rangeData), expected: expectGet}); err != nil {
		t.Fatalf("failed get with curl (%v)", err)
	}

	if cfg.clientTLS == clientTLSAndNonTLS {
		if err := cURLPost(epc, cURLReq{endpoint: "/v3alpha/kv/range", value: string(rangeData), expected: expectGet, isTLS: true}); err != nil {
			t.Fatalf("failed get with curl (%v)", err)
		}
	}
}

func TestV3CurlWatch(t *testing.T) {
	defer testutil.AfterTest(t)

	epc, err := newEtcdProcessCluster(&configNoTLS)
	if err != nil {
		t.Fatalf("could not start etcd process cluster (%v)", err)
	}
	defer func() {
		if cerr := epc.Close(); err != nil {
			t.Fatalf("error closing etcd processes (%v)", cerr)
		}
	}()

	// store "bar" into "foo"
	putreq, err := json.Marshal(&pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")})
	if err != nil {
		t.Fatal(err)
	}
	if err = cURLPost(epc, cURLReq{endpoint: "/v3alpha/kv/put", value: string(putreq), expected: "revision"}); err != nil {
		t.Fatalf("failed put with curl (%v)", err)
	}
	// watch for first update to "foo"
	wcr := &pb.WatchCreateRequest{Key: []byte("foo"), StartRevision: 1}
	wreq, err := json.Marshal(wcr)
	if err != nil {
		t.Fatal(err)
	}
	// marshaling the grpc to json gives:
	// "{"RequestUnion":{"CreateRequest":{"key":"Zm9v","start_revision":1}}}"
	// but the gprc-gateway expects a different format..
	wstr := `{"create_request" : ` + string(wreq) + "}"
	// expects "bar", timeout after 2 seconds since stream waits forever
	if err = cURLPost(epc, cURLReq{endpoint: "/v3alpha/watch", value: wstr, expected: `"YmFy"`, timeout: 2}); err != nil {
		t.Fatal(err)
	}
}
<commit_msg>e2e: test txn over grpc json<commit_after>// Copyright 2016 The etcd Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package e2e

import (
	"encoding/json"
	"testing"

	pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
	"github.com/coreos/etcd/pkg/testutil"

	"github.com/grpc-ecosystem/grpc-gateway/runtime"
)

func TestV3CurlPutGetNoTLS(t *testing.T)     { testCurlPutGetGRPCGateway(t, &configNoTLS) }
func TestV3CurlPutGetAutoTLS(t *testing.T)   { testCurlPutGetGRPCGateway(t, &configAutoTLS) }
func TestV3CurlPutGetAllTLS(t *testing.T)    { testCurlPutGetGRPCGateway(t, &configTLS) }
func TestV3CurlPutGetPeerTLS(t *testing.T)   { testCurlPutGetGRPCGateway(t, &configPeerTLS) }
func TestV3CurlPutGetClientTLS(t *testing.T) { testCurlPutGetGRPCGateway(t, &configClientTLS) }
func testCurlPutGetGRPCGateway(t *testing.T, cfg *etcdProcessClusterConfig) {
	defer testutil.AfterTest(t)

	epc, err := newEtcdProcessCluster(cfg)
	if err != nil {
		t.Fatalf("could not start etcd process cluster (%v)", err)
	}
	defer func() {
		if cerr := epc.Close(); err != nil {
			t.Fatalf("error closing etcd processes (%v)", cerr)
		}
	}()

	var (
		key   = []byte("foo")
		value = []byte("bar") // this will be automatically base64-encoded by Go

		expectPut = `"revision":"`
		expectGet = `"value":"`
	)
	putData, err := json.Marshal(&pb.PutRequest{
		Key:   key,
		Value: value,
	})
	if err != nil {
		t.Fatal(err)
	}
	rangeData, err := json.Marshal(&pb.RangeRequest{
		Key: key,
	})
	if err != nil {
		t.Fatal(err)
	}

	if err := cURLPost(epc, cURLReq{endpoint: "/v3alpha/kv/put", value: string(putData), expected: expectPut}); err != nil {
		t.Fatalf("failed put with curl (%v)", err)
	}
	if err := cURLPost(epc, cURLReq{endpoint: "/v3alpha/kv/range", value: string(rangeData), expected: expectGet}); err != nil {
		t.Fatalf("failed get with curl (%v)", err)
	}

	if cfg.clientTLS == clientTLSAndNonTLS {
		if err := cURLPost(epc, cURLReq{endpoint: "/v3alpha/kv/range", value: string(rangeData), expected: expectGet, isTLS: true}); err != nil {
			t.Fatalf("failed get with curl (%v)", err)
		}
	}
}

func TestV3CurlWatch(t *testing.T) {
	defer testutil.AfterTest(t)

	epc, err := newEtcdProcessCluster(&configNoTLS)
	if err != nil {
		t.Fatalf("could not start etcd process cluster (%v)", err)
	}
	defer func() {
		if cerr := epc.Close(); err != nil {
			t.Fatalf("error closing etcd processes (%v)", cerr)
		}
	}()

	// store "bar" into "foo"
	putreq, err := json.Marshal(&pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")})
	if err != nil {
		t.Fatal(err)
	}
	if err = cURLPost(epc, cURLReq{endpoint: "/v3alpha/kv/put", value: string(putreq), expected: "revision"}); err != nil {
		t.Fatalf("failed put with curl (%v)", err)
	}
	// watch for first update to "foo"
	wcr := &pb.WatchCreateRequest{Key: []byte("foo"), StartRevision: 1}
	wreq, err := json.Marshal(wcr)
	if err != nil {
		t.Fatal(err)
	}
	// marshaling the grpc to json gives:
	// "{"RequestUnion":{"CreateRequest":{"key":"Zm9v","start_revision":1}}}"
	// but the gprc-gateway expects a different format..
	wstr := `{"create_request" : ` + string(wreq) + "}"
	// expects "bar", timeout after 2 seconds since stream waits forever
	if err = cURLPost(epc, cURLReq{endpoint: "/v3alpha/watch", value: wstr, expected: `"YmFy"`, timeout: 2}); err != nil {
		t.Fatal(err)
	}
}

func TestV3CurlTxn(t *testing.T) {
	defer testutil.AfterTest(t)
	epc, err := newEtcdProcessCluster(&configNoTLS)
	if err != nil {
		t.Fatalf("could not start etcd process cluster (%v)", err)
	}
	defer func() {
		if cerr := epc.Close(); err != nil {
			t.Fatalf("error closing etcd processes (%v)", cerr)
		}
	}()

	txn := &pb.TxnRequest{
		Compare: []*pb.Compare{
			{
				Key:         []byte("foo"),
				Result:      pb.Compare_EQUAL,
				Target:      pb.Compare_CREATE,
				TargetUnion: &pb.Compare_CreateRevision{0},
			},
		},
		Success: []*pb.RequestOp{
			{
				Request: &pb.RequestOp_RequestPut{
					RequestPut: &pb.PutRequest{
						Key:   []byte("foo"),
						Value: []byte("bar"),
					},
				},
			},
		},
	}
	m := &runtime.JSONPb{}
	jsonDat, jerr := m.Marshal(txn)
	if jerr != nil {
		t.Fatal(jerr)
	}
	expected := `"succeeded":true,"responses":[{"response_put":{"header":{"revision":"2"}}}]`
	if err = cURLPost(epc, cURLReq{endpoint: "/v3alpha/kv/txn", value: string(jsonDat), expected: expected}); err != nil {
		t.Fatalf("failed txn with curl (%v)", err)
	}

	// was crashing etcd server
	malformed := `{"compare":[{"result":0,"target":1,"key":"Zm9v","TargetUnion":null}],"success":[{"Request":{"RequestPut":{"key":"Zm9v","value":"YmFy"}}}]}`
	if err = cURLPost(epc, cURLReq{endpoint: "/v3alpha/kv/txn", value: malformed, expected: "error"}); err != nil {
		t.Fatalf("failed put with curl (%v)", err)
	}
}
<|endoftext|>


<commit_before>/*
    PulseHA - HA Cluster Daemon
    Copyright (C) 2017  Andrew Zak <andrew@pulseha.com>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published
    by the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package main

import (
	"sync"
	"github.com/coreos/go-log/log"
	"github.com/Syleron/PulseHA/proto"
	"errors"
	"google.golang.org/grpc/credentials"
	"google.golang.org/grpc"
)

/**
	Member struct type
 */
type Member struct {
	hostname string
	status   proto.MemberStatus_Status
	Client
	sync.Mutex
}

/*
	Getters and setters for Member which allow us to make them go routine safe
 */

func (m *Member) getHostname() string {
	m.Lock()
	defer m.Unlock()
	return m.hostname
}

/**

 */
func (m *Member) setHostname(hostname string) {
	m.Lock()
	defer m.Unlock()
	m.hostname = hostname
}

/**

 */
func (m *Member) getStatus() proto.MemberStatus_Status {
	m.Lock()
	defer m.Unlock()
	return m.status
}

/**

 */
func (m *Member) setStatus(status proto.MemberStatus_Status) {
	m.Lock()
	defer m.Unlock()
	m.status = status
}

/**

 */
func (m *Member) setClient(client Client) {
	m.Client = client
}

/**
	Note: Hostname is required for TLS as the certs are named after the hostname.
 */
func (m *Member) Connect() (error) {
	if m.Connection == nil {
		nodeDetails, _ := NodeGetByName(m.hostname)
		err := m.Client.Connect(nodeDetails.IP, nodeDetails.Port, m.hostname)
		if err != nil {
			return err
		}
	}
	return nil
}

/**
	Close the client connection
 */
func (m *Member) Close() {
	log.Debug("Member:Close() Connection closed")
	m.Connection.Close()
}

/**
	Send GRPC health check to current member
 */
func (m *Member) sendHealthCheck() (interface{}, error) {
	if m.Connection == nil {
		return nil, errors.New("unable to send health check as member connection has not been initiated")
	}
	r, err := m.Send(SendHealthCheck, &proto.PulseHealthCheck{})
	return r, err
}

/*
	Make the node active (bring up its groups)
 */
func (m *Member) makeActive() bool {
	log.Debugf("Member:makeActive() Making %s active", m.getHostname())

	if m.hostname == gconf.getLocalNode() {
		makeMemberActive()
	} else {
		log.Debug("member is not local node making grpc call")
		_, err := m.Send(
			SendMakeActive,
			&proto.PulsePromote{
				Success: false,
				Message: "",
				Member:  m.getHostname(),
			},
		)
		if err != nil {
			log.Error(err)
			log.Errorf("Error making %s active. Error: %s", m.getHostname(), err.Error())
			return false
		}
	}
	m.status = proto.MemberStatus_ACTIVE
	return true
}

/**
	Make the node passive (take down its groups)
 */
func (m *Member) makePassive() bool {
	log.Debugf("Member:makePassive() Making %s passive", m.getHostname())
	if m.hostname == gconf.getLocalNode() {
		makeMemberPassive()
	} else {
		log.Debug("member is not local node making grpc call")
		_, err := m.Send(
			SendMakePassive,
			&proto.PulsePromote{
				Success: false,
				Message: "",
				Member:  m.getHostname(),
			})
		if err != nil {
			log.Error(err)
			log.Errorf("Error making %s passive. Error: %s", m.getHostname(), err.Error())
			return false
		}
	}
	m.status = proto.MemberStatus_PASSIVE
	return true
}

/**
	Used to bring up a single IP on member
	We need to know the group to work out what interface to
	bring it up on.
 */
func (m *Member) bringUpIPs(ips []string, group string) bool {
	configCopy := gconf.GetConfig()
	iface := configCopy.GetGroupIface(m.hostname, group)
	if m.hostname == gconf.getLocalNode() {
		log.Debug("member is local node bringing up IP's")
		bringUpIPs(iface, ips)
	} else {
		log.Debug("member is not local node making grpc call")
		_, err := m.Send(
			SendBringUpIP,
			&proto.PulseBringIP{
				Iface: iface,
				Ips:   ips,
			})
		if err != nil {
			log.Error(err)
			log.Errorf("Error making %s passive. Error: %s", m.getHostname(), err.Error())
			return false
		}
	}
	m.status = proto.MemberStatus_PASSIVE
	return true
}
<commit_msg>resolve issue with travis<commit_after>/*
    PulseHA - HA Cluster Daemon
    Copyright (C) 2017  Andrew Zak <andrew@pulseha.com>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published
    by the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package main

import (
	"sync"
	"github.com/coreos/go-log/log"
	"github.com/Syleron/PulseHA/proto"
	"errors"
)

/**
	Member struct type
 */
type Member struct {
	hostname string
	status   proto.MemberStatus_Status
	Client
	sync.Mutex
}

/*
	Getters and setters for Member which allow us to make them go routine safe
 */

func (m *Member) getHostname() string {
	m.Lock()
	defer m.Unlock()
	return m.hostname
}

/**

 */
func (m *Member) setHostname(hostname string) {
	m.Lock()
	defer m.Unlock()
	m.hostname = hostname
}

/**

 */
func (m *Member) getStatus() proto.MemberStatus_Status {
	m.Lock()
	defer m.Unlock()
	return m.status
}

/**

 */
func (m *Member) setStatus(status proto.MemberStatus_Status) {
	m.Lock()
	defer m.Unlock()
	m.status = status
}

/**

 */
func (m *Member) setClient(client Client) {
	m.Client = client
}

/**
	Note: Hostname is required for TLS as the certs are named after the hostname.
 */
func (m *Member) Connect() (error) {
	if m.Connection == nil {
		nodeDetails, _ := NodeGetByName(m.hostname)
		err := m.Client.Connect(nodeDetails.IP, nodeDetails.Port, m.hostname)
		if err != nil {
			return err
		}
	}
	return nil
}

/**
	Close the client connection
 */
func (m *Member) Close() {
	log.Debug("Member:Close() Connection closed")
	m.Connection.Close()
}

/**
	Send GRPC health check to current member
 */
func (m *Member) sendHealthCheck() (interface{}, error) {
	if m.Connection == nil {
		return nil, errors.New("unable to send health check as member connection has not been initiated")
	}
	r, err := m.Send(SendHealthCheck, &proto.PulseHealthCheck{})
	return r, err
}

/*
	Make the node active (bring up its groups)
 */
func (m *Member) makeActive() bool {
	log.Debugf("Member:makeActive() Making %s active", m.getHostname())

	if m.hostname == gconf.getLocalNode() {
		makeMemberActive()
	} else {
		log.Debug("member is not local node making grpc call")
		_, err := m.Send(
			SendMakeActive,
			&proto.PulsePromote{
				Success: false,
				Message: "",
				Member:  m.getHostname(),
			},
		)
		if err != nil {
			log.Error(err)
			log.Errorf("Error making %s active. Error: %s", m.getHostname(), err.Error())
			return false
		}
	}
	m.status = proto.MemberStatus_ACTIVE
	return true
}

/**
	Make the node passive (take down its groups)
 */
func (m *Member) makePassive() bool {
	log.Debugf("Member:makePassive() Making %s passive", m.getHostname())
	if m.hostname == gconf.getLocalNode() {
		makeMemberPassive()
	} else {
		log.Debug("member is not local node making grpc call")
		_, err := m.Send(
			SendMakePassive,
			&proto.PulsePromote{
				Success: false,
				Message: "",
				Member:  m.getHostname(),
			})
		if err != nil {
			log.Error(err)
			log.Errorf("Error making %s passive. Error: %s", m.getHostname(), err.Error())
			return false
		}
	}
	m.status = proto.MemberStatus_PASSIVE
	return true
}

/**
	Used to bring up a single IP on member
	We need to know the group to work out what interface to
	bring it up on.
 */
func (m *Member) bringUpIPs(ips []string, group string) bool {
	configCopy := gconf.GetConfig()
	iface := configCopy.GetGroupIface(m.hostname, group)
	if m.hostname == gconf.getLocalNode() {
		log.Debug("member is local node bringing up IP's")
		bringUpIPs(iface, ips)
	} else {
		log.Debug("member is not local node making grpc call")
		_, err := m.Send(
			SendBringUpIP,
			&proto.PulseBringIP{
				Iface: iface,
				Ips:   ips,
			})
		if err != nil {
			log.Error(err)
			log.Errorf("Error making %s passive. Error: %s", m.getHostname(), err.Error())
			return false
		}
	}
	m.status = proto.MemberStatus_PASSIVE
	return true
}
<|endoftext|>


<commit_before>package testutil

import (
	"encoding/json"
	"strconv"
	"testing"

	"github.com/chris-ramon/graphql-go/executor"
	"github.com/chris-ramon/graphql-go/language/ast"
	"github.com/chris-ramon/graphql-go/language/parser"
	"github.com/chris-ramon/graphql-go/types"
	"github.com/kr/pretty"
)

var (
	Luke           StarWarsChar
	Vader          StarWarsChar
	Han            StarWarsChar
	Leia           StarWarsChar
	Tarkin         StarWarsChar
	Threepio       StarWarsChar
	Artoo          StarWarsChar
	HumanData      map[int]StarWarsChar
	DroidData      map[int]StarWarsChar
	StarWarsSchema types.GraphQLSchema

	humanType *types.GraphQLObjectType
	droidType *types.GraphQLObjectType
)

type StarWarsChar struct {
	Id              string
	Name            string
	Friends         []StarWarsChar
	AppearsIn       []int
	HomePlanet      string
	PrimaryFunction string
}

func init() {
	Luke = StarWarsChar{
		Id:         "1000",
		Name:       "Luke Skywalker",
		AppearsIn:  []int{4, 5, 6},
		HomePlanet: "Tatooine",
	}
	Vader = StarWarsChar{
		Id:         "1001",
		Name:       "Darth Vader",
		AppearsIn:  []int{4, 5, 6},
		HomePlanet: "Tatooine",
	}
	Han = StarWarsChar{
		Id:        "1002",
		Name:      "Han Solo",
		AppearsIn: []int{4, 5, 6},
	}
	Leia = StarWarsChar{
		Id:         "1003",
		Name:       "Leia Organa",
		AppearsIn:  []int{4, 5, 6},
		HomePlanet: "Alderaa",
	}
	Tarkin = StarWarsChar{
		Id:        "1004",
		Name:      "Wilhuff Tarkin",
		AppearsIn: []int{4},
	}
	Threepio = StarWarsChar{
		Id:              "2000",
		Name:            "C-3PO",
		AppearsIn:       []int{4, 5, 6},
		PrimaryFunction: "Protocol",
	}
	Artoo = StarWarsChar{
		Id:              "2001",
		Name:            "R2-D2",
		AppearsIn:       []int{4, 5, 6},
		PrimaryFunction: "Astromech",
	}
	Luke.Friends = append(Luke.Friends, []StarWarsChar{Han, Leia, Threepio, Artoo}...)
	Vader.Friends = append(Luke.Friends, []StarWarsChar{Tarkin}...)
	Han.Friends = append(Han.Friends, []StarWarsChar{Luke, Leia, Artoo}...)
	Leia.Friends = append(Leia.Friends, []StarWarsChar{Luke, Han, Threepio, Artoo}...)
	Tarkin.Friends = append(Tarkin.Friends, []StarWarsChar{Vader}...)
	Threepio.Friends = append(Threepio.Friends, []StarWarsChar{Luke, Han, Leia, Artoo}...)
	Artoo.Friends = append(Artoo.Friends, []StarWarsChar{Luke, Han, Leia}...)
	HumanData = map[int]StarWarsChar{
		1000: Luke,
		1001: Vader,
		1002: Han,
		1003: Leia,
		1004: Tarkin,
	}
	DroidData = map[int]StarWarsChar{
		2000: Threepio,
		2001: Artoo,
	}

	episodeEnum := types.NewGraphQLEnumType(types.GraphQLEnumTypeConfig{
		Name:        "Episode",
		Description: "One of the films in the Star Wars Trilogy",
		Values: types.GraphQLEnumValueConfigMap{
			"NEWHOPE": types.GraphQLEnumValueConfig{
				Value:       4,
				Description: "Released in 1977.",
			},
			"EMPIRE": types.GraphQLEnumValueConfig{
				Value:       5,
				Description: "Released in 1980.",
			},
			"JEDI": types.GraphQLEnumValueConfig{
				Value:       6,
				Description: "Released in 1983.",
			},
		},
	})

	characterInterface := types.NewGraphQLInterfaceType(types.GraphQLInterfaceTypeConfig{
		Name:        "Character",
		Description: "A character in the Star Wars Trilogy",
		Fields: types.GraphQLFieldConfigMap{
			"id": &types.GraphQLFieldConfig{
				Type:        types.NewGraphQLNonNull(types.GraphQLString),
				Description: "The id of the character.",
			},
			"name": &types.GraphQLFieldConfig{
				Type:        types.GraphQLString,
				Description: "The name of the character.",
			},
			"appearsIn": &types.GraphQLFieldConfig{
				Type:        types.NewGraphQLList(episodeEnum),
				Description: "Which movies they appear in.",
			},
		},
		ResolveType: func(value interface{}, info types.GraphQLResolveInfo) *types.GraphQLObjectType {
			if character, ok := value.(StarWarsChar); ok {
				id, _ := strconv.Atoi(character.Id)
				human := GetHuman(id)
				if human.Id != "" {
					return humanType
				}
			}
			return droidType
		},
	})
	characterInterface.AddFieldConfig("friends", &types.GraphQLFieldConfig{
		Type:        types.NewGraphQLList(characterInterface),
		Description: "The friends of the character, or an empty list if they have none.",
	})

	humanType = types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name:        "Human",
		Description: "A humanoid creature in the Star Wars universe.",
		Fields: types.GraphQLFieldConfigMap{
			"id": &types.GraphQLFieldConfig{
				Type:        types.NewGraphQLNonNull(types.GraphQLString),
				Description: "The id of the human.",
				Resolve: func(p types.GQLFRParams) interface{} {
					if human, ok := p.Source.(StarWarsChar); ok {
						return human.Id
					}
					return nil
				},
			},
			"name": &types.GraphQLFieldConfig{
				Type:        types.GraphQLString,
				Description: "The name of the human.",
				Resolve: func(p types.GQLFRParams) interface{} {
					if human, ok := p.Source.(StarWarsChar); ok {
						return human.Name
					}
					return nil
				},
			},
			"friends": &types.GraphQLFieldConfig{
				Type:        types.NewGraphQLList(characterInterface),
				Description: "The friends of the human, or an empty list if they have none.",
				Resolve: func(p types.GQLFRParams) interface{} {
					if human, ok := p.Source.(StarWarsChar); ok {
						return human.Friends
					}
					return []interface{}{}
				},
			},
			"appearsIn": &types.GraphQLFieldConfig{
				Type:        types.NewGraphQLList(episodeEnum),
				Description: "Which movies they appear in.",
				Resolve: func(p types.GQLFRParams) interface{} {
					if human, ok := p.Source.(StarWarsChar); ok {
						return human.AppearsIn
					}
					return nil
				},
			},
			"homePlanet": &types.GraphQLFieldConfig{
				Type:        types.GraphQLString,
				Description: "The home planet of the human, or null if unknown.",
				Resolve: func(p types.GQLFRParams) interface{} {
					if human, ok := p.Source.(StarWarsChar); ok {
						return human.HomePlanet
					}
					return nil
				},
			},
		},
		Interfaces: []*types.GraphQLInterfaceType{
			characterInterface,
		},
	})
	droidType = types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name:        "Droid",
		Description: "A mechanical creature in the Star Wars universe.",
		Fields: types.GraphQLFieldConfigMap{
			"id": &types.GraphQLFieldConfig{
				Type:        types.NewGraphQLNonNull(types.GraphQLString),
				Description: "The id of the droid.",
				Resolve: func(p types.GQLFRParams) interface{} {
					if droid, ok := p.Source.(StarWarsChar); ok {
						return droid.Id
					}
					return nil
				},
			},
			"name": &types.GraphQLFieldConfig{
				Type:        types.GraphQLString,
				Description: "The name of the droid.",
				Resolve: func(p types.GQLFRParams) interface{} {
					if droid, ok := p.Source.(StarWarsChar); ok {
						return droid.Name
					}
					return nil
				},
			},
			"friends": &types.GraphQLFieldConfig{
				Type:        types.NewGraphQLList(characterInterface),
				Description: "The friends of the droid, or an empty list if they have none.",
				Resolve: func(p types.GQLFRParams) interface{} {
					if droid, ok := p.Source.(StarWarsChar); ok {
						friends := []map[string]interface{}{}
						for _, friend := range droid.Friends {
							friends = append(friends, map[string]interface{}{
								"name": friend.Name,
								"id":   friend.Id,
							})
						}
						return droid.Friends
					}
					return []interface{}{}
				},
			},
			"appearsIn": &types.GraphQLFieldConfig{
				Type:        types.NewGraphQLList(episodeEnum),
				Description: "Which movies they appear in.",
				Resolve: func(p types.GQLFRParams) interface{} {
					if droid, ok := p.Source.(StarWarsChar); ok {
						return droid.AppearsIn
					}
					return nil
				},
			},
			"primaryFunction": &types.GraphQLFieldConfig{
				Type:        types.GraphQLString,
				Description: "The primary function of the droid.",
				Resolve: func(p types.GQLFRParams) interface{} {
					if droid, ok := p.Source.(StarWarsChar); ok {
						return droid.PrimaryFunction
					}
					return nil
				},
			},
		},
		Interfaces: []*types.GraphQLInterfaceType{
			characterInterface,
		},
	})

	queryType := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name: "Query",
		Fields: types.GraphQLFieldConfigMap{
			"hero": &types.GraphQLFieldConfig{
				Type: characterInterface,
				Args: types.GraphQLFieldConfigArgumentMap{
					"episode": &types.GraphQLArgumentConfig{
						Description: "If omitted, returns the hero of the whole saga. If " +
							"provided, returns the hero of that particular episode.",
						Type: episodeEnum,
					},
				},
				Resolve: func(p types.GQLFRParams) (r interface{}) {
					return GetHero(p.Args["episode"])
				},
			},
			"human": &types.GraphQLFieldConfig{
				Type: humanType,
				Args: types.GraphQLFieldConfigArgumentMap{
					"id": &types.GraphQLArgumentConfig{
						Description: "id of the human",
						Type:        types.NewGraphQLNonNull(types.GraphQLString),
					},
				},
				Resolve: func(p types.GQLFRParams) (r interface{}) {
					return GetHuman(p.Args["id"].(int))
				},
			},
			"droid": &types.GraphQLFieldConfig{
				Type: droidType,
				Args: types.GraphQLFieldConfigArgumentMap{
					"id": &types.GraphQLArgumentConfig{
						Description: "id of the droid",
						Type:        types.NewGraphQLNonNull(types.GraphQLString),
					},
				},
				Resolve: func(p types.GQLFRParams) (r interface{}) {
					return GetDroid(p.Args["id"].(int))
				},
			},
		},
	})
	StarWarsSchema, _ = types.NewGraphQLSchema(types.GraphQLSchemaConfig{
		Query: queryType,
	})
}

func GetHuman(id int) StarWarsChar {
	if human, ok := HumanData[id]; ok {
		return human
	}
	return StarWarsChar{}
}
func GetDroid(id int) StarWarsChar {
	if droid, ok := DroidData[id]; ok {
		return droid
	}
	return StarWarsChar{}
}
func GetHero(episode interface{}) interface{} {
	if episode == 5 {
		return Luke
	}
	return Artoo
}

// Test helper functions

func Parse(t *testing.T, query string) *ast.Document {
	astDoc, err := parser.Parse(parser.ParseParams{
		Source: query,
		Options: parser.ParseOptions{
			// include source, for error reporting
			NoSource: false,
		},
	})
	if err != nil {
		t.Fatalf("Parse failed: %v", err)
	}
	return astDoc
}
func Execute(t *testing.T, ep executor.ExecuteParams) *types.GraphQLResult {
	resultChannel := make(chan *types.GraphQLResult)
	go executor.Execute(ep, resultChannel)
	result := <-resultChannel
	return result
}

func Diff(a, b interface{}) []string {
	return pretty.Diff(a, b)
}

// TODO: EqualSet, commenting by now
// perhaps not need to depend on
// github.com/deckarep/golang-set
//func EqualSet(a, b interface{}) bool {

//aa := []interface{}{}
//bb := []interface{}{}

//aVal := reflect.ValueOf(a)
//bVal := reflect.ValueOf(b)
//if aVal.Type().Kind() == reflect.Slice {
//for i := 0; i < aVal.Len(); i++ {
//val := aVal.Index(i).Interface()
//aa = append(aa, &val)
//}
//}
//if bVal.Type().Kind() == reflect.Slice {
//for i := 0; i < bVal.Len(); i++ {
//val := bVal.Index(i).Interface()
//bb = append(bb, &val)
//}
//}
//xx := mapset.NewSetFromSlice(aa)
//yy := mapset.NewSetFromSlice(bb)
//return xx.Equal(yy)
//}

func ASTToJSON(t *testing.T, a ast.Node) interface{} {
	b, err := json.Marshal(a)
	if err != nil {
		t.Fatalf("Failed to marshal ast.Node %v", err)
	}
	var f interface{}
	err = json.Unmarshal(b, &f)
	if err != nil {
		t.Fatalf("Failed to unmarshal ast.Node %v", err)
	}
	return f
}
<commit_msg>removes testutil.EqualSet<commit_after>package testutil

import (
	"encoding/json"
	"strconv"
	"testing"

	"github.com/chris-ramon/graphql-go/executor"
	"github.com/chris-ramon/graphql-go/language/ast"
	"github.com/chris-ramon/graphql-go/language/parser"
	"github.com/chris-ramon/graphql-go/types"
	"github.com/kr/pretty"
)

var (
	Luke           StarWarsChar
	Vader          StarWarsChar
	Han            StarWarsChar
	Leia           StarWarsChar
	Tarkin         StarWarsChar
	Threepio       StarWarsChar
	Artoo          StarWarsChar
	HumanData      map[int]StarWarsChar
	DroidData      map[int]StarWarsChar
	StarWarsSchema types.GraphQLSchema

	humanType *types.GraphQLObjectType
	droidType *types.GraphQLObjectType
)

type StarWarsChar struct {
	Id              string
	Name            string
	Friends         []StarWarsChar
	AppearsIn       []int
	HomePlanet      string
	PrimaryFunction string
}

func init() {
	Luke = StarWarsChar{
		Id:         "1000",
		Name:       "Luke Skywalker",
		AppearsIn:  []int{4, 5, 6},
		HomePlanet: "Tatooine",
	}
	Vader = StarWarsChar{
		Id:         "1001",
		Name:       "Darth Vader",
		AppearsIn:  []int{4, 5, 6},
		HomePlanet: "Tatooine",
	}
	Han = StarWarsChar{
		Id:        "1002",
		Name:      "Han Solo",
		AppearsIn: []int{4, 5, 6},
	}
	Leia = StarWarsChar{
		Id:         "1003",
		Name:       "Leia Organa",
		AppearsIn:  []int{4, 5, 6},
		HomePlanet: "Alderaa",
	}
	Tarkin = StarWarsChar{
		Id:        "1004",
		Name:      "Wilhuff Tarkin",
		AppearsIn: []int{4},
	}
	Threepio = StarWarsChar{
		Id:              "2000",
		Name:            "C-3PO",
		AppearsIn:       []int{4, 5, 6},
		PrimaryFunction: "Protocol",
	}
	Artoo = StarWarsChar{
		Id:              "2001",
		Name:            "R2-D2",
		AppearsIn:       []int{4, 5, 6},
		PrimaryFunction: "Astromech",
	}
	Luke.Friends = append(Luke.Friends, []StarWarsChar{Han, Leia, Threepio, Artoo}...)
	Vader.Friends = append(Luke.Friends, []StarWarsChar{Tarkin}...)
	Han.Friends = append(Han.Friends, []StarWarsChar{Luke, Leia, Artoo}...)
	Leia.Friends = append(Leia.Friends, []StarWarsChar{Luke, Han, Threepio, Artoo}...)
	Tarkin.Friends = append(Tarkin.Friends, []StarWarsChar{Vader}...)
	Threepio.Friends = append(Threepio.Friends, []StarWarsChar{Luke, Han, Leia, Artoo}...)
	Artoo.Friends = append(Artoo.Friends, []StarWarsChar{Luke, Han, Leia}...)
	HumanData = map[int]StarWarsChar{
		1000: Luke,
		1001: Vader,
		1002: Han,
		1003: Leia,
		1004: Tarkin,
	}
	DroidData = map[int]StarWarsChar{
		2000: Threepio,
		2001: Artoo,
	}

	episodeEnum := types.NewGraphQLEnumType(types.GraphQLEnumTypeConfig{
		Name:        "Episode",
		Description: "One of the films in the Star Wars Trilogy",
		Values: types.GraphQLEnumValueConfigMap{
			"NEWHOPE": types.GraphQLEnumValueConfig{
				Value:       4,
				Description: "Released in 1977.",
			},
			"EMPIRE": types.GraphQLEnumValueConfig{
				Value:       5,
				Description: "Released in 1980.",
			},
			"JEDI": types.GraphQLEnumValueConfig{
				Value:       6,
				Description: "Released in 1983.",
			},
		},
	})

	characterInterface := types.NewGraphQLInterfaceType(types.GraphQLInterfaceTypeConfig{
		Name:        "Character",
		Description: "A character in the Star Wars Trilogy",
		Fields: types.GraphQLFieldConfigMap{
			"id": &types.GraphQLFieldConfig{
				Type:        types.NewGraphQLNonNull(types.GraphQLString),
				Description: "The id of the character.",
			},
			"name": &types.GraphQLFieldConfig{
				Type:        types.GraphQLString,
				Description: "The name of the character.",
			},
			"appearsIn": &types.GraphQLFieldConfig{
				Type:        types.NewGraphQLList(episodeEnum),
				Description: "Which movies they appear in.",
			},
		},
		ResolveType: func(value interface{}, info types.GraphQLResolveInfo) *types.GraphQLObjectType {
			if character, ok := value.(StarWarsChar); ok {
				id, _ := strconv.Atoi(character.Id)
				human := GetHuman(id)
				if human.Id != "" {
					return humanType
				}
			}
			return droidType
		},
	})
	characterInterface.AddFieldConfig("friends", &types.GraphQLFieldConfig{
		Type:        types.NewGraphQLList(characterInterface),
		Description: "The friends of the character, or an empty list if they have none.",
	})

	humanType = types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name:        "Human",
		Description: "A humanoid creature in the Star Wars universe.",
		Fields: types.GraphQLFieldConfigMap{
			"id": &types.GraphQLFieldConfig{
				Type:        types.NewGraphQLNonNull(types.GraphQLString),
				Description: "The id of the human.",
				Resolve: func(p types.GQLFRParams) interface{} {
					if human, ok := p.Source.(StarWarsChar); ok {
						return human.Id
					}
					return nil
				},
			},
			"name": &types.GraphQLFieldConfig{
				Type:        types.GraphQLString,
				Description: "The name of the human.",
				Resolve: func(p types.GQLFRParams) interface{} {
					if human, ok := p.Source.(StarWarsChar); ok {
						return human.Name
					}
					return nil
				},
			},
			"friends": &types.GraphQLFieldConfig{
				Type:        types.NewGraphQLList(characterInterface),
				Description: "The friends of the human, or an empty list if they have none.",
				Resolve: func(p types.GQLFRParams) interface{} {
					if human, ok := p.Source.(StarWarsChar); ok {
						return human.Friends
					}
					return []interface{}{}
				},
			},
			"appearsIn": &types.GraphQLFieldConfig{
				Type:        types.NewGraphQLList(episodeEnum),
				Description: "Which movies they appear in.",
				Resolve: func(p types.GQLFRParams) interface{} {
					if human, ok := p.Source.(StarWarsChar); ok {
						return human.AppearsIn
					}
					return nil
				},
			},
			"homePlanet": &types.GraphQLFieldConfig{
				Type:        types.GraphQLString,
				Description: "The home planet of the human, or null if unknown.",
				Resolve: func(p types.GQLFRParams) interface{} {
					if human, ok := p.Source.(StarWarsChar); ok {
						return human.HomePlanet
					}
					return nil
				},
			},
		},
		Interfaces: []*types.GraphQLInterfaceType{
			characterInterface,
		},
	})
	droidType = types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name:        "Droid",
		Description: "A mechanical creature in the Star Wars universe.",
		Fields: types.GraphQLFieldConfigMap{
			"id": &types.GraphQLFieldConfig{
				Type:        types.NewGraphQLNonNull(types.GraphQLString),
				Description: "The id of the droid.",
				Resolve: func(p types.GQLFRParams) interface{} {
					if droid, ok := p.Source.(StarWarsChar); ok {
						return droid.Id
					}
					return nil
				},
			},
			"name": &types.GraphQLFieldConfig{
				Type:        types.GraphQLString,
				Description: "The name of the droid.",
				Resolve: func(p types.GQLFRParams) interface{} {
					if droid, ok := p.Source.(StarWarsChar); ok {
						return droid.Name
					}
					return nil
				},
			},
			"friends": &types.GraphQLFieldConfig{
				Type:        types.NewGraphQLList(characterInterface),
				Description: "The friends of the droid, or an empty list if they have none.",
				Resolve: func(p types.GQLFRParams) interface{} {
					if droid, ok := p.Source.(StarWarsChar); ok {
						friends := []map[string]interface{}{}
						for _, friend := range droid.Friends {
							friends = append(friends, map[string]interface{}{
								"name": friend.Name,
								"id":   friend.Id,
							})
						}
						return droid.Friends
					}
					return []interface{}{}
				},
			},
			"appearsIn": &types.GraphQLFieldConfig{
				Type:        types.NewGraphQLList(episodeEnum),
				Description: "Which movies they appear in.",
				Resolve: func(p types.GQLFRParams) interface{} {
					if droid, ok := p.Source.(StarWarsChar); ok {
						return droid.AppearsIn
					}
					return nil
				},
			},
			"primaryFunction": &types.GraphQLFieldConfig{
				Type:        types.GraphQLString,
				Description: "The primary function of the droid.",
				Resolve: func(p types.GQLFRParams) interface{} {
					if droid, ok := p.Source.(StarWarsChar); ok {
						return droid.PrimaryFunction
					}
					return nil
				},
			},
		},
		Interfaces: []*types.GraphQLInterfaceType{
			characterInterface,
		},
	})

	queryType := types.NewGraphQLObjectType(types.GraphQLObjectTypeConfig{
		Name: "Query",
		Fields: types.GraphQLFieldConfigMap{
			"hero": &types.GraphQLFieldConfig{
				Type: characterInterface,
				Args: types.GraphQLFieldConfigArgumentMap{
					"episode": &types.GraphQLArgumentConfig{
						Description: "If omitted, returns the hero of the whole saga. If " +
							"provided, returns the hero of that particular episode.",
						Type: episodeEnum,
					},
				},
				Resolve: func(p types.GQLFRParams) (r interface{}) {
					return GetHero(p.Args["episode"])
				},
			},
			"human": &types.GraphQLFieldConfig{
				Type: humanType,
				Args: types.GraphQLFieldConfigArgumentMap{
					"id": &types.GraphQLArgumentConfig{
						Description: "id of the human",
						Type:        types.NewGraphQLNonNull(types.GraphQLString),
					},
				},
				Resolve: func(p types.GQLFRParams) (r interface{}) {
					return GetHuman(p.Args["id"].(int))
				},
			},
			"droid": &types.GraphQLFieldConfig{
				Type: droidType,
				Args: types.GraphQLFieldConfigArgumentMap{
					"id": &types.GraphQLArgumentConfig{
						Description: "id of the droid",
						Type:        types.NewGraphQLNonNull(types.GraphQLString),
					},
				},
				Resolve: func(p types.GQLFRParams) (r interface{}) {
					return GetDroid(p.Args["id"].(int))
				},
			},
		},
	})
	StarWarsSchema, _ = types.NewGraphQLSchema(types.GraphQLSchemaConfig{
		Query: queryType,
	})
}

func GetHuman(id int) StarWarsChar {
	if human, ok := HumanData[id]; ok {
		return human
	}
	return StarWarsChar{}
}
func GetDroid(id int) StarWarsChar {
	if droid, ok := DroidData[id]; ok {
		return droid
	}
	return StarWarsChar{}
}
func GetHero(episode interface{}) interface{} {
	if episode == 5 {
		return Luke
	}
	return Artoo
}

// Test helper functions

func Parse(t *testing.T, query string) *ast.Document {
	astDoc, err := parser.Parse(parser.ParseParams{
		Source: query,
		Options: parser.ParseOptions{
			// include source, for error reporting
			NoSource: false,
		},
	})
	if err != nil {
		t.Fatalf("Parse failed: %v", err)
	}
	return astDoc
}
func Execute(t *testing.T, ep executor.ExecuteParams) *types.GraphQLResult {
	resultChannel := make(chan *types.GraphQLResult)
	go executor.Execute(ep, resultChannel)
	result := <-resultChannel
	return result
}

func Diff(a, b interface{}) []string {
	return pretty.Diff(a, b)
}

func ASTToJSON(t *testing.T, a ast.Node) interface{} {
	b, err := json.Marshal(a)
	if err != nil {
		t.Fatalf("Failed to marshal ast.Node %v", err)
	}
	var f interface{}
	err = json.Unmarshal(b, &f)
	if err != nil {
		t.Fatalf("Failed to unmarshal ast.Node %v", err)
	}
	return f
}
<|endoftext|>


<commit_before>package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
)

func Example_GetSimple() {
	run([]string{"get", "WIKI/CSCO", "-c4", "-t2014-01-01", "-T2014-01-04", "-C0"})
	// Output:
	// Date,Close
	// 2014-01-03,21.98
	// 2014-01-02,22.0
}

func Example_GetCollapse() {
	run([]string{"get", "WIKI/AAPL", "-t2014-01-01", "-T2014-02-01", "-x", "-c4", "--collapse=weekly", "-C0"})
	// Output:
	// 2014-02-02,500.6
	// 2014-01-26,546.07
	// 2014-01-19,540.67
	// 2014-01-12,532.94
	// 2014-01-05,540.98
}

func Example_GetTransformation() {
	run([]string{"get", "WIKI/MSFT", "-t2014-01-01", "-T2014-01-10", "-sasc", "-c4", "--transformation=normalize", "-C0"})
	// Output:
	// Date,Close
	// 2014-01-02,100.0
	// 2014-01-03,99.327233584499
	// 2014-01-06,97.228202368138
	// 2014-01-07,97.981700753498
	// 2014-01-08,96.232508073197
	// 2014-01-09,95.613562970936
	// 2014-01-10,96.986006458558
}

func Example_GetFile() {
	run([]string{"get", "WIKI/AAPL", "-c4", "-t2014-01-01", "-T2014-01-04", "-otmp", "-sasc", "-C0"})
	data, _ := ioutil.ReadFile("tmp")
	os.Remove("tmp")
	fmt.Println(string(data))
	// Output:
	// Date,Close
	// 2014-01-02,553.13
	// 2014-01-03,540.98
}

func Example_List() {
	run([]string{"list", "WIKI", "-P2", "-fjson", "-otmp", "-C0"})
	data, _ := ioutil.ReadFile("tmp")
	os.Remove("tmp")
	var r map[string]interface{}
	json.Unmarshal(data, &r)

	countTest := r["total_count"].(float64) > 2000
	lenTest := len(r["docs"].([]interface{}))
	sourceTest := r["sources"].([]interface{})[0].(map[string]interface{})["id"]

	fmt.Println(countTest, lenTest, sourceTest)
	// Output:
	// true 2 4922
}

func Example_Search() {
	run([]string{"search", "nasdaq composite", "-P3", "-fjson", "-otmp", "-C0"})
	data, _ := ioutil.ReadFile("tmp")
	os.Remove("tmp")
	var r map[string]interface{}
	json.Unmarshal(data, &r)

	countTest := r["total_count"].(float64) > 570000
	lenTest := len(r["docs"].([]interface{}))

	fmt.Println(countTest, lenTest)
	// Output:
	// true 3
}
<commit_msg>fix test to match quandl's response change<commit_after>package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
)

func Example_GetSimple() {
	run([]string{"get", "WIKI/CSCO", "-c4", "-t2014-01-01", "-T2014-01-04", "-C0"})
	// Output:
	// Date,Close
	// 2014-01-03,21.98
	// 2014-01-02,22.0
}

func Example_GetCollapse() {
	run([]string{"get", "WIKI/AAPL", "-t2014-01-01", "-T2014-02-01", "-x", "-c4", "--collapse=weekly", "-C0"})
	// Output:
	// 2014-02-02,500.6
	// 2014-01-26,546.07
	// 2014-01-19,540.67
	// 2014-01-12,532.94
	// 2014-01-05,540.98
}

func Example_GetTransformation() {
	run([]string{"get", "WIKI/MSFT", "-t2014-01-01", "-T2014-01-10", "-sasc", "-c4", "--transformation=normalize", "-C0"})
	// Output:
	// Date,Close
	// 2014-01-02,100.0
	// 2014-01-03,99.327233584499
	// 2014-01-06,97.228202368138
	// 2014-01-07,97.981700753498
	// 2014-01-08,96.232508073197
	// 2014-01-09,95.613562970936
	// 2014-01-10,96.986006458558
}

func Example_GetFile() {
	run([]string{"get", "WIKI/AAPL", "-c4", "-t2014-01-01", "-T2014-01-04", "-otmp", "-sasc", "-C0"})
	data, _ := ioutil.ReadFile("tmp")
	os.Remove("tmp")
	fmt.Println(string(data))
	// Output:
	// Date,Close
	// 2014-01-02,553.13
	// 2014-01-03,540.98
}

func Example_List() {
	run([]string{"list", "WIKI", "-P2", "-fjson", "-otmp", "-C0"})
	data, _ := ioutil.ReadFile("tmp")
	os.Remove("tmp")
	var r map[string]interface{}
	json.Unmarshal(data, &r)

	countTest := r["total_count"].(float64) > 2000
	lenTest := len(r["docs"].([]interface{}))
	sourceTest := r["docs"].([]interface{})[0].(map[string]interface{})["source_id"]

	fmt.Println(countTest, lenTest, sourceTest)
	// Output:
	// true 2 4922
}

func Example_Search() {
	run([]string{"search", "nasdaq composite", "-P3", "-fjson", "-otmp", "-C0"})
	data, _ := ioutil.ReadFile("tmp")
	os.Remove("tmp")
	var r map[string]interface{}
	json.Unmarshal(data, &r)

	countTest := r["total_count"].(float64) > 570000
	lenTest := len(r["docs"].([]interface{}))

	fmt.Println(countTest, lenTest)
	// Output:
	// true 3
}
<|endoftext|>


<commit_before>package thuder

import (
	"github.com/stianeikeland/go-rpio"
)

func init() {
	gpioErr = setupGPIO()
}

func setupGPIO() error {
	err := rpio.Open()
	if err != nil {
		return err
	}
	pin := rpio.Pin(0)
	pin.Output()
	lightOn = pin.High
	lightOff = pin.Low
}
<commit_msg>fix: missing return at end of function<commit_after>package thuder

import (
	"github.com/stianeikeland/go-rpio"
)

func init() {
	gpioErr = setupGPIO()
}

func setupGPIO() error {
	err := rpio.Open()
	if err != nil {
		return err
	}
	pin := rpio.Pin(0)
	pin.Output()
	lightOn = pin.High
	lightOff = pin.Low
	return nil
}
<|endoftext|>


<commit_before>package rest

import (
	"encoding/json"
	"fmt"
	"net/http"

	"github.com/dchest/uniuri"
	"github.com/gorilla/mux"
	"github.com/snickers/snickers/db"
	"github.com/snickers/snickers/lib"
	"github.com/snickers/snickers/types"
)

// CreateJob creates a job
func CreateJob(w http.ResponseWriter, r *http.Request) {
	dbInstance, err := db.GetDatabase()
	if err != nil {
		HTTPError(w, http.StatusBadRequest, "getting database", err)
		return
	}

	var jobInput types.JobInput
	if err := json.NewDecoder(r.Body).Decode(&jobInput); err != nil {
		HTTPError(w, http.StatusBadRequest, "unpacking job", err)
		return
	}

	preset, err := dbInstance.RetrievePreset(jobInput.PresetName)
	if err != nil {
		HTTPError(w, http.StatusBadRequest, "retrieving preset", err)
		return
	}

	//TODO should we move this to lib?
	var job types.Job
	job.ID = uniuri.New()
	job.Source = jobInput.Source
	job.Destination = jobInput.Destination
	job.Preset = preset
	job.Status = types.JobCreated
	_, err = dbInstance.StoreJob(job)
	if err != nil {
		HTTPError(w, http.StatusBadRequest, "storing job", err)
		return
	}

	w.WriteHeader(http.StatusOK)
}

// ListJobs lists all jobs
func ListJobs(w http.ResponseWriter, r *http.Request) {
	dbInstance, err := db.GetDatabase()
	if err != nil {
		HTTPError(w, http.StatusBadRequest, "getting database", err)
		return
	}

	jobs, _ := dbInstance.GetJobs()
	result, err := json.Marshal(jobs)
	if err != nil {
		HTTPError(w, http.StatusBadRequest, "getting jobs", err)
		return
	}

	fmt.Fprintf(w, string(result))
}

// GetJobDetails returns the details of a given job
func GetJobDetails(w http.ResponseWriter, r *http.Request) {
	dbInstance, err := db.GetDatabase()
	if err != nil {
		HTTPError(w, http.StatusBadRequest, "getting database", err)
		return
	}

	vars := mux.Vars(r)
	jobID := vars["jobID"]
	job, err := dbInstance.RetrieveJob(jobID)
	if err != nil {
		HTTPError(w, http.StatusBadRequest, "retrieving job", err)
		return
	}

	result, err := json.Marshal(job)
	if err != nil {
		HTTPError(w, http.StatusBadRequest, "packing job data", err)
		return
	}
	fmt.Fprintf(w, "%s", result)
}

// StartJob triggers an encoding process
func StartJob(w http.ResponseWriter, r *http.Request) {
	dbInstance, err := db.GetDatabase()
	if err != nil {
		HTTPError(w, http.StatusBadRequest, "getting database", err)
		return
	}

	vars := mux.Vars(r)
	jobID := vars["jobID"]
	job, err := dbInstance.RetrieveJob(jobID)
	if err != nil {
		HTTPError(w, http.StatusBadRequest, "retrieving job", err)
		return
	}

	w.WriteHeader(http.StatusOK)
	go lib.StartJob(job)
}
<commit_msg>return the created jon with id closes #64<commit_after>package rest

import (
	"encoding/json"
	"fmt"
	"net/http"

	"github.com/dchest/uniuri"
	"github.com/gorilla/mux"
	"github.com/snickers/snickers/db"
	"github.com/snickers/snickers/lib"
	"github.com/snickers/snickers/types"
)

// CreateJob creates a job
func CreateJob(w http.ResponseWriter, r *http.Request) {
	dbInstance, err := db.GetDatabase()
	if err != nil {
		HTTPError(w, http.StatusBadRequest, "getting database", err)
		return
	}

	var jobInput types.JobInput
	if err := json.NewDecoder(r.Body).Decode(&jobInput); err != nil {
		HTTPError(w, http.StatusBadRequest, "unpacking job", err)
		return
	}

	preset, err := dbInstance.RetrievePreset(jobInput.PresetName)
	if err != nil {
		HTTPError(w, http.StatusBadRequest, "retrieving preset", err)
		return
	}

	//TODO should we move this to lib?
	var job types.Job
	job.ID = uniuri.New()
	job.Source = jobInput.Source
	job.Destination = jobInput.Destination
	job.Preset = preset
	job.Status = types.JobCreated
	_, err = dbInstance.StoreJob(job)
	if err != nil {
		HTTPError(w, http.StatusBadRequest, "storing job", err)
		return
	}

	result, err := json.Marshal(job)
	if err != nil {
		HTTPError(w, http.StatusBadRequest, "packing job data", err)
		return
	}
	fmt.Fprintf(w, "%s", result)
}

// ListJobs lists all jobs
func ListJobs(w http.ResponseWriter, r *http.Request) {
	dbInstance, err := db.GetDatabase()
	if err != nil {
		HTTPError(w, http.StatusBadRequest, "getting database", err)
		return
	}

	jobs, _ := dbInstance.GetJobs()
	result, err := json.Marshal(jobs)
	if err != nil {
		HTTPError(w, http.StatusBadRequest, "getting jobs", err)
		return
	}

	fmt.Fprintf(w, string(result))
}

// GetJobDetails returns the details of a given job
func GetJobDetails(w http.ResponseWriter, r *http.Request) {
	dbInstance, err := db.GetDatabase()
	if err != nil {
		HTTPError(w, http.StatusBadRequest, "getting database", err)
		return
	}

	vars := mux.Vars(r)
	jobID := vars["jobID"]
	job, err := dbInstance.RetrieveJob(jobID)
	if err != nil {
		HTTPError(w, http.StatusBadRequest, "retrieving job", err)
		return
	}

	result, err := json.Marshal(job)
	if err != nil {
		HTTPError(w, http.StatusBadRequest, "packing job data", err)
		return
	}
	fmt.Fprintf(w, "%s", result)
}

// StartJob triggers an encoding process
func StartJob(w http.ResponseWriter, r *http.Request) {
	dbInstance, err := db.GetDatabase()
	if err != nil {
		HTTPError(w, http.StatusBadRequest, "getting database", err)
		return
	}

	vars := mux.Vars(r)
	jobID := vars["jobID"]
	job, err := dbInstance.RetrieveJob(jobID)
	if err != nil {
		HTTPError(w, http.StatusBadRequest, "retrieving job", err)
		return
	}

	w.WriteHeader(http.StatusOK)
	go lib.StartJob(job)
}
<|endoftext|>


<commit_before>// Copyright 2012 Arne Roomann-Kurrik
//
// 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.

// Run with
//   go test -bench=".*"

package json

import (
	stdjson "encoding/json"
	"testing"
)

var RAW = []byte(`{"created_at":"Thu Sep 20 20:08:32 +0000 2012","id":248876316206714880,"id_str":"248876316206714880","text":"@mynetx you can send me an email - jasoncosta@twitter.com.","source":"web","truncated":false,"in_reply_to_status_id":248875708464640000,"in_reply_to_status_id_str":"248875708464640000","in_reply_to_user_id":14648265,"in_reply_to_user_id_str":"14648265","in_reply_to_screen_name":"mynetx","user":{"id":14927800,"id_str":"14927800","name":"Jason Costa","screen_name":"jasoncosta","location":"","description":"Platform at Twitter","url":"http:\/\/t.co\/YCA3ZKY","entities":{"url":{"urls":[{"url":"http:\/\/t.co\/YCA3ZKY","expanded_url":"http:\/\/www.jason-costa.blogspot.com\/","display_url":"jason-costa.blogspot.com","indices":[0,19]}]},"description":{"urls":[]}},"protected":false,"followers_count":9128,"friends_count":166,"listed_count":150,"created_at":"Wed May 28 00:20:15 +0000 2008","favourites_count":911,"utc_offset":-28800,"time_zone":"Pacific Time (US & Canada)","geo_enabled":true,"verified":false,"statuses_count":5567,"lang":"en","contributors_enabled":false,"is_translator":true,"profile_background_color":"709397","profile_background_image_url":"http:\/\/a0.twimg.com\/images\/themes\/theme6\/bg.gif","profile_background_image_url_https":"https:\/\/si0.twimg.com\/images\/themes\/theme6\/bg.gif","profile_background_tile":false,"profile_image_url":"http:\/\/a0.twimg.com\/profile_images\/1751674923\/new_york_beard_normal.jpg","profile_image_url_https":"https:\/\/si0.twimg.com\/profile_images\/1751674923\/new_york_beard_normal.jpg","profile_link_color":"FF3300","profile_sidebar_border_color":"86A4A6","profile_sidebar_fill_color":"A0C5C7","profile_text_color":"333333","profile_use_background_image":true,"default_profile":false,"default_profile_image":false,"following":null,"follow_request_sent":false,"notifications":null},"geo":null,"coordinates":null,"place":{"id":"3c1f852ebe886470","url":"https:\/\/api.twitter.com\/1.1\/geo\/id\/3c1f852ebe886470.json","place_type":"city","name":"Northwest Marin","full_name":"Northwest Marin, CA","country_code":"US","country":"United States","bounding_box":{"type":"Polygon","coordinates":[[[-123.134523,37.886947],[-122.563580,37.886947],[-122.563580,38.321227],[-123.134523,38.321227]]]},"attributes":{}},"contributors":null,"retweet_count":0,"entities":{"hashtags":[],"urls":[],"user_mentions":[{"screen_name":"mynetx","name":"J.M.","id":14648265,"id_str":"14648265","indices":[0,7]}]},"favorited":false,"retweeted":false}`)

func BenchmarkStdJSON(b *testing.B) {
	for i := 0; i < b.N; i++ {
		t := &map[string]interface{}{}
		stdjson.Unmarshal(RAW, t)
	}
}

func BenchmarkJSON(b *testing.B) {
	for i := 0; i < b.N; i++ {
		t := &map[string]interface{}{}
		Unmarshal(RAW, t)
	}
}

var RAW_LIST = []byte("[{\"foo\":1},{\"foo\":2}]")

func BenchmarkStdBucket(b *testing.B) {
	for i := 0; i < b.N; i++ {
		var t BucketList
		stdjson.Unmarshal(RAW_LIST, &t)
	}
}

func BenchmarkBucket(b *testing.B) {
	for i := 0; i < b.N; i++ {
		var t BucketList
		Unmarshal(RAW_LIST, &t)
	}
}
<commit_msg>Compare the speed of using types vs. empty interfaces.<commit_after>// Copyright 2012 Arne Roomann-Kurrik
//
// 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.

// Run with
//   go test -bench=".*"

package json

import (
	stdjson "encoding/json"
	"testing"
)

var RAW = []byte(`{"created_at":"Thu Sep 20 20:08:32 +0000 2012","id":248876316206714880,"id_str":"248876316206714880","text":"@mynetx you can send me an email - jasoncosta@twitter.com.","source":"web","truncated":false,"in_reply_to_status_id":248875708464640000,"in_reply_to_status_id_str":"248875708464640000","in_reply_to_user_id":14648265,"in_reply_to_user_id_str":"14648265","in_reply_to_screen_name":"mynetx","user":{"id":14927800,"id_str":"14927800","name":"Jason Costa","screen_name":"jasoncosta","location":"","description":"Platform at Twitter","url":"http:\/\/t.co\/YCA3ZKY","entities":{"url":{"urls":[{"url":"http:\/\/t.co\/YCA3ZKY","expanded_url":"http:\/\/www.jason-costa.blogspot.com\/","display_url":"jason-costa.blogspot.com","indices":[0,19]}]},"description":{"urls":[]}},"protected":false,"followers_count":9128,"friends_count":166,"listed_count":150,"created_at":"Wed May 28 00:20:15 +0000 2008","favourites_count":911,"utc_offset":-28800,"time_zone":"Pacific Time (US & Canada)","geo_enabled":true,"verified":false,"statuses_count":5567,"lang":"en","contributors_enabled":false,"is_translator":true,"profile_background_color":"709397","profile_background_image_url":"http:\/\/a0.twimg.com\/images\/themes\/theme6\/bg.gif","profile_background_image_url_https":"https:\/\/si0.twimg.com\/images\/themes\/theme6\/bg.gif","profile_background_tile":false,"profile_image_url":"http:\/\/a0.twimg.com\/profile_images\/1751674923\/new_york_beard_normal.jpg","profile_image_url_https":"https:\/\/si0.twimg.com\/profile_images\/1751674923\/new_york_beard_normal.jpg","profile_link_color":"FF3300","profile_sidebar_border_color":"86A4A6","profile_sidebar_fill_color":"A0C5C7","profile_text_color":"333333","profile_use_background_image":true,"default_profile":false,"default_profile_image":false,"following":null,"follow_request_sent":false,"notifications":null},"geo":null,"coordinates":null,"place":{"id":"3c1f852ebe886470","url":"https:\/\/api.twitter.com\/1.1\/geo\/id\/3c1f852ebe886470.json","place_type":"city","name":"Northwest Marin","full_name":"Northwest Marin, CA","country_code":"US","country":"United States","bounding_box":{"type":"Polygon","coordinates":[[[-123.134523,37.886947],[-122.563580,37.886947],[-122.563580,38.321227],[-123.134523,38.321227]]]},"attributes":{}},"contributors":null,"retweet_count":0,"entities":{"hashtags":[],"urls":[],"user_mentions":[{"screen_name":"mynetx","name":"J.M.","id":14648265,"id_str":"14648265","indices":[0,7]}]},"favorited":false,"retweeted":false}`)

func BenchmarkStdJSON(b *testing.B) {
	for i := 0; i < b.N; i++ {
		t := &map[string]interface{}{}
		stdjson.Unmarshal(RAW, t)
	}
}

func BenchmarkJSON(b *testing.B) {
	for i := 0; i < b.N; i++ {
		t := &map[string]interface{}{}
		Unmarshal(RAW, t)
	}
}

var RAW_LIST = []byte("[{\"foo\":1},{\"foo\":2}]")

func BenchmarkStdBucket(b *testing.B) {
	for i := 0; i < b.N; i++ {
		var t BucketList
		stdjson.Unmarshal(RAW_LIST, &t)
	}
}

func BenchmarkBucket(b *testing.B) {
	for i := 0; i < b.N; i++ {
		var t BucketList
		Unmarshal(RAW_LIST, &t)
	}
}

func BenchmarkUntypedBucket(b *testing.B) {
	for i := 0; i < b.N; i++ {
		var t []interface{}
		Unmarshal(RAW_LIST, &t)
	}
}
<|endoftext|>


<commit_before>// errchk $G -e $D/$F.go

// Copyright 2010 The Go Authors.  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Check line numbers in error messages.

package main

var (
	_ = x	// ERROR "undefined: x"
	_ = x	// ERROR "undefined: x"
	_ = x	// ERROR "undefined: x"
)

type T struct {
	y int
}

func foo() *T { return &T{y: 99} }
func bar() int { return y }	// ERROR "undefined: y"

type T1 struct {
	y1 int
}

func foo1() *T1 { return &T1{y1: 99} }
var y1 = 2
func bar1() int { return y1 }

func f1(val interface{}) {
	switch v := val.(type) {
	default:
		println(v)
	}
}

func f2(val interface{}) {
	switch val.(type) {
	default:
		println(v)	// ERROR "undefined: v"
	}
}
<commit_msg>test: Match gccgo error messages.<commit_after>// errchk $G -e $D/$F.go

// Copyright 2010 The Go Authors.  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Check line numbers in error messages.

package main

var (
	_ = x	// ERROR "undefined.*x"
	_ = x	// ERROR "undefined.*x"
	_ = x	// ERROR "undefined.*x"
)

type T struct {
	y int
}

func foo() *T { return &T{y: 99} }
func bar() int { return y }	// ERROR "undefined.*y"

type T1 struct {
	y1 int
}

func foo1() *T1 { return &T1{y1: 99} }
var y1 = 2
func bar1() int { return y1 }

func f1(val interface{}) {
	switch v := val.(type) {
	default:
		println(v)
	}
}

func f2(val interface{}) {
	switch val.(type) {
	default:
		println(v)	// ERROR "undefined.*v"
	}
}
<|endoftext|>


<commit_before>package main

import (
	"log"
	"os"
	"strconv"
	"time"

	"github.com/toorop/gopentsdb"
)

// Fonction principale, appelée au lancement du programme
func main() {
	var err error
	// Ces variables vont stocker differences d'usage des CPU/Core entre deux
	// mesures
	var diffUser, diffNice, diffSys, diffWait, diffIdle, diffSum uint64
	// Les variables suivant vont êtres utilisées pour stocker les stats entre
	// deux mesures
	var cStatsPrev map[string]CPUStats
	var netIOPrev *NetIO
	var disksIOPrev map[string]DiskIO

	// On va lire la configuration depuis l'environnement
	// Le nom d'hote de la machine
	hostname := os.Getenv("SENSOR_HOSTNAME")
	if hostname == "" {
		log.Fatalln("env var SENSOR_HOSTNAME does not exist")
	}

	// La période en secondes => le temps à attendre entre 2 mesures.
	period := int64(10)
	periodStr := os.Getenv("SENSOR_PERIOD")
	if periodStr != "" {
		period, err = strconv.ParseInt(periodStr, 10, 32)
	}

	// Tokens d'authentification
	username := os.Getenv("SENSOR_OPENSTDB_USERNAME")
	if username == "" {
		log.Fatalln("env var SENSOR_OPENSTDB_USERNAME does not exist")
	}
	password := os.Getenv("SENSOR_OPENSTDB_PASSWORD")
	if password == "" {
		log.Fatalln("env var SENSOR_OPENSTDB_PASSWORD does not exist")
	}

	// On initialise un nouveau client OpenSTDB
	OpenSTDBClient, err := gopentsdb.NewClient(gopentsdb.ClientConfig{
		Endpoint:           "https://opentsdb-gra1.tsaas.ovh.com",
		Username:           username,
		Password:           password,
		InsecureSkipVerify: false,
	})
	if err != nil {
		log.Fatalln(err)
	}

	// Boucle infinie.
	// A chaque tour on va faire une serie de mesures
	for {
		// Cette variable va contenir les points a pousser vers OpenSTDB
		points2Push := []gopentsdb.Point{}

		// On fait une pause  entre chaque mesure
		// pour les curieux le fait de la faire en début de boucle, nous permet de
		// ne pas ajouter cette instruction avant chaque "continue" en cas d'erreur
		time.Sleep(time.Duration(period) * time.Second)

		// On va chercher le load
		load, err := GetLoadAvg()
		if err != nil {
			log.Print("ERROR: ", err)
			continue
		}

		// On crée les trois points relatifs au load
		ptLoadCurrent := gopentsdb.NewPoint()
		ptLoadCurrent.Metric = "loadavg.current"
		ptLoadCurrent.Timestamp = load.timestamp
		ptLoadCurrent.Value = load.current
		ptLoadCurrent.Tags["host"] = hostname
		points2Push = append(points2Push, ptLoadCurrent)

		ptLoad5Min := gopentsdb.NewPoint()
		ptLoad5Min.Metric = "loadavg.5min"
		ptLoad5Min.Timestamp = load.timestamp
		ptLoad5Min.Value = load.avg5
		ptLoad5Min.Tags["host"] = hostname
		points2Push = append(points2Push, ptLoad5Min)

		ptLoad15Min := gopentsdb.NewPoint()
		ptLoad15Min.Metric = "loadavg.15min"
		ptLoad15Min.Timestamp = load.timestamp
		ptLoad15Min.Value = load.avg15
		ptLoad15Min.Tags["host"] = hostname
		points2Push = append(points2Push, ptLoad15Min)

		// Les stats cpu
		// cStatsPrev va stocker les stats cpu du test précédent. Ca va nous
		// permettre d'avoir des usage en % sur la periode donnée
		now := time.Now().Unix()
		cStats, err := GetCPUStats()
		if err != nil {
			log.Print("ERROR: ", err)
			continue
		}

		// On génere les point pour tous les cpu/cores
		for cpu, stats := range *cStats {
			// si on a des stats antérieures on fait un dif pour connaitre la conso de
			// chaque en pourcentage sur l'interval
			if &cStatsPrev != nil {
				if prevStats, ok := cStatsPrev[cpu]; ok {
					diffUser = stats.User - prevStats.User
					diffNice = stats.Nice - prevStats.Nice
					diffSys = stats.Sys - prevStats.Sys
					diffWait = stats.Wait - prevStats.Wait
					diffIdle = stats.Idle - prevStats.Idle
					diffSum = diffUser + diffNice + diffSys + diffWait + diffIdle

					// user
					point := gopentsdb.NewPoint()
					point.Metric = "cpu." + cpu + ".user.percent"
					point.Timestamp = now
					point.Value = float64(diffUser * 100 / diffSum)
					point.Tags["host"] = hostname
					points2Push = append(points2Push, point)

					// nice
					point = gopentsdb.NewPoint()
					point.Metric = "cpu." + cpu + ".nice.percent"
					point.Timestamp = now
					point.Value = float64(diffNice * 100 / diffSum)
					point.Tags["host"] = hostname
					points2Push = append(points2Push, point)

					// sys
					point = gopentsdb.NewPoint()
					point.Metric = "cpu." + cpu + ".sys.percent"
					point.Timestamp = now
					point.Value = float64(diffSys * 100 / diffSum)
					point.Tags["host"] = hostname
					points2Push = append(points2Push, point)

					// wait
					point = gopentsdb.NewPoint()
					point.Metric = "cpu." + cpu + ".wait.percent"
					point.Timestamp = now
					point.Value = float64(diffWait * 100 / diffSum)
					point.Tags["host"] = hostname
					points2Push = append(points2Push, point)

					// idle
					point = gopentsdb.NewPoint()
					point.Metric = "cpu." + cpu + ".idle.percent"
					point.Timestamp = now
					point.Value = float64(diffIdle * 100 / diffSum)
					point.Tags["host"] = hostname
					points2Push = append(points2Push, point)
				}
			}
		}
		cStatsPrev = *cStats

		// Mémoire
		now = time.Now().Unix()
		memStats, err := GetMemStats()
		if err == nil {
			// Free
			ptMemFree := gopentsdb.NewPoint()
			ptMemFree.Metric = "mem.free"
			ptMemFree.Timestamp = now
			ptMemFree.Value = float64(memStats["MemFree"])
			ptMemFree.Tags["host"] = hostname
			points2Push = append(points2Push, ptMemFree)

			// Memoire Utilisée
			ptMemUsed := gopentsdb.NewPoint()
			ptMemUsed.Metric = "mem.used"
			ptMemUsed.Timestamp = now
			ptMemUsed.Value = float64(memStats["MemTotal"] - memStats["MemFree"])
			ptMemUsed.Tags["host"] = hostname
			points2Push = append(points2Push, ptMemUsed)

			// Cached
			ptMemCached := gopentsdb.NewPoint()
			ptMemCached.Metric = "mem.cached"
			ptMemCached.Timestamp = now
			ptMemCached.Value = float64(memStats["Cached"])
			ptMemCached.Tags["host"] = hostname
			points2Push = append(points2Push, ptMemCached)

			// Buffers
			ptMemBuffers := gopentsdb.NewPoint()
			ptMemBuffers.Metric = "mem.buffers"
			ptMemBuffers.Timestamp = now
			ptMemBuffers.Value = float64(memStats["Buffers"])
			ptMemBuffers.Tags["host"] = hostname
			points2Push = append(points2Push, ptMemBuffers)

			// Swap free
			ptSwapFree := gopentsdb.NewPoint()
			ptSwapFree.Metric = "mem.swap.free"
			ptSwapFree.Timestamp = now
			ptSwapFree.Value = float64(memStats["SwapFree"])
			ptSwapFree.Tags["host"] = hostname
			points2Push = append(points2Push, ptSwapFree)

			// Swap used
			ptSwapused := gopentsdb.NewPoint()
			ptSwapused.Metric = "mem.swap.used"
			ptSwapused.Timestamp = now
			ptSwapused.Value = float64(memStats["SwapTotal"] - memStats["SwapFree"])
			ptSwapused.Tags["host"] = hostname
			points2Push = append(points2Push, ptSwapused)
		}

		// Le reseau
		io, err := GetNetIO()
		if err != nil {
			log.Println(err)
		} else if netIOPrev != nil {
			timeDelta := uint64(io.timestamp - netIOPrev.timestamp)

			// IN
			ptNetIn := gopentsdb.NewPoint()
			ptNetIn.Metric = "net.in"
			ptNetIn.Timestamp = io.timestamp
			ptNetIn.Value = float64((io.in - netIOPrev.in) / timeDelta)
			ptNetIn.Tags["host"] = hostname
			points2Push = append(points2Push, ptNetIn)

			// OUT
			ptNetOut := gopentsdb.NewPoint()
			ptNetOut.Metric = "net.out"
			ptNetOut.Timestamp = io.timestamp
			ptNetOut.Value = float64((io.out - netIOPrev.out) / timeDelta)
			ptNetOut.Tags["host"] = hostname
			points2Push = append(points2Push, ptNetOut)

		}
		netIOPrev = io

		// Les lectures / écritues disk
		disksIO, err := GetDisksIO()
		if err != nil {
			log.Println(err)
		} else if disksIOPrev != nil {
			for disk, stats := range disksIO {
				timeDelta := uint64(stats.Timestamp - disksIOPrev[disk].Timestamp)
				point := gopentsdb.NewPoint()
				point.Metric = "disk." + disk + ".reads"
				point.Timestamp = stats.Timestamp
				point.Value = float64((stats.Reads - disksIOPrev[disk].Reads) / timeDelta)
				point.Tags["host"] = hostname
				points2Push = append(points2Push, point)

				point = gopentsdb.NewPoint()
				point.Metric = "disk." + disk + ".writes"
				point.Timestamp = stats.Timestamp
				point.Value = float64((stats.Writes - disksIOPrev[disk].Writes) / timeDelta)
				point.Tags["host"] = hostname
				points2Push = append(points2Push, point)
			}
		}
		disksIOPrev = disksIO

		// On pousse les points vers OVH
		if err = OpenSTDBClient.Push(points2Push); err != nil {
			log.Println(err)
		}
	}
}
<commit_msg>change endpoint address<commit_after>package main

import (
	"log"
	"os"
	"strconv"
	"time"

	"github.com/toorop/gopentsdb"
)

// Fonction principale, appelée au lancement du programme
func main() {
	var err error
	// Ces variables vont stocker differences d'usage des CPU/Core entre deux
	// mesures
	var diffUser, diffNice, diffSys, diffWait, diffIdle, diffSum uint64
	// Les variables suivant vont êtres utilisées pour stocker les stats entre
	// deux mesures
	var cStatsPrev map[string]CPUStats
	var netIOPrev *NetIO
	var disksIOPrev map[string]DiskIO

	// On va lire la configuration depuis l'environnement
	// Le nom d'hote de la machine
	hostname := os.Getenv("SENSOR_HOSTNAME")
	if hostname == "" {
		log.Fatalln("env var SENSOR_HOSTNAME does not exist")
	}

	// La période en secondes => le temps à attendre entre 2 mesures.
	period := int64(10)
	periodStr := os.Getenv("SENSOR_PERIOD")
	if periodStr != "" {
		period, err = strconv.ParseInt(periodStr, 10, 32)
	}

	// Tokens d'authentification
	username := os.Getenv("SENSOR_OPENSTDB_USERNAME")
	if username == "" {
		log.Fatalln("env var SENSOR_OPENSTDB_USERNAME does not exist")
	}
	password := os.Getenv("SENSOR_OPENSTDB_PASSWORD")
	if password == "" {
		log.Fatalln("env var SENSOR_OPENSTDB_PASSWORD does not exist")
	}

	// On initialise un nouveau client OpenSTDB
	OpenSTDBClient, err := gopentsdb.NewClient(gopentsdb.ClientConfig{
		Endpoint:           "https://opentsdb.gra1.metrics.ovh.net",
		Username:           username,
		Password:           password,
		InsecureSkipVerify: false,
	})
	if err != nil {
		log.Fatalln(err)
	}

	// Boucle infinie.
	// A chaque tour on va faire une serie de mesures
	for {
		// Cette variable va contenir les points a pousser vers OpenSTDB
		points2Push := []gopentsdb.Point{}

		// On fait une pause  entre chaque mesure
		// pour les curieux le fait de la faire en début de boucle, nous permet de
		// ne pas ajouter cette instruction avant chaque "continue" en cas d'erreur
		time.Sleep(time.Duration(period) * time.Second)

		// On va chercher le load
		load, err := GetLoadAvg()
		if err != nil {
			log.Print("ERROR: ", err)
			continue
		}

		// On crée les trois points relatifs au load
		ptLoadCurrent := gopentsdb.NewPoint()
		ptLoadCurrent.Metric = "loadavg.current"
		ptLoadCurrent.Timestamp = load.timestamp
		ptLoadCurrent.Value = load.current
		ptLoadCurrent.Tags["host"] = hostname
		points2Push = append(points2Push, ptLoadCurrent)

		ptLoad5Min := gopentsdb.NewPoint()
		ptLoad5Min.Metric = "loadavg.5min"
		ptLoad5Min.Timestamp = load.timestamp
		ptLoad5Min.Value = load.avg5
		ptLoad5Min.Tags["host"] = hostname
		points2Push = append(points2Push, ptLoad5Min)

		ptLoad15Min := gopentsdb.NewPoint()
		ptLoad15Min.Metric = "loadavg.15min"
		ptLoad15Min.Timestamp = load.timestamp
		ptLoad15Min.Value = load.avg15
		ptLoad15Min.Tags["host"] = hostname
		points2Push = append(points2Push, ptLoad15Min)

		// Les stats cpu
		// cStatsPrev va stocker les stats cpu du test précédent. Ca va nous
		// permettre d'avoir des usage en % sur la periode donnée
		now := time.Now().Unix()
		cStats, err := GetCPUStats()
		if err != nil {
			log.Print("ERROR: ", err)
			continue
		}

		// On génere les point pour tous les cpu/cores
		for cpu, stats := range *cStats {
			// si on a des stats antérieures on fait un dif pour connaitre la conso de
			// chaque en pourcentage sur l'interval
			if &cStatsPrev != nil {
				if prevStats, ok := cStatsPrev[cpu]; ok {
					diffUser = stats.User - prevStats.User
					diffNice = stats.Nice - prevStats.Nice
					diffSys = stats.Sys - prevStats.Sys
					diffWait = stats.Wait - prevStats.Wait
					diffIdle = stats.Idle - prevStats.Idle
					diffSum = diffUser + diffNice + diffSys + diffWait + diffIdle

					// user
					point := gopentsdb.NewPoint()
					point.Metric = "cpu." + cpu + ".user.percent"
					point.Timestamp = now
					point.Value = float64(diffUser * 100 / diffSum)
					point.Tags["host"] = hostname
					points2Push = append(points2Push, point)

					// nice
					point = gopentsdb.NewPoint()
					point.Metric = "cpu." + cpu + ".nice.percent"
					point.Timestamp = now
					point.Value = float64(diffNice * 100 / diffSum)
					point.Tags["host"] = hostname
					points2Push = append(points2Push, point)

					// sys
					point = gopentsdb.NewPoint()
					point.Metric = "cpu." + cpu + ".sys.percent"
					point.Timestamp = now
					point.Value = float64(diffSys * 100 / diffSum)
					point.Tags["host"] = hostname
					points2Push = append(points2Push, point)

					// wait
					point = gopentsdb.NewPoint()
					point.Metric = "cpu." + cpu + ".wait.percent"
					point.Timestamp = now
					point.Value = float64(diffWait * 100 / diffSum)
					point.Tags["host"] = hostname
					points2Push = append(points2Push, point)

					// idle
					point = gopentsdb.NewPoint()
					point.Metric = "cpu." + cpu + ".idle.percent"
					point.Timestamp = now
					point.Value = float64(diffIdle * 100 / diffSum)
					point.Tags["host"] = hostname
					points2Push = append(points2Push, point)
				}
			}
		}
		cStatsPrev = *cStats

		// Mémoire
		now = time.Now().Unix()
		memStats, err := GetMemStats()
		if err == nil {
			// Free
			ptMemFree := gopentsdb.NewPoint()
			ptMemFree.Metric = "mem.free"
			ptMemFree.Timestamp = now
			ptMemFree.Value = float64(memStats["MemFree"])
			ptMemFree.Tags["host"] = hostname
			points2Push = append(points2Push, ptMemFree)

			// Memoire Utilisée
			ptMemUsed := gopentsdb.NewPoint()
			ptMemUsed.Metric = "mem.used"
			ptMemUsed.Timestamp = now
			ptMemUsed.Value = float64(memStats["MemTotal"] - memStats["MemFree"])
			ptMemUsed.Tags["host"] = hostname
			points2Push = append(points2Push, ptMemUsed)

			// Cached
			ptMemCached := gopentsdb.NewPoint()
			ptMemCached.Metric = "mem.cached"
			ptMemCached.Timestamp = now
			ptMemCached.Value = float64(memStats["Cached"])
			ptMemCached.Tags["host"] = hostname
			points2Push = append(points2Push, ptMemCached)

			// Buffers
			ptMemBuffers := gopentsdb.NewPoint()
			ptMemBuffers.Metric = "mem.buffers"
			ptMemBuffers.Timestamp = now
			ptMemBuffers.Value = float64(memStats["Buffers"])
			ptMemBuffers.Tags["host"] = hostname
			points2Push = append(points2Push, ptMemBuffers)

			// Swap free
			ptSwapFree := gopentsdb.NewPoint()
			ptSwapFree.Metric = "mem.swap.free"
			ptSwapFree.Timestamp = now
			ptSwapFree.Value = float64(memStats["SwapFree"])
			ptSwapFree.Tags["host"] = hostname
			points2Push = append(points2Push, ptSwapFree)

			// Swap used
			ptSwapused := gopentsdb.NewPoint()
			ptSwapused.Metric = "mem.swap.used"
			ptSwapused.Timestamp = now
			ptSwapused.Value = float64(memStats["SwapTotal"] - memStats["SwapFree"])
			ptSwapused.Tags["host"] = hostname
			points2Push = append(points2Push, ptSwapused)
		}

		// Le reseau
		io, err := GetNetIO()
		if err != nil {
			log.Println(err)
		} else if netIOPrev != nil {
			timeDelta := uint64(io.timestamp - netIOPrev.timestamp)

			// IN
			ptNetIn := gopentsdb.NewPoint()
			ptNetIn.Metric = "net.in"
			ptNetIn.Timestamp = io.timestamp
			ptNetIn.Value = float64((io.in - netIOPrev.in) / timeDelta)
			ptNetIn.Tags["host"] = hostname
			points2Push = append(points2Push, ptNetIn)

			// OUT
			ptNetOut := gopentsdb.NewPoint()
			ptNetOut.Metric = "net.out"
			ptNetOut.Timestamp = io.timestamp
			ptNetOut.Value = float64((io.out - netIOPrev.out) / timeDelta)
			ptNetOut.Tags["host"] = hostname
			points2Push = append(points2Push, ptNetOut)

		}
		netIOPrev = io

		// Les lectures / écritues disk
		disksIO, err := GetDisksIO()
		if err != nil {
			log.Println(err)
		} else if disksIOPrev != nil {
			for disk, stats := range disksIO {
				timeDelta := uint64(stats.Timestamp - disksIOPrev[disk].Timestamp)
				point := gopentsdb.NewPoint()
				point.Metric = "disk." + disk + ".reads"
				point.Timestamp = stats.Timestamp
				point.Value = float64((stats.Reads - disksIOPrev[disk].Reads) / timeDelta)
				point.Tags["host"] = hostname
				points2Push = append(points2Push, point)

				point = gopentsdb.NewPoint()
				point.Metric = "disk." + disk + ".writes"
				point.Timestamp = stats.Timestamp
				point.Value = float64((stats.Writes - disksIOPrev[disk].Writes) / timeDelta)
				point.Tags["host"] = hostname
				points2Push = append(points2Push, point)
			}
		}
		disksIOPrev = disksIO

		// On pousse les points vers OVH
		if err = OpenSTDBClient.Push(points2Push); err != nil {
			log.Println(err)
		}
	}
}
<|endoftext|>


<commit_before>package pubnative

import (
	"encoding/json"
	"fmt"
	"net/http"
	"net/url"
	"strconv"

	"github.com/mxmCherry/openrtb"
	"github.com/prebid/prebid-server/adapters"
	"github.com/prebid/prebid-server/config"
	"github.com/prebid/prebid-server/errortypes"
	"github.com/prebid/prebid-server/openrtb_ext"
)

type PubnativeAdapter struct {
	URI string
}

func (a *PubnativeAdapter) MakeRequests(request *openrtb.BidRequest, reqInfo *adapters.ExtraRequestInfo) ([]*adapters.RequestData, []error) {
	impCount := len(request.Imp)
	requestData := make([]*adapters.RequestData, 0, impCount)
	errs := []error{}

	headers := http.Header{}
	headers.Add("Content-Type", "application/json;charset=utf-8")
	headers.Add("Accept", "application/json")

	err := checkRequest(request)
	if err != nil {
		errs = append(errs, err)
		return nil, errs
	}

	for _, imp := range request.Imp {
		requestCopy := *request
		var bidderExt adapters.ExtImpBidder
		if err := json.Unmarshal(imp.Ext, &bidderExt); err != nil {
			errs = append(errs, err)
			continue
		}

		var pubnativeExt openrtb_ext.ExtImpPubnative
		if err := json.Unmarshal(bidderExt.Bidder, &pubnativeExt); err != nil {
			errs = append(errs, err)
			continue
		}

		err := convertImpression(&imp)
		if err != nil {
			errs = append(errs, err)
			continue
		}

		requestCopy.Imp = []openrtb.Imp{imp}
		reqJSON, err := json.Marshal(&requestCopy)
		if err != nil {
			errs = append(errs, err)
			return nil, errs
		}

		queryParams := url.Values{}
		queryParams.Add("apptoken", pubnativeExt.AppAuthToken)
		queryParams.Add("zoneid", strconv.Itoa(pubnativeExt.ZoneID))
		queryString := queryParams.Encode()

		reqData := &adapters.RequestData{
			Method:  "POST",
			Uri:     fmt.Sprintf("%s?%s", a.URI, queryString),
			Body:    reqJSON,
			Headers: headers,
		}

		requestData = append(requestData, reqData)
	}
	return requestData, errs
}

func checkRequest(request *openrtb.BidRequest) error {
	if request.Device == nil || len(request.Device.OS) == 0 {
		return &errortypes.BadInput{
			Message: "Impression is missing device OS information",
		}
	}

	return nil
}

func convertImpression(imp *openrtb.Imp) error {
	if imp.Banner == nil && imp.Video == nil && imp.Native == nil {
		return &errortypes.BadInput{
			Message: "Pubnative only supports banner, video or native ads.",
		}
	}
	if imp.Banner != nil {
		err := convertBanner(imp.Banner)
		if err != nil {
			return err
		}
	}

	return nil
}

// make sure that banner has openrtb 2.3-compatible size information
func convertBanner(banner *openrtb.Banner) error {
	if banner.W == nil || banner.H == nil || *banner.W == 0 || *banner.H == 0 {
		if len(banner.Format) > 0 {
			f := banner.Format[0]
			banner.W = &f.W
			banner.H = &f.H
		} else {
			return &errortypes.BadInput{
				Message: "Size information missing for banner",
			}
		}
	}
	return nil
}

func (a *PubnativeAdapter) MakeBids(internalRequest *openrtb.BidRequest, externalRequest *adapters.RequestData, response *adapters.ResponseData) (*adapters.BidderResponse, []error) {
	if response.StatusCode == http.StatusNoContent {
		return nil, nil
	}

	if response.StatusCode == http.StatusBadRequest {
		return nil, []error{&errortypes.BadInput{
			Message: fmt.Sprintf("Unexpected status code: %d. Run with request.debug = 1 for more info", response.StatusCode),
		}}
	}

	if response.StatusCode != http.StatusOK {
		return nil, []error{&errortypes.BadServerResponse{
			Message: fmt.Sprintf("Unexpected status code: %d. Run with request.debug = 1 for more info", response.StatusCode),
		}}
	}

	var parsedResponse openrtb.BidResponse
	if err := json.Unmarshal(response.Body, &parsedResponse); err != nil {
		return nil, []error{&errortypes.BadServerResponse{
			Message: err.Error(),
		}}
	}

	bidResponse := adapters.NewBidderResponseWithBidsCapacity(1)

	for _, sb := range parsedResponse.SeatBid {
		for i := 0; i < len(sb.Bid); i++ {
			bid := sb.Bid[i]
			if bid.Price != 0 {
				bidResponse.Bids = append(bidResponse.Bids, &adapters.TypedBid{
					Bid:     &bid,
					BidType: getMediaTypeForImp(bid.ImpID, internalRequest.Imp),
				})
			}
		}
	}
	return bidResponse, nil
}

// Builder builds a new instance of the Pubnative adapter for the given bidder with the given config.
func Builder(bidderName openrtb_ext.BidderName, config config.Adapter) (adapters.Bidder, error) {
	bidder := &PubnativeAdapter{
		URI: config.Endpoint,
	}
	return bidder, nil
}

func getMediaTypeForImp(impId string, imps []openrtb.Imp) openrtb_ext.BidType {
	mediaType := openrtb_ext.BidTypeBanner
	for _, imp := range imps {
		if imp.ID == impId {
			if imp.Video != nil {
				mediaType = openrtb_ext.BidTypeVideo
			} else if imp.Native != nil {
				mediaType = openrtb_ext.BidTypeNative
			}
			return mediaType
		}
	}
	return mediaType
}
<commit_msg>Pubnative: Fix Shared Memory Overwriting (#1760)<commit_after>package pubnative

import (
	"encoding/json"
	"fmt"
	"net/http"
	"net/url"
	"strconv"

	"github.com/mxmCherry/openrtb"
	"github.com/prebid/prebid-server/adapters"
	"github.com/prebid/prebid-server/config"
	"github.com/prebid/prebid-server/errortypes"
	"github.com/prebid/prebid-server/openrtb_ext"
)

type PubnativeAdapter struct {
	URI string
}

func (a *PubnativeAdapter) MakeRequests(request *openrtb.BidRequest, reqInfo *adapters.ExtraRequestInfo) ([]*adapters.RequestData, []error) {
	impCount := len(request.Imp)
	requestData := make([]*adapters.RequestData, 0, impCount)
	errs := []error{}

	headers := http.Header{}
	headers.Add("Content-Type", "application/json;charset=utf-8")
	headers.Add("Accept", "application/json")

	err := checkRequest(request)
	if err != nil {
		errs = append(errs, err)
		return nil, errs
	}

	for _, imp := range request.Imp {
		requestCopy := *request
		var bidderExt adapters.ExtImpBidder
		if err := json.Unmarshal(imp.Ext, &bidderExt); err != nil {
			errs = append(errs, err)
			continue
		}

		var pubnativeExt openrtb_ext.ExtImpPubnative
		if err := json.Unmarshal(bidderExt.Bidder, &pubnativeExt); err != nil {
			errs = append(errs, err)
			continue
		}

		err := convertImpression(&imp)
		if err != nil {
			errs = append(errs, err)
			continue
		}

		requestCopy.Imp = []openrtb.Imp{imp}
		reqJSON, err := json.Marshal(&requestCopy)
		if err != nil {
			errs = append(errs, err)
			return nil, errs
		}

		queryParams := url.Values{}
		queryParams.Add("apptoken", pubnativeExt.AppAuthToken)
		queryParams.Add("zoneid", strconv.Itoa(pubnativeExt.ZoneID))
		queryString := queryParams.Encode()

		reqData := &adapters.RequestData{
			Method:  "POST",
			Uri:     fmt.Sprintf("%s?%s", a.URI, queryString),
			Body:    reqJSON,
			Headers: headers,
		}

		requestData = append(requestData, reqData)
	}
	return requestData, errs
}

func checkRequest(request *openrtb.BidRequest) error {
	if request.Device == nil || len(request.Device.OS) == 0 {
		return &errortypes.BadInput{
			Message: "Impression is missing device OS information",
		}
	}

	return nil
}

func convertImpression(imp *openrtb.Imp) error {
	if imp.Banner == nil && imp.Video == nil && imp.Native == nil {
		return &errortypes.BadInput{
			Message: "Pubnative only supports banner, video or native ads.",
		}
	}
	if imp.Banner != nil {
		bannerCopy, err := convertBanner(imp.Banner)
		if err != nil {
			return err
		}
		imp.Banner = bannerCopy
	}

	return nil
}

// make sure that banner has openrtb 2.3-compatible size information
func convertBanner(banner *openrtb.Banner) (*openrtb.Banner, error) {
	if banner.W == nil || banner.H == nil || *banner.W == 0 || *banner.H == 0 {
		if len(banner.Format) > 0 {
			f := banner.Format[0]

			bannerCopy := *banner

			bannerCopy.W = openrtb.Uint64Ptr(f.W)
			bannerCopy.H = openrtb.Uint64Ptr(f.H)

			return &bannerCopy, nil
		} else {
			return nil, &errortypes.BadInput{
				Message: "Size information missing for banner",
			}
		}
	}
	return banner, nil
}

func (a *PubnativeAdapter) MakeBids(internalRequest *openrtb.BidRequest, externalRequest *adapters.RequestData, response *adapters.ResponseData) (*adapters.BidderResponse, []error) {
	if response.StatusCode == http.StatusNoContent {
		return nil, nil
	}

	if response.StatusCode == http.StatusBadRequest {
		return nil, []error{&errortypes.BadInput{
			Message: fmt.Sprintf("Unexpected status code: %d. Run with request.debug = 1 for more info", response.StatusCode),
		}}
	}

	if response.StatusCode != http.StatusOK {
		return nil, []error{&errortypes.BadServerResponse{
			Message: fmt.Sprintf("Unexpected status code: %d. Run with request.debug = 1 for more info", response.StatusCode),
		}}
	}

	var parsedResponse openrtb.BidResponse
	if err := json.Unmarshal(response.Body, &parsedResponse); err != nil {
		return nil, []error{&errortypes.BadServerResponse{
			Message: err.Error(),
		}}
	}

	bidResponse := adapters.NewBidderResponseWithBidsCapacity(1)

	for _, sb := range parsedResponse.SeatBid {
		for i := 0; i < len(sb.Bid); i++ {
			bid := sb.Bid[i]
			if bid.Price != 0 {
				bidResponse.Bids = append(bidResponse.Bids, &adapters.TypedBid{
					Bid:     &bid,
					BidType: getMediaTypeForImp(bid.ImpID, internalRequest.Imp),
				})
			}
		}
	}
	return bidResponse, nil
}

// Builder builds a new instance of the Pubnative adapter for the given bidder with the given config.
func Builder(bidderName openrtb_ext.BidderName, config config.Adapter) (adapters.Bidder, error) {
	bidder := &PubnativeAdapter{
		URI: config.Endpoint,
	}
	return bidder, nil
}

func getMediaTypeForImp(impId string, imps []openrtb.Imp) openrtb_ext.BidType {
	mediaType := openrtb_ext.BidTypeBanner
	for _, imp := range imps {
		if imp.ID == impId {
			if imp.Video != nil {
				mediaType = openrtb_ext.BidTypeVideo
			} else if imp.Native != nil {
				mediaType = openrtb_ext.BidTypeNative
			}
			return mediaType
		}
	}
	return mediaType
}
<|endoftext|>


<commit_before>package config

import (
	"k8s.io/client-go/tools/clientcmd"
	"k8s.io/client-go/tools/clientcmd/api"
)

// KubeConfig gets the kubernetes config
func KubeConfig(context *Context) clientcmd.ClientConfig {
	rules := clientcmd.NewDefaultClientConfigLoadingRules()

	overrides := &clientcmd.ConfigOverrides{}
	if context != nil {
		overrides.CurrentContext = "pachyderm"
		overrides.Context = api.Context{
			LocationOfOrigin: "pachyderm",
			Cluster:          context.ClusterName,
			AuthInfo:         context.AuthInfo,
			Namespace:        context.Namespace,
		}
	}

	return clientcmd.NewNonInteractiveDeferredLoadingClientConfig(rules, overrides)
}
<commit_msg>Do not set the current context<commit_after>package config

import (
	"k8s.io/client-go/tools/clientcmd"
	"k8s.io/client-go/tools/clientcmd/api"
)

// KubeConfig gets the kubernetes config
func KubeConfig(context *Context) clientcmd.ClientConfig {
	rules := clientcmd.NewDefaultClientConfigLoadingRules()

	overrides := &clientcmd.ConfigOverrides{}
	if context != nil {
		overrides.Context = api.Context{
			LocationOfOrigin: "pachyderm",
			Cluster:          context.ClusterName,
			AuthInfo:         context.AuthInfo,
			Namespace:        context.Namespace,
		}
	}

	return clientcmd.NewNonInteractiveDeferredLoadingClientConfig(rules, overrides)
}
<|endoftext|>