<commit_before>/*
 * Copyright (c) 2014 Santiago Arias | Remy Jourde
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

package tournaments

import (
	"errors"
	"net/http"
	"strconv"

	"appengine"

	"github.com/taironas/route"

	"github.com/santiaago/gonawin/helpers"
	"github.com/santiaago/gonawin/helpers/log"
	templateshlp "github.com/santiaago/gonawin/helpers/templates"

	mdl "github.com/santiaago/gonawin/models"
)

// A GroupJson is a variable to hold a the name of a group and an array of Teams.
// We use it to group tournament teams information by group to meet world cup organization.
type GroupJson struct {
	Name  string
	Teams []TeamJson
}

// A TeamJson is a variable to hold the basic information of a Team:
// The name of the team, the number of points recorded in the group phase, the goals for and against.
type TeamJson struct {
	Name   string
	Points int64
	GoalsF int64
	GoalsA int64
	Iso    string
}

// json tournament groups handler
// use this handler to get groups of a tournament.
func Groups(w http.ResponseWriter, r *http.Request, u *mdl.User) error {
	if r.Method != "GET" {
		return &helpers.BadRequest{Err: errors.New(helpers.ErrorCodeNotSupported)}
	}

	c := appengine.NewContext(r)
	desc := "Tournament Group Handler:"

	// get tournament id
	strTournamentId, err := route.Context.Get(r, "tournamentId")
	if err != nil {
		log.Errorf(c, "%s error getting tournament id, err:%v", desc, err)
		return &helpers.BadRequest{Err: errors.New(helpers.ErrorCodeTournamentNotFound)}
	}

	var tournamentId int64
	tournamentId, err = strconv.ParseInt(strTournamentId, 0, 64)
	if err != nil {
		log.Errorf(c, "%s error converting tournament id from string to int64, err:%v", desc, err)
		return &helpers.BadRequest{Err: errors.New(helpers.ErrorCodeTournamentNotFound)}
	}

	var tournament *mdl.Tournament
	tournament, err = mdl.TournamentById(c, tournamentId)
	if err != nil {
		log.Errorf(c, "%s tournament with id:%v was not found %v", desc, tournamentId, err)
		return &helpers.NotFound{Err: errors.New(helpers.ErrorCodeTournamentNotFound)}
	}

	groups := mdl.Groups(c, tournament.GroupIds)
	groupsJson := formatGroupsJson(groups)

	data := struct {
		Groups []GroupJson
	}{
		groupsJson,
	}

	return templateshlp.RenderJson(w, c, data)
}

// Format a TGroup array into a GroupJson array.
func formatGroupsJson(groups []*mdl.Tgroup) []GroupJson {

	groupsJson := make([]GroupJson, len(groups))
	for i, g := range groups {
		groupsJson[i].Name = g.Name
		teams := make([]TeamJson, len(g.Teams))
		for j, t := range g.Teams {
			teams[j].Name = t.Name
			teams[j].Points = g.Points[j]
			teams[j].GoalsF = g.GoalsF[j]
			teams[j].GoalsA = g.GoalsA[j]
			teams[j].Iso = t.Iso
		}
		groupsJson[i].Teams = teams
	}
	return groupsJson
}
<commit_msg>tournament Groups - refactor tournament retrieval<commit_after>/*
 * Copyright (c) 2014 Santiago Arias | Remy Jourde
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

package tournaments

import (
	"errors"
	"net/http"

	"appengine"

	"github.com/santiaago/gonawin/helpers"
	templateshlp "github.com/santiaago/gonawin/helpers/templates"

	mdl "github.com/santiaago/gonawin/models"
)

// A GroupJson is a variable to hold a the name of a group and an array of Teams.
// We use it to group tournament teams information by group to meet world cup organization.
type GroupJson struct {
	Name  string
	Teams []TeamJson
}

// A TeamJson is a variable to hold the basic information of a Team:
// The name of the team, the number of points recorded in the group phase, the goals for and against.
type TeamJson struct {
	Name   string
	Points int64
	GoalsF int64
	GoalsA int64
	Iso    string
}

// Groups handelr sends the JSON tournament groups data.
// use this handler to get groups of a tournament.
func Groups(w http.ResponseWriter, r *http.Request, u *mdl.User) error {
	if r.Method != "GET" {
		return &helpers.BadRequest{Err: errors.New(helpers.ErrorCodeNotSupported)}
	}

	c := appengine.NewContext(r)
	desc := "Tournament Group Handler:"

	rc := requestContext{c, desc, r}
	var err error
	var tournament *mdl.Tournament
	if tournament, err = rc.tournament(); err != nil {
		return err
	}

	groups := mdl.Groups(c, tournament.GroupIds)
	groupsJson := formatGroupsJson(groups)

	data := struct {
		Groups []GroupJson
	}{
		groupsJson,
	}

	return templateshlp.RenderJson(w, c, data)
}

// Format a TGroup array into a GroupJson array.
func formatGroupsJson(groups []*mdl.Tgroup) []GroupJson {

	groupsJson := make([]GroupJson, len(groups))
	for i, g := range groups {
		groupsJson[i].Name = g.Name
		teams := make([]TeamJson, len(g.Teams))
		for j, t := range g.Teams {
			teams[j].Name = t.Name
			teams[j].Points = g.Points[j]
			teams[j].GoalsF = g.GoalsF[j]
			teams[j].GoalsA = g.GoalsA[j]
			teams[j].Iso = t.Iso
		}
		groupsJson[i].Teams = teams
	}
	return groupsJson
}
<|endoftext|>


<commit_before><commit_msg>k8s: wait for k8s resources to be deleted in tests<commit_after><|endoftext|>


<commit_before>// Copyright 2013 Matthew Baird
// 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 elastigo

import (
	"encoding/json"
	"fmt"
	"strconv"
	"strings"
)

type BaseResponse struct {
	Ok      bool             `json:"ok"`
	Index   string           `json:"_index,omitempty"`
	Type    string           `json:"_type,omitempty"`
	Id      string           `json:"_id,omitempty"`
	Source  *json.RawMessage `json:"_source,omitempty"` // depends on the schema you've defined
	Version int              `json:"_version,omitempty"`
	Found   bool             `json:"found,omitempty"`
	Exists  bool             `json:"exists,omitempty"`
	Created bool             `json:"created,omitempty"`
	Matches []string         `json:"matches,omitempty"` // percolate matches
}

// StatusInt is required because /_optimize, at least, returns its status as
// strings instead of integers.
type StatusInt int

func (self *StatusInt) UnmarshalJSON(b []byte) error {
	s := ""
	if json.Unmarshal(b, &s) == nil {
		if i, err := strconv.Atoi(s); err == nil {
			*self = StatusInt(i)
			return nil
		}
	}
	i := 0
	err := json.Unmarshal(b, &i)
	if err == nil {
		*self = StatusInt(i)
	}
	return err
}

func (self *StatusInt) MarshalJSON() ([]byte, error) {
	return json.Marshal(*self)
}

// StatusBool is required because /_optimize, at least, returns its status as
// strings instead of booleans.
type StatusBool bool

func (self *StatusBool) UnmarshalJSON(b []byte) error {
	s := ""
	if json.Unmarshal(b, &s) == nil {
		switch s {
		case "true":
			*self = StatusBool(true)
			return nil
		case "false":
			*self = StatusBool(false)
			return nil
		default:
		}
	}
	b2 := false
	err := json.Unmarshal(b, &b2)
	if err == nil {
		*self = StatusBool(b2)
	}
	return err
}

func (self *StatusBool) MarshalJSON() ([]byte, error) {
	return json.Marshal(*self)
}

type Status struct {
	Total      StatusInt `json:"total"`
	Successful StatusInt `json:"successful"`
	Failed     StatusInt `json:"failed"`
	Failures   []Failure `json:"failures,omitempty"`
}

type Failure struct {
	Index  string    `json:"index"`
	Shard  StatusInt `json:"shard"`
	Reason string    `json:"reason"`
}

func (f Failure) String() string {
	return fmt.Sprintf("Failed on shard %d on index %s:\n%s", f.Shard, f.Index, f.Reason)
}

// failures is a convenience type to allow []Failure formated easily in the
// library
type failures []Failure

func (f failures) String() string {
	message := make([]string, len(f))
	for i, failure := range f {
		message[i] = failure.String()
	}
	return strings.Join(message, "\n")
}

type ExtendedStatus struct {
	Ok           StatusBool `json:"ok"`
	ShardsStatus Status     `json:"_shards"`
}

type Match struct {
	OK          bool         `json:"ok"`
	Matches     []string     `json:"matches"`
	Explanation *Explanation `json:"explanation,omitempty"`
}

type Explanation struct {
	Value       float32        `json:"value"`
	Description string         `json:"description"`
	Details     []*Explanation `json:"details,omitempty"`
}

func ScrollDuration(duration string) string {
	scrollString := ""
	if duration != "" {
		scrollString = "&scroll=" + duration
	}
	return scrollString
}

// http://www.elasticsearch.org/guide/reference/api/search/search-type/
<commit_msg>Partial Fix percolator result structure<commit_after>// Copyright 2013 Matthew Baird
// 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 elastigo

import (
	"encoding/json"
	"fmt"
	"strconv"
	"strings"
)

type BaseResponse struct {
	Ok      bool             `json:"ok"`
	Index   string           `json:"_index,omitempty"`
	Type    string           `json:"_type,omitempty"`
	Id      string           `json:"_id,omitempty"`
	Source  *json.RawMessage `json:"_source,omitempty"` // depends on the schema you've defined
	Version int              `json:"_version,omitempty"`
	Found   bool             `json:"found,omitempty"`
	Exists  bool             `json:"exists,omitempty"`
	Created bool             `json:"created,omitempty"`
	Matches []string         `json:"matches,omitempty"` // percolate matches
}

// StatusInt is required because /_optimize, at least, returns its status as
// strings instead of integers.
type StatusInt int

func (self *StatusInt) UnmarshalJSON(b []byte) error {
	s := ""
	if json.Unmarshal(b, &s) == nil {
		if i, err := strconv.Atoi(s); err == nil {
			*self = StatusInt(i)
			return nil
		}
	}
	i := 0
	err := json.Unmarshal(b, &i)
	if err == nil {
		*self = StatusInt(i)
	}
	return err
}

func (self *StatusInt) MarshalJSON() ([]byte, error) {
	return json.Marshal(*self)
}

// StatusBool is required because /_optimize, at least, returns its status as
// strings instead of booleans.
type StatusBool bool

func (self *StatusBool) UnmarshalJSON(b []byte) error {
	s := ""
	if json.Unmarshal(b, &s) == nil {
		switch s {
		case "true":
			*self = StatusBool(true)
			return nil
		case "false":
			*self = StatusBool(false)
			return nil
		default:
		}
	}
	b2 := false
	err := json.Unmarshal(b, &b2)
	if err == nil {
		*self = StatusBool(b2)
	}
	return err
}

func (self *StatusBool) MarshalJSON() ([]byte, error) {
	return json.Marshal(*self)
}

type Status struct {
	Total      StatusInt `json:"total"`
	Successful StatusInt `json:"successful"`
	Failed     StatusInt `json:"failed"`
	Failures   []Failure `json:"failures,omitempty"`
}

type Failure struct {
	Index  string    `json:"index"`
	Shard  StatusInt `json:"shard"`
	Reason string    `json:"reason"`
}

func (f Failure) String() string {
	return fmt.Sprintf("Failed on shard %d on index %s:\n%s", f.Shard, f.Index, f.Reason)
}

// failures is a convenience type to allow []Failure formated easily in the
// library
type failures []Failure

func (f failures) String() string {
	message := make([]string, len(f))
	for i, failure := range f {
		message[i] = failure.String()
	}
	return strings.Join(message, "\n")
}

type ExtendedStatus struct {
	Ok           StatusBool `json:"ok"`
	ShardsStatus Status     `json:"_shards"`
}

type MatchRes struct {
	Index string `json:"_index"`
	Id    string `json:"_id"`
}

type Match struct {
	OK          bool         `json:"ok"`
	Matches     []MatchRes   `json:"matches"`
	Explanation *Explanation `json:"explanation,omitempty"`
}

type Explanation struct {
	Value       float32        `json:"value"`
	Description string         `json:"description"`
	Details     []*Explanation `json:"details,omitempty"`
}

func ScrollDuration(duration string) string {
	scrollString := ""
	if duration != "" {
		scrollString = "&scroll=" + duration
	}
	return scrollString
}

// http://www.elasticsearch.org/guide/reference/api/search/search-type/
<|endoftext|>


<commit_before>package trace

import (
	"encoding/json"
	"net"
	"time"

	log "github.com/Sirupsen/logrus"
	"github.com/jonboulle/clockwork"
)

const (
	// UDPDefaultAddr is a default address to emit logs to
	UDPDefaultAddr = "127.0.0.1:5000"
	// UDPDefaultNet is a default network
	UDPDefaultNet = "udp"
)

// UDPOptionSetter represents functional arguments passed to ELKHook
type UDPOptionSetter func(f *UDPHook)

// NewUDPHook returns logrus-compatible hook that sends data to UDP socket
func NewUDPHook(opts ...UDPOptionSetter) (*UDPHook, error) {
	f := &UDPHook{}
	for _, o := range opts {
		o(f)
	}
	if f.Clock == nil {
		f.Clock = clockwork.NewRealClock()
	}
	if f.clientNet == "" {
		f.clientNet = UDPDefaultNet
	}
	if f.clientAddr == "" {
		f.clientAddr = UDPDefaultAddr
	}
	addr, err := net.ResolveUDPAddr(f.clientNet, f.clientAddr)
	if err != nil {
		return nil, Wrap(err)
	}
	conn, err := net.ListenPacket("udp", ":0")
	if err != nil {
		return nil, Wrap(err)
	}
	f.addr = addr
	f.conn = conn.(*net.UDPConn)
	return f, nil
}

type UDPHook struct {
	Clock      clockwork.Clock
	clientNet  string
	clientAddr string
	addr       *net.UDPAddr
	conn       *net.UDPConn
}

type Frame struct {
	Time    time.Time              `json:"time"`
	Type    string                 `json:"type"`
	Entry   map[string]interface{} `json:"entry"`
	Message string                 `json:"message"`
	Level   string                 `json:"level"`
}

// Fire fires the event to the ELK beat
func (elk *UDPHook) Fire(e *log.Entry) error {
	// Make a copy to safely modify
	entry := e.WithFields(nil)
	if frameNo := findFrame(); frameNo != -1 {
		t := newTrace(frameNo-1, nil)
		entry.Data[FileField] = t.String()
		entry.Data[FunctionField] = t.Func()
	}
	data, err := json.Marshal(Frame{
		Time:    elk.Clock.Now().UTC(),
		Type:    "trace",
		Entry:   entry.Data,
		Message: entry.Message,
		Level:   entry.Level.String(),
	})
	if err != nil {
		return Wrap(err)
	}

	c, err := net.ListenPacket("udp", ":0")
	if err != nil {
		return Wrap(err)
	}

	ra, err := net.ResolveUDPAddr("udp", "127.0.0.1:5000")
	if err != nil {
		return Wrap(err)
	}

	_, err = (c.(*net.UDPConn)).WriteToUDP(data, ra)
	return Wrap(err)

}

// Levels returns logging levels supported by logrus
func (elk *UDPHook) Levels() []log.Level {
	return []log.Level{
		log.PanicLevel,
		log.FatalLevel,
		log.ErrorLevel,
		log.WarnLevel,
		log.InfoLevel,
		log.DebugLevel,
	}
}
<commit_msg>Avoid leaking a connection on each UDPHook.Fire call<commit_after>package trace

import (
	"encoding/json"
	"net"
	"time"

	log "github.com/Sirupsen/logrus"
	"github.com/jonboulle/clockwork"
)

const (
	// UDPDefaultAddr is a default address to emit logs to
	UDPDefaultAddr = "127.0.0.1:5000"
	// UDPDefaultNet is a default network
	UDPDefaultNet = "udp"
)

// UDPOptionSetter represents functional arguments passed to ELKHook
type UDPOptionSetter func(f *UDPHook)

// NewUDPHook returns logrus-compatible hook that sends data to UDP socket
func NewUDPHook(opts ...UDPOptionSetter) (*UDPHook, error) {
	f := &UDPHook{}
	for _, o := range opts {
		o(f)
	}
	if f.Clock == nil {
		f.Clock = clockwork.NewRealClock()
	}
	if f.clientNet == "" {
		f.clientNet = UDPDefaultNet
	}
	if f.clientAddr == "" {
		f.clientAddr = UDPDefaultAddr
	}
	addr, err := net.ResolveUDPAddr(f.clientNet, f.clientAddr)
	if err != nil {
		return nil, Wrap(err)
	}
	conn, err := net.ListenPacket("udp", ":0")
	if err != nil {
		return nil, Wrap(err)
	}
	f.addr = addr
	f.conn = conn.(*net.UDPConn)
	return f, nil
}

type UDPHook struct {
	Clock      clockwork.Clock
	clientNet  string
	clientAddr string
	addr       *net.UDPAddr
	conn       *net.UDPConn
}

type Frame struct {
	Time    time.Time              `json:"time"`
	Type    string                 `json:"type"`
	Entry   map[string]interface{} `json:"entry"`
	Message string                 `json:"message"`
	Level   string                 `json:"level"`
}

// Fire fires the event to the ELK beat
func (elk *UDPHook) Fire(e *log.Entry) error {
	// Make a copy to safely modify
	entry := e.WithFields(nil)
	if frameNo := findFrame(); frameNo != -1 {
		t := newTrace(frameNo-1, nil)
		entry.Data[FileField] = t.String()
		entry.Data[FunctionField] = t.Func()
	}
	data, err := json.Marshal(Frame{
		Time:    elk.Clock.Now().UTC(),
		Type:    "trace",
		Entry:   entry.Data,
		Message: entry.Message,
		Level:   entry.Level.String(),
	})
	if err != nil {
		return Wrap(err)
	}

	conn, err := net.ListenPacket("udp", ":0")
	if err != nil {
		return Wrap(err)
	}
	defer conn.Close()

	resolvedAddr, err := net.ResolveUDPAddr("udp", "127.0.0.1:5000")
	if err != nil {
		return Wrap(err)
	}

	_, err = (c.(*net.UDPConn)).WriteToUDP(data, resolvedAddr)
	return Wrap(err)

}

// Levels returns logging levels supported by logrus
func (elk *UDPHook) Levels() []log.Level {
	return []log.Level{
		log.PanicLevel,
		log.FatalLevel,
		log.ErrorLevel,
		log.WarnLevel,
		log.InfoLevel,
		log.DebugLevel,
	}
}
<|endoftext|>


<commit_before>package discovery

import (
	"testing"

	"gopkg.in/redis.v3"

	pb "github.com/TheThingsNetwork/ttn/api/discovery"
	. "github.com/smartystreets/assertions"
)

func getRedisClient(db int64) *redis.Client {
	return redis.NewClient(&redis.Options{
		Addr:     "localhost:6379",
		Password: "", // no password set
		DB:       db, // use default DB
	})
}

func TestDiscoveryAnnounce(t *testing.T) {
	a := New(t)

	localDiscovery := &discovery{
		services: map[string]map[string]*pb.Announcement{},
	}

	client := getRedisClient(1)
	redisDiscovery := NewRedisDiscovery(client)
	defer func() {
		client.Del("service:broker:broker1.1")
		client.Del("service:broker:broker1.2")
	}()
	client.FlushAll()

	discoveries := map[string]Discovery{
		"local": localDiscovery,
		"redis": redisDiscovery,
	}

	for name, d := range discoveries {
		broker1a := &pb.Announcement{ServiceName: "broker", Id: "broker1.1", Token: "abcd", NetAddress: "current address"}
		broker1aNoToken := &pb.Announcement{ServiceName: "broker", Id: "broker1.1", NetAddress: "attacker address"}
		broker1b := &pb.Announcement{ServiceName: "broker", Id: "broker1.1", Token: "abcd", NetAddress: "updated address"}
		broker2 := &pb.Announcement{ServiceName: "broker", Id: "broker1.2", NetAddress: "other address"}

		t.Logf("Testing %s\n", name)

		err := d.Announce(broker1a)
		a.So(err, ShouldBeNil)

		err = d.Announce(broker1aNoToken)
		a.So(err, ShouldNotBeNil)

		services, err := d.Discover("broker")
		a.So(err, ShouldBeNil)
		a.So(services, ShouldHaveLength, 1)
		a.So(services[0].NetAddress, ShouldEqual, "current address")

		err = d.Announce(broker1b)
		a.So(err, ShouldBeNil)

		services, err = d.Discover("broker")
		a.So(err, ShouldBeNil)
		a.So(services, ShouldHaveLength, 1)
		a.So(services[0].NetAddress, ShouldEqual, "updated address")

		err = d.Announce(broker2)
		a.So(err, ShouldBeNil)

		services, err = d.Discover("broker")
		a.So(err, ShouldBeNil)
		a.So(services, ShouldHaveLength, 2)
	}

}

func TestDiscoveryDiscover(t *testing.T) {
	a := New(t)

	router := &pb.Announcement{ServiceName: "router", Id: "router2.0", Token: "abcd"}
	broker1 := &pb.Announcement{ServiceName: "broker", Id: "broker2.1"}
	broker2 := &pb.Announcement{ServiceName: "broker", Id: "broker2.2"}

	localDiscovery := &discovery{
		services: map[string]map[string]*pb.Announcement{
			"router": map[string]*pb.Announcement{
				"router": router,
			},
			"broker": map[string]*pb.Announcement{
				"broker1": broker1,
				"broker2": broker2,
			},
		},
	}

	client := getRedisClient(2)
	redisDiscovery := NewRedisDiscovery(client)
	defer func() {
		client.Del("service:router:router2.0")
		client.Del("service:broker:broker2.1")
		client.Del("service:broker:broker2.2")
	}()
	client.FlushAll()

	// This depends on the previous test to pass
	redisDiscovery.Announce(router)
	redisDiscovery.Announce(broker1)
	redisDiscovery.Announce(broker2)

	discoveries := map[string]Discovery{
		"local": localDiscovery,
		"redis": redisDiscovery,
	}

	for name, d := range discoveries {
		t.Logf("Testing %s\n", name)

		services, err := d.Discover("random")
		a.So(err, ShouldBeNil)
		a.So(services, ShouldBeEmpty)

		services, err = d.Discover("router")
		a.So(err, ShouldBeNil)
		a.So(services, ShouldHaveLength, 1)
		a.So(services[0].Id, ShouldEqual, router.Id)
		a.So(services[0].Token, ShouldBeEmpty)

		services, err = d.Discover("broker")
		a.So(err, ShouldBeNil)
		a.So(services, ShouldHaveLength, 2)

	}
}
<commit_msg>Stop flushing all DBs<commit_after>package discovery

import (
	"testing"

	"gopkg.in/redis.v3"

	pb "github.com/TheThingsNetwork/ttn/api/discovery"
	. "github.com/smartystreets/assertions"
)

func getRedisClient(db int64) *redis.Client {
	return redis.NewClient(&redis.Options{
		Addr:     "localhost:6379",
		Password: "", // no password set
		DB:       db, // use default DB
	})
}

func TestDiscoveryAnnounce(t *testing.T) {
	a := New(t)

	localDiscovery := &discovery{
		services: map[string]map[string]*pb.Announcement{},
	}

	client := getRedisClient(1)
	redisDiscovery := NewRedisDiscovery(client)
	defer func() {
		client.Del("service:broker:broker1.1")
		client.Del("service:broker:broker1.2")
	}()

	discoveries := map[string]Discovery{
		"local": localDiscovery,
		"redis": redisDiscovery,
	}

	for name, d := range discoveries {
		broker1a := &pb.Announcement{ServiceName: "broker", Id: "broker1.1", Token: "abcd", NetAddress: "current address"}
		broker1aNoToken := &pb.Announcement{ServiceName: "broker", Id: "broker1.1", NetAddress: "attacker address"}
		broker1b := &pb.Announcement{ServiceName: "broker", Id: "broker1.1", Token: "abcd", NetAddress: "updated address"}
		broker2 := &pb.Announcement{ServiceName: "broker", Id: "broker1.2", NetAddress: "other address"}

		t.Logf("Testing %s\n", name)

		err := d.Announce(broker1a)
		a.So(err, ShouldBeNil)

		err = d.Announce(broker1aNoToken)
		a.So(err, ShouldNotBeNil)

		services, err := d.Discover("broker")
		a.So(err, ShouldBeNil)
		a.So(services, ShouldHaveLength, 1)
		a.So(services[0].NetAddress, ShouldEqual, "current address")

		err = d.Announce(broker1b)
		a.So(err, ShouldBeNil)

		services, err = d.Discover("broker")
		a.So(err, ShouldBeNil)
		a.So(services, ShouldHaveLength, 1)
		a.So(services[0].NetAddress, ShouldEqual, "updated address")

		err = d.Announce(broker2)
		a.So(err, ShouldBeNil)

		services, err = d.Discover("broker")
		a.So(err, ShouldBeNil)
		a.So(services, ShouldHaveLength, 2)
	}

}

func TestDiscoveryDiscover(t *testing.T) {
	a := New(t)

	router := &pb.Announcement{ServiceName: "router", Id: "router2.0", Token: "abcd"}
	broker1 := &pb.Announcement{ServiceName: "broker", Id: "broker2.1"}
	broker2 := &pb.Announcement{ServiceName: "broker", Id: "broker2.2"}

	localDiscovery := &discovery{
		services: map[string]map[string]*pb.Announcement{
			"router": map[string]*pb.Announcement{
				"router": router,
			},
			"broker": map[string]*pb.Announcement{
				"broker1": broker1,
				"broker2": broker2,
			},
		},
	}

	client := getRedisClient(2)
	redisDiscovery := NewRedisDiscovery(client)
	defer func() {
		client.Del("service:router:router2.0")
		client.Del("service:broker:broker2.1")
		client.Del("service:broker:broker2.2")
	}()

	// This depends on the previous test to pass
	redisDiscovery.Announce(router)
	redisDiscovery.Announce(broker1)
	redisDiscovery.Announce(broker2)

	discoveries := map[string]Discovery{
		"local": localDiscovery,
		"redis": redisDiscovery,
	}

	for name, d := range discoveries {
		t.Logf("Testing %s\n", name)

		services, err := d.Discover("random")
		a.So(err, ShouldBeNil)
		a.So(services, ShouldBeEmpty)

		services, err = d.Discover("router")
		a.So(err, ShouldBeNil)
		a.So(services, ShouldHaveLength, 1)
		a.So(services[0].Id, ShouldEqual, router.Id)
		a.So(services[0].Token, ShouldBeEmpty)

		services, err = d.Discover("broker")
		a.So(err, ShouldBeNil)
		a.So(services, ShouldHaveLength, 2)

	}
}
<|endoftext|>


<commit_before>package aero_test

import (
	"net/http"
	"testing"

	"github.com/aerogo/aero"
	"github.com/stretchr/testify/assert"
)

func TestApplicationMiddleware(t *testing.T) {
	app := aero.New()

	// Register route
	app.Get("/", func(ctx *aero.Context) string {
		return ctx.Text(helloWorld)
	})

	// Register middleware
	app.Use(func(ctx *aero.Context, next func()) {
		ctx.StatusCode = http.StatusPermanentRedirect
		next()
	})

	// Get response
	response := request(app, "/")

	// Verify response
	assert.Equal(t, http.StatusPermanentRedirect, response.Code)
	assert.Equal(t, helloWorld, response.Body.String())
}

func TestApplicationMiddlewareSkipNext(t *testing.T) {
	app := aero.New()

	// Register route
	app.Get("/", func(ctx *aero.Context) string {
		return ctx.Text(helloWorld)
	})

	// Register middleware
	app.Use(func(ctx *aero.Context, next func()) {
		ctx.StatusCode = http.StatusUnauthorized
		// Not calling next() will stop the response chain
	})

	// Get response
	response := request(app, "/")

	// Verify response
	assert.Equal(t, "", response.Body.String())
}
<commit_msg>Minor test fix<commit_after>package aero_test

import (
	"net/http"
	"testing"

	"github.com/aerogo/aero"
	"github.com/stretchr/testify/assert"
)

func TestApplicationMiddleware(t *testing.T) {
	app := aero.New()

	// Register route
	app.Get("/", func(ctx *aero.Context) string {
		return ctx.Text(helloWorld)
	})

	// Register middleware
	app.Use(func(ctx *aero.Context, next func()) {
		ctx.StatusCode = http.StatusPermanentRedirect
		next()
	})

	// Get response
	response := request(app, "/")

	// Verify response
	assert.Equal(t, http.StatusPermanentRedirect, response.Code)
	assert.Equal(t, helloWorld, response.Body.String())
}

func TestApplicationMiddlewareSkipNext(t *testing.T) {
	app := aero.New()

	// Register route
	app.Get("/", func(ctx *aero.Context) string {
		return ctx.Text(helloWorld)
	})

	// Register middleware
	app.Use(func(ctx *aero.Context, next func()) {
		// Not calling next() will stop the response chain
	})

	// Get response
	response := request(app, "/")

	// Verify response
	assert.Equal(t, "", response.Body.String())
}
<|endoftext|>


<commit_before>package periodic

var Version = "0.1.5"
<commit_msg>set version 0.1.6<commit_after>package periodic

var Version = "0.1.6"
<|endoftext|>


<commit_before>package main

import "github.com/tsaikd/KDGoLib/version"

func init() {
	version.VERSION = "0.1.9"
	version.NAME = "gobuilder"
}
<commit_msg>0.2.0<commit_after>package main

import "github.com/tsaikd/KDGoLib/version"

func init() {
	version.NAME = "gobuilder"
	version.VERSION = "0.2.0"
}
<|endoftext|>


<commit_before>package specs

import "fmt"

const (
	// VersionMajor is for an API incompatible changes
	VersionMajor = 0
	// VersionMinor is for functionality in a backwards-compatible manner
	VersionMinor = 2
	// VersionPatch is for backwards-compatible bug fixes
	VersionPatch = 0

	// VersionDev indicates development branch. Releases will be empty string.
	VersionDev = ""
)

// Version is the specification version that the package types support.
var Version = fmt.Sprintf("%d.%d.%d%s", VersionMajor, VersionMinor, VersionPatch, VersionDev)
<commit_msg>version: bump v0.3.0-dev<commit_after>package specs

import "fmt"

const (
	// VersionMajor is for an API incompatible changes
	VersionMajor = 0
	// VersionMinor is for functionality in a backwards-compatible manner
	VersionMinor = 3
	// VersionPatch is for backwards-compatible bug fixes
	VersionPatch = 0

	// VersionDev indicates development branch. Releases will be empty string.
	VersionDev = "-dev"
)

// Version is the specification version that the package types support.
var Version = fmt.Sprintf("%d.%d.%d%s", VersionMajor, VersionMinor, VersionPatch, VersionDev)
<|endoftext|>


<commit_before>package test161

import (
	"fmt"
)

type ProgramVersion struct {
	Major    uint `yaml:"major"`
	Minor    uint `yaml:"minor"`
	Revision uint `yaml:"revision"`
}

var Version = ProgramVersion{
	Major:    1,
	Minor:    2,
	Revision: 4,
}

func (v ProgramVersion) String() string {
	return fmt.Sprintf("%v.%v.%v", v.Major, v.Minor, v.Revision)
}

// Returns 1 if this > other, 0 if this == other, and -1 if this < other
func (this ProgramVersion) CompareTo(other ProgramVersion) int {

	if this.Major > other.Major {
		return 1
	} else if this.Major < other.Major {
		return -1
	} else if this.Minor > other.Minor {
		return 1
	} else if this.Minor < other.Minor {
		return -1
	} else if this.Revision > other.Revision {
		return 1
	} else if this.Revision < other.Revision {
		return -1
	} else {
		return 0
	}

}
<commit_msg>Updated version to 1.2.5<commit_after>package test161

import (
	"fmt"
)

type ProgramVersion struct {
	Major    uint `yaml:"major"`
	Minor    uint `yaml:"minor"`
	Revision uint `yaml:"revision"`
}

var Version = ProgramVersion{
	Major:    1,
	Minor:    2,
	Revision: 5,
}

func (v ProgramVersion) String() string {
	return fmt.Sprintf("%v.%v.%v", v.Major, v.Minor, v.Revision)
}

// Returns 1 if this > other, 0 if this == other, and -1 if this < other
func (this ProgramVersion) CompareTo(other ProgramVersion) int {

	if this.Major > other.Major {
		return 1
	} else if this.Major < other.Major {
		return -1
	} else if this.Minor > other.Minor {
		return 1
	} else if this.Minor < other.Minor {
		return -1
	} else if this.Revision > other.Revision {
		return 1
	} else if this.Revision < other.Revision {
		return -1
	} else {
		return 0
	}

}
<|endoftext|>


<commit_before>package main

import (
	"context"
	"log"
	"net/http"
	"time"

	"github.com/google/go-github/github"
)

// githubTimeout defines how long to wait for a response from GitHub
// when checking for new SAM Local versions.
const githubTimeout = 3

// checkVersionResult contains information on the current version of AWS SAM CLI, and
// whether there are any newer versions available to upgrade to.
type checkVersionResult struct {
	IsUpToDate    bool
	LatestVersion string
}

// checkVersion checks whether the current version of AWS SAM CLI is the latest
func checkVersion() (*checkVersionResult, error) {

	const RepoOwner = "awslabs"
	const RepoName = "aws-sam-local"

	// Create a HTTP client with appropriate timeouts configured
	client := &http.Client{
		Timeout: time.Duration(githubTimeout * time.Second),
	}

	// Get the latest version details from Github release
	gh := github.NewClient(client)
	releases, _, err := gh.Repositories.ListReleases(context.Background(), RepoOwner, RepoName, nil)
	if err != nil {
		return &checkVersionResult{}, err
	}

	// Grab the latest release - without the first 'v' character from the tag
	// ie. v0.0.1 -> 0.0.1
	latest := releases[0]
	latestVersion := (*latest.TagName)[1:]
	log.Print(latestVersion)

	return &checkVersionResult{
		LatestVersion: latestVersion,
		IsUpToDate:    version == latestVersion,
	}, nil

}
<commit_msg>Fixing debug log print when checking package version. Fixes #11<commit_after>package main

import (
	"context"
	"net/http"
	"time"

	"github.com/google/go-github/github"
)

// githubTimeout defines how long to wait for a response from GitHub
// when checking for new SAM Local versions.
const githubTimeout = 3

// checkVersionResult contains information on the current version of AWS SAM CLI, and
// whether there are any newer versions available to upgrade to.
type checkVersionResult struct {
	IsUpToDate    bool
	LatestVersion string
}

// checkVersion checks whether the current version of AWS SAM CLI is the latest
func checkVersion() (*checkVersionResult, error) {

	const RepoOwner = "awslabs"
	const RepoName = "aws-sam-local"

	// Create a HTTP client with appropriate timeouts configured
	client := &http.Client{
		Timeout: time.Duration(githubTimeout * time.Second),
	}

	// Get the latest version details from Github release
	gh := github.NewClient(client)
	releases, _, err := gh.Repositories.ListReleases(context.Background(), RepoOwner, RepoName, nil)
	if err != nil || len(releases) == 0 {
		return &checkVersionResult{}, err
	}

	// Grab the latest release - without the first 'v' character from the tag
	// ie. v0.0.1 -> 0.0.1
	latest := releases[0]
	latestVersion := (*latest.TagName)[1:]

	return &checkVersionResult{
		LatestVersion: latestVersion,
		IsUpToDate:    version == latestVersion,
	}, nil

}
<|endoftext|>


<commit_before>// Copyright 2018 The Moov Authors
// Use of this source code is governed by an Apache License
// license that can be found in the LICENSE file.

package ach

const Version = "v0.4.0"
<commit_msg>bump version for dev<commit_after>// Copyright 2018 The Moov Authors
// Use of this source code is governed by an Apache License
// license that can be found in the LICENSE file.

package ach

const Version = "v0.4.1-dev"
<|endoftext|>


<commit_before>package transloadit

// Go SDK's version
var Version = "v0.1.7"
<commit_msg>bump version to v0.1.8<commit_after>package transloadit

// Go SDK's version
var Version = "v0.1.8"
<|endoftext|>


<commit_before>package gitbook

const (
	VERSION = "1.0.0"
)
<commit_msg>Bump version to 1.0.1<commit_after>package gitbook

const (
	VERSION = "1.0.1"
)
<|endoftext|>


<commit_before>package dns

import "fmt"

// Version is current version of this library.
var Version = v{1, 1, 35}

// v holds the version of this library.
type v struct {
	Major, Minor, Patch int
}

func (v v) String() string {
	return fmt.Sprintf("%d.%d.%d", v.Major, v.Minor, v.Patch)
}
<commit_msg>Release 1.1.36<commit_after>package dns

import "fmt"

// Version is current version of this library.
var Version = v{1, 1, 36}

// v holds the version of this library.
type v struct {
	Major, Minor, Patch int
}

func (v v) String() string {
	return fmt.Sprintf("%d.%d.%d", v.Major, v.Minor, v.Patch)
}
<|endoftext|>


<commit_before>package dns

import "fmt"

// Version is current version of this library.
var Version = V{1, 1, 10}

// V holds the version of this library.
type V struct {
	Major, Minor, Patch int
}

func (v V) String() string {
	return fmt.Sprintf("%d.%d.%d", v.Major, v.Minor, v.Patch)
}
<commit_msg>Release 1.1.11<commit_after>package dns

import "fmt"

// Version is current version of this library.
var Version = V{1, 1, 11}

// V holds the version of this library.
type V struct {
	Major, Minor, Patch int
}

func (v V) String() string {
	return fmt.Sprintf("%d.%d.%d", v.Major, v.Minor, v.Patch)
}
<|endoftext|>


<commit_before>package main

var version = "0.4.2"
<commit_msg>bump version<commit_after>package main

var version = "0.4.3"
<|endoftext|>


<commit_before>package sdk

const VERSION = "8.2.1"
<commit_msg>Incremented version.<commit_after>package sdk

const VERSION = "8.2.2"
<|endoftext|>


<commit_before>package veille

import (
    "fmt"
    "io/ioutil"
    "os"
    "log"

    "launchpad.net/goyaml"
)

type ConfigLoader interface {
    GetConfig() (*Config, error)
    ReloadConfig() (*Config, error)
}

type MockConfigLoader struct {
    Config *Config
}
func (loader *MockConfigLoader) GetConfig() (*Config, error) {
    return loader.Config, nil
}
func (loader *MockConfigLoader) ReloadConfig() (*Config, error) {
    return loader.Config, nil
}

type Config struct {
    Services []ServiceConfig
}
type ServiceConfig struct {
    Service_Name string
    Tests []TestConfig
}
type TestConfig struct {
    Functionality string
    Script string
    Run_Every int
    Alert_After int
    Alert AlertConfig
}
type AlertConfig struct {
    Mode string
    Target string
}

type ConfigError struct { msg string }
func (e ConfigError) Error() string { return "Config error: " + e.msg }

// Sends notifications on channels whenever the config changes.
type ConfigWatcher struct {
    Loader ConfigLoader
    outputChans []chan *Config
}
func (cw *ConfigWatcher) Subscribe() chan *Config {
    ch := make(chan *Config)
    cw.outputChans = append(cw.outputChans, ch)
    return ch
}
func (cw *ConfigWatcher) Publish(c *Config) {
    log.Println("Notifying", len(cw.outputChans), "goroutines of config reload")
    for _, ch := range cw.outputChans {
        go func() {ch <- c}()
    }
}
// Returns a channel that can be registered with signal.Notify to make
// the ConfigWatcher publish whenever a signal is received.
//
// e.g.
//
//     signal.Notify(cw.PublishOnSignals(), syscall.SIGHUP)
func (cw *ConfigWatcher) PublishOnSignals() (chan os.Signal) {
    ch := make(chan os.Signal)
    go func() {
        for {
            <- ch
            fmt.Println("Alpha")
            conf, err := cw.Loader.ReloadConfig()
            if err != nil {
                fmt.Println("Received a SIGHUP, but failed to parse config: " + err.Error())
            }
            cw.Publish(conf)
        }
    }()
    return ch
}

// A ConfigLoader that loads from a YAML file.
//
// Must be initialized with SetPath() before you can load anything.
type YamlFileConfigLoader struct {
    Path string
    cachedConfig *Config
}

// Returns the active configuration.
func (loader *YamlFileConfigLoader) GetConfig() (*Config, error) {
    if loader.cachedConfig == nil {
        cc, err := loader.parseFile(loader.Path)
        if err != nil { return nil, err }
        loader.cachedConfig = cc
    }
    return loader.cachedConfig, nil
}

// Returns the active configuration.
func (loader *YamlFileConfigLoader) ReloadConfig() (*Config, error) {
    return nil, nil
}

// Reads the YAML file and returns the parsed Config.
func (loader *YamlFileConfigLoader) parseFile(path string) (*Config, error) {
    conf := new(Config)
    yBlob, err := ioutil.ReadFile(path)
    if err != nil { return nil, err }
    err = goyaml.Unmarshal(yBlob, conf)
    if err != nil { return nil, err }
    return conf, nil
}
<commit_msg>Removed debug line<commit_after>package veille

import (
    "fmt"
    "io/ioutil"
    "os"
    "log"

    "launchpad.net/goyaml"
)

type ConfigLoader interface {
    GetConfig() (*Config, error)
    ReloadConfig() (*Config, error)
}

type MockConfigLoader struct {
    Config *Config
}
func (loader *MockConfigLoader) GetConfig() (*Config, error) {
    return loader.Config, nil
}
func (loader *MockConfigLoader) ReloadConfig() (*Config, error) {
    return loader.Config, nil
}

type Config struct {
    Services []ServiceConfig
}
type ServiceConfig struct {
    Service_Name string
    Tests []TestConfig
}
type TestConfig struct {
    Functionality string
    Script string
    Run_Every int
    Alert_After int
    Alert AlertConfig
}
type AlertConfig struct {
    Mode string
    Target string
}

type ConfigError struct { msg string }
func (e ConfigError) Error() string { return "Config error: " + e.msg }

// Sends notifications on channels whenever the config changes.
type ConfigWatcher struct {
    Loader ConfigLoader
    outputChans []chan *Config
}
func (cw *ConfigWatcher) Subscribe() chan *Config {
    ch := make(chan *Config)
    cw.outputChans = append(cw.outputChans, ch)
    return ch
}
func (cw *ConfigWatcher) Publish(c *Config) {
    log.Println("Notifying", len(cw.outputChans), "goroutines of config reload")
    for _, ch := range cw.outputChans {
        go func() {ch <- c}()
    }
}
// Returns a channel that can be registered with signal.Notify to make
// the ConfigWatcher publish whenever a signal is received.
//
// e.g.
//
//     signal.Notify(cw.PublishOnSignals(), syscall.SIGHUP)
func (cw *ConfigWatcher) PublishOnSignals() (chan os.Signal) {
    ch := make(chan os.Signal)
    go func() {
        for {
            <- ch
            conf, err := cw.Loader.ReloadConfig()
            if err != nil {
                fmt.Println("Received a SIGHUP, but failed to parse config: " + err.Error())
            }
            cw.Publish(conf)
        }
    }()
    return ch
}

// A ConfigLoader that loads from a YAML file.
//
// Must be initialized with SetPath() before you can load anything.
type YamlFileConfigLoader struct {
    Path string
    cachedConfig *Config
}

// Returns the active configuration.
func (loader *YamlFileConfigLoader) GetConfig() (*Config, error) {
    if loader.cachedConfig == nil {
        cc, err := loader.parseFile(loader.Path)
        if err != nil { return nil, err }
        loader.cachedConfig = cc
    }
    return loader.cachedConfig, nil
}

// Returns the active configuration.
func (loader *YamlFileConfigLoader) ReloadConfig() (*Config, error) {
    return nil, nil
}

// Reads the YAML file and returns the parsed Config.
func (loader *YamlFileConfigLoader) parseFile(path string) (*Config, error) {
    conf := new(Config)
    yBlob, err := ioutil.ReadFile(path)
    if err != nil { return nil, err }
    err = goyaml.Unmarshal(yBlob, conf)
    if err != nil { return nil, err }
    return conf, nil
}
<|endoftext|>


<commit_before>package lib

import (
	"bytes"
	"io/ioutil"

	"github.com/BurntSushi/toml"
	"github.com/containers/image/pkg/sysregistries"
	"github.com/containers/image/types"
	"github.com/containers/storage"
	"github.com/kubernetes-incubator/cri-o/oci"
)

// Default paths if none are specified
const (
	conmonPath          = "/usr/local/libexec/crio/conmon"
	pauseImage          = "kubernetes/pause"
	pauseCommand        = "/pause"
	defaultTransport    = "docker://"
	seccompProfilePath  = "/etc/crio/seccomp.json"
	apparmorProfileName = "crio-default"
	cniConfigDir        = "/etc/cni/net.d/"
	cniBinDir           = "/opt/cni/bin/"
	cgroupManager       = oci.CgroupfsCgroupsManager
	lockPath            = "/run/crio.lock"
	containerExitsDir   = oci.ContainerExitsDir
)

// Config represents the entire set of configuration values that can be set for
// the server. This is intended to be loaded from a toml-encoded config file.
type Config struct {
	RootConfig
	RuntimeConfig
	ImageConfig
	NetworkConfig
}

// ImageVolumesType describes image volume handling strategies
type ImageVolumesType string

const (
	// ImageVolumesMkdir option is for using mkdir to handle image volumes
	ImageVolumesMkdir ImageVolumesType = "mkdir"
	// ImageVolumesIgnore option is for ignoring image volumes altogether
	ImageVolumesIgnore ImageVolumesType = "ignore"
	// ImageVolumesBind option is for using bind mounted volumes
	ImageVolumesBind ImageVolumesType = "bind"
)

const (
	// DefaultPidsLimit is the default value for maximum number of processes
	// allowed inside a container
	DefaultPidsLimit = 1024

	// DefaultLogSizeMax is the default value for the maximum log size
	// allowed for a container. Negative values mean that no limit is imposed.
	DefaultLogSizeMax = -1
)

// DefaultCapabilities for the capabilities option in the crio.conf file
var DefaultCapabilities = []string{
	"CHOWN",
	"DAC_OVERRIDE",
	"FSETID",
	"FOWNER",
	"NET_RAW",
	"SETGID",
	"SETUID",
	"SETPCAP",
	"NET_BIND_SERVICE",
	"SYS_CHROOT",
	"KILL",
}

// This structure is necessary to fake the TOML tables when parsing,
// while also not requiring a bunch of layered structs for no good
// reason.

// RootConfig represents the root of the "crio" TOML config table.
type RootConfig struct {
	// Root is a path to the "root directory" where data not
	// explicitly handled by other options will be stored.
	Root string `toml:"root"`

	// RunRoot is a path to the "run directory" where state information not
	// explicitly handled by other options will be stored.
	RunRoot string `toml:"runroot"`

	// Storage is the name of the storage driver which handles actually
	// storing the contents of containers.
	Storage string `toml:"storage_driver"`

	// StorageOption is a list of storage driver specific options.
	StorageOptions []string `toml:"storage_option"`

	// LogDir is the default log directory were all logs will go unless kubelet
	// tells us to put them somewhere else.
	LogDir string `toml:"log_dir"`

	// FileLocking specifies whether to use file-based or in-memory locking
	// File-based locking is required when multiple users of lib are
	// present on the same system
	FileLocking bool `toml:"file_locking"`
}

// RuntimeConfig represents the "crio.runtime" TOML config table.
type RuntimeConfig struct {
	// Runtime is the OCI compatible runtime used for trusted container workloads.
	// This is a mandatory setting as this runtime will be the default one and
	// will also be used for untrusted container workloads if
	// RuntimeUntrustedWorkload is not set.
	Runtime string `toml:"runtime"`

	// RuntimeUntrustedWorkload is the OCI compatible runtime used for untrusted
	// container workloads. This is an optional setting, except if
	// DefaultWorkloadTrust is set to "untrusted".
	RuntimeUntrustedWorkload string `toml:"runtime_untrusted_workload"`

	// DefaultWorkloadTrust is the default level of trust crio puts in container
	// workloads. This can either be "trusted" or "untrusted" and the default
	// is "trusted"
	// Containers can be run through different container runtimes, depending on
	// the trust hints we receive from kubelet:
	// - If kubelet tags a container workload as untrusted, crio will try first
	// to run it through the untrusted container workload runtime. If it is not
	// set, crio will use the trusted runtime.
	// - If kubelet does not provide any information about the container workload trust
	// level, the selected runtime will depend on the DefaultWorkloadTrust setting.
	// If it is set to "untrusted", then all containers except for the host privileged
	// ones, will be run by the RuntimeUntrustedWorkload runtime. Host privileged
	// containers are by definition trusted and will always use the trusted container
	// runtime. If DefaultWorkloadTrust is set to "trusted", crio will use the trusted
	// container runtime for all containers.
	DefaultWorkloadTrust string `toml:"default_workload_trust"`

	// NoPivot instructs the runtime to not use `pivot_root`, but instead use `MS_MOVE`
	NoPivot bool `toml:"no_pivot"`

	// Conmon is the path to conmon binary, used for managing the runtime.
	Conmon string `toml:"conmon"`

	// ConmonEnv is the environment variable list for conmon process.
	ConmonEnv []string `toml:"conmon_env"`

	// SELinux determines whether or not SELinux is used for pod separation.
	SELinux bool `toml:"selinux"`

	// SeccompProfile is the seccomp json profile path which is used as the
	// default for the runtime.
	SeccompProfile string `toml:"seccomp_profile"`

	// ApparmorProfile is the apparmor profile name which is used as the
	// default for the runtime.
	ApparmorProfile string `toml:"apparmor_profile"`

	// CgroupManager is the manager implementation name which is used to
	// handle cgroups for containers.
	CgroupManager string `toml:"cgroup_manager"`

	// HooksDirPath location of oci hooks config files
	HooksDirPath string `toml:"hooks_dir_path"`

	// DefaultMounts is the list of mounts to be mounted for each container
	// The format of each mount is "host-path:container-path"
	DefaultMounts []string `toml:"default_mounts"`

	// DefaultMountsFile is the file path for the default mounts to be mounted for the container
	// Note, for testing purposes mainly
	DefaultMountsFile string `toml:"default_mounts_file"`

	// Hooks List of hooks to run with container
	Hooks map[string]HookParams

	// PidsLimit is the number of processes each container is restricted to
	// by the cgroup process number controller.
	PidsLimit int64 `toml:"pids_limit"`

	// LogSizeMax is the maximum number of bytes after which the log file
	// will be truncated. It can be expressed as a human-friendly string
	// that is parsed to bytes.
	// Negative values indicate that the log file won't be truncated.
	LogSizeMax int64 `toml:"log_size_max"`

	// ContainerExitsDir is the directory in which container exit files are
	// written to by conmon.
	ContainerExitsDir string `toml:"container_exits_dir"`

	// ManageNetworkNSLifecycle determines whether we pin and remove network namespace
	// and manage its lifecycle
	ManageNetworkNSLifecycle bool `toml:"manage_network_ns_lifecycle"`

	// ReadOnly run all pods/containers in read-only mode.
	// This mode will mount tmpfs on /run, /tmp and /var/tmp, if those are not mountpoints
	// Will also set the readonly flag in the OCI Runtime Spec.  In this mode containers
	// will only be able to write to volumes mounted into them
	ReadOnly bool `toml:"read_only"`

	// BindMountPrefix is the prefix to use for the source of the bind mounts.
	BindMountPrefix string `toml:"bind_mount_prefix"`

	// UIDMappings specifies the UID mappings to have in the user namespace.
	// A range is specified in the form containerUID:HostUID:Size.  Multiple
	// ranges are separed by comma.
	UIDMappings string `toml:"uid_mappings"`

	// GIDMappings specifies the GID mappings to have in the user namespace.
	// A range is specified in the form containerUID:HostUID:Size.  Multiple
	// ranges are separed by comma.
	GIDMappings string `toml:"gid_mappings"`

	// Capabilities to add to all containers.
	DefaultCapabilities []string `toml:"default_capabilities"`
}

// ImageConfig represents the "crio.image" TOML config table.
type ImageConfig struct {
	// DefaultTransport is a value we prefix to image names that fail to
	// validate source references.
	DefaultTransport string `toml:"default_transport"`
	// PauseImage is the name of an image which we use to instantiate infra
	// containers.
	PauseImage string `toml:"pause_image"`
	// PauseCommand is the path of the binary we run in an infra
	// container that's been instantiated using PauseImage.
	PauseCommand string `toml:"pause_command"`
	// SignaturePolicyPath is the name of the file which decides what sort
	// of policy we use when deciding whether or not to trust an image that
	// we've pulled.  Outside of testing situations, it is strongly advised
	// that this be left unspecified so that the default system-wide policy
	// will be used.
	SignaturePolicyPath string `toml:"signature_policy"`
	// InsecureRegistries is a list of registries that must be contacted w/o
	// TLS verification.
	InsecureRegistries []string `toml:"insecure_registries"`
	// ImageVolumes controls how volumes specified in image config are handled
	ImageVolumes ImageVolumesType `toml:"image_volumes"`
	// Registries holds a list of registries used to pull unqualified images
	Registries []string `toml:"registries"`
}

// NetworkConfig represents the "crio.network" TOML config table
type NetworkConfig struct {
	// NetworkDir is where CNI network configuration files are stored.
	NetworkDir string `toml:"network_dir"`

	// PluginDir is where CNI plugin binaries are stored.
	PluginDir string `toml:"plugin_dir"`
}

// tomlConfig is another way of looking at a Config, which is
// TOML-friendly (it has all of the explicit tables). It's just used for
// conversions.
type tomlConfig struct {
	Crio struct {
		RootConfig
		Runtime struct{ RuntimeConfig } `toml:"runtime"`
		Image   struct{ ImageConfig }   `toml:"image"`
		Network struct{ NetworkConfig } `toml:"network"`
	} `toml:"crio"`
}

func (t *tomlConfig) toConfig(c *Config) {
	c.RootConfig = t.Crio.RootConfig
	c.RuntimeConfig = t.Crio.Runtime.RuntimeConfig
	c.ImageConfig = t.Crio.Image.ImageConfig
	c.NetworkConfig = t.Crio.Network.NetworkConfig
}

func (t *tomlConfig) fromConfig(c *Config) {
	t.Crio.RootConfig = c.RootConfig
	t.Crio.Runtime.RuntimeConfig = c.RuntimeConfig
	t.Crio.Image.ImageConfig = c.ImageConfig
	t.Crio.Network.NetworkConfig = c.NetworkConfig
}

// UpdateFromFile populates the Config from the TOML-encoded file at the given path.
// Returns errors encountered when reading or parsing the files, or nil
// otherwise.
func (c *Config) UpdateFromFile(path string) error {
	data, err := ioutil.ReadFile(path)
	if err != nil {
		return err
	}

	t := new(tomlConfig)
	t.fromConfig(c)

	_, err = toml.Decode(string(data), t)
	if err != nil {
		return err
	}

	t.toConfig(c)
	return nil
}

// ToFile outputs the given Config as a TOML-encoded file at the given path.
// Returns errors encountered when generating or writing the file, or nil
// otherwise.
func (c *Config) ToFile(path string) error {
	var w bytes.Buffer
	e := toml.NewEncoder(&w)

	t := new(tomlConfig)
	t.fromConfig(c)

	if err := e.Encode(*t); err != nil {
		return err
	}

	return ioutil.WriteFile(path, w.Bytes(), 0644)
}

// DefaultConfig returns the default configuration for crio.
func DefaultConfig() *Config {
	registries, _ := sysregistries.GetRegistries(&types.SystemContext{})
	insecureRegistries, _ := sysregistries.GetInsecureRegistries(&types.SystemContext{})
	return &Config{
		RootConfig: RootConfig{
			Root:           storage.DefaultStoreOptions.GraphRoot,
			RunRoot:        storage.DefaultStoreOptions.RunRoot,
			Storage:        storage.DefaultStoreOptions.GraphDriverName,
			StorageOptions: storage.DefaultStoreOptions.GraphDriverOptions,
			LogDir:         "/var/log/crio/pods",
			FileLocking:    true,
		},
		RuntimeConfig: RuntimeConfig{
			Runtime:                  "/usr/bin/runc",
			RuntimeUntrustedWorkload: "",
			DefaultWorkloadTrust:     "trusted",

			Conmon: conmonPath,
			ConmonEnv: []string{
				"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
			},
			SELinux:             selinuxEnabled(),
			SeccompProfile:      seccompProfilePath,
			ApparmorProfile:     apparmorProfileName,
			CgroupManager:       cgroupManager,
			PidsLimit:           DefaultPidsLimit,
			ContainerExitsDir:   containerExitsDir,
			HooksDirPath:        DefaultHooksDirPath,
			LogSizeMax:          DefaultLogSizeMax,
			DefaultMountsFile:   "",
			DefaultCapabilities: DefaultCapabilities,
		},
		ImageConfig: ImageConfig{
			DefaultTransport:    defaultTransport,
			PauseImage:          pauseImage,
			PauseCommand:        pauseCommand,
			SignaturePolicyPath: "",
			ImageVolumes:        ImageVolumesMkdir,
			Registries:          registries,
			InsecureRegistries:  insecureRegistries,
		},
		NetworkConfig: NetworkConfig{
			NetworkDir: cniConfigDir,
			PluginDir:  cniBinDir,
		},
	}
}
<commit_msg>lib: config: use official kube pause image from gcr<commit_after>package lib

import (
	"bytes"
	"io/ioutil"

	"github.com/BurntSushi/toml"
	"github.com/containers/image/pkg/sysregistries"
	"github.com/containers/image/types"
	"github.com/containers/storage"
	"github.com/kubernetes-incubator/cri-o/oci"
)

// Default paths if none are specified
const (
	conmonPath          = "/usr/local/libexec/crio/conmon"
	pauseImage          = "k8s.gcr.io/pause:3.1"
	pauseCommand        = "/pause"
	defaultTransport    = "docker://"
	seccompProfilePath  = "/etc/crio/seccomp.json"
	apparmorProfileName = "crio-default"
	cniConfigDir        = "/etc/cni/net.d/"
	cniBinDir           = "/opt/cni/bin/"
	cgroupManager       = oci.CgroupfsCgroupsManager
	lockPath            = "/run/crio.lock"
	containerExitsDir   = oci.ContainerExitsDir
)

// Config represents the entire set of configuration values that can be set for
// the server. This is intended to be loaded from a toml-encoded config file.
type Config struct {
	RootConfig
	RuntimeConfig
	ImageConfig
	NetworkConfig
}

// ImageVolumesType describes image volume handling strategies
type ImageVolumesType string

const (
	// ImageVolumesMkdir option is for using mkdir to handle image volumes
	ImageVolumesMkdir ImageVolumesType = "mkdir"
	// ImageVolumesIgnore option is for ignoring image volumes altogether
	ImageVolumesIgnore ImageVolumesType = "ignore"
	// ImageVolumesBind option is for using bind mounted volumes
	ImageVolumesBind ImageVolumesType = "bind"
)

const (
	// DefaultPidsLimit is the default value for maximum number of processes
	// allowed inside a container
	DefaultPidsLimit = 1024

	// DefaultLogSizeMax is the default value for the maximum log size
	// allowed for a container. Negative values mean that no limit is imposed.
	DefaultLogSizeMax = -1
)

// DefaultCapabilities for the capabilities option in the crio.conf file
var DefaultCapabilities = []string{
	"CHOWN",
	"DAC_OVERRIDE",
	"FSETID",
	"FOWNER",
	"NET_RAW",
	"SETGID",
	"SETUID",
	"SETPCAP",
	"NET_BIND_SERVICE",
	"SYS_CHROOT",
	"KILL",
}

// This structure is necessary to fake the TOML tables when parsing,
// while also not requiring a bunch of layered structs for no good
// reason.

// RootConfig represents the root of the "crio" TOML config table.
type RootConfig struct {
	// Root is a path to the "root directory" where data not
	// explicitly handled by other options will be stored.
	Root string `toml:"root"`

	// RunRoot is a path to the "run directory" where state information not
	// explicitly handled by other options will be stored.
	RunRoot string `toml:"runroot"`

	// Storage is the name of the storage driver which handles actually
	// storing the contents of containers.
	Storage string `toml:"storage_driver"`

	// StorageOption is a list of storage driver specific options.
	StorageOptions []string `toml:"storage_option"`

	// LogDir is the default log directory were all logs will go unless kubelet
	// tells us to put them somewhere else.
	LogDir string `toml:"log_dir"`

	// FileLocking specifies whether to use file-based or in-memory locking
	// File-based locking is required when multiple users of lib are
	// present on the same system
	FileLocking bool `toml:"file_locking"`
}

// RuntimeConfig represents the "crio.runtime" TOML config table.
type RuntimeConfig struct {
	// Runtime is the OCI compatible runtime used for trusted container workloads.
	// This is a mandatory setting as this runtime will be the default one and
	// will also be used for untrusted container workloads if
	// RuntimeUntrustedWorkload is not set.
	Runtime string `toml:"runtime"`

	// RuntimeUntrustedWorkload is the OCI compatible runtime used for untrusted
	// container workloads. This is an optional setting, except if
	// DefaultWorkloadTrust is set to "untrusted".
	RuntimeUntrustedWorkload string `toml:"runtime_untrusted_workload"`

	// DefaultWorkloadTrust is the default level of trust crio puts in container
	// workloads. This can either be "trusted" or "untrusted" and the default
	// is "trusted"
	// Containers can be run through different container runtimes, depending on
	// the trust hints we receive from kubelet:
	// - If kubelet tags a container workload as untrusted, crio will try first
	// to run it through the untrusted container workload runtime. If it is not
	// set, crio will use the trusted runtime.
	// - If kubelet does not provide any information about the container workload trust
	// level, the selected runtime will depend on the DefaultWorkloadTrust setting.
	// If it is set to "untrusted", then all containers except for the host privileged
	// ones, will be run by the RuntimeUntrustedWorkload runtime. Host privileged
	// containers are by definition trusted and will always use the trusted container
	// runtime. If DefaultWorkloadTrust is set to "trusted", crio will use the trusted
	// container runtime for all containers.
	DefaultWorkloadTrust string `toml:"default_workload_trust"`

	// NoPivot instructs the runtime to not use `pivot_root`, but instead use `MS_MOVE`
	NoPivot bool `toml:"no_pivot"`

	// Conmon is the path to conmon binary, used for managing the runtime.
	Conmon string `toml:"conmon"`

	// ConmonEnv is the environment variable list for conmon process.
	ConmonEnv []string `toml:"conmon_env"`

	// SELinux determines whether or not SELinux is used for pod separation.
	SELinux bool `toml:"selinux"`

	// SeccompProfile is the seccomp json profile path which is used as the
	// default for the runtime.
	SeccompProfile string `toml:"seccomp_profile"`

	// ApparmorProfile is the apparmor profile name which is used as the
	// default for the runtime.
	ApparmorProfile string `toml:"apparmor_profile"`

	// CgroupManager is the manager implementation name which is used to
	// handle cgroups for containers.
	CgroupManager string `toml:"cgroup_manager"`

	// HooksDirPath location of oci hooks config files
	HooksDirPath string `toml:"hooks_dir_path"`

	// DefaultMounts is the list of mounts to be mounted for each container
	// The format of each mount is "host-path:container-path"
	DefaultMounts []string `toml:"default_mounts"`

	// DefaultMountsFile is the file path for the default mounts to be mounted for the container
	// Note, for testing purposes mainly
	DefaultMountsFile string `toml:"default_mounts_file"`

	// Hooks List of hooks to run with container
	Hooks map[string]HookParams

	// PidsLimit is the number of processes each container is restricted to
	// by the cgroup process number controller.
	PidsLimit int64 `toml:"pids_limit"`

	// LogSizeMax is the maximum number of bytes after which the log file
	// will be truncated. It can be expressed as a human-friendly string
	// that is parsed to bytes.
	// Negative values indicate that the log file won't be truncated.
	LogSizeMax int64 `toml:"log_size_max"`

	// ContainerExitsDir is the directory in which container exit files are
	// written to by conmon.
	ContainerExitsDir string `toml:"container_exits_dir"`

	// ManageNetworkNSLifecycle determines whether we pin and remove network namespace
	// and manage its lifecycle
	ManageNetworkNSLifecycle bool `toml:"manage_network_ns_lifecycle"`

	// ReadOnly run all pods/containers in read-only mode.
	// This mode will mount tmpfs on /run, /tmp and /var/tmp, if those are not mountpoints
	// Will also set the readonly flag in the OCI Runtime Spec.  In this mode containers
	// will only be able to write to volumes mounted into them
	ReadOnly bool `toml:"read_only"`

	// BindMountPrefix is the prefix to use for the source of the bind mounts.
	BindMountPrefix string `toml:"bind_mount_prefix"`

	// UIDMappings specifies the UID mappings to have in the user namespace.
	// A range is specified in the form containerUID:HostUID:Size.  Multiple
	// ranges are separed by comma.
	UIDMappings string `toml:"uid_mappings"`

	// GIDMappings specifies the GID mappings to have in the user namespace.
	// A range is specified in the form containerUID:HostUID:Size.  Multiple
	// ranges are separed by comma.
	GIDMappings string `toml:"gid_mappings"`

	// Capabilities to add to all containers.
	DefaultCapabilities []string `toml:"default_capabilities"`
}

// ImageConfig represents the "crio.image" TOML config table.
type ImageConfig struct {
	// DefaultTransport is a value we prefix to image names that fail to
	// validate source references.
	DefaultTransport string `toml:"default_transport"`
	// PauseImage is the name of an image which we use to instantiate infra
	// containers.
	PauseImage string `toml:"pause_image"`
	// PauseCommand is the path of the binary we run in an infra
	// container that's been instantiated using PauseImage.
	PauseCommand string `toml:"pause_command"`
	// SignaturePolicyPath is the name of the file which decides what sort
	// of policy we use when deciding whether or not to trust an image that
	// we've pulled.  Outside of testing situations, it is strongly advised
	// that this be left unspecified so that the default system-wide policy
	// will be used.
	SignaturePolicyPath string `toml:"signature_policy"`
	// InsecureRegistries is a list of registries that must be contacted w/o
	// TLS verification.
	InsecureRegistries []string `toml:"insecure_registries"`
	// ImageVolumes controls how volumes specified in image config are handled
	ImageVolumes ImageVolumesType `toml:"image_volumes"`
	// Registries holds a list of registries used to pull unqualified images
	Registries []string `toml:"registries"`
}

// NetworkConfig represents the "crio.network" TOML config table
type NetworkConfig struct {
	// NetworkDir is where CNI network configuration files are stored.
	NetworkDir string `toml:"network_dir"`

	// PluginDir is where CNI plugin binaries are stored.
	PluginDir string `toml:"plugin_dir"`
}

// tomlConfig is another way of looking at a Config, which is
// TOML-friendly (it has all of the explicit tables). It's just used for
// conversions.
type tomlConfig struct {
	Crio struct {
		RootConfig
		Runtime struct{ RuntimeConfig } `toml:"runtime"`
		Image   struct{ ImageConfig }   `toml:"image"`
		Network struct{ NetworkConfig } `toml:"network"`
	} `toml:"crio"`
}

func (t *tomlConfig) toConfig(c *Config) {
	c.RootConfig = t.Crio.RootConfig
	c.RuntimeConfig = t.Crio.Runtime.RuntimeConfig
	c.ImageConfig = t.Crio.Image.ImageConfig
	c.NetworkConfig = t.Crio.Network.NetworkConfig
}

func (t *tomlConfig) fromConfig(c *Config) {
	t.Crio.RootConfig = c.RootConfig
	t.Crio.Runtime.RuntimeConfig = c.RuntimeConfig
	t.Crio.Image.ImageConfig = c.ImageConfig
	t.Crio.Network.NetworkConfig = c.NetworkConfig
}

// UpdateFromFile populates the Config from the TOML-encoded file at the given path.
// Returns errors encountered when reading or parsing the files, or nil
// otherwise.
func (c *Config) UpdateFromFile(path string) error {
	data, err := ioutil.ReadFile(path)
	if err != nil {
		return err
	}

	t := new(tomlConfig)
	t.fromConfig(c)

	_, err = toml.Decode(string(data), t)
	if err != nil {
		return err
	}

	t.toConfig(c)
	return nil
}

// ToFile outputs the given Config as a TOML-encoded file at the given path.
// Returns errors encountered when generating or writing the file, or nil
// otherwise.
func (c *Config) ToFile(path string) error {
	var w bytes.Buffer
	e := toml.NewEncoder(&w)

	t := new(tomlConfig)
	t.fromConfig(c)

	if err := e.Encode(*t); err != nil {
		return err
	}

	return ioutil.WriteFile(path, w.Bytes(), 0644)
}

// DefaultConfig returns the default configuration for crio.
func DefaultConfig() *Config {
	registries, _ := sysregistries.GetRegistries(&types.SystemContext{})
	insecureRegistries, _ := sysregistries.GetInsecureRegistries(&types.SystemContext{})
	return &Config{
		RootConfig: RootConfig{
			Root:           storage.DefaultStoreOptions.GraphRoot,
			RunRoot:        storage.DefaultStoreOptions.RunRoot,
			Storage:        storage.DefaultStoreOptions.GraphDriverName,
			StorageOptions: storage.DefaultStoreOptions.GraphDriverOptions,
			LogDir:         "/var/log/crio/pods",
			FileLocking:    true,
		},
		RuntimeConfig: RuntimeConfig{
			Runtime:                  "/usr/bin/runc",
			RuntimeUntrustedWorkload: "",
			DefaultWorkloadTrust:     "trusted",

			Conmon: conmonPath,
			ConmonEnv: []string{
				"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
			},
			SELinux:             selinuxEnabled(),
			SeccompProfile:      seccompProfilePath,
			ApparmorProfile:     apparmorProfileName,
			CgroupManager:       cgroupManager,
			PidsLimit:           DefaultPidsLimit,
			ContainerExitsDir:   containerExitsDir,
			HooksDirPath:        DefaultHooksDirPath,
			LogSizeMax:          DefaultLogSizeMax,
			DefaultMountsFile:   "",
			DefaultCapabilities: DefaultCapabilities,
		},
		ImageConfig: ImageConfig{
			DefaultTransport:    defaultTransport,
			PauseImage:          pauseImage,
			PauseCommand:        pauseCommand,
			SignaturePolicyPath: "",
			ImageVolumes:        ImageVolumesMkdir,
			Registries:          registries,
			InsecureRegistries:  insecureRegistries,
		},
		NetworkConfig: NetworkConfig{
			NetworkDir: cniConfigDir,
			PluginDir:  cniBinDir,
		},
	}
}
<|endoftext|>


<commit_before>package main

// Author Tim Jinkerson M7TJX
// Date 20th December 2020
// Accepts the values of a capacitor and an inductor
// and calculates the resonant frequency of the tuned
// circuit that that they would create

import (
	flag "flag"
	"fmt"
	"math"
	"os"
)

func stringfrequency(f float64) string {
	var punits string
	var pvalue float64
	if f > math.Pow(10, 9) {
		pvalue = f / math.Pow(10, 9)
		punits = "Ghz"
	} else if f > math.Pow(10, 6) {
		pvalue = f / math.Pow(10, 6)
		punits = "Mhz"
	} else if f > math.Pow(10, 3) {
		pvalue = f / math.Pow(10, 3)
		punits = "khz"
	} else {
		pvalue = f
		punits = "hz"
	}
	preturn := fmt.Sprintf("%f", pvalue) + " " + punits
	return preturn
}

func main() {
	const pi = 3.14159

	lPtr := flag.Int64("L", 0, "Inductance")
	cPtr := flag.Int64("C", 0, "Capacitance")
	cuPtr := flag.String("cunit", "uF", "F, mF, uF, nF or pF")
	luPtr := flag.String("lunit", "uH", "H, mH, uH, nH, pH")

	flag.Parse()

	inductance := *lPtr
	capacitance := *cPtr

	fmt.Printf("Capacitance = %d %s\n", capacitance, *cuPtr)
	fmt.Printf("Inductance = %d %s\n", inductance, *luPtr)

	var cscale float64 = 1
	var lscale float64 = 1

	switch *cuPtr {
	case "F":
		cscale = 1
	case "mF":
		cscale = float64(math.Pow(10, -3))
	case "uF":
		cscale = float64(math.Pow(10, -6))
	case "nF":
		cscale = float64(math.Pow(10, -9))
	case "pF":
		cscale = float64(math.Pow(10, -12))
	default:
		// Shouldn't get here
		fmt.Println("Invalid capacitance unit")
		os.Exit(2)
	}
	switch *luPtr {
	case "H":
		lscale = 1
	case "mH":
		lscale = float64(math.Pow(10, -3))
	case "uH":
		lscale = float64(math.Pow(10, -6))
	case "nH":
		lscale = float64(math.Pow(10, -9))
	case "pH":
		lscale = float64(math.Pow(10, -12))
	default:
		// Shouldn't get here
		fmt.Println("Invalid inductance unit")
		os.Exit(2)
	}

	if inductance <= 0 || capacitance <= 0 {
		fmt.Println("Both values must be greater than zero")
		os.Exit(2)
	}

	var f float64
	f = 1 / (2 * pi * (math.Sqrt((float64(capacitance) * cscale) * (float64(inductance) * lscale))))
	fmt.Printf("The resonant frequency is %s\n", stringfrequency(f))

}
<commit_msg>include function to calculate resonance<commit_after>package main

// Author Tim Jinkerson M7TJX
// Date 20th December 2020
// Accepts the values of a capacitor and an inductor
// and calculates the resonant frequency of the tuned
// circuit that that they would create

import (
	flag "flag"
	"fmt"
	"math"
	"os"
)

func stringfrequency(f float64) string {
	var punits string
	var pvalue float64
	if f > math.Pow(10, 9) {
		pvalue = f / math.Pow(10, 9)
		punits = "Ghz"
	} else if f > math.Pow(10, 6) {
		pvalue = f / math.Pow(10, 6)
		punits = "Mhz"
	} else if f > math.Pow(10, 3) {
		pvalue = f / math.Pow(10, 3)
		punits = "khz"
	} else {
		pvalue = f
		punits = "hz"
	}
	preturn := fmt.Sprintf("%f", pvalue) + " " + punits
	return preturn
}

func calculateValue(c float64, l float64) float64 {
	var freq float64 = 0
	freq = 1 / (2 * pi * (math.Sqrt(c * l)))
	return freq
}

func main() {
	const pi = 3.14159

	lPtr := flag.Int64("L", 0, "Inductance")
	cPtr := flag.Int64("C", 0, "Capacitance")
	cuPtr := flag.String("cunit", "uF", "F, mF, uF, nF or pF")
	luPtr := flag.String("lunit", "uH", "H, mH, uH, nH, pH")

	flag.Parse()

	inductance := *lPtr
	capacitance := *cPtr

	fmt.Printf("Capacitance = %d %s\n", capacitance, *cuPtr)
	fmt.Printf("Inductance = %d %s\n", inductance, *luPtr)

	var cscale float64 = 1
	var lscale float64 = 1

	switch *cuPtr {
	case "F":
		cscale = 1
	case "mF":
		cscale = float64(math.Pow(10, -3))
	case "uF":
		cscale = float64(math.Pow(10, -6))
	case "nF":
		cscale = float64(math.Pow(10, -9))
	case "pF":
		cscale = float64(math.Pow(10, -12))
	default:
		// Shouldn't get here
		fmt.Println("Invalid capacitance unit")
		os.Exit(2)
	}
	switch *luPtr {
	case "H":
		lscale = 1
	case "mH":
		lscale = float64(math.Pow(10, -3))
	case "uH":
		lscale = float64(math.Pow(10, -6))
	case "nH":
		lscale = float64(math.Pow(10, -9))
	case "pH":
		lscale = float64(math.Pow(10, -12))
	default:
		// Shouldn't get here
		fmt.Println("Invalid inductance unit")
		os.Exit(2)
	}

	if inductance <= 0 || capacitance <= 0 {
		fmt.Println("Both values must be greater than zero")
		os.Exit(2)
	}

	var f float64
	f = calculateValue(float64(capacitance)*cscale, float64(inductance)*lscale)

	fmt.Printf("The resonant frequency is %s\n", stringfrequency(f))

}
<|endoftext|>


<commit_before>//
// Copyright (C) 2014-2017 Nippon Telegraph and Telephone Corporation.
//
// 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 (
	"fmt"
	"io/ioutil"
	"net/http"
	_ "net/http/pprof"
	"os"
	"os/signal"
	"runtime"
	"syscall"

	"github.com/jessevdk/go-flags"
	"github.com/kr/pretty"
	log "github.com/sirupsen/logrus"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"

	api "github.com/osrg/gobgp/api"
	"github.com/osrg/gobgp/config"
	"github.com/osrg/gobgp/packet/bgp"
	"github.com/osrg/gobgp/server"
	"github.com/osrg/gobgp/table"
)

var version = "master"

func main() {
	sigCh := make(chan os.Signal, 1)
	signal.Notify(sigCh, syscall.SIGTERM)

	var opts struct {
		ConfigFile      string `short:"f" long:"config-file" description:"specifying a config file"`
		ConfigType      string `short:"t" long:"config-type" description:"specifying config type (toml, yaml, json)" default:"toml"`
		LogLevel        string `short:"l" long:"log-level" description:"specifying log level"`
		LogPlain        bool   `short:"p" long:"log-plain" description:"use plain format for logging (json by default)"`
		UseSyslog       string `short:"s" long:"syslog" description:"use syslogd"`
		Facility        string `long:"syslog-facility" description:"specify syslog facility"`
		DisableStdlog   bool   `long:"disable-stdlog" description:"disable standard logging"`
		CPUs            int    `long:"cpus" description:"specify the number of CPUs to be used"`
		GrpcHosts       string `long:"api-hosts" description:"specify the hosts that gobgpd listens on" default:":50051"`
		GracefulRestart bool   `short:"r" long:"graceful-restart" description:"flag restart-state in graceful-restart capability"`
		Dry             bool   `short:"d" long:"dry-run" description:"check configuration"`
		PProfHost       string `long:"pprof-host" description:"specify the host that gobgpd listens on for pprof" default:"localhost:6060"`
		PProfDisable    bool   `long:"pprof-disable" description:"disable pprof profiling"`
		TLS             bool   `long:"tls" description:"enable TLS authentication for gRPC API"`
		TLSCertFile     string `long:"tls-cert-file" description:"The TLS cert file"`
		TLSKeyFile      string `long:"tls-key-file" description:"The TLS key file"`
		Version         bool   `long:"version" description:"show version number"`
	}
	_, err := flags.Parse(&opts)
	if err != nil {
		os.Exit(1)
	}

	if opts.Version {
		fmt.Println("gobgpd version", version)
		os.Exit(0)
	}

	if opts.CPUs == 0 {
		runtime.GOMAXPROCS(runtime.NumCPU())
	} else {
		if runtime.NumCPU() < opts.CPUs {
			log.Errorf("Only %d CPUs are available but %d is specified", runtime.NumCPU(), opts.CPUs)
			os.Exit(1)
		}
		runtime.GOMAXPROCS(opts.CPUs)
	}

	if !opts.PProfDisable {
		go func() {
			log.Println(http.ListenAndServe(opts.PProfHost, nil))
		}()
	}

	switch opts.LogLevel {
	case "debug":
		log.SetLevel(log.DebugLevel)
	case "info":
		log.SetLevel(log.InfoLevel)
	default:
		log.SetLevel(log.InfoLevel)
	}

	if opts.DisableStdlog == true {
		log.SetOutput(ioutil.Discard)
	} else {
		log.SetOutput(os.Stdout)
	}

	if opts.UseSyslog != "" {
		if err := addSyslogHook(opts.UseSyslog, opts.Facility); err != nil {
			log.Error("Unable to connect to syslog daemon, ", opts.UseSyslog)
		}
	}

	if opts.LogPlain {
		if opts.DisableStdlog {
			log.SetFormatter(&log.TextFormatter{
				DisableColors: true,
			})
		}
	} else {
		log.SetFormatter(&log.JSONFormatter{})
	}

	configCh := make(chan *config.BgpConfigSet)
	if opts.Dry {
		go config.ReadConfigfileServe(opts.ConfigFile, opts.ConfigType, configCh)
		c := <-configCh
		if opts.LogLevel == "debug" {
			pretty.Println(c)
		}
		os.Exit(0)
	}

	log.Info("gobgpd started")
	bgpServer := server.NewBgpServer()
	go bgpServer.Serve()

	var grpcOpts []grpc.ServerOption
	if opts.TLS {
		creds, err := credentials.NewServerTLSFromFile(opts.TLSCertFile, opts.TLSKeyFile)
		if err != nil {
			log.Fatalf("Failed to generate credentials: %v", err)
		}
		grpcOpts = []grpc.ServerOption{grpc.Creds(creds)}
	}
	// start grpc Server
	apiServer := api.NewServer(bgpServer, grpc.NewServer(grpcOpts...), opts.GrpcHosts)
	go func() {
		if err := apiServer.Serve(); err != nil {
			log.Fatalf("failed to listen grpc port: %s", err)
		}
	}()

	if opts.ConfigFile != "" {
		go config.ReadConfigfileServe(opts.ConfigFile, opts.ConfigType, configCh)
	}

	var c *config.BgpConfigSet = nil
	for {
		select {
		case newConfig := <-configCh:
			var added, deleted, updated []config.Neighbor
			var addedPg, deletedPg, updatedPg []config.PeerGroup
			var updatePolicy bool

			if c == nil {
				c = newConfig
				if err := bgpServer.Start(&newConfig.Global); err != nil {
					log.Fatalf("failed to set global config: %s", err)
				}
				if newConfig.Zebra.Config.Enabled {
					if err := bgpServer.StartZebraClient(&newConfig.Zebra.Config); err != nil {
						log.Fatalf("failed to set zebra config: %s", err)
					}
				}
				if len(newConfig.Collector.Config.Url) > 0 {
					if err := bgpServer.StartCollector(&newConfig.Collector.Config); err != nil {
						log.Fatalf("failed to set collector config: %s", err)
					}
				}
				for _, c := range newConfig.RpkiServers {
					if err := bgpServer.AddRpki(&c.Config); err != nil {
						log.Fatalf("failed to set rpki config: %s", err)
					}
				}
				for _, c := range newConfig.BmpServers {
					if err := bgpServer.AddBmp(&c.Config); err != nil {
						log.Fatalf("failed to set bmp config: %s", err)
					}
				}
				for _, c := range newConfig.MrtDump {
					if len(c.Config.FileName) == 0 {
						continue
					}
					if err := bgpServer.EnableMrt(&c.Config); err != nil {
						log.Fatalf("failed to set mrt config: %s", err)
					}
				}
				p := config.ConfigSetToRoutingPolicy(newConfig)
				if err := bgpServer.UpdatePolicy(*p); err != nil {
					log.Fatalf("failed to set routing policy: %s", err)
				}

				added = newConfig.Neighbors
				addedPg = newConfig.PeerGroups
				if opts.GracefulRestart {
					for i, n := range added {
						if n.GracefulRestart.Config.Enabled {
							added[i].GracefulRestart.State.LocalRestarting = true
						}
					}
				}

			} else {
				addedPg, deletedPg, updatedPg = config.UpdatePeerGroupConfig(c, newConfig)
				added, deleted, updated = config.UpdateNeighborConfig(c, newConfig)
				updatePolicy = config.CheckPolicyDifference(config.ConfigSetToRoutingPolicy(c), config.ConfigSetToRoutingPolicy(newConfig))

				if updatePolicy {
					log.Info("Policy config is updated")
					p := config.ConfigSetToRoutingPolicy(newConfig)
					bgpServer.UpdatePolicy(*p)
				}
				// global policy update
				if !newConfig.Global.ApplyPolicy.Config.Equal(&c.Global.ApplyPolicy.Config) {
					a := newConfig.Global.ApplyPolicy.Config
					toDefaultTable := func(r config.DefaultPolicyType) table.RouteType {
						var def table.RouteType
						switch r {
						case config.DEFAULT_POLICY_TYPE_ACCEPT_ROUTE:
							def = table.ROUTE_TYPE_ACCEPT
						case config.DEFAULT_POLICY_TYPE_REJECT_ROUTE:
							def = table.ROUTE_TYPE_REJECT
						}
						return def
					}
					toPolicyDefinitions := func(r []string) []*config.PolicyDefinition {
						p := make([]*config.PolicyDefinition, 0, len(r))
						for _, n := range r {
							p = append(p, &config.PolicyDefinition{
								Name: n,
							})
						}
						return p
					}

					def := toDefaultTable(a.DefaultImportPolicy)
					ps := toPolicyDefinitions(a.ImportPolicyList)
					bgpServer.ReplacePolicyAssignment("", table.POLICY_DIRECTION_IMPORT, ps, def)

					def = toDefaultTable(a.DefaultExportPolicy)
					ps = toPolicyDefinitions(a.ExportPolicyList)
					bgpServer.ReplacePolicyAssignment("", table.POLICY_DIRECTION_EXPORT, ps, def)

					updatePolicy = true

				}
				c = newConfig
			}
			for i, pg := range addedPg {
				log.Infof("PeerGroup %s is added", pg.Config.PeerGroupName)
				if err := bgpServer.AddPeerGroup(&addedPg[i]); err != nil {
					log.Warn(err)
				}
			}
			for i, pg := range deletedPg {
				log.Infof("PeerGroup %s is deleted", pg.Config.PeerGroupName)
				if err := bgpServer.DeletePeerGroup(&deletedPg[i]); err != nil {
					log.Warn(err)
				}
			}
			for i, pg := range updatedPg {
				log.Infof("PeerGroup %s is updated", pg.Config.PeerGroupName)
				u, err := bgpServer.UpdatePeerGroup(&updatedPg[i])
				if err != nil {
					log.Warn(err)
				}
				updatePolicy = updatePolicy || u
			}
			for i, dn := range newConfig.DynamicNeighbors {
				log.Infof("Dynamic Neighbor %s is added to PeerGroup %s", dn.Config.Prefix, dn.Config.PeerGroup)
				if err := bgpServer.AddDynamicNeighbor(&newConfig.DynamicNeighbors[i]); err != nil {
					log.Warn(err)
				}
			}
			for i, p := range added {
				log.Infof("Peer %v is added", p.State.NeighborAddress)
				if err := bgpServer.AddNeighbor(&added[i]); err != nil {
					log.Warn(err)
				}
			}
			for i, p := range deleted {
				log.Infof("Peer %v is deleted", p.State.NeighborAddress)
				if err := bgpServer.DeleteNeighbor(&deleted[i]); err != nil {
					log.Warn(err)
				}
			}
			for i, p := range updated {
				log.Infof("Peer %v is updated", p.State.NeighborAddress)
				u, err := bgpServer.UpdateNeighbor(&updated[i])
				if err != nil {
					log.Warn(err)
				}
				updatePolicy = updatePolicy || u
			}

			if updatePolicy {
				bgpServer.SoftResetIn("", bgp.RouteFamily(0))
			}
		case <-sigCh:
			bgpServer.Shutdown()
		}
	}
}
<commit_msg>gobgpd: fix multiple configs handling<commit_after>//
// Copyright (C) 2014-2017 Nippon Telegraph and Telephone Corporation.
//
// 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 (
	"fmt"
	"io/ioutil"
	"net/http"
	_ "net/http/pprof"
	"os"
	"os/signal"
	"runtime"
	"syscall"

	"github.com/jessevdk/go-flags"
	"github.com/kr/pretty"
	log "github.com/sirupsen/logrus"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"

	api "github.com/osrg/gobgp/api"
	"github.com/osrg/gobgp/config"
	"github.com/osrg/gobgp/packet/bgp"
	"github.com/osrg/gobgp/server"
	"github.com/osrg/gobgp/table"
)

var version = "master"

func main() {
	sigCh := make(chan os.Signal, 1)
	signal.Notify(sigCh, syscall.SIGTERM)

	var opts struct {
		ConfigFile      string `short:"f" long:"config-file" description:"specifying a config file"`
		ConfigType      string `short:"t" long:"config-type" description:"specifying config type (toml, yaml, json)" default:"toml"`
		LogLevel        string `short:"l" long:"log-level" description:"specifying log level"`
		LogPlain        bool   `short:"p" long:"log-plain" description:"use plain format for logging (json by default)"`
		UseSyslog       string `short:"s" long:"syslog" description:"use syslogd"`
		Facility        string `long:"syslog-facility" description:"specify syslog facility"`
		DisableStdlog   bool   `long:"disable-stdlog" description:"disable standard logging"`
		CPUs            int    `long:"cpus" description:"specify the number of CPUs to be used"`
		GrpcHosts       string `long:"api-hosts" description:"specify the hosts that gobgpd listens on" default:":50051"`
		GracefulRestart bool   `short:"r" long:"graceful-restart" description:"flag restart-state in graceful-restart capability"`
		Dry             bool   `short:"d" long:"dry-run" description:"check configuration"`
		PProfHost       string `long:"pprof-host" description:"specify the host that gobgpd listens on for pprof" default:"localhost:6060"`
		PProfDisable    bool   `long:"pprof-disable" description:"disable pprof profiling"`
		TLS             bool   `long:"tls" description:"enable TLS authentication for gRPC API"`
		TLSCertFile     string `long:"tls-cert-file" description:"The TLS cert file"`
		TLSKeyFile      string `long:"tls-key-file" description:"The TLS key file"`
		Version         bool   `long:"version" description:"show version number"`
	}
	_, err := flags.Parse(&opts)
	if err != nil {
		os.Exit(1)
	}

	if opts.Version {
		fmt.Println("gobgpd version", version)
		os.Exit(0)
	}

	if opts.CPUs == 0 {
		runtime.GOMAXPROCS(runtime.NumCPU())
	} else {
		if runtime.NumCPU() < opts.CPUs {
			log.Errorf("Only %d CPUs are available but %d is specified", runtime.NumCPU(), opts.CPUs)
			os.Exit(1)
		}
		runtime.GOMAXPROCS(opts.CPUs)
	}

	if !opts.PProfDisable {
		go func() {
			log.Println(http.ListenAndServe(opts.PProfHost, nil))
		}()
	}

	switch opts.LogLevel {
	case "debug":
		log.SetLevel(log.DebugLevel)
	case "info":
		log.SetLevel(log.InfoLevel)
	default:
		log.SetLevel(log.InfoLevel)
	}

	if opts.DisableStdlog == true {
		log.SetOutput(ioutil.Discard)
	} else {
		log.SetOutput(os.Stdout)
	}

	if opts.UseSyslog != "" {
		if err := addSyslogHook(opts.UseSyslog, opts.Facility); err != nil {
			log.Error("Unable to connect to syslog daemon, ", opts.UseSyslog)
		}
	}

	if opts.LogPlain {
		if opts.DisableStdlog {
			log.SetFormatter(&log.TextFormatter{
				DisableColors: true,
			})
		}
	} else {
		log.SetFormatter(&log.JSONFormatter{})
	}

	configCh := make(chan *config.BgpConfigSet)
	if opts.Dry {
		go config.ReadConfigfileServe(opts.ConfigFile, opts.ConfigType, configCh)
		c := <-configCh
		if opts.LogLevel == "debug" {
			pretty.Println(c)
		}
		os.Exit(0)
	}

	log.Info("gobgpd started")
	bgpServer := server.NewBgpServer()
	go bgpServer.Serve()

	var grpcOpts []grpc.ServerOption
	if opts.TLS {
		creds, err := credentials.NewServerTLSFromFile(opts.TLSCertFile, opts.TLSKeyFile)
		if err != nil {
			log.Fatalf("Failed to generate credentials: %v", err)
		}
		grpcOpts = []grpc.ServerOption{grpc.Creds(creds)}
	}
	// start grpc Server
	apiServer := api.NewServer(bgpServer, grpc.NewServer(grpcOpts...), opts.GrpcHosts)
	go func() {
		if err := apiServer.Serve(); err != nil {
			log.Fatalf("failed to listen grpc port: %s", err)
		}
	}()

	if opts.ConfigFile != "" {
		go config.ReadConfigfileServe(opts.ConfigFile, opts.ConfigType, configCh)
	}

	var c *config.BgpConfigSet = nil
	for {
		select {
		case newConfig := <-configCh:
			var added, deleted, updated []config.Neighbor
			var addedPg, deletedPg, updatedPg []config.PeerGroup
			var updatePolicy bool

			if c == nil {
				c = newConfig
				if err := bgpServer.Start(&newConfig.Global); err != nil {
					log.Fatalf("failed to set global config: %s", err)
				}
				if newConfig.Zebra.Config.Enabled {
					if err := bgpServer.StartZebraClient(&newConfig.Zebra.Config); err != nil {
						log.Fatalf("failed to set zebra config: %s", err)
					}
				}
				if len(newConfig.Collector.Config.Url) > 0 {
					if err := bgpServer.StartCollector(&newConfig.Collector.Config); err != nil {
						log.Fatalf("failed to set collector config: %s", err)
					}
				}
				for i, _ := range newConfig.RpkiServers {
					if err := bgpServer.AddRpki(&newConfig.RpkiServers[i].Config); err != nil {
						log.Fatalf("failed to set rpki config: %s", err)
					}
				}
				for i, _ := range newConfig.BmpServers {
					if err := bgpServer.AddBmp(&newConfig.BmpServers[i].Config); err != nil {
						log.Fatalf("failed to set bmp config: %s", err)
					}
				}
				for i, _ := range newConfig.MrtDump {
					if len(newConfig.MrtDump[i].Config.FileName) == 0 {
						continue
					}
					if err := bgpServer.EnableMrt(&newConfig.MrtDump[i].Config); err != nil {
						log.Fatalf("failed to set mrt config: %s", err)
					}
				}
				p := config.ConfigSetToRoutingPolicy(newConfig)
				if err := bgpServer.UpdatePolicy(*p); err != nil {
					log.Fatalf("failed to set routing policy: %s", err)
				}

				added = newConfig.Neighbors
				addedPg = newConfig.PeerGroups
				if opts.GracefulRestart {
					for i, n := range added {
						if n.GracefulRestart.Config.Enabled {
							added[i].GracefulRestart.State.LocalRestarting = true
						}
					}
				}

			} else {
				addedPg, deletedPg, updatedPg = config.UpdatePeerGroupConfig(c, newConfig)
				added, deleted, updated = config.UpdateNeighborConfig(c, newConfig)
				updatePolicy = config.CheckPolicyDifference(config.ConfigSetToRoutingPolicy(c), config.ConfigSetToRoutingPolicy(newConfig))

				if updatePolicy {
					log.Info("Policy config is updated")
					p := config.ConfigSetToRoutingPolicy(newConfig)
					bgpServer.UpdatePolicy(*p)
				}
				// global policy update
				if !newConfig.Global.ApplyPolicy.Config.Equal(&c.Global.ApplyPolicy.Config) {
					a := newConfig.Global.ApplyPolicy.Config
					toDefaultTable := func(r config.DefaultPolicyType) table.RouteType {
						var def table.RouteType
						switch r {
						case config.DEFAULT_POLICY_TYPE_ACCEPT_ROUTE:
							def = table.ROUTE_TYPE_ACCEPT
						case config.DEFAULT_POLICY_TYPE_REJECT_ROUTE:
							def = table.ROUTE_TYPE_REJECT
						}
						return def
					}
					toPolicyDefinitions := func(r []string) []*config.PolicyDefinition {
						p := make([]*config.PolicyDefinition, 0, len(r))
						for _, n := range r {
							p = append(p, &config.PolicyDefinition{
								Name: n,
							})
						}
						return p
					}

					def := toDefaultTable(a.DefaultImportPolicy)
					ps := toPolicyDefinitions(a.ImportPolicyList)
					bgpServer.ReplacePolicyAssignment("", table.POLICY_DIRECTION_IMPORT, ps, def)

					def = toDefaultTable(a.DefaultExportPolicy)
					ps = toPolicyDefinitions(a.ExportPolicyList)
					bgpServer.ReplacePolicyAssignment("", table.POLICY_DIRECTION_EXPORT, ps, def)

					updatePolicy = true

				}
				c = newConfig
			}
			for i, pg := range addedPg {
				log.Infof("PeerGroup %s is added", pg.Config.PeerGroupName)
				if err := bgpServer.AddPeerGroup(&addedPg[i]); err != nil {
					log.Warn(err)
				}
			}
			for i, pg := range deletedPg {
				log.Infof("PeerGroup %s is deleted", pg.Config.PeerGroupName)
				if err := bgpServer.DeletePeerGroup(&deletedPg[i]); err != nil {
					log.Warn(err)
				}
			}
			for i, pg := range updatedPg {
				log.Infof("PeerGroup %s is updated", pg.Config.PeerGroupName)
				u, err := bgpServer.UpdatePeerGroup(&updatedPg[i])
				if err != nil {
					log.Warn(err)
				}
				updatePolicy = updatePolicy || u
			}
			for i, dn := range newConfig.DynamicNeighbors {
				log.Infof("Dynamic Neighbor %s is added to PeerGroup %s", dn.Config.Prefix, dn.Config.PeerGroup)
				if err := bgpServer.AddDynamicNeighbor(&newConfig.DynamicNeighbors[i]); err != nil {
					log.Warn(err)
				}
			}
			for i, p := range added {
				log.Infof("Peer %v is added", p.State.NeighborAddress)
				if err := bgpServer.AddNeighbor(&added[i]); err != nil {
					log.Warn(err)
				}
			}
			for i, p := range deleted {
				log.Infof("Peer %v is deleted", p.State.NeighborAddress)
				if err := bgpServer.DeleteNeighbor(&deleted[i]); err != nil {
					log.Warn(err)
				}
			}
			for i, p := range updated {
				log.Infof("Peer %v is updated", p.State.NeighborAddress)
				u, err := bgpServer.UpdateNeighbor(&updated[i])
				if err != nil {
					log.Warn(err)
				}
				updatePolicy = updatePolicy || u
			}

			if updatePolicy {
				bgpServer.SoftResetIn("", bgp.RouteFamily(0))
			}
		case <-sigCh:
			bgpServer.Shutdown()
		}
	}
}
<|endoftext|>