<commit_before>package configcommands

import (
	"errors"
	"fmt"

	"github.com/pivotalservices/cf-mgmt/config"
	"github.com/xchapter7x/lo"
)

type UpdateOrgConfigurationCommand struct {
	ConfigManager config.Manager
	BaseConfigCommand
	OrgName                          string        `long:"org" description:"Org name" required:"true"`
	PrivateDomains                   []string      `long:"private-domain" description:"Private Domain(s) to add, specify multiple times"`
	PrivateDomainsToRemove           []string      `long:"private-domain-to-remove" description:"Private Domain(s) to remove, specify multiple times"`
	EnableRemovePrivateDomains       string        `long:"enable-remove-private-domains" description:"Enable removing private domains" choice:"true" choice:"false"`
	SharedPrivateDomains             []string      `long:"shared-private-domain" description:"Shared Private Domain(s) to add, specify multiple times"`
	SharedPrivateDomainsToRemove     []string      `long:"shared-private-domain-to-remove" description:"Shared Private Domain(s) to remove, specify multiple times"`
	EnableRemoveSharedPrivateDomains string        `long:"enable-remove-shared-private-domains" description:"Enable removing shared private domains" choice:"true" choice:"false"`
	EnableRemoveSpaces               string        `long:"enable-remove-spaces" description:"Enable removing spaces" choice:"true" choice:"false"`
	DefaultIsolationSegment          string        `long:"default-isolation-segment" description:"Default isolation segment for org" `
	ClearDefaultIsolationSegment     bool          `long:"clear-default-isolation-segment" description:"Sets the default isolation segment to blank"`
	EnableRemoveUsers                string        `long:"enable-remove-users" description:"Enable removing users from the org" choice:"true" choice:"false"`
	NamedQuota                       string        `long:"named-quota" description:"Named quota to assign to org"`
	ClearNamedQuota                  bool          `long:"clear-named-quota" description:"Sets the named quota to blank"`
	Quota                            OrgQuota      `group:"quota"`
	BillingManager                   UserRole      `group:"billing-manager" namespace:"billing-manager"`
	Manager                          UserRole      `group:"manager" namespace:"manager"`
	Auditor                          UserRole      `group:"auditor" namespace:"auditor"`
	ServiceAccess                    ServiceAccess `group:"service-access"`
}

//Execute - updates org configuration`
func (c *UpdateOrgConfigurationCommand) Execute(args []string) error {
	lo.G.Warning("*** Deprecated *** - Use `org` command instead for adding/updating org configurations")
	c.initConfig()
	orgConfig, err := c.ConfigManager.GetOrgConfig(c.OrgName)
	if err != nil {
		return err
	}

	if c.Quota.EnableOrgQuota == "true" && c.NamedQuota != "" {
		return fmt.Errorf("cannot enable org quota and use named quotas")
	}

	orgSpaces, err := c.ConfigManager.OrgSpaces(c.OrgName)
	if err != nil {
		return err
	}
	errorString := ""

	convertToBool("enable-remove-spaces", &orgSpaces.EnableDeleteSpaces, c.EnableRemoveSpaces, &errorString)
	if c.DefaultIsolationSegment != "" {
		orgConfig.DefaultIsoSegment = c.DefaultIsolationSegment
	}
	if c.ClearDefaultIsolationSegment {
		orgConfig.DefaultIsoSegment = ""
	}
	convertToBool("enable-remove-users", &orgConfig.RemoveUsers, c.EnableRemoveUsers, &errorString)
	orgConfig.PrivateDomains = removeFromSlice(addToSlice(orgConfig.PrivateDomains, c.PrivateDomains, &errorString), c.PrivateDomainsToRemove)
	convertToBool("enable-remove-private-domains", &orgConfig.RemovePrivateDomains, c.EnableRemovePrivateDomains, &errorString)

	orgConfig.SharedPrivateDomains = removeFromSlice(addToSlice(orgConfig.SharedPrivateDomains, c.SharedPrivateDomains, &errorString), c.SharedPrivateDomainsToRemove)
	convertToBool("enable-remove-shared-private-domains", &orgConfig.RemoveSharedPrivateDomains, c.EnableRemoveSharedPrivateDomains, &errorString)

	updateOrgQuotaConfig(orgConfig, c.Quota, &errorString)
	if c.NamedQuota != "" {
		orgConfig.NamedQuota = c.NamedQuota
	}
	if c.ClearNamedQuota {
		orgConfig.NamedQuota = ""
	}
	c.updateUsers(orgConfig, &errorString)

	if c.ServiceAccess.ServiceNameToRemove != "" {
		delete(orgConfig.ServiceAccess, c.ServiceAccess.ServiceNameToRemove)
	}

	if c.ServiceAccess.ServiceName != "" {
		if len(c.ServiceAccess.Plans) > 0 {
			orgConfig.ServiceAccess[c.ServiceAccess.ServiceName] = c.ServiceAccess.Plans
		} else {
			orgConfig.ServiceAccess[c.ServiceAccess.ServiceName] = []string{"*"}
		}
	}

	if errorString != "" {
		return errors.New(errorString)
	}

	if err := c.ConfigManager.SaveOrgConfig(orgConfig); err != nil {
		return err
	}

	if err := c.ConfigManager.SaveOrgSpaces(orgSpaces); err != nil {
		return err
	}

	fmt.Println(fmt.Sprintf("The org [%s] has been updated", c.OrgName))
	return nil
}

func (c *UpdateOrgConfigurationCommand) updateUsers(orgConfig *config.OrgConfig, errorString *string) {
	updateUsersBasedOnRole(&orgConfig.BillingManager, orgConfig.GetBillingManagerGroups(), &c.BillingManager, errorString)
	updateUsersBasedOnRole(&orgConfig.Auditor, orgConfig.GetAuditorGroups(), &c.Auditor, errorString)
	updateUsersBasedOnRole(&orgConfig.Manager, orgConfig.GetManagerGroups(), &c.Manager, errorString)

	orgConfig.BillingManagerGroup = ""
	orgConfig.ManagerGroup = ""
	orgConfig.AuditorGroup = ""
}

func (c *UpdateOrgConfigurationCommand) initConfig() {
	if c.ConfigManager == nil {
		c.ConfigManager = config.NewManager(c.ConfigDirectory)
	}
}
<commit_msg>add deprecation warnings and no longer marshal out service-access not<commit_after>package configcommands

import (
	"errors"
	"fmt"

	"github.com/pivotalservices/cf-mgmt/config"
	"github.com/xchapter7x/lo"
)

type UpdateOrgConfigurationCommand struct {
	ConfigManager config.Manager
	BaseConfigCommand
	OrgName                          string        `long:"org" description:"Org name" required:"true"`
	PrivateDomains                   []string      `long:"private-domain" description:"Private Domain(s) to add, specify multiple times"`
	PrivateDomainsToRemove           []string      `long:"private-domain-to-remove" description:"Private Domain(s) to remove, specify multiple times"`
	EnableRemovePrivateDomains       string        `long:"enable-remove-private-domains" description:"Enable removing private domains" choice:"true" choice:"false"`
	SharedPrivateDomains             []string      `long:"shared-private-domain" description:"Shared Private Domain(s) to add, specify multiple times"`
	SharedPrivateDomainsToRemove     []string      `long:"shared-private-domain-to-remove" description:"Shared Private Domain(s) to remove, specify multiple times"`
	EnableRemoveSharedPrivateDomains string        `long:"enable-remove-shared-private-domains" description:"Enable removing shared private domains" choice:"true" choice:"false"`
	EnableRemoveSpaces               string        `long:"enable-remove-spaces" description:"Enable removing spaces" choice:"true" choice:"false"`
	DefaultIsolationSegment          string        `long:"default-isolation-segment" description:"Default isolation segment for org" `
	ClearDefaultIsolationSegment     bool          `long:"clear-default-isolation-segment" description:"Sets the default isolation segment to blank"`
	EnableRemoveUsers                string        `long:"enable-remove-users" description:"Enable removing users from the org" choice:"true" choice:"false"`
	NamedQuota                       string        `long:"named-quota" description:"Named quota to assign to org"`
	ClearNamedQuota                  bool          `long:"clear-named-quota" description:"Sets the named quota to blank"`
	Quota                            OrgQuota      `group:"quota"`
	BillingManager                   UserRole      `group:"billing-manager" namespace:"billing-manager"`
	Manager                          UserRole      `group:"manager" namespace:"manager"`
	Auditor                          UserRole      `group:"auditor" namespace:"auditor"`
	ServiceAccess                    ServiceAccess `group:"service-access"`
}

//Execute - updates org configuration`
func (c *UpdateOrgConfigurationCommand) Execute(args []string) error {
	lo.G.Warning("*** Deprecated *** - Use `org` command instead for adding/updating org configurations")
	c.initConfig()
	orgConfig, err := c.ConfigManager.GetOrgConfig(c.OrgName)
	if err != nil {
		return err
	}

	if c.Quota.EnableOrgQuota == "true" && c.NamedQuota != "" {
		return fmt.Errorf("cannot enable org quota and use named quotas")
	}

	orgSpaces, err := c.ConfigManager.OrgSpaces(c.OrgName)
	if err != nil {
		return err
	}
	errorString := ""

	convertToBool("enable-remove-spaces", &orgSpaces.EnableDeleteSpaces, c.EnableRemoveSpaces, &errorString)
	if c.DefaultIsolationSegment != "" {
		orgConfig.DefaultIsoSegment = c.DefaultIsolationSegment
	}
	if c.ClearDefaultIsolationSegment {
		orgConfig.DefaultIsoSegment = ""
	}
	convertToBool("enable-remove-users", &orgConfig.RemoveUsers, c.EnableRemoveUsers, &errorString)
	orgConfig.PrivateDomains = removeFromSlice(addToSlice(orgConfig.PrivateDomains, c.PrivateDomains, &errorString), c.PrivateDomainsToRemove)
	convertToBool("enable-remove-private-domains", &orgConfig.RemovePrivateDomains, c.EnableRemovePrivateDomains, &errorString)

	orgConfig.SharedPrivateDomains = removeFromSlice(addToSlice(orgConfig.SharedPrivateDomains, c.SharedPrivateDomains, &errorString), c.SharedPrivateDomainsToRemove)
	convertToBool("enable-remove-shared-private-domains", &orgConfig.RemoveSharedPrivateDomains, c.EnableRemoveSharedPrivateDomains, &errorString)

	updateOrgQuotaConfig(orgConfig, c.Quota, &errorString)
	if c.NamedQuota != "" {
		orgConfig.NamedQuota = c.NamedQuota
	}
	if c.ClearNamedQuota {
		orgConfig.NamedQuota = ""
	}
	c.updateUsers(orgConfig, &errorString)

	if c.ServiceAccess.ServiceNameToRemove != "" {
		return errors.New("Service access is managed with cf-mgmt-config service-access command")
	}

	if c.ServiceAccess.ServiceName != "" {
		return errors.New("Service access is managed with cf-mgmt-config service-access command")
	}

	if errorString != "" {
		return errors.New(errorString)
	}

	if err := c.ConfigManager.SaveOrgConfig(orgConfig); err != nil {
		return err
	}

	if err := c.ConfigManager.SaveOrgSpaces(orgSpaces); err != nil {
		return err
	}

	fmt.Println(fmt.Sprintf("The org [%s] has been updated", c.OrgName))
	return nil
}

func (c *UpdateOrgConfigurationCommand) updateUsers(orgConfig *config.OrgConfig, errorString *string) {
	updateUsersBasedOnRole(&orgConfig.BillingManager, orgConfig.GetBillingManagerGroups(), &c.BillingManager, errorString)
	updateUsersBasedOnRole(&orgConfig.Auditor, orgConfig.GetAuditorGroups(), &c.Auditor, errorString)
	updateUsersBasedOnRole(&orgConfig.Manager, orgConfig.GetManagerGroups(), &c.Manager, errorString)

	orgConfig.BillingManagerGroup = ""
	orgConfig.ManagerGroup = ""
	orgConfig.AuditorGroup = ""
}

