<commit_before>package main

import (
	"errors"
	"fmt"
	"os"
	"os/user"
	"path"

	log "github.com/Sirupsen/logrus"
	"github.com/kelseyhightower/envconfig"
)

// Context provides shared state among individual route handlers.
type Context struct {
	Settings
	Storage
}

// Settings contains configuration options loaded from the environment.
type Settings struct {
	Port         int
	LogLevel     string
	MongoURL     string
	AdminName    string
	AdminKey     string
	DockerHost   string
	DockerTLS    bool
	DockerCACert string
	DockerCert   string
	DockerKey    string
	Image        string
	Poll         int
	Web          bool
	Runner       bool
}

// NewContext loads the active configuration and applies any immediate, global settings like the
// logging level.
func NewContext() (*Context, error) {
	c := &Context{}

	if err := c.Load(); err != nil {
		return c, err
	}

	// Summarize the loaded settings.

	log.WithFields(log.Fields{
		"port":          c.Port,
		"logging level": c.LogLevel,
		"mongo URL":     c.MongoURL,
		"admin account": c.AdminName,
	}).Info("Initializing with loaded settings.")

	// Configure the logging level.

	level, err := log.ParseLevel(c.LogLevel)
	if err != nil {
		return c, err
	}
	log.SetLevel(level)

	// Connect to MongoDB.

	c.Storage, err = NewMongoStorage(c)
	if err != nil {
		return c, err
	}
	if err := c.Storage.Bootstrap(); err != nil {
		return c, err
	}

	return c, nil
}

// Load configuration settings from the environment, apply defaults, and validate them.
func (c *Context) Load() error {
	if err := envconfig.Process("RHO", &c.Settings); err != nil {
		return err
	}

	if c.Port == 0 {
		c.Port = 8000
	}

	if c.LogLevel == "" {
		c.LogLevel = "info"
	}

	if c.MongoURL == "" {
		c.MongoURL = "mongo"
	}

	if c.Poll == 0 {
		c.Poll = 500
	}

	if c.DockerHost == "" {
		if host := os.Getenv("DOCKER_HOST"); host != "" {
			c.DockerHost = host
		} else {
			c.DockerHost = "unix:///var/run/docker.sock"
		}
	}

	certRoot := os.Getenv("DOCKER_CERT_PATH")
	if certRoot == "" {
		user, err := user.Current()
		if err != nil {
			return fmt.Errorf("Unable to read the current OS user: %v", err)
		}

		certRoot = path.Join(user.HomeDir, ".docker")
	}

	if c.DockerCACert == "" {
		c.DockerCACert = path.Join(certRoot, "ca.pem")
	}

	if c.DockerCert == "" {
		c.DockerCert = path.Join(certRoot, "cert.pem")
	}

	if c.DockerKey == "" {
		c.DockerKey = path.Join(certRoot, "key.pem")
	}

	if c.Image == "" {
		c.Image = "rgbkrk/inrhocloud"
	}

	if _, err := log.ParseLevel(c.LogLevel); err != nil {
		return err
	}

	// If neither web nor runner are explicitly enabled, enable both.
	if !c.Web && !c.Runner {
		if os.Getenv("RHO_WEB") != "" && os.Getenv("RHO_RUNNER") != "" {
			return errors.New("You must enable either RHO_WEB or RHO_RUNNER!")
		}

		c.Web, c.Runner = true, true
	}

	return nil
}

// ListenAddr generates an address to bind the net/http server to based on the current settings.
func (c *Context) ListenAddr() string {
	return fmt.Sprintf(":%d", c.Port)
}
<commit_msg>New default image name.<commit_after>package main

import (
	"errors"
	"fmt"
	"os"
	"os/user"
	"path"

	log "github.com/Sirupsen/logrus"
	"github.com/kelseyhightower/envconfig"
)

// Context provides shared state among individual route handlers.
type Context struct {
	Settings
	Storage
}

// Settings contains configuration options loaded from the environment.
type Settings struct {
	Port         int
	LogLevel     string
	MongoURL     string
	AdminName    string
	AdminKey     string
	DockerHost   string
	DockerTLS    bool
	DockerCACert string
	DockerCert   string
	DockerKey    string
	Image        string
	Poll         int
	Web          bool
	Runner       bool
}

// NewContext loads the active configuration and applies any immediate, global settings like the
// logging level.
func NewContext() (*Context, error) {
	c := &Context{}

	if err := c.Load(); err != nil {
		return c, err
	}

	// Summarize the loaded settings.

	log.WithFields(log.Fields{
		"port":          c.Port,
		"logging level": c.LogLevel,
		"mongo URL":     c.MongoURL,
		"admin account": c.AdminName,
	}).Info("Initializing with loaded settings.")

	// Configure the logging level.

	level, err := log.ParseLevel(c.LogLevel)
	if err != nil {
		return c, err
	}
	log.SetLevel(level)

	// Connect to MongoDB.

	c.Storage, err = NewMongoStorage(c)
	if err != nil {
		return c, err
	}
	if err := c.Storage.Bootstrap(); err != nil {
		return c, err
	}

	return c, nil
}

// Load configuration settings from the environment, apply defaults, and validate them.
func (c *Context) Load() error {
	if err := envconfig.Process("RHO", &c.Settings); err != nil {
		return err
	}

	if c.Port == 0 {
		c.Port = 8000
	}

	if c.LogLevel == "" {
		c.LogLevel = "info"
	}

	if c.MongoURL == "" {
		c.MongoURL = "mongo"
	}

	if c.Poll == 0 {
		c.Poll = 500
	}

	if c.DockerHost == "" {
		if host := os.Getenv("DOCKER_HOST"); host != "" {
			c.DockerHost = host
		} else {
			c.DockerHost = "unix:///var/run/docker.sock"
		}
	}

	certRoot := os.Getenv("DOCKER_CERT_PATH")
	if certRoot == "" {
		user, err := user.Current()
		if err != nil {
			return fmt.Errorf("Unable to read the current OS user: %v", err)
		}

		certRoot = path.Join(user.HomeDir, ".docker")
	}

	if c.DockerCACert == "" {
		c.DockerCACert = path.Join(certRoot, "ca.pem")
	}

	if c.DockerCert == "" {
		c.DockerCert = path.Join(certRoot, "cert.pem")
	}

	if c.DockerKey == "" {
		c.DockerKey = path.Join(certRoot, "key.pem")
	}

	if c.Image == "" {
		c.Image = "cloudpipe/runner-py2"
	}

	if _, err := log.ParseLevel(c.LogLevel); err != nil {
		return err
	}

	// If neither web nor runner are explicitly enabled, enable both.
	if !c.Web && !c.Runner {
		if os.Getenv("RHO_WEB") != "" && os.Getenv("RHO_RUNNER") != "" {
			return errors.New("You must enable either RHO_WEB or RHO_RUNNER!")
		}

		c.Web, c.Runner = true, true
	}

	return nil
}

// ListenAddr generates an address to bind the net/http server to based on the current settings.
func (c *Context) ListenAddr() string {
	return fmt.Sprintf(":%d", c.Port)
}
<|endoftext|>


<commit_before>package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"os/user"

	flag "github.com/docker/docker/pkg/mflag"
)

type Config struct {
	BuildFlags string `json:"build_flags,omitempty"`
	AuthToken  string `json:"auth_token"`
}

// initialize flags
var (
	// Config needs to be initted in init()
	ConfigPath  *string
	BuildFlags  = flag.String([]string{"b", "-buildflags"}, "", "Pass build flags to gox")
	ForceCreate = flag.Bool([]string{"f", "-force"}, false, "Replace the asset if it already exists")
	AssetName   = flag.String([]string{"n", "-name"}, "", "Set the name for the release asset")
	Prerelease  = flag.Bool([]string{"p", "-prerelease"}, false, "With -create, create as a dev release")
	ReleaseName = flag.String([]string{"r", "-release"}, "", "Create the release if it does not exist and set the release name")
	Version     = flag.Bool([]string{"v", "-version"}, false, "Print the name and version")
)

func init() {
	CurrentUser, _ := user.Current()
	DefaultConfigPath := fmt.Sprintf("%s/.config/ghrelease/config.json", CurrentUser.HomeDir)
	ConfigPath = flag.String([]string{"c", "-config"}, DefaultConfigPath, "Set ghrelease config file")

	flag.Parse()
}

func LoadConfig(ConfigPath *string) Config {
	var ret Config
	ConfigFile, err := ioutil.ReadFile(*ConfigPath)
	err := json.Unmarshal(ConfigFile, &ret)
	if err != nil {
		log.Fatalln(err)
	}
	return ret
}

func main() {
}
<commit_msg>init LoadConfig in init()<commit_after>package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"os/user"

	flag "github.com/docker/docker/pkg/mflag"
)

type Config struct {
	BuildFlags string `json:"build_flags,omitempty"`
	AuthToken  string `json:"auth_token"`
}

// initialize flags
var (
	// Config needs to be initted in init()
	ConfigPath  *string
	BuildFlags  = flag.String([]string{"b", "-buildflags"}, "", "Pass build flags to gox")
	ForceCreate = flag.Bool([]string{"f", "-force"}, false, "Replace the asset if it already exists")
	AssetName   = flag.String([]string{"n", "-name"}, "", "Set the name for the release asset")
	Prerelease  = flag.Bool([]string{"p", "-prerelease"}, false, "With -create, create as a dev release")
	ReleaseName = flag.String([]string{"r", "-release"}, "", "Create the release if it does not exist and set the release name")
	Version     = flag.Bool([]string{"v", "-version"}, false, "Print the name and version")
)

func LoadConfig(ConfigPath *string) Config {
	var ret Config
	ConfigFile, err := ioutil.ReadFile(*ConfigPath)
	err := json.Unmarshal(ConfigFile, &ret)
	if err != nil {
		log.Fatalln(err)
	}
	return ret
}

func init() {
	CurrentUser, _ := user.Current()
	DefaultConfigPath := fmt.Sprintf("%s/.config/ghrelease/config.json", CurrentUser.HomeDir)
	ConfigPath = flag.String([]string{"c", "-config"}, DefaultConfigPath, "Set ghrelease config file")

	flag.Parse()

	GHRConfig := LoadConfig(ConfigPath)
}

func main() {
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"encoding/json"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"os/user"
	"path"

	"code.google.com/p/goauth2/oauth"

	flag "github.com/docker/docker/pkg/mflag"
	"github.com/google/go-github/github"
)

type Config struct {
	BuildFlags []string `json:"build_flags,omitempty"`
	AuthToken  string   `json:"auth_token"`
}

// initialize flags
var (
	// Config needs to be initted in init()
	ConfigPath  *string
	BuildFlags  = flag.String([]string{"b", "-buildflags"}, "", "Pass build flags to gox")
	ForceCreate = flag.Bool([]string{"f", "-force"}, false, "Replace the asset if it already exists")
	AssetName   = flag.String([]string{"n", "-name"}, "", "Set the name for the release asset")
	Prerelease  = flag.Bool([]string{"p", "-prerelease"}, false, "With -create, create as a dev release")
	ReleaseName = flag.String([]string{"r", "-release"}, "", "Create the release if it does not exist and set the release name")
	Version     = flag.Bool([]string{"v", "-version"}, false, "Print the name and version")
	GoxPath     *string
)

func LoadConfig(ConfigPath *string) Config {
	var ret Config
	ConfigFile, err := ioutil.ReadFile(*ConfigPath)
	err = json.Unmarshal(ConfigFile, &ret)
	if err != nil {
		log.Fatalln(err)
	}
	return ret
}

func init() {
	CurrentUser, _ := user.Current()
	DefaultConfigPath := path.Join(CurrentUser.HomeDir, ".config/ghrelease/config.json")
	ConfigPath = flag.String([]string{"c", "-config"}, DefaultConfigPath, "Set ghrelease config file")
	GoxPath = flag.String([]string{"g", "-gox"}, *FindGox(), "Path to gox")

	flag.Parse()
}

func FindGox() *string {
	Path, err := exec.LookPath("gox")
	if err != nil {
		log.Fatalln("gox is not in your $PATH")
	}
	return &Path
}

func Gox(BuildFlags *string) *string {
	cmd := exec.Command(*GoxPath, *BuildFlags)
	var out bytes.Buffer
	cmd.Stdout = &out
	err := cmd.Run()
	if err != nil {
		log.Fatalln(err)
	}
	output := out.String()
	return &output
}

func main() {
	GHRConfig := LoadConfig(ConfigPath)

	EnvAuthToken := os.Getenv("GHRELEASE_AUTH_TOKEN")
	if EnvAuthToken != "" {
		GHRConfig.AuthToken = EnvAuthToken
	}
	if GHRConfig.AuthToken == "" {
		log.Println("auth_token is required to upload release assets to GitHub")
	}

	transport := &oauth.Transport{
		Token: &oauth.Token{AccessToken: GHRConfig.AuthToken},
	}
	client := github.NewClient(transport.Client())

	BuildOutput := Gox(BuildFlags)
}
<commit_msg>move init() further up in the file<commit_after>package main

import (
	"bytes"
	"encoding/json"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"os/user"
	"path"

	"code.google.com/p/goauth2/oauth"

	flag "github.com/docker/docker/pkg/mflag"
	"github.com/google/go-github/github"
)

type Config struct {
	BuildFlags []string `json:"build_flags,omitempty"`
	AuthToken  string   `json:"auth_token"`
}