func (c *UpdateOrgConfigurationCommand) initConfig() {
	if c.ConfigManager == nil {
		c.ConfigManager = config.NewManager(c.ConfigDirectory)
	}
}
<|endoftext|>


<commit_before>package main

import (
	"github.com/Preetam/onecontactlink/middleware"

	"github.com/VividCortex/siesta"

	"flag"
	"html/template"
	"log"
	"net/http"
)

var (
	templ = template.Must(template.ParseGlob("./templates/*"))
)

func main() {
	addr := flag.String("addr", ":4003", "Listen address")
	staticDir := flag.String("static-dir", "./static", "Path to static content")
	flag.Parse()

	service := siesta.NewService("/")
	service.AddPre(middleware.RequestIdentifier)

	service.Route("GET", "/", "serves index", func(w http.ResponseWriter, r *http.Request) {
		templ.ExecuteTemplate(w, "index", nil)
	})

	service.SetNotFound(http.FileServer(http.Dir(*staticDir)))
	log.Println("static directory set to", *staticDir)
	log.Println("listening on", *addr)
	log.Fatal(http.ListenAndServe(*addr, service))
}
<commit_msg>use flag for templates path<commit_after>package main

import (
	"github.com/Preetam/onecontactlink/middleware"

	"github.com/VividCortex/siesta"

	"flag"
	"html/template"
	"log"
	"net/http"
	"path/filepath"
)

var (
	templ *template.Template
)

func main() {
	addr := flag.String("addr", ":4003", "Listen address")
	staticDir := flag.String("static-dir", "./static", "Path to static content")
	templatesDir := flag.String("templates-dir", "./templates", "Path to templates")
	flag.Parse()

	var err error
	templ, err = template.ParseGlob(filepath.Join(*templatesDir, "*"))
	if err != nil {
		log.Fatal(err)
	}

	service := siesta.NewService("/")
	service.AddPre(middleware.RequestIdentifier)

	service.Route("GET", "/", "serves index", func(w http.ResponseWriter, r *http.Request) {
		templ.ExecuteTemplate(w, "index", nil)
	})

	service.SetNotFound(http.FileServer(http.Dir(*staticDir)))
	log.Println("static directory set to", *staticDir)
	log.Println("listening on", *addr)
	log.Fatal(http.ListenAndServe(*addr, service))
}
<|endoftext|>


<commit_before>// +build ignore

package main

import (
	"fmt"
	"io"
	"os"
	"strings"

	"github.com/PuerkitoBio/goquery"
)

var elemNameMap = map[string]string{
	"a":          "Anchor",
	"abbr":       "Abbreviation",
	"b":          "Bold",
	"bdi":        "BidirectionalIsolation",
	"bdo":        "BidirectionalOverride",
	"blockquote": "BlockQuote",
	"br":         "Break",
	"cite":       "Citation",
	"col":        "Column",
	"colgroup":   "ColumnGroup",
	"datalist":   "DataList",
	"dd":         "Description",
	"del":        "DeletedText",
	"dfn":        "Definition",
	"dl":         "DescriptionList",
	"dt":         "DefinitionTerm",
	"em":         "Emphasis",
	"fieldset":   "FieldSet",
	"figcaption": "FigureCaption",
	"h1":         "Header1",
	"h2":         "Header2",
	"h3":         "Header3",
	"h4":         "Header4",
	"h5":         "Header5",
	"h6":         "Header6",
	"hgroup":     "HeadingsGroup",
	"hr":         "HorizontalRule",
	"i":          "Italic",
	"iframe":     "InlineFrame",
	"img":        "Image",
	"ins":        "InsertedText",
	"kbd":        "KeyboardInput",
	"keygen":     "KeyGeneration",
	"li":         "ListItem",
	"menuitem":   "MenuItem",
	"nav":        "Navigation",
	"noframes":   "NoFrames",
	"noscript":   "NoScript",
	"ol":         "OrderedList",
	"optgroup":   "OptionsGroup",
	"p":          "Paragraph",
	"param":      "Parameter",
	"pre":        "Preformatted",
	"q":          "Quote",
	"rp":         "RubyParenthesis",
	"rt":         "RubyText",
	"rtc":        "RubyTextContainer",
	"s":          "Strikethrough",
	"samp":       "Sample",
	"sub":        "Subscript",
	"sup":        "Superscript",
	"tbody":      "TableBody",
	"textarea":   "TextArea",
	"td":         "TableData",
	"tfoot":      "TableFoot",
	"th":         "TableHeader",
	"thead":      "TableHead",
	"tr":         "TableRow",
	"u":          "Underline",
	"ul":         "UnorderedList",
	"var":        "Variable",
	"wbr":        "WordBreakOpportunity",
}

func main() {
	doc, err := goquery.NewDocument("https://developer.mozilla.org/en-US/docs/Web/HTML/Element")
	if err != nil {
		panic(err)
	}

	file, err := os.Create("elem.gen.go")
	if err != nil {
		panic(err)
	}
	defer file.Close()

	fmt.Fprint(file, `//go:generate go run generate.go

// Documentation source: "HTML element reference" by Mozilla Contributors, https://developer.mozilla.org/en-US/docs/Web/HTML/Element, licensed under CC-BY-SA 2.5.
package elem

import (
	"github.com/gopherjs/vecty"
)
`)

	doc.Find(".quick-links a").Each(func(i int, s *goquery.Selection) {
		link, _ := s.Attr("href")
		if !strings.HasPrefix(link, "/en-US/docs/Web/HTML/Element/") {
			return
		}

		if s.Parent().Find(".icon-trash, .icon-thumbs-down-alt, .icon-warning-sign").Length() > 0 {
			return
		}

		desc, _ := s.Attr("title")

		text := s.Text()
		if text == "Heading elements" {
			writeElem(file, "h1", desc, link)
			writeElem(file, "h2", desc, link)
			writeElem(file, "h3", desc, link)
			writeElem(file, "h4", desc, link)
			writeElem(file, "h5", desc, link)
			writeElem(file, "h6", desc, link)
			return
		}

		name := text[1 : len(text)-1]
		if name == "html" || name == "head" || name == "body" {
			return
		}

		writeElem(file, name, desc, link)
	})
}

func writeElem(w io.Writer, name, desc, link string) {
	funName := elemNameMap[name]
	if funName == "" {
		funName = capitalize(name)
	}

	fmt.Fprintf(w, `
// %s
// https://developer.mozilla.org%s
func %s(markup ...vecty.Markup) *vecty.Element {
	e := &vecty.Element{TagName: "%s"}
	vecty.List(markup).Apply(e)
	return e
}
`, desc, link, funName, name)
}

func capitalize(s string) string {
	return strings.ToUpper(s[:1]) + s[1:]
}
<commit_msg>elem: single line import statement<commit_after>// +build ignore

package main

import (
	"fmt"
	"io"
	"os"
	"strings"

	"github.com/PuerkitoBio/goquery"
)

var elemNameMap = map[string]string{
	"a":          "Anchor",
	"abbr":       "Abbreviation",
	"b":          "Bold",
	"bdi":        "BidirectionalIsolation",
	"bdo":        "BidirectionalOverride",
	"blockquote": "BlockQuote",
	"br":         "Break",
	"cite":       "Citation",
	"col":        "Column",
	"colgroup":   "ColumnGroup",
	"datalist":   "DataList",
	"dd":         "Description",
	"del":        "DeletedText",
	"dfn":        "Definition",
	"dl":         "DescriptionList",
	"dt":         "DefinitionTerm",
	"em":         "Emphasis",
	"fieldset":   "FieldSet",
	"figcaption": "FigureCaption",
	"h1":         "Header1",
	"h2":         "Header2",
	"h3":         "Header3",
	"h4":         "Header4",
	"h5":         "Header5",
	"h6":         "Header6",
	"hgroup":     "HeadingsGroup",
	"hr":         "HorizontalRule",
	"i":          "Italic",
	"iframe":     "InlineFrame",
	"img":        "Image",
	"ins":        "InsertedText",
	"kbd":        "KeyboardInput",
	"keygen":     "KeyGeneration",
	"li":         "ListItem",
	"menuitem":   "MenuItem",
	"nav":        "Navigation",
	"noframes":   "NoFrames",
	"noscript":   "NoScript",
	"ol":         "OrderedList",
	"optgroup":   "OptionsGroup",
	"p":          "Paragraph",
	"param":      "Parameter",
	"pre":        "Preformatted",
	"q":          "Quote",
	"rp":         "RubyParenthesis",
	"rt":         "RubyText",
	"rtc":        "RubyTextContainer",
	"s":          "Strikethrough",
	"samp":       "Sample",
	"sub":        "Subscript",
	"sup":        "Superscript",
	"tbody":      "TableBody",
	"textarea":   "TextArea",
	"td":         "TableData",
	"tfoot":      "TableFoot",
	"th":         "TableHeader",
	"thead":      "TableHead",
	"tr":         "TableRow",
	"u":          "Underline",
	"ul":         "UnorderedList",
	"var":        "Variable",
	"wbr":        "WordBreakOpportunity",
}

func main() {
	doc, err := goquery.NewDocument("https://developer.mozilla.org/en-US/docs/Web/HTML/Element")
	if err != nil {
		panic(err)
	}

	file, err := os.Create("elem.gen.go")
	if err != nil {
		panic(err)
	}
	defer file.Close()

	fmt.Fprint(file, `//go:generate go run generate.go

// Documentation source: "HTML element reference" by Mozilla Contributors, https://developer.mozilla.org/en-US/docs/Web/HTML/Element, licensed under CC-BY-SA 2.5.
package elem

import "github.com/gopherjs/vecty"
`)

	doc.Find(".quick-links a").Each(func(i int, s *goquery.Selection) {
		link, _ := s.Attr("href")
		if !strings.HasPrefix(link, "/en-US/docs/Web/HTML/Element/") {
			return
		}

		if s.Parent().Find(".icon-trash, .icon-thumbs-down-alt, .icon-warning-sign").Length() > 0 {
			return
		}

		desc, _ := s.Attr("title")

		text := s.Text()
		if text == "Heading elements" {
			writeElem(file, "h1", desc, link)
			writeElem(file, "h2", desc, link)
			writeElem(file, "h3", desc, link)
			writeElem(file, "h4", desc, link)
			writeElem(file, "h5", desc, link)
			writeElem(file, "h6", desc, link)
			return
		}

		name := text[1 : len(text)-1]
		if name == "html" || name == "head" || name == "body" {
			return
		}

		writeElem(file, name, desc, link)
	})
}

func writeElem(w io.Writer, name, desc, link string) {
	funName := elemNameMap[name]
	if funName == "" {
		funName = capitalize(name)
	}

	fmt.Fprintf(w, `
// %s
// https://developer.mozilla.org%s
func %s(markup ...vecty.Markup) *vecty.Element {
	e := &vecty.Element{TagName: "%s"}
	vecty.List(markup).Apply(e)
	return e
}
`, desc, link, funName, name)
}

func capitalize(s string) string {
	return strings.ToUpper(s[:1]) + s[1:]
}
<|endoftext|>


<commit_before>package formatters

import (
	"bytes"
	"fmt"
	"os"

	"github.com/behance/go-logrus"
)

// SumologicFormatter - takes entries and flattens them into a K=V format
// with an additional APP_NAME key
type SumologicFormatter struct{}

// Format - See logrus.Formatter.Format for docs
func (f SumologicFormatter) Format(entry *logrus.Entry) ([]byte, error) {
	b := &bytes.Buffer{}

	fmt.Fprintf(b, "APP_NAME='%s' ", appName())
	// KVEntryString in the kv.go file
	fmt.Fprintf(b, KVEntryString(entry))
	fmt.Fprintln(b)

	return b.Bytes(), nil
}

func appName() string {
	appname := os.Getenv("LOG_APP_NAME")
	if appname == "" {
		return "GolangApp"
	}
	return appname
}
<commit_msg>formatters/sumologic: add severity<commit_after>package formatters

import (
	"bytes"
	"fmt"
	"os"
	"strings"

	"github.com/behance/go-logrus"
)

// SumologicFormatter - takes entries and flattens them into a K=V format
// with an additional APP_NAME key
type SumologicFormatter struct{}

// Format - See logrus.Formatter.Format for docs
func (f SumologicFormatter) Format(entry *logrus.Entry) ([]byte, error) {
	b := &bytes.Buffer{}

	fmt.Fprintf(
		b,
		"APP_NAME='%s' SEVERITY='%s' ",
		appName(),
		strings.ToUpper(entry.Level.String()),
	)
	// KVEntryString in the kv.go file
	fmt.Fprintf(b, KVEntryString(entry))
	fmt.Fprintln(b)

	return b.Bytes(), nil
}

func appName() string {
	appname := os.Getenv("LOG_APP_NAME")
	if appname == "" {
		return "GolangApp"
	}
	return appname
}
<|endoftext|>


<commit_before>package frame

import (
	"fmt"
	"os"
	"strings"

	"github.com/zetamatta/go-windows-netresource"
	"github.com/zetamatta/go-windows-subst"
)

func optionNetUse(arg string) {
	piece := strings.SplitN(arg, "=", 2)
	if len(piece) >= 2 {
		_, err := netresource.NetUse(piece[0], piece[1])
		if err != nil {
			fmt.Fprintf(os.Stderr, "--netuse: %s: %s\n", arg, err.Error())
		}
	}
}

func optionSubst(arg string) {
	piece := strings.SplitN(arg, "=", 2)
	if len(piece) >= 2 {
		subst.Define(piece[0], piece[1])
	}
}
<commit_msg>Revert "If option --netuse fails, print error"<commit_after>package frame

import (
	"strings"

	"github.com/zetamatta/go-windows-netresource"
	"github.com/zetamatta/go-windows-subst"
)

func optionNetUse(arg string) {
	piece := strings.SplitN(arg, "=", 2)
	if len(piece) >= 2 {
		netresource.NetUse(piece[0], piece[1])
	}
}

func optionSubst(arg string) {
	piece := strings.SplitN(arg, "=", 2)
	if len(piece) >= 2 {
		subst.Define(piece[0], piece[1])
	}
}
<|endoftext|>


<commit_before>package main

import (
	"configuration"
	"coordinator"
	"flag"
	"fmt"
	"io/ioutil"
	"os"
	"path"
	"path/filepath"
	"runtime"
	"server"
	"strconv"
	"time"

	"github.com/jmhodges/levigo"

	log "code.google.com/p/log4go"
)

func setupLogging(loggingLevel, logFile string) {
	level := log.DEBUG
	switch loggingLevel {
	case "info":
		level = log.INFO
	case "warn":
		level = log.WARNING
	case "error":
		level = log.ERROR
	}

	log.Global = make(map[string]*log.Filter)

	if logFile == "stdout" {
		flw := log.NewConsoleLogWriter()
		log.AddFilter("stdout", level, flw)

	} else {
		logFileDir := filepath.Dir(logFile)
		os.MkdirAll(logFileDir, 0744)

		flw := log.NewFileLogWriter(logFile, false)
		log.AddFilter("file", level, flw)

		flw.SetFormat("[%D %T] [%L] (%S) %M")
		flw.SetRotate(true)
		flw.SetRotateSize(0)
		flw.SetRotateLines(0)
		flw.SetRotateDaily(true)
	}

	log.Info("Redirectoring logging to %s", logFile)
}

func main() {
	fileName := flag.String("config", "config.sample.toml", "Config file")
	wantsVersion := flag.Bool("v", false, "Get version number")
	resetRootPassword := flag.Bool("reset-root", false, "Reset root password")
	hostname := flag.String("hostname", "", "Override the hostname, the `hostname` config option will be overridden")
	raftPort := flag.Int("raft-port", 0, "Override the raft port, the `raft.port` config option will be overridden")
	protobufPort := flag.Int("protobuf-port", 0, "Override the protobuf port, the `protobuf_port` config option will be overridden")
	pidFile := flag.String("pidfile", "", "the pid file")
	repairLeveldb := flag.Bool("repair-ldb", false, "set to true to repair the leveldb files")

	runtime.GOMAXPROCS(runtime.NumCPU())
	flag.Parse()

	v := fmt.Sprintf("InfluxDB v%s (git: %s) (leveldb: %d.%d)", version, gitSha, levigo.GetLevelDBMajorVersion(), levigo.GetLevelDBMinorVersion())
	if wantsVersion != nil && *wantsVersion {
		fmt.Println(version)
		return
	}
	config := configuration.LoadConfiguration(*fileName)

	// override the hostname if it was specified on the command line
	if hostname != nil && *hostname != "" {
		config.Hostname = *hostname
	}

	if raftPort != nil && *raftPort != 0 {
		config.RaftServerPort = *raftPort
	}

	if protobufPort != nil && *protobufPort != 0 {
		config.ProtobufPort = *protobufPort
	}

	config.Version = v
	config.InfluxDBVersion = version

	setupLogging(config.LogLevel, config.LogFile)

	if *repairLeveldb {
		log.Info("Repairing leveldb")
		files, err := ioutil.ReadDir(config.DataDir)
		if err != nil {
			panic(err)
		}
		o := levigo.NewOptions()
		defer o.Close()
		for _, f := range files {
			p := path.Join(config.DataDir, f.Name())
			log.Info("Repairing %s", p)
			if err := levigo.RepairDatabase(p, o); err != nil {
				panic(err)
			}
		}
	}

	if pidFile != nil && *pidFile != "" {
		pid := strconv.Itoa(os.Getpid())
		if err := ioutil.WriteFile(*pidFile, []byte(pid), 0644); err != nil {
			panic(err)
		}
	}

	if config.BindAddress == "" {
		log.Info("Starting Influx Server %s...", version)
	} else {
		log.Info("Starting Influx Server %s bound to %s...", version, config.BindAddress)
	}
	fmt.Printf(`
+---------------------------------------------+
|  _____        __ _            _____  ____   |
| |_   _|      / _| |          |  __ \|  _ \  |
|   | |  _ __ | |_| |_   ___  _| |  | | |_) | |
|   | | | '_ \|  _| | | | \ \/ / |  | |  _ <  |
|  _| |_| | | | | | | |_| |>  <| |__| | |_) | |
| |_____|_| |_|_| |_|\__,_/_/\_\_____/|____/  |
+---------------------------------------------+

`)
	os.MkdirAll(config.RaftDir, 0744)
	os.MkdirAll(config.DataDir, 0744)
	server, err := server.NewServer(config)
	if err != nil {
		// sleep for the log to flush
		time.Sleep(time.Second)
		panic(err)
	}

	if err := startProfiler(server); err != nil {
		panic(err)
	}

	if *resetRootPassword {
		// TODO: make this not suck
		// This is ghetto as hell, but it'll work for now.
		go func() {
			time.Sleep(2 * time.Second) // wait for the raft server to join the cluster

			log.Warn("Resetting root's password to %s", coordinator.DEFAULT_ROOT_PWD)
			if err := server.RaftServer.CreateRootUser(); err != nil {
				panic(err)
			}
		}()
	}
	err = server.ListenAndServe()
	if err != nil {
		log.Error("ListenAndServe failed: ", err)
	}
}
<commit_msg>print the correct version<commit_after>package main

import (
	"configuration"
	"coordinator"
	"flag"
	"fmt"
	"io/ioutil"
	"os"
	"path"
	"path/filepath"
	"runtime"
	"server"
	"strconv"
	"time"

	"github.com/jmhodges/levigo"

	log "code.google.com/p/log4go"
)

func setupLogging(loggingLevel, logFile string) {
	level := log.DEBUG
	switch loggingLevel {
	case "info":
		level = log.INFO
	case "warn":
		level = log.WARNING
	case "error":
		level = log.ERROR
	}

	log.Global = make(map[string]*log.Filter)

	if logFile == "stdout" {
		flw := log.NewConsoleLogWriter()
		log.AddFilter("stdout", level, flw)

	} else {
		logFileDir := filepath.Dir(logFile)
		os.MkdirAll(logFileDir, 0744)

		flw := log.NewFileLogWriter(logFile, false)
		log.AddFilter("file", level, flw)

		flw.SetFormat("[%D %T] [%L] (%S) %M")
		flw.SetRotate(true)
		flw.SetRotateSize(0)
		flw.SetRotateLines(0)
		flw.SetRotateDaily(true)
	}

	log.Info("Redirectoring logging to %s", logFile)
}

func main() {
	fileName := flag.String("config", "config.sample.toml", "Config file")
	wantsVersion := flag.Bool("v", false, "Get version number")
	resetRootPassword := flag.Bool("reset-root", false, "Reset root password")
	hostname := flag.String("hostname", "", "Override the hostname, the `hostname` config option will be overridden")
	raftPort := flag.Int("raft-port", 0, "Override the raft port, the `raft.port` config option will be overridden")
	protobufPort := flag.Int("protobuf-port", 0, "Override the protobuf port, the `protobuf_port` config option will be overridden")
	pidFile := flag.String("pidfile", "", "the pid file")
	repairLeveldb := flag.Bool("repair-ldb", false, "set to true to repair the leveldb files")

	runtime.GOMAXPROCS(runtime.NumCPU())
	flag.Parse()

	v := fmt.Sprintf("InfluxDB v%s (git: %s) (leveldb: %d.%d)", version, gitSha, levigo.GetLevelDBMajorVersion(), levigo.GetLevelDBMinorVersion())
	if wantsVersion != nil && *wantsVersion {
		fmt.Println(v)
		return
	}
	config := configuration.LoadConfiguration(*fileName)

	// override the hostname if it was specified on the command line
	if hostname != nil && *hostname != "" {
		config.Hostname = *hostname
	}

	if raftPort != nil && *raftPort != 0 {
		config.RaftServerPort = *raftPort
	}

	if protobufPort != nil && *protobufPort != 0 {
		config.ProtobufPort = *protobufPort
	}

	config.Version = v
	config.InfluxDBVersion = version

	setupLogging(config.LogLevel, config.LogFile)

	if *repairLeveldb {
		log.Info("Repairing leveldb")
		files, err := ioutil.ReadDir(config.DataDir)
		if err != nil {
			panic(err)
		}
		o := levigo.NewOptions()
		defer o.Close()
		for _, f := range files {
			p := path.Join(config.DataDir, f.Name())
			log.Info("Repairing %s", p)
			if err := levigo.RepairDatabase(p, o); err != nil {
				panic(err)
			}
		}
	}

	if pidFile != nil && *pidFile != "" {
		pid := strconv.Itoa(os.Getpid())
		if err := ioutil.WriteFile(*pidFile, []byte(pid), 0644); err != nil {
			panic(err)
		}
	}

	if config.BindAddress == "" {
		log.Info("Starting Influx Server %s...", version)
	} else {
		log.Info("Starting Influx Server %s bound to %s...", version, config.BindAddress)
	}
	fmt.Printf(`
+---------------------------------------------+
|  _____        __ _            _____  ____   |
| |_   _|      / _| |          |  __ \|  _ \  |
|   | |  _ __ | |_| |_   ___  _| |  | | |_) | |
|   | | | '_ \|  _| | | | \ \/ / |  | |  _ <  |
|  _| |_| | | | | | | |_| |>  <| |__| | |_) | |
| |_____|_| |_|_| |_|\__,_/_/\_\_____/|____/  |
+---------------------------------------------+

`)
	os.MkdirAll(config.RaftDir, 0744)
	os.MkdirAll(config.DataDir, 0744)
	server, err := server.NewServer(config)
	if err != nil {
		// sleep for the log to flush
		time.Sleep(time.Second)
		panic(err)
	}

	if err := startProfiler(server); err != nil {
		panic(err)
	}

	if *resetRootPassword {
		// TODO: make this not suck
		// This is ghetto as hell, but it'll work for now.
		go func() {
			time.Sleep(2 * time.Second) // wait for the raft server to join the cluster

			log.Warn("Resetting root's password to %s", coordinator.DEFAULT_ROOT_PWD)
			if err := server.RaftServer.CreateRootUser(); err != nil {
				panic(err)
			}
		}()
	}
	err = server.ListenAndServe()
	if err != nil {
		log.Error("ListenAndServe failed: ", err)
	}
}
<|endoftext|>