// initialize flags
var (
	// Config needs to be initted in init()
	ConfigPath  *string
	BuildFlags  = flag.String([]string{"b", "-buildflags"}, "", "Pass build flags to gox")
	ForceCreate = flag.Bool([]string{"f", "-force"}, false, "Replace the asset if it already exists")
	AssetName   = flag.String([]string{"n", "-name"}, "", "Set the name for the release asset")
	Prerelease  = flag.Bool([]string{"p", "-prerelease"}, false, "With -create, create as a dev release")
	ReleaseName = flag.String([]string{"r", "-release"}, "", "Create the release if it does not exist and set the release name")
	Version     = flag.Bool([]string{"v", "-version"}, false, "Print the name and version")
	GoxPath     *string
)

func init() {
	CurrentUser, _ := user.Current()
	DefaultConfigPath := path.Join(CurrentUser.HomeDir, ".config/ghrelease/config.json")
	ConfigPath = flag.String([]string{"c", "-config"}, DefaultConfigPath, "Set ghrelease config file")
	GoxPath = flag.String([]string{"g", "-gox"}, *FindGox(), "Path to gox")

	flag.Parse()
}

func LoadConfig(ConfigPath *string) Config {
	var ret Config
	ConfigFile, err := ioutil.ReadFile(*ConfigPath)
	err = json.Unmarshal(ConfigFile, &ret)
	if err != nil {
		log.Fatalln(err)
	}
	return ret
}

func FindGox() *string {
	Path, err := exec.LookPath("gox")
	if err != nil {
		log.Fatalln("gox is not in your $PATH")
	}
	return &Path
}

func Gox(BuildFlags *string) *string {
	cmd := exec.Command(*GoxPath, *BuildFlags)
	var out bytes.Buffer
	cmd.Stdout = &out
	err := cmd.Run()
	if err != nil {
		log.Fatalln(err)
	}
	output := out.String()
	return &output
}

func main() {
	GHRConfig := LoadConfig(ConfigPath)

	EnvAuthToken := os.Getenv("GHRELEASE_AUTH_TOKEN")
	if EnvAuthToken != "" {
		GHRConfig.AuthToken = EnvAuthToken
	}
	if GHRConfig.AuthToken == "" {
		log.Println("auth_token is required to upload release assets to GitHub")
	}

	transport := &oauth.Transport{
		Token: &oauth.Token{AccessToken: GHRConfig.AuthToken},
	}
	client := github.NewClient(transport.Client())

	BuildOutput := Gox(BuildFlags)
}
<|endoftext|>


<commit_before>package configurations

import (
	"fmt"
	"github.com/karlseguin/garnish/gc"
	"net"
	"net/http"
	"strings"
	"time"
)

// The default headers to forward to the upstream
var DefaultHeaders = []string{"Content-Length"}

type Upstreams struct {
	upstreams map[string]*Upstream
}

func NewUpstreams() *Upstreams {
	return &Upstreams{
		upstreams: make(map[string]*Upstream),
	}
}

// Used internally
func (u *Upstreams) Add(name string) *Upstream {
	if _, exists := u.upstreams[name]; exists {
		gc.Log.Warnf("Upstream %q already defined. Overwriting.", name)
	}
	one := &Upstream{
		name:        name,
		dnsDuration: time.Minute,
		headers:     DefaultHeaders,
		transports:  make([]*Transport, 0, 2),
	}
	u.upstreams[name] = one
	return one
}

func (u *Upstreams) Build(runtime *gc.Runtime, defaultTweaker gc.RequestTweaker) error {
	if u == nil {
		runtime.Upstreams = make(map[string]gc.Upstream, 0)
		return nil
	}

	upstreams := make(map[string]gc.Upstream, len(u.upstreams))
	for name, one := range u.upstreams {
		tweaker := defaultTweaker
		if len(one.tweakerRef) != 0 {
			ref, ok := u.upstreams[one.tweakerRef]
			if ok == false {
				return fmt.Errorf("upstream %s's tweaker referenced %s, a non-existent upstream", name, one.tweakerRef)
			}
			if ref.tweaker == nil {
				return fmt.Errorf("upstream %s's tweaker referenced %s, which does not have a tweaker", name, one.tweakerRef)
			}
			tweaker = ref.tweaker
		}
		upstream, err := one.Build(runtime, tweaker)
		if err != nil {
			return err
		}
		upstreams[name] = upstream
	}
	runtime.Upstreams = upstreams
	return nil
}

type Upstream struct {
	name        string
	transports  []*Transport
	dnsDuration time.Duration
	headers     []string
	tweakerRef  string
	tweaker     gc.RequestTweaker
}

type Transport struct {
	address   string
	keepalive int
}

// the duration to cache the upstream's dns lookup. Set to 0 to prevent
// garnish from caching this value (even a few seconds can help)
// [1 minute]
func (u *Upstream) DnsCache(duration time.Duration) *Upstream {
	u.dnsDuration = duration
	return u
}

// The headers to copy from the incoming request to the outgoing request
// [Content-Length]
func (u *Upstream) Headers(headers ...string) *Upstream {
	u.headers = headers
	return u
}

// Custom callback to modify the request (out) that will get sent to the upstream
func (u *Upstream) Tweaker(tweaker gc.RequestTweaker) *Upstream {
	u.tweaker = tweaker
	return u
}

// Allows the upstream to reference another upstream's tweaker (based on that
// upstream's name). Used by the file-based configuration; when configured
// programmatically, Tweaker should be used.
func (u *Upstream) TweakerRef(upstream string) *Upstream {
	u.tweakerRef = upstream
	return u
}

// the address to connect to. Should begin with unix:/  http://  or https://
// [""]
func (u *Upstream) Address(address string) *Transport {
	transport := &Transport{
		address:   address,
		keepalive: 16,
	}
	u.transports = append(u.transports, transport)
	return transport
}

// the number of connections to keep alive. Set to 0 to disable
// [16]
func (t *Transport) KeepAlive(count uint32) *Transport {
	t.keepalive = int(count)
	return t
}

func (u *Upstream) Build(runtime *gc.Runtime, tweaker gc.RequestTweaker) (gc.Upstream, error) {
	l := len(u.transports)
	if l == 0 {
		return nil, fmt.Errorf("Upstream %s doesn't have a configured transport", u.name)
	}

	transports := make([]*gc.Transport, l)
	for i := 0; i < l; i++ {
		t := u.transports[i]
		if len(t.address) < 8 {
			return nil, fmt.Errorf("Upstream %s has an invalid address: %q", u.name, t.address)
		}
		var domain string
		if t.address[:7] == "http://" {
			domain = t.address[7:]
		} else if t.address[:8] == "https://" {
			domain = t.address[8:]
		}
		if t.address[:6] != "unix:/" && len(domain) == 0 {
			return nil, fmt.Errorf("Upstream %s's address should begin with unix:/, http:// or https://", u.name)
		}

		transport := &http.Transport{
			MaxIdleConnsPerHost: t.keepalive,
			DisableKeepAlives:   t.keepalive == 0,
		}
		if t.address[:6] == "unix:/" {
			transport.Dial = func(network, address string) (net.Conn, error) {
				//strip out the :80 which Go adds
				return net.Dial("unix", address[:len(address)-3])
			}
		} else if strings.Contains(t.address, "localhost") {
			transport.Dial = func(network, address string) (net.Conn, error) {
				return net.Dial(network, address)
			}
		} else {
			transport.Dial = func(network, address string) (net.Conn, error) {
				host, port, _ := net.SplitHostPort(address)
				ip, _ := runtime.Resolver.FetchOneString(host)
				return net.Dial(network, net.JoinHostPort(ip, port))
			}
		}

		if u.dnsDuration > 0 && len(domain) > 0 {
			runtime.Resolver.TTL(domain, u.dnsDuration)
		}

		transports[i] = &gc.Transport{
			Transport: transport,
			Address:   t.address,
		}
	}

	if u.tweaker != nil {
		tweaker = u.tweaker
	}

	return gc.CreateUpstream(u.headers, tweaker, transports)
}
<commit_msg>limit ourselves to ipv4 for now<commit_after>package configurations

import (
	"fmt"
	"github.com/karlseguin/garnish/gc"
	"net"
	"net/http"
	"strings"
	"time"
)

// The default headers to forward to the upstream
var DefaultHeaders = []string{"Content-Length"}

type Upstreams struct {
	upstreams map[string]*Upstream
}

func NewUpstreams() *Upstreams {
	return &Upstreams{
		upstreams: make(map[string]*Upstream),
	}
}

// Used internally
func (u *Upstreams) Add(name string) *Upstream {
	if _, exists := u.upstreams[name]; exists {
		gc.Log.Warnf("Upstream %q already defined. Overwriting.", name)
	}
	one := &Upstream{
		name:        name,
		dnsDuration: time.Minute,
		headers:     DefaultHeaders,
		transports:  make([]*Transport, 0, 2),
	}
	u.upstreams[name] = one
	return one
}

func (u *Upstreams) Build(runtime *gc.Runtime, defaultTweaker gc.RequestTweaker) error {
	if u == nil {
		runtime.Upstreams = make(map[string]gc.Upstream, 0)
		return nil
	}

	upstreams := make(map[string]gc.Upstream, len(u.upstreams))
	for name, one := range u.upstreams {
		tweaker := defaultTweaker
		if len(one.tweakerRef) != 0 {
			ref, ok := u.upstreams[one.tweakerRef]
			if ok == false {
				return fmt.Errorf("upstream %s's tweaker referenced %s, a non-existent upstream", name, one.tweakerRef)
			}
			if ref.tweaker == nil {
				return fmt.Errorf("upstream %s's tweaker referenced %s, which does not have a tweaker", name, one.tweakerRef)
			}
			tweaker = ref.tweaker
		}
		upstream, err := one.Build(runtime, tweaker)
		if err != nil {
			return err
		}
		upstreams[name] = upstream
	}
	runtime.Upstreams = upstreams
	return nil
}

type Upstream struct {
	name        string
	transports  []*Transport
	dnsDuration time.Duration
	headers     []string
	tweakerRef  string
	tweaker     gc.RequestTweaker
}

type Transport struct {
	address   string
	keepalive int
}

// the duration to cache the upstream's dns lookup. Set to 0 to prevent
// garnish from caching this value (even a few seconds can help)
// [1 minute]
func (u *Upstream) DnsCache(duration time.Duration) *Upstream {
	u.dnsDuration = duration
	return u
}

// The headers to copy from the incoming request to the outgoing request
// [Content-Length]
func (u *Upstream) Headers(headers ...string) *Upstream {
	u.headers = headers
	return u
}

// Custom callback to modify the request (out) that will get sent to the upstream
func (u *Upstream) Tweaker(tweaker gc.RequestTweaker) *Upstream {
	u.tweaker = tweaker
	return u
}

// Allows the upstream to reference another upstream's tweaker (based on that
// upstream's name). Used by the file-based configuration; when configured
// programmatically, Tweaker should be used.
func (u *Upstream) TweakerRef(upstream string) *Upstream {
	u.tweakerRef = upstream
	return u
}

// the address to connect to. Should begin with unix:/  http://  or https://
// [""]
func (u *Upstream) Address(address string) *Transport {
	transport := &Transport{
		address:   address,
		keepalive: 16,
	}
	u.transports = append(u.transports, transport)
	return transport
}

// the number of connections to keep alive. Set to 0 to disable
// [16]
func (t *Transport) KeepAlive(count uint32) *Transport {
	t.keepalive = int(count)
	return t
}

func (u *Upstream) Build(runtime *gc.Runtime, tweaker gc.RequestTweaker) (gc.Upstream, error) {
	l := len(u.transports)
	if l == 0 {
		return nil, fmt.Errorf("Upstream %s doesn't have a configured transport", u.name)
	}

	transports := make([]*gc.Transport, l)
	for i := 0; i < l; i++ {
		t := u.transports[i]
		if len(t.address) < 8 {
			return nil, fmt.Errorf("Upstream %s has an invalid address: %q", u.name, t.address)
		}
		var domain string
		if t.address[:7] == "http://" {
			domain = t.address[7:]
		} else if t.address[:8] == "https://" {
			domain = t.address[8:]
		}
		if t.address[:6] != "unix:/" && len(domain) == 0 {
			return nil, fmt.Errorf("Upstream %s's address should begin with unix:/, http:// or https://", u.name)
		}

		transport := &http.Transport{
			MaxIdleConnsPerHost: t.keepalive,
			DisableKeepAlives:   t.keepalive == 0,
		}
		if t.address[:6] == "unix:/" {
			transport.Dial = func(network, address string) (net.Conn, error) {
				//strip out the :80 which Go adds
				return net.Dial("unix", address[:len(address)-3])
			}
		} else if strings.Contains(t.address, "localhost") {
			transport.Dial = func(network, address string) (net.Conn, error) {
				return net.Dial(network, address)
			}
		} else {
			transport.Dial = func(network, address string) (net.Conn, error) {
				host, port, _ := net.SplitHostPort(address)
				ip, _ := runtime.Resolver.FetchOneV4String(host)
				return net.Dial(network, net.JoinHostPort(ip, port))
			}
		}

		if u.dnsDuration > 0 && len(domain) > 0 {
			runtime.Resolver.TTL(domain, u.dnsDuration)
		}

		transports[i] = &gc.Transport{
			Transport: transport,
			Address:   t.address,
		}
	}

	if u.tweaker != nil {
		tweaker = u.tweaker
	}

	return gc.CreateUpstream(u.headers, tweaker, transports)
}
<|endoftext|>


<commit_before>// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2016 The Go Authors.  All rights reserved.
// https://github.com/golang/protobuf
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

// conformance implements the conformance test subprocess protocol as
// documented in conformance.proto.
package main

import (
	"encoding/binary"
	"fmt"
	"io"
	"os"

	pb "github.com/golang/protobuf/conformance/internal/conformance_proto"
	"github.com/golang/protobuf/jsonpb"
	"github.com/golang/protobuf/proto"
)

func main() {
	var sizeBuf [4]byte
	inbuf := make([]byte, 0, 4096)
	outbuf := proto.NewBuffer(nil)
	for {
		if _, err := io.ReadFull(os.Stdin, sizeBuf[:]); err == io.EOF {
			break
		} else if err != nil {
			fmt.Fprintln(os.Stderr, "go conformance: read request:", err)
			os.Exit(1)
		}
		size := binary.LittleEndian.Uint32(sizeBuf[:])
		if int(size) > cap(inbuf) {
			inbuf = make([]byte, size)
		}
		inbuf = inbuf[:size]
		if _, err := io.ReadFull(os.Stdin, inbuf); err != nil {
			fmt.Fprintln(os.Stderr, "go conformance: read request:", err)
			os.Exit(1)
		}

		req := new(pb.ConformanceRequest)
		if err := proto.Unmarshal(inbuf, req); err != nil {
			fmt.Fprintln(os.Stderr, "go conformance: parse request:", err)
			os.Exit(1)
		}
		res := handle(req)

		if err := outbuf.Marshal(res); err != nil {
			fmt.Fprintln(os.Stderr, "go conformance: marshal response:", err)
			os.Exit(1)
		}
		binary.LittleEndian.PutUint32(sizeBuf[:], uint32(len(outbuf.Bytes())))
		if _, err := os.Stdout.Write(sizeBuf[:]); err != nil {
			fmt.Fprintln(os.Stderr, "go conformance: write response:", err)
			os.Exit(1)
		}
		if _, err := os.Stdout.Write(outbuf.Bytes()); err != nil {
			fmt.Fprintln(os.Stderr, "go conformance: write response:", err)
			os.Exit(1)
		}
		outbuf.Reset()
	}
}

var jsonMarshaler = jsonpb.Marshaler{
	OrigName: true,
}