<commit_before>package main

import (
	log "code.google.com/p/log4go"
	"configuration"
	"coordinator"
	"flag"
	"fmt"
	"io/ioutil"
	"os"
	"os/signal"
	"path/filepath"
	"runtime"
	"server"
	"strconv"
	"syscall"
	"time"
)

const (
	version = "dev"
	gitSha  = "HEAD"
)

func waitForSignals(stopped <-chan bool) {
	ch := make(chan os.Signal)
	signal.Notify(ch, syscall.SIGTERM, syscall.SIGINT)
	for {
		sig := <-ch
		log.Info("Received signal: %s\n", sig.String())
		switch sig {
		case syscall.SIGINT, syscall.SIGTERM:
			runtime.SetCPUProfileRate(0)
			<-stopped
			os.Exit(0)
		}
	}
}

func startProfiler(filename *string) error {
	if filename == nil || *filename == "" {
		return nil
	}

	cpuProfileFile, err := os.Create(*filename)
	if err != nil {
		return err
	}
	runtime.SetCPUProfileRate(500)
	stopped := make(chan bool)

	go waitForSignals(stopped)

	go func() {
		for {
			select {
			default:
				data := runtime.CPUProfile()
				if data == nil {
					cpuProfileFile.Close()
					stopped <- true
					break
				}
				cpuProfileFile.Write(data)
			}
		}
	}()
	return nil
}

func setupLogging(loggingLevel, logFile string) {
	level := log.DEBUG
	switch loggingLevel {
	case "info":
		level = log.INFO
	case "warn":
		level = log.WARNING
	case "error":
		level = log.ERROR
	}

	for _, filter := range log.Global {
		filter.Level = level
	}

	logFileDir := filepath.Dir(logFile)
	os.MkdirAll(logFileDir, 0744)

	flw := log.NewFileLogWriter(logFile, false)
	flw.SetFormat("[%D %T] [%L] (%S) %M")
	flw.SetRotate(true)
	flw.SetRotateSize(0)
	flw.SetRotateLines(0)
	flw.SetRotateDaily(true)
	log.AddFilter("file", level, flw)
	log.Info("Redirectoring logging to %s", logFile)
}

func main() {
	fileName := flag.String("config", "config.toml.sample", "Config file")
	wantsVersion := flag.Bool("v", false, "Get version number")
	resetRootPassword := flag.Bool("reset-root", false, "Reset root password")
	pidFile := flag.String("pidfile", "", "the pid file")
	cpuProfiler := flag.String("cpuprofile", "", "filename where cpu profile data will be written")

	runtime.GOMAXPROCS(runtime.NumCPU())
	flag.Parse()

	startProfiler(cpuProfiler)

	if wantsVersion != nil && *wantsVersion {
		fmt.Printf("InfluxDB v%s (git: %s)\n", version, gitSha)
		return
	}
	config := configuration.LoadConfiguration(*fileName)
	setupLogging(config.LogLevel, config.LogFile)

	if pidFile != nil && *pidFile != "" {
		pid := strconv.Itoa(os.Getpid())
		if err := ioutil.WriteFile(*pidFile, []byte(pid), 0644); err != nil {
			panic(err)
		}
	}

	log.Info("Starting Influx Server...")
	log.Info(`
+---------------------------------------------+
|  _____        __ _            _____  ____   |
| |_   _|      / _| |          |  __ \|  _ \  |
|   | |  _ __ | |_| |_   ___  _| |  | | |_) | |
|   | | | '_ \|  _| | | | \ \/ / |  | |  _ <  |
|  _| |_| | | | | | | |_| |>  <| |__| | |_) | |
| |_____|_| |_|_| |_|\__,_/_/\_\_____/|____/  |
+---------------------------------------------+

`)
	os.MkdirAll(config.RaftDir, 0744)
	os.MkdirAll(config.DataDir, 0744)
	server, err := server.NewServer(config)
	if err != nil {
		panic(err)
	}

	if *resetRootPassword {
		// TODO: make this not suck
		// This is ghetto as hell, but it'll work for now.
		go func() {
			time.Sleep(2 * time.Second) // wait for the raft server to join the cluster

			log.Warn("Resetting root's password to %s", coordinator.DEFAULT_ROOT_PWD)
			if err := server.RaftServer.CreateRootUser(); err != nil {
				panic(err)
			}
		}()
	}
	err = server.ListenAndServe()
	if err != nil {
		log.Error("ListenAndServe failed: ", err)
	}
}
<commit_msg>allow logging to stdout<commit_after>package main

import (
	log "code.google.com/p/log4go"
	"configuration"
	"coordinator"
	"flag"
	"fmt"
	"io/ioutil"
	"os"
	"os/signal"
	"path/filepath"
	"runtime"
	"server"
	"strconv"
	"syscall"
	"time"
)

const (
	version = "dev"
	gitSha  = "HEAD"
)

func waitForSignals(stopped <-chan bool) {
	ch := make(chan os.Signal)
	signal.Notify(ch, syscall.SIGTERM, syscall.SIGINT)
	for {
		sig := <-ch
		log.Info("Received signal: %s\n", sig.String())
		switch sig {
		case syscall.SIGINT, syscall.SIGTERM:
			runtime.SetCPUProfileRate(0)
			<-stopped
			os.Exit(0)
		}
	}
}

func startProfiler(filename *string) error {
	if filename == nil || *filename == "" {
		return nil
	}

	cpuProfileFile, err := os.Create(*filename)
	if err != nil {
		return err
	}
	runtime.SetCPUProfileRate(500)
	stopped := make(chan bool)

	go waitForSignals(stopped)

	go func() {
		for {
			select {
			default:
				data := runtime.CPUProfile()
				if data == nil {
					cpuProfileFile.Close()
					stopped <- true
					break
				}
				cpuProfileFile.Write(data)
			}
		}
	}()
	return nil
}

func setupLogging(loggingLevel, logFile string) {
	level := log.DEBUG
	switch loggingLevel {
	case "info":
		level = log.INFO
	case "warn":
		level = log.WARNING
	case "error":
		level = log.ERROR
	}

	for _, filter := range log.Global {
		filter.Level = level
	}

	if logFile == "stdout" {
		flw := log.NewConsoleLogWriter()
		log.AddFilter("stdout", level, flw)

	} else {
		logFileDir := filepath.Dir(logFile)
		os.MkdirAll(logFileDir, 0744)

		flw := log.NewFileLogWriter(logFile, false)
		log.AddFilter("file", level, flw)

		flw.SetFormat("[%D %T] [%L] (%S) %M")
		flw.SetRotate(true)
		flw.SetRotateSize(0)
		flw.SetRotateLines(0)
		flw.SetRotateDaily(true)
	}

	log.Info("Redirectoring logging to %s", logFile)
}

func main() {
	fileName := flag.String("config", "config.toml.sample", "Config file")
	wantsVersion := flag.Bool("v", false, "Get version number")
	resetRootPassword := flag.Bool("reset-root", false, "Reset root password")
	pidFile := flag.String("pidfile", "", "the pid file")
	cpuProfiler := flag.String("cpuprofile", "", "filename where cpu profile data will be written")

	runtime.GOMAXPROCS(runtime.NumCPU())
	flag.Parse()

	startProfiler(cpuProfiler)

	if wantsVersion != nil && *wantsVersion {
		fmt.Printf("InfluxDB v%s (git: %s)\n", version, gitSha)
		return
	}
	config := configuration.LoadConfiguration(*fileName)
	setupLogging(config.LogLevel, config.LogFile)

	if pidFile != nil && *pidFile != "" {
		pid := strconv.Itoa(os.Getpid())
		if err := ioutil.WriteFile(*pidFile, []byte(pid), 0644); err != nil {
			panic(err)
		}
	}

	log.Info("Starting Influx Server...")
	log.Info(`
+---------------------------------------------+
|  _____        __ _            _____  ____   |
| |_   _|      / _| |          |  __ \|  _ \  |
|   | |  _ __ | |_| |_   ___  _| |  | | |_) | |
|   | | | '_ \|  _| | | | \ \/ / |  | |  _ <  |
|  _| |_| | | | | | | |_| |>  <| |__| | |_) | |
| |_____|_| |_|_| |_|\__,_/_/\_\_____/|____/  |
+---------------------------------------------+

`)
	os.MkdirAll(config.RaftDir, 0744)
	os.MkdirAll(config.DataDir, 0744)
	server, err := server.NewServer(config)
	if err != nil {
		panic(err)
	}

	if *resetRootPassword {
		// TODO: make this not suck
		// This is ghetto as hell, but it'll work for now.
		go func() {
			time.Sleep(2 * time.Second) // wait for the raft server to join the cluster

			log.Warn("Resetting root's password to %s", coordinator.DEFAULT_ROOT_PWD)
			if err := server.RaftServer.CreateRootUser(); err != nil {
				panic(err)
			}
		}()
	}
	err = server.ListenAndServe()
	if err != nil {
		log.Error("ListenAndServe failed: ", err)
	}
}
<|endoftext|>


<commit_before>package data

import (
	"encoding/csv"
	"time"
	"fmt"
	"strconv"
	"io"
)

func CSVParse(file io.Reader) (labels []string, data []Record) {
	labels, data = csvParse(file)
	return
}

func csvParse(file io.Reader) (labels []string, data []Record) {
	reader := csv.NewReader (file)
	tmpdata, err := reader.ReadAll()
	if  err != nil {
		fmt.Println(err)
	}
	fmt.Println(len(tmpdata) - 1)
	labels = make([]string, 6)
	//labels = tmpdata[0]
	data  = make([]Record,  len(tmpdata)-1)
	for i := 1; i<len(tmpdata)-1; i++ {
		data[i-1].Time, _ = time.Parse(ISO, tmpdata[i][0])
		data[i-1].Radiation, err = strconv.ParseFloat(tmpdata[i][1], 64)
		if err != nil {
			data[i-1].empty = true
		}
		data[i-1].Humidity, err = strconv.ParseFloat(tmpdata[i][2], 64)
		if err != nil {
			data[i-1].empty = true
		}
		data[i-1].Temperature, err = strconv.ParseFloat(tmpdata[i][2], 64)
		if err != nil {
			data[i-1].empty = true
		}
		data[i-1].Wind, err = strconv.ParseFloat(tmpdata[i][2], 64)
		if err != nil {
			data[i-1].empty = true
		}
		data[i-1].Power, err = strconv.ParseFloat(tmpdata[i][2], 64)
		if err != nil {
			data[i-1].Null = true
		}
	}
	fmt.Println(len(data))
	data = fillRecords (data)
	fmt.Println(len(data))
	return
}

func fillRecords (emptyData []Record) (data []Record){
	gradRad, gradHumidity, gradTemp, gradWind := 0.0, 0.0, 0.0, 0.0
	fmt.Println(len(emptyData))
	for i := 0; i<len(emptyData); i++ {
		if emptyData[i].empty && i > 0 {
			emptyData[i].Radiation = emptyData[i-1].Radiation + gradRad
			emptyData[i].Humidity = emptyData[i-1].Humidity + gradHumidity
			emptyData[i].Temperature = emptyData[i-1].Temperature + gradTemp
			emptyData[i].Wind = emptyData[i-1].Wind + gradWind
			emptyData[i].empty = false
		} else {
			if i + 4 < len (emptyData) {
				gradRad = (emptyData[i+4].Radiation - emptyData[i].Radiation)/4
				gradHumidity = (emptyData[i+4].Humidity - emptyData[i].Humidity)/4
				gradTemp = (emptyData[i+4].Temperature - emptyData[i].Temperature)/4
				gradWind = (emptyData[i+4].Wind - emptyData[i].Wind)/4
			} else {
				gradRad = 0
				gradHumidity = 0
				gradTemp = 0
				gradWind = 0
			}
		}
	}
	return emptyData
}
<commit_msg>I'm an idiot who doesn't pay attention to indices<commit_after>package data