func handle(req *pb.ConformanceRequest) *pb.ConformanceResponse {
	var err error
	var msg pb.TestAllTypes
	switch p := req.Payload.(type) {
	case *pb.ConformanceRequest_ProtobufPayload:
		err = proto.Unmarshal(p.ProtobufPayload, &msg)
	case *pb.ConformanceRequest_JsonPayload:
		err = jsonpb.UnmarshalString(p.JsonPayload, &msg)
	default:
		return &pb.ConformanceResponse{
			Result: &pb.ConformanceResponse_RuntimeError{
				RuntimeError: "unknown request payload type",
			},
		}
	}
	if err != nil {
		return &pb.ConformanceResponse{
			Result: &pb.ConformanceResponse_ParseError{
				ParseError: err.Error(),
			},
		}
	}
	switch req.RequestedOutputFormat {
	case pb.WireFormat_PROTOBUF:
		var p []byte
		p, err := proto.Marshal(&msg)
		if err != nil {
			return &pb.ConformanceResponse{
				Result: &pb.ConformanceResponse_SerializeError{
					SerializeError: err.Error(),
				},
			}
		}
		return &pb.ConformanceResponse{
			Result: &pb.ConformanceResponse_ProtobufPayload{
				ProtobufPayload: p,
			},
		}
	case pb.WireFormat_JSON:
		p, err := jsonMarshaler.MarshalToString(&msg)
		if err != nil {
			return &pb.ConformanceResponse{
				Result: &pb.ConformanceResponse_SerializeError{
					SerializeError: err.Error(),
				},
			}
		}
		return &pb.ConformanceResponse{
			Result: &pb.ConformanceResponse_JsonPayload{
				JsonPayload: p,
			},
		}
	default:
		return &pb.ConformanceResponse{
			Result: &pb.ConformanceResponse_RuntimeError{
				RuntimeError: "unknown output format",
			},
		}
	}
}
<commit_msg>conformance: remove useless variable declaration (#558)<commit_after>// Go support for Protocol Buffers - Google's data interchange format
//
// Copyright 2016 The Go Authors.  All rights reserved.
// https://github.com/golang/protobuf
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

// conformance implements the conformance test subprocess protocol as
// documented in conformance.proto.
package main

import (
	"encoding/binary"
	"fmt"
	"io"
	"os"

	pb "github.com/golang/protobuf/conformance/internal/conformance_proto"
	"github.com/golang/protobuf/jsonpb"
	"github.com/golang/protobuf/proto"
)

func main() {
	var sizeBuf [4]byte
	inbuf := make([]byte, 0, 4096)
	outbuf := proto.NewBuffer(nil)
	for {
		if _, err := io.ReadFull(os.Stdin, sizeBuf[:]); err == io.EOF {
			break
		} else if err != nil {
			fmt.Fprintln(os.Stderr, "go conformance: read request:", err)
			os.Exit(1)
		}
		size := binary.LittleEndian.Uint32(sizeBuf[:])
		if int(size) > cap(inbuf) {
			inbuf = make([]byte, size)
		}
		inbuf = inbuf[:size]
		if _, err := io.ReadFull(os.Stdin, inbuf); err != nil {
			fmt.Fprintln(os.Stderr, "go conformance: read request:", err)
			os.Exit(1)
		}

		req := new(pb.ConformanceRequest)
		if err := proto.Unmarshal(inbuf, req); err != nil {
			fmt.Fprintln(os.Stderr, "go conformance: parse request:", err)
			os.Exit(1)
		}
		res := handle(req)

		if err := outbuf.Marshal(res); err != nil {
			fmt.Fprintln(os.Stderr, "go conformance: marshal response:", err)
			os.Exit(1)
		}
		binary.LittleEndian.PutUint32(sizeBuf[:], uint32(len(outbuf.Bytes())))
		if _, err := os.Stdout.Write(sizeBuf[:]); err != nil {
			fmt.Fprintln(os.Stderr, "go conformance: write response:", err)
			os.Exit(1)
		}
		if _, err := os.Stdout.Write(outbuf.Bytes()); err != nil {
			fmt.Fprintln(os.Stderr, "go conformance: write response:", err)
			os.Exit(1)
		}
		outbuf.Reset()
	}
}

var jsonMarshaler = jsonpb.Marshaler{
	OrigName: true,
}

func handle(req *pb.ConformanceRequest) *pb.ConformanceResponse {
	var err error
	var msg pb.TestAllTypes
	switch p := req.Payload.(type) {
	case *pb.ConformanceRequest_ProtobufPayload:
		err = proto.Unmarshal(p.ProtobufPayload, &msg)
	case *pb.ConformanceRequest_JsonPayload:
		err = jsonpb.UnmarshalString(p.JsonPayload, &msg)
	default:
		return &pb.ConformanceResponse{
			Result: &pb.ConformanceResponse_RuntimeError{
				RuntimeError: "unknown request payload type",
			},
		}
	}
	if err != nil {
		return &pb.ConformanceResponse{
			Result: &pb.ConformanceResponse_ParseError{
				ParseError: err.Error(),
			},
		}
	}
	switch req.RequestedOutputFormat {
	case pb.WireFormat_PROTOBUF:
		p, err := proto.Marshal(&msg)
		if err != nil {
			return &pb.ConformanceResponse{
				Result: &pb.ConformanceResponse_SerializeError{
					SerializeError: err.Error(),
				},
			}
		}
		return &pb.ConformanceResponse{
			Result: &pb.ConformanceResponse_ProtobufPayload{
				ProtobufPayload: p,
			},
		}
	case pb.WireFormat_JSON:
		p, err := jsonMarshaler.MarshalToString(&msg)
		if err != nil {
			return &pb.ConformanceResponse{
				Result: &pb.ConformanceResponse_SerializeError{
					SerializeError: err.Error(),
				},
			}
		}
		return &pb.ConformanceResponse{
			Result: &pb.ConformanceResponse_JsonPayload{
				JsonPayload: p,
			},
		}
	default:
		return &pb.ConformanceResponse{
			Result: &pb.ConformanceResponse_RuntimeError{
				RuntimeError: "unknown output format",
			},
		}
	}
}
<|endoftext|>


<commit_before>package controllers

import (
	"github.com/revel/revel"
	"fmt"
	"net/http"
	"io/ioutil"
	"encoding/json"
	"math"
	"strings"
	"time"
	"github.com/kldavis4/telerobot/app"
)

//Basic response structure for API requests
type ApiResponse struct {
	Code int
	Message string
	Body string
}

type App struct {
	*revel.Controller
}

func (c App) Index() revel.Result {
	return c.Render()
}

func (c App) Program() revel.Result {
	return c.Render()
}

// Executes a set of motion commands specified one per line
// Each command consists of two 3 digit numeric value with a max value of 255 prefixed with a plus or minus symbol
// and a duration specified in milliseconds
// Only one program can execute at a time
func (c App) ExecuteProgram(commandset string) revel.Result {
	if app.ProgramExecuting == false {
		commands := strings.Split(commandset,"\n")

		go executeCommands(commands)

		return c.RenderJson(ApiResponse{200,"Success",fmt.Sprintf("%d instructions sent",len(commands))})
	} else {
		return c.RenderJson(ApiResponse{400,"Failure","Program execution in progress"})
	}
}

//Updates the current move command to the one specified
//dx, dy are collected from a joystick.js virtual joystick
func (c App) Move(dx int, dy int) revel.Result {
	if app.ProgramExecuting == true {
		return c.RenderJson(ApiResponse{400,"Failure","Program executing"})
	}

	state := formatJoystickMotion(dx,dy)

	if strings.Compare(state,app.State) != 0 {
		app.Dirty = true
		app.State = state
	}

	return c.RenderJson(ApiResponse{200,"Success",app.State})
}

//Queries the current device status via the particle api
func (c App) Status() revel.Result {
	resp, err := http.Get(fmt.Sprintf("https://api.particle.io/v1/devices/%s?access_token=%s",app.Config.DeviceId,app.Config.AccessToken))

	if ( err == nil ) {
		defer resp.Body.Close()
		body, err := ioutil.ReadAll(resp.Body)

		if ( err == nil ) {
			var f map[string]interface{}
			err := json.Unmarshal(body, &f)

			if ( err == nil ) {
				if f["connected"] == true {
					return c.RenderJson(ApiResponse{200,"Success","connected"})
				} else {
					return c.RenderJson(ApiResponse{200,"Success","not_connected"})
				}
			} else {
				fmt.Printf(fmt.Sprintf("Error parsing json: %s", err))
			}
			return c.RenderJson(ApiResponse{200,"Success",string(body[:])})
		} else {
			fmt.Printf(fmt.Sprintf("Error reading response body: %s\n", err));
			return c.RenderJson(ApiResponse{500,"Failure",fmt.Sprintf("Error reading response body: %s", err)})
		}
	} else {
		fmt.Printf(fmt.Sprintf("Error during request: %s\n", err));
		return c.RenderJson(ApiResponse{500,"Failure",fmt.Sprintf("Error during request: %s", err)})
	}
}

//Parse the joystick.js dx / dy into a format that that robot can use
func formatJoystickMotion(dx int, dy int) string {
	rightMagnitude := -float64(dy)
	leftMagnitude := -float64(dy)

	//Set a deadzone between -15 and +15 to make driving straight easier
	if dx > 15 {
		leftMagnitude = leftMagnitude * (1.0 - float64(dx) / 255.0)
	} else if dx < 15 {
		rightMagnitude = rightMagnitude * (1.0 + float64(dx) / 255.0)
	}

	return fmt.Sprintf("%0+4d%0+4d",int(math.Floor(leftMagnitude)),int(math.Floor(rightMagnitude)))
}

//Execute a command set
func executeCommands(commands []string) {
	fmt.Println(fmt.Sprintf("Executing %d commands", len(commands)))
	app.ProgramExecuting = true
	for _, command := range commands {
		parts := strings.Split(command," ")

		d, err := time.ParseDuration(fmt.Sprintf("%sms", parts[2]))
		if err != nil {
			fmt.Println("Invalid duration ", parts[2])
			continue
		}
		time.Sleep(d)

		app.State = fmt.Sprintf("%s%s",parts[0],parts[1])
		app.Dirty = true
		fmt.Println(app.State)
	}
	app.ProgramExecuting = false
}
<commit_msg>Fix bug in dead zone logic<commit_after>package controllers

import (
	"github.com/revel/revel"
	"fmt"
	"net/http"
	"io/ioutil"
	"encoding/json"
	"math"
	"strings"
	"time"
	"github.com/kldavis4/telerobot/app"
)

//Basic response structure for API requests
type ApiResponse struct {
	Code int
	Message string
	Body string
}

type App struct {
	*revel.Controller
}

func (c App) Index() revel.Result {
	return c.Render()
}

func (c App) Program() revel.Result {
	return c.Render()
}

// Executes a set of motion commands specified one per line
// Each command consists of two 3 digit numeric value with a max value of 255 prefixed with a plus or minus symbol
// and a duration specified in milliseconds
// Only one program can execute at a time
func (c App) ExecuteProgram(commandset string) revel.Result {
	if app.ProgramExecuting == false {
		commands := strings.Split(commandset,"\n")

		go executeCommands(commands)

		return c.RenderJson(ApiResponse{200,"Success",fmt.Sprintf("%d instructions sent",len(commands))})
	} else {
		return c.RenderJson(ApiResponse{400,"Failure","Program execution in progress"})
	}
}

//Updates the current move command to the one specified
//dx, dy are collected from a joystick.js virtual joystick
func (c App) Move(dx int, dy int) revel.Result {
	if app.ProgramExecuting == true {
		return c.RenderJson(ApiResponse{400,"Failure","Program executing"})
	}

	state := formatJoystickMotion(dx,dy)

	if strings.Compare(state,app.State) != 0 {
		app.Dirty = true
		app.State = state
	}

	return c.RenderJson(ApiResponse{200,"Success",app.State})
}

//Queries the current device status via the particle api
func (c App) Status() revel.Result {
	resp, err := http.Get(fmt.Sprintf("https://api.particle.io/v1/devices/%s?access_token=%s",app.Config.DeviceId,app.Config.AccessToken))

	if ( err == nil ) {
		defer resp.Body.Close()
		body, err := ioutil.ReadAll(resp.Body)

		if ( err == nil ) {
			var f map[string]interface{}
			err := json.Unmarshal(body, &f)

			if ( err == nil ) {
				if f["connected"] == true {
					return c.RenderJson(ApiResponse{200,"Success","connected"})
				} else {
					return c.RenderJson(ApiResponse{200,"Success","not_connected"})
				}
			} else {
				fmt.Printf(fmt.Sprintf("Error parsing json: %s", err))
			}
			return c.RenderJson(ApiResponse{200,"Success",string(body[:])})
		} else {
			fmt.Printf(fmt.Sprintf("Error reading response body: %s\n", err));
			return c.RenderJson(ApiResponse{500,"Failure",fmt.Sprintf("Error reading response body: %s", err)})
		}
	} else {
		fmt.Printf(fmt.Sprintf("Error during request: %s\n", err));
		return c.RenderJson(ApiResponse{500,"Failure",fmt.Sprintf("Error during request: %s", err)})
	}
}

//Parse the joystick.js dx / dy into a format that that robot can use
func formatJoystickMotion(dx int, dy int) string {
	rightMagnitude := -float64(dy)
	leftMagnitude := -float64(dy)

	//Set a deadzone between -15 and +15 to make driving straight easier
	if dx > 15 {
		leftMagnitude = leftMagnitude * (1.0 - float64(dx) / 255.0)
	} else if dx < -15 {
		rightMagnitude = rightMagnitude * (1.0 + float64(dx) / 255.0)
	}

	return fmt.Sprintf("%0+4d%0+4d",int(math.Floor(leftMagnitude)),int(math.Floor(rightMagnitude)))
}

//Execute a command set
func executeCommands(commands []string) {
	fmt.Println(fmt.Sprintf("Executing %d commands", len(commands)))
	app.ProgramExecuting = true
	for _, command := range commands {
		parts := strings.Split(command," ")

		d, err := time.ParseDuration(fmt.Sprintf("%sms", parts[2]))
		if err != nil {
			fmt.Println("Invalid duration ", parts[2])
			continue
		}
		time.Sleep(d)

		app.State = fmt.Sprintf("%s%s",parts[0],parts[1])
		app.Dirty = true
		fmt.Println(app.State)
	}
	app.ProgramExecuting = false
}
<|endoftext|>


<commit_before>// 在这里写你的事件。
// Write your event here.

package main

import (
	"fmt"

	"unsafe"

	"github.com/tryor/gdiplus"
	"github.com/tryor/winapi"
	"github.com/ying32/govcl/vcl"
	"github.com/ying32/govcl/vcl/types"
	"github.com/ying32/govcl/vcl/win"
)

//::private::
type TGdipFormFields struct {
}

func (f *TGdipForm) OnFormCreate(sender vcl.IObject) {
	fmt.Println("OnCreate")
	style := win.GetWindowLongPtr(f.Handle(), win.GWL_EXSTYLE) | win.WS_EX_LAYERED | win.WS_EX_TOOLWINDOW
	win.SetWindowLongPtr(f.Handle(), win.GWL_EXSTYLE, uintptr(style))
	f.UpdateLayer()
}

func (f *TGdipForm) UpdateLayer() {
	defer func() {
		if err := recover(); err != nil {
			fmt.Println("err:", err)
		}
	}()
	hWd := f.Handle()
	formDC := win.GetDC(hWd)
	if formDC == 0 {
		return
	}
	defer win.ReleaseDC(hWd, formDC)
	aWidth := f.Width()
	aHeight := f.Height()

	memDC := win.CreateCompatibleDC(formDC)
	if memDC == 0 {
		return
	}
	defer win.DeleteDC(memDC)

	bmih := win.TBitmapInfo{}
	bmih.BmiHeader.BiSize = uint32(unsafe.Sizeof(bmih.BmiHeader))
	bmih.BmiHeader.BiWidth = uint32(aWidth)
	bmih.BmiHeader.BiHeight = uint32(aHeight)
	bmih.BmiHeader.BiPlanes = 1
	bmih.BmiHeader.BiBitCount = 32
	bmih.BmiHeader.BiCompression = win.BI_RGB
	bmih.BmiHeader.BiSizeImage = 0
	bmih.BmiHeader.BiXPelsPerMeter = 0
	bmih.BmiHeader.BiYPelsPerMeter = 0
	bmih.BmiHeader.BiClrUsed = 0
	bmih.BmiHeader.BiClrImportant = 0

	var pBits uintptr
	hBitMap := win.CreateDIBSection(0, &bmih, 0, &pBits, 0, 0)
	if hBitMap == 0 {
		return
	}
	defer win.DeleteObject(types.HGDIOBJ(hBitMap))
	win.SelectObject(memDC, types.HGDIOBJ(hBitMap))

	// 这里写gdi+处理

	g, err := gdiplus.FromHDC(winapi.HDC(memDC))
	if err != nil {
		return
	}
	defer g.Release()

	g.SetSmoothingMode(gdiplus.SmoothingModeAntiAlias)
	g.SetInterpolationMode(gdiplus.InterpolationModeHighQualityBicubic)
	g.SetTextRenderingHint(gdiplus.TextRenderingHintAntiAlias)

	// 自己画一个半透明的作为背景
	brush, err := gdiplus.NewSolidBrush(gdiplus.NewColor3(0xB2, 0, 0, 0))
	defer brush.Release()
	if err == nil {
		g.FillRectangle(brush, 0, 0, gdiplus.REAL(aWidth), gdiplus.REAL(aHeight))
	}

	// 使用带有透明通道的图片作为背景
	//r := f.ClientRect()
	//bmp, err := gdiplus.NewBitmap("./testbk.png")
	//defer bmp.Release()
	//if err != nil {
	//	return
	//}
	//fmt.Println(bmp.GetWidth(), ", ", bmp.GetHeight())
	//destR := gdiplus.Rect{0, 0, winapi.INT(r.Width()), winapi.INT(r.Height())}
	//g.DrawImageI7(bmp, &destR, 0, 0, winapi.INT(bmp.GetWidth()-1), winapi.INT(bmp.GetHeight()-1), gdiplus.UnitPixel, nil, nil, 0)

	// 画文字
	//path, _ := gdiplus.NewGraphicsPath()
	//defer path.Release()

	family, _ := gdiplus.NewFontFamily("黑体", nil)
	defer family.Release()

	strFormat, _ := gdiplus.NewStringFormat()
	defer strFormat.Release()
	strFormat.SetFormatFlags(winapi.INT(gdiplus.StringFormatFlagsNoWrap))
	strFormat.SetAlignment(gdiplus.StringAlignmentCenter)

	// 红色
	f.DrawText("文字String", 0, g, family, strFormat, gdiplus.NewColor3(0xFF, 0xB3, 0x00, 0x00), gdiplus.NewColor3(0xFF, 0xFE, 0x95, 0x00))
	// 蓝色
	f.DrawText("文字String", 200, g, family, strFormat, gdiplus.NewColor3(0xFF, 0x00, 0x43, 0x93), gdiplus.NewColor3(0xFF, 0x02, 0xB4, 0xEA))
	// 绿色
	f.DrawText("文字String", 400, g, family, strFormat, gdiplus.NewColor3(0xFF, 0x0B, 0x63, 0x00), gdiplus.NewColor3(0xFF, 0x8A, 0xF6, 0x22))
	// 更新分层窗口
	winsize := types.TSize{aWidth, aHeight}
	scrPoint := types.TPoint{}
	blend := win.TBlendFunction{}
	blend.BlendOp = win.AC_SRC_OVER
	blend.BlendFlags = 0
	blend.AlphaFormat = win.AC_SRC_ALPHA
	blend.SourceConstantAlpha = 255

	ret := win.UpdateLayeredWindow(hWd, formDC, nil, &winsize, memDC, &scrPoint, 0, &blend, win.ULW_ALPHA)
	fmt.Println("更新结果：", ret)
}

func (f *TGdipForm) DrawText(s string, top int, g *gdiplus.Graphics, family *gdiplus.FontFamily, strFormat *gdiplus.StringFormat, color1, color2 gdiplus.Color) {
	rF := gdiplus.RectF{0, gdiplus.REAL(top), gdiplus.REAL(f.Width()), 0}
	var fontHeight gdiplus.REAL = 100

	path, _ := gdiplus.NewGraphicsPath()
	defer path.Release()

	path.AddString(s, family, gdiplus.FontStyleBold, fontHeight, &rF, strFormat)

	// 画笔
	pen, err := gdiplus.NewPen(gdiplus.NewColor3(155, 215, 215, 215), 3)
	defer pen.Release()
	if err != nil {
		return
	}
	pen.SetColor(gdiplus.NewColor3(65, 1, 3, 3))
	pen.SetLineJoin(gdiplus.LineJoinRound)
	g.DrawPath(pen, path)

	brush2, err := gdiplus.NewLinearGradientBrush(
		gdiplus.NewPointF(0, 0),
		gdiplus.NewPointF(0, fontHeight), color1, color2)
	defer brush2.Release()
	if err != nil {
		return
	}

	// 多绘制几次
	for i := 0; i < 4; i++ {
		pen.SetWidth(gdiplus.REAL(i))
		g.DrawPath(pen, path)
	}
	g.FillPath(brush2, path)
}

func (f *TGdipForm) OnFormMouseDown(sender vcl.IObject, button types.TMouseButton, shift types.TShiftState, x, y int32) {
	if button == types.MbLeft {
		win.ReleaseCapture()
		f.Perform(win.WM_SYSCOMMAND, win.SC_MOVE+1, 0)
	}
}
<commit_msg>fix gdiplustest example.<commit_after>// 在这里写你的事件。
// Write your event here.

package main

import (
	"fmt"

	"unsafe"

	"github.com/tryor/gdiplus"
	"github.com/tryor/winapi"
	"github.com/ying32/govcl/vcl"
	"github.com/ying32/govcl/vcl/types"
	"github.com/ying32/govcl/vcl/win"
)

//::private::
type TGdipFormFields struct {
}

func (f *TGdipForm) OnFormCreate(sender vcl.IObject) {
	fmt.Println("OnCreate")
	style := win.GetWindowLongPtr(f.Handle(), win.GWL_EXSTYLE) | win.WS_EX_LAYERED | win.WS_EX_TOOLWINDOW
	win.SetWindowLongPtr(f.Handle(), win.GWL_EXSTYLE, uintptr(style))
	f.UpdateLayer()
}

func (f *TGdipForm) UpdateLayer() {
	defer func() {
		if err := recover(); err != nil {
			fmt.Println("err:", err)
		}
	}()
	hWd := f.Handle()
	formDC := win.GetDC(hWd)
	if formDC == 0 {
		return
	}
	defer win.ReleaseDC(hWd, formDC)
	aWidth := f.Width()
	aHeight := f.Height()

	memDC := win.CreateCompatibleDC(formDC)
	if memDC == 0 {
		return
	}
	defer win.DeleteDC(memDC)

	bmih := win.TBitmapInfo{}
	bmih.BmiHeader.BiSize = uint32(unsafe.Sizeof(bmih.BmiHeader))
	bmih.BmiHeader.BiWidth = uint32(aWidth)
	bmih.BmiHeader.BiHeight = uint32(aHeight)
	bmih.BmiHeader.BiPlanes = 1
	bmih.BmiHeader.BiBitCount = 32
	bmih.BmiHeader.BiCompression = win.BI_RGB
	bmih.BmiHeader.BiSizeImage = 0
	bmih.BmiHeader.BiXPelsPerMeter = 0
	bmih.BmiHeader.BiYPelsPerMeter = 0
	bmih.BmiHeader.BiClrUsed = 0
	bmih.BmiHeader.BiClrImportant = 0

	var pBits uintptr
	hBitMap := win.CreateDIBSection(0, &bmih, 0, &pBits, 0, 0)
	if hBitMap == 0 {
		return
	}
	defer win.DeleteObject(types.HGDIOBJ(hBitMap))
	win.SelectObject(memDC, types.HGDIOBJ(hBitMap))

	// 这里写gdi+处理

	g, err := gdiplus.FromHDC(winapi.HDC(memDC))
	if err != nil {
		return
	}
	defer g.Release()

	g.SetSmoothingMode(gdiplus.SmoothingModeAntiAlias)
	g.SetInterpolationMode(gdiplus.InterpolationModeHighQualityBicubic)
	g.SetTextRenderingHint(gdiplus.TextRenderingHintAntiAlias)

	// 自己画一个半透明的作为背景
	brush, err := gdiplus.NewSolidBrush(gdiplus.NewColor3(0xB2, 0, 0, 0))
	defer brush.Release()
	if err == nil {
		g.FillRectangle(brush, 0, 0, gdiplus.REAL(aWidth), gdiplus.REAL(aHeight))
	}

	// 使用带有透明通道的图片作为背景
	//r := f.ClientRect()
	//bmp, err := gdiplus.NewBitmap("./testbk.png")
	//defer bmp.Release()
	//if err != nil {
	//	return
	//}
	//fmt.Println(bmp.GetWidth(), ", ", bmp.GetHeight())
	//destR := gdiplus.Rect{0, 0, winapi.INT(r.Width()), winapi.INT(r.Height())}
	//g.DrawImageI7(bmp, &destR, 0, 0, winapi.INT(bmp.GetWidth()-1), winapi.INT(bmp.GetHeight()-1), gdiplus.UnitPixel, nil, nil, 0)

	// 画文字
	//path, _ := gdiplus.NewGraphicsPath()
	//defer path.Release()

	family, _ := gdiplus.NewFontFamily("黑体", nil)
	defer family.Release()

	strFormat, _ := gdiplus.NewStringFormat()
	defer strFormat.Release()
	strFormat.SetFormatFlags(winapi.INT(gdiplus.StringFormatFlagsNoWrap))
	strFormat.SetAlignment(gdiplus.StringAlignmentCenter)

	// 红色
	f.DrawText("文字String", 0, g, family, strFormat, gdiplus.NewColor3(0xFF, 0xB3, 0x00, 0x00), gdiplus.NewColor3(0xFF, 0xFE, 0x95, 0x00))
	// 蓝色
	f.DrawText("文字String", 200, g, family, strFormat, gdiplus.NewColor3(0xFF, 0x00, 0x43, 0x93), gdiplus.NewColor3(0xFF, 0x02, 0xB4, 0xEA))
	// 绿色
	f.DrawText("文字String", 400, g, family, strFormat, gdiplus.NewColor3(0xFF, 0x0B, 0x63, 0x00), gdiplus.NewColor3(0xFF, 0x8A, 0xF6, 0x22))
	// 更新分层窗口
	winsize := types.TSize{aWidth, aHeight}
	scrPoint := types.TPoint{}
	blend := win.TBlendFunction{}
	blend.BlendOp = win.AC_SRC_OVER
	blend.BlendFlags = 0
	blend.AlphaFormat = win.AC_SRC_ALPHA
	blend.SourceConstantAlpha = 255

	ret := win.UpdateLayeredWindow(hWd, formDC, nil, &winsize, memDC, &scrPoint, 0, &blend, win.ULW_ALPHA)
	fmt.Println("更新结果：", ret)
}

func (f *TGdipForm) DrawText(s string, top int, g *gdiplus.Graphics, family *gdiplus.FontFamily, strFormat *gdiplus.StringFormat, color1, color2 gdiplus.Color) {
	rF := gdiplus.RectF{0, gdiplus.REAL(top), gdiplus.REAL(f.Width()), 0}
	var fontHeight gdiplus.REAL = 100

	path, _ := gdiplus.NewGraphicsPath()
	defer path.Release()

	path.AddString(s, family, gdiplus.FontStyleBold, fontHeight, &rF, strFormat)

	// 画笔
	pen, err := gdiplus.NewPen(gdiplus.NewColor3(155, 215, 215, 215), 3)
	defer pen.Release()
	if err != nil {
		return
	}
	pen.SetColor(gdiplus.NewColor3(65, 1, 3, 3))
	pen.SetLineJoin(gdiplus.LineJoinRound)
	g.DrawPath(pen, path)

	brush2, err := gdiplus.NewLinearGradientBrush(
		gdiplus.NewPointF(0, 0),
		gdiplus.NewPointF(0, fontHeight), color1, color2)
	defer brush2.Release()
	if err != nil {
		return
	}

	// 多绘制几次
	for i := 0; i < 4; i++ {
		pen.SetWidth(gdiplus.REAL(i))
		g.DrawPath(pen, path)
	}
	g.FillPath(brush2, path)
}

func (f *TGdipForm) OnFormMouseDown(sender vcl.IObject, button types.TMouseButton, shift types.TShiftState, x, y int32) {
	if button == types.MbLeft {
		win.ReleaseCapture()
		win.PostMessage(f.Handle(), win.WM_SYSCOMMAND, win.SC_MOVE+1, 0)
	}
}
<|endoftext|>


<commit_before>package aws

import (
	"fmt"
	"log"
	"time"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/rds"
	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/helper/schema"
)

func resourceAwsRDSClusterInstance() *schema.Resource {
	return &schema.Resource{
		Create: resourceAwsRDSClusterInstanceCreate,
		Read:   resourceAwsRDSClusterInstanceRead,
		Update: resourceAwsRDSClusterInstanceUpdate,
		Delete: resourceAwsRDSClusterInstanceDelete,

		Schema: map[string]*schema.Schema{
			"identifier": &schema.Schema{
				Type:         schema.TypeString,
				Optional:     true,
				ForceNew:     true,
				ValidateFunc: validateRdsId,
			},

			"db_subnet_group_name": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
				ForceNew: true,
				Computed: true,
			},

			"writer": &schema.Schema{
				Type:     schema.TypeBool,
				Computed: true,
			},

			"cluster_identifier": &schema.Schema{
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},

			"endpoint": &schema.Schema{
				Type:     schema.TypeString,
				Computed: true,
			},

			"port": &schema.Schema{
				Type:     schema.TypeInt,
				Computed: true,
			},

			"publicly_accessible": &schema.Schema{
				Type:     schema.TypeBool,
				Optional: true,
				Default:  false,
				ForceNew: true,
			},

			"instance_class": &schema.Schema{
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},

			"tags": tagsSchema(),
		},
	}
}

func resourceAwsRDSClusterInstanceCreate(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).rdsconn
	tags := tagsFromMapRDS(d.Get("tags").(map[string]interface{}))

	createOpts := &rds.CreateDBInstanceInput{
		DBInstanceClass:     aws.String(d.Get("instance_class").(string)),
		DBClusterIdentifier: aws.String(d.Get("cluster_identifier").(string)),
		Engine:              aws.String("aurora"),
		PubliclyAccessible:  aws.Bool(d.Get("publicly_accessible").(bool)),
		Tags:                tags,
	}

	if v := d.Get("identifier").(string); v != "" {
		createOpts.DBInstanceIdentifier = aws.String(v)
	} else {
		createOpts.DBInstanceIdentifier = aws.String(resource.UniqueId())
	}

	if attr, ok := d.GetOk("db_subnet_group_name"); ok {
		createOpts.DBSubnetGroupName = aws.String(attr.(string))
	}

	log.Printf("[DEBUG] Creating RDS DB Instance opts: %s", createOpts)
	resp, err := conn.CreateDBInstance(createOpts)
	if err != nil {
		return err
	}

	d.SetId(*resp.DBInstance.DBInstanceIdentifier)

	// reuse db_instance refresh func
	stateConf := &resource.StateChangeConf{
		Pending:    []string{"creating", "backing-up", "modifying"},
		Target:     []string{"available"},
		Refresh:    resourceAwsDbInstanceStateRefreshFunc(d, meta),
		Timeout:    40 * time.Minute,
		MinTimeout: 10 * time.Second,
		Delay:      10 * time.Second,
	}

	// Wait, catching any errors
	_, err = stateConf.WaitForState()
	if err != nil {
		return err
	}

	return resourceAwsRDSClusterInstanceRead(d, meta)
}

func resourceAwsRDSClusterInstanceRead(d *schema.ResourceData, meta interface{}) error {
	db, err := resourceAwsDbInstanceRetrieve(d, meta)
	// Errors from this helper are always reportable
	if err != nil {
		return fmt.Errorf("[WARN] Error on retrieving RDS Cluster Instance (%s): %s", d.Id(), err)
	}
	// A nil response means "not found"
	if db == nil {
		log.Printf("[WARN] RDS Cluster Instance (%s): not found, removing from state.", d.Id())
		d.SetId("")
		return nil
	}

	// Retreive DB Cluster information, to determine if this Instance is a writer
	conn := meta.(*AWSClient).rdsconn
	resp, err := conn.DescribeDBClusters(&rds.DescribeDBClustersInput{
		DBClusterIdentifier: db.DBClusterIdentifier,
	})

	var dbc *rds.DBCluster
	for _, c := range resp.DBClusters {
		if *c.DBClusterIdentifier == *db.DBClusterIdentifier {
			dbc = c
		}
	}

	if dbc == nil {
		return fmt.Errorf("[WARN] Error finding RDS Cluster (%s) for Cluster Instance (%s): %s",
			*db.DBClusterIdentifier, *db.DBInstanceIdentifier, err)
	}

	for _, m := range dbc.DBClusterMembers {
		if *db.DBInstanceIdentifier == *m.DBInstanceIdentifier {
			if *m.IsClusterWriter == true {
				d.Set("writer", true)
			} else {
				d.Set("writer", false)
			}
		}
	}

	if db.Endpoint != nil {
		d.Set("endpoint", db.Endpoint.Address)
		d.Set("port", db.Endpoint.Port)
	}

	d.Set("publicly_accessible", db.PubliclyAccessible)

	// Fetch and save tags
	arn, err := buildRDSARN(d.Id(), meta)
	if err != nil {
		log.Printf("[DEBUG] Error building ARN for RDS Cluster Instance (%s), not setting Tags", *db.DBInstanceIdentifier)
	} else {
		if err := saveTagsRDS(conn, d, arn); err != nil {
			log.Printf("[WARN] Failed to save tags for RDS Cluster Instance (%s): %s", *db.DBClusterIdentifier, err)
		}
	}

	return nil
}

func resourceAwsRDSClusterInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).rdsconn

	if arn, err := buildRDSARN(d.Id(), meta); err == nil {
		if err := setTagsRDS(conn, d, arn); err != nil {
			return err
		}
	}

	return resourceAwsRDSClusterInstanceRead(d, meta)
}

func resourceAwsRDSClusterInstanceDelete(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).rdsconn

	log.Printf("[DEBUG] RDS Cluster Instance destroy: %v", d.Id())

	opts := rds.DeleteDBInstanceInput{DBInstanceIdentifier: aws.String(d.Id())}

	log.Printf("[DEBUG] RDS Cluster Instance destroy configuration: %s", opts)
	if _, err := conn.DeleteDBInstance(&opts); err != nil {
		return err
	}

	// re-uses db_instance refresh func
	log.Println("[INFO] Waiting for RDS Cluster Instance to be destroyed")
	stateConf := &resource.StateChangeConf{
		Pending:    []string{"modifying", "deleting"},
		Target:     []string{},
		Refresh:    resourceAwsDbInstanceStateRefreshFunc(d, meta),
		Timeout:    40 * time.Minute,
		MinTimeout: 10 * time.Second,
	}

	if _, err := stateConf.WaitForState(); err != nil {
		return err
	}

	return nil

}
<commit_msg>support aurora instance's parameter group and modifyinstance<commit_after>package aws

import (
	"fmt"
	"log"
	"time"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/rds"
	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/helper/schema"
)

func resourceAwsRDSClusterInstance() *schema.Resource {
	return &schema.Resource{
		Create: resourceAwsRDSClusterInstanceCreate,
		Read:   resourceAwsRDSClusterInstanceRead,
		Update: resourceAwsRDSClusterInstanceUpdate,
		Delete: resourceAwsRDSClusterInstanceDelete,

		Schema: map[string]*schema.Schema{
			"identifier": &schema.Schema{
				Type:         schema.TypeString,
				Optional:     true,
				ForceNew:     true,
				ValidateFunc: validateRdsId,
			},

			"db_subnet_group_name": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
				ForceNew: true,
				Computed: true,
			},

			"writer": &schema.Schema{
				Type:     schema.TypeBool,
				Computed: true,
			},

			"cluster_identifier": &schema.Schema{
				Type:     schema.TypeString,
				Required: true,
				ForceNew: true,
			},

			"endpoint": &schema.Schema{
				Type:     schema.TypeString,
				Computed: true,
			},

			"port": &schema.Schema{
				Type:     schema.TypeInt,
				Computed: true,
			},

			"publicly_accessible": &schema.Schema{
				Type:     schema.TypeBool,
				Optional: true,
				Default:  false,
			},

			"instance_class": &schema.Schema{
				Type:     schema.TypeString,
				Required: true,
			},

			"db_parameter_group_name": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
				Computed: true,
			},

			"status": &schema.Schema{
				Type:     schema.TypeString,
				Computed: true,
			},

			// apply_immediately is used to determine when the update modifications
			// take place.
			// See http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Overview.DBInstance.Modifying.html
			"apply_immediately": &schema.Schema{
				Type:     schema.TypeBool,
				Optional: true,
				Computed: true,
			},

			"tags": tagsSchema(),
		},
	}
}

func resourceAwsRDSClusterInstanceCreate(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).rdsconn
	tags := tagsFromMapRDS(d.Get("tags").(map[string]interface{}))

	createOpts := &rds.CreateDBInstanceInput{
		DBInstanceClass:     aws.String(d.Get("instance_class").(string)),
		DBClusterIdentifier: aws.String(d.Get("cluster_identifier").(string)),
		Engine:              aws.String("aurora"),
		PubliclyAccessible:  aws.Bool(d.Get("publicly_accessible").(bool)),
		Tags:                tags,
	}

	if attr, ok := d.GetOk("db_parameter_group_name"); ok {
		createOpts.DBParameterGroupName = aws.String(attr.(string))
	}

	if v := d.Get("identifier").(string); v != "" {
		createOpts.DBInstanceIdentifier = aws.String(v)
	} else {
		createOpts.DBInstanceIdentifier = aws.String(resource.UniqueId())
	}

	if attr, ok := d.GetOk("db_subnet_group_name"); ok {
		createOpts.DBSubnetGroupName = aws.String(attr.(string))
	}

	log.Printf("[DEBUG] Creating RDS DB Instance opts: %s", createOpts)
	resp, err := conn.CreateDBInstance(createOpts)
	if err != nil {
		return err
	}

	d.SetId(*resp.DBInstance.DBInstanceIdentifier)

	// reuse db_instance refresh func
	stateConf := &resource.StateChangeConf{
		Pending:    []string{"creating", "backing-up", "modifying"},
		Target:     []string{"available"},
		Refresh:    resourceAwsDbInstanceStateRefreshFunc(d, meta),
		Timeout:    40 * time.Minute,
		MinTimeout: 10 * time.Second,
		Delay:      10 * time.Second,
	}

	// Wait, catching any errors
	_, err = stateConf.WaitForState()
	if err != nil {
		return err
	}

	return resourceAwsRDSClusterInstanceRead(d, meta)
}