import (
	"encoding/csv"
	"time"
	"fmt"
	"strconv"
	"io"
)

func CSVParse(file io.Reader) (labels []string, data []Record) {
	labels, data = csvParse(file)
	return
}

func csvParse(file io.Reader) (labels []string, data []Record) {
	reader := csv.NewReader (file)
	tmpdata, err := reader.ReadAll()
	if  err != nil {
		fmt.Println(err)
	}
	fmt.Println(len(tmpdata) - 1)
	labels = make([]string, 6)
	//labels = tmpdata[0]
	data  = make([]Record,  len(tmpdata)-1)
	for i := 1; i<len(tmpdata)-1; i++ {
		data[i-1].Time, _ = time.Parse(ISO, tmpdata[i][0])
		data[i-1].Radiation, err = strconv.ParseFloat(tmpdata[i][1], 64)
		if err != nil {
			data[i-1].empty = true
		}
		data[i-1].Humidity, err = strconv.ParseFloat(tmpdata[i][2], 64)
		if err != nil {
			data[i-1].empty = true
		}
		data[i-1].Temperature, err = strconv.ParseFloat(tmpdata[i][3], 64)
		if err != nil {
			data[i-1].empty = true
		}
		data[i-1].Wind, err = strconv.ParseFloat(tmpdata[i][4], 64)
		if err != nil {
			data[i-1].empty = true
		}
		data[i-1].Power, err = strconv.ParseFloat(tmpdata[i][5], 64)
		if err != nil {
			data[i-1].Null = true
		}
	}
	fmt.Println(len(data))
	data = fillRecords (data)
	fmt.Println(len(data))
	return
}

func fillRecords (emptyData []Record) (data []Record){
	gradRad, gradHumidity, gradTemp, gradWind := 0.0, 0.0, 0.0, 0.0
	fmt.Println(len(emptyData))
	for i := 0; i<len(emptyData); i++ {
		if emptyData[i].empty && i > 0 {
			emptyData[i].Radiation = emptyData[i-1].Radiation + gradRad
			emptyData[i].Humidity = emptyData[i-1].Humidity + gradHumidity
			emptyData[i].Temperature = emptyData[i-1].Temperature + gradTemp
			emptyData[i].Wind = emptyData[i-1].Wind + gradWind
			emptyData[i].empty = false
		} else {
			if i + 4 < len (emptyData) {
				gradRad = (emptyData[i+4].Radiation - emptyData[i].Radiation)/4
				gradHumidity = (emptyData[i+4].Humidity - emptyData[i].Humidity)/4
				gradTemp = (emptyData[i+4].Temperature - emptyData[i].Temperature)/4
				gradWind = (emptyData[i+4].Wind - emptyData[i].Wind)/4
			} else {
				gradRad = 0
				gradHumidity = 0
				gradTemp = 0
				gradWind = 0
			}
		}
	}
	return emptyData
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"github.com/onsi/ginkgo/ginkgo/testsuite"
	"os"
	"os/exec"
)

func verifyNotificationsAreAvailable() {
	_, err := exec.LookPath("terminal-notifier")
	if err != nil {
		fmt.Printf(`--notify requires terminal-notifier, which you don't seem to have installed.

To remedy this:

    brew install terminal-notifer

To learn more about terminal-notifier:

    https://github.com/alloy/terminal-notifier
`)
		os.Exit(1)
	}
}

func sendSuiteCompletionNotification(suite *testsuite.TestSuite, suitePassed bool) {
	if suitePassed {
		sendNotification("Ginkgo [PASS]", fmt.Sprintf(`Test suite for "%s" passed.`, suite.PackageName))
	} else {
		sendNotification("Ginkgo [FAIL]", fmt.Sprintf(`Test suite for "%s" failed.`, suite.PackageName))
	}
}

func sendNotification(title string, subtitle string) {
	args := []string{"-title", title, "-subtitle", subtitle, "-group", "com.onsi.ginkgo"}

	terminal := os.Getenv("TERM_PROGRAM")
	if terminal == "iTerm.app" {
		args = append(args, "-activate", "com.googlecode.iterm2")
	} else if terminal == "Apple_Terminal" {
		args = append(args, "-activate", "com.apple.Terminal")
	}

	if notify {
		exec.Command("terminal-notifier", args...).Run()
	}
}
<commit_msg>Fix typo in 'terminal-notifier' instructions<commit_after>package main

import (
	"fmt"
	"github.com/onsi/ginkgo/ginkgo/testsuite"
	"os"
	"os/exec"
)

func verifyNotificationsAreAvailable() {
	_, err := exec.LookPath("terminal-notifier")
	if err != nil {
		fmt.Printf(`--notify requires terminal-notifier, which you don't seem to have installed.

To remedy this:

    brew install terminal-notifier

To learn more about terminal-notifier:

    https://github.com/alloy/terminal-notifier
`)
		os.Exit(1)
	}
}

func sendSuiteCompletionNotification(suite *testsuite.TestSuite, suitePassed bool) {
	if suitePassed {
		sendNotification("Ginkgo [PASS]", fmt.Sprintf(`Test suite for "%s" passed.`, suite.PackageName))
	} else {
		sendNotification("Ginkgo [FAIL]", fmt.Sprintf(`Test suite for "%s" failed.`, suite.PackageName))
	}
}

func sendNotification(title string, subtitle string) {
	args := []string{"-title", title, "-subtitle", subtitle, "-group", "com.onsi.ginkgo"}

	terminal := os.Getenv("TERM_PROGRAM")
	if terminal == "iTerm.app" {
		args = append(args, "-activate", "com.googlecode.iterm2")
	} else if terminal == "Apple_Terminal" {
		args = append(args, "-activate", "com.apple.Terminal")
	}

	if notify {
		exec.Command("terminal-notifier", args...).Run()
	}
}
<|endoftext|>


<commit_before>package functional

// A Consumer of T consumes the T values from a Stream of T.
type Consumer interface {

  // Consume consumes values from Stream s
  Consume(s Stream)
}

// ModifyConsumerStream returns a new Consumer that applies f to its Stream
// and then gives the result to c. If c is a Consumer of T and f takes a
// Stream of U and returns a Stream of T, then ModifyConsumerStream returns a
// Consumer of U.
func ModifyConsumerStream(c Consumer, f func(s Stream) Stream) Consumer {
  return &modifiedConsumerStream{c, f}
}

// MultiConsume consumes the values of s, a Stream of T, sending those T
// values to each Consumer in consumers. MultiConsume consumes values from s
// until no Consumer in consumers is accepting values.
// ptr is a *T that receives the values from s. copier is a Copier
// of T used to copy T values to the Streams sent to each Consumer in
// consumers. Passing null for copier means use simple assignment.
// Finally MultiConsume closes s and returns the result.
func MultiConsume(s Stream, ptr interface{}, copier Copier, consumers ...Consumer) error {
  if copier == nil {
    copier = assignCopier
  }
  streams := make([]*splitStream, len(consumers))
  stillConsuming := false
  for i := range streams {
    streams[i] = &splitStream{emitterStream{ptrCh: make(chan interface{}), errCh: make(chan error)}}
    go func(idx int) {
      streams[idx].startStream()
      consumers[idx].Consume(streams[idx])
      streams[idx].endStream()
    }(i)
    streams[i].Return(nil)
    if !streams[i].isClosed() {
      stillConsuming = true
    }
  }
  for stillConsuming {
    err := s.Next(ptr)
    stillConsuming = false
    for i := range streams {
      if !streams[i].isClosed() {
        p := streams[i].EmitPtr()
        copier(ptr, p)
        streams[i].Return(err)
        if !streams[i].isClosed() {
          stillConsuming = true
        }
      }
    }
  }
  return s.Close()
}

type modifiedConsumerStream struct {
  c Consumer
  f func(s Stream) Stream
}

func (mc *modifiedConsumerStream) Consume(s Stream) {
  mc.c.Consume(mc.f(s))
}

type splitStream struct {
  emitterStream
}

func (s *splitStream) Next(ptr interface{}) error {
  if ptr == nil {
    panic("Got nil pointer in Next.")
  }
  return s.emitterStream.Next(ptr)
}

func (s *splitStream) Close() error {
  return nil
}

func (s *splitStream) Return(err error) {
  if s.isClosed() {
    return
  }
  s.emitterStream.Return(err)
  if s.EmitPtr() == nil {
    s.close()
  }
}
<commit_msg>In MultiConsume, allow each Consumer to run concurrently.<commit_after>package functional

// A Consumer of T consumes the T values from a Stream of T.
type Consumer interface {

  // Consume consumes values from Stream s
  Consume(s Stream)
}

// ModifyConsumerStream returns a new Consumer that applies f to its Stream
// and then gives the result to c. If c is a Consumer of T and f takes a
// Stream of U and returns a Stream of T, then ModifyConsumerStream returns a
// Consumer of U.
func ModifyConsumerStream(c Consumer, f func(s Stream) Stream) Consumer {
  return &modifiedConsumerStream{c, f}
}

// MultiConsume consumes the values of s, a Stream of T, sending those T
// values to each Consumer in consumers. MultiConsume consumes values from s
// until no Consumer in consumers is accepting values.
// ptr is a *T that receives the values from s. copier is a Copier
// of T used to copy T values to the Streams sent to each Consumer in
// consumers. Passing null for copier means use simple assignment.
// Finally MultiConsume closes s and returns the result.
func MultiConsume(s Stream, ptr interface{}, copier Copier, consumers ...Consumer) error {
  if copier == nil {
    copier = assignCopier
  }
  streams := make([]*splitStream, len(consumers))
  for i := range streams {
    streams[i] = &splitStream{emitterStream{ptrCh: make(chan interface{}), errCh: make(chan error)}}
    go func(s *splitStream, c Consumer) {
      s.startStream()
      c.Consume(s)
      s.endStream()
    }(streams[i], consumers[i])
  }
  var err error
  for asyncReturn(streams, err) {
    err = s.Next(ptr)
    for i := range streams {
      if !streams[i].isClosed() {
        p := streams[i].EmitPtr()
        copier(ptr, p)
      }
    }
  }
  return s.Close()
}

type modifiedConsumerStream struct {
  c Consumer
  f func(s Stream) Stream
}

func (mc *modifiedConsumerStream) Consume(s Stream) {
  mc.c.Consume(mc.f(s))
}

type splitStream struct {
  emitterStream
}

func (s *splitStream) Next(ptr interface{}) error {
  if ptr == nil {
    panic("Got nil pointer in Next.")
  }
  return s.emitterStream.Next(ptr)
}

func (s *splitStream) Close() error {
  return nil
}

func asyncReturn(streams []*splitStream, err error) bool {
  for i := range streams {
    if !streams[i].isClosed() {
      streams[i].errCh <- err
    }
  }
  result := false
  for i := range streams {
    if !streams[i].isClosed() {
      streams[i].ptr = <-streams[i].ptrCh
      if streams[i].ptr == nil {
        streams[i].close()
      } else {
        result = true
      }
    }
  }
  return result
}
<|endoftext|>


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

package model

import (
	"strings"
)

const (
	// ExporterLabelPrefix is the label name prefix to prepend if a
	// synthetic label is already present in the exported metrics.
	ExporterLabelPrefix LabelName = "exporter_"

	// MetricNameLabel is the label name indicating the metric name of a
	// timeseries.
	MetricNameLabel LabelName = "__name__"

	// AddressLabel is the name of the label that holds the address of
	// a scrape target.
	AddressLabel LabelName = "__address__"

	// ReservedLabelPrefix is a prefix which is not legal in user-supplied
	// label names.
	ReservedLabelPrefix = "__"

	// HiddenLabelPrefix is a prefix which is legal in user-supplied label names
	// but will not appear in the eventual metrics.
	// Reserved labels may be excepted from that rule.
	HiddenLabelPrefix = "_"

	// JobLabel is the label name indicating the job from which a timeseries
	// was scraped.
	JobLabel LabelName = "job"

	// InstanceLabel is the label name used for the instance label.
	InstanceLabel LabelName = "instance"

	// BucketLabel is used for the label that defines the upper bound of a
	// bucket of a histogram ("le" -> "less or equal").
	BucketLabel = "le"

	// QuantileLabel is used for the label that defines the quantile in a
	// summary.
	QuantileLabel = "quantile"
)