func resourceAwsRDSClusterInstanceRead(d *schema.ResourceData, meta interface{}) error {
	db, err := resourceAwsDbInstanceRetrieve(d, meta)
	// Errors from this helper are always reportable
	if err != nil {
		return fmt.Errorf("[WARN] Error on retrieving RDS Cluster Instance (%s): %s", d.Id(), err)
	}
	// A nil response means "not found"
	if db == nil {
		log.Printf("[WARN] RDS Cluster Instance (%s): not found, removing from state.", d.Id())
		d.SetId("")
		return nil
	}

	// Retreive DB Cluster information, to determine if this Instance is a writer
	conn := meta.(*AWSClient).rdsconn
	resp, err := conn.DescribeDBClusters(&rds.DescribeDBClustersInput{
		DBClusterIdentifier: db.DBClusterIdentifier,
	})

	var dbc *rds.DBCluster
	for _, c := range resp.DBClusters {
		if *c.DBClusterIdentifier == *db.DBClusterIdentifier {
			dbc = c
		}
	}

	if dbc == nil {
		return fmt.Errorf("[WARN] Error finding RDS Cluster (%s) for Cluster Instance (%s): %s",
			*db.DBClusterIdentifier, *db.DBInstanceIdentifier, err)
	}

	for _, m := range dbc.DBClusterMembers {
		if *db.DBInstanceIdentifier == *m.DBInstanceIdentifier {
			if *m.IsClusterWriter == true {
				d.Set("writer", true)
			} else {
				d.Set("writer", false)
			}
		}
	}

	if db.Endpoint != nil {
		d.Set("endpoint", db.Endpoint.Address)
		d.Set("port", db.Endpoint.Port)
	}

	d.Set("publicly_accessible", db.PubliclyAccessible)

	if len(db.DBParameterGroups) > 0 {
		d.Set("parameter_group_name", db.DBParameterGroups[0].DBParameterGroupName)
	}

	// Fetch and save tags
	arn, err := buildRDSARN(d.Id(), meta)
	if err != nil {
		log.Printf("[DEBUG] Error building ARN for RDS Cluster Instance (%s), not setting Tags", *db.DBInstanceIdentifier)
	} else {
		if err := saveTagsRDS(conn, d, arn); err != nil {
			log.Printf("[WARN] Failed to save tags for RDS Cluster Instance (%s): %s", *db.DBClusterIdentifier, err)
		}
	}

	return nil
}

func resourceAwsRDSClusterInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).rdsconn
	requestUpdate := false

	req := &rds.ModifyDBInstanceInput{
		ApplyImmediately:     aws.Bool(d.Get("apply_immediately").(bool)),
		DBInstanceIdentifier: aws.String(d.Id()),
	}

	if d.HasChange("db_parameter_group_name") {
		req.DBParameterGroupName = aws.String(d.Get("db_parameter_group_name").(string))
		requestUpdate = true

	}

	if d.HasChange("instance_class") {
		req.DBInstanceClass = aws.String(d.Get("instance_class").(string))
		requestUpdate = true

	}

	log.Printf("[DEBUG] Send DB Instance Modification request: %#v", requestUpdate)
	if requestUpdate {
		log.Printf("[DEBUG] DB Instance Modification request: %#v", req)
		_, err := conn.ModifyDBInstance(req)
		if err != nil {
			return fmt.Errorf("Error modifying DB Instance %s: %s", d.Id(), err)
		}

		// reuse db_instance refresh func
		stateConf := &resource.StateChangeConf{
			Pending:    []string{"creating", "backing-up", "modifying"},
			Target:     []string{"available"},
			Refresh:    resourceAwsDbInstanceStateRefreshFunc(d, meta),
			Timeout:    40 * time.Minute,
			MinTimeout: 10 * time.Second,
			Delay:      10 * time.Second,
		}

		// Wait, catching any errors
		_, err = stateConf.WaitForState()
		if err != nil {
			return err
		}

	}

	if arn, err := buildRDSARN(d.Id(), meta); err == nil {
		if err := setTagsRDS(conn, d, arn); err != nil {
			return err
		}
	}

	return resourceAwsRDSClusterInstanceRead(d, meta)
}

func resourceAwsRDSClusterInstanceDelete(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).rdsconn

	log.Printf("[DEBUG] RDS Cluster Instance destroy: %v", d.Id())

	opts := rds.DeleteDBInstanceInput{DBInstanceIdentifier: aws.String(d.Id())}

	log.Printf("[DEBUG] RDS Cluster Instance destroy configuration: %s", opts)
	if _, err := conn.DeleteDBInstance(&opts); err != nil {
		return err
	}

	// re-uses db_instance refresh func
	log.Println("[INFO] Waiting for RDS Cluster Instance to be destroyed")
	stateConf := &resource.StateChangeConf{
		Pending:    []string{"modifying", "deleting"},
		Target:     []string{},
		Refresh:    resourceAwsDbInstanceStateRefreshFunc(d, meta),
		Timeout:    40 * time.Minute,
		MinTimeout: 10 * time.Second,
	}

	if _, err := stateConf.WaitForState(); err != nil {
		return err
	}

	return nil

}
<|endoftext|>


<commit_before>package contenttype

import "io"

// ContentType processes incoming data for a specific type with supplied metadata.
//
// This allows the caller of the /upload/:type api to inform Kala of metadata about
// the data being uploaded. The Kala upload plugin (such as a jpeg or mp3 plugin)
// will do the bulk of the actual processing, but this interface ensures that
// arbitrary metadata that already exists is not lost on upload.
//
// Does it need to be parse exif data? Does it need to parse mp3 tags? Etc.
//
// The ContentType is responsible for writing raw blobs as needed. If multipart
// or blob chunks need to be written, it is responsible for doing so!
type ContentType interface {
	// StoreContent stores content with the given meta changes.
	StoreContent(io.ReadCloser, Version, Changes) ([]string, error)

	// StoreMeta applies just metadata changes.
	StoreMeta(Version, Changes) ([]string, error)

	// TODO(leeola): move the UnmarshallMetadata to this method.
	// MetaToIndexable([]byte) (index.Indexable, error)

	// MetaToChanges unmarshalls the given bytes into changes.
	//
	// The purpose of this (similar to  MetaToIndexable), is to export metadata
	// to be imported at a future time and passed in as StoreContent.
	//
	// Note that the format of Changes is up to the ContentType implementor.
	// The only requirement is that the produced Changes struct is deterministic
	// when returned and uploaded again.
	MetaToChanges([]byte) (Changes, error)
}

// // TODO(leeola): deprecate, move into ContentType interface
// type MetadataUnmarshaller interface {
// 	UnmarshalMetadata([]byte) (index.Indexable, error)
// }
//
// type MetadataUnmarshallerFunc func([]byte) (index.Indexable, error)
//
// func (fn MetadataUnmarshallerFunc) UnmarshalMetadata(b []byte) (index.Indexable, error) {
// 	return fn(b)
// }
<commit_msg>refactor: remove MetaToChanges (exporting)<commit_after>package contenttype

import "io"

// ContentType processes incoming data for a specific type with supplied metadata.
//
// This allows the caller of the /upload/:type api to inform Kala of metadata about
// the data being uploaded. The Kala upload plugin (such as a jpeg or mp3 plugin)
// will do the bulk of the actual processing, but this interface ensures that
// arbitrary metadata that already exists is not lost on upload.
//
// Does it need to be parse exif data? Does it need to parse mp3 tags? Etc.
//
// The ContentType is responsible for writing raw blobs as needed. If multipart
// or blob chunks need to be written, it is responsible for doing so!
type ContentType interface {
	// StoreContent stores content with the given meta changes.
	StoreContent(io.ReadCloser, Version, Changes) ([]string, error)

	// StoreMeta applies just metadata changes.
	StoreMeta(Version, Changes) ([]string, error)

	// TODO(leeola): move the UnmarshallMetadata to this method.
	// MetaToIndexable([]byte) (index.Indexable, error)
}

// // TODO(leeola): deprecate, move into ContentType interface
// type MetadataUnmarshaller interface {
// 	UnmarshalMetadata([]byte) (index.Indexable, error)
// }
//
// type MetadataUnmarshallerFunc func([]byte) (index.Indexable, error)
//
// func (fn MetadataUnmarshallerFunc) UnmarshalMetadata(b []byte) (index.Indexable, error) {
// 	return fn(b)
// }
<|endoftext|>


<commit_before>package gocd

import (
	"context"
)

// PropertiesService describes Actions which can be performed on agents
type RoleService service

type Role struct {
	Name       string              `json:"name"`
	Type       string              `json:"type"`
	Attributes *RoleAttributesGoCD `json:"attributes"`
}

type RoleAttributesGoCD struct {
	Users []string `json:"users"`
}

type RoleAttributesPlugin struct{}

// Create a role
func (rs *RoleService) Create(ctx context.Context, role *Role) (r *Role, resp *APIResponse, err error) {
	r = &Role{}
	_, resp, err = rs.client.postAction(ctx, &APIClientRequest{
		APIVersion:   apiV1,
		Path:         "admin/security/roles",
		RequestBody:  role,
		ResponseBody: r,
	})

	return
}
<commit_msg>Add missing comments<commit_after>package gocd

import (
	"context"
)

// RoleService describes Actions which can be performed on roles
type RoleService service

// Role represents a type of agent/actor who can access resources perform operations
type Role struct {
	Name       string              `json:"name"`
	Type       string              `json:"type"`
	Attributes *RoleAttributesGoCD `json:"attributes"`
}

// RoleAttributesGoCD are attributes describing a role, in this cae, which users are present in the role.
type RoleAttributesGoCD struct {
	Users []string `json:"users"`
}

type RoleAttributesPlugin struct{}

// Create a role
func (rs *RoleService) Create(ctx context.Context, role *Role) (r *Role, resp *APIResponse, err error) {
	r = &Role{}
	_, resp, err = rs.client.postAction(ctx, &APIClientRequest{
		APIVersion:   apiV1,
		Path:         "admin/security/roles",
		RequestBody:  role,
		ResponseBody: r,
	})

	return
}
<|endoftext|>


<commit_before>package golangsdk

import (
	"crypto/tls"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"strconv"
	"time"
)

const (
	zincBaseURL = "https://api.zinc.io/v1"
)

type Retailer string

const (
	Amazon     Retailer = "amazon"
	AmazonUK   Retailer = "amazon_uk"
	AmazonCA   Retailer = "amazon_ca"
	AmazonMX   Retailer = "amazon_mx"
	Walmart    Retailer = "walmart"
	Aliexpress Retailer = "aliexpress"
)

var DefaultProductOptions = ProductOptions{
	Timeout: time.Duration(time.Second * 90),
}

type Zinc struct {
	ClientToken string
	ZincBaseURL string
}

func NewZinc(clientToken string) (*Zinc, error) {
	z := Zinc{
		ClientToken: clientToken,
		ZincBaseURL: zincBaseURL,
	}
	return &z, nil
}

type ProductOffersResponse struct {
	Code     string            `json:"code"`
	Data     ErrorDataResponse `json:"data"`
	Status   string            `json:"status"`
	Retailer string            `json:"retailer"`
	Offers   []ProductOffer    `json:"offers"`
}

type ProductOffer struct {
	Available            bool             `json:"available"`
	Addon                bool             `json:"addon"`
	Condition            string           `json:"condition"`
	ShippingOptions      []ShippingOption `json:"shipping_options"`
	HandlingDays         HandlingDays     `json:"handling_days"`
	PrimeOnly            bool             `json:"prime_only"`
	MarketplaceFulfilled bool             `json:"marketplace_fulfilled"`
	Currency             string           `json:"currency"`
	Seller               Seller           `json:"seller"`
	BuyBoxWinner         bool             `json:"buy_box_winner"`
	International        bool             `json:"international"`
	OfferId              string           `json:"offer_id"`
	Price                int              `json:"price"`
}

type ShippingOption struct {
	Price int `json:"price"`
}

type HandlingDays struct {
	Max int `json:"max"`
	Min int `json:"min"`
}

type Seller struct {
	NumRatings      int    `json:"num_ratings"`
	PercentPositive int    `json:"percent_positive"`
	FirstParty      bool   `json:"first_party"`
	Name            string `json:"name"`
	Id              string `json:"id"`
}

type ProductDetailsResponse struct {
	Code               string              `json:"code"`
	Data               ErrorDataResponse   `json:"data"`
	Status             string              `json:"status"`
	ProductDescription string              `json:"product_description"`
	Retailer           string              `json:"retailer"`
	Epids              []ExternalProductId `json:"epids"`
	ProductDetails     []string            `json:"product_details"`
	Title              string              `json:"title"`
	VariantSpecifics   []VariantSpecific   `json:"variant_specifics"`
	ProductId          string              `json:"product_id"`
	MainImage          string              `json:"main_image"`
	Brand              string              `json:"brand"`
	MPN                string              `json:"mpn"`
	Images             []string            `json:"images"`
	FeatureBullets     []string            `json:"feature_bullets"`
}

type ExternalProductId struct {
	Type  string `json:"type"`
	Value string `json:"value"`
}

type VariantSpecific struct {
	Dimension string `json:"dimension"`
	Value     string `json:"value"`
}

type ErrorDataResponse struct {
	Message string `json:"message"`
}

type ProductOptions struct {
	MaxAge    int           `json:"max_age"`
	NewerThan time.Time     `json:"newer_than"`
	Timeout   time.Duration `json:"timeout"`
}

func (z Zinc) GetProductInfo(productId string, retailer Retailer, options ProductOptions) (*ProductOffersResponse, *ProductDetailsResponse, error) {
	offersChan := make(chan *ProductOffersResponse, 1)
	detailsChan := make(chan *ProductDetailsResponse, 1)
	errorsChan := make(chan error, 2)

	go func() {
		offers, err := z.GetProductOffers(productId, retailer, options)
		errorsChan <- err
		offersChan <- offers
	}()

	go func() {
		details, err := z.GetProductDetails(productId, retailer, options)
		errorsChan <- err
		detailsChan <- details
	}()

	offers := <-offersChan
	details := <-detailsChan
	for i := 0; i < 2; i++ {
		err := <-errorsChan
		if err != nil {
			return nil, nil, err
		}
	}
	return offers, details, nil
}

func (z Zinc) GetProductOffers(productId string, retailer Retailer, options ProductOptions) (*ProductOffersResponse, error) {
	values := url.Values{}
	values.Set("retailer", string(retailer))
	values.Set("version", "2")
	if options.MaxAge != 0 {
		values.Set("max_age", strconv.Itoa(options.MaxAge))
	}
	if !options.NewerThan.IsZero() {
		values.Set("newer_than", strconv.FormatInt(options.NewerThan.Unix(), 10))
	}
	requestPath := fmt.Sprintf("%v/products/%v/offers?%v", z.ZincBaseURL, productId, values.Encode())

	respBody, err := z.sendGetRequest(requestPath, options.Timeout)
	if err != nil {
		return nil, err
	}
	var resp ProductOffersResponse
	if err := json.Unmarshal(respBody, &resp); err != nil {
		return nil, err
	}
	if resp.Status == "failed" {
		return &resp, fmt.Errorf("Zinc API returned status 'failed' response=%v", resp)
	}
	return &resp, nil
}

func (z Zinc) GetProductDetails(productId string, retailer Retailer, options ProductOptions) (*ProductDetailsResponse, error) {
	values := url.Values{}
	values.Set("retailer", string(retailer))
	if options.MaxAge != 0 {
		values.Set("max_age", strconv.Itoa(options.MaxAge))
	}
	if !options.NewerThan.IsZero() {
		values.Set("newer_than", strconv.FormatInt(options.NewerThan.Unix(), 10))
	}
	requestPath := fmt.Sprintf("%v/products/%v?%v", z.ZincBaseURL, productId, values.Encode())

	respBody, err := z.sendGetRequest(requestPath, options.Timeout)
	if err != nil {
		return nil, err
	}
	var resp ProductDetailsResponse
	if err := json.Unmarshal(respBody, &resp); err != nil {
		return nil, err
	}
	if resp.Status == "failed" {
		return &resp, fmt.Errorf("Zinc API returned status 'failed' response=%v", resp)
	}
	return &resp, nil
}

func (z Zinc) sendGetRequest(requestPath string, timeout time.Duration) ([]byte, error) {
	httpReq, err := http.NewRequest("GET", requestPath, nil)
	if err != nil {
		return nil, err
	}
	httpReq.SetBasicAuth(z.ClientToken, "")
	tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
	client := &http.Client{Transport: tr, Timeout: timeout}
	resp, err := client.Do(httpReq)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	respBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	return respBody, nil
}
<commit_msg>Add post description for product details response.<commit_after>package golangsdk

import (
	"crypto/tls"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"strconv"
	"time"
)

const (
	zincBaseURL = "https://api.zinc.io/v1"
)

type Retailer string

const (
	Amazon     Retailer = "amazon"
	AmazonUK   Retailer = "amazon_uk"
	AmazonCA   Retailer = "amazon_ca"
	AmazonMX   Retailer = "amazon_mx"
	Walmart    Retailer = "walmart"
	Aliexpress Retailer = "aliexpress"
)

var DefaultProductOptions = ProductOptions{
	Timeout: time.Duration(time.Second * 90),
}

type Zinc struct {
	ClientToken string
	ZincBaseURL string
}

func NewZinc(clientToken string) (*Zinc, error) {
	z := Zinc{
		ClientToken: clientToken,
		ZincBaseURL: zincBaseURL,
	}
	return &z, nil
}

type ProductOffersResponse struct {
	Code     string            `json:"code"`
	Data     ErrorDataResponse `json:"data"`
	Status   string            `json:"status"`
	Retailer string            `json:"retailer"`
	Offers   []ProductOffer    `json:"offers"`
}

type ProductOffer struct {
	Available            bool             `json:"available"`
	Addon                bool             `json:"addon"`
	Condition            string           `json:"condition"`
	ShippingOptions      []ShippingOption `json:"shipping_options"`
	HandlingDays         HandlingDays     `json:"handling_days"`
	PrimeOnly            bool             `json:"prime_only"`
	MarketplaceFulfilled bool             `json:"marketplace_fulfilled"`
	Currency             string           `json:"currency"`
	Seller               Seller           `json:"seller"`
	BuyBoxWinner         bool             `json:"buy_box_winner"`
	International        bool             `json:"international"`
	OfferId              string           `json:"offer_id"`
	Price                int              `json:"price"`
}

type ShippingOption struct {
	Price int `json:"price"`
}

type HandlingDays struct {
	Max int `json:"max"`
	Min int `json:"min"`
}

type Seller struct {
	NumRatings      int    `json:"num_ratings"`
	PercentPositive int    `json:"percent_positive"`
	FirstParty      bool   `json:"first_party"`
	Name            string `json:"name"`
	Id              string `json:"id"`
}

type ProductDetailsResponse struct {
	Code               string              `json:"code"`
	Data               ErrorDataResponse   `json:"data"`
	Status             string              `json:"status"`
	ProductDescription string              `json:"product_description"`
	PostDescription    string              `json:"post_description"`
	Retailer           string              `json:"retailer"`
	Epids              []ExternalProductId `json:"epids"`
	ProductDetails     []string            `json:"product_details"`
	Title              string              `json:"title"`
	VariantSpecifics   []VariantSpecific   `json:"variant_specifics"`
	ProductId          string              `json:"product_id"`
	MainImage          string              `json:"main_image"`
	Brand              string              `json:"brand"`
	MPN                string              `json:"mpn"`
	Images             []string            `json:"images"`
	FeatureBullets     []string            `json:"feature_bullets"`
}

type ExternalProductId struct {
	Type  string `json:"type"`
	Value string `json:"value"`
}

type VariantSpecific struct {
	Dimension string `json:"dimension"`
	Value     string `json:"value"`
}

type ErrorDataResponse struct {
	Message string `json:"message"`
}

type ProductOptions struct {
	MaxAge    int           `json:"max_age"`
	NewerThan time.Time     `json:"newer_than"`
	Timeout   time.Duration `json:"timeout"`
}

func (z Zinc) GetProductInfo(productId string, retailer Retailer, options ProductOptions) (*ProductOffersResponse, *ProductDetailsResponse, error) {
	offersChan := make(chan *ProductOffersResponse, 1)
	detailsChan := make(chan *ProductDetailsResponse, 1)
	errorsChan := make(chan error, 2)

	go func() {
		offers, err := z.GetProductOffers(productId, retailer, options)
		errorsChan <- err
		offersChan <- offers
	}()

	go func() {
		details, err := z.GetProductDetails(productId, retailer, options)
		errorsChan <- err
		detailsChan <- details
	}()

	offers := <-offersChan
	details := <-detailsChan
	for i := 0; i < 2; i++ {
		err := <-errorsChan
		if err != nil {
			return nil, nil, err
		}
	}
	return offers, details, nil
}

func (z Zinc) GetProductOffers(productId string, retailer Retailer, options ProductOptions) (*ProductOffersResponse, error) {
	values := url.Values{}
	values.Set("retailer", string(retailer))
	values.Set("version", "2")
	if options.MaxAge != 0 {
		values.Set("max_age", strconv.Itoa(options.MaxAge))
	}
	if !options.NewerThan.IsZero() {
		values.Set("newer_than", strconv.FormatInt(options.NewerThan.Unix(), 10))
	}
	requestPath := fmt.Sprintf("%v/products/%v/offers?%v", z.ZincBaseURL, productId, values.Encode())

	respBody, err := z.sendGetRequest(requestPath, options.Timeout)
	if err != nil {
		return nil, err
	}
	var resp ProductOffersResponse
	if err := json.Unmarshal(respBody, &resp); err != nil {
		return nil, err
	}
	if resp.Status == "failed" {
		return &resp, fmt.Errorf("Zinc API returned status 'failed' response=%v", resp)
	}
	return &resp, nil
}

func (z Zinc) GetProductDetails(productId string, retailer Retailer, options ProductOptions) (*ProductDetailsResponse, error) {
	values := url.Values{}
	values.Set("retailer", string(retailer))
	if options.MaxAge != 0 {
		values.Set("max_age", strconv.Itoa(options.MaxAge))
	}
	if !options.NewerThan.IsZero() {
		values.Set("newer_than", strconv.FormatInt(options.NewerThan.Unix(), 10))
	}
	requestPath := fmt.Sprintf("%v/products/%v?%v", z.ZincBaseURL, productId, values.Encode())

	respBody, err := z.sendGetRequest(requestPath, options.Timeout)
	if err != nil {
		return nil, err
	}
	var resp ProductDetailsResponse
	if err := json.Unmarshal(respBody, &resp); err != nil {
		return nil, err
	}
	if resp.Status == "failed" {
		return &resp, fmt.Errorf("Zinc API returned status 'failed' response=%v", resp)
	}
	return &resp, nil
}

func (z Zinc) sendGetRequest(requestPath string, timeout time.Duration) ([]byte, error) {
	httpReq, err := http.NewRequest("GET", requestPath, nil)
	if err != nil {
		return nil, err
	}
	httpReq.SetBasicAuth(z.ClientToken, "")
	tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
	client := &http.Client{Transport: tr, Timeout: timeout}
	resp, err := client.Do(httpReq)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	respBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	return respBody, nil
}
<|endoftext|>


<commit_before>package main

import (
	"gost/api/appuserapi"
	"gost/cache"
	"gost/config"
	"gost/httphandle"
	"gost/servers"
	"gost/service"
	"log"
	"os"
	"os/signal"
	"runtime"
)

var numberOfProcessors = runtime.NumCPU()

// Add all the existing endpoints as part of this container
type ApiContainer struct {
	appuserapi.ApplicationUsersApi
}

func StartWebFramework() {
	// Start listener for performing a graceful shutdown of the server
	go listenForInterruptSignal()

	// Start a http or and https server depending on the program arguments
	if len(os.Args) <= 1 || os.Args[1] == "http" {
		servers.StartHTTPServer()
	} else if os.Args[1] == "https" {
		servers.StartHTTPSServer()
	}
}

// Function for performing automatic initializations at application startup
func init() {
	var emptyConfigParam string = ""

	// Initialize application configuration
	config.InitApp(emptyConfigParam)
	config.InitDatabase(emptyConfigParam)
	config.InitRoutes(emptyConfigParam)

	// Initialize the MongoDb service
	service.InitDbService()

	// Register the API endpoints
	httphandle.SetApiInterface(new(ApiContainer))

	// Start the caching system
	cache.StartCachingSystem(cache.CACHE_EXPIRE_TIME)

	// Set the app to use all the available processors
	runtime.GOMAXPROCS(numberOfProcessors)
}

// Application entry point - sets the behavior for the app
func main() {
	StartWebFramework()
}

func listenForInterruptSignal() {
	signalChan := make(chan os.Signal, 1)
	signal.Notify(signalChan, os.Interrupt)

	<-signalChan

	log.Println("The server will now shut down gracefully...")

	service.CloseDbService()
	cache.StopCachingSystem()

	os.Exit(0)
}
<commit_msg>Registered missing endpoints at app start<commit_after>package main

import (
	"gost/api/appuserapi"
	"gost/api/transactionapi"
	"gost/api/userloginapi"
	"gost/cache"
	"gost/config"
	"gost/httphandle"
	"gost/servers"
	"gost/service"
	"log"
	"os"
	"os/signal"
	"runtime"
)

var numberOfProcessors = runtime.NumCPU()

// Add all the existing endpoints as part of this container
type ApiContainer struct {
	appuserapi.ApplicationUsersApi
	transactionapi.TransactionsApi
	userloginapi.UserSessionsApi
}

func StartWebFramework() {
	// Start listener for performing a graceful shutdown of the server
	go listenForInterruptSignal()

	// Start a http or and https server depending on the program arguments
	if len(os.Args) <= 1 || os.Args[1] == "http" {
		servers.StartHTTPServer()
	} else if os.Args[1] == "https" {
		servers.StartHTTPSServer()
	}
}

// Function for performing automatic initializations at application startup
func init() {
	var emptyConfigParam string = ""

	// Initialize application configuration
	config.InitApp(emptyConfigParam)
	config.InitDatabase(emptyConfigParam)
	config.InitRoutes(emptyConfigParam)

	// Initialize the MongoDb service
	service.InitDbService()

	// Register the API endpoints
	httphandle.SetApiInterface(new(ApiContainer))

	// Start the caching system
	cache.StartCachingSystem(cache.CACHE_EXPIRE_TIME)

	// Set the app to use all the available processors
	runtime.GOMAXPROCS(numberOfProcessors)
}