// A LabelName is a key for a LabelSet or Metric.  It has a value associated
// therewith.
type LabelName string

// LabelNames is a sortable LabelName slice. In implements sort.Interface.
type LabelNames []LabelName

func (l LabelNames) Len() int {
	return len(l)
}

func (l LabelNames) Less(i, j int) bool {
	return l[i] < l[j]
}

func (l LabelNames) Swap(i, j int) {
	l[i], l[j] = l[j], l[i]
}

func (l LabelNames) String() string {
	labelStrings := make([]string, 0, len(l))
	for _, label := range l {
		labelStrings = append(labelStrings, string(label))
	}
	return strings.Join(labelStrings, ", ")
}
<commit_msg>Replace hidden label prefix with meta prefix.<commit_after>// Copyright 2013 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package model

import (
	"strings"
)

const (
	// ExporterLabelPrefix is the label name prefix to prepend if a
	// synthetic label is already present in the exported metrics.
	ExporterLabelPrefix LabelName = "exporter_"

	// MetricNameLabel is the label name indicating the metric name of a
	// timeseries.
	MetricNameLabel LabelName = "__name__"

	// AddressLabel is the name of the label that holds the address of
	// a scrape target.
	AddressLabel LabelName = "__address__"

	// ReservedLabelPrefix is a prefix which is not legal in user-supplied
	// label names.
	ReservedLabelPrefix = "__"

	// MetaLabelPrefix is a prefix for labels that provide meta information.
	// Labels with this prefix are used for intermediate label processing and
	// will not be attached to time series.
	MetaLabelPrefix = "__meta_"

	// JobLabel is the label name indicating the job from which a timeseries
	// was scraped.
	JobLabel LabelName = "job"

	// InstanceLabel is the label name used for the instance label.
	InstanceLabel LabelName = "instance"

	// BucketLabel is used for the label that defines the upper bound of a
	// bucket of a histogram ("le" -> "less or equal").
	BucketLabel = "le"

	// QuantileLabel is used for the label that defines the quantile in a
	// summary.
	QuantileLabel = "quantile"
)

// A LabelName is a key for a LabelSet or Metric.  It has a value associated
// therewith.
type LabelName string

// LabelNames is a sortable LabelName slice. In implements sort.Interface.
type LabelNames []LabelName

func (l LabelNames) Len() int {
	return len(l)
}

func (l LabelNames) Less(i, j int) bool {
	return l[i] < l[j]
}

func (l LabelNames) Swap(i, j int) {
	l[i], l[j] = l[j], l[i]
}

func (l LabelNames) String() string {
	labelStrings := make([]string, 0, len(l))
	for _, label := range l {
		labelStrings = append(labelStrings, string(label))
	}
	return strings.Join(labelStrings, ", ")
}
<|endoftext|>


<commit_before>package kong

import (
	"fmt"
	"net/http"

	"github.com/dghubble/sling"
	//"github.com/hashicorp/terraform/helper/schema"
	"github.com/hashicorp/terraform/helper/schema"
)

var (
	HealthchecksTypes = []string{"http", "tcp", "https"}
)

type Upstream struct {
	ID                 string `json:"id,omitempty"`
	Name               string `json:"name,omitempty"`
	Slots              int    `json:"slots,omitempty"`
	HashOn             string `json:"hash_on,omitempty"`
	HashFallback       string `json:"hash_fallback,omitempty"`
	HashOnHeader       string `json:"hash_on_header,omitempty"`
	HashFallbackHeader string `json:"hash_fallback_header,omitempty"`
	HashOnCookie       string `json:"hash_on_cookie,omitempty"`
	HashOnCookiePath   string `json:"hash_on_cookie_path,omitempty"`
	Algorithm          string `json:"algorithm,omitempty"`
	HealthChecks       []interface{} `json:"healthchecks,omitempty"`
}

func resourceKongUpstream() *schema.Resource {
	return &schema.Resource{
		Create: resourceKongUpstreamCreate,
		Read:   resourceKongUpstreamRead,
		Update: resourceKongUpstreamUpdate,
		Delete: resourceKongUpstreamDelete,

		Schema: map[string]*schema.Schema{
			"name": {
				Type:        schema.TypeString,
				Required:    true,
				Description: "This is a hostname, which must be equal to the host of a Service.",
			},
			"slots": {
				Type:        schema.TypeInt,
				Optional:    true,
				Description: "The number of slots in the loadbalancer algorithm (10-65536, defaults to 1000).",
				Default:     1000,
				ValidateFunc: func(i interface{}, s string) (strings []string, errors []error) {
					slots := i.(int)

					if slots >= 10 && slots <= 65536 {
						return nil, nil
					}

					return nil, []error{fmt.Errorf("slots value of %d not in the range of 10-65536", slots)}
				},
			},
			"hash_on": {
				Type:        schema.TypeString,
				Optional:    true,
				Description: "What to use as hashing input: none, consumer, ip, header, or cookie (defaults to none resulting in a weighted-round-robin scheme).",
				Default:     "none",
				ValidateFunc: func(i interface{}, s string) (strings []string, errors []error) {
					// TODO: validate against [none, consume, ip, header, cookie]
					return nil, nil
				},
			},
			"hash_fallback": {
				Type:        schema.TypeString,
				Optional:    true,
				Description: "What to use as hashing input if the primary hash_on does not return a hash (eg. header is missing, or no consumer identified). One of: none, consumer, ip, header, or cookie (defaults to none, not available if hash_on is set to cookie).",
				Default:     "none",
				ValidateFunc: func(i interface{}, s string) (strings []string, errors []error) {
					// TODO: validate against [none, consume, ip, header, cookie]
					return nil, nil
				},
			},
			"hash_on_header": {
				Type:        schema.TypeString,
				Optional:    true,
				Description: "The header name to take the value from as hash input (only required when hash_on is set to header).",
			},
			"hash_fallback_header": {
				Type:        schema.TypeString,
				Optional:    true,
				Description: "The header name to take the value from as hash input (only required when hash_fallback is set to header).",
			},
			"hash_on_cookie": {
				Type:        schema.TypeString,
				Optional:    true,
				Description: "The cookie name to take the value from as hash input (only required when hash_on or hash_fallback is set to cookie). If the specified cookie is not in the request, Kong will generate a value and set the cookie in the response.",
			},
			"hash_on_cookie_path": {
				Type:     schema.TypeString,
				Optional: true,
				Default:  "/",
				DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
					return (old == "" && new == "/") || (old == "/" && new == "")
				},
				Description: "The cookie path to set in the response headers (only required when hash_on or hash_fallback is set to cookie, defaults to \"/\")",
			},
			"algorithm": {
				Type:        schema.TypeString,
				Optional:    true,
				Description: "Which load balancing algorithm to use. One of: round-robin, consistent-hashing, or least-connections. Defaults to \"round-robin\". Kong 1.3.0 and up.",
				ValidateFunc: func(i interface{}, s string) (strings []string, errors []error) {
					algs := []string{"round-robin", "consistent-hashing", "least-connections"}
					for i := 0; i < len(algs); i++ {
						if algs[i] == s {
							return nil, nil
						}
					}

					return nil, append(errors, fmt.Errorf("algorithm must be one of %v. %s was provided instead", algs, s))
				},
			},
			"healthchecks": {
				Type:        schema.TypeList,
				Optional:    true,
				ForceNew:    true,
				MaxItems:    1,
				Description: "Health checks configuration for upstream.",
				Elem: &schema.Resource{
					Schema: map[string]*schema.Schema{
						"active": {
							Type:     schema.TypeList,
							Optional: true,
							ForceNew: true,
							MaxItems: 1,
							Elem: &schema.Resource{
								Schema: map[string]*schema.Schema{
									"https_verify_certificate": {
										Type:     schema.TypeBool,
										Optional: true,
									},
									"http_path": {
										Type:     schema.TypeString,
										Optional: true,
									},
									"timeout": {
										Type:     schema.TypeInt,
										Optional: true,
									},
									"https_sni": {
										Type:     schema.TypeString,
										Optional: true,
									},
									"concurrency": {
										Type:     schema.TypeInt,
										Optional: true,
									},
									"type": {
										Type:     schema.TypeString,
										Optional: true,
										//ExactlyOneOf: HealthchecksTypes,
									},
									"healthy": {
										Type:     schema.TypeList,
										Optional: true,
										ForceNew: true,
										MaxItems: 1,
										Elem: &schema.Resource{
											Schema: map[string]*schema.Schema{
												"successes": {
													Type:     schema.TypeInt,
													Optional: true,
												},
												"interval": {
													Type:     schema.TypeInt,
													Optional: true,
												},
												"http_statuses": {
													Type:     schema.TypeList,
													Optional: true,
													Elem:     schema.TypeString,
												},
											},
										},
									},
									"unhealthy": {
										Type:     schema.TypeList,
										Optional: true,
										ForceNew: true,
										MaxItems: 1,
										Elem: &schema.Resource{
											Schema: map[string]*schema.Schema{
												"http_statuses": {
													Type:     schema.TypeList,
													Optional: true,
													Elem:     schema.TypeString,
												},
												"tcp_failures": {
													Type:     schema.TypeInt,
													Optional: true,
												},
												"timeouts": {
													Type:     schema.TypeInt,
													Optional: true,
												},
												"http_failures": {
													Type:     schema.TypeInt,
													Optional: true,
												},
												"interval": {
													Type:     schema.TypeInt,
													Optional: true,
												},
											},
										},
									},
								},
							},
						},
						"passive": {
							Type:     schema.TypeList,
							Optional: true,
							ForceNew: true,
							MaxItems: 1,
							Elem: &schema.Resource{
								Schema: map[string]*schema.Schema{
									"type": {
										Type:     schema.TypeString,
										Optional: true,
										//ExactlyOneOf: HealthchecksTypes,
									},
									"healthy": {
										Type:     schema.TypeList,
										Optional: true,
										ForceNew: true,
										MaxItems: 1,
										Elem: &schema.Resource{
											Schema: map[string]*schema.Schema{
												"successes": {
													Type:     schema.TypeInt,
													Optional: true,
												},
												"http_statuses": {
													Type:     schema.TypeList,
													Optional: true,
													Elem:     schema.TypeString,
												},
											},
										},
									},
									"unhealthy": {
										Type:     schema.TypeList,
										Optional: true,
										ForceNew: true,
										MaxItems: 1,
										Elem: &schema.Resource{
											Schema: map[string]*schema.Schema{
												"http_failures": {
													Type:     schema.TypeInt,
													Optional: true,
												},
												"http_statuses": {
													Type:     schema.TypeList,
													Optional: true,
													Elem:     schema.TypeString,
												},
												"tcp_failures": {
													Type:     schema.TypeInt,
													Optional: true,
												},
												"timeout": {
													Type:     schema.TypeInt,
													Optional: true,
												},
											},
										},
									},
								},
							},
						},
					},
				},
			},
		},
	}
}

func resourceKongUpstreamCreate(d *schema.ResourceData, meta interface{}) error {
	Sling := meta.(*sling.Sling)

	upstream := getUpstreamFromResourceData(d)

	createdUpstream := getUpstreamFromResourceData(d)

	response, Error := Sling.New().BodyJSON(upstream).Post("upstreams/").ReceiveSuccess(createdUpstream)
	if Error != nil {
		return fmt.Errorf("Error while creating upstream.")
	}

	if response.StatusCode != http.StatusCreated {
		return fmt.Errorf(response.Status)
	}

	setUpstreamToResourceData(d, createdUpstream)

	return nil
}