// Application entry point - sets the behavior for the app
func main() {
	StartWebFramework()
}

func listenForInterruptSignal() {
	signalChan := make(chan os.Signal, 1)
	signal.Notify(signalChan, os.Interrupt)

	<-signalChan

	log.Println("The server will now shut down gracefully...")

	service.CloseDbService()
	cache.StopCachingSystem()

	os.Exit(0)
}
<|endoftext|>


<commit_before>package nodefs

import (
	"fmt"
	"os"
	"sync"
	"syscall"

	"github.com/hanwen/go-fuse/fuse"
)

// DataFile is for implementing read-only filesystems.  This
// assumes we already have the data in memory.
type dataFile struct {
	data []byte

	File
}

func (f *dataFile) String() string {
	l := len(f.data)
	if l > 10 {
		l = 10
	}

	return fmt.Sprintf("dataFile(%x)", f.data[:l])
}

func (f *dataFile) GetAttr(out *fuse.Attr) fuse.Status {
	out.Mode = fuse.S_IFREG | 0644
	out.Size = uint64(len(f.data))
	return fuse.OK
}

func NewDataFile(data []byte) File {
	f := new(dataFile)
	f.data = data
	f.File = NewDefaultFile()
	return f
}

func (f *dataFile) Read(buf []byte, off int64) (res fuse.ReadResult, code fuse.Status) {
	end := int(off) + int(len(buf))
	if end > len(f.data) {
		end = len(f.data)
	}

	return fuse.ReadResultData(f.data[off:end]), fuse.OK
}

type devNullFile struct {
	File
}

// NewDevNullFile returns a file that accepts any write, and always
// returns EOF for reads.
func NewDevNullFile() File {
	return &devNullFile{
		File: NewDefaultFile(),
	}
}

func (f *devNullFile) Allocate(off uint64, size uint64, mode uint32) (code fuse.Status) {
	return fuse.OK
}

func (f *devNullFile) String() string {
	return "devNullFile"
}

func (f *devNullFile) Read(buf []byte, off int64) (fuse.ReadResult, fuse.Status) {
	return fuse.ReadResultData(nil), fuse.OK
}

func (f *devNullFile) Write(content []byte, off int64) (uint32, fuse.Status) {
	return uint32(len(content)), fuse.OK
}

func (f *devNullFile) Flush() fuse.Status {
	return fuse.OK
}

func (f *devNullFile) Fsync(flags int) (code fuse.Status) {
	return fuse.OK
}

func (f *devNullFile) Truncate(size uint64) (code fuse.Status) {
	return fuse.OK
}

////////////////

// LoopbackFile delegates all operations back to an underlying os.File.
func NewLoopbackFile(f *os.File) File {
	return &loopbackFile{File: f}
}

type loopbackFile struct {
	File *os.File

	// os.File is not threadsafe. Although fd themselves are
	// constant during the lifetime of an open file, the OS may
	// reuse the fd number after it is closed. When open races
	// with another close, they may lead to confusion as which
	// file gets written in the end.
	lock sync.Mutex
}

func (f *loopbackFile) InnerFile() File {
	return nil
}

func (f *loopbackFile) SetInode(n *Inode) {
}

func (f *loopbackFile) String() string {
	return fmt.Sprintf("loopbackFile(%s)", f.File.Name())
}

func (f *loopbackFile) Read(buf []byte, off int64) (res fuse.ReadResult, code fuse.Status) {
	f.lock.Lock()
	// This is not racy by virtue of the kernel properly
	// synchronizing the open/write/close.
	r := fuse.ReadResultFd(f.File.Fd(), off, len(buf))
	f.lock.Unlock()
	return r, fuse.OK
}

func (f *loopbackFile) Write(data []byte, off int64) (uint32, fuse.Status) {
	f.lock.Lock()
	n, err := f.File.WriteAt(data, off)
	f.lock.Unlock()
	return uint32(n), fuse.ToStatus(err)
}

func (f *loopbackFile) Release() {
	f.lock.Lock()
	f.File.Close()
	f.lock.Unlock()
}

func (f *loopbackFile) Flush() fuse.Status {
	f.lock.Lock()

	// Since Flush() may be called for each dup'd fd, we don't
	// want to really close the file, we just want to flush. This
	// is achieved by closing a dup'd fd.
	newFd, err := syscall.Dup(int(f.File.Fd()))
	f.lock.Unlock()

	if err != nil {
		return fuse.ToStatus(err)
	}
	err = syscall.Close(newFd)
	return fuse.ToStatus(err)
}

func (f *loopbackFile) Fsync(flags int) (code fuse.Status) {
	f.lock.Lock()
	r := fuse.ToStatus(syscall.Fsync(int(f.File.Fd())))
	f.lock.Unlock()

	return r
}

func (f *loopbackFile) Truncate(size uint64) fuse.Status {
	f.lock.Lock()
	r := fuse.ToStatus(syscall.Ftruncate(int(f.File.Fd()), int64(size)))
	f.lock.Unlock()

	return r
}

func (f *loopbackFile) Chmod(mode uint32) fuse.Status {
	f.lock.Lock()
	r := fuse.ToStatus(f.File.Chmod(os.FileMode(mode)))
	f.lock.Unlock()

	return r
}

func (f *loopbackFile) Chown(uid uint32, gid uint32) fuse.Status {
	f.lock.Lock()
	r := fuse.ToStatus(f.File.Chown(int(uid), int(gid)))
	f.lock.Unlock()

	return r
}

func (f *loopbackFile) GetAttr(a *fuse.Attr) fuse.Status {
	st := syscall.Stat_t{}
	f.lock.Lock()
	err := syscall.Fstat(int(f.File.Fd()), &st)
	f.lock.Unlock()
	if err != nil {
		return fuse.ToStatus(err)
	}
	a.FromStat(&st)

	return fuse.OK
}

// Allocate, Utimens implemented in files_linux.go

////////////////////////////////////////////////////////////////

func NewReadOnlyFile(f File) File {
	return &readOnlyFile{File: f}
}

// readOnlyFile is a wrapper that denies writable operations
type readOnlyFile struct {
	File
}

func (f *readOnlyFile) String() string {
	return fmt.Sprintf("readOnlyFile(%s)", f.File.String())
}

func (f *readOnlyFile) Write(data []byte, off int64) (uint32, fuse.Status) {
	return 0, fuse.EPERM
}

func (f *readOnlyFile) Fsync(flag int) (code fuse.Status) {
	return fuse.OK
}

func (f *readOnlyFile) Truncate(size uint64) fuse.Status {
	return fuse.EPERM
}

func (f *readOnlyFile) Chmod(mode uint32) fuse.Status {
	return fuse.EPERM
}

func (f *readOnlyFile) Chown(uid uint32, gid uint32) fuse.Status {
	return fuse.EPERM
}

func (f *readOnlyFile) Allocate(off uint64, sz uint64, mode uint32) fuse.Status {
	return fuse.EPERM
}
<commit_msg>fuse/nodefs: doc NewReadOnlyFile.<commit_after>package nodefs

import (
	"fmt"
	"os"
	"sync"
	"syscall"

	"github.com/hanwen/go-fuse/fuse"
)

// DataFile is for implementing read-only filesystems.  This
// assumes we already have the data in memory.
type dataFile struct {
	data []byte

	File
}

func (f *dataFile) String() string {
	l := len(f.data)
	if l > 10 {
		l = 10
	}

	return fmt.Sprintf("dataFile(%x)", f.data[:l])
}

func (f *dataFile) GetAttr(out *fuse.Attr) fuse.Status {
	out.Mode = fuse.S_IFREG | 0644
	out.Size = uint64(len(f.data))
	return fuse.OK
}

func NewDataFile(data []byte) File {
	f := new(dataFile)
	f.data = data
	f.File = NewDefaultFile()
	return f
}

func (f *dataFile) Read(buf []byte, off int64) (res fuse.ReadResult, code fuse.Status) {
	end := int(off) + int(len(buf))
	if end > len(f.data) {
		end = len(f.data)
	}

	return fuse.ReadResultData(f.data[off:end]), fuse.OK
}

type devNullFile struct {
	File
}

// NewDevNullFile returns a file that accepts any write, and always
// returns EOF for reads.
func NewDevNullFile() File {
	return &devNullFile{
		File: NewDefaultFile(),
	}
}

func (f *devNullFile) Allocate(off uint64, size uint64, mode uint32) (code fuse.Status) {
	return fuse.OK
}

func (f *devNullFile) String() string {
	return "devNullFile"
}

func (f *devNullFile) Read(buf []byte, off int64) (fuse.ReadResult, fuse.Status) {
	return fuse.ReadResultData(nil), fuse.OK
}

func (f *devNullFile) Write(content []byte, off int64) (uint32, fuse.Status) {
	return uint32(len(content)), fuse.OK
}

func (f *devNullFile) Flush() fuse.Status {
	return fuse.OK
}

func (f *devNullFile) Fsync(flags int) (code fuse.Status) {
	return fuse.OK
}

func (f *devNullFile) Truncate(size uint64) (code fuse.Status) {
	return fuse.OK
}

////////////////

// LoopbackFile delegates all operations back to an underlying os.File.
func NewLoopbackFile(f *os.File) File {
	return &loopbackFile{File: f}
}

type loopbackFile struct {
	File *os.File

	// os.File is not threadsafe. Although fd themselves are
	// constant during the lifetime of an open file, the OS may
	// reuse the fd number after it is closed. When open races
	// with another close, they may lead to confusion as which
	// file gets written in the end.
	lock sync.Mutex
}

func (f *loopbackFile) InnerFile() File {
	return nil
}

func (f *loopbackFile) SetInode(n *Inode) {
}

func (f *loopbackFile) String() string {
	return fmt.Sprintf("loopbackFile(%s)", f.File.Name())
}

func (f *loopbackFile) Read(buf []byte, off int64) (res fuse.ReadResult, code fuse.Status) {
	f.lock.Lock()
	// This is not racy by virtue of the kernel properly
	// synchronizing the open/write/close.
	r := fuse.ReadResultFd(f.File.Fd(), off, len(buf))
	f.lock.Unlock()
	return r, fuse.OK
}

func (f *loopbackFile) Write(data []byte, off int64) (uint32, fuse.Status) {
	f.lock.Lock()
	n, err := f.File.WriteAt(data, off)
	f.lock.Unlock()
	return uint32(n), fuse.ToStatus(err)
}

func (f *loopbackFile) Release() {
	f.lock.Lock()
	f.File.Close()
	f.lock.Unlock()
}

func (f *loopbackFile) Flush() fuse.Status {
	f.lock.Lock()

	// Since Flush() may be called for each dup'd fd, we don't
	// want to really close the file, we just want to flush. This
	// is achieved by closing a dup'd fd.
	newFd, err := syscall.Dup(int(f.File.Fd()))
	f.lock.Unlock()

	if err != nil {
		return fuse.ToStatus(err)
	}
	err = syscall.Close(newFd)
	return fuse.ToStatus(err)
}

func (f *loopbackFile) Fsync(flags int) (code fuse.Status) {
	f.lock.Lock()
	r := fuse.ToStatus(syscall.Fsync(int(f.File.Fd())))
	f.lock.Unlock()

	return r
}

func (f *loopbackFile) Truncate(size uint64) fuse.Status {
	f.lock.Lock()
	r := fuse.ToStatus(syscall.Ftruncate(int(f.File.Fd()), int64(size)))
	f.lock.Unlock()

	return r
}

func (f *loopbackFile) Chmod(mode uint32) fuse.Status {
	f.lock.Lock()
	r := fuse.ToStatus(f.File.Chmod(os.FileMode(mode)))
	f.lock.Unlock()

	return r
}

func (f *loopbackFile) Chown(uid uint32, gid uint32) fuse.Status {
	f.lock.Lock()
	r := fuse.ToStatus(f.File.Chown(int(uid), int(gid)))
	f.lock.Unlock()

	return r
}

func (f *loopbackFile) GetAttr(a *fuse.Attr) fuse.Status {
	st := syscall.Stat_t{}
	f.lock.Lock()
	err := syscall.Fstat(int(f.File.Fd()), &st)
	f.lock.Unlock()
	if err != nil {
		return fuse.ToStatus(err)
	}
	a.FromStat(&st)

	return fuse.OK
}

// Allocate, Utimens implemented in files_linux.go

////////////////////////////////////////////////////////////////

// NewReadOnlyFile wraps a File so all read/write operations are
// denied.
func NewReadOnlyFile(f File) File {
	return &readOnlyFile{File: f}
}

type readOnlyFile struct {
	File
}

func (f *readOnlyFile) InnerFile() File {
	return f.File
}

func (f *readOnlyFile) String() string {
	return fmt.Sprintf("readOnlyFile(%s)", f.File.String())
}

func (f *readOnlyFile) Write(data []byte, off int64) (uint32, fuse.Status) {
	return 0, fuse.EPERM
}

func (f *readOnlyFile) Fsync(flag int) (code fuse.Status) {
	return fuse.OK
}

func (f *readOnlyFile) Truncate(size uint64) fuse.Status {
	return fuse.EPERM
}

func (f *readOnlyFile) Chmod(mode uint32) fuse.Status {
	return fuse.EPERM
}

func (f *readOnlyFile) Chown(uid uint32, gid uint32) fuse.Status {
	return fuse.EPERM
}

func (f *readOnlyFile) Allocate(off uint64, sz uint64, mode uint32) fuse.Status {
	return fuse.EPERM
}
<|endoftext|>