func resourceKongUpstreamRead(d *schema.ResourceData, meta interface{}) error {
	Sling := meta.(*sling.Sling)

	upstream := getUpstreamFromResourceData(d)

	response, Error := Sling.New().Path("upstreams/").Get(upstream.ID).ReceiveSuccess(upstream)
	if Error != nil {
		return fmt.Errorf(Error.Error()) //fmt.Errorf("Error while updating upstream")
	}

	if response.StatusCode == http.StatusNotFound {
		d.SetId("")
		return nil
	} else if response.StatusCode != http.StatusOK {
		return fmt.Errorf(response.Status)
	}

	setUpstreamToResourceData(d, upstream)

	return nil
}

func resourceKongUpstreamUpdate(d *schema.ResourceData, meta interface{}) error {
	Sling := meta.(*sling.Sling)

	upstream := getUpstreamFromResourceData(d)

	updatedUpstream := getUpstreamFromResourceData(d)

	response, Error := Sling.New().BodyJSON(upstream).Path("upstreams/").Patch(upstream.ID).ReceiveSuccess(updatedUpstream)
	if Error != nil {
		return fmt.Errorf(Error.Error())//fmt.Errorf("Error while updating upstream")
	}

	if response.StatusCode != http.StatusOK {
		return fmt.Errorf(response.Status)
	}

	setUpstreamToResourceData(d, updatedUpstream)

	return nil
}

func resourceKongUpstreamDelete(d *schema.ResourceData, meta interface{}) error {
	Sling := meta.(*sling.Sling)

	upstream := getUpstreamFromResourceData(d)

	response, Error := Sling.New().Path("upstreams/").Delete(upstream.ID).ReceiveSuccess(nil)
	if Error != nil {
		return fmt.Errorf("Error while deleting upstream")
	}

	if response.StatusCode != http.StatusNoContent {
		return fmt.Errorf(response.Status)
	}

	return nil
}

func getUpstreamFromResourceData(d *schema.ResourceData) *Upstream {
	upstream := &Upstream{
		ID:                 d.Id(),
		Name:               d.Get("name").(string),
		Slots:              d.Get("slots").(int),
		HashOn:             d.Get("hash_on").(string),
		HashFallback:       d.Get("hash_fallback").(string),
		HashOnHeader:       d.Get("hash_on_header").(string),
		HashFallbackHeader: d.Get("hash_fallback_header").(string),
		HashOnCookie:       d.Get("hash_on_cookie").(string),
		HashOnCookiePath:   d.Get("hash_on_cookie_path").(string),
		Algorithm:          d.Get("algorithm").(string),
		HealthChecks:       d.Get("healthchecks").([]interface{}),
	}

	return upstream
}

func setUpstreamToResourceData(d *schema.ResourceData, upstream *Upstream) {
	d.SetId(upstream.ID)
	d.Set("name", upstream.Name)
	d.Set("slots", upstream.Slots)
	d.Set("hash_on", upstream.HashOn)
	d.Set("hash_fallback", upstream.HashFallback)
	d.Set("hash_on_header", upstream.HashOnHeader)
	d.Set("hash_fallback_header", upstream.HashFallbackHeader)
	d.Set("hash_on_cookie", upstream.HashOnCookie)
	d.Set("algorithm", upstream.Algorithm)
	d.Set("healthchecks", upstream.HealthChecks)
}
<commit_msg>set and get functions for healthchecks<commit_after>package kong

import (
	"fmt"
	"net/http"

	"github.com/dghubble/sling"
	//"github.com/hashicorp/terraform/helper/schema"
	"github.com/hashicorp/terraform/helper/schema"
)

var (
	HealthchecksTypes = []string{"http", "tcp", "https"}
)

type PassiveHealthy struct {
	Successes     int       `json:"successes,omitempty"`
	HttpStatuses  []string  `json:"http_statuses,omitempty"`
}

type PassiveUnhealthy struct {
	HttpFailures  int       `json:"http_failures,omitempty"`
	HttpStatuses  []string  `json:"http_statuses,omitempty"`
	TcpFailures   int       `json:"tcp_failures,omitempty"`
	Timeouts      int       `json:"timeout,omitempty"`
}

type HealthChecksPassive struct {
	Type       string            `json:"type,omitempty"`
	Healthy    PassiveHealthy    `json:"healthy,omitempty"`
	Unhealthy  PassiveUnhealthy  `json:"unhealthy,omitempty"`
}

type ActiveHealthy struct {
	Successes     int       `json:"successes,omitempty"`
	Interval      int       `json:"interval,omitempty"`
	HttpStatuses  []string  `json:"http_statuses,omitempty"`
}

type ActiveUnhealthy struct {
	HttpStatuses  []string  `json:"http_statuses,omitempty"`
	TcpFailures   int       `json:"tcp_failures,omitempty"`
	Timeouts      int       `json:"timeouts,omitempty"`
	HttpFailures  int       `json:"http_failures,omitempty"`
	Interval      int       `json:"interval,omitempty"`
}

type HealthChecksActive struct {
	HttpsVerifyCertificate    bool              `json:"https_verify_certificate,omitempty"`
	HttpPath                  string            `json:"http_path,omitempty"`
	Timeout                   int               `json:"timeout,omitempty"`
	HttpsSni                  string            `json:"https_sni,omitempty"`
	Concurrency               int               `json:"concurrency,omitempty"`
	Type                      string            `json:"type,omitempty"`
	Healthy                   ActiveHealthy     `json:"healthy,omitempty"`
	Unhealthy                 ActiveUnhealthy   `json:"unhealthy,omitempty"`
}

type UpstreamHealthChecks struct {
	Active  HealthChecksActive
	Passive HealthChecksPassive
}

type Upstream struct {
	ID                 string `json:"id,omitempty"`
	Name               string `json:"name,omitempty"`
	Slots              int    `json:"slots,omitempty"`
	HashOn             string `json:"hash_on,omitempty"`
	HashFallback       string `json:"hash_fallback,omitempty"`
	HashOnHeader       string `json:"hash_on_header,omitempty"`
	HashFallbackHeader string `json:"hash_fallback_header,omitempty"`
	HashOnCookie       string `json:"hash_on_cookie,omitempty"`
	HashOnCookiePath   string `json:"hash_on_cookie_path,omitempty"`
	Algorithm          string `json:"algorithm,omitempty"`
	HealthChecks       UpstreamHealthChecks `json:"healthchecks,omitempty"`
}

func resourceKongUpstream() *schema.Resource {
	return &schema.Resource{
		Create: resourceKongUpstreamCreate,
		Read:   resourceKongUpstreamRead,
		Update: resourceKongUpstreamUpdate,
		Delete: resourceKongUpstreamDelete,

		Schema: map[string]*schema.Schema{
			"name": {
				Type:        schema.TypeString,
				Required:    true,
				Description: "This is a hostname, which must be equal to the host of a Service.",
			},
			"slots": {
				Type:        schema.TypeInt,
				Optional:    true,
				Description: "The number of slots in the loadbalancer algorithm (10-65536, defaults to 1000).",
				Default:     1000,
				ValidateFunc: func(i interface{}, s string) (strings []string, errors []error) {
					slots := i.(int)

					if slots >= 10 && slots <= 65536 {
						return nil, nil
					}

					return nil, []error{fmt.Errorf("slots value of %d not in the range of 10-65536", slots)}
				},
			},
			"hash_on": {
				Type:        schema.TypeString,
				Optional:    true,
				Description: "What to use as hashing input: none, consumer, ip, header, or cookie (defaults to none resulting in a weighted-round-robin scheme).",
				Default:     "none",
				ValidateFunc: func(i interface{}, s string) (strings []string, errors []error) {
					// TODO: validate against [none, consume, ip, header, cookie]
					return nil, nil
				},
			},
			"hash_fallback": {
				Type:        schema.TypeString,
				Optional:    true,
				Description: "What to use as hashing input if the primary hash_on does not return a hash (eg. header is missing, or no consumer identified). One of: none, consumer, ip, header, or cookie (defaults to none, not available if hash_on is set to cookie).",
				Default:     "none",
				ValidateFunc: func(i interface{}, s string) (strings []string, errors []error) {
					// TODO: validate against [none, consume, ip, header, cookie]
					return nil, nil
				},
			},
			"hash_on_header": {
				Type:        schema.TypeString,
				Optional:    true,
				Description: "The header name to take the value from as hash input (only required when hash_on is set to header).",
			},
			"hash_fallback_header": {
				Type:        schema.TypeString,
				Optional:    true,
				Description: "The header name to take the value from as hash input (only required when hash_fallback is set to header).",
			},
			"hash_on_cookie": {
				Type:        schema.TypeString,
				Optional:    true,
				Description: "The cookie name to take the value from as hash input (only required when hash_on or hash_fallback is set to cookie). If the specified cookie is not in the request, Kong will generate a value and set the cookie in the response.",
			},
			"hash_on_cookie_path": {
				Type:     schema.TypeString,
				Optional: true,
				Default:  "/",
				DiffSuppressFunc: func(k, old, new string, d *schema.ResourceData) bool {
					return (old == "" && new == "/") || (old == "/" && new == "")
				},
				Description: "The cookie path to set in the response headers (only required when hash_on or hash_fallback is set to cookie, defaults to \"/\")",
			},
			"algorithm": {
				Type:        schema.TypeString,
				Optional:    true,
				Description: "Which load balancing algorithm to use. One of: round-robin, consistent-hashing, or least-connections. Defaults to \"round-robin\". Kong 1.3.0 and up.",
				ValidateFunc: func(i interface{}, s string) (strings []string, errors []error) {
					algs := []string{"round-robin", "consistent-hashing", "least-connections"}
					for i := 0; i < len(algs); i++ {
						if algs[i] == s {
							return nil, nil
						}
					}

					return nil, append(errors, fmt.Errorf("algorithm must be one of %v. %s was provided instead", algs, s))
				},
			},
			"healthchecks": {
				Type:        schema.TypeMap,
				Optional:    true,
				ForceNew:    true,
				Description: "Health checks configuration for upstream.",
				Elem: &schema.Resource{
					Schema: map[string]*schema.Schema{
						"active": {
							Type:     schema.TypeMap,
							Optional: true,
							ForceNew: true,
							Elem: &schema.Resource{
								Schema: map[string]*schema.Schema{
									"https_verify_certificate": {
										Type:     schema.TypeBool,
										Optional: true,
									},
									"http_path": {
										Type:     schema.TypeString,
										Optional: true,
									},
									"timeout": {
										Type:     schema.TypeInt,
										Optional: true,
									},
									"https_sni": {
										Type:     schema.TypeString,
										Optional: true,
									},
									"concurrency": {
										Type:     schema.TypeInt,
										Optional: true,
									},
									"type": {
										Type:     schema.TypeString,
										Optional: true,
										//ExactlyOneOf: HealthchecksTypes,
									},
									"healthy": {
										Type:     schema.TypeMap,
										Optional: true,
										ForceNew: true,
										Elem: &schema.Resource{
											Schema: map[string]*schema.Schema{
												"successes": {
													Type:     schema.TypeInt,
													Optional: true,
												},
												"interval": {
													Type:     schema.TypeInt,
													Optional: true,
												},
												"http_statuses": {
													Type:     schema.TypeList,
													Optional: true,
													Elem:     schema.TypeString,
												},
											},
										},
									},
									"unhealthy": {
										Type:     schema.TypeMap,
										Optional: true,
										ForceNew: true,
										Elem: &schema.Resource{
											Schema: map[string]*schema.Schema{
												"http_statuses": {
													Type:     schema.TypeList,
													Optional: true,
													Elem:     schema.TypeString,
												},
												"tcp_failures": {
													Type:     schema.TypeInt,
													Optional: true,
												},
												"timeouts": {
													Type:     schema.TypeInt,
													Optional: true,
												},
												"http_failures": {
													Type:     schema.TypeInt,
													Optional: true,
												},
												"interval": {
													Type:     schema.TypeInt,
													Optional: true,
												},
											},
										},
									},
								},
							},
						},
						"passive": {
							Type:     schema.TypeMap,
							Optional: true,
							ForceNew: true,
							Elem: &schema.Resource{
								Schema: map[string]*schema.Schema{
									"type": {
										Type:     schema.TypeString,
										Optional: true,
										//ExactlyOneOf: HealthchecksTypes,
									},
									"healthy": {
										Type:     schema.TypeMap,
										Optional: true,
										ForceNew: true,
										Elem: &schema.Resource{
											Schema: map[string]*schema.Schema{
												"successes": {
													Type:     schema.TypeInt,
													Optional: true,
												},
												"http_statuses": {
													Type:     schema.TypeList,
													Optional: true,
													Elem:     schema.TypeString,
												},
											},
										},
									},
									"unhealthy": {
										Type:     schema.TypeMap,
										Optional: true,
										ForceNew: true,
										Elem: &schema.Resource{
											Schema: map[string]*schema.Schema{
												"http_failures": {
													Type:     schema.TypeInt,
													Optional: true,
												},
												"http_statuses": {
													Type:     schema.TypeList,
													Optional: true,
													Elem:     schema.TypeString,
												},
												"tcp_failures": {
													Type:     schema.TypeInt,
													Optional: true,
												},
												"timeout": {
													Type:     schema.TypeInt,
													Optional: true,
												},
											},
										},
									},
								},
							},
						},
					},
				},
			},
		},
	}
}

func resourceKongUpstreamCreate(d *schema.ResourceData, meta interface{}) error {
	Sling := meta.(*sling.Sling)

	upstream := getUpstreamFromResourceData(d)

	createdUpstream := getUpstreamFromResourceData(d)

	response, Error := Sling.New().BodyJSON(upstream).Post("upstreams/").ReceiveSuccess(createdUpstream)
	if Error != nil {
		return fmt.Errorf("Error while creating upstream.")
	}

	if response.StatusCode != http.StatusCreated {
		return fmt.Errorf(response.Status)
	}

	setUpstreamToResourceData(d, createdUpstream)

	return nil
}

func resourceKongUpstreamRead(d *schema.ResourceData, meta interface{}) error {
	Sling := meta.(*sling.Sling)

	upstream := getUpstreamFromResourceData(d)

	response, Error := Sling.New().Path("upstreams/").Get(upstream.ID).ReceiveSuccess(upstream)
	if Error != nil {
		return fmt.Errorf(Error.Error()) //fmt.Errorf("Error while updating upstream")
	}

	if response.StatusCode == http.StatusNotFound {
		d.SetId("")
		return nil
	} else if response.StatusCode != http.StatusOK {
		return fmt.Errorf(response.Status)
	}

	setUpstreamToResourceData(d, upstream)

	return nil
}

func resourceKongUpstreamUpdate(d *schema.ResourceData, meta interface{}) error {
	Sling := meta.(*sling.Sling)

	upstream := getUpstreamFromResourceData(d)

	updatedUpstream := getUpstreamFromResourceData(d)

	response, Error := Sling.New().BodyJSON(upstream).Path("upstreams/").Patch(upstream.ID).ReceiveSuccess(updatedUpstream)
	if Error != nil {
		return fmt.Errorf(Error.Error())//fmt.Errorf("Error while updating upstream")
	}

	if response.StatusCode != http.StatusOK {
		return fmt.Errorf(response.Status)
	}

	setUpstreamToResourceData(d, updatedUpstream)

	return nil
}

func resourceKongUpstreamDelete(d *schema.ResourceData, meta interface{}) error {
	Sling := meta.(*sling.Sling)

	upstream := getUpstreamFromResourceData(d)

	response, Error := Sling.New().Path("upstreams/").Delete(upstream.ID).ReceiveSuccess(nil)
	if Error != nil {
		return fmt.Errorf("Error while deleting upstream")
	}

	if response.StatusCode != http.StatusNoContent {
		return fmt.Errorf(response.Status)
	}

	return nil
}

func setHealthCheck(u UpstreamHealthChecks) map[string]interface{} {
	m := make(map[string]interface{})
	active := make(map[string]interface{})
	passive := make(map[string]interface{})
	active["healthy"] = u.Active.Healthy
	active["unhealthy"] = u.Active.Unhealthy
	passive["healthy"] = u.Passive.Healthy
	passive["unhealthy"] = u.Passive.Unhealthy
	m["active"] = active
	m["passive"] = passive
	return m
}

func getUpstreamFromResourceData(d *schema.ResourceData) *Upstream {
	upstream := &Upstream{
		ID:                 d.Id(),
		Name:               d.Get("name").(string),
		Slots:              d.Get("slots").(int),
		HashOn:             d.Get("hash_on").(string),
		HashFallback:       d.Get("hash_fallback").(string),
		HashOnHeader:       d.Get("hash_on_header").(string),
		HashFallbackHeader: d.Get("hash_fallback_header").(string),
		HashOnCookie:       d.Get("hash_on_cookie").(string),
		HashOnCookiePath:   d.Get("hash_on_cookie_path").(string),
		Algorithm:          d.Get("algorithm").(string),
		HealthChecks:       d.Get("healthchecks").(UpstreamHealthChecks),
	}

	return upstream
}

func setUpstreamToResourceData(d *schema.ResourceData, upstream *Upstream) {
	d.SetId(upstream.ID)
	d.Set("name", upstream.Name)
	d.Set("slots", upstream.Slots)
	d.Set("hash_on", upstream.HashOn)
	d.Set("hash_fallback", upstream.HashFallback)
	d.Set("hash_on_header", upstream.HashOnHeader)
	d.Set("hash_fallback_header", upstream.HashFallbackHeader)
	d.Set("hash_on_cookie", upstream.HashOnCookie)
	d.Set("algorithm", upstream.Algorithm)
	d.Set("healthchecks", setHealthCheck(upstream.HealthChecks))
}
<|endoftext|>


<commit_before>package mailgun

// GetWebhooks returns the complete set of webhooks configured for your domain.
// Note that a zero-length mapping is not an error.
func (mg *MailgunImpl) GetWebhooks() (map[string]string, error) {
	r := newHTTPRequest(generateDomainApiUrl(mg, webhooksEndpoint))
	r.setClient(mg.Client())
	r.setBasicAuth(basicAuthUser, mg.ApiKey())
	var envelope struct {
		Webhooks map[string]interface{} `json:"webhooks"`
	}
	err := getResponseFromJSON(r, &envelope)
	hooks := make(map[string]string, 0)
	if err != nil {
		return hooks, err
	}
	for k, v := range envelope.Webhooks {
		object := v.(map[string]interface{})
		url := object["url"]
		hooks[k] = url.(string)
	}
	return hooks, nil
}

// CreateWebhook installs a new webhook for your domain.
func (mg *MailgunImpl) CreateWebhook(t, u string) error {
	r := newHTTPRequest(generateDomainApiUrl(mg, webhooksEndpoint))
	r.setClient(mg.Client())
	r.setBasicAuth(basicAuthUser, mg.ApiKey())
	p := newUrlEncodedPayload()
	p.addValue("id", t)
	p.addValue("url", u)
	_, err := makePostRequest(r, p)
	return err
}

// DeleteWebhook removes the specified webhook from your domain's configuration.
func (mg *MailgunImpl) DeleteWebhook(t string) error {
	r := newHTTPRequest(generateDomainApiUrl(mg, webhooksEndpoint) + "/" + t)
	r.setClient(mg.Client())
	r.setBasicAuth(basicAuthUser, mg.ApiKey())
	_, err := makeDeleteRequest(r)
	return err
}

// GetWebhookByType retrieves the currently assigned webhook URL associated with the provided type of webhook.
func (mg *MailgunImpl) GetWebhookByType(t string) (string, error) {
	r := newHTTPRequest(generateDomainApiUrl(mg, webhooksEndpoint) + "/" + t)
	r.setClient(mg.Client())
	r.setBasicAuth(basicAuthUser, mg.ApiKey())
	var envelope struct {
		Webhook struct {
			Url string `json:"url"`
		} `json:"webhook"`
	}
	err := getResponseFromJSON(r, &envelope)
	return envelope.Webhook.Url, err
}

// UpdateWebhook replaces one webhook setting for another.
func (mg *MailgunImpl) UpdateWebhook(t, u string) error {
	r := newHTTPRequest(generateDomainApiUrl(mg, webhooksEndpoint) + "/" + t)
	r.setClient(mg.Client())
	r.setBasicAuth(basicAuthUser, mg.ApiKey())
	p := newUrlEncodedPayload()
	p.addValue("url", u)
	_, err := makePutRequest(r, p)
	return err
}
<commit_msg>Added function to validate webhook invokes. Fixes #36.<commit_after>package mailgun

import (
	"crypto/hmac"
	"crypto/sha256"
	"crypto/subtle"
	"encoding/hex"
	"io"
	"net/http"
)

// GetWebhooks returns the complete set of webhooks configured for your domain.
// Note that a zero-length mapping is not an error.
func (mg *MailgunImpl) GetWebhooks() (map[string]string, error) {
	r := newHTTPRequest(generateDomainApiUrl(mg, webhooksEndpoint))
	r.setClient(mg.Client())
	r.setBasicAuth(basicAuthUser, mg.ApiKey())
	var envelope struct {
		Webhooks map[string]interface{} `json:"webhooks"`
	}
	err := getResponseFromJSON(r, &envelope)
	hooks := make(map[string]string, 0)
	if err != nil {
		return hooks, err
	}
	for k, v := range envelope.Webhooks {
		object := v.(map[string]interface{})
		url := object["url"]
		hooks[k] = url.(string)
	}
	return hooks, nil
}

// CreateWebhook installs a new webhook for your domain.
func (mg *MailgunImpl) CreateWebhook(t, u string) error {
	r := newHTTPRequest(generateDomainApiUrl(mg, webhooksEndpoint))
	r.setClient(mg.Client())
	r.setBasicAuth(basicAuthUser, mg.ApiKey())
	p := newUrlEncodedPayload()
	p.addValue("id", t)
	p.addValue("url", u)
	_, err := makePostRequest(r, p)
	return err
}

// DeleteWebhook removes the specified webhook from your domain's configuration.
func (mg *MailgunImpl) DeleteWebhook(t string) error {
	r := newHTTPRequest(generateDomainApiUrl(mg, webhooksEndpoint) + "/" + t)
	r.setClient(mg.Client())
	r.setBasicAuth(basicAuthUser, mg.ApiKey())
	_, err := makeDeleteRequest(r)
	return err
}

// GetWebhookByType retrieves the currently assigned webhook URL associated with the provided type of webhook.
func (mg *MailgunImpl) GetWebhookByType(t string) (string, error) {
	r := newHTTPRequest(generateDomainApiUrl(mg, webhooksEndpoint) + "/" + t)
	r.setClient(mg.Client())
	r.setBasicAuth(basicAuthUser, mg.ApiKey())
	var envelope struct {
		Webhook struct {
			Url string `json:"url"`
		} `json:"webhook"`
	}
	err := getResponseFromJSON(r, &envelope)
	return envelope.Webhook.Url, err
}

// UpdateWebhook replaces one webhook setting for another.
func (mg *MailgunImpl) UpdateWebhook(t, u string) error {
	r := newHTTPRequest(generateDomainApiUrl(mg, webhooksEndpoint) + "/" + t)
	r.setClient(mg.Client())
	r.setBasicAuth(basicAuthUser, mg.ApiKey())
	p := newUrlEncodedPayload()
	p.addValue("url", u)
	_, err := makePutRequest(r, p)
	return err
}

func (mg *MailgunImpl) VerifyWebhookRequest(req *http.Request) (verified bool, err error) {
	h := hmac.New(sha256.New, []byte(mg.ApiKey()))
	io.WriteString(h, req.Form.Get("timestamp"))
	io.WriteString(h, req.Form.Get("token"))

	calculatedSignature := h.Sum(nil)
	signature, err := hex.DecodeString(req.Form.Get("signature"))
	if err != nil {
		return false, err
	}
	if len(calculatedSignature) != len(signature) {
		return false, nil
	}

	return subtle.ConstantTimeCompare(signature, calculatedSignature) == 1, nil
}
<|endoftext|>